From 1c21814368f5479300088c011c6af62ea5e7afde Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 18:19:54 -0600 Subject: [PATCH 01/21] feat(python): loss codes as Python warnings and MCP losses (#2371) Python raises each notice with a loss code as a warning, a subclass of rustgis.DataLossWarning per kind with `code` and `kind`, so warning filters can turn losses into errors. MCP, Assistant and file-bridge results carry `losses` ({code, kind, text, action}) beside `notices`. --- ROADMAP.md | 4 +- .../rustgis-python/python/rustgis/__init__.py | 108 ++++++++++++++++-- .../python/rustgis/_rustgis.pyi | 1 + apps/rustgis-python/src/lib.rs | 50 +++++++- apps/rustgis-python/tests/test_session.py | 43 +++++++ crates/assistant/src/filebridge.rs | 6 +- crates/assistant/src/mcp.rs | 6 +- crates/assistant/src/tools.rs | 67 ++++++++++- docs/mcp.md | 6 +- docs/python.md | 18 +++ 10 files changed, 283 insertions(+), 26 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 36f1d7f202..e3742b8c88 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -89,8 +89,8 @@ A result is right, or RustGIS says what it lost or assumed XLSM shares the XLSX parser; macros are untested. Exports are checked by `never_silent_roundtrip.rs` _(open)_. - 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)). + tool results today), so `rustgis-cli run --strict`, Python's warnings and MCP's `losses` see + them ([#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-python/python/rustgis/__init__.py b/apps/rustgis-python/python/rustgis/__init__.py index d530c4e6d9..67a3f5a45e 100644 --- a/apps/rustgis-python/python/rustgis/__init__.py +++ b/apps/rustgis-python/python/rustgis/__init__.py @@ -27,11 +27,86 @@ from ._rustgis import RustGISError, __version__ from ._rustgis import load_plugins as _load_plugins -__all__ = ["Layer", "Map", "RustGISError", "Session", "__version__", "load_plugins"] +__all__ = [ + "ApproximatedWarning", + "AssumedWarning", + "ChangedWarning", + "DataLossWarning", + "DroppedWarning", + "Layer", + "Map", + "RustGISError", + "Session", + "__version__", + "load_plugins", +] PathLike = Union[str, "os.PathLike[str]"] +class DataLossWarning(UserWarning): + """A command lost data: it dropped, changed, approximated or assumed something. + + Raised through :mod:`warnings` for each notice that carries a loss code, so + ``warnings.filterwarnings("error", category=rustgis.DataLossWarning)`` turns a loss into + an exception. The notice also stays in :meth:`Session.notices`. + + Attributes: + code: The loss code, such as ``"dropped.ring"``: never translated, renamed or reused. + The command line guide lists every code with what to do about it. + kind: The code's kind: ``"dropped"``, ``"changed"``, ``"approximated"`` or ``"assumed"``. + """ + + def __init__(self, message: str, code: str) -> None: + """Keeps the notice's text as the message, and its code. + + Args: + message: The notice's text. + code: The loss code. + """ + super().__init__(message) + self.code = code + self.kind = code.split(".", 1)[0] + + +class DroppedWarning(DataLossWarning): + """Something in the input isn't in the result (``dropped.*`` codes).""" + + +class ChangedWarning(DataLossWarning): + """A value is in the result but different (``changed.*`` codes).""" + + +class ApproximatedWarning(DataLossWarning): + """The result stands in for something it couldn't represent exactly (``approximated.*``).""" + + +class AssumedWarning(DataLossWarning): + """The data didn't say, so RustGIS picked (``assumed.*`` codes).""" + + +_LOSS_WARNINGS = { + "dropped": DroppedWarning, + "changed": ChangedWarning, + "approximated": ApproximatedWarning, + "assumed": AssumedWarning, +} + +# Warnings point at the caller's line, not at this package's. +_PACKAGE = (os.path.dirname(__file__),) + + +def _warn_losses(engine: _Engine) -> None: + """Raises each loss the engine reported since the last call as a :class:`DataLossWarning`. + + Args: + engine: The session's engine. + """ + for kind, code, text in engine._take_losses(): + category = _LOSS_WARNINGS.get(kind, DataLossWarning) + warnings.warn(category(f"{text} [{code}]", code), skip_file_prefixes=_PACKAGE) + + def __getattr__(name: str) -> Any: """Imports ``Map`` on first use, so the package works without the notebook widget's dependencies. @@ -847,7 +922,11 @@ def run(self, command: str, params: Optional[Dict[str, Any]] = None, /, **kwargs encoded = json.dumps(merged, default=_jsonable, allow_nan=False) if merged else "" except ValueError as e: raise ValueError(f"{command}: parameters must be finite numbers, text, lists and dicts ({e})") from e - text = self._engine.run(command, encoded) + try: + text = self._engine.run(command, encoded) + finally: + # A failed command can still have lost data it can't take back. + _warn_losses(self._engine) return json.loads(text) def notices(self) -> List[Tuple[str, bool]]: @@ -866,7 +945,10 @@ def _layer_geojson(self, layer: int, selected: bool) -> str: layer: The layer's id. selected: Only its selected features. """ - return self._engine.layer_geojson(layer, selected) + try: + return self._engine.layer_geojson(layer, selected) + finally: + _warn_losses(self._engine) def _root(self) -> "Session": """The session that holds the project: this one.""" @@ -888,7 +970,10 @@ def project_json(self) -> str: Returns: The JSON text; ``run("project.openText", text=...)`` opens it. """ - return self._engine.project_json() + try: + return self._engine.project_json() + finally: + _warn_losses(self._engine) # Maps ---------------------------------------------------------------------------------- @@ -911,13 +996,16 @@ def to_png( Returns: The PNG bytes. """ - png = bytes( - self._engine.render_png( - None if width is None else float(width), - None if height is None else float(height), - None if dpi is None else float(dpi), + try: + png = bytes( + self._engine.render_png( + None if width is None else float(width), + None if height is None else float(height), + None if dpi is None else float(dpi), + ) ) - ) + finally: + _warn_losses(self._engine) if path is not None: with open(path, "wb") as f: f.write(png) diff --git a/apps/rustgis-python/python/rustgis/_rustgis.pyi b/apps/rustgis-python/python/rustgis/_rustgis.pyi index a3fd762080..221514eb4f 100644 --- a/apps/rustgis-python/python/rustgis/_rustgis.pyi +++ b/apps/rustgis-python/python/rustgis/_rustgis.pyi @@ -13,5 +13,6 @@ class Engine: def layer_geojson(self, layer: Union[int, str], selected: bool = False) -> str: ... def project_json(self) -> str: ... def take_notices(self) -> List[Tuple[str, bool]]: ... + def _take_losses(self) -> List[Tuple[str, str, str]]: ... def load_plugins() -> List[str]: ... diff --git a/apps/rustgis-python/src/lib.rs b/apps/rustgis-python/src/lib.rs index 28372e9887..ffc2f7dd77 100644 --- a/apps/rustgis-python/src/lib.rs +++ b/apps/rustgis-python/src/lib.rs @@ -11,6 +11,7 @@ use pyo3::create_exception; use pyo3::exceptions::{PyException, PyValueError}; use pyo3::prelude::*; use pyo3::types::PyBytes; +use rustgis_engine::data::loss::LossCode; use rustgis_engine::{Project, Session}; use serde_json::Value; use std::io::Write; @@ -84,6 +85,9 @@ struct Engine { /// What the session's store reported (the first failure of the keychain, a preferences file /// that couldn't be read), waiting to be logged by the call that is running or the next one. diagnostics: Arc>>, + /// Classified losses not yet raised as warnings, and where collecting them last stopped (the + /// notice mark and the session's loss counts). Only locked inside the session's lock. + losses: Mutex, } impl Engine { @@ -104,8 +108,39 @@ impl Engine { } } +/// See [`Engine::losses`]. +struct Losses { + pending: Vec<(String, String, String)>, + mark: u64, + given: Vec<(LossCode, u64)>, +} + +impl Losses { + /// Sets aside the losses `session` gave since the last call, while their notices are still in + /// its queue (before `take_notices` drains it). One the queue no longer keeps (past its last + /// 200) is set aside as one entry per code that says how many. + fn collect(&mut self, session: &Session) { + let kept: Vec<(LossCode, String)> = + session.notices_since(self.mark).iter().filter_map(|n| n.loss().map(|code| (code, n.text.clone()))).collect(); + for &(code, given) in session.losses_given() { + let was = self.given.iter().find(|(c, _)| *c == code).map_or(0, |(_, n)| *n); + let held = kept.iter().filter(|(c, _)| *c == code).count() as u64; + let lost = given.saturating_sub(was).saturating_sub(held); + if lost > 0 { + let spec = code.spec(); + self.pending.push((spec.kind.id().into(), spec.id.into(), format!("{lost} further {} notice(s) were not kept", spec.id))); + } + } + self.pending.extend(kept.into_iter().map(|(code, text)| (code.spec().kind.id().into(), code.spec().id.into(), text))); + self.mark = session.notice_mark(); + self.given = session.losses_given().to_vec(); + } +} + #[pymethods] impl Engine { + /// An empty session; `use_saved_secrets` reads the desktop app's saved connections, and + /// asks the system keychain for a secret only when a command needs one. #[new] #[pyo3(signature = (use_saved_secrets=false))] fn new(py: Python<'_>, use_saved_secrets: bool) -> Self { @@ -121,7 +156,8 @@ impl Engine { } session }); - let engine = Engine { session: Mutex::new(session), diagnostics }; + let losses = Losses { pending: Vec::new(), mark: session.notice_mark(), given: session.losses_given().to_vec() }; + let engine = Engine { session: Mutex::new(session), diagnostics, losses: Mutex::new(losses) }; engine.flush(py); engine } @@ -270,12 +306,24 @@ impl Engine { result.map_err(RustGISError::new_err) } + /// The classified losses given since the last call, as `(kind, code, text)`, oldest first, + /// which the package raises as warnings; `take_notices` still returns them too. + fn _take_losses(&self, py: Python<'_>) -> Vec<(String, String, String)> { + let losses = &self.losses; + self.with_session(py, |session| { + let mut losses = losses.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + losses.collect(session); + std::mem::take(&mut losses.pending) + }) + } + /// The notices commands have given since the last call (a file's warnings, a tool's /// summary): `(text, is_error)` pairs, oldest first. fn take_notices(&self, py: Python<'_>) -> Vec<(String, bool)> { let notices: Vec<(String, bool)> = self.with_session(py, |session| { // A client made on a background thread since the last command may have chosen the trust. session.notice_trust(); + self.losses.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).collect(session); session.notices.drain(..).map(|n| (n.text, n.error)).collect() }); self.flush(py); diff --git a/apps/rustgis-python/tests/test_session.py b/apps/rustgis-python/tests/test_session.py index 3173d13af0..908b3f3126 100644 --- a/apps/rustgis-python/tests/test_session.py +++ b/apps/rustgis-python/tests/test_session.py @@ -119,6 +119,49 @@ def test_data_files(tmp_path): assert s.layers()[0]["features"] == 2 +def _feed(hole): + """A GeoRSS feed of one polygon with this hole.""" + return ( + 'ti' + "0 0 0 4 4 4 0 0" + f"{hole}" + "" + ) + + +def test_losses_are_warnings_with_their_code(tmp_path): + lossy, clean = tmp_path / "lossy.rss", tmp_path / "clean.rss" + lossy.write_text(_feed("1 x")) + clean.write_text(_feed("1 1 1 2 2 2 1 1")) + s = rustgis.Session() + with pytest.warns(rustgis.DroppedWarning, match=r"\[dropped\.ring\]") as seen: + s.add_data(lossy) + [warning] = [w for w in seen if issubclass(w.category, rustgis.DataLossWarning)] + assert (warning.message.code, warning.message.kind) == ("dropped.ring", "dropped") + assert warning.filename == __file__, "the warning points at the caller's line" + text = str(warning.message).removesuffix(" [dropped.ring]") + assert (text, False) in s.notices(), "the notice is kept too" + # Python's filters decide: an error filter raises it, after the command ran. + with warnings.catch_warnings(): + warnings.filterwarnings("error", category=rustgis.DataLossWarning) + with pytest.raises(rustgis.DroppedWarning): + s.add_data(lossy) + assert len(s.layers()) == 2 + s.add_data(clean) + # A command's loss: a fraction written to a whole-number field. + s.run("layer.addDataText", fileName="records.csv", text="n\n1\n2\n") + s.run("edit.enable", on=True) + with pytest.warns(rustgis.ChangedWarning) as seen: + s.run("edit.calculateField", table="records", field="n", expression="n + 1.5") + assert [w.message.code for w in seen if issubclass(w.category, rustgis.DataLossWarning)] == ["changed.truncated"] + s.notices() + with warnings.catch_warnings(record=True) as seen: + warnings.simplefilter("always") + s.run("edit.calculateField", table="records", field="n", expression="n + 1") + assert not [w for w in seen if issubclass(w.category, rustgis.DataLossWarning)] + + @pytest.mark.parametrize("as_text", [False, True]) def test_pmtiles_options_survive_a_project_round_trip(as_text): """The Python names reach the engine, including JSON-text styles and extensionless URLs.""" diff --git a/crates/assistant/src/filebridge.rs b/crates/assistant/src/filebridge.rs index 05e862a5b8..5a3fa84170 100644 --- a/crates/assistant/src/filebridge.rs +++ b/crates/assistant/src/filebridge.rs @@ -312,7 +312,7 @@ impl FileBridge { let reply = text.and_then(|r| serde_json::from_str::(&r).ok()).unwrap_or(Value::Null); result_of(&reply, started.elapsed()) } - Err(e) => json!({"success": false, "result": null, "error": e, "notices": [], "duration_s": 0.0}), + Err(e) => json!({"success": false, "result": null, "error": e, "notices": [], "losses": [], "duration_s": 0.0}), }; let secs = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); if let Some(o) = outcome.as_object_mut() { @@ -351,7 +351,7 @@ fn read_script(path: &Path) -> Result { } /// The result file's JSON from the `run` tool's reply: `{success, result, error, notices, -/// duration_s}`. A refusal (plain text, not the tool's JSON) is the error. +/// losses, duration_s}`. A refusal (plain text, not the tool's JSON) is the error. fn result_of(reply: &Value, took: Duration) -> Value { let text = reply.pointer("/result/content/0/text").and_then(Value::as_str).unwrap_or(""); let is_error = reply.pointer("/result/isError") == Some(&Value::Bool(true)); @@ -364,7 +364,7 @@ fn result_of(reply: &Value, took: Duration) -> Value { text.to_string() }; json!({"success": !is_error && reply.get("error").is_none() && !text.is_empty(), "result": null, "error": error, "notices": [], - "duration_s": (took.as_secs_f64() * 1000.0).round() / 1000.0}) + "losses": [], "duration_s": (took.as_secs_f64() * 1000.0).round() / 1000.0}) } } } diff --git a/crates/assistant/src/mcp.rs b/crates/assistant/src/mcp.rs index 47f7e17fee..2df36d538e 100644 --- a/crates/assistant/src/mcp.rs +++ b/crates/assistant/src/mcp.rs @@ -481,12 +481,14 @@ fn read_only(name: &str) -> bool { !matches!(name, "run_command" | "run_tool" | "run" | "snapshot") } +/// The tools `tools/list` offers: the assistant's, with MCP's own wording where the server's +/// rules differ (`--yes`), and MCP's own tools (`run`, `snapshot`). fn tool_list() -> Vec { let mut out: Vec = tools::defs() .into_iter() .map(|d| { let description = match d.name { - "run_command" => "Run a RustGIS command by id with JSON parameters (see search_commands for ids and parameters). Each run that changes the project is one undo step (edit.undo undoes it). Commands that read or write files or use the network run only when the server was started with --yes.".to_string(), + "run_command" => "Run a RustGIS command by id with JSON parameters (see search_commands for ids and parameters). Each run that changes the project is one undo step (edit.undo undoes it). Commands that read or write files or use the network run only when the server was started with --yes. A notice that reports lost data is also in the result's losses, as {code, kind, text, action}; for an assumed.* code, ask the user rather than guess.".to_string(), "read_doc" => { let pages: Vec<&str> = docs::PAGES.iter().map(|p| p.path).collect(); format!("Read a RustGIS documentation page or section as Markdown. Use next_offset to continue budgeted results. Pages: {}.", pages.join(", ")) @@ -498,7 +500,7 @@ fn tool_list() -> Vec { .collect(); out.push(json!({ "name": "run", - "description": "Run several RustGIS commands in one call, as one undo step (none when its lines only read the project, moved the view, exported, left a request, or ran a command that reports it changed nothing, such as a move to where the layers already are; a line that sets a value to the one it has still counts): a script with one `command-id {json}` per line (# starts a comment), e.g. `map.basemap {\"name\": \"ocean\"}`. A failing line stops the script, nothing it did to the project is kept (a file an earlier line wrote stays written), and the error names the line. Returns {success, result (the last command's), lines, layersAdded, notices, error, duration_s}. Each line follows the same rules as run_command.", + "description": "Run several RustGIS commands in one call, as one undo step (none when its lines only read the project, moved the view, exported, left a request, or ran a command that reports it changed nothing, such as a move to where the layers already are; a line that sets a value to the one it has still counts): a script with one `command-id {json}` per line (# starts a comment), e.g. `map.basemap {\"name\": \"ocean\"}`. A failing line stops the script, nothing it did to the project is kept (a file an earlier line wrote stays written), and the error names the line. Returns {success, result (the last command's), lines, layersAdded, notices, losses ({code, kind, text, action} for each notice that reports lost data), error, duration_s}. Each line follows the same rules as run_command.", "inputSchema": { "type": "object", "properties": {"script": {"type": "string", "description": "One command per line: id {json}"}}, diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index 5f2f6c8c4a..e7104cb602 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -68,7 +68,7 @@ pub fn defs() -> Vec { }, ToolDef { name: "run_command", - description: "Run a RustGIS command by id with JSON parameters (see search_commands for ids and parameters). Project edits are undoable. Source publication and other external file writes cannot be undone. Commands that read or write files, use the network or replace the project ask the user first.", + description: "Run a RustGIS command by id with JSON parameters (see search_commands for ids and parameters). Project edits are undoable. Source publication and other external file writes cannot be undone. Commands that read or write files, use the network or replace the project ask the user first. A notice that reports lost data is also in the result's losses, as {code, kind, text, action}; for an assumed.* code, ask the user rather than guess.", schema: json!({ "type": "object", "properties": { @@ -788,7 +788,7 @@ fn with_new_layers(r: Value, s: &Session, before: &[(String, Vec)]) -> Valu /// call and one undo step, none when its lines only read, moved the view, exported, left a /// request or reported they changed nothing. A failing line stops the script and nothing it did /// to the project is kept (files it wrote stay). The answer is -/// `{success, result, lines, layersAdded, notices, error, duration_s}`, where `result` is the +/// `{success, result, lines, layersAdded, notices, losses, error, duration_s}`, where `result` is the /// last command's; a failure is an `Err` holding the same JSON. fn run_script(s: &mut Session, call: &ToolCall, tokens: usize, scope: Scope, permit: Option) -> Result { let a = &call.args; @@ -807,13 +807,14 @@ fn run_script(s: &mut Session, call: &ToolCall, tokens: usize, scope: Scope, per }; let secs = (start.elapsed().as_secs_f64() * 1000.0).round() / 1000.0; let notices: Vec<&str> = s.notices_since(mark).iter().map(|n| n.text.as_str()).collect(); + let losses = losses_since(s, mark); match r { Ok(v) => { let ran = v.get("ran").and_then(Value::as_array); let last = ran.and_then(|r| r.last()).and_then(|l| l.get("result")).cloned().unwrap_or(Value::Null); let added = with_new_layers(json!({}), s, &before).get("layersAdded").cloned().unwrap_or_else(|| json!([])); let out = json!({"success": true, "result": last, "lines": ran.map_or(0, Vec::len), "layersAdded": added, - "notices": notices, "error": null, "duration_s": secs}); + "notices": notices, "losses": losses, "error": null, "duration_s": secs}); Ok(public_envelope(s, out, tokens)) } Err(e) => { @@ -823,7 +824,7 @@ fn run_script(s: &mut Session, call: &ToolCall, tokens: usize, scope: Scope, per let told = rustgis_engine::data::diagnostics::redact(&e); let said: Vec<&&str> = notices.iter().filter(|t| **t != e && **t != told).collect(); let out = json!({"success": false, "result": null, "lines": 0, "layersAdded": [], "notices": said, - "error": clip(&e, 8000), "duration_s": secs}); + "losses": losses, "error": clip(&e, 8000), "duration_s": secs}); Err(public_envelope(s, out, tokens)) } } @@ -831,20 +832,38 @@ fn run_script(s: &mut Session, call: &ToolCall, tokens: usize, scope: Scope, per /// A run's result with what it said beside it (a notice that only the first tables of a GeoPackage /// were added, a file's warnings), which the status bar shows in the app. +/// Classified losses also go in `losses`, so an agent can match their codes. fn with_notices(r: Value, s: &Session, mark: u64) -> Value { let said: Vec = s.notices_since(mark).iter().map(|n| public_text(n.text.clone())).collect(); if said.is_empty() { return r; } + let losses = losses_since(s, mark); match r { Value::Object(mut o) if !o.contains_key("notices") => { o.insert("notices".into(), json!(said)); + if !losses.is_empty() && !o.contains_key("losses") { + o.insert("losses".into(), json!(losses)); + } Value::Object(o) } - other => json!({"result": other, "notices": said}), + other if losses.is_empty() => json!({"result": other, "notices": said}), + other => json!({"result": other, "notices": said, "losses": losses}), } } +/// The notices since `mark` that report a classified loss, as `{code, kind, text, action}`: the +/// code is never translated or renamed, so it can be matched where the text can't. +fn losses_since(s: &Session, mark: u64) -> Vec { + s.notices_since(mark) + .iter() + .filter_map(|n| { + let spec = n.loss()?.spec(); + Some(json!({"code": spec.id, "kind": spec.kind.id(), "text": public_text(n.text.clone()), "action": spec.action})) + }) + .collect() +} + /// A failed run's error with what the command said before failing (a GDAL layer that couldn't be /// converted). fn error_with_notices(e: String, s: &Session, mark: u64) -> String { @@ -1364,6 +1383,44 @@ mod tests { assert_eq!(s.notices_since(0).len(), 1, "the app also receives one aggregate loss notice"); } + /// A notice that reports lost data comes with its code in `losses`, beside the notice text; + /// a run that loses nothing has no `losses`, and a script's answer an empty list. + #[test] + fn results_give_the_codes_of_the_losses_their_notices_report() { + let mut s = Session::new(rustgis_engine::Project::default()); + // An MCP agent the server lets act without asking (`--yes`). + let scope = Scope::agent(rustgis_engine::policy::AgentAccess::Full, true, "loss-codes", None, std::sync::Arc::new(Live::default())); + const WMS: &str = r#" +Test WMS +image/png +EPSG:3857roadsRoads +"#; + // A legend picture whose address is too long to keep is left out, and said with its code. + let long = format!("https://maps.example.com/legends/{}.png", "a".repeat(5000)); + let params = |legend: &str| json!({"url": "https://maps.example.com/wms", "layer": "roads", "text": WMS.replace("LEGEND", legend)}); + let lossy = params(&long); + let clean = params("https://maps.example.com/legends/roads.png"); + let add = |params: &Value| ToolCall { + id: "add".into(), + name: "run_command".into(), + args: json!({"command": "service.add", "params": params}), + }; + let mut run = |call: &ToolCall| -> Value { + serde_json::from_str(&run_with_budget(&mut s, call, DEFAULT_OUTPUT_TOKENS, scope.clone(), None).unwrap()).unwrap() + }; + let out = run(&add(&lossy)); + let [loss] = out["losses"].as_array().map(Vec::as_slice).unwrap_or_default() else { panic!("one loss: {out}") }; + assert_eq!((&loss["code"], &loss["kind"]), (&json!("dropped.legend"), &json!("dropped")), "{out}"); + assert_eq!(loss["action"], "Use a service with short HTTP or HTTPS addresses for its legend pictures."); + assert!(out["notices"].as_array().unwrap().iter().any(|n| n == &loss["text"]), "the loss is a notice too: {out}"); + assert!(run(&add(&clean)).get("losses").is_none()); + let line = |params: &Value| format!("service.add {params}"); + let script = |text: String| ToolCall { id: "script".into(), name: "run".into(), args: json!({"script": text}) }; + let out = run(&script(line(&lossy))); + assert_eq!(out["losses"][0]["code"], "dropped.legend", "{out}"); + assert_eq!(run(&script(line(&clean)))["losses"], json!([])); + } + #[test] fn successful_results_scrub_active_raw_service_keys_without_a_wrapper() { let mut s = Session::new(rustgis_engine::Project::default()); diff --git a/docs/mcp.md b/docs/mcp.md index f3ce3822ec..adee011fa6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -218,7 +218,7 @@ couldn't start: agents then stay on, and the status bar says only the file bridg the same rules as the `run` tool: a refused or failing line stops it, and nothing it did to the project is kept. Files written by an earlier line stay written. 3. The outcome is written to `bridge-result.json` in the same folder: `{success, result, lines, - layersAdded, notices, error, duration_s, timestamp}`. The status bar says whether it worked. + layersAdded, notices, losses, error, duration_s, timestamp}`. The status bar says whether it worked. Only one RustGIS at a time runs the bridge: a second copy's is refused while the first's runs (it holds `bridge.lock`). The bridge runs a script each time the file changes. Whatever the file held when the bridge started @@ -342,8 +342,8 @@ These behavioral tests in `crates/assistant/src/relay.rs` check the requirements | `view_map` | The map as a PNG image at the current view; `width` and `height` default to 1024 × 640, each clamped to 64–2048 pixels. A picture over 3.75 MiB (a satellite basemap near 2048 pixels) is drawn again smaller, and its caption gives the size drawn and the size asked. `layout` (a layout's name) draws its page instead, fitted to `width` (and `height` when given); `region` draws part of either at full detail: `[x, y, w, h]` in mm on a layout (up to 600 dpi), `[west, south, east, north]` in degrees on the map. What drawing it said (texts cut off, layers without their cast shadows) follows the caption | | `snapshot` | The map as a PNG with JSON metadata: `mode`, `width`, `height`, `extent` (longitude/latitude), `center`, `scale`, `projection`, `render_settled`, `saved` and `note`. `mode: "screen"` captures the RustGIS window through the relay, once the map has finished drawing or after `wait_s` seconds (default 5, clamped to 0–30); `overlays: false` leaves out the map's controls, scale bar, north arrow and sketches. `mode: "render"` draws offscreen at `max_width` (default 1024, clamped to 64–2048 pixels); height follows the view's shape, with each side capped at 2048. It works while the window is hidden. `mode: "auto"` (default) takes the screen when the map is on it. Unavailable screen captures fall back to render. `save_path` also writes the PNG to a file, which needs file access | | `search_commands` | Finds RustGIS commands by words: their ids, ribbon locations and parameters | -| `run_command` | Runs a command by id with JSON parameters; each run that changes the project is one undo step. The result names the layers it added (`layersAdded`) and what the command said beside it (`notices`), including any parameters it ignored (`layer.moveDown ignores 'steps' (it reads layer)`) | -| `run` | Runs several commands in one call, as one undo step (none when its lines only read the project, moved the view, exported, left a request, or ran a command that reports it changed nothing, such as a move to where the layers already are; a line that sets a value to the one it has still counts): a script in the `script.run` format (one `command-id {json}` per line, `#` comments). A failing line stops it, nothing it did to the project is kept, and the error names the line; files an earlier line wrote (an export) stay written. Answers `{success, result, lines, layersAdded, notices, error, duration_s}`, where `result` is the last command's. Each line follows `run_command`'s rules, checked before any line runs | +| `run_command` | Runs a command by id with JSON parameters; each run that changes the project is one undo step. The result names the layers it added (`layersAdded`) and what the command said beside it (`notices`), including any parameters it ignored (`layer.moveDown ignores 'steps' (it reads layer)`). A notice that reports lost data is also in `losses`, as `{code, kind, text, action}`, with a [loss code](cli.md#loss-codes) an agent can match: for an `assumed.*` code it can ask instead of guessing | +| `run` | Runs several commands in one call, as one undo step (none when its lines only read the project, moved the view, exported, left a request, or ran a command that reports it changed nothing, such as a move to where the layers already are; a line that sets a value to the one it has still counts): a script in the `script.run` format (one `command-id {json}` per line, `#` comments). A failing line stops it, nothing it did to the project is kept, and the error names the line; files an earlier line wrote (an export) stay written. Answers `{success, result, lines, layersAdded, notices, losses, error, duration_s}`, where `result` is the last command's. Each line follows `run_command`'s rules, checked before any line runs | | `search_tools` | Finds geoprocessing tools by words | | `describe_tool` | A geoprocessing tool's parameters | | `run_tool` | Runs a geoprocessing tool; its output is added to the map as a new layer (with `layersAdded` and `notices` as for `run_command`), or to the project as a standalone table, which the result names (`table`) | diff --git a/docs/python.md b/docs/python.md index 134a183104..6392d14b27 100644 --- a/docs/python.md +++ b/docs/python.md @@ -212,6 +212,24 @@ s.undo() s.redo() ``` +A notice that says a command lost data, and has a [loss code](cli.md#loss-codes), is also raised +as a Python warning: `rustgis.DroppedWarning`, `ChangedWarning`, `ApproximatedWarning` or +`AssumedWarning`, all subclasses of `rustgis.DataLossWarning`. The warning's `code` (such as +`"dropped.ring"`) and `kind` say which, and its message is the notice's text with the code. The +notice stays in `s.notices()`. Python's warning filters decide what happens, so a script can turn +losses into errors and allow the ones it expects: + +```python +import warnings + +warnings.filterwarnings("error", category=rustgis.DataLossWarning) +warnings.filterwarnings("ignore", category=rustgis.DroppedWarning, message=r".*\[dropped\.ring\]") +s.add_data("storms.rss") # raises on any other loss +``` + +A warning turned into an error is raised after the command has run, so what it changed is kept. +Losses that don't have a code yet are only in `s.notices()`. + `run_tool` runs a geoprocessing tool and returns the layer it made (a list when it made several), or the tool's own result for one that selects or makes a table. Layers can be given as `Layer` objects or by name; tools take layers by name, so of two layers with the same name the upper one From f192214ad40f24e24e2ec7ce22166a8ce6db939a Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 19:22:29 -0600 Subject: [PATCH 02/21] fix(python): each call raises its own losses; MCP keeps codes on failures, past redaction and the budget --- .../rustgis-python/python/rustgis/__init__.py | 64 +++--- apps/rustgis-python/src/lib.rs | 38 ++-- apps/rustgis-python/tests/test_session.py | 41 ++++ crates/assistant/src/tools.rs | 185 ++++++++++++++---- 4 files changed, 251 insertions(+), 77 deletions(-) diff --git a/apps/rustgis-python/python/rustgis/__init__.py b/apps/rustgis-python/python/rustgis/__init__.py index 67a3f5a45e..cc9e7fc187 100644 --- a/apps/rustgis-python/python/rustgis/__init__.py +++ b/apps/rustgis-python/python/rustgis/__init__.py @@ -97,7 +97,8 @@ class AssumedWarning(DataLossWarning): def _warn_losses(engine: _Engine) -> None: - """Raises each loss the engine reported since the last call as a :class:`DataLossWarning`. + """Raises each loss this thread's calls reported since the last call as a + :class:`DataLossWarning`. Args: engine: The session's engine. @@ -107,6 +108,33 @@ def _warn_losses(engine: _Engine) -> None: warnings.warn(category(f"{text} [{code}]", code), skip_file_prefixes=_PACKAGE) +def _native(engine: _Engine, operation: Any, *args: Any) -> Any: + """Calls one of the engine's methods, then raises the losses it reported as warnings. + + A failed call still raises them, as it can have lost data it couldn't take back, but its own + exception stays the one raised: a warning a filter turns into an error is added to it as a + note. + + Args: + engine: The session's engine. + operation: The engine method. + *args: Its arguments. + + Returns: + What the method returned. + """ + try: + result = operation(*args) + except BaseException as failure: + try: + _warn_losses(engine) + except Warning as promoted: + failure.add_note(f"{type(promoted).__name__}: {promoted}") + raise + _warn_losses(engine) + return result + + def __getattr__(name: str) -> Any: """Imports ``Map`` on first use, so the package works without the notebook widget's dependencies. @@ -922,12 +950,7 @@ def run(self, command: str, params: Optional[Dict[str, Any]] = None, /, **kwargs encoded = json.dumps(merged, default=_jsonable, allow_nan=False) if merged else "" except ValueError as e: raise ValueError(f"{command}: parameters must be finite numbers, text, lists and dicts ({e})") from e - try: - text = self._engine.run(command, encoded) - finally: - # A failed command can still have lost data it can't take back. - _warn_losses(self._engine) - return json.loads(text) + return json.loads(_native(self._engine, self._engine.run, command, encoded)) def notices(self) -> List[Tuple[str, bool]]: """What commands have reported since the last call: warnings about a file, a tool's @@ -945,10 +968,7 @@ def _layer_geojson(self, layer: int, selected: bool) -> str: layer: The layer's id. selected: Only its selected features. """ - try: - return self._engine.layer_geojson(layer, selected) - finally: - _warn_losses(self._engine) + return _native(self._engine, self._engine.layer_geojson, layer, selected) def _root(self) -> "Session": """The session that holds the project: this one.""" @@ -970,10 +990,7 @@ def project_json(self) -> str: Returns: The JSON text; ``run("project.openText", text=...)`` opens it. """ - try: - return self._engine.project_json() - finally: - _warn_losses(self._engine) + return _native(self._engine, self._engine.project_json) # Maps ---------------------------------------------------------------------------------- @@ -996,16 +1013,15 @@ def to_png( Returns: The PNG bytes. """ - try: - png = bytes( - self._engine.render_png( - None if width is None else float(width), - None if height is None else float(height), - None if dpi is None else float(dpi), - ) + png = bytes( + _native( + self._engine, + self._engine.render_png, + None if width is None else float(width), + None if height is None else float(height), + None if dpi is None else float(dpi), ) - finally: - _warn_losses(self._engine) + ) if path is not None: with open(path, "wb") as f: f.write(png) diff --git a/apps/rustgis-python/src/lib.rs b/apps/rustgis-python/src/lib.rs index ffc2f7dd77..9820e35ad7 100644 --- a/apps/rustgis-python/src/lib.rs +++ b/apps/rustgis-python/src/lib.rs @@ -91,10 +91,14 @@ struct Engine { } impl Engine { + /// Runs `operation` on the session, then sets aside the losses it reported for the thread that + /// called it, under the same lock, so a call on another thread can't take them. fn with_session(&self, py: Python<'_>, operation: impl FnOnce(&mut Session) -> T + Send) -> T { with_native(py, || { let mut session = self.session.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - operation(&mut session) + let result = operation(&mut session); + self.losses.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).collect(&session); + result }) } @@ -110,16 +114,19 @@ impl Engine { /// See [`Engine::losses`]. struct Losses { - pending: Vec<(String, String, String)>, + /// `(kind, code, text)` for the thread whose call reported it. + pending: Vec<(std::thread::ThreadId, (String, String, String))>, mark: u64, given: Vec<(LossCode, u64)>, } impl Losses { - /// Sets aside the losses `session` gave since the last call, while their notices are still in - /// its queue (before `take_notices` drains it). One the queue no longer keeps (past its last - /// 200) is set aside as one entry per code that says how many. + /// Sets aside the losses `session` gave since the last call, for the calling thread, while + /// their notices are still in its queue (after every call, so before `take_notices` drains + /// it). One the queue no longer keeps (past its last 200) is set aside as one entry per code + /// that says how many. fn collect(&mut self, session: &Session) { + let thread = std::thread::current().id(); let kept: Vec<(LossCode, String)> = session.notices_since(self.mark).iter().filter_map(|n| n.loss().map(|code| (code, n.text.clone()))).collect(); for &(code, given) in session.losses_given() { @@ -128,10 +135,11 @@ impl Losses { let lost = given.saturating_sub(was).saturating_sub(held); if lost > 0 { let spec = code.spec(); - self.pending.push((spec.kind.id().into(), spec.id.into(), format!("{lost} further {} notice(s) were not kept", spec.id))); + let text = format!("{lost} further {} notice(s) were not kept", spec.id); + self.pending.push((thread, (spec.kind.id().into(), spec.id.into(), text))); } } - self.pending.extend(kept.into_iter().map(|(code, text)| (code.spec().kind.id().into(), code.spec().id.into(), text))); + self.pending.extend(kept.into_iter().map(|(code, text)| (thread, (code.spec().kind.id().into(), code.spec().id.into(), text)))); self.mark = session.notice_mark(); self.given = session.losses_given().to_vec(); } @@ -306,14 +314,19 @@ impl Engine { result.map_err(RustGISError::new_err) } - /// The classified losses given since the last call, as `(kind, code, text)`, oldest first, - /// which the package raises as warnings; `take_notices` still returns them too. + /// The classified losses this thread's calls reported since it last asked, as + /// `(kind, code, text)`, oldest first, which the package raises as warnings; `take_notices` + /// still returns them too. fn _take_losses(&self, py: Python<'_>) -> Vec<(String, String, String)> { + let thread = std::thread::current().id(); let losses = &self.losses; - self.with_session(py, |session| { + // Never set aside while the session runs: its lock is taken inside the session's. + with_native(py, || { + let _session = self.session.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let mut losses = losses.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - losses.collect(session); - std::mem::take(&mut losses.pending) + let (mine, others) = std::mem::take(&mut losses.pending).into_iter().partition(|(t, _)| *t == thread); + losses.pending = others; + mine.into_iter().map(|(_, loss)| loss).collect::>() }) } @@ -323,7 +336,6 @@ impl Engine { let notices: Vec<(String, bool)> = self.with_session(py, |session| { // A client made on a background thread since the last command may have chosen the trust. session.notice_trust(); - self.losses.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).collect(session); session.notices.drain(..).map(|n| (n.text, n.error)).collect() }); self.flush(py); diff --git a/apps/rustgis-python/tests/test_session.py b/apps/rustgis-python/tests/test_session.py index 908b3f3126..f15ba70cff 100644 --- a/apps/rustgis-python/tests/test_session.py +++ b/apps/rustgis-python/tests/test_session.py @@ -162,6 +162,47 @@ def test_losses_are_warnings_with_their_code(tmp_path): assert not [w for w in seen if issubclass(w.category, rustgis.DataLossWarning)] +def test_a_loss_is_raised_on_the_call_that_reported_it(tmp_path): + import threading + + lossy = tmp_path / "lossy.rss" + lossy.write_text(_feed("1 x")) + s = rustgis.Session() + s._engine.run("layer.addData", json.dumps({"path": str(lossy)})) + # Another thread's call on the same session doesn't take this thread's loss. + other = [] + thread = threading.Thread(target=lambda: other.extend(s._engine._take_losses())) + thread.start() + thread.join() + assert other == [] + assert [code for _, code, _ in s._engine._take_losses()] == ["dropped.ring"] + + +_WMS = ( + '' + "Test WMSimage/png" + '' + "EPSG:3857roadsRoads" +) + + +def test_a_failed_command_keeps_its_error_and_still_says_its_loss(): + # A legend left out is counted, so it is said even though the script failed after it. + add = json.dumps({"url": "https://maps.example.com/wms", "layer": "roads", "text": _WMS}) + script = f"service.add {add}\nlayer.addDataText {json.dumps({'fileName': 'broken.geojson', 'text': '{'})}" + s = rustgis.Session() + with warnings.catch_warnings(): + warnings.filterwarnings("error", category=rustgis.DataLossWarning) + with pytest.raises(rustgis.RustGISError) as failed: + s.run("script.run", script=script) + assert any("DroppedWarning" in note and "[dropped.legend]" in note for note in failed.value.__notes__) + with pytest.warns(rustgis.DroppedWarning, match=r"\[dropped\.legend\]"): + with pytest.raises(rustgis.RustGISError): + s.run("script.run", script=script) + + @pytest.mark.parametrize("as_text", [False, True]) def test_pmtiles_options_survive_a_project_round_trip(as_text): """The Python names reach the engine, including JSON-text styles and extensionless URLs.""" diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index e7104cb602..16546be806 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -481,17 +481,17 @@ pub fn run_with_budget(s: &mut Session, call: &ToolCall, tokens: usize, scope: S #[cfg(not(target_arch = "wasm32"))] pub(crate) struct CommandCompletion { before: Vec<(String, Vec)>, - mark: u64, + said: Said, } #[cfg(not(target_arch = "wasm32"))] impl CommandCompletion { pub(crate) fn capture(s: &Session) -> Self { - Self { before: layer_snap(s), mark: s.notice_mark() } + Self { before: layer_snap(s), said: Said::now(s) } } pub(crate) fn finish(self, s: &mut Session, result: Result) -> Result { result - .map(|value| command_result(s, value, &self.before, self.mark, DEFAULT_OUTPUT_TOKENS)) - .map_err(|e| public_error(&error_with_notices(e, s, self.mark))) + .map(|value| command_result(s, value, &self.before, &self.said, DEFAULT_OUTPUT_TOKENS)) + .map_err(|e| public_error(&error_with_notices(e, s, &self.said))) } } @@ -502,13 +502,13 @@ fn run_with_budget_inner(s: &mut Session, call: &ToolCall, tokens: usize, scope: return Err("ui.* commands only open panes and dialogs; the assistant can't use them".into()); } let engine = policy_call(call)?.ok_or("missing executable call")?; - let (before, mark) = (layer_snap(s), s.notice_mark()); + let (before, said) = (layer_snap(s), Said::now(s)); let result = match permit { Some(p) => s.run_permitted(scope, p, &engine), None => s.run_scoped(scope, &engine), } - .map_err(|e| error_with_notices(e, s, mark))?; - return Ok(command_result(s, result, &before, mark, tokens)); + .map_err(|e| error_with_notices(e, s, &said))?; + return Ok(command_result(s, result, &before, &said, tokens)); } if permit.is_some() { return Err("this approval is for an executable call".into()); @@ -582,12 +582,18 @@ fn public_result(s: &mut Session, value: Value, tokens: usize) -> String { /// These fields belong to the adapter's response schema; only their values contain data. fn public_envelope(s: &mut Session, value: Value, tokens: usize) -> String { + let (value, withheld) = public_projection(value); + finish_result(s, value, tokens, withheld) +} + +/// [`public_envelope`]'s cleaning, without serializing, so fixed-schema fields can be added after. +fn public_projection(value: Value) -> (Value, Withheld) { let mut withheld = Withheld::default(); let value = match value { Value::Object(o) => Value::Object(o.into_iter().map(|(key, value)| (key, public_addresses(value, 1, &mut withheld))).collect()), value => public_addresses(value, 0, &mut withheld), }; - finish_result(s, value, tokens, withheld) + (value, withheld) } /// Generated search, tool and project metadata has a fixed schema at every level. Its @@ -609,10 +615,12 @@ fn public_metadata(value: Value, depth: usize, withheld: &mut Withheld) -> Value } /// Cleans the arbitrary command payload before adding adapter-owned notices/layer metadata. -fn command_result(s: &mut Session, value: Value, before: &[(String, Vec)], mark: u64, tokens: usize) -> String { +fn command_result(s: &mut Session, value: Value, before: &[(String, Vec)], said: &Said, tokens: usize) -> String { let mut withheld = Withheld::default(); let value = public_addresses(value, 0, &mut withheld); - let value = with_notices(with_new_layers(value, s, before), s, mark); + let value = with_notices(with_new_layers(value, s, before), s, said.mark); + // Added after cleaning: its keys and codes are fixed, and its text was cleaned on its own. + let value = with_losses(value, losses_since(s, said), tokens, false); finish_result(s, value, tokens, withheld) } @@ -799,7 +807,8 @@ fn run_script(s: &mut Session, call: &ToolCall, tokens: usize, scope: Scope, per .filter(|t| !t.trim().is_empty()) .ok_or("script is required: one `command-id {json}` per line")?; let start = web_time::Instant::now(); - let (before, mark) = (layer_snap(s), s.notice_mark()); + let (before, said) = (layer_snap(s), Said::now(s)); + let mark = said.mark; let engine = Call::script(script).with_request(&call.id); let r = match permit { Some(p) => s.run_permitted(scope, p, &engine), @@ -807,15 +816,16 @@ fn run_script(s: &mut Session, call: &ToolCall, tokens: usize, scope: Scope, per }; let secs = (start.elapsed().as_secs_f64() * 1000.0).round() / 1000.0; let notices: Vec<&str> = s.notices_since(mark).iter().map(|n| n.text.as_str()).collect(); - let losses = losses_since(s, mark); + let losses = losses_since(s, &said); match r { Ok(v) => { let ran = v.get("ran").and_then(Value::as_array); let last = ran.and_then(|r| r.last()).and_then(|l| l.get("result")).cloned().unwrap_or(Value::Null); let added = with_new_layers(json!({}), s, &before).get("layersAdded").cloned().unwrap_or_else(|| json!([])); let out = json!({"success": true, "result": last, "lines": ran.map_or(0, Vec::len), "layersAdded": added, - "notices": notices, "losses": losses, "error": null, "duration_s": secs}); - Ok(public_envelope(s, out, tokens)) + "notices": notices, "error": null, "duration_s": secs}); + let (out, withheld) = public_projection(out); + Ok(finish_result(s, with_losses(out, losses, tokens, true), tokens, withheld)) } Err(e) => { let e = public_error(&e); @@ -824,54 +834,107 @@ fn run_script(s: &mut Session, call: &ToolCall, tokens: usize, scope: Scope, per let told = rustgis_engine::data::diagnostics::redact(&e); let said: Vec<&&str> = notices.iter().filter(|t| **t != e && **t != told).collect(); let out = json!({"success": false, "result": null, "lines": 0, "layersAdded": [], "notices": said, - "losses": losses, "error": clip(&e, 8000), "duration_s": secs}); - Err(public_envelope(s, out, tokens)) + "error": clip(&e, 8000), "duration_s": secs}); + let (out, withheld) = public_projection(out); + Err(finish_result(s, with_losses(out, losses, tokens, true), tokens, withheld)) } } } /// A run's result with what it said beside it (a notice that only the first tables of a GeoPackage /// were added, a file's warnings), which the status bar shows in the app. -/// Classified losses also go in `losses`, so an agent can match their codes. fn with_notices(r: Value, s: &Session, mark: u64) -> Value { let said: Vec = s.notices_since(mark).iter().map(|n| public_text(n.text.clone())).collect(); if said.is_empty() { return r; } - let losses = losses_since(s, mark); match r { Value::Object(mut o) if !o.contains_key("notices") => { o.insert("notices".into(), json!(said)); - if !losses.is_empty() && !o.contains_key("losses") { - o.insert("losses".into(), json!(losses)); - } Value::Object(o) } - other if losses.is_empty() => json!({"result": other, "notices": said}), - other => json!({"result": other, "notices": said, "losses": losses}), + other => json!({"result": other, "notices": said}), + } +} + +/// Where a run's notices start, and the session's loss counts then: what [`losses_since`] reads. +struct Said { + mark: u64, + given: Vec<(rustgis_engine::data::loss::LossCode, u64)>, +} + +impl Said { + fn now(s: &Session) -> Self { + Self { mark: s.notice_mark(), given: s.losses_given().to_vec() } } } -/// The notices since `mark` that report a classified loss, as `{code, kind, text, action}`: the -/// code is never translated or renamed, so it can be matched where the text can't. -fn losses_since(s: &Session, mark: u64) -> Vec { - s.notices_since(mark) +/// The notices since `said` that report a classified loss, as `{code, kind, text, action}`: the +/// code is never translated or renamed, so it can be matched where the text can't. Losses whose +/// notices the session no longer keeps (past its last 200) come as one entry per code with their +/// `count`. +fn losses_since(s: &Session, said: &Said) -> Vec { + let entry = |code: rustgis_engine::data::loss::LossCode, text: String| { + let spec = code.spec(); + json!({"code": spec.id, "kind": spec.kind.id(), "text": text, "action": spec.action}) + }; + let kept: Vec<_> = s.notices_since(said.mark).iter().filter_map(|n| Some((n.loss()?, public_text(n.text.clone())))).collect(); + let mut out: Vec = s + .losses_given() .iter() - .filter_map(|n| { - let spec = n.loss()?.spec(); - Some(json!({"code": spec.id, "kind": spec.kind.id(), "text": public_text(n.text.clone()), "action": spec.action})) + .filter_map(|&(code, given)| { + let was = said.given.iter().find(|(c, _)| *c == code).map_or(0, |(_, n)| *n); + let held = kept.iter().filter(|(c, _)| *c == code).count() as u64; + let lost = given.saturating_sub(was).saturating_sub(held); + (lost > 0).then(|| { + let mut e = entry(code, format!("{lost} further {} notice(s) were not kept", code.spec().id)); + e["count"] = json!(lost); + e + }) }) - .collect() + .collect(); + out.extend(kept.into_iter().map(|(code, text)| entry(code, text))); + out +} + +/// `r` with `losses` (or `[]` when `always`), within the output budget: when the whole list +/// doesn't fit beside what `r` holds, each entry keeps only its code and kind, and +/// `lossesTrimmed` says so. A result already over the budget is left as it is. +fn with_losses(r: Value, losses: Vec, tokens: usize, always: bool) -> Value { + let Value::Object(mut o) = r else { return r }; + if o.contains_key("losses") || (losses.is_empty() && !always) { + return Value::Object(o); + } + let room = output_bytes(tokens).saturating_sub(Value::Object(o.clone()).to_string().len()); + let full = json!(losses); + if full.to_string().len() + 12 <= room { + o.insert("losses".into(), full); + } else { + let short: Vec = losses.iter().map(|l| json!({"code": l["code"], "kind": l["kind"]})).collect(); + let short = json!(short); + if short.to_string().len() + 40 <= room { + o.insert("losses".into(), short); + o.insert("lossesTrimmed".into(), json!(true)); + } + } + Value::Object(o) } /// A failed run's error with what the command said before failing (a GDAL layer that couldn't be /// converted). -fn error_with_notices(e: String, s: &Session, mark: u64) -> String { +/// A failed command can still report losses its rollback can't take back (a counted omission): +/// their codes follow, as a `losses:` line of JSON. +fn error_with_notices(e: String, s: &Session, said: &Said) -> String { let told = rustgis_engine::data::diagnostics::redact(&e); - let said: Vec<&str> = s.notices_since(mark).iter().map(|n| n.text.as_str()).filter(|t| *t != e && *t != told).collect(); + let notices: Vec<&str> = s.notices_since(said.mark).iter().map(|n| n.text.as_str()).filter(|t| *t != e && *t != told).collect(); + let losses: Vec = + losses_since(s, said).iter().map(|l| json!({"code": l["code"], "kind": l["kind"], "action": l["action"]})).collect(); + // Before the notices, so the 8,000-character cap cuts them first. + let mut lines: Vec = losses.is_empty().then(Vec::new).unwrap_or_else(|| vec![format!("losses: {}", json!(losses))]); + lines.extend(notices.into_iter().map(str::to_string)); // Preserve the original 8,000-character diagnostic assembly cap for MCP errors; // the agent additionally applies its serialized output budget. - if said.is_empty() { e } else { clip(&format!("{e}\n{}", said.join("\n")), 8000) } + if lines.is_empty() { e } else { clip(&format!("{e}\n{}", lines.join("\n")), 8000) } } /// How well `words` match `hay` (all lower case): matched words, with whole-id hits counting more. @@ -1405,20 +1468,62 @@ mod tests { name: "run_command".into(), args: json!({"command": "service.add", "params": params}), }; - let mut run = |call: &ToolCall| -> Value { - serde_json::from_str(&run_with_budget(&mut s, call, DEFAULT_OUTPUT_TOKENS, scope.clone(), None).unwrap()).unwrap() + let run = |s: &mut Session, call: &ToolCall| -> Value { + serde_json::from_str(&run_with_budget(s, call, DEFAULT_OUTPUT_TOKENS, scope.clone(), None).unwrap()).unwrap() }; - let out = run(&add(&lossy)); + let out = run(&mut s, &add(&lossy)); let [loss] = out["losses"].as_array().map(Vec::as_slice).unwrap_or_default() else { panic!("one loss: {out}") }; assert_eq!((&loss["code"], &loss["kind"]), (&json!("dropped.legend"), &json!("dropped")), "{out}"); assert_eq!(loss["action"], "Use a service with short HTTP or HTTPS addresses for its legend pictures."); assert!(out["notices"].as_array().unwrap().iter().any(|n| n == &loss["text"]), "the loss is a notice too: {out}"); - assert!(run(&add(&clean)).get("losses").is_none()); + assert!(run(&mut s, &add(&clean)).get("losses").is_none()); let line = |params: &Value| format!("service.add {params}"); let script = |text: String| ToolCall { id: "script".into(), name: "run".into(), args: json!({"script": text}) }; - let out = run(&script(line(&lossy))); + let out = run(&mut s, &script(line(&lossy))); + assert_eq!(out["losses"][0]["code"], "dropped.legend", "{out}"); + assert_eq!(run(&mut s, &script(line(&clean)))["losses"], json!([])); + // A failed command still says the loss its rollback can't take back, with its code. + let failing = format!("{}\nlayer.addDataText {}", line(&lossy), json!({"fileName": "broken.geojson", "text": "{"})); + let command = ToolCall { + id: "fail".into(), + name: "run_command".into(), + args: json!({"command": "script.run", "params": {"script": failing}}), + }; + let error = run_with_budget(&mut s, &command, DEFAULT_OUTPUT_TOKENS, scope.clone(), None).unwrap_err(); + assert!(error.contains(r#"losses: [{"action":"Use a service"#) && error.contains(r#""code":"dropped.legend""#), "{error}"); + let error = run_with_budget(&mut s, &script(failing), DEFAULT_OUTPUT_TOKENS, scope.clone(), None).unwrap_err(); + let failed: Value = serde_json::from_str(&error).unwrap(); + assert_eq!((&failed["success"], &failed["losses"][0]["code"]), (&json!(false), &json!("dropped.legend")), "{failed}"); + // A login value that matches a code's words cleans the notice's text, never the code. + let id = s + .run( + "connection.new", + &json!({"kind":"wms","address":"https://echo-2371.example.invalid/wms","auth":"header","keyName":"X-Key"}), + ) + .unwrap()["id"] + .as_str() + .unwrap() + .to_string(); + s.run("connection.login", &json!({"id": id, "apiKey": "legend"})).unwrap(); + let out = run(&mut s, &script(line(&lossy))); assert_eq!(out["losses"][0]["code"], "dropped.legend", "{out}"); - assert_eq!(run(&script(line(&clean)))["losses"], json!([])); + assert!(out["losses"][0].get("code").is_some() && !out["losses"][0]["text"].as_str().unwrap().contains("legend"), "{out}"); + } + + /// Losses that don't fit the output budget beside the result keep only their codes, so the + /// result stays whole instead of becoming a preview. + #[test] + fn losses_beyond_the_output_budget_keep_their_codes() { + let loss = json!({"code": "dropped.value", "kind": "dropped", "text": "x".repeat(600), "action": "Correct the value."}); + let out = with_losses(json!({"notices": ["n"]}), vec![loss.clone(), loss], 200, false); + assert_eq!(out["losses"], json!([{"code": "dropped.value", "kind": "dropped"}, {"code": "dropped.value", "kind": "dropped"}])); + assert_eq!(out["lossesTrimmed"], true); + assert!(out.to_string().len() <= output_bytes(200)); + let small = json!({"code": "dropped.value", "kind": "dropped", "text": "t", "action": "a"}); + let out = with_losses(json!({"notices": ["n"]}), vec![small.clone()], 200, false); + assert_eq!((&out["losses"], out.get("lossesTrimmed")), (&json!([small]), None)); + assert_eq!(with_losses(json!({"notices": ["n"]}), vec![], 200, true)["losses"], json!([])); + assert!(with_losses(json!({"notices": ["n"]}), vec![], 200, false).get("losses").is_none()); } #[test] From bd1ef519acc853974b83a741a69cf1615528a729 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 19:57:32 -0600 Subject: [PATCH 03/21] fix(python): say every loss when one is an error; keep MCP failure codes whole and uncleaned --- .../rustgis-python/python/rustgis/__init__.py | 25 ++- apps/rustgis-python/tests/test_session.py | 23 +++ crates/assistant/src/tools.rs | 168 +++++++++++++----- 3 files changed, 167 insertions(+), 49 deletions(-) diff --git a/apps/rustgis-python/python/rustgis/__init__.py b/apps/rustgis-python/python/rustgis/__init__.py index cc9e7fc187..511175b88e 100644 --- a/apps/rustgis-python/python/rustgis/__init__.py +++ b/apps/rustgis-python/python/rustgis/__init__.py @@ -96,16 +96,32 @@ class AssumedWarning(DataLossWarning): _PACKAGE = (os.path.dirname(__file__),) -def _warn_losses(engine: _Engine) -> None: +def _warn_losses(engine: _Engine, failure: Optional[BaseException] = None) -> None: """Raises each loss this thread's calls reported since the last call as a :class:`DataLossWarning`. + Every loss is warned of, even after a filter turns one into an error: that first one is + raised once all are, and the later ones promoted too are added to it as notes. After a + failed call (``failure``), each promoted warning is added to that exception as a note + instead, and nothing is raised here. + Args: engine: The session's engine. + failure: The exception the call raised, if it failed. """ + raised: Optional[Warning] = None for kind, code, text in engine._take_losses(): category = _LOSS_WARNINGS.get(kind, DataLossWarning) - warnings.warn(category(f"{text} [{code}]", code), skip_file_prefixes=_PACKAGE) + try: + warnings.warn(category(f"{text} [{code}]", code), skip_file_prefixes=_PACKAGE) + except Warning as promoted: + noted = failure if failure is not None else raised + if noted is None: + raised = promoted + else: + noted.add_note(f"{type(promoted).__name__}: {promoted}") + if raised is not None: + raise raised def _native(engine: _Engine, operation: Any, *args: Any) -> Any: @@ -126,10 +142,7 @@ def _native(engine: _Engine, operation: Any, *args: Any) -> Any: try: result = operation(*args) except BaseException as failure: - try: - _warn_losses(engine) - except Warning as promoted: - failure.add_note(f"{type(promoted).__name__}: {promoted}") + _warn_losses(engine, failure) raise _warn_losses(engine) return result diff --git a/apps/rustgis-python/tests/test_session.py b/apps/rustgis-python/tests/test_session.py index f15ba70cff..86cd0956dd 100644 --- a/apps/rustgis-python/tests/test_session.py +++ b/apps/rustgis-python/tests/test_session.py @@ -203,6 +203,29 @@ def test_a_failed_command_keeps_its_error_and_still_says_its_loss(): s.run("script.run", script=script) +def test_every_loss_of_a_call_is_said_when_one_is_an_error(tmp_path): + lossy = tmp_path / "lossy.rss" + lossy.write_text(_feed("1 x")) + add = json.dumps({"url": "https://maps.example.com/wms", "layer": "roads", "text": _WMS}) + script = f"layer.addData {json.dumps({'path': str(lossy)})}\nservice.add {add}" + s = rustgis.Session() + # The first promoted warning is raised once the others are said, each in a note. + with warnings.catch_warnings(): + warnings.filterwarnings("error", category=rustgis.DataLossWarning) + with pytest.raises(rustgis.DataLossWarning) as raised: + s.run("script.run", script=script) + codes = {raised.value.code} | {code for code in ("dropped.ring", "dropped.legend") if any(code in n for n in raised.value.__notes__)} + assert codes == {"dropped.ring", "dropped.legend"} + # A failed call keeps its own error, with each promoted warning as a note. + failing = f"{script}\nlayer.addDataText {json.dumps({'fileName': 'broken.geojson', 'text': '{'})}" + with warnings.catch_warnings(): + warnings.filterwarnings("error", category=rustgis.DataLossWarning) + with pytest.raises(rustgis.RustGISError) as failed: + s.run("script.run", script=failing) + notes = " ".join(failed.value.__notes__) + assert "[dropped.legend]" in notes + + @pytest.mark.parametrize("as_text", [False, True]) def test_pmtiles_options_survive_a_project_round_trip(as_text): """The Python names reach the engine, including JSON-text styles and extensionless URLs.""" diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index 16546be806..1c9e927b8d 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -473,7 +473,29 @@ pub fn run_with_budget(s: &mut Session, call: &ToolCall, tokens: usize, scope: S if call.name == "run" { return run_script(s, call, tokens, scope, permit); } - run_with_budget_inner(s, call, tokens, scope, permit).map_err(|e| public_error(&e)) + run_with_budget_inner(s, call, tokens, scope, permit).map_err(|e| match e { + Failure::Plain(e) => public_error(&e), + Failure::Clean(e) => e, + }) +} + +/// A call's failure, which [`run_with_budget`] cleans of login values; a command's failure is +/// cleaned already, with the codes of its losses added after cleaning ([`error_with_notices`]). +enum Failure { + Plain(String), + Clean(String), +} + +impl From for Failure { + fn from(e: String) -> Self { + Self::Plain(e) + } +} + +impl From<&str> for Failure { + fn from(e: &str) -> Self { + Self::Plain(e.into()) + } } /// Adapter-owned presentation state for one already-admitted archive command. Execution @@ -491,12 +513,12 @@ impl CommandCompletion { pub(crate) fn finish(self, s: &mut Session, result: Result) -> Result { result .map(|value| command_result(s, value, &self.before, &self.said, DEFAULT_OUTPUT_TOKENS)) - .map_err(|e| public_error(&error_with_notices(e, s, &self.said))) + .map_err(|e| error_with_notices(e, s, &self.said, DEFAULT_OUTPUT_TOKENS)) } } /// Retains the initiating scope and one-use permit while assembling ordinary tool results. -fn run_with_budget_inner(s: &mut Session, call: &ToolCall, tokens: usize, scope: Scope, permit: Option) -> Result { +fn run_with_budget_inner(s: &mut Session, call: &ToolCall, tokens: usize, scope: Scope, permit: Option) -> Result { if matches!(call.name.as_str(), "run_command" | "run_tool") { if call.name == "run_command" && str_arg(&call.args, "command").is_some_and(|id| id.starts_with("ui.")) { return Err("ui.* commands only open panes and dialogs; the assistant can't use them".into()); @@ -507,13 +529,13 @@ fn run_with_budget_inner(s: &mut Session, call: &ToolCall, tokens: usize, scope: Some(p) => s.run_permitted(scope, p, &engine), None => s.run_scoped(scope, &engine), } - .map_err(|e| error_with_notices(e, s, &said))?; + .map_err(|e| Failure::Clean(error_with_notices(e, s, &said, tokens)))?; return Ok(command_result(s, result, &before, &said, tokens)); } if permit.is_some() { return Err("this approval is for an executable call".into()); } - s.with_scope(scope, |s| run_read(s, call, tokens))? + s.with_scope(scope, |s| run_read(s, call, tokens))?.map_err(Failure::Plain) } fn run_read(s: &mut Session, call: &ToolCall, tokens: usize) -> Result { @@ -620,8 +642,8 @@ fn command_result(s: &mut Session, value: Value, before: &[(String, Vec)], let value = public_addresses(value, 0, &mut withheld); let value = with_notices(with_new_layers(value, s, before), s, said.mark); // Added after cleaning: its keys and codes are fixed, and its text was cleaned on its own. - let value = with_losses(value, losses_since(s, said), tokens, false); - finish_result(s, value, tokens, withheld) + let losses = losses_since(s, said); + finish_with_losses(s, value, losses, tokens, withheld, false) } /// Publishes counted projection losses without sending the completed envelope through a second redactor. @@ -825,7 +847,7 @@ fn run_script(s: &mut Session, call: &ToolCall, tokens: usize, scope: Scope, per let out = json!({"success": true, "result": last, "lines": ran.map_or(0, Vec::len), "layersAdded": added, "notices": notices, "error": null, "duration_s": secs}); let (out, withheld) = public_projection(out); - Ok(finish_result(s, with_losses(out, losses, tokens, true), tokens, withheld)) + Ok(finish_with_losses(s, out, losses, tokens, withheld, true)) } Err(e) => { let e = public_error(&e); @@ -836,7 +858,7 @@ fn run_script(s: &mut Session, call: &ToolCall, tokens: usize, scope: Scope, per let out = json!({"success": false, "result": null, "lines": 0, "layersAdded": [], "notices": said, "error": clip(&e, 8000), "duration_s": secs}); let (out, withheld) = public_projection(out); - Err(finish_result(s, with_losses(out, losses, tokens, true), tokens, withheld)) + Err(finish_with_losses(s, out, losses, tokens, withheld, true)) } } } @@ -897,44 +919,80 @@ fn losses_since(s: &Session, said: &Said) -> Vec { out } -/// `r` with `losses` (or `[]` when `always`), within the output budget: when the whole list -/// doesn't fit beside what `r` holds, each entry keeps only its code and kind, and -/// `lossesTrimmed` says so. A result already over the budget is left as it is. -fn with_losses(r: Value, losses: Vec, tokens: usize, always: bool) -> Value { - let Value::Object(mut o) = r else { return r }; +/// [`finish_result`] for `r` with `losses` (or `[]` when `always`), within the output budget. +/// When the whole list doesn't fit beside what `r` holds, each entry keeps only its code and +/// kind; when that doesn't fit either, one entry per code with its count ([`loss_summary`]) is +/// kept, and the rest of the result is cut to leave it room. `lossesTrimmed` says when either +/// happened, so the codes are never left out without a word. +fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usize, withheld: Withheld, always: bool) -> String { + let Value::Object(o) = r else { return finish_result(s, r, tokens, withheld) }; if o.contains_key("losses") || (losses.is_empty() && !always) { - return Value::Object(o); + return finish_result(s, Value::Object(o), tokens, withheld); } - let room = output_bytes(tokens).saturating_sub(Value::Object(o.clone()).to_string().len()); - let full = json!(losses); - if full.to_string().len() + 12 <= room { - o.insert("losses".into(), full); - } else { - let short: Vec = losses.iter().map(|l| json!({"code": l["code"], "kind": l["kind"]})).collect(); - let short = json!(short); - if short.to_string().len() + 40 <= room { - o.insert("losses".into(), short); + let with = |list: Value, trimmed: bool| { + let mut o = o.clone(); + o.insert("losses".into(), list); + if trimmed { o.insert("lossesTrimmed".into(), json!(true)); } + Value::Object(o) + }; + let max = output_bytes(tokens); + let compact: Vec = losses.iter().map(|l| json!({"code": l["code"], "kind": l["kind"]})).collect(); + for (list, trimmed) in [(json!(losses), false), (json!(compact), true)] { + let v = with(list, trimmed); + if v.to_string().len() <= max { + return finish_result(s, v, tokens, withheld); + } + } + let summary = loss_summary(&losses).unwrap_or_else(|| json!([])); + let reserve = summary.to_string().len() + 40; + let text = finish_result(s, Value::Object(o), max.saturating_sub(reserve).div_ceil(4).max(1), withheld); + match serde_json::from_str::(&text) { + Ok(Value::Object(mut cut)) => { + cut.insert("losses".into(), summary); + cut.insert("lossesTrimmed".into(), json!(true)); + Value::Object(cut).to_string() + } + _ => format!("{text}\nlosses: {summary}"), } - Value::Object(o) } /// A failed run's error with what the command said before failing (a GDAL layer that couldn't be /// converted). -/// A failed command can still report losses its rollback can't take back (a counted omission): -/// their codes follow, as a `losses:` line of JSON. -fn error_with_notices(e: String, s: &Session, said: &Said) -> String { +/// A failed command's error, cleaned of login values, with what the command said before failing +/// (a GDAL layer that couldn't be converted). It can still report losses its rollback can't take +/// back (a counted omission): their codes follow on a `losses:` line of JSON, added after cleaning +/// so a login can't rewrite them, and kept whole however long the rest is: the error and notices +/// are cut to leave it room within 8,000 characters and the output budget. +fn error_with_notices(e: String, s: &Session, said: &Said, tokens: usize) -> String { let told = rustgis_engine::data::diagnostics::redact(&e); let notices: Vec<&str> = s.notices_since(said.mark).iter().map(|n| n.text.as_str()).filter(|t| *t != e && *t != told).collect(); - let losses: Vec = - losses_since(s, said).iter().map(|l| json!({"code": l["code"], "kind": l["kind"], "action": l["action"]})).collect(); - // Before the notices, so the 8,000-character cap cuts them first. - let mut lines: Vec = losses.is_empty().then(Vec::new).unwrap_or_else(|| vec![format!("losses: {}", json!(losses))]); - lines.extend(notices.into_iter().map(str::to_string)); - // Preserve the original 8,000-character diagnostic assembly cap for MCP errors; - // the agent additionally applies its serialized output budget. - if lines.is_empty() { e } else { clip(&format!("{e}\n{}", lines.join("\n")), 8000) } + let Some(losses) = loss_summary(&losses_since(s, said)) else { + // Preserve the original 8,000-character diagnostic assembly cap for MCP errors; + // the agent additionally applies its serialized output budget. + return public_error(&if notices.is_empty() { e } else { clip(&format!("{e}\n{}", notices.join("\n")), 8000) }); + }; + let line = format!("\nlosses: {losses}"); + // Within the 8,000-character cap, and the agent's `{"error": …}` within its output budget. + let room = 8000.min(output_bytes(tokens).saturating_sub(64)).saturating_sub(line.chars().count()); + let text = public_error(&if notices.is_empty() { e } else { format!("{e}\n{}", notices.join("\n")) }); + // Less what `clip` adds when it cuts. + format!("{}{line}", clip(&text, room.saturating_sub(40))) +} + +/// The losses as one entry per code, `{code, kind, count, action}`: short enough to keep whole +/// when the full list can't be. `None` for none. +fn loss_summary(losses: &[Value]) -> Option { + let mut out: Vec = Vec::new(); + for l in losses { + let n = l.get("count").and_then(Value::as_u64).unwrap_or(1); + match out.iter_mut().find(|o| o["code"] == l["code"]) { + Some(o) => o["count"] = json!(o["count"].as_u64().unwrap_or(0).saturating_add(n)), + None => out.push(json!({"code": l["code"], "kind": l["kind"], "count": n, "action": l["action"]})), + } + } + (!out.is_empty()).then(|| json!(out)) } /// How well `words` match `hay` (all lower case): matched words, with whole-id hits counting more. @@ -1508,22 +1566,46 @@ mod tests { let out = run(&mut s, &script(line(&lossy))); assert_eq!(out["losses"][0]["code"], "dropped.legend", "{out}"); assert!(out["losses"][0].get("code").is_some() && !out["losses"][0]["text"].as_str().unwrap().contains("legend"), "{out}"); + let error = run_with_budget(&mut s, &command, DEFAULT_OUTPUT_TOKENS, scope.clone(), None).unwrap_err(); + assert!(error.contains(r#""code":"dropped.legend""#), "a failure's code isn't cleaned either: {error}"); + // An error too long to keep whole is cut, never the losses after it. + let long = format!("{}\nmap.drawingMode {}", line(&lossy), json!({"mode": "x".repeat(9000)})); + let command = + ToolCall { id: "long".into(), name: "run_command".into(), args: json!({"command": "script.run", "params": {"script": long}}) }; + let error = run_with_budget(&mut s, &command, DEFAULT_OUTPUT_TOKENS, scope.clone(), None).unwrap_err(); + let last = error.lines().last().unwrap_or_default(); + assert!(last.starts_with("losses: [") && last.contains(r#""code":"dropped.legend""#), "{last}"); + assert!(error.chars().count() <= 8000, "{}", error.chars().count()); } /// Losses that don't fit the output budget beside the result keep only their codes, so the - /// result stays whole instead of becoming a preview. + /// result stays whole; when even those don't fit, one entry per code is kept and the rest of + /// the result is cut to leave it room. #[test] fn losses_beyond_the_output_budget_keep_their_codes() { + let mut s = Session::new(rustgis_engine::Project::default()); + let mut finish = |r: Value, losses: Vec, always: bool| -> Value { + serde_json::from_str(&finish_with_losses(&mut s, r, losses, 200, Withheld::default(), always)).unwrap() + }; let loss = json!({"code": "dropped.value", "kind": "dropped", "text": "x".repeat(600), "action": "Correct the value."}); - let out = with_losses(json!({"notices": ["n"]}), vec![loss.clone(), loss], 200, false); + let out = finish(json!({"notices": ["n"]}), vec![loss.clone(), loss.clone()], false); assert_eq!(out["losses"], json!([{"code": "dropped.value", "kind": "dropped"}, {"code": "dropped.value", "kind": "dropped"}])); - assert_eq!(out["lossesTrimmed"], true); - assert!(out.to_string().len() <= output_bytes(200)); + assert_eq!((&out["lossesTrimmed"], &out["notices"]), (&json!(true), &json!(["n"]))); let small = json!({"code": "dropped.value", "kind": "dropped", "text": "t", "action": "a"}); - let out = with_losses(json!({"notices": ["n"]}), vec![small.clone()], 200, false); + let out = finish(json!({"notices": ["n"]}), vec![small.clone()], false); assert_eq!((&out["losses"], out.get("lossesTrimmed")), (&json!([small]), None)); - assert_eq!(with_losses(json!({"notices": ["n"]}), vec![], 200, true)["losses"], json!([])); - assert!(with_losses(json!({"notices": ["n"]}), vec![], 200, false).get("losses").is_none()); + // A result over the budget by itself is cut, and keeps one entry per code with its count. + let big = json!({"notices": ["n"], "result": "y".repeat(5000)}); + let text = finish_with_losses(&mut s, big, vec![loss.clone(), loss], 200, Withheld::default(), false); + assert!(text.len() <= output_bytes(200), "{}", text.len()); + let out: Value = serde_json::from_str(&text).unwrap(); + assert_eq!(out["losses"], json!([{"code": "dropped.value", "kind": "dropped", "count": 2, "action": "Correct the value."}])); + assert_eq!((&out["lossesTrimmed"], &out["truncated"]), (&json!(true), &json!(true))); + let mut finish = |r: Value, always: bool| -> Value { + serde_json::from_str(&finish_with_losses(&mut s, r, vec![], 200, Withheld::default(), always)).unwrap() + }; + assert_eq!(finish(json!({"notices": ["n"]}), true)["losses"], json!([])); + assert!(finish(json!({"notices": ["n"]}), false).get("losses").is_none()); } #[test] From 6a90f8610960af174ee62be86c61e9327b8951d0 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 20:06:56 -0600 Subject: [PATCH 04/21] fix(mcp): fit loss codes in bytes and keep them, with success, in cut results --- crates/assistant/src/tools.rs | 140 ++++++++++++++++++++++++++-------- 1 file changed, 107 insertions(+), 33 deletions(-) diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index 1c9e927b8d..4de437763a 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -920,42 +920,76 @@ fn losses_since(s: &Session, said: &Said) -> Vec { } /// [`finish_result`] for `r` with `losses` (or `[]` when `always`), within the output budget. -/// When the whole list doesn't fit beside what `r` holds, each entry keeps only its code and -/// kind; when that doesn't fit either, one entry per code with its count ([`loss_summary`]) is -/// kept, and the rest of the result is cut to leave it room. `lossesTrimmed` says when either -/// happened, so the codes are never left out without a word. +/// The list shrinks until it fits beside `r` ([`loss_forms`]): each entry's code and kind, one +/// entry per code, and at last the codes alone. When none fits beside `r` whole, `r` is cut to +/// leave room for one entry per code, keeping its `success`, and the list shrinks again if it +/// must. `lossesTrimmed` says when the list was shortened or, with the tightest budgets, left out. fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usize, withheld: Withheld, always: bool) -> String { let Value::Object(o) = r else { return finish_result(s, r, tokens, withheld) }; if o.contains_key("losses") || (losses.is_empty() && !always) { return finish_result(s, Value::Object(o), tokens, withheld); } - let with = |list: Value, trimmed: bool| { - let mut o = o.clone(); - o.insert("losses".into(), list); - if trimmed { + let max = output_bytes(tokens); + let forms = loss_forms(&losses); + let with = |mut o: serde_json::Map, (list, trimmed): &(Value, bool)| { + o.insert("losses".into(), list.clone()); + if *trimmed { o.insert("lossesTrimmed".into(), json!(true)); } Value::Object(o) }; - let max = output_bytes(tokens); - let compact: Vec = losses.iter().map(|l| json!({"code": l["code"], "kind": l["kind"]})).collect(); - for (list, trimmed) in [(json!(losses), false), (json!(compact), true)] { - let v = with(list, trimmed); - if v.to_string().len() <= max { - return finish_result(s, v, tokens, withheld); - } + if let Some(v) = forms.iter().map(|form| with(o.clone(), form)).find(|v| v.to_string().len() <= max) { + return finish_result(s, v, tokens, withheld); + } + // The result cut to leave room for one entry per code. + let summary = forms.get(2).or(forms.last()).map_or(0, |(list, _)| list.to_string().len()); + let text = finish_result(s, Value::Object(o.clone()), max.saturating_sub(summary + 64).div_ceil(4).max(1), withheld); + let mut cut = match serde_json::from_str::(&text) { + Ok(Value::Object(cut)) => cut, + // A failure's error alone (`error: …`), kept as JSON with as much of it as fits below. + _ => serde_json::Map::from_iter([("error".to_string(), json!(text))]), + }; + if let Some(success) = o.get("success") { + cut.insert("success".into(), success.clone()); } - let summary = loss_summary(&losses).unwrap_or_else(|| json!([])); - let reserve = summary.to_string().len() + 40; - let text = finish_result(s, Value::Object(o), max.saturating_sub(reserve).div_ceil(4).max(1), withheld); - match serde_json::from_str::(&text) { - Ok(Value::Object(mut cut)) => { - cut.insert("losses".into(), summary); - cut.insert("lossesTrimmed".into(), json!(true)); - Value::Object(cut).to_string() + for form in forms.iter().skip(2) { + let v = with(cut.clone(), form); + let over = v.to_string().len().saturating_sub(max); + if over == 0 { + return v.to_string(); + } + // Only a failure's error can still give way: cut it by what's over. + if let Some(error) = v.get("error").and_then(Value::as_str) { + let mut v = v.clone(); + v["error"] = json!(clip_bytes(error, error.len().saturating_sub(over + 8))); + if v.to_string().len() <= max { + return v.to_string(); + } } - _ => format!("{text}\nlosses: {summary}"), } + cut.insert("lossesTrimmed".into(), json!(true)); + Value::Object(cut).to_string() +} + +/// `losses` in the forms [`finish_with_losses`] tries, longest first, each with whether it is +/// shortened: whole; each entry's code and kind; one entry per code ([`loss_summary`]); one entry +/// per code with its count only; the codes alone. +fn loss_forms(losses: &[Value]) -> Vec<(Value, bool)> { + let compact: Vec = losses.iter().map(|l| json!({"code": l["code"], "kind": l["kind"]})).collect(); + let summary = loss_summary(losses).unwrap_or_else(|| json!([])); + let counts: Vec = + summary.as_array().map(|a| a.iter().map(|e| json!({"code": e["code"], "count": e["count"]})).collect()).unwrap_or_default(); + let codes: Vec = summary.as_array().map(|a| a.iter().map(|e| e["code"].clone()).collect()).unwrap_or_default(); + vec![(json!(losses), false), (json!(compact), true), (summary, true), (json!(counts), true), (json!(codes), true)] +} + +/// The first `max` bytes of `text`, cut at a character boundary. +fn clip_bytes(text: &str, max: usize) -> String { + let mut end = max.min(text.len()); + while !text.is_char_boundary(end) { + end -= 1; + } + text[..end].to_string() } /// A failed run's error with what the command said before failing (a GDAL layer that couldn't be @@ -973,12 +1007,30 @@ fn error_with_notices(e: String, s: &Session, said: &Said, tokens: usize) -> Str // the agent additionally applies its serialized output budget. return public_error(&if notices.is_empty() { e } else { clip(&format!("{e}\n{}", notices.join("\n")), 8000) }); }; - let line = format!("\nlosses: {losses}"); - // Within the 8,000-character cap, and the agent's `{"error": …}` within its output budget. - let room = 8000.min(output_bytes(tokens).saturating_sub(64)).saturating_sub(line.chars().count()); let text = public_error(&if notices.is_empty() { e } else { format!("{e}\n{}", notices.join("\n")) }); - // Less what `clip` adds when it cuts. - format!("{}{line}", clip(&text, room.saturating_sub(40))) + // Within the 8,000-character cap, and the agent's `{"error": …}` within its output budget, + // the error giving way first and then the list ([`loss_forms`]). + let fits = |t: &str| t.chars().count() <= 8000 && json!({"error": t}).to_string().len() <= output_bytes(tokens); + let raw: Vec = losses.as_array().cloned().unwrap_or_default(); + for (list, _) in loss_forms(&raw).into_iter().skip(2) { + let line = format!("\nlosses: {list}"); + if !fits(&line) { + continue; + } + if fits(&format!("{text}{line}")) { + return format!("{text}{line}"); + } + // The longest start of the error that leaves the line room. + let chars: Vec = text.chars().collect(); + let cut = |keep: usize| format!("{}…{line}", chars.iter().take(keep).collect::()); + let (mut low, mut high) = (0, chars.len()); + while low < high { + let mid = low + (high - low).div_ceil(2); + if fits(&cut(mid)) { low = mid } else { high = mid - 1 } + } + return cut(low); + } + clip(&text, 8000) } /// The losses as one entry per code, `{code, kind, count, action}`: short enough to keep whole @@ -1576,6 +1628,14 @@ mod tests { let last = error.lines().last().unwrap_or_default(); assert!(last.starts_with("losses: [") && last.contains(r#""code":"dropped.legend""#), "{last}"); assert!(error.chars().count() <= 8000, "{}", error.chars().count()); + // Within a small output budget too, counted in the bytes of the agent's `{"error": …}`, + // with text of several bytes a character. + let wide = format!("{}\nmap.drawingMode {}", line(&lossy), json!({"mode": "界".repeat(3000)})); + let command = + ToolCall { id: "wide".into(), name: "run_command".into(), args: json!({"command": "script.run", "params": {"script": wide}}) }; + let error = run_with_budget(&mut s, &command, 200, scope.clone(), None).unwrap_err(); + assert!(json!({"error": error}).to_string().len() <= output_bytes(200), "{error}"); + assert!(error.lines().last().unwrap_or_default().contains("dropped.legend"), "{error}"); } /// Losses that don't fit the output budget beside the result keep only their codes, so the @@ -1594,13 +1654,27 @@ mod tests { let small = json!({"code": "dropped.value", "kind": "dropped", "text": "t", "action": "a"}); let out = finish(json!({"notices": ["n"]}), vec![small.clone()], false); assert_eq!((&out["losses"], out.get("lossesTrimmed")), (&json!([small]), None)); - // A result over the budget by itself is cut, and keeps one entry per code with its count. - let big = json!({"notices": ["n"], "result": "y".repeat(5000)}); - let text = finish_with_losses(&mut s, big, vec![loss.clone(), loss], 200, Withheld::default(), false); + // A result over the budget by itself is cut, keeping its `success` and one entry per code + // with its count; a tighter budget keeps the codes alone, and the tightest says only that + // they were left out, always as JSON within the budget. + let big = json!({"success": true, "notices": ["n"], "result": "y".repeat(5000)}); + let text = finish_with_losses(&mut s, big.clone(), vec![loss.clone(), loss.clone()], 200, Withheld::default(), false); assert!(text.len() <= output_bytes(200), "{}", text.len()); let out: Value = serde_json::from_str(&text).unwrap(); assert_eq!(out["losses"], json!([{"code": "dropped.value", "kind": "dropped", "count": 2, "action": "Correct the value."}])); - assert_eq!((&out["lossesTrimmed"], &out["truncated"]), (&json!(true), &json!(true))); + assert_eq!((&out["lossesTrimmed"], &out["truncated"], &out["success"]), (&json!(true), &json!(true), &json!(true))); + for tokens in [32, 8] { + let text = finish_with_losses(&mut s, big.clone(), vec![loss.clone()], tokens, Withheld::default(), false); + let out: Value = serde_json::from_str(&text).unwrap(); + assert!(text.len() <= output_bytes(tokens) || out.get("losses").is_none(), "{tokens}: {text}"); + assert_eq!((&out["lossesTrimmed"], &out["success"]), (&json!(true), &json!(true)), "{tokens}: {text}"); + } + // A failure's error alone gives way to its losses, as JSON. + let failed = json!({"success": false, "error": "e".repeat(5000)}); + let text = finish_with_losses(&mut s, failed, vec![loss.clone()], 200, Withheld::default(), true); + assert!(text.len() <= output_bytes(200), "{}", text.len()); + let out: Value = serde_json::from_str(&text).unwrap(); + assert_eq!((&out["success"], &out["losses"][0]["code"]), (&json!(false), &json!("dropped.value")), "{out}"); let mut finish = |r: Value, always: bool| -> Value { serde_json::from_str(&finish_with_losses(&mut s, r, vec![], 200, Withheld::default(), always)).unwrap() }; From e02f39c9dfce3861f24b4ec516848cd178161204 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 20:17:35 -0600 Subject: [PATCH 05/21] fix(mcp): keep the codes ahead of a cut result at the tightest budgets --- crates/assistant/src/tools.rs | 47 ++++++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 12 deletions(-) diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index 4de437763a..5dfa3d82aa 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -647,7 +647,12 @@ fn command_result(s: &mut Session, value: Value, before: &[(String, Vec)], } /// Publishes counted projection losses without sending the completed envelope through a second redactor. -fn finish_result(s: &mut Session, mut value: Value, tokens: usize, withheld: Withheld) -> String { +fn finish_result(s: &mut Session, value: Value, tokens: usize, withheld: Withheld) -> String { + bounded_json(&with_withheld(s, value, withheld), tokens) +} + +/// `value` with the notices of what cleaning it withheld, also given to the app. +fn with_withheld(s: &mut Session, mut value: Value, withheld: Withheld) -> Value { if withheld.depth > 0 || withheld.keys > 0 { let mark = s.notice_mark(); if withheld.depth > 0 { @@ -662,7 +667,7 @@ fn finish_result(s: &mut Session, mut value: Value, tokens: usize, withheld: Wit value = with_notices(value, s, mark); } } - bounded_json(&value, tokens) + value } /// Counts output withheld for depth limits or field names that collide after redaction. @@ -925,9 +930,11 @@ fn losses_since(s: &Session, said: &Said) -> Vec { /// leave room for one entry per code, keeping its `success`, and the list shrinks again if it /// must. `lossesTrimmed` says when the list was shortened or, with the tightest budgets, left out. fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usize, withheld: Withheld, always: bool) -> String { - let Value::Object(o) = r else { return finish_result(s, r, tokens, withheld) }; + // What cleaning withheld is said first, so the sizes below are the final ones. + let r = with_withheld(s, r, withheld); + let Value::Object(o) = r else { return bounded_json(&r, tokens) }; if o.contains_key("losses") || (losses.is_empty() && !always) { - return finish_result(s, Value::Object(o), tokens, withheld); + return bounded_json(&Value::Object(o), tokens); } let max = output_bytes(tokens); let forms = loss_forms(&losses); @@ -939,17 +946,18 @@ fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usi Value::Object(o) }; if let Some(v) = forms.iter().map(|form| with(o.clone(), form)).find(|v| v.to_string().len() <= max) { - return finish_result(s, v, tokens, withheld); + return v.to_string(); } // The result cut to leave room for one entry per code. let summary = forms.get(2).or(forms.last()).map_or(0, |(list, _)| list.to_string().len()); - let text = finish_result(s, Value::Object(o.clone()), max.saturating_sub(summary + 64).div_ceil(4).max(1), withheld); + let text = bounded_json(&Value::Object(o.clone()), max.saturating_sub(summary + 64).div_ceil(4).max(1)); let mut cut = match serde_json::from_str::(&text) { Ok(Value::Object(cut)) => cut, // A failure's error alone (`error: …`), kept as JSON with as much of it as fits below. _ => serde_json::Map::from_iter([("error".to_string(), json!(text))]), }; - if let Some(success) = o.get("success") { + let success = o.get("success").cloned(); + if let Some(success) = &success { cut.insert("success".into(), success.clone()); } for form in forms.iter().skip(2) { @@ -967,8 +975,19 @@ fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usi } } } - cut.insert("lossesTrimmed".into(), json!(true)); - Value::Object(cut).to_string() + // The codes before what is left of the result: then only that the list was left out. + let bare = serde_json::Map::from_iter(success.map(|v| ("success".to_string(), v))); + for form in forms.iter().skip(2) { + let v = with(bare.clone(), form); + if v.to_string().len() <= max { + return v.to_string(); + } + } + let mut v = bare; + v.insert("lossesTrimmed".into(), json!(true)); + let v = Value::Object(v).to_string(); + // The tightest budgets: the marker alone. + if v.len() <= max { v } else { json!({"lossesTrimmed": true}).to_string() } } /// `losses` in the forms [`finish_with_losses`] tries, longest first, each with whether it is @@ -1028,7 +1047,8 @@ fn error_with_notices(e: String, s: &Session, said: &Said, tokens: usize) -> Str let mid = low + (high - low).div_ceil(2); if fits(&cut(mid)) { low = mid } else { high = mid - 1 } } - return cut(low); + // With no room for even a character of the error, the line alone. + return if fits(&cut(low)) { cut(low) } else { line.trim_start().to_string() }; } clip(&text, 8000) } @@ -1663,12 +1683,15 @@ mod tests { let out: Value = serde_json::from_str(&text).unwrap(); assert_eq!(out["losses"], json!([{"code": "dropped.value", "kind": "dropped", "count": 2, "action": "Correct the value."}])); assert_eq!((&out["lossesTrimmed"], &out["truncated"], &out["success"]), (&json!(true), &json!(true), &json!(true))); - for tokens in [32, 8] { + for tokens in [32, 16] { let text = finish_with_losses(&mut s, big.clone(), vec![loss.clone()], tokens, Withheld::default(), false); let out: Value = serde_json::from_str(&text).unwrap(); - assert!(text.len() <= output_bytes(tokens) || out.get("losses").is_none(), "{tokens}: {text}"); + assert!(text.len() <= output_bytes(tokens), "{tokens}: {text}"); assert_eq!((&out["lossesTrimmed"], &out["success"]), (&json!(true), &json!(true)), "{tokens}: {text}"); + assert!(out["losses"].to_string().contains("dropped.value"), "{tokens}: {text}"); } + let text = finish_with_losses(&mut s, big.clone(), vec![loss.clone()], 8, Withheld::default(), false); + assert!(text.len() <= output_bytes(8), "{text}"); // A failure's error alone gives way to its losses, as JSON. let failed = json!({"success": false, "error": "e".repeat(5000)}); let text = finish_with_losses(&mut s, failed, vec![loss.clone()], 200, Withheld::default(), true); From 48cf82e31fa0788a142b55d17dc408f15c519267 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 21:00:15 -0600 Subject: [PATCH 06/21] fix(python): warnings skip only the package's own files; MCP errors say when their codes were left out --- apps/rustgis-python/python/rustgis/__init__.py | 2 +- crates/assistant/src/tools.rs | 12 +++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/apps/rustgis-python/python/rustgis/__init__.py b/apps/rustgis-python/python/rustgis/__init__.py index 511175b88e..31b08afeef 100644 --- a/apps/rustgis-python/python/rustgis/__init__.py +++ b/apps/rustgis-python/python/rustgis/__init__.py @@ -93,7 +93,7 @@ class AssumedWarning(DataLossWarning): } # Warnings point at the caller's line, not at this package's. -_PACKAGE = (os.path.dirname(__file__),) +_PACKAGE = (os.path.join(os.path.dirname(__file__), ""),) def _warn_losses(engine: _Engine, failure: Optional[BaseException] = None) -> None: diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index 5dfa3d82aa..608aa410f0 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -1011,13 +1011,12 @@ fn clip_bytes(text: &str, max: usize) -> String { text[..end].to_string() } -/// A failed run's error with what the command said before failing (a GDAL layer that couldn't be -/// converted). /// A failed command's error, cleaned of login values, with what the command said before failing /// (a GDAL layer that couldn't be converted). It can still report losses its rollback can't take /// back (a counted omission): their codes follow on a `losses:` line of JSON, added after cleaning /// so a login can't rewrite them, and kept whole however long the rest is: the error and notices -/// are cut to leave it room within 8,000 characters and the output budget. +/// are cut to leave it room within 8,000 characters and the output budget. When no form of the +/// list fits, a `lossesTrimmed: true` line says the codes were left out. fn error_with_notices(e: String, s: &Session, said: &Said, tokens: usize) -> String { let told = rustgis_engine::data::diagnostics::redact(&e); let notices: Vec<&str> = s.notices_since(said.mark).iter().map(|n| n.text.as_str()).filter(|t| *t != e && *t != told).collect(); @@ -1031,8 +1030,8 @@ fn error_with_notices(e: String, s: &Session, said: &Said, tokens: usize) -> Str // the error giving way first and then the list ([`loss_forms`]). let fits = |t: &str| t.chars().count() <= 8000 && json!({"error": t}).to_string().len() <= output_bytes(tokens); let raw: Vec = losses.as_array().cloned().unwrap_or_default(); - for (list, _) in loss_forms(&raw).into_iter().skip(2) { - let line = format!("\nlosses: {list}"); + let lines = loss_forms(&raw).into_iter().skip(2).map(|(list, _)| format!("\nlosses: {list}")); + for line in lines.chain(["\nlossesTrimmed: true".to_string()]) { if !fits(&line) { continue; } @@ -1656,6 +1655,9 @@ mod tests { let error = run_with_budget(&mut s, &command, 200, scope.clone(), None).unwrap_err(); assert!(json!({"error": error}).to_string().len() <= output_bytes(200), "{error}"); assert!(error.lines().last().unwrap_or_default().contains("dropped.legend"), "{error}"); + // With no room for even the codes, a line says they were left out. + let error = run_with_budget(&mut s, &command, 9, scope.clone(), None).unwrap_err(); + assert!(error.ends_with("lossesTrimmed: true"), "{error}"); } /// Losses that don't fit the output budget beside the result keep only their codes, so the From 31613eca604174dc1d8442c12c192b8b1630bc0f Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 21:30:13 -0600 Subject: [PATCH 07/21] fix(python): loss warnings pickle; MCP losses fit the tightest budgets; docs give the trimmed forms --- apps/rustgis-python/python/rustgis/__init__.py | 9 +++++++++ apps/rustgis-python/tests/test_session.py | 4 ++++ crates/assistant/src/tools.rs | 16 +++++++++++++--- docs/mcp.md | 2 +- 4 files changed, 27 insertions(+), 4 deletions(-) diff --git a/apps/rustgis-python/python/rustgis/__init__.py b/apps/rustgis-python/python/rustgis/__init__.py index 31b08afeef..bd80c1b12a 100644 --- a/apps/rustgis-python/python/rustgis/__init__.py +++ b/apps/rustgis-python/python/rustgis/__init__.py @@ -68,6 +68,15 @@ def __init__(self, message: str, code: str) -> None: self.code = code self.kind = code.split(".", 1)[0] + def __reduce__(self) -> Tuple[Any, ...]: + """Pickles with the code and what was added to it (notes), so a warning turned into an + error crosses a process boundary, as in a process pool. + + Returns: + The class, its arguments and its state. + """ + return (type(self), (self.args[0], self.code), self.__dict__) + class DroppedWarning(DataLossWarning): """Something in the input isn't in the result (``dropped.*`` codes).""" diff --git a/apps/rustgis-python/tests/test_session.py b/apps/rustgis-python/tests/test_session.py index 86cd0956dd..8414ec7db4 100644 --- a/apps/rustgis-python/tests/test_session.py +++ b/apps/rustgis-python/tests/test_session.py @@ -139,6 +139,10 @@ def test_losses_are_warnings_with_their_code(tmp_path): s.add_data(lossy) [warning] = [w for w in seen if issubclass(w.category, rustgis.DataLossWarning)] assert (warning.message.code, warning.message.kind) == ("dropped.ring", "dropped") + import pickle + + copy = pickle.loads(pickle.dumps(warning.message)) + assert (type(copy), str(copy), copy.code) == (rustgis.DroppedWarning, str(warning.message), "dropped.ring") assert warning.filename == __file__, "the warning points at the caller's line" text = str(warning.message).removesuffix(" [dropped.ring]") assert (text, False) in s.notices(), "the notice is kept too" diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index 608aa410f0..c8b36edbff 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -987,7 +987,15 @@ fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usi v.insert("lossesTrimmed".into(), json!(true)); let v = Value::Object(v).to_string(); // The tightest budgets: the marker alone. - if v.len() <= max { v } else { json!({"lossesTrimmed": true}).to_string() } + // The tightest budgets: the marker alone, else nothing a client could misread. + let marker = json!({"lossesTrimmed": true}).to_string(); + if v.len() <= max { + v + } else if marker.len() <= max { + marker + } else { + "{}".to_string() + } } /// `losses` in the forms [`finish_with_losses`] tries, longest first, each with whether it is @@ -1692,8 +1700,10 @@ mod tests { assert_eq!((&out["lossesTrimmed"], &out["success"]), (&json!(true), &json!(true)), "{tokens}: {text}"); assert!(out["losses"].to_string().contains("dropped.value"), "{tokens}: {text}"); } - let text = finish_with_losses(&mut s, big.clone(), vec![loss.clone()], 8, Withheld::default(), false); - assert!(text.len() <= output_bytes(8), "{text}"); + for tokens in 1..=8 { + let text = finish_with_losses(&mut s, big.clone(), vec![loss.clone()], tokens, Withheld::default(), false); + assert!(text.len() <= output_bytes(tokens), "{tokens}: {text}"); + } // A failure's error alone gives way to its losses, as JSON. let failed = json!({"success": false, "error": "e".repeat(5000)}); let text = finish_with_losses(&mut s, failed, vec![loss.clone()], 200, Withheld::default(), true); diff --git a/docs/mcp.md b/docs/mcp.md index adee011fa6..17522504d4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -342,7 +342,7 @@ These behavioral tests in `crates/assistant/src/relay.rs` check the requirements | `view_map` | The map as a PNG image at the current view; `width` and `height` default to 1024 × 640, each clamped to 64–2048 pixels. A picture over 3.75 MiB (a satellite basemap near 2048 pixels) is drawn again smaller, and its caption gives the size drawn and the size asked. `layout` (a layout's name) draws its page instead, fitted to `width` (and `height` when given); `region` draws part of either at full detail: `[x, y, w, h]` in mm on a layout (up to 600 dpi), `[west, south, east, north]` in degrees on the map. What drawing it said (texts cut off, layers without their cast shadows) follows the caption | | `snapshot` | The map as a PNG with JSON metadata: `mode`, `width`, `height`, `extent` (longitude/latitude), `center`, `scale`, `projection`, `render_settled`, `saved` and `note`. `mode: "screen"` captures the RustGIS window through the relay, once the map has finished drawing or after `wait_s` seconds (default 5, clamped to 0–30); `overlays: false` leaves out the map's controls, scale bar, north arrow and sketches. `mode: "render"` draws offscreen at `max_width` (default 1024, clamped to 64–2048 pixels); height follows the view's shape, with each side capped at 2048. It works while the window is hidden. `mode: "auto"` (default) takes the screen when the map is on it. Unavailable screen captures fall back to render. `save_path` also writes the PNG to a file, which needs file access | | `search_commands` | Finds RustGIS commands by words: their ids, ribbon locations and parameters | -| `run_command` | Runs a command by id with JSON parameters; each run that changes the project is one undo step. The result names the layers it added (`layersAdded`) and what the command said beside it (`notices`), including any parameters it ignored (`layer.moveDown ignores 'steps' (it reads layer)`). A notice that reports lost data is also in `losses`, as `{code, kind, text, action}`, with a [loss code](cli.md#loss-codes) an agent can match: for an `assumed.*` code it can ask instead of guessing | +| `run_command` | Runs a command by id with JSON parameters; each run that changes the project is one undo step. The result names the layers it added (`layersAdded`) and what the command said beside it (`notices`), including any parameters it ignored (`layer.moveDown ignores 'steps' (it reads layer)`). A notice that reports lost data with a [loss code](cli.md#loss-codes) is also in `losses`, as `{code, kind, text, action}`, so an agent can match the code: for an `assumed.*` code it can ask instead of guessing. A loss that has no code yet is only in `notices`. When the list doesn't fit the output budget beside the result, it is shortened (each entry's `code` and `kind`, then one entry per code with its `count`, then the codes alone) and `lossesTrimmed` is `true`; with the tightest budgets `losses` is left out and only `lossesTrimmed` says so. A failed command's error ends with a `losses:` line of JSON in the same forms, or `lossesTrimmed: true` | | `run` | Runs several commands in one call, as one undo step (none when its lines only read the project, moved the view, exported, left a request, or ran a command that reports it changed nothing, such as a move to where the layers already are; a line that sets a value to the one it has still counts): a script in the `script.run` format (one `command-id {json}` per line, `#` comments). A failing line stops it, nothing it did to the project is kept, and the error names the line; files an earlier line wrote (an export) stay written. Answers `{success, result, lines, layersAdded, notices, losses, error, duration_s}`, where `result` is the last command's. Each line follows `run_command`'s rules, checked before any line runs | | `search_tools` | Finds geoprocessing tools by words | | `describe_tool` | A geoprocessing tool's parameters | From 77c24aeb4ec66e06d858f4017d8aaacff6294c8c Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 22:16:03 -0600 Subject: [PATCH 08/21] fix(mcp): a shortened entry for losses not kept keeps its count --- crates/assistant/src/tools.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index c8b36edbff..644374fb27 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -1002,7 +1002,17 @@ fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usi /// shortened: whole; each entry's code and kind; one entry per code ([`loss_summary`]); one entry /// per code with its count only; the codes alone. fn loss_forms(losses: &[Value]) -> Vec<(Value, bool)> { - let compact: Vec = losses.iter().map(|l| json!({"code": l["code"], "kind": l["kind"]})).collect(); + // An entry for losses whose notices weren't kept keeps its count. + let compact: Vec = losses + .iter() + .map(|l| { + let mut e = json!({"code": l["code"], "kind": l["kind"]}); + if let Some(n) = l.get("count") { + e["count"] = n.clone(); + } + e + }) + .collect(); let summary = loss_summary(losses).unwrap_or_else(|| json!([])); let counts: Vec = summary.as_array().map(|a| a.iter().map(|e| json!({"code": e["code"], "count": e["count"]})).collect()).unwrap_or_default(); @@ -1681,6 +1691,10 @@ mod tests { let out = finish(json!({"notices": ["n"]}), vec![loss.clone(), loss.clone()], false); assert_eq!(out["losses"], json!([{"code": "dropped.value", "kind": "dropped"}, {"code": "dropped.value", "kind": "dropped"}])); assert_eq!((&out["lossesTrimmed"], &out["notices"]), (&json!(true), &json!(["n"]))); + // An entry for losses whose notices weren't kept keeps its count when shortened. + let unkept = json!({"code": "dropped.value", "kind": "dropped", "count": 250, "text": "x".repeat(900), "action": "a"}); + let out = finish(json!({"notices": ["n"]}), vec![unkept], false); + assert_eq!(out["losses"], json!([{"code": "dropped.value", "kind": "dropped", "count": 250}]), "{out}"); let small = json!({"code": "dropped.value", "kind": "dropped", "text": "t", "action": "a"}); let out = finish(json!({"notices": ["n"]}), vec![small.clone()], false); assert_eq!((&out["losses"], out.get("lossesTrimmed")), (&json!([small]), None)); From b8298b058e8559eb3bebffefb33d651f29303aed Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 22:39:10 -0600 Subject: [PATCH 09/21] fix(mcp): a cut failure keeps its error as text, and the tightest budgets keep a marker --- crates/assistant/src/tools.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index 644374fb27..66364e1223 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -954,6 +954,7 @@ fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usi let mut cut = match serde_json::from_str::(&text) { Ok(Value::Object(cut)) => cut, // A failure's error alone (`error: …`), kept as JSON with as much of it as fits below. + Ok(Value::String(preview)) => serde_json::Map::from_iter([("error".to_string(), json!(preview))]), _ => serde_json::Map::from_iter([("error".to_string(), json!(text))]), }; let success = o.get("success").cloned(); @@ -987,12 +988,16 @@ fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usi v.insert("lossesTrimmed".into(), json!(true)); let v = Value::Object(v).to_string(); // The tightest budgets: the marker alone. - // The tightest budgets: the marker alone, else nothing a client could misread. + // The tightest budgets: the marker alone, then its name alone; below that (15 bytes) no + // marker fits, and nothing a client could misread is said. let marker = json!({"lossesTrimmed": true}).to_string(); + let name = json!("lossesTrimmed").to_string(); if v.len() <= max { v } else if marker.len() <= max { marker + } else if name.len() <= max { + name } else { "{}".to_string() } @@ -1724,6 +1729,7 @@ mod tests { assert!(text.len() <= output_bytes(200), "{}", text.len()); let out: Value = serde_json::from_str(&text).unwrap(); assert_eq!((&out["success"], &out["losses"][0]["code"]), (&json!(false), &json!("dropped.value")), "{out}"); + assert!(out["error"].as_str().unwrap().starts_with("error: eee"), "the error as text, not encoded twice: {out}"); let mut finish = |r: Value, always: bool| -> Value { serde_json::from_str(&finish_with_losses(&mut s, r, vec![], 200, Withheld::default(), always)).unwrap() }; From 92ede8504108742865fa3bf0c9840b7e01ece22f Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 22:57:26 -0600 Subject: [PATCH 10/21] fix(mcp): size loss forms without serializing the result again; run_tool says it gives losses --- crates/assistant/src/tools.rs | 17 +++++++++++------ docs/mcp.md | 2 +- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index 66364e1223..ddf743727e 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -101,7 +101,7 @@ pub fn defs() -> Vec { }, ToolDef { name: "run_tool", - description: "Run a geoprocessing tool. Its output is added to the map as a new layer, or to the project as a standalone table (for example Summary Statistics), whose name the result gives (use it as the input of a next step; read a table with read_features). One undo step.", + description: "Run a geoprocessing tool. Its output is added to the map as a new layer, or to the project as a standalone table (for example Summary Statistics), whose name the result gives (use it as the input of a next step; read a table with read_features). One undo step. As for run_command, a notice that reports lost data is also in the result's losses, as {code, kind, text, action}.", schema: json!({ "type": "object", "properties": { @@ -859,8 +859,8 @@ fn run_script(s: &mut Session, call: &ToolCall, tokens: usize, scope: Scope, per // Nothing was kept, so no line ran and no layer was added. // The notice of the failure is the error redacted: compared as such, it isn't repeated. let told = rustgis_engine::data::diagnostics::redact(&e); - let said: Vec<&&str> = notices.iter().filter(|t| **t != e && **t != told).collect(); - let out = json!({"success": false, "result": null, "lines": 0, "layersAdded": [], "notices": said, + let kept: Vec<&&str> = notices.iter().filter(|t| **t != e && **t != told).collect(); + let out = json!({"success": false, "result": null, "lines": 0, "layersAdded": [], "notices": kept, "error": clip(&e, 8000), "duration_s": secs}); let (out, withheld) = public_projection(out); Err(finish_with_losses(s, out, losses, tokens, withheld, true)) @@ -945,8 +945,14 @@ fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usi } Value::Object(o) }; - if let Some(v) = forms.iter().map(|form| with(o.clone(), form)).find(|v| v.to_string().len() <= max) { - return v.to_string(); + // Sized from the parts, so the result is serialized once: its own bytes, then each form's + // with its key (and `lossesTrimmed`'s). + let base = Value::Object(o.clone()).to_string().len(); + let size = |(list, trimmed): &(Value, bool)| { + base + list.to_string().len() + r#","losses":"#.len() + if *trimmed { r#","lossesTrimmed":true"#.len() } else { 0 } + }; + if let Some(form) = forms.iter().find(|form| size(form) <= max) { + return with(o, form).to_string(); } // The result cut to leave room for one entry per code. let summary = forms.get(2).or(forms.last()).map_or(0, |(list, _)| list.to_string().len()); @@ -987,7 +993,6 @@ fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usi let mut v = bare; v.insert("lossesTrimmed".into(), json!(true)); let v = Value::Object(v).to_string(); - // The tightest budgets: the marker alone. // The tightest budgets: the marker alone, then its name alone; below that (15 bytes) no // marker fits, and nothing a client could misread is said. let marker = json!({"lossesTrimmed": true}).to_string(); diff --git a/docs/mcp.md b/docs/mcp.md index 17522504d4..2923e3a985 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -346,7 +346,7 @@ These behavioral tests in `crates/assistant/src/relay.rs` check the requirements | `run` | Runs several commands in one call, as one undo step (none when its lines only read the project, moved the view, exported, left a request, or ran a command that reports it changed nothing, such as a move to where the layers already are; a line that sets a value to the one it has still counts): a script in the `script.run` format (one `command-id {json}` per line, `#` comments). A failing line stops it, nothing it did to the project is kept, and the error names the line; files an earlier line wrote (an export) stay written. Answers `{success, result, lines, layersAdded, notices, losses, error, duration_s}`, where `result` is the last command's. Each line follows `run_command`'s rules, checked before any line runs | | `search_tools` | Finds geoprocessing tools by words | | `describe_tool` | A geoprocessing tool's parameters | -| `run_tool` | Runs a geoprocessing tool; its output is added to the map as a new layer (with `layersAdded` and `notices` as for `run_command`), or to the project as a standalone table, which the result names (`table`) | +| `run_tool` | Runs a geoprocessing tool; its output is added to the map as a new layer (with `layersAdded`, `notices` and `losses` as for `run_command`), or to the project as a standalone table, which the result names (`table`) | | `read_features` | A vector layer's or a standalone table's attribute rows: `layer` (name or id) or `table` (a standalone table's name or id; a `layer` name that no layer has reads the table of that name), optional `where`, `fields`, `order_by`, `descending` and `selected` (layers only); `limit` defaults to 20, capped at 200. Returns the matching count and rows with `_row`, and a layer's `_lon` and `_lat` | | `search_docs` | Searches this documentation and returns the best matching sections | | `read_doc` | Reads a documentation page or section as Markdown; `offset` (1-based line) and `limit` (default 2000 lines) page through long results using `next_offset` | From a765187bb0fc6144a637bad77d39451cd24341b8 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 23:21:39 -0600 Subject: [PATCH 11/21] fix(python): peer-text calls raise their own losses; a result with its own losses keeps it under result --- apps/rustgis-python/python/rustgis/_embed.py | 7 ++++--- crates/assistant/src/tools.rs | 11 ++++++++++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/apps/rustgis-python/python/rustgis/_embed.py b/apps/rustgis-python/python/rustgis/_embed.py index da7b45f8a7..ca23621a18 100644 --- a/apps/rustgis-python/python/rustgis/_embed.py +++ b/apps/rustgis-python/python/rustgis/_embed.py @@ -18,7 +18,7 @@ from typing import Any, Dict, Iterable, List, Optional, Tuple, Union from urllib.parse import quote -from . import PathLike, RustGISError, Session, _Api +from . import PathLike, RustGISError, Session, _Api, _native #: The web app the widgets show; ``RUSTGIS_WEB_URL`` points them at another build (a local #: ``trunk serve``, a self-hosted copy). @@ -205,7 +205,8 @@ def to_png( def _push(self) -> None: """Sends the session's project to the app, when it changed.""" try: - text, keys, notices = self._session._engine._peer_text() + engine = self._session._engine + text, keys, notices = _native(engine, engine._peer_text) # A new loss may leave the public project text unchanged. if text != self._project or notices != self._sent_notices: self._hold([(notice, False) for notice in notices]) @@ -246,7 +247,7 @@ def _from_app(self, content: Any) -> None: # Peer input is an import: keep its containment notices and invalidate old trust. self._hold(self._session.notices()) try: - self._session._engine._open_peer_text(text) + _native(engine, engine._open_peer_text, text) except RustGISError as e: self._hold([(f"the app's project couldn't be read: {e}", True)]) return diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index ddf743727e..9637c5ee6b 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -933,9 +933,12 @@ fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usi // What cleaning withheld is said first, so the sizes below are the final ones. let r = with_withheld(s, r, withheld); let Value::Object(o) = r else { return bounded_json(&r, tokens) }; - if o.contains_key("losses") || (losses.is_empty() && !always) { + if losses.is_empty() && !always { return bounded_json(&Value::Object(o), tokens); } + // A result with its own `losses` goes under `result`, as a result that isn't an object does + // beside `notices`, so the codes still have their key. + let o = if o.contains_key("losses") { serde_json::Map::from_iter([("result".to_string(), Value::Object(o))]) } else { o }; let max = output_bytes(tokens); let forms = loss_forms(&losses); let with = |mut o: serde_json::Map, (list, trimmed): &(Value, bool)| { @@ -1693,6 +1696,7 @@ mod tests { /// the result is cut to leave it room. #[test] fn losses_beyond_the_output_budget_keep_their_codes() { + let small_loss = || json!({"code": "dropped.value", "kind": "dropped", "text": "t", "action": "a"}); let mut s = Session::new(rustgis_engine::Project::default()); let mut finish = |r: Value, losses: Vec, always: bool| -> Value { serde_json::from_str(&finish_with_losses(&mut s, r, losses, 200, Withheld::default(), always)).unwrap() @@ -1740,6 +1744,11 @@ mod tests { }; assert_eq!(finish(json!({"notices": ["n"]}), true)["losses"], json!([])); assert!(finish(json!({"notices": ["n"]}), false).get("losses").is_none()); + // A result with its own `losses` keeps it under `result`, beside the codes. + let own = json!({"losses": 3}); + let out: Value = + serde_json::from_str(&finish_with_losses(&mut s, own.clone(), vec![small_loss()], 200, Withheld::default(), false)).unwrap(); + assert_eq!((&out["result"], &out["losses"][0]["code"]), (&own, &json!("dropped.value")), "{out}"); } #[test] From 8a61158c7669c74076c8fc3fa5cf28b7400978a6 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 22 Nov 2026 23:54:39 -0600 Subject: [PATCH 12/21] fix(python): a project message from the app opens it through its own engine --- apps/rustgis-python/python/rustgis/_embed.py | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/rustgis-python/python/rustgis/_embed.py b/apps/rustgis-python/python/rustgis/_embed.py index ca23621a18..30fc540a00 100644 --- a/apps/rustgis-python/python/rustgis/_embed.py +++ b/apps/rustgis-python/python/rustgis/_embed.py @@ -247,6 +247,7 @@ def _from_app(self, content: Any) -> None: # Peer input is an import: keep its containment notices and invalidate old trust. self._hold(self._session.notices()) try: + engine = self._session._engine _native(engine, engine._open_peer_text, text) except RustGISError as e: self._hold([(f"the app's project couldn't be read: {e}", True)]) From 18533a02e733f4543c4242f2962cf8d7f9ca6394 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 00:37:15 -0600 Subject: [PATCH 13/21] fix(python): the widget records the app's project before raising its losses; descriptions say losses are the coded ones --- apps/rustgis-python/python/rustgis/_embed.py | 11 +++++++---- crates/assistant/src/mcp.rs | 4 ++-- crates/assistant/src/tools.rs | 4 ++-- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/apps/rustgis-python/python/rustgis/_embed.py b/apps/rustgis-python/python/rustgis/_embed.py index 30fc540a00..147563e96b 100644 --- a/apps/rustgis-python/python/rustgis/_embed.py +++ b/apps/rustgis-python/python/rustgis/_embed.py @@ -18,7 +18,7 @@ from typing import Any, Dict, Iterable, List, Optional, Tuple, Union from urllib.parse import quote -from . import PathLike, RustGISError, Session, _Api, _native +from . import PathLike, RustGISError, Session, _Api, _native, _warn_losses #: The web app the widgets show; ``RUSTGIS_WEB_URL`` points them at another build (a local #: ``trunk serve``, a self-hosted copy). @@ -246,17 +246,20 @@ def _from_app(self, content: Any) -> None: return # Peer input is an import: keep its containment notices and invalidate old trust. self._hold(self._session.notices()) + engine = self._session._engine try: - engine = self._session._engine - _native(engine, engine._open_peer_text, text) + engine._open_peer_text(text) except RustGISError as e: self._hold([(f"the app's project couldn't be read: {e}", True)]) + _warn_losses(engine, e) return finally: self._hold(self._session.notices()) # The app's own text, not the session's re-serialised copy: the app then sees its - # project and doesn't open it again. + # project and doesn't open it again. Recorded before its losses are raised, which a + # warning filter can turn into an error. self._project = text + _warn_losses(engine) elif kind == "result" and content.get("ok") is False: self._hold([(str(content.get("error", "the command failed")), True)]) diff --git a/crates/assistant/src/mcp.rs b/crates/assistant/src/mcp.rs index 2df36d538e..997d2f7517 100644 --- a/crates/assistant/src/mcp.rs +++ b/crates/assistant/src/mcp.rs @@ -488,7 +488,7 @@ fn tool_list() -> Vec { .into_iter() .map(|d| { let description = match d.name { - "run_command" => "Run a RustGIS command by id with JSON parameters (see search_commands for ids and parameters). Each run that changes the project is one undo step (edit.undo undoes it). Commands that read or write files or use the network run only when the server was started with --yes. A notice that reports lost data is also in the result's losses, as {code, kind, text, action}; for an assumed.* code, ask the user rather than guess.".to_string(), + "run_command" => "Run a RustGIS command by id with JSON parameters (see search_commands for ids and parameters). Each run that changes the project is one undo step (edit.undo undoes it). Commands that read or write files or use the network run only when the server was started with --yes. A notice that reports lost data with a loss code is also in the result's losses, as {code, kind, text, action}; for an assumed.* code, ask the user rather than guess.".to_string(), "read_doc" => { let pages: Vec<&str> = docs::PAGES.iter().map(|p| p.path).collect(); format!("Read a RustGIS documentation page or section as Markdown. Use next_offset to continue budgeted results. Pages: {}.", pages.join(", ")) @@ -500,7 +500,7 @@ fn tool_list() -> Vec { .collect(); out.push(json!({ "name": "run", - "description": "Run several RustGIS commands in one call, as one undo step (none when its lines only read the project, moved the view, exported, left a request, or ran a command that reports it changed nothing, such as a move to where the layers already are; a line that sets a value to the one it has still counts): a script with one `command-id {json}` per line (# starts a comment), e.g. `map.basemap {\"name\": \"ocean\"}`. A failing line stops the script, nothing it did to the project is kept (a file an earlier line wrote stays written), and the error names the line. Returns {success, result (the last command's), lines, layersAdded, notices, losses ({code, kind, text, action} for each notice that reports lost data), error, duration_s}. Each line follows the same rules as run_command.", + "description": "Run several RustGIS commands in one call, as one undo step (none when its lines only read the project, moved the view, exported, left a request, or ran a command that reports it changed nothing, such as a move to where the layers already are; a line that sets a value to the one it has still counts): a script with one `command-id {json}` per line (# starts a comment), e.g. `map.basemap {\"name\": \"ocean\"}`. A failing line stops the script, nothing it did to the project is kept (a file an earlier line wrote stays written), and the error names the line. Returns {success, result (the last command's), lines, layersAdded, notices, losses ({code, kind, text, action} for each notice that reports lost data with a loss code), error, duration_s}. Each line follows the same rules as run_command.", "inputSchema": { "type": "object", "properties": {"script": {"type": "string", "description": "One command per line: id {json}"}}, diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index 9637c5ee6b..1ceb5c0554 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -68,7 +68,7 @@ pub fn defs() -> Vec { }, ToolDef { name: "run_command", - description: "Run a RustGIS command by id with JSON parameters (see search_commands for ids and parameters). Project edits are undoable. Source publication and other external file writes cannot be undone. Commands that read or write files, use the network or replace the project ask the user first. A notice that reports lost data is also in the result's losses, as {code, kind, text, action}; for an assumed.* code, ask the user rather than guess.", + description: "Run a RustGIS command by id with JSON parameters (see search_commands for ids and parameters). Project edits are undoable. Source publication and other external file writes cannot be undone. Commands that read or write files, use the network or replace the project ask the user first. A notice that reports lost data with a loss code is also in the result's losses, as {code, kind, text, action}; for an assumed.* code, ask the user rather than guess.", schema: json!({ "type": "object", "properties": { @@ -101,7 +101,7 @@ pub fn defs() -> Vec { }, ToolDef { name: "run_tool", - description: "Run a geoprocessing tool. Its output is added to the map as a new layer, or to the project as a standalone table (for example Summary Statistics), whose name the result gives (use it as the input of a next step; read a table with read_features). One undo step. As for run_command, a notice that reports lost data is also in the result's losses, as {code, kind, text, action}.", + description: "Run a geoprocessing tool. Its output is added to the map as a new layer, or to the project as a standalone table (for example Summary Statistics), whose name the result gives (use it as the input of a next step; read a table with read_features). One undo step. As for run_command, a notice that reports lost data with a loss code is also in the result's losses, as {code, kind, text, action}.", schema: json!({ "type": "object", "properties": { From d7743edecb097db7bc6a5f6e1f7aee2587b02fe0 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 01:27:16 -0600 Subject: [PATCH 14/21] fix(assistant): a result that isn't an object keeps its losses; the widget raises an app message's losses on any failure --- apps/rustgis-python/python/rustgis/_embed.py | 4 ++++ crates/assistant/src/tools.rs | 12 ++++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/apps/rustgis-python/python/rustgis/_embed.py b/apps/rustgis-python/python/rustgis/_embed.py index 147563e96b..362708b24d 100644 --- a/apps/rustgis-python/python/rustgis/_embed.py +++ b/apps/rustgis-python/python/rustgis/_embed.py @@ -253,6 +253,10 @@ def _from_app(self, content: Any) -> None: self._hold([(f"the app's project couldn't be read: {e}", True)]) _warn_losses(engine, e) return + except BaseException as failure: + # Whatever else stopped it, its losses are raised with it, not by a later call. + _warn_losses(engine, failure) + raise finally: self._hold(self._session.notices()) # The app's own text, not the session's re-serialised copy: the app then sees its diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index 1ceb5c0554..df9f7d3156 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -932,7 +932,12 @@ fn losses_since(s: &Session, said: &Said) -> Vec { fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usize, withheld: Withheld, always: bool) -> String { // What cleaning withheld is said first, so the sizes below are the final ones. let r = with_withheld(s, r, withheld); - let Value::Object(o) = r else { return bounded_json(&r, tokens) }; + // A result that isn't an object goes under `result`, so the codes have their key. + let o = match r { + Value::Object(o) => o, + other if losses.is_empty() && !always => return bounded_json(&other, tokens), + other => serde_json::Map::from_iter([("result".to_string(), other)]), + }; if losses.is_empty() && !always { return bounded_json(&Value::Object(o), tokens); } @@ -1744,7 +1749,10 @@ mod tests { }; assert_eq!(finish(json!({"notices": ["n"]}), true)["losses"], json!([])); assert!(finish(json!({"notices": ["n"]}), false).get("losses").is_none()); - // A result with its own `losses` keeps it under `result`, beside the codes. + // A result that isn't an object, or has its own `losses`, goes under `result`, beside the codes. + let out: Value = + serde_json::from_str(&finish_with_losses(&mut s, json!([1, 2]), vec![small_loss()], 200, Withheld::default(), false)).unwrap(); + assert_eq!((&out["result"], &out["losses"][0]["code"]), (&json!([1, 2]), &json!("dropped.value")), "{out}"); let own = json!({"losses": 3}); let out: Value = serde_json::from_str(&finish_with_losses(&mut s, own.clone(), vec![small_loss()], 200, Withheld::default(), false)).unwrap(); From 4bd486432b0675e479517433f4d486207b05a163 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 03:16:05 -0600 Subject: [PATCH 15/21] fix(assistant): a successful result cut past its budget is said to be cut, never as an error --- crates/assistant/src/tools.rs | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index df9f7d3156..18241cf91f 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -965,11 +965,14 @@ fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usi // The result cut to leave room for one entry per code. let summary = forms.get(2).or(forms.last()).map_or(0, |(list, _)| list.to_string().len()); let text = bounded_json(&Value::Object(o.clone()), max.saturating_sub(summary + 64).div_ceil(4).max(1)); + let failed = o.contains_key("error"); let mut cut = match serde_json::from_str::(&text) { Ok(Value::Object(cut)) => cut, // A failure's error alone (`error: …`), kept as JSON with as much of it as fits below. - Ok(Value::String(preview)) => serde_json::Map::from_iter([("error".to_string(), json!(preview))]), - _ => serde_json::Map::from_iter([("error".to_string(), json!(text))]), + Ok(Value::String(preview)) if failed => serde_json::Map::from_iter([("error".to_string(), json!(preview))]), + _ if failed => serde_json::Map::from_iter([("error".to_string(), json!(text))]), + // No room for any of a result that didn't fail: only that it was cut. + _ => serde_json::Map::from_iter([("truncated".to_string(), json!(true))]), }; let success = o.get("success").cloned(); if let Some(success) = &success { @@ -990,12 +993,17 @@ fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usi } } } - // The codes before what is left of the result: then only that the list was left out. + // The codes before what is left of the result, saying it was cut where that fits: then only + // that the list was left out. let bare = serde_json::Map::from_iter(success.map(|v| ("success".to_string(), v))); + let mut said_cut = bare.clone(); + said_cut.insert("truncated".into(), json!(true)); for form in forms.iter().skip(2) { - let v = with(bare.clone(), form); - if v.to_string().len() <= max { - return v.to_string(); + for base in [&said_cut, &bare] { + let v = with(base.clone(), form); + if v.to_string().len() <= max { + return v.to_string(); + } } } let mut v = bare; @@ -1732,6 +1740,10 @@ mod tests { assert!(text.len() <= output_bytes(tokens), "{tokens}: {text}"); assert_eq!((&out["lossesTrimmed"], &out["success"]), (&json!(true), &json!(true)), "{tokens}: {text}"); assert!(out["losses"].to_string().contains("dropped.value"), "{tokens}: {text}"); + // A success cut this far is never said as an error; it is said to be cut where that + // fits beside the codes. + assert!(out.get("error").is_none(), "{tokens}: {text}"); + assert_eq!(out.get("truncated").is_some(), tokens == 32, "{tokens}: {text}"); } for tokens in 1..=8 { let text = finish_with_losses(&mut s, big.clone(), vec![loss.clone()], tokens, Withheld::default(), false); From 254eb1120114b942b4afd9c438d829d6c8b9b3ff Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 03:54:52 -0600 Subject: [PATCH 16/21] fix(assistant): run's success is cut as a success; a failure cut to its losses says so; the widget sends the project before raising its losses --- apps/rustgis-python/python/rustgis/_embed.py | 12 +++++++++--- crates/assistant/src/tools.rs | 19 ++++++++++++++----- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/apps/rustgis-python/python/rustgis/_embed.py b/apps/rustgis-python/python/rustgis/_embed.py index 362708b24d..3b7944f5a8 100644 --- a/apps/rustgis-python/python/rustgis/_embed.py +++ b/apps/rustgis-python/python/rustgis/_embed.py @@ -18,7 +18,7 @@ from typing import Any, Dict, Iterable, List, Optional, Tuple, Union from urllib.parse import quote -from . import PathLike, RustGISError, Session, _Api, _native, _warn_losses +from . import PathLike, RustGISError, Session, _Api, _warn_losses #: The web app the widgets show; ``RUSTGIS_WEB_URL`` points them at another build (a local #: ``trunk serve``, a self-hosted copy). @@ -204,9 +204,9 @@ def to_png( def _push(self) -> None: """Sends the session's project to the app, when it changed.""" + engine = self._session._engine try: - engine = self._session._engine - text, keys, notices = _native(engine, engine._peer_text) + text, keys, notices = engine._peer_text() # A new loss may leave the public project text unchanged. if text != self._project or notices != self._sent_notices: self._hold([(notice, False) for notice in notices]) @@ -216,10 +216,16 @@ def _push(self) -> None: self._sent_keys = keys except RustGISError as e: self._hold([(f"couldn't show the project in the app: {e}", True)]) + _warn_losses(engine, e) return + except BaseException as failure: + _warn_losses(engine, failure) + raise if text != self._project: self._project = text self._send_project(text) + # Raised once the app has the project, which a warning filter can turn into an error. + _warn_losses(engine) def _hold(self, notices: List[Tuple[str, bool]]) -> None: """Keeps notices for :meth:`notices`. diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index 18241cf91f..3ece950bc5 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -965,7 +965,8 @@ fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usi // The result cut to leave room for one entry per code. let summary = forms.get(2).or(forms.last()).map_or(0, |(list, _)| list.to_string().len()); let text = bounded_json(&Value::Object(o.clone()), max.saturating_sub(summary + 64).div_ceil(4).max(1)); - let failed = o.contains_key("error"); + // A result's `error` that is null (`run`'s on success) isn't a failure. + let failed = o.get("error").is_some_and(|e| !e.is_null()); let mut cut = match serde_json::from_str::(&text) { Ok(Value::Object(cut)) => cut, // A failure's error alone (`error: …`), kept as JSON with as much of it as fits below. @@ -1075,10 +1076,13 @@ fn error_with_notices(e: String, s: &Session, said: &Said, tokens: usize) -> Str let fits = |t: &str| t.chars().count() <= 8000 && json!({"error": t}).to_string().len() <= output_bytes(tokens); let raw: Vec = losses.as_array().cloned().unwrap_or_default(); let lines = loss_forms(&raw).into_iter().skip(2).map(|(list, _)| format!("\nlosses: {list}")); + // The first line that fits alone, for a budget with no room for any of the error. + let mut alone = None; for line in lines.chain(["\nlossesTrimmed: true".to_string()]) { if !fits(&line) { continue; } + alone.get_or_insert_with(|| line.trim_start().to_string()); if fits(&format!("{text}{line}")) { return format!("{text}{line}"); } @@ -1090,10 +1094,13 @@ fn error_with_notices(e: String, s: &Session, said: &Said, tokens: usize) -> Str let mid = low + (high - low).div_ceil(2); if fits(&cut(mid)) { low = mid } else { high = mid - 1 } } - // With no room for even a character of the error, the line alone. - return if fits(&cut(low)) { cut(low) } else { line.trim_start().to_string() }; + // With room for the mark that the error was cut, as much of it as fits; without, a + // shorter line may leave it room. + if fits(&cut(low)) { + return cut(low); + } } - clip(&text, 8000) + alone.unwrap_or_else(|| clip(&text, 8000)) } /// The losses as one entry per code, `{code, kind, count, action}`: short enough to keep whole @@ -1734,7 +1741,9 @@ mod tests { let out: Value = serde_json::from_str(&text).unwrap(); assert_eq!(out["losses"], json!([{"code": "dropped.value", "kind": "dropped", "count": 2, "action": "Correct the value."}])); assert_eq!((&out["lossesTrimmed"], &out["truncated"], &out["success"]), (&json!(true), &json!(true), &json!(true))); - for tokens in [32, 16] { + // `run`'s success, whose `error` is null, is cut the same way. + let run_ok = json!({"success": true, "error": null, "notices": ["n"], "result": "y".repeat(5000)}); + for (tokens, big) in [(32, &big), (16, &big), (32, &run_ok), (16, &run_ok)] { let text = finish_with_losses(&mut s, big.clone(), vec![loss.clone()], tokens, Withheld::default(), false); let out: Value = serde_json::from_str(&text).unwrap(); assert!(text.len() <= output_bytes(tokens), "{tokens}: {text}"); From 3272a647eb08127c611445c06af0e01aa8de65c6 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 04:23:07 -0600 Subject: [PATCH 17/21] fix(python): the widget raises a failed sync's losses itself, as the failure is only held --- apps/rustgis-python/python/rustgis/_embed.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/rustgis-python/python/rustgis/_embed.py b/apps/rustgis-python/python/rustgis/_embed.py index 3b7944f5a8..5c380eb191 100644 --- a/apps/rustgis-python/python/rustgis/_embed.py +++ b/apps/rustgis-python/python/rustgis/_embed.py @@ -216,7 +216,8 @@ def _push(self) -> None: self._sent_keys = keys except RustGISError as e: self._hold([(f"couldn't show the project in the app: {e}", True)]) - _warn_losses(engine, e) + # The error is held, not raised: its losses are raised themselves. + _warn_losses(engine) return except BaseException as failure: _warn_losses(engine, failure) @@ -257,7 +258,8 @@ def _from_app(self, content: Any) -> None: engine._open_peer_text(text) except RustGISError as e: self._hold([(f"the app's project couldn't be read: {e}", True)]) - _warn_losses(engine, e) + # The error is held, not raised: its losses are raised themselves. + _warn_losses(engine) return except BaseException as failure: # Whatever else stopped it, its losses are raised with it, not by a later call. From cf19628d1abdf2b1012885438a8f4bc283dc9bf1 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 05:23:40 -0600 Subject: [PATCH 18/21] fix(assistant): a failure cut to its error says it was cut; the widget drains its losses if sending the project fails --- apps/rustgis-python/python/rustgis/_embed.py | 10 +++++++--- crates/assistant/src/tools.rs | 7 +++++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/apps/rustgis-python/python/rustgis/_embed.py b/apps/rustgis-python/python/rustgis/_embed.py index 5c380eb191..7dfc49e095 100644 --- a/apps/rustgis-python/python/rustgis/_embed.py +++ b/apps/rustgis-python/python/rustgis/_embed.py @@ -222,9 +222,13 @@ def _push(self) -> None: except BaseException as failure: _warn_losses(engine, failure) raise - if text != self._project: - self._project = text - self._send_project(text) + try: + if text != self._project: + self._project = text + self._send_project(text) + except BaseException as failure: + _warn_losses(engine, failure) + raise # Raised once the app has the project, which a warning filter can turn into an error. _warn_losses(engine) diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index 3ece950bc5..958cac07b0 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -970,8 +970,10 @@ fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usi let mut cut = match serde_json::from_str::(&text) { Ok(Value::Object(cut)) => cut, // A failure's error alone (`error: …`), kept as JSON with as much of it as fits below. - Ok(Value::String(preview)) if failed => serde_json::Map::from_iter([("error".to_string(), json!(preview))]), - _ if failed => serde_json::Map::from_iter([("error".to_string(), json!(text))]), + Ok(Value::String(preview)) if failed => { + serde_json::Map::from_iter([("error".to_string(), json!(preview)), ("truncated".to_string(), json!(true))]) + } + _ if failed => serde_json::Map::from_iter([("error".to_string(), json!(text)), ("truncated".to_string(), json!(true))]), // No room for any of a result that didn't fail: only that it was cut. _ => serde_json::Map::from_iter([("truncated".to_string(), json!(true))]), }; @@ -1765,6 +1767,7 @@ mod tests { let out: Value = serde_json::from_str(&text).unwrap(); assert_eq!((&out["success"], &out["losses"][0]["code"]), (&json!(false), &json!("dropped.value")), "{out}"); assert!(out["error"].as_str().unwrap().starts_with("error: eee"), "the error as text, not encoded twice: {out}"); + assert_eq!(out["truncated"], json!(true), "the error is said to be cut: {out}"); let mut finish = |r: Value, always: bool| -> Value { serde_json::from_str(&finish_with_losses(&mut s, r, vec![], 200, Withheld::default(), always)).unwrap() }; From 482ef9b8d68b532d16239beb98333d0c65b6162f Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 06:00:54 -0600 Subject: [PATCH 19/21] fix(assistant): a result or error cut to its codes always says so; losses are taken without waiting on other sessions; a widget test pins the loss order --- apps/rustgis-python/src/lib.rs | 6 ++-- apps/rustgis-python/tests/test_widget.py | 40 ++++++++++++++++++++++++ crates/assistant/src/tools.rs | 39 +++++++++++++---------- docs/mcp.md | 2 +- 4 files changed, 67 insertions(+), 20 deletions(-) diff --git a/apps/rustgis-python/src/lib.rs b/apps/rustgis-python/src/lib.rs index 9820e35ad7..137c9732c3 100644 --- a/apps/rustgis-python/src/lib.rs +++ b/apps/rustgis-python/src/lib.rs @@ -320,9 +320,9 @@ impl Engine { fn _take_losses(&self, py: Python<'_>) -> Vec<(String, String, String)> { let thread = std::thread::current().id(); let losses = &self.losses; - // Never set aside while the session runs: its lock is taken inside the session's. - with_native(py, || { - let _session = self.session.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + // This thread's own call set them aside under the session's lock and has returned, so + // only their own lock is needed: taking them doesn't wait for another session's work. + py.detach(|| { let mut losses = losses.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let (mine, others) = std::mem::take(&mut losses.pending).into_iter().partition(|(t, _)| *t == thread); losses.pending = others; diff --git a/apps/rustgis-python/tests/test_widget.py b/apps/rustgis-python/tests/test_widget.py index f8c608a884..47dc12736a 100644 --- a/apps/rustgis-python/tests/test_widget.py +++ b/apps/rustgis-python/tests/test_widget.py @@ -1,6 +1,7 @@ """The Jupyter widget: its project stays in step with the session both ways.""" import json +import warnings import pytest @@ -69,6 +70,45 @@ def test_a_bad_project_from_the_app_is_a_notice_not_a_crash(): assert m.notices() == [("unknown command", True)] +class _LossOnOpen: + """The session's engine, reporting a lost ring whenever the app's project is opened.""" + + def __init__(self, engine): + self._engine = engine + self._pending = [] + + def __getattr__(self, name): + return getattr(self._engine, name) + + def _open_peer_text(self, text): + self._pending = [("dropped", "dropped.ring", "Drawn: 1 ring left out")] + return self._engine._open_peer_text(text) + + def _take_losses(self): + taken, self._pending = self._pending, [] + return taken + + +def test_a_loss_from_the_app_is_raised_after_its_project_is_kept(): + """A loss opening the app's project is raised, under an error filter too, once the widget has + kept the project; a project that can't be read raises its losses, not its error.""" + m = rustgis.Map() + other = rustgis.Session() + other.add_geojson(POINT, name="Drawn") + text = other.project_json() + m._session._engine = _LossOnOpen(m._session._engine) + with warnings.catch_warnings(): + warnings.filterwarnings("error", category=rustgis.DataLossWarning) + with pytest.raises(rustgis.DroppedWarning, match=r"\[dropped\.ring\]"): + from_app(m, text) + assert m._project == text + with pytest.raises(rustgis.DroppedWarning): + from_app(m, "not a project") + assert any(error for _, error in m.notices()) + with pytest.warns(rustgis.DroppedWarning): + from_app(m, other.project_json().replace("Drawn", "Drawn again")) + + def test_options_and_local_files(tmp_path): path = tmp_path / "sites.geojson" path.write_text(json.dumps(POINT)) diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index 958cac07b0..a6e5773dd9 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -996,28 +996,27 @@ fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usi } } } - // The codes before what is left of the result, saying it was cut where that fits: then only - // that the list was left out. - let bare = serde_json::Map::from_iter(success.map(|v| ("success".to_string(), v))); - let mut said_cut = bare.clone(); + // The codes, saying the result (or the failure's error) was cut: then only that both were. + let mut said_cut = serde_json::Map::from_iter(success.map(|v| ("success".to_string(), v))); said_cut.insert("truncated".into(), json!(true)); for form in forms.iter().skip(2) { - for base in [&said_cut, &bare] { - let v = with(base.clone(), form); - if v.to_string().len() <= max { - return v.to_string(); - } + let v = with(said_cut.clone(), form); + if v.to_string().len() <= max { + return v.to_string(); } } - let mut v = bare; + let mut v = said_cut; v.insert("lossesTrimmed".into(), json!(true)); let v = Value::Object(v).to_string(); - // The tightest budgets: the marker alone, then its name alone; below that (15 bytes) no - // marker fits, and nothing a client could misread is said. + // The tightest budgets: the markers alone, then the list's name alone; below that (15 bytes) + // no marker fits, and nothing a client could misread is said. + let both = json!({"truncated": true, "lossesTrimmed": true}).to_string(); let marker = json!({"lossesTrimmed": true}).to_string(); let name = json!("lossesTrimmed").to_string(); if v.len() <= max { v + } else if both.len() <= max { + both } else if marker.len() <= max { marker } else if name.len() <= max { @@ -1750,16 +1749,24 @@ mod tests { let out: Value = serde_json::from_str(&text).unwrap(); assert!(text.len() <= output_bytes(tokens), "{tokens}: {text}"); assert_eq!((&out["lossesTrimmed"], &out["success"]), (&json!(true), &json!(true)), "{tokens}: {text}"); - assert!(out["losses"].to_string().contains("dropped.value"), "{tokens}: {text}"); - // A success cut this far is never said as an error; it is said to be cut where that - // fits beside the codes. + // A success cut this far is never said as an error, and always said to be cut: the + // codes go first. assert!(out.get("error").is_none(), "{tokens}: {text}"); - assert_eq!(out.get("truncated").is_some(), tokens == 32, "{tokens}: {text}"); + assert_eq!(out["truncated"], json!(true), "{tokens}: {text}"); + assert_eq!(out["losses"].to_string().contains("dropped.value"), tokens == 32, "{tokens}: {text}"); } for tokens in 1..=8 { let text = finish_with_losses(&mut s, big.clone(), vec![loss.clone()], tokens, Withheld::default(), false); assert!(text.len() <= output_bytes(tokens), "{tokens}: {text}"); } + // A failure whose error gives way says so, at every budget. + for tokens in 12..=24 { + let failed = json!({"success": false, "error": "e".repeat(5000)}); + let text = finish_with_losses(&mut s, failed, vec![loss.clone()], tokens, Withheld::default(), true); + let out: Value = serde_json::from_str(&text).unwrap(); + assert!(text.len() <= output_bytes(tokens), "{tokens}: {text}"); + assert_eq!(out["truncated"], json!(true), "{tokens}: {text}"); + } // A failure's error alone gives way to its losses, as JSON. let failed = json!({"success": false, "error": "e".repeat(5000)}); let text = finish_with_losses(&mut s, failed, vec![loss.clone()], 200, Withheld::default(), true); diff --git a/docs/mcp.md b/docs/mcp.md index 2923e3a985..3e8f867766 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -342,7 +342,7 @@ These behavioral tests in `crates/assistant/src/relay.rs` check the requirements | `view_map` | The map as a PNG image at the current view; `width` and `height` default to 1024 × 640, each clamped to 64–2048 pixels. A picture over 3.75 MiB (a satellite basemap near 2048 pixels) is drawn again smaller, and its caption gives the size drawn and the size asked. `layout` (a layout's name) draws its page instead, fitted to `width` (and `height` when given); `region` draws part of either at full detail: `[x, y, w, h]` in mm on a layout (up to 600 dpi), `[west, south, east, north]` in degrees on the map. What drawing it said (texts cut off, layers without their cast shadows) follows the caption | | `snapshot` | The map as a PNG with JSON metadata: `mode`, `width`, `height`, `extent` (longitude/latitude), `center`, `scale`, `projection`, `render_settled`, `saved` and `note`. `mode: "screen"` captures the RustGIS window through the relay, once the map has finished drawing or after `wait_s` seconds (default 5, clamped to 0–30); `overlays: false` leaves out the map's controls, scale bar, north arrow and sketches. `mode: "render"` draws offscreen at `max_width` (default 1024, clamped to 64–2048 pixels); height follows the view's shape, with each side capped at 2048. It works while the window is hidden. `mode: "auto"` (default) takes the screen when the map is on it. Unavailable screen captures fall back to render. `save_path` also writes the PNG to a file, which needs file access | | `search_commands` | Finds RustGIS commands by words: their ids, ribbon locations and parameters | -| `run_command` | Runs a command by id with JSON parameters; each run that changes the project is one undo step. The result names the layers it added (`layersAdded`) and what the command said beside it (`notices`), including any parameters it ignored (`layer.moveDown ignores 'steps' (it reads layer)`). A notice that reports lost data with a [loss code](cli.md#loss-codes) is also in `losses`, as `{code, kind, text, action}`, so an agent can match the code: for an `assumed.*` code it can ask instead of guessing. A loss that has no code yet is only in `notices`. When the list doesn't fit the output budget beside the result, it is shortened (each entry's `code` and `kind`, then one entry per code with its `count`, then the codes alone) and `lossesTrimmed` is `true`; with the tightest budgets `losses` is left out and only `lossesTrimmed` says so. A failed command's error ends with a `losses:` line of JSON in the same forms, or `lossesTrimmed: true` | +| `run_command` | Runs a command by id with JSON parameters; each run that changes the project is one undo step. The result names the layers it added (`layersAdded`) and what the command said beside it (`notices`), including any parameters it ignored (`layer.moveDown ignores 'steps' (it reads layer)`). A notice that reports lost data with a [loss code](cli.md#loss-codes) is also in `losses`, as `{code, kind, text, action}`, so an agent can match the code: for an `assumed.*` code it can ask instead of guessing. A loss that has no code yet is only in `notices`. When the list doesn't fit the output budget beside the result, it is shortened (each entry's `code` and `kind`, then one entry per code with its `count`, then the codes alone) and `lossesTrimmed` is `true`; with the tightest budgets `losses` is left out and only `lossesTrimmed` says so. A failed command's error ends with a `losses:` line of JSON: one entry per code with its `action` and `count`, then the counts alone, then the codes alone, or `lossesTrimmed: true` | | `run` | Runs several commands in one call, as one undo step (none when its lines only read the project, moved the view, exported, left a request, or ran a command that reports it changed nothing, such as a move to where the layers already are; a line that sets a value to the one it has still counts): a script in the `script.run` format (one `command-id {json}` per line, `#` comments). A failing line stops it, nothing it did to the project is kept, and the error names the line; files an earlier line wrote (an export) stay written. Answers `{success, result, lines, layersAdded, notices, losses, error, duration_s}`, where `result` is the last command's. Each line follows `run_command`'s rules, checked before any line runs | | `search_tools` | Finds geoprocessing tools by words | | `describe_tool` | A geoprocessing tool's parameters | From 3f92ed5d87388b384be0881cb1e1d849ad9a62f3 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 06:31:06 -0600 Subject: [PATCH 20/21] fix(assistant): a result with its own losses keeps its success and failure when cut --- crates/assistant/src/tools.rs | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index a6e5773dd9..e1e7b95439 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -941,9 +941,21 @@ fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usi if losses.is_empty() && !always { return bounded_json(&Value::Object(o), tokens); } + // Read before a wrap below moves them. A result's `error` that is null (`run`'s on success) + // isn't a failure. + let failed = o.get("error").is_some_and(|e| !e.is_null()); + let success = o.get("success").cloned(); // A result with its own `losses` goes under `result`, as a result that isn't an object does - // beside `notices`, so the codes still have their key. - let o = if o.contains_key("losses") { serde_json::Map::from_iter([("result".to_string(), Value::Object(o))]) } else { o }; + // beside `notices`, so the codes still have their key; its `success` stays beside them. + let o = if o.contains_key("losses") { + let mut wrapped = serde_json::Map::from_iter([("result".to_string(), Value::Object(o))]); + if let Some(success) = &success { + wrapped.insert("success".into(), success.clone()); + } + wrapped + } else { + o + }; let max = output_bytes(tokens); let forms = loss_forms(&losses); let with = |mut o: serde_json::Map, (list, trimmed): &(Value, bool)| { @@ -965,8 +977,6 @@ fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usi // The result cut to leave room for one entry per code. let summary = forms.get(2).or(forms.last()).map_or(0, |(list, _)| list.to_string().len()); let text = bounded_json(&Value::Object(o.clone()), max.saturating_sub(summary + 64).div_ceil(4).max(1)); - // A result's `error` that is null (`run`'s on success) isn't a failure. - let failed = o.get("error").is_some_and(|e| !e.is_null()); let mut cut = match serde_json::from_str::(&text) { Ok(Value::Object(cut)) => cut, // A failure's error alone (`error: …`), kept as JSON with as much of it as fits below. @@ -977,7 +987,6 @@ fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usi // No room for any of a result that didn't fail: only that it was cut. _ => serde_json::Map::from_iter([("truncated".to_string(), json!(true))]), }; - let success = o.get("success").cloned(); if let Some(success) = &success { cut.insert("success".into(), success.clone()); } @@ -1759,6 +1768,11 @@ mod tests { let text = finish_with_losses(&mut s, big.clone(), vec![loss.clone()], tokens, Withheld::default(), false); assert!(text.len() <= output_bytes(tokens), "{tokens}: {text}"); } + // A failure with its own `losses`, cut, keeps its `success` and says it was cut. + let own = json!({"success": false, "error": "e".repeat(5000), "losses": 3}); + let text = finish_with_losses(&mut s, own, vec![loss.clone()], 200, Withheld::default(), true); + let out: Value = serde_json::from_str(&text).unwrap(); + assert_eq!((&out["success"], &out["truncated"]), (&json!(false), &json!(true)), "{out}"); // A failure whose error gives way says so, at every budget. for tokens in 12..=24 { let failed = json!({"success": false, "error": "e".repeat(5000)}); From 9e6415c2f838bacc844532077e412dcf9e2beb7a Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 06:56:38 -0600 Subject: [PATCH 21/21] fix(assistant): a cut result with no losses doesn't say a list was trimmed --- crates/assistant/src/tools.rs | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/crates/assistant/src/tools.rs b/crates/assistant/src/tools.rs index e1e7b95439..efcaff60c2 100644 --- a/crates/assistant/src/tools.rs +++ b/crates/assistant/src/tools.rs @@ -1014,21 +1014,25 @@ fn finish_with_losses(s: &mut Session, r: Value, losses: Vec, tokens: usi return v.to_string(); } } + // With no losses to leave out, only that the result was cut. + let trimmed = !losses.is_empty(); let mut v = said_cut; - v.insert("lossesTrimmed".into(), json!(true)); + if trimmed { + v.insert("lossesTrimmed".into(), json!(true)); + } let v = Value::Object(v).to_string(); // The tightest budgets: the markers alone, then the list's name alone; below that (15 bytes) // no marker fits, and nothing a client could misread is said. - let both = json!({"truncated": true, "lossesTrimmed": true}).to_string(); + let both = if trimmed { json!({"truncated": true, "lossesTrimmed": true}) } else { json!({"truncated": true}) }.to_string(); let marker = json!({"lossesTrimmed": true}).to_string(); let name = json!("lossesTrimmed").to_string(); if v.len() <= max { v } else if both.len() <= max { both - } else if marker.len() <= max { + } else if trimmed && marker.len() <= max { marker - } else if name.len() <= max { + } else if trimmed && name.len() <= max { name } else { "{}".to_string() @@ -1054,7 +1058,9 @@ fn loss_forms(losses: &[Value]) -> Vec<(Value, bool)> { let counts: Vec = summary.as_array().map(|a| a.iter().map(|e| json!({"code": e["code"], "count": e["count"]})).collect()).unwrap_or_default(); let codes: Vec = summary.as_array().map(|a| a.iter().map(|e| e["code"].clone()).collect()).unwrap_or_default(); - vec![(json!(losses), false), (json!(compact), true), (summary, true), (json!(counts), true), (json!(codes), true)] + // An empty list is never shortened. + let shortened = !losses.is_empty(); + vec![(json!(losses), false), (json!(compact), shortened), (summary, shortened), (json!(counts), shortened), (json!(codes), shortened)] } /// The first `max` bytes of `text`, cut at a character boundary. @@ -1768,6 +1774,10 @@ mod tests { let text = finish_with_losses(&mut s, big.clone(), vec![loss.clone()], tokens, Withheld::default(), false); assert!(text.len() <= output_bytes(tokens), "{tokens}: {text}"); } + // A cut result with no losses says it was cut, not that a list was. + let text = finish_with_losses(&mut s, run_ok.clone(), vec![], 32, Withheld::default(), true); + let out: Value = serde_json::from_str(&text).unwrap(); + assert_eq!((&out["truncated"], out.get("lossesTrimmed"), &out["losses"]), (&json!(true), None, &json!([])), "{out}"); // A failure with its own `losses`, cut, keeps its `success` and says it was cut. let own = json!({"success": false, "error": "e".repeat(5000), "losses": 3}); let text = finish_with_losses(&mut s, own, vec![loss.clone()], 200, Withheld::default(), true);