Quitting while preview frames render no longer crashes at exit (#3846) (#3847)

* #3846: stop the frame workers before the app exits

Rayon's pools don't join their threads, so on quit `main` could return
while a preview worker was still polling or reading back from the GPU.
The process's exit handlers then tore the Vulkan device down under that
worker: SIGSEGV (in the readback copy, or a freed dispatch table) or an
abort in the validation layer. `Frames::shutdown` drops the queued
frames, calls off the viewer's running ones and waits (up to 5 s) for
the frames still rendering; `on_exit` calls it first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Wait for all frame workers before tearing down the GPU

* Release the shutdown regression worker during test unwinding

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Fredrik Hallin <fredrik.hallin@guidelinegeo.com>
This commit is contained in:
authored and GitHub committed 2026-11-28 09:34:44 +01:00
1 parent ebc1d0076b
commit 8aac28cf6c
3 files changed
+146 -11

No files matched your search

+5
View File
@@ -160,6 +160,11 @@ impl EffectcraftApp {
impl eframe::App for EffectcraftApp {
fn on_exit(&mut self) {
// The frame workers must be off the GPU before `main` returns (see `Frames::shutdown`).
#[cfg(not(target_arch = "wasm32"))]
while !self.frames.shutdown(std::time::Duration::from_secs(5)) {
log::warn!("waiting for frame renders to stop before GPU teardown");
}
self.save_workspace_state();
// Clean exit: no crash recovery next launch (unless the graphics device was lost with
// unsaved changes, which are in the auto-save it offers).
+55 -8
View File
@@ -758,6 +758,12 @@ pub struct Frames {
#[cfg(not(target_arch = "wasm32"))]
content_key_jobs: Arc<Mutex<ContentKeyJobs>>,
gpu_retired: Arc<AtomicBool>,
/// [`Frames::shutdown`] was called: the workers start no more frames.
#[cfg(not(target_arch = "wasm32"))]
closing: Arc<AtomicBool>,
/// Pool and lane threads inside [`Worker::drain`] (see [`Frames::shutdown`]).
#[cfg(not(target_arch = "wasm32"))]
draining: Arc<std::sync::atomic::AtomicUsize>,
/// [`comp_content`] identities by (revision, comp), with the project that keeps an identity
/// found by [`Frames::identity`] in another project.
identities: Mutex<HashMap<(u64, u64), Identity>>,
@@ -881,6 +887,10 @@ impl Frames {
#[cfg(not(target_arch = "wasm32"))]
content_key_jobs: Arc::default(),
gpu_retired: Arc::default(),
#[cfg(not(target_arch = "wasm32"))]
closing: Arc::default(),
#[cfg(not(target_arch = "wasm32"))]
draining: Arc::default(),
identities: Mutex::default(),
bases: Mutex::default(),
keepers: Mutex::default(),
@@ -1049,6 +1059,31 @@ impl Frames {
}
}
/// Stops the frame workers before the app exits: queued frames are dropped, the viewer's
/// running frames are called off, and this waits up to `limit` for the frames still
/// rendering. Rayon's pools don't join their threads, so without it `main` returned while a
/// worker was still polling or reading back from the GPU, and the exit handlers that tear
/// the driver's device down crashed it (SIGSEGV or abort at exit). `false` if workers were
/// still rendering at `limit`.
#[cfg(not(target_arch = "wasm32"))]
pub fn shutdown(&self, limit: std::time::Duration) -> bool {
self.closing.store(true, Ordering::SeqCst);
if let Ok(mut q) = self.queue.lock() {
q.jobs.clear();
for (_, cancel) in &q.urgent_cancels {
cancel.store(true, Ordering::Relaxed);
}
}
let end = std::time::Instant::now() + limit;
while self.draining.load(Ordering::SeqCst) > 0 {
if std::time::Instant::now() >= end {
return false;
}
std::thread::sleep(std::time::Duration::from_millis(2));
}
true
}
/// Actual native frame-worker capacity, including the OS fallback pool.
#[cfg(not(target_arch = "wasm32"))]
pub fn parallelism(&self) -> usize {
@@ -1692,6 +1727,10 @@ impl Frames {
content_keys: self.content_keys.clone(),
virtual_id: self.virtual_id.clone(),
gpu_retired: self.gpu_retired.clone(),
#[cfg(not(target_arch = "wasm32"))]
closing: self.closing.clone(),
#[cfg(not(target_arch = "wasm32"))]
draining: self.draining.clone(),
}
}
@@ -1830,6 +1869,10 @@ struct Worker {
content_keys: ContentKeys,
virtual_id: Option<Arc<dyn Fn(&str) -> Option<(u64, u64)> + Send + Sync>>,
gpu_retired: Arc<AtomicBool>,
#[cfg(not(target_arch = "wasm32"))]
closing: Arc<AtomicBool>,
#[cfg(not(target_arch = "wasm32"))]
draining: Arc<std::sync::atomic::AtomicUsize>,
}
#[cfg(not(target_arch = "wasm32"))]
@@ -1840,24 +1883,27 @@ thread_local! {
static DRAINING_LANE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Clears [`DRAINING`] when the drain ends, even by a panic.
/// Clears [`DRAINING`] and leaves the count of drains ([`Frames::shutdown`] waits for it) when
/// the drain ends, even by a panic.
#[cfg(not(target_arch = "wasm32"))]
struct Draining;
struct Draining<'a>(&'a std::sync::atomic::AtomicUsize);
#[cfg(not(target_arch = "wasm32"))]
impl Draining {
fn enter(lane: Option<usize>) -> Option<Self> {
impl<'a> Draining<'a> {
fn enter(lane: Option<usize>, count: &'a std::sync::atomic::AtomicUsize) -> Option<Self> {
if DRAINING.replace(true) {
return None;
}
DRAINING_LANE.set(lane.is_some());
Some(Self)
count.fetch_add(1, Ordering::SeqCst);
Some(Self(count))
}
}
#[cfg(not(target_arch = "wasm32"))]
impl Drop for Draining {
impl Drop for Draining<'_> {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::SeqCst);
DRAINING_LANE.set(false);
DRAINING.set(false);
}
@@ -1887,8 +1933,9 @@ impl Worker {
/// `lane`: the lane this runs on (see [`Queue::idle_lanes`]), `None` on the pool.
#[cfg(not(target_arch = "wasm32"))]
fn drain(&self, lane: Option<usize>) {
let Some(_reset) = Draining::enter(lane) else { return };
while self.run_next(lane) {}
let Some(_reset) = Draining::enter(lane, &self.draining) else { return };
// (`closing` is read after joining the count: `shutdown` sets it before reading the count)
while !self.closing.load(Ordering::SeqCst) && self.run_next(lane) {}
}
/// Render the queued job that matters most right now, on lane `lane` (`None`: on
+86 -3
View File
@@ -439,6 +439,87 @@ fn a_newer_viewer_frame_calls_off_the_one_rendering() {
assert_eq!(f.inflight(), 0, "released");
}
/// Quitting while frames render: `main` returned with a worker still inside a frame's GPU work,
/// and the process's exit handlers tore the device down under it (SIGSEGV or abort at exit).
/// `shutdown` returns only once the running frame is done, and the queued ones never start.
#[test]
fn shutdown_waits_for_the_frames_rendering_and_drops_the_queued_ones() {
use effectcraft_engine::Session;
use effectcraft_engine::project::{Footage, FootageKind};
use effectcraft_engine::render::Image;
use effectcraft_engine::time::FrameRate;
use serde_json::json;
use std::sync::atomic::AtomicUsize;
/// A movie whose frames each take a while and can't be called off (like a GPU readback).
#[derive(Default)]
struct Slow {
started: AtomicUsize,
finished: AtomicUsize,
release: std::sync::atomic::AtomicBool,
}
impl FootageSource for Slow {
fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option<Arc<Image>> {
self.started.fetch_add(1, Ordering::SeqCst);
while !self.release.load(Ordering::SeqCst) {
std::thread::yield_now();
}
self.finished.fetch_add(1, Ordering::SeqCst);
Some(Arc::new(Image::new(4, 4)))
}
}
struct Release(Arc<Slow>);
impl Drop for Release {
fn drop(&mut self) {
self.0.release.store(true, Ordering::SeqCst);
}
}
let mut s = Session::default();
let cid = ItemId(s.execute("comp.new", json!({"name": "A", "width": 8, "height": 8, "duration": 10})).unwrap()["comp"].as_u64().unwrap());
let clip = Footage {
kind: FootageKind::Video,
width: 4,
height: 4,
has_video: true,
frame_rate: FrameRate::FPS_30,
duration: Tick::from_seconds_f64(10.0),
..Default::default()
};
let item = Arc::make_mut(&mut s.project).add_item("clip.mov", Default::default(), None, ItemKind::Footage(clip));
s.execute("layer.addItem", json!({"item": item.0})).unwrap();
let footage = Arc::new(Slow::default());
let src = RenderSource {
project: s.project.clone(),
footage: footage.clone(),
expr: None,
layer_cache: Arc::default(),
gpu: None,
gpu_display: false,
disk: None,
};
let f = Frames::default();
let _release = Release(footage.clone());
let content = f.content_of(&s.project, s.revision, cid);
let key = |frame| FrameKey { revision: s.revision, content, comp: cid.0, frame, scale: 1000, view: 0, opts: 0 };
for frame in 0..64 {
f.request(&src, key(frame), cid, FrameRate::FPS_30.tick_of(frame), RenderOpts::default());
}
for _ in 0..1000 {
if footage.started.load(Ordering::SeqCst) > 0 {
break;
}
std::thread::sleep(std::time::Duration::from_millis(2));
}
assert!(footage.started.load(Ordering::SeqCst) > 0, "a frame started rendering");
assert!(!f.shutdown(std::time::Duration::ZERO), "an active render prevents shutdown");
footage.release.store(true, Ordering::SeqCst);
assert!(f.shutdown(std::time::Duration::from_secs(10)), "the workers stopped in time");
let started = footage.started.load(Ordering::SeqCst);
assert_eq!(footage.finished.load(Ordering::SeqCst), started, "no frame is still rendering once shutdown returns");
assert!(started < 64, "the queued frames were dropped ({started} of 64 started)");
std::thread::sleep(std::time::Duration::from_millis(400));
assert_eq!(footage.started.load(Ordering::SeqCst), started, "no frame starts after shutdown");
}
/// #284: scrubbing asks for a viewer frame at every step; a newer one drops the comp's viewer
/// frames still waiting (they would all render first), but not prefetch frames or another
/// comp's viewer frame.
@@ -3508,11 +3589,12 @@ fn gpu_preview_lane_waits_for_admission_and_resets_its_marker() {
let pool = rayon::ThreadPoolBuilder::new().num_threads(LANE_WIDTH).build().unwrap();
let (started, ready) = std::sync::mpsc::channel();
let (tx, rx) = std::sync::mpsc::channel();
let drains = std::sync::atomic::AtomicUsize::new(0);
let (early, admitted, helper) = std::thread::scope(|scope| {
scope.spawn(|| {
pool.install(|| {
let _drain = Draining::enter(Some(0)).unwrap();
assert!(Draining::enter(None).is_none(), "a lane cannot start a nested drain");
let _drain = Draining::enter(Some(0), &drains).unwrap();
assert!(Draining::enter(None, &drains).is_none(), "a lane cannot start a nested drain");
assert!(DRAINING_LANE.get(), "nested rejection must not clear the lane marker");
started.send(()).unwrap();
tx.send(slots.for_render(2).is_some()).unwrap();
@@ -3536,10 +3618,11 @@ fn gpu_preview_lane_waits_for_admission_and_resets_its_marker() {
assert!(!DRAINING.get());
assert!(!DRAINING_LANE.get());
let panic = std::panic::catch_unwind(|| {
let _drain = Draining::enter(Some(0)).unwrap();
let _drain = Draining::enter(Some(0), &drains).unwrap();
panic!("synthetic lane failure");
});
assert!(panic.is_err());
assert_eq!(drains.load(Ordering::SeqCst), 0, "a panicking drain leaves the count");
assert!(!DRAINING.get());
assert!(!DRAINING_LANE.get());
});