Merge #139 from dexterlabs1: contain GPU initialization errors and retire failed compositor work

This commit is contained in:
bflatastic
2026-10-07 07:52:46 +07:00
17 changed files with 1776 additions and 316 deletions
+65 -8
View File
@@ -24,6 +24,7 @@
//! them (Info panel, eyedroppers, histograms).
use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use effectcraft_engine::project::{Comp, ItemId, ItemKind, LayerSource, Node, Project, PropGroup};
@@ -365,6 +366,7 @@ pub struct Frames {
/// Render time of the last viewer (urgent) frame in ms, for the Info panel / perf readout.
pub last_ms: Arc<Mutex<f64>>,
content_keys: ContentKeys,
gpu_retired: Arc<AtomicBool>,
/// [`comp_content`] identities by (revision, comp), with the project that keeps an identity
/// found by [`Frames::identity`] in another project.
identities: Mutex<HashMap<(u64, u64), Identity>>,
@@ -398,6 +400,7 @@ impl Default for Frames {
ctx: None,
last_ms: Arc::new(Mutex::new(0.0)),
content_keys: Arc::default(),
gpu_retired: Arc::default(),
identities: Mutex::default(),
bases: Mutex::default(),
keepers: Mutex::default(),
@@ -423,6 +426,24 @@ pub fn to_color_image(img: &effectcraft_engine::render::Image) -> egui::ColorIma
}
impl Frames {
/// Retire only GPU preview state; documents, CPU frames and running job leases survive.
/// Publication checks the same latch while holding the cache lock, so a late GPU frame
/// cannot restore an invalid texture after this removal.
pub fn retire_gpu(&self) {
self.gpu_retired.store(true, Ordering::Release);
if let Ok(mut cache) = self.cache.lock() {
let keys: Vec<_> = cache.map.iter().filter_map(|(key, image)| image.is_gpu().then_some(*key)).collect();
for key in keys {
cache.remove(&key);
}
let Cache { map, order, .. } = &mut *cache;
order.retain(|key| map.contains_key(key));
}
if let Some(ctx) = &self.ctx {
ctx.request_repaint();
}
}
/// Actual native frame-worker capacity, including the OS fallback pool.
#[cfg(not(target_arch = "wasm32"))]
pub fn parallelism(&self) -> usize {
@@ -649,6 +670,7 @@ impl Frames {
ctx: self.ctx.clone(),
last: self.last_ms.clone(),
content_keys: self.content_keys.clone(),
gpu_retired: self.gpu_retired.clone(),
}
}
@@ -777,6 +799,7 @@ struct Worker {
ctx: Option<egui::Context>,
last: Arc<Mutex<f64>>,
content_keys: ContentKeys,
gpu_retired: Arc<AtomicBool>,
}
impl Worker {
@@ -830,7 +853,9 @@ impl Worker {
if urgent && let Ok(mut l) = self.last.lock() {
*l = t0.elapsed().as_secs_f64() * 1000.0;
}
if let Ok(mut c) = self.cache.lock() {
if let Ok(mut c) = self.cache.lock()
&& (!img.is_gpu() || !self.gpu_retired.load(Ordering::Acquire))
{
c.insert(key, img);
}
self.release(key, urgent);
@@ -862,8 +887,13 @@ impl Worker {
})
}
/// The GPU ran out of video memory rendering a frame (#106): fewer GPU frames are kept.
fn out_of_memory(&self, e: &str) {
/// A failed scoped attempt retries on CPU. Retired contexts cannot recover by reducing
/// their budget; only a healthy device's allocation failure uses the upstream backoff.
fn gpu_attempt_failed(&self, gpu: &Gpu, e: &str) {
if gpu.context().check_health().is_err() {
log::warn!("the GPU context is retired ({e}); the frame renders on the CPU");
return;
}
log::warn!("the GPU ran out of memory ({e}); the frame renders on the CPU and fewer GPU frames are kept");
if let Ok(mut c) = self.cache.lock() {
c.gpu_out_of_memory();
@@ -872,6 +902,9 @@ impl Worker {
/// The frame on the GPU, kept there for the viewer, if the compositor can do it alone.
fn render_gpu(&self, job: &Job) -> Option<FrameImage> {
if self.gpu_retired.load(Ordering::Acquire) {
return None;
}
let g = job.src.gpu.as_ref()?;
let mut r = Renderer::new(&job.src.project, job.src.footage.as_ref(), job.opts);
r.expr = job.src.expr.as_deref();
@@ -881,7 +914,7 @@ impl Worker {
match g.within_memory(|| g.render_display(&r, job.comp, job.t)) {
Ok(f) => f.map(|f| FrameImage::Gpu(Arc::new(f))),
Err(e) => {
self.out_of_memory(&e);
self.gpu_attempt_failed(g, &e);
None
}
}
@@ -891,8 +924,11 @@ impl Worker {
fn render_job(&self, job: &Job, gpu: bool) -> FrameImage {
let mut r = Renderer::new(&job.src.project, job.src.footage.as_ref(), job.opts);
r.expr = job.src.expr.as_deref();
r.cache = Some(&job.src.layer_cache);
let gpu = job.src.gpu.as_ref().filter(|_| gpu);
let gpu_allowed = gpu && !self.gpu_retired.load(Ordering::Acquire);
// A failed GPU attempt may have populated intermediate entries before its scope
// reported failure. The CPU retry must compute its own pixels from the snapshot.
r.cache = gpu_allowed.then_some(job.src.layer_cache.as_ref());
let gpu = job.src.gpu.as_ref().filter(|_| gpu_allowed);
r.accel = gpu.map(|g| g as &dyn effectcraft_engine::render::Accelerator);
// The GPU leaves the frame in a texture for the viewer; otherwise (Software Only, no
// adapter, or a frame the GPU cannot finish here) the CPU renders it.
@@ -911,6 +947,9 @@ impl Worker {
if let Some((p, key)) = auto {
// Time the GPU's work, not just its recording.
g.wait();
if g.context().check_health().is_err() {
return self.render_job(job, false);
}
p.record(key, true, t0.elapsed().as_secs_f64() * 1000.0);
}
return FrameImage::Gpu(Arc::new(f));
@@ -921,7 +960,7 @@ impl Worker {
}
}
Err(e) => {
self.out_of_memory(&e);
self.gpu_attempt_failed(g, &e);
return self.render_job(job, false);
}
}
@@ -938,7 +977,7 @@ impl Worker {
return match g.within_memory(|| r.comp_frame(job.comp, job.t)) {
Ok(img) => FrameImage::Cpu(Arc::new(to_color_image(&img))),
Err(e) => {
self.out_of_memory(&e);
self.gpu_attempt_failed(g, &e);
self.render_job(job, false)
}
};
@@ -976,6 +1015,24 @@ impl Queue {
mod tests {
use super::*;
#[test]
fn retirement_reaches_existing_workers_and_keeps_cpu_frames_and_completion_live() {
let frames = Frames::default();
let worker = frames.worker();
let first = key(1, 0, 0);
insert(&frames, first);
frames.retire_gpu();
assert!(worker.gpu_retired.load(Ordering::Acquire), "already queued workers share retirement");
assert!(frames.is_cached(&first), "healthy materialized CPU frames survive");
let next = key(1, 1, 0);
frames.inflight.lock().unwrap().insert(next);
frames.queue.lock().unwrap().running.insert(next);
worker.finish_key(next, false, img(), web_time::Instant::now());
assert!(frames.is_cached(&next), "CPU retry can still publish");
assert_eq!(frames.inflight(), 0);
assert!(frames.queue.lock().unwrap().running.is_empty());
}
fn key(content: u64, frame: i64, opts: u64) -> FrameKey {
FrameKey { revision: content, content, comp: 1, frame, scale: 1000, view: 0, opts }
}
+158
View File
@@ -0,0 +1,158 @@
//! Host-owned shared-device failure forwarding. Device handlers belong to the executable or
//! embedding host, never to a library borrowing its device. This bridge does no device work,
//! document mutation, file I/O or renderer locking inside a notification.
use std::sync::{Arc, Mutex};
type Notifier = Arc<dyn Fn(String) + Send + Sync>;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GpuFailure {
pub reason: String,
/// Device loss requires restarting/recreating the presentation backend too. CPU
/// compositing alone cannot make a lost eframe presentation device usable again.
pub presentation_lost: bool,
}
#[derive(Default)]
struct State {
failure: Option<GpuFailure>,
notifier: Option<Notifier>,
}
/// One bridge per host device. Failure is latched; duplicate reports cannot grow a queue.
#[derive(Clone)]
pub struct GpuFailureBridge {
state: Arc<Mutex<State>>,
ctx: egui::Context,
}
impl GpuFailureBridge {
pub fn new(ctx: &egui::Context) -> Self {
Self { state: Arc::default(), ctx: ctx.clone() }
}
pub fn failure(&self) -> Option<GpuFailure> {
self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner).failure.clone()
}
/// Forward to a compositor's weak notifier once construction succeeds. A fault that
/// preceded registration is replayed; the compositor must not then be attached to the UI.
pub fn forward_to(&self, notifier: impl Fn(String) + Send + Sync + 'static) {
let notifier: Notifier = Arc::new(notifier);
let failure = {
let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
state.notifier = Some(notifier.clone());
state.failure.clone()
};
if let Some(failure) = failure {
notify(&notifier, failure.reason);
}
}
/// Called by the device owner for an uncaptured error or device loss. A later device-loss
/// notification escalates the recovery message without completing pending work twice.
pub fn report(&self, reason: &str, presentation_lost: bool) -> bool {
let (notification, changed) = {
let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(failure) = &mut state.failure {
let changed = presentation_lost && !failure.presentation_lost;
failure.presentation_lost |= presentation_lost;
(None, changed)
} else {
let reason: String = reason.chars().take(2048).collect();
state.failure = Some(GpuFailure { reason: reason.clone(), presentation_lost });
(state.notifier.clone().map(|notifier| (notifier, reason)), true)
}
};
if let Some((notifier, reason)) = notification {
notify(&notifier, reason);
}
if changed {
self.ctx.request_repaint();
}
changed
}
}
fn notify(notifier: &Notifier, reason: String) {
// A host callback must never propagate a consumer panic into wgpu's error handling.
#[cfg(not(target_arch = "wasm32"))]
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| notifier(reason))).is_err() {
log::error!("GPU failure consumer panicked");
}
#[cfg(target_arch = "wasm32")]
notifier(reason);
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
#[test]
fn a_construction_failure_is_replayed_after_notifier_registration() {
let bridge = GpuFailureBridge::new(&egui::Context::default());
bridge.report("pipeline allocation failed", false);
let observed = Arc::new(Mutex::new(Vec::new()));
let copy = observed.clone();
let probe = Arc::downgrade(&bridge.state);
bridge.forward_to(move |reason| {
assert!(probe.upgrade().unwrap().try_lock().is_ok(), "consumer runs outside bridge lock");
copy.lock().unwrap().push(reason);
});
assert_eq!(*observed.lock().unwrap(), ["pipeline allocation failed"]);
bridge.report("duplicate", false);
assert_eq!(observed.lock().unwrap().len(), 1);
}
#[test]
fn a_late_failure_notifies_once_and_later_device_loss_escalates() {
let bridge = GpuFailureBridge::new(&egui::Context::default());
let calls = Arc::new(AtomicUsize::new(0));
let copy = calls.clone();
bridge.forward_to(move |_| {
copy.fetch_add(1, Ordering::SeqCst);
});
assert!(bridge.failure().is_none());
bridge.report("uncaptured allocation failure", false);
bridge.report("device lost", true);
bridge.report("another error", false);
assert_eq!(calls.load(Ordering::SeqCst), 1);
let failure = bridge.failure().unwrap();
assert!(failure.presentation_lost);
assert_eq!(failure.reason, "uncaptured allocation failure");
}
#[test]
fn diagnostics_are_bounded_and_native_consumer_panics_are_isolated() {
let bridge = GpuFailureBridge::new(&egui::Context::default());
#[cfg(not(target_arch = "wasm32"))]
bridge.forward_to(|_| panic!("synthetic consumer failure"));
bridge.report(&"é".repeat(3000), false);
assert_eq!(bridge.failure().unwrap().reason.chars().count(), 2048);
bridge.report("device lost after consumer failure", true);
assert!(bridge.failure().unwrap().presentation_lost);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn concurrent_registration_and_failure_deliver_exactly_once() {
let bridge = GpuFailureBridge::new(&egui::Context::default());
let barrier = Arc::new(std::sync::Barrier::new(2));
let calls = Arc::new(AtomicUsize::new(0));
let reporter = bridge.clone();
let ready = barrier.clone();
let thread = std::thread::spawn(move || {
ready.wait();
reporter.report("device failed during subscription", false);
});
let count = calls.clone();
barrier.wait();
bridge.forward_to(move |_| {
count.fetch_add(1, Ordering::SeqCst);
});
thread.join().unwrap();
assert_eq!(calls.load(Ordering::SeqCst), 1);
}
}
+109
View File
@@ -14,6 +14,7 @@ pub mod control;
pub mod dock;
pub mod dock_ui;
pub mod frames;
pub mod gpu_failure;
pub mod header;
pub mod i18n;
pub mod icons;
@@ -215,6 +216,8 @@ pub struct EffectcraftApp {
/// The GPU compositor on that device (None: no usable adapter → CPU only).
pub(crate) gpu: Option<effectcraft_gpu::Gpu>,
gpu_checked: bool,
gpu_failures: Option<gpu_failure::GpuFailureBridge>,
gpu_failure_applied: Option<bool>,
/// Commands from the native menu bar.
pub command_inbox: Option<Receiver<String>>,
/// Pointer position in comp pixels (Info panel).
@@ -286,6 +289,8 @@ impl EffectcraftApp {
wgpu: None,
gpu: None,
gpu_checked: false,
gpu_failures: None,
gpu_failure_applied: None,
command_inbox: None,
pointer_comp: None,
dialog_state: Default::default(),
@@ -455,6 +460,60 @@ impl EffectcraftApp {
&& self.ui.viewer.extended.is_none()
}
/// Provide the executable/embedding host's device notifications. The host installs the
/// handlers once; this frontend never replaces handlers on a borrowed device.
pub fn set_gpu_failure_bridge(&mut self, bridge: gpu_failure::GpuFailureBridge) {
if let Some(gpu) = &self.gpu {
bridge.forward_to(gpu.context().device_failure_notifier());
}
self.gpu_failures = Some(bridge);
}
fn apply_gpu_failure(&mut self, ctx: &egui::Context) {
let Some(bridge) = &self.gpu_failures else { return };
// Readback deadlines can retire the compositor without a host device notification.
if let Some(gpu) = &self.gpu
&& let Err(reason) = gpu.context().check_health()
{
bridge.report(&reason, false);
}
let Some(failure) = bridge.failure() else { return };
if self.gpu_failure_applied == Some(failure.presentation_lost) {
return;
}
self.gpu_failure_applied = Some(failure.presentation_lost);
self.gpu_checked = true;
self.frames.retire_gpu();
self.session.accel = None;
self.session.layer_cache.clear();
self.gpu = None;
if let Some(rs) = &self.wgpu {
let mut renderer = rs.renderer.write();
if let Some((id, _, _)) = &self.viewer_native {
renderer.free_texture(id);
}
for (_, texture) in self.passive_tex.values() {
if let panels::viewers::PassiveTexture::Gpu(id, _) = texture {
renderer.free_texture(id);
}
}
}
self.viewer_native = None;
self.passive_tex.retain(|_, (_, texture)| matches!(texture, panels::viewers::PassiveTexture::Cpu(_)));
self.viewer_shown = self.viewer_tex.as_ref().map(|(texture, key)| (texture.id(), *key));
self.viewer_image = None;
// Old completion closures retain only their detached slot, not the replacement.
self.viewer_readback = Default::default();
self.wgpu = None;
self.ui.status = if failure.presentation_lost {
"Graphics device lost. The project is still open; presentation requires restarting the application.".into()
} else {
"Shared GPU preview disabled; CPU compositing remains available.".into()
};
log::warn!("GPU preview retired: {}", failure.reason);
ctx.request_repaint();
}
/// Set up the GPU compositor on egui-wgpu's device (once). Without an adapter that runs
/// compute shaders (WebGL2, software GL) everything stays on the CPU.
pub(crate) fn init_gpu(&mut self, frame: &eframe::Frame) {
@@ -462,12 +521,21 @@ impl EffectcraftApp {
return;
}
self.gpu_checked = true;
if self.gpu_failures.as_ref().is_some_and(|bridge| bridge.failure().is_some()) {
return;
}
let Some(rs) = frame.wgpu_render_state() else { return };
// Backend validation can panic on shader compilation even when device creation
// succeeded. Keep the document and the egui renderer, and use CPU compositing.
let gpu = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| effectcraft_gpu::Gpu::new(&rs.adapter, rs.device.clone(), rs.queue.clone())));
match gpu {
Ok(Ok(g)) => {
if let Some(bridge) = &self.gpu_failures {
bridge.forward_to(g.context().device_failure_notifier());
if bridge.failure().is_some() {
return;
}
}
log::info!("GPU compositor: {}", effectcraft_engine::render::Accelerator::name(&g));
self.session.accel = Some(Arc::new(g.clone()));
self.gpu = Some(g);
@@ -1263,6 +1331,7 @@ impl EffectcraftApp {
fn frame(&mut self, ui: &mut egui::Ui) {
let ctx = ui.ctx().clone();
self.apply_gpu_failure(&ctx);
self.auto.begin_frame();
self.frames.set_context(&ctx);
if self.session.render_job.is_some() {
@@ -1439,6 +1508,7 @@ impl eframe::App for EffectcraftApp {
}
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
self.apply_gpu_failure(ctx);
if !self.styled {
theme::install(ctx, &self.tokens);
self.styled = true;
@@ -1495,3 +1565,42 @@ impl eframe::App for EffectcraftApp {
pub(crate) fn tick_playback(app: &mut EffectcraftApp, ctx: &egui::Context, scale: f64) {
app.advance_playback(ctx, scale);
}
#[cfg(test)]
mod gpu_failure_tests {
use super::*;
#[test]
fn host_failure_preserves_document_undo_and_cpu_pixels_and_detaches_late_readbacks() {
let mut session = Session::default();
let comp = ItemId(session.execute("comp.new", json!({"name": "Recovery", "width": 4, "height": 4, "duration": 1})).unwrap()["comp"].as_u64().unwrap());
session.execute("layer.newSolid", json!({"comp": comp.0, "color": "#ff0000"})).unwrap();
let before = session.render(comp, Tick::ZERO, RenderOpts::default());
let project = session.project.clone();
let revision = session.revision;
let prefs = serde_json::to_value(&session.prefs).unwrap();
let mut app = EffectcraftApp::new(session);
let ctx = egui::Context::default();
let bridge = gpu_failure::GpuFailureBridge::new(&ctx);
app.set_gpu_failure_bridge(bridge.clone());
let late_slot = app.viewer_readback.1.clone();
let key = FrameKey { revision, content: 1, comp: comp.0, frame: 0, scale: 1000, view: 0, opts: 0 };
app.viewer_readback.0 = Some(key);
bridge.report("synthetic host device failure", true);
app.apply_gpu_failure(&ctx);
assert!(Arc::ptr_eq(&project, &app.session.project));
assert_eq!(app.session.revision, revision);
assert_eq!(serde_json::to_value(&app.session.prefs).unwrap(), prefs);
assert!(app.gpu_checked, "failed device cannot be initialized again next frame");
assert!(app.session.accel.is_none());
assert!(app.ui.status.contains("presentation requires restarting"));
assert_eq!(app.session.render(comp, Tick::ZERO, RenderOpts::default()).data, before.data);
*late_slot.lock().unwrap() = Some((key, Arc::new(egui::ColorImage::new([1, 1], vec![egui::Color32::RED]))));
assert!(app.viewer_readback.0.is_none());
assert!(app.viewer_readback.1.lock().unwrap().is_none(), "a late completion cannot refill the replacement slot");
app.session.execute("edit.undo", json!({})).unwrap();
assert!(app.session.project.comp(comp).unwrap().layers.is_empty());
app.session.execute("edit.redo", json!({})).unwrap();
assert_eq!(app.session.render(comp, Tick::ZERO, RenderOpts::default()).data, before.data);
}
}