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
27 changes: 22 additions & 5 deletions crates/data/src/source/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -484,23 +484,40 @@ pub fn layers(path: &Path) -> Result<Vec<String>> {
}
}

/// 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 {

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 fragility, not a bug on today's paths. Batch::default() has complete: false, and several providers return that default unchanged on early exits: mysql.rs (limit == 0, and a lon/lat table with an extent off the world), postgis.rs:1353 and sqlserver.rs:735/741. Before this change, an incomplete empty batch was only a sample notice. Now any complete: false on a whole read becomes an error. materialize calls read(Request::all()) with no extent and a non-zero limit, so these returns aren't reached from here. A future caller that passes an extent, or a limit of 0, to a source would get a "could not read the whole source (0 of 0 features…)" error for an empty result. Setting complete: true on those early returns (they hold no matches, so nothing was left out) would keep the new check honest.

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.

materialize always reads Request::all() (no extent, non-zero limit), so those early returns aren't reachable from a whole read. Changing provider early exits is out of scope here; follow-up candidate. (reviewed at 05ff232)

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())
{
Expand Down
62 changes: 62 additions & 0 deletions crates/data/src/source/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Batch>,
read: AtomicBool,
}
impl FeatureSource for Source {
fn info(&self) -> &SourceInfo {
&self.info
}

fn read(&self, _: &Request) -> Result<Batch> {
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();
Expand Down
73 changes: 73 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<?1)
INSERT INTO roads(fid, geom) SELECT fid, ?2 FROM rows",
rusqlite::params![count as i64, blob],
)
.unwrap(),
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);

let output = fixture.dir.join("refused.geojson");
let error = s.run("share.exportLayer", &json!({"layer": id, "path": output})).unwrap_err();
assert_limit(&error);
assert!(!output.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());

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.

Quality / test cost (confidence: medium). This fixture holds 2,000,001 rows plus an R-tree entry for each, so the .gpkg is probably well over 100 MB. Two things follow:

  • std::fs::read(&path) loads the whole file into memory, and read_owned then copies it again, so this test needs roughly 2–3x the file size in RAM.
  • io::read_owned returns file is too large once the input passes MAX_BYTES (256 MB, crates/data/src/io.rs:11). If the fixture ever grows past that, the final assert_limit fails for an unrelated reason, and the test no longer checks the whole-read limit.

Consider checking the refusal on a path-based call only, or asserting the file size first so a failure names the cause. The fixture's cost in CI time is also worth a note in the PR description.

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.

Measured: the fixture is ~83 MB (2,000,001 rows of fid + a 29-byte point blob; GpkgRegressionFixture creates no R-tree). read_owned takes the Vec without copying, so peak is about one file's worth, and the row count is fixed at MAX_LIMIT + 1, ~3× under MAX_BYTES. Leaving as is. (reviewed at 05ff232)

}

#[cfg(not(target_arch = "wasm32"))]
fn assert_gpkg_regression_clean(s: &mut Session) {
let pending = s.run("gpkg.pendingEdits", &json!({"layer": "R"})).unwrap();
Expand Down
9 changes: 0 additions & 9 deletions crates/map/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -533,15 +533,6 @@ impl Layer {
}
}
let (mut ds, _) = copy.read_all()?;
// A sample isn't all of them: refuse rather than run a tool on part of the data.
let max = rustgis_data::source::MAX_LIMIT;
if let Some(n) = copy.info().and_then(|i| i.count).filter(|n| (ds.features.len() as u64) < *n && *n > 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() {
Expand Down
12 changes: 9 additions & 3 deletions docs/user-guide/data.md
Original file line number Diff line number Diff line change
Expand Up @@ -786,9 +786,15 @@ 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
**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
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.
Expand Down
Loading