From 72cef1a00a0fe77e260088ee6b58b579b17a2441 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 13:43:25 -0600 Subject: [PATCH 1/3] feat(cli): run --strict stops at a loss a job does not allow (#2371) `rustgis-cli run --strict` stops after the first command that reports a classified loss no `--allow ` accepts, before later commands and `--save`, and exits with status 3, listing each loss by code with what to do. A failed command's losses that outlive its rollback count too. The loss registry declares each code once, giving `LossCode::ALL` and `from_id`; the command line guide lists every code, checked by a test. `Session::losses_given` counts loss notices per code beyond the notice queue's 200, so a strict run can't miss one. --- ROADMAP.md | 7 +- apps/rustgis-cli/src/main.rs | 135 ++++++++++++++++--- apps/rustgis-cli/tests/integration/main.rs | 1 + apps/rustgis-cli/tests/integration/strict.rs | 116 ++++++++++++++++ crates/data/src/loss.rs | 127 ++++++++++++----- crates/engine/src/lib.rs | 26 +++- crates/engine/src/tests.rs | 20 +++ docs/cli.md | 35 +++++ 8 files changed, 414 insertions(+), 53 deletions(-) create mode 100644 apps/rustgis-cli/tests/integration/strict.rs diff --git a/ROADMAP.md b/ROADMAP.md index 81fba75c7a..f75c93154d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -88,10 +88,9 @@ A result is right, or RustGIS says what it lost or assumed error-cell losses for XLSX; other loss kinds remain. XLSM shares the XLSX parser; macros are untested. Exports are checked by `never_silent_roundtrip.rs` _(open)_. -- Loss notices classified by code so scheduled jobs can detect them (the engine carries codes - through reader and tool results today; the remaining notices are to migrate). Then - `rustgis-cli run --strict`, which exits non-zero on a disallowed loss, and the codes exposed - to Python and MCP ([#2371](https://github.com/opengeos/RustGIS/issues/2371)). +- The remaining loss notices classified by code (the engine carries codes through reader and + tool results today), so `rustgis-cli run --strict` stops at them, and the codes exposed to + Python and MCP ([#2371](https://github.com/opengeos/RustGIS/issues/2371)). - NTv2 grid shifts named in a file's own definition (a WKT or PROJ string that binds NAD27 to WGS 84 through a `.gsb` grid), which are said but not applied today (the grids PROJ's operations use are applied when present and downloaded on request). _Coordinate first_ (needs diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index 75c1d45ce7..d38bbad0f8 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -9,6 +9,7 @@ //! --cmd 'gp.run={"tool":"buffer","params":{"input":"Cities","distance":100}}' \ //! --cmd 'share.exportMap={"path":"out.png"}' [--save out.rgis] //! rustgis-cli run … --use-saved-secrets # use what the desktop app saved in the system keychain +//! rustgis-cli run … --strict [--allow dropped.ring] # exit 3 when a command loses data (see the guide's loss codes) //! rustgis-cli run … --threads 4 # the most threads one piece of work uses (default: the cores, up to 16) //! rustgis-cli ask [--sample | --project p.rgis | --data f.geojson …] "Which cities have over 10 million people?" \ //! [--provider anthropic|openai|chatgpt|gemini|openrouter|ollama|custom|requesty|trustedrouter|opper] [--model M] [--base-url URL] [--yes] [--save out.rgis] [--trace log.txt] @@ -42,13 +43,14 @@ macro_rules! out { } use rustgis_assistant::{Config, provider}; +use rustgis_engine::data::loss::{LossCode, LossKind}; use rustgis_engine::data::secrets::SecretStore; use rustgis_engine::{Project, Session}; use serde_json::{Map, Value, json}; fn usage() -> ExitCode { eprintln!( - "usage:\n rustgis-cli commands | tools\n rustgis-cli plugins [install | uninstall | enable | disable | browse | get | prepare ] [--registry URL]\n rustgis-cli skills [add | remove | enable | disable ]\n rustgis-cli info \n rustgis-cli logo [--size N] [--canvas WxH --at X,Y (.bmp only)]\n rustgis-cli render [--basemap NAME] [--tiles URL] [--width N] [--height N] [--dpi N] [--worldview auto|default|CODE] [--worldview-detail simplified|original]\n rustgis-cli run [--sample] [--project P] [--data F]… --cmd 'id={{json}}'… [--save P] [--worldview auto|default|CODE] [--worldview-detail simplified|original]\n rustgis-cli ask [--sample] [--project P] [--data F]… \"request\" [--image PICTURE]… [--provider P] [--model M] [--base-url URL] [--yes] [--save P]\n rustgis-cli ask --models [--provider P]\n rustgis-cli ask --login [--another-account] [--account CLIENT_ID] | --logout\n rustgis-cli ask --accounts | --account CLIENT_ID | --remove-account CLIENT_ID\n common options: --use-saved-secrets (use the connections, passwords, keys, ChatGPT sign-in and Earthdata Login token the RustGIS app saved; reads the system keychain), --threads N (the most threads one piece of work uses, 1-1024; default: the cores, up to 16)\n rustgis-cli mcp [--sample] [--project P] [--data F]… [--yes] [--attach [PORT] [--token-file FILE] [--timeout SECONDS (5-600)]]\n rustgis-cli mcp-register [--client claude] [--name NAME] [--port PORT]" + "usage:\n rustgis-cli commands | tools\n rustgis-cli plugins [install | uninstall | enable | disable | browse | get | prepare ] [--registry URL]\n rustgis-cli skills [add | remove | enable | disable ]\n rustgis-cli info \n rustgis-cli logo [--size N] [--canvas WxH --at X,Y (.bmp only)]\n rustgis-cli render [--basemap NAME] [--tiles URL] [--width N] [--height N] [--dpi N] [--worldview auto|default|CODE] [--worldview-detail simplified|original]\n rustgis-cli run [--sample] [--project P] [--data F]… --cmd 'id={{json}}'… [--save P] [--strict [--allow KIND|CODE]…] [--worldview auto|default|CODE] [--worldview-detail simplified|original]\n rustgis-cli ask [--sample] [--project P] [--data F]… \"request\" [--image PICTURE]… [--provider P] [--model M] [--base-url URL] [--yes] [--save P]\n rustgis-cli ask --models [--provider P]\n rustgis-cli ask --login [--another-account] [--account CLIENT_ID] | --logout\n rustgis-cli ask --accounts | --account CLIENT_ID | --remove-account CLIENT_ID\n common options: --use-saved-secrets (use the connections, passwords, keys, ChatGPT sign-in and Earthdata Login token the RustGIS app saved; reads the system keychain), --threads N (the most threads one piece of work uses, 1-1024; default: the cores, up to 16)\n rustgis-cli mcp [--sample] [--project P] [--data F]… [--yes] [--attach [PORT] [--token-file FILE] [--timeout SECONDS (5-600)]]\n rustgis-cli mcp-register [--client claude] [--name NAME] [--port PORT]" ); ExitCode::from(2) } @@ -111,6 +113,98 @@ fn prepare_env(id: &str) -> Result { Ok(python.display().to_string()) } +/// The exit status of a run `--strict` stopped because a command lost data it doesn't allow. +const LOSS_EXIT: u8 = 3; + +/// `run --strict`: the run stops after the first command that reports a loss of a kind or code +/// no `--allow` accepts, before the commands after it and the final save. +struct Strict { + allow: Vec, + /// Whether a loss stopped the run, so it exits with [`LOSS_EXIT`]. + stopped: std::cell::Cell, +} + +impl Strict { + /// Reads `--strict` and each `--allow `: `None` without `--strict`. + fn from_args(cmd: &str, args: &[String]) -> Result, String> { + if args.iter().any(|a| a.starts_with("--strict=")) { + return Err("--strict takes no value; accept losses with --allow".into()); + } + let strict = args.iter().any(|a| a == "--strict"); + let mut allow = Vec::new(); + // `--allow X`, or `--allow=X` as `--threads=N` is read. + for (i, a) in args.iter().enumerate() { + let v = match a.strip_prefix("--allow=") { + Some(v) => Some(v), + None if a == "--allow" => args.get(i + 1).map(String::as_str).filter(|v| !v.starts_with("--")), + None => continue, + }; + let Some(v) = v.filter(|v| !v.is_empty()) else { + return Err("--allow needs a loss kind or code, such as dropped or dropped.ring".into()); + }; + if LossKind::from_id(v).is_none() && LossCode::from_id(v).is_none() { + let kinds: Vec<&str> = LossKind::ALL.iter().map(|k| k.id()).collect(); + return Err(format!("--allow {v}: not a loss kind ({}) or code (listed in the command line guide)", kinds.join(", "))); + } + allow.push(v.to_string()); + } + if (strict || !allow.is_empty()) && cmd != "run" { + return Err("--strict and --allow apply to run".into()); + } + if !strict { + return if allow.is_empty() { Ok(None) } else { Err("--allow needs --strict".into()) }; + } + Ok(Some(Strict { allow, stopped: std::cell::Cell::new(false) })) + } + + /// Whether an `--allow` names this code or its kind (`dropped` allows `dropped.ring`). + fn allows(&self, code: LossCode) -> bool { + let spec = code.spec(); + self.allow.iter().any(|a| a == spec.id || a == spec.kind.id()) + } + + /// Stops the run when `id` reported a loss this run doesn't allow: `before` is + /// [`Session::losses_given`] from before it ran, so no loss escapes however much it said. + fn check(&self, s: &Session, before: &[(LossCode, u64)], id: &str) -> Result<(), String> { + let lost: Vec<(LossCode, u64)> = s + .losses_given() + .iter() + .filter(|(code, _)| !self.allows(*code)) + .filter_map(|&(code, n)| { + let was = before.iter().find(|(c, _)| *c == code).map_or(0, |(_, n)| *n); + (n > was).then_some((code, n - was)) + }) + .collect(); + if lost.is_empty() { + return Ok(()); + } + self.stopped.set(true); + let mut said = format!("--strict: stopped after {id}, which reported a loss no --allow accepts:"); + for (code, n) in lost { + let spec = code.spec(); + let notices = if n == 1 { "1 notice".to_string() } else { format!("{n} notices") }; + said.push_str(&format!("\n {} ({notices}): {}", spec.id, spec.action)); + } + Err(said) + } +} + +/// [`run`], then [`Strict::check`] when the run is strict: after a failure too, as a failed +/// command still reports the losses that outlive its rollback (a counted omission). +fn run_strict(s: &mut Session, strict: Option<&Strict>, id: &str, p: Value) -> Result { + let before = strict.map(|_| s.losses_given().to_vec()); + let out = run(s, id, p); + if let (Some(strict), Some(before)) = (strict, before) + && let Err(said) = strict.check(s, &before, id) + { + return Err(match out { + Err(e) => format!("{e}\n{said}"), + Ok(_) => said, + }); + } + out +} + fn is_project(path: &str) -> bool { rustgis_engine::project::opens_as_project(path) } @@ -119,28 +213,29 @@ fn num(args: &[String], name: &str) -> Option { opt(args, name).and_then(|v| v.parse::().ok()).filter(|v| v.is_finite()) } -fn load(s: &mut Session, path: &str) -> Result<(), String> { +/// Opens a project, or adds any other file as a layer; `strict` only from `run`. +fn load(s: &mut Session, strict: Option<&Strict>, path: &str) -> Result<(), String> { if is_project(path) { - run(s, "project.open", json!({"path": path}))?; + run_strict(s, strict, "project.open", json!({"path": path}))?; } else { - run(s, "layer.addData", json!({"path": path}))?; + run_strict(s, strict, "layer.addData", json!({"path": path}))?; } Ok(()) } /// Opens `--sample`, `--project` and every `--data`. -fn open_inputs(s: &mut Session, args: &[String]) -> Result<(), String> { +fn open_inputs(s: &mut Session, strict: Option<&Strict>, args: &[String]) -> Result<(), String> { if args.iter().any(|a| a == "--sample") { - run(s, "project.sample", Value::Null)?; + run_strict(s, strict, "project.sample", Value::Null)?; } if let Some(p) = opt(args, "--project") { - load(s, p)?; + load(s, strict, p)?; } for (i, a) in args.iter().enumerate() { if a == "--data" && let Some(p) = args.get(i + 1) { - load(s, p)?; + load(s, strict, p)?; } } Ok(()) @@ -743,6 +838,13 @@ fn cli() -> ExitCode { } let args: Vec = std::env::args().skip(1).collect(); let Some(cmd) = args.first().map(|s| s.as_str()) else { return usage() }; + let strict = match Strict::from_args(cmd, &args) { + Ok(strict) => strict, + Err(e) => { + eprintln!("rustgis-cli: {e}"); + return ExitCode::from(2); + } + }; if !args.iter().any(|a| a == "--no-plugins") { for e in rustgis_engine::cmd::plugins::load_installed() { eprintln!("rustgis-cli: warning: {e}"); @@ -870,7 +972,7 @@ fn cli() -> ExitCode { } "info" => { let path = args.get(1).ok_or("info needs a file")?; - load(&mut s, path)?; + load(&mut s, None, path)?; print(&run(&mut s, "info.project", Value::Null)?); Ok(()) } @@ -917,7 +1019,7 @@ fn cli() -> ExitCode { } "render" => { let (Some(input), Some(out)) = (args.get(1), args.get(2)) else { return Err("render needs ".into()) }; - load(&mut s, input)?; + load(&mut s, None, input)?; if let Some(b) = opt(&args, "--basemap") { run(&mut s, "map.basemap", json!({"name": b}))?; } @@ -936,7 +1038,7 @@ fn cli() -> ExitCode { Ok(()) } "ask" => { - open_inputs(&mut s, &args)?; + open_inputs(&mut s, None, &args)?; // What the assistant did is saved even when it couldn't finish. let asked = ask(&mut s, &args, saved.as_ref(), &Environment::process()); if let Some(p) = opt(&args, "--save") @@ -948,7 +1050,7 @@ fn cli() -> ExitCode { } "mcp" => { if !args.iter().any(|a| a == "--attach") { - open_inputs(&mut s, &args)?; + open_inputs(&mut s, None, &args)?; } mcp(&mut s, &args) } @@ -959,7 +1061,8 @@ fn cli() -> ExitCode { // calling it may have a timeout, and keeps the caps. s.long_runs = Some(progress); s.stoppable = std::io::stdin().is_terminal() && std::io::stderr().is_terminal(); - open_inputs(&mut s, &args)?; + let strict = strict.as_ref(); + open_inputs(&mut s, strict, &args)?; for (i, a) in args.iter().enumerate() { if a == "--cmd" && let Some(c) = args.get(i + 1) @@ -968,14 +1071,14 @@ fn cli() -> ExitCode { Some((id, json)) => (id, serde_json::from_str(json).map_err(|e| format!("{id}: bad JSON: {e}"))?), None => (c.as_str(), Value::Null), }; - let out = run(&mut s, id, p)?; + let out = run_strict(&mut s, strict, id, p)?; if !out.is_null() { print(&out); } } } if let Some(p) = opt(&args, "--save") { - run(&mut s, "project.saveAs", json!({"path": p}))?; + run_strict(&mut s, strict, "project.saveAs", json!({"path": p}))?; } Ok(()) } @@ -985,7 +1088,7 @@ fn cli() -> ExitCode { Ok(()) => ExitCode::SUCCESS, Err(e) => { eprintln!("rustgis-cli: {e}"); - ExitCode::FAILURE + if strict.is_some_and(|strict| strict.stopped.get()) { ExitCode::from(LOSS_EXIT) } else { ExitCode::FAILURE } } } } diff --git a/apps/rustgis-cli/tests/integration/main.rs b/apps/rustgis-cli/tests/integration/main.rs index 153a8d7ede..70567ba870 100644 --- a/apps/rustgis-cli/tests/integration/main.rs +++ b/apps/rustgis-cli/tests/integration/main.rs @@ -3,4 +3,5 @@ mod memory_override; mod reproducible_exports; mod saved_secrets; +mod strict; mod threads; diff --git a/apps/rustgis-cli/tests/integration/strict.rs b/apps/rustgis-cli/tests/integration/strict.rs new file mode 100644 index 0000000000..fa319cd350 --- /dev/null +++ b/apps/rustgis-cli/tests/integration/strict.rs @@ -0,0 +1,116 @@ +//! `run --strict` stops at the first command that loses data no `--allow` accepts (#2371). + +use std::process::{Command, Output}; + +/// Removes the test's folder even when an assertion fails. +struct TempDir(std::path::PathBuf); + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn cli(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_rustgis-cli")).args(["run", "--no-plugins"]).args(args).output().unwrap() +} + +/// A GeoRSS feed of one polygon with this hole. +fn feed(hole: &str) -> String { + format!( + r#"ti0 0 0 4 4 4 0 0{hole}"# + ) +} + +#[test] +fn a_strict_run_stops_at_a_loss_it_does_not_allow() { + let dir = TempDir(std::env::temp_dir().join(format!("rustgis-cli-strict-{}", std::process::id()))); + std::fs::create_dir_all(&dir.0).unwrap(); + let lossy = dir.0.join("lossy.rss"); + let clean = dir.0.join("clean.rss"); + std::fs::write(&lossy, feed("1 x")).unwrap(); + std::fs::write(&clean, feed("1 1 1 2 2 2 1 1")).unwrap(); + let saved = dir.0.join("out.rgis"); + let (lossy, clean, saved) = (lossy.to_str().unwrap(), clean.to_str().unwrap(), saved.to_str().unwrap()); + let run = |input: &str, strict: &[&str]| { + let _ = std::fs::remove_file(saved); + let mut args = vec!["--data", input, "--cmd", "gp.threads", "--save", saved]; + args.extend(strict); + let out = cli(&args); + (out.status.code(), String::from_utf8_lossy(&out.stderr).into_owned(), !out.stdout.is_empty(), std::path::Path::new(saved).exists()) + }; + + // Without --strict the loss is said and the run goes on. + let (code, err, printed, wrote) = run(lossy, &[]); + assert_eq!((code, printed, wrote), (Some(0), true, true), "{err}"); + // Strict: it stops after reading, before the next command and the save, and says the code. + let (code, err, printed, wrote) = run(lossy, &["--strict"]); + assert_eq!((code, printed, wrote), (Some(3), false, false), "{err}"); + assert!(err.contains("stopped after layer.addData") && err.contains("dropped.ring (1 notice): Correct the unreadable"), "{err}"); + // Allowed by its code or its kind, it runs to the end; another kind doesn't allow it. + for allow in [&["--allow", "dropped.ring"][..], &["--allow", "dropped"], &["--allow=dropped.ring"]] { + let (code, err, _, wrote) = run(lossy, &[&["--strict"][..], allow].concat()); + assert_eq!((code, wrote), (Some(0), true), "{allow:?}: {err}"); + } + let (code, err, _, _) = run(lossy, &["--strict", "--allow", "changed"]); + assert_eq!(code, Some(3), "{err}"); + // Clean input passes. + let (code, err, printed, wrote) = run(clean, &["--strict"]); + assert_eq!((code, printed, wrote), (Some(0), true, true), "{err}"); +} + +#[test] +fn a_strict_run_stops_at_a_command_that_loses_data() { + let out = cli(&[ + "--strict", + "--cmd", + r#"layer.addDataText={"fileName":"records.csv","text":"n\n1\n2\n"}"#, + "--cmd", + r#"edit.enable={"on":true}"#, + "--cmd", + r#"edit.calculateField={"table":"records","field":"n","expression":"n + 1.5"}"#, + "--cmd", + "gp.threads", + ]); + let err = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(3), "{err}"); + assert!(err.contains("stopped after edit.calculateField") && err.contains("changed.truncated (1 notice)"), "{err}"); + let printed = String::from_utf8_lossy(&out.stdout); + assert!(!printed.contains("\"cores\""), "the command after it didn't run: {printed}"); +} + +/// A failed command still reports the losses its rollback can't take back (a counted omission): +/// strict says them and exits 3, after the failure. +#[test] +fn a_strict_run_reports_the_losses_of_a_command_that_failed() { + const WMS: &str = r#" +Test WMS +image/png +EPSG:3857roadsRoads +"#; + let legend = format!("https://maps.example.com/legends/{}.png", "a".repeat(5000)); + let add = serde_json::json!({"url": "https://maps.example.com/wms", "layer": "roads", "text": WMS.replace("LEGEND", &legend)}); + let fail = serde_json::json!({"fileName": "broken.geojson", "text": "{"}); + let script = serde_json::json!({"script": format!("service.add {add}\nlayer.addDataText {fail}")}); + let out = cli(&["--strict", "--cmd", &format!("script.run={script}")]); + let err = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(3), "{err}"); + assert!(err.contains("stopped after script.run") && err.contains("dropped.legend (1 notice)"), "{err}"); +} + +#[test] +fn allow_takes_a_known_kind_or_code_and_needs_strict() { + for (args, said) in [ + (&["--strict", "--allow", "dropped.everything"][..], "--allow dropped.everything: not a loss kind"), + (&["--strict", "--allow"][..], "--allow needs a loss kind or code"), + (&["--allow", "dropped"][..], "--allow needs --strict"), + (&["--strict", "--allow=dropped.everything"][..], "--allow dropped.everything: not a loss kind"), + (&["--strict", "--allow="][..], "--allow needs a loss kind or code"), + (&["--strict=yes"][..], "--strict takes no value"), + ] { + let out = cli(&[args, &["--cmd", "gp.threads"]].concat()); + let err = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(2), "{args:?}: {err}"); + assert!(err.contains(said), "{args:?}: {err}"); + } +} diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index 1834882787..4149d044ba 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -1,4 +1,8 @@ //! Shared classification for data-loss notices, independent of their wording. +//! +//! A code's identifier is public: scripts match on it (`rustgis-cli run --strict --allow`), so it +//! is never translated, renamed or reused. The command line guide lists every code, checked by +//! `the_guide_lists_every_code`. /// What happened to the data. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -10,6 +14,9 @@ pub enum LossKind { } impl LossKind { + /// Every kind, in the order the guide lists them. + pub const ALL: [LossKind; 4] = [Self::Dropped, Self::Changed, Self::Approximated, Self::Assumed]; + /// A language-independent name for this kind of loss. pub const fn id(self) -> &'static str { match self { @@ -19,19 +26,61 @@ impl LossKind { Self::Assumed => "assumed", } } + + /// The kind this identifier names. + pub fn from_id(id: &str) -> Option { + Self::ALL.into_iter().find(|kind| kind.id() == id) + } } -/// The specific cause of a loss. Add causes here so producers use the same code for the same loss. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[non_exhaustive] -pub enum LossCode { - DroppedLegend, - DroppedRing, - DroppedExtraAttributes, - DroppedTime, - DroppedValue, - DroppedCalculationResult, - ChangedTruncated, +/// Declares the codes once, so the list of every code can't miss one. +macro_rules! loss_codes { + ($($code:ident => ($id:literal, $kind:ident, $action:literal),)*) => { + /// The specific cause of a loss. Add causes here so producers use the same code for the + /// same loss. + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + #[non_exhaustive] + pub enum LossCode { + $($code,)* + } + + impl LossCode { + /// Every code, in the order they are declared. + pub const ALL: &'static [LossCode] = &[$(Self::$code,)*]; + + /// The registry entry that supplies the untranslated identifier and remediation. + pub const fn spec(self) -> LossSpec { + match self { + $(Self::$code => LossSpec { id: $id, kind: LossKind::$kind, action: $action },)* + } + } + } + }; +} + +loss_codes! { + DroppedLegend => ("dropped.legend", Dropped, "Use a service with short HTTP or HTTPS addresses for its legend pictures."), + DroppedRing => ("dropped.ring", Dropped, "Correct the unreadable polygon ring in the source."), + DroppedExtraAttributes => ( + "dropped.extra-attributes", + Dropped, + "Add fields for the extra attribute values or remove those values from the input." + ), + DroppedTime => ("dropped.time", Dropped, "Write to a date-time field to keep the time of day."), + DroppedValue => ("dropped.value", Dropped, "Correct the value or use a destination field that can hold it."), + DroppedCalculationResult => ( + "dropped.calculation-result", + Dropped, + "Correct the expression or check the input rows named in the notice." + ), + ChangedTruncated => ("changed.truncated", Changed, "Use a decimal field to keep the fractional part."), +} + +impl LossCode { + /// The code this identifier names. + pub fn from_id(id: &str) -> Option { + Self::ALL.iter().copied().find(|code| code.spec().id == id) + } } /// A code's identifier, effect on the data, and what the user can do about it. @@ -41,30 +90,44 @@ pub struct LossSpec { pub action: &'static str, } -impl LossCode { - /// The registry entry that supplies the untranslated identifier and remediation. - pub const fn spec(self) -> LossSpec { - use LossKind::{Changed, Dropped}; - let (id, kind, action) = match self { - Self::DroppedRing => ("dropped.ring", Dropped, "Correct the unreadable polygon ring in the source."), - Self::DroppedExtraAttributes => { - ("dropped.extra-attributes", Dropped, "Add fields for the extra attribute values or remove those values from the input.") - } - Self::DroppedLegend => ("dropped.legend", Dropped, "Use a service with short HTTP or HTTPS addresses for its legend pictures."), - Self::DroppedTime => ("dropped.time", Dropped, "Write to a date-time field to keep the time of day."), - Self::DroppedValue => ("dropped.value", Dropped, "Correct the value or use a destination field that can hold it."), - Self::DroppedCalculationResult => { - ("dropped.calculation-result", Dropped, "Correct the expression or check the input rows named in the notice.") - } - Self::ChangedTruncated => ("changed.truncated", Changed, "Use a decimal field to keep the fractional part."), - }; - LossSpec { id, kind, action } - } -} - /// A message produced at the point a reader or tool detects a loss. #[derive(Clone, Debug, PartialEq, Eq)] pub struct LossMessage { pub code: LossCode, pub text: String, } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn codes_are_unique_and_named_after_their_kind() { + for (i, code) in LossCode::ALL.iter().enumerate() { + let spec = code.spec(); + assert!(spec.id.starts_with(&format!("{}.", spec.kind.id())), "{} is not under {}", spec.id, spec.kind.id()); + assert!(LossCode::ALL[..i].iter().all(|other| other.spec().id != spec.id), "{} is declared twice", spec.id); + assert_eq!(LossCode::from_id(spec.id), Some(*code)); + } + assert_eq!(LossCode::from_id("dropped"), None); + assert_eq!(LossKind::from_id("assumed"), Some(LossKind::Assumed)); + assert_eq!(LossKind::from_id("dropped.ring"), None); + } + + #[test] + fn the_guide_lists_every_code() { + let guide = include_str!("../../../docs/cli.md").replace("\r\n", "\n"); + let section = guide.split("\n### Loss codes\n").nth(1).unwrap_or_default(); + let section = section.split("\n#").next().unwrap_or_default(); + let rows: Vec<&str> = section.lines().filter(|l| l.starts_with("| `")).collect(); + for code in LossCode::ALL { + let spec = code.spec(); + let row = format!("| `{}` | {} |", spec.id, spec.action); + assert!(rows.contains(&row.as_str()), "docs/cli.md: the loss codes should list\n{row}"); + } + for row in rows { + let id = row.trim_start_matches("| `").split('`').next().unwrap_or_default(); + assert!(LossCode::from_id(id).is_some(), "docs/cli.md lists `{id}`, which is not a loss code"); + } + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index df455d2b99..dd84b8b25c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -904,6 +904,9 @@ pub struct Session { /// Notices given in this session, including ones no longer kept (see [`Session::notices_since`]), /// less those a failed command withdrew. notices_given: u64, + /// Loss notices given in this session by code, including ones no longer kept, less those a + /// failed command withdrew (see [`Session::losses_given`]). + losses_given: Vec<(rustgis_data::loss::LossCode, u64)>, /// Whether the outermost command now running has said that a zoom couldn't reach its place; /// `None` between commands. Its inner steps would each say it (a zoom refused by each layer an /// add frames): it is said once in a command, however many notices come after. @@ -1458,6 +1461,7 @@ impl Session { bundled_roots_said: false, diagnostics: rustgis_data::diagnostics::History::default(), notices_given: 0, + losses_given: Vec::new(), beyond_said: None, crs_notes_said: Vec::new(), grid_pairs: Vec::new(), @@ -2477,7 +2481,12 @@ impl Session { if withdrawn.iter().any(|n| !n.error && !n.written && n.text == BEYOND_PROJECTION) && self.beyond_said == Some(true) { self.beyond_said = Some(false); } - let kept: Vec = withdrawn.into_iter().filter(|n| n.error || n.written).collect(); + let (kept, gone): (Vec, Vec) = withdrawn.into_iter().partition(|n| n.error || n.written); + for code in gone.iter().filter_map(Notice::loss) { + if let Some(given) = self.losses_given.iter_mut().find(|(c, _)| *c == code) { + given.1 = given.1.saturating_sub(1); + } + } self.notices_given -= (new - kept.len()) as u64; self.notices.extend(kept); let mut recorded_failure = false; @@ -3478,6 +3487,12 @@ impl Session { loss, }); self.notices_given += 1; + if let Some(code) = loss { + match self.losses_given.iter_mut().find(|(c, _)| *c == code) { + Some(given) => given.1 = given.1.saturating_add(1), + None => self.losses_given.push((code, 1)), + } + } if self.notices.len() > 200 { self.notices.remove(0); } @@ -3493,6 +3508,15 @@ impl Session { self.notices_given } + /// How many loss notices this session has given for each code, including those the notice + /// queue no longer keeps: compare two of these to learn what a run lost, however much it said. + /// A failed command's losses are taken back with its changes, except one whose notice the + /// queue had already let go: which of those described a committed write isn't kept, so it + /// stays counted, erring towards a loss. + pub fn losses_given(&self) -> &[(rustgis_data::loss::LossCode, u64)] { + &self.losses_given + } + /// The notices given since `mark` was taken (those still kept): what a command said beside its /// result, for front ends without a status bar (the CLI, the MCP server, the AI Assistant). pub fn notices_since(&self, mark: u64) -> &[Notice] { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 992012c363..8b5e5e1901 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -646,6 +646,26 @@ fn scoped_table_writes_need_prepared_worker_results() { assert_eq!(serde_json::to_value(&s.project.tables).unwrap(), before); } +#[test] +fn losses_given_counts_what_the_notice_queue_no_longer_keeps() { + use rustgis_data::loss::LossCode; + let mut s = Session::new(Project::default()); + s.notify_loss(LossCode::DroppedRing, String::from("a ring").into()); + for i in 0..300 { + s.notify(format!("notice {i}"), false); + } + assert!(s.notices_since(0).iter().all(|n| n.loss().is_none()), "the loss notice left the queue"); + assert_eq!(s.losses_given(), &[(LossCode::DroppedRing, 1)]); + // A loss a failed command reported is withdrawn with what it changed. + let failed = s.guarded("Lose then fail", true, |s| { + s.notify_loss(LossCode::DroppedRing, String::from("another ring").into()); + s.notify_loss(LossCode::DroppedValue, String::from("a value").into()); + Err("failed after the loss".into()) + }); + assert!(failed.is_err()); + assert_eq!(s.losses_given(), &[(LossCode::DroppedRing, 1), (LossCode::DroppedValue, 0)]); +} + #[test] fn a_standalone_table_is_edited_with_the_edit_commands() { let mut s = world(); diff --git a/docs/cli.md b/docs/cli.md index 598af9afc7..867a8363d5 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -130,6 +130,41 @@ rustgis-cli run --data dem.tif \
A map exported by rustgis-cli, with no window open.
+### Strict runs + +A notice that says a command lost data carries a loss code, such as `dropped.ring`, that stays the +same however its wording changes. `run --strict` stops after the first command that reports a +loss with a code that no `--allow` accepts, and exits with status 3, before the commands after it +and before `--save`. That command, including a failed one, has already run: a file it wrote, or the +project `--save` wrote when the save itself reported the loss, is already there. Standard error +lists each loss by code, with how many notices reported it and what to do about it. Other failures +still exit with status 1. + +Repeat `--allow` to accept the losses a job expects, by kind (`dropped`, `changed`, `approximated` +or `assumed`) or by code: + +```sh +rustgis-cli run --strict --allow dropped.ring --data storms.rss \ + --cmd 'share.exportMap={"path":"storms.png"}' +``` + +An `--allow` that names no kind or code is refused with status 2, as is `--allow` without +`--strict`. A code is never renamed or reused, so a job can match on it. + +### Loss codes + +| Code | What to do | +|---|---| +| `dropped.legend` | Use a service with short HTTP or HTTPS addresses for its legend pictures. | +| `dropped.ring` | Correct the unreadable polygon ring in the source. | +| `dropped.extra-attributes` | Add fields for the extra attribute values or remove those values from the input. | +| `dropped.time` | Write to a date-time field to keep the time of day. | +| `dropped.value` | Correct the value or use a destination field that can hold it. | +| `dropped.calculation-result` | Correct the expression or check the input rows named in the notice. | +| `changed.truncated` | Use a decimal field to keep the fractional part. | + +Not every loss has a code yet: losses still reported without one don't stop a strict run. + ## Asking the AI assistant `ask` gives the [AI Assistant](user-guide/assistant.md) one request. It loads data like `run`, From f8be5e1099139b8c906bd69dff09e641633e5da5 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 13:48:50 -0600 Subject: [PATCH 2/3] test(cli): the strict failure report keeps the failure; guide says some losses have codes --- apps/rustgis-cli/tests/integration/strict.rs | 1 + docs/cli.md | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/rustgis-cli/tests/integration/strict.rs b/apps/rustgis-cli/tests/integration/strict.rs index fa319cd350..a19e85985e 100644 --- a/apps/rustgis-cli/tests/integration/strict.rs +++ b/apps/rustgis-cli/tests/integration/strict.rs @@ -96,6 +96,7 @@ fn a_strict_run_reports_the_losses_of_a_command_that_failed() { let err = String::from_utf8_lossy(&out.stderr); assert_eq!(out.status.code(), Some(3), "{err}"); assert!(err.contains("stopped after script.run") && err.contains("dropped.legend (1 notice)"), "{err}"); + assert!(err.contains("line 2: layer.addDataText"), "the failure is said too: {err}"); } #[test] diff --git a/docs/cli.md b/docs/cli.md index 867a8363d5..42ad492fa5 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -132,8 +132,8 @@ rustgis-cli run --data dem.tif \ ### Strict runs -A notice that says a command lost data carries a loss code, such as `dropped.ring`, that stays the -same however its wording changes. `run --strict` stops after the first command that reports a +Some notices that say a command lost data carry a loss code, such as `dropped.ring`, that stays +the same however their wording changes. `run --strict` stops after the first command that reports a loss with a code that no `--allow` accepts, and exits with status 3, before the commands after it and before `--save`. That command, including a failed one, has already run: a file it wrote, or the project `--save` wrote when the save itself reported the loss, is already there. Standard error From 2f1241b26fc780d9ab6cde02cf9183407b272d9d Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 15:02:54 -0600 Subject: [PATCH 3/3] fix(engine): counted losses past the kind cap keep their code A loss counted after 32 other counted notices in one command went into an uncoded overflow warning, so `run --strict` passed it. The overflow is now kept per cause: each code flushes its own coded notice, and unclassified advisories keep the uncoded one. --- apps/rustgis-cli/src/main.rs | 1 + crates/engine/src/lib.rs | 29 +++++++++++++++++++---------- crates/engine/src/parameters.rs | 15 ++++++++++----- docs/cli.md | 3 ++- 4 files changed, 32 insertions(+), 16 deletions(-) diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index d38bbad0f8..8587a9e391 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -182,6 +182,7 @@ impl Strict { let mut said = format!("--strict: stopped after {id}, which reported a loss no --allow accepts:"); for (code, n) in lost { let spec = code.spec(); + // A counted notice says how many it lost in its text; this counts the notices. let notices = if n == 1 { "1 notice".to_string() } else { format!("{n} notices") }; said.push_str(&format!("\n {} ({notices}): {}", spec.id, spec.action)); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index dd84b8b25c..01c7fdbacd 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -896,7 +896,9 @@ pub struct Session { /// Counted losses await the outermost guard's cleanup, including failed nested commands. /// Runtime-only: never in Project, undo or PutAside, so replacement cannot erase them. loss_notices: Vec, - loss_notice_overflow: u32, + /// Occurrences past [`MAX_LOSS_NOTICE_KINDS`], by cause (`None` for unclassified advisories), + /// so a strict run still sees the code: at most one entry per code. + loss_notice_overflow: Vec<(Option, u32)>, /// Whether this session has said that native HTTPS trusts the bundled CA roots (#1591). bundled_roots_said: bool, /// Troubleshooting history, independent of the active pane, project files and undo. @@ -1457,7 +1459,7 @@ impl Session { on_window_thread: false, notices: Vec::new(), loss_notices: Vec::new(), - loss_notice_overflow: 0, + loss_notice_overflow: Vec::new(), bundled_roots_said: false, diagnostics: rustgis_data::diagnostics::History::default(), notices_given: 0, @@ -3420,8 +3422,10 @@ impl Session { loss.text = text(loss.count); } else if self.loss_notices.len() < MAX_LOSS_NOTICE_KINDS { self.loss_notices.push(LossNotice { code, template, count, text: text(count), source: self.diagnostic_source }); + } else if let Some(over) = self.loss_notice_overflow.iter_mut().find(|(c, _)| *c == code) { + over.1 = over.1.saturating_add(count); } else { - self.loss_notice_overflow = self.loss_notice_overflow.saturating_add(count); + self.loss_notice_overflow.push((code, count)); } } @@ -3430,10 +3434,14 @@ impl Session { for loss in std::mem::take(&mut self.loss_notices) { self.publish_counted(loss.text, loss.code, loss.source); } - let overflow = std::mem::take(&mut self.loss_notice_overflow); - if overflow > 0 { - // The overflow count may combine several causes and unclassified advisories. - self.warn(format!("{overflow} further counted notice occurrence(s) could not be described")); + for (code, n) in std::mem::take(&mut self.loss_notice_overflow) { + match code { + Some(code) => { + let text = Self::redacted(&format!("{n} further {} occurrence(s) could not be described", code.spec().id)); + self.publish_counted(text, Some(code), self.diagnostic_source); + } + None => self.warn(format!("{n} further counted notice occurrence(s) could not be described")), + } } } @@ -3510,9 +3518,10 @@ impl Session { /// How many loss notices this session has given for each code, including those the notice /// queue no longer keeps: compare two of these to learn what a run lost, however much it said. - /// A failed command's losses are taken back with its changes, except one whose notice the - /// queue had already let go: which of those described a committed write isn't kept, so it - /// stays counted, erring towards a loss. + /// A failed command's losses are taken back with its changes, except counted losses + /// ([`Session::notify_counted`]), which outlive its rollback, and one whose notice the queue + /// had already let go: which of those described a committed write isn't kept, so it stays + /// counted, erring towards a loss. pub fn losses_given(&self) -> &[(rustgis_data::loss::LossCode, u64)] { &self.losses_given } diff --git a/crates/engine/src/parameters.rs b/crates/engine/src/parameters.rs index b95ac5a5a3..1e81523309 100644 --- a/crates/engine/src/parameters.rs +++ b/crates/engine/src/parameters.rs @@ -147,7 +147,7 @@ mod tests { } #[test] - fn counted_notice_overflow_warns_without_assigning_a_cause() { + fn counted_notice_overflow_keeps_each_cause() { use rustgis_data::{diagnostics::Severity, loss::LossCode}; let mut session = crate::Session::new(crate::Project::default()); session @@ -164,12 +164,17 @@ mod tests { source: None, }); s.notify_counted(Some(LossCode::DroppedLegend), "{n} omitted legends", 2); + s.notify_counted(Some(LossCode::DroppedLegend), "{n} other omitted legends", 1); + s.notify_counted(None, "{n} other advisories", 4); Ok(Value::Null) }) .unwrap(); - let overflow = session.notices.last().unwrap(); - assert_eq!(overflow.text, "2 further counted notice occurrence(s) could not be described"); - assert_eq!(overflow.severity, Severity::Warning); - assert_eq!(overflow.loss(), None); + // Past the cap each cause still says its code, so a strict run sees it. + let [.., legends, advisories] = session.notices.as_slice() else { panic!("expected the overflow notices") }; + assert_eq!(legends.text, "3 further dropped.legend occurrence(s) could not be described"); + assert_eq!((legends.severity, legends.loss()), (Severity::Warning, Some(LossCode::DroppedLegend))); + assert_eq!(advisories.text, "4 further counted notice occurrence(s) could not be described"); + assert_eq!((advisories.severity, advisories.loss()), (Severity::Warning, None)); + assert_eq!(session.losses_given(), &[(LossCode::DroppedLegend, 1)]); } } diff --git a/docs/cli.md b/docs/cli.md index 42ad492fa5..c72b40e588 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -137,7 +137,8 @@ the same however their wording changes. `run --strict` stops after the first com loss with a code that no `--allow` accepts, and exits with status 3, before the commands after it and before `--save`. That command, including a failed one, has already run: a file it wrote, or the project `--save` wrote when the save itself reported the loss, is already there. Standard error -lists each loss by code, with how many notices reported it and what to do about it. Other failures +lists each loss by code, with how many notices reported it (each notice says how much it lost) +and what to do about it. Other failures still exit with status 1. Repeat `--allow` to accept the losses a job expects, by kind (`dropped`, `changed`, `approximated`