From 7b4124b6c07b841023627a7f6eb5329cd71bd95e Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Thu, 5 Nov 2026 07:00:31 -0500 Subject: [PATCH] fix(cook): catch panics in the cook worker and in app and control commands A panic in the background cook left stale previews with no error, and a dead worker (Disconnected) was cleared silently. The worker now runs under catch_unwind and reports failure; the failure and a vanished worker mark every node with the error and raise a toast. App::run and the control channel's command.run also run commands under catch_unwind and reply with an error instead of crashing. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/control.rs | 2 +- crates/ui-egui/src/cook.rs | 48 +++++++++++++++++++++++++----- crates/ui-egui/src/cook.test.rs | 52 +++++++++++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 7 +++-- crates/ui-egui/src/lib.test.rs | 24 +++++++++++++++ 5 files changed, 123 insertions(+), 10 deletions(-) create mode 100644 crates/ui-egui/src/cook.test.rs create mode 100644 crates/ui-egui/src/lib.test.rs diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 39708774..43e1a451 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -225,7 +225,7 @@ pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p: "command.run" => { let Some(id) = p.get("id").and_then(Value::as_str) else { return err("`id` is required") }; let params = p.get("params").cloned().unwrap_or(Value::Null); - match materialcraft_engine::execute(&mut app.session, id, ¶ms) { + match crate::cook::execute_guarded(&mut app.session, id, ¶ms) { Ok(v) => ok(v), Err(e) => err(e), } diff --git a/crates/ui-egui/src/cook.rs b/crates/ui-egui/src/cook.rs index 9b6e4100..81b0b136 100644 --- a/crates/ui-egui/src/cook.rs +++ b/crates/ui-egui/src/cook.rs @@ -1,15 +1,41 @@ //! Background cooking: when the open graph changes, a worker thread cooks a snapshot of the //! package through the shared cache while the UI keeps drawing the previous results. +use std::panic::{AssertUnwindSafe, catch_unwind}; use std::sync::mpsc::{Receiver, TryRecvError}; -use materialcraft_engine::eval::Cooked; +use materialcraft_engine::eval::{Cooked, NodeResult}; use crate::MaterialCraftApp; +/// Run `f`, turning a panic into an error naming `what`, so one bad node or command can't take +/// the app (and unsaved work) down. +pub fn guard(what: &str, f: impl FnOnce() -> Result) -> Result { + catch_unwind(AssertUnwindSafe(f)).unwrap_or_else(|p| { + let msg = p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::().cloned()).unwrap_or_default(); + Err(format!("internal error in {what}: {msg}")) + }) +} + +/// Run an engine command; a panic inside it becomes an error reply (the session is kept). +pub fn execute_guarded(session: &mut materialcraft_engine::Session, id: &str, params: &serde_json::Value) -> Result { + guard(&format!("command `{id}`"), || materialcraft_engine::execute(session, id, params).map_err(|e| e.to_string())) +} + +/// A cook that crashed or died: every node of the open graph shows the error instead of stale +/// previews, and the user sees a toast. +fn report_failure(app: &mut MaterialCraftApp, msg: String) { + let ids: Vec<_> = app.session.graph().map(|g| g.nodes.iter().map(|n| n.id).collect()).unwrap_or_default(); + app.session.cooked = Cooked::default(); + for id in ids { + app.session.cooked.nodes.insert(id, NodeResult { outputs: Default::default(), error: Some(msg.clone()), ms: 0.0, key: 0, cached: false }); + } + app.toast(msg, true); +} + #[derive(Default)] pub struct Cooker { - rx: Option>, + rx: Option>>, /// When the running cook started (app seconds). pub started: Option, } @@ -24,10 +50,13 @@ impl Cooker { pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) { if let Some(rx) = &app.cooker.rx { match rx.try_recv() { - Ok(c) => { - app.session.cooked = c; + Ok(result) => { app.cooker.rx = None; app.cooker.started = None; + match result { + Ok(c) => app.session.cooked = c, + Err(msg) => report_failure(app, msg), + } ctx.request_repaint(); } Err(TryRecvError::Empty) => { @@ -37,6 +66,7 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) { Err(TryRecvError::Disconnected) => { app.cooker.rx = None; app.cooker.started = None; + report_failure(app, "the cook worker stopped unexpectedly".into()); } } } @@ -60,10 +90,10 @@ fn start(app: &mut MaterialCraftApp, now: f64) { let spawned = std::thread::Builder::new().name("materialcraft-cook".into()).spawn(move || { let mut opts = Options::new(&dec); opts.max_size = max; - let cooked = { + let cooked = guard("cook", || { let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner); - materialcraft_engine::eval::cook(&pkg, gi, &opts, &mut cache) - }; + Ok(materialcraft_engine::eval::cook(&pkg, gi, &opts, &mut cache)) + }); let _ = tx.send(cooked); }); match spawned { @@ -83,3 +113,7 @@ fn start(app: &mut MaterialCraftApp, _now: f64) { // shortcut: no threads on the web; the cook runs on the UI thread (the page pauses). app.session.cook(); } + +#[cfg(test)] +#[path = "cook.test.rs"] +mod tests; diff --git a/crates/ui-egui/src/cook.test.rs b/crates/ui-egui/src/cook.test.rs new file mode 100644 index 00000000..cffb4309 --- /dev/null +++ b/crates/ui-egui/src/cook.test.rs @@ -0,0 +1,52 @@ +#[cfg(test)] +mod cook_tests { + use crate::MaterialCraftApp; + use crate::cook::{drive, guard}; + use crate::state::UiState; + use materialcraft_engine::eval::Cooked; + use materialcraft_engine::sample_session; + + fn app() -> MaterialCraftApp { + let mut session = sample_session(); + session.preview_size = Some(64); + session.cook(); + MaterialCraftApp::headless(session, UiState::default()) + } + + #[test] + fn guard_turns_a_panic_into_an_error() { + let r: Result = guard("test", || -> Result { panic!("boom") }); + let e = r.unwrap_err(); + assert!(e.contains("boom"), "{e}"); + assert_eq!(guard("test", || Ok::<_, String>(7)).unwrap(), 7); + } + + #[test] + fn a_panicked_cook_worker_reports_errors_on_every_node() { + let mut app = app(); + assert!(app.session.cook_failures().0.is_empty()); + let (tx, rx) = std::sync::mpsc::channel::>(); + app.cooker.rx = Some(rx); + tx.send(Err("boom".into())).unwrap(); + app.session.dirty = false; + drive(&mut app, &egui::Context::default()); + assert!(!app.cooker.busy()); + let (failed, _) = app.session.cook_failures(); + assert!(!failed.is_empty()); + assert!(failed.iter().all(|(_, e)| e.contains("boom"))); + assert!(app.toasts.iter().any(|t| t.error && t.text.contains("boom"))); + } + + #[test] + fn a_dead_cook_worker_is_reported_not_silent() { + let mut app = app(); + let (tx, rx) = std::sync::mpsc::channel::>(); + app.cooker.rx = Some(rx); + drop(tx); + app.session.dirty = false; + drive(&mut app, &egui::Context::default()); + assert!(!app.cooker.busy()); + assert!(app.toasts.iter().any(|t| t.error)); + assert!(!app.session.cook_failures().0.is_empty()); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 68aac018..1f4ca4dd 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,6 +16,9 @@ pub mod function_editor; pub mod graph_view; pub mod i18n; pub mod levels_editor; +#[cfg(test)] +#[path = "lib.test.rs"] +mod lib_test; pub mod library; pub mod menus; pub mod properties; @@ -135,10 +138,10 @@ impl MaterialCraftApp { /// Run an engine command, reporting errors as toasts. Returns the result on success. pub fn run(&mut self, id: &str, params: Value) -> Option { - match materialcraft_engine::execute(&mut self.session, id, ¶ms) { + match cook::execute_guarded(&mut self.session, id, ¶ms) { Ok(v) => Some(v), Err(e) => { - self.toast(e.to_string(), true); + self.toast(e, true); None } } diff --git a/crates/ui-egui/src/lib.test.rs b/crates/ui-egui/src/lib.test.rs new file mode 100644 index 00000000..36092902 --- /dev/null +++ b/crates/ui-egui/src/lib.test.rs @@ -0,0 +1,24 @@ +#[cfg(test)] +mod lib_tests { + use crate::MaterialCraftApp; + use crate::cook::execute_guarded; + use crate::state::UiState; + use materialcraft_engine::sample_session; + use serde_json::json; + + #[test] + fn run_reports_errors_as_toasts_and_keeps_the_session() { + let mut app = MaterialCraftApp::headless(sample_session(), UiState::default()); + assert!(app.run("no.such.command", json!({})).is_none()); + assert!(app.toasts.iter().any(|t| t.error)); + assert!(app.run("graph.node.add", json!({"def": "levels"})).is_some()); + } + + #[test] + fn guarded_execute_returns_command_errors_as_strings() { + let mut s = sample_session(); + let e = execute_guarded(&mut s, "no.such.command", &json!({})).unwrap_err(); + assert!(!e.is_empty()); + assert!(execute_guarded(&mut s, "graph.node.add", &json!({"def": "levels"})).is_ok()); + } +}