Repository navigation
perf(data): read a whole layer within a memory budget instead of a feature count #1255
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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<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)? }; | ||
|
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. | ||
|
|
@@ -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())?; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 Suggest either counting the transient peak in the
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
| } 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. | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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() { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 Suggest a fake
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The growth across chunks is exercised by |
||
| 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(); | ||
|
|
||
There was a problem hiding this comment.
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.There was a problem hiding this comment.
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.