From 5b5e924a4654d4a7b49f3b40970eff574682f89d Mon Sep 17 00:00:00 2001 From: Daniel Hofbauer Date: Thu, 29 Oct 2026 00:04:52 +0100 Subject: [PATCH 1/2] fix(data): refuse a source over the read limit instead of reading a sample as the whole of it (#1108) --- crates/data/src/source/mod.rs | 27 +++++++++--- crates/data/src/source/tests.rs | 62 ++++++++++++++++++++++++++++ crates/engine/src/tests.rs | 73 +++++++++++++++++++++++++++++++++ crates/map/src/lib.rs | 9 ---- docs/user-guide/data.md | 8 +++- 5 files changed, 163 insertions(+), 16 deletions(-) diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 0635d8287e..a4862b605c 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -484,23 +484,40 @@ pub fn layers(path: &Path) -> Result> { } } -/// Reads a whole source into a dataset. +/// Reads a whole source into a dataset, refusing sources over [`MAX_LIMIT`] and incomplete reads. pub fn materialize(src: &dyn FeatureSource) -> Result<(Dataset, ReadReport)> { let info = src.info(); + let too_many = |n| DataError::Format(format!("{}: the layer has {n} features, more than the {MAX_LIMIT} read at once", info.name)); + // Refuse before reading or allocating a sample when the source already knows its size. + if let Some(n) = info.count.filter(|n| *n > MAX_LIMIT as u64) { + return Err(too_many(n)); + } let batch = src.read(&Request::all())?; + if !batch.complete { + if batch.matched > MAX_LIMIT as u64 { + return Err(too_many(batch.matched)); + } + return Err(DataError::Format(format!( + "{}: could not read the whole source ({} of {} features; read limit {MAX_LIMIT})", + info.name, + batch.features.len(), + batch.matched + ))); + } + // Preserve Load All Features' conservative refusal when the source cannot give a count. + if info.count.is_none() && batch.features.len() >= MAX_LIMIT { + return Err(DataError::Format(format!("{}: the layer has more features than the {MAX_LIMIT} read at once", info.name))); + } let mut ds = Dataset::new(info.name.clone(), info.geometry_type, info.fields.clone()); ds.crs = info.coordinate_system(); // A streamed Shapefile skips unconvertible shapes rather than retaining empty geometry. // Once materialized, it must still direct CRS repairs back to the original file. ds.crs_incomplete = (info.format == "Shapefile" && batch.skipped > 0) || src.lost_to_crs(); ds.features = batch.features.into(); - let mut report = ReadReport { + let report = ReadReport { skipped: batch.skipped + src.skipped_at_open(), messages: info.notes.iter().map(|n| format!("{}: {n}", info.name)).collect(), }; - if !batch.complete { - report.messages.push(format!("{}: read a sample of {} of {} features", info.name, ds.features.len(), batch.matched)); - } if ds.geometry_type == GeometryType::None && let Some(g) = ds.features.iter().find_map(|f| f.geometry.as_ref()) { diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 43ff8f280c..71ec5783fd 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -207,6 +207,68 @@ fn check(src: &dyn FeatureSource, expect_indexed: bool) { assert!(report.messages.is_empty()); } +#[test] +fn materialize_refuses_oversized_and_incomplete_sources() { + use std::sync::atomic::{AtomicBool, Ordering}; + + struct Source { + info: SourceInfo, + batch: Option, + read: AtomicBool, + } + impl FeatureSource for Source { + fn info(&self) -> &SourceInfo { + &self.info + } + + fn read(&self, _: &Request) -> Result { + self.read.store(true, Ordering::Relaxed); + self.batch.clone().ok_or_else(|| DataError::Format("read reached".into())) + } + } + let mut src = Source { + info: SourceInfo { + name: "large".into(), + format: "Test", + geometry_type: GeometryType::None, + fields: vec![], + extent: Extent::EMPTY, + count: Some(MAX_LIMIT as u64 + 1), + crs: "EPSG:4326".into(), + indexed: false, + notes: vec![], + }, + batch: None, + read: AtomicBool::new(false), + }; + let error = materialize(&src).unwrap_err().to_string(); + assert!(error.contains(&(MAX_LIMIT + 1).to_string()) && error.contains(&MAX_LIMIT.to_string()), "{error}"); + assert!(!src.read.load(Ordering::Relaxed), "an oversized source must be refused before reading"); + + // Exactly the limit is allowed through to the provider; no huge allocation needed to check. + src.info.count = Some(MAX_LIMIT as u64); + assert!(materialize(&src).unwrap_err().to_string().contains("read reached")); + assert!(src.read.load(Ordering::Relaxed)); + + // Unknown or stale metadata must not allow an incomplete batch to become a dataset. + for count in [None, Some(1)] { + src.info.count = count; + src.batch = Some(Batch { matched: MAX_LIMIT as u64 + 1, complete: false, ..Batch::default() }); + let error = materialize(&src).unwrap_err().to_string(); + assert!(error.contains(&(MAX_LIMIT + 1).to_string()) && error.contains(&MAX_LIMIT.to_string()), "{error}"); + } + // Even an incomplete answer below the cap isn't a whole read. + src.batch = Some(Batch { matched: 1, complete: false, ..Batch::default() }); + let error = materialize(&src).unwrap_err().to_string(); + assert!(error.contains("large") && error.contains(&MAX_LIMIT.to_string()), "{error}"); + + // Unreadable rows reported by a complete scan still follow ReadReport's skip contract. + src.batch = Some(Batch { matched: 1, complete: true, skipped: 1, ..Batch::default() }); + let (ds, report) = materialize(&src).unwrap(); + assert!(ds.features.is_empty()); + assert_eq!(report.skipped, 1); +} + #[test] fn geoparquet_with_and_without_a_covering() { let d = dir(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9ecb5e6c4a..0082c0766d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -19323,6 +19323,79 @@ impl Drop for GpkgRegressionFixture { } } +/// Whole reads must refuse an oversized provider instead of returning its capped sample (#1108). +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn oversized_geopackage_refuses_whole_reads_but_can_stream() { + use rustgis_data::{Dataset, Geometry, GeometryType, source::MAX_LIMIT}; + + let fixture = GpkgRegressionFixture::new("whole-read-limit"); + let path = fixture.path(); + let count = MAX_LIMIT + 1; + let db = rusqlite::Connection::open(&path).unwrap(); + // A single SQLite statement generates the rows without keeping millions of features in Rust. + // The compact, valid point blob omits the optional envelope to keep this fixture small. + let mut blob = b"GP\x00\x01".to_vec(); + blob.extend_from_slice(&4326i32.to_le_bytes()); + blob.extend(rustgis_data::wkb::encode(&Geometry::Point(rustgis_geom::Coord::new(1.0, 20.0)))); + db.execute_batch( + "DELETE FROM roads; + UPDATE gpkg_contents SET min_x=1, max_x=1, min_y=20, max_y=20 WHERE table_name='roads';", + ) + .unwrap(); + assert_eq!( + db.execute( + "WITH RECURSIVE rows(fid) AS (SELECT 1 UNION ALL SELECT fid+1 FROM rows WHERE fid max as u64) { - return Err(format!("the layer has {n} features, more than the {max} read at once")); - } - // A count the source doesn't know, and a read that hit the limit: maybe not all of them. - if copy.info().is_some_and(|i| i.count.is_none()) && ds.features.len() >= max { - return Err(format!("the layer has more features than the {max} read at once")); - } ds.name = self.dataset.name.clone(); // (A project that lists no fields keeps the source's, as `sync_source` gives it.) if !self.dataset.fields.is_empty() { diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 8b8b08d61d..022ab70c93 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -787,8 +787,12 @@ features it shows. A single feature, a bare geometry or TopoJSON is loaded whole A streamed layer works like any other for symbology, labels, pop-ups, selection and the attribute table (which lists the features read for the view). Geoprocessing tools, exports and **Load All Features** read the whole source, up to 2 million features (500,000 in the web app); -a larger source is refused rather than processed as a sample. A tool given a streamed layer with -a selection uses the selected features read for the view. Edits are refused, since the features are read again as the view moves: right-click the +a larger source is refused rather than processed as a sample. This also applies when adding a +file without streaming (`layer.addData` with `"stream": false`), or giving a geoprocessing tool +a file path. If the source's feature count is known, an oversized whole read is refused before +reading its features; an incomplete read is an error, not a successful sample. A tool given a +streamed layer with a selection uses the selected features read for the view. Edits are refused, +since the features are read again as the view moves: right-click the layer in Layers and choose **Load All Features** (`layer.loadAll`) to load it into memory and edit it. Projects save the layer's file path, not its features, and read the file again when they open; a browser upload is kept in the project. From 05ff23230a667fb391f0a346e7783b8e1e1b9c79 Mon Sep 17 00:00:00 2001 From: Daniel Hofbauer Date: Thu, 29 Oct 2026 00:23:21 +0100 Subject: [PATCH 2/2] docs: name the formats a whole read refuses, and the boundary for sources without a count --- docs/user-guide/data.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 022ab70c93..be58465afa 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -786,11 +786,13 @@ features it shows. A single feature, a bare geometry or TopoJSON is loaded whole A streamed layer works like any other for symbology, labels, pop-ups, selection and the attribute table (which lists the features read for the view). Geoprocessing tools, exports and -**Load All Features** read the whole source, up to 2 million features (500,000 in the web app); -a larger source is refused rather than processed as a sample. This also applies when adding a -file without streaming (`layer.addData` with `"stream": false`), or giving a geoprocessing tool -a file path. If the source's feature count is known, an oversized whole read is refused before -reading its features; an incomplete read is an error, not a successful sample. A tool given a +**Load All Features** read the whole source, up to 2 million features (500,000 in the web app; +a source that doesn't report its feature count must have fewer than that, since a read that +reaches the limit is refused); a larger source is refused rather than processed as a sample. A +GeoPackage, GeoParquet, FlatGeobuf or LAS/LAZ file is refused the same way when added without +streaming (`layer.addData` with `"stream": false`) or given to a geoprocessing tool as a file +path. If the source's feature count is known, an oversized whole read is refused before reading +its features; an incomplete read is an error, not a successful sample. A tool given a streamed layer with a selection uses the selected features read for the view. Edits are refused, since the features are read again as the view moves: right-click the layer in Layers and choose **Load All Features** (`layer.loadAll`) to load it into memory and