Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions crates/data/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,17 @@ 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| {
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<Vec<Tok>, String> {
lex_spans(s, false).map(|l| l.toks)
}
Expand Down
5 changes: 5 additions & 0 deletions crates/data/src/rows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
5 changes: 5 additions & 0 deletions crates/data/src/source/fgb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::WindowRowOrder> {
super::dense_one_based_prefix(&batch.features)
}

fn reads_own_box(&self) -> bool {
true
}
Expand Down
6 changes: 6 additions & 0 deletions crates/data/src/source/geojson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<super::WindowRowOrder> {
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
}
Expand Down
5 changes: 5 additions & 0 deletions crates/data/src/source/gpkg_mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<super::WindowRowOrder> {
(batch.complete && self.info.count == Some(batch.features.len() as u64)).then_some(super::WindowRowOrder::WholeLayer)
}

fn reads_own_box(&self) -> bool {
true
}
Expand Down
5 changes: 5 additions & 0 deletions crates/data/src/source/lidar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<super::WindowRowOrder> {
(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
Expand Down
24 changes: 24 additions & 0 deletions crates/data/src/source/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,20 @@ pub fn rounded_dates_note(fields: &[crate::Field], counts: &[usize]) -> Option<c
Some(crate::loss::Note::loss(crate::loss::LossCode::ChangedRounded, text))
}

/// What a read proves about its window's positions in the layer.
#[derive(Clone, Copy)]
pub enum WindowRowOrder {
/// The read returned every feature in layer order.
WholeLayer,
/// IDs are increasing and are the zero-based layer positions plus this first ID.
IdsStartingAt(u64),
}

/// A view containing the file prefix can prove its record ids are dense row numbers.
fn dense_one_based_prefix(rows: &[Feature]) -> Option<WindowRowOrder> {
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`])
Expand Down Expand Up @@ -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<WindowRowOrder> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Twin check: this default makes every source without an override refuse @row_number on a window. The overrides cover fgb, geojson, gpkg_mem, lidar, parquet and shp. GpkgSource (crates/data/src/source/gpkg.rs, desktop GeoPackage, read in place via reads_own_box) is not overridden, so on desktop every window of a GeoPackage now refuses @row_number until Load All Features. The PR body doesn't mention this, and it is a common format. Refusing is the right default (no wrong numbers), but the PR should say GeoPackage refuses, and say whether a proof is possible for it (for example rowid order on an unchanged file, as geojson does with FileVersion). Postgis, MySQL, SQL Server and ArcGIS refusing is reasonable and could be stated the same way. I checked the other FeatureSource impls listed by grep; Fetching delegates correctly.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added the desktop GeoPackage and database/service limitations to the PR description. These sources intentionally keep the conservative default and require Load All Features. GeoPackage's order_by() provides stable key/rowid ordering, but those values can have gaps, differ from the feature key, and include rows whose geometry cannot be read. File freshness alone does not establish dense feature positions. This change therefore does not infer positions from those keys.

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 {
Expand Down Expand Up @@ -924,6 +944,10 @@ impl FeatureSource for Fetching {
self.0.holds_more_than(n)
}

fn window_row_order(&self, batch: &Batch) -> Option<WindowRowOrder> {
self.0.window_row_order(batch)
}

fn says_unplaced_at_open(&self) -> bool {
self.0.says_unplaced_at_open()
}
Expand Down
5 changes: 5 additions & 0 deletions crates/data/src/source/parquet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::WindowRowOrder> {
super::dense_one_based_prefix(&batch.features)
}

fn reads_own_box(&self) -> bool {
true
}
Expand Down
5 changes: 5 additions & 0 deletions crates/data/src/source/shp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::WindowRowOrder> {
super::dense_one_based_prefix(&batch.features)
}

fn reads_own_box(&self) -> bool {
true
}
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/connections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
119 changes: 113 additions & 6 deletions crates/map/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<bool>> {
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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low confidence (about 25%), defensive. If the ordering proof is ever wrong, or ids are not increasing in window order, checked_sub returns None and is_some_and hides the row with no notice. Under AGENTS.md's "Never silent" rule, a row that disappears from a result is a silent loss. Under the current proofs (fgb/shp/parquet require ids 1..=k in window order, geojson checks skipped == 0 and the file version) I could not construct a case that reaches this branch, so it is a guard, not a known bug. Suggest making the failure visible, for example by returning the refusal (vec![false; …] plus row_order_refused) instead of hiding the single row, or a debug_assert! plus a regression test that a non-monotone window is refused.

Category: bug

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current providers establish the bounds before returning this variant. FlatGeobuf, Shapefile and Parquet require the exact prefix id = row + 1. GeoJSON assigns id = accepted_index + 1 and returns an increasing subset of that index, with no skipped reads and an unchanged file. LiDAR assigns zero-based point positions, returns an ordered subset, and permits this proof only when every point was retained. Thus id - origin is a valid whole-layer position and is at least the row's window index. The immutable GeoPackage proof uses the separate WholeLayer variant.

I found no input through these providers that reaches the failed subtraction/conversion. This is a proposed defensive check for a future broken provider contract, rather than a demonstrated silent-loss path in the current change; no code change is made for it.

});
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
Expand Down Expand Up @@ -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());
Expand All @@ -5290,6 +5309,94 @@ 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());

// 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.
#[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));
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);
Expand Down
Loading
Loading