Repository navigation
fix(export): honor layer definition queries (#1998) - #2417
Conversation
…on-query # Conflicts: # crates/data/src/query.rs
|
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
| (None, rustgis_map::Unreadable::default()) | ||
| }; | ||
| let (mut whole, unreadable) = | ||
| if l.is_streamed() && chunks.is_none() { l.load_all_counted()? } else { (l.dataset.clone(), rustgis_map::Unreadable::default()) }; |
There was a problem hiding this comment.
Performance (medium, high confidence). This now copies the whole in-memory dataset (l.dataset.clone()) on every export, including exports with no definition query. The old code borrowed &l.dataset, so a large non-streamed layer now needs roughly twice its memory at export time. The same applies to the else branch on the chunked path, where the clone is never used. Suggest copying only when a query is set, and borrowing otherwise, e.g. let owned = (query.is_some() && chunks.is_none()).then(|| l.dataset.clone()); and then filtering a clone only when owned is present. Note that filter_dataset and write_source_filtered already see the query, so the clone is only needed in the in-memory case.
There was a problem hiding this comment.
Native exports now borrow the in-memory dataset and make an owned copy only when filtering removes rows. The original clone copied dataset metadata and shared the feature storage. This also removes the unused metadata clone on the streaming path.
0364bf25e4 passed fork CI.
| } else { | ||
| (None, Default::default()) | ||
| }; | ||
| let (mut dataset, lost) = if l.is_streamed() { l.load_all_counted()? } else { (l.dataset.clone(), Default::default()) }; |
There was a problem hiding this comment.
Performance (medium, high confidence). The same full clone happens in the web download path: (l.dataset.clone(), ...) runs on every non-streamed download, even without a definition query. The browser is single-threaded and memory-constrained, so this doubles the peak memory of large layers. Copy only when l.definition_query is set, as in the share.rs comment. The let ds = &dataset; alias below also adds nothing and can be dropped.
There was a problem hiding this comment.
Browser downloads now borrow the in-memory dataset until a query removes rows. A whole read of a streamed layer is already owned and can be filtered in place.
0364bf25e4 passed fork CI.
| /// Applies a layer's definition query to a whole dataset, using the same missing or invalid | ||
| /// query behavior as drawing the layer. Returns the number of rows excluded. | ||
| pub fn filter_dataset(ds: &mut Dataset, definition_query: Option<&str>) -> Result<usize> { | ||
| match definition_query.and_then(|text| query::parse_fields(text, ds).ok()) { |
There was a problem hiding this comment.
Never silent (low-medium, about 40% confidence). .ok() throws away the parse error. If the stored query doesn't parse, for example one imported from another program, every feature is exported with no notice, and the export shows rows the user filtered out. Drawing the layer also ignores such a query, so this matches the map, which is probably why it was written this way. Still, the user asked for a filter and gets none, so either refuse the export with the parse error or add a notice that the query was not applied. A test with an unparseable query would show which behaviour is intended.
There was a problem hiding this comment.
An unreadable stored query now produces one notice with the parser error. The export uses the unfiltered rows because the map shows those same rows when its stored query cannot be read. Regression coverage checks the output and notice for in-memory and read-in-place exports, alongside the valid-query and no-query cases.
0364bf25e4 passed fork CI.
| crate::progress::begin(src.info().count.map_or(0, |n| usize::try_from(n).unwrap_or(usize::MAX))); | ||
| let batch = src.visit_chunks(None, bytes, &mut |mut chunk| { | ||
| if let Some(expr) = query { | ||
| let mut input = layer.clone(); |
There was a problem hiding this comment.
Performance (nit, high confidence). layer.clone() runs for every chunk, copying the layer's name and every Field just to carry the chunk's features. Build the scratch Dataset once before visit_chunks and swap the features in and out per chunk. This is cheap next to the write, so it's a release-quality-pass item unless it shows up in a profile.
There was a problem hiding this comment.
The streamed writer now sets up one scratch dataset for the query and moves each chunk's features in and out of it. The scratch dataset is reused across chunks and writer retries.
0364bf25e4 passed fork CI.
Code reviewThe PR makes Export Features honor a layer's definition query. The row-number offset across chunks, the query-omission notice, and the no-double-notice path all check out on reading. The tests cover streamed, in-memory, background, and browser exports, with and without a query. I could not compile or run the tests here, so the findings below come from reading the code. Bugs
Security
Performance
Quality
Never silent
AGENTS.md
Low-confidence observations (not posted)
Prior reviews: none on this PR, so no earlier concerns were left alone. Change sizeCompared: the whole PR against main (merge base fd81ab2 to PR head 7d7877f).
|
📖 Docs preview
GitHub Pages takes a minute or two to publish a new commit. Newer commits from the fork aren't published until a maintainer adds the |
| } | ||
| if filtered > 0 { | ||
| let mut keep = keep.into_iter(); | ||
| ds.to_mut().features.retain(|_| keep.next().unwrap_or(false)); |
There was a problem hiding this comment.
Performance (medium, about 70% confidence). This is the memory concern from the earlier threads, narrowed but still present. ds is Cow::Borrowed(&l.dataset) on the in-memory path (share.rs and the browser download). Dataset clones share the Features Arc, so the first to_mut() / DerefMut retain calls Arc::make_mut, which deep-clones every feature in the layer, then drops the excluded ones. A query that excludes a single row of a large layer therefore still needs about twice the layer's memory at export time.
Suggested direction: when the input is borrowed, copy only the kept rows, for example:
let kept: Vec<Feature> = ds.features.iter().zip(keep).filter(|(_, k)| *k).map(|(f, _)| f.clone()).collect();
ds.to_mut().features = kept.into();Keep the in-place retain for Cow::Owned, where the Arc is already unique, so streamed whole reads don't pay an extra copy. The Features::from(Vec) conversion is already used by the chunk path. The two earlier threads (share.rs full clone, lib.rs web clone) are answered for the unfiltered case but this path still doubles memory whenever any row is excluded.
There was a problem hiding this comment.
Confirmed that retain on the borrowed path called Arc::make_mut and cloned the full feature vector before dropping excluded rows. The borrowed path now copies just the matching rows into a new Features value while preserving source order. The owned path still retains rows in place. The existing export tests passed locally.
c99d9bd9f5 passed fork CI.
Code reviewBugs
Security
Performance
Quality (nits, grouped; per AGENTS these may wait for the release quality pass)
AGENTS.md
Prior threads: 4 earlier threads on this PR. Two are answered and left alone: the unreadable-query Change sizeCompared with the base branch (merge base fd81ab2 to PR head 0364bf2): the whole PR against
|
| kept.try_reserve_exact(len - filtered).map_err(|_| DataError::Format("not enough memory to filter export rows".into()))?; | ||
| for feature in source.kept_features(&keep) { | ||
| crate::progress::check()?; | ||
| kept.push(feature.clone()); |
There was a problem hiding this comment.
Performance (medium, about 60% confidence). Re-raised because the code changed and the cost is still there.
The borrowed branch now copies only kept rows, which fixes the Arc::make_mut clone of excluded rows. But kept.push(feature.clone()) deep-clones every kept feature (geometry vectors and Text attributes). When a query is set on an in-memory layer, peak memory is the layer plus a full copy of the kept rows, roughly 2x for a query that keeps most rows. Without a query there is no copy.
The chunk path avoids this because it filters one chunk at a time. Routing the in-memory export through the same chunk writer, or writing the kept rows in CHUNK_BYTES-sized batches, would keep the peak near one chunk. If that is out of scope for this PR, say so in the description.
There was a problem hiding this comment.
Confirmed the kept-row copy. I documented it in the PR description. The chunk writer covers only some native formats. Removing this copy across the whole-dataset writers and browser downloads would require a separate writer change.
4c15747abe passed fork CI.
Code reviewBugs
Security
Performance
Quality (grouped nits; these fall under the release quality pass)
AGENTS.md
Prior threads: 5 earlier concerns on this PR. 4 are fixed in the new code (per-export dataset clone, per-chunk layer clone, full Not verified: the new test covers empty chunks only for GeoJSON. Empty chunks are now passed to the GeoPackage, FlatGeobuf, Parquet and CSV writers, and I did not confirm they handle that. Change sizeCompared with the base branch, merge base fd81ab2 to PR head c99d9bd.
|
…on-query # Conflicts: # crates/ui-egui/src/lib.rs
|
Data Interop now shares Export Features’ query filtering and notices. The regression covers text conversion, streamed GeoJSON, and a whole-source WKT conversion, each with and without a query. I checked the empty-chunk paths in the writers. CSV and FlatGeobuf iterate features, Parquet creates row groups only for nonempty batches, and GeoPackage inserts zero rows and can replay the feed if a later chunk needs a different geometry layout. The progress reset, parameter prose placement, tuple argument, and threading are left for the release quality pass. 4c15747abe passed fork CI. |
| let batch = src.visit_chunks(None, bytes, &mut |mut chunk| { | ||
| if let Some((expr, input)) = &mut scratch { | ||
| input.to_mut().features = chunk.into(); | ||
| filtered += retain_matches(input, expr, total.saturating_add(filtered), false)?; |
There was a problem hiding this comment.
Bugs (low-medium, about 50% confidence). Streamed exports number @row_number by source position: offset is total + filtered, so rows are numbered across chunks. The streamed map view evaluates the same query per chunk, with positions restarting at each chunk (crates/map/src/source/window.rs:164). The same definition query can therefore select different rows on screen than in the export. The export's numbering is arguably the more correct one, but the PR doesn't say the two differ. Either note it in docs/user-guide/sharing.md and the PR, or align the view in a follow-up.
There was a problem hiding this comment.
Confirmed. The export numbers rows by position in the whole layer, which is what @row_number means. The streamed map view restarting at each chunk is the older bug, so it is now on #1998 to fix in the view rather than here.
| let mut filtered = 0; | ||
| for row in 0..len { | ||
| crate::progress::step(usize::from(count_progress))?; | ||
| let matches = query::eval_in_chunk(expr, ds, row, offset); |
There was a problem hiding this comment.
Never silent (low, about 35% confidence). eval_in_chunk returns cond == Some(true), so a row whose evaluation faults (division by zero, a type error that gives null) is dropped. The export then counts it as "left out by the definition query" with no mention of the fault. The fault is kept in Eval (value_or_fault) but only the field calculator reads it. The count is accurate, but the reason is not reported. Consider counting faulting rows separately in QueryReport and saying so in the notice, or documenting that a faulting row is excluded.
There was a problem hiding this comment.
Leaving this as is. A row whose condition evaluates to null or faults is not drawn by the map view either, so the export writes the rows the map shows, as SQL WHERE does. Reporting faults separately would be a change to the query language, not to export, and is left for the release quality pass.
| kept.try_reserve_exact(len - filtered).map_err(|_| DataError::Format("not enough memory to filter export rows".into()))?; | ||
| for feature in source.kept_features(&keep) { | ||
| crate::progress::check()?; | ||
| kept.push(feature.clone()); |
There was a problem hiding this comment.
Re-raised, with new evidence. The author's reply says the kept-row copy (about 2x peak memory for an in-memory layer when the query keeps most rows) is "documented in the PR description". The current PR body (pr-context/metadata.json) has no such note. The code is unchanged here, so the cost is still there. Please add the memory note to the description, or drop the claim. The code can stay as it is.
There was a problem hiding this comment.
The description has it now (Summary, last line): "A filtered in-memory export briefly holds a copy of the kept rows because bounded writing across the whole-dataset and browser formats requires a separate writer change." The metadata you read was probably from before that edit.
Code reviewI checked the source the diff touches, not just the diff. I found no crash paths, no silent loss on the paths I traced, and no unsafe use. The chunk-offset arithmetic, the Bugs
Security
Performance
Quality
AGENTS.md
Prior threads
Change sizeCompared: the whole PR against main (merge base 5f49f29 to PR head 4c15747).
|
Summary
Layer.to_file(), Assistant, MCP, and any plugin workflow that dispatches it. The browser applies the same filtering before download. On a phone, Export Features is available through the desktop interface. Exported files can be reopened as layers.A filtered in-memory export briefly holds a copy of the kept rows because bounded writing across the whole-dataset and browser formats requires a separate writer change.
Testing
rustgis-data,rustgis-engineandrustgis-ui-eguipassed. The local data suite excluded one existing FileGDB test after reproducing GDAL 3.10.3 rejecting its TIN fixture.UI evidence
Both screenshots use the sample Cities layer with
pop_max > 10000000. The export went from 243 cities to 17. The Messages pane reports the 226 excluded cities.Related issue
Part of #1998
Summary by CodeRabbit