diff --git a/AGENTS.md b/AGENTS.md index 76a5649243..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` or `edit.previewShapeConversion`) 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/analysis/src/network.rs b/crates/analysis/src/network.rs index 7a3679cc89..e90a596544 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -800,29 +800,105 @@ pub fn profile_fields(ds: &Dataset) -> Vec { .collect() } +/// 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 { + 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. -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. +/// 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))); + 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(); + 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(); + 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 { + return Err("the reference row needs a finite numeric value in every compared field".into()); + }; + let mut distance_pace = control::Pace::default(); + let mut out = Vec::new(); + let mut skipped = 0; + for r in 0..ds.features.len() { + control::check()?; + control::advance(1); + if r != row { + let Some(v) = vec_of(r)? else { + skipped += 1; + continue; + }; + 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(Similarity { matches: out, skipped }) } fn radius_scale(at: Coord) -> f64 { @@ -1533,8 +1609,8 @@ 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); - assert_eq!(sim[0].0, 1); + let sim = similar(&ds, 0, &[0], 2).unwrap(); + 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 de54c68184..47f7e17fee 100644 --- a/crates/assistant/src/mcp.rs +++ b/crates/assistant/src/mcp.rs @@ -165,6 +165,8 @@ impl ArchiveBatch { "map.reloadTiles" | "map.repairTiles" | "table.statistics" + | "data.similar" + | "topology.validate" | "edit.previewShapeConversion" | "raster.imageGrid" | "layer.sizeBy" diff --git a/crates/data/src/source/duckdb.rs b/crates/data/src/source/duckdb.rs index 5ad7f20cc9..e0fb4e5dc9 100644 --- a/crates/data/src/source/duckdb.rs +++ b/crates/data/src/source/duckdb.rs @@ -1219,15 +1219,16 @@ mod tests { fn a_querys_credentials_stay_out_of_duckdbs_arguments() { let dir = tempfile::tempdir().unwrap(); let exe = recording_duckdb(dir.path()); - let secret = "X-Amz-Signature=0123456789abcdef-synthetic"; + let secret = "dummy"; let sql = format!("SELECT * FROM read_parquet('https://bucket.example/data.parquet?{secret}')\nWHERE 'line;\n.shell no' <> ''"); let script = format!("{} CREATE TEMP TABLE r AS SELECT * FROM query({});", prelude(dir.path(), None, false).unwrap(), literal(&sql)); 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/design.rs b/crates/engine/src/cmd/design.rs index 80ac2c497e..482a532ef9 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -2284,50 +2284,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 as it holds its coordinates, and its covering layer: rows shared with the map's, - /// so a check read ahead is known to have read what the rules read now. Each is converted to - /// longitude/latitude, where the rules are checked, as the check runs. data: rustgis_data::Dataset, - rows: Vec, + query: Option, by: 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. +/// 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 rows: Vec = l.visible_rows().iter().enumerate().filter(|(_, v)| **v).map(|(i, _)| i).collect(); - // A covering layer that is gone leaves the rule with nothing to check (its layer's - // latitudes are still checked). + // 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 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: l.dataset.clone(), rows, by }); + inputs.push(TopologyInput { rule, layer: l.name.clone(), data: l.dataset.clone(), query: l.definition_query.clone(), by }); } inputs } -/// Whether two layers' data are the same: the same system they hold coordinates in (a relabel -/// keeps the rows), 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.coord_crs() == b.coord_crs() && 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 == b.query && same_data(&a.data, &b.data) && match (&a.by, &b.by) { (Some(x), Some(y)) => same_data(x, y), @@ -2337,44 +2336,97 @@ 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 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; - 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())?; - // In longitude/latitude, a copy only of a layer held in another system; refused, naming - // the layer, rather than checked on coordinates of another system. - // A cancel while converting is the check's cancel, said as the rules' is. + 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 named = |e: String| { if matches!(rustgis_data::DataError::of_conversion(e.clone()), rustgis_data::DataError::Cancelled) { - "the topology check was cancelled".to_string() + cancelled() } else { format!("{}: {e}", i.layer) } }; let data = i.data.in_lonlat().map_err(named)?; let by = i.by.as_ref().map(|b| b.in_lonlat().map_err(named)).transpose()?; - rustgis_analysis::validate_latitudes(&data, i.rows.iter().copied())?; - found.push(match (&i.rule, &by) { - (TopologyRule::MustNotOverlap { .. }, _) => t::overlaps(&data, &i.rows), - (TopologyRule::MustNotHaveGaps { .. }, _) => t::gaps(&data, &i.rows), - (TopologyRule::MustNotSelfIntersect { .. }, _) => t::self_intersections(&data, &i.rows), - (TopologyRule::MustNotHaveDangles { .. }, _) => t::dangles(&data, &i.rows, tol), + rustgis_data::progress::check().map_err(|_| cancelled())?; + 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(&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. @@ -2387,12 +2439,24 @@ 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, - /// The datum grids there were when it was made ([`rustgis_data::raster::crs::grid_generation`]): - /// a grid that arrives meanwhile changes how a layer held in another system converts. + /// Datum grids captured at admission; a newly available grid changes conversion results. grids: u64, - 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 @@ -2400,13 +2464,15 @@ struct TopologyAhead { /// 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 (opened, map) = (s.opened, s.map().instance_id()); if inputs.is_empty() { return None; } + let retained = retain_topology(s, &inputs); let grids = rustgis_data::raster::crs::grid_generation(); Some(super::reads::ahead("Error Inspector", TOPOLOGY_AHEAD.to_string(), move || { let found = check_topology(&inputs, tol); - TopologyAhead { inputs, tol, grids, found } + TopologyAhead { opened, map, inputs, tol, grids, found, _retained: retained } })) } @@ -2416,22 +2482,61 @@ 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) { + let grids = rustgis_data::raster::crs::grid_generation(); + 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.tol == tol && ahead.grids == rustgis_data::raster::crs::grid_generation() && same_topology(&ahead.inputs, &inputs) => + if ahead.opened == s.opened + && ahead.map == s.map().instance_id() + && ahead.tol == tol + && ahead.grids == grids + && same_topology(&ahead.inputs, &inputs) => { - ahead.found? + ahead.found } // Checking again here would hold the window: the check made on its thread is dropped. - Some(_) => { - return Err("the topology rules, their layers or the datum grids changed while they were checked: validate again".into()); - } - None => check_topology(&inputs, tol)?, + Some(_) => return Err("the topology rules, their layers or the datum grids changed while they were checked: validate again".into()), + 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, grids, 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() @@ -2448,33 +2553,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", @@ -2492,6 +2570,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, error) in inputs.iter().zip(&query_errors) { + if let Some(error) = 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})) } @@ -2626,7 +2730,7 @@ mod tests { let (ahead, now) = (topology_checks(&s), topology_checks(&s)); assert!(same_topology(&ahead, &now), "{crs:?}"); let found = check_topology(&ahead, 1.0).unwrap(); - errors.push(found[0].errors.len()); + errors.push(found.errors.len()); } assert_eq!(errors[0], errors[1]); assert!(errors[0] > 0, "the overlap is found"); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index c7ca21046b..3ad48f37c6 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1324,7 +1324,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 e961810aa6..e92710a0ef 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -813,6 +813,44 @@ 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 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 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()) }; + 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"))] +/// 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"))] @@ -820,7 +858,7 @@ pub(crate) enum RanAhead { /// 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"))] @@ -864,8 +902,15 @@ 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. + 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. + 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)>, grids: Vec, } @@ -875,7 +920,12 @@ 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 { - s.tools_ahead = Some(Ahead::Taking(ran.tools.into())); + 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(), ran.created_layers)); s.files_ahead = Some(FilesAhead::Taking(ran.files.into())); s.grids_ahead = Some(crate::image_grid::Ahead::taking(ran.grids)); s.zones_ahead = Some(super::imagery::ZonesAhead::Taking(ran.zones.into())); @@ -883,6 +933,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; s.grids_ahead = None; r.unwrap_or_else(|p| std::panic::resume_unwind(p)) } @@ -894,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(), @@ -906,7 +964,7 @@ pub(crate) fn ran_ahead(s: &mut Session) -> RanAheads { Some(crate::image_grid::Ahead::Recording(read)) => read, _ => Vec::new(), }; - RanAheads { tools, files, zones, grids } + RanAheads { tools, created_layers, files, zones, grids, retained: None, selection_admission: s.selection_admission.clone() } } #[cfg(not(target_arch = "wasm32"))] @@ -934,7 +992,7 @@ fn read_batch_file(s: &mut Session, path: &std::path::Path) -> Result<(Dataset, /// The next tool run ahead, if it is this one on the same inputs: its result, the streamed rows /// it read whole and how long it took. Any other drops the rest, which came after it. fn take_ahead(s: &mut Session, pin: &crate::policy::ToolPin, params: &Value) -> Option> { - let Some(Ahead::Taking(ran)) = &mut s.tools_ahead else { + let Some(Ahead::Taking(ran, _)) = &mut s.tools_ahead else { crate::image_grid::invalidate_script_grids(s); return None; }; diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 30e86f96d3..85b6cd86be 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -54,6 +54,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 0a457aca58..098dc3c894 100644 --- a/crates/engine/src/cmd/reads.rs +++ b/crates/engine/src/cmd/reads.rs @@ -287,8 +287,9 @@ pub(crate) fn prepare(s: &mut Session, op: Authorized, owner: Continu "raster.imageGrid" => ("Read Original Image Grid", crate::image_grid::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, Read Original Image Grid, Preview Shape Conversion, 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, Read Original Image Grid, Preview Shape Conversion, 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) @@ -340,6 +341,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() +} + /// What `read` prepared, when it is a `T`, for a test to look at before it lands. #[cfg(test)] pub(crate) fn prepared(read: &Read) -> Option<&T> { diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 2f092264a1..e39cb0f505 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -39,7 +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(); + clear(s); Ok(Value::Null) }).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_selection), @@ -128,8 +128,26 @@ 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_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_intent = s.selection_intent.max(s.selection_epoch()); + 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 new file mode 100644 index 0000000000..c01f0c1db2 --- /dev/null +++ b/crates/engine/src/cmd/similar.rs @@ -0,0 +1,267 @@ +//! 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(Clone, 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(Clone, PartialEq)] +struct Visibility { + query: Option, + filters: Vec, + time: Option<(String, Option<(f64, f64)>)>, +} + +/// Captures only this layer's metadata and shared row storage, never a project/session copy. +#[derive(Clone)] +struct Input { + target: Target, + opened: u64, + map: u64, + instance: u64, + name: String, + data: Dataset, + visibility: Option, + _retained: crate::undo_memory::ReadRows, +} + +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") { + 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()); + } + 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 = 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(), + 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)), + }); + 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, + _retained: s.undo_memory.readers().retain(vec![l.dataset.features.allocation_key()]), + }) + } + + /// Refuses data/reference/filter changes while work ran. Comparing row allocations avoids + /// 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 + && 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 + } +} + +#[derive(Clone)] +struct Done { + answer: Value, + selection: Option>, + notices: Vec, +} + +#[derive(Clone)] +struct Ahead { + input: Input, + done: Result, + request: (u64, u64), +} + +/// Orders admissions, not completions. Script workers share this sequence with their session. +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. +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)? { + 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 is indivisible, checked before/after. +/// Time detection checks Cancel and keeps no layer-wide timestamp or visibility cache. Only +/// the at-most-1,001 result/reference rows need query/filter/time evaluation. +fn gather(input: &Input) -> Result { + let t = &input.target; + 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 }) }; + 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 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 { + 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), + } + } + 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()?; + let request = request(s); + Some(super::reads::ahead("Find Similar", "data.similar".into(), move || { + let done = gather(&input); + Ahead { input, done, request } + })) +} + +/// 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"))] + 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; 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, 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); + (gather(&input), 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(), request }); + } + let done = done?; + if let Some(rows) = done.selection { + 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 request.0 < s.selection_intent { + "Selection or data 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, + ); + } + } + 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 6335c9d478..b7eb5aefd7 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -82,6 +82,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() @@ -94,8 +95,8 @@ 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) - .params(r#"{"layer"?, "row"?: number (the selected feature when omitted), "fields"?: [numeric fields], "count"?: number, "select"?: bool}"#), + C::new("data.similar", "Embeddings", "Analyze › Workflows", super::similar::run).roles(&[]).effects(crate::policy::Effects::NONE) + .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}"#), @@ -827,9 +828,16 @@ 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_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(); @@ -841,16 +849,23 @@ 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_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. 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.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); - super::gp::ran_ahead(&mut copy) + let mut ran = super::gp::ran_ahead(&mut copy); + ran.retained = Some(retained); + ran }) } @@ -912,8 +927,8 @@ fn check_prepared_prefix(s: &Session, lines: &[(usize, String, Value)]) -> Resul #[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", @@ -929,6 +944,9 @@ pub(crate) const ON_A_COPY: &[&str] = &[ "gp.spatialJoin", "gp.zonalStats", "gp.env", + "data.similar", + "topology.rules", + "topology.validate", "select.all", "select.atPoint", "select.byAttributes", @@ -1948,7 +1966,8 @@ pub(crate) fn hold_as( } } -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() @@ -1963,7 +1982,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)?; @@ -2006,31 +2025,6 @@ fn explore(s: &mut Session, p: &Value) -> CmdResult { ) } -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); - super::select::set(s, id, sel, super::select::Mode::New); - } - 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/lib.rs b/crates/engine/src/lib.rs index 3652a39df7..8c8900f2b2 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -829,6 +829,16 @@ pub struct Session { pub registry: Registry, /// Bumped on every change so views can cache. pub revision: u64, + /// 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, 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. @@ -1323,6 +1333,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"))] @@ -1330,6 +1350,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")))] @@ -1369,6 +1391,11 @@ impl Session { layout_arrangements: serde_json::Map::new(), registry: Registry { commands: cmd::all() }, revision: 1, + 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 cd2d565959..eb21357ca8 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -123,7 +123,7 @@ impl Session { } let CallKind::Command { id, params } = &call.kind else { return Err( - "only standalone archive, column-statistics, shape-conversion, image-grid or size-by-field commands can prepare a scoped read".into() + "only standalone archive, column-statistics, similarity, topology, shape-conversion, image-grid or size-by-field commands can prepare a scoped read".into() ); }; if !matches!( @@ -131,12 +131,14 @@ impl Session { "map.reloadTiles" | "map.repairTiles" | "table.statistics" + | "data.similar" + | "topology.validate" | "edit.previewShapeConversion" | "raster.imageGrid" | "layer.sizeBy" ) { return Err( - "only standalone archive, column-statistics, shape-conversion, image-grid or size-by-field commands can prepare a scoped read".into() + "only standalone archive, column-statistics, similarity, topology, shape-conversion, image-grid or size-by-field commands can prepare a scoped read".into() ); } let capture = |s: &mut Session| s.capture_read(id, params); @@ -168,12 +170,13 @@ impl Session { | "service.add" | "source.syncState" | "table.statistics" + | "data.similar" | "raster.imageGrid" | "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, Read Original Image Grid, Preview Shape Conversion, 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, Read Original Image Grid, Preview Shape Conversion, 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 @@ -186,6 +189,7 @@ impl Session { | "labels.convert" | "source.syncState" | "table.statistics" + | "data.similar" | "raster.imageGrid" | "edit.previewShapeConversion" | "layer.sizeBy" @@ -952,6 +956,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); @@ -984,6 +995,14 @@ impl Session { Txn::Shared => self.shared_step(&spec, run), }; self.url_completion_landed(spec.id, ¶ms, &result); + 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); + } result } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 86c7b4389d..ae123ec0bc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -57343,6 +57343,826 @@ 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::>() + ); + } + // 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); + let unreadable = query == Some("missing = 1"); + 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.iter().any(|n| n.text.starts_with(&format!("{excluded} features aren't drawn")))); + } + if unreadable { + 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(); + 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); + assert_eq!(s.map().layer(id).unwrap().selection, vec![2]); + 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 { + 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(), 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"); +} + +/// 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() + ); +} + +/// 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")); + } +} + +/// 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) +} + +/// 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() { + use crate::cmd::reads::{read_ahead, read_land}; + use rustgis_analysis::control::Control; + let (mut s, id) = similar_lifecycle_session(); + 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\"}" + )}); + 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"][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))); + 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!(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]); +} + +#[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 change in 0..3 { + 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 change == 0 { id } else { other }; + if change == 2 { + // The conservative guard also covers mutations with no selection change. + s.run("layer.rename", &json!({"layer":other,"name":"renamed"})).unwrap(); + } else { + 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"))); + if change == 2 { + assert!(s.notices_since(mark).iter().any(|n| n.text.contains("data changed"))); + } + } +} + +#[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}; + 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"); + } + } + } +} + +/// 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"); + } + } + } +} + +/// 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() { + use crate::cmd::reads::{read_ahead, read_land}; + use rustgis_analysis::control::Control; + for prepared_prefix in [false, true] { + for window in [false, true] { + let (mut s, _) = similar_lifecycle_session(); + s.statistics_need_read_ahead(window); + let prefix = if prepared_prefix { + "data.similar {\"layer\":\"values\",\"row\":0,\"fields\":[\"n\"],\"count\":1,\"select\":false}\n" + } else { + "" + }; + let p = json!({"script": format!("{prefix}{}", concat!( + "map.setScale {\"scale\":100000}\n", + "data.similar {\"layer\":\"values\",\"row\":0,\"fields\":[\"n\"],\"count\":1}" + ))}); + let result = if prepared_prefix { + let read = read_ahead(&mut s, "script.run", &p).unwrap(); + assert!(read.reads()); + read_land(&mut s, read.run(&Control::stoppable()).unwrap()) + } else { + s.run("script.run", &p) + }; + if window { + let error = result.unwrap_err(); + assert!(error.contains("background read queue") && error.contains("setup separately"), "{error}"); + } else { + let answer = result.unwrap(); + assert_eq!(answer["ran"].as_array().unwrap().last().unwrap()["result"]["similar"][0]["row"], 1); + } + } + } +} + +/// 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, even if a later step removes them. +#[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 (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(); + 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"))] +#[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; + 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); + } +} + +/// 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()); + } +} + /// A dated cloud-optimised GeoTIFF's file is named in its notices cut to 80 characters, and a cut /// name ends in an ellipsis so it doesn't pass for the whole one. #[test] diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index 29bb9b3ef6..8f804c39b1 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -206,6 +206,17 @@ 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); + // 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 4014f5d8d6..e6cb7f3808 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,11 +89,71 @@ 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.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 { /// 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, @@ -283,6 +348,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 @@ -326,7 +405,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)), @@ -346,7 +425,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}; @@ -357,8 +437,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) @@ -368,8 +449,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) @@ -383,21 +465,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 => {} }, @@ -417,9 +499,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. @@ -552,6 +634,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") @@ -559,7 +642,10 @@ 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() + && (app.workflow.section != "similar" || *id != "similar") + { + forget_similar(&mut app.workflow); app.workflow.section = id; app.workflow.result = None; app.workflow.error = None; @@ -599,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(); @@ -922,10 +1013,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"); @@ -1698,7 +1804,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; @@ -1715,14 +1822,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 } @@ -2840,6 +2948,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/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 34ff2f1edc..f86da2b759 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2951,6 +2951,8 @@ impl RustGisApp { self.map.deleting = None; // A spectral profile's points were read on the old project's rasters. self.workflow.spectral.clear(); + crate::analysispane::forget_similar(&mut self.workflow); + (self.workflow.result, self.workflow.error) = (None, None); self.retire_cog_probes(); if let Some(steps) = self.ws.recording.take() { self.session.notify( @@ -3029,6 +3031,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); } @@ -3177,6 +3182,8 @@ impl RustGisApp { self.map.deleting = None; // Nor are a spectral profile's points read on a namesake raster of the new one. self.workflow.spectral.clear(); + crate::analysispane::forget_similar(&mut self.workflow); + (self.workflow.result, self.workflow.error) = (None, None); // A recording's steps name the old project's layers: it ends here, and says so. if let Some(steps) = self.ws.recording.take() { let n = steps.len().to_string(); @@ -3735,9 +3742,14 @@ impl RustGisApp { 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), @@ -8928,6 +8940,26 @@ mod download_service_tests { mod peer_output_tests { use super::*; + /// Completed rankings belong to the replaced project, through User and peer entry points. + #[test] + fn project_replacement_clears_similar_output() { + for peer in [false, true] { + let mut app = RustGisApp::new(Session::new(Project::default())); + app.workflow.section = "similar"; + app.workflow.result = Some(json!({"similar":[{"row":1,"distance":0.5}]})); + app.workflow.error = Some("old project error".into()); + assert!(app.open_peer_text("invalid project").is_err()); + assert!(app.workflow.result.is_some() && app.workflow.error.is_some(), "a refused replacement keeps current output"); + if peer { + let (text, _) = Project::default().saved_text(None).unwrap(); + app.open_peer_text(&text).unwrap(); + } else { + app.run("project.new", json!({})).unwrap(); + } + assert!(app.workflow.result.is_none() && app.workflow.error.is_none(), "a replacement cannot show old row indices"); + } + } + /// Drives the actual receiving wrapper, including the UI state a direct Session call misses. #[test] fn peer_project_uses_import_authority_and_resets_old_ui_work() { diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 635c64b4d8..c7dd87ab2d 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -4431,7 +4431,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); } @@ -5418,6 +5418,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/crates/ui-egui/src/readjob.rs b/crates/ui-egui/src/readjob.rs index 1def825991..44b9cf2488 100644 --- a/crates/ui-egui/src/readjob.rs +++ b/crates/ui-egui/src/readjob.rs @@ -97,6 +97,7 @@ pub type Then = fn(&mut RustGisApp, Landed); enum Completion { Command(Then), ShapeConversion(Option), + WorkflowSimilar(u64), ImageGrid(u64), } impl Completion { @@ -104,6 +105,7 @@ impl Completion { 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), Self::ImageGrid(request) => crate::annotation::landed(app, request, result), } } @@ -146,6 +148,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) +} + /// Original grid lookup shares the read queue and carries its request through every outcome. pub(crate) fn run_image_grid(app: &mut RustGisApp, p: Value, request: u64) -> Result { run_presented(app, "raster.imageGrid", p, Some(Completion::ImageGrid(request)), None, None) @@ -201,6 +208,7 @@ fn run_presented( | "labels.convert" | "source.syncState" | "table.statistics" + | "data.similar" | "raster.imageGrid" | "edit.previewShapeConversion" | "layer.sizeBy" @@ -306,7 +314,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 = @@ -401,6 +409,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"), @@ -530,6 +539,8 @@ fn start(app: &mut RustGisApp, mut asked: Asked, p: Value) -> Result Result { + 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" | "error_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 + } + 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" | "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()); + 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()); + 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" | "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()); + } + _ => 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] + fn similarity_uses_the_read_queue_for_ui_and_relay() { + use rustgis_engine::data::{Dataset, Field, FieldType, GeometryType, Value as V}; + 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 = Dataset::new("numbers", GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); + for n in [0, 2, 10] { + ds.push(None, vec![V::Int(n)]); + } + let id = rustgis_engine::cmd::layer::add_dataset(&mut app.session, ds); + let l = app.session.map_mut().layer_mut(id).unwrap(); + l.selection = vec![0]; + l.definition_query = Some("n >= 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); + } + } + + /// 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 bf57ef029d..145b3cf3a9 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1521,6 +1521,39 @@ 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 `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 +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; +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 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. +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 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. +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**. For `raster.function`, set `"function": "slope", "units": "percent"`; in `raster.functionChain`, diff --git a/docs/user-guide/editing.md b/docs/user-guide/editing.md index 4bc2a4bd8e..9cd0fda6e3 100644 --- a/docs/user-guide/editing.md +++ b/docs/user-guide/editing.md @@ -151,15 +151,19 @@ 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 - at, and its rule is said to be incomplete. + 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**). - **Status**: features added, changed and deleted per layer since the last save.