From 928692ebfddd2126f12d8312c910eada564b7a89 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 11:15:59 -0800 Subject: [PATCH] craft-gpu-device: keep the choice off avoided entries, stop waits on a recorded fault - choose and a named or software preference follow the newest-version correction until the entry is its own newest version. An entry without a bus id between two cards of one model no longer leaves the choice on an entry that avoided() excludes. The host test accepts every safe fallback, and None only when the Intel Vulkan entry is all there is. - An optional experimental feature is no longer requested, so the device opens without it instead of failing the adapter. - A bounded wait stops after the current slice once another clone records a loss or an error other than out of memory. - Both loss writers record the loss before setting device_lost. - Docs: recovery starts on device_status; the software notice shows only when a software adapter opened; surfaces are configured from the new adapter's capabilities; GPUInternalError on the browser backend panics in wgpu 30 before the handler runs; late completion counts as Finished. --- crates/gpu-device/README.md | 23 ++++++--- crates/gpu-device/src/adapter.rs | 73 +++++++++++++++++++++-------- crates/gpu-device/src/health.rs | 59 ++++++++++++++++++----- crates/gpu-device/src/open.rs | 18 ++++++- crates/gpu-device/src/preference.rs | 5 +- 5 files changed, 135 insertions(+), 43 deletions(-) diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md index 3c7da59b5c..f1f5a9a558 100644 --- a/crates/gpu-device/README.md +++ b/crates/gpu-device/README.md @@ -41,7 +41,9 @@ Licensed under MIT OR Apache-2.0. browser's adapter, with `Notice::NoSoftwareAdapter` unless that adapter is a software one, and `Recovery` cannot move drawing to software there. `Capabilities` and `Recovery` otherwise work there as they do on native, and so does `DeviceHealth` apart from `wait`, - `wait_timeout` and `wait_timeout_cancelable`, which are native only. + `wait_timeout` and `wait_timeout_cancelable`, which are native only. On the browser backend, + wgpu 30 panics on an uncaptured `GPUInternalError` before the handler `DeviceHealth::watch` + installs runs, so such an error is not recorded. Validation and out-of-memory errors are. - An adapter that lacks `Request::required_features`, or whose `request_device` fails, adds a `Notice::DeviceFailed`, and `open` tries the next one. When every adapter fails, the error lists each failure. @@ -74,9 +76,11 @@ Licensed under MIT OR Apache-2.0. ## After a device loss -`DeviceHealth::device_lost` turns true, and `DeviceHealth::device_status` returns -`GpuFault::DeviceLost`, once the device is lost. Nothing made with the lost device can be used -again, and wgpu keeps none of its contents. The caller then: +`DeviceHealth::device_status` returns `GpuFault::DeviceLost` once a loss is recorded, and the +caller starts recovery then. `DeviceHealth::device_lost` turns true only when wgpu itself reported +the loss; it stays false for a loss the health layer recorded on its own, such as a bounded wait +that reached its deadline. Nothing made with the lost device can be used again, and wgpu keeps +none of its contents. The caller then: 1. Drops the old `Opened` and everything made with its device: buffers, textures and their views, samplers, bind group layouts and bind groups, shader modules, pipeline layouts and @@ -85,14 +89,19 @@ again, and wgpu keeps none of its contents. The caller then: waits on it return `false`. 2. Calls `Recovery::lost` with the time and opens a new device with `open` or `open_async`, using the returned preference and the same `Request`. When the step has a notice - (`Notice::SoftwareAfterLosses`), the app shows it. + (`Notice::SoftwareAfterLosses`), the app shows it only if the new `Opened::caps.software()` is + true. Otherwise no software adapter opened (in a browser, or with none listed), and the new + `Opened::notices` say what was opened instead. 3. Reads the new `Opened::caps` before choosing pipelines again. The new device can be another adapter, or a software one, with other features and limits: for example, without NV12 the planes are drawn into `R8Unorm` and `Rg8Unorm` textures instead. 4. Configures each window surface again with the new device (`Surface::configure`). The surface itself is kept when it was passed to `open`, which then opens only an adapter that can draw - to it. -5. Builds the pipelines, bind groups and renderers again, and uploads the textures and buffers + to it. The new adapter may not support the old configuration (an HDR format, for example), so + the caller reads `Surface::get_capabilities` with the new adapter and picks a format, present + mode and alpha mode from it. +5. Builds the pipelines for the surface format picked in step 4, the bind groups and renderers + again, bind groups and renderers again, and uploads the textures and buffers again from the app's own copies of their data. 6. Makes any `craft-gpu` context again on the new device, with the new `Opened::device_caps`, and submits again the jobs and frames that did not complete. diff --git a/crates/gpu-device/src/adapter.rs b/crates/gpu-device/src/adapter.rs index c0d1b5c8ff..ce62be43ec 100644 --- a/crates/gpu-device/src/adapter.rs +++ b/crates/gpu-device/src/adapter.rs @@ -160,22 +160,40 @@ pub fn native_descriptor() -> wgpu::InstanceDescriptor { /// The index of the adapter to draw with for `power`: [`wgpu_choice`], or the entry exposing the /// most features among those that are the same GPU listed by the same driver (the first of them -/// when several expose as many). For an Intel Gen 9 to Gen 11 GPU on Intel's Windows Vulkan -/// driver it is the same GPU's DirectX 12 entry, or without one the best other usable adapter. -/// `None` without a usable adapter, and when that Intel Vulkan entry is the only one. +/// when several expose as many), repeated until the entry is its own newest version. For an Intel +/// Gen 9 to Gen 11 GPU on Intel's Windows Vulkan driver it is the same GPU's DirectX 12 entry, or +/// without one the best other usable adapter. `None` without a usable adapter, and when that +/// Intel Vulkan entry is the only one. The result is never an entry [`avoided`] excludes. pub fn choose(candidates: &[Candidate], power: PowerPreference) -> Option { let first = wgpu_choice(candidates, power)?; - let preferred = candidates.get(first)?; - let index = corrected(candidates, first, preferred); + let index = settled(candidates, first); if candidates.get(index).is_some_and(intel_vulkan_crashes) { // No usable DirectX 12 entry for that GPU: the best other adapter wgpu would take. let safe = candidates.iter().enumerate().filter(|(_, c)| c.usable && !intel_vulkan_crashes(c)); - let (other, c) = safe.min_by_key(|(i, c)| (type_order(c.device_type, power), *i))?; - return Some(corrected(candidates, other, c)); + let (other, _) = safe.min_by_key(|(i, c)| (type_order(c.device_type, power), *i))?; + return Some(settled(candidates, other)); } Some(index) } +/// [`corrected`] applied until it returns the entry it was given. An entry without a bus id can +/// be the same GPU as two entries on different buses, so one correction can land on an entry that +/// has a newer version of its own. Each step moves to an entry exposing more features (or the +/// same number at a lower index), or to a DirectX 12 entry, so the loop ends. +pub(crate) fn settled(candidates: &[Candidate], mut index: usize) -> usize { + for _ in 0..=candidates.len() { + let Some(c) = candidates.get(index) else { + return index; + }; + let next = corrected(candidates, index, c); + if next == index { + return index; + } + index = next; + } + index +} + /// `index` (the entry `preferred`), or the entry to draw with instead of it. pub(crate) fn corrected(candidates: &[Candidate], index: usize, preferred: &Candidate) -> usize { if let Some(dx12) = dx12_instead(candidates, preferred) { @@ -341,6 +359,20 @@ pub(crate) mod tests { assert!(avoided(&three, 0) && avoided(&three, 1) && !avoided(&three, 2)); } + #[test] + fn an_entry_without_a_bus_between_two_cards_is_never_drawn_with_when_avoided() { + // two cards of one model on their own buses, and an entry of the same driver without a bus + // id, which can be either card's other version + let radeon = |bus, features| gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, bus, "AMD proprietary driver", "", features); + let adapters = vec![radeon("0000:03:00.0", 60), radeon("", 70), radeon("0000:04:00.0", 80)]; + for power in POWERS { + let chosen = choose(&adapters, power); + assert_eq!(chosen, Some(2), "{power:?}"); + assert!(chosen.is_some_and(|i| !avoided(&adapters, i)), "{power:?}"); + } + assert!(avoided(&adapters, 0) && avoided(&adapters, 1) && !avoided(&adapters, 2)); + } + #[test] fn a_newer_version_never_overtakes_another_gpu_or_backend() { assert_eq!(choose(&two_amd_drivers(), LowPower), Some(2)); @@ -550,9 +582,10 @@ pub(crate) mod tests { } /// Against the adapters of the machine running the tests: [`wgpu_choice`] is what wgpu's - /// `request_adapter` returns, and [`choose`] returns that adapter too, a version of it exposing - /// more features, or for an Intel Gen 9 to Gen 11 GPU its DirectX 12 entry. Passes without - /// adapters. + /// `request_adapter` returns, and [`choose`] returns that adapter too, or, when wgpu's choice + /// is one [`avoided`] excludes, an adapter it does not exclude: a version exposing more + /// features, an Intel Gen 9 to Gen 11 GPU's DirectX 12 entry, or the best other adapter. + /// `None` only when every usable adapter is that Intel Vulkan entry. Passes without adapters. #[test] #[cfg(not(target_arch = "wasm32"))] fn on_this_host_the_choice_is_wgpus_unless_a_correction_applies() { @@ -564,15 +597,17 @@ pub(crate) mod tests { let options = wgpu::RequestAdapterOptions { power_preference: power, ..Default::default() }; let wgpu_own = pollster::block_on(instance.request_adapter(&options)).ok().map(|a| Candidate::of(&a, None)); assert_eq!(wgpu_choice(&candidates, power).and_then(|i| candidates.get(i)), wgpu_own.as_ref(), "{power:?} over {candidates:#?}"); - let picked = choose(&candidates, power).and_then(|i| candidates.get(i)); - match (&wgpu_own, picked) { - (Some(wgpu_own), Some(picked)) if wgpu_own != picked => { - let newer_version = same_gpu_and_driver(wgpu_own, picked) && picked.features > wgpu_own.features; - let intel_dx12 = wgpu_own.vendor == INTEL - && intel_gen9_to_gen11(wgpu_own.device) - && picked.backend == Backend::Dx12 - && picked.device == wgpu_own.device; - assert!(newer_version || intel_dx12, "{power:?}: {picked} instead of {wgpu_own}"); + let own_index = wgpu_choice(&candidates, power); + let chosen = choose(&candidates, power); + let picked = chosen.and_then(|i| candidates.get(i)); + match (own_index, chosen) { + (Some(own), Some(index)) if own != index => { + assert!(avoided(&candidates, own), "{power:?}: {picked:?} instead of {wgpu_own:?}, which is not avoided"); + assert!(!avoided(&candidates, index), "{power:?}: {picked:?} is avoided"); + } + (Some(own), None) => { + let only_intel_vulkan = candidates.iter().filter(|c| c.usable).all(intel_vulkan_crashes); + assert!(only_intel_vulkan, "{power:?}: nothing instead of {:?}", candidates.get(own)); } _ => assert_eq!(picked, wgpu_own.as_ref(), "{power:?}"), } diff --git a/crates/gpu-device/src/health.rs b/crates/gpu-device/src/health.rs index f1ff61b640..bad057b6b5 100644 --- a/crates/gpu-device/src/health.rs +++ b/crates/gpu-device/src/health.rs @@ -19,7 +19,8 @@ use std::time::{Duration, Instant}; /// Outcome of a bounded wait for submitted GPU work. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum WaitOutcome { - /// The submitted work finished before the deadline. + /// The submitted work finished before the deadline, or just after it, when wgpu read the + /// fence again at the end of the last poll. Finished, /// The deadline passed (or the device faulted) before the work finished. TimedOut, @@ -121,7 +122,9 @@ impl DeviceHealth { } /// Watch `device`: its device-lost callback and uncaptured errors mark the returned flag - /// instead of panicking. Replaces any handler set before (wgpu keeps one of each). + /// instead of panicking. Replaces any handler set before (wgpu keeps one of each). On the + /// browser backend, wgpu 30 panics on an uncaptured `GPUInternalError` before this handler + /// runs, so such an error is not recorded; validation and out-of-memory errors are. pub fn watch(device: &wgpu::Device) -> Self { let health = Self::new(); let lost = health.clone(); @@ -133,8 +136,9 @@ impl DeviceHealth { (_, false) => message, }; log::error!("wgpu device lost ({reason:?}): {detail}"); - lost.0.device_lost.store(true, Ordering::Release); + // The loss first: a caller that sees `device_lost` then also sees the fault. lost.mark(Fault::Lost(detail)); + lost.0.device_lost.store(true, Ordering::Release); }); let errors = health.clone(); device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| errors.uncaptured(&e))); @@ -270,8 +274,8 @@ impl DeviceHealth { /// `Device::poll` panicked: wgpu found the device lost. fn lost_by_poll(&self) { - self.0.device_lost.store(true, Ordering::Release); self.mark(Fault::Lost("the device stopped responding".into())); + self.0.device_lost.store(true, Ordering::Release); } /// Block until `index` (or all submitted work) finished, unless the device was lost or @@ -327,7 +331,10 @@ impl DeviceHealth { /// [`Self::wait_timeout`] that polls in slices of at most 100 ms and checks `canceled` between /// them, keeping the same overall deadline. Every slice waits for the same `index`. A slice /// that times out means the work has not finished yet; only the overall deadline (or a poll - /// that panics) marks the device faulted. + /// that panics) marks the device faulted. A loss or an error other than out of memory that + /// another clone records during the wait ends it after the current slice, with + /// [`WaitOutcome::TimedOut`]. wgpu reads the fence again after a slice's own timeout, so work + /// that finishes in that gap, just after the deadline, is [`WaitOutcome::Finished`]. #[cfg(not(target_arch = "wasm32"))] pub fn wait_timeout_cancelable( &self, @@ -349,14 +356,8 @@ impl DeviceHealth { device.poll(wgpu::PollType::Wait { submission_index: Some(index.clone()), timeout: Some(slice) }) })); match poll { - Ok(Ok(_)) => { - if self.pollable() { - SlicePoll::Done - } else { - SlicePoll::Failed - } - } - Ok(Err(wgpu::PollError::Timeout)) => SlicePoll::Pending, + Ok(Ok(_)) => self.after_slice(true), + Ok(Err(wgpu::PollError::Timeout)) => self.after_slice(false), // A submission index the device never issued: the caller's mistake, not the GPU's. Ok(Err(e)) => { log::warn!("wgpu poll: {e}"); @@ -375,6 +376,20 @@ impl DeviceHealth { } outcome } + + /// What a slice that returned reports, `finished` or not: failed once a clone of this flag + /// recorded a loss or an error other than out of memory, so the next slice does not poll a + /// device that is not to be used. + #[cfg(not(target_arch = "wasm32"))] + fn after_slice(&self, finished: bool) -> SlicePoll { + if !self.pollable() { + SlicePoll::Failed + } else if finished { + SlicePoll::Done + } else { + SlicePoll::Pending + } + } } /// What one bounded poll reported. @@ -564,6 +579,24 @@ mod tests { assert_eq!(polls, 1, "a cancel set during a pending poll ends the wait"); } + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn a_fault_recorded_during_a_wait_stops_the_next_slice() { + let h = DeviceHealth::new(); + assert_eq!(h.after_slice(false), SlicePoll::Pending); + assert_eq!(h.after_slice(true), SlicePoll::Done); + // out of memory alone: polls keep reclaiming memory + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert_eq!(h.after_slice(false), SlicePoll::Pending); + // another clone records a validation error while a slice is pending + h.clone().mark(Fault::Error("Validation Error".into())); + assert_eq!(h.after_slice(false), SlicePoll::Failed, "the next slice must not poll"); + assert_eq!(h.after_slice(true), SlicePoll::Failed); + let lost = DeviceHealth::new(); + lost.clone().mark(Fault::Lost("reset".into())); + assert_eq!(lost.after_slice(false), SlicePoll::Failed); + } + #[test] fn fault_text() { assert_eq!(Fault::Lost(String::new()).to_string(), "GPU device lost"); diff --git a/crates/gpu-device/src/open.rs b/crates/gpu-device/src/open.rs index 48325095cb..984f53f34b 100644 --- a/crates/gpu-device/src/open.rs +++ b/crates/gpu-device/src/open.rs @@ -15,7 +15,9 @@ pub struct Request<'a> { pub label: Option<&'a str>, /// Features the device must have. An adapter without them is skipped. pub required_features: Features, - /// Features asked for when the adapter has them. + /// Features asked for when the adapter has them. Experimental features + /// (`Features::all_experimental_mask`) are left out here: the device descriptor does not + /// enable experimental features, and wgpu refuses a device that asks for one without that. pub optional_features: Features, /// The limits to ask for; `None` asks for the adapter's own limits. pub limits: Option, @@ -254,7 +256,7 @@ async fn open_on(adapter: &Adapter, request: &Request<'_>) -> Result<(wgpu::Devi let required_limits = request.limits.clone().unwrap_or_else(|| adapter.limits()); let desc = wgpu::DeviceDescriptor { label: request.label, - required_features: request.required_features | (request.optional_features & has), + required_features: request.required_features | (request.optional_features & has & !Features::all_experimental_mask()), required_limits, ..Default::default() }; @@ -316,6 +318,18 @@ mod tests { assert_eq!(pollster::block_on(open_async(&none, None, &Preference::Auto, &Request::default())).unwrap_err(), OpenError::NoAdapter); } + #[test] + fn an_optional_experimental_feature_does_not_stop_the_device_opening() { + let instance = noop(Some(Features::EXPERIMENTAL_RAY_QUERY | Features::TEXTURE_FORMAT_NV12)); + let request = Request { optional_features: Features::EXPERIMENTAL_RAY_QUERY | Features::TEXTURE_FORMAT_NV12, ..Default::default() }; + let opened = open(&instance, None, &Preference::Software, &request).unwrap(); + assert!(opened.caps.nv12(), "{}", opened.caps); + assert!(!opened.device.features().contains(Features::EXPERIMENTAL_RAY_QUERY)); + // a required one still fails as before + let required = Request { required_features: Features::EXPERIMENTAL_RAY_QUERY, ..Default::default() }; + assert!(matches!(open(&instance, None, &Preference::Software, &required), Err(OpenError::NoDevice(_)))); + } + #[test] fn an_adapter_without_a_required_feature_is_reported() { let instance = noop(Some(Features::empty())); diff --git a/crates/gpu-device/src/preference.rs b/crates/gpu-device/src/preference.rs index 539cde153f..542bf66305 100644 --- a/crates/gpu-device/src/preference.rs +++ b/crates/gpu-device/src/preference.rs @@ -4,7 +4,7 @@ use std::fmt; use wgpu::{Backend, PowerPreference}; -use crate::adapter::{Candidate, avoided, choose, corrected, intel_vulkan_crashes, type_order}; +use crate::adapter::{Candidate, avoided, choose, intel_vulkan_crashes, settled, type_order}; /// Which adapter to draw with. #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -183,7 +183,8 @@ pub fn select(candidates: &[Candidate], preference: &Preference) -> Option Option { - let index = corrected(candidates, index, candidates.get(index)?); + candidates.get(index)?; + let index = settled(candidates, index); (!candidates.get(index).is_some_and(intel_vulkan_crashes)).then_some(index) }