From 43fbe5b0a56662199fdb37ddcf6f8adb3a40c492 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 19 Nov 2026 15:19:53 -0600 Subject: [PATCH 01/15] fix(engine): report topology query fallbacks and preserve row contracts --- crates/engine/src/cmd/design.rs | 50 ++++++++-- crates/engine/src/cmd/workflows.rs | 5 +- crates/engine/src/tests.rs | 155 +++++++++++++++++++++++++++++ 3 files changed, 201 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 64973a7f95..6a440a65b5 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -2170,24 +2170,31 @@ struct TopologyInput { data: rustgis_data::Dataset, rows: Vec, by: Option, + query_error: Option, } /// The rules as the map has them now, each with what it reads; a rule whose layer is gone is left -/// out, as it always was. -fn topology_checks(s: &Session) -> Vec { +/// out, as it always was. Primary rows use Query, ignoring selection; covering rows use All. +/// The resolver query pass has no internal Cancel checks, as the previous visible-row pass did. +fn topology_checks(s: &Session) -> Result, String> { let mut inputs = Vec::new(); for rule in s.map().editing.topology.clone() { let Some(l) = s.map().layer_by_name(rule.layer()) else { continue }; - let rows: Vec = l.visible_rows().iter().enumerate().filter(|(_, v)| **v).map(|(i, _)| i).collect(); + let resolved = l.resolve_rows(&l.dataset, rustgis_map::rows::Policy::Query, None)?; + let rows = match resolved.rows { + rustgis_map::rows::Rows::All => (0..l.dataset.features.len()).collect(), + rustgis_map::rows::Rows::Subset(rows) => rows, + }; // A covering layer that is gone leaves the rule with nothing to check (its layer's - // latitudes are still checked). + // latitudes are still checked). Its whole resident dataset supplies coverage, + // independently of its selection and definition query. let by = match &rule { TopologyRule::MustBeCoveredBy { by, .. } => s.map().layer_by_name(by).map(|b| b.dataset.clone()), _ => None, }; - inputs.push(TopologyInput { rule, layer: l.name.clone(), data: l.dataset.clone(), rows, by }); + inputs.push(TopologyInput { rule, layer: l.name.clone(), data: l.dataset.clone(), rows, by, query_error: resolved.query_error }); } - inputs + Ok(inputs) } /// Whether two layers' data are the same: the same rows (shared, not compared one by one), fields @@ -2203,6 +2210,7 @@ fn same_topology(was: &[TopologyInput], now: &[TopologyInput]) -> bool { a.rule == b.rule && a.layer == b.layer && a.rows == b.rows + && a.query_error == b.query_error && same_data(&a.data, &b.data) && match (&a.by, &b.by) { (Some(x), Some(y)) => same_data(x, y), @@ -2259,7 +2267,7 @@ struct TopologyAhead { /// rule on a thread of its own, with progress and Cancel and no work limit. The command takes it /// as it lands when the rules and their layers are still the ones checked. pub(crate) fn topology_ahead(s: &Session, p: &Json) -> Option { - let (inputs, tol) = (topology_checks(s), topology_tolerance(p)); + let (inputs, tol) = (topology_checks(s).ok()?, topology_tolerance(p)); if inputs.is_empty() { return None; } @@ -2278,7 +2286,7 @@ pub(crate) fn topology_ahead(s: &Session, p: &Json) -> Option CmdResult { let tol = topology_tolerance(p); - let inputs = topology_checks(s); + let inputs = topology_checks(s)?; let found = match super::reads::take::(s, TOPOLOGY_AHEAD) { Some(ahead) if ahead.tol == tol && same_topology(&ahead.inputs, &inputs) => ahead.found?, // Checking again here would hold the window: the check made on its thread is dropped. @@ -2345,6 +2353,32 @@ fn topology_validate(s: &mut Session, p: &Json) -> CmdResult { let out: Vec = errors.iter().take(1000).map(|e| json!({"rule": e.rule, "layer": e.layer, "rows": e.rows, "lon": e.lon, "lat": e.lat})).collect(); s.topology_errors = errors; + // Count layers once even when several rules read the same unreadable query. Bound + // NoticeText::list nesting independently of the number of rules or layers. + use crate::notice_text::NoticeText; + let mut seen = std::collections::HashSet::new(); + let mut details = Vec::new(); + for input in &inputs { + if let Some(error) = &input.query_error + && seen.insert(&input.layer) + && details.len() < 5 + { + details.push(NoticeText::format("{layer}: {error}", [("layer", input.layer.clone().into()), ("error", error.clone().into())])); + } + } + if !seen.is_empty() { + let more = seen.len() - details.len(); + let mut layers = NoticeText::list(details); + if more > 0 { + layers = NoticeText::format("{layers}; {count} more layers", [("layers", layers), ("count", more.to_string().into())]); + } + let key = if seen.len() == 1 { + "{count} layer with an unreadable definition query; reading without that query: {layers}" + } else { + "{count} layers with unreadable definition queries; reading without those queries: {layers}" + }; + s.notify_text(NoticeText::format(key, [("count", seen.len().to_string().into()), ("layers", layers)]), false); + } Ok(json!({"errors": n, "first": out, "incomplete": incomplete})) } diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 856ea85976..8344d26f7d 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -80,6 +80,7 @@ pub fn commands() -> Vec { r#"{"layer": polygons, "count"?: points per polygon, "seed"?: number, "field"?: numeric field (count per polygon from it, scaled by "rate"), "rate"?: number, "name"?: output}"#, ), C::new("data.profile", "Data Engineering", "Analyze › Workflows", |s, p| { + // All resident rows: completeness profiling is independent of map filters/selection. let ds = feature_ds(s, p)?; let rows: Vec = network::profile_fields(ds) .into_iter() @@ -1881,7 +1882,7 @@ fn numeric_fields(ds: &Dataset, p: &Value) -> Result, String> { } } -/// Histograms of numeric fields and their correlation matrix. +/// Histograms and correlations over All resident rows, independent of map filters/selection. fn explore(s: &mut Session, p: &Value) -> CmdResult { let ds = feature_ds(s, p)?; let fields = numeric_fields(ds, p)?; @@ -1924,6 +1925,8 @@ fn explore(s: &mut Session, p: &Value) -> CmdResult { ) } +/// Compare All resident candidates. Selection supplies only the reference when row is omitted; +/// filtering candidates would also change the population used to standardize distances. fn similar(s: &mut Session, p: &Value) -> CmdResult { let id = s.layer_id(p)?; let l = s.map().layer(id).ok_or("no such layer")?; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ed3faf2419..a47aff49e2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -54295,3 +54295,158 @@ fn row_resolver_buffer_and_both_clip_inputs() { } } } + +/// Whole-resident diagnostics retain nulls and hidden candidates. Similar's selection is a +/// reference, not an input subset, and its returned row positions never become feature IDs. +#[test] +fn resident_data_diagnostics_keep_all_rows_despite_map_filters() { + let mut ds = rustgis_data::Dataset::new( + "values", + rustgis_data::GeometryType::None, + vec![rustgis_data::Field::new("n", rustgis_data::FieldType::Integer)], + ); + for n in [Some(0), Some(2), Some(10), None] { + ds.push(None, vec![n.map_or(rustgis_data::Value::Null, rustgis_data::Value::Int)]); + } + for (f, id) in ds.features.iter_mut().zip([90, 10, 70, 30]) { + f.id = id; + } + let mut s = Session::new(Project::default()); + let id = crate::cmd::layer::add_dataset(&mut s, ds); + let held = s.map().layer(id).unwrap().dataset.clone(); + let params = json!({"layer": id, "fields": ["n"]}); + let profile = s.run("data.profile", ¶ms).unwrap(); + assert_eq!(profile["features"], 4); + assert_eq!(profile["fields"][0]["nulls"], 1); + assert_eq!(profile["fields"][0]["distinct"], 3); + assert_eq!(profile["fields"][0]["mean"], 4.0); + let explore = s.run("data.explore", ¶ms).unwrap(); + assert_eq!(explore["histograms"][0]["max"], 10.0); + assert_eq!(explore["histograms"][0]["counts"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).sum::(), 3); + let expected = s.run("data.similar", &json!({"layer": id, "row": 0, "fields": ["n"], "count": 2, "select": false})).unwrap(); + assert_eq!(expected["similar"][0]["row"], 1); + assert_eq!(expected["similar"][1]["row"], 2); + for query in [None, Some("n = 10"), Some("n > 100"), Some("missing = 1")] { + let l = s.map_mut().layer_mut(id).unwrap(); + l.definition_query = query.map(str::to_string); + l.selection = vec![0]; + let mark = s.notice_mark(); + assert_eq!(s.run("data.profile", ¶ms).unwrap(), profile); + assert_eq!(s.run("data.explore", ¶ms).unwrap(), explore); + assert_eq!(s.run("data.similar", &json!({"layer": id, "fields": ["n"], "count": 2, "select": false})).unwrap(), expected); + assert_eq!(s.map().layer(id).unwrap().selection, vec![0]); + assert!( + s.notices_since(mark).iter().all(|n| !n.text.contains("unreadable definition quer")), + "All policy must not report query fallback: {:?}", + s.notices_since(mark).iter().map(|n| &n.text).collect::>() + ); + } + assert_eq!(s.run("data.similar", &json!({"layer": id, "row": 0, "fields": ["n"], "count": 2})).unwrap(), expected); + let l = s.map().layer(id).unwrap(); + assert_eq!(l.selection, vec![0, 1, 2]); + assert!(held.features.shares(&l.dataset.features), "readers and selection retain shared rows"); +} + +/// Primary Query scope ignores selection; the covering layer deliberately supplies All rows. +/// Empty primary subsets check nothing, and repeated rules count one literal fallback per layer. +#[test] +fn topology_row_contracts_and_unreadable_query_notice() { + use rustgis_data::Geometry; + use rustgis_data::{Dataset, Field, FieldType, GeometryType, Value as V}; + use rustgis_geom::Coord; + let mut s = Session::new(Project::default()); + let mut points = Dataset::new("points {layer}", GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); + points.push(Some(Geometry::Point(Coord::new(0.5, 0.5))), vec![V::Int(1)]); + points.push(Some(Geometry::Point(Coord::new(3.0, 3.0))), vec![V::Int(2)]); + points.features[0].id = 71; + points.features[1].id = 19; + let id = crate::cmd::layer::add_dataset(&mut s, points); + let cover = json!({"type":"FeatureCollection","features":[{"type":"Feature","properties":{"n":1},"geometry":{"type":"Polygon","coordinates":[[[0,0],[1,0],[1,1],[0,1],[0,0]]]}}]}); + s.run("layer.addDataText", &json!({"fileName":"cover.geojson","text":cover.to_string()})).unwrap(); + let cover_id = s.map().layer_by_name("cover").unwrap().id; + s.map_mut().layer_mut(cover_id).unwrap().definition_query = Some("n > 100".into()); + s.run("topology.rules", &json!({"add":{"rule":"mustBeCoveredBy","layer":"points {layer}","by":"cover"}})).unwrap(); + s.run("topology.rules", &json!({"add":{"rule":"mustNotSelfIntersect","layer":"points {layer}"}})).unwrap(); + let held = s.map().layer(id).unwrap().dataset.clone(); + for (query, errors) in [(None, 1), (Some("n = 1"), 0), (Some("n = 2"), 1), (Some("n > 100"), 0)] { + let l = s.map_mut().layer_mut(id).unwrap(); + l.definition_query = query.map(str::to_string); + l.selection = vec![0]; + let mark = s.notice_mark(); + let out = s.run("topology.validate", &Value::Null).unwrap(); + assert_eq!(out["errors"], errors, "{query:?}: {out}"); + if errors == 1 { + assert_eq!(out["first"][0]["rows"], json!([1])); + } + assert!(s.notices_since(mark).is_empty()); + } + s.map_mut().layer_mut(id).unwrap().definition_query = Some("missing = 1".into()); + let mark = s.notice_mark(); + assert_eq!(s.run("topology.validate", &Value::Null).unwrap()["errors"], 1); + let notices = s.notices_since(mark); + assert_eq!(notices.len(), 1); + assert!(notices[0].text.starts_with("1 layer with an unreadable definition query")); + let keys = std::cell::RefCell::new(Vec::new()); + let rendered = notices[0].translated(|key, args| { + keys.borrow_mut().push(key.to_string()); + let mut out = format!("translated:{key}"); + for (k, v) in args { + out = out.replace(&format!("{{{k}}}"), v); + } + out + }); + let rendered = rendered.unwrap(); + assert!(rendered.contains("points {layer}")); + assert!(keys.borrow().iter().all(|key| !key.contains("points {layer}") && !key.contains("missing"))); + assert!(held.features.shares(&s.map().layer(id).unwrap().dataset.features)); + + #[cfg(not(target_arch = "wasm32"))] + { + use crate::cmd::reads::{read_ahead, read_land}; + use rustgis_analysis::control::Control; + let read = read_ahead(&mut s, "topology.validate", &json!({})).unwrap().run(&Control::stoppable()).unwrap(); + // Same rows, different fallback state: don't land an obsolete diagnostic. + s.map_mut().layer_mut(id).unwrap().definition_query = None; + let mark = s.notice_mark(); + assert!(read_land(&mut s, read).unwrap_err().contains("changed while they were checked")); + let notices = s.notices_since(mark); + assert_eq!(notices.len(), 1); + assert!(notices[0].error && notices[0].text.contains("changed while they were checked")); + assert_eq!(s.topology_errors.len(), 1); + } +} + +/// Seven unreadable primary queries produce one bounded notice on successful read-ahead landing. +#[test] +fn topology_query_details_are_bounded_and_land_with_ahead_results() { + let mut s = Session::new(Project::default()); + for i in 0..7 { + let name = format!("query layer {i}"); + let mut ds = rustgis_data::Dataset::new(&name, rustgis_data::GeometryType::Point, vec![]); + ds.push(Some(rustgis_data::Geometry::Point(rustgis_geom::Coord::new(0.0, 0.0))), vec![]); + let id = crate::cmd::layer::add_dataset(&mut s, ds); + s.map_mut().layer_mut(id).unwrap().definition_query = Some("missing = 1".into()); + s.run("topology.rules", &json!({"add":{"rule":"mustNotSelfIntersect","layer":name}})).unwrap(); + } + let mark = s.notice_mark(); + #[cfg(not(target_arch = "wasm32"))] + { + use crate::cmd::reads::{read_ahead, read_land}; + let read = + read_ahead(&mut s, "topology.validate", &json!({})).unwrap().run(&rustgis_analysis::control::Control::stoppable()).unwrap(); + assert!(s.notices_since(mark).is_empty()); + read_land(&mut s, read).unwrap(); + } + #[cfg(target_arch = "wasm32")] + s.run("topology.validate", &Value::Null).unwrap(); + let notices = s.notices_since(mark); + assert_eq!(notices.len(), 1); + assert!(notices[0].text.starts_with("7 layers with unreadable definition queries")); + assert!(notices[0].text.contains("2 more layers")); + assert!(!notices[0].text.contains("query layer 5")); + assert!( + notices[0] + .translated(|key, args| { args.iter().fold(key.to_string(), |text, (k, v)| text.replace(&format!("{{{k}}}"), v)) }) + .is_some() + ); +} From fc74b0b094a1027343f6e2ae5bdfcc9c11b7a600 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 19 Nov 2026 17:34:12 -0600 Subject: [PATCH 02/15] fix(engine): keep Similar selection within drawn rows --- crates/engine/src/cmd/workflows.rs | 14 ++++++++++++ crates/engine/src/tests.rs | 34 +++++++++++++++++++++++++++--- docs/user-guide/analysis.md | 8 +++++++ 3 files changed, 53 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 8344d26f7d..b231396b18 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1927,6 +1927,7 @@ fn explore(s: &mut Session, p: &Value) -> CmdResult { /// Compare All resident candidates. Selection supplies only the reference when row is omitted; /// filtering candidates would also change the population used to standardize distances. +/// Output selection keeps only drawn rows, reporting candidates/reference excluded by map filters. fn similar(s: &mut Session, p: &Value) -> CmdResult { let id = s.layer_id(p)?; let l = s.map().layer(id).ok_or("no such layer")?; @@ -1947,7 +1948,20 @@ fn similar(s: &mut Session, p: &Value) -> CmdResult { if b(p, "select").unwrap_or(true) { let mut sel: Vec = found.iter().map(|x| x.0).collect(); sel.push(row); + let drawn = l.drawn_rows(s.scale()); + let matched = sel.len(); + sel.retain(|r| drawn.get(*r) == Some(&true)); + let excluded = matched - sel.len(); super::select::set(s, id, sel, super::select::Mode::New); + if excluded > 0 { + s.notify_text( + crate::notice_text::NoticeText::format( + "{n} features aren't drawn (the layer's definition query, time window or display filters hide them), and aren't selected", + [("n", excluded.to_string().into())], + ), + false, + ); + } } Ok(json!({"similar": rows})) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a47aff49e2..e4bdf1d51a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -54341,10 +54341,38 @@ fn resident_data_diagnostics_keep_all_rows_despite_map_filters() { s.notices_since(mark).iter().map(|n| &n.text).collect::>() ); } + // Ranking still includes hidden candidates, but output selection follows the map's + // drawn-row contract, including an explicitly supplied reference hidden by the query. + for (query, selection, excluded) in [ + (None, vec![0, 1, 2], 0), + (Some("n >= 2"), vec![1, 2], 1), + (Some("n = 10"), vec![2], 2), + (Some("n > 100"), vec![], 3), + (Some("missing = 1"), vec![0, 1, 2], 0), + ] { + s.map_mut().layer_mut(id).unwrap().definition_query = query.map(str::to_string); + let mark = s.notice_mark(); + assert_eq!(s.run("data.similar", &json!({"layer": id, "row": 0, "fields": ["n"], "count": 2})).unwrap(), expected); + assert_eq!(s.map().layer(id).unwrap().selection, selection, "{query:?}"); + let notices = s.notices_since(mark); + assert_eq!(notices.len(), usize::from(excluded > 0)); + if excluded > 0 { + assert!(notices[0].text.starts_with(&format!("{excluded} features aren't drawn"))); + } + } + let l = s.map_mut().layer_mut(id).unwrap(); + l.definition_query = None; + l.display_filters.push(rustgis_map::effects::DisplayFilter { + name: "only ten".into(), + min_scale: None, + max_scale: None, + where_: "n = 10".into(), + }); + let mark = s.notice_mark(); assert_eq!(s.run("data.similar", &json!({"layer": id, "row": 0, "fields": ["n"], "count": 2})).unwrap(), expected); - let l = s.map().layer(id).unwrap(); - assert_eq!(l.selection, vec![0, 1, 2]); - assert!(held.features.shares(&l.dataset.features), "readers and selection retain shared rows"); + assert_eq!(s.map().layer(id).unwrap().selection, vec![2]); + assert!(s.notices_since(mark)[0].text.starts_with("2 features aren't drawn")); + assert!(held.features.shares(&s.map().layer(id).unwrap().dataset.features), "readers and selection retain shared rows"); } /// Primary Query scope ignores selection; the covering layer deliberately supplies All rows. diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index b998ad5342..9b597320ce 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1483,6 +1483,14 @@ click them on the map: | Embeddings | The features most like the selected one, by their numeric attributes | | Data Interop | KML, GPX, CSV with WKT, GeoJSON or CSV | +Data Engineering and Exploratory Analysis use every resident row, independently of the +layer's selection and map filters. Embeddings also compares and standardizes numeric values +over every resident row; the selection supplies its reference when no explicit row is given. +Its returned matches can include hidden rows. With the default `select: true`, only matches +and the reference that pass the layer's definition query, time window and display filters +are selected; one notice counts those excluded. `select: false` leaves selection unchanged. +These workflows use the loaded resident dataset, without reloading a streamed layer's source. + Slope, in Raster Functions and the Function Editor, uses Horn's 3 × 3 gradient. Choose **Slope units**: **Degrees (0–90)** (the default, from flat to vertical) or **Percent**. For `raster.function`, set `"function": "slope", "units": "percent"`; in `raster.functionChain`, From 7a2e61cca2f3d6bd96701b3fc8772a361fa6ee72 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 19 Nov 2026 18:16:52 -0600 Subject: [PATCH 03/15] fix(engine): report Similar selection filter fallback --- crates/engine/src/cmd/workflows.rs | 20 +++++++++++++++++++- crates/engine/src/tests.rs | 22 +++++++++++++++++++++- docs/user-guide/analysis.md | 4 +++- 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index b231396b18..5cf1d68f49 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1948,11 +1948,29 @@ fn similar(s: &mut Session, p: &Value) -> CmdResult { if b(p, "select").unwrap_or(true) { let mut sel: Vec = found.iter().map(|x| x.0).collect(); sel.push(row); - let drawn = l.drawn_rows(s.scale()); + let scale = s.scale(); + // The shared drawn mask keeps the established fallback. Report the settings it + // cannot read, retaining only the first literal diagnostic regardless of filter count. + let mut errors = rustgis_data::rows::Query::compile(l.definition_query.as_deref(), &l.dataset).err().into_iter().chain( + l.display_filters + .iter() + .filter(|f| f.applies(scale)) + .filter_map(|f| rustgis_data::query::parse_fields(&f.where_, &l.dataset).err()), + ); + let unreadable = errors.next().map(|error| { + crate::notice_text::NoticeText::format( + "{layer}: selecting without unreadable query/filter settings ({count}). First parser error: {error}", + [("layer", l.name.clone().into()), ("count", (1 + errors.count()).to_string().into()), ("error", error.into())], + ) + }); + let drawn = l.drawn_rows(scale); let matched = sel.len(); sel.retain(|r| drawn.get(*r) == Some(&true)); let excluded = matched - sel.len(); super::select::set(s, id, sel, super::select::Mode::New); + if let Some(notice) = unreadable { + s.notify_text(notice, false); + } if excluded > 0 { s.notify_text( crate::notice_text::NoticeText::format( diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e4bdf1d51a..2599ab4fec 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -54355,10 +54355,15 @@ fn resident_data_diagnostics_keep_all_rows_despite_map_filters() { assert_eq!(s.run("data.similar", &json!({"layer": id, "row": 0, "fields": ["n"], "count": 2})).unwrap(), expected); assert_eq!(s.map().layer(id).unwrap().selection, selection, "{query:?}"); let notices = s.notices_since(mark); - assert_eq!(notices.len(), usize::from(excluded > 0)); + let unreadable = query == Some("missing = 1"); + assert_eq!(notices.len(), usize::from(excluded > 0) + usize::from(unreadable)); if excluded > 0 { assert!(notices[0].text.starts_with(&format!("{excluded} features aren't drawn"))); } + if unreadable { + assert!(notices[0].text.contains("selecting without unreadable query/filter settings (1)")); + assert!(notices[0].text.contains("missing")); + } } let l = s.map_mut().layer_mut(id).unwrap(); l.definition_query = None; @@ -54372,6 +54377,21 @@ fn resident_data_diagnostics_keep_all_rows_despite_map_filters() { assert_eq!(s.run("data.similar", &json!({"layer": id, "row": 0, "fields": ["n"], "count": 2})).unwrap(), expected); assert_eq!(s.map().layer(id).unwrap().selection, vec![2]); assert!(s.notices_since(mark)[0].text.starts_with("2 features aren't drawn")); + let l = s.map_mut().layer_mut(id).unwrap(); + l.display_filters[0].where_ = "missing = 1".into(); + l.display_filters.push(rustgis_map::effects::DisplayFilter { + name: "second unreadable".into(), + min_scale: None, + max_scale: None, + where_: "another_missing = 1".into(), + }); + let mark = s.notice_mark(); + assert_eq!(s.run("data.similar", &json!({"layer": id, "row": 0, "fields": ["n"], "count": 2})).unwrap(), expected); + assert_eq!(s.map().layer(id).unwrap().selection, vec![0, 1, 2]); + let notices = s.notices_since(mark); + assert_eq!(notices.len(), 1); + assert!(notices[0].text.contains("selecting without unreadable query/filter settings (2)")); + assert!(notices[0].text.contains("missing")); assert!(held.features.shares(&s.map().layer(id).unwrap().dataset.features), "readers and selection retain shared rows"); } diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 9b597320ce..4acd4ef20e 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1488,7 +1488,9 @@ layer's selection and map filters. Embeddings also compares and standardizes num over every resident row; the selection supplies its reference when no explicit row is given. Its returned matches can include hidden rows. With the default `select: true`, only matches and the reference that pass the layer's definition query, time window and display filters -are selected; one notice counts those excluded. `select: false` leaves selection unchanged. +are selected; one notice counts those excluded. Unreadable definition queries or active +display filters are ignored for selection, with one notice giving the count and first parser +error. `select: false` leaves selection unchanged and does not apply these filters. These workflows use the loaded resident dataset, without reloading a streamed layer's source. Slope, in Raster Functions and the Function Editor, uses Horn's 3 × 3 gradient. Choose From 827e68f8d3669aaa7f4d5b5a1f9d61817fbb5556 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 19 Nov 2026 20:59:45 -0600 Subject: [PATCH 04/15] fix(engine): compute Similar on the desktop read queue --- AGENTS.md | 2 +- crates/analysis/src/network.rs | 102 +++++++++--- crates/assistant/src/mcp.rs | 9 +- crates/engine/src/cmd/mod.rs | 1 + crates/engine/src/cmd/reads.rs | 3 +- crates/engine/src/cmd/similar.rs | 207 ++++++++++++++++++++++++ crates/engine/src/cmd/workflows.rs | 64 +------- crates/engine/src/policy/dispatch.rs | 10 +- crates/engine/src/tests.rs | 76 +++++++++ crates/engine/src/tests/cancellation.rs | 1 + crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/readjob.rs | 49 +++++- docs/user-guide/analysis.md | 2 + 13 files changed, 440 insertions(+), 89 deletions(-) create mode 100644 crates/engine/src/cmd/similar.rs diff --git a/AGENTS.md b/AGENTS.md index 3d6a264988..2ae2abe813 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,7 +43,7 @@ is out of scope. - A new background raster command or export, or a tool whose work grows with its input, goes in the lists in `long_commands` (`crates/engine/src/tests/cancellation.rs`), which both cancel tests run; the raster and export lists must match the background registries. A read-ahead command - (`reads::prepare`, such as `service.layers` or `edit.previewShapeConversion`) has no registry: + (`reads::prepare`, such as `service.layers`, `edit.previewShapeConversion` or `data.similar`) has no registry: add its call to `long_commands` by hand. `long_commands_stop_when_cancelled_while_they_run` fails one that never looks at Cancel; `cancelling_at_each_check_leaves_nothing_behind` cancels at every check in turn until the command diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 16a2fe50a8..5cb4689fdc 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -757,28 +757,90 @@ pub fn profile_fields(ds: &Dataset) -> Vec { } /// Rows ranked by how close their numeric attributes are to a row's (z-scored Euclidean -/// distance over `fields`), nearest first, excluding the row itself. -pub fn similar(ds: &Dataset, row: usize, fields: &[usize], n: usize) -> Vec<(usize, f64)> { - let stats: Vec<(f64, f64)> = fields - .iter() - .map(|fi| { - let vals: Vec = (0..ds.features.len()).filter_map(|r| ds.value(r, *fi).as_f64()).filter(|v| v.is_finite()).collect(); - let m = vals.iter().sum::() / vals.len().max(1) as f64; - let sd = (vals.iter().map(|v| (v - m).powi(2)).sum::() / vals.len().max(1) as f64).sqrt(); - (m, if sd > 0.0 { sd } else { 1.0 }) - }) - .collect(); - let vec_of = |r: usize| -> Option> { - fields.iter().zip(&stats).map(|(fi, (m, sd))| ds.value(r, *fi).as_f64().filter(|v| v.is_finite()).map(|v| (v - m) / sd)).collect() +/// distance over `fields`), nearest first, excluding the row itself. Counts progress and checks +/// Cancel between rows and within wide vectors. The stable library sort is one indivisible step, +/// checked immediately before and after; equal-distance rows keep their original order. +pub fn similar(ds: &Dataset, row: usize, fields: &[usize], n: usize) -> Result, String> { + use crate::control; + control::begin(ds.features.len().saturating_mul(fields.len().saturating_mul(3).saturating_add(1))); + let mut stats = Vec::with_capacity(fields.len()); + for fi in fields { + let mut vals = Vec::new(); + for r in 0..ds.features.len() { + control::check()?; + control::advance(1); + if let Some(v) = ds.value(r, *fi).as_f64().filter(|v| v.is_finite()) { + vals.push(v); + } + } + // Result's sum delegates to the same f64 reduction as the original iterator sum; + // cancellation changes neither its order nor its identity value. + let m = vals + .iter() + .map(|v| { + control::check()?; + control::advance(1); + Ok(*v) + }) + .sum::>()? + / vals.len().max(1) as f64; + let sd = (vals + .iter() + .map(|v| { + control::check()?; + control::advance(1); + Ok((v - m).powi(2)) + }) + .sum::>()? + / vals.len().max(1) as f64) + .sqrt(); + stats.push((m, if sd > 0.0 { sd } else { 1.0 })); + } + let mut vector_pace = control::Pace::default(); + let mut vec_of = |r: usize| -> Result>, control::Cancelled> { + fields + .iter() + .zip(&stats) + .map(|(fi, (m, sd))| { + if vector_pace.stop(1) { + return Err(control::Cancelled); + } + Ok(ds.value(r, *fi).as_f64().filter(|v| v.is_finite()).map(|v| (v - m) / sd)) + }) + .collect() }; - let Some(target) = vec_of(row) else { return Vec::new() }; - let mut out: Vec<(usize, f64)> = (0..ds.features.len()) - .filter(|r| *r != row) - .filter_map(|r| vec_of(r).map(|v| (r, v.iter().zip(&target).map(|(a, b)| (a - b).powi(2)).sum::().sqrt()))) - .collect(); + let Some(target) = vec_of(row)? else { + control::finish(); + return Ok(Vec::new()); + }; + let mut distance_pace = control::Pace::default(); + let mut out = Vec::new(); + for r in 0..ds.features.len() { + control::check()?; + control::advance(1); + if r != row + && let Some(v) = vec_of(r)? + { + let distance = v + .iter() + .zip(&target) + .map(|(a, b)| { + if distance_pace.stop(1) { + return Err(control::Cancelled); + } + Ok((a - b).powi(2)) + }) + .sum::>()? + .sqrt(); + out.push((r, distance)); + } + } + control::check()?; out.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal)); + control::check()?; out.truncate(n); - out + control::finish(); + Ok(out) } fn radius_scale(at: Coord) -> f64 { @@ -1489,7 +1551,7 @@ mod tests { assert_eq!(random_points(&poly, &[0], 25, 7), pts, "reproducible"); let p = profile_fields(&ds); assert_eq!((p[0].min, p[0].max, p[0].distinct), (Some(1.0), Some(5.0), 2)); - let sim = similar(&ds, 0, &[0], 2); + let sim = similar(&ds, 0, &[0], 2).unwrap(); assert_eq!(sim[0].0, 1); let near = within(&ds, &rows, Coord::new(0.5, 0.001), 500.0); assert_eq!(near.first().map(|x| x.0), Some(0)); diff --git a/crates/assistant/src/mcp.rs b/crates/assistant/src/mcp.rs index b47dc01590..b1d6687a82 100644 --- a/crates/assistant/src/mcp.rs +++ b/crates/assistant/src/mcp.rs @@ -164,7 +164,14 @@ impl ArchiveBatch { if name != "run_command" || !matches!( args.get("command").and_then(Value::as_str).map(str::trim), - Some("map.reloadTiles" | "map.repairTiles" | "table.statistics" | "edit.previewShapeConversion" | "layer.sizeBy") + Some( + "map.reloadTiles" + | "map.repairTiles" + | "table.statistics" + | "data.similar" + | "edit.previewShapeConversion" + | "layer.sizeBy" + ) ) { return None; diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 17d9ef5b57..514b2de2f7 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -53,6 +53,7 @@ pub mod service; pub mod service_added; pub mod share; pub mod sharing; +mod similar; pub mod sources; pub mod sql; pub mod stac; diff --git a/crates/engine/src/cmd/reads.rs b/crates/engine/src/cmd/reads.rs index 3548ccb741..852c2aa804 100644 --- a/crates/engine/src/cmd/reads.rs +++ b/crates/engine/src/cmd/reads.rs @@ -285,8 +285,9 @@ pub(crate) fn prepare(s: &mut Session, op: Authorized, owner: Continu "source.syncState" => ("Source File State", super::publish::sync_ahead(s, params), None), "edit.previewShapeConversion" => ("Preview Shape Conversion", crate::shape_conversion::ahead(s, params), None), "table.statistics" => ("Column Statistics", super::table_stats::stats_ahead(s, params), None), + "data.similar" => ("Find Similar", super::similar::ahead(s, params), None), "layer.sizeBy" => ("Size by Field", super::layer::size_by_ahead(s, params), None), - _ => return Err("only Add Data, Load All, Repair/Reload Data, Convert To Annotation, models, scripts, tile archives, service listings, topology, Source File State, Column Statistics and Size by Field prepare background work".into()), + _ => return Err("only Add Data, Load All, Repair/Reload Data, Convert To Annotation, models, scripts, tile archives, service listings, topology, Source File State, Column Statistics, Similar and Size by Field prepare background work".into()), }; let name = work.as_ref().map_or(name, |work| work.name); let table = super::edit::table_edit_in_background(spec.id) diff --git a/crates/engine/src/cmd/similar.rs b/crates/engine/src/cmd/similar.rs new file mode 100644 index 0000000000..1fbf2a88ae --- /dev/null +++ b/crates/engine/src/cmd/similar.rs @@ -0,0 +1,207 @@ +//! Similarity ranks every resident row. Desktop adapters prepare the work off the window +//! thread; only validated completion may replace selection or deliver its notices. + +use rustgis_data::{Dataset, query}; +use rustgis_map::effects::DisplayFilter; +use serde_json::{Value, json}; + +use crate::notice_text::NoticeText; +use crate::{CmdResult, Session}; + +#[derive(PartialEq)] +struct Target { + id: u32, + row: usize, + fields: Vec, + count: usize, + select: bool, +} + +/// The map filters affecting output selection, independently of the ranking population. +#[derive(PartialEq)] +struct Visibility { + query: Option, + filters: Vec, + time: Option<(String, Option<(f64, f64)>)>, + scale: f64, +} + +/// Captures only this layer's metadata and shared row storage, never a project/session copy. +struct Input { + target: Target, + opened: u64, + map: u64, + instance: u64, + name: String, + data: Dataset, + visibility: Option, +} + +impl Input { + /// Resolves the reference and schema without traversing features. Selection supplies only + /// its first row when no explicit reference is given. + fn resolve(s: &Session, p: &Value) -> Result { + let id = s.layer_id(p)?; + let l = s.map().layer(id).ok_or("no such layer")?; + let row = match p.get("row").and_then(Value::as_u64) { + Some(r) => r as usize, + None => *l.selection.first().ok_or("select a feature (or give row)")?, + }; + if row >= l.dataset.features.len() { + return Err("no such row".into()); + } + let fields = super::workflows::numeric_fields(&l.dataset, p)?; + if fields.is_empty() { + return Err("the layer has no numeric fields to compare".into()); + } + let count = p.get("count").and_then(Value::as_u64).unwrap_or(10).clamp(1, 1000) as usize; + let select = super::b(p, "select").unwrap_or(true); + let visibility = select.then(|| Visibility { + query: l.definition_query.clone(), + filters: l.display_filters.clone(), + time: l.time.as_ref().map(|t| (t.field.clone(), t.window)), + scale: s.scale(), + }); + Ok(Self { + target: Target { id, row, fields, count, select }, + opened: s.opened, + map: s.map().instance_id(), + instance: l.instance_id(), + name: l.name.clone(), + data: l.dataset.clone(), + visibility, + }) + } + + /// Refuses data/reference/filter changes while work ran. Comparing row allocations avoids + /// copying or visiting features on the window thread. + fn same(&self, now: &Self) -> bool { + self.target == now.target + && self.opened == now.opened + && self.map == now.map + && self.instance == now.instance + && self.name == now.name + && self.data.features.shares(&now.data.features) + && self.data.fields == now.data.fields + && self.data.coord_crs() == now.data.coord_crs() + && self.visibility == now.visibility + } +} + +struct Done { + answer: Value, + selection: Option>, + notices: Vec, +} + +struct Ahead { + input: Input, + done: Result, +} + +/// Filters the bounded result/reference rows with cancellation, without a layer-wide mask. +fn keep(rows: Vec, mut matches: impl FnMut(usize) -> bool) -> Result, String> { + rustgis_data::progress::begin(rows.len()); + let mut kept = Vec::with_capacity(rows.len()); + for row in rows { + rustgis_data::progress::step(1).map_err(|e| e.to_string())?; + if matches(row) { + kept.push(row); + } + } + Ok(kept) +} + +/// Computes rankings and output intent without mutating the session. Ranking checks Cancel in +/// its loops; expression evaluation of one candidate and a time binding's initial mask fill are +/// indivisible library steps, checked before/after. A detached time cache cannot lock the live +/// window's cache. Only the at-most-1,001 result/reference rows need query/filter evaluation. +fn gather(input: &Input) -> Result { + let t = &input.target; + let found = rustgis_analysis::network::similar(&input.data, t.row, &t.fields, t.count)?; + let answer = json!({"similar": found.iter().map(|(r, d)| json!({"row": r, "distance": d})).collect::>()}); + let Some(v) = &input.visibility else { return Ok(Done { answer, selection: None, notices: Vec::new() }) }; + let mut rows: Vec = found.iter().map(|(r, _)| *r).collect(); + rows.push(t.row); + let matched = rows.len(); + let mut failed = 0usize; + let mut first = None; + let mut error = |e| { + failed += 1; + if first.is_none() { + first = Some(e); + } + }; + rustgis_data::progress::check().map_err(|e| e.to_string())?; + match rustgis_data::rows::Query::compile(v.query.as_deref(), &input.data) { + Ok(q) => rows = keep(rows, |r| q.matches(&input.data, r, &query::Env::default()))?, + Err(e) => error(e), + } + if let Some((field, Some(window))) = &v.time { + let mut time = rustgis_map::time::TimeBinding::new(field); + time.window = Some(*window); + let mask = time.keeps(&input.data); + rustgis_data::progress::check().map_err(|e| e.to_string())?; + if let Some(mask) = mask { + rows = keep(rows, |r| mask.get(r) == Some(&true))?; + } + } + for filter in v.filters.iter().filter(|f| f.applies(v.scale)) { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + match query::parse_fields(&filter.where_, &input.data) { + Ok(q) => rows = keep(rows, |r| query::matches(&q, &input.data, r, &query::Env::default()))?, + Err(e) => error(e), + } + } + let mut notices = Vec::new(); + if let Some(error) = first { + notices.push(NoticeText::format( + "{layer}: selecting without unreadable query/filter settings ({count}). First parser error: {error}", + [("layer", input.name.clone().into()), ("count", failed.to_string().into()), ("error", error.into())], + )); + } + let excluded = matched - rows.len(); + if excluded > 0 { + notices.push(NoticeText::format( + "{n} features aren't drawn (the layer's definition query, time window or display filters hide them), and aren't selected", + [("n", excluded.to_string().into())], + )); + } + rustgis_data::progress::check().map_err(|e| e.to_string())?; + Ok(Done { answer, selection: Some(rows), notices }) +} + +/// Prepares desktop Similar work on shared rows. Invalid requests remain cheap synchronous +/// errors; successful work is taken only by the original admitted command at landing. +pub(super) fn ahead(s: &Session, p: &Value) -> Option { + let input = Input::resolve(s, p).ok()?; + Some(super::reads::ahead("Find Similar", "data.similar".into(), move || { + let done = gather(&input); + Ahead { input, done } + })) +} + +/// Desktop UI and direct MCP adapters use the prepared read queue, with progress and Cancel. +/// A borrowed synchronous Session cannot yield a deferred command reply; headless/script callers +/// run here on their caller's thread, and the browser has one thread. A registered window owner +/// refuses an unprepared run instead of repeating heavy work inline. +pub(super) fn run(s: &mut Session, p: &Value) -> CmdResult { + let input = Input::resolve(s, p)?; + let ahead = super::reads::take::(s, "data.similar"); + #[cfg(not(target_arch = "wasm32"))] + if ahead.is_none() && s.statistics_window_thread == Some(std::thread::current().id()) { + return Err("Similarity needs the desktop background read queue; run Find Similar or a direct MCP data.similar request".into()); + } + let done = match ahead { + Some(a) if a.input.same(&input) => a.done?, + Some(_) => return Err("the layer, reference or map filters changed while similarity was computed: ask again".into()), + None => gather(&input)?, + }; + if let Some(rows) = done.selection { + super::select::set(s, input.target.id, rows, super::select::Mode::New); + } + for notice in done.notices { + s.notify_text(notice, false); + } + Ok(done.answer) +} diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 5cf1d68f49..dacc2dec7a 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -93,7 +93,7 @@ pub fn commands() -> Vec { C::new("data.explore", "Exploratory Analysis", "Analyze › Workflows", explore).roles(&[]).effects(crate::policy::Effects::NONE) .view() .params(r#"{"layer"?, "fields"?: [numeric fields], "bins"?: number}"#), - C::new("data.similar", "Embeddings", "Analyze › Workflows", similar).roles(&[]).effects(crate::policy::Effects::NONE) + C::new("data.similar", "Embeddings", "Analyze › Workflows", super::similar::run).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"layer"?, "row"?: number (the selected feature when omitted), "fields"?: [numeric fields], "count"?: number, "select"?: bool}"#), C::new("data.convert", "Data Interop", "Analyze › Workflows", convert).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() @@ -1867,7 +1867,8 @@ fn simulate(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({"layer": nid, "points": n})) } -fn numeric_fields(ds: &Dataset, p: &Value) -> Result, String> { +/// Numeric fields requested by name, or all numeric fields when omitted; invalid names fail. +pub(super) fn numeric_fields(ds: &Dataset, p: &Value) -> Result, String> { match p.get("fields").and_then(Value::as_array) { Some(a) => a .iter() @@ -1925,65 +1926,6 @@ fn explore(s: &mut Session, p: &Value) -> CmdResult { ) } -/// Compare All resident candidates. Selection supplies only the reference when row is omitted; -/// filtering candidates would also change the population used to standardize distances. -/// Output selection keeps only drawn rows, reporting candidates/reference excluded by map filters. -fn similar(s: &mut Session, p: &Value) -> CmdResult { - let id = s.layer_id(p)?; - let l = s.map().layer(id).ok_or("no such layer")?; - let row = match p.get("row").and_then(Value::as_u64) { - Some(r) => r as usize, - None => *l.selection.first().ok_or("select a feature (or give row)")?, - }; - if row >= l.dataset.features.len() { - return Err("no such row".into()); - } - let fields = numeric_fields(&l.dataset, p)?; - if fields.is_empty() { - return Err("the layer has no numeric fields to compare".into()); - } - let n = p.get("count").and_then(Value::as_u64).unwrap_or(10).clamp(1, 1000) as usize; - let found = network::similar(&l.dataset, row, &fields, n); - let rows: Vec = found.iter().map(|(r, d)| json!({"row": r, "distance": d})).collect(); - if b(p, "select").unwrap_or(true) { - let mut sel: Vec = found.iter().map(|x| x.0).collect(); - sel.push(row); - let scale = s.scale(); - // The shared drawn mask keeps the established fallback. Report the settings it - // cannot read, retaining only the first literal diagnostic regardless of filter count. - let mut errors = rustgis_data::rows::Query::compile(l.definition_query.as_deref(), &l.dataset).err().into_iter().chain( - l.display_filters - .iter() - .filter(|f| f.applies(scale)) - .filter_map(|f| rustgis_data::query::parse_fields(&f.where_, &l.dataset).err()), - ); - let unreadable = errors.next().map(|error| { - crate::notice_text::NoticeText::format( - "{layer}: selecting without unreadable query/filter settings ({count}). First parser error: {error}", - [("layer", l.name.clone().into()), ("count", (1 + errors.count()).to_string().into()), ("error", error.into())], - ) - }); - let drawn = l.drawn_rows(scale); - let matched = sel.len(); - sel.retain(|r| drawn.get(*r) == Some(&true)); - let excluded = matched - sel.len(); - super::select::set(s, id, sel, super::select::Mode::New); - if let Some(notice) = unreadable { - s.notify_text(notice, false); - } - if excluded > 0 { - s.notify_text( - crate::notice_text::NoticeText::format( - "{n} features aren't drawn (the layer's definition query, time window or display filters hide them), and aren't selected", - [("n", excluded.to_string().into())], - ), - false, - ); - } - } - Ok(json!({"similar": rows})) -} - /// Converts text on the caller's thread for scripts and browser downloads. A streamed layer /// needs a file path so its full source can be read off the desktop frame, rather than returning /// only its loaded view. File conversions use the shared export lifecycle. diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index a4b0b58ed2..70087080bc 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -123,15 +123,15 @@ impl Session { } let CallKind::Command { id, params } = &call.kind else { return Err( - "only standalone archive, column-statistics, shape-conversion or size-by-field commands can prepare a scoped read".into() + "only standalone archive, column-statistics, similarity, shape-conversion or size-by-field commands can prepare a scoped read".into() ); }; if !matches!( id.as_str(), - "map.reloadTiles" | "map.repairTiles" | "table.statistics" | "edit.previewShapeConversion" | "layer.sizeBy" + "map.reloadTiles" | "map.repairTiles" | "table.statistics" | "data.similar" | "edit.previewShapeConversion" | "layer.sizeBy" ) { return Err( - "only standalone archive, column-statistics, shape-conversion or size-by-field commands can prepare a scoped read".into() + "only standalone archive, column-statistics, similarity, shape-conversion or size-by-field commands can prepare a scoped read".into() ); } let capture = |s: &mut Session| s.capture_read(id, params); @@ -163,11 +163,12 @@ impl Session { | "service.add" | "source.syncState" | "table.statistics" + | "data.similar" | "edit.previewShapeConversion" | "layer.sizeBy" ) && crate::cmd::edit::table_edit_in_background(command).is_none() { - return Err("only Add Data, Load All, Repair/Reload Data, Convert To Annotation, models, scripts, tile archives, service reads, topology, Source File State, Column Statistics and Size by Field prepare background work".into()); + return Err("only Add Data, Load All, Repair/Reload Data, Convert To Annotation, models, scripts, tile archives, service reads, topology, Source File State, Column Statistics, Similar and Size by Field prepare background work".into()); } let mut params = params.as_object().cloned().ok_or("read parameters must be an object")?; // Scoped previews retain the raw invocation that was approved. Their admitted owner @@ -180,6 +181,7 @@ impl Session { | "labels.convert" | "source.syncState" | "table.statistics" + | "data.similar" | "edit.previewShapeConversion" | "layer.sizeBy" ) && (command != "edit.previewShapeConversion" || self.policy_user()) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2599ab4fec..9a230812d0 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -54498,3 +54498,79 @@ fn topology_query_details_are_bounded_and_land_with_ahead_results() { .is_some() ); } + +/// Prepared Similar work shares data and mutates only on current successful completion. +/// Query/reference/time/display/schema/row changes refuse a stale answer without re-running it. +#[test] +fn similar_prepared_results_require_current_inputs() { + use crate::cmd::reads::{read_ahead, read_land}; + use rustgis_analysis::control::Control; + let mut ds = rustgis_data::Dataset::new( + "values", + rustgis_data::GeometryType::None, + vec![rustgis_data::Field::new("n", rustgis_data::FieldType::Integer)], + ); + for n in [0, 2, 10] { + ds.push(None, vec![rustgis_data::Value::Int(n)]); + } + let mut s = Session::new(Project::default()); + let id = crate::cmd::layer::add_dataset(&mut s, ds); + let l = s.map_mut().layer_mut(id).unwrap(); + l.selection = vec![0]; + l.definition_query = Some("n >= 2".into()); + let p = json!({"layer":id,"fields":["n"],"count":2}); + let expected = s.run("data.similar", &json!({"layer":id,"fields":["n"],"count":2,"select":false})).unwrap(); + let held = s.map().layer(id).unwrap().dataset.clone(); + let mark = s.notice_mark(); + let read = read_ahead(&mut s, "data.similar", &p).unwrap(); + assert!(read.reads()); + let control = Control::stoppable(); + let done = read.run(&control).unwrap(); + assert_eq!(s.map().layer(id).unwrap().selection, vec![0]); + assert!(s.notices_since(mark).is_empty()); + assert!(control.progress().is_some()); + assert_eq!(read_land(&mut s, done).unwrap(), expected); + assert_eq!(s.map().layer(id).unwrap().selection, vec![1, 2]); + assert!(held.features.shares(&s.map().layer(id).unwrap().dataset.features)); + s.map_mut().layer_mut(id).unwrap().selection = vec![0]; + let project = s.project.clone(); + for change in 0..6 { + let mut changed = Session::new(project.clone()); + let done = read_ahead(&mut changed, "data.similar", &p).unwrap().run(&Control::stoppable()).unwrap(); + let l = changed.map_mut().layer_mut(id).unwrap(); + match change { + 0 => l.definition_query = Some("n > 100".into()), + 1 => l.selection = vec![1], + 2 => l.dataset.features[0].attrs[0] = rustgis_data::Value::Int(20), + 3 => l.dataset.fields.push(rustgis_data::Field::new("extra", rustgis_data::FieldType::Text)), + 4 => l.display_filters.push(rustgis_map::effects::DisplayFilter { + name: "hidden".into(), + min_scale: None, + max_scale: None, + where_: "n > 100".into(), + }), + _ => { + let mut time = rustgis_map::time::TimeBinding::new("n"); + time.window = Some((0.0, 1000.0)); + l.time = Some(time); + } + } + let selection = changed.map().layer(id).unwrap().selection.clone(); + let mark = changed.notice_mark(); + assert!(read_land(&mut changed, done).unwrap_err().contains("changed while"), "change {change}"); + assert_eq!(changed.map().layer(id).unwrap().selection, selection); + assert!(changed.notices_since(mark).iter().all(|n| n.error), "only the refusal, no success diagnostics"); + } + let mark = s.notice_mark(); + let read = read_ahead(&mut s, "data.similar", &p).unwrap(); + assert!(read.run(&Control::cancelled_once_started()).err().is_some_and(|e| e.contains("cancelled"))); + assert_eq!(s.map().layer(id).unwrap().selection, vec![0]); + assert!(s.notices_since(mark).is_empty()); + let retry = read_ahead(&mut s, "data.similar", &p).unwrap().run(&Control::stoppable()).unwrap(); + assert_eq!(read_land(&mut s, retry).unwrap(), expected); + #[cfg(not(target_arch = "wasm32"))] + { + s.statistics_need_read_ahead(true); + assert!(s.run("data.similar", &p).unwrap_err().contains("background read queue")); + } +} diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index 136012457b..1126f6f8db 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -184,6 +184,7 @@ pub(super) fn long_commands(boundaries: bool) { s.run("layout.export", &json!({"path": out("page.pdf"), "dpi": 36, "allPages": false})).unwrap(); exercise(&s, "layer.addData", &json!({"path": out("page.pdf")}), Kind::Read, &dir.0, boundaries); exercise(&s, "table.statistics", &json!({"layer": "Cities", "field": "pop_max"}), Kind::Read, &dir.0, boundaries); + exercise(&s, "data.similar", &json!({"layer": "Cities", "row": 0, "fields": ["pop_max"], "count": 2}), Kind::Read, &dir.0, boundaries); // A Zarr point series is read on a thread of its own by the Time Series pane (#2282). It isn't // one of the queues above (it has no read-ahead), so it is run here: a local store, swept at // each of its checks in the boundary mode. It changes nothing in the project. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 461423fd9b..48495fe449 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2892,6 +2892,9 @@ impl RustGisApp { if id == "table.statistics" { return readjob::run_then(self, "table.statistics", params, Some(table::statistics_landed)); } + if id == "data.similar" { + return readjob::run(self, "data.similar", params); + } if id == "layer.sizeBy" { return readjob::run(self, "layer.sizeBy", params); } diff --git a/crates/ui-egui/src/readjob.rs b/crates/ui-egui/src/readjob.rs index ca98888036..7e64c70b0f 100644 --- a/crates/ui-egui/src/readjob.rs +++ b/crates/ui-egui/src/readjob.rs @@ -173,6 +173,7 @@ fn run_presented( | "labels.convert" | "source.syncState" | "table.statistics" + | "data.similar" | "edit.previewShapeConversion" | "layer.sizeBy" ) @@ -277,7 +278,7 @@ pub fn admitted(app: &mut RustGisApp, ahead: reads::ReadAhead, relay: rustgis_as }; let params = params.clone(); let archive = matches!(command, "map.reloadTiles" | "map.repairTiles").then(|| reads::archive_target(&app.session, ¶ms)).flatten(); - let layer = matches!(command, "table.statistics" | "layer.sizeBy") + let layer = matches!(command, "table.statistics" | "data.similar" | "layer.sizeBy") .then(|| app.session.layer_id(¶ms).ok().and_then(|id| app.session.map().layer(id)).map(|l| (l.instance_id(), l.name.clone()))) .flatten(); let what = @@ -372,6 +373,7 @@ fn called<'a>(command: &str, what: &'a str) -> &'a str { (true, "script.run") => tl_raw!("Run Script"), (true, "topology.validate") => tl_raw!("Error Inspector"), (true, "table.statistics") => tl_raw!("Column Statistics"), + (true, "data.similar") => tl_raw!("Find Similar"), (true, "layer.sizeBy") => tl_raw!("Size by Field"), (true, "service.add") => tl_raw!("Add Service Layer"), (true, _) => tl_raw!("Run Model"), @@ -500,6 +502,7 @@ fn start(app: &mut RustGisApp, mut asked: Asked, p: Value) -> Result= 2".into()); + app.reads_off_frame = true; + let p = json!({"layer":id,"fields":["n"],"count":2}); + let relay = if relay_call { + let (relay, grant, client, ahead) = paused_relay(&mut app, relay_command(1, "data.similar", p.clone())); + admitted(&mut app, ahead, relay.clone()); + Some((relay, grant, client)) + } else { + assert_eq!(app.run("data.similar", p.clone()).unwrap()["started"], "Find Similar"); + None + }; + assert_eq!(app.session.map().layer(id).unwrap().selection, vec![0]); + landed(&mut app, 60); + assert_eq!(app.session.map().layer(id).unwrap().selection, vec![1, 2]); + if let Some((relay, _grant, client)) = relay { + let mut text = String::new(); + BufReader::new(client).read_line(&mut text).unwrap(); + let answer: Value = serde_json::from_str(&text).unwrap(); + assert_eq!(answer["result"]["isError"], false, "{answer}"); + assert!(answer["result"]["content"][0]["text"].as_str().unwrap().contains("similar")); + relay.stop(); + } + app.reads.fail_spawn = true; + let before = app.session.map().layer(id).unwrap().selection.clone(); + assert!(app.run("data.similar", p).unwrap_err().contains("background worker could not start")); + assert_eq!(app.session.map().layer(id).unwrap().selection, before); + } + } + /// Statistics… counts the column on a thread of its own and keeps the answer for its window /// once it lands; a layer changed meanwhile is left, and nothing is kept. #[test] diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 4acd4ef20e..05e0e56842 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1492,6 +1492,8 @@ are selected; one notice counts those excluded. Unreadable definition queries or display filters are ignored for selection, with one notice giving the count and first parser error. `select: false` leaves selection unchanged and does not apply these filters. These workflows use the loaded resident dataset, without reloading a streamed layer's source. +On the desktop, Find Similar computes on the background read queue with progress and Cancel; +selection changes only when the completed result still matches its layer, reference and filters. Slope, in Raster Functions and the Function Editor, uses Horn's 3 × 3 gradient. Choose **Slope units**: **Degrees (0–90)** (the default, from flat to vertical) or **Percent**. From 2f5047affa4833ce511ec510789c5a115d909453 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 08:26:32 -0600 Subject: [PATCH 05/15] fix(engine): preserve prepared read ownership and completion --- crates/analysis/src/network.rs | 26 ++- crates/assistant/src/mcp.rs | 1 + crates/engine/src/cmd/design.rs | 264 +++++++++++++++--------- crates/engine/src/cmd/gp.rs | 34 ++- crates/engine/src/cmd/select.rs | 2 + crates/engine/src/cmd/similar.rs | 79 ++++--- crates/engine/src/cmd/workflows.rs | 11 +- crates/engine/src/lib.rs | 4 + crates/engine/src/policy/dispatch.rs | 17 +- crates/engine/src/tests.rs | 252 +++++++++++++++++++++- crates/engine/src/tests/cancellation.rs | 10 + crates/engine/src/undo_memory.rs | 98 ++++++++- crates/map/src/time.rs | 117 +++++++++++ crates/ui-egui/src/analysispane.rs | 82 ++++++++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/readjob.rs | 168 ++++++++++++++- docs/user-guide/analysis.md | 8 +- docs/user-guide/editing.md | 12 +- 18 files changed, 1032 insertions(+), 155 deletions(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 5cb4689fdc..14548a8e63 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -756,11 +756,19 @@ pub fn profile_fields(ds: &Dataset) -> Vec { .collect() } +/// Ranked rows and the count of other resident rows lacking a finite value in every +/// compared field. Per-field standardization still uses every finite value in that field. +#[derive(Debug)] +pub struct Similarity { + pub matches: Vec<(usize, f64)>, + pub skipped: usize, +} + /// Rows ranked by how close their numeric attributes are to a row's (z-scored Euclidean /// distance over `fields`), nearest first, excluding the row itself. Counts progress and checks /// Cancel between rows and within wide vectors. The stable library sort is one indivisible step, /// checked immediately before and after; equal-distance rows keep their original order. -pub fn similar(ds: &Dataset, row: usize, fields: &[usize], n: usize) -> Result, String> { +pub fn similar(ds: &Dataset, row: usize, fields: &[usize], n: usize) -> Result { use crate::control; control::begin(ds.features.len().saturating_mul(fields.len().saturating_mul(3).saturating_add(1))); let mut stats = Vec::with_capacity(fields.len()); @@ -810,17 +818,19 @@ pub fn similar(ds: &Dataset, row: usize, fields: &[usize], n: usize) -> Result Result f64 { @@ -1552,7 +1562,7 @@ mod tests { let p = profile_fields(&ds); assert_eq!((p[0].min, p[0].max, p[0].distinct), (Some(1.0), Some(5.0), 2)); let sim = similar(&ds, 0, &[0], 2).unwrap(); - assert_eq!(sim[0].0, 1); + assert_eq!(sim.matches[0].0, 1); let near = within(&ds, &rows, Coord::new(0.5, 0.001), 500.0); assert_eq!(near.first().map(|x| x.0), Some(0)); } diff --git a/crates/assistant/src/mcp.rs b/crates/assistant/src/mcp.rs index b1d6687a82..aa95a177f9 100644 --- a/crates/assistant/src/mcp.rs +++ b/crates/assistant/src/mcp.rs @@ -169,6 +169,7 @@ impl ArchiveBatch { | "map.repairTiles" | "table.statistics" | "data.similar" + | "topology.validate" | "edit.previewShapeConversion" | "layer.sizeBy" ) diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 0de5cb9d86..013db23fda 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -2289,69 +2289,49 @@ fn topology_rules(s: &mut Session, p: &Json) -> CmdResult { Ok(Json::Array(rules)) } -/// One topology rule as `topology.validate` checks it: the layer's rows shown (their data shared, -/// not copied) and, for a rule against another layer, that layer's. +/// One topology rule's immutable input: raw shared row storage and only the metadata needed +/// by the worker. Capturing or comparing it never evaluates a query or converts coordinates. struct TopologyInput { rule: TopologyRule, layer: String, - /// The layer in longitude/latitude, where the rules are checked, and its covering layer's. data: rustgis_data::Dataset, - rows: Vec, + query: Option, by: Option, - query_error: Option, - /// Why the layer, or its covering layer, can't be given in longitude/latitude: the check is - /// refused rather than run on coordinates of another system. - unreadable: Option, } -/// The rules as the map has them now, each with what it reads; a rule whose layer is gone is left -/// out, as it always was. Primary rows use Query, ignoring selection; covering rows use All. -/// The resolver query pass has no internal Cancel checks, as the previous visible-row pass did. -fn topology_checks(s: &Session) -> Result, String> { +/// Captures the rules and their raw inputs; a rule whose layer is gone is left out, as before. +/// Primary rows use Query, ignoring selection; covering rows use All. Row traversal, query +/// evaluation and longitude/latitude conversion belong to [`check_topology`], not this capture. +fn topology_checks(s: &Session) -> Vec { let mut inputs = Vec::new(); for rule in s.map().editing.topology.clone() { let Some(l) = s.map().layer_by_name(rule.layer()) else { continue }; - let resolved = l.resolve_rows(&l.dataset, rustgis_map::rows::Policy::Query, None)?; - let rows = match resolved.rows { - rustgis_map::rows::Rows::All => (0..l.dataset.features.len()).collect(), - rustgis_map::rows::Rows::Subset(rows) => rows, - }; - // A covering layer that is gone leaves the rule with nothing to check (its layer's + // A covering layer that is gone leaves the rule with nothing to check (its primary // latitudes are still checked). Its whole resident dataset supplies coverage, - // independently of its selection and definition query. - // Both in longitude/latitude: a copy only of a layer in another system. - let lonlat = |d: &rustgis_data::Dataset| d.in_lonlat().map(std::borrow::Cow::into_owned); - let (by, by_unreadable) = match &rule { - TopologyRule::MustBeCoveredBy { by, .. } => match s.map().layer_by_name(by).map(|b| lonlat(&b.dataset)) { - Some(Ok(d)) => (Some(d), None), - Some(Err(e)) => (None, Some(e)), - None => (None, None), - }, - _ => (None, None), - }; - let (data, unreadable) = match lonlat(&l.dataset) { - Ok(d) => (d, by_unreadable), - Err(e) => (l.dataset.clone(), Some(e)), + // independently of selection, definition query, display filters and time window. + let by = match &rule { + TopologyRule::MustBeCoveredBy { by, .. } => s.map().layer_by_name(by).map(|b| b.dataset.clone()), + _ => None, }; - inputs.push(TopologyInput { rule, layer: l.name.clone(), data, rows, by, query_error: resolved.query_error, unreadable }); + inputs.push(TopologyInput { rule, layer: l.name.clone(), data: l.dataset.clone(), query: l.definition_query.clone(), by }); } - Ok(inputs) + inputs } -/// Whether two layers' data are the same: the same rows (shared, not compared one by one), fields -/// and geometry type. +/// Whether two raw inputs have the same shared rows, schema, geometry kind and coordinate +/// system. No row traversal or coordinate conversion is needed on the window thread. fn same_data(a: &rustgis_data::Dataset, b: &rustgis_data::Dataset) -> bool { - a.features.shares(&b.features) && a.fields == b.fields && a.geometry_type == b.geometry_type + a.features.shares(&b.features) && a.fields == b.fields && a.geometry_type == b.geometry_type && a.coord_crs() == b.coord_crs() } -/// Whether `was` (what a check read on another thread) is what the rules read now. +/// Whether the captured rules and metadata still match. A changed query is stale even when it +/// would happen to match the same rows, so landing never needs to evaluate it again. fn same_topology(was: &[TopologyInput], now: &[TopologyInput]) -> bool { was.len() == now.len() && was.iter().zip(now).all(|(a, b)| { a.rule == b.rule && a.layer == b.layer - && a.rows == b.rows - && a.query_error == b.query_error + && a.query == b.query && same_data(&a.data, &b.data) && match (&a.by, &b.by) { (Some(x), Some(y)) => same_data(x, y), @@ -2361,35 +2341,92 @@ fn same_topology(was: &[TopologyInput], now: &[TopologyInput]) -> bool { }) } -/// Checks each rule, in order, a result for each (a cancelled run is an error): a layer with a -/// latitude out of range is an error, as it always was. Each check looks at Cancel between features -/// and counts its progress, except the gaps check's union of every polygon, one step; in a run that -/// can be cancelled it takes no work limit (see `rustgis_analysis::topology`). -fn check_topology(inputs: &[TopologyInput], tol: f64) -> Result, String> { +/// Fully materialized worker output. Applying it moves the issue vector; the window thread +/// never visits every feature error. Query diagnostics follow captured rule order. +struct TopologyChecked { + errors: Vec, + incomplete: Vec, + skipped: Vec, + query_errors: Vec>, +} + +/// Checks each rule and its query on the worker, with Cancel between rows/rules and counted +/// query progress. Each rule's row indices and converted data are released before the next. +/// One row's expression evaluation, coordinate conversion, latitude validation and a gaps +/// check's polygon union are indivisible library steps, checked around them; geometric checks +/// otherwise look between features. +/// A cancellable run takes no work limit (see `rustgis_analysis::topology`). +fn check_topology(inputs: &[TopologyInput], tol: f64) -> Result { use rustgis_analysis::topology as t; - let mut found = Vec::with_capacity(inputs.len()); + let cancelled = || "the topology check was cancelled".to_string(); + let mut errors = Vec::new(); + let mut incomplete = Vec::new(); + let mut skipped = Vec::new(); + let mut query_errors = Vec::with_capacity(inputs.len()); for i in inputs { - // A cancelled run stops between rules too (a gaps rule's union doesn't look), as an error, - // so no result short of its rules is ever taken. - rustgis_data::progress::check().map_err(|_| "the topology check was cancelled".to_string())?; - if let Some(e) = &i.unreadable { - return Err(format!("{}: {e}", i.layer)); - } - rustgis_analysis::validate_latitudes(&i.data, i.rows.iter().copied())?; - found.push(match (&i.rule, &i.by) { - (TopologyRule::MustNotOverlap { .. }, _) => t::overlaps(&i.data, &i.rows), - (TopologyRule::MustNotHaveGaps { .. }, _) => t::gaps(&i.data, &i.rows), - (TopologyRule::MustNotSelfIntersect { .. }, _) => t::self_intersections(&i.data, &i.rows), - (TopologyRule::MustNotHaveDangles { .. }, _) => t::dangles(&i.data, &i.rows, tol), + rustgis_data::progress::check().map_err(|_| cancelled())?; + let (query, error) = match rustgis_data::rows::Query::compile(i.query.as_deref(), &i.data) { + Ok(query) => (Some(query), None), + Err(error) => (None, Some(error)), + }; + let mut rows = Vec::new(); + let env = rustgis_data::query::Env::default(); + rustgis_data::progress::begin(i.data.features.len()); + for row in 0..i.data.features.len() { + rustgis_data::progress::step(1).map_err(|_| cancelled())?; + if query.as_ref().is_none_or(|q| q.matches(&i.data, row, &env)) { + rows.push(row); + } + } + // Preserve the existing coordinate boundary and error precedence. A primary failure + // wins over a covering-layer failure; neither can run on coordinates of another system. + rustgis_data::progress::check().map_err(|_| cancelled())?; + let lonlat = |d: &rustgis_data::Dataset| d.in_lonlat().map(std::borrow::Cow::into_owned); + let by = i.by.as_ref().map(lonlat).transpose(); + let data = lonlat(&i.data); + rustgis_data::progress::check().map_err(|_| cancelled())?; + let data = data.map_err(|e| format!("{}: {e}", i.layer))?; + let by = by.map_err(|e| format!("{}: {e}", i.layer))?; + rustgis_analysis::validate_latitudes(&data, rows.iter().copied())?; + rustgis_data::progress::check().map_err(|_| cancelled())?; + let checked = match (&i.rule, &by) { + (TopologyRule::MustNotOverlap { .. }, _) => t::overlaps(&data, &rows), + (TopologyRule::MustNotHaveGaps { .. }, _) => t::gaps(&data, &rows), + (TopologyRule::MustNotSelfIntersect { .. }, _) => t::self_intersections(&data, &rows), + (TopologyRule::MustNotHaveDangles { .. }, _) => t::dangles(&data, &rows, tol), (TopologyRule::MustBeCoveredBy { .. }, Some(by)) => { rustgis_analysis::validate_latitudes(by, 0..by.features.len())?; - t::not_covered(&i.data, &i.rows, by) + rustgis_data::progress::check().map_err(|_| cancelled())?; + t::not_covered(&data, &rows, by) } // Its covering layer is gone: nothing checked, nothing said, as it always was. (TopologyRule::MustBeCoveredBy { .. }, None) => t::Checked { errors: Vec::new(), complete: true, skipped: 0 }, - }); + }; + rustgis_data::progress::check().map_err(|_| cancelled())?; + if !checked.complete || checked.skipped > 0 { + incomplete.push(i.rule.label().to_string()); + } + if checked.skipped > 0 { + // The features left out are the covering layer's. + let of = match &i.rule { + TopologyRule::MustBeCoveredBy { by, .. } => by.as_str(), + _ => i.layer.as_str(), + }; + skipped.push(format!("{} on '{}': {} feature(s) of '{}'", i.rule.label(), i.layer, checked.skipped, of)); + } + for issue in checked.errors { + rustgis_data::progress::check().map_err(|_| cancelled())?; + errors.push(crate::TopologyIssue { + rule: i.rule.label().to_string(), + layer: i.layer.clone(), + rows: issue.rows, + lon: issue.at.x, + lat: issue.at.y, + }); + } + query_errors.push(error); } - Ok(found) + Ok(TopologyChecked { errors, incomplete, skipped, query_errors }) } /// The tolerance `topology.validate` checks dangles with, in metres. @@ -2402,22 +2439,37 @@ const TOPOLOGY_AHEAD: &str = "topology.validate"; /// A topology check made on a thread of its own ([`topology_ahead`]), with what it read. struct TopologyAhead { + opened: u64, + map: u64, inputs: Vec, tol: f64, - found: Result, String>, + found: Result, + _retained: crate::undo_memory::ReadRows, +} + +/// Queue lifetime accounting shares the same allocation identities as live rows and Undo. +fn retain_topology(s: &Session, inputs: &[TopologyInput]) -> crate::undo_memory::ReadRows { + let rows = inputs + .iter() + .flat_map(|input| std::iter::once(&input.data).chain(input.by.as_ref())) + .map(|data| data.features.allocation_key()) + .collect(); + s.undo_memory.readers().retain(rows) } /// The check `topology.validate` makes before it runs in the desktop app (#1291, #1562): every /// rule on a thread of its own, with progress and Cancel and no work limit. The command takes it /// as it lands when the rules and their layers are still the ones checked. pub(crate) fn topology_ahead(s: &Session, p: &Json) -> Option { - let (inputs, tol) = (topology_checks(s).ok()?, topology_tolerance(p)); + let (inputs, tol) = (topology_checks(s), topology_tolerance(p)); + let (opened, map) = (s.opened, s.map().instance_id()); if inputs.is_empty() { return None; } + let retained = retain_topology(s, &inputs); Some(super::reads::ahead("Error Inspector", TOPOLOGY_AHEAD.to_string(), move || { let found = check_topology(&inputs, tol); - TopologyAhead { inputs, tol, found } + TopologyAhead { opened, map, inputs, tol, found, _retained: retained } })) } @@ -2427,16 +2479,59 @@ pub(crate) fn topology_ahead(s: &Session, p: &Json) -> Option CmdResult { let tol = topology_tolerance(p); - let inputs = topology_checks(s)?; - let found = match super::reads::take::(s, TOPOLOGY_AHEAD) { - Some(ahead) if ahead.tol == tol && same_topology(&ahead.inputs, &inputs) => ahead.found?, + let inputs = topology_checks(s); + let ahead = super::reads::take::(s, TOPOLOGY_AHEAD); + #[cfg(not(target_arch = "wasm32"))] + let ahead = match ahead { + Some(ahead) => Some(ahead), + None => super::gp::take_read::(s, TOPOLOGY_AHEAD, p)?, + }; + #[cfg(not(target_arch = "wasm32"))] + if ahead.is_none() && !inputs.is_empty() && s.statistics_window_thread == Some(std::thread::current().id()) { + return Err( + "Topology validation needs the desktop background read queue; run Error Inspector or a direct MCP topology.validate request" + .into(), + ); + } + let found = match ahead { + Some(ahead) + if ahead.opened == s.opened + && ahead.map == s.map().instance_id() + && ahead.tol == tol + && same_topology(&ahead.inputs, &inputs) => + { + ahead.found + } // Checking again here would hold the window: the check made on its thread is dropped. Some(_) => return Err("the topology rules or their layers changed while they were checked: validate again".into()), - None => check_topology(&inputs, tol)?, + None => check_topology(&inputs, tol), }; + #[cfg(not(target_arch = "wasm32"))] + if matches!(s.tools_ahead, Some(super::gp::Ahead::Recording(_))) { + // No replayable prefix command reads the Error Inspector's issue list. Retain it once + // for live delivery, rather than cloning a potentially large vector into the copy. + let answer = found + .as_ref() + .map(|checked| { + let first: Vec = checked + .errors + .iter() + .take(1000) + .map(|e| json!({"rule": e.rule, "layer": e.layer, "rows": e.rows, "lon": e.lon, "lat": e.lat})) + .collect(); + json!({"errors": checked.errors.len(), "first": first, "incomplete": checked.incomplete}) + }) + .map_err(Clone::clone); + let retained = retain_topology(s, &inputs); + let recorded = TopologyAhead { opened: s.opened, map: s.map().instance_id(), inputs, tol, found, _retained: retained }; + super::gp::record_read(s, TOPOLOGY_AHEAD, p, recorded); + return answer; + } + let TopologyChecked { errors, incomplete, skipped, query_errors } = found?; // Rules whose layer, or covering layer, isn't on the map are checked for nothing: said. let unchecked: Vec = s .map() @@ -2453,33 +2548,6 @@ fn topology_validate(s: &mut Session, p: &Json) -> CmdResult { unchecked.join(", ") )); } - let mut errors = Vec::new(); - // Rules whose check stopped early (an error or work limit), or measured some part more coarsely - // than it's meant to (a line winding round a pole many times): their counts may be off. - let mut incomplete = Vec::new(); - // Polygons a check had to leave out, by rule. - let mut skipped = Vec::new(); - for (i, found) in inputs.iter().zip(found) { - let rule = &i.rule; - if !found.complete || found.skipped > 0 { - incomplete.push(rule.label().to_string()); - } - if found.skipped > 0 { - // The features left out are the covering layer's. - let of = match rule { - TopologyRule::MustBeCoveredBy { by, .. } => by.as_str(), - _ => i.layer.as_str(), - }; - skipped.push(format!("{} on '{}': {} feature(s) of '{}'", rule.label(), i.layer, found.skipped, of)); - } - errors.extend(found.errors.into_iter().map(|e| crate::TopologyIssue { - rule: rule.label().to_string(), - layer: i.layer.clone(), - rows: e.rows, - lon: e.at.x, - lat: e.at.y, - })); - } if !incomplete.is_empty() { s.warn(format!( "{} topology rule(s) weren't checked completely ({}): a check stopped early, left out a polygon, or measured a line winding round a pole coarsely, so their counts may be off", @@ -2502,8 +2570,8 @@ fn topology_validate(s: &mut Session, p: &Json) -> CmdResult { use crate::notice_text::NoticeText; let mut seen = std::collections::HashSet::new(); let mut details = Vec::new(); - for input in &inputs { - if let Some(error) = &input.query_error + for (input, error) in inputs.iter().zip(&query_errors) { + if let Some(error) = error && seen.insert(&input.layer) && details.len() < 5 { diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 967802c149..ac01f00872 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -809,6 +809,35 @@ pub(crate) struct ToolAhead { pub(crate) enum RanAhead { Tool(Box), Table(Box), + Read(ScriptRead), +} + +#[cfg(not(target_arch = "wasm32"))] +/// A read-only command's prepared result, replayed by its ordinary admitted handler. +pub(crate) struct ScriptRead { + command: &'static str, + params: Value, + value: Box, +} + +#[cfg(not(target_arch = "wasm32"))] +/// Keeps a typed worker result in prefix order for the live command's authorized replay. +pub(crate) fn record_read(s: &mut Session, command: &'static str, params: &Value, value: T) { + if let Some(Ahead::Recording(ran)) = &mut s.tools_ahead { + ran.push(RanAhead::Read(ScriptRead { command, params: params.clone(), value: Box::new(value) })); + } +} + +#[cfg(not(target_arch = "wasm32"))] +/// A replayed read must consume its recorded result, never recompute after an earlier mismatch. +pub(crate) fn take_read(s: &mut Session, command: &str, params: &Value) -> Result, String> { + let Some(Ahead::Taking(ran)) = &mut s.tools_ahead else { return Ok(None) }; + let mismatch = || "the script's prepared read changed: run the script again".to_string(); + let Some(RanAhead::Read(next)) = ran.pop_front() else { return Err(mismatch()) }; + if next.command != command || next.params != *params { + return Err(mismatch()); + } + next.value.downcast::().map(|value| Some(*value)).map_err(|_| mismatch()) } #[cfg(not(target_arch = "wasm32"))] @@ -862,6 +891,8 @@ pub(crate) struct RanAheads { tools: Vec, files: Vec, zones: Vec, + // The copy's initial project can outlive history while queued or waiting to replay. + pub(crate) retained: Option, } #[cfg(not(target_arch = "wasm32"))] @@ -870,6 +901,7 @@ pub(crate) struct RanAheads { /// files read ahead the same way. Restored on every path, a panic included (raised again), so no /// later run takes them. pub(crate) fn taking(s: &mut Session, ran: RanAheads, run: impl FnOnce(&mut Session) -> T) -> T { + let _retained = ran.retained; s.tools_ahead = Some(Ahead::Taking(ran.tools.into())); s.files_ahead = Some(FilesAhead::Taking(ran.files.into())); s.zones_ahead = Some(super::imagery::ZonesAhead::Taking(ran.zones.into())); @@ -895,7 +927,7 @@ pub(crate) fn ran_ahead(s: &mut Session) -> RanAheads { Some(super::imagery::ZonesAhead::Recording(read)) => read, _ => Vec::new(), }; - RanAheads { tools, files, zones } + RanAheads { tools, files, zones, retained: None } } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 44c8d95114..3997854f43 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -40,6 +40,7 @@ pub fn commands() -> Vec { .params(r#"{"layer"?, "rows": [number], "mode"?}"#), C::new("select.clear", "Clear", "Home › Selection", |s, _| { s.map_mut().clear_selection(); + s.selection_generation = s.selection_generation.wrapping_add(1); Ok(Value::Null) }).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_selection), @@ -125,6 +126,7 @@ fn area_mode(p: &Value) -> Result { /// Applies a selection to one layer (New clears the others too, like desktop GIS). pub fn set(s: &mut Session, id: u32, rows: Vec, m: Mode) { + s.selection_generation = s.selection_generation.wrapping_add(1); if m == Mode::New { s.map_mut().clear_selection(); } diff --git a/crates/engine/src/cmd/similar.rs b/crates/engine/src/cmd/similar.rs index 1fbf2a88ae..ab4cdd2527 100644 --- a/crates/engine/src/cmd/similar.rs +++ b/crates/engine/src/cmd/similar.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; use crate::notice_text::NoticeText; use crate::{CmdResult, Session}; -#[derive(PartialEq)] +#[derive(Clone, PartialEq)] struct Target { id: u32, row: usize, @@ -18,15 +18,15 @@ struct Target { } /// The map filters affecting output selection, independently of the ranking population. -#[derive(PartialEq)] +#[derive(Clone, PartialEq)] struct Visibility { query: Option, filters: Vec, time: Option<(String, Option<(f64, f64)>)>, - scale: f64, } /// Captures only this layer's metadata and shared row storage, never a project/session copy. +#[derive(Clone)] struct Input { target: Target, opened: u64, @@ -35,6 +35,8 @@ struct Input { name: String, data: Dataset, visibility: Option, + selection_generation: u64, + _retained: crate::undo_memory::ReadRows, } impl Input { @@ -58,9 +60,8 @@ impl Input { let select = super::b(p, "select").unwrap_or(true); let visibility = select.then(|| Visibility { query: l.definition_query.clone(), - filters: l.display_filters.clone(), + filters: l.display_filters.iter().filter(|filter| filter.applies(s.scale())).cloned().collect(), time: l.time.as_ref().map(|t| (t.field.clone(), t.window)), - scale: s.scale(), }); Ok(Self { target: Target { id, row, fields, count, select }, @@ -70,6 +71,8 @@ impl Input { name: l.name.clone(), data: l.dataset.clone(), visibility, + selection_generation: s.selection_generation, + _retained: s.undo_memory.readers().retain(vec![l.dataset.features.allocation_key()]), }) } @@ -88,12 +91,14 @@ impl Input { } } +#[derive(Clone)] struct Done { answer: Value, selection: Option>, notices: Vec, } +#[derive(Clone)] struct Ahead { input: Input, done: Result, @@ -101,11 +106,16 @@ struct Ahead { /// Filters the bounded result/reference rows with cancellation, without a layer-wide mask. fn keep(rows: Vec, mut matches: impl FnMut(usize) -> bool) -> Result, String> { + try_keep(rows, |row| Ok(matches(row))) +} + +/// Filters bounded result rows while preserving predicate errors, including cancellation. +fn try_keep(rows: Vec, mut matches: impl FnMut(usize) -> Result) -> Result, String> { rustgis_data::progress::begin(rows.len()); let mut kept = Vec::with_capacity(rows.len()); for row in rows { rustgis_data::progress::step(1).map_err(|e| e.to_string())?; - if matches(row) { + if matches(row)? { kept.push(row); } } @@ -113,14 +123,22 @@ fn keep(rows: Vec, mut matches: impl FnMut(usize) -> bool) -> Result Result { let t = &input.target; - let found = rustgis_analysis::network::similar(&input.data, t.row, &t.fields, t.count)?; + let ranked = rustgis_analysis::network::similar(&input.data, t.row, &t.fields, t.count)?; + let mut notices = Vec::new(); + if ranked.skipped > 0 { + notices.push(NoticeText::format( + "Candidate features skipped: {count} on {layer} (missing or non-finite compared values)", + [("count", ranked.skipped.to_string().into()), ("layer", input.name.clone().into())], + )); + } + let found = ranked.matches; let answer = json!({"similar": found.iter().map(|(r, d)| json!({"row": r, "distance": d})).collect::>()}); - let Some(v) = &input.visibility else { return Ok(Done { answer, selection: None, notices: Vec::new() }) }; + let Some(v) = &input.visibility else { return Ok(Done { answer, selection: None, notices }) }; let mut rows: Vec = found.iter().map(|(r, _)| *r).collect(); rows.push(t.row); let matched = rows.len(); @@ -138,22 +156,16 @@ fn gather(input: &Input) -> Result { Err(e) => error(e), } if let Some((field, Some(window))) = &v.time { - let mut time = rustgis_map::time::TimeBinding::new(field); - time.window = Some(*window); - let mask = time.keeps(&input.data); - rustgis_data::progress::check().map_err(|e| e.to_string())?; - if let Some(mask) = mask { - rows = keep(rows, |r| mask.get(r) == Some(&true))?; - } + let time = rustgis_map::time::candidate_window(&input.data, field, *window).map_err(|e| e.to_string())?; + rows = try_keep(rows, |row| time.keeps(row).map_err(|e| e.to_string()))?; } - for filter in v.filters.iter().filter(|f| f.applies(v.scale)) { + for filter in &v.filters { rustgis_data::progress::check().map_err(|e| e.to_string())?; match query::parse_fields(&filter.where_, &input.data) { Ok(q) => rows = keep(rows, |r| query::matches(&q, &input.data, r, &query::Env::default()))?, Err(e) => error(e), } } - let mut notices = Vec::new(); if let Some(error) = first { notices.push(NoticeText::format( "{layer}: selecting without unreadable query/filter settings ({count}). First parser error: {error}", @@ -189,16 +201,35 @@ pub(super) fn run(s: &mut Session, p: &Value) -> CmdResult { let input = Input::resolve(s, p)?; let ahead = super::reads::take::(s, "data.similar"); #[cfg(not(target_arch = "wasm32"))] + let ahead = match ahead { + Some(ahead) => Some(ahead), + None => super::gp::take_read::(s, "data.similar", p)?, + }; + #[cfg(not(target_arch = "wasm32"))] if ahead.is_none() && s.statistics_window_thread == Some(std::thread::current().id()) { return Err("Similarity needs the desktop background read queue; run Find Similar or a direct MCP data.similar request".into()); } - let done = match ahead { - Some(a) if a.input.same(&input) => a.done?, + let (done, selection_generation) = match ahead { + Some(a) if a.input.same(&input) => (a.done, a.input.selection_generation), Some(_) => return Err("the layer, reference or map filters changed while similarity was computed: ask again".into()), - None => gather(&input)?, + None => (gather(&input), input.selection_generation), }; + #[cfg(not(target_arch = "wasm32"))] + if matches!(s.tools_ahead, Some(super::gp::Ahead::Recording(_))) { + super::gp::record_read(s, "data.similar", p, Ahead { input: input.clone(), done: done.clone() }); + } + let done = done?; if let Some(rows) = done.selection { - super::select::set(s, input.target.id, rows, super::select::Mode::New); + if selection_generation == s.selection_generation { + super::select::set(s, input.target.id, rows, super::select::Mode::New); + } else { + s.notify_text( + NoticeText::term( + "Selection changed while similarity was computed; its ranking is returned without replacing the current selection", + ), + false, + ); + } } for notice in done.notices { s.notify_text(notice, false); diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index dacc2dec7a..ba85e7622e 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -820,9 +820,12 @@ const SCRIPT_AHEAD: &str = "script.run"; pub(crate) fn ahead_on_copy(s: &Session, command: &'static str, p: &Value) -> super::reads::ReadWork { let name = if command == SCRIPT_AHEAD { "Run Script" } else { "Run Model" }; let (project, trusted) = (s.project.clone(), s.trusted_models.clone()); + let readers = s.undo_memory.readers(); + let retained = readers.retain(crate::undo_memory::allocations(&project)); // The copy follows the extensions turned on or off here (#1752). let extensions = s.extensions().clone(); let (view_size, active_layer, opened, p) = (s.view_size, s.active_layer, s.opened, p.clone()); + let selection_generation = s.selection_generation; // What its tools ask of servers and files goes in this session's Diagnostics, as when they // run here: the run here takes their results and asks nothing. let requests = s.diagnostics.capture(); @@ -834,15 +837,19 @@ pub(crate) fn ahead_on_copy(s: &Session, command: &'static str, p: &Value) -> su copy.view_size = view_size; copy.active_layer = active_layer; copy.opened = opened; + copy.selection_generation = selection_generation; // The copy shares this session's rows, which this session already counts in what the // process holds (#2431): it neither measures nor adds them again. copy.undo_memory.memory = None; + copy.undo_memory.use_readers(readers); copy.sync_policy_generation(); copy.tools_ahead = Some(super::gp::Ahead::Recording(Vec::new())); copy.files_ahead = Some(super::gp::FilesAhead::Recording(Vec::new())); copy.zones_ahead = Some(super::imagery::ZonesAhead::Recording(Vec::new())); let _ = copy.run(command, &p); - super::gp::ran_ahead(&mut copy) + let mut ran = super::gp::ran_ahead(&mut copy); + ran.retained = Some(retained); + ran }) } @@ -922,6 +929,8 @@ pub(crate) const ON_A_COPY: &[&str] = &[ "gp.spatialJoin", "gp.zonalStats", "gp.env", + "data.similar", + "topology.validate", "select.all", "select.atPoint", "select.byAttributes", diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 33f55f6b03..4d6c1d8dc6 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -787,6 +787,9 @@ pub struct Session { pub registry: Registry, /// Bumped on every change so views can cache. pub revision: u64, + /// Runtime selection intent, including changes on other layers that a new selection clears. + /// Mutation dispatch conservatively advances it too; view-only commands leave it alone. + pub(crate) selection_generation: u64, /// Bumped each time another project replaces this one (new, open, sample, template), however /// the command came (the app, an agent, a script): the interface drops what it kept for the /// old one. @@ -1307,6 +1310,7 @@ impl Session { layout_arrangements: serde_json::Map::new(), registry: Registry { commands: cmd::all() }, revision: 1, + selection_generation: 0, opened: 0, exchange: None, tool: Tool::Explore, diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 70087080bc..74da061535 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -123,15 +123,21 @@ impl Session { } let CallKind::Command { id, params } = &call.kind else { return Err( - "only standalone archive, column-statistics, similarity, shape-conversion or size-by-field commands can prepare a scoped read".into() + "only standalone archive, column-statistics, similarity, topology, shape-conversion or size-by-field commands can prepare a scoped read".into() ); }; if !matches!( id.as_str(), - "map.reloadTiles" | "map.repairTiles" | "table.statistics" | "data.similar" | "edit.previewShapeConversion" | "layer.sizeBy" + "map.reloadTiles" + | "map.repairTiles" + | "table.statistics" + | "data.similar" + | "topology.validate" + | "edit.previewShapeConversion" + | "layer.sizeBy" ) { return Err( - "only standalone archive, column-statistics, similarity, shape-conversion or size-by-field commands can prepare a scoped read".into() + "only standalone archive, column-statistics, similarity, topology, shape-conversion or size-by-field commands can prepare a scoped read".into() ); } let capture = |s: &mut Session| s.capture_read(id, params); @@ -979,6 +985,11 @@ impl Session { Txn::Shared => run(self), }; self.url_completion_landed(spec.id, ¶ms, &result); + if result.is_ok() && spec.mutates { + // Some edits replace selections without going through select::set. A pending + // read must preserve the later intent, even when this edit touched another layer. + self.selection_generation = self.selection_generation.wrapping_add(1); + } result } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9a230812d0..fa8ff2b143 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -54356,13 +54356,17 @@ fn resident_data_diagnostics_keep_all_rows_despite_map_filters() { assert_eq!(s.map().layer(id).unwrap().selection, selection, "{query:?}"); let notices = s.notices_since(mark); let unreadable = query == Some("missing = 1"); - assert_eq!(notices.len(), usize::from(excluded > 0) + usize::from(unreadable)); + assert_eq!(notices.len(), 1 + usize::from(excluded > 0) + usize::from(unreadable)); + assert!(notices.iter().any(|n| n.text.starts_with("Candidate features skipped: 1"))); if excluded > 0 { - assert!(notices[0].text.starts_with(&format!("{excluded} features aren't drawn"))); + assert!(notices.iter().any(|n| n.text.starts_with(&format!("{excluded} features aren't drawn")))); } if unreadable { - assert!(notices[0].text.contains("selecting without unreadable query/filter settings (1)")); - assert!(notices[0].text.contains("missing")); + assert!( + notices + .iter() + .any(|n| n.text.contains("selecting without unreadable query/filter settings (1)") && n.text.contains("missing")) + ); } } let l = s.map_mut().layer_mut(id).unwrap(); @@ -54376,7 +54380,7 @@ fn resident_data_diagnostics_keep_all_rows_despite_map_filters() { let mark = s.notice_mark(); assert_eq!(s.run("data.similar", &json!({"layer": id, "row": 0, "fields": ["n"], "count": 2})).unwrap(), expected); assert_eq!(s.map().layer(id).unwrap().selection, vec![2]); - assert!(s.notices_since(mark)[0].text.starts_with("2 features aren't drawn")); + assert!(s.notices_since(mark).iter().any(|n| n.text.starts_with("2 features aren't drawn"))); let l = s.map_mut().layer_mut(id).unwrap(); l.display_filters[0].where_ = "missing = 1".into(); l.display_filters.push(rustgis_map::effects::DisplayFilter { @@ -54389,9 +54393,11 @@ fn resident_data_diagnostics_keep_all_rows_despite_map_filters() { assert_eq!(s.run("data.similar", &json!({"layer": id, "row": 0, "fields": ["n"], "count": 2})).unwrap(), expected); assert_eq!(s.map().layer(id).unwrap().selection, vec![0, 1, 2]); let notices = s.notices_since(mark); - assert_eq!(notices.len(), 1); - assert!(notices[0].text.contains("selecting without unreadable query/filter settings (2)")); - assert!(notices[0].text.contains("missing")); + assert_eq!(notices.len(), 2); + assert!(notices.iter().any(|n| n.text.starts_with("Candidate features skipped: 1"))); + assert!( + notices.iter().any(|n| n.text.contains("selecting without unreadable query/filter settings (2)") && n.text.contains("missing")) + ); assert!(held.features.shares(&s.map().layer(id).unwrap().dataset.features), "readers and selection retain shared rows"); } @@ -54574,3 +54580,233 @@ fn similar_prepared_results_require_current_inputs() { assert!(s.run("data.similar", &p).unwrap_err().contains("background read queue")); } } + +/// An unusable reference is an error before selection or success notices are applied. +#[test] +fn similar_invalid_reference_is_refused_without_selecting() { + use rustgis_data::{Dataset, Field, FieldType, GeometryType, Value as V}; + let mut ds = Dataset::new("values", GeometryType::None, vec![Field::new("n", FieldType::Double)]); + for n in [0.0, 2.0, 10.0] { + ds.push(None, vec![V::Float(n)]); + } + let mut s = Session::new(Project::default()); + let id = crate::cmd::layer::add_dataset(&mut s, ds); + let p = json!({"layer":id,"row":0,"fields":["n"],"count":2}); + for value in [V::Null, V::Float(f64::NAN), V::Float(f64::INFINITY)] { + let l = s.map_mut().layer_mut(id).unwrap(); + l.dataset.features[0].attrs[0] = value; + l.selection = vec![2]; + let mark = s.notice_mark(); + assert!(s.run("data.similar", &p).unwrap_err().contains("reference row needs a finite numeric value")); + assert_eq!(s.map().layer(id).unwrap().selection, vec![2]); + assert!(s.notices_since(mark).iter().all(|n| n.error)); + } + s.map_mut().layer_mut(id).unwrap().dataset.features[0].attrs[0] = V::Float(0.0); + let mark = s.notice_mark(); + assert_eq!(s.run("data.similar", &p).unwrap()["similar"].as_array().unwrap().len(), 2); + assert!(s.notices_since(mark).is_empty()); +} + +/// Incomplete candidates are counted even without output selection; clean inputs stay quiet. +#[test] +fn similar_reports_skipped_candidates() { + use rustgis_data::{Dataset, Field, FieldType, GeometryType, Value as V}; + let mut ds = Dataset::new("values", GeometryType::None, vec![Field::new("n", FieldType::Double)]); + for value in [V::Float(0.0), V::Float(2.0), V::Null, V::Float(f64::NAN), V::Float(f64::INFINITY)] { + ds.push(None, vec![value]); + } + let mut s = Session::new(Project::default()); + let id = crate::cmd::layer::add_dataset(&mut s, ds); + s.map_mut().layer_mut(id).unwrap().selection = vec![4]; + let p = json!({"layer":id,"row":0,"fields":["n"],"count":4,"select":false}); + let mark = s.notice_mark(); + let result = s.run("data.similar", &p).unwrap(); + assert_eq!(result["similar"].as_array().unwrap().len(), 1); + assert_eq!(result["similar"][0]["row"], 1); + assert_eq!(s.map().layer(id).unwrap().selection, vec![4]); + let notices = s.notices_since(mark); + assert_eq!(notices.len(), 1); + assert!(notices[0].text.starts_with("Candidate features skipped: 3")); + for row in 2..5 { + s.map_mut().layer_mut(id).unwrap().dataset.features[row].attrs[0] = V::Float((row * 2) as f64); + } + let mark = s.notice_mark(); + assert_eq!(s.run("data.similar", &p).unwrap()["similar"].as_array().unwrap().len(), 4); + assert!(s.notices_since(mark).is_empty()); + assert_eq!(s.map().layer(id).unwrap().selection, vec![4]); +} + +/// Query changes are checked by metadata, even if they would match identical rows; replacing +/// the map with shared source rows also invalidates its worker. No heavy check runs inline. +#[test] +fn topology_prepared_queries_require_current_map_and_metadata() { + use crate::cmd::reads::{read_ahead, read_land}; + use rustgis_analysis::control::Control; + use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value as Cell}; + let mut s = Session::new(Project::default()); + let mut ds = Dataset::new("points", GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); + ds.push(Some(Geometry::Point(rustgis_geom::Coord::new(1.0, 2.0))), vec![Cell::Int(1)]); + let id = crate::cmd::layer::add_dataset(&mut s, ds); + s.map_mut().layer_mut(id).unwrap().definition_query = Some("n >= 0".into()); + s.run("topology.rules", &json!({"add":{"rule":"mustNotSelfIntersect","layer":"points"}})).unwrap(); + let p = json!({}); + let read = read_ahead(&mut s, "topology.validate", &p).unwrap().run(&Control::stoppable()).unwrap(); + s.map_mut().layer_mut(id).unwrap().definition_query = Some("n >= -1".into()); + assert!(read_land(&mut s, read).unwrap_err().contains("changed while")); + assert!(s.topology_errors.is_empty()); + let read = read_ahead(&mut s, "topology.validate", &p).unwrap().run(&Control::stoppable()).unwrap(); + let original = s.map().layer(id).unwrap().dataset.clone(); + let rules = s.map().editing.topology.clone(); + let mut replacement = Project::default(); + let next = replacement.map_mut().add_dataset(original); + replacement.map_mut().layer_mut(next).unwrap().definition_query = Some("n >= -1".into()); + replacement.map_mut().editing.topology = rules; + s.project = replacement; + assert!(read_land(&mut s, read).is_err(), "a replacement map must not take the original map's result"); + assert!(s.topology_errors.is_empty()); + assert_eq!(s.run("topology.validate", &p).unwrap()["errors"], 0, "an immediate retry succeeds"); + #[cfg(not(target_arch = "wasm32"))] + { + s.statistics_need_read_ahead(true); + assert!(s.run("topology.validate", &p).unwrap_err().contains("background read queue")); + let read = read_ahead(&mut s, "topology.validate", &p).unwrap().run(&Control::stoppable()).unwrap(); + assert_eq!(read_land(&mut s, read).unwrap()["errors"], 0); + let mut empty = Session::new(Project::default()); + empty.statistics_need_read_ahead(true); + assert_eq!(empty.run("topology.validate", &p).unwrap()["errors"], 0, "no rules needs no worker"); + } +} + +/// Small shared fixture for queued ranking, script replay and retained-reader regressions. +fn similar_lifecycle_session() -> (Session, u32) { + use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value as V}; + let mut ds = Dataset::new("values", GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); + for n in [0, 2, 10] { + ds.push(Some(Geometry::Point(rustgis_geom::Coord::new(n as f64, 0.0))), vec![V::Int(n)]); + } + let mut s = Session::new(Project::default()); + let id = crate::cmd::layer::add_dataset(&mut s, ds); + (s, id) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_script_replays_similar_and_topology_before_the_following_line() { + use crate::cmd::reads::{read_ahead, read_land}; + use rustgis_analysis::control::Control; + let (mut s, id) = similar_lifecycle_session(); + s.run("topology.rules", &json!({"add":{"rule":"mustNotSelfIntersect","layer":"values"}})).unwrap(); + s.run("select.rows", &json!({"layer":id,"rows":[0]})).unwrap(); + s.statistics_need_read_ahead(true); + let depth = s.undo_depth(); + let p = json!({"script": concat!( + "topology.validate {}\n", + "data.similar {\"layer\":\"values\",\"fields\":[\"n\"],\"count\":1}\n", + "select.layerFromSelection {\"layer\":\"values\"}" + )}); + let read = read_ahead(&mut s, "script.run", &p).unwrap(); + assert!(read.reads()); + let read = read.run(&Control::stoppable()).unwrap(); + assert!(s.map().layer(id).unwrap().selection == vec![0], "the worker cannot change live selection"); + let answer = read_land(&mut s, read).unwrap(); + assert_eq!(answer["ran"][0]["result"]["errors"], 0); + assert_eq!(answer["ran"][1]["result"]["similar"][0]["row"], 1); + let made = answer["ran"][2]["result"]["layer"].as_u64().unwrap() as u32; + let rows = &s.map().layer(made).unwrap().dataset; + assert_eq!(rows.features.len(), 2); + assert_eq!((rows.value(0, 0), rows.value(1, 0)), (&rustgis_data::Value::Int(0), &rustgis_data::Value::Int(2))); + assert_eq!(s.undo_depth(), depth + 1); + assert!(s.read_ahead.is_none() && s.tools_ahead.is_none()); + s.run("edit.undo", &Value::Null).unwrap(); + assert!(s.map().layer(made).is_none()); + assert_eq!(s.map().layer(id).unwrap().selection, vec![0]); +} + +#[test] +fn similar_zoom_keeps_results_until_the_active_filter_set_changes() { + use crate::cmd::reads::{read_ahead, read_land}; + use rustgis_analysis::control::Control; + for case in 0..3 { + let (mut s, id) = similar_lifecycle_session(); + s.run("map.setScale", &json!({"scale":1_000_000})).unwrap(); + if case > 0 { + s.map_mut().layer_mut(id).unwrap().display_filters.push(rustgis_map::effects::DisplayFilter { + name: "active".into(), + min_scale: None, + max_scale: Some(if case == 1 { 200_000.0 } else { 750_000.0 }), + where_: "n >= 2".into(), + }); + } + let p = json!({"layer":id,"row":0,"fields":["n"],"count":2}); + let read = read_ahead(&mut s, "data.similar", &p).unwrap().run(&Control::stoppable()).unwrap(); + s.run("map.setScale", &json!({"scale":500_000})).unwrap(); + let answer = read_land(&mut s, read); + if case == 2 { + assert!(answer.unwrap_err().contains("changed while")); + assert!(s.map().layer(id).unwrap().selection.is_empty()); + } else { + assert_eq!(answer.unwrap()["similar"].as_array().unwrap().len(), 2); + assert_eq!(s.map().layer(id).unwrap().selection, if case == 0 { vec![0, 1, 2] } else { vec![1, 2] }); + assert!(!s.notices.iter().any(|n| n.text.contains("without replacing the current selection"))); + } + } +} + +#[test] +fn prepared_similar_preserves_newer_selection_on_any_layer() { + use crate::cmd::reads::{read_ahead, read_land}; + use rustgis_analysis::control::Control; + for elsewhere in [false, true] { + let (mut s, id) = similar_lifecycle_session(); + let another = s.map().layer(id).unwrap().dataset.clone(); + let other = crate::cmd::layer::add_dataset(&mut s, another); + s.run("select.rows", &json!({"layer":id,"rows":[0]})).unwrap(); + // Explicit reference means a later selection changes output intent, not the ranking. + let p = json!({"layer":id,"row":0,"fields":["n"],"count":1}); + let read = read_ahead(&mut s, "data.similar", &p).unwrap().run(&Control::stoppable()).unwrap(); + let changed = if elsewhere { other } else { id }; + s.run("select.rows", &json!({"layer":changed,"rows":[2],"mode":"add"})).unwrap(); + // Add/Remove exercise the in-place selection mutation that pointer/length snapshots miss. + s.run("select.rows", &json!({"layer":changed,"rows":[2],"mode":"remove"})).unwrap(); + let selections: Vec<_> = s.map().layers.iter().map(|l| (l.id, l.selection.clone())).collect(); + let mark = s.notice_mark(); + assert_eq!(read_land(&mut s, read).unwrap()["similar"][0]["row"], 1); + assert_eq!(s.map().layers.iter().map(|l| (l.id, l.selection.clone())).collect::>(), selections); + assert!(s.notices_since(mark).iter().any(|n| n.text.contains("without replacing the current selection"))); + } +} + +#[test] +fn queued_similar_and_topology_snapshots_are_charged_until_drop_or_cancel() { + use crate::cmd::reads::read_ahead; + use rustgis_analysis::control::Control; + for topology in [false, true] { + let (mut s, id) = similar_lifecycle_session(); + if topology { + s.run("topology.rules", &json!({"add":{"rule":"mustNotSelfIntersect","layer":"values"}})).unwrap(); + } + s.undo_memory.memory = None; + let old = s.map().layer(id).unwrap().dataset.features.clone(); + let old_size = s.undo_memory.rows_bytes(&old); + let (command, p) = if topology { + ("topology.validate", json!({})) + } else { + ("data.similar", json!({"layer":id,"row":0,"fields":["n"],"select":false})) + }; + let first = read_ahead(&mut s, command, &p).unwrap(); + let second = read_ahead(&mut s, command, &p).unwrap(); + drop(old); + s.run("edit.setValue", &json!({"layer":id,"row":0,"field":"n","value":42})).unwrap(); + s.clear_history(); + let mut live_only = crate::undo_memory::Budget::default(); + let current = live_only.held(&s.project, &[], &[]); + assert_eq!(s.undo_memory.held(&s.project, &[], &[]), current + old_size); + drop(first); + assert_eq!(s.undo_memory.held(&s.project, &[], &[]), current + old_size); + drop(second); + assert_eq!(s.undo_memory.held(&s.project, &[], &[]), current); + let queued = read_ahead(&mut s, command, &p).unwrap(); + assert!(queued.run(&Control::cancelled_once_started()).is_err()); + assert_eq!(s.undo_memory.held(&s.project, &[], &[]), current); + } +} diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index 1126f6f8db..1f51619035 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -185,6 +185,16 @@ pub(super) fn long_commands(boundaries: bool) { exercise(&s, "layer.addData", &json!({"path": out("page.pdf")}), Kind::Read, &dir.0, boundaries); exercise(&s, "table.statistics", &json!({"layer": "Cities", "field": "pop_max"}), Kind::Read, &dir.0, boundaries); exercise(&s, "data.similar", &json!({"layer": "Cities", "row": 0, "fields": ["pop_max"], "count": 2}), Kind::Read, &dir.0, boundaries); + // The topology worker evaluates the primary query before its geometric check. + { + let id = s.map().layer_by_name("Cities").unwrap().id; + let query = s.map_mut().layer_mut(id).unwrap().definition_query.replace("pop_max >= 0".into()); + let rules = s.map().editing.topology.clone(); + s.run("topology.rules", &json!({"add":{"rule":"mustNotSelfIntersect","layer":"Cities"}})).unwrap(); + exercise(&s, "topology.validate", &json!({}), Kind::Read, &dir.0, boundaries); + s.map_mut().layer_mut(id).unwrap().definition_query = query; + s.map_mut().editing.topology = rules; + } // A Zarr point series is read on a thread of its own by the Time Series pane (#2282). It isn't // one of the queues above (it has no read-ahead), so it is run here: a local store, swept at // each of its checks in the boundary mode. It changes nothing in the project. diff --git a/crates/engine/src/undo_memory.rs b/crates/engine/src/undo_memory.rs index 235987f611..e6e9f9e63c 100644 --- a/crates/engine/src/undo_memory.rs +++ b/crates/engine/src/undo_memory.rs @@ -1,4 +1,4 @@ -//! Budget for feature allocations retained by undo and redo snapshots. +//! Budget for feature allocations retained by live data, Undo/Redo and queued readers. use crate::{Project, Step, notice_text::NoticeText}; use rustgis_data::{Coord, Feature, Features, Geometry, Value}; use std::{ @@ -15,6 +15,33 @@ type Key = Weak>; /// The allocation identities in a snapshot. The project keeps the corresponding rows alive. pub(crate) type Allocations = Vec; +/// Weak registrations let the budget count a queued reader without keeping its rows alive. +#[derive(Clone, Default)] +pub(crate) struct Readers(Arc>>>); + +/// Kept beside a reader's strong row snapshots, through queueing, execution and replay. +#[derive(Clone)] +pub(crate) struct ReadRows { + _allocations: Arc, +} + +impl Readers { + /// Records identities only; preparing a reader never visits feature contents. + pub(crate) fn retain(&self, allocations: Allocations) -> ReadRows { + let allocations = Arc::new(allocations); + let mut readers = self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + readers.retain(|reader| reader.strong_count() > 0); + readers.push(Arc::downgrade(&allocations)); + ReadRows { _allocations: allocations } + } + + fn allocations(&self) -> Allocations { + let mut readers = self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + readers.retain(|reader| reader.strong_count() > 0); + readers.iter().filter_map(Weak::upgrade).flat_map(|rows| rows.as_ref().clone()).collect() + } +} + pub(crate) struct Budget { pub(crate) limit: usize, // Command dispatch also runs post-command maintenance, which can record a second step. @@ -37,6 +64,7 @@ pub(crate) struct Budget { // Keeping the weak key prevents address reuse while its estimate is cached, without keeping // the rows themselves alive. Copy-on-write gives changed rows a different key. estimates: HashMap, + readers: Readers, } impl Default for Budget { @@ -52,13 +80,16 @@ impl Default for Budget { // Unit tests here don't depend on what else runs; they set it where they test it. free: if cfg!(test) { || None } else { rustgis_data::memory::available }, estimates: HashMap::new(), + readers: Readers::default(), } } } impl Budget { pub(crate) fn clear(&mut self) { - self.estimates.clear(); + let retained: HashSet<_> = self.readers.allocations().iter().map(|key| key.as_ptr() as usize).collect(); + // Clearing history must not discard the cached measurement of reader-only old rows. + self.estimates.retain(|id, (key, _)| retained.contains(id) && key.strong_count() > 0); self.said = false; self.room_said = false; } @@ -67,6 +98,7 @@ impl Budget { /// highest-priority owner, so the estimate falls only once its last snapshot is evicted. pub(crate) fn trim(&mut self, live: &Project, undo: &mut Vec, redo: &mut Vec) -> Option { let mut seen: HashSet<_> = rows(live).map(|features| features.allocation_key().as_ptr() as usize).collect(); + seen.extend(self.readers.allocations().iter().map(|key| key.as_ptr() as usize)); let mut used = 0usize; let undo_protected = usize::from(!undo.is_empty()); let mut account = |step: &Step| { @@ -99,8 +131,8 @@ impl Budget { } /// What the session holds (#2431 fix 3): the rows of the open project and those only Undo and - /// Redo keep, each allocation counted once however many snapshots share it, and the pixels - /// and embedded files of their rasters likewise. Rows are estimated as for the budget, from a + /// Redo or queued readers keep, each allocation counted once however many snapshots share it, + /// and the pixels and embedded files of their rasters likewise. Rows are estimated as for the budget, from a /// cache, so this visits allocations, not rows. pub(crate) fn held(&mut self, live: &Project, undo: &[Step], redo: &[Step]) -> u64 { let mut seen = HashSet::new(); @@ -108,6 +140,7 @@ impl Budget { for step in undo.iter().chain(redo) { bytes = bytes.saturating_add(self.private_bytes(&step.8, &mut seen)); } + bytes = bytes.saturating_add(self.private_bytes(&self.readers.allocations(), &mut seen)); let projects = std::iter::once(live).chain(undo.iter().chain(redo).map(|step| &step.0)); (bytes as u64).saturating_add(raster_bytes(projects)) } @@ -193,6 +226,17 @@ impl Budget { Reservation { in_flight: Arc::clone(&self.in_flight), bytes, _held: rustgis_data::memory::Holding::of(bytes) } } + /// Shared with script workers, so their retained inputs stay in the initiating budget. + pub(crate) fn readers(&self) -> Readers { + self.readers.clone() + } + + /// Joins the initiating session's registry without charging a shared copy independently. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn use_readers(&mut self, readers: Readers) { + self.readers = readers; + } + /// The estimated size of `features`' rows: what the first write to them copies while a /// snapshot shares them. pub(crate) fn rows_bytes(&mut self, features: &Features) -> u64 { @@ -536,6 +580,52 @@ mod tests { assert_eq!(value(&session), &Value::Text("c".into())); } + #[test] + fn queued_readers_keep_one_cached_allocation_after_history_is_cleared() { + let mut session = session(4096); + session.undo_memory.memory = None; + let first = session.map().layer_by_name("rows").unwrap().dataset.clone(); + let second = first.clone(); + let key = first.features.allocation_key(); + let size = session.undo_memory.rows_bytes(&first.features); + let readers = session.undo_memory.readers(); + let one = readers.retain(vec![key.clone()]); + let two = readers.retain(vec![key.clone(), key.clone()]); + assert_eq!(session.undo_memory.held(&session.project, &[], &[]), size, "live and duplicate readers share rows"); + edit(&mut session, &"b".repeat(4096)); + session.clear_history(); + let live = session.map().layer_by_name("rows").unwrap().dataset.features.clone(); + let live_size = session.undo_memory.rows_bytes(&live); + assert!(session.undo_memory.estimates.contains_key(&(key.as_ptr() as usize)), "reader-only size stays cached"); + assert_eq!(session.undo_memory.held(&session.project, &[], &[]), size + live_size); + drop((one, first)); + assert_eq!(session.undo_memory.held(&session.project, &[], &[]), size + live_size, "another reader still owns the old rows"); + drop((two, second)); + assert_eq!(session.undo_memory.held(&session.project, &[], &[]), live_size); + } + + #[test] + fn queued_reader_rows_cannot_be_evicted_to_admit_an_edit() { + let mut session = session(4096); + session.undo_memory.memory = None; + let snapshot = session.map().layer_by_name("rows").unwrap().dataset.clone(); + let retained = session.undo_memory.readers().retain(vec![snapshot.features.allocation_key()]); + edit(&mut session, &"b".repeat(4096)); + session.clear_history(); + let live = session.map().layer_by_name("rows").unwrap().dataset.features.clone(); + let size = session.undo_memory.rows_bytes(&live); + // Room for current rows and their copy, but not the old rows the reader still needs. + session.undo_memory.memory = Some(((2 * size + 64) * 4).div_ceil(3) + 4); + let p = json!({"layer":"rows", "row":0, "field":"text", "value":"c"}); + let error = session.run("edit.setValue", &p).unwrap_err(); + assert!(error.contains("not enough memory to edit rows"), "{error}"); + assert_eq!(value(&session), &Value::Text("b".repeat(4096))); + assert_eq!(session.undo_depth(), 0); + drop((retained, snapshot, live)); + session.run("edit.setValue", &p).unwrap(); + assert_eq!(value(&session), &Value::Text("c".into())); + } + #[test] fn redo_goes_before_undo_to_make_room() { let mut session = session(4096); diff --git a/crates/map/src/time.rs b/crates/map/src/time.rs index a25e041495..8261f6d78f 100644 --- a/crates/map/src/time.rs +++ b/crates/map/src/time.rs @@ -253,6 +253,53 @@ pub fn rows_in(ds: &Dataset, field: &str, window: (f64, f64)) -> Vec { keep(dated(ds, field).as_deref(), ds.features.len(), window) } +/// A window tested only on requested rows. It borrows the dataset and stores no per-row cache. +pub struct CandidateWindow<'a> { + data: &'a Dataset, + field_kind: Option<(usize, time::Kind)>, + window: (f64, f64), +} + +impl CandidateWindow<'_> { + /// Whether this row is in the window. Missing fields or undetected dates keep every valid + /// row, as [`rows_in`] does; a missing date in a detected field excludes its row. + pub fn keeps(&self, row: usize) -> rustgis_data::Result { + rustgis_data::progress::check()?; + if row >= self.data.features.len() { + return Ok(false); + } + let Some((field, kind)) = self.field_kind else { return Ok(true) }; + let (from, to) = self.window; + Ok(time::instant(self.data.value(row, field), kind).is_some_and(|t| if from == to { t == from } else { t >= from && t < to })) + } +} + +/// Detects the same date kind as [`rows_in`], with Cancel checks even when empty values make +/// its 500-value sample span the whole layer. Only requested candidates are then converted to +/// dates, avoiding the full timestamp and visibility vectors of a binding's display cache. +pub fn candidate_window<'a>(data: &'a Dataset, field: &str, window: (f64, f64)) -> rustgis_data::Result> { + rustgis_data::progress::check()?; + let mut field_kind = None; + if let Some(fi) = data.field_index(field) { + let mut error = None; + let kind = time::detect( + (0..data.features.len()).map_while(|row| match rustgis_data::progress::check() { + Ok(()) => Some(data.value(row, fi)), + Err(e) => { + error = Some(e); + None + } + }), + 500, + ); + if let Some(e) = error { + return Err(e); + } + field_kind = kind.map(|(kind, _)| (fi, kind)); + } + Ok(CandidateWindow { data, field_kind, window }) +} + /// Each row's moment in `field`, or `None` when the field is gone (renamed, deleted) or holds no /// dates. fn dated(ds: &Dataset, field: &str) -> Option>> { @@ -346,3 +393,73 @@ pub fn time_fields(ds: &Dataset) -> Vec<(String, f64)> { out.sort_by(|a, b| a.2.cmp(&b.2).then(b.1.total_cmp(&a.1)).then(b.3.cmp(&a.3))); out.into_iter().map(|(n, s, ..)| (n, s)).collect() } + +#[cfg(test)] +mod candidate_window_tests { + use super::*; + use rustgis_data::{DataError, Field, FieldType, GeometryType, Value, progress}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn dates(values: Vec) -> Dataset { + let mut ds = Dataset::new("dates", GeometryType::Point, vec![Field::new("date", FieldType::Text)]); + for value in values { + ds.push(None, vec![value]); + } + ds + } + + #[test] + fn candidate_windows_match_display_windows_without_full_caches() { + let sets = [ + vec![Value::Text("2020-01-01".into()), Value::Text("2021-01-01".into()), Value::Null, Value::Text("bad".into())], + vec![Value::Int(2020), Value::Int(2021), Value::Null, Value::Int(42)], + vec![Value::Float(1_577_836_800_000.0), Value::Float(1_609_459_200_000.0), Value::Null], + vec![Value::Float(1_577_836_800.0), Value::Float(1_609_459_200.0), Value::Null], + vec![Value::Null, Value::Text("".into()), Value::Text("bad".into())], + ]; + let start = time::parse_text("2020-01-01").unwrap(); + let end = time::parse_text("2021-01-01").unwrap(); + for values in sets { + let ds = dates(values); + for field in ["date", "missing"] { + for window in [(start, end), (start, start), (f64::NEG_INFINITY, end)] { + let expected = rows_in(&ds, field, window); + let candidates = candidate_window(&ds, field, window).unwrap(); + for row in (0..ds.features.len()).rev() { + assert_eq!(candidates.keeps(row).unwrap(), expected[row]); + } + assert!(!candidates.keeps(ds.features.len()).unwrap()); + } + } + } + // The 500-value sample skips empty cells, so a late date still determines the kind. + let mut sparse = dates(vec![Value::Null; 600]); + sparse.push(None, vec![Value::Text("2020-01-01".into())]); + let candidates = candidate_window(&sparse, "date", (start, end)).unwrap(); + assert!(!candidates.keeps(0).unwrap()); + assert!(candidates.keeps(600).unwrap()); + } + + /// Cancels after a known number of checks, including checks during an all-empty sample. + struct CancelAfter(AtomicUsize); + + impl progress::Probe for CancelAfter { + fn cancelled(&self) -> bool { + self.0.fetch_sub(1, Ordering::Relaxed) <= 1 + } + fn begin(&self, _: u64) {} + fn advance(&self, _: u64) {} + } + + #[test] + fn candidate_windows_cancel_during_detection_and_matching() { + let sparse = dates(vec![Value::Null; 600]); + { + let _guard = progress::install(Some(Arc::new(CancelAfter(AtomicUsize::new(300))))); + assert!(matches!(candidate_window(&sparse, "date", (0.0, 1.0)), Err(DataError::Cancelled))); + } + let candidates = candidate_window(&sparse, "date", (0.0, 1.0)).unwrap(); + let _guard = progress::install(Some(Arc::new(CancelAfter(AtomicUsize::new(1))))); + assert!(matches!(candidates.keeps(0), Err(DataError::Cancelled))); + } +} diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 0148065949..866f15624c 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -35,6 +35,11 @@ pub struct Workflow { pub pick: Option, pub result: Option, pub error: Option, + /// Only this request may replace the Similar section's pending result. + #[cfg(not(target_arch = "wasm32"))] + similar_request: Option, + #[cfg(not(target_arch = "wasm32"))] + similar_next: u64, pub script: String, pub script_out: Vec<(String, bool)>, /// The Script pane's last run, shown above its results. @@ -84,6 +89,65 @@ pub struct Workflow { pub job: Option, } +#[cfg(not(target_arch = "wasm32"))] +struct SimilarRequest { + id: u64, + opened: u64, + map: u64, + layer: String, + instance: Option, +} + +/// A pane/input change relinquishes ownership of a pending ranking. The read still completes +/// through its ordinary command, but cannot overwrite another section or a newer request. +pub(crate) fn forget_similar(workflow: &mut Workflow) { + #[cfg(not(target_arch = "wasm32"))] + { + workflow.similar_request = None; + } + #[cfg(target_arch = "wasm32")] + let _ = workflow; +} + +#[cfg(not(target_arch = "wasm32"))] +fn start_similar(app: &mut RustGisApp) { + app.workflow.similar_next = app.workflow.similar_next.wrapping_add(1); + let id = app.workflow.similar_next; + app.workflow.similar_request = Some(SimilarRequest { + id, + opened: app.session.opened, + map: app.session.map().instance_id(), + layer: app.workflow.layer.clone(), + instance: app.session.map().layer_by_name(&app.workflow.layer).map(|l| l.instance_id()), + }); + (app.workflow.result, app.workflow.error) = (None, None); + let params = json!({"layer": app.workflow.layer, "count": 10}); + // Success here is only an admission receipt. Completion owns success and every failure. + let _ = crate::readjob::run_workflow_similar(app, params, id); +} + +#[cfg(not(target_arch = "wasm32"))] +/// Delivers only to the still-current pane request; the admission receipt never becomes output. +pub(crate) fn similar_ran(app: &mut RustGisApp, request: u64, landed: crate::Landed) { + if !app.workflow.similar_request.as_ref().is_some_and(|r| r.id == request) { + return; + } + let Some(asked) = app.workflow.similar_request.take() else { return }; + if app.ui.right != Some(crate::RightPane::Workflows) + || app.workflow.section != "similar" + || app.workflow.layer != asked.layer + || app.session.opened != asked.opened + || app.session.map().instance_id() != asked.map + || app.session.map().layer_by_name(&asked.layer).map(|l| l.instance_id()) != asked.instance + { + return; + } + match landed { + crate::Landed::Ran(r) => show(app, r), + crate::Landed::NotRun(why) => show(app, Err(why)), + } +} + /// A workflow running on a thread of its own, so the window goes on while it works (#1291 step 3). #[cfg(not(target_arch = "wasm32"))] pub struct Job { @@ -270,6 +334,7 @@ fn model_ran(app: &mut RustGisApp, landed: crate::Landed) { /// Shows how a workflow's command went, and redraws the map it may have changed. fn show(app: &mut RustGisApp, r: Result) { + forget_similar(&mut app.workflow); match r { Ok(v) => { app.workflow.result = Some(v); @@ -552,6 +617,7 @@ pub fn workflows(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { if !app.workflow.section.is_empty() { app.workflow.pick = None; } + forget_similar(&mut app.workflow); app.workflow.section = "rasterFunctions"; } egui::ComboBox::from_id_salt("wf_section") @@ -560,6 +626,7 @@ pub fn workflows(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { .show_ui(ui, |ui| { for (id, title) in SECTIONS.iter().filter(|s| section_shown(&app.session, s.0)) { if ui.selectable_label(app.workflow.section == *id, tl!(*title)).clicked() { + forget_similar(&mut app.workflow); app.workflow.section = id; app.workflow.result = None; app.workflow.error = None; @@ -922,10 +989,25 @@ pub fn workflows(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { } "similar" => { heading(ui, "Features most like the selected one"); + let before = app.workflow.layer.clone(); combo(ui, "wf_e", "Layer", &mut app.workflow.layer, &features); + if app.workflow.layer != before { + forget_similar(&mut app.workflow); + (app.workflow.result, app.workflow.error) = (None, None); + } if ui.button(tl!("Find Similar")).clicked() { + #[cfg(not(target_arch = "wasm32"))] + start_similar(app); + #[cfg(target_arch = "wasm32")] run(app, "data.similar", json!({"layer": app.workflow.layer, "count": 10})); } + #[cfg(not(target_arch = "wasm32"))] + if app.workflow.similar_request.is_some() { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(tl!("Running…")); + }); + } } "interop" => { heading(ui, "Convert a layer to another format"); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 48495fe449..5457ec07a4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3578,6 +3578,8 @@ impl RustGisApp { if let Some(why) = section.and_then(|s| analysispane::section_blocked(&self.session, s)) { return Err(why); } + // A pending ranking belongs to the section/request that started it. + analysispane::forget_similar(&mut self.workflow); // A map pick started in another section (or before the pane closes) ends here. self.workflow.pick = None; match section.and_then(|s| analysispane::SECTIONS.iter().find(|x| x.0 == s)) { diff --git a/crates/ui-egui/src/readjob.rs b/crates/ui-egui/src/readjob.rs index 7e64c70b0f..26058a8ea5 100644 --- a/crates/ui-egui/src/readjob.rs +++ b/crates/ui-egui/src/readjob.rs @@ -76,12 +76,14 @@ pub type Then = fn(&mut RustGisApp, Landed); enum Completion { Command(Then), ShapeConversion(Option), + WorkflowSimilar(u64), } impl Completion { fn deliver(self, app: &mut RustGisApp, result: Landed) { match self { Self::Command(then) => then(app, result), Self::ShapeConversion(request) => crate::shapeconvert::landed(app, request, result), + Self::WorkflowSimilar(request) => crate::analysispane::similar_ran(app, request, result), } } } @@ -123,6 +125,11 @@ pub(crate) fn run_shape_conversion(app: &mut RustGisApp, p: Value) -> Result Result { + run_presented(app, "data.similar", p, Some(Completion::WorkflowSimilar(request)), None, None) +} + /// Keeps a service layer's title and connection display name outside recorded parameters /// until its admitted discovery lands. The ordinary read queue owns progress and Cancel. #[cfg(not(target_arch = "wasm32"))] @@ -503,6 +510,7 @@ fn start(app: &mut RustGisApp, mut asked: Asked, p: Value) -> Result Result h.state().reads.cancel_for_tests(), + "layer" => { + h.state_mut().workflow.layer = "other".into(); + h.state_mut().workflow.result = Some(json!({"kept":"other layer"})); + } + "newer" => { + // The older completion cannot erase the newer pending state or show its + // ranking. Keep the worker slots deterministic without timing the scan. + let end = std::time::Instant::now() + Duration::from_secs(60); + while !h.state().reads.read_finished_for_tests() { + assert!(std::time::Instant::now() < end); + std::thread::sleep(Duration::from_millis(5)); // test-wait: completion slot before testing queued pane ownership + } + h.get_by_role_and_label(egui::accesskit::Role::Button, "Find Similar").click(); + for _ in 0..4 { + h.step(); + } + assert_eq!(h.state().reads.waiting.len(), 1); + land(h.state_mut()); + assert!(h.state().workflow.result.is_none(), "older ranking cannot replace the newer pending request"); + h.state().reads.cancel_for_tests(); + } + _ => {} + } + allow_landing.set(true); + let end = std::time::Instant::now() + Duration::from_secs(60); + while showing(h.state()) || !h.state().reads.waiting.is_empty() { + assert!(std::time::Instant::now() < end, "{outcome}: pane read never landed"); + h.step(); + std::thread::sleep(Duration::from_millis(5)); // test-wait: worker completion delivered by the real app frame + } + // Completion used the full app frame above. Inspect the actual pane alone so its + // diagnostic cannot be confused with the same text in another app surface. + allow_landing.set(false); + h.step(); + h.run(); + match outcome { + "success" => { + let answer = h.state().workflow.result.as_ref().expect("the pane shows the completed ranking"); + assert_eq!(answer["similar"].as_array().unwrap().len(), 2); + assert!(answer["similar"][0]["distance"].is_number()); + assert!(h.query_by_label_contains("distance").is_some(), "the ranking is drawn in the pane"); + assert!(h.state().workflow.error.is_none()); + } + "error" => { + assert!(h.state().workflow.result.is_none()); + assert!(h.state().workflow.error.as_deref().is_some_and(|e| e.contains("reference row"))); + assert!( + h.query_by_role_and_label(egui::accesskit::Role::Label, h.state().workflow.error.as_deref().unwrap()).is_some() + ); + } + "spawn" => { + assert!(h.state().workflow.result.is_none()); + assert!(h.state().workflow.error.as_deref().is_some_and(|e| e.contains("background worker could not start"))); + assert!( + h.query_by_role_and_label(egui::accesskit::Role::Label, h.state().workflow.error.as_deref().unwrap()).is_some() + ); + } + "cancel" | "newer" => { + assert!(h.state().workflow.result.is_none()); + assert!(h.state().workflow.error.as_deref().is_some_and(|e| e.contains("cancelled"))); + assert!( + h.query_by_role_and_label(egui::accesskit::Role::Label, h.state().workflow.error.as_deref().unwrap()).is_some() + ); + } + "layer" => { + assert_eq!(h.state().workflow.result, Some(json!({"kept":"other layer"}))); + assert!(h.state().workflow.error.is_none()); + } + _ => panic!("unexpected Similar pane scenario"), + } + } + } + /// UI and direct relay Similar requests defer selection until the worker lands; a failed /// worker spawn must refuse rather than compute synchronously on the window thread. #[test] @@ -1856,6 +1984,40 @@ mod tests { } } + /// Topology's worker is used by both UI and scoped relay paths, with no inline spawn fallback. + #[test] + fn topology_uses_the_read_queue_for_ui_and_relay() { + use std::io::{BufRead, BufReader}; + for relay_call in [false, true] { + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + let mut ds = rustgis_engine::data::Dataset::new("points", rustgis_engine::data::GeometryType::Point, vec![]); + ds.push(Some(rustgis_engine::data::Geometry::Point(rustgis_engine::geom::Coord::new(1.0, 2.0))), vec![]); + rustgis_engine::cmd::layer::add_dataset(&mut app.session, ds); + app.run("topology.rules", json!({"add":{"rule":"mustNotSelfIntersect","layer":"points"}})).unwrap(); + app.reads_off_frame = true; + let p = json!({}); + let relay = if relay_call { + let (relay, grant, client, ahead) = paused_relay(&mut app, relay_command(1, "topology.validate", p.clone())); + admitted(&mut app, ahead, relay.clone()); + Some((relay, grant, client)) + } else { + assert_eq!(app.run("topology.validate", p.clone()).unwrap()["started"], "Error Inspector"); + None + }; + landed(&mut app, 60); + if let Some((relay, _grant, client)) = relay { + let mut text = String::new(); + BufReader::new(client).read_line(&mut text).unwrap(); + let answer: Value = serde_json::from_str(&text).unwrap(); + assert_eq!(answer["result"]["isError"], false, "{answer}"); + assert!(answer["result"]["content"][0]["text"].as_str().unwrap().contains("errors")); + relay.stop(); + } + app.reads.fail_spawn = true; + assert!(app.run("topology.validate", p).unwrap_err().contains("background worker could not start")); + } + } + /// Statistics… counts the column on a thread of its own and keeps the answer for its window /// once it lands; a layer changed meanwhile is left, and nothing is kept. #[test] diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 05e0e56842..9098230447 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1493,7 +1493,13 @@ display filters are ignored for selection, with one notice giving the count and error. `select: false` leaves selection unchanged and does not apply these filters. These workflows use the loaded resident dataset, without reloading a streamed layer's source. On the desktop, Find Similar computes on the background read queue with progress and Cancel; -selection changes only when the completed result still matches its layer, reference and filters. +the completed ranking appears in the Workflows pane. A changed layer, reference or active filter +invalidates the result. Zooming without changing which display filters apply does not invalidate it. +If selection changes while an explicit-reference request runs, its ranking still returns but it +does not replace the newer selection. +The reference must have a finite numeric value in every compared field; otherwise the command +refuses without changing selection. Other incomplete candidate rows are skipped with one count, +including when `select: false`. Standardization still uses each field's finite resident values. Slope, in Raster Functions and the Function Editor, uses Horn's 3 × 3 gradient. Choose **Slope units**: **Degrees (0–90)** (the default, from flat to vertical) or **Percent**. diff --git a/docs/user-guide/editing.md b/docs/user-guide/editing.md index 39bddcbc61..5f0b9cbbbc 100644 --- a/docs/user-guide/editing.md +++ b/docs/user-guide/editing.md @@ -151,14 +151,18 @@ you edit the value or choose units; click **Apply elevation** to apply the new i (Move, and `edit.traverse`, which draws a line or polygon from distances and bearings). - **Topology**: rules (must not overlap, must not have gaps, must not self-intersect, must not have dangles, must be covered by); Validate lists the errors, and clicking one zooms to it. + Primary rows follow the layer's definition query, independently of selection, time windows + and display filters. For **must be covered by**, every resident row of the covering layer + supplies the reference coverage; its map filters do not narrow that reference set. On the desktop the check runs in the background, so the map stays in use: the status bar shows **Error Inspector** with its progress and **Cancel**, and a check that can be cancelled takes any amount of work (a gaps rule first joins all its polygons in one step, which **Cancel** stops only once it is done). A layer edited while it is checked makes the check say - so: run Validate again. Checked from a script, the assistant or the command line, it holds - the window and stops after a fixed amount of work, saying which rules weren't checked - completely (a gaps rule's join of its polygons has no such limit). A line or ring too complex - to check for self-intersections within the limit is listed at its first point, to be looked + so: run Validate again. Headless script, assistant and command-line calls check on their + caller's thread; when they cannot be cancelled, they stop after a fixed amount of work, + saying which rules weren't checked completely (a gaps rule's join has no such limit). + A desktop window requires the background queue instead of running the check inline. A line or + ring too complex to check for self-intersections within the limit is listed at its first point, to be looked at, and its rule is said to be incomplete. Beyond 85.05° they follow the geometry tools (see [Geoprocessing tools](analysis.md#geoprocessing-tools), **Near the poles**). From 4a75ecdcdbedc61866de47aed9035822adfb1624 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 13:17:03 -0600 Subject: [PATCH 06/15] fix(engine): retain workflow results and reject numeric overflow --- crates/analysis/src/network.rs | 4 +++ crates/engine/src/cmd/workflows.rs | 5 ++-- crates/engine/src/tests.rs | 40 ++++++++++++++++++++++++--- crates/ui-egui/src/analysispane.rs | 44 +++++++++++++++++++++--------- crates/ui-egui/src/readjob.rs | 38 ++++++++++++++++++++++---- docs/user-guide/analysis.md | 2 ++ 6 files changed, 109 insertions(+), 24 deletions(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 14548a8e63..45f5038b24 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -768,6 +768,7 @@ pub struct Similarity { /// distance over `fields`), nearest first, excluding the row itself. Counts progress and checks /// Cancel between rows and within wide vectors. The stable library sort is one indivisible step, /// checked immediately before and after; equal-distance rows keep their original order. +/// Non-finite standardization statistics are refused before ranking any candidates. pub fn similar(ds: &Dataset, row: usize, fields: &[usize], n: usize) -> Result { use crate::control; control::begin(ds.features.len().saturating_mul(fields.len().saturating_mul(3).saturating_add(1))); @@ -802,6 +803,9 @@ pub fn similar(ds: &Dataset, row: usize, fields: &[usize], n: usize) -> Result>()? / vals.len().max(1) as f64) .sqrt(); + if !m.is_finite() || !sd.is_finite() { + return Err("a compared field's values are too large to standardize (its mean or spread overflows)".into()); + } stats.push((m, if sd > 0.0 { sd } else { 1.0 })); } let mut vector_pace = control::Pace::default(); diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index ba85e7622e..d143cd3255 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -912,8 +912,8 @@ fn check_table_prefix(s: &Session, lines: &[(usize, String, Value)]) -> Result<( #[cfg(not(target_arch = "wasm32"))] /// The commands a script's line may run on a copy of the session ([`runs_on_a_copy`]): those /// whose results are taken (a tool, a model, a batch) and those that change only what the taking compares -/// by value (a selection, a layer's name or query, the environment, the projection). A line that -/// makes rows of its own (a layer edit, a layer from a selection) isn't one. Table edits are the +/// by value (a selection, a layer's name or query, topology rules, the environment, the projection). +/// A line that makes rows of its own (a layer edit, a layer from a selection) isn't one. Table edits are the /// exception: their rows are recorded and taken, so later tools retain their shared input. pub(crate) const ON_A_COPY: &[&str] = &[ "edit.enable", @@ -930,6 +930,7 @@ pub(crate) const ON_A_COPY: &[&str] = &[ "gp.zonalStats", "gp.env", "data.similar", + "topology.rules", "topology.validate", "select.all", "select.atPoint", diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index fa8ff2b143..a57f8139c5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -54695,11 +54695,11 @@ fn native_script_replays_similar_and_topology_before_the_following_line() { use crate::cmd::reads::{read_ahead, read_land}; use rustgis_analysis::control::Control; let (mut s, id) = similar_lifecycle_session(); - s.run("topology.rules", &json!({"add":{"rule":"mustNotSelfIntersect","layer":"values"}})).unwrap(); s.run("select.rows", &json!({"layer":id,"rows":[0]})).unwrap(); s.statistics_need_read_ahead(true); let depth = s.undo_depth(); let p = json!({"script": concat!( + "topology.rules {\"add\":{\"rule\":\"mustNotSelfIntersect\",\"layer\":\"values\"}}\n", "topology.validate {}\n", "data.similar {\"layer\":\"values\",\"fields\":[\"n\"],\"count\":1}\n", "select.layerFromSelection {\"layer\":\"values\"}" @@ -54709,9 +54709,9 @@ fn native_script_replays_similar_and_topology_before_the_following_line() { let read = read.run(&Control::stoppable()).unwrap(); assert!(s.map().layer(id).unwrap().selection == vec![0], "the worker cannot change live selection"); let answer = read_land(&mut s, read).unwrap(); - assert_eq!(answer["ran"][0]["result"]["errors"], 0); - assert_eq!(answer["ran"][1]["result"]["similar"][0]["row"], 1); - let made = answer["ran"][2]["result"]["layer"].as_u64().unwrap() as u32; + assert_eq!(answer["ran"][1]["result"]["errors"], 0); + assert_eq!(answer["ran"][2]["result"]["similar"][0]["row"], 1); + let made = answer["ran"][3]["result"]["layer"].as_u64().unwrap() as u32; let rows = &s.map().layer(made).unwrap().dataset; assert_eq!(rows.features.len(), 2); assert_eq!((rows.value(0, 0), rows.value(1, 0)), (&rustgis_data::Value::Int(0), &rustgis_data::Value::Int(2))); @@ -54719,6 +54719,7 @@ fn native_script_replays_similar_and_topology_before_the_following_line() { assert!(s.read_ahead.is_none() && s.tools_ahead.is_none()); s.run("edit.undo", &Value::Null).unwrap(); assert!(s.map().layer(made).is_none()); + assert!(s.map().editing.topology.is_empty(), "Undo also removes the rules created by the script"); assert_eq!(s.map().layer(id).unwrap().selection, vec![0]); } @@ -54810,3 +54811,34 @@ fn queued_similar_and_topology_snapshots_are_charged_until_drop_or_cancel() { assert_eq!(s.undo_memory.held(&s.project, &[], &[]), current); } } + +/// Finite sentinels can overflow the spread or mean; neither may select a misleading ranking. +#[test] +fn similar_refuses_overflowing_statistics_without_selecting() { + use rustgis_data::{Dataset, Field, FieldType, GeometryType, Value as V}; + for values in [[1.0, 2.0, -f64::MAX], [f64::MAX; 3]] { + let mut ds = Dataset::new("extremes", GeometryType::Point, vec![Field::new("n", FieldType::Double)]); + for value in values { + ds.push(None, vec![V::Float(value)]); + } + let mut s = Session::new(Project::default()); + let id = crate::cmd::layer::add_dataset(&mut s, ds); + s.map_mut().layer_mut(id).unwrap().selection = vec![2]; + let p = json!({"layer":id,"row":0,"fields":["n"],"count":2}); + let mark = s.notice_mark(); + assert!(s.run("data.similar", &p).unwrap_err().contains("mean or spread overflows")); + assert_eq!(s.map().layer(id).unwrap().selection, vec![2]); + assert!(!s.notices_since(mark).is_empty()); + assert!(s.notices_since(mark).iter().all(|n| n.error)); + for row in 0..3 { + s.map_mut().layer_mut(id).unwrap().dataset.features[row].attrs[0] = V::Float((row + 1) as f64); + } + let mark = s.notice_mark(); + let answer = s.run("data.similar", &p).unwrap(); + let matches = answer["similar"].as_array().unwrap(); + assert_eq!(matches.len(), 2); + assert!(matches.iter().all(|m| m["distance"].as_f64().is_some_and(|d| d.is_finite() && d > 0.0))); + assert_eq!(s.map().layer(id).unwrap().selection, vec![0, 1, 2]); + assert!(s.notices_since(mark).is_empty()); + } +} diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 866f15624c..fddccb4a35 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -153,6 +153,8 @@ pub(crate) fn similar_ran(app: &mut RustGisApp, request: u64, landed: crate::Lan pub struct Job { /// What it is called, for its progress line. name: &'static str, + /// Only this section owns the pane output; data and error notices still land elsewhere. + section: &'static str, /// Stops it, and counts its progress. control: std::sync::Arc, kind: JobKind, @@ -334,7 +336,6 @@ fn model_ran(app: &mut RustGisApp, landed: crate::Landed) { /// Shows how a workflow's command went, and redraws the map it may have changed. fn show(app: &mut RustGisApp, r: Result) { - forget_similar(&mut app.workflow); match r { Ok(v) => { app.workflow.result = Some(v); @@ -348,6 +349,20 @@ fn show(app: &mut RustGisApp, r: Result) { app.map.invalidate(); } +/// A background workflow changes only its own section's output. Its applied data redraws the +/// map either way, and failures remain visible as notices after the user changes sections. +#[cfg(not(target_arch = "wasm32"))] +fn show_job(app: &mut RustGisApp, section: &'static str, r: Result) { + if app.workflow.section == section { + show(app, r); + } else { + if let Err(error) = r { + app.session.notify(error, true); + } + app.map.invalidate(); + } +} + /// The workflows that run on a thread of their own on the desktop, as their command and name: /// Zonal Statistics, and those that make a raster /// ([`rustgis_engine::cmd::workflows::runs_in_background`]). Their work grows with the raster and @@ -391,7 +406,7 @@ fn start(app: &mut RustGisApp, command: &'static str, name: &'static str, p: Val }; match kind { Ok(kind) => { - app.workflow.job = Some(Job { name, control, kind }); + app.workflow.job = Some(Job { name, section: app.workflow.section, control, kind }); (app.workflow.result, app.workflow.error) = (None, None); } Err(e) => show(app, Err(e)), @@ -411,7 +426,8 @@ fn fill(slot: &crate::Slot, v: T) { /// A workflow that has finished on its thread, applied (so it's in the History and can be undone): /// called every frame, whatever pane is in view, so a run lands though the pane closed. `true` -/// while one is still running. +/// while one is still running. Pane output stays in its originating section; failures still +/// reach session notices after a section change. #[cfg(not(target_arch = "wasm32"))] pub fn land_job(app: &mut RustGisApp) -> bool { use rustgis_engine::cmd::{gp, workflows}; @@ -422,8 +438,9 @@ pub fn land_job(app: &mut RustGisApp) -> bool { if !gp::tool_waiting(&app.session, *id) { job.control.cancel(); let name = job.name; + let section = job.section; app.workflow.job = None; - dropped(app, name); + dropped(app, section, name); return false; } filled(slot) @@ -433,8 +450,9 @@ pub fn land_job(app: &mut RustGisApp) -> bool { if !workflows::raster_waiting(&app.session, *id) { job.control.cancel(); let name = job.name; + let section = job.section; app.workflow.job = None; - dropped(app, name); + dropped(app, section, name); return false; } filled(slot) @@ -448,21 +466,21 @@ pub fn land_job(app: &mut RustGisApp) -> bool { JobKind::Tool { id, slot } => { let Some(done) = take(&slot) else { return false }; let r = gp::tool_complete(&mut app.session, id, done).and_then(|_| app.finish_gp(id)); - show(app, r); + show_job(app, job.section, r); } JobKind::Raster { id, command, params, slot } => match take(&slot) { // Added by its command, as if it had run here. Some(Ok(made)) => match workflows::raster_land(&mut app.session, id, made) { Ok(true) => { let result = app.finish_raster(command, id, ¶ms); - show(app, result); + show_job(app, job.section, result); } - Ok(false) => dropped(app, job.name), - Err(e) => show(app, Err(e)), + Ok(false) => dropped(app, job.section, job.name), + Err(e) => show_job(app, job.section, Err(e)), }, Some(Err(e)) => { workflows::raster_abandon(&mut app.session, id); - show(app, Err(e)); + show_job(app, job.section, Err(e)); } None => {} }, @@ -482,9 +500,9 @@ fn take(slot: &crate::Slot) -> Option { /// Says that a workflow's run was dropped: its project closed while it ran. #[cfg(not(target_arch = "wasm32"))] -fn dropped(app: &mut RustGisApp, name: &'static str) { - app.workflow.error = Some(crate::i18n::fmt("{tool} was stopped: its project was closed while it ran.", &[("tool", tl_raw!(name))])); - app.workflow.result = None; +fn dropped(app: &mut RustGisApp, section: &'static str, name: &'static str) { + let error = crate::i18n::fmt("{tool} was stopped: its project was closed while it ran.", &[("tool", tl_raw!(name))]); + show_job(app, section, Err(error)); } /// A workflow under way: its name, progress and Cancel. diff --git a/crates/ui-egui/src/readjob.rs b/crates/ui-egui/src/readjob.rs index 26058a8ea5..ffbb3a95ab 100644 --- a/crates/ui-egui/src/readjob.rs +++ b/crates/ui-egui/src/readjob.rs @@ -1821,12 +1821,15 @@ mod tests { #[test] fn similar_pane_receives_success_failure_and_cancellation() { use egui_kittest::kittest::Queryable; - use rustgis_engine::data::{Dataset, Field, FieldType, GeometryType, Value as V}; - for outcome in ["success", "error", "cancel", "spawn", "newer", "layer"] { + use rustgis_engine::data::{Dataset, Field, FieldType, Geometry, GeometryType, Value as V}; + for outcome in ["success", "error", "cancel", "spawn", "newer", "layer", "workflow"] { let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); let mut ds = Dataset::new("numbers", GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); for n in [0, 2, 10] { - ds.push(None, vec![if n == 0 && outcome == "error" { V::Null } else { V::Int(n) }]); + ds.push( + Some(Geometry::Point(rustgis_engine::geom::Coord::new(n as f64, n as f64))), + vec![if n == 0 && outcome == "error" { V::Null } else { V::Int(n) }], + ); } let id = rustgis_engine::cmd::layer::add_dataset(&mut app.session, ds.clone()); ds.name = "other".into(); @@ -1834,6 +1837,15 @@ mod tests { app.session.map_mut().layer_mut(id).unwrap().selection = vec![0]; app.reads_off_frame = true; app.reads.fail_spawn = outcome == "spawn"; + if outcome == "workflow" { + crate::analysispane::run_elsewhere( + &mut app, + "interpolate", + "analysis.interpolate", + json!({"layer":"numbers","field":"n","cellSize":2}), + ); + assert!(app.workflow.job.is_some(), "the raster workflow is pending before Similar starts"); + } app.run("ui.pane.workflows", json!({"section":"similar"})).unwrap(); app.workflow.layer = "numbers".into(); // Pause only the frame's completion pass until the button and queue ownership have @@ -1858,7 +1870,14 @@ mod tests { }, app, ); - h.run(); + if outcome == "workflow" { + // This deliberately held background job shows a spinner until we land it. + for _ in 0..4 { + h.step(); + } + } else { + h.run(); + } h.get_by_role_and_label(egui::accesskit::Role::Button, "Find Similar").click(); for _ in 0..4 { h.step(); @@ -1866,6 +1885,15 @@ mod tests { assert_eq!(showing(h.state()), outcome != "spawn", "{outcome}: worker admission"); assert!(h.state().workflow.result.is_none(), "a receipt is not a ranking"); match outcome { + "workflow" => { + let end = std::time::Instant::now() + Duration::from_secs(60); + while crate::analysispane::land_job(h.state_mut()) { + assert!(std::time::Instant::now() < end, "the raster workflow never landed"); + std::thread::sleep(Duration::from_millis(5)); // test-wait: the real raster completion lands while Similar remains pending + } + assert!(h.state().session.map().layers.iter().any(|l| l.is_raster())); + assert!(h.state().workflow.result.is_none(), "another section cannot show its result in the Similar pane"); + } "cancel" => h.state().reads.cancel_for_tests(), "layer" => { h.state_mut().workflow.layer = "other".into(); @@ -1903,7 +1931,7 @@ mod tests { h.step(); h.run(); match outcome { - "success" => { + "success" | "workflow" => { let answer = h.state().workflow.result.as_ref().expect("the pane shows the completed ranking"); assert_eq!(answer["similar"].as_array().unwrap().len(), 2); assert!(answer["similar"][0]["distance"].is_number()); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 9098230447..d500e5c08d 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1500,6 +1500,8 @@ does not replace the newer selection. The reference must have a finite numeric value in every compared field; otherwise the command refuses without changing selection. Other incomplete candidate rows are skipped with one count, including when `select: false`. Standardization still uses each field's finite resident values. +If a field's mean or spread overflows the numeric range, the comparison is refused; rescale its +values before comparing. Slope, in Raster Functions and the Function Editor, uses Horn's 3 × 3 gradient. Choose **Slope units**: **Degrees (0–90)** (the default, from flat to vertical) or **Percent**. From ba65cf9b8ef31f96f9ee2a4c72eba02fb5daadba Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 16:53:13 -0600 Subject: [PATCH 07/15] fix(engine): preserve queued Similar intent and Trend output --- crates/engine/src/cmd/select.rs | 11 ++++ crates/engine/src/cmd/similar.rs | 2 +- crates/engine/src/policy/dispatch.rs | 3 +- crates/engine/src/tests.rs | 30 +++++++++++ crates/ui-egui/src/analysispane.rs | 81 ++++++++++++++++++++++++++-- docs/user-guide/analysis.md | 2 +- 6 files changed, 122 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 3997854f43..aa9c0f4e5a 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -127,6 +127,17 @@ fn area_mode(p: &Value) -> Result { /// Applies a selection to one layer (New clears the others too, like desktop GIS). pub fn set(s: &mut Session, id: u32, rows: Vec, m: Mode) { s.selection_generation = s.selection_generation.wrapping_add(1); + apply(s, id, rows, m); +} + +/// A queued Similar result must not invalidate the selection intent of later queued requests. +/// External selection commands still advance the generation through `set`. +pub(super) fn set_similar_result(s: &mut Session, id: u32, rows: Vec) { + apply(s, id, rows, Mode::New); +} + +/// Applies either external intent or a validated result with the same row bounds and modes. +fn apply(s: &mut Session, id: u32, rows: Vec, m: Mode) { if m == Mode::New { s.map_mut().clear_selection(); } diff --git a/crates/engine/src/cmd/similar.rs b/crates/engine/src/cmd/similar.rs index ab4cdd2527..5183a4ea10 100644 --- a/crates/engine/src/cmd/similar.rs +++ b/crates/engine/src/cmd/similar.rs @@ -221,7 +221,7 @@ pub(super) fn run(s: &mut Session, p: &Value) -> CmdResult { let done = done?; if let Some(rows) = done.selection { if selection_generation == s.selection_generation { - super::select::set(s, input.target.id, rows, super::select::Mode::New); + super::select::set_similar_result(s, input.target.id, rows); } else { s.notify_text( NoticeText::term( diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 74da061535..446bc29594 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -985,9 +985,10 @@ impl Session { Txn::Shared => run(self), }; self.url_completion_landed(spec.id, ¶ms, &result); - if result.is_ok() && spec.mutates { + if result.is_ok() && spec.mutates && spec.id != "data.similar" { // Some edits replace selections without going through select::set. A pending // read must preserve the later intent, even when this edit touched another layer. + // Similar's own result is derived output, not a new external selection intent. self.selection_generation = self.selection_generation.wrapping_add(1); } result diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a57f8139c5..89c207d891 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -54777,6 +54777,36 @@ fn prepared_similar_preserves_newer_selection_on_any_layer() { } } +#[test] +fn queued_similar_results_preserve_later_requests_and_user_intent() { + use crate::cmd::reads::{read_ahead, read_land}; + use rustgis_analysis::control::Control; + for first_selects in [false, true] { + for user_changes_selection in [false, true] { + let (mut s, id) = similar_lifecycle_session(); + let first = json!({"layer":id,"row":0,"fields":["n"],"count":1,"select":first_selects}); + let second = json!({"layer":id,"row":2,"fields":["n"],"count":1}); + // Both requests capture intent before either completion reaches the live session. + let first = read_ahead(&mut s, "data.similar", &first).unwrap(); + let second = read_ahead(&mut s, "data.similar", &second).unwrap(); + read_land(&mut s, first.run(&Control::stoppable()).unwrap()).unwrap(); + if user_changes_selection { + s.run("select.rows", &json!({"layer":id,"rows":[0]})).unwrap(); + } + let mark = s.notice_mark(); + let answer = read_land(&mut s, second.run(&Control::stoppable()).unwrap()).unwrap(); + assert_eq!(answer["similar"][0]["row"], 1); + if user_changes_selection { + assert_eq!(s.map().layer(id).unwrap().selection, vec![0]); + assert!(s.notices_since(mark).iter().any(|n| n.text.contains("without replacing the current selection"))); + } else { + assert_eq!(s.map().layer(id).unwrap().selection, vec![1, 2], "the latest request owns selection"); + assert!(s.notices_since(mark).is_empty(), "an earlier result is not a user selection change"); + } + } + } +} + #[test] fn queued_similar_and_topology_snapshots_are_charged_until_drop_or_cancel() { use crate::cmd::reads::read_ahead; diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index fddccb4a35..a695341208 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -1798,7 +1798,8 @@ fn trend(app: &mut RustGisApp, ui: &mut Ui, rasters: &[String]) { /// A trend that has finished, its layers added through `cube.trend` (so it's in the History): /// called every frame, whatever pane is in view, so a run lands though the Workflows pane -/// closed. `true` while one is still running. +/// closed. Output stays with the Trend section; failures elsewhere become notices. +/// `true` while one is still running. #[cfg(not(target_arch = "wasm32"))] pub fn land_trend(app: &mut RustGisApp) -> bool { use std::sync::atomic::Ordering; @@ -1815,14 +1816,15 @@ pub fn land_trend(app: &mut RustGisApp) -> bool { Ok(_) if cancelled => {} // Another project opened meanwhile: nothing added, and said. Ok(_) if !current => { - app.workflow.error = Some(tl!("The trend finished after another project was opened, so it wasn't added").to_string()); + show_job(app, "trend", Err(tl!("The trend finished after another project was opened, so it wasn't added").to_string())); } Ok((rasters, dates)) => { p["ran"] = json!(rustgis_engine::cmd::cube::land(&mut app.session, rasters, dates)); - run(app, "cube.trend", p); + let result = app.run("cube.trend", p); + show_job(app, "trend", result); } Err(_) if cancelled => {} - Err(e) => app.workflow.error = Some(e), + Err(e) => show_job(app, "trend", Err(e)), } false } @@ -2902,6 +2904,77 @@ mod tests { assert_eq!(copied, Some(pretty(&long)), "Copy keeps the long line whole"); } + /// Ready Trend completions land through the real app frame without replacing another + /// section's output; Trend still receives its own result/error and Cancel stays quiet. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn trend_completion_preserves_other_workflow_output() { + for section in ["similar", "trend"] { + for outcome in ["failure", "project changed", "success", "cancelled"] { + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + let id = app.session.download_started(); + if outcome == "project changed" { + app.session.run("project.new", &Value::Null).unwrap(); + } + app.run("ui.pane.workflows", json!({"section":section})).unwrap(); + let kept = json!({"similar": [{"row":1,"distance":0.5}]}); + app.workflow.result = Some(kept.clone()); + let result = match outcome { + "project changed" | "success" => Ok((Vec::new(), 0)), + _ => Err("trend test failure".into()), + }; + app.workflow.trend.running = Some(Trending { + total: 1, + id, + params: Value::Null, + cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(outcome == "cancelled")), + done: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(1)), + result: std::sync::Arc::new(std::sync::Mutex::new(Some(result))), + }); + let mark = app.session.notice_mark(); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_ui_state( + move |ui, app: &mut RustGisApp| { + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + app.logic(ui.ctx()); + app.ui(ui); + }, + app, + ); + for _ in 0..4 { + h.step(); + } + assert!(h.state().workflow.trend.running.is_none(), "the real frame consumed the worker completion"); + let notices = h.state().session.notices_since(mark); + if outcome == "cancelled" || (section == "similar" && outcome == "success") { + assert!(h.state().workflow.error.is_none()); + assert_eq!(h.state().workflow.result, Some(kept)); + assert!(notices.is_empty()); + } else if outcome == "success" { + assert!(h.state().workflow.error.is_none()); + assert_eq!(h.state().workflow.result, Some(json!({"layers":[],"dates":0}))); + assert!(notices.is_empty()); + } else { + let needle = if outcome == "project changed" { "after another project" } else { "trend test failure" }; + if section == "similar" { + assert!(h.state().workflow.error.is_none(), "Trend's error belongs outside the Similar pane"); + assert_eq!(h.state().workflow.result, Some(kept)); + assert_eq!(notices.len(), 1); + assert!(notices[0].error && notices[0].text.contains(needle)); + } else { + assert!(h.state().workflow.error.as_deref().is_some_and(|e| e.contains(needle))); + assert!(h.state().workflow.result.is_none()); + assert!(notices.is_empty()); + } + } + } + } + } + /// Interpolate runs on a thread of its own from the pane (#1291 step 3): the pane goes on while /// it works, a second run waits for the first, and its layer lands through its command, which /// Record Task takes without the raster it handed over (a replay works it out again). diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index d500e5c08d..2101200890 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1495,7 +1495,7 @@ These workflows use the loaded resident dataset, without reloading a streamed la On the desktop, Find Similar computes on the background read queue with progress and Cancel; the completed ranking appears in the Workflows pane. A changed layer, reference or active filter invalidates the result. Zooming without changing which display filters apply does not invalidate it. -If selection changes while an explicit-reference request runs, its ranking still returns but it +If you change selection while an explicit-reference request runs, its ranking still returns but it does not replace the newer selection. The reference must have a finite numeric value in every compared field; otherwise the command refuses without changing selection. Other incomplete candidate rows are skipped with one count, From fa60c48118e17997d9488f28cc4d46311a31e6be Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 18:09:20 -0600 Subject: [PATCH 08/15] fix(engine): preserve popup clears and newer Similar selections --- crates/engine/src/cmd/select.rs | 9 +++-- crates/engine/src/cmd/similar.rs | 31 ++++++++++++----- crates/engine/src/cmd/workflows.rs | 3 ++ crates/engine/src/lib.rs | 8 +++++ crates/engine/src/tests.rs | 53 +++++++++++++++++++++++++++++ crates/ui-egui/src/mapview.rs | 54 +++++++++++++++++++++++++++++- docs/user-guide/analysis.md | 2 ++ 7 files changed, 148 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index aa9c0f4e5a..9ecb0b36fc 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -39,8 +39,7 @@ pub fn commands() -> Vec { }).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"layer"?, "rows": [number], "mode"?}"#), C::new("select.clear", "Clear", "Home › Selection", |s, _| { - s.map_mut().clear_selection(); - s.selection_generation = s.selection_generation.wrapping_add(1); + clear(s); Ok(Value::Null) }).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_selection), @@ -124,6 +123,12 @@ fn area_mode(p: &Value) -> Result { } } +/// Records an external clear without a command/Undo step, as pop-up browsing requires. +pub fn clear(s: &mut Session) { + s.map_mut().clear_selection(); + s.selection_generation = s.selection_generation.wrapping_add(1); +} + /// Applies a selection to one layer (New clears the others too, like desktop GIS). pub fn set(s: &mut Session, id: u32, rows: Vec, m: Mode) { s.selection_generation = s.selection_generation.wrapping_add(1); diff --git a/crates/engine/src/cmd/similar.rs b/crates/engine/src/cmd/similar.rs index 5183a4ea10..f66c9903ed 100644 --- a/crates/engine/src/cmd/similar.rs +++ b/crates/engine/src/cmd/similar.rs @@ -102,6 +102,12 @@ struct Done { struct Ahead { input: Input, done: Result, + request: u64, +} + +/// Orders admissions, not completions. Script workers share this sequence with their session. +fn request(s: &Session) -> u64 { + s.similar_sequence.fetch_add(1, std::sync::atomic::Ordering::Relaxed).wrapping_add(1) } /// Filters the bounded result/reference rows with cancellation, without a layer-wide mask. @@ -187,9 +193,10 @@ fn gather(input: &Input) -> Result { /// errors; successful work is taken only by the original admitted command at landing. pub(super) fn ahead(s: &Session, p: &Value) -> Option { let input = Input::resolve(s, p).ok()?; + let request = request(s); Some(super::reads::ahead("Find Similar", "data.similar".into(), move || { let done = gather(&input); - Ahead { input, done } + Ahead { input, done, request } })) } @@ -209,24 +216,30 @@ pub(super) fn run(s: &mut Session, p: &Value) -> CmdResult { if ahead.is_none() && s.statistics_window_thread == Some(std::thread::current().id()) { return Err("Similarity needs the desktop background read queue; run Find Similar or a direct MCP data.similar request".into()); } - let (done, selection_generation) = match ahead { - Some(a) if a.input.same(&input) => (a.done, a.input.selection_generation), + let (done, selection_generation, request) = match ahead { + Some(a) if a.input.same(&input) => (a.done, a.input.selection_generation, a.request), Some(_) => return Err("the layer, reference or map filters changed while similarity was computed: ask again".into()), - None => (gather(&input), input.selection_generation), + None => { + let request = request(s); + (gather(&input), input.selection_generation, request) + } }; #[cfg(not(target_arch = "wasm32"))] if matches!(s.tools_ahead, Some(super::gp::Ahead::Recording(_))) { - super::gp::record_read(s, "data.similar", p, Ahead { input: input.clone(), done: done.clone() }); + super::gp::record_read(s, "data.similar", p, Ahead { input: input.clone(), done: done.clone(), request }); } let done = done?; if let Some(rows) = done.selection { - if selection_generation == s.selection_generation { + if selection_generation == s.selection_generation && request >= s.similar_selected { super::select::set_similar_result(s, input.target.id, rows); + s.similar_selected = request; } else { s.notify_text( - NoticeText::term( - "Selection changed while similarity was computed; its ranking is returned without replacing the current selection", - ), + NoticeText::term(if selection_generation != s.selection_generation { + "Selection changed while similarity was computed; its ranking is returned without replacing the current selection" + } else { + "A newer Similar result has already changed selection; this ranking is returned without replacing it" + }), false, ); } diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index d143cd3255..65b10e9fa3 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -826,6 +826,7 @@ pub(crate) fn ahead_on_copy(s: &Session, command: &'static str, p: &Value) -> su let extensions = s.extensions().clone(); let (view_size, active_layer, opened, p) = (s.view_size, s.active_layer, s.opened, p.clone()); let selection_generation = s.selection_generation; + let (similar_sequence, similar_selected) = (s.similar_sequence.clone(), s.similar_selected); // What its tools ask of servers and files goes in this session's Diagnostics, as when they // run here: the run here takes their results and asks nothing. let requests = s.diagnostics.capture(); @@ -838,6 +839,8 @@ pub(crate) fn ahead_on_copy(s: &Session, command: &'static str, p: &Value) -> su copy.active_layer = active_layer; copy.opened = opened; copy.selection_generation = selection_generation; + copy.similar_sequence = similar_sequence; + copy.similar_selected = similar_selected; // The copy shares this session's rows, which this session already counts in what the // process holds (#2431): it neither measures nor adds them again. copy.undo_memory.memory = None; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4d6c1d8dc6..9d71ee7c99 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -790,6 +790,10 @@ pub struct Session { /// Runtime selection intent, including changes on other layers that a new selection clears. /// Mutation dispatch conservatively advances it too; view-only commands leave it alone. pub(crate) selection_generation: u64, + /// Similar requests share an order with script workers; their completion order may differ. + pub(crate) similar_sequence: std::sync::Arc, + /// The last Similar request that applied selection here, independently of external intent. + pub(crate) similar_selected: u64, /// Bumped each time another project replaces this one (new, open, sample, template), however /// the command came (the app, an agent, a script): the interface drops what it kept for the /// old one. @@ -1272,6 +1276,8 @@ impl Session { self.statistics_window_thread = enabled.then(|| std::thread::current().id()); } + /// Starts an independent session with fresh runtime selection intent and request order. + /// Prepared script copies explicitly share request order with their originating session. pub fn new(mut project: Project) -> Self { // The engine's tests never add Shapefile indexes to the user's cache (#1230). #[cfg(all(test, not(target_arch = "wasm32")))] @@ -1311,6 +1317,8 @@ impl Session { registry: Registry { commands: cmd::all() }, revision: 1, selection_generation: 0, + similar_sequence: Default::default(), + similar_selected: 0, opened: 0, exchange: None, tool: Tool::Explore, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 89c207d891..03081c17d1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -54807,6 +54807,59 @@ fn queued_similar_results_preserve_later_requests_and_user_intent() { } } +/// Completion order may differ for embedded prepared reads and a direct command. An older +/// ranking still returns, but only a newer selecting result may replace the current selection. +#[test] +fn older_similar_completion_preserves_a_newer_similar_selection() { + use crate::cmd::reads::{read_ahead, read_land}; + use rustgis_analysis::control::Control; + for queued_newer in [false, true] { + for newer_selects in [false, true] { + let (mut s, id) = similar_lifecycle_session(); + let old = json!({"layer":id,"row":0,"fields":["n"],"count":1}); + let new = json!({"layer":id,"row":2,"fields":["n"],"count":1,"select":newer_selects}); + let pending = read_ahead(&mut s, "data.similar", &old).unwrap(); + if queued_newer { + let newer = read_ahead(&mut s, "data.similar", &new).unwrap().run(&Control::stoppable()).unwrap(); + read_land(&mut s, newer).unwrap(); + } else { + s.run("data.similar", &new).unwrap(); + } + let mark = s.notice_mark(); + assert_eq!(read_land(&mut s, pending.run(&Control::stoppable()).unwrap()).unwrap()["similar"][0]["row"], 1); + assert_eq!(s.map().layer(id).unwrap().selection, if newer_selects { vec![1, 2] } else { vec![0, 1] }); + let notices = s.notices_since(mark); + if newer_selects { + assert!(notices.iter().any(|n| n.text.contains("newer Similar result"))); + } else { + assert!(notices.is_empty(), "a nonselecting newer request leaves selection ownership alone"); + } + } + } +} + +/// A script worker and its live session share request order: a fresh command after replay +/// must be newer than both Similar commands that the worker computed. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn similar_request_order_continues_after_script_replay() { + use crate::cmd::reads::{read_ahead, read_land}; + use rustgis_analysis::control::Control; + let (mut s, id) = similar_lifecycle_session(); + let p = json!({"script": concat!( + "data.similar {\"layer\":\"values\",\"row\":0,\"fields\":[\"n\"],\"count\":1}\n", + "data.similar {\"layer\":\"values\",\"row\":2,\"fields\":[\"n\"],\"count\":1}" + )}); + let read = read_ahead(&mut s, "script.run", &p).unwrap(); + assert!(read.reads()); + read_land(&mut s, read.run(&Control::stoppable()).unwrap()).unwrap(); + assert_eq!(s.map().layer(id).unwrap().selection, vec![1, 2]); + let mark = s.notice_mark(); + s.run("data.similar", &json!({"layer":id,"row":0,"fields":["n"],"count":1})).unwrap(); + assert_eq!(s.map().layer(id).unwrap().selection, vec![0, 1]); + assert!(s.notices_since(mark).is_empty()); +} + #[test] fn queued_similar_and_topology_snapshots_are_charged_until_drop_or_cancel() { use crate::cmd::reads::read_ahead; diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 67634bbcbb..4e97fc0ad2 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -4419,7 +4419,7 @@ fn select_shown(app: &mut RustGisApp) { if let Some((id, row)) = found { rustgis_engine::cmd::select::set(&mut app.session, id, vec![row], rustgis_engine::cmd::select::Mode::New); } else { - app.session.map_mut().clear_selection(); + rustgis_engine::cmd::select::clear(&mut app.session); } app.session.revision = app.session.revision.wrapping_add(1); } @@ -5395,6 +5395,58 @@ mod tests { assert!(app.session.map().layer_by_name("Countries").unwrap().selection.is_empty()); } + /// Browsing to a service result clears vector selection without an Undo step. A Similar + /// read prepared before that actual pop-up gesture must not replace the user's clear. + #[test] + fn popup_clear_preserves_selection_intent_against_pending_similar() { + use egui_kittest::kittest::Queryable; + use rustgis_engine::analysis::control::Control; + use rustgis_engine::cmd::reads::{read_ahead, read_land}; + use rustgis_engine::data::{Dataset, Field, FieldType, Geometry, GeometryType, Value as Cell}; + let mut s = rustgis_engine::Session::new(rustgis_engine::Project::default()); + let mut data = Dataset::new("values", GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); + for n in [0, 2, 10] { + data.push(Some(Geometry::Point(Coord::new(n as f64, 0.0))), vec![Cell::Int(n)]); + } + let id = rustgis_engine::cmd::layer::add_dataset(&mut s, data); + let fid = s.map().layer(id).unwrap().dataset.features[0].id; + let url = "https://wms.example.org/?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=over&STYLES=&CRS=EPSG:3857&BBOX={bbox-epsg-3857}&WIDTH=256&HEIGHT=256&FORMAT=image%2Fpng"; + s.run("map.addTiles", &json!({"url":url,"name":"Remote","overlay":true})).unwrap(); + s.run("select.rows", &json!({"layer":id,"rows":[0]})).unwrap(); + let pending = read_ahead(&mut s, "data.similar", &json!({"layer":id,"row":0,"fields":["n"],"count":1})).unwrap(); + let depth = s.undo_depth(); + let first = json!({"layerId":id,"fid":fid,"layer":"values","attributes":{"name":"Reference"}}); + let mut info = first.clone(); + info["results"] = json!([first,{"tileLayer":"Remote","attributes":{"name":"Remote feature"}}]); + let pp = Popup::new(info, Coord::new(0.0, 0.0), s.project.active_map, s.opened); + let mut app = RustGisApp::new(s); + app.map.popup = Some(pp); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state( + move |ui, app: &mut RustGisApp| { + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + let rect = ui.max_rect(); + popup(app, ui, rect); + }, + app, + ); + h.run(); + h.get_by_role_and_label(egui::accesskit::Role::Button, "›").click(); + h.run(); + assert_eq!(h.state().map.popup.as_ref().unwrap().index, 1); + assert!(h.state().session.map().layer(id).unwrap().selection.is_empty()); + assert_eq!(h.state().session.undo_depth(), depth, "pop-up browsing creates no Undo step"); + let mark = h.state().session.notice_mark(); + let answer = read_land(&mut h.state_mut().session, pending.run(&Control::stoppable()).unwrap()).unwrap(); + assert_eq!(answer["similar"][0]["row"], 1); + assert!(h.state().session.map().layer(id).unwrap().selection.is_empty(), "the pending read must preserve the pop-up clear"); + assert!(h.state().session.notices_since(mark).iter().any(|n| n.text.contains("without replacing the current selection"))); + } + /// A WMS layer's answer comes in the drawing order (#808): drawn over Countries, its feature /// comes first, and with topmost replaces Switzerland; drawn under the map's layers, it comes /// after them, and topmost keeps Switzerland. diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 2101200890..dc4e4fabf3 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1497,6 +1497,8 @@ the completed ranking appears in the Workflows pane. A changed layer, reference invalidates the result. Zooming without changing which display filters apply does not invalidate it. If you change selection while an explicit-reference request runs, its ranking still returns but it does not replace the newer selection. +An older result also preserves selection applied by a newer Similar request. Earlier completions +do not prevent later queued requests from selecting their own results. The reference must have a finite numeric value in every compared field; otherwise the command refuses without changing selection. Other incomplete candidate rows are skipped with one count, including when `select: false`. Standardization still uses each field's finite resident values. From 58d0427a01f5b7f4d9021d44e0a55a28c86c3fe9 Mon Sep 17 00:00:00 2001 From: mavrick Date: Fri, 20 Nov 2026 19:46:01 -0600 Subject: [PATCH 09/15] fix(engine): keep script admission and Similar pane ownership --- crates/engine/src/cmd/gp.rs | 9 +++- crates/engine/src/cmd/reads.rs | 6 +++ crates/engine/src/cmd/select.rs | 4 +- crates/engine/src/cmd/similar.rs | 24 ++++++----- crates/engine/src/cmd/workflows.rs | 12 ++++-- crates/engine/src/lib.rs | 33 ++++++++++---- crates/engine/src/policy/dispatch.rs | 10 ++++- crates/engine/src/tests.rs | 64 ++++++++++++++++++++++++++++ crates/ui-egui/src/analysispane.rs | 3 +- crates/ui-egui/src/lib.rs | 11 +++-- crates/ui-egui/src/readjob.rs | 15 ++++++- docs/user-guide/analysis.md | 6 +++ 12 files changed, 161 insertions(+), 36 deletions(-) diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index ac01f00872..5b03f3deeb 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -893,6 +893,8 @@ pub(crate) struct RanAheads { zones: Vec, // The copy's initial project can outlive history while queued or waiting to replay. pub(crate) retained: Option, + /// Selection effects and inner reads keep the parent admission through live replay. + pub(crate) selection_admission: Option<(u64, std::sync::Arc)>, } #[cfg(not(target_arch = "wasm32"))] @@ -902,6 +904,10 @@ pub(crate) struct RanAheads { /// later run takes them. pub(crate) fn taking(s: &mut Session, ran: RanAheads, run: impl FnOnce(&mut Session) -> T) -> T { let _retained = ran.retained; + let previous_admission = s.selection_admission.clone(); + if ran.selection_admission.is_some() { + s.selection_admission = ran.selection_admission; + } s.tools_ahead = Some(Ahead::Taking(ran.tools.into())); s.files_ahead = Some(FilesAhead::Taking(ran.files.into())); s.zones_ahead = Some(super::imagery::ZonesAhead::Taking(ran.zones.into())); @@ -909,6 +915,7 @@ pub(crate) fn taking(s: &mut Session, ran: RanAheads, run: impl FnOnce(&mut S s.tools_ahead = None; s.files_ahead = None; s.zones_ahead = None; + s.selection_admission = previous_admission; r.unwrap_or_else(|p| std::panic::resume_unwind(p)) } @@ -927,7 +934,7 @@ pub(crate) fn ran_ahead(s: &mut Session) -> RanAheads { Some(super::imagery::ZonesAhead::Recording(read)) => read, _ => Vec::new(), }; - RanAheads { tools, files, zones, retained: None } + RanAheads { tools, files, zones, retained: None, selection_admission: s.selection_admission.clone() } } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/cmd/reads.rs b/crates/engine/src/cmd/reads.rs index 852c2aa804..09ce2f04d1 100644 --- a/crates/engine/src/cmd/reads.rs +++ b/crates/engine/src/cmd/reads.rs @@ -339,6 +339,12 @@ pub(crate) fn take(s: &mut Session, key: &str) -> Option { read.value.downcast::().ok().map(|v| *v) } +/// Borrows prepared metadata during its admitted command, without consuming the value. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn peek<'a, T: 'static>(s: &'a Session, key: &str) -> Option<&'a T> { + s.read_ahead.as_ref().filter(|r| r.key == key)?.value.downcast_ref() +} + /// Whether a read is placed for `key`, without taking it. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn placed_for(s: &Session, key: &str) -> bool { diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 9ecb0b36fc..e37a53b4ae 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -126,12 +126,12 @@ fn area_mode(p: &Value) -> Result { /// Records an external clear without a command/Undo step, as pop-up browsing requires. pub fn clear(s: &mut Session) { s.map_mut().clear_selection(); - s.selection_generation = s.selection_generation.wrapping_add(1); + s.selection_intent = s.selection_intent.max(s.selection_epoch()); } /// Applies a selection to one layer (New clears the others too, like desktop GIS). pub fn set(s: &mut Session, id: u32, rows: Vec, m: Mode) { - s.selection_generation = s.selection_generation.wrapping_add(1); + s.selection_intent = s.selection_intent.max(s.selection_epoch()); apply(s, id, rows, m); } diff --git a/crates/engine/src/cmd/similar.rs b/crates/engine/src/cmd/similar.rs index f66c9903ed..e3199a20d5 100644 --- a/crates/engine/src/cmd/similar.rs +++ b/crates/engine/src/cmd/similar.rs @@ -35,7 +35,6 @@ struct Input { name: String, data: Dataset, visibility: Option, - selection_generation: u64, _retained: crate::undo_memory::ReadRows, } @@ -71,7 +70,6 @@ impl Input { name: l.name.clone(), data: l.dataset.clone(), visibility, - selection_generation: s.selection_generation, _retained: s.undo_memory.readers().retain(vec![l.dataset.features.allocation_key()]), }) } @@ -102,12 +100,16 @@ struct Done { struct Ahead { input: Input, done: Result, - request: u64, + request: (u64, u64), } /// Orders admissions, not completions. Script workers share this sequence with their session. -fn request(s: &Session) -> u64 { - s.similar_sequence.fetch_add(1, std::sync::atomic::Ordering::Relaxed).wrapping_add(1) +fn request(s: &Session) -> (u64, u64) { + #[cfg(not(target_arch = "wasm32"))] + if let Some((epoch, inner)) = &s.selection_admission { + return (*epoch, inner.fetch_add(1, std::sync::atomic::Ordering::Relaxed).wrapping_add(1)); + } + (s.selection_epoch(), 0) } /// Filters the bounded result/reference rows with cancellation, without a layer-wide mask. @@ -214,14 +216,14 @@ pub(super) fn run(s: &mut Session, p: &Value) -> CmdResult { }; #[cfg(not(target_arch = "wasm32"))] if ahead.is_none() && s.statistics_window_thread == Some(std::thread::current().id()) { - return Err("Similarity needs the desktop background read queue; run Find Similar or a direct MCP data.similar request".into()); + return Err("Similarity needs the desktop background read queue; use Find Similar or a direct MCP data.similar request. In desktop scripts, run file or network setup separately before the analysis script.".into()); } - let (done, selection_generation, request) = match ahead { - Some(a) if a.input.same(&input) => (a.done, a.input.selection_generation, a.request), + let (done, request) = match ahead { + Some(a) if a.input.same(&input) => (a.done, a.request), Some(_) => return Err("the layer, reference or map filters changed while similarity was computed: ask again".into()), None => { let request = request(s); - (gather(&input), input.selection_generation, request) + (gather(&input), request) } }; #[cfg(not(target_arch = "wasm32"))] @@ -230,12 +232,12 @@ pub(super) fn run(s: &mut Session, p: &Value) -> CmdResult { } let done = done?; if let Some(rows) = done.selection { - if selection_generation == s.selection_generation && request >= s.similar_selected { + if request.0 >= s.selection_intent && request >= s.similar_selected { super::select::set_similar_result(s, input.target.id, rows); s.similar_selected = request; } else { s.notify_text( - NoticeText::term(if selection_generation != s.selection_generation { + NoticeText::term(if request.0 < s.selection_intent { "Selection changed while similarity was computed; its ranking is returned without replacing the current selection" } else { "A newer Similar result has already changed selection; this ranking is returned without replacing it" diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 65b10e9fa3..de3c30bf43 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -825,8 +825,11 @@ pub(crate) fn ahead_on_copy(s: &Session, command: &'static str, p: &Value) -> su // The copy follows the extensions turned on or off here (#1752). let extensions = s.extensions().clone(); let (view_size, active_layer, opened, p) = (s.view_size, s.active_layer, s.opened, p.clone()); - let selection_generation = s.selection_generation; - let (similar_sequence, similar_selected) = (s.similar_sequence.clone(), s.similar_selected); + let selection_intent = s.selection_intent; + let (selection_sequence, similar_selected) = (s.selection_sequence.clone(), s.similar_selected); + // Reserve before the worker starts: its inner reads belong to this admission, even when + // a newer UI request arrives while this script waits in the queue. + let selection_admission = s.selection_admission.clone().unwrap_or_else(|| (s.selection_epoch(), Default::default())); // What its tools ask of servers and files goes in this session's Diagnostics, as when they // run here: the run here takes their results and asks nothing. let requests = s.diagnostics.capture(); @@ -838,8 +841,9 @@ pub(crate) fn ahead_on_copy(s: &Session, command: &'static str, p: &Value) -> su copy.view_size = view_size; copy.active_layer = active_layer; copy.opened = opened; - copy.selection_generation = selection_generation; - copy.similar_sequence = similar_sequence; + copy.selection_intent = selection_intent; + copy.selection_sequence = selection_sequence; + copy.selection_admission = Some(selection_admission); copy.similar_selected = similar_selected; // The copy shares this session's rows, which this session already counts in what the // process holds (#2431): it neither measures nor adds them again. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 9d71ee7c99..194a821e66 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -787,13 +787,16 @@ pub struct Session { pub registry: Registry, /// Bumped on every change so views can cache. pub revision: u64, - /// Runtime selection intent, including changes on other layers that a new selection clears. - /// Mutation dispatch conservatively advances it too; view-only commands leave it alone. - pub(crate) selection_generation: u64, - /// Similar requests share an order with script workers; their completion order may differ. - pub(crate) similar_sequence: std::sync::Arc, + /// The latest external selection admission, including changes on other layers. Mutations + /// conservatively record intent too; an older replay cannot advance it past newer intent. + pub(crate) selection_intent: u64, + /// External selection intent and Similar requests share one admission sequence. + pub(crate) selection_sequence: std::sync::Arc, + /// A prepared script/model's admission and its inner Similar request sequence. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) selection_admission: Option<(u64, std::sync::Arc)>, /// The last Similar request that applied selection here, independently of external intent. - pub(crate) similar_selected: u64, + pub(crate) similar_selected: (u64, u64), /// Bumped each time another project replaces this one (new, open, sample, template), however /// the command came (the app, an agent, a script): the interface drops what it kept for the /// old one. @@ -1269,6 +1272,16 @@ pub(crate) fn edits_features(id: &str) -> bool { } impl Session { + /// Attributes replayed selection effects to their initiating script/model. Ordinary + /// synchronous actions take a fresh admission, so later user intent wins over queued work. + pub(crate) fn selection_epoch(&self) -> u64 { + #[cfg(not(target_arch = "wasm32"))] + if let Some((epoch, _)) = &self.selection_admission { + return *epoch; + } + self.selection_sequence.fetch_add(1, std::sync::atomic::Ordering::Relaxed).wrapping_add(1) + } + /// Marks this thread as the desktop window owner for column statistics and shape fitting. Adapters with a /// window use the prepared read queue; headless adapters leave this disabled. #[cfg(not(target_arch = "wasm32"))] @@ -1316,9 +1329,11 @@ impl Session { layout_arrangements: serde_json::Map::new(), registry: Registry { commands: cmd::all() }, revision: 1, - selection_generation: 0, - similar_sequence: Default::default(), - similar_selected: 0, + selection_intent: 0, + selection_sequence: Default::default(), + #[cfg(not(target_arch = "wasm32"))] + selection_admission: None, + similar_selected: (0, 0), opened: 0, exchange: None, tool: Tool::Explore, diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 446bc29594..1ec945a5f3 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -953,6 +953,13 @@ impl Session { if let Some(error) = self.url_completion_refusal(spec.id, ¶ms)? { return Err(error); } + // The outer replay's mutation is part of its original admission, just like + // the inner commands. Read this metadata before the handler consumes it. + #[cfg(not(target_arch = "wasm32"))] + let selection_epoch = crate::cmd::reads::peek::(self, spec.id) + .and_then(|ran| ran.selection_admission.as_ref().map(|a| a.0)); + #[cfg(target_arch = "wasm32")] + let selection_epoch = None; let run = |s: &mut Session| { s.with_node(node, |s| { let editor = s.trust_editor(spec.id, ¶ms); @@ -989,7 +996,8 @@ impl Session { // Some edits replace selections without going through select::set. A pending // read must preserve the later intent, even when this edit touched another layer. // Similar's own result is derived output, not a new external selection intent. - self.selection_generation = self.selection_generation.wrapping_add(1); + let epoch = selection_epoch.unwrap_or_else(|| self.selection_epoch()); + self.selection_intent = self.selection_intent.max(epoch); } result } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 03081c17d1..3256ebe7f3 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -54838,6 +54838,70 @@ fn older_similar_completion_preserves_a_newer_similar_selection() { } } +/// Script admission precedes its worker's execution. A later Similar request owns selection +/// whether the script or that request completes first. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn script_admission_preserves_later_similar_and_user_selection() { + use crate::cmd::reads::{read_ahead, read_land}; + use rustgis_analysis::control::Control; + for script_lands_first in [false, true] { + for user_selects in [false, true] { + let (mut s, id) = similar_lifecycle_session(); + let script = json!({"script":"data.similar {\"layer\":\"values\",\"row\":0,\"fields\":[\"n\"],\"count\":1}"}); + let script = read_ahead(&mut s, "script.run", &script).unwrap(); + assert!(script.reads()); + let newer = read_ahead(&mut s, "data.similar", &json!({"layer":id,"row":2,"fields":["n"],"count":1})).unwrap(); + if user_selects { + s.run("select.rows", &json!({"layer":id,"rows":[2]})).unwrap(); + } + // The script's worker reaches its inner command only after the newer admission. + let script = script.run(&Control::stoppable()).unwrap(); + let newer = newer.run(&Control::stoppable()).unwrap(); + if script_lands_first { + read_land(&mut s, script).unwrap(); + let mark = s.notice_mark(); + assert_eq!(read_land(&mut s, newer).unwrap()["similar"][0]["row"], 1); + if user_selects { + assert!(s.notices_since(mark).iter().any(|n| n.text.contains("without replacing the current selection"))); + } else { + assert!(s.notices_since(mark).is_empty(), "an earlier script cannot invalidate later selection intent"); + } + } else { + read_land(&mut s, newer).unwrap(); + read_land(&mut s, script).unwrap(); + } + assert_eq!( + s.map().layer(id).unwrap().selection, + if user_selects { vec![2] } else { vec![1, 2] }, + "the later intent owns selection" + ); + } + } +} + +/// An unprepared desktop script refuses heavy inline work with a usable setup split; +/// the same script remains synchronous for a headless caller. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn unprepared_desktop_script_refuses_similar_with_setup_guidance() { + for window in [false, true] { + let (mut s, _) = similar_lifecycle_session(); + s.statistics_need_read_ahead(window); + let p = json!({"script": concat!( + "map.setScale {\"scale\":100000}\n", + "data.similar {\"layer\":\"values\",\"row\":0,\"fields\":[\"n\"],\"count\":1}" + )}); + let result = s.run("script.run", &p); + if window { + let error = result.unwrap_err(); + assert!(error.contains("background read queue") && error.contains("setup separately"), "{error}"); + } else { + assert_eq!(result.unwrap()["ran"][1]["result"]["similar"][0]["row"], 1); + } + } +} + /// A script worker and its live session share request order: a fresh command after replay /// must be newer than both Similar commands that the worker computed. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index a695341208..64dbcf9f4f 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -133,8 +133,7 @@ pub(crate) fn similar_ran(app: &mut RustGisApp, request: u64, landed: crate::Lan return; } let Some(asked) = app.workflow.similar_request.take() else { return }; - if app.ui.right != Some(crate::RightPane::Workflows) - || app.workflow.section != "similar" + if app.workflow.section != "similar" || app.workflow.layer != asked.layer || app.session.opened != asked.opened || app.session.map().instance_id() != asked.map diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5457ec07a4..5b5171cbbe 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3578,15 +3578,18 @@ impl RustGisApp { if let Some(why) = section.and_then(|s| analysispane::section_blocked(&self.session, s)) { return Err(why); } - // A pending ranking belongs to the section/request that started it. - analysispane::forget_similar(&mut self.workflow); // A map pick started in another section (or before the pane closes) ends here. self.workflow.pick = None; match section.and_then(|s| analysispane::SECTIONS.iter().find(|x| x.0 == s)) { Some((id, _)) => { + // Opening the same Similar section preserves its pending/completed result, + // including when the pane was hidden while the worker finished. + if *id != "similar" || self.workflow.section != *id { + analysispane::forget_similar(&mut self.workflow); + self.workflow.result = None; + self.workflow.error = None; + } self.workflow.section = id; - self.workflow.result = None; - self.workflow.error = None; self.ui.open_right(RightPane::Workflows); } None => toggle_right(&mut self.ui, RightPane::Workflows), diff --git a/crates/ui-egui/src/readjob.rs b/crates/ui-egui/src/readjob.rs index ffbb3a95ab..4c2510176b 100644 --- a/crates/ui-egui/src/readjob.rs +++ b/crates/ui-egui/src/readjob.rs @@ -1822,7 +1822,7 @@ mod tests { fn similar_pane_receives_success_failure_and_cancellation() { use egui_kittest::kittest::Queryable; use rustgis_engine::data::{Dataset, Field, FieldType, Geometry, GeometryType, Value as V}; - for outcome in ["success", "error", "cancel", "spawn", "newer", "layer", "workflow"] { + for outcome in ["success", "error", "cancel", "spawn", "newer", "layer", "workflow", "reopen", "closed"] { let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); let mut ds = Dataset::new("numbers", GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); for n in [0, 2, 10] { @@ -1884,6 +1884,12 @@ mod tests { } assert_eq!(showing(h.state()), outcome != "spawn", "{outcome}: worker admission"); assert!(h.state().workflow.result.is_none(), "a receipt is not a ranking"); + if outcome == "reopen" { + h.state_mut().run("ui.pane.workflows", json!({"section":"similar"})).unwrap(); + } else if outcome == "closed" { + h.state_mut().run("ui.pane.workflows", json!({})).unwrap(); + assert_ne!(h.state().ui.right, Some(crate::RightPane::Workflows)); + } match outcome { "workflow" => { let end = std::time::Instant::now() + Duration::from_secs(60); @@ -1925,13 +1931,18 @@ mod tests { h.step(); std::thread::sleep(Duration::from_millis(5)); // test-wait: worker completion delivered by the real app frame } + if outcome == "closed" { + assert!(h.state().workflow.result.is_some(), "closing the pane keeps its completed ranking for reopening"); + h.state_mut().run("ui.pane.workflows", json!({"section":"similar"})).unwrap(); + h.step(); + } // Completion used the full app frame above. Inspect the actual pane alone so its // diagnostic cannot be confused with the same text in another app surface. allow_landing.set(false); h.step(); h.run(); match outcome { - "success" | "workflow" => { + "success" | "workflow" | "reopen" | "closed" => { let answer = h.state().workflow.result.as_ref().expect("the pane shows the completed ranking"); assert_eq!(answer["similar"].as_array().unwrap().len(), 2); assert!(answer["similar"][0]["distance"].is_number()); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index dc4e4fabf3..d7082bca01 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1499,6 +1499,12 @@ If you change selection while an explicit-reference request runs, its ranking st does not replace the newer selection. An older result also preserves selection applied by a newer Similar request. Earlier completions do not prevent later queued requests from selecting their own results. +Script/model ordering starts when the whole run is queued, so its later-computed steps do not +overtake a newer Find Similar request. Closing the Workflows pane keeps the current ranking +and any pending request for reopening the same section; changing its section or layer replaces it. +Desktop scripts prepare only a replayable prefix. Run file or network setup separately before +the analysis script: a Similar step after setup that cannot be prepared is refused rather than +run on the window thread. Command-line and Python scripts still run synchronously. The reference must have a finite numeric value in every compared field; otherwise the command refuses without changing selection. Other incomplete candidate rows are skipped with one count, including when `select: false`. Standardization still uses each field's finite resident values. From 3e6cd0e473c0bab295edb054269dbefad259ea03 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 21 Nov 2026 11:15:43 -0600 Subject: [PATCH 10/15] fix(engine): accept verified script-created Similar inputs --- crates/data/src/source/duckdb.rs | 5 +++-- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/gp.rs | 27 ++++++++++++++++++++++----- crates/engine/src/cmd/similar.rs | 14 ++++++++++---- crates/engine/src/cmd/workflows.rs | 11 +++++++++++ crates/engine/src/tests.rs | 25 +++++++++++++++++++++++++ crates/ui-egui/src/analysispane.rs | 4 +++- crates/ui-egui/src/readjob.rs | 11 +++++++---- 8 files changed, 82 insertions(+), 17 deletions(-) diff --git a/crates/data/src/source/duckdb.rs b/crates/data/src/source/duckdb.rs index 872a961059..e0fb4e5dc9 100644 --- a/crates/data/src/source/duckdb.rs +++ b/crates/data/src/source/duckdb.rs @@ -1226,8 +1226,9 @@ mod tests { run_with_stand_in(&exe, dir.path(), &script).unwrap(); let args = std::fs::read_to_string(dir.path().join("args.txt")).unwrap(); let input = std::fs::read_to_string(dir.path().join("input.txt")).unwrap(); - assert!(!args.contains(secret) && !args.contains("read_parquet"), "{args}"); - assert!(args.lines().any(|a| a == "-bail") && !args.lines().any(|a| a == "-c"), "{args}"); + // A path may contain the dummy value too. Only these arguments are allowed; all SQL, + // including its test credential, must arrive on standard input instead. + assert_eq!(args.lines().collect::>(), ["-init", dir.path().join("init.sql").to_str().unwrap(), "-bail"]); assert_eq!(input, script, "the whole script, as it was"); } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 2ca4440d8f..07f4e5f1ba 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1303,7 +1303,7 @@ pub(crate) fn script_table( use super::gp::{Ahead, RanAhead}; if prepared { let next = match &mut s.tools_ahead { - Some(Ahead::Taking(ran)) => ran.pop_front(), + Some(Ahead::Taking(ran, _)) => ran.pop_front(), _ => None, }; let Some(RanAhead::Table(next)) = next else { diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index d162760691..b5225eda68 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -834,7 +834,7 @@ pub(crate) fn record_read(s: &mut Session, command: &'static /// A replayed read must consume its recorded result, never recompute after a mismatch. /// Past the recorded prefix, return no result so the caller's normal execution guard applies. pub(crate) fn take_read(s: &mut Session, command: &str, params: &Value) -> Result, String> { - let Some(Ahead::Taking(ran)) = &mut s.tools_ahead else { return Ok(None) }; + let Some(Ahead::Taking(ran, _)) = &mut s.tools_ahead else { return Ok(None) }; let mismatch = || "the script's prepared read changed: run the script again".to_string(); let Some(next) = ran.pop_front() else { return Ok(None) }; let RanAhead::Read(next) = next else { return Err(mismatch()) }; @@ -844,12 +844,19 @@ pub(crate) fn take_read(s: &mut Session, command: &str, params: &Val next.value.downcast::().map(|value| Some(*value)).map_err(|_| mismatch()) } +#[cfg(not(target_arch = "wasm32"))] +/// Whether this typed replay created the worker's layer identity. Callers must still compare +/// map, row storage and metadata with the live output; this never authorizes an existing layer. +pub(super) fn replay_created_layer(s: &Session, map: u64, layer: u32, instance: u64) -> bool { + matches!(&s.tools_ahead, Some(Ahead::Taking(_, created)) if created.contains(&(map, layer, instance))) +} + #[cfg(not(target_arch = "wasm32"))] /// The tools of a model or script run ahead: recorded on the copy, then taken in order by the run /// here. pub(crate) enum Ahead { Recording(Vec), - Taking(std::collections::VecDeque), + Taking(std::collections::VecDeque, std::collections::HashSet<(u64, u32, u64)>), } #[cfg(not(target_arch = "wasm32"))] @@ -893,6 +900,9 @@ pub(crate) enum FilesAhead { /// its batches read, in order. pub(crate) struct RanAheads { tools: Vec, + /// Worker-created (map, layer id, instance) identities; live replay creates fresh Layers + /// over their verified recorded rows. Existing layers never receive this exception. + pub(super) created_layers: std::collections::HashSet<(u64, u32, u64)>, files: Vec, zones: Vec, // The copy's initial project can outlive history while queued or waiting to replay. @@ -912,7 +922,7 @@ pub(crate) fn taking(s: &mut Session, ran: RanAheads, run: impl FnOnce(&mut S if ran.selection_admission.is_some() { s.selection_admission = ran.selection_admission; } - s.tools_ahead = Some(Ahead::Taking(ran.tools.into())); + s.tools_ahead = Some(Ahead::Taking(ran.tools.into(), ran.created_layers)); s.files_ahead = Some(FilesAhead::Taking(ran.files.into())); s.zones_ahead = Some(super::imagery::ZonesAhead::Taking(ran.zones.into())); let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(s))); @@ -938,7 +948,14 @@ pub(crate) fn ran_ahead(s: &mut Session) -> RanAheads { Some(super::imagery::ZonesAhead::Recording(read)) => read, _ => Vec::new(), }; - RanAheads { tools, files, zones, retained: None, selection_admission: s.selection_admission.clone() } + RanAheads { + tools, + created_layers: Default::default(), + files, + zones, + retained: None, + selection_admission: s.selection_admission.clone(), + } } #[cfg(not(target_arch = "wasm32"))] @@ -970,7 +987,7 @@ fn take_ahead( pin: &crate::policy::ToolPin, params: &Value, ) -> Option<(Result, FullIds, u64)> { - let Some(Ahead::Taking(ran)) = &mut s.tools_ahead else { return None }; + let Some(Ahead::Taking(ran, _)) = &mut s.tools_ahead else { return None }; let next = ran.pop_front()?; let RanAhead::Tool(next) = next else { s.tools_ahead = None; diff --git a/crates/engine/src/cmd/similar.rs b/crates/engine/src/cmd/similar.rs index d2dfbad07d..e8a8cfe5e7 100644 --- a/crates/engine/src/cmd/similar.rs +++ b/crates/engine/src/cmd/similar.rs @@ -75,12 +75,18 @@ impl Input { } /// Refuses data/reference/filter changes while work ran. Comparing row allocations avoids - /// copying or visiting features on the window thread. - fn same(&self, now: &Self) -> bool { + /// copying or visiting features on the window thread. Only replay-created output layers + /// may bridge worker/live instance ids; all captured rows and metadata still have to match. + fn same(&self, now: &Self, s: &Session) -> bool { + let instance = self.instance == now.instance; + #[cfg(not(target_arch = "wasm32"))] + let instance = instance || super::gp::replay_created_layer(s, self.map, self.target.id, self.instance); + #[cfg(target_arch = "wasm32")] + let _ = s; self.target == now.target && self.opened == now.opened && self.map == now.map - && self.instance == now.instance + && instance && self.name == now.name && self.data.features.shares(&now.data.features) && self.data.fields == now.data.fields @@ -219,7 +225,7 @@ pub(super) fn run(s: &mut Session, p: &Value) -> CmdResult { return Err("Similarity needs the desktop background read queue; use Find Similar or a direct MCP data.similar request. In desktop scripts, run file or network setup separately before the analysis script.".into()); } let (done, request) = match ahead { - Some(a) if a.input.same(&input) => (a.done, a.request), + Some(a) if a.input.same(&input, s) => (a.done, a.request), Some(_) => return Err("the layer, reference or map filters changed while similarity was computed: ask again".into()), None => { let request = request(s); diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index aa5ce2cf4e..9dc2a4e1b5 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -850,11 +850,22 @@ pub(crate) fn ahead_on_copy(s: &Session, command: &'static str, p: &Value) -> su copy.undo_memory.memory = None; copy.undo_memory.use_readers(readers); copy.sync_policy_generation(); + // Capture only runtime identities on the worker, not feature copies. New tool outputs + // become fresh Layer instances again when their recorded datasets land in the live map. + let initial: std::collections::HashSet = + copy.project.maps.iter().flat_map(|map| map.layers.iter().map(|layer| layer.instance_id())).collect(); copy.tools_ahead = Some(super::gp::Ahead::Recording(Vec::new())); copy.files_ahead = Some(super::gp::FilesAhead::Recording(Vec::new())); copy.zones_ahead = Some(super::imagery::ZonesAhead::Recording(Vec::new())); let _ = copy.run(command, &p); let mut ran = super::gp::ran_ahead(&mut copy); + for map in ©.project.maps { + for layer in &map.layers { + if !initial.contains(&layer.instance_id()) { + ran.created_layers.insert((map.instance_id(), layer.id, layer.instance_id())); + } + } + } ran.retained = Some(retained); ran }) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1fac8f3982..d24b749374 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -55931,6 +55931,31 @@ fn unprepared_desktop_script_refuses_similar_with_setup_guidance() { } } +/// A tool output is a new Layer in each session, but its verified recorded rows are the same. +/// Only replay-owned creations may bridge that identity difference. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn similar_accepts_replayed_tool_output_but_not_unrelated_replacement() { + use crate::cmd::reads::{read_ahead, read_land}; + use rustgis_analysis::control::Control; + let (mut s, _) = similar_lifecycle_session(); + s.statistics_need_read_ahead(true); + let p = json!({"script": concat!( + "gp.run {\"tool\":\"buffer\",\"params\":{\"input\":\"values\",\"distance\":10,\"output\":\"buffered\"}}\n", + "data.similar {\"layer\":\"buffered\",\"row\":0,\"fields\":[\"n\"],\"count\":1}" + )}); + let read = read_ahead(&mut s, "script.run", &p).unwrap().run(&Control::stoppable()).unwrap(); + let answer = read_land(&mut s, read).unwrap(); + assert_eq!(answer["ran"][1]["result"]["similar"][0]["row"], 1); + let id = s.map().layer_by_name("buffered").unwrap().id; + let p = json!({"layer":id,"row":0,"fields":["n"],"count":1}); + let read = read_ahead(&mut s, "data.similar", &p).unwrap().run(&Control::stoppable()).unwrap(); + s.map_mut().layer_mut(id).unwrap().renew_instance_id(); + assert!(read_land(&mut s, read).unwrap_err().contains("changed while"), "an unrelated identity replacement stays stale"); + s.run("edit.undo", &Value::Null).unwrap(); + assert!(s.map().layer_by_name("buffered").is_none()); +} + /// A script worker and its live session share request order: a fresh command after replay /// must be newer than both Similar commands that the worker computed. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 64dbcf9f4f..e7fcf114fe 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -642,7 +642,9 @@ pub fn workflows(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { .width(ui.available_width() - 8.0) .show_ui(ui, |ui| { for (id, title) in SECTIONS.iter().filter(|s| section_shown(&app.session, s.0)) { - if ui.selectable_label(app.workflow.section == *id, tl!(*title)).clicked() { + if ui.selectable_label(app.workflow.section == *id, tl!(*title)).clicked() + && (*id != "similar" || app.workflow.section != *id) + { forget_similar(&mut app.workflow); app.workflow.section = id; app.workflow.result = None; diff --git a/crates/ui-egui/src/readjob.rs b/crates/ui-egui/src/readjob.rs index 4c2510176b..6a83a61446 100644 --- a/crates/ui-egui/src/readjob.rs +++ b/crates/ui-egui/src/readjob.rs @@ -1822,13 +1822,13 @@ mod tests { fn similar_pane_receives_success_failure_and_cancellation() { use egui_kittest::kittest::Queryable; use rustgis_engine::data::{Dataset, Field, FieldType, Geometry, GeometryType, Value as V}; - for outcome in ["success", "error", "cancel", "spawn", "newer", "layer", "workflow", "reopen", "closed"] { + for outcome in ["success", "error", "cancel", "spawn", "newer", "layer", "workflow", "reopen", "closed", "error_layer"] { let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); let mut ds = Dataset::new("numbers", GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); for n in [0, 2, 10] { ds.push( Some(Geometry::Point(rustgis_engine::geom::Coord::new(n as f64, n as f64))), - vec![if n == 0 && outcome == "error" { V::Null } else { V::Int(n) }], + vec![if n == 0 && matches!(outcome, "error" | "error_layer") { V::Null } else { V::Int(n) }], ); } let id = rustgis_engine::cmd::layer::add_dataset(&mut app.session, ds.clone()); @@ -1901,7 +1901,7 @@ mod tests { assert!(h.state().workflow.result.is_none(), "another section cannot show its result in the Similar pane"); } "cancel" => h.state().reads.cancel_for_tests(), - "layer" => { + "layer" | "error_layer" => { h.state_mut().workflow.layer = "other".into(); h.state_mut().workflow.result = Some(json!({"kept":"other layer"})); } @@ -1970,7 +1970,10 @@ mod tests { h.query_by_role_and_label(egui::accesskit::Role::Label, h.state().workflow.error.as_deref().unwrap()).is_some() ); } - "layer" => { + "layer" | "error_layer" => { + if outcome == "error_layer" { + assert_eq!(h.state().session.notices.iter().filter(|n| n.error && n.text.contains("reference row")).count(), 1); + } assert_eq!(h.state().workflow.result, Some(json!({"kept":"other layer"}))); assert!(h.state().workflow.error.is_none()); } From 86033f89c9a43cc482be31c5aa7b1d6b49ce7e9a Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 21 Nov 2026 12:11:58 -0600 Subject: [PATCH 11/15] fix(ui): clear Similar output on automatic layer fallback --- crates/ui-egui/src/analysispane.rs | 7 ++++++- crates/ui-egui/src/readjob.rs | 10 ++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index e7fcf114fe..5525e1ba6e 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -685,7 +685,12 @@ pub fn workflows(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { _ => &features, }; if !inputs.contains(&w.layer) { - w.layer = inputs.first().cloned().unwrap_or_default(); + let layer = inputs.first().cloned().unwrap_or_default(); + if w.section == "similar" && w.layer != layer { + forget_similar(w); + (w.result, w.error) = (None, None); + } + w.layer = layer; } if (w.section == "zonalStats" || w.section == "process") && !polygons.contains(&w.layer2) { w.layer2 = polygons.first().cloned().unwrap_or_default(); diff --git a/crates/ui-egui/src/readjob.rs b/crates/ui-egui/src/readjob.rs index 6a83a61446..fb12297ee2 100644 --- a/crates/ui-egui/src/readjob.rs +++ b/crates/ui-egui/src/readjob.rs @@ -1948,6 +1948,16 @@ mod tests { assert!(answer["similar"][0]["distance"].is_number()); assert!(h.query_by_label_contains("distance").is_some(), "the ranking is drawn in the pane"); assert!(h.state().workflow.error.is_none()); + if outcome == "success" { + let answer = h.state().workflow.result.clone(); + h.step(); + assert_eq!(h.state().workflow.result, answer, "an unchanged layer keeps its ranking"); + h.state_mut().run("layer.remove", json!({"layer":id})).unwrap(); + h.step(); + assert_eq!(h.state().workflow.layer, "other"); + assert!(h.state().workflow.result.is_none() && h.state().workflow.error.is_none()); + assert!(h.query_by_label_contains("distance").is_none(), "a fallback layer cannot show the removed layer's rows"); + } } "error" => { assert!(h.state().workflow.result.is_none()); From 53ea95ab7a106e3ae851b421769660562c4bb66f Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 21 Nov 2026 16:13:32 -0600 Subject: [PATCH 12/15] fix(engine): retain identities of removed prepared outputs --- crates/engine/src/cmd/gp.rs | 19 +++++++++---------- crates/engine/src/cmd/workflows.rs | 11 ----------- crates/engine/src/tests.rs | 10 +++++++++- 3 files changed, 18 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index fb25973e3f..463a35f5ad 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -904,7 +904,7 @@ pub(crate) struct RanAheads { tools: Vec, /// Worker-created (map, layer id, instance) identities; live replay creates fresh Layers /// over their verified recorded rows. Existing layers never receive this exception. - pub(super) created_layers: std::collections::HashSet<(u64, u32, u64)>, + created_layers: std::collections::HashSet<(u64, u32, u64)>, files: Vec, zones: Vec, // The copy's initial project can outlive history while queued or waiting to replay. @@ -945,6 +945,13 @@ pub(crate) fn ran_ahead(s: &mut Session) -> RanAheads { Some(Ahead::Recording(ran)) => ran, _ => Vec::new(), }; + // Outputs were captured when installed, before a following step could remove them. + // Their worker identities must survive until live replay reaches those steps too. + let created_layers = tools + .iter() + .filter_map(|ran| if let RanAhead::Tool(tool) = ran { Some(tool) } else { None }) + .flat_map(|tool| tool.grid_outputs.iter().map(|layer| (tool.read.map.instance_id(), layer.id, layer.instance_id()))) + .collect(); let files = match s.files_ahead.take() { Some(FilesAhead::Recording(read)) => read, _ => Vec::new(), @@ -957,15 +964,7 @@ pub(crate) fn ran_ahead(s: &mut Session) -> RanAheads { Some(crate::image_grid::Ahead::Recording(read)) => read, _ => Vec::new(), }; - RanAheads { - tools, - created_layers: Default::default(), - files, - zones, - grids, - retained: None, - selection_admission: s.selection_admission.clone(), - } + RanAheads { tools, created_layers, files, zones, grids, retained: None, selection_admission: s.selection_admission.clone() } } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 26b1fe4d27..f2d016efab 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -850,23 +850,12 @@ pub(crate) fn ahead_on_copy(s: &Session, command: &'static str, p: &Value) -> su copy.undo_memory.memory = None; copy.undo_memory.use_readers(readers); copy.sync_policy_generation(); - // Capture only runtime identities on the worker, not feature copies. New tool outputs - // become fresh Layer instances again when their recorded datasets land in the live map. - let initial: std::collections::HashSet = - copy.project.maps.iter().flat_map(|map| map.layers.iter().map(|layer| layer.instance_id())).collect(); copy.tools_ahead = Some(super::gp::Ahead::Recording(Vec::new())); copy.files_ahead = Some(super::gp::FilesAhead::Recording(Vec::new())); copy.grids_ahead = Some(crate::image_grid::Ahead::Recording(Vec::new())); copy.zones_ahead = Some(super::imagery::ZonesAhead::Recording(Vec::new())); let _ = copy.run(command, &p); let mut ran = super::gp::ran_ahead(&mut copy); - for map in ©.project.maps { - for layer in &map.layers { - if !initial.contains(&layer.instance_id()) { - ran.created_layers.insert((map.instance_id(), layer.id, layer.instance_id())); - } - } - } ran.retained = Some(retained); ran }) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b5aa76d820..4586d292b1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -56501,7 +56501,7 @@ fn unprepared_desktop_script_refuses_similar_with_setup_guidance() { } /// A tool output is a new Layer in each session, but its verified recorded rows are the same. -/// Only replay-owned creations may bridge that identity difference. +/// Only replay-owned creations may bridge that identity difference, even if a later step removes them. #[cfg(not(target_arch = "wasm32"))] #[test] fn similar_accepts_replayed_tool_output_but_not_unrelated_replacement() { @@ -56516,6 +56516,14 @@ fn similar_accepts_replayed_tool_output_but_not_unrelated_replacement() { let read = read_ahead(&mut s, "script.run", &p).unwrap().run(&Control::stoppable()).unwrap(); let answer = read_land(&mut s, read).unwrap(); assert_eq!(answer["ran"][1]["result"]["similar"][0]["row"], 1); + let (mut removed, _) = similar_lifecycle_session(); + removed.statistics_need_read_ahead(true); + let mut removal = p.clone(); + removal["script"] = json!(format!("{}\nlayer.remove {{\"layer\":\"buffered\"}}", p["script"].as_str().unwrap())); + let read = read_ahead(&mut removed, "script.run", &removal).unwrap().run(&Control::stoppable()).unwrap(); + let answer = read_land(&mut removed, read).unwrap(); + assert_eq!(answer["ran"][1]["result"]["similar"][0]["row"], 1); + assert!(removed.map().layer_by_name("buffered").is_none()); let id = s.map().layer_by_name("buffered").unwrap().id; let p = json!({"layer":id,"row":0,"fields":["n"],"count":1}); let read = read_ahead(&mut s, "data.similar", &p).unwrap().run(&Control::stoppable()).unwrap(); From b12e8a55d6f8e6a5e39b335caa2bd7825c111b30 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 21 Nov 2026 19:00:02 -0600 Subject: [PATCH 13/15] docs(engine): state topology conversion and cancellation costs --- crates/analysis/src/network.rs | 2 +- crates/engine/src/cmd/design.rs | 7 ++++--- docs/user-guide/analysis.md | 4 +++- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 0b892bf960..e90a596544 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -800,7 +800,7 @@ pub fn profile_fields(ds: &Dataset) -> Vec { .collect() } -/// Ranked rows and the count of other resident rows lacking a finite value in every +/// Ranked rows and the count of other resident rows lacking a finite value in at least one /// compared field. Per-field standardization still uses every finite value in that field. #[derive(Debug)] pub struct Similarity { diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index d5a5626c2f..8e303d2ed9 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -2352,9 +2352,10 @@ struct TopologyChecked { /// Checks each rule and its query on the worker, with Cancel between rows/rules and counted /// query progress. Each rule's row indices and converted data are released before the next. -/// One row's expression evaluation, coordinate conversion, latitude validation and a gaps -/// check's polygon union are indivisible library steps, checked around them; geometric checks -/// otherwise look between features. +/// One row's expression evaluation or coordinate conversion, the initial full-row copy for a +/// projected dataset, each complete latitude-validation pass and a gaps check's polygon union +/// are indivisible library steps, checked around them; geometric checks otherwise look between +/// features. /// A cancellable run takes no work limit (see `rustgis_analysis::topology`). fn check_topology(inputs: &[TopologyInput], tol: f64) -> Result { use rustgis_analysis::topology as t; diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 1ee83bf54c..41dca3704d 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1531,7 +1531,9 @@ An older result also preserves selection applied by a newer Similar request. Ear do not prevent later queued requests from selecting their own results. Script/model ordering starts when the whole run is queued, so its later-computed steps do not overtake a newer Find Similar request. Closing the Workflows pane keeps the current ranking -and any pending request for reopening the same section; changing its section or layer replaces it. +and any pending request for reopening the same section. Changing section or layer discards the +pane's ranking but does not cancel the command; its selection can still apply unless a newer +selection takes precedence. Use Cancel to stop the computation. Desktop scripts prepare only a replayable prefix. Run file or network setup separately before the analysis script: a Similar step after setup that cannot be prepared is refused rather than run on the window thread. Command-line and Python scripts still run synchronously. From 62cc4cbe13435637cde06cc1174dcaf14350f933 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 21 Nov 2026 20:47:16 -0600 Subject: [PATCH 14/15] fix(engine): refuse invalid Similar reference and count --- AGENTS.md | 4 +-- crates/engine/src/cmd/similar.rs | 16 ++++++++--- crates/engine/src/cmd/workflows.rs | 2 +- crates/engine/src/tests.rs | 44 ++++++++++++++++++++++++++++++ crates/ui-egui/src/analysispane.rs | 2 +- docs/user-guide/analysis.md | 5 +++- docs/user-guide/editing.md | 4 +-- 7 files changed, 66 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c83665100f..e4c20bd0b8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,8 +43,8 @@ is out of scope. - A new background raster command or export, or a tool whose work grows with its input, goes in the lists in `long_commands` (`crates/engine/src/tests/cancellation.rs`), which both cancel tests run; the raster and export lists must match the background registries. A read-ahead command - (`reads::prepare`, such as `service.layers`, `edit.previewShapeConversion` or `data.similar`) has no registry: - add its call to `long_commands` by hand. + (`reads::prepare`, such as `service.layers`, `edit.previewShapeConversion` or `data.similar`) + has no registry: add its call to `long_commands` by hand. `long_commands_stop_when_cancelled_while_they_run` fails one that never looks at Cancel; `cancelling_at_each_check_leaves_nothing_behind` cancels at every check in turn until the command finishes before reaching it, on small fixtures, failing if one needs 256 or more checks. It diff --git a/crates/engine/src/cmd/similar.rs b/crates/engine/src/cmd/similar.rs index e8a8cfe5e7..c01f0c1db2 100644 --- a/crates/engine/src/cmd/similar.rs +++ b/crates/engine/src/cmd/similar.rs @@ -44,9 +44,12 @@ impl Input { fn resolve(s: &Session, p: &Value) -> Result { let id = s.layer_id(p)?; let l = s.map().layer(id).ok_or("no such layer")?; - let row = match p.get("row").and_then(Value::as_u64) { - Some(r) => r as usize, - None => *l.selection.first().ok_or("select a feature (or give row)")?, + let row = match p.get("row") { + None | Some(Value::Null) => *l.selection.first().ok_or("select a feature (or give row)")?, + Some(value) => { + let row = value.as_u64().ok_or("row must be a non-negative whole number")?; + usize::try_from(row).map_err(|_| "no such row")? + } }; if row >= l.dataset.features.len() { return Err("no such row".into()); @@ -55,7 +58,12 @@ impl Input { if fields.is_empty() { return Err("the layer has no numeric fields to compare".into()); } - let count = p.get("count").and_then(Value::as_u64).unwrap_or(10).clamp(1, 1000) as usize; + let count = match p.get("count") { + None | Some(Value::Null) => 10, + Some(value) => { + value.as_u64().filter(|count| (1..=1000).contains(count)).ok_or("count must be a whole number from 1 to 1000")? + } + } as usize; let select = super::b(p, "select").unwrap_or(true); let visibility = select.then(|| Visibility { query: l.definition_query.clone(), diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index f2d016efab..9d65c90fc5 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -94,7 +94,7 @@ pub fn commands() -> Vec { .view() .params(r#"{"layer"?, "fields"?: [numeric fields], "bins"?: number}"#), C::new("data.similar", "Embeddings", "Analyze › Workflows", super::similar::run).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"layer"?, "row"?: number (the selected feature when omitted), "fields"?: [numeric fields], "count"?: number, "select"?: bool}"#), + .params(r#"{"layer"?, "row"?: number (zero-based whole number; selected feature when omitted or null), "fields"?: [numeric fields], "count"?: number (whole number 1 to 1000; default 10), "select"?: bool}"#), C::new("data.convert", "Data Interop", "Analyze › Workflows", convert).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .params(r#"{"layer"?, "format": "geojson"|"csv"|"kml"|"gpx"|"wkt", "path"?: file (the text is returned without one), "nameField"?: field}"#), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c6d5b7de09..d6c11b796b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -56627,6 +56627,50 @@ fn similar_lifecycle_session() -> (Session, u32) { (s, id) } +/// Invalid explicit references must not fall back to the selected feature or replace selection. +#[test] +fn similar_rejects_invalid_rows_without_selecting() { + let (mut s, id) = similar_lifecycle_session(); + s.run("select.rows", &json!({"layer":id,"rows":[0]})).unwrap(); + let depth = s.undo_depth(); + for row in [json!(-1), json!("1"), json!(1.5), json!(u64::MAX)] { + let error = s.run("data.similar", &json!({"layer":id,"row":row,"fields":["n"]})).unwrap_err(); + assert!(error.contains("row"), "{row}: {error}"); + assert_eq!(s.map().layer(id).unwrap().selection, vec![0]); + assert_eq!(s.undo_depth(), depth); + } + let params = json!({"layer":id,"fields":["n"],"select":false}); + let expected = s.run("data.similar", ¶ms).unwrap(); + for row in [Value::Null, json!(0)] { + let mut params = params.clone(); + params["row"] = row; + assert_eq!(s.run("data.similar", ¶ms).unwrap(), expected); + } +} + +/// Invalid counts must be refused rather than silently changing the requested ranking size. +#[test] +fn similar_rejects_invalid_counts_without_selecting() { + let (mut s, id) = similar_lifecycle_session(); + s.run("select.rows", &json!({"layer":id,"rows":[0]})).unwrap(); + let depth = s.undo_depth(); + for count in [json!(0), json!(1001), json!(-1), json!("2"), json!(1.5)] { + let error = s.run("data.similar", &json!({"layer":id,"row":0,"count":count,"fields":["n"]})).unwrap_err(); + assert!(error.contains("count"), "{count}: {error}"); + assert_eq!(s.map().layer(id).unwrap().selection, vec![0]); + assert_eq!(s.undo_depth(), depth); + } + let params = json!({"layer":id,"row":0,"fields":["n"],"select":false}); + let expected = s.run("data.similar", ¶ms).unwrap(); + let mut params = params; + params["count"] = Value::Null; + assert_eq!(s.run("data.similar", ¶ms).unwrap(), expected); + for count in [1, 1000] { + params["count"] = json!(count); + assert_eq!(s.run("data.similar", ¶ms).unwrap()["similar"].as_array().unwrap().len(), count.min(2)); + } +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn native_script_replays_similar_and_topology_before_the_following_line() { diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 0e97e7499c..2c4103982e 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -643,7 +643,7 @@ pub fn workflows(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { .show_ui(ui, |ui| { for (id, title) in SECTIONS.iter().filter(|s| section_shown(&app.session, s.0)) { if ui.selectable_label(app.workflow.section == *id, tl!(*title)).clicked() - && (*id != "similar" || app.workflow.section != *id) + && (app.workflow.section != "similar" || *id != "similar") { forget_similar(&mut app.workflow); app.workflow.section = id; diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 41dca3704d..6e33aa7835 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1515,7 +1515,10 @@ click them on the map: Data Engineering and Exploratory Analysis use every resident row, independently of the layer's selection and map filters. Embeddings also compares and standardizes numeric values -over every resident row; the selection supplies its reference when no explicit row is given. +over every resident row; the selection supplies its reference when `row` is omitted or null. +An explicit `row` must be a zero-based whole number in the layer. `count` must be a whole number +from 1 to 1000; omitting it or passing null uses 10. Invalid values are refused without changing +selection. Its returned matches can include hidden rows. With the default `select: true`, only matches and the reference that pass the layer's definition query, time window and display filters are selected; one notice counts those excluded. Unreadable definition queries or active diff --git a/docs/user-guide/editing.md b/docs/user-guide/editing.md index 645e8e7cb2..9cd0fda6e3 100644 --- a/docs/user-guide/editing.md +++ b/docs/user-guide/editing.md @@ -162,8 +162,8 @@ you edit the value or choose units; click **Apply elevation** to apply the new i caller's thread; when they cannot be cancelled, they stop after a fixed amount of work, saying which rules weren't checked completely (a gaps rule's join has no such limit). A desktop window requires the background queue instead of running the check inline. A line or - ring too complex to check for self-intersections within the limit is listed at its first point, to be looked - at, and its rule is said to be incomplete. + ring too complex to check for self-intersections within the limit is listed at its first point, + to be looked at, and its rule is said to be incomplete. Beyond 85.05° they follow the geometry tools (see [Geoprocessing tools](analysis.md#geoprocessing-tools), **Near the poles**). - **Status**: features added, changed and deleted per layer since the last save. From 2e1b38c43f245db637d18d1f816ae60703d52a3d Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 21 Nov 2026 21:57:03 -0600 Subject: [PATCH 15/15] fix(engine): preserve history-restored selection during Similar --- crates/engine/src/policy/dispatch.rs | 7 ++++--- crates/engine/src/tests.rs | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 5ee95b0b75..1eb140b52c 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -995,9 +995,10 @@ impl Session { Txn::Shared => run(self), }; self.url_completion_landed(spec.id, ¶ms, &result); - if result.is_ok() && spec.mutates && spec.id != "data.similar" { - // Some edits replace selections without going through select::set. A pending - // read must preserve the later intent, even when this edit touched another layer. + if result.is_ok() && (spec.mutates || spec.effects.contains(crate::policy::Effect::History)) && spec.id != "data.similar" { + // Edits and history moves can replace selections without select::set. History + // commands are non-mutating to avoid an extra Undo snapshot, but still express + // later selection intent. Pending reads must preserve it, on any layer. // Similar's own result is derived output, not a new external selection intent. let epoch = selection_epoch.unwrap_or_else(|| self.selection_epoch()); self.selection_intent = self.selection_intent.max(epoch); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 65b7e38529..7a5fd7515c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -57354,6 +57354,31 @@ fn prepared_similar_preserves_newer_selection_on_any_layer() { } } +#[test] +fn prepared_similar_preserves_selection_after_undo_and_redo() { + use crate::cmd::reads::{read_ahead, read_land}; + use rustgis_analysis::control::Control; + for redo in [false, true] { + let (mut s, id) = similar_lifecycle_session(); + s.run("select.rows", &json!({"layer":id,"rows":[0]})).unwrap(); + s.run("select.rows", &json!({"layer":id,"rows":[2]})).unwrap(); + if redo { + s.run("edit.undo", &Value::Null).unwrap(); + } + // History changes only selection, so the ranking's shared rows still match. + let p = json!({"layer":id,"row":0,"fields":["n"],"count":1}); + let read = read_ahead(&mut s, "data.similar", &p).unwrap().run(&Control::stoppable()).unwrap(); + let command = if redo { "edit.redo" } else { "edit.undo" }; + s.run(command, &Value::Null).unwrap(); + let expected = if redo { vec![2] } else { vec![0] }; + assert_eq!(s.map().layer(id).unwrap().selection, expected, "{command} restores selection before completion"); + let mark = s.notice_mark(); + assert_eq!(read_land(&mut s, read).unwrap()["similar"][0]["row"], 1); + assert_eq!(s.map().layer(id).unwrap().selection, expected, "{command} owns the later selection"); + assert!(s.notices_since(mark).iter().any(|n| n.text.contains("without replacing the current selection"))); + } +} + #[test] fn queued_similar_results_preserve_later_requests_and_user_intent() { use crate::cmd::reads::{read_ahead, read_land};