Skip to main content

alpha2_render/
gpu_errors.rs

1//! GPU error tracking for a frame's work.
2//!
3//! An out-of-memory texture or invalid pass makes its whole submission rejected, and
4//! `queue.submit` does not say so; the error goes to an error scope or the uncaptured-error
5//! handler. Unchecked, the renderer would keep results never drawn, reuse failed allocations,
6//! and misread the missing readback canary as a device dropping work.
7//!
8//! Every renderer encoder therefore opens a [`FrameErrorScope`] that its submission closes.
9//! Natively scopes resolve at once and an error fails the frame ([`crate::RenderError::Gpu`]).
10//! In a browser scopes resolve only on the event loop, so the embedding reports uncaptured
11//! errors ([`GpuErrorReports::report`]) and the renderer drops kept state before its next frame.
12//!
13//! Either way, everything pooled before the error is distrusted
14//! ([`crate::retire::Retirement::doubt`]), since `wgpu` cannot say which object is invalid.
15
16use std::sync::Arc;
17use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
18
19use alpha2_gpu::GpuErrorKind;
20
21use crate::Shared;
22use crate::retire::Retirement;
23
24/// Internal, out-of-memory and validation scopes of one renderer encoder, open until submission.
25///
26/// Scopes are per thread and close in reverse order, so this is neither `Send` nor `Sync`, and
27/// a nested encoder must be submitted or dropped first.
28#[derive(Debug)]
29pub(crate) struct FrameErrorScope {
30    #[cfg(not(target_arch = "wasm32"))]
31    scopes: Option<[wgpu::ErrorScopeGuard; 3]>,
32    /// Told when an encoder is dropped unsubmitted with an error, since it may have pooled an
33    /// invalid resource.
34    retirement: Shared<Retirement>,
35    #[cfg(target_arch = "wasm32")]
36    _thread_bound: std::marker::PhantomData<*mut ()>,
37}
38
39impl FrameErrorScope {
40    /// Opens the scopes on this thread; a no-op in a browser.
41    pub(crate) fn open(
42        #[cfg_attr(target_arch = "wasm32", allow(unused_variables))] device: &wgpu::Device,
43        retirement: Shared<Retirement>,
44    ) -> Self {
45        Self {
46            #[cfg(not(target_arch = "wasm32"))]
47            scopes: Some([
48                device.push_error_scope(wgpu::ErrorFilter::Internal),
49                device.push_error_scope(wgpu::ErrorFilter::OutOfMemory),
50                device.push_error_scope(wgpu::ErrorFilter::Validation),
51            ]),
52            retirement,
53            #[cfg(target_arch = "wasm32")]
54            _thread_bound: std::marker::PhantomData,
55        }
56    }
57
58    /// Closes the scopes and returns the error: out-of-memory first because a failed allocation
59    /// also causes validation errors downstream, then internal, then validation.
60    pub(crate) fn close(mut self) -> Option<GpuErrorKind> {
61        self.pop()
62    }
63
64    #[cfg(not(target_arch = "wasm32"))]
65    fn pop(&mut self) -> Option<GpuErrorKind> {
66        let [internal, out_of_memory, validation] = self.scopes.take()?;
67        let validation = resolved(validation.pop());
68        let out_of_memory = resolved(out_of_memory.pop());
69        let internal = resolved(internal.pop());
70        out_of_memory
71            .or(internal)
72            .or(validation)
73            .map(|error| GpuErrorKind::of(&error))
74    }
75
76    #[cfg(target_arch = "wasm32")]
77    #[allow(clippy::unused_self)] // The browser opens no scope to pop.
78    const fn pop(&mut self) -> Option<GpuErrorKind> {
79        None
80    }
81}
82
83impl Drop for FrameErrorScope {
84    fn drop(&mut self) {
85        if self.pop().is_some() {
86            self.retirement.doubt();
87        }
88    }
89}
90
91/// Runs `create` under out-of-memory and validation scopes, returning what they caught as
92/// [`FrameErrorScope::close`] does.
93///
94/// For resources made outside a frame, whose failure must fail the call. A no-op in a browser,
95/// where the uncaptured-error report covers it.
96pub(crate) fn capture_creation<T>(
97    #[cfg_attr(target_arch = "wasm32", allow(unused_variables))] device: &wgpu::Device,
98    create: impl FnOnce() -> T,
99) -> (T, Option<GpuErrorKind>) {
100    #[cfg(not(target_arch = "wasm32"))]
101    {
102        let out_of_memory = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
103        let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
104        let created = create();
105        let validation = resolved(validation.pop());
106        let out_of_memory = resolved(out_of_memory.pop());
107        (
108            created,
109            out_of_memory
110                .or(validation)
111                .map(|error| GpuErrorKind::of(&error)),
112        )
113    }
114    #[cfg(target_arch = "wasm32")]
115    {
116        (create(), None)
117    }
118}
119
120/// Scopes for every error class shader-module or pipeline creation can raise.
121///
122/// `wgpu` routes an error only to a scope of its class. A backend compiler rejecting code
123/// generated from valid WGSL reports an internal error, and OOM its own class; uncaught, either
124/// leaves an invalid pipeline that invalidates every submission drawing it.
125pub(crate) struct CreationErrorScopes([wgpu::ErrorScopeGuard; 3]);
126
127impl CreationErrorScopes {
128    pub(crate) fn push(device: &wgpu::Device) -> Self {
129        Self([
130            device.push_error_scope(wgpu::ErrorFilter::Internal),
131            device.push_error_scope(wgpu::ErrorFilter::OutOfMemory),
132            device.push_error_scope(wgpu::ErrorFilter::Validation),
133        ])
134    }
135
136    /// Pops the scopes in reverse push order and returns what they caught.
137    pub(crate) fn pop(self) -> ScopeErrors {
138        let [internal, out_of_memory, validation] = self.0;
139        let validation = validation.pop();
140        let out_of_memory = out_of_memory.pop();
141        let internal = internal.pop();
142        Box::pin(async move {
143            [validation.await, out_of_memory.await, internal.await]
144                .into_iter()
145                .flatten()
146                .collect()
147        })
148    }
149}
150
151/// Not `Send` in a browser, where the device answers on its own event loop.
152#[cfg(not(target_arch = "wasm32"))]
153pub(crate) type Answer<T> = std::pin::Pin<Box<dyn std::future::Future<Output = T> + Send>>;
154#[cfg(target_arch = "wasm32")]
155pub(crate) type Answer<T> = std::pin::Pin<Box<dyn std::future::Future<Output = T>>>;
156
157pub(crate) type ScopeErrors = Answer<Vec<wgpu::Error>>;
158
159/// Runs `create` under scopes of every creation error class and returns the first error caught:
160/// out-of-memory, then internal, then validation.
161///
162/// Lazily created pipelines keep only a success, so a failed creation fails its frame and the
163/// next frame tries again. In a browser scopes answer only on the event loop, so this is `Ok`.
164#[cfg_attr(target_arch = "wasm32", allow(clippy::unnecessary_wraps))]
165pub(crate) fn create_checked<T>(
166    #[cfg_attr(target_arch = "wasm32", allow(unused_variables))] device: &wgpu::Device,
167    create: impl FnOnce() -> T,
168) -> Result<T, GpuErrorKind> {
169    #[cfg(not(target_arch = "wasm32"))]
170    {
171        let CreationErrorScopes([internal, out_of_memory, validation]) =
172            CreationErrorScopes::push(device);
173        let created = create();
174        let validation = resolved(validation.pop());
175        let out_of_memory = resolved(out_of_memory.pop());
176        let internal = resolved(internal.pop());
177        match out_of_memory.or(internal).or(validation) {
178            Some(error) => Err(GpuErrorKind::of(&error)),
179            None => Ok(created),
180        }
181    }
182    #[cfg(target_arch = "wasm32")]
183    {
184        Ok(create())
185    }
186}
187
188/// `cell`'s value, created under [`create_checked`] when empty; a failed creation stores nothing.
189pub(crate) fn checked_cell<'a, T>(
190    cell: &'a std::sync::OnceLock<T>,
191    device: &wgpu::Device,
192    create: impl FnOnce() -> T,
193) -> Result<&'a T, crate::RenderError> {
194    if let Some(value) = cell.get() {
195        return Ok(value);
196    }
197    let created =
198        create_checked(device, create).map_err(|kind| crate::RenderError::Gpu { kind })?;
199    Ok(cell.get_or_init(|| created))
200}
201
202/// A native scope's result, ready when popped on `wgpu-core`.
203#[cfg(not(target_arch = "wasm32"))]
204fn resolved<T>(future: impl std::future::Future<Output = Option<T>>) -> Option<T> {
205    let mut future = std::pin::pin!(future);
206    let mut context = std::task::Context::from_waker(std::task::Waker::noop());
207    match future.as_mut().poll(&mut context) {
208        std::task::Poll::Ready(result) => result,
209        std::task::Poll::Pending => None,
210    }
211}
212
213/// GPU errors the embedding saw outside the renderer's scopes (in a browser, all of them).
214///
215/// Clones share one record, so the embedding keeps one in its error handler. The renderer acts
216/// on reports at its next encoder.
217#[derive(Clone, Debug, Default)]
218pub struct GpuErrorReports {
219    inner: Arc<ReportState>,
220}
221
222#[derive(Debug, Default)]
223struct ReportState {
224    /// Errors reported so far.
225    reported: AtomicU64,
226    /// How many reports the renderer has dropped its kept state for.
227    handled: AtomicU64,
228    /// The last kind, encoded by [`kind_code`].
229    last: AtomicU8,
230}
231
232impl GpuErrorReports {
233    /// Records an error reported outside the renderer's scopes. Lock-free; callable from any
234    /// thread.
235    pub fn report(&self, kind: GpuErrorKind) {
236        self.inner.last.store(kind_code(kind), Ordering::Release);
237        self.inner.reported.fetch_add(1, Ordering::AcqRel);
238    }
239
240    /// How many errors have been reported.
241    pub(crate) fn count(&self) -> u64 {
242        self.inner.reported.load(Ordering::Acquire)
243    }
244
245    pub(crate) fn last_kind(&self) -> Option<GpuErrorKind> {
246        match self.inner.last.load(Ordering::Acquire) {
247            1 => Some(GpuErrorKind::OutOfMemory),
248            2 => Some(GpuErrorKind::Validation),
249            3 => Some(GpuErrorKind::Internal),
250            _ => None,
251        }
252    }
253
254    /// Whether errors were reported since the last call, marking them handled.
255    pub(crate) fn take_unhandled(&self) -> bool {
256        let reported = self.count();
257        self.inner.handled.swap(reported, Ordering::AcqRel) != reported
258    }
259}
260
261const fn kind_code(kind: GpuErrorKind) -> u8 {
262    match kind {
263        GpuErrorKind::OutOfMemory => 1,
264        GpuErrorKind::Validation => 2,
265        _ => 3,
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272
273    #[test]
274    fn reports_are_counted_and_handled_once() {
275        let reports = GpuErrorReports::default();
276        assert!(!reports.take_unhandled());
277        assert_eq!(reports.last_kind(), None);
278        let handler = reports.clone();
279        handler.report(GpuErrorKind::OutOfMemory);
280        handler.report(GpuErrorKind::Validation);
281        assert_eq!(reports.count(), 2);
282        assert_eq!(reports.last_kind(), Some(GpuErrorKind::Validation));
283        assert!(reports.take_unhandled());
284        assert!(!reports.take_unhandled());
285        handler.report(GpuErrorKind::Internal);
286        assert_eq!(reports.last_kind(), Some(GpuErrorKind::Internal));
287        assert!(reports.take_unhandled());
288    }
289}