From 9f97eb1a10a94e38efe4b287c395686167a4473f Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 20:10:28 -0600 Subject: [PATCH 1/7] feat(engine): a bug says it is one, with a reference; the next launch says what was running; a full disk says what to do A panic caught in a command, a tool, a read, an export or a raster run is said as a bug in RustGIS with an incident reference: "Buffer failed unexpectedly, a bug in RustGIS (incident 7F3A2C); the project is as it was before". Messages keeps the panic's message, place and the version under it, and the desktop crash log names the same reference. Each top-level command run is noted in the desktop app's run marker. A run that ends without closing (out of memory, a forced quit) has the next launch say what was running, on what and when; without a crash log, that it was most likely stopped from outside, with what to try. An I/O error that is the computer's (a full disk, a read-only folder, no permission, no memory) says what happened and what to do before the system's own words. --- apps/rustgis-cli/src/main.rs | 2 + apps/rustgis/src/main.rs | 160 +++++++++++++++++++++--- crates/analysis/src/lib.rs | 12 +- crates/data/src/diagnostics.rs | 15 +++ crates/data/src/incident.rs | 157 +++++++++++++++++++++++ crates/data/src/lib.rs | 42 ++++++- crates/engine/src/cmd/exports.rs | 5 +- crates/engine/src/cmd/plugins.rs | 8 +- crates/engine/src/cmd/reads.rs | 5 +- crates/engine/src/cmd/workflows.rs | 5 +- crates/engine/src/lib.rs | 26 +++- crates/engine/src/policy/dispatch.rs | 10 +- crates/engine/src/tests/message_runs.rs | 26 ++++ crates/map/src/source.rs | 16 ++- 14 files changed, 455 insertions(+), 34 deletions(-) create mode 100644 crates/data/src/incident.rs diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index e96873c587..8c91f16f80 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -919,6 +919,8 @@ fn mcp(s: &mut Session, args: &[String]) -> Result<(), String> { /// Runs the command line, then stops the session plugins' programs its commands started. fn main() -> ExitCode { + // A bug caught in a command says so, with a reference to its details. + rustgis_engine::data::incident::install(); let code = cli(); // Session plugins' programs a command started end with the command line. rustgis_engine::plugins::session::stop_all(); diff --git a/apps/rustgis/src/main.rs b/apps/rustgis/src/main.rs index 5cc15356d5..3fcd4e78c3 100644 --- a/apps/rustgis/src/main.rs +++ b/apps/rustgis/src/main.rs @@ -154,6 +154,36 @@ mod prefs { } } +/// What the start of a run says of the last one: an internal error it met (`crash_log`, which a +/// caught one writes too), and, when it didn't close (`unclean`), the command it was running then. +/// Without a crash log, a run that didn't close was stopped from outside, most often by running out +/// of memory. +fn last_run_notice(app: &RustGisApp, crash_log: Option<&std::path::Path>, unclean: bool, last: Option<&running::Breadcrumb>) -> String { + use rustgis_ui_egui::i18n::{fmt, t}; + let what = last.map(|b| { + let name = app.session.registry.get(b.command.as_str()).map_or(b.command.as_str(), |spec| t(spec.label)); + let at = crash::utc(b.at); + match &b.target { + Some(target) => fmt("{command} on {target}, started {at} UTC", &[("command", name), ("target", target), ("at", &at)]), + None => fmt("{command}, started {at} UTC", &[("command", name), ("at", &at)]), + } + }); + match (crash_log, unclean, what) { + (Some(log), true, Some(what)) => fmt( + "RustGIS closed after an internal error last time, while running {what}. The details are in {path}; please attach them to a bug report.", + &[("what", &what), ("path", &log.display().to_string())], + ), + (Some(log), _, _) => fmt( + "RustGIS ran into an internal error last time. The details are in {path}; please attach them to a bug report.", + &[("path", &log.display().to_string())], + ), + (None, _, what) => fmt( + "RustGIS closed without a crash report last time, while running {what}: it was most likely stopped from outside, by the computer running out of memory, a forced quit or a power cut. If it happens again with the same data, try a smaller part of it, such as by filtering or clipping it first.", + &[("what", &what.unwrap_or_default())], + ), + } +} + /// Crash reports. A panic, caught or not, is written to `crash.log` in the settings folder (a /// release build on Windows has no console to print it to), and the next launch says where it is. mod crash { @@ -173,17 +203,20 @@ mod crash { })); } + /// Appends a panic to `/crash.log`: the version, system, time, thread and the incident's + /// reference, the panic and its backtrace. The log starts over past its cap. fn write(dir: &Path, info: &std::panic::PanicHookInfo<'_>) { let path = dir.join("crash.log"); let used = std::fs::metadata(&path).map_or(0, |m| m.len()); let thread = std::thread::current(); let entry = format!( - "--- RustGIS {} on {} {}, {} UTC, thread {}\n{info}\n{}\n\n", + "--- RustGIS {} on {} {}, {} UTC, thread {}{}\n{info}\n{}\n\n", env!("CARGO_PKG_VERSION"), std::env::consts::OS, std::env::consts::ARCH, utc_now(), thread.name().unwrap_or("unnamed"), + rustgis_engine::data::incident::last_id().map(|id| format!(", incident {id}")).unwrap_or_default(), std::backtrace::Backtrace::force_capture(), ); // The log starts over when this entry doesn't fit, and one huge entry is cut to the cap. @@ -253,18 +286,53 @@ mod running { pub other_copy: bool, } + /// The command the last run was running when it ended without closing, as its marker held it. + #[derive(Debug, PartialEq, Eq)] + pub struct Breadcrumb { + /// The registered command's id. + pub command: String, + /// What it worked on, redacted as a message is ([`rustgis_engine::data::diagnostics::Run`]). + pub target: Option, + /// When it started, in seconds since 1970 (UTC). + pub at: u64, + } + + /// The marker's text while `run` runs: `running`, then the command, its target and its start, + /// tab-separated on a second line. + fn running_text(run: Option<&rustgis_engine::data::diagnostics::Run>, at: u64) -> String { + match run { + None => "running".to_string(), + Some(run) => { + // One line of fields: tabs and line breaks in a layer's name read as spaces. + let clean = |s: &str| s.chars().map(|c| if c.is_control() { ' ' } else { c }).collect::(); + format!("running\n{}\t{}\t{at}", clean(&run.command), clean(run.target.as_deref().unwrap_or(""))) + } + } + } + + /// The command a marker's text says was running ([`running_text`]), if any. + fn breadcrumb(text: &str) -> Option { + let line = text.strip_prefix("running\n")?; + let mut fields = line.trim_end().split('\t'); + let command = fields.next().filter(|c| !c.is_empty())?.to_string(); + let target = fields.next().filter(|t| !t.is_empty()).map(str::to_string); + let at = fields.next().and_then(|s| s.parse().ok()).unwrap_or(0); + Some(Breadcrumb { command, target, at }) + } + /// Takes `/running` for this run: the marker, or why there is none (another copy holds - /// it, or the folder can't be written), and whether the previous run didn't close cleanly. - pub fn start(dir: Option<&Path>) -> (Result, bool) { + /// it, or the folder can't be written), whether the previous run didn't close cleanly, and the + /// command it was running then, when its marker says. + pub fn start(dir: Option<&Path>) -> (Result, bool, Option) { let none = |why: String| Err(NoMarker { why, other_copy: false }); - let Some(dir) = dir else { return (none("this computer has no settings folder for RustGIS".into()), false) }; + let Some(dir) = dir else { return (none("this computer has no settings folder for RustGIS".into()), false, None) }; let file = std::fs::create_dir_all(dir) .and_then(|_| OpenOptions::new().read(true).write(true).create(true).truncate(false).open(dir.join("running"))); let mut file = match file { Ok(f) => f, Err(e) => { log::warn!("no run marker in {} ({e}): an unclean exit won't be noticed", dir.display()); - return (none(format!("the settings folder {} can't be written ({e})", dir.display())), false); + return (none(format!("the settings folder {} can't be written ({e})", dir.display())), false, None); } }; let locked = match file.try_lock() { @@ -272,7 +340,7 @@ mod running { Err(std::fs::TryLockError::WouldBlock) => { log::info!("the run marker is held: another copy of RustGIS is running"); let why = "another copy of RustGIS is running, and only the first keeps a recovery copy".into(); - return (Err(NoMarker { why, other_copy: true }), false); + return (Err(NoMarker { why, other_copy: true }), false, None); } // The folder can't lock files (some network or FUSE folders): keep the marker unlocked, // so unclean exits are still noticed. Without a lock, copies running side by side share @@ -295,6 +363,8 @@ mod running { true } }; + // What it was running when it ended, when it says. + let crumb = if unclean { breadcrumb(&String::from_utf8_lossy(&bytes)) } else { None }; // Written over what is there, then cut to its length: a write that fails leaves the old // content, so a marker that was set never reads as a clean exit. const RUNNING: &[u8] = b"running"; @@ -303,7 +373,7 @@ mod running { if let Err(e) = marked { log::warn!("could not mark this run: {e}"); } - (Ok(Marker { file, locked }), unclean) + (Ok(Marker { file, locked }), unclean, crumb) } impl Marker { @@ -313,6 +383,18 @@ mod running { self.locked } + /// Writes what is running now (`run`, or nothing between commands), so a run that ends + /// without closing leaves it for the next launch to say. A few bytes over the old ones; a + /// write that fails leaves the marker set, as a run without a note. + pub fn note(&mut self, run: Option<&rustgis_engine::data::diagnostics::Run>, at: u64) { + let text = running_text(run, at); + let written = + self.file.rewind().and_then(|_| self.file.write_all(text.as_bytes())).and_then(|_| self.file.set_len(text.len() as u64)); + if let Err(e) = written { + log::warn!("could not note the running command in the run marker: {e}"); + } + } + /// A clean exit: the next launch starts as usual. Dropping the file releases the lock. pub fn close(self) { if let Err(e) = self.file.set_len(0) { @@ -326,6 +408,15 @@ mod running { /// eframe failing to start before the app exists). pub type Shared = std::sync::Arc>>; + /// Notes what a shared marker's run is running now ([`Marker::note`]). + pub fn note(marker: &Shared, run: Option<&rustgis_engine::data::diagnostics::Run>) { + let at = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()); + let mut held = marker.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(m) = held.as_mut() { + m.note(run, at); + } + } + /// Clears a shared marker once. pub fn close(marker: &Shared) { let taken = marker.lock().map(|mut m| m.take()).unwrap_or_else(|poisoned| poisoned.into_inner().take()); @@ -603,8 +694,11 @@ fn main() -> eframe::Result { let crashed = crash::take_previous(prefs::dir()); // Whether it closed cleanly: if not, the Start With project isn't opened (it may be what // crashed, and reopening it on every launch would leave no way into Settings). - let (marker, unclean) = running::start(prefs::dir().as_deref()); + let (marker, unclean, last_command) = running::start(prefs::dir().as_deref()); crash::install(prefs::dir()); + // Every panic an incident with a reference, which the crash log above names and a caught bug's + // message gives (installed after it, so it runs first). + rustgis_engine::data::incident::install(); // Finder can supply documents before eframe creates the app. Keep the native target alive // through run_native and attach its wakeup when the app's egui context becomes available. #[cfg(target_os = "macos")] @@ -663,14 +757,10 @@ fn main() -> eframe::Result { if let Err(e) = app.start(&rustgis_ui_egui::Start { blank, after_crash: unclean, ..Default::default() }) { log::warn!("start-up: {e}"); } - if let Some(log) = crashed { + if crashed.is_some() || unclean && last_command.is_some() { // Notices are shown as written: translate this one now that the language is known. rustgis_ui_egui::i18n::set_current(app.chosen_lang()); - let text = rustgis_ui_egui::i18n::fmt( - "RustGIS ran into an internal error last time. The details are in {path}; please attach them to a bug report.", - &[("path", &log.display().to_string())], - ); - app.session.notify(text, true); + app.session.notify(last_run_notice(&app, crashed.as_deref(), unclean, last_command.as_ref()), true); } if let Some(e) = no_autosave { log::warn!("no autosave: {e}"); @@ -738,6 +828,9 @@ fn main() -> eframe::Result { } let marker: running::Shared = std::sync::Arc::new(std::sync::Mutex::new(marker.ok())); let held = marker.clone(); + // What runs, noted in the marker, so a run that ends without closing says what it was doing. + let crumbs = marker.clone(); + app.session.on_run = Some(Box::new(move |run| running::note(&crumbs, run))); let menus = Menus::default(); let result = eframe::run_native( "RustGIS", @@ -850,28 +943,59 @@ mod tests { assert_eq!(flag(&["--backend".to_string()], "--backend"), None); } + #[test] + fn a_run_that_did_not_close_says_the_command_it_was_running() { + let dir = std::env::temp_dir().join(format!("rustgis-running-crumb-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let _cleanup = TempDir(dir.clone()); + let (first, _, _) = running::start(Some(&dir)); + let mut first = first.unwrap(); + let run = rustgis_engine::data::diagnostics::Run { + id: 1, + command: "gp.run".into(), + before: 0, + after: None, + target: Some("Parcels\tcounty".into()), + }; + first.note(Some(&run), 1_700_000_000); + // It ends without closing, in the middle of the command. + drop(first); + let (second, unclean, crumb) = running::start(Some(&dir)); + assert!(unclean); + assert_eq!(crumb, Some(running::Breadcrumb { command: "gp.run".into(), target: Some("Parcels county".into()), at: 1_700_000_000 })); + // Between commands there is nothing to say, and a clean close says nothing at all. + let mut second = second.unwrap(); + second.note(None, 0); + drop(second); + let (third, unclean, crumb) = running::start(Some(&dir)); + assert!(unclean && crumb.is_none()); + third.unwrap().close(); + let (_, unclean, crumb) = running::start(Some(&dir)); + assert!(!unclean && crumb.is_none()); + } + #[test] fn a_run_that_did_not_close_is_noticed_once() { let dir = std::env::temp_dir().join(format!("rustgis-running-test-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); // Removed however the test ends (declared first, so dropped after the markers). let _cleanup = TempDir(dir.clone()); - let (first, unclean) = running::start(Some(&dir)); + let (first, unclean, _) = running::start(Some(&dir)); assert!(first.is_ok() && !unclean, "a first run"); // Held alone: autosave may use the recovery folder. assert!(first.as_ref().is_ok_and(running::Marker::locked)); // Another copy running alongside can't take it, and doesn't count as a crash. - let (second, unclean) = running::start(Some(&dir)); + let (second, unclean, _) = running::start(Some(&dir)); // It says why, which the app shows as it starts without autosave. assert!(second.as_ref().err().is_some_and(|no| no.other_copy && no.why.contains("another copy")) && !unclean); // A folder that can't be written isn't another copy. assert!(running::start(None).0.err().is_some_and(|no| !no.other_copy)); // This run ends without closing (a crash): the next one notices, once it closes cleanly. drop(first); - let (after_crash, unclean) = running::start(Some(&dir)); + let (after_crash, unclean, _) = running::start(Some(&dir)); assert!(unclean); after_crash.unwrap().close(); - let (next, unclean) = running::start(Some(&dir)); + let (next, unclean, _) = running::start(Some(&dir)); assert!(!unclean); drop(next); } diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index 1f65b464ef..3d112a3576 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -798,7 +798,11 @@ pub fn run(id: &str, inputs: &dyn Inputs, params: &Value) -> Result u64) { *lock(&CLOCK) = Some(clock); } +/// Milliseconds since 1970 by the application's clock ([`set_clock`]). +pub(crate) fn now_ms() -> u64 { + timestamp_ms() +} + fn timestamp_ms() -> u64 { let clock = *lock(&CLOCK); if let Some(clock) = clock { @@ -280,6 +285,16 @@ impl History { } } + /// Adds `details` (redacted and bounded) to the newest record: what a bug's failure keeps for a + /// report ([`crate::incident::Incident::details`]). + pub fn detail_newest(&self, details: &str) { + let mut state = lock(&self.0); + if let Some(record) = state.records.back_mut() { + record.details = bounded(&redact(details), MAX_DETAILS_BYTES); + } + state.generation = state.generation.wrapping_add(1); + } + /// Oldest first; both the count and every string in this independent snapshot are bounded. pub fn records(&self) -> Vec { lock(&self.0).records.iter().cloned().collect() diff --git a/crates/data/src/incident.rs b/crates/data/src/incident.rs new file mode 100644 index 0000000000..26817f0785 --- /dev/null +++ b/crates/data/src/incident.rs @@ -0,0 +1,157 @@ +//! A bug in RustGIS met while a command or a tool ran, caught before it could take the app down: +//! a short reference that ties the message the user sees to the details kept for a bug report +//! (the panic's message and where in the code it happened) and to the app's crash log. +//! +//! [`install`] records each panic as it happens, on whatever thread, then hands it on to the hook +//! that was there before (the desktop app's crash log). A catch site turns what it caught into an +//! [`Incident`] with [`caught`], and says [`message`]; [`find`] gives the details back by reference. + +use std::collections::VecDeque; +use std::sync::{Mutex, MutexGuard, Once}; + +/// The incidents kept for their details: a session meets few, and a long one keeps the newest. +const KEPT: usize = 16; + +/// A bug met and caught: its reference, the panic's message and where it happened. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Incident { + /// Six hexadecimal digits, as the user sees them and the crash log names them. + pub id: String, + pub message: String, + /// `file:line` in RustGIS's source, when the panic gave it. + pub location: Option, +} + +impl Incident { + /// The details a bug report needs, as Messages shows them under the failure. + pub fn details(&self) -> String { + let at = self.location.as_deref().map(|at| format!("\nat {at}")).unwrap_or_default(); + format!("Incident {} in RustGIS {}\n{}{at}", self.id, env!("CARGO_PKG_VERSION"), self.message) + } +} + +static RECENT: Mutex> = Mutex::new(VecDeque::new()); +static COUNT: Mutex = Mutex::new(0); +static INSTALLED: Once = Once::new(); + +std::thread_local! { + /// The reference of the last panic on this thread, for the catch site and the crash log. + static LAST: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// A reference no other incident of this session has: the time and a count, mixed, as six +/// hexadecimal digits. +fn new_id() -> String { + let n = { + let mut count = lock(&COUNT); + *count = count.wrapping_add(1); + *count + }; + let mixed = crate::diagnostics::now_ms().wrapping_mul(0x9E37_79B9_7F4A_7C15).wrapping_add(n.wrapping_mul(0xBF58_476D_1CE4_E5B9)); + format!("{:06X}", (mixed >> 40) & 0xFF_FFFF) +} + +/// Keeps `incident` for its details, the oldest let go past [`KEPT`]. +fn keep(incident: Incident) { + let mut recent = lock(&RECENT); + if recent.len() >= KEPT { + recent.pop_front(); + } + recent.push_back(incident); +} + +fn payload_text(payload: &(dyn std::any::Any + Send)) -> String { + payload + .downcast_ref::<&str>() + .map(|s| (*s).to_string()) + .or_else(|| payload.downcast_ref::().cloned()) + .unwrap_or_else(|| "a panic without a message".to_string()) +} + +/// Records every panic as an incident before the hook that was there runs (the app's crash log, +/// which can name it by [`last_id`]). Installing it again does nothing. +pub fn install() { + INSTALLED.call_once(|| { + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + let id = new_id(); + let message = info + .payload() + .downcast_ref::<&str>() + .map(|s| (*s).to_string()) + .or_else(|| info.payload().downcast_ref::().cloned()) + .unwrap_or_else(|| "a panic without a message".to_string()); + let location = info.location().map(|l| format!("{}:{}", l.file(), l.line())); + LAST.with(|last| *last.borrow_mut() = Some(id.clone())); + keep(Incident { id, message, location }); + previous(info); + })); + }); +} + +/// The reference of the last panic on this thread, if [`install`] recorded one. +pub fn last_id() -> Option { + LAST.with(|last| last.borrow().clone()) +} + +/// The incident a catch site caught: the one [`install`] recorded on this thread, or, without the +/// hook, one made from what was caught. +pub fn caught(payload: &(dyn std::any::Any + Send)) -> Incident { + if let Some(id) = LAST.with(|last| last.borrow_mut().take()) + && let Some(found) = find(&id) + { + return found; + } + let incident = Incident { id: new_id(), message: payload_text(payload), location: None }; + keep(incident.clone()); + incident +} + +/// An incident kept by its reference. +pub fn find(id: &str) -> Option { + lock(&RECENT).iter().rev().find(|i| i.id == id).cloned() +} + +/// What a caught bug says: what failed, that it is a bug in RustGIS, its reference, and, when the +/// project was put back as it was (`restored`), that nothing it did was kept. It keeps the words +/// "failed unexpectedly", which tests and scripts look for to tell a bug from a refusal. +pub fn message(what: &str, restored: bool, id: &str) -> String { + let kept = if restored { "; the project is as it was before" } else { "" }; + format!( + "{what} failed unexpectedly, a bug in RustGIS (incident {id}){kept}. The details are in Messages; please include them in a bug report" + ) +} + +/// The reference a message from [`message`] names, if it names one. +pub fn named_in(text: &str) -> Option<&str> { + let (_, rest) = text.split_once("(incident ")?; + let id = rest.get(..6)?; + id.bytes().all(|b| b.is_ascii_hexdigit()).then_some(id) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_caught_panic_is_an_incident_with_its_place_and_a_message_naming_it() { + install(); + let payload = std::panic::catch_unwind(|| panic!("the bug")).unwrap_err(); + let incident = caught(payload.as_ref()); + assert_eq!(incident.message, "the bug"); + assert!(incident.location.as_deref().is_some_and(|at| at.contains("incident.rs")), "{incident:?}"); + assert_eq!(find(&incident.id).as_ref(), Some(&incident)); + let said = message("Buffer", true, &incident.id); + assert!(said.starts_with("Buffer failed unexpectedly, a bug in RustGIS (incident "), "{said}"); + assert!(said.contains("the project is as it was before"), "{said}"); + assert_eq!(named_in(&said), Some(incident.id.as_str())); + assert!(incident.details().contains("the bug") && incident.details().contains(&incident.id)); + // Caught once: the next catch on this thread doesn't take it again. + assert_eq!(last_id(), None); + assert_eq!(named_in("Buffer failed: no layer"), None); + } +} diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 9e8f5cac6e..a70a66092a 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -25,6 +25,7 @@ pub mod gml; pub mod gpx; #[cfg(not(target_arch = "wasm32"))] pub mod http; +pub mod incident; pub mod interop; pub mod io; pub mod kml; @@ -90,7 +91,9 @@ pub fn no_programs_here() -> &'static str { #[derive(Debug, thiserror::Error)] pub enum DataError { - #[error("i/o: {0}")] + /// A failure of the computer rather than the data (a full disk, a read-only folder, no + /// permission, no memory) says so, and what to do, before the system's own words. + #[error("{}", io_text(.0))] Io(#[source] std::io::Error), #[error("{0}")] Format(String), @@ -118,6 +121,24 @@ impl DataError { } } +/// An I/O error in words: what the computer ran into and what to do, for a failure of the computer +/// rather than the data, then the system's own words; `i/o: …` for any other. +pub fn io_text(e: &std::io::Error) -> String { + use std::io::ErrorKind as K; + let plain = match e.kind() { + K::StorageFull => "the disk is full: free some space, or save somewhere else", + K::QuotaExceeded => "the storage quota on this disk is used up: free some space, or save somewhere else", + K::FileTooLarge => "the file is larger than this disk or system allows: save it in pieces, or to a disk that holds larger files", + K::ReadOnlyFilesystem => "the disk or folder is read-only: save somewhere else", + K::PermissionDenied => "RustGIS isn't allowed to use this file or folder: check its permissions, or choose another", + K::OutOfMemory => { + "the computer ran out of memory: close other programs, or work on a smaller part of the data, such as by filtering or clipping it first" + } + _ => return format!("i/o: {e}"), + }; + format!("{plain} ({e})") +} + /// An I/O error, or [`DataError::Cancelled`] when it carries one: a write that only returns I/O /// errors stops with it for a cancelled run ([`progress`]). impl From for DataError { @@ -168,6 +189,25 @@ impl DataError { #[cfg(test)] mod unplaced_out_tests; +#[cfg(test)] +mod io_text_tests { + use super::*; + + #[test] + fn a_failure_of_the_computer_says_what_to_do_and_keeps_the_systems_words() { + use std::io::{Error, ErrorKind as K}; + let full = DataError::Io(Error::from(K::StorageFull)).to_string(); + assert!(full.starts_with("the disk is full: free some space, or save somewhere else ("), "{full}"); + assert!(full.ends_with(&format!("{})", Error::from(K::StorageFull))), "{full}"); + for kind in [K::QuotaExceeded, K::FileTooLarge, K::ReadOnlyFilesystem, K::PermissionDenied, K::OutOfMemory] { + let said = DataError::Io(Error::from(kind)).to_string(); + assert!(!said.starts_with("i/o:") && said.contains(':'), "{kind:?}: {said}"); + } + // Any other failure is said as before. + assert_eq!(DataError::Io(Error::other("unchanged")).to_string(), "i/o: unchanged"); + } +} + #[cfg(test)] mod secret_redaction_tests { use super::*; diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index ef8f198358..3f179a65cc 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -429,7 +429,10 @@ impl ExportRun { } }) })) - .unwrap_or_else(|_| Err(format!("{name} failed unexpectedly"))) + .unwrap_or_else(|payload| { + let incident = rustgis_data::incident::caught(payload.as_ref()); + Err(rustgis_data::incident::message(name, false, &incident.id)) + }) .map(|w| Wrote { owner: Some(owner), crs_used: rustgis_data::raster::crs::take_used(), ..w }); if let Some(inputs) = inputs { started.inputs.lock().unwrap_or_else(|e| e.into_inner()).extend(inputs.inputs()); diff --git a/crates/engine/src/cmd/plugins.rs b/crates/engine/src/cmd/plugins.rs index ad5be9231d..3285c83729 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -696,6 +696,8 @@ impl Bridge<'_> { Ok(json!({"layer": id, "skipped": report.skipped})) } + /// Runs a command a plugin asked for, as the plugin may: a RustGIS command's bug is said as + /// one, with its incident reference. fn command(&mut self, id: &str, params: &Value) -> CmdResult { if id.starts_with(rustgis_plugins::PREFIX) { return Err("plugins can't run other plugins' commands".into()); @@ -740,7 +742,11 @@ impl Bridge<'_> { let op = s.authorize(id, params)?; super::workflows::steps_of(s, |s| s.invoke(op, crate::policy::Txn::Shared)) }) - .unwrap_or_else(|_| Err(format!("{label} failed unexpectedly"))); + .unwrap_or_else(|payload| { + // A RustGIS command the plugin ran hit a bug: said as ours, with its reference. + let incident = rustgis_data::incident::caught(payload.as_ref()); + Err(rustgis_data::incident::message(label, false, &incident.id)) + }); if let Some(before) = before { let mut dropped = false; for m in &mut self.s.project.maps { diff --git a/crates/engine/src/cmd/reads.rs b/crates/engine/src/cmd/reads.rs index d0b8f25946..34f0057711 100644 --- a/crates/engine/src/cmd/reads.rs +++ b/crates/engine/src/cmd/reads.rs @@ -191,7 +191,10 @@ impl ReadAhead { }) }) })) - .unwrap_or_else(|_| Err(format!("{name} failed unexpectedly"))); + .unwrap_or_else(|payload| { + let incident = rustgis_data::incident::caught(payload.as_ref()); + Err(rustgis_data::incident::message(name, false, &incident.id)) + }); res?; Ok(Read { op, diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index b4fac8af81..730e72dc1a 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -588,7 +588,10 @@ impl RasterRun { rustgis_analysis::run_under(name, control, || reading_files(name, work)) }) })) - .unwrap_or_else(|_| Err(format!("{name} failed unexpectedly"))) + .unwrap_or_else(|payload| { + let incident = rustgis_data::incident::caught(payload.as_ref()); + Err(rustgis_data::incident::message(name, false, &incident.id)) + }) .map(|m| Made { ran: Some((name, map)), continuation: Some(continuation), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 042518e237..7f29819329 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1061,6 +1061,9 @@ pub struct Session { /// The top-level command running, as the messages it says remember it, and how many have run. run: Option, runs: u64, + /// Told of each top-level command run as it starts, and with `None` as it ends: the desktop app + /// notes it in its run marker, so a run that ends without closing can say what it was doing. + pub on_run: Option) + Send>>, /// How many of the commands running now restore the project if they fail: a replacement is /// put aside only under one of them, as only then can it be rolled back. restorable: u32, @@ -1575,6 +1578,7 @@ impl Session { diagnostic_source: None, run: None, runs: 0, + on_run: None, restorable: 0, published_syncs: Vec::new(), actor: None, @@ -1976,7 +1980,11 @@ impl Session { after: None, target: run_target(params), }; - self.run.replace(run) + let previous = self.run.replace(run); + if let Some(on_run) = self.on_run.as_mut() { + on_run(self.run.as_ref()); + } + previous }); let history_deferred = std::mem::replace(&mut self.undo_memory.deferred, true); let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { @@ -2071,6 +2079,9 @@ impl Session { self.diagnostics.finish_run(ended.id, self.state); } self.run = run; + if let Some(on_run) = self.on_run.as_mut() { + on_run(None); + } } self.undo_memory.deferred = history_deferred; // Every top-level invocation consumes its key, even a refusal or panic before guarded. @@ -2487,8 +2498,11 @@ impl Session { let retry_state = (self.plugin_retries.clone(), self.url_waits.clone()); let file_outputs: Vec<_> = self.file_outputs.iter().map(|file| file.id).collect(); let said = self.notices_given; - let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self))) - .unwrap_or_else(|_| Err(format!("{label} failed unexpectedly; the project was restored"))); + let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self))).unwrap_or_else(|payload| { + // A bug in RustGIS: said as one, with a reference to its details in Messages. + let incident = rustgis_data::incident::caught(payload.as_ref()); + Err(rustgis_data::incident::message(label, mutates, &incident.id)) + }); self.shared_steps = outer_steps; self.depth = self.depth.saturating_sub(1); self.restorable = self.restorable.saturating_sub(u32::from(mutates)); @@ -3668,6 +3682,12 @@ impl Session { return; } self.diagnostics.push_redacted(severity, source.unwrap_or("Application"), &text, loss, self.run.clone()); + // A bug's failure keeps its details (the panic's message and place) under it, for a report. + if severity == rustgis_data::diagnostics::Severity::Error + && let Some(incident) = rustgis_data::incident::named_in(text.as_str()).and_then(rustgis_data::incident::find) + { + self.diagnostics.detail_newest(&incident.details()); + } self.notices.push(Notice { text: text.into_string(), error: severity == rustgis_data::diagnostics::Severity::Error, diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 388e206660..faab657112 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -1024,7 +1024,10 @@ impl Session { let add = |s: &mut Session| { let before = crate::service_logins::before(s, spec.id, ¶ms)?; let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| spec.run.call(s, ¶ms))) - .unwrap_or_else(|_| Err(format!("{} failed unexpectedly", spec.label))); + .unwrap_or_else(|payload| { + let incident = rustgis_data::incident::caught(payload.as_ref()); + Err(rustgis_data::incident::message(spec.label, spec.mutates, &incident.id)) + }); // A nested plugin command may fail after making additions. Its outer // transaction owns rollback; mark those additions anonymous meanwhile. if let Some(before) = before { @@ -1036,7 +1039,10 @@ impl Session { || (matches!(spec.id, "layer.addUrl" | "layer.addDownload") && params.get("anonymous").and_then(Value::as_bool) == Some(true)); let result = crate::service_logins::anonymously(s, anonymous, add) - .unwrap_or_else(|_| Err(format!("{} failed unexpectedly", spec.label))) + .unwrap_or_else(|payload| { + let incident = rustgis_data::incident::caught(payload.as_ref()); + Err(rustgis_data::incident::message(spec.label, spec.mutates, &incident.id)) + }) .map_err(|e| crate::durable::generated_text(&e)); if let Ok(value) = &result { s.trust_after(spec.id, ¶ms, value, editor); diff --git a/crates/engine/src/tests/message_runs.rs b/crates/engine/src/tests/message_runs.rs index 3fe56b4abe..bab6e5417c 100644 --- a/crates/engine/src/tests/message_runs.rs +++ b/crates/engine/src/tests/message_runs.rs @@ -65,3 +65,29 @@ fn a_runs_target_masks_a_login_in_use() { assert!(!target.contains(secret), "{target}"); assert!(target.starts_with("roads "), "{target}"); } + +#[test] +fn a_bug_in_a_command_is_said_as_one_with_its_details_kept() { + rustgis_data::incident::install(); + let mut s = Session::new(Project::default()); + s.registry.commands.push(crate::CommandSpec::new("test.bug", "Bug", "Test", |_, _| panic!("the test's bug"))); + let error = s.run("test.bug", &json!({})).unwrap_err(); + assert!(error.contains("failed unexpectedly, a bug in RustGIS (incident "), "{error}"); + let id = rustgis_data::incident::named_in(&error).expect("a reference").to_string(); + // Messages keeps what a report needs: the reference, the panic's message and its place. + let record = s.diagnostics.records().into_iter().rev().find(|r| r.message.contains(&id)).expect("the failure in Messages"); + assert!(record.details.contains(&format!("Incident {id}")), "{}", record.details); + assert!(record.details.contains("the test's bug") && record.details.contains("message_runs.rs"), "{}", record.details); + // The next command runs as usual. + s.run("map.zoomIn", &json!({})).unwrap(); +} + +#[test] +fn a_command_run_is_told_as_it_starts_and_ends() { + let mut s = world(); + let told = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let heard = told.clone(); + s.on_run = Some(Box::new(move |run| heard.lock().unwrap().push(run.map(|r| (r.command.clone(), r.target.clone()))))); + s.run("layer.zoomTo", &json!({"layer": "Cities"})).unwrap(); + assert_eq!(*told.lock().unwrap(), [Some(("layer.zoomTo".to_string(), Some("Cities".to_string()))), None]); +} diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index ddbe8f8ceb..2f6a0f29e0 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -1694,8 +1694,10 @@ impl SourceLayer { let _progress = rustgis_data::progress::install(progress.map(|p| p as Arc)); let result = rustgis_data::source::remote::with_optional_still(still, || { rustgis_data::progress::check()?; - let source = std::panic::catch_unwind(std::panic::AssertUnwindSafe(work)) - .unwrap_or_else(|_| Err(rustgis_data::DataError::Format("opening the layer failed unexpectedly".into())))?; + let source = std::panic::catch_unwind(std::panic::AssertUnwindSafe(work)).unwrap_or_else(|payload| { + let incident = rustgis_data::incident::caught(payload.as_ref()); + Err(rustgis_data::DataError::Format(rustgis_data::incident::message("Opening the layer", false, &incident.id))) + })?; rustgis_data::progress::check()?; Ok(Arc::from(source)) }); @@ -2129,7 +2131,10 @@ impl SourceLayer { std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { window::read_mode(h2.as_ref(), &req, budget, &projection, estimate, full_read, fields, query.as_ref()) })) - .unwrap_or_else(|_| Err(rustgis_data::DataError::Format("the read failed unexpectedly".into()))) + .unwrap_or_else(|payload| { + let incident = rustgis_data::incident::caught(payload.as_ref()); + Err(rustgis_data::DataError::Format(rustgis_data::incident::message("The read", false, &incident.id))) + }) }); rustgis_data::source::remote::drive( file, @@ -2152,7 +2157,10 @@ impl SourceLayer { std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { window::read_mode(h.as_ref(), &req, budget, &projection, estimate, full_read, fields, query.as_ref()) })) - .unwrap_or_else(|_| Err(rustgis_data::DataError::Format("the read failed unexpectedly".into()))) + .unwrap_or_else(|payload| { + let incident = rustgis_data::incident::caught(payload.as_ref()); + Err(rustgis_data::DataError::Format(rustgis_data::incident::message("The read", false, &incident.id))) + }) .map_err(|e| e.to_string()) }) .and_then(|r| rustgis_data::source::remote::check_still(&still).map(|()| r)); From 386361eadaf5aa9a20501e09c951fc7079dfff34 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 20:55:34 -0600 Subject: [PATCH 2/7] fix(engine): a tool run in the background says its bug as one too; a test expects the new wording --- crates/engine/src/cmd/gp.rs | 7 +++++-- crates/engine/src/parameters.rs | 4 +++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index d968a558b1..af413f4e19 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -487,8 +487,11 @@ impl PluginRun { pub fn run(&self, control: &rustgis_plugins::tools::Control) -> Result { self.continuation.check()?; // A bug in a tool must not take the app down. - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.job.run(control))) - .unwrap_or_else(|_| Err(format!("{} failed unexpectedly", self.job.name()))) + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.job.run(control))).unwrap_or_else(|payload| { + // A bug in a tool run in the background: said as one, with its reference. + let incident = rustgis_data::incident::caught(payload.as_ref()); + Err(rustgis_data::incident::message(self.job.name(), false, &incident.id)) + }) } } diff --git a/crates/engine/src/parameters.rs b/crates/engine/src/parameters.rs index 35cdbe3c92..1fd45da43a 100644 --- a/crates/engine/src/parameters.rs +++ b/crates/engine/src/parameters.rs @@ -169,7 +169,9 @@ mod tests { s.notify("Deleted 3 features", false); panic!("synthetic loss rollback"); }); - assert_eq!(result.unwrap_err(), "Loss rollback failed unexpectedly; the project was restored"); + let error = result.unwrap_err(); + assert!(error.starts_with("Loss rollback failed unexpectedly, a bug in RustGIS (incident "), "{error}"); + assert!(error.contains("the project is as it was before"), "{error}"); assert_eq!(session.project.name, name); let notices = session.notices_since(mark); assert_eq!(notices.iter().filter(|n| !n.error).count(), 1); From c7b0e352f0d12fca0652dd5a9035bbfb33575d57 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 21:59:45 -0600 Subject: [PATCH 3/7] fix(engine): every RustGIS catch site names its incident, a panic keeps its reference across threads, details attach by record, and the start-up notice tells an error from what was running --- apps/rustgis/src/main.rs | 51 ++++++++++++++++------------ crates/analysis/src/tools.rs | 4 +-- crates/data/src/diagnostics.rs | 18 +++++----- crates/data/src/incident.rs | 40 ++++++++++++++++++---- crates/engine/src/cmd/connections.rs | 3 +- crates/engine/src/cmd/embeddings.rs | 2 +- crates/engine/src/cmd/gp.rs | 6 ++-- crates/engine/src/cmd/items.rs | 4 +-- crates/engine/src/cmd/notebook.rs | 2 +- crates/engine/src/cmd/plugins.rs | 2 +- crates/engine/src/cmd/reads.rs | 2 +- crates/engine/src/cmd/stac_bands.rs | 25 +++++++++----- crates/engine/src/cmd/time.rs | 2 +- crates/engine/src/cmd/zarr.rs | 2 +- crates/engine/src/lib.rs | 14 ++++++-- 15 files changed, 117 insertions(+), 60 deletions(-) diff --git a/apps/rustgis/src/main.rs b/apps/rustgis/src/main.rs index 3fcd4e78c3..85d0b57032 100644 --- a/apps/rustgis/src/main.rs +++ b/apps/rustgis/src/main.rs @@ -155,9 +155,10 @@ mod prefs { } /// What the start of a run says of the last one: an internal error it met (`crash_log`, which a -/// caught one writes too), and, when it didn't close (`unclean`), the command it was running then. -/// Without a crash log, a run that didn't close was stopped from outside, most often by running out -/// of memory. +/// caught one writes too) and, when it didn't close (`unclean`), the command it was running then, +/// said apart, as the error may have been an earlier command's. Without a crash log, a run that +/// didn't close was stopped from outside (most often by running out of memory) or by a crash +/// RustGIS can't catch, such as a stack overflow. fn last_run_notice(app: &RustGisApp, crash_log: Option<&std::path::Path>, unclean: bool, last: Option<&running::Breadcrumb>) -> String { use rustgis_ui_egui::i18n::{fmt, t}; let what = last.map(|b| { @@ -168,20 +169,26 @@ fn last_run_notice(app: &RustGisApp, crash_log: Option<&std::path::Path>, unclea None => fmt("{command}, started {at} UTC", &[("command", name), ("at", &at)]), } }); - match (crash_log, unclean, what) { - (Some(log), true, Some(what)) => fmt( - "RustGIS closed after an internal error last time, while running {what}. The details are in {path}; please attach them to a bug report.", - &[("what", &what), ("path", &log.display().to_string())], - ), - (Some(log), _, _) => fmt( + let report = |log: &std::path::Path| { + fmt( "RustGIS ran into an internal error last time. The details are in {path}; please attach them to a bug report.", &[("path", &log.display().to_string())], - ), - (None, _, what) => fmt( - "RustGIS closed without a crash report last time, while running {what}: it was most likely stopped from outside, by the computer running out of memory, a forced quit or a power cut. If it happens again with the same data, try a smaller part of it, such as by filtering or clipping it first.", - &[("what", &what.unwrap_or_default())], - ), - } + ) + }; + let closed = match (unclean, &what, crash_log) { + (false, _, _) => None, + (true, Some(what), _) => Some(fmt("RustGIS didn't close normally last time, while running {what}.", &[("what", what)])), + (true, None, _) => Some(t("RustGIS didn't close normally last time, between commands.").to_string()), + }; + let cause = (unclean && crash_log.is_none()).then(|| { + let mut cause = t("With no crash report, it was most likely stopped from outside (the computer running out of memory, a forced quit or a power cut) or by a crash RustGIS can't catch, such as a stack overflow.").to_string(); + if what.is_some() { + cause.push(' '); + cause.push_str(t("If it happens again with the same data, try a smaller part of it, such as by filtering or clipping it first.")); + } + cause + }); + [closed, cause, crash_log.map(report)].into_iter().flatten().collect::>().join(" ") } /// Crash reports. A panic, caught or not, is written to `crash.log` in the settings folder (a @@ -748,6 +755,12 @@ fn main() -> eframe::Result { app }; let mut app = app.with_services(services); + // The marker, shared from here: what runs is noted in it, start-up commands (a project or file + // opened) included, so a run that ends without closing says what it was doing. + let other_copy = marker.as_ref().is_err_and(|no| no.other_copy); + let marker: running::Shared = std::sync::Arc::new(std::sync::Mutex::new(marker.ok())); + let crumbs = marker.clone(); + app.session.on_run = Some(Box::new(move |run| running::note(&crumbs, run))); // Add Data and Load All read on a thread of their own, so a large file doesn't hold the window. app.reads_off_frame = true; // Linked local files changed by another program are reported, with Reload Data (#1477). @@ -757,7 +770,7 @@ fn main() -> eframe::Result { if let Err(e) = app.start(&rustgis_ui_egui::Start { blank, after_crash: unclean, ..Default::default() }) { log::warn!("start-up: {e}"); } - if crashed.is_some() || unclean && last_command.is_some() { + if crashed.is_some() || unclean { // Notices are shown as written: translate this one now that the language is known. rustgis_ui_egui::i18n::set_current(app.chosen_lang()); app.session.notify(last_run_notice(&app, crashed.as_deref(), unclean, last_command.as_ref()), true); @@ -777,7 +790,7 @@ fn main() -> eframe::Result { // update that hasn't run yet. A settings folder that can't lock, or can't be written, can't // tell a second copy apart, and is asked anyway: a note the installer may still be at work on // is left alone, and asked about again once it can't be, and the notice isn't put off for good. - if !marker.as_ref().is_err_and(|no| no.other_copy) + if !other_copy && let Some((text, error)) = { rustgis_ui_egui::i18n::set_current(app.chosen_lang()); app.update.last_install_notice() @@ -826,11 +839,7 @@ fn main() -> eframe::Result { builder.with_default_menu(false); })); } - let marker: running::Shared = std::sync::Arc::new(std::sync::Mutex::new(marker.ok())); let held = marker.clone(); - // What runs, noted in the marker, so a run that ends without closing says what it was doing. - let crumbs = marker.clone(); - app.session.on_run = Some(Box::new(move |run| running::note(&crumbs, run))); let menus = Menus::default(); let result = eframe::run_native( "RustGIS", diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index dc1e932c95..b35730f4ae 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -11853,7 +11853,7 @@ mod tests { ds.push(Some(Geometry::Line(vec![off.to_vec()])), vec![]); let m = Map(HashMap::from([("f".to_string(), ds)])); let r = crate::run("buffer", &m, &serde_json::json!({"input": "f", "distance": 1})); - assert!(!matches!(&r, Err(e) if e.ends_with("failed unexpectedly")), "{:?}", r.err()); + assert!(!matches!(&r, Err(e) if e.contains("failed unexpectedly")), "{:?}", r.err()); } /// Buffers are geodesic (#394): Web Mercator's scale changes with latitude, so one scale for @@ -13393,7 +13393,7 @@ mod tests { for p in &junk { // A panic is caught and becomes this error, which would pass unnoticed. let r = crate::run(t.id, &m, p); - assert!(!matches!(&r, Err(e) if e.ends_with("failed unexpectedly")), "{} panicked on {p}", t.id); + assert!(!matches!(&r, Err(e) if e.contains("failed unexpectedly")), "{} panicked on {p}", t.id); } } } diff --git a/crates/data/src/diagnostics.rs b/crates/data/src/diagnostics.rs index 4dc9af3795..8460a0f636 100644 --- a/crates/data/src/diagnostics.rs +++ b/crates/data/src/diagnostics.rs @@ -252,7 +252,7 @@ impl History { message: &Redacted, loss: Option, run: Option, - ) { + ) -> u64 { self.retain(Record { id: 0, timestamp_ms: timestamp_ms(), @@ -263,11 +263,12 @@ impl History { network: None, loss, run, - }); + }) } - fn retain(&self, record: Record) { - store(&mut lock(&self.0), record); + /// Keeps `record`, and gives the id it was kept under. + fn retain(&self, record: Record) -> u64 { + store(&mut lock(&self.0), record) } /// Records the state the run `id` left the project in ([`Run::after`]) on the messages it said, @@ -285,11 +286,12 @@ impl History { } } - /// Adds `details` (redacted and bounded) to the newest record: what a bug's failure keeps for a - /// report ([`crate::incident::Incident::details`]). - pub fn detail_newest(&self, details: &str) { + /// Adds `details` (redacted and bounded) to the record kept as `id`, if it still is: what a + /// bug's failure keeps for a report ([`crate::incident::Incident::details`]). By id, so a record + /// another thread keeps meanwhile isn't given them. + pub fn detail(&self, id: u64, details: &str) { let mut state = lock(&self.0); - if let Some(record) = state.records.back_mut() { + if let Some(record) = state.records.iter_mut().rev().find(|r| r.id == id) { record.details = bounded(&redact(details), MAX_DETAILS_BYTES); } state.generation = state.generation.wrapping_add(1); diff --git a/crates/data/src/incident.rs b/crates/data/src/incident.rs index 26817f0785..a09059b655 100644 --- a/crates/data/src/incident.rs +++ b/crates/data/src/incident.rs @@ -98,15 +98,22 @@ pub fn last_id() -> Option { LAST.with(|last| last.borrow().clone()) } -/// The incident a catch site caught: the one [`install`] recorded on this thread, or, without the -/// hook, one made from what was caught. +/// The incident a catch site caught: the one [`install`] recorded for this panic, or, without the +/// hook, one made from what was caught. The panic is told by its message: this thread's last one +/// when it matches (a catch site that drops what it caught leaves an older one there), else the +/// newest kept with that message, as a worker's panic raised again on its caller's thread is +/// (`analysis::parallel`), so it keeps the reference the crash log gave it. pub fn caught(payload: &(dyn std::any::Any + Send)) -> Incident { - if let Some(id) = LAST.with(|last| last.borrow_mut().take()) - && let Some(found) = find(&id) - { + let message = payload_text(payload); + let last = LAST.with(|last| last.borrow_mut().take()); + let found = last + .and_then(|id| find(&id)) + .filter(|found| found.message == message) + .or_else(|| lock(&RECENT).iter().rev().find(|i| i.message == message).cloned()); + if let Some(found) = found { return found; } - let incident = Incident { id: new_id(), message: payload_text(payload), location: None }; + let incident = Incident { id: new_id(), message, location: None }; keep(incident.clone()); incident } @@ -137,6 +144,10 @@ pub fn named_in(text: &str) -> Option<&str> { mod tests { use super::*; + fn find_by_message(message: &str) -> Option { + lock(&RECENT).iter().rev().find(|i| i.message == message).cloned() + } + #[test] fn a_caught_panic_is_an_incident_with_its_place_and_a_message_naming_it() { install(); @@ -146,12 +157,29 @@ mod tests { assert!(incident.location.as_deref().is_some_and(|at| at.contains("incident.rs")), "{incident:?}"); assert_eq!(find(&incident.id).as_ref(), Some(&incident)); let said = message("Buffer", true, &incident.id); + assert!(said.contains("failed unexpectedly"), "the words tests look for: {said}"); assert!(said.starts_with("Buffer failed unexpectedly, a bug in RustGIS (incident "), "{said}"); assert!(said.contains("the project is as it was before"), "{said}"); assert_eq!(named_in(&said), Some(incident.id.as_str())); assert!(incident.details().contains("the bug") && incident.details().contains(&incident.id)); // Caught once: the next catch on this thread doesn't take it again. assert_eq!(last_id(), None); + // Raised on another thread and caught here (a worker's, raised again on its caller), it + // keeps its reference. + let worker = std::thread::scope(|s| { + std::thread::Builder::new() + .spawn_scoped(s, || std::panic::catch_unwind(|| panic!("the worker's bug")).unwrap_err()) + .unwrap() + .join() + }) + .unwrap(); + let on_worker = find_by_message("the worker's bug"); + assert_eq!(Some(caught(worker.as_ref()).id), on_worker.map(|i| i.id)); + // A stale reference from an earlier panic, its payload dropped, isn't given to another. + let _ = std::panic::catch_unwind(|| panic!("dropped")); + let other = caught(&"a different payload"); + assert_eq!(other.message, "a different payload"); + assert_eq!(other.location, None); assert_eq!(named_in("Buffer failed: no layer"), None); } } diff --git a/crates/engine/src/cmd/connections.rs b/crates/engine/src/cmd/connections.rs index 0088f11314..42d09b2732 100644 --- a/crates/engine/src/cmd/connections.rs +++ b/crates/engine/src/cmd/connections.rs @@ -1271,7 +1271,8 @@ fn test(s: &mut Session, p: &Value) -> CmdResult { let c = tested(s, p)?; // An unsaved web service reads anonymously, whatever saved connection shares its origin. let anonymous = web::is_service(&c) && c.id.is_empty(); - web::anonymously(s, anonymous, |s| test_connection(s, p, c)).unwrap_or_else(|_| Err("connection.test failed unexpectedly".into())) + web::anonymously(s, anonymous, |s| test_connection(s, p, c)) + .unwrap_or_else(|payload| Err(crate::bug("Test Connection", payload.as_ref()))) } fn test_connection(s: &mut Session, p: &Value, c: Connection) -> CmdResult { diff --git a/crates/engine/src/cmd/embeddings.rs b/crates/engine/src/cmd/embeddings.rs index 236e607d94..4dcf466b7d 100644 --- a/crates/engine/src/cmd/embeddings.rs +++ b/crates/engine/src/cmd/embeddings.rs @@ -1014,7 +1014,7 @@ fn read_window(url: &str, area: [f64; 4], cell: Option) -> Result Result CmdResult { s.narrowed(crate::policy::Narrow::Item { kind: "task", name }, |s| run_task_steps(s, p))? } })) - .unwrap_or_else(|_| Err("the task failed unexpectedly".into())); + .unwrap_or_else(|payload| Err(crate::bug("The task", payload.as_ref()))); s.task_running = false; result } @@ -1127,7 +1127,7 @@ fn run_task_steps(s: &mut Session, p: &Value) -> CmdResult { let op = s.authorize(&st.command, &st.params)?; s.invoke(op, crate::policy::Txn::Shared) })) - .unwrap_or_else(|_| Err("failed unexpectedly".into())) + .unwrap_or_else(|payload| Err(crate::bug(&st.command, payload.as_ref()))) .map_err(|e| format!("step {} ({}): {e}", i + 1, st.title))?; done.push(json!({"step": i, "title": st.title, "result": r})); } diff --git a/crates/engine/src/cmd/notebook.rs b/crates/engine/src/cmd/notebook.rs index 4a35c145ae..8e17fd6e34 100644 --- a/crates/engine/src/cmd/notebook.rs +++ b/crates/engine/src/cmd/notebook.rs @@ -313,7 +313,7 @@ fn run(s: &mut Session, p: &Value) -> CmdResult { s.narrowed(crate::policy::Narrow::Item { kind: "notebook", name }, |s| run_cells(s, p))? } })) - .unwrap_or_else(|_| Err("the notebook failed unexpectedly".into())); + .unwrap_or_else(|payload| Err(crate::bug("The notebook", payload.as_ref()))); s.notebook_running = false; r } diff --git a/crates/engine/src/cmd/plugins.rs b/crates/engine/src/cmd/plugins.rs index 3285c83729..f6814027b7 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -1093,7 +1093,7 @@ impl Host for Between<'_> { .s .as_session_plugin(plugin.clone(), |s| { std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| bridge(s).0)) - .unwrap_or_else(|_| Err(format!("'{op}' failed unexpectedly"))) + .unwrap_or_else(|payload| Err(crate::bug(&format!("'{op}'"), payload.as_ref()))) }) .and_then(|r| r); } diff --git a/crates/engine/src/cmd/reads.rs b/crates/engine/src/cmd/reads.rs index 34f0057711..1b9d9fef15 100644 --- a/crates/engine/src/cmd/reads.rs +++ b/crates/engine/src/cmd/reads.rs @@ -235,7 +235,7 @@ pub fn scan_import( Ok(()) }) })) - .unwrap_or_else(|_| Err("Import QGIS Project failed unexpectedly".to_string())); + .unwrap_or_else(|payload| Err(crate::bug("Import QGIS Project", payload.as_ref()))); let inputs = capture.as_ref().map_or_else(Vec::new, rustgis_data::provenance::Capture::inputs); res?; scanned.map(|scan| scan.with_inputs(inputs)) diff --git a/crates/engine/src/cmd/stac_bands.rs b/crates/engine/src/cmd/stac_bands.rs index 7cd5c1421f..97bce98d47 100644 --- a/crates/engine/src/cmd/stac_bands.rs +++ b/crates/engine/src/cmd/stac_bands.rs @@ -336,12 +336,12 @@ mod desktop { // Taken as references and values, so the reader thread owns what it uses. let (stop_r, cause_r, diagnostics_r, still_r) = (&stop, &cause, &diagnostics, &still); let (signed_s, bands_n) = (signed.as_str(), *bands); - let message = format!("{href}: the read failed unexpectedly"); + let what = format!("{href}: the read"); let reader = std::thread::Builder::new().name("STAC band window".into()).spawn_scoped(scope, move || { let _diagnostics = diagnostics_r.enter(); rustgis_data::source::remote::with_optional_still(still_r.clone(), || { // A reader that panics stops the run too (the guard, unless it is disarmed on return). - let mut guard = PanicStop { stop: stop_r, cause: cause_r, message, armed: true }; + let mut guard = PanicStop { stop: stop_r, cause: cause_r, what, armed: true }; let read = read_one(signed_s, bbox, cell, bands_n, stop_r); guard.armed = false; // A file that failed stops the reads beside it: they would only finish to be dropped. @@ -363,7 +363,7 @@ mod desktop { started .into_iter() .map(|(href, signed, bands, reader)| match reader { - Ok(r) => r.join().unwrap_or_else(|_| Err(format!("{href}: the read failed unexpectedly"))), + Ok(r) => r.join().unwrap_or_else(|payload| Err(crate::bug(&format!("{href}: the read"), payload.as_ref()))), Err(_) => { // Looked at before it starts: once started, this read runs to its end. rustgis_data::progress::check().map_err(|e| e.to_string())?; @@ -392,14 +392,21 @@ mod desktop { pub(super) struct PanicStop<'a> { pub(super) stop: &'a AtomicBool, pub(super) cause: &'a std::sync::Mutex>, - pub(super) message: String, + /// What was being done (`a.tif: the read`): what failed, in the message. + pub(super) what: String, pub(super) armed: bool, } impl Drop for PanicStop<'_> { + /// Said as a bug, with the reference the panic hook gave this thread's panic, when it gave + /// one ([`rustgis_data::incident`]). fn drop(&mut self) { if self.armed { - note_failure(self.stop, self.cause, &self.message); + let message = match rustgis_data::incident::last_id() { + Some(id) => rustgis_data::incident::message(&self.what, false, &id), + None => format!("{} failed unexpectedly", self.what), + }; + note_failure(self.stop, self.cause, &message); } } } @@ -1141,17 +1148,19 @@ mod tests { // A reader that panics (the guard dropped while unwinding, still armed) stops the others. let panicked = std::thread::scope(|s| { s.spawn(|| { - let _guard = PanicStop { stop: &stop, cause: &cause, message: "a.tif: the read failed unexpectedly".into(), armed: true }; + let _guard = PanicStop { stop: &stop, cause: &cause, what: "a.tif: the read".into(), armed: true }; panic!("a reader panics"); }) .join() }); assert!(panicked.is_err()); assert!(stop.load(Ordering::Relaxed)); - assert_eq!(cause.lock().unwrap().as_deref(), Some("a.tif: the read failed unexpectedly")); + // Said as a bug: with the incident's reference when the panic hook is in. + let said = cause.lock().unwrap().clone().unwrap_or_default(); + assert!(said.starts_with("a.tif: the read failed unexpectedly"), "{said}"); // One that returned (disarmed) leaves the run alone. let (stop, cause) = (AtomicBool::new(false), Mutex::new(None)); - drop(PanicStop { stop: &stop, cause: &cause, message: "x".into(), armed: false }); + drop(PanicStop { stop: &stop, cause: &cause, what: "x".into(), armed: false }); assert!(!stop.load(Ordering::Relaxed) && cause.lock().unwrap().is_none()); } diff --git a/crates/engine/src/cmd/time.rs b/crates/engine/src/cmd/time.rs index ae6c74067d..2df8fd5e1f 100644 --- a/crates/engine/src/cmd/time.rs +++ b/crates/engine/src/cmd/time.rs @@ -364,7 +364,7 @@ fn export(s: &mut Session, p: &Value) -> CmdResult { s.map_mut().apply_time(); // The step it is back at, read here: a command after the export may read the layer. super::zarr::follow_time_now(s); - let bytes = made.map_err(|_| "exporting the time steps failed unexpectedly".to_string())??; + let bytes = made.map_err(|payload| crate::bug("Exporting the time steps", payload.as_ref()))??; rustgis_data::io::write_atomic(std::path::Path::new(&path), &bytes).map_err(|e| format!("{path}: {e}"))?; s.retain_written_notices(written); Ok(json!({"path": path, "frames": steps.len(), "bytes": bytes.len()})) diff --git a/crates/engine/src/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index 73c04673d2..de27a89dc6 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -1053,7 +1053,7 @@ impl PendingRead { crate::render::rustgis_tiles::cache::with_optional_still(self.still.clone(), || { let _diagnostic_scope = self.capture.enter(); std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| read_step(&self.zt, self.step, self.key.clone()))) - .unwrap_or_else(|_| Err(format!("{}: reading step {} failed unexpectedly", self.zt.store, self.step))) + .unwrap_or_else(|payload| Err(crate::bug(&format!("{}: reading step {}", self.zt.store, self.step), payload.as_ref()))) }) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7f29819329..9c833d6004 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -686,6 +686,13 @@ impl RoomMade { } } +/// What a bug RustGIS caught while doing `what` says ([`rustgis_data::incident::message`]), with its +/// incident's reference: the panic `payload` is told apart from a refusal, and its details kept. +pub(crate) fn bug(what: &str, payload: &(dyn std::any::Any + Send)) -> String { + let incident = rustgis_data::incident::caught(payload); + rustgis_data::incident::message(what, false, &incident.id) +} + /// What a command run worked on, as its parameters name it, for the messages it says: a layer, a /// table or an input by name, cut short. File paths are left out, as they can hold a login. fn run_target(params: &Value) -> Option { @@ -3681,12 +3688,13 @@ impl Session { if severity == rustgis_data::diagnostics::Severity::Error && self.rerun_said.iter().any(|said| said == text.as_str()) { return; } - self.diagnostics.push_redacted(severity, source.unwrap_or("Application"), &text, loss, self.run.clone()); - // A bug's failure keeps its details (the panic's message and place) under it, for a report. + let record = self.diagnostics.push_redacted(severity, source.unwrap_or("Application"), &text, loss, self.run.clone()); + // A bug's failure keeps its details (the panic's message and place) under it, for a report, + // scrubbed as a message is, logins in use included. if severity == rustgis_data::diagnostics::Severity::Error && let Some(incident) = rustgis_data::incident::named_in(text.as_str()).and_then(rustgis_data::incident::find) { - self.diagnostics.detail_newest(&incident.details()); + self.diagnostics.detail(record, Self::redacted(&incident.details()).as_str()); } self.notices.push(Notice { text: text.into_string(), From 943f877bdf5336156846ffd39351cdf52f4aed73 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 27 Nov 2026 23:09:19 -0600 Subject: [PATCH 4/7] fix(engine): background work keeps its command noted, the run marker is the user's alone, every session takes incidents, and the UI's crash catches name theirs --- apps/rustgis/src/main.rs | 56 +++++++++++++++++++++++++++--- crates/data/src/incident.rs | 45 ++++++++++++++++++------ crates/engine/src/grids.rs | 2 +- crates/engine/src/lib.rs | 6 ++-- crates/engine/src/sample.rs | 2 +- crates/plugins/src/session.rs | 2 +- crates/ui-egui/src/analysispane.rs | 2 +- crates/ui-egui/src/docpanes.rs | 2 +- crates/ui-egui/src/lib.rs | 34 ++++++++++++------ crates/ui-egui/src/reportpane.rs | 4 +-- 10 files changed, 121 insertions(+), 34 deletions(-) diff --git a/apps/rustgis/src/main.rs b/apps/rustgis/src/main.rs index 85d0b57032..0443c1d6c4 100644 --- a/apps/rustgis/src/main.rs +++ b/apps/rustgis/src/main.rs @@ -283,6 +283,9 @@ mod running { file: File, /// This run has it to itself: no other copy can take it while this one runs. locked: bool, + /// The command noted has ended, but is kept until the work it started in the background + /// has too ([`Marker::settle`]). + ended: bool, } /// Why a run has no marker: shown as it starts without autosave. @@ -333,8 +336,14 @@ mod running { pub fn start(dir: Option<&Path>) -> (Result, bool, Option) { let none = |why: String| Err(NoMarker { why, other_copy: false }); let Some(dir) = dir else { return (none("this computer has no settings folder for RustGIS".into()), false, None) }; - let file = std::fs::create_dir_all(dir) - .and_then(|_| OpenOptions::new().read(true).write(true).create(true).truncate(false).open(dir.join("running"))); + // Readable by this user only: it names the command running and what it worked on. + let file = std::fs::create_dir_all(dir).and_then(|_| { + let mut options = OpenOptions::new(); + options.read(true).write(true).create(true).truncate(false); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + options.open(dir.join("running")) + }); let mut file = match file { Ok(f) => f, Err(e) => { @@ -380,7 +389,7 @@ mod running { if let Err(e) = marked { log::warn!("could not mark this run: {e}"); } - (Ok(Marker { file, locked }), unclean, crumb) + (Ok(Marker { file, locked, ended: false }), unclean, crumb) } impl Marker { @@ -394,7 +403,24 @@ mod running { /// without closing leaves it for the next launch to say. A few bytes over the old ones; a /// write that fails leaves the marker set, as a run without a note. pub fn note(&mut self, run: Option<&rustgis_engine::data::diagnostics::Run>, at: u64) { - let text = running_text(run, at); + // A command's end is kept for [`Marker::settle`]: what it started may still run. + self.ended = run.is_none(); + if self.ended { + return; + } + self.write(&running_text(run, at)); + } + + /// Between frames: once no work runs in the background (`busy`), a command that has ended + /// is no longer noted, and the marker says only that this run is open. + pub fn settle(&mut self, busy: bool) { + if self.ended && !busy { + self.ended = false; + self.write(&running_text(None, 0)); + } + } + + fn write(&mut self, text: &str) { let written = self.file.rewind().and_then(|_| self.file.write_all(text.as_bytes())).and_then(|_| self.file.set_len(text.len() as u64)); if let Err(e) = written { @@ -424,6 +450,14 @@ mod running { } } + /// [`Marker::settle`] on a shared marker. + pub fn settle(marker: &Shared, busy: bool) { + let mut held = marker.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(m) = held.as_mut() { + m.settle(busy); + } + } + /// Clears a shared marker once. pub fn close(marker: &Shared) { let taken = marker.lock().map(|mut m| m.take()).unwrap_or_else(|poisoned| poisoned.into_inner().take()); @@ -495,6 +529,8 @@ impl eframe::App for App { self.0.session.notify(text, true); } self.0.logic(ctx); + // A command that has ended stays noted while what it started runs in the background. + running::settle(&self.1, self.0.work_under_way()); #[cfg(target_os = "macos")] self.menus(ctx); if self.0.quit_requested { @@ -972,9 +1008,19 @@ mod tests { let (second, unclean, crumb) = running::start(Some(&dir)); assert!(unclean); assert_eq!(crumb, Some(running::Breadcrumb { command: "gp.run".into(), target: Some("Parcels county".into()), at: 1_700_000_000 })); - // Between commands there is nothing to say, and a clean close says nothing at all. + // A command that ended stays noted while what it started runs on; once that is done, + // there is nothing to say, and a clean close says nothing at all. + let mut second = second.unwrap(); + second.note(Some(&run), 1_700_000_000); + second.note(None, 0); + second.settle(true); + drop(second); + let (second, unclean, crumb) = running::start(Some(&dir)); + assert!(unclean && crumb.is_some_and(|c| c.command == "gp.run"), "kept while work runs on"); let mut second = second.unwrap(); + second.note(Some(&run), 1_700_000_000); second.note(None, 0); + second.settle(false); drop(second); let (third, unclean, crumb) = running::start(Some(&dir)); assert!(unclean && crumb.is_none()); diff --git a/crates/data/src/incident.rs b/crates/data/src/incident.rs index a09059b655..b146515215 100644 --- a/crates/data/src/incident.rs +++ b/crates/data/src/incident.rs @@ -43,9 +43,18 @@ fn lock(m: &Mutex) -> MutexGuard<'_, T> { m.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } -/// A reference no other incident of this session has: the time and a count, mixed, as six -/// hexadecimal digits. +/// A reference no incident kept has: the time and a count, mixed, as six hexadecimal digits. fn new_id() -> String { + loop { + let id = mixed_id(); + if find(&id).is_none() { + return id; + } + } +} + +/// A reference from the time and a count, mixed, as six hexadecimal digits. +fn mixed_id() -> String { let n = { let mut count = lock(&COUNT); *count = count.wrapping_add(1); @@ -64,12 +73,26 @@ fn keep(incident: Incident) { recent.push_back(incident); } +/// The most of a panic's message kept: a report needs its start, and a long one stays in memory +/// until [`KEPT`] newer incidents push it out. +const MESSAGE_BYTES: usize = 4096; + +/// A panic's message, cut to [`MESSAGE_BYTES`] at a character boundary. fn payload_text(payload: &(dyn std::any::Any + Send)) -> String { - payload + let mut text = payload .downcast_ref::<&str>() .map(|s| (*s).to_string()) .or_else(|| payload.downcast_ref::().cloned()) - .unwrap_or_else(|| "a panic without a message".to_string()) + .unwrap_or_else(|| "a panic without a message".to_string()); + if text.len() > MESSAGE_BYTES { + let mut cut = MESSAGE_BYTES; + while !text.is_char_boundary(cut) { + cut -= 1; + } + text.truncate(cut); + text.push('…'); + } + text } /// Records every panic as an incident before the hook that was there runs (the app's crash log, @@ -79,12 +102,7 @@ pub fn install() { let previous = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { let id = new_id(); - let message = info - .payload() - .downcast_ref::<&str>() - .map(|s| (*s).to_string()) - .or_else(|| info.payload().downcast_ref::().cloned()) - .unwrap_or_else(|| "a panic without a message".to_string()); + let message = payload_text(info.payload()); let location = info.location().map(|l| format!("{}:{}", l.file(), l.line())); LAST.with(|last| *last.borrow_mut() = Some(id.clone())); keep(Incident { id, message, location }); @@ -133,6 +151,13 @@ pub fn message(what: &str, restored: bool, id: &str) -> String { ) } +/// What a bug caught while doing `what` says ([`message`]), its incident taken from the panic +/// `payload` ([`caught`]): for a catch site that rolls nothing back. +pub fn bug(what: &str, payload: &(dyn std::any::Any + Send)) -> String { + let incident = caught(payload); + message(what, false, &incident.id) +} + /// The reference a message from [`message`] names, if it names one. pub fn named_in(text: &str) -> Option<&str> { let (_, rest) = text.split_once("(incident ")?; diff --git a/crates/engine/src/grids.rs b/crates/engine/src/grids.rs index 2cac061e38..f9b5108e2e 100644 --- a/crates/engine/src/grids.rs +++ b/crates/engine/src/grids.rs @@ -548,7 +548,7 @@ fn fetch_now(grid: &MissingGrid) { let bytes = download(&grid.url, MAX_GRID, DOWNLOAD_TIMEOUT)?; keep(&grid.name, &bytes).map(|()| bytes.len()) }) - .unwrap_or_else(|_| Err("the download stopped unexpectedly".into())); + .unwrap_or_else(|payload| Err(crate::bug("the download", payload.as_ref()))); finish(&grid.name, got); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 9c833d6004..af40acbc67 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -689,8 +689,7 @@ impl RoomMade { /// What a bug RustGIS caught while doing `what` says ([`rustgis_data::incident::message`]), with its /// incident's reference: the panic `payload` is told apart from a refusal, and its details kept. pub(crate) fn bug(what: &str, payload: &(dyn std::any::Any + Send)) -> String { - let incident = rustgis_data::incident::caught(payload); - rustgis_data::incident::message(what, false, &incident.id) + rustgis_data::incident::bug(what, payload) } /// What a command run worked on, as its parameters name it, for the messages it says: a layer, a @@ -1463,6 +1462,9 @@ impl Session { /// Starts an independent session with fresh runtime selection intent and request order. /// Prepared script copies explicitly share request order with their originating session. pub fn new(mut project: Project) -> Self { + // Every panic an incident with a reference, whatever embeds the session (the apps, Python, + // MCP): installed once, before the hook that was there (a crash log) runs. + rustgis_data::incident::install(); // The engine's tests never add Shapefile indexes to the user's cache (#1230). #[cfg(all(test, not(target_arch = "wasm32")))] rustgis_data::source::shp::use_temporary_index_dir(); diff --git a/crates/engine/src/sample.rs b/crates/engine/src/sample.rs index 68d16c1ec3..aff313174b 100644 --- a/crates/engine/src/sample.rs +++ b/crates/engine/src/sample.rs @@ -170,7 +170,7 @@ pub(crate) fn fetch_with( if let Some((work, done)) = mine.lock().ok().and_then(|mut g| g.take()) { // A panic (a parser on hostile bytes) is the download's error, not a silent stall. let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(work)) - .unwrap_or_else(|_| Err("the download stopped unexpectedly".to_string())); + .unwrap_or_else(|payload| Err(crate::bug("the download", payload.as_ref()))); done(r); } }); diff --git a/crates/plugins/src/session.rs b/crates/plugins/src/session.rs index 2302b8b025..01a6e34784 100644 --- a/crates/plugins/src/session.rs +++ b/crates/plugins/src/session.rs @@ -318,7 +318,7 @@ fn handle(m: &Map, host: &mut dyn Host, r: &mut Running) -> Resul // A request that fails unexpectedly is an error answer, as in a WebAssembly plugin: the // program, out of the list while it's talked to, is never left running untracked. let answer = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| host.call(op, ¶ms))) - .unwrap_or_else(|_| Err(format!("'{op}' failed unexpectedly"))); + .unwrap_or_else(|payload| Err(rustgis_data::incident::bug(&format!("'{op}'"), payload.as_ref()))); let mut reply = match answer { Ok(v) => json!({"ok": v}), Err(e) => json!({"error": e}), diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index b0a305ca2a..cec34410dc 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -2011,7 +2011,7 @@ fn trend(app: &mut RustGisApp, ui: &mut Ui, rasters: &[String]) { let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { job.run(&cancel, &done).map(|rasters| (rasters, job.dates())) })) - .unwrap_or_else(|_| Err(tl!("The trend failed unexpectedly").to_string())); + .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug(tl!("The trend"), payload.as_ref()))); if let Ok(mut g) = result.lock() { *g = Some(out); } diff --git a/crates/ui-egui/src/docpanes.rs b/crates/ui-egui/src/docpanes.rs index 1c5f86595b..62d4b83e07 100644 --- a/crates/ui-egui/src/docpanes.rs +++ b/crates/ui-egui/src/docpanes.rs @@ -280,7 +280,7 @@ fn preview(app: &mut RustGisApp, ui: &mut Ui, i: usize, t: &Tokens) { let drawn_at = rustgis_engine::render::rustgis_tiles::cache::generation(); let (drawn, said) = rustgis_engine::render::shadows_said(|| { std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::cmd::presentation::draw_page(s, i, page, 30.0))) - .unwrap_or_else(|_| Err("the preview failed unexpectedly".into())) + .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("the preview", payload.as_ref()))) }); crate::layoutview::say_frame_shadows(app, &said); let tex = drawn.map(|pm| { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index af5ccc7619..88763da626 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -385,7 +385,7 @@ fn read_download( std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { rustgis_engine::cmd::raster::read_download_shared_page(name, bytes.clone(), page, place) })) - .unwrap_or_else(|_| Err(tl!("Reading the download failed unexpectedly").to_string())) + .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug(tl!("Reading the download"), payload.as_ref()))) } /// A shell's overrides of the Settings › Start-up preferences for one launch. @@ -2642,7 +2642,7 @@ impl RustGisApp { rustgis_engine::render::pdf::Options::default(), ) })) - .unwrap_or_else(|_| Err("the layout export failed unexpectedly".into())); + .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("the layout export", payload.as_ref()))); if let Err(e) = &r { self.session.notify(e.clone(), true); } @@ -3387,6 +3387,19 @@ impl RustGisApp { chrome::background_busy(self) } + /// Whether any work a command started runs on in the background: what [`background_busy`] + /// shows, a tool run or a raster made in the background. The desktop's run marker keeps the + /// command that started it until then, as that work is what most often runs out of memory. + /// + /// [`background_busy`]: RustGisApp::background_busy + pub fn work_under_way(&self) -> bool { + #[cfg(not(target_arch = "wasm32"))] + if self.gp.tool_run.is_some() { + return true; + } + self.background_busy() || self.workflow.job.is_some() + } + /// Draws that work's progress and Cancel into `ui`, as the desktop's status bar does; with a /// shell's interface in place ([`RustGisApp::chrome`]), at a finger's size. pub fn background_status(&mut self, ui: &mut egui::Ui) { @@ -5221,7 +5234,7 @@ impl RustGisApp { let bytes = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { rustgis_engine::cmd::report::report_bytes(session, i, 150.0, true) })) - .unwrap_or_else(|_| Err("the report export failed unexpectedly".into())) + .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("the report export", payload.as_ref()))) .inspect_err(|e| self.session.notify(e.clone(), true))? .0; self.download(&format!("{name}.pdf"), bytes); @@ -5311,7 +5324,7 @@ impl RustGisApp { let session = &mut self.session; let (name, bytes, notes) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::cmd::items::item_output(session, kind, p))) - .unwrap_or_else(|_| Err("saving failed unexpectedly".into())) + .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("saving", payload.as_ref()))) .inspect_err(|e| { // An area a field package made before it failed goes too. rustgis_engine::cmd::field::forget_new_areas(&mut self.session, areas); @@ -5400,7 +5413,7 @@ impl RustGisApp { let session = &mut self.session; let png = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::cmd::share::map_png_fitted(session, 192.0))) - .unwrap_or_else(|_| Err("the capture failed unexpectedly".into()))?; + .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("the capture", payload.as_ref())))?; let pm = rustgis_engine::render::decode_png(&png).ok_or("could not draw the map")?; let size = [pm.width() as usize, pm.height() as usize]; self.ui.copy_image = Some(egui::ColorImage::from_rgba_premultiplied(size, pm.data())); @@ -5430,7 +5443,7 @@ impl RustGisApp { let png = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { rustgis_engine::cmd::layout::layout_bytes(session, li, false, dpi, false) })) - .unwrap_or_else(|_| Err(tl!("the capture failed unexpectedly").into()))?; + .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug(tl!("the capture"), payload.as_ref())))?; let pm = rustgis_engine::render::decode_png(&png).ok_or_else(|| tl!("could not draw the layout").to_string())?; let size = [pm.width() as usize, pm.height() as usize]; self.ui.copy_image = Some(egui::ColorImage::from_rgba_premultiplied(size, pm.data())); @@ -5454,7 +5467,7 @@ impl RustGisApp { "ui.printMap" => { let session = &mut self.session; let pdf = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::cmd::share::map_pdf(session, 300.0))) - .unwrap_or_else(|_| Err("printing failed unexpectedly".into())) + .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("printing", payload.as_ref()))) .inspect_err(|e| self.session.notify(e.clone(), true))?; let name = format!("{}.pdf", self.session.map().name); if self.services.download.is_some() { @@ -5612,7 +5625,7 @@ impl RustGisApp { let bytes = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { rustgis_engine::cmd::presentation::export_bytes(session, i, "html", 110.0) })) - .unwrap_or_else(|_| Err("the presentation export failed unexpectedly".into())) + .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("the presentation export", payload.as_ref()))) .inspect_err(|e| self.session.notify(e.clone(), true))? .0; self.download(&format!("{name}.html"), bytes); @@ -5766,7 +5779,7 @@ impl RustGisApp { let session = &mut self.session; let png = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::cmd::share::map_png_fitted(session, 192.0))) - .unwrap_or_else(|_| Err("Export Map failed unexpectedly".into())); + .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("Export Map", payload.as_ref()))); let png = match png { Ok(p) => p, Err(e) => { @@ -6843,7 +6856,8 @@ impl RustGisApp { let read = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { rustgis_engine::cmd::layer::read_cog_window_until(&asked, &leaving) })); - let read = read.unwrap_or_else(|_| Err(tl!("Reading the window failed unexpectedly").to_string())); + let read = + read.unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug(tl!("Reading the window"), payload.as_ref()))); // Stopped by `left`: said as one given up before its turn is. A read that failed // for its own reason keeps it. read.map_err(|e| { diff --git a/crates/ui-egui/src/reportpane.rs b/crates/ui-egui/src/reportpane.rs index 2962dad612..d6cd1be416 100644 --- a/crates/ui-egui/src/reportpane.rs +++ b/crates/ui-egui/src/reportpane.rs @@ -315,7 +315,7 @@ fn preview(app: &mut RustGisApp, ui: &mut Ui, i: usize, t: &Tokens) { if app.reports.built.as_ref().is_none_or(|b| b.0 != built_for) { let s = &app.session; let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::cmd::report::pages(s, i))) - .unwrap_or_else(|_| Err("the preview failed unexpectedly".into())); + .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("the preview", payload.as_ref()))); // A failure is kept too, so it isn't retried every frame until something changes. app.reports.built = Some((built_for, built)); } @@ -336,7 +336,7 @@ fn preview(app: &mut RustGisApp, ui: &mut Ui, i: usize, t: &Tokens) { rustgis_engine::render::report::draw_page(doc, pages, page, 60.0, &s.project.layouts, &mut s.project.maps)?; Ok((pm, page, pages.len())) })) - .unwrap_or_else(|_| Err("the preview failed unexpectedly".into())) + .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("the preview", payload.as_ref()))) }); crate::layoutview::say_frame_shadows(app, &said); match drawn { From d70266a74925268b0e56341695d42074b5fe7cee Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 00:16:36 -0600 Subject: [PATCH 5/7] fix(ui): the raster job is looked at in the desktop build only --- crates/ui-egui/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 88763da626..8d15e7a3c7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3394,10 +3394,10 @@ impl RustGisApp { /// [`background_busy`]: RustGisApp::background_busy pub fn work_under_way(&self) -> bool { #[cfg(not(target_arch = "wasm32"))] - if self.gp.tool_run.is_some() { + if self.gp.tool_run.is_some() || self.workflow.job.is_some() { return true; } - self.background_busy() || self.workflow.job.is_some() + self.background_busy() } /// Draws that work's progress and Cancel into `ui`, as the desktop's status bar does; with a From 51314922e3bda8a3b28c25b0ee7a722cb7f3584c Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 01:19:06 -0600 Subject: [PATCH 6/7] fix(engine): a panic's message is kept whole and scrubbed before it's shown, the UI says a bug in its own language, inline previews say theirs once, and the run marker's mode is set on every open --- apps/rustgis/src/main.rs | 9 ++++++++- crates/data/src/incident.rs | 27 ++++++++++--------------- crates/engine/src/lib.rs | 2 +- crates/ui-egui/src/analysispane.rs | 10 ++++++++-- crates/ui-egui/src/docpanes.rs | 9 ++++++++- crates/ui-egui/src/lib.rs | 32 ++++++++++++++++++++---------- crates/ui-egui/src/reportpane.rs | 18 +++++++++++++++-- 7 files changed, 73 insertions(+), 34 deletions(-) diff --git a/apps/rustgis/src/main.rs b/apps/rustgis/src/main.rs index 0443c1d6c4..22dab12f83 100644 --- a/apps/rustgis/src/main.rs +++ b/apps/rustgis/src/main.rs @@ -342,7 +342,14 @@ mod running { options.read(true).write(true).create(true).truncate(false); #[cfg(unix)] std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); - options.open(dir.join("running")) + let file = options.open(dir.join("running"))?; + // `mode` applies only when the file is made: one an earlier version made is set too. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + file.set_permissions(std::fs::Permissions::from_mode(0o600))?; + } + Ok(file) }); let mut file = match file { Ok(f) => f, diff --git a/crates/data/src/incident.rs b/crates/data/src/incident.rs index b146515215..c7fb800291 100644 --- a/crates/data/src/incident.rs +++ b/crates/data/src/incident.rs @@ -73,26 +73,15 @@ fn keep(incident: Incident) { recent.push_back(incident); } -/// The most of a panic's message kept: a report needs its start, and a long one stays in memory -/// until [`KEPT`] newer incidents push it out. -const MESSAGE_BYTES: usize = 4096; - -/// A panic's message, cut to [`MESSAGE_BYTES`] at a character boundary. +/// A panic's message, whole: matched whole to tell one panic from another, and scrubbed whole +/// (a login cut in two isn't recognised) before Messages bounds it for showing. A session keeps +/// [`KEPT`] at most. fn payload_text(payload: &(dyn std::any::Any + Send)) -> String { - let mut text = payload + payload .downcast_ref::<&str>() .map(|s| (*s).to_string()) .or_else(|| payload.downcast_ref::().cloned()) - .unwrap_or_else(|| "a panic without a message".to_string()); - if text.len() > MESSAGE_BYTES { - let mut cut = MESSAGE_BYTES; - while !text.is_char_boundary(cut) { - cut -= 1; - } - text.truncate(cut); - text.push('…'); - } - text + .unwrap_or_else(|| "a panic without a message".to_string()) } /// Records every panic as an incident before the hook that was there runs (the app's crash log, @@ -158,6 +147,12 @@ pub fn bug(what: &str, payload: &(dyn std::any::Any + Send)) -> String { message(what, false, &incident.id) } +/// The kept incident `text` names by its reference (`… (incident 7F3A2C)…`, in any language the +/// message is said in), the newest if several. +pub fn named(text: &str) -> Option { + lock(&RECENT).iter().rev().find(|i| text.contains(&format!("{})", i.id))).cloned() +} + /// The reference a message from [`message`] names, if it names one. pub fn named_in(text: &str) -> Option<&str> { let (_, rest) = text.split_once("(incident ")?; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index af40acbc67..464b00ff0e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -3694,7 +3694,7 @@ impl Session { // A bug's failure keeps its details (the panic's message and place) under it, for a report, // scrubbed as a message is, logins in use included. if severity == rustgis_data::diagnostics::Severity::Error - && let Some(incident) = rustgis_data::incident::named_in(text.as_str()).and_then(rustgis_data::incident::find) + && let Some(incident) = rustgis_data::incident::named(text.as_str()) { self.diagnostics.detail(record, Self::redacted(&incident.details()).as_str()); } diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index cec34410dc..bfd343215f 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -2011,7 +2011,7 @@ fn trend(app: &mut RustGisApp, ui: &mut Ui, rasters: &[String]) { let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { job.run(&cancel, &done).map(|rasters| (rasters, job.dates())) })) - .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug(tl!("The trend"), payload.as_ref()))); + .unwrap_or_else(|payload| Err(crate::bug(tl!("The trend"), payload.as_ref()))); if let Ok(mut g) = result.lock() { *g = Some(out); } @@ -2059,7 +2059,13 @@ pub fn land_trend(app: &mut RustGisApp) -> bool { show_job(app, "trend", result); } Err(_) if cancelled => {} - Err(e) => show_job(app, "trend", Err(e)), + Err(e) => { + // A bug's failure, said as it lands, so Messages keeps its details. + if rustgis_engine::data::incident::named(&e).is_some() { + app.session.notify(e.clone(), true); + } + show_job(app, "trend", Err(e)) + } } false } diff --git a/crates/ui-egui/src/docpanes.rs b/crates/ui-egui/src/docpanes.rs index 62d4b83e07..c313ba6a5f 100644 --- a/crates/ui-egui/src/docpanes.rs +++ b/crates/ui-egui/src/docpanes.rs @@ -280,9 +280,16 @@ fn preview(app: &mut RustGisApp, ui: &mut Ui, i: usize, t: &Tokens) { let drawn_at = rustgis_engine::render::rustgis_tiles::cache::generation(); let (drawn, said) = rustgis_engine::render::shadows_said(|| { std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::cmd::presentation::draw_page(s, i, page, 30.0))) - .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("the preview", payload.as_ref()))) + .unwrap_or_else(|payload| Err(crate::bug("the preview", payload.as_ref()))) }); crate::layoutview::say_frame_shadows(app, &said); + // A bug's failure, said once as it's made (the pane draws it each frame), so Messages + // keeps its details. + if let Err(e) = &drawn + && rustgis_engine::data::incident::named(e).is_some() + { + app.session.notify(e.clone(), true); + } let tex = drawn.map(|pm| { let img = egui::ColorImage::from_rgba_premultiplied([pm.width() as usize, pm.height() as usize], pm.data()); ui.ctx().load_texture("presentation_preview", img, egui::TextureOptions::LINEAR) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8d15e7a3c7..1745316846 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -260,6 +260,17 @@ const LAYOUT_ARRANGEMENTS_PREF: &str = "layout_saved_arrangements"; /// A result an asynchronous service fills in when it's done (the app polls it each frame). pub type Slot = std::sync::Arc>>; +/// What a bug RustGIS caught while doing `what` says, in the interface's language, with its +/// incident's reference: the session finds the incident by it and keeps its details in Messages +/// once the text is said ([`rustgis_engine::data::incident`]). +pub(crate) fn bug(what: &str, payload: &(dyn std::any::Any + Send)) -> String { + let incident = rustgis_engine::data::incident::caught(payload); + crate::i18n::fmt( + "{what} failed unexpectedly, a bug in RustGIS (incident {id}). The details are in Messages; please include them in a bug report", + &[("what", what), ("id", &incident.id)], + ) +} + /// Runs `work` on a thread of its own named `name`, off the frame. When the system refuses one, /// `slot` gets the refusal as its error instead and `work` is dropped unrun, so the job ends with /// an error rather than the app (AGENTS.md › Use the threads). In the browser, which has no @@ -385,7 +396,7 @@ fn read_download( std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { rustgis_engine::cmd::raster::read_download_shared_page(name, bytes.clone(), page, place) })) - .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug(tl!("Reading the download"), payload.as_ref()))) + .unwrap_or_else(|payload| Err(crate::bug(tl!("Reading the download"), payload.as_ref()))) } /// A shell's overrides of the Settings › Start-up preferences for one launch. @@ -2642,7 +2653,7 @@ impl RustGisApp { rustgis_engine::render::pdf::Options::default(), ) })) - .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("the layout export", payload.as_ref()))); + .unwrap_or_else(|payload| Err(crate::bug("the layout export", payload.as_ref()))); if let Err(e) = &r { self.session.notify(e.clone(), true); } @@ -5234,7 +5245,7 @@ impl RustGisApp { let bytes = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { rustgis_engine::cmd::report::report_bytes(session, i, 150.0, true) })) - .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("the report export", payload.as_ref()))) + .unwrap_or_else(|payload| Err(crate::bug("the report export", payload.as_ref()))) .inspect_err(|e| self.session.notify(e.clone(), true))? .0; self.download(&format!("{name}.pdf"), bytes); @@ -5324,7 +5335,7 @@ impl RustGisApp { let session = &mut self.session; let (name, bytes, notes) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::cmd::items::item_output(session, kind, p))) - .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("saving", payload.as_ref()))) + .unwrap_or_else(|payload| Err(crate::bug("saving", payload.as_ref()))) .inspect_err(|e| { // An area a field package made before it failed goes too. rustgis_engine::cmd::field::forget_new_areas(&mut self.session, areas); @@ -5413,7 +5424,7 @@ impl RustGisApp { let session = &mut self.session; let png = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::cmd::share::map_png_fitted(session, 192.0))) - .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("the capture", payload.as_ref())))?; + .unwrap_or_else(|payload| Err(crate::bug("the capture", payload.as_ref())))?; let pm = rustgis_engine::render::decode_png(&png).ok_or("could not draw the map")?; let size = [pm.width() as usize, pm.height() as usize]; self.ui.copy_image = Some(egui::ColorImage::from_rgba_premultiplied(size, pm.data())); @@ -5443,7 +5454,7 @@ impl RustGisApp { let png = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { rustgis_engine::cmd::layout::layout_bytes(session, li, false, dpi, false) })) - .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug(tl!("the capture"), payload.as_ref())))?; + .unwrap_or_else(|payload| Err(crate::bug(tl!("the capture"), payload.as_ref())))?; let pm = rustgis_engine::render::decode_png(&png).ok_or_else(|| tl!("could not draw the layout").to_string())?; let size = [pm.width() as usize, pm.height() as usize]; self.ui.copy_image = Some(egui::ColorImage::from_rgba_premultiplied(size, pm.data())); @@ -5467,7 +5478,7 @@ impl RustGisApp { "ui.printMap" => { let session = &mut self.session; let pdf = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::cmd::share::map_pdf(session, 300.0))) - .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("printing", payload.as_ref()))) + .unwrap_or_else(|payload| Err(crate::bug("printing", payload.as_ref()))) .inspect_err(|e| self.session.notify(e.clone(), true))?; let name = format!("{}.pdf", self.session.map().name); if self.services.download.is_some() { @@ -5625,7 +5636,7 @@ impl RustGisApp { let bytes = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { rustgis_engine::cmd::presentation::export_bytes(session, i, "html", 110.0) })) - .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("the presentation export", payload.as_ref()))) + .unwrap_or_else(|payload| Err(crate::bug("the presentation export", payload.as_ref()))) .inspect_err(|e| self.session.notify(e.clone(), true))? .0; self.download(&format!("{name}.html"), bytes); @@ -5779,7 +5790,7 @@ impl RustGisApp { let session = &mut self.session; let png = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::cmd::share::map_png_fitted(session, 192.0))) - .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("Export Map", payload.as_ref()))); + .unwrap_or_else(|payload| Err(crate::bug("Export Map", payload.as_ref()))); let png = match png { Ok(p) => p, Err(e) => { @@ -6856,8 +6867,7 @@ impl RustGisApp { let read = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { rustgis_engine::cmd::layer::read_cog_window_until(&asked, &leaving) })); - let read = - read.unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug(tl!("Reading the window"), payload.as_ref()))); + let read = read.unwrap_or_else(|payload| Err(crate::bug(tl!("Reading the window"), payload.as_ref()))); // Stopped by `left`: said as one given up before its turn is. A read that failed // for its own reason keeps it. read.map_err(|e| { diff --git a/crates/ui-egui/src/reportpane.rs b/crates/ui-egui/src/reportpane.rs index d6cd1be416..0e612a839a 100644 --- a/crates/ui-egui/src/reportpane.rs +++ b/crates/ui-egui/src/reportpane.rs @@ -315,7 +315,14 @@ fn preview(app: &mut RustGisApp, ui: &mut Ui, i: usize, t: &Tokens) { if app.reports.built.as_ref().is_none_or(|b| b.0 != built_for) { let s = &app.session; let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::cmd::report::pages(s, i))) - .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("the preview", payload.as_ref()))); + .unwrap_or_else(|payload| Err(crate::bug("the preview", payload.as_ref()))); + // A bug's failure, said once as it's made (the pane draws it each frame), so Messages + // keeps its details. + if let Err(e) = &built + && rustgis_engine::data::incident::named(e).is_some() + { + app.session.notify(e.clone(), true); + } // A failure is kept too, so it isn't retried every frame until something changes. app.reports.built = Some((built_for, built)); } @@ -336,9 +343,16 @@ fn preview(app: &mut RustGisApp, ui: &mut Ui, i: usize, t: &Tokens) { rustgis_engine::render::report::draw_page(doc, pages, page, 60.0, &s.project.layouts, &mut s.project.maps)?; Ok((pm, page, pages.len())) })) - .unwrap_or_else(|payload| Err(rustgis_engine::data::incident::bug("the preview", payload.as_ref()))) + .unwrap_or_else(|payload| Err(crate::bug("the preview", payload.as_ref()))) }); crate::layoutview::say_frame_shadows(app, &said); + // A bug's failure, said once as it's made (the pane draws it each frame), so Messages + // keeps its details. + if let Err(e) = &drawn + && rustgis_engine::data::incident::named(e).is_some() + { + app.session.notify(e.clone(), true); + } match drawn { Ok((pm, page, total)) => { app.reports.page = page; From cbddee202ddc8ed691ee4989219a4d95bf121602 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 02:32:26 -0600 Subject: [PATCH 7/7] fix(ui): say a failed report page once and keep the trend's language A page that fails to draw is kept for its report, page and revision, so it isn't drawn and said again each frame; the trend worker uses the interface's language for a bug's message. --- crates/ui-egui/src/analysispane.rs | 3 +++ crates/ui-egui/src/reportpane.rs | 12 +++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index bfd343215f..f09f5245ef 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -2006,7 +2006,10 @@ fn trend(app: &mut RustGisApp, ui: &mut Ui, rasters: &[String]) { // A panic on the thread (a hostile store) lands as an error, so the run always ends; // a thread the system can't start is said. let diagnostics = app.session.diagnostics.capture(); + // The interface's language, which is the thread's own: a bug's message is in it. + let lang = crate::i18n::current(); let spawned = std::thread::Builder::new().name("trend".into()).spawn(move || { + crate::i18n::set_current(lang); let _diagnostics = diagnostics.enter(); let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { job.run(&cancel, &done).map(|rasters| (rasters, job.dates())) diff --git a/crates/ui-egui/src/reportpane.rs b/crates/ui-egui/src/reportpane.rs index 0e612a839a..f0e739711e 100644 --- a/crates/ui-egui/src/reportpane.rs +++ b/crates/ui-egui/src/reportpane.rs @@ -14,6 +14,9 @@ pub struct ReportState { pub page: usize, /// The preview: what it shows (report JSON and page), its texture and the page count. pub preview: Option<(String, egui::TextureHandle, usize)>, + /// A page that failed to draw, for the report, page and project revision it was drawn for: not + /// drawn again, nor said again, until one of them changes. + pub failed_draw: Option<(String, String)>, /// The built report and its pages, for the report and project revision they were built from: /// turning pages only redraws a page, it doesn't rebuild the report. pub built: Option<((usize, u64), Result<(rustgis_engine::map::report::Doc, Vec), String>)>, @@ -334,6 +337,12 @@ fn preview(app: &mut RustGisApp, ui: &mut Ui, i: usize, t: &Tokens) { } None => return, }; + if let Some((failed, e)) = &app.reports.failed_draw + && *failed == key + { + ui.label(egui::RichText::new(e.as_str()).small().color(Color32::from_rgb(0xC0, 0x30, 0x30))); + return; + } let (s, page) = (&mut app.session, app.reports.page); let drawn_at = rustgis_engine::render::rustgis_tiles::cache::generation(); let (drawn, said) = rustgis_engine::render::shadows_said(|| { @@ -362,7 +371,8 @@ fn preview(app: &mut RustGisApp, ui: &mut Ui, i: usize, t: &Tokens) { app.reports.preview = Some((crate::layoutview::preview_key(&key, &said, drawn_at), tex, total)); } Err(e) => { - ui.label(egui::RichText::new(e).small().color(Color32::from_rgb(0xC0, 0x30, 0x30))); + ui.label(egui::RichText::new(e.as_str()).small().color(Color32::from_rgb(0xC0, 0x30, 0x30))); + app.reports.failed_draw = Some((key, e)); return; } }