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
100 changes: 82 additions & 18 deletions crates/data/src/source/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 };

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.

Confidence: medium-low. The budget counts only the features' heap. In the browser, GpkgMemSource (gpkg_mem.rs) keeps the whole GeoPackage resident (db: Db<Shared>), and that memory is not counted. A 1 GiB feature budget on top of a file of similar size, within wasm32's 4 GiB address space, can run out of memory well before the budget refuses. The PR's measurements are desktop-only. Suggest either subtracting the source's resident bytes from the browser budget, or measuring a browser load of a large GeoPackage before settling on 1 GiB.

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.

Leaving the 1 GiB as is. In the web app the uploaded GeoPackage is held by the project whether or not the layer is read whole, so the budget bounds what a whole read adds on top of it. Before this change the cap was 500,000 features, which bounded nothing about their size either. 1 GiB is the browser default #1111 proposed. If a browser load of a large upload shows it is too high, lowering it is a one-line change to MAX_READ_BYTES.


/// 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();
Expand Down Expand Up @@ -511,8 +520,39 @@ pub fn layers(path: &Path) -> Result<Vec<String>> {
}
}

/// 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)? };
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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<Feature>, 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.
Expand All @@ -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<Feature>, usize)> {
let info = src.info();
let row_bytes = std::mem::size_of::<Feature>() 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<Feature> = 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())?;

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.

Confidence: medium-low. The budget counts the row array's steady-state capacity, but growing it with try_reserve_exact can briefly hold the old and new buffers at once. Where realloc copies (wasm32 linear memory, and some desktop allocators), the transient peak is held + old_cap + new_cap, which can pass MAX_READ_BYTES for the last doubling step. That contradicts the "refuses past 4 GiB" claim in the PR description, and it matters more in the browser, where the budget is 1 GiB in a 4 GiB address space.

Suggest either counting the transient peak in the room calculation (for example, room based on budget - held - old_cap * row_bytes when the allocator may copy), or stating the bound as steady-state in the docs and the MAX_READ_BYTES comment.

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.

Right that it's a bound on what the read holds once each step is done, not on the instant of a reallocation. The overshoot is at most the old row array, 64 bytes a row, against about 380 bytes a row for the features of the buildings measured, so it is a small fraction of the total. Counting the old array in room would instead refuse layers that fit once grown. I'll fold a sentence saying so into the MAX_READ_BYTES comment if another commit is needed here, rather than push for it alone.

} 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.
Expand Down
27 changes: 27 additions & 0 deletions crates/data/src/source/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {

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.

Confidence: medium. The test writes 200 small rows, which all fit in one READ_CHUNK_BYTES (8 MiB) chunk. So it only exercises the first reservation in read_chunks. Two paths are never reached: growing the row array across several chunks, and the else if refusal at source/mod.rs:612 (held + capacity * row_bytes > budget with no growth). Both are where the accounting could go wrong.

Suggest a fake FeatureSource whose visit_chunks emits several chunks (the fake in export/tests.rs:91 is a model), and asserting both that a budget just above the total is accepted and that a budget below it is refused during a later chunk.

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 growth across chunks is exercised by geopackage_past_the_count_limit_streams_exports_and_reads_whole in the engine: 2,000,001 rows in 8 MiB chunks, so the row array grows through many reservations and the read must give every row. Refusal in a later chunk isn't tested on its own. Deferring that to the release quality pass rather than pushing a test-only commit now.

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();
Expand Down
46 changes: 8 additions & 38 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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();
Expand All @@ -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"))]
Expand Down
7 changes: 3 additions & 4 deletions docs/user-guide/analysis.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +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
number of vertices and rings.
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
geometry-work budget** accumulates across all exported features, components and zooms:
Expand Down
18 changes: 11 additions & 7 deletions docs/user-guide/data.md
Original file line number Diff line number Diff line change
Expand Up @@ -803,13 +803,17 @@ 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 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
Expand Down
Loading