diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index 0da3423d80..68aad49e0c 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -457,6 +457,36 @@ pub fn resolve_params(spec: &ToolSpec, params: &Value) -> Result params_for(spec, params, source_of(spec).is_none()) } +/// The keys of `params` that `spec` doesn't read, for an error that a required parameter is +/// missing (#2307): a misspelled key is the likely reason, and a failed run's warnings are taken +/// back, so the error says it: " (given 'clips', which Clip doesn't read)". Empty when there are +/// none. Bounded as [`quoted_keys`] bounds them. +fn unread(spec: &ToolSpec, params: &Value) -> String { + let Some(given) = params.as_object() else { return String::new() }; + let unknown: Vec<&str> = given.keys().map(String::as_str).filter(|k| !is_expected_key(spec, params, k)).collect(); + if unknown.is_empty() { + return String::new(); + } + format!(" (given {}, which {} doesn't read)", quoted_keys(unknown), spec.name) +} + +/// Parameter keys a command or tool was given but doesn't read, quoted for a notice or an error +/// (#194, #2307): `'a', 'b', 'c', 'd', 'e', 2 more`. Bounded, since the keys come from the caller: +/// the first five, sorted, each cut to 40 characters, then how many more. +pub fn quoted_keys(mut unknown: Vec<&str>) -> String { + unknown.sort_unstable(); + // A control character (a newline, an escape) would reach a terminal as it is: shown as `?`. + let clip = |k: &str| { + let safe = k.chars().map(|c| if c.is_control() { '?' } else { c }); + if k.chars().count() > 40 { safe.take(40).chain(['…']).collect() } else { safe.collect::() } + }; + let mut said: Vec = unknown.iter().take(5).map(|k| format!("'{}'", clip(k))).collect(); + if unknown.len() > 5 { + said.push(format!("{} more", unknown.len() - 5)); + } + said.join(", ") +} + /// Applies the captured schema without looking its suite up again after a reload. fn params_for(spec: &ToolSpec, params: &Value, built_in: bool) -> Result { let mut p = params.as_object().cloned().unwrap_or_default(); @@ -471,22 +501,23 @@ fn params_for(spec: &ToolSpec, params: &Value, built_in: bool) -> Result bool { - if spec.params.iter().any(|p| p.name == key) { - return true; - } - if spec.id == "joinField" { JOIN_FIELD_ALIASES.contains(&key) } else { false } + spec.params.iter().any(|p| p.name == key) || (spec.id == "joinField" && JOIN_FIELD_ALIASES.contains(&key)) +} + +/// Whether a key given with a run isn't one to warn of (#2307): one [`is_accepted_param`] accepts, +/// or the name the app's tool dialog puts beside a table's id for the run's history: `_name` +/// beside a layer parameter `` that holds a table id (a number, or its digits as text for a +/// tool that isn't built in, read as a table id is read). No tool reads it, so it isn't a +/// parameter to run over either; given without the id, it's taken for a stray. +pub fn is_expected_key(spec: &ToolSpec, params: &Value, key: &str) -> bool { + // A built-in tool reads digit text as a name, not a table id. + let table_id = |id: &Value| { + id.as_u64().is_some_and(|n| u32::try_from(n).is_ok()) + || (source_of(spec).is_some() && id.as_str().is_some_and(|t| t.trim().parse::().is_ok())) + }; + is_accepted_param(spec, key) + || key.strip_suffix("_name").is_some_and(|base| { + spec.params.iter().any(|p| p.name == base && matches!(p.kind, ParamKind::Layer)) && params.get(base).is_some_and(table_id) + }) } /// The names a tool reads one of its parameters under, `key` among them, or none when it has no diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 5773a34bae..9bf54fdce8 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -7806,10 +7806,7 @@ fn zonal_stats(inp: &dyn Inputs, p: &Json) -> Result { /// [`zonal_stats`] on `threads` threads (none: as many as pay off and the masks' memory allows). fn zonal_stats_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result { - let r_name = { - let n = s(p, "raster"); - if n.is_empty() { s(p, "layer") } else { n } - }; + let r_name = s(p, "raster"); if r_name.is_empty() { return Err("parameter 'raster' is required".into()); } @@ -7817,7 +7814,7 @@ fn zonal_stats_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result< let r = r_input.raster; r.require_coordinates()?; - let poly_param = if !s(p, "polygons").is_empty() { "polygons" } else { "input" }; + let poly_param = "polygons"; let poly_ds = input(inp, p, poly_param)?; if poly_ds.geometry_type != GeometryType::Polygon { return Err(format!( diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 0640b9cb3f..ab75cf6951 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -23,7 +23,7 @@ pub fn commands() -> Vec { C::new("gp.spatialJoin", "Spatial Join", "Analyze › Overlay", spatial_join).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_layers) .params( - r#"{"target": layer, "join": layer, "match"?: "Intersects" (default) | "Contains" | "Within", "operation"?: "Join one to one" (default) | "Join one to many", "keepAll"?: "Keep all" (default) | "Keep only matching", "prefix"?: "join_", "output"?: text}"#, + r#"{"target": layer, "join": layer, "match"?: "Intersects" (default) | "Contains" | "Within" | "Have their center in" | "Largest overlap" | "Closest" | "Within a distance", "distance"?: number (Closest: how far to look; Within a distance: required), "units"?: "Kilometers" (default) | "Meters" | "Miles" | "Feet", "distanceField"?: text (a field for the distance, Closest and Within a distance), "operation"?: "Join one to one" (default) | "Join one to many", "keepAll"?: "Keep all" (default) | "Keep only matching", "merge"?: [{"field", "rule": "first" | "last" | "sum" | "mean" | "min" | "max" | "count" | "join", "delimiter"?}] (one to one), "prefix"?: "join_", "output"?: text}"#, ), C::new("gp.zonalStats", "Zonal Statistics", "Analyze › Raster", zonal_stats).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_layers) @@ -386,7 +386,7 @@ pub type ExternalOutput = Result<(Vec<(String, Vec)>, Vec), String>; pub fn external_start(s: &mut Session, tool: &str, params: &Value) -> Result { #[cfg(feature = "geolibre")] { - let op = s.authorize_tool(tool, params)?; + let op = admitted_saying(s, tool, params)?; let continuation = s.tool_continuation(&op)?; let crate::policy::ToolOp { pin, params } = op.op(); let spec = pin.spec(); @@ -526,7 +526,7 @@ fn preparing(continuation: &crate::policy::Continuation, f: impl FnOnce() -> /// Prepares a run of a plugin tool on the active map, as `gp.run` would run it: its parameters /// checked and its layers read now, so that the map can change while it runs. pub fn plugin_start(s: &mut Session, tool: &str, params: &Value) -> Result { - let op = s.authorize_tool(tool, params)?; + let op = admitted_saying(s, tool, params)?; let continuation = s.tool_continuation(&op)?; let crate::policy::ToolOp { pin, params: resolved } = op.op(); let spec = pin.spec(); @@ -734,7 +734,7 @@ impl ToolRun { /// layer edited meanwhile is handled as for a plugin tool. Plugin tools start with /// [`plugin_start`]. pub fn tool_start(s: &mut Session, tool: &str, params: &Value) -> Result { - let op = s.authorize_tool(tool, params)?; + let op = admitted_saying(s, tool, params)?; let continuation = s.tool_continuation(&op)?; let crate::policy::ToolOp { pin, params: resolved } = op.op(); let pin = pin.clone(); @@ -1582,7 +1582,7 @@ impl Inputs for MapInputs<'_> { fn run(s: &mut Session, p: &Value) -> CmdResult { let tool = ps(p, "tool").ok_or("tool is required")?.to_string(); let params = p.get("params").cloned().unwrap_or(json!({})); - run_tool(s, &tool, ¶ms) + run_tool_saying(s, &tool, ¶ms) } /// Whether `inputs` is the wildcard `"*"` (either as a string or a single-element array `["*"]`). @@ -1728,7 +1728,7 @@ pub fn run_batch_with(s: &mut Session, p: &Value, control: &std::sync::Arc { let err_str = e.to_string(); + let rec_params = batch_item_params(spec, &base_params, batch_param, target); let spec = rustgis_analysis::tool(tool_id); let name = spec.map(|t| t.name).unwrap_or("Tool").to_string(); - let mut rec_params = base_params.clone(); - if let Value::Object(ref mut map) = rec_params { - map.insert(batch_param.to_string(), json!(target)); - } let mut record_json = json!({ "tool": tool_id, "inputs": [target], @@ -2069,29 +2066,15 @@ pub fn run_batch_with(s: &mut Session, p: &Value, control: &std::sync::Arc CmdResult { run_tool(s, "zonalStats", p) } -/// Runs a (built-in) tool and applies its result, as `gp.run` does. Where a person at a terminal -/// can stop it with Ctrl-C ([`Session::stoppable`](crate::Session::stoppable)), it takes no work -/// cap ([`rustgis_analysis::control::Control::stoppable`]). -pub fn run_tool(s: &mut Session, tool: &str, params: &Value) -> CmdResult { +/// A `gp.batch` item's parameters: `base` with `batch_param` set to `input`. A tool reading the +/// input under another name (Join Field's `input` for `target`) mustn't take a static value given +/// under it in place of each batch input, nor keep the tool dialog's name of the table it replaced +/// (`input_name`, `target_name`), so those go. An alias the tool declares itself goes too (Join +/// Field's `target` beside a `target_layer` batch): `gp.batch` says which names it replaced. +fn batch_item_params(spec: &rustgis_analysis::ToolSpec, base: &Value, batch_param: &str, input: &str) -> Value { + let mut p = base.clone(); + if let Value::Object(ref mut map) = p { + for name in rustgis_analysis::param_aliases(spec, batch_param).iter().copied().chain([batch_param]) { + for key in [name.to_string(), format!("{name}_name")] { + if key != batch_param && (key == name || !rustgis_analysis::is_accepted_param(spec, &key)) { + map.remove(&key); + } + } + } + map.insert(batch_param.to_string(), json!(input)); + } + p +} + +/// What a tool says of the keys in `params` it doesn't read (#2307), as `Session::run` says it of a +/// command's (#194) and `gp.batch` of its items': "Buffer ignores 'unit' (it reads input, +/// distance, units, dissolve, output)". `None` when it reads them all. A misspelled parameter +/// would otherwise leave the tool at its default without a word: `"unit": "Miles"` buffers in +/// kilometers. +pub(crate) fn ignored_params(spec: &rustgis_analysis::ToolSpec, params: &Value) -> Option { + let unknown: Vec<&str> = + params.as_object()?.keys().map(String::as_str).filter(|k| !rustgis_analysis::is_expected_key(spec, params, k)).collect(); + if unknown.is_empty() { + return None; + } + let reads: Vec<&str> = spec.params.iter().map(|p| p.name).collect(); + crate::ignored_keys(spec.name, unknown, &reads) +} + +/// The run of `tool` admitted, as [`Session::authorize_tool`] admits it, warning which of +/// `params` it ignores ([`ignored_params`]). A refused run's error says them itself when a +/// required parameter is missing, the likely reason (a failed command takes its warnings back). +/// For the runs started from what a caller wrote (`gp.run`, the app's runs). A command that runs a +/// tool with its own parameters (`gp.spatialJoin`, `gp.zonalStats`) declares the tool's keys as +/// its own, so `Session::run` has said any it ignores, as a command. +pub(crate) fn admitted_saying( + s: &mut Session, + tool: &str, + params: &Value, +) -> Result, String> { + let op = s.authorize_tool(tool, params)?; + if let Some(said) = ignored_params(op.op().pin.spec(), params) { + s.warn(said); + } + Ok(op) +} + +/// [`run_tool`] for parameters a caller wrote (`gp.run`, a model's step), saying first which of +/// them the tool ignores ([`admitted_saying`]). A failed run takes that warning back, so its +/// error says the keys too when the run fails over its parameters or inside the tool (a run the +/// policy refuses is refused for who asked, not for what it was given). +pub(crate) fn run_tool_saying(s: &mut Session, tool: &str, params: &Value) -> CmdResult { + let control = run_control(s); + let op = admitted_saying(s, tool, params)?; + let spec = op.op().pin.spec(); + s.invoke_tool(op, &control).map_err(|e| saying_unread(spec, params, e)) +} + +/// [`run_tool_saying`] without the warning about ignored parameters: a model's run says them once +/// for all its steps ([`crate::model::run`]), beside its result or its error, so a run that fails +/// later keeps them. The error still says the keys it doesn't read. +pub(crate) fn run_step(s: &mut Session, tool: &str, params: &Value) -> CmdResult { + let control = run_control(s); + let op = s.authorize_tool(tool, params)?; + let spec = op.op().pin.spec(); + s.invoke_tool(op, &control).map_err(|e| saying_unread(spec, params, e)) +} + +/// `error` with the keys of `params` that `spec` doesn't read after it — " (given 'unit', which +/// Buffer doesn't read)" — unless it says them already (a refused parameter's does). +fn saying_unread(spec: &rustgis_analysis::ToolSpec, params: &Value, error: String) -> String { + if error.ends_with("doesn't read)") { + return error; + } + let unknown: Vec<&str> = params + .as_object() + .into_iter() + .flat_map(|m| m.keys().map(String::as_str)) + .filter(|k| !rustgis_analysis::is_expected_key(spec, params, k)) + .collect(); + if unknown.is_empty() { + return error; + } + format!("{error} (given {}, which {} doesn't read)", rustgis_analysis::quoted_keys(unknown), spec.name) +} + +/// The control a tool run in the session takes: where a person at a terminal can stop it with +/// Ctrl-C ([`Session::stoppable`](crate::Session::stoppable)), no work cap +/// ([`rustgis_analysis::control::Control::stoppable`]). +fn run_control(s: &Session) -> std::sync::Arc { use rustgis_analysis::control::Control; - let control = if s.stoppable { Control::stoppable() } else { Control::new() }; + if s.stoppable { Control::stoppable() } else { Control::new() } +} + +/// Runs a (built-in) tool and applies its result, as `gp.run` does, under [`run_control`]. +pub fn run_tool(s: &mut Session, tool: &str, params: &Value) -> CmdResult { + let control = run_control(s); run_tool_with(s, tool, params, &control) } @@ -4727,6 +4807,19 @@ mod batch_tests { ); assert!(res.is_err()); assert!(res.unwrap_err().contains("tool 'buffer' has no parameter 'imput'")); + // The tool dialog's `input_name` isn't warned of, but nor is it a parameter to run over. + let res = s.run( + "gp.batch", + &json!({"tool": "buffer", "inputs": ["Cities"], "param": "input_name", "params": {"input": "Cities", "distance": 10}}), + ); + assert!(res.is_err_and(|e| e.contains("tool 'buffer' has no parameter 'input_name'"))); + // Each item drops the dialog's name of the table it replaces, so its history doesn't name + // the wrong one. + let n = s.project.gp_history.len(); + s.run("gp.batch", &json!({"tool": "buffer", "inputs": ["Cities"], "params": {"input": 7, "input_name": "Old", "distance": 10}})) + .unwrap(); + let recorded = &s.project.gp_history[n..]; + assert!(!recorded.is_empty() && recorded.iter().all(|h| h.params.get("input_name").is_none()), "{recorded:?}"); } #[test] @@ -5709,6 +5802,155 @@ mod batch_tests { ); } + /// `gp.run`, a run started in the background and a model's step say which parameters a tool + /// ignores (#2307), as `gp.batch` does: a misspelled `unit` would otherwise leave Buffer at its + /// default, kilometers, without a word. The run itself is as before; a clean run says nothing; + /// a batch says it once, its own way; `model.validate` lists it as a warning, which doesn't + /// keep the model from running. + #[test] + fn a_tool_says_which_parameters_it_ignores() { + let said = |s: &Session, mark: u64| -> Vec { + s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains(" ignores ")).collect() + }; + let buffer = "Buffer ignores 'unit' (it reads input, distance, units, dissolve, output)"; + let mut s = test_session(); + let mark = s.notices.len() as u64; + s.run("gp.run", &json!({"tool": "buffer", "params": {"input": "Cities", "distance": 100, "unit": "Miles"}})).unwrap(); + assert_eq!(said(&s, mark), [buffer]); + // The run is as before: the default units, which its own message names. + assert!(s.notices_since(mark).iter().any(|n| n.text.contains("at 100 Kilometers"))); + let mark = s.notices.len() as u64; + s.run("gp.run", &json!({"tool": "buffer", "params": {"input": "Cities", "distance": 100, "units": "Miles"}})).unwrap(); + assert!(said(&s, mark).is_empty(), "{:?}", said(&s, mark)); + // The name the tool dialog puts beside a table's id (`input_name`) isn't taken for a stray; + // `_name` beside a parameter that isn't a layer is. + let buffer_spec = resolve_tool("buffer").unwrap(); + assert_eq!(ignored_params(buffer_spec, &json!({"input": 7, "distance": 1, "input_name": "Cities"})), None); + // Beside a layer's name (a built-in tool reads digit text as one), or with no table id at + // all, it's a stray: no tool reads it. + for params in [ + json!({"input": "Cities", "distance": 1, "input_name": "Rivers"}), + json!({"input": "7", "distance": 1, "input_name": "Rivers"}), + json!({"distance": 1, "input_name": "Rivers"}), + ] { + let said = ignored_params(buffer_spec, ¶ms).unwrap(); + assert!(said.starts_with("Buffer ignores 'input_name'"), "{said}"); + } + let stray = ignored_params(buffer_spec, &json!({"input": "Cities", "distance": 1, "distance_name": "x"})).unwrap(); + assert!(stray.starts_with("Buffer ignores 'distance_name'"), "{stray}"); + // Many keys: the first five, sorted, each cut to 40 characters, then how many more. + let mark = s.notices.len() as u64; + let long = "x".repeat(60); + let mut params = json!({"input": "Cities", "distance": 1, "a": 1, "b": 1, "c": 1, "d": 1, "e": 1, "f": 1}); + params[&long] = json!(1); + s.run("gp.run", &json!({"tool": "buffer", "params": params})).unwrap(); + let got = said(&s, mark); + assert_eq!(got.len(), 1, "{got:?}"); + assert!(got[0].starts_with("Buffer ignores 'a', 'b', 'c', 'd', 'e', 2 more"), "{got:?}"); + let mark = s.notices.len() as u64; + s.run("gp.run", &json!({"tool": "buffer", "params": {"input": "Cities", "distance": 1, &long: 1}})).unwrap(); + assert!(said(&s, mark)[0].contains(&format!("'{}…'", "x".repeat(40))), "{:?}", said(&s, mark)); + // A control character in a key reaches no terminal as it is. + let mark = s.notices.len() as u64; + s.run("gp.run", &json!({"tool": "buffer", "params": {"input": "Cities", "distance": 1, "a\n\u{1b}[31mb": 1}})).unwrap(); + assert!(said(&s, mark)[0].starts_with("Buffer ignores 'a??[31mb'"), "{:?}", said(&s, mark)); + // A run refused for want of a parameter that was misspelled says which key it didn't read, + // in its error: a failed command takes its warnings back. + let e = s.run("gp.run", &json!({"tool": "clip", "params": {"input": "Cities", "clips": "Parks"}})).unwrap_err(); + assert!(e.ends_with("'Clip Features' is required (given 'clips', which Clip doesn't read)"), "{e}"); + // Any failed run says them, not only one missing a required parameter. + let e = s + .run("gp.run", &json!({"tool": "buffer", "params": {"input": "Cities", "distance": 1, "dissolve": "maybe", "unit": "Miles"}})) + .unwrap_err(); + assert!(e.ends_with(" (given 'unit', which Buffer doesn't read)"), "{e}"); + assert_eq!(e.matches("doesn't read").count(), 1, "{e}"); + let e = + s.run("gp.run", &json!({"tool": "buffer", "params": {"input": "No Such Layer", "distance": 1, "unit": "Miles"}})).unwrap_err(); + assert!(e.ends_with(" (given 'unit', which Buffer doesn't read)"), "{e}"); + // So does a model's step that fails for it. + s.run("model.new", &json!({"name": "Clips", "steps": [{"tool": "clip", "params": {"input": "Cities", "clips": "Parks"}}]})) + .unwrap(); + let e = s.run("model.run", &json!({"name": "Clips"})).unwrap_err(); + assert!(e.contains("(given 'clips', which Clip doesn't read)"), "{e}"); + assert_eq!(e.matches("'clips'").count(), 1, "said once: {e}"); + // A command that runs a tool for its own parameters says a stray key once, as a command. + let mark = s.notices.len() as u64; + s.run("gp.spatialJoin", &json!({"target": "Cities", "join": "Parks", "prefx": "j_"})).unwrap(); + let got = said(&s, mark); + assert!(got.len() == 1 && got[0].starts_with("gp.spatialJoin ignores 'prefx'"), "{got:?}"); + // It declares every key its tool reads, so those aren't taken for strays. + let mark = s.notices.len() as u64; + let join = json!({"target": "Cities", "join": "Parks", "match": "Within a distance", "distance": 5000, "units": "Miles", "distanceField": "d"}); + s.run("gp.spatialJoin", &join).unwrap(); + assert!(said(&s, mark).is_empty(), "{:?}", said(&s, mark)); + for (cmd, tool) in [("gp.spatialJoin", "spatialJoin"), ("gp.zonalStats", "zonalStats")] { + let command = s.registry.get(cmd).and_then(|c| c.param_keys()).unwrap(); + let tool = resolve_tool(tool).unwrap(); + let missing: Vec<&str> = tool.params.iter().map(|p| p.name).filter(|k| !command.contains(k)).collect(); + assert!(missing.is_empty(), "{cmd} doesn't declare {missing:?}"); + } + // Zonal Statistics reads its raster only as `raster`: a run given the old `layer` is + // refused, and the error names the key it was given. + let e = s.run("gp.run", &json!({"tool": "zonalStats", "params": {"layer": "Cities", "polygons": "Parks"}})).unwrap_err(); + assert!(e.ends_with("'Input Raster' is required (given 'layer', which Zonal Statistics doesn't read)"), "{e}"); + // A run started in the background says it too, before its work. + let mark = s.notices.len() as u64; + let _run = tool_start(&mut s, "buffer", &json!({"input": "Cities", "distance": 100, "unit": "Miles"})).unwrap(); + assert_eq!(said(&s, mark), [buffer]); + // A batch says it once, its own way, not once per item as well. + let mark = s.notices.len() as u64; + s.run("gp.batch", &json!({"tool": "buffer", "inputs": ["Cities"], "params": {"distance": 10, "unit": "Miles"}})).unwrap(); + assert!(said(&s, mark).is_empty(), "{:?}", said(&s, mark)); + assert!(s.notices_since(mark).iter().any(|n| n.text.contains("unrecognised parameter(s) ignored in 'params' (unit)"))); + // A model: validate warns without refusing it, and its step says it as it runs. + let step = |p: Value| json!({"name": "Typo", "steps": [{"tool": "buffer", "params": p}]}); + s.run("model.new", &step(json!({"input": "Cities", "distance": 100, "unit": "Miles"}))).unwrap(); + let v = s.run("model.validate", &json!({"name": "Typo"})).unwrap(); + assert_eq!(v["ok"], true, "{v}"); + let warnings = v["warnings"].as_array().unwrap(); + assert_eq!(warnings.len(), 1, "{v}"); + assert_eq!((warnings[0]["code"].as_str(), warnings[0]["message"].as_str()), (Some("unknown-param"), Some(buffer)), "{v}"); + let mark = s.notices.len() as u64; + s.run("model.run", &json!({"name": "Typo"})).unwrap(); + assert_eq!(said(&s, mark), [buffer]); + s.run("model.new", &json!({"name": "Clean", "steps": [{"tool": "buffer", "params": {"input": "Cities", "distance": 100}}]})) + .unwrap(); + let v = s.run("model.validate", &json!({"name": "Clean"})).unwrap(); + assert_eq!(v["warnings"], json!([]), "{v}"); + } + + /// A model saved as steps says each kind of ignored parameter once for its run, with the + /// steps that give it, and a failed run carries it in its error instead of a notice that + /// would go back with the run's changes. + #[test] + fn a_model_of_steps_says_ignored_parameters_once() { + let said = |s: &Session, mark: u64| -> Vec { + s.notices_since(mark).iter().filter(|n| !n.error).map(|n| n.text.clone()).filter(|t| t.contains(" ignores ")).collect() + }; + let buffer = "Buffer ignores 'unit' (it reads input, distance, units, dissolve, output)"; + let mut s = test_session(); + let twice = json!([ + {"tool": "buffer", "params": {"input": "Cities", "distance": 100, "unit": "Miles"}}, + {"tool": "buffer", "params": {"input": "%1", "distance": 10, "unit": "Miles"}} + ]); + s.run("model.new", &json!({"name": "Twice", "steps": twice})).unwrap(); + let mark = s.notices.len() as u64; + s.run("model.run", &json!({"name": "Twice"})).unwrap(); + assert_eq!(said(&s, mark), [format!("{buffer} (in 2 steps)")]); + // A failing step after an ignoring one: the error carries the warning, and no warning + // is left behind for the run that failed (its error is posted as one, as any is). + let stops = json!([ + {"tool": "buffer", "params": {"input": "Cities", "distance": 100, "unit": "Miles"}}, + {"tool": "buffer", "params": {"distance": 10}} + ]); + s.run("model.new", &json!({"name": "Stops", "steps": stops})).unwrap(); + let mark = s.notices.len() as u64; + let e = s.run("model.run", &json!({"name": "Stops"})).unwrap_err(); + assert!(e.starts_with("step 2 (buffer)"), "{e}"); + assert!(e.ends_with(&format!("; {buffer}")), "{e}"); + assert!(said(&s, mark).is_empty(), "{:?}", said(&s, mark)); + } + #[test] fn batch_run_params_batch_param_overwritten_notified() { let mut s = test_session(); @@ -5911,15 +6153,16 @@ mod batch_tests { "tool": "joinField", "inputs": ["Tracts", "Blocks"], "param": "target_layer", - // `input` names Join Field's target too: it must not stand in for each batch input. - "params": {"input": "Other", "targetField": "GEOID", "joinTable": "Census", "joinField": "FIPS"} + // `input` names Join Field's target too: it must not stand in for each batch input, + // nor its dialog-given name (`input_name`) stay beside each. + "params": {"input": "Other", "input_name": "Other", "targetField": "GEOID", "joinTable": "Census", "joinField": "FIPS"} }), ) .unwrap(); assert_eq!(res["succeeded"], 2, "{res}"); let targets: Vec<_> = s.project.gp_history[before..].iter().map(|r| r.params["target_layer"].clone()).collect(); assert_eq!(targets, [json!("Tracts"), json!("Blocks")]); - assert!(s.project.gp_history[before..].iter().all(|r| r.params.get("input").is_none())); + assert!(s.project.gp_history[before..].iter().all(|r| r.params.get("input").is_none() && r.params.get("input_name").is_none())); let other = s.map().layer_by_name("Other").unwrap(); assert!(!other.dataset.fields.iter().any(|f| f.name == "FIPS"), "the static alias's layer was joined"); } @@ -5929,11 +6172,14 @@ mod batch_tests { let mut s = test_session(); let before = s.project.gp_history.len(); // A name that is neither a layer, a table nor a file: the tool's input can't be mapped. - let res = s.run("gp.batch", &json!({"tool": "buffer", "inputs": ["Cities", "Nowhere"], "params": {"distance": 1}})).unwrap(); + let params = json!({"input": 7, "input_name": "Old", "distance": 1}); + let res = s.run("gp.batch", &json!({"tool": "buffer", "inputs": ["Cities", "Nowhere"], "params": params})).unwrap(); assert_eq!(res["failed"], 1, "{res}"); let failed: Vec<_> = s.project.gp_history[before..].iter().filter(|r| !r.ok).collect(); assert_eq!(failed.len(), 1); assert_eq!(failed[0].params["input"], "Nowhere"); + // It doesn't keep the tool dialog's name of the table it replaced either. + assert!(failed[0].params.get("input_name").is_none(), "{:?}", failed[0].params); } #[test] diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 647854bfd7..efc49b6720 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -37,7 +37,9 @@ pub fn commands() -> Vec { let (_, g, _) = model_graph(s, p)?; note_passed_graph(s, p); let problems = crate::model::validate(s, &g); - Ok(json!({"ok": problems.is_empty(), "problems": problems})) + // What the model does that it may not mean, which doesn't keep it from running. + let warnings = crate::model::warnings(&g); + Ok(json!({"ok": problems.is_empty(), "problems": problems, "warnings": warnings})) }).roles(&[crate::ParamRole { key: "graph", role: crate::Role::ModelGraph }]).effects(crate::policy::Effects::NONE) .view() .params(r#"{"name"?: model (default: the last), "graph"?: graph}"#), @@ -1057,13 +1059,36 @@ fn run_steps(s: &mut Session, model: Model) -> CmdResult { st.tool )); } + // The parameters the steps ignore are said once for the run, as a graph's run says them + // (#2307). A failed run's error carries them, as its notices go back with its changes. + let mut ignored = Vec::new(); + let res = run_step_list(s, &model, &mut ignored); + let said = crate::model::ignored_summary(&ignored); + match res { + Err(e) if !said.is_empty() => Err(format!("{e}; {said}")), + res => { + if !said.is_empty() { + s.warn(said); + } + res + } + } +} + +/// Runs each of a model's steps in order ([`run_steps`]), collecting into `ignored` what each +/// step's tool ignores ([`super::gp::ignored_params`]). +fn run_step_list(s: &mut Session, model: &Model, ignored: &mut Vec) -> CmdResult { let mut outputs: Vec = Vec::new(); let mut ran = Vec::new(); for (i, st) in model.steps.iter().enumerate() { let mut params = st.params.clone(); wire(&mut params, &outputs, i, 0)?; let before = s.project.gp_history.len(); - let r = super::gp::run_tool(s, &st.tool, ¶ms).map_err(|e| format!("step {} ({}): {e}", i + 1, st.tool))?; + let r = super::gp::run_step(s, &st.tool, ¶ms).map_err(|e| format!("step {} ({}): {e}", i + 1, st.tool))?; + // Said once for the run; a failing step's error names its own keys already. + if let Some(said) = rustgis_analysis::resolve_published(&st.tool).and_then(|r| super::gp::ignored_params(r.spec(), ¶ms)) { + ignored.push(said); + } // A step that made no layer leaves nothing for a later %n to use. let out = (s.project.gp_history.len() > before).then(|| s.project.gp_history.last().and_then(|h| h.outputs.first().cloned())).flatten(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a5987a2ade..5239ca203c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -372,6 +372,18 @@ fn param_entries<'a>(desc: &'a str, mut visit: impl FnMut(&'a str, bool)) -> Opt /// What a zoom to a place the map's projection doesn't reach says, once in a command. const BEYOND_PROJECTION: &str = "The place lies beyond what the map's projection shows, so the view wasn't moved to it."; +/// What a command (#194) or a tool (#2307) says of the parameters it was given but doesn't read, +/// so a script or an agent can correct itself: "Buffer ignores 'unit' (it reads input, distance, +/// units, dissolve, output)". `None` when `unknown` is empty. The keys are listed as a tool's +/// missing-parameter error lists them ([`rustgis_analysis::quoted_keys`]). +pub(crate) fn ignored_keys(name: &str, unknown: Vec<&str>, known: &[&str]) -> Option { + if unknown.is_empty() { + return None; + } + let reads = if known.is_empty() { "no parameters".to_string() } else { known.join(", ") }; + Some(format!("{name} ignores {} (it reads {reads})", rustgis_analysis::quoted_keys(unknown))) +} + /// `s` cut to `n` characters, with `…` when cut. fn clip(s: &str, n: usize) -> String { if s.chars().count() > n { s.chars().take(n).chain(['…']).collect() } else { s.to_string() } @@ -1851,15 +1863,9 @@ impl Session { } // Keys the command does not read: said, so a script or an agent can correct itself. if let (Value::Object(given), Some(known)) = (params, spec.param_keys()) { - // Bounded: the keys come from the caller (the first few, each clipped). - let unknown: Vec<&String> = given.keys().filter(|k| !known.contains(&k.as_str())).collect(); - if !unknown.is_empty() { - let mut said: Vec = unknown.iter().take(5).map(|k| format!("'{}'", clip(k, 40))).collect(); - if unknown.len() > 5 { - said.push(format!("{} more", unknown.len() - 5)); - } - let reads = if known.is_empty() { "no parameters".to_string() } else { known.join(", ") }; - self.warn(format!("{id} ignores {} (it reads {reads})", said.join(", "))); + let unknown = given.keys().map(String::as_str).filter(|k| !known.contains(k)).collect(); + if let Some(said) = ignored_keys(id, unknown, &known) { + self.warn(said); } } let active = self.active_layer; diff --git a/crates/engine/src/model.rs b/crates/engine/src/model.rs index 8eba96214a..d4042bb4a5 100644 --- a/crates/engine/src/model.rs +++ b/crates/engine/src/model.rs @@ -241,6 +241,24 @@ pub fn validate(s: &Session, g: &ModelGraph) -> Vec { out } +/// What a graph does that it may not mean, without keeping it from running (#2307): a tool's +/// parameter the tool doesn't read, so the step runs with the tool's default (a misspelled `unit` +/// for `units`). Each step's run says it again. A graph past the size bound has none listed: +/// [`validate`] refuses it. +pub fn warnings(g: &ModelGraph) -> Vec { + if g.nodes.len() > MAX_NODES || g.edges.len() > MAX_EDGES { + return Vec::new(); + } + g.nodes + .iter() + .filter(|n| n.kind == ModelNodeKind::Tool) + .filter_map(|n| { + let said = crate::cmd::gp::ignored_params(tool_of(n)?, &n.params)?; + Some(problem("unknown-param", Some(&n.id), said)) + }) + .collect() +} + impl PortKind { /// The more specific of a node's known kind and its port's. fn max_kind(self, port: PortKind) -> PortKind { @@ -612,6 +630,9 @@ pub struct RunReport { /// Correlates browser acknowledgements with this run only, never a newer report. #[serde(skip)] pending_files: HashMap, + /// What each step's tool ignores, one line per step (#2307): [`run`] says them once per kind. + #[serde(skip)] + ignored: Vec, } impl RunReport { @@ -638,6 +659,18 @@ pub(crate) fn run(s: &mut Session, op: crate::policy::Authorized Err(format!("{e}; {ignored}")), + res => { + if !ignored.is_empty() { + s.warn(ignored); + } + res + } + }; if res.is_err() { for node in report.nodes.iter_mut().filter(|node| node.status == "pending") { node.status = "error"; @@ -652,6 +685,29 @@ pub(crate) fn run(s: &mut Session, op: crate::policy::Authorized String { + let mut kinds: Vec<(&str, usize)> = Vec::new(); + for text in said { + let text = text.as_str(); + match kinds.iter_mut().find(|(k, _)| *k == text) { + Some((_, n)) => *n += 1, + None => kinds.push((text, 1)), + } + } + let parts: Vec = + kinds.iter().take(IGNORED_KINDS_SAID).map(|&(k, n)| if n > 1 { format!("{k} (in {n} steps)") } else { k.to_string() }).collect(); + match kinds.len().saturating_sub(IGNORED_KINDS_SAID) { + 0 => parts.join("; "), + more => format!("{}; {more} more kinds", parts.join("; ")), + } +} + /// Validate the graph and reject an imported graph's external tools before executing any node. /// Trusted graphs retain the normal tool execution and output wiring. fn run_into(s: &mut Session, g: &ModelGraph, report: &mut RunReport) -> Result, String> { @@ -699,8 +755,13 @@ fn run_into(s: &mut Session, g: &ModelGraph, report: &mut RunReport) -> Result = s.map().layers.iter().map(|l| l.id).collect(); let history = s.project.gp_history.len(); - match crate::cmd::gp::run_tool(s, tool, ¶ms) { + match crate::cmd::gp::run_step(s, tool, ¶ms) { Ok(r) => { + // Which of its parameters the tool ignores is said by `run`, once for the + // model (#2307). A failing step's error names its own keys already. + if let Some(said) = tool_of(n).and_then(|spec| crate::cmd::gp::ignored_params(spec, ¶ms)) { + report.ignored.push(said); + } let ids: Vec = s.map().layers.iter().filter(|l| !before.contains(&l.id)).map(|l| l.id).collect(); // The first layer it added (else the first output it recorded: a table). let first_id = ids.iter().rev().copied().find(|id| s.map().layer(*id).is_some()); @@ -1000,6 +1061,19 @@ mod tests { use super::*; use crate::Project; + /// A run's ignored-parameter warning lists at most five kinds, and counts the rest, so a long + /// model's warning still fits a notice; a kind given by several steps says how many. + #[test] + fn ignored_summary_lists_five_kinds_and_counts_the_rest() { + assert_eq!(ignored_summary(&[]), ""); + let mut said: Vec = (0..7).map(|i| format!("Tool{i} ignores 'x'")).collect(); + said.push("Tool0 ignores 'x'".to_string()); + let text = ignored_summary(&said); + assert!(text.starts_with("Tool0 ignores 'x' (in 2 steps); Tool1 ignores 'x'; "), "{text}"); + assert!(text.ends_with("Tool4 ignores 'x'; 2 more kinds"), "{text}"); + assert!(!text.contains("Tool5"), "{text}"); + } + /// Graph and web-tool envelopes reflect only their saved executable payload, and default /// km² remains readable without the capability even if the omitted representation needs it. #[test] diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cab0994ff3..86abd62294 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -39068,6 +39068,27 @@ fn model_graphs(s: &mut Session) { let rep = s.model_run.clone().unwrap(); assert_eq!(rep.nodes.last().unwrap().status, "error"); assert_eq!(s.map().layers.len(), layers, "a failed run is undone"); + // A parameter a step's tool ignores is said once for the run (#2307): in the error of a run + // that fails later, which keeps it after the rollback, and beside the result of one that doesn't. + let failing_ignores = json!({"nodes": [ + {"id": "i1", "kind": "input", "layer": "Cities"}, + {"id": "t1", "kind": "tool", "tool": "buffer", "params": {"distance": 20, "unit": "Miles"}}, + {"id": "t2", "kind": "tool", "tool": "dissolve", "params": {"field": "no_such_field"}}], + "edges": [{"from": "i1", "fromPort": "out", "to": "t1", "toPort": "input"}, + {"from": "t1", "fromPort": "out", "to": "t2", "toPort": "input"}]}); + let e = s.run("model.run", &json!({"graph": failing_ignores})).unwrap_err(); + assert!(e.contains("Buffer ignores 'unit'"), "{e}"); + let repeats = json!({"nodes": [ + {"id": "i1", "kind": "input", "layer": "Cities"}, + {"id": "t1", "kind": "tool", "tool": "buffer", "params": {"distance": 20, "unit": "Miles"}}, + {"id": "t2", "kind": "tool", "tool": "buffer", "params": {"distance": 5, "unit": "Miles"}}], + "edges": [{"from": "i1", "fromPort": "out", "to": "t1", "toPort": "input"}, + {"from": "t1", "fromPort": "out", "to": "t2", "toPort": "input"}]}); + let mark = s.notice_mark(); + s.run("model.run", &json!({"graph": repeats})).unwrap(); + let said: Vec<&str> = s.notices_since(mark).iter().map(|n| n.text.as_str()).filter(|t| t.contains("ignores 'unit'")).collect(); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].contains("(in 2 steps)"), "{said:?}"); // Two outputs on one result are refused. let mut twice = graph.clone(); twice["nodes"].as_array_mut().unwrap().push(json!({"id": "o2", "kind": "output", "name": "Again"})); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index b9440743fa..4af976f8d3 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -228,6 +228,11 @@ larger limit, or none, lets through. From the command line or a script (`gp.run`), a built-in tool's parameter with a list of choices, such as Buffer's units, takes one of them in any letter case (`"meters"` for `Meters`); any other value is an error that names the choices (Buffer's units no longer take the abbreviations `m`, `mi` or `metres`). +A parameter the tool doesn't have is said, not dropped without a word, since the tool then uses +its default: `"unit": "Miles"` for `units` gives *Buffer ignores 'unit' (it reads input, distance, +units, dissolve, output)*, and the buffers are in kilometers. `gp.run`, a model's steps and +`gp.batch` all say so, and `model.validate` lists it under `warnings`, which don't keep the model +from running. Buffer and Select Layer By Location accept **Kilometers**, **Meters**, **Miles** and **Feet**. Feet are international feet (exactly 0.3048 metres): a 500-foot notification radius is 152.4 metres on the ground.