From 91735930c0b67567a843f5610a20153835ba4e2d Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 19 Nov 2026 14:46:08 -0600 Subject: [PATCH 1/3] feat(engine): carry loss codes through reader and tool results --- ROADMAP.md | 6 +- crates/analysis/src/dggs.rs | 4 +- crates/analysis/src/lib.rs | 2 + crates/analysis/src/merge.rs | 6 +- crates/analysis/src/tissot.rs | 2 +- crates/analysis/src/tools.rs | 41 +++-- crates/analysis/src/tools/check_geometry.rs | 2 +- crates/analysis/src/tools/geometry.rs | 2 +- crates/analysis/src/tools/network_analysis.rs | 4 +- crates/analysis/src/tools/repair_geometry.rs | 18 +- crates/analysis/src/tools/tabulate_area.rs | 2 +- crates/analysis/tests/repair_geometry.rs | 8 +- crates/analysis/tests/resolved_tools.rs | 6 +- crates/data/src/georss.rs | 10 +- crates/data/src/lib.rs | 9 + crates/data/src/loss.rs | 13 ++ crates/data/src/source/mod.rs | 1 + crates/engine/src/cmd/gp.rs | 156 +++++++++++++----- crates/engine/src/cmd/layer.rs | 4 + crates/engine/src/cmd/stac_area.rs | 2 +- crates/engine/src/policy/dispatch.rs | 2 +- crates/engine/src/tests.rs | 40 ++++- crates/engine/tests/never_silent_reading.rs | 27 ++- crates/geolibre/src/lib.rs | 2 +- crates/plugins/src/tools.rs | 4 +- 25 files changed, 271 insertions(+), 102 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 9749397777..c1adbb1662 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -82,9 +82,9 @@ A result is right, or RustGIS says what it lost or assumed FlatGeobuf, GeoParquet and FileGDB, Z/M-loss cases for Shapefile, and ring-loss cases for OSM PBF, WKT height/member losses for XLSX and ODS, and error-cell losses for XLSX; other loss kinds remain. Exports are checked by `never_silent_roundtrip.rs` _(open)_. -- A `--strict` option for `rustgis-cli run` that exits non-zero when a loss is reported, for - scheduled jobs. Notices carry a severity but not a kind today (`Notice` in - `crates/engine/src/lib.rs`): start with an issue on which notices count as a loss. +- Classify existing loss notices so scheduled jobs can detect them by code. Then add + `rustgis-cli run --strict`, which exits non-zero on a disallowed loss, and expose the codes + to Python and MCP ([#2371](https://github.com/opengeos/RustGIS/issues/2371)). - Grid datum shifts (NTv2 and GeoTIFF grids) for NAD27, NAD83(HARN), GDA94↔GDA2020 and OSGB36 without the GDAL program (a layer read without its shift says so today). _Coordinate first_ (needs an issue). diff --git a/crates/analysis/src/dggs.rs b/crates/analysis/src/dggs.rs index 4e5854b557..c4ffb00484 100644 --- a/crates/analysis/src/dggs.rs +++ b/crates/analysis/src/dggs.rs @@ -322,7 +322,7 @@ pub fn grid(inp: &dyn Inputs, p: &Json) -> Result { if skipped > 0 { msg.push_str(&format!("; {}", left_out(skipped, "polygon part", "outline"))); } - Ok(ToolResult { output: Output::Layer(out), messages: vec![msg] }) + Ok(ToolResult { losses: Vec::new(), output: Output::Layer(out), messages: vec![msg] }) } /// The Aggregate Points to A5 tool: a layer's points counted by the cell holding them (and a @@ -404,7 +404,7 @@ pub fn aggregate(inp: &dyn Inputs, p: &Json) -> Result { if outside > 0 { msg.push_str(&format!("; {}", left_out(outside, "point", "position"))); } - Ok(ToolResult { output: Output::Layer(out), messages: vec![msg] }) + Ok(ToolResult { losses: Vec::new(), output: Output::Layer(out), messages: vec![msg] }) } #[cfg(test)] diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index 43579deaa5..367e2ba177 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -165,6 +165,8 @@ pub struct RasterInput<'a> { pub struct ToolResult { pub output: Output, pub messages: Vec, + /// Losses identified by the producer. Text-only consumers also display their text. + pub losses: Vec, } /// Access to the map's layers by name. diff --git a/crates/analysis/src/merge.rs b/crates/analysis/src/merge.rs index cda15f76eb..14a04095b1 100644 --- a/crates/analysis/src/merge.rs +++ b/crates/analysis/src/merge.rs @@ -71,7 +71,11 @@ pub(crate) fn run(inputs: &dyn Inputs, params: &Json) -> Result Result { if unmeasured > 0 { msg.push_str(&format!("; {unmeasured} at the projection's edge or beyond it have none")); } - Ok(ToolResult { output: Output::Layer(out), messages: vec![msg] }) + Ok(ToolResult { losses: Vec::new(), output: Output::Layer(out), messages: vec![msg] }) } #[cfg(test)] diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 56d363941b..de0ee078d4 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1437,7 +1437,7 @@ fn vector_to_pmtiles(inp: &dyn Inputs, p: &Json) -> Result { let file_name = if output.is_empty() { format!("{default_name}.pmtiles") } else { output.to_string() }; let selected = inp.selection(s(p, "input")); let (bytes, messages) = inp.vector_to_pmtiles(ds, selected, min_zoom, max_zoom, source_layer)?; - Ok(ToolResult { output: Output::File { file_name, bytes }, messages }) + Ok(ToolResult { losses: Vec::new(), output: Output::File { file_name, bytes }, messages }) } fn raster_to_pmtiles(inp: &dyn Inputs, p: &Json) -> Result { @@ -1447,7 +1447,7 @@ fn raster_to_pmtiles(inp: &dyn Inputs, p: &Json) -> Result { let default_name = name.rsplit(['/', '\\']).find(|part| !part.is_empty()).unwrap_or("output"); let file_name = if output.is_empty() { format!("{default_name}.pmtiles") } else { output.to_string() }; let bytes = inp.raster_to_pmtiles(name, min_zoom, max_zoom)?; - Ok(ToolResult { output: Output::File { file_name, bytes }, messages: vec![] }) + Ok(ToolResult { losses: Vec::new(), output: Output::File { file_name, bytes }, messages: vec![] }) } /// The name of a tool's new layer, from its `output` parameter. @@ -1475,7 +1475,7 @@ fn to_metres(d: f64, units: &str) -> Result { } fn result(ds: Dataset, msg: String) -> Result { - Ok(ToolResult { output: Output::Layer(ds), messages: vec![msg] }) + Ok(ToolResult { losses: Vec::new(), output: Output::Layer(ds), messages: vec![msg] }) } /// A geometry's polygons, or none when it has no polygon to give: an empty polygon, or a point @@ -2647,7 +2647,7 @@ fn update_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result) -> Result Result { )); } messages.extend(rounded_notice(&rounded, out.fields.get(first_added..).unwrap_or_default())); - Ok(ToolResult { output: Output::Layer(out), messages }) + Ok(ToolResult { losses: Vec::new(), output: Output::Layer(out), messages }) } /// The farthest (meters, either way) Minimum Bounding Geometry takes a point from the analysis @@ -4065,7 +4069,7 @@ fn xy_table_to_point(inp: &dyn Inputs, p: &Json) -> Result { if placed < total { messages.push(format!("{} of {total} rows have no usable coordinates; they are in the table without a point", total - placed)); } - Ok(ToolResult { output: Output::Layer(out), messages }) + Ok(ToolResult { losses: Vec::new(), output: Output::Layer(out), messages }) } /// The distances a Douglas–Peucker run of `n` vertices may measure, `n` times this: far more than @@ -4484,7 +4488,7 @@ fn simplify_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result 0 { messages.push(format!("Simplify: {without} feature(s) left out: they have no geometry to simplify")); } - Ok(ToolResult { output: Output::Layer(out), messages }) + Ok(ToolResult { losses: Vec::new(), output: Output::Layer(out), messages }) } /// A Select by Location selector: its shape and extent in the analysis plane, and the poles it @@ -4632,7 +4636,7 @@ fn select_by_location_with_work_limit(inp: &dyn Inputs, p: &Json, limit: usize, "{coarse} selecting features' buffers have outline edges left with fewer points along them than they need (the points a ring may add ran out, as on a ring of thousands of long edges, or a very long edge was halved as many times as it may be): features near their edges there may be selected or not by more than a buffer otherwise keeps to (0.012% of the distance, 0.05% along a line or outline buffered in stretches, or 1 cm)" )); } - Ok(ToolResult { output: Output::Selection { layer: ds.name.clone(), rows: hits }, messages }) + Ok(ToolResult { losses: Vec::new(), output: Output::Selection { layer: ds.name.clone(), rows: hits }, messages }) } fn select_by_attributes(inp: &dyn Inputs, p: &Json) -> Result { @@ -4640,6 +4644,7 @@ fn select_by_attributes(inp: &dyn Inputs, p: &Json) -> Result Result { let bytes = rustgis_data::raster::geotiff::write(&r, 0).map_err(|e| e.to_string())?; let msg = format!("IDW Interpolation: {} × {} cells from {} points", r.width, r.height, pts.len()); Ok(ToolResult { + losses: Vec::new(), output: Output::Layers(vec![OutputLayer::Raster { file_name: format!("{name}.tif"), name, bytes }]), messages: std::iter::once(msg).chain(beyond_note).chain(crs_note).collect(), }) @@ -4838,6 +4844,7 @@ fn kriging_interpolation(inp: &dyn Inputs, p: &Json) -> Result Result format!("Kernel Density: {} × {} cells from {} points (bandwidth: {:.2})", r.width, r.height, pts.len(), bandwidth) }; Ok(ToolResult { + losses: Vec::new(), output: Output::Layers(vec![OutputLayer::Raster { file_name: format!("{name}.tif"), name, bytes }]), messages: std::iter::once(msg) .chain(beyond_note) @@ -5371,7 +5379,7 @@ fn count_points_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result } let mut messages = vec![format!("Summarize Within: {total} points counted")]; messages.extend(rounded_notice(&rounded, out.fields.get(first..).unwrap_or_default())); - Ok(ToolResult { output: Output::Layer(out), messages }) + Ok(ToolResult { losses: Vec::new(), output: Output::Layer(out), messages }) } /// A lon/lat line or ring as a `geo` line string, in degrees. @@ -5686,6 +5694,7 @@ fn calculate_geometry(inp: &dyn Inputs, p: &Json) -> Result } } Ok(ToolResult { + losses: Vec::new(), output: Output::Update { layer: ds.name.clone(), dataset: out }, messages: vec![format!("Calculated geometry attributes for {}", ds.name)], }) @@ -5752,7 +5761,7 @@ fn summary_statistics(inp: &dyn Inputs, p: &Json) -> Result let n = out.features.len(); let mut messages = vec![format!("Summary Statistics: {n} rows")]; messages.extend(rounded_notice(&rounded, out.fields.get(first_added..).unwrap_or_default())); - Ok(ToolResult { output: Output::Table(out), messages }) + Ok(ToolResult { losses: Vec::new(), output: Output::Table(out), messages }) } /// The output fields of a statistics list over `ds`: `_` for each request, typed by @@ -6091,7 +6100,7 @@ fn pivot_table(inp: &dyn Inputs, p: &Json) -> Result { let n = out.features.len(); let mut messages = vec![format!("Pivot Table: {n} rows, {} pivot fields", columns.len())]; messages.extend(rounded_notice(&rounded, out.fields.get(first_pivot_field..).unwrap_or_default())); - Ok(ToolResult { output: Output::Table(out), messages }) + Ok(ToolResult { losses: Vec::new(), output: Output::Table(out), messages }) } /// Whether a pivot value is missing: null, or a number that isn't one. @@ -6590,7 +6599,7 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result messages.push("1 class feature lies partly or wholly outside the zones: its value outside isn't shared out".into()), n => messages.push(format!("{n} class features lie partly or wholly outside the zones: their values outside aren't shared out")), } - Ok(ToolResult { output: Output::Table(out), messages }) + Ok(ToolResult { losses: Vec::new(), output: Output::Table(out), messages }) } fn export_features(inp: &dyn Inputs, p: &Json) -> Result { @@ -7555,7 +7564,7 @@ fn spatial_join_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result )); } messages.extend(rounded_notice(&rounded, &merged_fields)); - Ok(ToolResult { output: Output::Layer(out), messages }) + Ok(ToolResult { losses: Vec::new(), output: Output::Layer(out), messages }) } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -7845,7 +7854,7 @@ fn zonal_stats_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result< messages.push(format!("... and {} more feature failure(s)", failure_details.len() - 5)); } } - Ok(ToolResult { output: Output::Layer(out), messages }) + Ok(ToolResult { losses: Vec::new(), output: Output::Layer(out), messages }) } /// Returns a borrowed dataset when rows match the full dataset in identity order, or a new dataset containing @@ -8042,7 +8051,7 @@ fn join_field_tool(inp: &dyn Inputs, p: &Json) -> Result { let output = if out.geometry_type == rustgis_data::GeometryType::None { Output::Table(out) } else { Output::Layer(out) }; - Ok(ToolResult { output, messages }) + Ok(ToolResult { losses: Vec::new(), output, messages }) } /// Keeps polygon boundaries in stored coordinates, including interior rings. diff --git a/crates/analysis/src/tools/check_geometry.rs b/crates/analysis/src/tools/check_geometry.rs index 11f7998ead..cf109466fc 100644 --- a/crates/analysis/src/tools/check_geometry.rs +++ b/crates/analysis/src/tools/check_geometry.rs @@ -156,7 +156,7 @@ fn run_with_room( let mut messages = notices(&tally, &problem_field); messages.extend(notes); - Ok(ToolResult { output: Output::Layer(out), messages }) + Ok(ToolResult { losses: Vec::new(), output: Output::Layer(out), messages }) } /// The memory an output row copying `attrs` (`width` of them, of `out_width` values in the diff --git a/crates/analysis/src/tools/geometry.rs b/crates/analysis/src/tools/geometry.rs index 69b97df4a6..fc16c06274 100644 --- a/crates/analysis/src/tools/geometry.rs +++ b/crates/analysis/src/tools/geometry.rs @@ -212,7 +212,7 @@ fn finish(out: Dataset, skipped: usize, tool: &str) -> Result Result 0) + .then(|| rustgis_data::loss::LossMessage { + code: rustgis_data::loss::LossCode::DroppedExtraAttributes, + text: format!( + "{TOOL}: {} had more attribute values than the layer has fields; the extra values aren't in the output", + features(tally.extra) + ), + }) + .into_iter() + .collect(); + Ok(ToolResult { output: Output::Layer(out), messages, losses }) } /// The run's notices: the result in one line, then one notice per kind of feature not repaired, @@ -289,12 +299,6 @@ fn notices(t: &Tally, field: &str) -> Vec { rounded_up(t.moved) )); } - if t.extra > 0 { - messages.push(format!( - "{TOOL}: {} had more attribute values than the layer has fields; the extra values aren't in the output", - features(t.extra) - )); - } messages } diff --git a/crates/analysis/src/tools/tabulate_area.rs b/crates/analysis/src/tools/tabulate_area.rs index 86610811a7..05f7400fae 100644 --- a/crates/analysis/src/tools/tabulate_area.rs +++ b/crates/analysis/src/tools/tabulate_area.rs @@ -114,7 +114,7 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Resu if empty > 0 { messages.push(format!("{empty} zone(s) contained no valid raster cell centres; their class values are zero")); } - Ok(ToolResult { output: Output::Table(out), messages }) + Ok(ToolResult { losses: Vec::new(), output: Output::Table(out), messages }) } /// All finite valid band values, sorted numerically. The wide table has Pivot Table's column diff --git a/crates/analysis/tests/repair_geometry.rs b/crates/analysis/tests/repair_geometry.rs index 75045de0e4..4589d94411 100644 --- a/crates/analysis/tests/repair_geometry.rs +++ b/crates/analysis/tests/repair_geometry.rs @@ -753,8 +753,12 @@ fn attributes_crs_ids_and_names_are_kept() { assert_eq!(ds.features[1].attrs, [Value::Text("bad".into()), Value::Float(2.5), Value::Null, Value::Text("self_intersection".into())]); assert_eq!(ds.features[2].attrs, [Value::Text("none".into()), Value::Null, Value::Int(3), Value::Text("null_geometry".into())]); assert_eq!( - r.messages.last().map(String::as_str), - Some("Repair Geometry: 1 feature had more attribute values than the layer has fields; the extra values aren't in the output") + r.losses, + [rustgis_data::loss::LossMessage { + code: rustgis_data::loss::LossCode::DroppedExtraAttributes, + text: "Repair Geometry: 1 feature had more attribute values than the layer has fields; the extra values aren't in the output" + .into(), + }] ); assert_eq!(dataset(&named(Some(" Fixed parcels "))).name, "Fixed parcels"); } diff --git a/crates/analysis/tests/resolved_tools.rs b/crates/analysis/tests/resolved_tools.rs index 857ec913d4..e98c447a1b 100644 --- a/crates/analysis/tests/resolved_tools.rs +++ b/crates/analysis/tests/resolved_tools.rs @@ -45,7 +45,11 @@ fn provider() -> Vec { /// Reports which captured schema and defaults actually reached the runner. fn runner(spec: &ToolSpec, _: &dyn Inputs, params: &Value) -> Result { - Ok(ToolResult { output: Output::Layers(Vec::new()), messages: vec![format!("{}:{}", spec.summary, params["value"])] }) + Ok(ToolResult { + losses: Vec::new(), + output: Output::Layers(Vec::new()), + messages: vec![format!("{}:{}", spec.summary, params["value"])], + }) } #[test] diff --git a/crates/data/src/georss.rs b/crates/data/src/georss.rs index c09e1058d0..190fe07136 100644 --- a/crates/data/src/georss.rs +++ b/crates/data/src/georss.rs @@ -197,7 +197,7 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> } else { format!("{lost_holes} holes in polygons were unreadable and left out") }; - report.messages.push(what); + report.losses.push(crate::loss::LossMessage { code: crate::loss::LossCode::DroppedRing, text: what }); } // What the file as a whole said goes with its first layer only. let out: Vec<(Dataset, ReadReport)> = layers @@ -293,14 +293,14 @@ mod tests { assert_eq!(lossy[0].0.features.len(), 1); assert!(lossy[0].0.features[0].geometry.is_some()); assert!( - lossy[0].1.messages.iter().any(|m| m.contains("1 hole in a polygon was unreadable and left out")), + lossy[0].1.losses.iter().any(|m| m.code == crate::loss::LossCode::DroppedRing && m.text.contains("1 hole in a polygon was unreadable and left out")), "{:?}", lossy[0].1.messages ); let clean = read("clean.rss", feed("45.2 -110.2 45.8 -110.2 45.8 -110.8 45.2 -110.2").as_bytes()).unwrap(); assert_eq!(clean[0].0.features.len(), 1); - assert!(!clean[0].1.messages.iter().any(|m| m.contains("hole")), "{:?}", clean[0].1.messages); + assert!(clean[0].1.losses.is_empty()); let multi = r#" @@ -313,7 +313,7 @@ mod tests { "#; let lossy_multi = read("multi.rss", multi.as_bytes()).unwrap(); assert!( - lossy_multi[0].1.messages.iter().any(|m| m.contains("2 holes in polygons were unreadable and left out")), + lossy_multi[0].1.losses.iter().any(|m| m.text.contains("2 holes in polygons were unreadable and left out")), "{:?}", lossy_multi[0].1.messages ); @@ -329,7 +329,7 @@ mod tests { "#; let mixed_lossy = read("mixed.rss", mixed.as_bytes()).unwrap(); assert!( - mixed_lossy[0].1.messages.iter().any(|m| m.contains("1 hole in a polygon was unreadable and left out")), + mixed_lossy[0].1.losses.iter().any(|m| m.text.contains("1 hole in a polygon was unreadable and left out")), "{:?}", mixed_lossy[0].1.messages ); diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index ad20addeb4..2eea9e2b5e 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -519,6 +519,8 @@ impl Serialize for Dataset { pub struct ReadReport { pub skipped: usize, pub messages: Vec, + /// Classified losses to publish alongside the ordinary messages. + pub losses: Vec, /// The files read and the rows read from them, when the read recorded them /// ([`sync::FileSync::around`]): what a layer kept in the project compares with its source /// before writing edits back. @@ -534,6 +536,13 @@ pub struct ReadReport { pub extrusion: Option, } +impl ReadReport { + /// All report messages in their text form for consumers that do not carry loss codes. + pub fn into_messages(self) -> impl Iterator { + self.messages.into_iter().chain(self.losses.into_iter().map(|loss| loss.text)) + } +} + /// An extrusion a reader suggests for a layer of polygons: heights from one field, on a base from /// another. #[derive(Clone, Debug, PartialEq)] diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index 8b2d572122..1834882787 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -26,6 +26,8 @@ impl LossKind { #[non_exhaustive] pub enum LossCode { DroppedLegend, + DroppedRing, + DroppedExtraAttributes, DroppedTime, DroppedValue, DroppedCalculationResult, @@ -44,6 +46,10 @@ impl LossCode { pub const fn spec(self) -> LossSpec { use LossKind::{Changed, Dropped}; let (id, kind, action) = match self { + Self::DroppedRing => ("dropped.ring", Dropped, "Correct the unreadable polygon ring in the source."), + Self::DroppedExtraAttributes => { + ("dropped.extra-attributes", Dropped, "Add fields for the extra attribute values or remove those values from the input.") + } Self::DroppedLegend => ("dropped.legend", Dropped, "Use a service with short HTTP or HTTPS addresses for its legend pictures."), Self::DroppedTime => ("dropped.time", Dropped, "Write to a date-time field to keep the time of day."), Self::DroppedValue => ("dropped.value", Dropped, "Correct the value or use a destination field that can hold it."), @@ -55,3 +61,10 @@ impl LossCode { LossSpec { id, kind, action } } } + +/// A message produced at the point a reader or tool detects a loss. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LossMessage { + pub code: LossCode, + pub text: String, +} diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index c5fe5369fd..13a48d354f 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -667,6 +667,7 @@ fn materialize_within(src: &dyn FeatureSource, budget: u64) -> Result<(Dataset, unread_dates: unread_dates.clone(), rounded_dates: rounded.clone(), extrusion: None, + losses: Vec::new(), }; let null_text = null_text_note(&info.fields, &null_text); report.messages.extend(unread_dates.into_iter().chain(rounded).chain(null_text).chain(notes).map(|n| format!("{}: {n}", info.name))); diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 0615fc402d..d30541fad1 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -2,6 +2,7 @@ use rustgis_analysis::{Inputs, Output, OutputLayer, RasterInput}; use rustgis_data::Dataset; +use rustgis_data::loss::{LossCode, LossMessage}; use serde_json::{Value, json}; use super::{need_layers, ps}; @@ -710,6 +711,7 @@ impl ToolRun { let mut result = pin.run(&inputs, ¶ms, control, &|| continuation.check()); if let Ok(r) = &mut result { r.messages.extend(inputs.messages.iter().cloned()); + r.losses.extend(inputs.losses.iter().cloned()); } ToolDone { inputs: Vec::new(), result, full_ids: full_ids(&inputs.loaded) } }) @@ -1215,6 +1217,7 @@ struct MapInputs<'a> { loaded: std::collections::HashMap, /// Import warnings from local file inputs, kept in the tool result and history. messages: Vec, + losses: Vec, /// The flat map's projection (its name, the projection and its unit in metres), built the /// first time a tool asks for it (Tissot's indicatrix does), once for the run; `None` on the /// globe. @@ -1252,8 +1255,9 @@ fn map_inputs<'a>(s: &'a Session, spec: Option<&rustgis_analysis::ToolSpec>, par /// thread. fn inputs_of<'a>(snap: Snapshot<'a>, spec: Option<&rustgis_analysis::ToolSpec>, params: &Value) -> Result, String> { let (full, mut messages) = streamed_inputs(&snap.map, spec, params)?; + let losses = Vec::new(); #[cfg(not(target_arch = "wasm32"))] - let mut full = full; + let (mut full, mut losses) = (full, losses); #[cfg(not(target_arch = "wasm32"))] if let Some(spec) = spec.filter(|t| rustgis_analysis::TOOLS.iter().any(|builtin| std::ptr::eq(builtin, *t))) { for parameter in spec.params.iter().filter(|p| p.kind == rustgis_analysis::ParamKind::VectorLayers) { @@ -1261,6 +1265,9 @@ fn inputs_of<'a>(snap: Snapshot<'a>, spec: Option<&rustgis_analysis::ToolSpec>, if vector_file_input(spec, &snap.map, name) && !full.contains_key(name) { let (dataset, report) = rustgis_data::io::read_path(std::path::Path::new(name)).map_err(|e| format!("{name}: {e}"))?; messages.extend(report.messages.into_iter().map(|message| format!("{name}: {message}"))); + losses.extend( + report.losses.into_iter().map(|loss| LossMessage { code: loss.code, text: format!("{name}: {}", loss.text) }), + ); full.insert(name.to_string(), dataset); } } @@ -1268,7 +1275,7 @@ fn inputs_of<'a>(snap: Snapshot<'a>, spec: Option<&rustgis_analysis::ToolSpec>, } let mut rows = env_inputs(&snap.map, &full, &snap.env, params)?; narrow_to_queries(&snap.map, spec, params, &full, &mut rows, &mut messages)?; - Ok(MapInputs { snap, rows, loaded: full, messages, flat: std::cell::OnceCell::new(), view: std::cell::OnceCell::new() }) + Ok(MapInputs { snap, rows, loaded: full, messages, losses, flat: std::cell::OnceCell::new(), view: std::cell::OnceCell::new() }) } /// Narrows the rows a tool reads of each layer to the features its definition query keeps, as the @@ -1885,9 +1892,9 @@ pub fn run_batch_with(s: &mut Session, p: &Value, control: &std::sync::Arc = Vec::new(); + let mut reader_warnings: Vec<(String, String, Option)> = Vec::new(); let mut items_reporting_messages = 0; - let mut distinct_tool_messages: Vec<(String, usize)> = Vec::new(); + let mut distinct_tool_messages: Vec<(String, Option, usize)> = Vec::new(); let mut cancelled_after = None; let mut next_suffix: std::collections::HashMap = std::collections::HashMap::new(); #[cfg(not(target_arch = "wasm32"))] @@ -1921,9 +1928,11 @@ pub fn run_batch_with(s: &mut Session, p: &Value, control: &std::sync::Arc { - for msg in report.messages { + let messages = report.messages.into_iter().map(|text| (text, None)); + let losses = report.losses.into_iter().map(|loss| (loss.text, Some(loss.code))); + for (msg, code) in messages.chain(losses) { item_reader_warnings.push(format!("{target}: {msg}")); - reader_warnings.push((target.clone(), msg)); + reader_warnings.push((target.clone(), msg, code)); } Some(super::layer::add_dataset(s, dataset)) } @@ -2058,12 +2067,12 @@ pub fn run_batch_with(s: &mut Session, p: &Value, control: &std::sync::Arc { succeeded.push(target.clone()); if !messages.is_empty() { - items_reporting_messages += 1; - for msg in &messages { - if let Some(entry) = distinct_tool_messages.iter_mut().find(|(m, _)| m == msg) { - entry.1 += 1; + items_reporting_messages += usize::from(messages.iter().any(|(_, code)| code.is_none())); + for (text, code) in &messages { + if let Some(entry) = distinct_tool_messages.iter_mut().find(|(m, c, _)| m == text && c == code) { + entry.2 += 1; } else { - distinct_tool_messages.push((msg.clone(), 1)); + distinct_tool_messages.push((text.clone(), *code, 1)); } } } @@ -2169,7 +2178,7 @@ pub fn run_batch_with(s: &mut Session, p: &Value, control: &std::sync::Arc 1 { - err_obj["messages"] = json!(messages); + err_obj["messages"] = json!(messages.iter().map(|(text, _)| text).collect::>()); } errors.push(err_obj); #[cfg(not(target_arch = "wasm32"))] @@ -2291,18 +2300,20 @@ pub fn run_batch_with(s: &mut Session, p: &Value, control: &std::sync::Arc 0 { + s.warn(format!("gp.batch: {unlisted} more loss messages are listed in the result")); + } if items_reporting_messages > 0 { - let sample = distinct_tool_messages - .iter() - .take(NAMED) - .map(|(m, c)| if *c > 1 { format!("{m} (×{c})") } else { m.clone() }) - .collect::>() - .join("; "); - let more = if distinct_tool_messages.len() > NAMED { - format!(" and {} more, in the result", distinct_tool_messages.len() - NAMED) - } else { - String::new() - }; + let plain = || distinct_tool_messages.iter().filter(|(_, code, _)| code.is_none()); + let sample = plain().take(NAMED).map(|(text, _, count)| batch_message(text, *count)).collect::>().join("; "); + let total = plain().count(); + let more = if total > NAMED { format!(" and {} more, in the result", total - NAMED) } else { String::new() }; s.notify(format!("gp.batch: {items_reporting_messages} item(s) reported messages ({sample}{more})"), false); } @@ -2323,21 +2334,26 @@ pub fn run_batch_with(s: &mut Session, p: &Value, control: &std::sync::Arc)> = Vec::new(); - for (target, msg) in &reader_warnings { - if let Some((_, inputs)) = aggregated.iter_mut().find(|(m, _)| *m == msg.as_str()) { + let mut aggregated: Vec<(&str, Option, Vec<&str>)> = Vec::new(); + for (target, msg, code) in &reader_warnings { + if let Some((_, _, inputs)) = aggregated.iter_mut().find(|(m, c, _)| *m == msg.as_str() && c == code) { if !inputs.contains(&target.as_str()) { inputs.push(target.as_str()); } } else { - aggregated.push((msg.as_str(), vec![target.as_str()])); + aggregated.push((msg.as_str(), *code, vec![target.as_str()])); } } - for (msg, inputs) in aggregated { + for (msg, code, inputs) in aggregated { let count = inputs.len(); let inputs_list = inputs.join(", "); let label = if count == 1 { "input" } else { "inputs" }; - s.notify(format!("gp.batch: {count} {label} ({inputs_list}): {msg}"), false); + let text = format!("gp.batch: {count} {label} ({inputs_list}): {msg}"); + if let Some(code) = code { + s.notify_loss(code, text.into()); + } else { + s.notify(text, false); + } } } @@ -2365,7 +2381,7 @@ pub fn run_batch_with(s: &mut Session, p: &Value, control: &std::sync::Arc 0 || is_cancelled); - let warnings: Vec = reader_warnings.iter().map(|(input, msg)| json!({"input": input, "warning": msg})).collect(); + let warnings: Vec = reader_warnings.iter().map(|(input, msg, _)| json!({"input": input, "warning": msg})).collect(); let mut ret = json!({ "tool": tool_id, @@ -2376,7 +2392,7 @@ pub fn run_batch_with(s: &mut Session, p: &Value, control: &std::sync::Arc>(), + "messages": distinct_tool_messages.iter().map(|(m, _, c)| json!({"message": m, "items": c})).collect::>(), }); if is_cancelled { ret["cancelled"] = json!(true); @@ -2500,7 +2516,7 @@ pub(crate) fn execute( op: crate::policy::Authorized, control: &std::sync::Arc, opts: &RunOpts, -) -> Result<(Value, Vec), String> { +) -> Result<(Value, ToolMessages), String> { let crate::policy::ToolOp { pin, params } = op.op(); pin.current()?; let spec = pin.spec(); @@ -2548,6 +2564,7 @@ pub(crate) fn execute( }; if let Ok(result) = &mut res { result.messages.extend(inputs.messages.iter().cloned()); + result.losses.extend(inputs.losses.iter().cloned()); } let ids = full_ids(&inputs.loaded); #[cfg(not(target_arch = "wasm32"))] @@ -2580,6 +2597,14 @@ pub(crate) fn execute( apply_with(s, run_of(t0), kept(), res, millis, opts) } +/// The text of a distinct batch notice, with its repetition count when it appeared more than once. +fn batch_message(text: &str, count: usize) -> String { + if count > 1 { format!("{text} (×{count})") } else { text.to_string() } +} + +/// Text and optional loss code from a tool that has run. +pub(crate) type ToolMessages = Vec<(String, Option)>; + /// How [`execute`] applies a run: by default as `gp.run` does. A batch item keeps the /// parameters and command it is replayed with, leaves its messages to the batch's one notice /// per kind, and adds a table beside one of the same name instead of replacing it. @@ -2600,7 +2625,7 @@ pub(crate) fn run_tool_quiet( record_params: Option<&Value>, command: Option<(String, Value)>, control: &std::sync::Arc, -) -> Result<(Value, Vec), String> { +) -> Result<(Value, ToolMessages), String> { let op = s.authorize_tool(tool, params)?; let opts = RunOpts { record: record_params.cloned(), command, quiet: true, keep_tables: true }; s.invoke_tool_with(op, control, &opts) @@ -2623,10 +2648,11 @@ pub(crate) struct PendingFile { pub(crate) file_name: String, pub(crate) bytes: Option>, record: GpRecord, + losses: Vec, } #[cfg(any(target_arch = "wasm32", test))] -fn queue_file(s: &mut Session, file_name: String, bytes: Vec, record: GpRecord) -> CmdResult { +fn queue_file(s: &mut Session, file_name: String, bytes: Vec, record: GpRecord, losses: Vec) -> CmdResult { let file_name = record.params.get("output").and_then(Value::as_str).map(str::trim).filter(|p| !p.is_empty()).unwrap_or(&file_name).to_string(); if file_name.is_empty() || file_name.contains(['/', '\\']) { @@ -2639,7 +2665,14 @@ fn queue_file(s: &mut Session, file_name: String, bytes: Vec, record: GpReco } s.next_pending = s.next_pending.wrapping_add(1); let id = s.next_pending; - s.file_outputs.push(PendingFile { id, file_name: file_name.clone(), bytes: Some(bytes), record, continuation: s.continuation()? }); + s.file_outputs.push(PendingFile { + id, + file_name: file_name.clone(), + bytes: Some(bytes), + record, + losses, + continuation: s.continuation()?, + }); s.request_only = true; Ok(json!({"pending": true, "download": id, "file": file_name})) } @@ -2668,6 +2701,14 @@ fn file_delivered(s: &mut Session, p: &Value) -> CmdResult { s.notify(message.clone(), true); } } + for loss in file.losses { + if file.record.ok { + publish_tool_loss(s, loss.code, &loss.text, true); + } else { + s.notify(loss.text.clone(), true); + } + file.record.messages.push(loss.text); + } let out = json!({"file": file.file_name, "delivered": file.record.ok, "messages": file.record.messages}); s.push_gp_record(file.record); if s.project.gp_history.len() > 500 { @@ -2791,7 +2832,7 @@ fn apply_with( res: Result, millis: u64, opts: &RunOpts, -) -> Result<(Value, Vec), String> { +) -> Result<(Value, ToolMessages), String> { let continuation = s.continuation()?; s.check_continuation(&continuation)?; let Ran { name, id, command, started } = ran; @@ -2820,12 +2861,13 @@ fn apply_with( Output::File { file_name, bytes } => { #[cfg(test)] if s.queue_gp_files { - let msgs = result.messages.clone(); + let msgs = result.messages.iter().cloned().map(|m| (m, None)).collect(); return queue_file( s, file_name, bytes, GpRecord { tool: name, id, params, command, at, ok: false, messages: result.messages, millis, outputs: Vec::new() }, + result.losses, ) .map(|v| (v, msgs)); } @@ -2834,6 +2876,7 @@ fn apply_with( let path = params.get("output").and_then(Value::as_str).map(str::trim).filter(|p| !p.is_empty()).unwrap_or(&file_name); if let Err(error) = write_file_output(s, std::path::Path::new(path), &bytes) { let error = format!("{path}: {error}"); + result.messages.extend(result.losses.into_iter().map(|loss| loss.text)); result.messages.push(error.clone()); s.push_gp_record(GpRecord { tool: name, @@ -2852,12 +2895,13 @@ fn apply_with( } #[cfg(target_arch = "wasm32")] { - let msgs = result.messages.clone(); + let msgs = result.messages.iter().cloned().map(|m| (m, None)).collect(); return queue_file( s, file_name, bytes, GpRecord { tool: name, id, params, command, at, ok: false, messages: result.messages, millis, outputs: Vec::new() }, + result.losses, ) .map(|v| (v, msgs)); } @@ -2925,16 +2969,25 @@ fn apply_with( ret } }; - let messages = result.messages.clone(); + let messages: ToolMessages = result + .messages + .iter() + .cloned() + .map(|m| (m, None)) + .chain(result.losses.iter().map(|loss| (loss.text.clone(), Some(loss.code)))) + .collect(); if !opts.quiet { - for m in &messages { - if wrote_file { - s.notify_written(m.clone(), false); + for (message, code) in &messages { + if let Some(code) = code { + publish_tool_loss(s, *code, message, wrote_file); + } else if wrote_file { + s.notify_written(message.clone(), false); } else { - s.notify(m.clone(), false); + s.notify(message.clone(), false); } } } + result.messages.extend(result.losses.into_iter().map(|loss| loss.text)); let ids: Vec = match (out.get("layer"), out.get("layers")) { (Some(id), _) => id.as_u64().into_iter().filter_map(|v| u32::try_from(v).ok()).collect(), (None, Some(Value::Array(v))) => v.iter().filter_map(Value::as_u64).filter_map(|v| u32::try_from(v).ok()).collect(), @@ -2948,6 +3001,15 @@ fn apply_with( Ok((out, messages)) } +/// Publishes a typed loss, retaining it through rollback when a file has already been delivered. +fn publish_tool_loss(s: &mut Session, code: LossCode, text: &str, written: bool) { + let mark = s.notice_mark(); + s.notify_loss(code, text.to_string().into()); + if written { + s.retain_written_notices(mark); + } +} + #[cfg(test)] mod file_tests { use super::*; @@ -3004,7 +3066,7 @@ mod file_tests { s.registry.commands.push(C::new("test.queueFile", "File export", "Test", |s, p| { let record = serde_json::from_value(p["record"].clone()).unwrap(); let bytes = serde_json::from_value(p["bytes"].clone()).unwrap(); - super::queue_file(s, p["name"].as_str().unwrap().into(), bytes, record) + super::queue_file(s, p["name"].as_str().unwrap().into(), bytes, record, Vec::new()) })); } s.run("test.queueFile", &json!({"name":name,"bytes":bytes,"record":record})) @@ -3778,6 +3840,7 @@ mod file_tests { Ran { name: "File export".into(), id: "vectorToPmtiles".into(), command: None, started: 1000 }, p.clone(), Ok(rustgis_analysis::ToolResult { + losses: Vec::new(), output: Output::File { file_name: "cities.pmtiles".into(), bytes: b"archive".to_vec() }, messages: vec!["Exported data".into()], }), @@ -4499,6 +4562,7 @@ mod batch_tests { vec![rustgis_data::Field::new("col", rustgis_data::FieldType::Integer)], ); Ok(rustgis_analysis::ToolResult { + losses: Vec::new(), output: rustgis_analysis::Output::Layers(vec![rustgis_analysis::OutputLayer::Table(table)]), messages: Vec::new(), }) @@ -4854,6 +4918,7 @@ mod batch_tests { _params: &serde_json::Value, ) -> Result { Ok(rustgis_analysis::ToolResult { + losses: Vec::new(), output: rustgis_analysis::Output::Layers(Vec::new()), messages: vec!["custom message from empty tool".to_string()], }) @@ -4907,6 +4972,7 @@ mod batch_tests { _params: &serde_json::Value, ) -> Result { Ok(rustgis_analysis::ToolResult { + losses: Vec::new(), output: rustgis_analysis::Output::Layers(Vec::new()), messages: vec!["Processed 10 features".to_string(), "0 features matched criteria".to_string()], }) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index a2e4a2fe0a..f7aa01f2f4 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2645,6 +2645,7 @@ fn add_picked( for (source, said) in file_wide { if let Some(kept) = reads.iter_mut().find(|r| r.dataset.source == source) { kept.report.messages.extend(said.messages); + kept.report.losses.extend(said.losses); kept.report.skipped += said.skipped; } } @@ -6088,6 +6089,9 @@ pub(crate) fn add_read( for m in report.messages { s.notify(m, false); } + for loss in report.losses { + s.notify_loss(loss.code, loss.text.into()); + } if ds.geometry_type == GeometryType::None { let name = ds.name.clone(); let id = s.project.add_table(ds); diff --git a/crates/engine/src/cmd/stac_area.rs b/crates/engine/src/cmd/stac_area.rs index e0d44bdc2f..88e5fba654 100644 --- a/crates/engine/src/cmd/stac_area.rs +++ b/crates/engine/src/cmd/stac_area.rs @@ -44,7 +44,7 @@ fn read_geometries(path: &str) -> Result<(Vec, Vec), String> { if ds.features.len() > area::MAX_FEATURES { return Err(format!("{path} has more than {} features: simplify it or use a bounding box", area::MAX_FEATURES)); } - let mut messages: Vec = report.messages.into_iter().map(|m| format!("{path}: {m}")).collect(); + let mut messages: Vec = report.into_messages().map(|m| format!("{path}: {m}")).collect(); let geometries: Vec = ds.features.iter().filter_map(|f| f.geometry.clone()).collect(); if geometries.len() < ds.features.len() { messages.push(format!( diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index a4b0b58ed2..d8223c584c 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -845,7 +845,7 @@ impl Session { op: Authorized, control: &Arc, opts: &crate::cmd::gp::RunOpts, - ) -> Result<(Value, Vec), String> { + ) -> Result<(Value, crate::cmd::gp::ToolMessages), String> { let node = op.node.clone(); let number = node.number; let result = self.with_node(node, |s| crate::cmd::gp::execute(s, op, control, opts)); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ed3faf2419..6bd3c16fa6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -17160,7 +17160,11 @@ fn plugin_tools_run_off_the_session() { // ...and an update, which would discard them, is refused. let update = |s: &Session| { let dataset = s.map().layer_by_name("Cities").unwrap().dataset.clone(); - Ok(rustgis_analysis::ToolResult { output: rustgis_analysis::Output::Update { layer: "Cities".into(), dataset }, messages: vec![] }) + Ok(rustgis_analysis::ToolResult { + losses: Vec::new(), + output: rustgis_analysis::Output::Update { layer: "Cities".into(), dataset }, + messages: vec![], + }) }; let run = plugin_start(&mut s, "plugin:eng-bg/x", &json!({"input": "Cities"})).unwrap(); let r = update(&s); @@ -21587,6 +21591,36 @@ fn wms_layers_draw_as_one_picture_or_tiles_of_a_size() { assert!(t.url.contains("&size=512,512&") && t.tile_size == 512 && !t.single_image, "{}", t.url); } +/// A tool's classified loss reaches the session in ordinary and batch runs. Its history +/// still holds the notice as text, and a feature with matching attributes needs no warning. +#[test] +fn tool_result_reports_classified_attribute_loss() { + use rustgis_data::{Dataset, Feature, Geometry, GeometryType, Value as FieldValue, diagnostics::Severity, loss::LossCode}; + for batch in [false, true] { + for extra in [false, true] { + let mut s = Session::new(Project::default()); + let mut ds = Dataset::new("Sites", GeometryType::Point, Vec::new()); + ds.features = vec![Feature { + id: 1, + geometry: Some(Geometry::Point(rustgis_geom::Coord::new(1.0, 2.0))), + attrs: if extra { vec![FieldValue::Int(7)] } else { Vec::new() }, + }] + .into(); + s.map_mut().add_dataset(ds); + let mark = s.notice_mark(); + if batch { + s.run("gp.batch", &json!({"tool": "repairGeometry", "inputs": ["Sites"], "params": {}})).unwrap(); + } else { + s.run("gp.run", &json!({"tool": "repairGeometry", "params": {"input": "Sites"}})).unwrap(); + } + let notices: Vec<_> = s.notices_since(mark).iter().filter(|n| n.loss() == Some(LossCode::DroppedExtraAttributes)).collect(); + assert_eq!(notices.len(), usize::from(extra), "batch {batch}"); + assert!(notices.iter().all(|n| n.severity == Severity::Warning && n.text.contains("extra values"))); + assert_eq!(s.project.gp_history.iter().any(|r| r.messages.iter().any(|m| m.contains("extra values"))), extra); + } + } +} + /// #1592: a legend picture the layer cannot keep (an address too long, as a same-origin link can /// become once its spaces are encoded for the login) is counted in a notice, not dropped silently. #[test] @@ -21604,7 +21638,9 @@ fn service_legends_left_out_are_reported() { .unwrap(); let notices = s.notices_since(mark); let reported = notices.iter().any(|n| { - n.loss() == Some(rustgis_data::loss::LossCode::DroppedLegend) && n.severity == rustgis_data::diagnostics::Severity::Warning + n.loss() == Some(rustgis_data::loss::LossCode::DroppedLegend) + && n.severity == rustgis_data::diagnostics::Severity::Warning + && n.text.contains("1 legend picture(s) the service listed were left out") }); assert_eq!(reported, left_out, "{notices:?}"); assert_eq!(s.map().tiles.first().map(|t| t.legends.len()), Some(usize::from(!left_out))); diff --git a/crates/engine/tests/never_silent_reading.rs b/crates/engine/tests/never_silent_reading.rs index 5fe2badde0..5dc0005e75 100644 --- a/crates/engine/tests/never_silent_reading.rs +++ b/crates/engine/tests/never_silent_reading.rs @@ -14,6 +14,7 @@ //! The table includes text, CityJSON, CityGML, KMZ, GeoPackage, FlatGeobuf, GeoParquet, FileGDB, //! Shapefile, XLSX, ODS and OSM PBF. More formats and loss kinds remain to add (ROADMAP.md); one loss //! does not certify a reader. +use rustgis_engine::data::loss::LossCode; use rustgis_engine::{Project, Session}; use serde_json::json; @@ -24,6 +25,8 @@ enum Expect { Said(&'static str), /// Imports the layer and says the loss in a notice; refusing this valid fixture is a failure. Imported(&'static str), + /// Imports successfully and identifies the loss with a code. + Classified(LossCode), /// Loses it without a notice today, still adding a layer: what is lost. Silent(&'static str), } @@ -307,7 +310,7 @@ fn cases(fixture_dir: &std::path::Path) -> Vec { "a.rss", georss(&[&georss_polygon("1 1 1 2 2 2 1 1")]), georss(&[&georss_polygon("1 x")]), - Said("hole in a polygon was unreadable"), + Expect::Classified(LossCode::DroppedRing), ), case( "GeoRSS: a point with more than one pair", @@ -595,7 +598,8 @@ fn check_workbook(ds: &rustgis_engine::data::Dataset) -> std::io::Result<()> { /// What `layer.addData` did with a file: the notices it gave and whether it added a layer or table, /// or why it refused the file. -type Reading = Result<(Vec, bool), String>; +type SaidNotices = Vec<(String, Option)>; +type Reading = Result<(SaidNotices, bool), String>; /// Writes `file` with `content`, and `beside`, into `dir` (emptied first) and reads it. `Err` when /// the fixture can't be prepared: a failure of the test, never taken for a refusal. Each file of a @@ -682,7 +686,7 @@ fn read(dir: &std::path::Path, file: &str, content: &[u8], beside: &[(&str, Vec< return Err(std::io::Error::other("clean spreadsheet fixture gave a notice")); } } - let said = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + let said = s.notices_since(mark).iter().map(|n| (n.text.clone(), n.loss())).collect(); Ok(Ok((said, held(&s) > before))) } @@ -709,7 +713,7 @@ fn a_reading_that_loses_something_says_so() { Ok(Ok((said, true))) => said, }; // What the lossy file says that the clean one doesn't, and whether it added a layer. - let (new, added): (Vec, bool) = match read(&dir, c.file, &c.lossy, &c.beside[1]) { + let (new, added): (SaidNotices, bool) = match read(&dir, c.file, &c.lossy, &c.beside[1]) { Err(e) => { failures.push(format!("{name}: the lossy file couldn't be written: {e}")); continue; @@ -719,18 +723,27 @@ fn a_reading_that_loses_something_says_so() { failures.push(format!("{name}: reading crashed: {e}")); continue; } - Ok(Err(e)) => (vec![e], false), + Ok(Err(e)) => (vec![(e, None)], false), Ok(Ok((said, added))) => (said.into_iter().filter(|n| !clean.contains(n)).collect(), added), }; + if let Expect::Classified(code) = c.expect { + if !added + || new.iter().filter(|(_, loss)| *loss == Some(code)).count() != 1 + || clean.iter().any(|(_, loss)| *loss == Some(code)) + { + failures.push(format!("{name}: expected one {code:?} only for the lossy import; clean: {clean:?}, new: {new:?}")); + } + continue; + } match c.expect { // Both ways (AGENTS.md, Never silent): the clean file doesn't say the loss. - Said(words) | Imported(words) if clean.iter().any(|n| n.contains(words)) => { + Said(words) | Imported(words) if clean.iter().any(|(text, _)| text.contains(words)) => { failures.push(format!("{name}: the clean file says the loss it doesn't have ({words:?}): {clean:?}")) } Imported(_) if !added => { failures.push(format!("{name}: the valid lossy fixture was refused instead of imported: {new:?}")) } - Said(words) | Imported(words) if !new.iter().any(|n| n.contains(words)) => { + Said(words) | Imported(words) if !new.iter().any(|(text, _)| text.contains(words)) => { failures.push(format!("{name}: not said: nothing new holds {words:?}; new: {new:?}; the clean file said {clean:?}")) } Silent(lost) if !new.is_empty() => failures.push(format!( diff --git a/crates/geolibre/src/lib.rs b/crates/geolibre/src/lib.rs index 1ae0461189..5b4934e657 100644 --- a/crates/geolibre/src/lib.rs +++ b/crates/geolibre/src/lib.rs @@ -874,7 +874,7 @@ pub fn finish(job: &Job, files: &[(String, Vec)], lines: &[String], dir: Opt if layers.is_empty() && messages.is_empty() { messages.push(format!("{} finished without output", job.name)); } - ToolResult { output: Output::Layers(layers), messages } + ToolResult { losses: Vec::new(), output: Output::Layers(layers), messages } } /// Runs a tool to completion: natively through the `geolibre` program; in the browser the diff --git a/crates/plugins/src/tools.rs b/crates/plugins/src/tools.rs index 6b20f08f3f..04e13667da 100644 --- a/crates/plugins/src/tools.rs +++ b/crates/plugins/src/tools.rs @@ -419,7 +419,7 @@ fn output(reply: &Value, tool: &str) -> Result { .and_then(Value::as_array) .map(|a| a.iter().filter_map(Value::as_u64).filter_map(|r| usize::try_from(r).ok()).collect()) .unwrap_or_default(); - return Ok(ToolResult { output: Output::Selection { layer, rows }, messages }); + return Ok(ToolResult { losses: Vec::new(), output: Output::Selection { layer, rows }, messages }); } let mut outs = Vec::new(); for v in reply.get("layers").and_then(Value::as_array).into_iter().flatten().take(64) { @@ -428,5 +428,5 @@ fn output(reply: &Value, tool: &str) -> Result { for v in reply.get("tables").and_then(Value::as_array).into_iter().flatten().take(64) { outs.push(OutputLayer::Table(dataset(v, tool)?)); } - Ok(ToolResult { output: Output::Layers(outs), messages }) + Ok(ToolResult { losses: Vec::new(), output: Output::Layers(outs), messages }) } From 3081dc347209ec3a94daf33e2bb957c9593c3821 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 19 Nov 2026 15:05:16 -0600 Subject: [PATCH 2/3] test(assistant): initialize tool loss fixture --- crates/assistant/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index f397b553ad..2ab053593b 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -384,7 +384,7 @@ fn undeclared_external_tools_refuse_by_id_and_display_name() { } /// A deterministic tool result makes unauthorized execution observable without I/O. fn run(_: &ToolSpec, _: &dyn Inputs, _: &Value) -> Result { - Ok(ToolResult { output: Output::Selection { layer: "Cities".into(), rows: vec![0, 2] }, messages: vec![] }) + Ok(ToolResult { output: Output::Selection { layer: "Cities".into(), rows: vec![0, 2] }, messages: vec![], losses: vec![] }) } analysis::register_external("assistant-containment", specs, run); // Explicit native discovery publishes metadata; untrusted callers cannot discover it. From fad00b66c839727b08f587cf51f709cf3a4b1e72 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 19 Nov 2026 15:48:22 -0600 Subject: [PATCH 3/3] fix(engine): aggregate batch warnings by loss code --- crates/analysis/src/lib.rs | 4 ++- crates/engine/src/cmd/gp.rs | 49 ++++++++++++++++++++++++++++++------- crates/engine/src/tests.rs | 18 +++++++++++++- 3 files changed, 60 insertions(+), 11 deletions(-) diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index 367e2ba177..b8652f6adf 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -164,8 +164,10 @@ pub struct RasterInput<'a> { #[derive(Clone, Debug)] pub struct ToolResult { pub output: Output, + /// Ordinary messages. Classified losses appear in `losses` only. pub messages: Vec, - /// Losses identified by the producer. Text-only consumers also display their text. + /// Losses identified by the producer. Consumers that display plain text read both + /// `messages` and the text of these losses. pub losses: Vec, } diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index d30541fad1..249c5a8fcf 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -2300,14 +2300,11 @@ pub fn run_batch_with(s: &mut Session, p: &Value, control: &std::sync::Arc 0 { - s.warn(format!("gp.batch: {unlisted} more loss messages are listed in the result")); + let mut losses = BatchLosses::default(); + for (text, code, count) in &distinct_tool_messages { + if let Some(code) = code { + losses.add(*code, text, *count); + } } if items_reporting_messages > 0 { let plain = || distinct_tool_messages.iter().filter(|(_, code, _)| code.is_none()); @@ -2350,12 +2347,13 @@ pub fn run_batch_with(s: &mut Session, p: &Value, control: &std::sync::Arc>().join(", "); @@ -2597,6 +2595,39 @@ pub(crate) fn execute( apply_with(s, run_of(t0), kept(), res, millis, opts) } +/// Counts classified reports across a batch and keeps a bounded sample for each code. +#[derive(Default)] +struct BatchLosses(std::collections::BTreeMap<&'static str, BatchLoss>); + +struct BatchLoss { + code: LossCode, + reports: usize, + examples: Vec, + omitted: usize, +} + +impl BatchLosses { + /// Counts every report, even when its text is beyond the sample. + fn add(&mut self, code: LossCode, text: &str, count: usize) { + let entry = self.0.entry(code.spec().id).or_insert_with(|| BatchLoss { code, reports: 0, examples: Vec::new(), omitted: 0 }); + entry.reports = entry.reports.saturating_add(count); + if entry.examples.len() < 3 { + entry.examples.push(batch_message(text, count)); + } else { + entry.omitted += 1; + } + } + + /// Publishes one warning per code. Full messages are in the batch result. + fn say(self, s: &mut Session) { + for loss in self.0.into_values() { + let sample = loss.examples.join("; "); + let more = if loss.omitted == 0 { String::new() } else { format!(" and {} more, in the result", loss.omitted) }; + s.notify_loss(loss.code, format!("gp.batch: {} loss report(s) ({sample}{more})", loss.reports).into()); + } + } +} + /// The text of a distinct batch notice, with its repetition count when it appeared more than once. fn batch_message(text: &str, count: usize) -> String { if count > 1 { format!("{text} (×{count})") } else { text.to_string() } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6bd3c16fa6..3b6425f681 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -21606,15 +21606,31 @@ fn tool_result_reports_classified_attribute_loss() { attrs: if extra { vec![FieldValue::Int(7)] } else { Vec::new() }, }] .into(); + if batch { + let mut second = ds.clone(); + second.name = "More sites".into(); + second.features.push(Feature { + id: 2, + geometry: Some(Geometry::Point(rustgis_geom::Coord::new(2.0, 3.0))), + attrs: if extra { vec![FieldValue::Int(8)] } else { Vec::new() }, + }); + s.map_mut().add_dataset(second); + } s.map_mut().add_dataset(ds); let mark = s.notice_mark(); if batch { - s.run("gp.batch", &json!({"tool": "repairGeometry", "inputs": ["Sites"], "params": {}})).unwrap(); + let result = + s.run("gp.batch", &json!({"tool": "repairGeometry", "inputs": ["Sites", "More sites"], "params": {}})).unwrap(); + assert_eq!(result["succeeded"], 2); } else { s.run("gp.run", &json!({"tool": "repairGeometry", "params": {"input": "Sites"}})).unwrap(); } let notices: Vec<_> = s.notices_since(mark).iter().filter(|n| n.loss() == Some(LossCode::DroppedExtraAttributes)).collect(); assert_eq!(notices.len(), usize::from(extra), "batch {batch}"); + if batch && extra { + let text = ¬ices[0].text; + assert!(text.contains("2 loss report(s)") && text.contains("1 feature had") && text.contains("2 features had"), "{text}"); + } assert!(notices.iter().all(|n| n.severity == Severity::Warning && n.text.contains("extra values"))); assert_eq!(s.project.gp_history.iter().any(|r| r.messages.iter().any(|m| m.contains("extra values"))), extra); }