From 01060e212e5ef31a88c1b8a6dee02970a06ea874 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:09:37 +0100 Subject: [PATCH] Retire the GPU context after a polling panic (#4230) * Retire GPU contexts when driver polling panics * Avoid submitting frame cleanup work after GPU retirement * Guard cleanup submission and reject results raced by device retirement --------- Co-authored-by: Fredrik Hallin --- crates/gpu/src/context.rs | 19 +++++++++++---- crates/gpu/src/readback.rs | 48 ++++++++++++++++++++++++++++++++++++++ crates/gpu/src/tests.rs | 4 ++++ 3 files changed, 67 insertions(+), 4 deletions(-) diff --git a/crates/gpu/src/context.rs b/crates/gpu/src/context.rs index 7125ea526..bc6f5fb7f 100644 --- a/crates/gpu/src/context.rs +++ b/crates/gpu/src/context.rs @@ -1090,7 +1090,7 @@ impl GpuContext { }, _ => self.poll_lock.lock().unwrap_or_else(|e| e.into_inner()), }; - self.device.poll(kind) + self.readbacks.run_device(|| self.device.poll(kind))? }; res.map_err(|e| { let error = format!("GPU readback poll: {e}"); @@ -1114,7 +1114,13 @@ impl GpuContext { let slice = remaining.min(Self::POLL_SLICE); let res = { let _guard = self.poll_lock.lock().unwrap_or_else(|e| e.into_inner()); - self.device.poll(wgpu::PollType::Wait { submission_index: Some(submission_index.clone()), timeout: Some(slice) }) + match self + .readbacks + .run_device(|| self.device.poll(wgpu::PollType::Wait { submission_index: Some(submission_index.clone()), timeout: Some(slice) })) + { + Ok(result) => result, + Err(_) => return, + } }; let done = match res { Ok(_) => true, @@ -1347,7 +1353,8 @@ impl GpuContext { (remaining, std::time::Duration::ZERO, Ok(wgpu::PollStatus::Poll)) } else { let slice = remaining.min(Self::POLL_SLICE); - let res = self.device.poll(wgpu::PollType::Wait { submission_index: submission.clone(), timeout: Some(slice) }); + let res = + self.readbacks.run_device(|| self.device.poll(wgpu::PollType::Wait { submission_index: submission.clone(), timeout: Some(slice) }))?; (remaining, slice, res) } }; @@ -1724,10 +1731,14 @@ impl GpuContext { /// count; if the wait frees none of them, later frames only poll until `dying` drops (a /// stopped queue must not re-wait [`crate::readback::TIMEOUT`] on every frame). pub fn pool_frame_end(&self) { + // CPU fallback still ends frames. Skip cleanup once retirement is already known. + if self.readbacks.check().is_err() { + return; + } let before = self.pool.lock().map(|mut p| p.frame_end()).unwrap_or_default(); if before > 0 { // A work-done callback waits for a submission; an empty one closes the wait. - let index = self.queue.submit([]); + let Ok(index) = self.readbacks.run_device(|| self.queue.submit([])) else { return }; self.poll_wait(index, crate::readback::TIMEOUT); if let Ok(mut p) = self.pool.lock() { p.waited(before); diff --git a/crates/gpu/src/readback.rs b/crates/gpu/src/readback.rs index 51d941640..4b34a2f60 100644 --- a/crates/gpu/src/readback.rs +++ b/crates/gpu/src/readback.rs @@ -181,6 +181,23 @@ impl Readbacks { } } + /// A driver panic invalidates this context just as a reported device failure does. + /// Driver calls can synchronously retire the context through error callbacks, so never + /// hold the retirement lock across them. Reject results if retirement races the call. + pub(crate) fn run_device(&self, run: impl FnOnce() -> T) -> Result { + self.check()?; + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(run)).map_err(|panic| { + let detail = + panic.downcast_ref::().map(String::as_str).or_else(|| panic.downcast_ref::<&str>().copied()).unwrap_or("internal driver error"); + let error = format!("GPU operation failed ({detail}); context retired"); + self.retire(error.clone()); + log::error!("{error}"); + error + })?; + self.check()?; + Ok(result) + } + pub(crate) fn start(self: &Arc, done: impl FnOnce(Result, Error>) + wgpu::WasmNotSend + 'static) -> Result { let mut done: Option = Some(Box::new(done)); let result = { @@ -445,6 +462,37 @@ mod tests { use super::*; use std::sync::atomic::{AtomicUsize, Ordering}; + #[test] + fn polling_panic_retires_context_and_settles_readbacks_once() { + let me = Readbacks::new().unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + let ticket = me + .start(move |result| { + tx.send(result).unwrap(); + }) + .unwrap(); + let error = me.run_device(|| panic!("submission index mismatch")).unwrap_err(); + assert!(error.contains("submission index mismatch")); + assert_eq!(rx.recv().unwrap(), Err(error.clone())); + assert_eq!(me.check(), Err(error)); + ticket.complete(Ok(vec![1])); + assert!(rx.try_recv().is_err(), "a late callback cannot complete twice"); + let called = std::cell::Cell::new(false); + assert!(me.run_device(|| called.set(true)).is_err()); + assert!(!called.get(), "a retired device is never polled again"); + } + + #[test] + fn retirement_during_a_driver_call_rejects_its_result_without_locking_callbacks() { + let me = Readbacks::new().unwrap(); + let result = me.run_device(|| { + // A device-error callback can run inside poll or submit, before the call returns. + me.retire("device lost during submission".into()); + 42 + }); + assert_eq!(result, Err("device lost during submission".into())); + } + #[test] fn timeout_racing_late_map_callback_unmaps_once() { let mapping = Arc::new(Mapping::new()); diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index b2b5474b1..433128248 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -1121,6 +1121,10 @@ fn retired_attempt_releases_kept_resources(retire_before: bool) { assert_eq!(g.ctx.pool_retained_bytes(), 0, "CPU fallback must not retain working textures"); drop(earlier); assert_eq!(g.ctx.pool_retained_bytes(), 0, "late leases cannot refill a retired pool"); + let waits = g.ctx.pool_waits(); + g.ctx.pool_charge_dying(1 << 20); + g.ctx.pool_frame_end(); + assert_eq!(g.ctx.pool_waits(), waits, "CPU fallback must not submit cleanup work to the retired queue"); } #[test]