From f973b71fe21c290022c50979dc0bff5dc100e84d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 9 Aug 2026 19:07:43 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(export):=20late-cancel=20win?= =?UTF-8?q?dow=20+=20atomic=20.part=20rename?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cancel was only checked inside the per-clip frame loop, so an esc during the drain, the audio pass or `finish` completed the export anyway and left a file the user had asked not to have. Cancel is now checked after the loop and again before `finish`. The worker also writes to `.part` and renames it onto the output only on full success, so the output name never points at a half-written file -- and a killed process orphans a `.part` instead of a playable-looking `.export.mp4`. --- crates/engine/src/export.rs | 49 +++++++++++++++++++++++------- crates/engine/tests/export.rs | 56 +++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 24fa122..1cf0e8f 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -5,11 +5,15 @@ //! pure-Rust AAC encoder to re-encode with. The worker owns everything: the //! caller gets an [`ExportHandle`] and polls it from its render loop. //! -//! Nothing partial survives a failure: cancel and every error path delete the -//! output file. A killed *process* still leaves it — only in-process cleanup is -//! promised. +//! Nothing partial survives a failure: the worker writes to `.part` and +//! renames it onto `out` only once the file is closed and complete, so the +//! output either does not exist or is finished — there is no window where a +//! half-written `.export.mp4` is sitting there looking playable. Cancel and +//! every error path delete the `.part`. A killed *process* leaves the `.part` +//! behind (only in-process cleanup is promised), which is an orphan a user can +//! delete rather than a file that plays for two seconds and stops. -use std::path::Path; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::sync::{Arc, Mutex}; use std::thread; @@ -53,8 +57,10 @@ impl ExportHandle { self.shared.progress.load(Ordering::Relaxed) as f32 / PROGRESS_SCALE as f32 } - /// Asks the worker to stop at its next frame and delete the partial file. - /// The outcome then reports the cancellation as an error. + /// Asks the worker to stop at its next checkpoint and delete the partial + /// file. The outcome then reports the cancellation as an error. Checkpoints + /// run to the last instant before the rename, so even a cancel at full + /// progress leaves no output. pub fn cancel(&self) { self.shared.cancel.store(true, Ordering::Relaxed); } @@ -82,11 +88,20 @@ pub(crate) fn start(source: &Path, project: Project, meta: VideoMeta, out: &Path let worker = Arc::clone(&shared); let source = source.to_path_buf(); let out = out.to_path_buf(); + // `.part`, appended rather than substituted: the temporary of + // `a.export.mp4` is `a.export.mp4.part`, which no other export claims. + let mut part = out.clone().into_os_string(); + part.push(".part"); + let part = PathBuf::from(part); let spawned = thread::Builder::new().name("export".into()).spawn(move || { - let result = run(&source, &project, &meta, &out, &worker); + // The rename is the last step and the only one that publishes a file + // under the name the caller asked for; it stays on the same directory, + // so it is atomic. + let result = run(&source, &project, &meta, &part, &worker) + .and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)); if result.is_err() { // The muxer -- and with it the file handle -- died with `run`. - let _ = std::fs::remove_file(&out); + let _ = std::fs::remove_file(&part); } settle(&worker, result); }); @@ -131,9 +146,7 @@ fn run( // need not line up with the cuts. let mut pictures = ClipDecoder::open(source, clip.in_frame)?; for _ in 0..clip.len() { - if shared.cancel.load(Ordering::Relaxed) { - return Err("export cancelled".into()); - } + cancelled(shared)?; let Some((y, u, v, width, height)) = pictures.next()? else { break; // source ran out early; the clip list outlives the file }; @@ -149,6 +162,9 @@ fn run( while let Some(au) = encoder.drain()? { write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?; } + // Progress reads 100% from here on, but nothing is published yet: draining, + // the audio pass and `finish` are all still cancellable. + cancelled(shared)?; let Some(mut muxer) = muxer else { return Err("export produced no coded pictures".into()); @@ -158,11 +174,22 @@ fn run( muxer.write_audio_packet(&packet.bytes)?; } } + cancelled(shared)?; muxer.finish()?; shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); Ok(()) } +/// `Err` once a cancel has been asked for. Called at every point where the work +/// left is more than an instant, so an `esc` at 99.9% still stops the export +/// instead of quietly completing it. +fn cancelled(shared: &Shared) -> crate::Result<()> { + if shared.cancel.load(Ordering::Relaxed) { + return Err("export cancelled".into()); + } + Ok(()) +} + /// Writes one access unit, creating the file on the first one -- the parameter /// sets for `avcC` only exist once the encoder has coded something. Units with /// no coded slice are skipped: a software encoder may hand back an empty buffer diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index f95fcb6..0b84f18 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -34,9 +34,16 @@ fn asset(name: &str) -> PathBuf { fn out_path(name: &str) -> PathBuf { let path = std::env::temp_dir().join(format!("ve_export_{name}.mp4")); let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(part_path(&path)); path } +/// What the worker actually writes to until it succeeds; the engine appends the +/// suffix rather than replacing the extension. +fn part_path(out: &Path) -> PathBuf { + PathBuf::from(format!("{}.part", out.display())) +} + /// Pins both paths to software for the whole test binary, so the default suite /// proves the fallback that every machine has. fn pin_software() { @@ -189,6 +196,55 @@ fn cancelling_leaves_no_file() { let result = wait(&handle, Duration::from_secs(5)); assert!(result.is_err(), "a cancelled export is an error"); assert!(!out.exists(), "no partial file survives a cancel"); + assert!(!part_path(&out).exists(), "the .part is cleaned up too"); +} + +/// The late window: cancel after the last frame, while the export is draining, +/// writing audio and closing the file. Progress already reads 100% there, and +/// before the cancel checkpoints outside the frame loop the export completed +/// anyway and left a file the user never asked for. +/// +/// Landing in that window is a race, so the attempt is repeated; whichever side +/// of it an attempt lands on, the invariant is the same -- a finished file or no +/// file, never a `.part`. +#[test] +fn cancelling_after_the_last_frame_leaves_no_file() { + pin_software(); + let out = out_path("late"); + let part = part_path(&out); + for attempt in 1..=5 { + let mut session = edited(&asset("test_baseline.mp4")); + session.pause(); + let handle = session.export_to(&out); + // Sleep while there is time to sleep, then spin: the window is the few + // milliseconds between the last frame and `finish`. + let started = Instant::now(); + while handle.progress() < 0.9 && !handle.is_finished() { + assert!( + started.elapsed() < Duration::from_secs(120), + "export stalled" + ); + std::thread::sleep(Duration::from_millis(20)); + } + while handle.progress() < 1.0 && !handle.is_finished() { + std::hint::spin_loop(); + } + handle.cancel(); + + let result = wait(&handle, Duration::from_secs(30)); + assert!(!part.exists(), "attempt {attempt} left a .part behind"); + if result.is_err() { + assert!(!out.exists(), "a late cancel still wrote {}", out.display()); + return; + } + // The export beat the cancel; then it must be a whole file, not a stump. + assert_eq!( + engine::demux::Demuxer::open(&out).unwrap().0.frame_count, + 120 + ); + std::fs::remove_file(&out).unwrap(); + } + panic!("cancel never landed in the drain/audio/finish window"); } /// Audio: the copied AAC packets have to land in the export as a track a reader