Late-cancel window + atomic .part rename
Browse files at this commitf973b71fe21c290022c50979dc0bff5dc100e84dParent: 9eac4be- fix
- late-cancel window + atomic .part rename
2 changed files +94 -11
- crates/engine/src/export.rs +38 -11
- crates/engine/tests/export.rs +56 -0
crates/engine/src/export.rsmodified+38 -11
| @@ -5,11 +5,15 @@ | |||
| 5 | //! pure-Rust AAC encoder to re-encode with. The worker owns everything: the | 5 | //! pure-Rust AAC encoder to re-encode with. The worker owns everything: the |
| 6 | //! caller gets an [`ExportHandle`] and polls it from its render loop. | 6 | //! caller gets an [`ExportHandle`] and polls it from its render loop. |
| 7 | //! | 7 | //! |
| 8 | -//! Nothing partial survives a failure: cancel and every error path delete the | 8 | +//! Nothing partial survives a failure: the worker writes to `<out>.part` and |
| 9 | -//! output file. A killed *process* still leaves it — only in-process cleanup is | 9 | +//! renames it onto `out` only once the file is closed and complete, so the |
| 10 | -//! promised. | 10 | +//! output either does not exist or is finished — there is no window where a |
| 11 | +//! half-written `.export.mp4` is sitting there looking playable. Cancel and | ||
| 12 | +//! every error path delete the `.part`. A killed *process* leaves the `.part` | ||
| 13 | +//! behind (only in-process cleanup is promised), which is an orphan a user can | ||
| 14 | +//! delete rather than a file that plays for two seconds and stops. | ||
| 11 | 15 | ||
| 12 | -use std::path::Path; | 16 | +use std::path::{Path, PathBuf}; |
| 13 | use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; | 17 | use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; |
| 14 | use std::sync::{Arc, Mutex}; | 18 | use std::sync::{Arc, Mutex}; |
| 15 | use std::thread; | 19 | use std::thread; |
| @@ -53,8 +57,10 @@ impl ExportHandle { | |||
| 53 | self.shared.progress.load(Ordering::Relaxed) as f32 / PROGRESS_SCALE as f32 | 57 | self.shared.progress.load(Ordering::Relaxed) as f32 / PROGRESS_SCALE as f32 |
| 54 | } | 58 | } |
| 55 | 59 | ||
| 56 | - /// Asks the worker to stop at its next frame and delete the partial file. | 60 | + /// Asks the worker to stop at its next checkpoint and delete the partial |
| 57 | - /// The outcome then reports the cancellation as an error. | 61 | + /// file. The outcome then reports the cancellation as an error. Checkpoints |
| 62 | + /// run to the last instant before the rename, so even a cancel at full | ||
| 63 | + /// progress leaves no output. | ||
| 58 | pub fn cancel(&self) { | 64 | pub fn cancel(&self) { |
| 59 | self.shared.cancel.store(true, Ordering::Relaxed); | 65 | self.shared.cancel.store(true, Ordering::Relaxed); |
| 60 | } | 66 | } |
| @@ -82,11 +88,20 @@ pub(crate) fn start(source: &Path, project: Project, meta: VideoMeta, out: &Path | |||
| 82 | let worker = Arc::clone(&shared); | 88 | let worker = Arc::clone(&shared); |
| 83 | let source = source.to_path_buf(); | 89 | let source = source.to_path_buf(); |
| 84 | let out = out.to_path_buf(); | 90 | let out = out.to_path_buf(); |
| 91 | + // `<out>.part`, appended rather than substituted: the temporary of | ||
| 92 | + // `a.export.mp4` is `a.export.mp4.part`, which no other export claims. | ||
| 93 | + let mut part = out.clone().into_os_string(); | ||
| 94 | + part.push(".part"); | ||
| 95 | + let part = PathBuf::from(part); | ||
| 85 | let spawned = thread::Builder::new().name("export".into()).spawn(move || { | 96 | let spawned = thread::Builder::new().name("export".into()).spawn(move || { |
| 86 | - let result = run(&source, &project, &meta, &out, &worker); | 97 | + // The rename is the last step and the only one that publishes a file |
| 98 | + // under the name the caller asked for; it stays on the same directory, | ||
| 99 | + // so it is atomic. | ||
| 100 | + let result = run(&source, &project, &meta, &part, &worker) | ||
| 101 | + .and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)); | ||
| 87 | if result.is_err() { | 102 | if result.is_err() { |
| 88 | // The muxer -- and with it the file handle -- died with `run`. | 103 | // The muxer -- and with it the file handle -- died with `run`. |
| 89 | - let _ = std::fs::remove_file(&out); | 104 | + let _ = std::fs::remove_file(&part); |
| 90 | } | 105 | } |
| 91 | settle(&worker, result); | 106 | settle(&worker, result); |
| 92 | }); | 107 | }); |
| @@ -131,9 +146,7 @@ fn run( | |||
| 131 | // need not line up with the cuts. | 146 | // need not line up with the cuts. |
| 132 | let mut pictures = ClipDecoder::open(source, clip.in_frame)?; | 147 | let mut pictures = ClipDecoder::open(source, clip.in_frame)?; |
| 133 | for _ in 0..clip.len() { | 148 | for _ in 0..clip.len() { |
| 134 | - if shared.cancel.load(Ordering::Relaxed) { | 149 | + cancelled(shared)?; |
| 135 | - return Err("export cancelled".into()); | ||
| 136 | - } | ||
| 137 | let Some((y, u, v, width, height)) = pictures.next()? else { | 150 | let Some((y, u, v, width, height)) = pictures.next()? else { |
| 138 | break; // source ran out early; the clip list outlives the file | 151 | break; // source ran out early; the clip list outlives the file |
| 139 | }; | 152 | }; |
| @@ -149,6 +162,9 @@ fn run( | |||
| 149 | while let Some(au) = encoder.drain()? { | 162 | while let Some(au) = encoder.drain()? { |
| 150 | write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?; | 163 | write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?; |
| 151 | } | 164 | } |
| 165 | + // Progress reads 100% from here on, but nothing is published yet: draining, | ||
| 166 | + // the audio pass and `finish` are all still cancellable. | ||
| 167 | + cancelled(shared)?; | ||
| 152 | 168 | ||
| 153 | let Some(mut muxer) = muxer else { | 169 | let Some(mut muxer) = muxer else { |
| 154 | return Err("export produced no coded pictures".into()); | 170 | return Err("export produced no coded pictures".into()); |
| @@ -158,11 +174,22 @@ fn run( | |||
| 158 | muxer.write_audio_packet(&packet.bytes)?; | 174 | muxer.write_audio_packet(&packet.bytes)?; |
| 159 | } | 175 | } |
| 160 | } | 176 | } |
| 177 | + cancelled(shared)?; | ||
| 161 | muxer.finish()?; | 178 | muxer.finish()?; |
| 162 | shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); | 179 | shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); |
| 163 | Ok(()) | 180 | Ok(()) |
| 164 | } | 181 | } |
| 165 | 182 | ||
| 183 | +/// `Err` once a cancel has been asked for. Called at every point where the work | ||
| 184 | +/// left is more than an instant, so an `esc` at 99.9% still stops the export | ||
| 185 | +/// instead of quietly completing it. | ||
| 186 | +fn cancelled(shared: &Shared) -> crate::Result<()> { | ||
| 187 | + if shared.cancel.load(Ordering::Relaxed) { | ||
| 188 | + return Err("export cancelled".into()); | ||
| 189 | + } | ||
| 190 | + Ok(()) | ||
| 191 | +} | ||
| 192 | + | ||
| 166 | /// Writes one access unit, creating the file on the first one -- the parameter | 193 | /// Writes one access unit, creating the file on the first one -- the parameter |
| 167 | /// sets for `avcC` only exist once the encoder has coded something. Units with | 194 | /// sets for `avcC` only exist once the encoder has coded something. Units with |
| 168 | /// no coded slice are skipped: a software encoder may hand back an empty buffer | 195 | /// no coded slice are skipped: a software encoder may hand back an empty buffer |
crates/engine/tests/export.rsmodified+56 -0
| @@ -34,9 +34,16 @@ fn asset(name: &str) -> PathBuf { | |||
| 34 | fn out_path(name: &str) -> PathBuf { | 34 | fn out_path(name: &str) -> PathBuf { |
| 35 | let path = std::env::temp_dir().join(format!("ve_export_{name}.mp4")); | 35 | let path = std::env::temp_dir().join(format!("ve_export_{name}.mp4")); |
| 36 | let _ = std::fs::remove_file(&path); | 36 | let _ = std::fs::remove_file(&path); |
| 37 | + let _ = std::fs::remove_file(part_path(&path)); | ||
| 37 | path | 38 | path |
| 38 | } | 39 | } |
| 39 | 40 | ||
| 41 | +/// What the worker actually writes to until it succeeds; the engine appends the | ||
| 42 | +/// suffix rather than replacing the extension. | ||
| 43 | +fn part_path(out: &Path) -> PathBuf { | ||
| 44 | + PathBuf::from(format!("{}.part", out.display())) | ||
| 45 | +} | ||
| 46 | + | ||
| 40 | /// Pins both paths to software for the whole test binary, so the default suite | 47 | /// Pins both paths to software for the whole test binary, so the default suite |
| 41 | /// proves the fallback that every machine has. | 48 | /// proves the fallback that every machine has. |
| 42 | fn pin_software() { | 49 | fn pin_software() { |
| @@ -189,6 +196,55 @@ fn cancelling_leaves_no_file() { | |||
| 189 | let result = wait(&handle, Duration::from_secs(5)); | 196 | let result = wait(&handle, Duration::from_secs(5)); |
| 190 | assert!(result.is_err(), "a cancelled export is an error"); | 197 | assert!(result.is_err(), "a cancelled export is an error"); |
| 191 | assert!(!out.exists(), "no partial file survives a cancel"); | 198 | assert!(!out.exists(), "no partial file survives a cancel"); |
| 199 | + assert!(!part_path(&out).exists(), "the .part is cleaned up too"); | ||
| 200 | +} | ||
| 201 | + | ||
| 202 | +/// The late window: cancel after the last frame, while the export is draining, | ||
| 203 | +/// writing audio and closing the file. Progress already reads 100% there, and | ||
| 204 | +/// before the cancel checkpoints outside the frame loop the export completed | ||
| 205 | +/// anyway and left a file the user never asked for. | ||
| 206 | +/// | ||
| 207 | +/// Landing in that window is a race, so the attempt is repeated; whichever side | ||
| 208 | +/// of it an attempt lands on, the invariant is the same -- a finished file or no | ||
| 209 | +/// file, never a `.part`. | ||
| 210 | +#[test] | ||
| 211 | +fn cancelling_after_the_last_frame_leaves_no_file() { | ||
| 212 | + pin_software(); | ||
| 213 | + let out = out_path("late"); | ||
| 214 | + let part = part_path(&out); | ||
| 215 | + for attempt in 1..=5 { | ||
| 216 | + let mut session = edited(&asset("test_baseline.mp4")); | ||
| 217 | + session.pause(); | ||
| 218 | + let handle = session.export_to(&out); | ||
| 219 | + // Sleep while there is time to sleep, then spin: the window is the few | ||
| 220 | + // milliseconds between the last frame and `finish`. | ||
| 221 | + let started = Instant::now(); | ||
| 222 | + while handle.progress() < 0.9 && !handle.is_finished() { | ||
| 223 | + assert!( | ||
| 224 | + started.elapsed() < Duration::from_secs(120), | ||
| 225 | + "export stalled" | ||
| 226 | + ); | ||
| 227 | + std::thread::sleep(Duration::from_millis(20)); | ||
| 228 | + } | ||
| 229 | + while handle.progress() < 1.0 && !handle.is_finished() { | ||
| 230 | + std::hint::spin_loop(); | ||
| 231 | + } | ||
| 232 | + handle.cancel(); | ||
| 233 | + | ||
| 234 | + let result = wait(&handle, Duration::from_secs(30)); | ||
| 235 | + assert!(!part.exists(), "attempt {attempt} left a .part behind"); | ||
| 236 | + if result.is_err() { | ||
| 237 | + assert!(!out.exists(), "a late cancel still wrote {}", out.display()); | ||
| 238 | + return; | ||
| 239 | + } | ||
| 240 | + // The export beat the cancel; then it must be a whole file, not a stump. | ||
| 241 | + assert_eq!( | ||
| 242 | + engine::demux::Demuxer::open(&out).unwrap().0.frame_count, | ||
| 243 | + 120 | ||
| 244 | + ); | ||
| 245 | + std::fs::remove_file(&out).unwrap(); | ||
| 246 | + } | ||
| 247 | + panic!("cancel never landed in the drain/audio/finish window"); | ||
| 192 | } | 248 | } |
| 193 | 249 | ||
| 194 | /// Audio: the copied AAC packets have to land in the export as a track a reader | 250 | /// Audio: the copied AAC packets have to land in the export as a track a reader |