A surface the GPU fails to reconfigure is logged and retried, not a crash (#1935) (#1966)

Thanks @HiroKenEz.
This commit is contained in:
HiroKenEz
2026-10-18 16:02:02 +02:00
committed by GitHub
parent 535a43ab3c
commit 1ee6611403
5 changed files with 465 additions and 14 deletions
+2
View File
@@ -77,6 +77,8 @@ mod pattern_arrow_tests;
#[cfg(test)]
mod surface_clamp_tests;
#[cfg(test)]
mod surface_errors_tests;
#[cfg(test)]
mod timeline_marks_tests;
#[cfg(test)]
mod status_tests {
+179
View File
@@ -0,0 +1,179 @@
//! A surface the driver fails to reconfigure was a crash (#1935): on D3D12, `Surface::configure`
//! reported "Failed to wait for GPU to come idle before reconfiguring the Surface", and the
//! device's default uncaptured-error handler panicked on it. The vendored egui-wgpu configures
//! its surfaces under `capture_errors`, logs the error and tries again once the retry is due. A
//! driver's refusal can't be provoked here, so these check the capture on a real device with an
//! error the validation always reports, and the retry policy with a stand-in clock and device.
use egui_wgpu::{Attempt, ConfigureRetry, SURFACE_RECREATE_AFTER, capture_errors, wgpu};
use std::time::Duration;
use web_time::Instant;
#[test]
fn an_error_under_capture_is_returned_not_a_panic() {
let Some((_, device, _)) = crate::gpu::offscreen_device() else { return };
// Mapped at creation with a size that isn't a multiple of 4: a validation error.
let (_, error) = capture_errors(&device, || {
device.create_buffer(&wgpu::BufferDescriptor { label: Some("bad"), size: 3, usage: wgpu::BufferUsages::MAP_WRITE, mapped_at_creation: true })
});
assert!(error.is_some_and(|e| matches!(e, wgpu::Error::Validation { .. })), "the validation error is captured");
// The device goes on working, and a clean call reports nothing.
let (buffer, error) = capture_errors(&device, || {
device.create_buffer(&wgpu::BufferDescriptor { label: Some("good"), size: 4, usage: wgpu::BufferUsages::COPY_DST, mapped_at_creation: false })
});
assert!(error.is_none(), "{error:?}");
assert_eq!(buffer.size(), 4);
}
/// A surface that keeps refusing its configuration waits 16 ms before the next try, doubling with
/// each refusal in a row up to 1 s, and every few refusals the surface is recreated (asked in
/// review of #1966). Only the first refusal of the streak is worth a warning.
#[test]
fn refused_configures_back_off_and_recreate_the_surface() {
let start = Instant::now();
let mut retry = ConfigureRetry::default();
let plans: Vec<_> = (0..9).map(|_| retry.refused(start)).collect();
let delays: Vec<u128> = plans.iter().map(|plan| plan.delay.as_millis()).collect();
assert_eq!(delays, [16, 32, 64, 128, 256, 512, 1000, 1000, 1000], "capped at a second");
assert_eq!(plans.iter().map(|plan| plan.failures).collect::<Vec<_>>(), (1..=9).collect::<Vec<_>>());
assert_eq!(plans.iter().filter(|plan| plan.first).count(), 1);
assert!(plans.first().is_some_and(|plan| plan.first));
let recreate: Vec<u32> = plans.iter().filter(|plan| plan.recreate).map(|plan| plan.failures).collect();
assert_eq!(recreate, [SURFACE_RECREATE_AFTER, 2 * SURFACE_RECREATE_AFTER, 3 * SURFACE_RECREATE_AFTER]);
// The last refusal's try is due a second later.
assert_eq!(retry.wait(start), Some(Duration::from_secs(1)));
assert!(retry.is_due(start + Duration::from_secs(1)));
}
/// The review of #1966: a repaint that comes before the retry is due (pointer input, an
/// animation, another UI update) must not configure or recreate the surface. Here the window
/// repaints every frame at 60 Hz for 10 s on a device that refuses every configure, and the
/// frames follow `paint_and_update_textures`: recreate when one is pending and due (which
/// `recreate_surface` marks done), then configure.
#[test]
fn repaints_before_the_retry_is_due_neither_configure_nor_recreate() {
let start = Instant::now();
// Just after a refusal, each early repaint is told how long is left and tries nothing.
let mut retry = ConfigureRetry::default();
retry.refused(start);
for ms in 0..16 {
let mut tried = false;
let attempt = retry.attempt(start + Duration::from_millis(ms), || {
tried = true;
Ok::<(), ()>(())
});
assert!(matches!(attempt, Attempt::Waiting(left) if left == Duration::from_millis(16 - ms)), "{ms} ms: {attempt:?}");
assert!(!tried, "{ms} ms: configured before the retry was due");
}
assert_eq!(retry.failures(), 1, "waiting doesn't count as a refusal");
let frame = Duration::from_micros(16_667);
let frames = 600;
let mut retry = ConfigureRetry::default();
let (mut configures, mut recreates) = (0u32, 0u32);
let mut refusals: Vec<(Instant, Duration)> = Vec::new();
for n in 0..frames {
let now = start + frame * n;
if retry.recreate_due(now) {
assert!(retry.is_due(now), "recreated before the retry was due");
recreates += 1;
retry.recreated();
} else if retry.recreate_pending() {
assert!(!retry.is_due(now), "a due recreate was left pending");
}
let attempt = retry.attempt(now, || {
configures += 1;
Err::<(), _>("refused")
});
match attempt {
Attempt::Refused(plan, _) => {
assert_eq!(plan.recreate, retry.recreate_pending(), "{plan:?}");
refusals.push((now, plan.delay));
}
Attempt::Waiting(left) => assert!(left <= Duration::from_secs(1), "{left:?}"),
Attempt::Took(_) => panic!("the device refuses every configure"),
}
}
// The tries ramp up through 16 ms .. 512 ms (7 tries in the first second), then one a second:
// 15 configures in 600 frames, not one a frame.
assert_eq!(configures, 15, "{refusals:?}");
assert_eq!(refusals.len(), 15);
// No try comes before the delay the previous refusal set.
for pair in refusals.windows(2) {
let [(at, delay), (next, _)] = pair else { continue };
assert!(next.duration_since(*at) >= *delay, "{pair:?}");
}
// A recreate before the try after every third refusal (the 3rd, 6th, 9th and 12th; the
// 15th's try falls after the 10 s), not every third frame.
assert_eq!(recreates, (configures - 1) / SURFACE_RECREATE_AFTER);
assert_eq!(recreates, 4);
assert!(retry.recreate_pending(), "the 15th refusal asked for a recreate, still waiting for its retry");
}
/// A configure the device takes ends the streak: the next refusal is a first one again, warned
/// about and retried after 16 ms. A first configure is never held back.
#[test]
fn a_configure_the_device_takes_ends_the_streak() {
let start = Instant::now();
let mut retry = ConfigureRetry::default();
assert!(retry.is_due(start), "nothing refused yet");
for _ in 0..4 {
retry.refused(start);
}
let due = start + Duration::from_millis(128);
assert!(!retry.is_due(due - Duration::from_millis(1)));
let attempt = retry.attempt(due, || Ok::<(), ()>(()));
assert!(matches!(attempt, Attempt::Took(4)), "{attempt:?}");
assert_eq!(retry, ConfigureRetry::default());
assert_eq!(retry.failures(), 0);
assert_eq!(retry.wait(due), None, "no deadline left");
let plan = retry.refused(due);
assert!(plan.first && plan.failures == 1 && !plan.recreate, "{plan:?}");
assert_eq!(plan.delay, Duration::from_millis(16));
assert_eq!(retry.wait(due), Some(Duration::from_millis(16)));
// `took` alone does the same, and reports an empty streak as 0.
assert_eq!(retry.took(), 1);
assert_eq!(retry.took(), 0);
}
/// A configure the device takes after the refusal that asked for a recreate (a resize at the
/// retry's deadline, before the next frame) ends the streak with its recreate: the surface took
/// its configuration, so the next frame doesn't recreate it.
#[test]
fn a_configure_taken_cancels_the_pending_recreate() {
let start = Instant::now();
let mut retry = ConfigureRetry::default();
let plans: Vec<_> = (0..SURFACE_RECREATE_AFTER).map(|_| retry.refused(start)).collect();
assert!(plans.last().is_some_and(|plan| plan.recreate));
let due = start + Duration::from_millis(64);
assert!(retry.recreate_pending());
assert!(!retry.recreate_due(due - Duration::from_millis(1)), "not before the deadline");
assert!(retry.recreate_due(due));
let attempt = retry.attempt(due, || Ok::<(), ()>(()));
assert!(matches!(attempt, Attempt::Took(n) if n == SURFACE_RECREATE_AFTER), "{attempt:?}");
assert!(!retry.recreate_pending());
assert!(!retry.recreate_due(due + Duration::from_secs(10)));
assert_eq!(retry, ConfigureRetry::default());
}
/// `recreate_surface` hands the old surface's retry to the new one with the recreate marked
/// done: the deadline still holds, the new surface doesn't recreate itself again, and the streak
/// goes on rather than starting again.
#[test]
fn the_retry_survives_a_recreate() {
let start = Instant::now();
let mut old = ConfigureRetry::default();
let plans: Vec<_> = (0..SURFACE_RECREATE_AFTER).map(|_| old.refused(start)).collect();
assert!(plans.last().is_some_and(|plan| plan.recreate));
let mut carried = old;
carried.recreated();
assert!(old.recreate_pending() && !carried.recreate_pending());
assert!(!carried.recreate_due(start + Duration::from_secs(10)));
assert_eq!(carried.failures(), old.failures());
let soon = start + Duration::from_millis(10);
assert_eq!(carried.wait(soon), old.wait(soon));
assert_eq!(carried.wait(soon), Some(Duration::from_millis(54)));
let next = carried.refused(start + Duration::from_millis(64));
assert!(!next.first, "{next:?}");
assert_eq!((next.failures, next.delay), (SURFACE_RECREATE_AFTER + 1, Duration::from_millis(128)));
}
+11
View File
@@ -234,3 +234,14 @@ SolidCraft changes:
an unsupported surface no longer unwrap.
- `src/winit.rs`: acquire a drawable before preparing paint callbacks, so a skipped
surface frame cannot discard initialization commands for cached viewport meshes.
- `src/lib.rs`, `src/winit.rs`: surfaces are configured under `capture_errors` (error scopes):
a configuration the device refuses (D3D12 "Failed to wait for GPU to come idle before
reconfiguring the Surface", #1935) is logged, the frame is skipped and the configure is tried
again, instead of the device's uncaptured-error handler panicking. A streak of refusals warns
once (debug after), waits 16 ms doubling up to 1 s between tries and recreates the surface
every `SURFACE_RECREATE_AFTER` refusals (`ConfigureRetry`). Each surface keeps the deadline of
its next try: until it is due, no configure or recreate happens, whether the repaint comes
from input, an animation, a resize (its size is kept for the retry) or an outdated surface,
and the frame is skipped with a repaint asked for when it is due. The streak and the deadline
survive a recreate; a configure the device takes ends the streak, a recreate it asked for
included. A recreate for a lost surface goes ahead as before.
+141
View File
@@ -712,6 +712,147 @@ mod msaa_tests {
}
}
/// SolidCraft: run `f` with `device`'s errors captured, and the first error it caused. Uncaptured,
/// an error goes to the device's handler, which panics by default: a surface the driver can't
/// reconfigure (D3D12 "Failed to wait for GPU to come idle", #1935) crashed the app. Native error
/// scopes resolve at once; on the web the scope still keeps the error from the handler.
pub fn capture_errors<T>(device: &wgpu::Device, f: impl FnOnce() -> T) -> (T, Option<wgpu::Error>) {
let scopes = [
wgpu::ErrorFilter::OutOfMemory,
wgpu::ErrorFilter::Internal,
wgpu::ErrorFilter::Validation,
]
.map(|filter| device.push_error_scope(filter));
let value = f();
let mut failed = None;
for scope in scopes.into_iter().rev() {
let mut popped = std::pin::pin!(scope.pop());
let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
if let std::task::Poll::Ready(Some(error)) =
std::future::Future::poll(popped.as_mut(), &mut cx)
{
failed.get_or_insert(error);
}
}
(value, failed)
}
/// SolidCraft: refused configures in a row after which the surface is recreated (#1935).
pub const SURFACE_RECREATE_AFTER: u32 = 3;
/// SolidCraft: a surface's streak of refused configures (#1935) and when the next try is due.
/// A refusal waits 16 ms, doubling with each refusal in a row up to 1 s, and every
/// [`SURFACE_RECREATE_AFTER`] refusals the surface is recreated before the next try. Until the
/// try is due, no configure or recreate happens however often the window repaints, so a device
/// that keeps refusing costs a try a second instead of one a frame. A configure the device takes
/// ends the streak, a recreate still pending included. The clock is passed in, for tests.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ConfigureRetry {
failures: u32,
due: Option<web_time::Instant>,
/// The streak asked for a recreate that hasn't happened yet.
recreate: bool,
}
/// SolidCraft: what follows a refused configure ([`ConfigureRetry::refused`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RetryPlan {
/// Refusals in a row, this one included.
pub failures: u32,
/// The first refusal of the streak: the one worth a warning.
pub first: bool,
/// How long until the next try.
pub delay: std::time::Duration,
/// This refusal asked for the surface to be recreated before the next try.
pub recreate: bool,
}
impl ConfigureRetry {
/// Refusals in a row so far.
pub fn failures(&self) -> u32 {
self.failures
}
/// How long until the next try is due at `now`; `None` when a configure may go ahead (no
/// refusal pending, or its delay has passed).
pub fn wait(&self, now: web_time::Instant) -> Option<std::time::Duration> {
self.due
.and_then(|due| due.checked_duration_since(now))
.filter(|left| !left.is_zero())
}
/// Whether a configure (or recreate) may go ahead at `now`.
pub fn is_due(&self, now: web_time::Instant) -> bool {
self.wait(now).is_none()
}
/// Whether the streak asked for a recreate that hasn't happened yet.
pub fn recreate_pending(&self) -> bool {
self.recreate
}
/// Whether the surface should be recreated at `now`: a recreate is pending and its try is due.
pub fn recreate_due(&self, now: web_time::Instant) -> bool {
self.recreate && self.is_due(now)
}
/// The surface was recreated: no recreate is pending. The streak and its deadline stay.
pub fn recreated(&mut self) {
self.recreate = false;
}
/// The device refused a configure at `now`: the streak grows and the next try waits.
pub fn refused(&mut self, now: web_time::Instant) -> RetryPlan {
self.failures = self.failures.saturating_add(1);
let doublings = self.failures.saturating_sub(1).min(6);
let delay = std::time::Duration::from_millis((16u64 << doublings).min(1000));
// A deadline past the clock's range can't happen in practice; it would make the try due.
self.due = now.checked_add(delay);
let recreate = self.failures % SURFACE_RECREATE_AFTER == 0;
self.recreate |= recreate;
RetryPlan {
failures: self.failures,
first: self.failures == 1,
delay,
recreate,
}
}
/// The device took a configure: the streak ends, and a pending recreate with it. Returns how
/// many refusals it had.
pub fn took(&mut self) -> u32 {
std::mem::take(self).failures
}
/// Runs `configure` at `now` unless a refused one's retry isn't due yet, and keeps the
/// streak. The surface's configures all go through here, so an early repaint (input, an
/// animation) can't bring a retry forward.
pub fn attempt<E>(
&mut self,
now: web_time::Instant,
configure: impl FnOnce() -> Result<(), E>,
) -> Attempt<E> {
if let Some(left) = self.wait(now) {
return Attempt::Waiting(left);
}
match configure() {
Ok(()) => Attempt::Took(self.took()),
Err(error) => Attempt::Refused(self.refused(now), error),
}
}
}
/// SolidCraft: what came of [`ConfigureRetry::attempt`].
#[derive(Debug)]
pub enum Attempt<E> {
/// Not tried: the retry after a refusal is due in this long.
Waiting(std::time::Duration),
/// The configure was taken, after this many refusals in a row (0 when none).
Took(u32),
/// The configure was refused with this error; the plan says what follows.
Refused(RetryPlan, E),
}
/// SolidCraft: the surface size for a window of `width` x `height` pixels on a device whose
/// textures are at most `max_side` on a side, and the scale it is drawn at. A window that fits is
/// unchanged (scale 1); a larger one shrinks uniformly, keeping its aspect ratio, so the image
+132 -14
View File
@@ -25,6 +25,9 @@ struct SurfaceState {
resizing: bool,
needs_reconfigure: bool,
needs_recreate: bool,
/// SolidCraft: configures the device refused in a row and when the next try is due (#1935),
/// kept across a recreate.
retry: crate::ConfigureRetry,
}
/// SolidCraft: whether a frame was presented yet (`crate::STEP_FIRST_PRESENT`).
@@ -102,11 +105,15 @@ impl Painter {
self.render_state.clone()
}
/// SolidCraft: a configuration the device refuses (D3D12: "Failed to wait for GPU to come
/// idle before reconfiguring the Surface", #1935) comes back as the error instead of reaching
/// the device's uncaptured-error handler, which panics. Called only through
/// [`Self::try_configure`], which says what follows.
fn configure_surface(
surface_state: &SurfaceState,
render_state: &RenderState,
config: &SurfaceConfig,
) {
) -> Result<(), wgpu::Error> {
profiling::function_scope!();
let SurfaceConfig {
@@ -132,7 +139,7 @@ impl Painter {
.get_default_config(&render_state.adapter, width, height)
else {
log::error!("The surface isn't supported by this adapter");
return;
return Ok(());
};
let mut surf_config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
@@ -147,9 +154,63 @@ impl Painter {
surf_config.desired_maximum_frame_latency = desired_maximum_frame_latency;
}
surface_state
.surface
.configure(&render_state.device, &surf_config);
let device = &render_state.device;
let ((), failed) = crate::capture_errors(device, || {
surface_state.surface.configure(device, &surf_config)
});
failed.map_or(Ok(()), Err)
}
/// SolidCraft: configures the surface at `now` unless a refused configure's retry isn't due
/// yet (#1935, [`crate::ConfigureRetry::attempt`]), and says whether the surface has its
/// configuration. A refusal is a warning once per streak (debug after that); it marks the
/// surface to be configured again (every few refusals in a row the retry state also asks for
/// a recreate first) and asks for a repaint when the retry is due. A try that isn't due
/// configures nothing and asks for that repaint again, since an earlier repaint may have used
/// up the one asked for before.
fn try_configure(
context: &Context,
viewport_id: ViewportId,
state: &mut SurfaceState,
render_state: &RenderState,
config: &SurfaceConfig,
now: web_time::Instant,
) -> bool {
// A copy, as the configure borrows the whole surface state.
let mut retry = state.retry;
let attempt = retry.attempt(now, || Self::configure_surface(state, render_state, config));
state.retry = retry;
match attempt {
crate::Attempt::Took(refusals) => {
if refusals > 0 {
log::info!("The surface took its configuration after {refusals} refusals");
}
state.needs_reconfigure = false;
true
}
crate::Attempt::Waiting(left) => {
state.needs_reconfigure = true;
context.request_repaint_after_for(left, viewport_id);
false
}
crate::Attempt::Refused(plan, error) => {
if plan.first {
log::warn!(
"The {}x{} surface could not be configured; trying again: {error}",
state.width,
state.height
);
} else {
log::debug!(
"The surface refused its configuration again ({} in a row): {error}",
plan.failures
);
}
state.needs_reconfigure = true;
context.request_repaint_after_for(plan.delay, viewport_id);
false
}
}
}
/// Drop the existing [`wgpu::Surface`] for `viewport_id` and create a fresh one for the
@@ -169,12 +230,17 @@ impl Painter {
};
let surface = self.instance.create_surface(Arc::clone(window))?;
// SolidCraft: the refusal streak and its deadline go on with the new surface (#1935); a
// recreate the streak asked for is done by this one.
let mut retry = old_state.retry;
retry.recreated();
self.install_surface(
surface,
viewport_id,
old_state.requested.0,
old_state.requested.1,
old_state.resizing,
retry,
);
Ok(())
}
@@ -265,7 +331,14 @@ impl Painter {
self.render_state = Some(render_state);
}
crate::startup_step(crate::STEP_SURFACE_CONFIGURE, ""); // SolidCraft
self.install_surface(surface, viewport_id, size.width, size.height, false);
self.install_surface(
surface,
viewport_id,
size.width,
size.height,
false,
crate::ConfigureRetry::default(),
);
Ok(())
}
@@ -280,6 +353,7 @@ impl Painter {
width: u32,
height: u32,
resizing: bool,
retry: crate::ConfigureRetry,
) {
let alpha_mode = {
// Panic: We use the same failure mode as `resize_and_generate_depth_texture_view_and_msaa_view`
@@ -318,6 +392,7 @@ impl Painter {
resizing,
needs_reconfigure: false,
needs_recreate: false,
retry,
},
);
let Some(width) = NonZeroU32::new(width) else {
@@ -377,7 +452,17 @@ impl Painter {
surface_state.requested = requested;
surface_state.scale = scale;
Self::configure_surface(surface_state, render_state, &self.config.surface);
// SolidCraft: while a refused configure waits for its retry (#1935), a resize doesn't
// try early, since the device refuses, not the size: the new size is kept above and the
// retry configures it.
Self::try_configure(
&self.context,
viewport_id,
surface_state,
render_state,
&self.config.surface,
web_time::Instant::now(),
);
if let Some(depth_format) = self.options.depth_stencil_format {
self.depth_texture_view.insert(
@@ -477,7 +562,15 @@ impl Painter {
.lock()
.setPresentsWithTransaction(resizing);
Self::configure_surface(state, render_state, &self.config.surface);
// SolidCraft: not before a refused configure's retry is due (#1935).
Self::try_configure(
&self.context,
viewport_id,
state,
render_state,
&self.config.surface,
web_time::Instant::now(),
);
}
}
}
@@ -547,14 +640,19 @@ impl Painter {
let capture = !capture_data.is_empty();
let mut vsync_sec = 0.0;
// SolidCraft: one clock reading for this frame's surface retries (#1935).
let now = web_time::Instant::now();
// If the previous frame produced `CurrentSurfaceTexture::Lost`, the action match
// below set `needs_recreate`. Recreate the surface now, before re-borrowing
// `self.render_state` / `self.surfaces` for the rest of the paint.
// SolidCraft: refused configures also ask for a recreate every few in a row (#1935),
// done only once their retry is due, whatever repaints before; until then the check
// below skips the frame. A recreate for `Lost` goes ahead as before.
if self
.surfaces
.get(&viewport_id)
.is_some_and(|s| s.needs_recreate)
.is_some_and(|s| s.needs_recreate || s.retry.recreate_due(now))
&& let Err(err) = self.recreate_surface(viewport_id, window)
{
log::error!("Failed to recreate surface for {viewport_id:?}: {err}");
@@ -588,9 +686,20 @@ impl Painter {
return vsync_sec;
};
if surface_state.needs_reconfigure {
Self::configure_surface(surface_state, render_state, &self.config.surface);
surface_state.needs_reconfigure = false;
// SolidCraft: a surface still refusing its configuration, or waiting for the retry of a
// refused one (to be configured or recreated), skips this frame rather than acquire a
// texture from it; the retry is scheduled (#1935).
if (surface_state.needs_reconfigure || surface_state.retry.recreate_pending())
&& !Self::try_configure(
&self.context,
viewport_id,
surface_state,
render_state,
&self.config.surface,
now,
)
{
return vsync_sec;
}
let output_frame = {
@@ -615,8 +724,17 @@ impl Painter {
other => {
match (*self.config.on_surface_status)(&other) {
SurfaceErrorAction::Reconfigure => {
Self::configure_surface(surface_state, render_state, &self.config.surface);
self.context.request_repaint_of(viewport_id);
// SolidCraft: not before a refused configure's retry is due (#1935).
if Self::try_configure(
&self.context,
viewport_id,
surface_state,
render_state,
&self.config.surface,
now,
) {
self.context.request_repaint_of(viewport_id);
}
}
SurfaceErrorAction::RecreateSurface => {
// Because of ownership, I could not find an easy way to do a full recovery here,