Repository navigation
feat(python): loss codes as Python warnings and MCP losses (#2371) #2755
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
1c21814
f192214
bd1ef51
6a90f86
e02f39c
48cf82e
31613ec
77c24ae
b8298b0
92ede85
a765187
8a61158
18533a0
d7743ed
4bd4864
254eb11
3272a64
cf19628
482ef9b
3f92ed5
9e6415c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Python's default filter for Suggest one of: say so in Category: quality
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Intended: these are ordinary warnings, and Python's filters decide how often they show. A loop that wants every one uses |
||
| 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), | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The widget's loss branches were rewritten in this PR. Suggested test, in the widget test module: a project that loses something on open, pushed through Category: quality
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added in 482ef9b: a widget test opens the app's project through an engine that reports a lost ring. Under an error filter, the |
||
| """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) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The reply on the earlier thread about Today the losses are drained on the success path (line 262) and on the Routing this line through Category: bug
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in d7743ed: |
||
| 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)]) | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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<Mutex<Vec<String>>>, | ||
| /// 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<Losses>, | ||
| } | ||
|
|
||
| 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<T: Send>(&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); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This delta can report losses that never reached the user. Category: bug
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This follows the engine rule that #2736 set for
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The "not kept" delta ( Category: quality
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Both copies agree today. Moving the rule into one |
||
| 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))); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Losses set aside here stay in Confidence: medium on the mechanism, low on current trigger. Category: bug
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in a765187: |
||
| } | ||
| } | ||
| 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)> { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
The session lock isn't needed here either. This thread's losses were already collected under the lock by its own call, which has returned. The only lock this method needs is Suggested direction: drop Confidence: medium-high on the mechanism, impact limited to multi-threaded use. Category: performance
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 482ef9b. |
||
| 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::<Vec<_>>() | ||
| }) | ||
| } | ||
|
|
||
| /// 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)> { | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.