Merge pull request #4349 from dotCooCoo/fix/gpu-device-loss-followup

GPU: reads, polls and uploads report device loss from a destroyed shared device
This commit is contained in:
BFlat authored and GitHub committed 2026-11-30 14:19:23 +07:00
commit aa82ca199c
4 files changed
+1364 -78

No files matched your search

+104 -31
View File
@@ -243,6 +243,11 @@ impl DeviceHealth {
self.0.lost.get().map(|text| Fault::Lost(text.clone())).or_else(|| self.0.error.get().map(|text| Fault::Error(text.clone())))
}
/// Whether an error other than out of memory was recorded, even if a device loss was also recorded.
pub fn has_non_oom_error(&self) -> bool {
self.0.error.get().is_some()
}
/// The device loss in the form of `craft_gpu::GpuContext::device_status`:
/// [`GpuFault::DeviceLost`](craft_gpu::GpuFault::DeviceLost) once a loss is recorded,
/// otherwise `Ok`. Other errors are reported by [`fault`](Self::fault). wgpu keeps one
@@ -312,33 +317,42 @@ impl DeviceHealth {
/// loss. Native only: the web has no blocking wait.
#[cfg(not(target_arch = "wasm32"))]
pub fn wait(&self, device: &wgpu::Device, index: wgpu::SubmissionIndex) -> bool {
self.wait_with_check(device, index, || true)
}
/// This method calls `check` before each [`Self::wait`] slice and stops if it returns false.
#[cfg(not(target_arch = "wasm32"))]
pub fn wait_with_check(&self, device: &wgpu::Device, index: wgpu::SubmissionIndex, check: impl FnMut() -> bool) -> bool {
const SLICE: Duration = Duration::from_millis(100);
self.wait_unbounded(|| {
let poll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
device.poll(wgpu::PollType::Wait { submission_index: Some(index.clone()), timeout: Some(SLICE) })
}));
match poll {
Ok(Ok(_)) => SlicePoll::Done,
Ok(Err(wgpu::PollError::Timeout)) => SlicePoll::Pending,
Ok(Err(e)) => {
log::warn!("wgpu poll: {e}");
SlicePoll::Failed
self.wait_unbounded(
|| {
let poll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
device.poll(wgpu::PollType::Wait { submission_index: Some(index.clone()), timeout: Some(SLICE) })
}));
match poll {
Ok(Ok(_)) => SlicePoll::Done,
Ok(Err(wgpu::PollError::Timeout)) => SlicePoll::Pending,
Ok(Err(e)) => {
log::warn!("wgpu poll: {e}");
SlicePoll::Failed
}
Err(_) => {
self.lost_by_poll();
SlicePoll::Failed
}
}
Err(_) => {
self.lost_by_poll();
SlicePoll::Failed
}
}
})
},
check,
)
}
/// [`Self::wait`]'s loop: `poll` runs one slice and reports what wgpu returned. The loop ends
/// when a slice finished or failed, and before the next slice once a clone of this flag
/// recorded a loss or an error other than out of memory.
#[cfg(not(target_arch = "wasm32"))]
fn wait_unbounded(&self, mut poll: impl FnMut() -> SlicePoll) -> bool {
fn wait_unbounded(&self, mut poll: impl FnMut() -> SlicePoll, mut check: impl FnMut() -> bool) -> bool {
loop {
if !self.pollable() {
if !self.pollable() || !check() || !self.pollable() {
return false;
}
match poll() {
@@ -657,26 +671,60 @@ mod tests {
let h = DeviceHealth::new();
let other = h.clone();
let mut polls = 0;
let finished = h.wait_unbounded(|| {
polls += 1;
if polls == 2 {
other.mark(Fault::Error("Validation Error".into()));
}
assert!(polls <= 2, "a slice ran after the fault");
SlicePoll::Pending
});
let finished = h.wait_unbounded(
|| {
polls += 1;
if polls == 2 {
other.mark(Fault::Error("Validation Error".into()));
}
assert!(polls <= 2, "a slice ran after the fault");
SlicePoll::Pending
},
|| true,
);
assert!(!finished);
assert_eq!(polls, 2);
// out of memory alone keeps the wait going until the work finishes
let oom = DeviceHealth::new();
oom.mark(Fault::Error(OUT_OF_MEMORY.into()));
let mut polls = 0;
assert!(oom.wait_unbounded(|| {
polls += 1;
if polls < 3 { SlicePoll::Pending } else { SlicePoll::Done }
}));
assert!(oom.wait_unbounded(
|| {
polls += 1;
if polls < 3 { SlicePoll::Pending } else { SlicePoll::Done }
},
|| true,
));
assert_eq!(polls, 3);
assert!(!DeviceHealth::new().wait_unbounded(|| SlicePoll::Failed));
assert!(!DeviceHealth::new().wait_unbounded(|| SlicePoll::Failed, || true));
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn a_validity_check_between_wait_slices_stops_pending_work() {
for fault in [None, Some(Fault::Lost("destroyed".into())), Some(Fault::Error("Validation Error".into()))] {
let health = DeviceHealth::new();
let polls = std::cell::Cell::new(0);
let finished = health.wait_unbounded(
|| {
polls.set(polls.get() + 1);
if polls.get() == 1 { SlicePoll::Pending } else { SlicePoll::Done }
},
|| {
if polls.get() == 0 {
return true;
}
if let Some(fault) = &fault {
health.mark(fault.clone());
true
} else {
false
}
},
);
assert!(!finished);
assert_eq!(polls.get(), 1);
}
}
#[test]
@@ -700,6 +748,31 @@ mod tests {
assert!(!Fault::Lost("out of memory".into()).is_out_of_memory());
}
#[test]
fn non_oom_errors_remain_visible_regardless_of_fault_precedence() {
for loss_first in [false, true] {
let health = DeviceHealth::new();
assert!(!health.has_non_oom_error());
health.mark(Fault::Error(OUT_OF_MEMORY.into()));
assert!(!health.has_non_oom_error());
if loss_first {
health.mark(Fault::Lost("reset".into()));
assert!(!health.has_non_oom_error());
}
health.mark(Fault::Error("Validation Error".into()));
assert!(health.has_non_oom_error());
health.mark(Fault::Error(OUT_OF_MEMORY.into()));
assert!(health.has_non_oom_error());
if !loss_first {
health.mark(Fault::Lost("reset".into()));
}
assert_eq!(health.polling_fault(), Some(Fault::Lost("reset".into())));
assert!(health.has_non_oom_error());
health.clear_out_of_memory(health.out_of_memory_count());
assert!(health.has_non_oom_error());
}
}
#[test]
fn out_of_memory_keeps_polls_running_until_cleared() {
let h = DeviceHealth::new();
+195 -40
View File
@@ -185,6 +185,37 @@ struct DeviceBacking {
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
impl DeviceBacking {
/// Copies reads whose map succeeded. Health is read before each copy, so an error another
/// user of the device records during the copies leaves the reads not yet copied pending.
fn collect_mapped_reads(&mut self, outcomes: &mut Vec<ReadOutcome>) {
let mut remaining = Vec::with_capacity(self.pending.len());
for pending in std::mem::take(&mut self.pending) {
let mapped = !self.health.has_non_oom_error() && pending.state.lock().map(|state| matches!(*state, Some(Ok(())))).unwrap_or(false);
if mapped {
outcomes.push(resolve_pending(&pending));
} else {
remaining.push(pending);
}
}
self.pending = remaining;
}
fn collect_readable_mapped_reads(&mut self, outcomes: &mut Vec<ReadOutcome>) {
let mut remaining = Vec::with_capacity(self.pending.len());
for pending in std::mem::take(&mut self.pending) {
let mapped = !self.health.has_non_oom_error() && pending.state.lock().map(|state| matches!(*state, Some(Ok(())))).unwrap_or(false);
if mapped {
let outcome = resolve_pending(&pending);
if outcome.result.is_ok() {
outcomes.push(outcome);
continue;
}
}
remaining.push(pending);
}
self.pending = remaining;
}
fn allocation_fault(&self, error: wgpu::Error, operation: &str) -> GpuFault {
self.health.caught(&self.device, &error);
if let Err(fault) = self.health.device_status() {
@@ -207,11 +238,22 @@ impl DeviceBacking {
if let Some(error) = pollster::block_on(scope.pop()) {
return Err(self.allocation_fault(error, "request_read: device reported an allocation error copying the buffer"));
}
self.check_device_valid()?;
let validity = self.check_device_valid();
if let Err(loss @ GpuFault::DeviceLost(_)) = validity {
return Err(loss);
}
// The probe's poll can run queue callbacks that record an out-of-memory error, which is
// reported on its own and before a validation error recorded in the same poll.
if let Some(fault) = self.health.fault() {
return Err(fault.into());
}
validity?;
Ok(submission)
}
fn check_device_valid(&self) -> Result<(), GpuFault> {
self.health.probe(&self.device);
self.health.device_status()?;
// wgpu-core 30.0.1 checks device validity before rejecting empty buffer usage.
// A valid device produces a scoped validation error; device loss bypasses the scope.
// Both paths return before HAL allocation or fence waits.
@@ -226,8 +268,6 @@ impl DeviceBacking {
}));
pollster::block_on(scope.pop())
}));
self.health.probe(&self.device);
self.health.device_status()?;
match result {
Ok(None) => {
self.health.confirm_device_lost("the device was destroyed or lost".into());
@@ -264,7 +304,7 @@ struct PendingRead {
}
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
fn resolve_pending(pending: PendingRead) -> ReadOutcome {
fn resolve_pending(pending: &PendingRead) -> ReadOutcome {
let PendingRead { request, handle, staging, true_len, state, .. } = pending;
let result = match state.lock() {
Ok(mut guard) => match guard.take() {
@@ -273,7 +313,7 @@ fn resolve_pending(pending: PendingRead) -> ReadOutcome {
let mut bytes = view.to_vec();
drop(view);
staging.unmap();
bytes.truncate(usize::try_from(true_len).unwrap_or(usize::MAX));
bytes.truncate(usize::try_from(*true_len).unwrap_or(usize::MAX));
Ok(bytes)
}
Err(err) => Err(GpuFault::Operation(err.to_string())),
@@ -283,7 +323,7 @@ fn resolve_pending(pending: PendingRead) -> ReadOutcome {
},
Err(_) => Err(GpuFault::Operation("read_buffer: map state lock poisoned".into())),
};
ReadOutcome { request, handle, result }
ReadOutcome { request: *request, handle: *handle, result }
}
/// wgpu-backed context. See the module docs for the real-device-vs-staging split.
@@ -396,10 +436,43 @@ impl WgpuContext {
#[cfg_attr(not(feature = "adapter-probe"), allow(unused_variables, clippy::unused_self))]
fn wait_between_reads(&mut self, request: ReadRequest) -> Option<GpuFault> {
#[cfg(feature = "adapter-probe")]
if let Backing::Device(d) = &mut self.backing
&& (d.health.polling_fault().is_some()
|| d.pending.iter().find(|p| p.request == request).is_some_and(|p| !d.health.wait(&d.device, p.submission.clone())))
{
if let Backing::Device(d) = &mut self.backing {
let ready_start = self.ready.len();
let mut waited = false;
let failed = d.health.polling_fault().is_some()
|| d.pending.iter().find(|p| p.request == request).map(|p| p.submission.clone()).is_some_and(|submission| {
let health = d.health.clone();
let device = d.device.clone();
!health.wait_with_check(&device, submission, || {
if waited {
d.collect_mapped_reads(&mut self.ready);
}
waited = false;
if !d.pending.iter().any(|p| p.request == request) {
return false;
}
let validity = d.check_device_valid();
let valid = validity.is_ok();
if valid {
d.collect_mapped_reads(&mut self.ready);
} else if matches!(validity, Err(GpuFault::DeviceLost(_))) && !d.health.has_non_oom_error() {
d.collect_readable_mapped_reads(&mut self.ready);
}
waited = valid && d.pending.iter().any(|p| p.request == request);
waited
})
});
if waited && !d.health.has_non_oom_error() {
d.collect_mapped_reads(&mut self.ready);
}
for outcome in &mut self.ready[ready_start..] {
if let Err(fault) = &mut outcome.result {
*fault = d.prefer_device_loss(fault.clone());
}
}
if self.ready.iter().any(|outcome| outcome.request == request) || !failed {
return None;
}
d.health.probe(&d.device);
if d.health.device_status().is_err() {
return None;
@@ -513,7 +586,16 @@ impl GpuContext for WgpuContext {
return Err(d.allocation_fault(err, "upload_buffer: device reported an allocation error writing the buffer"));
}
// Loss bypasses error scopes and its callback can wait for pending queue work.
d.check_device_valid()?;
let validity = d.check_device_valid();
if let Err(loss @ GpuFault::DeviceLost(_)) = validity {
return Err(loss);
}
// The probe's poll can run queue callbacks that record an out-of-memory error,
// which is reported before a validation error recorded in the same poll.
if let Some(fault) = d.health.fault() {
return Err(fault.into());
}
validity?;
let id = u32::try_from(d.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?;
d.buffers.push(Some((buffer, true_len)));
Ok(HandleId(id))
@@ -555,10 +637,14 @@ impl GpuContext for WgpuContext {
.get(handle.0 as usize)
.and_then(Option::as_ref)
.ok_or_else(|| d.prefer_device_loss(GpuFault::InvalidJob("bad handle".into())))?;
d.check_device_valid()?;
let validity = d.check_device_valid();
if let Err(loss @ GpuFault::DeviceLost(_)) = validity {
return Err(loss);
}
if let Some(fault) = self.take_work_fault() {
return Err(fault);
}
validity?;
}
match &mut self.backing {
Backing::Staging(buffers) => {
@@ -669,37 +755,106 @@ 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 {
// 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.
d.health.probe(&d.device);
let fault = d.health.polling_fault().map(GpuFault::from);
if let Some(fault) = fault {
let fault = d.prefer_device_loss(fault);
outcomes.extend(d.pending.drain(..).map(|p| ReadOutcome { request: p.request, handle: p.handle, result: Err(fault.clone()) }));
return outcomes;
}
let mut remaining: Vec<PendingRead> = Vec::with_capacity(d.pending.len());
let mut pending_reads = std::mem::take(&mut d.pending).into_iter();
while let Some(pending) = pending_reads.next() {
let is_ready = pending.state.lock().map(|g| g.is_some()).unwrap_or(false);
if is_ready {
let mut outcome = resolve_pending(pending);
outcome.result = outcome.result.map_err(|fault| d.prefer_device_loss(fault));
if let Err(fault @ GpuFault::DeviceLost(_)) = &outcome.result {
outcomes.extend(remaining.into_iter().chain(pending_reads).map(|p| ReadOutcome {
request: p.request,
handle: p.handle,
result: Err(fault.clone()),
}));
outcomes.push(outcome);
return outcomes;
}
outcomes.push(outcome);
let mut disqualified = false;
// A loss recorded before this call fails every pending read. A loss first seen by
// this call's polls keeps the bytes of reads whose map already succeeded.
let lost_at_entry = d.health.device_status().is_err();
// The first pass polls and collects completed reads. A validity check runs on the
// first pass when nothing is pending, and on a second pass for reads still waiting.
// A third pass runs only when a map error probe on the second pass recorded a fault,
// so the reads still waiting fail in this call.
for pass in 0..3 {
if pass == 2 && d.health.polling_fault().is_none() {
break;
}
let check_validity = match pass {
0 => d.pending.is_empty(),
1 => true,
_ => false,
};
let validity = if check_validity {
d.check_device_valid()
} else {
remaining.push(pending);
d.health.probe(&d.device);
Ok(())
};
// The error slot is never cleared, so reading it first means an error recorded
// between the two reads is also seen by `polling_fault`.
disqualified |= d.health.has_non_oom_error();
let polling_fault = d.health.polling_fault();
let fault = polling_fault.map(GpuFault::from).or_else(|| validity.err());
if let Some(fault) = fault {
let fault = d.prefer_device_loss(fault);
// A validation error recorded after the first read and before the loss is
// hidden by `polling_fault`, so the flag is read again before each copy.
for pending in d.pending.drain(..) {
disqualified |= d.health.has_non_oom_error();
let completed = !lost_at_entry
&& !disqualified
&& matches!(&fault, GpuFault::DeviceLost(_))
&& pending.state.lock().map(|state| matches!(*state, Some(Ok(())))).unwrap_or(false);
if completed {
let mut outcome = resolve_pending(&pending);
outcome.result = outcome.result.map_err(|_| fault.clone());
outcomes.push(outcome);
} else {
outcomes.push(ReadOutcome { request: pending.request, handle: pending.handle, result: Err(fault.clone()) });
}
}
return outcomes;
}
loop {
let mut remaining: Vec<PendingRead> = Vec::with_capacity(d.pending.len());
let outcomes_start = outcomes.len();
for pending in std::mem::take(&mut d.pending) {
let is_ready = pending.state.lock().map(|g| g.is_some()).unwrap_or(false);
// A mapped read is not copied once the device has recorded an error other
// than out of memory; it stays pending and the fault handling fails it.
let mapped = pending.state.lock().map(|g| matches!(*g, Some(Ok(())))).unwrap_or(false);
if is_ready && !(mapped && d.health.has_non_oom_error()) {
outcomes.push(resolve_pending(&pending));
} else {
remaining.push(pending);
}
}
d.pending = remaining;
let mut probed = false;
let mut outcome_index = outcomes_start;
while outcome_index < outcomes.len() {
if let Err(fault) = &mut outcomes[outcome_index].result {
probed = true;
*fault = d.prefer_device_loss(fault.clone());
let loss = matches!(fault, GpuFault::DeviceLost(_)).then(|| fault.clone());
disqualified |= d.health.has_non_oom_error();
// The probe can run a map callback, so reads that mapped are collected
// before a loss fails the rest.
if !disqualified {
d.collect_mapped_reads(&mut outcomes);
}
if let Some(fault) = loss {
for outcome in outcomes.iter_mut().skip(outcome_index + 1) {
if outcome.result.is_err() {
outcome.result = Err(fault.clone());
}
}
outcomes.extend(d.pending.drain(..).map(|pending| ReadOutcome {
request: pending.request,
handle: pending.handle,
result: Err(fault.clone()),
}));
return outcomes;
}
}
outcome_index += 1;
}
if !probed || d.pending.is_empty() || d.health.polling_fault().is_some() {
break;
}
}
if d.pending.is_empty() {
break;
}
}
d.pending = remaining;
}
outcomes
}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -25,7 +25,7 @@ Buffers are real `wgpu::Buffer`s (`STORAGE | COPY_SRC | COPY_DST`). The host-sta
## Device loss (RFC-0022 requirement 1)
`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`. Before returning that fault on a device backing, both calls check device validity without allocating GPU memory. A detected loss returns `GpuFault::DeviceLost` even while the device-lost callback is deferred. `poll_reads()` fails pending reads on recorded faults other than out of memory; an out-of-memory fault leaves those reads eligible to complete. `device_status()` reports a loss only, and `free_buffer` keeps running. An allocation error the context's own error scopes catch is recorded in the `DeviceHealth` as well (`DeviceHealth::caught`).
`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`. Before returning that fault on a device backing, both calls check device validity without allocating GPU memory. A detected loss returns `GpuFault::DeviceLost` even while the device-lost callback is deferred. `poll_reads()` fails pending reads on recorded faults other than out of memory; an out-of-memory fault leaves those reads eligible to complete. When a loss is first detected by the polls of a `poll_reads()` or `read_buffer` call, a read whose map already succeeded can still return its bytes when its mapped range is still readable, unless the call reads an error other than out of memory from the `DeviceHealth` before it copies that read. The call checks for such an error before each copy; an error another thread records while a copy runs is not checked against that copy. Bytes copied earlier in the same call are returned even when the call later sees such an error. A read that returns bytes does not show that the device is still usable. `device_status()` reports only a loss already recorded, and wgpu can deliver the loss on a later poll. `device_status()` reports a loss only, and `free_buffer` keeps 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):