From b53bac2f714fa055dc24baa37970bf53b5b8f20d Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 1 Nov 2026 04:39:04 -0600 Subject: [PATCH 1/2] perf(data): read a whole layer within a memory budget instead of a feature count A whole read of a source that can be read a chunk at a time (GeoPackage, FlatGeobuf, GeoParquet, a Shapefile read in place) counts the memory its features hold and refuses past 4 GiB (1 GiB in the web app), instead of refusing at 2,000,000 features. Other sources keep the one-read path and its limit. Step 3 of #1111. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/source/mod.rs | 100 ++++++++++++++++++++++++++------ crates/data/src/source/tests.rs | 27 +++++++++ crates/engine/src/tests.rs | 46 +++------------ docs/user-guide/analysis.md | 6 +- docs/user-guide/data.md | 16 ++--- 5 files changed, 129 insertions(+), 66 deletions(-) diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index b77e425a5d..1aa45d8932 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -105,9 +105,18 @@ impl Family { /// File types read through a provider. pub const EXTENSIONS: &[&str] = &["gpkg", "parquet", "geoparquet", "fgb", "las", "laz"]; -/// The most features one read returns, whatever the request asks for. +/// The most features one read returns, whatever the request asks for. A whole read of a source +/// read a chunk at a time is bounded by [`MAX_READ_BYTES`] instead. pub const MAX_LIMIT: usize = if cfg!(target_arch = "wasm32") { 500_000 } else { 2_000_000 }; +/// The most memory a whole read may hold of a source that can be read a chunk at a time +/// ([`FeatureSource::visits_chunks`]): its features' storage, as [`chunk_memory::features_bytes`] +/// counts it. +pub const MAX_READ_BYTES: u64 = if cfg!(target_arch = "wasm32") { 1 << 30 } else { 4 << 30 }; + +/// The chunk size a whole read asks for; each chunk is moved into the dataset as it comes. +const READ_CHUNK_BYTES: usize = 8 << 20; + /// Whether a file name is read through a provider. pub fn is_source_name(name: &str) -> bool { let ext = Path::new(name).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); @@ -511,8 +520,39 @@ pub fn layers(path: &Path) -> Result> { } } -/// Reads a whole source into a dataset, refusing sources over [`MAX_LIMIT`] and incomplete reads. +/// Reads a whole source into a dataset: a chunk at a time up to [`MAX_READ_BYTES`] where the +/// source can, otherwise in one read up to [`MAX_LIMIT`]. A larger source, or an incomplete read, +/// is refused. pub fn materialize(src: &dyn FeatureSource) -> Result<(Dataset, ReadReport)> { + materialize_within(src, MAX_READ_BYTES) +} + +/// [`materialize`], with `budget` bytes for a source read a chunk at a time. +fn materialize_within(src: &dyn FeatureSource, budget: u64) -> Result<(Dataset, ReadReport)> { + let info = src.info(); + let (features, skipped) = if src.visits_chunks() { read_chunks(src, budget)? } else { read_at_once(src)? }; + 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" && skipped > 0) || src.lost_to_crs(); + ds.zm_dropped = info.zm_dropped; + ds.features = features.into(); + let report = ReadReport { + skipped: skipped + src.skipped_at_open(), + messages: info.notes.iter().map(|n| format!("{}: {n}", info.name)).collect(), + }; + if ds.geometry_type == GeometryType::None + && let Some(g) = ds.features.iter().find_map(|f| f.geometry.as_ref()) + { + ds.geometry_type = g.kind(); + } + Ok((ds, report)) +} + +/// Every feature of a source in one read, and the rows it skipped, refusing a source over +/// [`MAX_LIMIT`] and an incomplete read. +fn read_at_once(src: &dyn FeatureSource) -> Result<(Vec, usize)> { 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. @@ -535,23 +575,47 @@ pub fn materialize(src: &dyn FeatureSource) -> Result<(Dataset, ReadReport)> { 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.zm_dropped = info.zm_dropped; - ds.features = batch.features.into(); - let report = ReadReport { - skipped: batch.skipped + src.skipped_at_open(), - messages: info.notes.iter().map(|n| format!("{}: {n}", info.name)).collect(), + Ok((batch.features, batch.skipped)) +} + +/// Every feature of a source that can be read a chunk at a time, and the rows it skipped, +/// refusing the source once its features would hold more than `budget` bytes. +fn read_chunks(src: &dyn FeatureSource, budget: u64) -> Result<(Vec, usize)> { + let info = src.info(); + let row_bytes = std::mem::size_of::() as u64; + let too_large = || { + DataError::Format(format!( + "{}: the layer needs more than the {} MiB a whole read may hold: clip or filter it first", + info.name, + budget >> 20 + )) }; - if ds.geometry_type == GeometryType::None - && let Some(g) = ds.features.iter().find_map(|f| f.geometry.as_ref()) - { - ds.geometry_type = g.kind(); - } - Ok((ds, report)) + let no_memory = || DataError::Format(format!("{}: not enough memory to read the whole layer", info.name)); + // A count that alone is too many rows is refused before reading. It isn't trusted to size the + // rows: a file's header can claim any count. + if info.count.is_some_and(|n| n.saturating_mul(row_bytes) > budget) { + return Err(too_large()); + } + let mut features: Vec = Vec::new(); + let mut held = 0u64; + let batch = src.visit_chunks(None, READ_CHUNK_BYTES, &mut |chunk| { + held = chunk.iter().fold(held, |n, f| n.saturating_add(chunk_memory::feature_bytes(f) as u64)); + let needed = features.len().saturating_add(chunk.len()); + if needed > features.capacity() { + // Grow by doubling, but never past what the budget leaves for the rows. + let room = usize::try_from(budget.saturating_sub(held) / row_bytes).unwrap_or(usize::MAX); + let grown = needed.max(features.capacity().saturating_mul(2)).min(room); + if grown < needed { + return Err(too_large()); + } + features.try_reserve_exact(grown - features.len()).map_err(|_| no_memory())?; + } else if held.saturating_add((features.capacity() as u64).saturating_mul(row_bytes)) > budget { + return Err(too_large()); + } + features.extend(chunk); + Ok(()) + })?; + Ok((features, batch.skipped)) } /// The geometry type of a source that doesn't declare one, from its first feature. diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 139b6e04ff..9be26e1cf9 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -279,6 +279,33 @@ fn materialize_refuses_oversized_and_incomplete_sources() { assert_eq!(report.skipped, 1); } +/// A whole read of a source that can be read a chunk at a time holds what one read gives, and is +/// refused once its features outgrow the memory budget (#1111). +#[test] +fn whole_reads_by_chunk_stay_within_the_memory_budget() { + let d = dir().join("budget"); + std::fs::create_dir_all(&d).unwrap(); + let mut ds = Dataset::new("lines", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + for i in 0..200 { + let x = f64::from(i) * 0.01; + ds.push_next(Some(Geometry::Line(vec![vec![Coord::new(x, 1.0), Coord::new(x, 2.0)]])), vec![Value::Text(format!("line {i}"))]); + } + for ext in ["gpkg", "fgb", "parquet", "shp"] { + let p = d.join(format!("lines.{ext}")); + let _ = std::fs::remove_file(&p); + crate::io::write_path(&ds, &p).unwrap(); + let src = open_path(&p, None).unwrap(); + assert!(src.visits_chunks(), "{ext}"); + let once = src.read(&Request::all()).unwrap().features; + let (whole, report) = materialize_within(src.as_ref(), MAX_READ_BYTES).unwrap(); + assert_eq!(whole.features.to_vec(), once, "{ext}"); + assert_eq!(report.skipped, 0, "{ext}"); + let half = chunk_memory::features_bytes(&once) as u64 / 2; + let error = materialize_within(src.as_ref(), half).unwrap_err().to_string(); + assert!(error.contains("clip or filter it first"), "{ext}: {error}"); + } +} + #[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 aa5a3e9725..8a725cc91e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -20374,11 +20374,12 @@ fn a_streamed_export_counts_the_rows_it_could_not_read() { } } -/// Whole reads must refuse an oversized provider instead of returning its capped sample (#1108). +/// A GeoPackage past the count limit is read whole within the memory budget, not refused or +/// sampled (#1108, #1111), and exported a chunk at a time. #[cfg(not(target_arch = "wasm32"))] #[test] -fn oversized_geopackage_refuses_whole_reads_but_streams_and_exports() { - use rustgis_data::{Dataset, Geometry, GeometryType, source::MAX_LIMIT}; +fn geopackage_past_the_count_limit_streams_exports_and_reads_whole() { + use rustgis_data::{Geometry, source::MAX_LIMIT}; let fixture = GpkgRegressionFixture::new("whole-read-limit"); let path = fixture.path(); @@ -20404,37 +20405,13 @@ fn oversized_geopackage_refuses_whole_reads_but_streams_and_exports() { count ); drop(db); - let assert_limit = |error: &str| { - assert!(error.contains(&count.to_string()), "missing source count: {error}"); - assert!(error.contains(&MAX_LIMIT.to_string()), "missing whole-read limit: {error}"); - }; - let mut s = Session::new(Project::default()); - let error = s.run("layer.addData", &json!({"path": path, "stream": false})).unwrap_err(); - assert_limit(&error); - assert!(s.map().layers.is_empty(), "a refused read must not add a partial layer"); - - // A real file input to merge must fail even when the map already has a usable input layer. - let mut initial = Dataset::new("Initial", GeometryType::Point, vec![]); - initial.push_next(Some(Geometry::Point(rustgis_geom::Coord::new(0.0, 0.0))), vec![]); - let initial_id = s.map_mut().add_dataset(initial); - let error = s.run("gp.run", &json!({"tool": "merge", "params": {"inputs": [path], "output": "Merged"}})).unwrap_err(); - assert_limit(&error); - assert_eq!(s.map().layers.len(), 1); - assert!(s.map().layer_by_name("Merged").is_none()); - assert_eq!(s.map().layer(initial_id).unwrap().dataset.features.len(), 1); - let loaded = s.run("layer.addData", &json!({"path": path, "stream": true})).unwrap(); assert_eq!(loaded["features"].as_u64(), Some(count as u64)); let id = loaded["layer"].as_u64().unwrap() as u32; assert!(s.map().layer(id).unwrap().is_streamed()); let resident = s.map().layer(id).unwrap().dataset.features.len(); assert!(resident < count); - let error = s.run("layer.loadAll", &json!({"layer": id})).unwrap_err(); - assert_limit(&error); - assert!(s.map().layer(id).unwrap().is_streamed()); - assert_eq!(s.map().layer(id).unwrap().dataset.features.len(), resident); - // Exported a chunk at a time, past the limit a whole read has. let output = fixture.dir.join("whole.csv"); let exported = s.run("share.exportLayer", &json!({"layer": id, "path": output})).unwrap(); @@ -20449,17 +20426,10 @@ fn oversized_geopackage_refuses_whole_reads_but_streams_and_exports() { rows += 1; } assert_eq!(rows, count, "every row"); - // A format still written from a whole layer is refused, and writes nothing. - let refused = fixture.dir.join("refused.kml"); - let error = s.run("share.exportLayer", &json!({"layer": id, "path": refused})).unwrap_err(); - assert_limit(&error); - assert!(!refused.exists(), "a refused export must not write a partial file"); - assert!(s.map().layer(id).unwrap().is_streamed()); - assert_eq!(s.map().layer(id).unwrap().dataset.features.len(), resident); - assert_eq!(s.map().layers.len(), 2); - - assert_limit(&rustgis_data::io::read_path(&path).unwrap_err().to_string()); - assert_limit(&rustgis_data::io::read_owned("oversized.gpkg", std::fs::read(&path).unwrap()).unwrap_err().to_string()); + // A whole read is bounded by memory, not by the count. + s.run("layer.loadAll", &json!({"layer": id})).unwrap(); + assert!(!s.map().layer(id).unwrap().is_streamed()); + assert_eq!(s.map().layer(id).unwrap().dataset.features.len(), count); } #[cfg(not(target_arch = "wasm32"))] diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index e09b1885f5..0ca5a3764c 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -154,9 +154,9 @@ integer attributes outside ±2^53 are rejected to avoid precision loss. This is an in-memory export, limited to 10,000 distinct output tiles and a conservative 256 MiB working-memory budget, including the input, clipping/encoding temporaries and final archive. This budget is checked after streamed-source materialization, not during provider -loading: the existing full-read limits (2,000,000 features on desktop, 500,000 in the browser) -apply first, and loading may use more than 256 MiB before export refuses the input. Reduce a -large source before loading it for export. Geometry allocation estimates are linear in the +loading: the whole-read limits ([Large files](data.md#large-files)) apply first, and loading may +use more than 256 MiB before export refuses the input. Reduce a large source before loading it +for export. Geometry allocation estimates are linear in the number of vertices and rings. Each geometry component's buffered candidate rectangle is limited to 40,000 tiles per zoom, including candidates where clipping produces no output. A separate **100,000,000-unit diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 7d7cf070be..40e9fa8ed2 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -803,13 +803,15 @@ GeoParquet source one row group at a time (memory grows with its largest row gro output a small index entry for each feature. A source read by its web address is exported whole, as below. Geoprocessing tools, other exports and -**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 +**Load All Features** read the whole source. A GeoPackage, FlatGeobuf or GeoParquet file, or a +Shapefile read in place, is read a chunk at a time, with no limit on its feature count, up to +4 GiB of features in memory (1 GiB in the web app). Other sources (a large GeoJSON read in +place, LAS/LAZ, databases, a file by its web address) are read at once, 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. The same holds for a GeoPackage, FlatGeobuf, GeoParquet or LAS/LAZ file +added without streaming (`layer.addData` with `"stream": false`) or given to a geoprocessing tool +as a file path. 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 From 2daa473d21a64be92fd8a7674c981dc13eee7182 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 1 Nov 2026 04:55:43 -0600 Subject: [PATCH 2/2] docs: say which limits apply to which whole reads Reword the Large files paragraph so the refusal names neither format as count-limited, note that a GeoParquet or FlatGeobuf file read by its web address in the web app must be downloaded to be read whole, and rejoin a line in the vector tile export section. Co-Authored-By: Claude Opus 5.5 --- docs/user-guide/analysis.md | 3 +-- docs/user-guide/data.md | 10 ++++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 0ca5a3764c..ad7dc99d20 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -156,8 +156,7 @@ This is an in-memory export, limited to 10,000 distinct output tiles and a conse archive. This budget is checked after streamed-source materialization, not during provider loading: the whole-read limits ([Large files](data.md#large-files)) apply first, and loading may use more than 256 MiB before export refuses the input. Reduce a large source before loading it -for export. Geometry allocation estimates are linear in the -number of vertices and rings. +for export. Geometry allocation estimates are linear in the number of vertices and rings. Each geometry component's buffered candidate rectangle is limited to 40,000 tiles per zoom, including candidates where clipping produces no output. A separate **100,000,000-unit geometry-work budget** accumulates across all exported features, components and zooms: diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 40e9fa8ed2..9cae98a73a 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -808,10 +808,12 @@ Shapefile read in place, is read a chunk at a time, with no limit on its feature 4 GiB of features in memory (1 GiB in the web app). Other sources (a large GeoJSON read in place, LAS/LAZ, databases, a file by its web address) are read at once, 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. The same holds for a GeoPackage, FlatGeobuf, GeoParquet or LAS/LAZ file -added without streaming (`layer.addData` with `"stream": false`) or given to a geoprocessing tool -as a file path. An incomplete read is an error, not a successful sample. A tool given a +that, since a read that reaches the limit is refused). A source past its limit, memory or +count, is refused rather than processed as a sample, and these limits also apply to a file added +without streaming (`layer.addData` with `"stream": false`) or given to a geoprocessing tool as a +file path (a Shapefile so added goes through the Shapefile reader and its file-size limit). An +incomplete read is an error, not a successful sample. In the web app, a GeoParquet or FlatGeobuf +file read in place by its web address isn't read whole: download it to load it. 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