Skip to content

Commit 9380156

Browse files
fix(engine): measure layers in shared steps, and say plugin commands are never steps (#2645) (#2653)
* fix(engine): measure layers in shared steps, and say plugin commands are never steps (#2645) What a shared step changed is compared before and after it; that now includes each map's layers, in every build, instead of a debug-only check. A step that failed inside its savepoint was undone whole and no longer counts as an edit; shared_step runs the savepoint itself, so the two can't disagree. Other failed steps that mutate still count: nothing undoes what they did part way, and measuring it would copy each layer per call. A plugin's command can't be a step of another command (scripts and tasks run registered commands only, and a plugin can't run another's), so invoke refuses one with a shared transaction instead of opening a nested transaction with an undo step of its own. * test(engine): a failed step is undone by its savepoint and only then isn't an edit (#2645) * fix(engine): a command says it runs as a savepoint, and the tests check every declaration (#2645) CommandSpec::savepoint replaces the command id written into the dispatcher: shared_step reads it from the spec. In the tests, invoke fails a command declared as not mutating that changes the layers without moving the rest of what undo restores, by itself or as a step, so a wrong declaration fails the suite instead of only a debug assertion on script steps. * fix(engine): marking the project unsaved doesn't excuse a layer change in the declaration check (#2645) The test-time check in invoke now lets a command declared as not mutating change the layers only when it moved the history state or the project, not when it only marked the project unsaved. CommandSpec's flag is renamed atomic, so it no longer shares its name with Session::savepoint. * fix(engine): failing doesn't excuse a layer change in the declaration check (#2645) * refactor(engine): read the declaration check and shared_step plainly (#2645) * docs: say what .view() promises about the layers, and the check that holds it (#2645) * fix(engine): the declaration check excuses a layer change by what a command declares (#2645) A command declared as not mutating may change the layers only when it declares that it moves the history (Undo, Redo) or replaces the project. What it does on the way, a nested edit included, no longer excuses it: a nested edit moved the history state the check used to read. * test(engine): the declaration check runs in the integration tests too (#2645)
1 parent 8f375db commit 9380156

8 files changed

Lines changed: 162 additions & 29 deletions

File tree

‎AGENTS.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,11 @@ measures.
9090
- **Everything is a command**: a `CommandSpec` in `crates/engine/src/cmd/*.rs`. UI-only
9191
commands (`ui.*`) live in `crates/ui-egui/src/lib.rs`. The ribbon, shortcuts, command search
9292
and CLI dispatch by id. Commands never open dialogs.
93+
- **`.view()` leaves the layers as they are**: a command that adds, removes or reorders layers
94+
mutates, even when it fails part way. Declared `.view()`, it leaves no Undo step when it runs by
95+
itself. Only Undo, Redo (`Effect::History`) and a project replaced (`Effect::Replaces`) may.
96+
The engine's unit and integration tests fail a registered command declared wrong (the check in
97+
`invoke`, `policy/dispatch.rs`, feature `declaration-check`), but only on the paths they run.
9398
- **Command ingress**: root `Session::run` is trusted native User dispatch. Assistant, MCP,
9499
plugin, imported-item and continuation adapters carry their named opaque policy scope;
95100
scopes inherit or narrow, and `with_scope` rejects nested ingress. Peer project text uses

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/engine/Cargo.toml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,15 @@ geolibre = ["dep:rustgis-geolibre"]
3636
pdf = ["rustgis-data/pdf"]
3737
# Existing in-tree Wasm fixtures for adapter tests; no guest or production interface change.
3838
testing = ["rustgis-plugins/testing"]
39+
# The check that a command declared as not mutating leaves the layers alone, in the integration
40+
# tests too (they link the library without `cfg(test)`; AGENTS.md). Never in a release.
41+
declaration-check = []
3942
# The JSON Schema of the project file (`cargo xtask schema`).
4043
schema = ["dep:schemars", "rustgis-data/schema", "rustgis-geom/schema"]
4144

4245
[dev-dependencies]
46+
# The declaration check in the integration tests.
47+
rustgis-engine = { path = ".", features = ["declaration-check"] }
4348
# Reading back the PDFs layouts export (#2336).
4449
rustgis-data = { workspace = true, features = ["pdf"] }
4550
miniz_oxide = { workspace = true }

‎crates/engine/src/cmd/edit.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ pub fn commands() -> Vec<C> {
1818
.roles(&[crate::ParamRole {key:"frame",role:crate::Role::Opaque}]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view()
1919
.when(crate::cmd::design::need_editable).params(r#"{"layer"?:name|id,"row":number,"featureId"?:number,"kind":"circle|rotatedBox","request"?:number (preview correlation only),"image"?:GeoTIFF layer name|id,"frame"?:construction grid as edit.addBox.box.frame (otherwise Web Mercator)}"#),
2020
C::new("edit.applyShapeConversion", "Apply Shape Conversion", "Edit › Features", crate::shape_conversion::apply).inputs(crate::shape_conversion::apply_inputs)
21-
.roles(&[crate::ParamRole {key:"preview",role:crate::Role::Opaque}]).effects(crate::policy::Effects::NONE)
21+
.roles(&[crate::ParamRole {key:"preview",role:crate::Role::Opaque}]).effects(crate::policy::Effects::NONE).atomic()
2222
.when(crate::shape_conversion::need_editing).params(r#"{"preview":result of edit.previewShapeConversion,"confirm":true}"#),
2323
C::new("edit.calculateGeometry", "Calculate Geometry", "Attribute Table", crate::geometry_calc::run).roles(&[]).effects(crate::policy::Effects::NONE)
2424
.when(super::design::need_editable)

‎crates/engine/src/lib.rs‎

Lines changed: 40 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,9 @@ pub struct CommandSpec {
109109
/// Pure executor-owned resolution for commands whose inputs exceed the common layer selector.
110110
pub(crate) transition: Option<fn(&cmd::InputContext<'_>, &Value) -> Result<Option<cmd::Selection>, String>>,
111111
pub(crate) inputs: Option<fn(&cmd::InputContext<'_>, &Value) -> Result<cmd::Inputs, String>>,
112+
/// As a step of another command, it is atomic: it runs in a [`Session::savepoint`], undone
113+
/// whole when it fails, since a plugin may handle the error and go on.
114+
pub(crate) atomic: bool,
112115
}
113116

114117
fn always(_: &Session) -> Option<&'static str> {
@@ -147,8 +150,14 @@ impl CommandSpec {
147150
roles: None,
148151
inputs: None,
149152
transition: None,
153+
atomic: false,
150154
}
151155
}
156+
/// See [`CommandSpec::atomic`].
157+
pub(crate) const fn atomic(mut self) -> Self {
158+
self.atomic = true;
159+
self
160+
}
152161
/// Declares the effects reviewed for this command; omitted declarations fail closed.
153162
pub const fn effects(mut self, effects: policy::Effects) -> Self {
154163
self.effects = effects;
@@ -760,18 +769,21 @@ pub(crate) struct StepTally {
760769
pub(crate) edited: bool,
761770
}
762771

763-
/// What a command that doesn't mutate can move of what undo restores: the history state
764-
/// (`edit.undo`), the project replaced (`project.new`), its file (`project.saveAs`), and the
765-
/// unsaved mark a write that changed layers leaves (Publish to Source). Measured before and after
766-
/// a shared step ([`Session::shared_step`]), not inferred from what the command may reach. The
767-
/// project's contents change only by commands that mutate, except its history log, where an
768-
/// export records itself as a log entry, not an edit, as when it runs by itself.
772+
/// What a step can move of what undo restores without saying so: the history state
773+
/// (`edit.undo`), the project replaced (`project.new`), its file (`project.saveAs`), the unsaved
774+
/// mark a write that changed layers leaves (Publish to Source), and which layers each map has,
775+
/// in what order, with the id its next layer takes. Measured before and after a shared step
776+
/// ([`Session::shared_step`]), not inferred from what the command may reach. The project's other
777+
/// contents (a layer's name, look or features) change only by commands that mutate, except its
778+
/// history log, where an export records itself as a log entry, not an edit, as when it runs by
779+
/// itself.
769780
#[derive(PartialEq, Eq)]
770781
struct Restored {
771782
state: u64,
772783
opened: u64,
773784
files: ProjectFiles,
774785
unsaved_marks: u64,
786+
layers: Vec<rustgis_map::LayerMark>,
775787
}
776788

777789
pub struct Session {
@@ -2260,35 +2272,36 @@ impl Session {
22602272
self.guarded_inner(label, true, false, f)
22612273
}
22622274

2263-
/// Runs `run`, the command `spec`, as a step of the command running now, in its transaction
2264-
/// (a script's line, a task's step, a plugin's call): it takes no undo step of its own, and
2265-
/// what it did goes into [`Session::shared_steps`]. Whether it left a request or changed
2266-
/// nothing ([`Session::request_only`]) is its own, never the enclosing command's. It edited
2267-
/// when it mutated and didn't say it changed nothing, or when [`Restored`] moved: a failed
2268-
/// step that kept a record (a failure note, a source file written) moved the history state.
2275+
/// Runs `run`, the command `spec`, as a step of the command running now (a script's line, a
2276+
/// task's step, a plugin's call), in its transaction or, for an [atomic](CommandSpec::atomic)
2277+
/// command, in a [`Session::savepoint`] of it. It takes no undo step of its own, and what it
2278+
/// did goes into [`Session::shared_steps`].
2279+
/// Whether it left a request or changed nothing ([`Session::request_only`]) is its own, never
2280+
/// the enclosing command's. It edited when it mutates and didn't say it changed nothing, or
2281+
/// when [`Restored`] moved. A failed step that mutates counts too unless a savepoint undid it:
2282+
/// telling what it changed would cost a copy of each layer it touched.
22692283
pub(crate) fn shared_step(&mut self, spec: &CommandSpec, run: impl FnOnce(&mut Session) -> CmdResult) -> CmdResult {
22702284
let outer = std::mem::take(&mut self.request_only);
2271-
let before = self.restored();
2272-
#[cfg(debug_assertions)]
2273-
let layers = (!spec.mutates).then(|| self.project.maps.iter().map(Map::layer_mark).collect::<Vec<_>>());
2274-
let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(self)));
2285+
// Once the account holds an edit, nothing a step does changes it: no need to measure.
2286+
let before = (!self.shared_steps.edited).then(|| self.restored());
2287+
let step = |s: &mut Session| if spec.atomic { s.savepoint(spec.label, run) } else { run(s) };
2288+
let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| step(self)));
22752289
let unchanged = std::mem::replace(&mut self.request_only, outer);
2276-
let moved = self.restored() != before;
2277-
// A command that doesn't mutate leaves the layers alone, or the measure above misses it.
2278-
#[cfg(debug_assertions)]
2279-
debug_assert!(
2280-
moved || res.is_err() || layers.is_none_or(|layers| self.project.maps.iter().map(Map::layer_mark).eq(layers)),
2281-
"{} doesn't mutate but changed the layers",
2282-
spec.id
2283-
);
2284-
// A failed step counts too: in a shared transaction nothing undoes what it did part way.
2290+
let moved = before.is_some_and(|before| self.restored() != before);
2291+
let kept = !spec.atomic || matches!(res, Ok(Ok(_)));
22852292
self.shared_steps.requested |= unchanged;
2286-
self.shared_steps.edited |= moved || (spec.mutates && !unchanged);
2293+
self.shared_steps.edited |= moved || (spec.mutates && kept && !unchanged);
22872294
res.unwrap_or_else(|panic| std::panic::resume_unwind(panic))
22882295
}
22892296

22902297
fn restored(&self) -> Restored {
2291-
Restored { state: self.state, opened: self.opened, files: self.project_files(), unsaved_marks: self.unsaved_marks }
2298+
Restored {
2299+
state: self.state,
2300+
opened: self.opened,
2301+
files: self.project_files(),
2302+
unsaved_marks: self.unsaved_marks,
2303+
layers: self.project.maps.iter().map(Map::layer_mark).collect(),
2304+
}
22922305
}
22932306

22942307
fn project_files(&self) -> ProjectFiles {

‎crates/engine/src/policy/dispatch.rs‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -927,6 +927,12 @@ impl Session {
927927
let node = op.node.clone();
928928
match &op.op {
929929
CommandOp::Plugin { pin, .. } => {
930+
// A plugin's command is a transaction of its own, never a step of another
931+
// command: scripts and tasks run registered commands only, and a plugin can't run
932+
// another's.
933+
if !matches!(txn, Txn::Own) {
934+
return Err("a plugin's command runs only by itself, not as a step of another command".into());
935+
}
930936
let pin = pin.clone();
931937
// Plugin host calls are checked against the pinned manifest, not an invented
932938
// finite list of calls made by code that has yet to run.
@@ -985,14 +991,28 @@ impl Session {
985991
// start in it, and inside the transaction that made it, so Undo and a failure take
986992
// it back and the project is unsaved ([`crate::cmd::project::first_layer_watch`]).
987993
let first_layer = crate::cmd::project::first_layer_watch(self, &spec);
994+
// A command that doesn't mutate leaves the layers alone, unless it says it moves the
995+
// history (Undo, Redo) or replaces the project: what it did on the way (a nested
996+
// edit, an unsaved mark, a failure) doesn't excuse it, since by itself nothing
997+
// undoes it. Checked on every registered command the unit and integration tests
998+
// run, by itself or as a step, so one declared wrong fails them on the paths they
999+
// reach (AGENTS.md).
1000+
#[cfg(any(test, feature = "declaration-check"))]
1001+
let declared = (!spec.mutates
1002+
&& !spec.effects.contains(crate::policy::Effect::History)
1003+
&& !spec.effects.contains(crate::policy::Effect::Replaces))
1004+
.then(|| self.restored().layers);
9881005
let result = match txn {
9891006
Txn::Own => self.guarded(spec.label, spec.mutates, run),
990-
Txn::Shared if spec.id == "edit.applyShapeConversion" => self.shared_step(&spec, |s| s.savepoint(spec.label, run)),
9911007
Txn::Shared => self.shared_step(&spec, run),
9921008
};
9931009
if let (Ok(_), Some(before)) = (&result, first_layer) {
9941010
crate::cmd::project::take_first_layer_system(self, &before);
9951011
}
1012+
#[cfg(any(test, feature = "declaration-check"))]
1013+
if let Some(before) = declared {
1014+
assert!(self.restored().layers == before, "{} doesn't mutate but changed the layers", spec.id);
1015+
}
9961016
self.url_completion_landed(spec.id, &params, &result);
9971017
if result.is_ok() && (spec.mutates || spec.effects.contains(crate::policy::Effect::History)) && spec.id != "data.similar" {
9981018
// Edits and history moves can replace selections without select::set. History

‎crates/engine/src/tests.rs‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,78 @@ fn script_step_follows_what_its_lines_change_not_what_they_reach() {
377377
assert_eq!(s.path.as_deref(), Some(first.as_path()));
378378
}
379379

380+
/// A plugin's command can't run as a step of another command (#2645): it would be a transaction
381+
/// of its own inside the caller's.
382+
#[test]
383+
fn invoke_refuses_a_plugin_command_as_a_step() {
384+
let mut s = world();
385+
plugin("step-plugin", &["edit"]);
386+
let err = s.run("script.run", &json!({"script": "plugin:step-plugin/h {}"})).unwrap_err();
387+
assert!(err.contains("unknown command"), "{err}");
388+
let op = s.authorize("plugin:step-plugin/h", &json!({})).unwrap();
389+
let err = s.invoke(op, crate::policy::Txn::Shared).unwrap_err();
390+
assert!(err.contains("runs only by itself"), "{err}");
391+
}
392+
393+
/// A step that changed the project and then failed is undone whole by its savepoint, so it isn't
394+
/// an edit; without one, nothing undoes it part way, so it counts (#2645).
395+
#[test]
396+
fn a_failed_step_counts_unless_its_savepoint_undid_it() {
397+
let mut s = world();
398+
let rename = *s.registry.get("map.rename").unwrap();
399+
let name = s.map().name.clone();
400+
let half_done = |s: &mut Session| -> crate::CmdResult {
401+
s.map_mut().name = "Half done".into();
402+
Err("failed part way".into())
403+
};
404+
for savepoint in [true, false] {
405+
s.shared_steps = crate::StepTally::default();
406+
let spec = crate::CommandSpec { atomic: savepoint, ..rename };
407+
assert!(s.shared_step(&spec, half_done).is_err());
408+
assert_eq!((s.map().name == name, s.shared_steps.edited), (savepoint, !savepoint), "savepoint: {savepoint}");
409+
s.map_mut().name = name.clone();
410+
}
411+
}
412+
413+
/// A step that doesn't mutate but changes the layers is still an edit (#2645): they are measured
414+
/// in every build, not inferred from the command's declaration.
415+
#[test]
416+
fn shared_step_measures_the_layers_a_step_changes() {
417+
let mut s = world();
418+
let spec = *s.registry.get("map.zoomFull").unwrap();
419+
let (count, ds) = (s.map().layers.len(), s.map().layers[0].dataset.clone());
420+
let quiet_layer = |s: &mut Session| -> crate::CmdResult {
421+
crate::cmd::layer::add_dataset(s, ds);
422+
Ok(Value::Null)
423+
};
424+
s.shared_step(&spec, quiet_layer).unwrap();
425+
assert_eq!((s.shared_steps.edited, s.map().layers.len()), (true, count + 1));
426+
}
427+
428+
/// A command declared as not mutating that adds, removes or reorders layers fails the tests
429+
/// (#2645), by itself or as a script's line; an edit it makes on the way, marking the project
430+
/// unsaved or failing afterwards doesn't excuse it. A layer's name, look or features aren't
431+
/// measured.
432+
#[test]
433+
#[should_panic(expected = "test.quietLayer doesn't mutate but changed the layers")]
434+
fn a_command_that_changes_layers_must_say_it_mutates() {
435+
let mut s = world();
436+
s.registry.commands.push(
437+
crate::CommandSpec::new("test.quietLayer", "Quiet layer", "Test", |s, _| {
438+
let ds = s.map().layers[0].dataset.clone();
439+
crate::cmd::layer::add_dataset(s, ds);
440+
s.mark_unsaved();
441+
s.guarded("Rename", true, |s| {
442+
s.map_mut().name = "Renamed on the way".into();
443+
Ok(Value::Null)
444+
})?;
445+
Err("failed after adding it".into())
446+
})
447+
.view(),
448+
);
449+
let _ = s.run("test.quietLayer", &Value::Null);
450+
}
451+
380452
/// A task's steps are counted as a script's lines: an undo step only when one edited (#2621).
381453
#[test]
382454
fn task_takes_an_undo_step_only_when_a_step_edits() {

‎crates/engine/tests/integration/workflows.rs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,23 @@ use rustgis_engine::{Project, Session};
99
use serde_json::{Value, json};
1010
use std::path::{Path, PathBuf};
1111

12+
/// The check that a command declared as not mutating leaves the layers alone runs here too, where
13+
/// commands take their valid paths (#2645; AGENTS.md, feature `declaration-check`).
14+
#[test]
15+
#[should_panic(expected = "test.quietLayer doesn't mutate but changed the layers")]
16+
fn a_command_that_adds_a_layer_must_say_it_mutates() {
17+
let mut s = Session::new(Project::new("Declared"));
18+
s.registry.commands.push(
19+
rustgis_engine::CommandSpec::new("test.quietLayer", "Quiet layer", "Test", |s, _| {
20+
let ds = Dataset::new("Quiet", rustgis_engine::data::GeometryType::Point, vec![]);
21+
rustgis_engine::cmd::layer::add_dataset(s, ds);
22+
Ok(Value::Null)
23+
})
24+
.view(),
25+
);
26+
let _ = s.run("test.quietLayer", &Value::Null);
27+
}
28+
1229
/// Declared versions are checked before payloads, and unreadable nodes cannot disappear on import.
1330
#[test]
1431
fn model_import_refuses_unsupported_files_without_changing_session() {

0 commit comments

Comments
 (0)