Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
234 changes: 230 additions & 4 deletions crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,10 @@ impl Project {
/// Apply the same capability predicate to every replayable project container.
fn uses_commands(&self, uses: CommandCheck) -> bool {
self.models.iter().any(|m| model_uses(&m.steps, m.graph.as_ref(), uses))
|| self.tasks.iter().any(|t| t.steps.iter().any(|s| uses(&s.command, &s.params)))
|| self.tasks.iter().any(|t| t.steps.iter().any(|s| command_uses(&uses, &s.command, &s.params)))
|| self.gp_history.iter().any(|h| {
uses(if h.id.is_empty() { &h.tool } else { &h.id }, &h.params)
|| h.command.as_ref().is_some_and(|(id, params)| uses(id, params))
command_uses(&uses, if h.id.is_empty() { &h.tool } else { &h.id }, &h.params)
|| h.command.as_ref().is_some_and(|(id, params)| command_uses(&uses, id, params))
})
|| self.notebooks.iter().any(|n| {
n.language().is_none()
Expand Down Expand Up @@ -530,7 +530,39 @@ fn script_uses(script: &str, uses: impl Fn(&str, &Value) -> bool) -> bool {
script
.lines()
.take(crate::cmd::workflows::MAX_SCRIPT_LINES)
.any(|line| crate::script_line(line).is_some_and(|parsed| parsed.is_ok_and(|(id, params)| uses(&id, &params))))
.any(|line| crate::script_line(line).is_some_and(|parsed| parsed.is_ok_and(|(id, params)| command_uses(&uses, &id, &params))))
}

/// `uses` on a saved command and, for a `model.run` given its graph inline, on each of the graph's
/// tool nodes as on a saved model's steps (#2758): that graph is in no saved model, so nothing
/// else reads it, and an older reader would run its nodes with the option dropped.
fn command_uses(uses: &impl Fn(&str, &Value) -> bool, id: &str, params: &Value) -> bool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Possible gap: model.new with an inline graph is not covered, and an older release can run it.

Only model.run is read here. model.new (and model.save, model.export) also accept graph inline, and a replayable task step, script line, notebook cell or history entry holding model.new with a graph, such as an a5Grid node with {"system": "H3"}, gets no dggs-system requirement. An older release that runs that step creates a model whose tool node keeps the system key but whose tool ignores it, so the model later runs as A5 with nothing flagged. The PR's reasoning that "a saved model is already covered" only holds once the new release has saved the model. Until then, the replayable step is the only place the graph exists, and it isn't checked.

I did not confirm the older release's exact behaviour, so confidence is medium. Either the older release keeps the key (the model then runs as A5) or drops it (silent loss on save). Both are the failure this PR fixes for model.run.

Suggested fix: extend the inline check to model.new as well (same graph read, same leaf check), with a test in an_inline_model_graph_requires_what_its_tool_nodes_do. Or state in the PR why a created model is safe.

Category: bug

uses(id, params) || (id == "model.run" && inline_graph_uses(params, uses))
}

/// A graph read as the run reads it (`model::graph_from_json_counted`): an object with `nodes`, at
/// most `MAX_NODES` nodes and `MAX_EDGES` connections (a bigger one is refused there, so needs
/// nothing), and only a node of kind `tool` runs, with `params` that aren't an object dropped (the
/// checks read nothing from one). Read in place, without a copy, so a node the run drops (an empty
/// or repeated id, an unreadable `x`, a `layer` that isn't text) is read here all the same: that
/// only over-requires, which is safe, and a node it can't use never hides the others.
///
/// No recursion: a node is checked by the leaf check only. A node runs a tool (`model::tool_of`),
/// so one naming a command, `model.run` included, fails there and is read as the id no check
/// matches; and one naming `script.run` is skipped, as its check is the one that reads into a

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: the reason given for skipping a script.run node is not the real one. script.run is not an analysis tool (crates/analysis has no such id), so model::tool_of resolves nothing and such a node never runs. The skip is correct for that reason, not because its check "could hold another graph". Recursion is bounded by the JSON nesting anyway. Saying "it runs no tool, so it is skipped" would be accurate and easier to check.

Category: quality

/// script, which could hold another graph.
fn inline_graph_uses(params: &Value, uses: &impl Fn(&str, &Value) -> bool) -> bool {
let Some(graph) = params.get("graph") else { return false };
let few = |key: &str, max: usize| graph.get(key).and_then(Value::as_array).is_none_or(|list| list.len() <= max);
few("edges", crate::model::MAX_EDGES)
&& graph.get("nodes").and_then(Value::as_array).filter(|nodes| nodes.len() <= crate::model::MAX_NODES).is_some_and(|nodes| {
nodes.iter().any(|node| {
let tool = node.get("tool").and_then(Value::as_str).unwrap_or("");
node.get("kind").and_then(Value::as_str) == Some("tool")
&& tool != "script.run"
&& uses(tool, node.get("params").unwrap_or(&Value::Null))
})
})
}

fn relief_effects(layer: &Layer) -> bool {
Expand Down Expand Up @@ -858,6 +890,200 @@ mod tests {
assert_eq!(serde_json::to_value(&fixture).unwrap()["requires"], json!(["dggs-system"]));
}

/// A `model.run` command given `graph` inline, as a saved task step, a script line in a task, a
/// notebook cell and a recorded command: what a project saves as `requires` for each (`None`:
/// no header).
fn saved_requires_of_inline_graph(run: &Value) -> Vec<Option<Value>> {
let script = format!("# Run\nmodel.run {run}");
let base = serde_json::to_value(Project::default()).unwrap();
[
("tasks", json!([{"name": "Task", "steps": [{"title": "Run", "command": "model.run", "params": run}]}])),
("tasks", json!([{"name": "Script", "steps": [{"title": "Run", "command": "script.run", "params": {"script": script}}]}])),
("notebooks", json!([{"name": "Notebook", "cells": [{"kind": "code", "source": script}]}])),
("gp_history", json!([{"tool": "Run", "params": {}, "command": ["model.run", run], "ok": true, "messages": [], "millis": 0}])),
]
.into_iter()
.map(|(field, value)| {
let mut document = base.clone();
document[field] = value;
let project = Project::from_json(&document.to_string()).unwrap();
serde_json::to_value(&project).unwrap().get("requires").cloned()
})
.collect()
}

fn graph_of_one_tool(tool: &str, params: Value) -> Value {
json!({"graph": {"nodes": [{"id": "n", "kind": "tool", "tool": tool, "params": params}]}})
}

/// A saved command that runs a graph given inline requires what its tool nodes would as
/// saved steps, wherever the command is saved (#2758); one that needs nothing, none.
#[test]
fn an_inline_model_graph_requires_what_its_tool_nodes_do() {
for (capability, tool, needs, needs_not) in [
("dggs-system", "a5Grid", json!({"system": "H3"}), json!({"system": "A5"})),
("dggs-system", "a5Aggregate", json!({"system": "Hexagon"}), json!({})),
("dggs-system", "A5 Grid", json!({"system": "S2"}), json!({"system": null})),
("tabulate-intersection-unit", "tabulateIntersection", json!({"areaUnit": "ac"}), json!({"areaUnit": "km2"})),
(
"tabulate-intersection-empty-zones",
"tabulateIntersection",
json!({"includeEmptyZones": true}),
json!({"includeEmptyZones": false}),
),
// As for a saved model's graph (`slope_percent_capability_follows_saved_executables`);
// no tool node runs a raster function, so this is parity, not a reachable run.
("slope-percent", "raster.function", json!({"function": "slope", "units": "percent"}), json!({"function": "slope"})),
] {
for (index, saved) in saved_requires_of_inline_graph(&graph_of_one_tool(tool, needs.clone())).into_iter().enumerate() {
assert_eq!(saved, Some(json!([capability])), "{tool} {needs} in container {index}");
}
for (index, saved) in saved_requires_of_inline_graph(&graph_of_one_tool(tool, needs_not.clone())).into_iter().enumerate() {
assert_eq!(saved, None, "{tool} {needs_not} in container {index}");
}
}
}

/// A node of an inline graph is checked as a step of a saved model is, by every capability: one
/// sample for each entry of `COMMAND_CAPABILITIES`, each requiring exactly its own name, so an
/// entry added later without a sample fails here. The walk takes a node's id and parameters as
/// they come, as a saved model's does, so every entry is reachable; only the tool-based ones
/// (`tabulate*`, `dggs-system`) are also a node a run can run, the rest are parity.
#[test]
fn an_inline_graph_node_is_checked_as_a_saved_step_is() {
let ink_layout = {
let fixture = Project::from_json(include_str!("../../../schema/fixtures/layout_element_ink.rgis")).unwrap();
serde_json::to_value(&fixture).unwrap()["layouts"][0].to_string()
};
let chart = json!({"kind": "chart"});
let samples: Vec<(Option<&str>, &str, Value)> = vec![
(Some("slope-percent"), "raster.function", json!({"function": "slope", "units": "percent"})),
(Some("slope-percent"), "raster.functionChain", json!({"steps": [{"function": "slope", "units": "percent"}]})),
(Some("tabulate-intersection-unit"), "tabulateIntersection", json!({"areaUnit": "ac"})),
(Some("tabulate-intersection-empty-zones"), "tabulateIntersection", json!({"includeEmptyZones": true})),
(Some("layout-element-background"), "layout.update", json!({"element": 1, "background": {}})),
(Some("picture-markers"), "layer.marker", json!({"image": "iVBORw0KGgo"})),
(Some("graticule-mgrs"), "map.graticule", json!({"type": "mgrs"})),
(Some("graticule-on-top"), "map.graticule", json!({"onTop": true})),
(Some("graticule-color"), "map.graticule", json!({"color": "#000000"})),
(Some("layout-element-ink"), "layout.import", json!({"text": ink_layout})),
(Some("layout-element-wrap"), "layout.addElement", json!({"kind": "text", "wrap": true})),
(Some("layout-chart-data"), "layout.addElement", json!({"kind": "chart", "group": "Region"})),
(Some("layout-chart-look"), "layout.update", json!({"element": 1, "values": true})),
(Some("layout-chart-classes"), "layout.update", json!({"element": 1, "classes": true})),
(Some("layout-chart-stack"), "layout.update", json!({"element": 1, "stack": "Kind"})),
(Some("layout-chart-facing"), "layout.update", json!({"element": 1, "mirror": true})),
(Some("blank-paper"), "map.basemap", json!({"name": "blank", "color": "#112233"})),
(Some("layout-frame-border"), "layout.update", json!({"element": 1, "border": {}})),
(Some("layout-text-size"), "layout.update", json!({"element": 1, "textSize": 12})),
(Some("dggs-system"), "a5Grid", json!({"system": "H3"})),
(Some("dggs-system"), "a5Aggregate", json!({"system": "S2"})),
(Some("label-weight"), "labels.placement", json!({"weight": 9})),
(None, "buffer", json!({"input": "Cities", "distance": 1})),
(None, "layout.addElement", chart),
];
let mut covered = std::collections::BTreeSet::new();
for (capability, id, params) in samples {
let step = [ModelStep { tool: id.into(), params: params.clone() }];
let names: Vec<&str> =
COMMAND_CAPABILITIES.iter().filter_map(|&(name, uses)| model_uses(&step, None, uses).then_some(name)).collect();
assert_eq!(names, capability.into_iter().collect::<Vec<_>>(), "the sample {id} {params} requires exactly its own capability");
covered.extend(capability);
for (index, saved) in saved_requires_of_inline_graph(&graph_of_one_tool(id, params.clone())).into_iter().enumerate() {
// The documents are otherwise empty, so the header names only what the node needs.
assert_eq!(saved, capability.map(|name| json!([name])), "{id} {params} in container {index}");
}
}
let missing: Vec<&str> = COMMAND_CAPABILITIES.iter().map(|&(name, _)| name).filter(|name| !covered.contains(name)).collect();
assert!(missing.is_empty(), "add a sample for each command capability, missing: {missing:?}");
assert_eq!(covered.len(), COMMAND_CAPABILITIES.len(), "a sample names a capability the table doesn't have: {covered:?}");
}

/// An inline graph is read as the run reads it: only an object with `nodes`, only nodes of kind
/// `tool` with an object for `params`; one it can't read it drops, not the rest.
#[test]
fn an_inline_graph_is_read_as_the_run_reads_it() {
let h3 = json!({"system": "H3"});
let node = |extra: Value| {
let mut n = json!({"id": "n", "kind": "tool", "tool": "a5Grid", "params": h3});
for (k, v) in extra.as_object().into_iter().flatten() {
n[k] = v.clone();
}
n
};
let none = |run: Value, why: &str| {
assert!(saved_requires_of_inline_graph(&run).iter().all(Option::is_none), "{why}");
};
let needs = |run: Value, why: &str| {
assert!(saved_requires_of_inline_graph(&run).iter().all(|r| r == &Some(json!(["dggs-system"]))), "{why}");
};
let graph = |nodes: Vec<Value>| json!({"graph": {"nodes": nodes}});
none(json!({"graph": graph(vec![node(json!({}))]).get("graph").map(Value::to_string)}), "a graph as text is refused by the run");
none(json!({"graph": null, "name": "Saved"}), "no graph: the named model is read as a saved model");
none(json!({"graph": []}), "not an object");
none(json!({"graph": {"nodes": "text"}}), "nodes not a list");
none(graph(vec![node(json!({"kind": null}))]), "no kind");
none(graph(vec![node(json!({"kind": "input"}))]), "an input node runs no tool");
none(graph(vec![node(json!({"kind": "output"}))]), "an output node runs no tool");
none(graph(vec![node(json!({"kind": "Tool"}))]), "kind is lowercase");
none(graph(vec![node(json!({"tool": 5}))]), "tool not text");
none(graph(vec![node(json!({"params": h3.to_string()}))]), "params as text are dropped");
none(graph(vec![node(json!({"params": [h3]}))]), "params as a list are dropped");
none(graph(vec![node(json!({"params": null}))]), "no params");
none(graph(vec![node(json!({"tool": "buffer"}))]), "another tool");
needs(graph(vec![node(json!({}))]), "the plain case");
needs(graph(vec![json!(5), json!({"id": 3}), json!(null), node(json!({}))]), "the run drops a node it can't read, not the rest");
needs(graph(vec![node(json!({"tool": "A5 Grid"}))]), "a tool by its former name");
needs(json!({"graph": {"nodes": [node(json!({}))], "edges": "junk"}}), "edges are not read");
}

/// A graph past the run's limits is refused there, so needs nothing; one no bigger is read to
/// its last node. Nested and cyclic graphs are read one level, without recursion.
#[test]
fn a_hostile_inline_graph_is_read_without_panic_or_hang() {
use crate::model::{MAX_EDGES, MAX_NODES};
let junk = || json!({"id": "j", "kind": "tool", "tool": "buffer", "params": {}});
let h3 = || json!({"id": "h", "kind": "tool", "tool": "a5Grid", "params": {"system": "H3"}});
let nodes_with_last = |count: usize, last: Value| {
let mut nodes = vec![junk(); count - 1];
nodes.push(last);
json!({"graph": {"nodes": nodes}})
};
let all = |run: Value, expected: Option<Value>, why: &str| {
for (index, saved) in saved_requires_of_inline_graph(&run).into_iter().enumerate() {
assert_eq!(saved, expected, "{why} (container {index})");
}
};
// A notebook cell is cut at `MAX_SOURCE` on load: the task and history containers cover the oversized graphs.
all(nodes_with_last(MAX_NODES, h3()), Some(json!(["dggs-system"])), "as many nodes as a run takes, the last one needing it");
all(nodes_with_last(MAX_NODES + 1, h3()), None, "one more is refused");
all(nodes_with_last(100_000, h3()), None, "far more is refused");
let mut edges = nodes_with_last(2, h3());
edges["graph"]["edges"] = json!(vec![json!({"from": "j", "to": "h", "toPort": "input"}); MAX_EDGES + 1]);
all(edges, None, "more connections than a run takes");
// A node that is itself a `model.run`, nested to the depth the project's JSON allows (128).
let mut nested = graph_of_one_tool("a5Grid", json!({"system": "H3"}));
for _ in 0..24 {
nested = json!({"graph": {"nodes": [{"id": "m", "kind": "tool", "tool": "model.run", "params": nested}]}});
}
all(nested, None, "a node is a tool, not a model run: nothing inside it is read");
// A node that is a script holding a graph holding a script, as deep as its escaping allows.
let mut cycle = graph_of_one_tool("a5Grid", json!({"system": "H3"}));
for _ in 0..12 {
let script = format!("model.run {cycle}");
cycle = json!({"graph": {"nodes": [{"id": "s", "kind": "tool", "tool": "script.run", "params": {"script": script}}]}});
}
all(cycle, None, "a script node is not read into");
// A script of as many graph lines as a script takes.
let line = format!("model.run {}", graph_of_one_tool("buffer", json!({})));
let script = vec![line; crate::cmd::workflows::MAX_SCRIPT_LINES].join("\n");
let base = serde_json::to_value(Project::default()).unwrap();
let mut document = base;
document["tasks"] = json!([{"name": "T", "steps": [{"title": "Run", "command": "script.run", "params": {"script": script}}]}]);
let project = Project::from_json(&document.to_string()).unwrap();
assert!(serde_json::to_value(&project).unwrap().get("requires").is_none());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test cannot detect the script bound being wrong. Every line is a buffer graph that needs nothing, so the assertion holds even if the walk reads zero lines. The node bound has a real check (nodes_with_last puts the requiring node last), but the script bound does not.

Fix: put a graph that needs dggs-system (for example a5Grid with {"system": "H3"}) on the last line, the 10,000th, and assert that requires is ["dggs-system"]. A walk that stopped one line early would then fail.

Category: quality

}

/// All replayable project containers require non-default options only when requested.
/// Selection of executable notebook cells follows the notebook runner's language boundary.
#[test]
Expand Down
4 changes: 4 additions & 0 deletions docs/maintaining.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,10 @@ The same containers require `dggs-system` when Generate Tessellation or Aggregat
reader would make A5 cells, warning only that it ignored the key. A blank `system`, `A5` or none
needs nothing.

Every command capability above also reads a `model.run` whose `graph` is given inline, in a saved
task step, script line, notebook cell or history entry: each of the graph's tool nodes needs what
the same tool as a step needs.

Projects with a background on a layout element, or a saved task step, script, notebook command
cell or history entry that gives one (`layout.addElement` or `layout.update` with a
`background` other than `null`), require `layout-element-background`, so an older reader
Expand Down
Loading