Remove a cancelled download's part file after its task has stopped

The download test, which 61458df of this branch made wait for the part file,
exposed a defect of the link: a download reports Started just before it opens its part file, and the
open ran on tokio's blocking pool. Link::cancel() aborted the task and removed
the part file at once; when the cancel came between Started and the end of the
open, there was no file yet to remove, the abort cannot stop an open that is
already on the blocking pool, and the open then made an empty `<name>.part`
next to the target after the transfer had been reported Cancelled. The user
sees a leftover file, and a later download with `resume` continues from it.

files::receive now makes the directory and opens the part file with std::fs in
one step (the same kind of small blocking call as Sink::offset and the removal
in cancel, which already ran on the loop), so an abort, which takes effect at
an await, cannot come in the middle of it. Link::cancel() keeps the task's
JoinHandle instead of its AbortHandle, aborts the task, and removes the part
file and reports Cancelled from a task of its own after the aborted one has
stopped: the file the task made is then there to be found, or the task never
got to make one. Cancelled is therefore reported after the removal and after
the task has stopped, where it was reported before both.

The test goes back to the shape it had before 61458df: it cancels as soon as
the transfer is Started (and now fails loudly if it never was). That shape
failed in 10 of 100 runs of the voelin-core lib tests three at a time with 16
busy loops beside them on a 32-core machine, and in the final runs of the CI
test step in the runner image of this task (the second of three); with this
change it failed in none of 200 such runs. The link and files tests pass.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Sonnet 5.5 committed 2026-10-24 23:07:48 +03:00
1 parent 443559aa79
commit 1de2725f19
3 files changed
+41 -31

No files matched your search

+14 -11
View File
@@ -199,19 +199,22 @@ async fn receive<R: AsyncRead + Unpin>(
let mut done = offset;
match sink {
Sink::File { part, dest, append } => {
// The directory and the file are made in one step, without a pause in
// which the task could be stopped: a cancel stops the task, waits for
// it and then removes the part file, so what the task made must be
// there by then (a pending open on the blocking pool would not be).
if let Some(dir) = part.parent().filter(|d| !d.as_os_str().is_empty()) {
tokio::fs::create_dir_all(dir)
.await
.map_err(|e| format!("{}: {e}", dir.display()))?;
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
}
let mut file = tokio::fs::OpenOptions::new()
.create(true)
.write(true)
.append(*append)
.truncate(!*append)
.open(part)
.await
.map_err(|e| format!("{}: {e}", part.display()))?;
let mut file = tokio::fs::File::from_std(
std::fs::OpenOptions::new()
.create(true)
.write(true)
.append(*append)
.truncate(!*append)
.open(part)
.map_err(|e| format!("{}: {e}", part.display()))?,
);
let received = async {
while done < size {
let n = stream.read(&mut buf).await.map_err(|e| e.to_string())?;
+19 -13
View File
@@ -77,7 +77,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use tokio::sync::mpsc;
use tokio::task::AbortHandle;
use tokio::task::JoinHandle;
use tracing::{debug, info, warn};
use voelin_audio::EncodedVoice;
use voelin_model::replica::{Replica, SCHEMA_GENERATION, ScopeId};
@@ -325,7 +325,7 @@ async fn drive(
/// A transfer a user can cancel.
struct Running {
task: AbortHandle,
task: JoinHandle<()>,
part: Option<PathBuf>,
report: Report,
/// The server has opened it (a part file may exist).
@@ -1479,7 +1479,7 @@ impl Conn {
receive.await;
}
});
self.running(transfer, Running { task: task.abort_handle(), part, report, started });
self.running(transfer, Running { task, part, report, started });
}
fn upload(
@@ -1560,7 +1560,7 @@ impl Conn {
let stored = async move { done.await.map(|_| ()).map_err(|e| text(&e, false)) };
files::upload_to(body, stored, from, size, offset, progress, task_report).await;
});
self.running(transfer, Running { task: task.abort_handle(), part: None, report, started });
self.running(transfer, Running { task, part: None, report, started });
}
fn running(&mut self, transfer: Option<TransferId>, running: Running) {
@@ -1572,15 +1572,21 @@ impl Conn {
fn cancel(&mut self, id: TransferId) {
match self.transfers.remove(&id) {
Some(running) if !running.task.is_finished() => {
running.task.abort();
// A part file exists once the server has opened the transfer.
if running.started.load(Ordering::Acquire)
&& let Some(part) = running.part
{
let _ = std::fs::remove_file(part);
}
(running.report)(TransferState::Cancelled);
Some(Running { task, part, report, started }) if !task.is_finished() => {
task.abort();
// The part file goes once the task has stopped, not at once: the task
// opens it in one step (files::download), so it is there or it never
// will be, and a removal that came before the open would leave it.
tokio::spawn(async move {
let _ = task.await;
// A part file exists once the server has opened the transfer.
if started.load(Ordering::Acquire)
&& let Some(part) = part
{
let _ = std::fs::remove_file(part);
}
report(TransferState::Cancelled);
});
}
_ => debug!(id, "cancel: no such transfer (finished?)"),
}
+8 -7
View File
@@ -598,20 +598,21 @@ async fn a_file_is_downloaded_through_the_connection_the_link_opens() {
report,
});
let LinkCmd::OpenRead { reply, .. } = rig.inner_cmd().await else { panic!("a connection") };
// A file whose bytes do not come: the transfer waits in the middle, with
// its part file made. `Started` is reported just before the part file is
// opened, and a cancel in between would find nothing to remove while the
// open still goes on, so the part file is what is waited for.
// A file whose bytes do not come: the transfer waits in the middle.
let (server, client) = tokio::io::duplex(64);
let _ = reply.send(Ok((1 << 20, Box::pin(client))));
for _ in 0..500 {
if part.exists() {
if states.lock().unwrap().iter().any(|s| matches!(s, TransferState::Started { .. })) {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert!(part.exists(), "the transfer made its part file: {:?}", states.lock().unwrap());
assert!(states.lock().unwrap().iter().any(|s| matches!(s, TransferState::Started { .. })));
assert!(
states.lock().unwrap().iter().any(|s| matches!(s, TransferState::Started { .. })),
"the transfer started: {:?}",
states.lock().unwrap()
);
// Cancelled the moment it is Started, when its part file may be opening.
rig.give(LinkCmd::CancelTransfer(3));
assert_eq!(final_state(&states).await, TransferState::Cancelled);
rig.quiet();