From 4f432df29f212fddecd1aa333633d6f0381b6853 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 10:25:33 -0600 Subject: [PATCH 1/3] fix(map): retain source positions in row-number queries --- crates/data/src/query.rs | 6 ++ crates/data/src/rows.rs | 5 ++ crates/data/src/source/fgb.rs | 5 ++ crates/data/src/source/geojson.rs | 6 ++ crates/data/src/source/gpkg_mem.rs | 5 ++ crates/data/src/source/lidar.rs | 5 ++ crates/data/src/source/mod.rs | 24 ++++++++ crates/data/src/source/parquet.rs | 5 ++ crates/data/src/source/shp.rs | 5 ++ crates/map/src/lib.rs | 91 ++++++++++++++++++++++++++++-- crates/map/src/source.rs | 30 ++++++++-- crates/map/src/source/window.rs | 47 +++++++-------- crates/render/src/layout/legend.rs | 2 +- crates/render/src/lib.rs | 16 +++++- crates/render/src/stream_tests.rs | 61 ++++++++++++++++++++ docs/user-guide/expressions.md | 3 + 16 files changed, 275 insertions(+), 41 deletions(-) diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index 2467369045..c312476c64 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -662,6 +662,12 @@ pub fn reads_series_page(text: &str) -> bool { }) } +/// Whether the text refers to a row number outside quotes. +pub fn reads_row_number(text: &str) -> bool { + text.contains('@') + && lex(text).is_ok_and(|tokens| tokens.iter().any(|t| matches!(t, Tok::Var(name) if name.eq_ignore_ascii_case("@row_number")))) +} + fn lex(s: &str) -> Result, String> { lex_spans(s, false).map(|l| l.toks) } diff --git a/crates/data/src/rows.rs b/crates/data/src/rows.rs index 1253daf9b4..d466e6f989 100644 --- a/crates/data/src/rows.rs +++ b/crates/data/src/rows.rs @@ -28,6 +28,11 @@ impl Query { self.expr.as_ref().is_none_or(|expr| query::matches(expr, dataset, row, env)) } + /// Tests a row in a window, with its offset from the corresponding whole-layer position. + pub fn matches_at(&self, dataset: &Dataset, row: usize, env: &query::Env, offset: usize) -> bool { + self.expr.as_ref().is_none_or(|expr| query::matches_at(expr, dataset, row, env, offset)) + } + /// Match a chunk row with the default expression environment. `offset` counts source rows /// preceding this chunk, including rows earlier chunks excluded; callers own that count. pub fn matches_in_chunk(&self, dataset: &Dataset, row: usize, offset: usize) -> bool { diff --git a/crates/data/src/source/fgb.rs b/crates/data/src/source/fgb.rs index 7700859dcb..23f864f85e 100644 --- a/crates/data/src/source/fgb.rs +++ b/crates/data/src/source/fgb.rs @@ -843,6 +843,11 @@ impl FeatureSource for FgbSource { &self.info } + /// A read assigns physical record ids even when records are skipped. + fn window_row_order(&self, batch: &Batch) -> Option { + super::dense_one_based_prefix(&batch.features) + } + fn reads_own_box(&self) -> bool { true } diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index 58748f91e9..8925232011 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -323,6 +323,12 @@ impl FeatureSource for GeoJsonSource { &self.info } + /// The unchanged file's open-time scan excluded unreadable features before numbering places. + fn window_row_order(&self, batch: &Batch) -> Option { + let metadata = std::fs::metadata(&self.path).ok()?; + (batch.skipped == 0 && self.version == FileVersion::of(&metadata)).then_some(super::WindowRowOrder::IdsStartingAt(1)) + } + fn reads_own_box(&self) -> bool { true } diff --git a/crates/data/src/source/gpkg_mem.rs b/crates/data/src/source/gpkg_mem.rs index 2ad9bbedc1..7aaa624aa1 100644 --- a/crates/data/src/source/gpkg_mem.rs +++ b/crates/data/src/source/gpkg_mem.rs @@ -355,6 +355,11 @@ impl FeatureSource for GpkgMemSource { &self.info } + /// The immutable upload's exact count shows when a window contains the whole table in order. + fn window_row_order(&self, batch: &Batch) -> Option { + (batch.complete && self.info.count == Some(batch.features.len() as u64)).then_some(super::WindowRowOrder::WholeLayer) + } + fn reads_own_box(&self) -> bool { true } diff --git a/crates/data/src/source/lidar.rs b/crates/data/src/source/lidar.rs index 8266499286..6bf6ef9754 100644 --- a/crates/data/src/source/lidar.rs +++ b/crates/data/src/source/lidar.rs @@ -76,6 +76,11 @@ impl FeatureSource for LidarSource { self.crs } + /// Point ids are zero-based file offsets. They are dense when the reader retained every point. + fn window_row_order(&self, _: &Batch) -> Option { + (self.info.count == Some(self.features.len() as u64)).then_some(super::WindowRowOrder::IdsStartingAt(0)) + } + /// A box in the file's own system is tested against the points as they are. fn reads_own_box(&self) -> bool { true diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 0cae2ad471..ceaca371b4 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -522,6 +522,20 @@ pub fn rounded_dates_note(fields: &[crate::Field], counts: &[usize]) -> Option Option { + rows.iter().enumerate().all(|(i, row)| row.id == i as u64 + 1).then_some(WindowRowOrder::IdsStartingAt(1)) +} + /// A vector data source read in place. pub trait FeatureSource: Send + Sync { /// Whether the map draws the source by complete traversal ([`FeatureSource::visit_chunks`]) @@ -615,6 +629,12 @@ pub trait FeatureSource: Send + Sync { fn reads_own_box(&self) -> bool { false } + /// The window's ordering, when it proves the positions of its rows in the whole layer. + /// Physical record positions alone are insufficient when earlier records can be skipped. + fn window_row_order(&self, _batch: &Batch) -> Option { + None + } + /// The encoding the source's text values are read in, for the notice of those that aren't /// valid in it ([`not_utf8_note`]). fn text_encoding(&self) -> &'static str { @@ -924,6 +944,10 @@ impl FeatureSource for Fetching { self.0.holds_more_than(n) } + fn window_row_order(&self, batch: &Batch) -> Option { + self.0.window_row_order(batch) + } + fn says_unplaced_at_open(&self) -> bool { self.0.says_unplaced_at_open() } diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 3114f92508..4603c3f6d0 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -633,6 +633,11 @@ impl FeatureSource for ParquetSource { (lo.is_finite() && hi.is_finite() && lo <= hi).then_some((lo, hi)) } + /// A read assigns physical record ids even when records are skipped. + fn window_row_order(&self, batch: &Batch) -> Option { + super::dense_one_based_prefix(&batch.features) + } + fn reads_own_box(&self) -> bool { true } diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 1fcfe6b41d..0bd07e6f98 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -440,6 +440,11 @@ impl FeatureSource for ShpSource { &self.info } + /// A read assigns physical record ids even when records are skipped. + fn window_row_order(&self, batch: &Batch) -> Option { + super::dense_one_based_prefix(&batch.features) + } + fn reads_own_box(&self) -> bool { true } diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 1a18af2a96..e29f8d2f6e 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -2009,7 +2009,27 @@ impl Layer { /// Applies the definition query in the supplied drawing context. pub fn query_rows_with(&self, dataset: &Dataset, env: &rustgis_data::query::Env) -> Option> { let query = rustgis_data::rows::Query::compile(self.definition_query.as_deref(), dataset).ok()?; - query.is_filtered().then(|| (0..dataset.features.len()).map(|row| query.matches(dataset, row, env)).collect()) + if !query.is_filtered() { + return None; + } + // A different dataset passed in by a whole-layer consumer has its own dense order. + if dataset.windowed + && let Some(source) = self.source.as_ref().filter(|_| std::ptr::eq(dataset, &self.dataset)) + && self.definition_query.as_deref().is_some_and(rustgis_data::query::reads_row_number) + { + // Hide unnumbered rows while the new query is pending or refused. + let Some(order) = source.window().and(source.row_order) else { + return Some(vec![false; dataset.features.len()]); + }; + if let rustgis_data::source::WindowRowOrder::IdsStartingAt(origin) = order { + let matches = dataset.features.rows().enumerate().map(|(row, feature)| { + let index = feature.id().checked_sub(origin).and_then(|id| usize::try_from(id).ok()); + index.and_then(|index| index.checked_sub(row)).is_some_and(|offset| query.matches_at(dataset, row, env, offset)) + }); + return Some(matches.collect()); + } + } + Some((0..dataset.features.len()).map(|row| query.matches(dataset, row, env)).collect()) } /// The rows whose shape's box, in the layer's own coordinates ([`Dataset::coord_crs`]), may @@ -5256,19 +5276,18 @@ mod tests { assert_eq!((shown(&l).len(), l.dataset.features.len()), (2, 2)); let src = l.source.as_ref().unwrap(); assert_eq!((src.sampled(), src.sampled_matches()), (Some((2, 4)), true)); - // A row number is a row's place in the view: the view is read as without a query. The - // words in a text are only text. + // The sample cannot prove the position of rows whose predecessors it omitted. l.definition_query = Some("@row_number = 1".into()); l.sync_source(&view, true); - let src = l.source.as_ref().unwrap(); - assert_eq!((src.sampled(), src.sampled_matches()), (Some((2, 5)), false)); + assert!(l.source.as_ref().unwrap().read_error().unwrap().contains("Use Load All Features")); + // The words in a string literal are only text. l.definition_query = Some(format!("n = {left_out} or 'x' = '@row_number'")); l.sync_source(&view, true); assert_eq!(shown(&l), [Value::Int(left_out)]); // However it's quoted or nested, a row number is found in the parsed query. l.definition_query = Some(format!("!n! = {left_out} and (@row_number >= 1 or 'it''s' = '')")); l.sync_source(&view, true); - assert!(!l.source.as_ref().unwrap().sampled_matches()); + assert!(l.source.as_ref().unwrap().read_error().unwrap().contains("Use Load All Features")); // One view on two series pages: a sampled-out match must arrive on each page, // and the map view afterwards must evaluate the same query with null page variables. l.definition_query = Some("n = @page_number - 1".into()); @@ -5290,6 +5309,66 @@ mod tests { assert_eq!(shown(&l), sampled); } + /// A spatial window must not call its first row the first row of the whole layer. + #[test] + fn a_spatial_window_does_not_renumber_a_definition_query() { + let mut ds = Dataset::new("sites", GeometryType::Point, vec![]); + for x in [-20.0, 20.0] { + ds.push(Some(Geometry::Point(Coord::new(x, 0.0))), vec![]); + } + let bytes = std::sync::Arc::new(rustgis_data::source::fgb::write(&ds).unwrap()); + let source = rustgis_data::source::open_shared("sites.fgb", bytes.clone(), None).unwrap(); + let reader = source::SourceLayer::from_bytes("sites.fgb", bytes, None, source); + let mut layer = Layer::new_streamed(1, reader); + let whole = layer.load_all().unwrap(); + let first = whole.features.first().unwrap(); + let other = whole.features.last().unwrap(); + let view = other.geometry.as_ref().unwrap().extent().padded(0.0, 0.1); + layer.sync_source(&view, true); + assert_eq!(layer.dataset.features.len(), 1); + assert_eq!(layer.dataset.features[0].id, other.id); + layer.selection.push(0); + layer.definition_query = Some("@row_number = 1".into()); + assert_eq!(layer.visible_rows(), [false], "old window rows must not be renumbered before the read"); + layer.sync_source(&view, true); + assert_eq!(layer.query_rows(&whole).unwrap(), [true, false]); + assert_eq!(layer.dataset.features[0].id, other.id); + assert_eq!(layer.selection, [0]); + assert!(layer.visible_rows().iter().all(|visible| !visible)); + let why = layer.source.as_ref().unwrap().read_error().unwrap(); + assert!(why.contains("@row_number") && why.contains("Use Load All Features"), "{why}"); + + let prefix = first.geometry.as_ref().unwrap().extent().padded(0.0, 0.1); + layer.sync_source(&prefix, true); + assert_eq!(layer.visible_rows(), [true]); + assert_eq!(layer.dataset.features[0].id, first.id); + assert!(layer.source.as_ref().unwrap().read_error().is_none()); + } + + /// The GeoJSON index knows that the geometry-less row belongs before a spatial match. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_geojson_window_uses_the_whole_layer_position() { + let mut ds = Dataset::new("sites", GeometryType::Point, vec![]); + ds.push(None, vec![]); + ds.push(Some(Geometry::Point(Coord::new(20.0, 0.0))), vec![]); + let path = std::env::temp_dir().join(format!("rustgis-map-row-number-{}.geojson", std::process::id())); + std::fs::write(&path, rustgis_data::io::to_geojson(&ds).to_string()).unwrap(); + let source = rustgis_data::source::geojson::GeoJsonSource::open_path(&path, "sites").unwrap(); + let reader = source::SourceLayer::from_path(path.to_string_lossy(), None, Box::new(source)); + let mut layer = Layer::new_streamed(1, reader); + let view = Extent::new(19.0, -1.0, 21.0, 1.0); + layer.sync_source(&view, true); + assert_eq!(layer.dataset.features.len(), 1); + + layer.definition_query = Some("@ROW_NUMBER = 2".into()); + layer.sync_source(&view, true); + assert_eq!(layer.visible_rows(), [true]); + assert_eq!(layer.query_rows(&layer.load_all().unwrap()).unwrap(), [false, true]); + assert!(layer.source.as_ref().unwrap().read_error().is_none()); + std::fs::remove_file(path).unwrap(); + } + #[test] fn geometry_only_lod_does_not_charge_for_unused_extents() { let l = long_line(100); diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index ee65e15bd7..cc7e965423 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -15,7 +15,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock, Weak}; use crate::projection::Flat; -use rustgis_data::source::{Batch, FeatureSource, Request, SourceInfo}; +use rustgis_data::source::{Batch, FeatureSource, Request, SourceInfo, WindowRowOrder}; use rustgis_geom::{Coord, Extent}; use serde::{Deserialize, Serialize}; @@ -182,6 +182,9 @@ pub struct SourceLayer { read_note_kinds: Vec, #[serde(skip)] window: Option, + /// How positions in the current window relate to positions in the layer. + #[serde(skip)] + pub(crate) row_order: Option, /// Whole-source thinning decisions shared by render snapshots, independent of view rows. #[serde(skip)] render_lod: Arc>, @@ -911,6 +914,7 @@ impl SourceLayer { byte_budget: _, estimated_row_bytes: _, full_read: _, + row_order: _, saved_selection: _, grids: _, window_fields: _, @@ -1118,6 +1122,13 @@ impl SourceLayer { self.error_said = None; } + /// A whole-source draw can succeed while the window still cannot number its rows. + pub fn clear_whole_draw_error(&mut self) { + if self.error.as_deref() != Some(window::ROW_ORDER_REFUSAL) { + self.clear_error(); + } + } + /// Takes each persistent read failure once, so redraws do not repeat its notice. A successful /// read, or an explicit reopen/repair, allows a later failure to be reported. pub fn error_unsaid(&mut self) -> Option { @@ -2046,13 +2057,15 @@ impl SourceLayer { let text = text.map(str::trim).filter(|t| !t.is_empty()); let page = env.page.as_ref().filter(|_| text.is_some_and(rustgis_data::query::reads_series_page)); if self.query.as_ref().map(|q| (q.text.as_str(), q.fields.as_slice(), q.env.page.as_ref())) != text.map(|t| (t, fields, page)) { + let reread = self.handle.as_ref().is_some_and(|h| h.visits_chunks()) + || [text, self.query.as_ref().map(|q| q.text.as_str())].into_iter().flatten().any(rustgis_data::query::reads_row_number); self.query = text.map(|t| Query { text: t.to_string(), fields: fields.to_vec(), env: rustgis_data::query::Env { page: page.cloned(), ..Default::default() }, }); - // A source that can't be walked reads the same rows whatever the query. - if self.handle.as_ref().is_some_and(|h| h.visits_chunks()) { + // Row numbering also needs a fresh window to verify its order or report a refusal. + if reread { self.reread(); } } @@ -2060,6 +2073,7 @@ impl SourceLayer { /// Drops disposable view rows while retaining decisions about the unchanged full source. pub(crate) fn reset_window(&mut self) { + self.row_order = None; self.window = None; self.pending = None; self.ready_cache = None; @@ -2246,14 +2260,21 @@ impl SourceLayer { let (extent, own) = (p.extent, p.own); let (kept, filtered, whole) = (b.features.len(), cache.filtered, cache.whole); let w = Window { extent, complete: b.complete, whole, matched: b.matched, kept, filtered, own }; + self.row_order = cache.row_order; + let row_order_refused = cache.row_order_refused; self.ready_cache = Some(cache); self.window = Some(w); - self.clear_error(); + if row_order_refused { + self.error = Some(window::ROW_ORDER_REFUSAL.into()); + } else { + self.clear_error(); + } return Polled::Done(w, Box::new(b)); } Some(Err(e)) => { self.pending = None; self.ready_cache = None; + self.row_order = None; self.saved_selection.clear(); self.error = Some(e.clone()); // Not read again until the view moves past it. @@ -2408,6 +2429,7 @@ impl SourceLayer { byte_budget: _, estimated_row_bytes: _, full_read: _, + row_order: _, saved_selection: _, grids: _, window_fields: _, diff --git a/crates/map/src/source/window.rs b/crates/map/src/source/window.rs index cd54fe18d5..21abcd7137 100644 --- a/crates/map/src/source/window.rs +++ b/crates/map/src/source/window.rs @@ -1,7 +1,7 @@ //! A view is decoded and projected on the source worker. The UI installs Arc-backed caches. use rustgis_data::query::Expr; use rustgis_data::raster::Crs; -use rustgis_data::source::{Batch, FeatureSource, Request, memory}; +use rustgis_data::source::{Batch, FeatureSource, Request, WindowRowOrder, memory}; use rustgis_data::{DataError, Dataset, Field, Geometry, Result}; use rustgis_geom::Extent; use std::sync::Arc; @@ -23,6 +23,9 @@ pub(crate) struct Cache { pub filtered: bool, /// Whether this retained read was verified to hold the complete source. pub whole: bool, + /// Whole-layer positions established for this window's definition query. + pub row_order: Option, + pub row_order_refused: bool, /// The system its rows are given in, the source's own ([`FeatureSource::coord_crs`]). pub crs: Crs, } @@ -77,6 +80,9 @@ pub(crate) struct Query { /// The bytes of features held at once while a filtered read walks the source. const FILTER_CHUNK_BYTES: usize = 8 << 20; +pub(super) const ROW_ORDER_REFUSAL: &str = + "The definition query uses @row_number, but this view can't determine the rows' positions in the whole layer. Use Load All Features."; + /// Reads a view for the worker: within `bytes` (an interactive view) or whole up to `req.limit` /// (`full`, a render or export), with the layer's definition query applied before the limit. pub(super) fn read_mode( @@ -102,11 +108,16 @@ pub(super) fn read_mode( // A view read whole is filtered exactly by the layer. A sampled one would leave matches out // (#1456): the source is walked instead, keeping up to the view's limit of the matches. // Half the budget holds them; their projection and display levels take the rest. - let first = read(source)?; + let mut first = read(source)?; if full { check_areas(&expr, &scratch, &first.0.features, &source.info().name, first.0.complete)?; } - if first.0.complete || !source.visits_chunks() || numbers_rows(&expr) { + if rustgis_data::query::reads_row_number(&query.text) { + first.1.row_order = source.window_row_order(&first.0); + first.1.row_order_refused = first.1.row_order.is_none() && !first.0.features.is_empty(); + return Ok(first); + } + if first.0.complete || !source.visits_chunks() { return Ok(first); } drop(first); @@ -122,13 +133,12 @@ pub(super) fn read_mode( /// What a sampled view of `source` is walked with, keeping the matches: the parsed `query` and a /// dataset of its fields to hold each chunk. `None` when the source can't be read a chunk at a -/// time, the query doesn't parse, or it uses a row number (a row's place in the view, which a walk -/// of the source can't number the same way). +/// time, the query doesn't parse, or a spatial walk cannot number every matching row in the layer. pub(super) fn walked(source: &dyn FeatureSource, query: &Query) -> Option<(Dataset, Expr)> { if !source.visits_chunks() { return None; } - parsed_query(source, query).filter(|(_, expr)| !numbers_rows(expr)) + parsed_query(source, query).filter(|_| !rustgis_data::query::reads_row_number(&query.text)) } /// Parse against metadata even when a source cannot be walked: its decoded view still needs @@ -142,27 +152,6 @@ fn parsed_query(source: &dyn FeatureSource, query: &Query) -> Option<(Dataset, E Some((scratch, expr)) } -/// Whether an expression reads `@row_number` anywhere. -fn numbers_rows(e: &Expr) -> bool { - use rustgis_data::query::Var; - let any = |es: &[Expr]| es.iter().any(numbers_rows); - match e { - Expr::Var(v) => *v == Var::RowNumber, - Expr::And(es) | Expr::Or(es) | Expr::Concat(es) | Expr::Call(_, es) => any(es), - Expr::Not(e) | Expr::IsNullExpr { e, .. } => numbers_rows(e), - Expr::Compare(_, a, b) | Expr::LikeExpr { e: a, pattern: b, .. } => numbers_rows(a) || numbers_rows(b), - Expr::InExpr { e, list, .. } => numbers_rows(e) || any(list), - Expr::Between { e, lo, hi, .. } => numbers_rows(e) || numbers_rows(lo) || numbers_rows(hi), - Expr::Chain(first, rest) => numbers_rows(first) || rest.iter().any(|(_, e)| numbers_rows(e)), - Expr::Case { subject, arms, otherwise } => { - subject.as_deref().is_some_and(numbers_rows) - || arms.iter().any(|(w, t)| numbers_rows(w) || numbers_rows(t)) - || otherwise.as_deref().is_some_and(numbers_rows) - } - Expr::Cmp { .. } | Expr::Like { .. } | Expr::IsNull { .. } | Expr::In { .. } | Expr::Lit(_) | Expr::Field(_) => false, - } -} - /// The features of `req` that `expr` keeps, walking every feature of its extent: an evenly /// spread sample of the matches when more than `req.limit` of them, or more than `bytes`, match. /// `scratch` holds each chunk, with the fields `expr` was parsed against. @@ -267,6 +256,8 @@ fn whole(batch: Batch, projection: &crate::Projection, crs: Crs) -> (Batch, Cach key: projection.code(), filtered: false, whole: false, + row_order: None, + row_order_refused: false, crs, }; (batch, cache) @@ -433,6 +424,8 @@ fn trim(mut batch: Batch, mut projected: Drawn, bytes: usize, projection: &crate projected_bytes, filtered: false, whole: false, + row_order: None, + row_order_refused: false, crs, }, )) diff --git a/crates/render/src/layout/legend.rs b/crates/render/src/layout/legend.rs index a003f145e6..3ee202bf93 100644 --- a/crates/render/src/layout/legend.rs +++ b/crates/render/src/layout/legend.rs @@ -139,7 +139,7 @@ fn read_whole( return None; } if let Some(source) = &mut layer.source { - source.clear_error(); + source.clear_whole_draw_error(); } Some(()) } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index fad01b84bc..858c3ae7d1 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2499,7 +2499,7 @@ fn render_pass( return None; } if let Some(source) = map.layer_mut(layer.id).and_then(|l| l.source.as_mut()) { - source.clear_error(); + source.clear_whole_draw_error(); } layer.selection = features.iter().enumerate().filter_map(|(r, f)| ids.contains(&f.id).then_some(r)).collect(); layer.source = None; @@ -5522,6 +5522,16 @@ fn render_frame( } let source = layer.source.as_ref().and_then(|s| s.chunk_source()); let complete_source = source.is_some(); + // A complete chunk traversal can draw even if the window refused row numbering. + // A window-only export must report that refusal. + if full_res_rasters + && !complete_source + && layer.source.as_ref().is_some_and(|source| source.error.is_some()) + && layer.definition_query.as_deref().is_some_and(rustgis_data::query::reads_row_number) + { + *failed_source = Some(layer.instance_id()); + return None; + } // LOD is chosen for the entire layer, not separately for each chunk. Both the // activation threshold and the required saving must match an ordinary whole read. let thin_tol = view.lod_tolerance(); @@ -7212,7 +7222,7 @@ fn render_frame( return None; } if let Some(source) = &mut layer.source { - source.clear_error(); + source.clear_whole_draw_error(); } } else if let Err(e) = draw_chunk(layer, 0) { if !declined { @@ -7631,7 +7641,7 @@ fn layer_masks( return None; } if let Some(source) = map.layers.get_mut(mi).and_then(|l| l.source.as_mut()) { - source.clear_error(); + source.clear_whole_draw_error(); } } else if let Some(ml) = map.layers.get_mut(mi) { if ctx.globe.is_some() { diff --git a/crates/render/src/stream_tests.rs b/crates/render/src/stream_tests.rs index d3e7551d4d..16522e2eb3 100644 --- a/crates/render/src/stream_tests.rs +++ b/crates/render/src/stream_tests.rs @@ -2373,3 +2373,64 @@ fn streamed_row_number_keeps_layer_position_across_chunks() { assert!(got.pixmap.data() == expected.pixmap.data(), "{name}: streamed pixels differed from whole layer"); } } + +/// Complete Shapefile drawings must not clear the interaction window's numbering refusal. +#[test] +fn streamed_row_number_refusal_survives_whole_draw() { + rustgis_data::source::shp::use_temporary_index_dir(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("sites.shp"); + let mut ds = Dataset::new("sites", GeometryType::Point, vec![]); + for x in [-20.0, 20.0] { + ds.push(Some(Geometry::Point(Coord::new(x, 0.0))), vec![]); + } + rustgis_data::io::write_path(&ds, &path).unwrap(); + for pitch in [0.0, 0.4] { + let source = rustgis_data::source::open_path(&path, None).unwrap(); + let mut map = Map::new("refused interaction window"); + map.basemap = rustgis_map::Basemap::Blank; + let id = map.add_streamed("Sites", SourceLayer::from_path(path.to_string_lossy(), None, source)); + map.layer_mut(id).unwrap().definition_query = Some("@row_number = 1".into()); + let mut camera = Camera::new(rustgis_geom::lonlat_to_merc(Coord::new(20.0, 0.0)), 30.0); + camera.pitch = pitch; + let view = View { width: 240.0, height: 120.0, pixels_per_point: 1.0, camera, sky: false }; + settle(&mut map, &view); + let layer = map.layer_mut(id).unwrap(); + assert_eq!(layer.dataset.features.len(), 1); + layer.selection = vec![0]; + let error = layer.source.as_ref().unwrap().read_error().unwrap(); + assert!(error.contains("Use Load All Features"), "{error}"); + assert!(render_with_backend(&mut map, &view, true, Backend::Cpu).is_some()); + let layer = map.layer(id).unwrap(); + assert_eq!(layer.source.as_ref().unwrap().read_error(), Some(error)); + assert_eq!(layer.selection, vec![0]); + assert_eq!(layer.query_rows(&layer.dataset), Some(vec![false])); + } +} + +/// A map export must report an unnumbered window rather than write a picture missing its layer. +#[test] +fn streamed_row_number_refusal_reaches_map_export() { + let mut ds = Dataset::new("sites", GeometryType::Point, vec![]); + for x in [-20.0, 20.0] { + ds.push(Some(Geometry::Point(Coord::new(x, 0.0))), vec![]); + } + let bytes = std::sync::Arc::new(rustgis_data::source::fgb::write(&ds).unwrap()); + let source = rustgis_data::source::open_shared("sites.fgb", bytes.clone(), None).unwrap(); + let mut map = Map::new("refused window"); + map.basemap = rustgis_map::Basemap::Blank; + let id = map.add_streamed("Sites", SourceLayer::from_bytes("sites.fgb", bytes, None, source)); + let layer = map.layer_mut(id).unwrap(); + layer.definition_query = Some("@row_number = 1".into()); + let whole = layer.load_all().unwrap(); + let second = whole.features.last().unwrap().geometry.as_ref().unwrap().extent().center(); + let view = View { + width: 240.0, + height: 120.0, + pixels_per_point: 1.0, + camera: Camera::new(rustgis_geom::lonlat_to_merc(second), 30.0), + sky: false, + }; + let why = render_png(&mut map, &view).unwrap_err(); + assert!(why.contains("Sites") && why.contains("@row_number") && why.contains("Use Load All Features"), "{why}"); +} diff --git a/docs/user-guide/expressions.md b/docs/user-guide/expressions.md index c9fc8237c2..20f57f0240 100644 --- a/docs/user-guide/expressions.md +++ b/docs/user-guide/expressions.md @@ -92,6 +92,9 @@ operator: write `a < b AND b < c`, not `a < b < c`. | `$area`, `$perimeter` | A polygon's area in square metres (holes subtract) and the length of its rings in metres | | `$length` | A line's length in metres | +A definition query using `@row_number` needs whole-layer positions. When a view of a layer read +in place can't determine those positions, use **Load All Features**. Other expressions on a layer read in place can still number the current window; load all features when they need whole-layer positions. + The three page variables are available to symbols, labels, definition queries and display filters in every map frame on a series page. They are null outside a series page, including in the map view, tools and Calculate Field, so `$id = @page_feature_id` matches no feature there. A definition From f2cf461bc5042e3ba3de2afec54c9e89b1d171fe Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 11:14:41 -0600 Subject: [PATCH 2/3] fix(render): retain row-number refusals through tilted exports --- crates/engine/src/cmd/connections.rs | 2 +- crates/map/src/lib.rs | 8 ++++ crates/map/src/source.rs | 65 +++++++++++++++++++++++++--- crates/render/src/lib.rs | 11 ++++- crates/render/src/stream_tests.rs | 21 ++++++++- docs/user-guide/expressions.md | 4 +- 6 files changed, 101 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/connections.rs b/crates/engine/src/cmd/connections.rs index 2038461ffb..235399f9ae 100644 --- a/crates/engine/src/cmd/connections.rs +++ b/crates/engine/src/cmd/connections.rs @@ -647,7 +647,7 @@ fn reopen(s: &mut Session, c: &Connection, saved: bool, session: bool, mode: Reo if matches!(mode, ReopenMode::Login { .. }) { src.allow_reconnect(); } - src.error = None; + src.clear_error(); match src.open() { Ok(()) => result.opened += 1, Err(e) => { diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index e29f8d2f6e..811280a7e3 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -5349,10 +5349,18 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] #[test] fn a_geojson_window_uses_the_whole_layer_position() { + // Remove the fixture on a failing assertion too, without adding a test dependency. + struct Remove(std::path::PathBuf); + impl Drop for Remove { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } let mut ds = Dataset::new("sites", GeometryType::Point, vec![]); ds.push(None, vec![]); ds.push(Some(Geometry::Point(Coord::new(20.0, 0.0))), vec![]); let path = std::env::temp_dir().join(format!("rustgis-map-row-number-{}.geojson", std::process::id())); + let _remove = Remove(path.clone()); std::fs::write(&path, rustgis_data::io::to_geojson(&ds).to_string()).unwrap(); let source = rustgis_data::source::geojson::GeoJsonSource::open_path(&path, "sites").unwrap(); let reader = source::SourceLayer::from_path(path.to_string_lossy(), None, Box::new(source)); diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index cc7e965423..58f0e7ea93 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -185,6 +185,9 @@ pub struct SourceLayer { /// How positions in the current window relate to positions in the layer. #[serde(skip)] pub(crate) row_order: Option, + /// The window's numbering refusal outlives a temporary read or traversal error. + #[serde(skip)] + row_order_refused: bool, /// Whole-source thinning decisions shared by render snapshots, independent of view rows. #[serde(skip)] render_lod: Arc>, @@ -915,6 +918,7 @@ impl SourceLayer { estimated_row_bytes: _, full_read: _, row_order: _, + row_order_refused: _, saved_selection: _, grids: _, window_fields: _, @@ -1115,16 +1119,16 @@ impl SourceLayer { }) } - /// Clears a recovered failure and its notice marker, even between notice passes. + /// Clears a recovered failure, retaining any unresolved window-numbering refusal. pub fn clear_error(&mut self) { self.schema_refused = false; - self.error = None; + self.error = self.row_order_refused.then(|| window::ROW_ORDER_REFUSAL.to_string()); self.error_said = None; } /// A whole-source draw can succeed while the window still cannot number its rows. pub fn clear_whole_draw_error(&mut self) { - if self.error.as_deref() != Some(window::ROW_ORDER_REFUSAL) { + if !self.row_order_refused || self.error.as_deref() != Some(window::ROW_ORDER_REFUSAL) { self.clear_error(); } } @@ -2074,6 +2078,10 @@ impl SourceLayer { /// Drops disposable view rows while retaining decisions about the unchanged full source. pub(crate) fn reset_window(&mut self) { self.row_order = None; + self.row_order_refused = false; + if self.error.as_deref() == Some(window::ROW_ORDER_REFUSAL) { + self.clear_error(); + } self.window = None; self.pending = None; self.ready_cache = None; @@ -2261,10 +2269,10 @@ impl SourceLayer { let (kept, filtered, whole) = (b.features.len(), cache.filtered, cache.whole); let w = Window { extent, complete: b.complete, whole, matched: b.matched, kept, filtered, own }; self.row_order = cache.row_order; - let row_order_refused = cache.row_order_refused; + self.row_order_refused = cache.row_order_refused; self.ready_cache = Some(cache); self.window = Some(w); - if row_order_refused { + if self.row_order_refused { self.error = Some(window::ROW_ORDER_REFUSAL.into()); } else { self.clear_error(); @@ -2430,6 +2438,7 @@ impl SourceLayer { estimated_row_bytes: _, full_read: _, row_order: _, + row_order_refused: _, saved_selection: _, grids: _, window_fields: _, @@ -2521,6 +2530,52 @@ impl SourceLayer { #[cfg(test)] mod tests { + /// A failed window read followed by successful whole drawing cannot erase its numbering refusal. + #[test] + fn row_number_refusal_survives_a_failed_read_and_recovered_draw() { + use super::{Pending, Polled, SourceLayer, window}; + use rustgis_data::source::Request; + use rustgis_data::{Dataset, Geometry, GeometryType}; + use rustgis_geom::Coord; + use std::sync::{Arc, Mutex}; + + let mut ds = Dataset::new("sites", GeometryType::Point, Vec::new()); + for x in [-20.0, 20.0] { + ds.push(Some(Geometry::Point(Coord::new(x, 0.0))), Vec::new()); + } + let bytes = Arc::new(rustgis_data::source::fgb::write(&ds).unwrap()); + let handle = rustgis_data::source::open_shared("sites.fgb", bytes.clone(), None).unwrap(); + let all = handle.read(&Request { extent: None, own: None, limit: 2 }).unwrap(); + let first = all.features.first().unwrap().geometry.as_ref().unwrap().extent().padded(0.0, 0.1); + let second = all.features.last().unwrap().geometry.as_ref().unwrap().extent().padded(0.0, 0.1); + let mut source = SourceLayer::from_bytes("sites.fgb", bytes, None, handle); + source.set_query(Some("@row_number = 1"), &[], &Default::default()); + source.start(second, true); + assert!(matches!(source.poll(true), Polled::Done(..))); + assert_eq!(source.error_unsaid().as_deref(), Some(window::ROW_ORDER_REFUSAL)); + + // Land a worker's I/O failure through the same poll path as a real failed read. + source.pending = Some(Arc::new(Pending { + extent: second, + own: None, + result: Mutex::new(Some(Err("temporary source failure".into()))), + still: None, + })); + assert!(matches!(source.poll(true), Polled::Failed(_))); + assert_eq!(source.error_unsaid().as_deref(), Some("temporary source failure")); + source.clear_whole_draw_error(); + assert_eq!(source.error_unsaid().as_deref(), Some(window::ROW_ORDER_REFUSAL)); + source.clear_whole_draw_error(); + assert_eq!(source.error_unsaid(), None, "a repeated draw must not repeat the refusal notice"); + + source.start(first, true); + assert!(matches!(source.poll(true), Polled::Done(..))); + assert!(source.read_error().is_none(), "a proven window recovers the refusal"); + source.error = Some("ordinary traversal failure".into()); + source.clear_whole_draw_error(); + assert!(source.read_error().is_none(), "ordinary recovered failures still clear"); + } + #[test] fn whole_layer_report_keeps_effective_conversion_notes_and_dimensions() { use rustgis_data::{Dataset, GeometryType}; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 858c3ae7d1..54b0e5f3e0 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2477,10 +2477,17 @@ fn render_pass( let mut snapshot = map.clone(); let mut snapshot_budget = SnapshotBudget::new(complete_snapshot_limit()); for layer in &mut snapshot.layers { - if !complete_layers.contains(&layer.id) || layer.source.as_ref().and_then(|s| s.chunk_source()).is_none() { + if !complete_layers.contains(&layer.id) { layer.source = None; continue; } + if layer.source.as_ref().and_then(|s| s.chunk_source()).is_none() { + // Keep a window's row-position proof or refusal, without sharing its pending read. + if let Some(source) = &mut layer.source { + source.detach_read(); + } + continue; + } if !needs_tilted_snapshot(map, layer, &complete_layers, depth_scale) { // Plain fills/lines keep their complete per-band traversal, outside the // global depth-order snapshot and its feature-storage budget. @@ -2977,7 +2984,7 @@ fn render_tilted( .and_then(|s| s.chunk_source()) .is_some() }); - if complete { + if failed_source.is_some() || complete { map.label_lock = lock; return None; } diff --git a/crates/render/src/stream_tests.rs b/crates/render/src/stream_tests.rs index 16522e2eb3..530ae4f1b9 100644 --- a/crates/render/src/stream_tests.rs +++ b/crates/render/src/stream_tests.rs @@ -2411,6 +2411,19 @@ fn streamed_row_number_refusal_survives_whole_draw() { /// A map export must report an unnumbered window rather than write a picture missing its layer. #[test] fn streamed_row_number_refusal_reaches_map_export() { + for pitch in [0.0, 35.0] { + row_number_export_refusal(pitch, false); + } +} + +/// A complete point layer must not strip a refused window's source from the tilted snapshot. +#[test] +fn streamed_row_number_refusal_survives_tilted_snapshot() { + row_number_export_refusal(35.0, true); +} + +/// Exercises exports with one window source, or with an additional complete depth snapshot. +fn row_number_export_refusal(pitch: f64, mixed: bool) { let mut ds = Dataset::new("sites", GeometryType::Point, vec![]); for x in [-20.0, 20.0] { ds.push(Some(Geometry::Point(Coord::new(x, 0.0))), vec![]); @@ -2424,13 +2437,19 @@ fn streamed_row_number_refusal_reaches_map_export() { layer.definition_query = Some("@row_number = 1".into()); let whole = layer.load_all().unwrap(); let second = whole.features.last().unwrap().geometry.as_ref().unwrap().extent().center(); + if mixed { + let other = map.add_dataset(whole.clone()); + *map.layer_mut(other).unwrap() = streamed(map.layer(other).unwrap(), 1); + } let view = View { width: 240.0, height: 120.0, pixels_per_point: 1.0, - camera: Camera::new(rustgis_geom::lonlat_to_merc(second), 30.0), + camera: Camera { pitch, ..Camera::new(rustgis_geom::lonlat_to_merc(second), 30.0) }, sky: false, }; let why = render_png(&mut map, &view).unwrap_err(); assert!(why.contains("Sites") && why.contains("@row_number") && why.contains("Use Load All Features"), "{why}"); + map.layer_mut(id).unwrap().definition_query = None; + assert!(render_png(&mut map, &view).is_ok(), "clearing the query must recover the export"); } diff --git a/docs/user-guide/expressions.md b/docs/user-guide/expressions.md index 20f57f0240..dd811a65fa 100644 --- a/docs/user-guide/expressions.md +++ b/docs/user-guide/expressions.md @@ -93,7 +93,9 @@ operator: write `a < b AND b < c`, not `a < b < c`. | `$length` | A line's length in metres | A definition query using `@row_number` needs whole-layer positions. When a view of a layer read -in place can't determine those positions, use **Load All Features**. Other expressions on a layer read in place can still number the current window; load all features when they need whole-layer positions. +in place can't determine those positions, use **Load All Features**. Outside definition queries, +`@row_number` in label and symbol expressions can still refer to the current window. Use +**Load All Features** when those expressions need whole-layer positions. The three page variables are available to symbols, labels, definition queries and display filters in every map frame on a series page. They are null outside a series page, including in the map From 8f39294de06effbd5c2f43e2cdd3e0d64707165b Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 30 Nov 2026 11:55:22 -0600 Subject: [PATCH 3/3] fix(map): refuse sampled row-number query windows --- crates/data/src/query.rs | 7 ++++++- crates/map/src/lib.rs | 20 ++++++++++++++++++++ crates/map/src/source/window.rs | 14 ++++++++++++-- docs/user-guide/expressions.md | 6 +++--- 4 files changed, 41 insertions(+), 6 deletions(-) diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index c312476c64..c33beef8e2 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -665,7 +665,12 @@ pub fn reads_series_page(text: &str) -> bool { /// Whether the text refers to a row number outside quotes. pub fn reads_row_number(text: &str) -> bool { text.contains('@') - && lex(text).is_ok_and(|tokens| tokens.iter().any(|t| matches!(t, Tok::Var(name) if name.eq_ignore_ascii_case("@row_number")))) + && lex(text).is_ok_and(|tokens| { + tokens.iter().any(|t| { + let Tok::Var(name) = t else { return false }; + VARS.iter().any(|s| matches!(s.var, Var::RowNumber) && s.names.iter().any(|n| n.eq_ignore_ascii_case(name))) + }) + }) } fn lex(s: &str) -> Result, String> { diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 811280a7e3..3e039b681c 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -5343,6 +5343,26 @@ mod tests { assert_eq!(layer.visible_rows(), [true]); assert_eq!(layer.dataset.features[0].id, first.id); assert!(layer.source.as_ref().unwrap().read_error().is_none()); + + // Even a correctly numbered prefix can omit the feature the query asks for. + layer.definition_query = Some("@row_number = 2".into()); + let source = layer.source.as_mut().unwrap(); + source.limit = 1; + source.reset(); + layer.sync_source(&Extent::WORLD_LONLAT, true); + let source = layer.source.as_ref().unwrap(); + assert_eq!(source.sampled(), Some((1, 2))); + assert_eq!(layer.dataset.features[0].id, first.id); + assert_eq!(layer.query_rows(&whole).unwrap(), [false, true]); + assert_eq!(layer.visible_rows(), [false]); + assert!(source.read_error().is_some_and(|why| why.contains("@row_number") && why.contains("Use Load All Features"))); + + let source = layer.source.as_mut().unwrap(); + source.limit = 2; + source.reset(); + layer.sync_source(&Extent::WORLD_LONLAT, true); + assert_eq!(layer.visible_rows(), [false, true]); + assert!(layer.source.as_ref().unwrap().read_error().is_none()); } /// The GeoJSON index knows that the geometry-less row belongs before a spatial match. diff --git a/crates/map/src/source/window.rs b/crates/map/src/source/window.rs index 21abcd7137..536bbef86e 100644 --- a/crates/map/src/source/window.rs +++ b/crates/map/src/source/window.rs @@ -113,8 +113,9 @@ pub(super) fn read_mode( check_areas(&expr, &scratch, &first.0.features, &source.info().name, first.0.complete)?; } if rustgis_data::query::reads_row_number(&query.text) { - first.1.row_order = source.window_row_order(&first.0); - first.1.row_order_refused = first.1.row_order.is_none() && !first.0.features.is_empty(); + // Known positions for a sample do not prove that the query's matches survived thinning. + first.1.row_order = first.0.complete.then(|| source.window_row_order(&first.0)).flatten(); + first.1.row_order_refused = !first.0.complete || (first.1.row_order.is_none() && !first.0.features.is_empty()); return Ok(first); } if first.0.complete || !source.visits_chunks() { @@ -793,6 +794,15 @@ mod tests { assert_eq!(batch.features.len(), cache.projected.len()); assert!(base_bytes(&batch, &(!cache.own).then(|| cache.projected.to_vec())) <= 96 * 1024); assert_eq!(source.read(&Request::all()).unwrap().features.len(), 600); + + // A capped probe that stays empty must refuse a row-number query too. + let mut reader = super::super::SourceLayer::from_path("sparse.fgb", None, Box::new(source)); + reader.limit = 1; + let mut layer = crate::Layer::new_streamed(1, reader); + layer.definition_query = Some("@row_number = 1".into()); + layer.sync_source(&Extent::WORLD_LONLAT, true); + assert!(layer.dataset.features.is_empty()); + assert!(layer.source.as_ref().unwrap().read_error().is_some_and(|why| why.contains("Use Load All Features"))); } #[test] fn one_feature_can_use_the_optional_display_reservation() { diff --git a/docs/user-guide/expressions.md b/docs/user-guide/expressions.md index dd811a65fa..9b5345cd95 100644 --- a/docs/user-guide/expressions.md +++ b/docs/user-guide/expressions.md @@ -93,9 +93,9 @@ operator: write `a < b AND b < c`, not `a < b < c`. | `$length` | A line's length in metres | A definition query using `@row_number` needs whole-layer positions. When a view of a layer read -in place can't determine those positions, use **Load All Features**. Outside definition queries, -`@row_number` in label and symbol expressions can still refer to the current window. Use -**Load All Features** when those expressions need whole-layer positions. +in place is sampled or can't determine those positions, use **Load All Features**. +Outside definition queries, `@row_number` in label and symbol expressions can still refer to the +current window. Use **Load All Features** when those expressions need whole-layer positions. The three page variables are available to symbols, labels, definition queries and display filters in every map frame on a series page. They are null outside a series page, including in the map