Wait for the GPU warm-up before a test or headless process ends (#620) (#4697)

* LR-BEHAV-GPU: no GPU warm-up is still loading the driver when a test or headless process ends (issue #620)

The first frame starts the GPU device warm-up on a thread of its own. A process
that ended a few milliseconds later, as every test does under nextest, could
exit while that thread was inside the Vulkan loader's dlopen of the driver,
running libLLVM's initializers: a SIGSEGV after the test had passed, or a hang.
Only the window's exit (LightcraftApp::shutdown) waited for GPU work.

warm_up now counts as in flight from the moment it is called, before its thread
exists, and wait_warm_up waits for it. Dropping a LightcraftApp waits for it,
bounded, unless shutdown already ran.

* LR-BEHAV-GPU: warm_up counts as in flight before it marks itself started (issue #620)

A second warm_up call racing the first could find it marked started and return
before the first had entered the gate, so a host dropping its app right after
that second call saw no warm-up in flight. The gate is now entered first, a
call that starts nothing drops its entry, and a closed gate starts nothing.

* LR-BEHAV-GPU: the app waits for the GPU warm-up when dropped on native builds only (issue #620)

The web build has no warm-up thread (warm_up and wait_warm_up do nothing there),
and the web host replaces the app's UI state by moving it out of the app, which
a Drop impl forbids (E0509 in the wasm check).

* LR-BEHAV-GPU: a deterministic test for the app's warm-up wait on drop (issue #620)

Fred's review of #4697: the first regression test could pass without
exercising the wait — ready() || !enabled() also holds when the warm-up
finished or never started, and no pending warm-up was ever established.

The gpu crate exposes doc-hidden test support, hold_warm_up_for_test(),
entering the same gate the real warm_up enters: a substitute warm-up the
caller holds. The test proves it is in flight (wait_warm_up(ZERO) is
false), builds an app that never ran a frame on another thread (the app
is not Send — its host-service callbacks are not — so it is built there),
and verifies with channel synchronization that dropping the app does not
return while the hold is kept, and returns once it is released. Without
the wait in Drop for LightcraftApp it fails at that assertion; with it,
it passes. No GPU, no device, no timing beyond a one-second observation
window whose proof is the release.

---------

Co-authored-by: skylartaylor <skylartaylor@users.noreply.github.com>
This commit is contained in:
skylar taylor-barrick
2026-12-02 08:34:26 -06:00
committed by GitHub
parent e944599ef4
commit e3e76fd0f0
5 changed files with 117 additions and 2 deletions
+52 -1
View File
@@ -291,6 +291,11 @@ fn env_disabled() -> bool {
#[cfg(not(target_arch = "wasm32"))]
static GPU: std::sync::OnceLock<Result<ctx::Gpu, String>> = std::sync::OnceLock::new();
/// A [`warm_up`] thread in flight. [`warm_up`] enters it before the thread exists, so
/// [`wait_warm_up`] sees the warm-up from the moment [`warm_up`] returns.
#[cfg(not(target_arch = "wasm32"))]
static WARM_UP: exit::Gate = exit::Gate::new();
/// Set while [`adopt_window_device`] is about to run or running: [`device`] and [`warm_up`] then
/// don't create a device of their own (review of PR #1065: the settings' warm-up raced the
/// adoption thread and could win, so the window's device went unused).
@@ -407,10 +412,16 @@ pub fn warm_up() {
#[cfg(not(target_arch = "wasm32"))]
if !env_disabled() && ENABLED.load(Ordering::SeqCst) && GPU.get().is_none() && !WINDOW_PENDING.load(Ordering::Acquire) {
static STARTED: AtomicBool = AtomicBool::new(false);
// In flight from here, before `STARTED` is set and before the thread exists: a host that ends
// the process right after any `warm_up` returns (this one, or a concurrent call that finds
// the thread starting) must find it with `wait_warm_up`. A closed gate starts nothing; a call
// that starts nothing drops its token again, and a failed spawn drops it with the closure.
let Some(in_flight) = WARM_UP.enter() else { return };
if STARTED.swap(true, Ordering::SeqCst) {
return;
}
let spawned = std::thread::Builder::new().name("lc-gpu-init".into()).spawn(|| {
let spawned = std::thread::Builder::new().name("lc-gpu-init".into()).spawn(move || {
let _in_flight = in_flight;
loop {
let _ = device();
if GPU.get().is_some() || shutting_down() || env_disabled() {
@@ -445,6 +456,46 @@ pub fn ready() -> bool {
}
}
/// Wait up to `timeout` for a [`warm_up`] thread to finish (the device created, or given up).
/// `true`: none is running. That thread loads the driver, and a process that ends meanwhile crashes
/// inside it (issue #620): a host that ends the process without [`begin_shutdown`] and
/// [`wait_idle`] (a test, a headless run) waits for it first.
pub fn wait_warm_up(timeout: std::time::Duration) -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
WARM_UP.wait_idle(timeout)
}
#[cfg(target_arch = "wasm32")]
{
let _ = timeout;
true
}
}
/// The guard [`hold_warm_up_for_test`] returns: the substitute warm-up, held until it is dropped.
#[cfg(not(target_arch = "wasm32"))]
struct WarmUpHold(Option<exit::Work<'static>>);
/// A substitute device warm-up in flight, held until the returned guard is dropped — the same
/// gate the real [`warm_up`] enters, so a caller can prove a warm-up is pending and that a wait
/// waits for it, without a GPU, a device or a race. Test support for one test,
/// `tests::gpu_warm_up::dropping_the_app_waits_for_a_warm_up_that_is_in_flight` in
/// lightcraft-ui-egui (a `#[cfg(test)]` helper here would not be visible to that crate's test
/// build); not for production code — a real warm-up is started with [`warm_up`]. `None` only
/// when the process is ending, when no warm-up can be in flight anyway.
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub fn hold_warm_up_for_test() -> Option<impl Drop> {
WARM_UP.enter().map(|work| WarmUpHold(Some(work)))
}
#[cfg(not(target_arch = "wasm32"))]
impl Drop for WarmUpHold {
fn drop(&mut self) {
drop(self.0.take());
}
}
/// Whether a usable GPU adapter exists and GPU rendering is enabled (creates the device on first
/// use).
pub fn available() -> bool {
+15
View File
@@ -775,6 +775,21 @@ impl LightcraftApp {
}
}
/// The app's first frame starts the GPU device warm-up (`app.gpu`), on a thread that loads the
/// driver. A process that ends while it does crashes inside the driver (issue #620; in CI, tests
/// killed by SIGSEGV after they had passed). The window ends through [`LightcraftApp::shutdown`],
/// which decides that itself; any other end (a test returning, a headless run) passes through here
/// first, so it waits for the warm-up, bounded. (Native only: there is no warm-up thread on the web,
/// and the web host moves fields out of the app.)
#[cfg(not(target_arch = "wasm32"))]
impl Drop for LightcraftApp {
fn drop(&mut self) {
if !lightcraft_engine::gpu::shutting_down() {
let _ = lightcraft_engine::gpu::wait_warm_up(std::time::Duration::from_secs(30));
}
}
}
/// "Found 3 faces in 2 photos" for a `faces.detect` result.
pub(crate) fn detect_summary(v: &Value) -> String {
let photos = v["photos"].as_array().map(Vec::as_slice).unwrap_or_default();
+1
View File
@@ -55,6 +55,7 @@ mod filmstrip_drag;
mod find_similar;
mod focus_point;
mod folder_drop;
mod gpu_warm_up;
mod grading;
mod grid;
mod grid_badges;
+44
View File
@@ -0,0 +1,44 @@
//! A test is a process of its own under nextest, and that process ends as soon as the test
//! returns. The app's first frame starts the GPU device warm-up on a thread of its own; a process
//! that ends while that thread is still loading the driver crashes there (issue #620; in CI,
//! tests killed by SIGSEGV after they had passed). So dropping the app waits for a warm-up that
//! is still in flight. This exercises that wait with a substitute warm-up held on the same gate,
//! so it needs no GPU, no device and no race.
use std::sync::mpsc;
use std::time::Duration;
use crate::{LightcraftApp, Services};
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn dropping_the_app_waits_for_a_warm_up_that_is_in_flight() {
// In flight from here until `hold` is dropped (test support in the gpu crate, on the gate the
// real warm-up enters)
let hold = lightcraft_engine::gpu::hold_warm_up_for_test().expect("the warm-up gate is open in a test");
assert!(!lightcraft_engine::gpu::wait_warm_up(Duration::ZERO), "the substitute warm-up is in flight");
let (tx, rx) = mpsc::channel::<&'static str>();
let dropping = std::thread::spawn(move || {
// Built here, not moved in: `LightcraftApp` is not `Send` (its host-service callbacks are
// not), and this test does not need it to be. An app that never ran a frame has nothing of
// its own pending, so the only thing that can hold up its drop is the warm-up wait.
let app = LightcraftApp::new(lightcraft_engine::Session::new(), Services { png: None, ..Default::default() });
tx.send("dropping").unwrap();
drop(app);
tx.send("dropped").unwrap();
});
assert_eq!(rx.recv_timeout(Duration::from_secs(30)).unwrap(), "dropping");
// The drop has not returned while the warm-up is held. The one second is only the
// observation window for that — the thread is already past "dropping", sent after the
// construction and just before the drop, so an unwaiting drop would have torn the app down
// and returned well inside it — and the proof is the step after: releasing the hold is what
// lets the drop return.
assert_eq!(
rx.recv_timeout(Duration::from_secs(1)),
Err(mpsc::RecvTimeoutError::Timeout),
"dropping the app returned while a warm-up was in flight"
);
drop(hold);
assert_eq!(rx.recv_timeout(Duration::from_secs(30)).unwrap(), "dropped");
dropping.join().unwrap();
}
+5 -1
View File
@@ -113,7 +113,11 @@ after settings and library are saved): `gpu::begin_shutdown()` — from then on
on the CPU — then the render pool stops (queued jobs dropped, running ones waited for) and
`gpu::wait_idle` waits for GPU work on other threads (export, denoise, the device warm-up). One
deadline of 2 s covers it all; past it the app quits anyway. A job pool that is dropped (headless
hosts, tests) waits for its running jobs the same way (`JobPool::shutdown`, `crates/preview/src/pool.rs`).
hosts, tests) waits for its running jobs the same way (`JobPool::shutdown`, `crates/preview/src/pool.rs`),
and a dropped `LightcraftApp` waits, bounded, for a device warm-up still loading the driver
(`gpu::wait_warm_up`; the warm-up counts from the moment `gpu::warm_up` is called) unless `shutdown`
already ran. Without that, a test process ending a few milliseconds after its first frame crashed or
hung inside the Vulkan loader as it opened the driver.
**Crash sentinel.** The desktop app writes `gpu-init.marker` into its settings folder (next to
`ui.json`: `%APPDATA%\LightCraft`, `~/Library/Application Support/LightCraft`,