diff --git a/Cargo.lock b/Cargo.lock index f99595d8da..0b5c9b8eb5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2273,6 +2273,7 @@ name = "craft-gpu-wgpu" version = "0.1.0" dependencies = [ "craft-gpu", + "craft-gpu-device", "craft-gpu-providers", "pollster 0.4.0", "wgpu", diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md index 3c7da59b5c..5c8c2d8fe5 100644 --- a/crates/gpu-device/README.md +++ b/crates/gpu-device/README.md @@ -65,7 +65,8 @@ Licensed under MIT OR Apache-2.0. `Device::poll` raises on a lost device and record the loss. - wgpu keeps one device-lost callback per device, and a later `set_device_lost_callback` replaces the one `DeviceHealth::watch` set. A `craft-gpu` context on a watched device reads - `DeviceHealth::device_status` instead of setting its own callback. + `DeviceHealth::device_status` instead of setting its own callback, as `craft-gpu-wgpu`'s + `WgpuContext` does. - After an out-of-memory error, polls and waits keep running, so staging memory is reclaimed. The app reads `DeviceHealth::out_of_memory_count` when it handles the error, frees memory, and passes the count to `DeviceHealth::clear_out_of_memory`. The device is then healthy again, diff --git a/crates/gpu-wgpu/Cargo.toml b/crates/gpu-wgpu/Cargo.toml index ecf45c62f0..da5d9ca867 100644 --- a/crates/gpu-wgpu/Cargo.toml +++ b/crates/gpu-wgpu/Cargo.toml @@ -16,12 +16,14 @@ craft-gpu = { workspace = true } wgpu = { workspace = true, features = ["webgpu"] } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# Chooses and opens the device, and watches it for a loss (`adapter-probe`). +craft-gpu-device = { workspace = true, optional = true } pollster = { workspace = true, optional = true } wgpu = { workspace = true } [features] default = [] -adapter-probe = ["dep:pollster"] +adapter-probe = ["dep:pollster", "dep:craft-gpu-device"] native-vulkan = ["wgpu/vulkan"] native-dx12 = ["wgpu/dx12"] native-metal = ["wgpu/metal"] @@ -33,3 +35,7 @@ pollster = { workspace = true } # providers against a real WgpuContext, not just craft-gpu-null, per RFC-0022 acceptance # requirement 2. Dev-only: no cycle (craft-gpu-providers never depends on craft-gpu-wgpu). craft-gpu-providers = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +# The noop backend opens devices without a GPU in the tests. +wgpu = { workspace = true, features = ["noop"] } diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index ec0e71b276..e261f85bb5 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -1,10 +1,13 @@ //! wgpu-backed [`GpuContext`](craft_gpu::GpuContext). //! //! WebGPU on `wasm32`; native APIs when backend features are enabled. With the `adapter-probe` -//! feature (native only, pollster) and at least one `native-*` backend feature, -//! [`WgpuContext::new`] requests a real device and builds [`DeviceCaps`] from what that device -//! actually enabled (`Device::limits()` / `Device::features()`), never from the adapter's -//! advertised maximum. Without a usable adapter (the features above are off, no GPU is present, +//! feature (native only), [`WgpuContext::new`] opens a real device through `craft-gpu-device` +//! (its adapter choice for `Preference::Auto`, its driver corrections and its fallback order) and +//! builds [`DeviceCaps`] from what that device actually enabled (`Device::limits()` / +//! `Device::features()`), never from the adapter's advertised maximum. +//! [`WgpuContext::from_opened`] and [`WgpuContext::with_device`] take a device the caller opened. +//! A loss is read from the device's `craft_gpu_device::DeviceHealth`, which owns the device's +//! device-lost callback. Without a usable adapter (`adapter-probe` is off, no GPU is present, //! or on `wasm32` where real device creation needs the async worker-init path noted in //! `docs/gpu-backends.md`), the context degrades to the same in-memory staging behavior as //! `craft_gpu_null::NullContext` (not a dependency of this crate; named here only for context); @@ -32,29 +35,17 @@ fn probe_fallback(backend_name: &str, device_name: &str) -> DeviceCaps { #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] fn probe_caps_native() -> DeviceCaps { - let instance = native::instance(); - let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) { - Ok(adapter) => adapter, - Err(_) => return probe_fallback("wgpu", "no-adapter"), - }; - let info = adapter.get_info(); - let limits = adapter.limits(); - DeviceCaps { - backend_name: format!("{:?}", info.backend), - device_name: info.name, - max_storage_buffer_binding_size: limits.max_storage_buffer_binding_size, - max_buffer_size: limits.max_buffer_size, - max_texture_dimension_2d: limits.max_texture_dimension_2d, - features: Vec::new(), - vendor_id: info.vendor, - software: info.device_type == wgpu::DeviceType::Cpu, - } + native::probe_caps_on(&native::instance()) } /// Adapter-advertised limits, when an adapter is available; otherwise conservative defaults. This /// is the quick, device-free probe for UI surfaces that want a number before any context exists /// (Settings). It is advisory only: these are the adapter's maximums, not a device's granted -/// ones. [`WgpuContext::caps`] is the authoritative, device-truth source once a context exists. +/// ones. With `adapter-probe` it reports the adapter `craft_gpu_device::pick` chooses for +/// `Preference::Auto` without opening a device on it; when a device then fails to open there, +/// [`WgpuContext::new`] opens the next adapter in `craft_gpu_device::ranked` order, or a software +/// one, which this probe does not report. [`WgpuContext::caps`] is the authoritative, device-truth +/// source once a context exists. pub fn probe_caps() -> DeviceCaps { #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] { @@ -74,11 +65,10 @@ pub fn probe_caps() -> DeviceCaps { #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] mod native { - use std::sync::{Arc, Mutex}; + use craft_gpu::DeviceCaps; + use craft_gpu_device::{Capabilities, DeviceHealth, Opened, Preference, Request}; - use craft_gpu::{DeviceCaps, GpuFault}; - - use crate::{Backing, DeviceBacking}; + use crate::{Backing, DeviceBacking, probe_fallback}; /// Features this context asks a device for. No provider dispatches a real WGSL job on wgpu /// yet (`craft-gpu-providers` ships CPU stand-ins, by design, until that lands); extend this @@ -86,60 +76,56 @@ mod native { /// [`create_device`]. const DESIRED_FEATURES: wgpu::Features = wgpu::Features::empty(); - /// An instance over whichever native backends were compiled in (`native-vulkan`, - /// `native-dx12`, `native-metal`, `native-gles`), honoring `WGPU_BACKEND` when set, so the + /// An instance over `craft_gpu_device::native_descriptor`'s backends (Vulkan, Metal and + /// DirectX 12, plus OpenGL except on Windows), honoring `WGPU_BACKEND` when set, so the /// same build can be pointed at a software Vulkan adapter (lavapipe/llvmpipe) in a local container run or a CI lane. - /// `new_without_display_handle` because this context never has a window (no surface is ever - /// requested); FilmCraft's own off-screen export device uses the same constructor for the - /// same reason (`filmcraft-gpu`'s `export_renderer.rs`, see `docs/gpu-backends.md`). + /// The descriptor has no display handle because this context never has a window (no surface + /// is ever requested); FilmCraft's own off-screen export device uses the same constructor for + /// the same reason (`filmcraft-gpu`'s `export_renderer.rs`, see `docs/gpu-backends.md`). pub(crate) fn instance() -> wgpu::Instance { - let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + let mut desc = craft_gpu_device::native_descriptor(); if let Some(backends) = wgpu::Backends::from_env() { desc.backends = backends; } wgpu::Instance::new(desc) } - /// Request a real device. `None` on the defined no-adapter path (no usable adapter): the - /// caller degrades to the staging backing, identical in shape to `craft-gpu-null`. + /// Open a real device on `instance` with `craft-gpu-device`'s choice for + /// `Preference::Auto`. `None` on the defined no-adapter path (no usable adapter): the caller + /// degrades to the staging backing, identical in shape to `craft-gpu-null`. /// - /// Never panics: `required_features` is intersected with what the adapter actually - /// advertises, and `required_limits` is set to the adapter's own limits (never more), so + /// Never panics: `craft_gpu_device::open` asks only for the features from + /// [`DESIRED_FEATURES`] the adapter has, and for the adapter's own limits (never more), so /// `request_device`'s documented panics ("features/limits not supported by this adapter") /// cannot trigger here. + pub(crate) fn create_device_on(instance: &wgpu::Instance) -> Option<(DeviceCaps, Backing)> { + let request = Request { label: Some("craft-gpu-wgpu"), optional_features: DESIRED_FEATURES, ..Default::default() }; + let opened = craft_gpu_device::open(instance, None, &Preference::Auto, &request).ok()?; + Some(backing_of(&opened)) + } + pub(crate) fn create_device() -> Option<(DeviceCaps, Backing)> { - let instance = instance(); - let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?; - let features = DESIRED_FEATURES & adapter.features(); - let limits = adapter.limits(); - let desc = - wgpu::DeviceDescriptor { label: Some("craft-gpu-wgpu"), required_features: features, required_limits: limits, ..Default::default() }; - let (device, queue) = pollster::block_on(adapter.request_device(&desc)).ok()?; + create_device_on(&instance()) + } - let lost = Arc::new(Mutex::new(None)); - { - let lost = Arc::clone(&lost); - device.set_device_lost_callback(move |reason, message| { - if let Ok(mut slot) = lost.lock() { - *slot = Some(GpuFault::DeviceLost(format!("{reason:?}: {message}"))); - } - }); + pub(crate) fn backing_of(opened: &Opened) -> (DeviceCaps, Backing) { + backing_with(opened.device.clone(), opened.queue.clone(), opened.health.clone()) + } + + /// The device's own caps, and a backing that reads the loss from `health`. + pub(crate) fn backing_with(device: wgpu::Device, queue: wgpu::Queue, health: DeviceHealth) -> (DeviceCaps, Backing) { + let caps = craft_gpu_device::device_caps(&device); + (caps, Backing::Device(DeviceBacking { device, queue, buffers: Vec::new(), health, pending: Vec::new() })) + } + + /// The adapter `craft-gpu-device` would open for `Preference::Auto`, with its advertised + /// limits and no features (no device was opened to grant any). + pub(crate) fn probe_caps_on(instance: &wgpu::Instance) -> DeviceCaps { + let (adapters, _) = craft_gpu_device::list(instance, None); + match craft_gpu_device::pick(&adapters, None, &Preference::Auto) { + Ok((adapter, _)) => DeviceCaps { features: Vec::new(), ..Capabilities::of_adapter(&adapter).into_device_caps() }, + Err(_) => probe_fallback("wgpu", "no-adapter"), } - - let info = device.adapter_info(); - let device_limits = device.limits(); - let caps = DeviceCaps { - backend_name: format!("{:?}", info.backend), - device_name: info.name, - max_storage_buffer_binding_size: device_limits.max_storage_buffer_binding_size, - max_buffer_size: device_limits.max_buffer_size, - max_texture_dimension_2d: device_limits.max_texture_dimension_2d, - features: device.features().iter_names().map(|(name, _)| name.to_string()).collect(), - vendor_id: info.vendor, - software: info.device_type == wgpu::DeviceType::Cpu, - }; - let backing = Backing::Device(DeviceBacking { device, queue, buffers: Vec::new(), lost, pending: Vec::new() }); - Some((caps, backing)) } } @@ -169,9 +155,9 @@ struct DeviceBacking { /// matching the staging path and `craft-gpu-null` exactly, with no padding visible. `None` /// once freed: see the `Backing::Staging` doc for why the slot stays rather than shifting. buffers: Vec>, - /// Set by the device-lost callback registered in [`native::create_device`]; checked before - /// every call that would otherwise touch the (now invalid) device. - lost: std::sync::Arc>>, + /// The device's health from `craft-gpu-device`, which holds its device-lost callback; its + /// loss is checked before every call that would otherwise touch the (now invalid) device. + health: craft_gpu_device::DeviceHealth, pending: Vec, } @@ -251,6 +237,37 @@ impl WgpuContext { Self { caps, worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() } } + /// A context on a device `craft_gpu_device::open` (or `open_async`) opened, sharing its + /// device, queue and [`DeviceHealth`](craft_gpu_device::DeviceHealth). The caps are the + /// device's own (`Opened::device_caps`). A loss the health records, from the device-lost + /// callback it set or from any other user of the device, is this context's + /// `GpuFault::DeviceLost`. + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + pub fn from_opened(worker_kind: WorkerKind, opened: &craft_gpu_device::Opened) -> Self { + let (caps, backing) = native::backing_of(opened); + Self { caps, worker_kind, backing, next_request: 0, ready: Vec::new() } + } + + /// A context on a device the caller opened, such as the one egui-wgpu's render state holds. + /// `health` is the device's [`DeviceHealth::watch`](craft_gpu_device::DeviceHealth::watch); + /// wgpu keeps one device-lost callback per device, so this context sets none of its own. The + /// caps are the device's own: the features and limits it was opened with, whatever they are. + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + pub fn with_device(worker_kind: WorkerKind, device: wgpu::Device, queue: wgpu::Queue, health: craft_gpu_device::DeviceHealth) -> Self { + let (caps, backing) = native::backing_with(device, queue, health); + Self { caps, worker_kind, backing, next_request: 0, ready: Vec::new() } + } + + /// The health of this context's device, when it has one: share it with the rest of the app, + /// and with `craft_gpu_device::Recovery` after a loss. + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + pub fn health(&self) -> Option<&craft_gpu_device::DeviceHealth> { + match &self.backing { + Backing::Device(d) => Some(&d.health), + Backing::Staging(_) => None, + } + } + /// True when this context holds a real device (`request_device` succeeded), false on the /// staging/no-adapter path. Settings UI can use this to show "no GPU" honestly instead of /// implying a device that was never created; tests use it to skip rather than fail when the @@ -272,7 +289,7 @@ impl WgpuContext { pub fn is_device_lost(&self) -> bool { #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] if let Backing::Device(d) = &self.backing { - return d.lost.lock().map(|g| g.is_some()).unwrap_or(false); + return d.health.device_status().is_err(); } false } @@ -280,7 +297,42 @@ impl WgpuContext { fn take_lost_fault(&self) -> Option { #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] if let Backing::Device(d) = &self.backing { - return d.lost.lock().ok().and_then(|g| g.clone()); + return d.health.device_status().err(); + } + None + } + + /// `read_buffer`'s wait for the device between polls. `DeviceHealth::wait` does not wait once + /// the device reported an error other than out of memory, or when its poll fails. Then the + /// read of `request` is dropped and fails with that error, instead of polling in a loop + /// until a map that may never complete; a loss is left to the next `poll_reads`, which + /// fails every pending read with it. + #[cfg(not(target_arch = "wasm32"))] + #[cfg_attr(not(feature = "adapter-probe"), allow(unused_variables, clippy::unused_self))] + fn wait_between_reads(&mut self, request: ReadRequest) -> Option { + #[cfg(feature = "adapter-probe")] + if let Backing::Device(d) = &mut self.backing + && !d.health.wait(&d.device, None) + { + d.health.probe(&d.device); + if d.health.device_status().is_err() { + return None; + } + d.pending.retain(|p| p.request != request); + return Some( + d.health.fault().map(GpuFault::from).unwrap_or_else(|| GpuFault::Operation("read_buffer: waiting for the device failed".into())), + ); + } + None + } + + /// Why no new work may go to the device: a loss as `GpuFault::DeviceLost`, and any other + /// fault its health recorded (an uncaptured error, or an out-of-memory error the app has not + /// cleared with `DeviceHealth::clear_out_of_memory`) as `GpuFault::Operation`. + fn take_work_fault(&self) -> Option { + #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] + if let Backing::Device(d) = &self.backing { + return d.health.fault().map(GpuFault::from); } None } @@ -297,7 +349,7 @@ impl GpuContext for WgpuContext { #[cfg_attr(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")), allow(unused_variables))] fn upload_buffer(&mut self, label: &str, bytes: &[u8]) -> Result { - if let Some(fault) = self.take_lost_fault() { + if let Some(fault) = self.take_work_fault() { return Err(fault); } match &mut self.backing { @@ -334,6 +386,8 @@ impl GpuContext for WgpuContext { mapped_at_creation: false, }); if let Some(err) = pollster::block_on(create_scope.pop()) { + // The scope kept it from the device's health; every user of the device sees it. + d.health.caught(&d.device, &err); return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error creating the buffer: {err}"))); } // write_buffer makes its own staging allocation to carry `bytes` to the device, a @@ -356,6 +410,7 @@ impl GpuContext for WgpuContext { // is still a submission as far as that flush is concerned, so it is enough. d.queue.submit(std::iter::empty()); if let Some(err) = pollster::block_on(write_scope.pop()) { + d.health.caught(&d.device, &err); return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error writing the buffer: {err}"))); } let id = u32::try_from(d.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?; @@ -383,7 +438,7 @@ impl GpuContext for WgpuContext { } fn request_read(&mut self, handle: HandleId) -> Result { - if let Some(fault) = self.take_lost_fault() { + if let Some(fault) = self.take_work_fault() { return Err(fault); } match &mut self.backing { @@ -432,6 +487,7 @@ impl GpuContext for WgpuContext { mapped_at_creation: false, }); if let Some(err) = pollster::block_on(create_scope.pop()) { + d.health.caught(&d.device, &err); return Err(GpuFault::Operation(format!("request_read: device reported an allocation error creating the staging buffer: {err}"))); } // The copy and its submission get their own scope rather than reusing the one @@ -441,6 +497,7 @@ impl GpuContext for WgpuContext { encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, copy_len); d.queue.submit(Some(encoder.finish())); if let Some(err) = pollster::block_on(copy_scope.pop()) { + d.health.caught(&d.device, &err); return Err(GpuFault::Operation(format!("request_read: device reported an allocation error copying the buffer: {err}"))); } let state = std::sync::Arc::new(std::sync::Mutex::new(None)); @@ -495,11 +552,14 @@ impl GpuContext for WgpuContext { let mut outcomes = std::mem::take(&mut self.ready); #[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] if let Backing::Device(d) = &mut self.backing { - if let Some(fault) = d.lost.lock().ok().and_then(|g| g.clone()) { + // A non-blocking poll that also runs after an error other than a loss was recorded, + // and records a loss instead of panicking when the device is gone. The loss check + // follows it, so a loss the poll found fails the pending reads now. + d.health.probe(&d.device); + if let Err(fault) = d.health.device_status() { outcomes.extend(d.pending.drain(..).map(|p| ReadOutcome { request: p.request, handle: p.handle, result: Err(fault.clone()) })); return outcomes; } - let _ = d.device.poll(wgpu::PollType::Poll); let mut remaining = Vec::with_capacity(d.pending.len()); for pending in d.pending.drain(..) { let is_ready = pending.state.lock().map(|g| g.is_some()).unwrap_or(false); @@ -536,9 +596,8 @@ impl GpuContext for WgpuContext { // Block on the GPU between polls instead of busy-spinning the CPU. A no-op when // `backing` is `Staging` (nothing to wait for; the request already resolved above) // or when wgpu is itself WebGPU under the hood, which self-polls. - #[cfg(feature = "adapter-probe")] - if let Backing::Device(d) = &self.backing { - let _ = d.device.poll(wgpu::PollType::wait_indefinitely()); + if let Some(fault) = self.wait_between_reads(request) { + return Err(fault); } } } diff --git a/crates/gpu-wgpu/src/tests.rs b/crates/gpu-wgpu/src/tests.rs index 6f0b74f88e..e91bb9b63b 100644 --- a/crates/gpu-wgpu/src/tests.rs +++ b/crates/gpu-wgpu/src/tests.rs @@ -365,3 +365,120 @@ fn real_device_empty_buffer_and_interleaved_read_buffer_behave_like_staging() { } assert!(seen_a, "a's completion must still arrive through poll_reads after b's read_buffer"); } + +/// Devices from `craft-gpu-device`, on wgpu's noop backend, so these run without a GPU. +#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))] +mod device_from_craft_gpu_device { + use craft_gpu::{GpuContext, GpuFault, WorkerKind}; + use craft_gpu_device::{DeviceHealth, Fault, Preference, Request}; + + use crate::{Backing, WgpuContext, native}; + + /// An instance whose only adapter is wgpu's noop one, which wgpu 30 lists as a software + /// adapter. + fn noop() -> wgpu::Instance { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + desc.backend_options.noop = wgpu::NoopBackendOptions { enable: true, ..Default::default() }; + wgpu::Instance::new(desc) + } + + fn opened() -> craft_gpu_device::Opened { + craft_gpu_device::open(&noop(), None, &Preference::Software, &Request::default()).expect("the noop adapter opens") + } + + #[test] + fn the_default_device_is_the_one_craft_gpu_device_opens() { + let (caps, backing) = native::create_device_on(&noop()).expect("the noop adapter opens"); + let Backing::Device(d) = &backing else { panic!("a device backing") }; + assert_eq!(caps, craft_gpu_device::device_caps(&d.device)); + assert!(caps.software, "{caps:?}"); + assert!(d.health.is_ok() && d.health.device_status().is_ok()); + // no adapter at all: the staging path + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + assert!(native::create_device_on(&wgpu::Instance::new(desc)).is_none()); + } + + #[test] + fn the_probe_reports_the_adapter_craft_gpu_device_picks() { + let opened = opened(); + let caps = native::probe_caps_on(&noop()); + assert_eq!(caps.device_name, opened.candidate.name); + assert!(caps.software && caps.features.is_empty(), "{caps:?}"); + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + assert_eq!(native::probe_caps_on(&wgpu::Instance::new(desc)).device_name, "no-adapter"); + } + + #[test] + fn a_context_on_an_opened_device_reads_the_loss_from_its_health() { + let opened = opened(); + let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened); + assert!(ctx.has_device()); + assert_eq!(ctx.caps(), opened.device_caps()); + assert_eq!(ctx.device_status(), Ok(())); + // a loss another user of the device records is this context's loss too + opened.health.mark(Fault::Lost("the driver reset the GPU".into())); + assert!(ctx.health().is_some_and(|h| h.device_status().is_err())); + assert_eq!(ctx.device_status(), Err(GpuFault::DeviceLost("the driver reset the GPU".into()))); + assert!(ctx.is_device_lost()); + assert!(matches!(ctx.upload_buffer("after-loss", b"x"), Err(GpuFault::DeviceLost(_)))); + } + + #[test] + fn a_destroyed_device_is_lost_through_the_health_that_watches_it() { + let opened = opened(); + let health = DeviceHealth::watch(&opened.device); + let mut ctx = WgpuContext::with_device(WorkerKind::DedicatedWorker, opened.device.clone(), opened.queue.clone(), health.clone()); + assert_eq!(ctx.caps(), opened.device_caps()); + opened.device.destroy(); + let _ = ctx.poll_reads(); + assert!(health.device_status().is_err(), "{health:?}"); + assert!(matches!(ctx.device_status(), Err(GpuFault::DeviceLost(_)))); + assert!(matches!(ctx.request_read(craft_gpu::HandleId(0)), Err(GpuFault::DeviceLost(_)))); + } + + #[test] + fn no_work_goes_to_a_device_whose_health_recorded_an_error() { + let opened = opened(); + let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened); + let handle = ctx.upload_buffer("before", b"abcd").expect("upload on a healthy device"); + // an out-of-memory error stops new work until the app clears it + opened.health.mark(Fault::Error(craft_gpu_device::OUT_OF_MEMORY.into())); + assert!(matches!(ctx.upload_buffer("oom", b"x"), Err(GpuFault::Operation(_)))); + assert!(matches!(ctx.request_read(handle), Err(GpuFault::Operation(_)))); + assert_eq!(ctx.device_status(), Ok(()), "only a loss is a device_status fault"); + ctx.free_buffer(handle); + opened.health.clear_out_of_memory(opened.health.out_of_memory_count()); + let handle = ctx.upload_buffer("after", b"abcd").expect("upload once the error is cleared"); + assert_eq!(ctx.buffer_len(handle), Ok(4)); + // another error stops it for good + opened.health.mark(Fault::Error("Validation Error".into())); + assert_eq!(ctx.upload_buffer("validation", b"x"), Err(GpuFault::Operation("Validation Error".into()))); + assert_eq!(ctx.device_status(), Ok(())); + } + + #[test] + fn a_read_waiting_when_the_device_reports_an_error_fails_instead_of_polling_forever() { + let opened = opened(); + let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened); + let handle = ctx.upload_buffer("pending", b"abcd").expect("upload"); + let request = ctx.request_read(handle).expect("request_read"); + opened.health.mark(Fault::Error("Validation Error".into())); + assert_eq!(ctx.wait_between_reads(request), Some(GpuFault::Operation("Validation Error".into()))); + let Backing::Device(d) = &ctx.backing else { panic!("a device backing") }; + assert!(d.pending.iter().all(|p| p.request != request), "the failed read is dropped"); + // a loss is left to poll_reads, which fails every pending read with it + let other = ctx.request_read(handle); + assert!(other.is_err()); + opened.health.mark(Fault::Lost("gone".into())); + assert_eq!(ctx.wait_between_reads(request), None); + } + + #[test] + fn a_staging_context_has_no_health() { + let ctx = WgpuContext::with_caps(WorkerKind::Main, craft_gpu::DeviceCaps::default()); + assert!(ctx.health().is_none()); + } +} diff --git a/docs/gpu-backends.md b/docs/gpu-backends.md index 6e2246e918..774992f922 100644 --- a/docs/gpu-backends.md +++ b/docs/gpu-backends.md @@ -8,12 +8,12 @@ Feature flags on `craft-gpu-wgpu`: -- `adapter-probe`: native only; uses pollster to `request_adapter`/`request_device` and build real [`DeviceCaps`](../crates/gpu/src/caps.rs) from the created device (falls back to the staging path when no GPU, e.g. CI with no backend feature enabled). -- `native-vulkan`, `native-dx12`, `native-metal`, `native-gles`: enable the matching wgpu backend. `adapter-probe` alone compiles the probing code but finds no adapter unless at least one of these is also on. +- `adapter-probe`: native only; opens the device through [`craft-gpu-device`](../crates/gpu-device/README.md) and builds real [`DeviceCaps`](../crates/gpu/src/caps.rs) from the created device (falls back to the staging path when no adapter opens). `craft-gpu-device` depends on wgpu with its default features, so this feature also turns on wgpu's default native backends. The context's instance uses `craft_gpu_device::native_descriptor`'s backends (no OpenGL on Windows) unless `WGPU_BACKEND` names others. +- `native-vulkan`, `native-dx12`, `native-metal`, `native-gles`: enable the matching wgpu backend. ## Real device, device-truth caps (RFC-0022 requirement 1) -With `adapter-probe` and a `native-*` backend, `WgpuContext::new` calls `Adapter::request_device` after `request_adapter`, creating a real device. `DeviceCaps` is built from the created `Device`'s own `limits()` / `features()`, never from the adapter's advertised maximum: an adapter can advertise more than a device grants. `required_features` is the adapter's features intersected with what this context asks for (currently nothing, since no provider dispatches a real WGSL job yet, see [gpu-providers.md](./gpu-providers.md)); `required_limits` is the adapter's own limits. Both choices mean `request_device` cannot panic on an unsupported feature or limit here. +With `adapter-probe`, `WgpuContext::new` opens a real device with `craft_gpu_device::open` for `Preference::Auto`: the same adapter choice, driver corrections and fallback order as every other caller of that crate, so the suite has one device selector. `probe_caps()` reports the adapter `craft_gpu_device::pick` chooses, without opening a device on it; when a device fails to open there, `WgpuContext::new` opens the next adapter in `ranked` order or a software one, and its `caps()` name that device. `WgpuContext::from_opened` takes a device the app opened with `craft-gpu-device` (with the user's own `Preference`, or after a `Recovery` step), and `WgpuContext::with_device` takes any device with its `DeviceHealth`. `DeviceCaps` is built from the created `Device`'s own `limits()` / `features()` (`craft_gpu_device::device_caps`), never from the adapter's advertised maximum: an adapter can advertise more than a device grants. `WgpuContext::new` asks for the adapter's features intersected with what this context asks for (currently nothing, since no provider dispatches a real WGSL job yet, see [gpu-providers.md](./gpu-providers.md)), and for the adapter's own limits. Both choices mean `request_device` cannot panic on an unsupported feature or limit here. A context on a device the caller opened takes the features and limits that device was opened with. Buffers are real `wgpu::Buffer`s (`STORAGE | COPY_SRC | COPY_DST`). The host-staged `Vec>` form survives only on the no-device path. @@ -23,7 +23,7 @@ Buffers are real `wgpu::Buffer`s (`STORAGE | COPY_SRC | COPY_DST`). The host-sta ## Device loss (RFC-0022 requirement 1) -`WgpuContext` registers `Device::set_device_lost_callback` when it creates a real device. Loss (a driver reset, OS-level eviction, or an explicit `destroy()`) surfaces as `GpuFault::DeviceLost`, from the next buffer call and from `poll_reads()`, never as a panic. +`WgpuContext` reads a device loss from the device's `craft_gpu_device::DeviceHealth`, which sets the device's one device-lost callback and records a loss without panicking; the context sets no callback of its own. Loss (a driver reset, OS-level eviction, an explicit `destroy()`, or a loss another user of the same `DeviceHealth` records) surfaces as `GpuFault::DeviceLost`, from the next buffer call, from `poll_reads()` and from `device_status()`, never as a panic. `WgpuContext::health()` gives that `DeviceHealth`, for `craft_gpu_device::Recovery` and the rest of the app. Any other fault the `DeviceHealth` records (an uncaptured error, or an out-of-memory error the app has not cleared with `DeviceHealth::clear_out_of_memory`) makes `upload_buffer` and `request_read` return `GpuFault::Operation`; `device_status()` reports a loss only, and `poll_reads()` and `free_buffer` keep running. An allocation error the context's own error scopes catch is recorded in the `DeviceHealth` as well (`DeviceHealth::caught`). Once a context has reported `GpuFault::DeviceLost`, every `DeviceCaps` it reported before that point is stale. The stated recovery, per the trait docs on [`GpuContext`](../crates/gpu/src/context.rs): @@ -39,7 +39,7 @@ No backend here supports continuing to dispatch jobs against a context that alre `read_buffer` stays as a blocking convenience with a default body built on those two primitives, for callers that need bytes now (the CPU-stand-in providers in `craft-gpu-providers`). Both bundled backends override that default body. The default has nowhere to put completions belonging to other outstanding requests. The overrides keep those queued for the next `poll_reads`: - `craft-gpu-null`: overrides to take only its own completion; every request resolves immediately, with nothing to wait for. -- `craft-gpu-wgpu`, native, with a real device: overrides to block by calling `Device::poll(PollType::wait_indefinitely())` between polls. It waits on the GPU without busy-spinning the CPU, re-queuing other requests' completions. +- `craft-gpu-wgpu`, native, with a real device: overrides to block by calling `DeviceHealth::wait` (a `Device::poll` that waits for all submitted work) between polls. It waits on the GPU without busy-spinning the CPU, re-queuing other requests' completions. When the device reports an error other than a loss or running out of memory while the read is pending, or the wait itself fails, `read_buffer` drops the read and returns that error as `GpuFault::Operation`; a loss fails it with `GpuFault::DeviceLost`. - `craft-gpu-wgpu`, native, staging path (no device): resolves immediately, same as the null context. - `craft-gpu-wgpu`, `wasm32`: **serves the staging read.** The only backing on this target today is the in-memory staging store, since real device creation needs the async worker-init path that has not landed. Staging reads resolve synchronously. `read_buffer` returns their bytes. Only a read that did not resolve synchronously returns `GpuFault::Operation`. That refusal will matter once a real device backing exists there: `wasm32` is single-threaded and blocking the one thread the browser needs to run `map_async`'s own completion callback on would hang the tab. A caller on a future device backing must drive `request_read` + `poll_reads` from the worker's own message loop. @@ -58,4 +58,4 @@ The question that decides whether a render-path app can adopt `WgpuContext` as-i **FilmCraft's answer today is "it depends on which device."** Its on-screen monitor compositor adopts egui's own device: both the native desktop app and the web app call `app.set_wgpu(cc.wgpu_render_state.clone())` (or the equivalent on native), so the compositor draws through the exact `Device`/`Queue` `eframe`'s `RenderState` already created. One device, shared, no second adapter opened for the window. Its **export** path is deliberately the opposite: a separate, off-screen `wgpu::Device` with no surface, created once and kept for the process (`export_renderer.rs`), specifically because export runs independent of the UI's lifecycle (worker threads, no window) and must keep working even if the UI's device were ever lost or recreated. -`WgpuContext::new` in this PR always opens its own device (or degrades to staging) and has no constructor that accepts an externally-supplied `(Device, Queue)`. That is **documented here as the named follow-up, not implemented in this PR**: accepting an existing device/queue pair (with `DeviceCaps` built from that pair, the same device-truth way `create_device` builds it today) is a small, additive constructor that does not change `GpuContext`'s trait shape, but it needs a decision this PR's scope doesn't force: whether the shared constructor should require the caller to prove the features/limits it needs were already granted (since a second caller can't call `request_device` again on a device that already exists), or whether it should accept whatever was granted and fail a job if it needs more. FilmCraft's own split (share for render, separate for export) is a reasonable default for this layer too: a render-path app wanting GPU compute on the same frame it draws with egui should share; a worker-isolated batch job (the first named consumer, `craft-libs#662`'s worker-host) has no window and no reason to share, and keeps its own device exactly as implemented here. +`WgpuContext::with_device` accepts an existing `(Device, Queue)` pair with its `DeviceHealth`, and `WgpuContext::from_opened` accepts a `craft_gpu_device::Opened`. Neither changes `GpuContext`'s trait shape. They take whatever the device was granted: `DeviceCaps` is built from that device, and a job that needs a feature the caps do not name takes its portable path or fails. A render-path app that wants GPU compute on the same frame it draws with egui passes egui's device to `with_device`, with the `DeviceHealth::watch` of that device. A worker-isolated batch job (the first named consumer, `craft-libs#662`'s worker-host) has no window and keeps its own device from `WgpuContext::new`.