diff --git a/Cargo.lock b/Cargo.lock index cfde6aecf5..28011d3b5c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4288,6 +4288,7 @@ dependencies = [ "lightcraft-develop", "lightcraft-faces", "lightcraft-geom", + "lightcraft-gpu", "lightcraft-pipeline", "lightcraft-raster", "lightcraft-raw", @@ -4496,6 +4497,7 @@ dependencies = [ "lightcraft-engine", "lightcraft-faces", "lightcraft-geom", + "lightcraft-gpu", "lightcraft-merge", "lightcraft-meta", "lightcraft-pipeline", diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml index 689d0e64ed..4512242e6f 100644 --- a/crates/gpu/Cargo.toml +++ b/crates/gpu/Cargo.toml @@ -32,12 +32,17 @@ default = [] denoise = ["dep:lightcraft-denoise", "lightcraft-denoise/runtime"] # SAM 3's vision backbone on the GPU (`sam3`); the engine's `sam` feature turns it on sam = ["dep:lightcraft-segment"] +# `shared_device`, for other crates' tests: only ever turned on from [dev-dependencies] (it overrides +# the switch that keeps the GPU off, so the app must not have it) +test-support = [] [dev-dependencies] # tests record why they skip (`cargo xtask ci` lists the skips) lightcraft-testkit = { workspace = true } lightcraft-scenes = { workspace = true } lightcraft-raw = { workspace = true } +# this crate's integration tests use `shared_device` too (tests/shared_device.rs) +lightcraft-gpu = { workspace = true, features = ["test-support"] } [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] # the SAM 3 backbone test and benchmark compare against the candle backbone diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 4fbef07c78..0b1e581ae8 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -320,6 +320,13 @@ pub(crate) fn device() -> Option<&'static ctx::Gpu> { if WINDOW_PENDING.load(Ordering::Acquire) { return None; } + create_device() +} + +/// Create the device (once; later calls return the first outcome), or `None` when creating it +/// failed or the process is ending. +#[cfg(not(target_arch = "wasm32"))] +fn create_device() -> Option<&'static ctx::Gpu> { // creating the device is a long call into the driver: not once the process is ending let _work = exit::enter()?; GPU.get_or_init(|| { @@ -342,6 +349,57 @@ pub(crate) fn existing_device() -> Option<&'static ctx::Gpu> { GPU.get().and_then(|g| g.as_ref().ok()) } +/// For tests (hidden, like [`inject_fault`]): the render device and its queue, so a test that needs +/// a device draws on this one instead of creating another. Creating another Vulkan instance while +/// this device is in use on another thread crashes Vulkan loaders before 1.4.345 +/// (KhronosGroup/Vulkan-Loader#1863: `vkEnumeratePhysicalDevices` unloads drivers, and frees loader +/// state, that a device call on another thread is walking). +/// +/// Unlike a render, this creates the device while GPU rendering is turned off by the preference +/// (which other tests switch: `app.gpu`), and waits while the window's device is being adopted. So +/// `None` means no render device can exist in this process any more: the environment switches the +/// GPU off, creating the device failed, or the process is ending. Only then may a test create a +/// device of its own without racing this one. +/// +/// What the caller does on the device is its own: [`wait_idle`] doesn't count it, and an error +/// outside the caller's error scopes stops GPU rendering for the whole process. +/// +/// When the process is ending ([`shutting_down`]) a test must not create a device of its own either: +/// it would be created during teardown. +/// +/// The wait for the window's device has a deadline (60 s): past it this panics rather than return +/// `None`, which would let the test create a device that races the window's. +/// +/// Never call this from the app: it overrides the switch that keeps the GPU off, including after a +/// launch that crashed while creating the device (#136). So it exists only in this crate's tests and +/// with the `test-support` feature, which only dev-dependencies turn on. +#[doc(hidden)] +#[cfg(all(not(target_arch = "wasm32"), any(test, feature = "test-support")))] +#[allow(clippy::panic, reason = "a window device that stays pending fails the test that waits for it")] +pub fn shared_device() -> Option<(wgpu::Device, wgpu::Queue)> { + if env_disabled() { + return None; + } + // (the adoption clears it whatever the outcome, and the window's device may become this one; + // it creates a device and builds the kernels, which can take a while on a slow or busy machine) + const WAIT: std::time::Duration = std::time::Duration::from_secs(60); + let deadline = std::time::Instant::now() + WAIT; + while WINDOW_PENDING.load(Ordering::Acquire) && GPU.get().is_none() { + if std::time::Instant::now() >= deadline { + panic!( + "gpu::shared_device: the window's device was still pending after {WAIT:?} \ + (set_window_device_pending(true) without an adoption or set_window_device_pending(false))" + ); + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let g = match GPU.get() { + Some(g) => g.as_ref().ok(), + None => create_device(), + }; + g.map(|g| (g.device.clone(), g.queue.clone())) +} + /// Create the device and compile the kernels on a background thread now (once the window is up), /// so the first render doesn't wait ~0.3–0.4 s for it and the UI thread never does. Does nothing /// while GPU rendering is turned off. Repeated calls start one thread at most. diff --git a/crates/gpu/tests/shared_device.rs b/crates/gpu/tests/shared_device.rs new file mode 100644 index 0000000000..0de25c2538 --- /dev/null +++ b/crates/gpu/tests/shared_device.rs @@ -0,0 +1,32 @@ +//! Review of PR #4992: a test that needs a device takes the render device (`shared_device`) and +//! creates one of its own only when no render device can exist in the process (a second Vulkan +//! instance races the render device: Vulkan-Loader#1863). Another test turning GPU rendering off, +//! or the window's device being adopted, must not make `shared_device` say there is none while a +//! render could still create it. One test in its own process: the switches are process-wide. + +use std::time::Duration; + +#[test] +fn the_shared_device_is_settled_while_gpu_rendering_is_off_or_the_window_device_pending() { + lightcraft_gpu::set_window_device_pending(true); + lightcraft_gpu::set_enabled(false); + let t0 = std::time::Instant::now(); + let adoption = std::thread::spawn(|| { + std::thread::sleep(Duration::from_millis(200)); + // (the adoption couldn't start) + lightcraft_gpu::set_window_device_pending(false); + }); + let shared = lightcraft_gpu::shared_device(); + let waited = t0.elapsed(); + adoption.join().unwrap(); + if lightcraft_gpu::env_off_reason().is_none() { + assert!(waited >= Duration::from_millis(200), "waited for the window's device ({waited:?})"); + } + // created, or failed for good, or switched off by the environment: no render device can appear later + assert!(lightcraft_gpu::ready(), "the render device is settled"); + lightcraft_gpu::set_enabled(true); + assert_eq!(shared.is_some(), lightcraft_gpu::available(), "the device renders use"); + if shared.is_none() { + lightcraft_testkit::skip!(Gpu, "no GPU device: {:?}", lightcraft_gpu::unavailable_reason()); + } +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 83a18de446..2bce6a814e 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -42,7 +42,8 @@ lightcraft-denoise = { workspace = true, features = ["runtime"] } lightcraft-codecs = { workspace = true } lightcraft-faces = { workspace = true } lightcraft-merge = { workspace = true } -# a device for the GPU-resident view test (`render.rs`) +# a device for the GPU-resident view test (`render.rs`): the render device (`shared_device`) +lightcraft-gpu = { workspace = true, features = ["test-support"] } pollster = { workspace = true } [build-dependencies] diff --git a/crates/ui-egui/src/render/thumbnail_tests.rs b/crates/ui-egui/src/render/thumbnail_tests.rs index e167edf315..bc66c3982d 100644 --- a/crates/ui-egui/src/render/thumbnail_tests.rs +++ b/crates/ui-egui/src/render/thumbnail_tests.rs @@ -490,22 +490,44 @@ impl ScreenTextures for TestScreen { /// from the GPU has its pixels. Before, a mid-drag `ui.screenshot {"headless": true}` showed the /// photo as a white rectangle: the GPU-resident draft left no CPU copy (review of PR #1065). /// The test fixture with a small GPU texture (5 × 3 known texels) and a [`TestScreen`] that -/// records the ids it frees; `None` without a GPU adapter. +/// records the ids it frees; `Err` (why the test is skipped) without a GPU adapter, or when the +/// process is ending. #[cfg(not(target_arch = "wasm32"))] #[allow(clippy::type_complexity)] fn gpu_drawn_fixture( freed: std::sync::Arc>>, -) -> Option<(crate::LightcraftApp, std::rc::Rc>, egui::Context, lightcraft_engine::media::ScreenFrame)> { +) -> Result<(crate::LightcraftApp, std::rc::Rc>, egui::Context, lightcraft_engine::media::ScreenFrame), &'static str> { use lightcraft_engine::gpu::wgpu; - let device = (|| { - let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); - desc.backends = lightcraft_engine::gpu::backend::window_backends(); - desc.backend_options = lightcraft_engine::gpu::backend::backend_options(); - let instance = wgpu::Instance::new(desc); - let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; - pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("test window"), ..Default::default() })).ok() - })(); - let (device, queue) = device?; + // The render device (created if need be, also while another test has turned GPU rendering + // off), or, only when no render device can exist in this process (the environment switches the + // GPU off, or creating it failed), one device of our own for the whole process, never dropped. + // A Vulkan instance created while other tests render on the render device on other threads + // crashed Vulkan loaders before 1.4.345 with SIGSEGV (Vulkan-Loader#1863: + // `vkEnumeratePhysicalDevices` unloads drivers that another thread's device call is walking). + static OWN: std::sync::OnceLock> = std::sync::OnceLock::new(); + let (device, queue) = match lightcraft_gpu::shared_device() { + Some(shared) => shared, + // (`gpu::begin_shutdown`: a device of our own would be created during teardown) + None if lightcraft_gpu::shutting_down() => return Err("the process is ending: no device is created any more"), + None => OWN + .get_or_init(|| { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = lightcraft_engine::gpu::backend::window_backends(); + desc.backend_options = lightcraft_engine::gpu::backend::backend_options(); + let instance = wgpu::Instance::new(desc); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; + pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("test window"), ..Default::default() })).ok() + }) + .clone() + .ok_or("no GPU adapter")?, + }; + // (an error outside a scope on the render device stops GPU rendering for every test in the + // process: this one's are caught here, on this thread) + let scopes = [ + device.push_error_scope(wgpu::ErrorFilter::Validation), + device.push_error_scope(wgpu::ErrorFilter::OutOfMemory), + device.push_error_scope(wgpu::ErrorFilter::Internal), + ]; let (w, h) = (5usize, 3usize); let texture = device.create_texture(&wgpu::TextureDescriptor { label: None, @@ -524,9 +546,14 @@ fn gpu_drawn_fixture( wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w as u32 * 4), rows_per_image: Some(h as u32) }, wgpu::Extent3d { width: w as u32, height: h as u32, depth_or_array_layers: 1 }, ); + for scope in scopes.into_iter().rev() { + if let Some(e) = pollster::block_on(scope.pop()) { + panic!("the test texture: {e}"); + } + } let (mut app, work, ctx) = fixture(); app.renderer.set_screen_textures(Box::new(TestScreen(device, queue, freed))); - Some((app, work, ctx, lightcraft_engine::media::ScreenFrame { texture, width: w, height: h })) + Ok((app, work, ctx, lightcraft_engine::media::ScreenFrame { texture, width: w, height: h })) } /// A headless screenshot (driven by the control channel: `keep_pixels`) of a view drawn straight @@ -535,9 +562,12 @@ fn gpu_drawn_fixture( #[cfg(not(target_arch = "wasm32"))] #[test] fn a_headless_screenshot_reads_back_a_view_drawn_from_the_gpu() { - let Some((mut app, work, ctx, frame)) = gpu_drawn_fixture(Default::default()) else { - lightcraft_testkit::skip!(Gpu, "no GPU adapter"); - return; + let (mut app, work, ctx, frame) = match gpu_drawn_fixture(Default::default()) { + Ok(fixture) => fixture, + Err(why) => { + lightcraft_testkit::skip!(Gpu, "{why}"); + return; + } }; let (w, h) = (frame.width, frame.height); assert!(app.renderer.keep_pixels); @@ -563,9 +593,12 @@ fn a_headless_screenshot_reads_back_a_view_drawn_from_the_gpu() { #[test] fn releasing_a_slot_frees_its_gpu_texture() { let freed = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); - let Some((mut app, work, ctx, frame)) = gpu_drawn_fixture(freed.clone()) else { - lightcraft_testkit::skip!(Gpu, "no GPU adapter"); - return; + let (mut app, work, ctx, frame) = match gpu_drawn_fixture(freed.clone()) { + Ok(fixture) => fixture, + Err(why) => { + lightcraft_testkit::skip!(Gpu, "{why}"); + return; + } }; let job = app.session.render_job(PhotoId(1), 64, 64, false, true).unwrap().draft(); app.renderer.request(Slot::Main, job, 100);