forge
Explore
Log in

Don't you dare go Hollow

A refused project load cannot hang on its own decoder

Browse files at this commit

771cd4a5cfa892580f150666532b75447dd696d2Ahmet Kaan GümüşParent: 5bc0cf5
  • fix
    • a refused project load cannot hang on its own decoder
Show full message
🐛 fix(engine): a refused project load cannot hang on its own decoder

`open_project` starts decoding source 0 before it validates anything, so
by the time a later source is refused that worker has filled the
two-frame channel and parked in `send`. The receiver and the worker were
two locals, and locals drop in reverse order of declaration: the worker
joined a decode thread that only the receiver beside it could ever wake.
The app froze on a bad project file instead of showing the error.

The two are one value now. `FrameStream` holds the receiver first and
the worker second, and Rust drops fields in declaration order, so the
disconnect always precedes the join -- in an early return, on an unwind,
and in call sites not written yet. Nothing on the seek path changes:
`start_span` still installs the new receiver and parks the old worker in
the retire list without ever joining.

The device moves below the validation for the same reason. Its feeder
thread outlives the `Audio` value and only a session's `drop` retires
it, so a refusal above that line left a PipeWire stream and a thread
behind for a project that never opened.

Tests: dropping a stream whose frames nobody took returns instead of
hanging (10 s bound; hangs if the two fields are swapped), and the
refusal path itself with enough sources that the park is certain -- 60 s
hang before the fix, 0.04 s after.
crates/engine/src/decode.rsmodified+83 -17
@@ -70,6 +70,21 @@ impl Drop for Worker {
7070 }
7171 }
7272
73+/// A running worker and the frames it is sending, handed out as one value
74+/// because they must be *dropped* as one, in this order: the receiver
75+/// disconnects first, which is the only thing that wakes a worker parked in a
76+/// full `send`, and the join inside [`Worker::drop`] runs second.
77+///
78+/// Rust drops fields in declaration order, so this struct *is* that rule, and
79+/// it holds wherever the value goes: an early return out of a half-built
80+/// session, an unwind, a caller not written yet. Two separate locals do not
81+/// hold it -- they drop in reverse order of declaration, so the worker there
82+/// joins a thread nobody will ever drain, which is a hang and not a slow path.
83+pub(crate) struct FrameStream {
84+ pub(crate) frames: Receiver<Frame>,
85+ pub(crate) worker: Worker,
86+}
87+
7388 pub struct DecodeSession;
7489
7590 impl DecodeSession {
@@ -104,8 +119,10 @@ impl DecodeSession {
104119 start_frame: u32,
105120 end_frame: u32,
106121 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
107- let (meta, rx, worker) = Self::open_worker(path, start_frame, end_frame)?;
108- Ok((meta, rx, worker.detach()))
122+ let (meta, stream) = Self::open_worker(path, start_frame, end_frame)?;
123+ // The public API hands out the flag alone, so the worker is detached and
124+ // the receiver goes to the caller: nothing here joins anything.
125+ Ok((meta, stream.frames, stream.worker.detach()))
109126 }
110127
111128 /// A worker that decodes nothing and emits `len` black frames, indexed from
@@ -113,17 +130,17 @@ impl DecodeSession {
113130 /// channel as decoded frames, so a gap costs the caller no branch at all
114131 /// beyond choosing this opener: same bounded channel, same backpressure,
115132 /// same cancel, same retire path.
116- pub(crate) fn open_black(width: u32, height: u32, len: u32) -> (Receiver<Frame>, Worker) {
133+ pub(crate) fn open_black(width: u32, height: u32, len: u32) -> FrameStream {
117134 let (tx, rx) = sync_channel(2);
118135 let cancel = Arc::new(AtomicBool::new(false));
119136 if len == 0 {
120- return (
121- rx,
122- Worker {
137+ return FrameStream {
138+ frames: rx,
139+ worker: Worker {
123140 cancel,
124141 handle: None,
125142 },
126- );
143+ };
127144 }
128145 let worker_cancel = Arc::clone(&cancel);
129146 // One buffer, cloned per frame: opaque black is a constant, and the
@@ -148,7 +165,10 @@ impl DecodeSession {
148165 }
149166 })
150167 .ok();
151- (rx, Worker { cancel, handle })
168+ FrameStream {
169+ frames: rx,
170+ worker: Worker { cancel, handle },
171+ }
152172 }
153173
154174 /// As [`DecodeSession::open_range`], but the caller gets the whole
@@ -158,7 +178,7 @@ impl DecodeSession {
158178 path: impl AsRef<Path>,
159179 start_frame: u32,
160180 end_frame: u32,
161- ) -> crate::Result<(VideoMeta, Receiver<Frame>, Worker)> {
181+ ) -> crate::Result<(VideoMeta, FrameStream)> {
162182 let path = path.as_ref().to_path_buf();
163183 let (meta, demuxer) = Demuxer::open(&path)?;
164184 let end_frame = end_frame.min(meta.frame_count);
@@ -171,10 +191,12 @@ impl DecodeSession {
171191 // so the caller sees an immediate end of stream rather than an error.
172192 return Ok((
173193 meta,
174- rx,
175- Worker {
176- cancel,
177- handle: None,
194+ FrameStream {
195+ frames: rx,
196+ worker: Worker {
197+ cancel,
198+ handle: None,
199+ },
178200 },
179201 ));
180202 }
@@ -210,10 +232,12 @@ impl DecodeSession {
210232 })?;
211233 Ok((
212234 meta,
213- rx,
214- Worker {
215- cancel,
216- handle: Some(handle),
235+ FrameStream {
236+ frames: rx,
237+ worker: Worker {
238+ cancel,
239+ handle: Some(handle),
240+ },
217241 },
218242 ))
219243 }
@@ -274,6 +298,48 @@ fn run_hw(
274298 }
275299 }
276300
301+#[cfg(test)]
302+mod tests {
303+ use super::*;
304+ use std::sync::mpsc::RecvTimeoutError;
305+ use std::time::Duration;
306+
307+ fn asset(name: &str) -> PathBuf {
308+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
309+ .join("../../assets")
310+ .join(name)
311+ }
312+
313+ /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait.
314+ /// The channel is bounded, so such a worker is parked in `send` within a
315+ /// few frames, and the only thing that can wake it is its receiver going
316+ /// away -- which is why the receiver is the first field and the join inside
317+ /// `Worker::drop` is the second. Swap those two fields and this hangs.
318+ ///
319+ /// This is the whole basis of every teardown path in the engine, so it is
320+ /// asserted rather than commented: the drop runs on a second thread and a
321+ /// regression fails in ten seconds instead of hanging the suite forever.
322+ #[test]
323+ fn dropping_a_frame_stream_never_waits_for_an_undrained_channel() {
324+ let (_meta, stream) =
325+ DecodeSession::open_worker(&asset("test_baseline.mp4"), 0, u32::MAX).expect("open");
326+ // Nothing is ever received: two frames fill the channel and the next
327+ // send parks the decode thread, exactly as a refused project load does.
328+ thread::sleep(Duration::from_millis(500));
329+
330+ let (done_tx, done_rx) = sync_channel(1);
331+ thread::spawn(move || {
332+ drop(stream);
333+ let _ = done_tx.send(());
334+ });
335+ assert!(
336+ done_rx.recv_timeout(Duration::from_secs(10)) != Err(RecvTimeoutError::Timeout),
337+ "dropping a parked stream deadlocked: it joined a decode thread \
338+ while still holding the receiver that thread is waiting on"
339+ );
340+ }
341+}
342+
277343 fn run(
278344 mut demuxer: Demuxer,
279345 tx: SyncSender<Frame>,
crates/engine/src/playback.rsmodified+32 -16
@@ -122,7 +122,7 @@ impl PlaybackSession {
122122 let path = path.as_ref().to_path_buf();
123123 // `open_worker` rather than `open` purely for the worker handle: the
124124 // field has to exist from the start for the first seek to use it.
125- let (meta, frames, worker) = DecodeSession::open_worker(&path, 0, u32::MAX)?;
125+ let (meta, stream) = DecodeSession::open_worker(&path, 0, u32::MAX)?;
126126 let audio = open_audio(&path);
127127 let source = match audio {
128128 Some(_) => ClockSource::Audio,
@@ -134,8 +134,8 @@ impl PlaybackSession {
134134 let span = project.span_at(Lane::Video, 0).expect("never empty");
135135 Ok(Self {
136136 meta,
137- frames,
138- worker,
137+ frames: stream.frames,
138+ worker: stream.worker,
139139 retired: Vec::new(),
140140 clock: PlaybackClock::new(source),
141141 audio,
@@ -162,13 +162,22 @@ impl PlaybackSession {
162162 /// The undo history is not saved: `undo` is `false` on a fresh load.
163163 pub fn open_project(path: &Path) -> crate::Result<Self> {
164164 let doc = crate::edith::load(path)?;
165- let first = doc.sources.first().ok_or("the project names no sources")?;
165+ // Owned: the sources move into the `Project` below, and the device is
166+ // opened after that (see the comment there).
167+ let first = doc
168+ .sources
169+ .first()
170+ .cloned()
171+ .ok_or("the project names no sources")?;
166172 // Source 0 both scaffolds the session and defines the timeline, so it
167173 // is opened for playback rather than merely probed.
168- let (meta, frames, worker) = DecodeSession::open_worker(first, 0, u32::MAX)
174+ // One value, not two locals: everything below this line can refuse, and
175+ // locals drop in reverse declaration order -- a bare worker would join
176+ // its decode thread while the receiver next to it was still holding
177+ // that thread parked in `send`, which is a hang (see [`FrameStream`]).
178+ let (meta, stream) = DecodeSession::open_worker(&first, 0, u32::MAX)
169179 .map_err(|e| format!("source {}: {e}", first.display()))?;
170- let audio = open_audio(first);
171- let first_audio = AudioSession::probe(first)?;
180+ let first_audio = AudioSession::probe(&first)?;
172181
173182 let mut counts = vec![meta.frame_count];
174183 for source in &doc.sources[1..] {
@@ -193,10 +202,16 @@ impl PlaybackSession {
193202 let playhead = doc.playhead;
194203 let project = Project::from_parts(doc.sources, doc.video, doc.audio)?;
195204 let span = project.span_at(Lane::Video, 0).expect("never empty");
205+ // Last, because it is the one thing here that cannot be taken back: the
206+ // feeder thread outlives the `Audio` value (it holds its own clones) and
207+ // only a session's `drop` retires it, so a refusal above this line would
208+ // leave a PipeWire stream and a thread behind for a project that never
209+ // opened. Nothing before it needs the device.
210+ let audio = open_audio(&first);
196211 let mut session = Self {
197212 meta,
198- frames,
199- worker,
213+ frames: stream.frames,
214+ worker: stream.worker,
200215 retired: Vec::new(),
201216 clock: PlaybackClock::new(match audio {
202217 Some(_) => ClockSource::Audio,
@@ -318,7 +333,7 @@ impl PlaybackSession {
318333 in_frame,
319334 in_frame + span.len,
320335 )
321- .map(|(_, frames, worker)| (frames, worker))
336+ .map(|(_, stream)| stream)
322337 .inspect_err(|e| eprintln!("timeline frame {}: video open failed: {e}", span.start)),
323338 None => Ok(DecodeSession::open_black(
324339 self.meta.width,
@@ -326,12 +341,13 @@ impl PlaybackSession {
326341 span.len,
327342 )),
328343 };
329- if let Ok((frames, worker)) = opened {
330- // Receiver first, worker second: the drop of the old receiver is
331- // what wakes a worker parked in `send`, and only then can it return
332- // and be reaped by a later sweep.
333- self.frames = frames;
334- self.retire(worker);
344+ if let Ok(stream) = opened {
345+ // Receiver first, worker second: the drop of the *old* receiver is
346+ // what wakes the outgoing worker if it is parked in `send`, and only
347+ // then can it return and be reaped by a later sweep. Nothing here
348+ // joins, so this ordering costs the seek nothing.
349+ self.frames = stream.frames;
350+ self.retire(stream.worker);
335351 }
336352 self.span = span;
337353 }
crates/engine/tests/saveload.rsmodified+41 -0
@@ -256,6 +256,47 @@ fn a_source_that_shrank_is_refused_by_clip() {
256256 assert_eq!(whole.timeline_duration(), 5.0);
257257 }
258258
259+/// A refusal must *return*. Opening a project starts decoding source 0 before
260+/// it has validated anything, so by the time a later source is refused the
261+/// worker is several frames in -- and with a two-frame channel that nobody is
262+/// draining, it is parked in `send`. Tearing that down in the wrong order joins
263+/// a thread that is waiting for a receiver the same scope still holds, and the
264+/// app hangs on a bad project file instead of showing the error.
265+///
266+/// The many sources are what make the park a certainty rather than a race: each
267+/// one is opened and probed before the clip check that refuses, which is far
268+/// longer than the few frames it takes to fill the channel.
269+#[test]
270+fn a_refused_project_does_not_hang_on_its_own_decoder() {
271+ let dir = scratch("refusal_hang");
272+ copy_in(&dir, "test_av.mp4");
273+ let path = dir.join("refused.edith");
274+ let mut text = String::from("edith 1\nplayhead 0\n");
275+ for _ in 0..1024 {
276+ text.push_str("source test_av.mp4\n");
277+ }
278+ // Legal until the last line, which runs off the end of a 150-frame file.
279+ text.push_str("clip 0 150 0\nclip 0 10000 0\n");
280+ std::fs::write(&path, &text).expect("write");
281+
282+ let (tx, rx) = std::sync::mpsc::sync_channel(1);
283+ let probe = path.clone();
284+ std::thread::spawn(move || {
285+ let err = PlaybackSession::open_project(&probe)
286+ .err()
287+ .map(|e| e.to_string());
288+ let _ = tx.send(err);
289+ });
290+ match rx.recv_timeout(std::time::Duration::from_secs(60)) {
291+ Ok(Some(err)) => assert!(err.contains("150"), "refused, but not by name: {err}"),
292+ Ok(None) => panic!("a clip past the end of its file must not open"),
293+ Err(_) => panic!(
294+ "open_project hung on a refusal: its own decode worker is parked in \
295+ send and the teardown is waiting for it"
296+ ),
297+ }
298+}
299+
259300 #[test]
260301 fn a_project_that_names_itself_is_refused() {
261302 let dir = scratch("self_reference");