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..bd80c1b12a 100644 --- a/apps/rustgis-python/python/rustgis/__init__.py +++ b/apps/rustgis-python/python/rustgis/__init__.py @@ -27,11 +27,136 @@ 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] + + 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).""" + + +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.join(os.path.dirname(__file__), ""),) + + +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) + 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: + """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: + _warn_losses(engine, failure) + 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. @@ -847,8 +972,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 - text = self._engine.run(command, encoded) - 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 @@ -866,7 +990,7 @@ 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) + return _native(self._engine, self._engine.layer_geojson, layer, selected) def _root(self) -> "Session": """The session that holds the project: this one.""" @@ -888,7 +1012,7 @@ def project_json(self) -> str: Returns: The JSON text; ``run("project.openText", text=...)`` opens it. """ - return self._engine.project_json() + return _native(self._engine, self._engine.project_json) # Maps ---------------------------------------------------------------------------------- @@ -912,7 +1036,9 @@ def to_png( The PNG bytes. """ png = bytes( - self._engine.render_png( + _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), diff --git a/apps/rustgis-python/python/rustgis/_embed.py b/apps/rustgis-python/python/rustgis/_embed.py index da7b45f8a7..7dfc49e095 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, _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,8 +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: - text, keys, notices = self._session._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]) @@ -215,10 +216,21 @@ 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)]) + # The error is held, not raised: its losses are raised themselves. + _warn_losses(engine) return - if text != self._project: - self._project = text - self._send_project(text) + except BaseException as failure: + _warn_losses(engine, failure) + raise + 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) def _hold(self, notices: List[Tuple[str, bool]]) -> None: """Keeps notices for :meth:`notices`. @@ -245,16 +257,25 @@ 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: - self._session._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)]) + # 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. + _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 - # 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/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..137c9732c3 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,13 +85,20 @@ 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 { + /// 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 }) } @@ -104,8 +112,43 @@ impl Engine { } } +/// See [`Engine::losses`]. +struct Losses { + /// `(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, 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() { + 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(); + 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)| (thread, (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 +164,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,6 +314,22 @@ impl Engine { result.map_err(RustGISError::new_err) } + /// 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; + // 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; + mine.into_iter().map(|(_, loss)| loss).collect::>() + }) + } + /// 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)> { diff --git a/apps/rustgis-python/tests/test_session.py b/apps/rustgis-python/tests/test_session.py index 3173d13af0..8414ec7db4 100644 --- a/apps/rustgis-python/tests/test_session.py +++ b/apps/rustgis-python/tests/test_session.py @@ -119,6 +119,117 @@ 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") + 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" + # 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)] + + +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) + + +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/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/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..997d2f7517 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 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(", ")) @@ -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 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 5f2f6c8c4a..efcaff60c2 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 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.", + 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": { @@ -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 @@ -481,39 +503,39 @@ 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| 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()); } 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| 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 { @@ -582,12 +604,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,15 +637,22 @@ 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); - finish_result(s, value, tokens, 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 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. -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 { @@ -632,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. @@ -788,7 +823,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; @@ -799,7 +834,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,6 +843,7 @@ 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, &said); match r { Ok(v) => { let ran = v.get("ran").and_then(Value::as_array); @@ -814,17 +851,19 @@ fn run_script(s: &mut Session, call: &ToolCall, tokens: usize, scope: Scope, per 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}); - Ok(public_envelope(s, out, tokens)) + let (out, withheld) = public_projection(out); + Ok(finish_with_losses(s, out, losses, tokens, withheld, true)) } Err(e) => { let e = public_error(&e); // 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}); - Err(public_envelope(s, out, tokens)) + let (out, withheld) = public_projection(out); + Err(finish_with_losses(s, out, losses, tokens, withheld, true)) } } } @@ -845,14 +884,253 @@ fn with_notices(r: Value, s: &Session, mark: u64) -> Value { } } -/// 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 { +/// 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 `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(|&(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(); + out.extend(kept.into_iter().map(|(code, text)| entry(code, text))); + out +} + +/// [`finish_result`] for `r` with `losses` (or `[]` when `always`), within the output budget. +/// 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 { + // What cleaning withheld is said first, so the sizes below are the final ones. + let r = with_withheld(s, r, withheld); + // 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); + } + // 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; 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)| { + o.insert("losses".into(), list.clone()); + if *trimmed { + o.insert("lossesTrimmed".into(), json!(true)); + } + Value::Object(o) + }; + // 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()); + 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. + 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))]), + }; + if let Some(success) = &success { + cut.insert("success".into(), success.clone()); + } + 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(); + } + } + } + // 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) { + let v = with(said_cut.clone(), form); + if v.to_string().len() <= max { + 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; + 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 = 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 trimmed && marker.len() <= max { + marker + } else if trimmed && name.len() <= max { + name + } else { + "{}".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)> { + // 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(); + let codes: Vec = summary.as_array().map(|a| a.iter().map(|e| e["code"].clone()).collect()).unwrap_or_default(); + // 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. +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 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. 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 said: Vec<&str> = s.notices_since(mark).iter().map(|n| n.text.as_str()).filter(|t| *t != e && *t != told).collect(); - // 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) } + let notices: Vec<&str> = s.notices_since(said.mark).iter().map(|n| n.text.as_str()).filter(|t| *t != e && *t != told).collect(); + 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 text = public_error(&if notices.is_empty() { e } else { format!("{e}\n{}", notices.join("\n")) }); + // 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(); + 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}"); + } + // 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 } + } + // 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); + } + } + alone.unwrap_or_else(|| clip(&text, 8000)) +} + +/// 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. @@ -1364,6 +1642,178 @@ 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 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(&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(&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(&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!(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()); + // 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}"); + // 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 + /// 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 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() + }; + let loss = json!({"code": "dropped.value", "kind": "dropped", "text": "x".repeat(600), "action": "Correct the value."}); + 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)); + // 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"], &out["success"]), (&json!(true), &json!(true), &json!(true))); + // `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}"); + assert_eq!((&out["lossesTrimmed"], &out["success"]), (&json!(true), &json!(true)), "{tokens}: {text}"); + // 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["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 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); + 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)}); + 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); + 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}"); + 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() + }; + assert_eq!(finish(json!({"notices": ["n"]}), true)["losses"], json!([])); + assert!(finish(json!({"notices": ["n"]}), false).get("losses").is_none()); + // 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(); + assert_eq!((&out["result"], &out["losses"][0]["code"]), (&own, &json!("dropped.value")), "{out}"); + } + #[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..3e8f867766 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,11 +342,11 @@ 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 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 | -| `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` | 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