Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

fix(gpu): rebuild the GPU canvas after an out-of-memory error (#8774)

FinnNkc06dd9c27c4c
diff --git a/crates/gpu/src/health.rs b/crates/gpu/src/health.rs
index 61aacf8b5..948ef2804 100644
--- a/crates/gpu/src/health.rs
+++ b/crates/gpu/src/health.rs
@@ -30,6 +30,14 @@ impl Fault {
matches!(self, Fault::Lost(_))
}
+ /// An out-of-memory error on a device that still works: freeing memory and trying again can
+ /// succeed, unlike after a loss or a validation error (#6564). Only wgpu's own out-of-memory
+ /// error is recorded with exactly [`OUT_OF_MEMORY`]; a validation error that merely mentions
+ /// memory is not one.
+ pub fn is_out_of_memory(&self) -> bool {
+ matches!(self, Fault::Error(s) if s == OUT_OF_MEMORY)
+ }
+
/// The driver's or wgpu's message.
pub fn detail(&self) -> &str {
match self {
@@ -48,6 +56,9 @@ impl fmt::Display for Fault {
}
}
+/// The message an out-of-memory [`Fault::Error`] carries (wgpu's `Error::OutOfMemory`).
+pub const OUT_OF_MEMORY: &str = "Out of Memory";
+
#[derive(Default)]
struct Inner {
faulted: AtomicBool,
@@ -102,16 +113,24 @@ impl DeviceHealth {
// Errors about invalid or lost objects follow a device loss whose callback may not have
// run yet (it fires on the next poll).
let lower = text.to_ascii_lowercase();
- let fault = if lower.contains("lost") || lower.contains("destroyed") { Fault::Lost(first_line(&text)) } else { Fault::Error(first_line(&text)) };
+ let fault = if matches!(e, wgpu::Error::OutOfMemory { .. }) {
+ Fault::Error(OUT_OF_MEMORY.into())
+ } else if lower.contains("lost") || lower.contains("destroyed") {
+ Fault::Lost(first_line(&text))
+ } else {
+ Fault::Error(first_line(&text))
+ };
self.mark(fault);
}
- /// Mark the device unusable. The first fault is kept; a later device loss upgrades an error.
+ /// Mark the device unusable. The first fault is kept; a later device loss upgrades an error,
+ /// and a later out-of-memory error upgrades another one, so the canvas can still recover by
+ /// itself when memory ran out after a validation error in the same frame (#6564).
pub fn mark(&self, fault: Fault) {
let mut slot = self.0.fault.lock().unwrap_or_else(PoisonError::into_inner);
let replace = match slot.as_ref() {
None => true,
- Some(old) => !old.is_lost() && fault.is_lost(),
+ Some(old) => !old.is_lost() && (fault.is_lost() || (fault.is_out_of_memory() && !old.is_out_of_memory())),
};
if replace {
*slot = Some(fault);
@@ -229,5 +248,17 @@ mod tests {
assert_eq!(Fault::Error("x".into()).to_string(), "GPU error: x");
assert_eq!(first_line("\n Buffer 'pc' is invalid\nmore"), "Buffer 'pc' is invalid");
assert_eq!(first_line(&"a".repeat(300)).chars().count(), 201);
+ assert!(Fault::Error("Out of Memory".into()).is_out_of_memory());
+ assert!(!Fault::Error("Validation Error".into()).is_out_of_memory());
+ assert!(!Fault::Error("Validation Error: buffer allocation would run out of memory".into()).is_out_of_memory());
+ // A later out-of-memory error replaces another error, but never a loss.
+ let h = DeviceHealth::new();
+ h.mark(Fault::Error("Validation Error".into()));
+ h.mark(Fault::Error(OUT_OF_MEMORY.into()));
+ assert!(h.fault().is_some_and(|f| f.is_out_of_memory()));
+ h.mark(Fault::Lost("reset".into()));
+ h.mark(Fault::Error(OUT_OF_MEMORY.into()));
+ assert!(h.fault().is_some_and(|f| f.is_lost()));
+ assert!(!Fault::Lost("out of memory".into()).is_out_of_memory());
}
}
diff --git a/crates/ui-egui/src/gpu_status.rs b/crates/ui-egui/src/gpu_status.rs
index cd2bb7bc4..e00c38479 100644
--- a/crates/ui-egui/src/gpu_status.rs
+++ b/crates/ui-egui/src/gpu_status.rs
@@ -19,10 +19,25 @@ const STARTED_MAX_FRAMES: u64 = 120;
/// Hook run once the app has rendered its first frames (see [`PhotocraftApp::on_started`]).
pub type StartedHook = Box<dyn FnOnce(&mut PhotocraftApp)>;
-/// Per-frame check: switch to the CPU canvas when the GPU faulted, and run the started hook.
+/// Out-of-memory errors after which the GPU canvas is rebuilt by itself; past them the CPU
+/// renderer stays until the user chooses Retry GPU, so a document that never fits doesn't rebuild
+/// the canvas on every frame.
+pub const OOM_AUTO_RETRIES: u32 = 3;
+
+/// Per-frame check: switch to the CPU canvas when the GPU faulted, and run the started hook. An
+/// out-of-memory error on a device that still works is not the end of the GPU for the session
+/// (#6564): the dropped canvas freed its memory, so a new one is built at once and the views
+/// redraw through it, up to [`OOM_AUTO_RETRIES`] times.
pub fn check(app: &mut PhotocraftApp, ctx: &egui::Context) {
if let Some(fault) = app.gpu.as_ref().and_then(|g| g.fault()) {
fall_back(app, &fault);
+ if fault.is_out_of_memory() && app.gpu_oom_retries < OOM_AUTO_RETRIES && can_retry_now(app) {
+ app.gpu_oom_retries += 1;
+ if retry_now(app) {
+ log::warn!("{fault}; rebuilt the GPU canvas (automatic retry {} of {OOM_AUTO_RETRIES})", app.gpu_oom_retries);
+ app.ui.gpu_fallback_notice = None;
+ }
+ }
ctx.request_repaint();
}
if app.started.is_some() {
@@ -372,6 +387,47 @@ mod tests {
assert_eq!(saves.get(), 2, "retry choice writes once");
}
+ /// #6564: an out-of-memory error on a device that still works rebuilds the GPU canvas by itself,
+ /// with no notice and the documents untouched, a few times a session; then the CPU renderer
+ /// stays until Retry GPU. Other errors and a loss still fall back at once.
+ #[test]
+ fn out_of_memory_rebuilds_the_gpu_canvas_by_itself() {
+ let _gpu = photocraft_testkit::gpu_lock();
+ let rs = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default()));
+ let Ok(rs) = rs else {
+ eprintln!("skipping: no GPU adapter");
+ return;
+ };
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ app.set_wgpu(rs);
+ app.run("file.new", json!({"width": 64, "height": 48})).unwrap();
+ let ctx = egui::Context::default();
+ let oom = || photocraft_gpu::Fault::Error("Out of Memory".into());
+ for n in 1..=OOM_AUTO_RETRIES {
+ app.gpu_health().unwrap().mark(oom());
+ check(&mut app, &ctx);
+ assert!(app.gpu_active(), "retry {n}: the GPU canvas is back");
+ assert!(app.gpu_health().unwrap().is_ok(), "retry {n}: with a fresh health flag");
+ assert_eq!(app.perf.gpu_info.canvas, "gpu");
+ assert!(app.ui.gpu_fallback_notice.is_none(), "retry {n}: no recovery dialog");
+ assert_eq!(app.session.documents().len(), 1);
+ }
+ // Past the limit the CPU renderer stays and the dialog offers Retry GPU.
+ app.gpu_health().unwrap().mark(oom());
+ check(&mut app, &ctx);
+ assert!(!app.gpu_active() && app.ui.gpu_fallback_notice.is_some());
+ assert_eq!(app.perf.gpu_info.canvas, "cpu");
+
+ // A validation error is not retried by itself.
+ let rs = egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default());
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ app.set_wgpu(rs);
+ app.run("file.new", json!({"width": 64, "height": 48})).unwrap();
+ app.gpu_health().unwrap().mark(photocraft_gpu::Fault::Error("Validation Error".into()));
+ check(&mut app, &ctx);
+ assert!(!app.gpu_active() && app.ui.gpu_fallback_notice.is_some());
+ }
+
/// #6577: after a GPU error on a device that still works (out of memory, validation), Retry
/// GPU builds a new GPU canvas at once, without a restart or closing documents. After a loss
/// the device can't be used again, so the retry still waits for the next launch.
@@ -388,8 +444,9 @@ mod tests {
app.set_wgpu(rs);
app.run("file.new", json!({"width": 64, "height": 48})).unwrap();
let ctx = egui::Context::default();
- // An error on a live device: Retry GPU rebuilds the canvas now.
- app.gpu_health().unwrap().mark(photocraft_gpu::Fault::Error("Out of Memory".into()));
+ // An error on a live device (one not retried by itself, see #6564): Retry GPU rebuilds
+ // the canvas now.
+ app.gpu_health().unwrap().mark(photocraft_gpu::Fault::Error("Validation Error".into()));
check(&mut app, &ctx);
assert!(!app.gpu_active() && app.ui.gpu_fallback_notice.is_some());
assert!(can_retry_now(&app));
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 6ea5992d4..e37aaf6ef 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -955,6 +955,8 @@ pub struct PhotocraftApp {
gpu_render_state: Option<eframe::egui_wgpu::RenderState>,
/// Why the GPU canvas was dropped (see `gpu_status::fall_back`).
gpu_fault: Option<photocraft_gpu::Fault>,
+ /// Out-of-memory errors this session after which the GPU canvas was rebuilt by itself (#6564).
+ gpu_oom_retries: u32,
/// Run once the first frames have rendered (see [`Self::on_started`]).
started: Option<gpu_status::StartedHook>,
/// Frame and canvas-upload timings (exposed via `ui.inspect`).
@@ -1135,6 +1137,7 @@ impl PhotocraftApp {
window_recovery_retry: None,
gpu_render_state: None,
gpu_fault: None,
+ gpu_oom_retries: 0,
started: None,
perf: Default::default(),
stroke_trace: stroke_trace::StrokeTrace::from_env(),