Repository navigation
fix(engine): honor row policies and prepare Similar in background - #2480
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
| // A covering layer that is gone leaves the rule with nothing to check (its layer's | ||
| // latitudes are still checked). | ||
| // latitudes are still checked). Its whole resident dataset supplies coverage, | ||
| // independently of its selection and definition query. |
There was a problem hiding this comment.
Silent: a covering layer's definition query is ignored with no notice (confidence: medium).
by is taken from b.dataset with no row policy, so a covering layer hidden by its definition query or selection still counts as coverage. The map shows that layer filtered, but topology.validate reports points as covered by polygons the user has hidden, and nothing says so. The new test at tests.rs (topology_row_contracts_and_unreadable_query_notice, the cover layer with definition_query = "n > 100") asserts exactly this behaviour, so it is now codified rather than incidental.
This is not new: the old code also used b.dataset.clone(). The PR body says covering-layer policy is preserved, so this may be intended. If it is, a notice (for example "covering layer X has a definition query; coverage uses all its rows") would meet the "never silent" rule. If it is not, switch the covering side to Policy::Query.
There was a problem hiding this comment.
Covering rows deliberately use the complete resident dataset. Before this change, topology_checks cloned b.dataset and check_topology passed that whole dataset to not_covered; the covering layer’s map query and selection are outside this rule’s input scope. Primary rows retain Query scope. The new command test checks that distinction, including an empty primary query. This path neither filters away covering geometry nor attempts to compile its query, so it does not use the unreadable-query fallback being reported here. Keeping the established covering contract avoids changing which primary features satisfy the rule.
Code reviewBugs
Security
Performance
Quality
AGENTS.md
Previously raised concerns: none. Change sizeCompared: the whole PR against main (merge base 96da316 to PR head 43fbe5b).
|
|
The covering-layer policy is intentional and unchanged; the inline reply explains its primary Query / covering All contract and actual-command coverage. The fallible-signature and doc-wording points are left for the release quality pass. |
📖 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 |
|
|
||
| /// Compare All resident candidates. Selection supplies only the reference when row is omitted; | ||
| /// filtering candidates would also change the population used to standardize distances. | ||
| fn similar(s: &mut Session, p: &Value) -> CmdResult { |
There was a problem hiding this comment.
Selected results can be rows the definition query hides (confidence: medium-high).
This PR now documents and tests "All resident candidates" for data.similar. The candidate population is right, but select defaults to true, and that path ends in select::set(.., Mode::New) (crates/engine/src/cmd/select.rs:127). That function only drops out-of-range rows, so the hidden candidates are written into the layer's selection. With a valid query such as n > 5, a user who runs Embeddings on a drawn row can end up with invisible features selected. That contradicts docs/user-guide/analysis.md:14, which says a definition query "keeps [a feature] out" of selection.
The new test does not cover this. Its final data.similar call (no select key) runs after the loop, and the loop's last query is missing = 1, which is unreadable and hides nothing. So the selection assertion at tests.rs (selection == [0, 1, 2]) never sees a hidden row.
Suggested fix, pick one:
- keep All as the candidate population, but when
selectis true, select only the returned rows the layer's definition query keeps (or the reference row), and add a test with a valid query that hides a candidate; - or keep the behaviour and say in the user guide and in the command's params text that Embeddings' selection can include hidden features.
There was a problem hiding this comment.
Fixed in fc74b0b. The regression first reproduced [0,1,2] selected under n >= 2, where only [1,2] should be selected. Similar still returns the same all-resident rankings; output selection now uses the existing drawn-row mask for queries, time windows and display filters, excludes a hidden explicit reference too, and reports the excluded count once. The valid/empty/unreadable-query and display-filter matrix passes, as do Clippy, strict wasm, hooks and full fork CI.
Code reviewBugs
Security
Performance
Quality (left for the release quality pass)
AGENTS.md
Already raised, left alone: 1 concern. The covering layer's definition query is ignored without a notice ( Change sizeCompared with the base branch: the whole PR, merge base efd48ea to PR head 20bd5cd.
|
|
The hidden-selection bug is fixed and covered by the reproduced regression in fc74b0b. The guide now explains the all-resident diagnostic/ranking populations and drawn-only Similar output selection. The PR body states the retained index storage and temporary visibility-mask sizes; no feature/geometry copy is added. The shared-notice-helper and fallible-signature refactor points are left for the release quality pass. |
| if b(p, "select").unwrap_or(true) { | ||
| let mut sel: Vec<usize> = found.iter().map(|x| x.0).collect(); | ||
| sel.push(row); | ||
| let drawn = l.drawn_rows(s.scale()); |
There was a problem hiding this comment.
Silent query fallback on the select path (confidence: medium).
drawn_rows falls back silently when the definition query doesn't compile (query_rows_with(...).unwrap_or_else(|| vec![true; ..])), and it skips an unparseable display filter with if let Ok(e). So with select on, an unreadable query such as missing = 1 selects every candidate, and nothing is said. The new test resident_data_diagnostics_keep_all_rows_despite_map_filters enshrines that: its loop asserts notices.len() == usize::from(excluded > 0), which is 0 for missing = 1.
This PR now reports the same fallback for topology.validate ("reading without that query"), so the two commands disagree. Under the "Never silent" rule, the selection path should say the same thing: when Query::compile fails for the layer's definition query (or a display filter fails to parse), add one notice with the count and layer, and extend the test so missing = 1 expects that notice while clean queries expect none.
There was a problem hiding this comment.
Fixed in 7a2e61c. The regression first failed with zero notices for missing = 1. Selection now reports unreadable definition queries and active display filters in one notice, counting all failed settings but retaining only the first literal parser error. The existing selection fallback and rankings remain unchanged; select: false stays quiet. The matrix also checks two failed display filters counted in one notice. Regression, Clippy, strict wasm, hooks and full fork CI passed.
Code reviewBugs
Security
Performance
Quality
AGENTS.md
Earlier concerns
Change sizeCompared with the base branch (merge base efd48ea to PR head fc74b0b).
|
|
The Similar selection fallback is now reported and covered in 7a2e61c. Both definition-query and active-display-filter failures are counted, with a single literal diagnostic rather than an unbounded detail list. The PR body gives index/visibility-buffer sizes as multiples of resident layer bytes and records zero additional full feature/geometry copies. The fallible-signature and TopologyInput doc wording points remain left for the release quality pass. |
| /// Compare All resident candidates. Selection supplies only the reference when row is omitted; | ||
| /// filtering candidates would also change the population used to standardize distances. | ||
| /// Output selection keeps only drawn rows, reporting candidates/reference excluded by map filters. | ||
| fn similar(s: &mut Session, p: &Value) -> CmdResult { |
There was a problem hiding this comment.
AGENTS.md: UI-thread work without a stated reason (confidence: medium-low).
data.similar is a synchronous command (Effects::NONE, no reads, gp::tool_start or workflows::runs_in_background path). Its work already grows with the layer: network::similar scans every resident row. This change adds a second all-row pass, l.drawn_rows(scale), which evaluates the definition query and applicable display filters over every row, and it runs on the UI thread too. The new doc comment doesn't say why the command stays on the UI thread or that the pass has no Cancel check.
The "never hold the window" rule asks for either an off-thread path or a doc comment saying why it must run on the UI thread. The first half was already missing before this PR, so this is not a regression on its own. The fix here is either to add that doc comment, or to route the command through a background path.
There was a problem hiding this comment.
Fixed in 827e68f. Desktop UI and direct scoped MCP compute Similar through the read queue with progress/Cancel, sharing input rows; only current successful completion applies selection and notices. Stale input and failed worker creation refuse instead of rerunning on the window thread. Ranking loops check cancellation, and selection predicates now examine only at most 1,001 result/reference rows. The stable sort and detached time-mask fill are documented indivisible steps. Actual UI/relay tests, both cancellation sweeps, 2,664 bitwise ranking comparisons and full exact-head fork CI passed.
Code reviewBugs
Security
Performance
Quality
AGENTS.md
Prior threads: I left 3 earlier concerns alone:
I did not run the tests or the build, because I had no shell. My review is by reading the code. Change sizeCompared with the base branch (merge base
|
|
The UI-thread work is fixed by 827e68f, with prepared-input validation, progress/Cancel and no synchronous worker-start fallback. The passing fork run names that exact head; the PR description and memory accounting now reflect the bounded result filtering and shared snapshot. The topology signature and plural-wording quality points remain left for the release quality pass. |
| .filter(|r| *r != row) | ||
| .filter_map(|r| vec_of(r).map(|v| (r, v.iter().zip(&target).map(|(a, b)| (a - b).powi(2)).sum::<f64>().sqrt()))) | ||
| .collect(); | ||
| let Some(target) = vec_of(row)? else { |
There was a problem hiding this comment.
Silent unusable result: a reference row with a missing value returns an empty ranking (confidence: high).
When the reference row has a null or non-finite value in any compared field, this returns Ok(Vec::new()) with no notice. Embeddings then answers {"similar": []} and, with the default select: true, selects only the reference row. AGENTS.md says unusable results are errors, so this should refuse.
The same applies to candidates: rows with a missing value in any field are dropped silently at line 821 (if r != row && let Some(v) = vec_of(r)?), and they also drop out of the standardization statistics at line ~771. The "features skipped" rule asks for a count. This predates the PR, but the PR rewrites this function and the rule says existing silent losses are bugs.
Minimal fix for the reference case:
| let Some(target) = vec_of(row)? else { | |
| let Some(target) = vec_of(row)? else { | |
| return Err("the reference row has no finite value in every compared field".into()); | |
| }; |
For candidates, count the skipped rows and return the count to similar.rs so gather can emit one notice.
There was a problem hiding this comment.
2f5047aff refuses a reference missing a finite compared value and counts skipped incomplete candidates, including with select: false. Null/NaN/infinite reference and candidate regressions pass. The comparison probe verifies 2,475 valid rankings retain identical row order and distance bits, and 189 unusable references are refused. Focused checks and full fork CI pass.
| if let Some((field, Some(window))) = &v.time { | ||
| let mut time = rustgis_map::time::TimeBinding::new(field); | ||
| time.window = Some(*window); | ||
| let mask = time.keeps(&input.data); |
There was a problem hiding this comment.
The time-window path allocates more than the PR body's memory account says (confidence: medium-high).
Visibility captures only the field and window, then TimeBinding::new(field) is a fresh binding with an empty cache. keeps therefore calls rows_in → dated, which builds a Vec<Option<f64>> of one 16-byte entry per row, plus the Vec<bool> mask, and runs time::detect again. The peak is about 17 bytes per resident row, not the "one byte per row" in the PR body. Per AGENTS.md "Size for real data", the PR body should state this multiple.
It also ignores the layer's already-cached time mask (l.time), so each run recomputes the moments. Cloning the layer's TimeBinding into Visibility would reuse its Arc cache. The code comment says a detached cache avoids locking the live window's cache, so that trade-off should be stated either way.
There was a problem hiding this comment.
2f5047aff removes the fresh layer-wide time binding. Date-kind detection preserves the existing 500-nonempty-value sample, with Cancel during sparse scans; only the at-most-1,001 result/reference rows are converted and tested. No timestamp/mask vectors are allocated. Parity/cancellation regressions and full fork CI pass; the PR memory account is updated.
| // independently of its selection and definition query. | ||
| // Both in longitude/latitude: a copy only of a layer in another system. | ||
| let lonlat = |d: &rustgis_data::Dataset| d.in_lonlat().map(std::borrow::Cow::into_owned); | ||
| let (by, by_unreadable) = match &rule { |
There was a problem hiding this comment.
Follow-up on the covering-layer thread (confidence: medium). The author's reply explains that the covering contract is intentional, and I agree it is not a regression. It doesn't address the "Never silent" requirement, though: coverage here counts rows the layer's definition query hides and the map doesn't draw, and no notice says so. Either add one notice per run when a covering layer has a readable definition query or an active time window (count and layer name, clean input silent), or state in the PR why that exception is exempt from the rule.
There was a problem hiding this comment.
For must-be-covered-by, every resident covering feature supplies the reference coverage. Its map query, selection, time and display filters do not narrow that declared All input. All covering geometry is consumed, so this path has no query fallback or dropped geometry to report. The guide now states that scope explicitly. Primary inputs keep their separate Query policy and counted parser-error fallback notice.
Code reviewI read the full 2,267-line diff, the staged metadata and the 35 existing review threads, and checked the source they point at. I found one new concern. I did not run cargo or the test suite, because this environment has no build access. Bugs
Security
Performance
Quality
AGENTS.md
Already raised (left alone)I left 34 of the 35 existing threads alone, because each is either answered by the author, already fixed, or deferred to the quality pass. I re-raised one (analysis-pane thread on switching section or layer), and only for its unaddressed selection side effect. Change sizeCompared: the whole PR against main (merge base b034f51 to PR head 53ea95a).
|
| format!("{}: {e}", i.layer) | ||
| } | ||
| }; | ||
| let data = i.data.in_lonlat().map_err(named)?; |
There was a problem hiding this comment.
AGENTS.md, size rule (confidence: medium-high). Dataset::in_lonlat() starts with self.clone() and then calls iter_mut(), which goes through Arc::make_mut (crates/data/src/lib.rs, DerefMut for Features). For a projected layer that copies every Feature, geometry and attributes included. So each topology check holds one extra full copy of each projected primary layer, plus one for each projected covering layer, for the length of the check. It is not counted by make_room, held or the undo budget. The copy predates this PR, but the PR's memory section says topology "holds only the current rule's matched-row index vector" and does not give the multiple. AGENTS asks for that multiple in the PR description. A layer already in lon/lat returns Borrowed, so this only applies to projected layers.
There was a problem hiding this comment.
Corrected the PR’s memory account. in_lonlat() borrows longitude/latitude inputs (0×L extra full-row copies) and makes one extra full-row copy for each projected input, including its attributes. Projected primary and covering copies coexist during the rule (1×Lp + 1×Lc); using the same projected source in both roles can therefore add 2×L. The description now states that these existing conversion copies are separate from Undo/read-retention accounting and are released between rules. Allocation and coordinate-conversion behavior are unchanged.
| (TopologyRule::MustNotSelfIntersect { .. }, _) => t::self_intersections(&data, &i.rows), | ||
| (TopologyRule::MustNotHaveDangles { .. }, _) => t::dangles(&data, &i.rows, tol), | ||
| rustgis_data::progress::check().map_err(|_| cancelled())?; | ||
| rustgis_analysis::validate_latitudes(&data, rows.iter().copied())?; |
There was a problem hiding this comment.
AGENTS.md, cancel rule (confidence: medium). The doc comment above check_topology calls "one row's ... latitude validation" an indivisible step. That is not what this call does. rustgis_analysis::validate_latitudes (crates/analysis/src/lib.rs:756) is one pass over every matched row, with no Cancel check, and the covering-layer call validate_latitudes(by, 0..by.features.len()) is the same. The checks on either side of it only bound the pass, so on a large layer Cancel waits for the whole pass. Either add a check inside that loop (progress::check every N rows) or say in its doc comment that it is one whole-layer step.
There was a problem hiding this comment.
Corrected in b12e8a55d. The doc comment now names each complete latitude-validation pass and the initial projected full-row copy as indivisible steps. It no longer describes latitude validation as one row’s work. The PR description states the same cancellation boundary; the existing checks around those passes remain unchanged. Full fork CI passed.
Code reviewBugs: No new correctness defect found. I traced the Similar and topology landing paths, the copy/replay ordering, the budget's dead-key handling, the Security: None found. The new MCP batch admissions only reach Performance: Nothing new beyond the earlier threads. Topology's per-rule query evaluation matches the old Quality (nits, grouped; these can wait for the release quality pass):
AGENTS.md:
Earlier review threads: 36 were already on this PR. I left all of them alone and re-raised none. Change sizeCompared: the whole PR against main (merge base 33d03c0 to PR head 6c46efd).
Largest changes by file:
|
|
The conversion-memory account and latitude-validation cancellation comment are corrected. b12e8a55d also fixes “every compared field” to “at least one” and clarifies that changing pane context does not cancel an admitted Similar command. Executable behavior is unchanged; formatting, guards, private preflight and full fork CI passed. Topology’s progress remains scoped to each rule. A unified progress display across rules and their library phases is left for the release quality pass. |
| fn resolve(s: &Session, p: &Value) -> Result<Self, String> { | ||
| let id = s.layer_id(p)?; | ||
| let l = s.map().layer(id).ok_or("no such layer")?; | ||
| let row = match p.get("row").and_then(Value::as_u64) { |
There was a problem hiding this comment.
Bug (medium confidence): an explicit but invalid row is silently replaced by the selected feature.
p.get("row").and_then(Value::as_u64) returns None for -1, "5" or 1.5, so the code falls back to the layer's first selected row. With the default select: true, that replaces the user's selection with neighbours of a feature they did not ask for, and nothing is said. AGENTS.md ("Never silent") and the hostile-input rule both point against this. The same pattern was already here before this PR, but the PR moves this code and rewrites the surrounding command, so it is a reasonable place to fix it.
Suggested change: only an absent or null row falls back to the selection; a supplied value must be a whole number, or it is an error.
| let row = match p.get("row").and_then(Value::as_u64) { | |
| let row = match p.get("row") { | |
| None | Some(Value::Null) => *l.selection.first().ok_or("select a feature (or give row)")?, | |
| Some(v) => v.as_u64().ok_or("row must be a whole number")? as usize, | |
| }; |
Add a regression test: row: -1 and row: "1" should return an error and leave the selection unchanged.
There was a problem hiding this comment.
Fixed in 62cc4cbe1, included at head 66f21b7b1. Only missing/null row falls back to the selected reference. A supplied row must be a non-negative integer, fit usize and be within the layer; invalid values return an error before selection changes.
The regression reproduced the old row: -1 fallback. It now checks negative/string/fractional/oversized references, unchanged selection and Undo on refusal, and retained null/omitted/valid-reference behavior. Targeted tests, strict wasm and full fork CI passed.
| if fields.is_empty() { | ||
| return Err("the layer has no numeric fields to compare".into()); | ||
| } | ||
| let count = p.get("count").and_then(Value::as_u64).unwrap_or(10).clamp(1, 1000) as usize; |
There was a problem hiding this comment.
Silent clamp (low-medium confidence): count is clamped to 1…1000 with no notice.
count: 5000 silently returns 1000 rows, count: 0 silently returns 1, and a non-numeric count silently becomes 10. The caller is not told that the answer was truncated. AGENTS.md says a command that truncates results must say what, how much and where, so this should be an error for out-of-range values or a notice when the clamp takes effect. The same clamp existed before this PR; it is kept here because the line is part of the code this PR moves.
There was a problem hiding this comment.
Fixed in 62cc4cbe1. Missing/null count keeps the default of 10; a supplied value must be an integer from 1 to 1000. Invalid values are refused before selection changes, rather than defaulted or clamped. Help and the guide now state the limit.
The regression failed on the old count: 0 clamp and now covers invalid types/range, valid bounds, unchanged selection/Undo and retained defaults. All 47 targeted tests passed; the parameter and actual-pane checks also passed after the base update. Full fork CI passed on the published head.
Code reviewI read the full diff (24 files), the 42 prior threads, and the source around the riskiest changes. I found no confirmed crash, data-loss, or wasm break in the new code. Two parameter-handling issues are posted inline. Several earlier concerns were already answered and I did not repeat them. Bugs
Security
Performance
Quality
AGENTS.md
Already raised and left aloneI left 42 earlier threads alone, because they are answered or already raised. That count includes the memory multiples, the Change sizeCompared: the whole PR against main (merge base 33d03c0 to PR head b12e8a5).
|
|
Both parameter findings are fixed in 62cc4cbe1, included at The two regressions failed before the fix. Targeted tests, independent review, Clippy, strict wasm, guards and full fork CI passed. |
Code reviewInline comments could not be posted: GitHub rejected both with "pull_request_review_thread.path could not be resolved", so the two findings below appear here only. Bugs
I checked and found no problems with the wasm gating, the Weak-key allocation accounting, the SecurityNone found. PerformanceNone new. The single-threaded distance pass and the full-candidate sort are already raised in earlier threads. QualityNothing new worth raising beyond the earlier threads, which are the release-quality-pass items. AGENTS.mdNo new violations found. The read-ahead list and the I left about 50 earlier review threads alone: they are already answered or already raised, and the code they point at has not changed in a way that reopens them. Change sizeCompared: the whole PR against main (merge base e55b20d to PR head 66f21b7).
|
|
The history finding reproduced: Undo restored The empty-hit selection paths are already covered. |
| } | ||
|
|
||
| /// Applies a selection to one layer (New clears the others too, like desktop GIS). | ||
| pub fn set(s: &mut Session, id: u32, rows: Vec<usize>, m: Mode) { |
There was a problem hiding this comment.
Question (confidence ~0.4): does a script's own selection line still overtake a newer user selection?
set records intent as max(selection_intent, selection_epoch()) and then applies unconditionally. Inside a replayed script, selection_epoch() returns the script's admission epoch E. So a script admitted at E that reaches a select.* line after the user has made a selection at F > E will overwrite that selection, and nothing refuses it. The PR body says an older script "cannot overtake a later request or user selection at completion". As written, that guarantee covers only inner Similar results (set_similar_result is gated, this path is not).
Scenario: admit a script whose last step is select.rows [5], click row 3 while it runs, then let the script finish. The final selection is row 5 and the user's later click is lost, with no notice.
This may be intended: a script's explicit selection is "last write wins". If so, please say that in the PR body, since it is the opposite of the newer-intent rule described for Similar. If not, the replay path would need the same epoch comparison as similar::run.
There was a problem hiding this comment.
That explicit selection step still applies when the live script reaches it. The ordering guard protects computed data.similar selections, including results prepared inside a script/model; it does not cancel the script’s explicit select.* commands. Those commands also establish selected inputs for later tool steps, so skipping them would change the script’s requested execution.
I clarified this boundary in the PR description, including the case where the user selects something after the script was queued. Ordinary script selection behavior is retained; no source change or new test is needed for this clarification.
Code reviewReviewed statically from the staged diff, with reads into the surrounding source. I did not build or run the tests. Of the 21 earlier review threads, I left all of them alone: 15 were answered or fixed, and 6 were deferred to the release quality pass. Bugs
Security
Performance
Quality
AGENTS.md
Coverage gaps: I read most of the diff but skimmed the middle of the new engine tests in Change sizeCompared: the whole PR against main (merge base e55b20d to PR head 2e1b38c).
The table lists the 20 largest changes from the stats file. Sizes are file sizes, not line counts. |
Code reviewNo new inline comments: I found no defect that the existing threads haven't already raised, so I posted none. I checked all 41 earlier threads and left every one alone. Some are answered and some were fixed in later commits. Reading the diff, I found one minor new nit and nothing confirmed as a bug. Bugs
Security
Performance
Quality
AGENTS.md
Change sizeCompared: the whole PR against main (merge base 76a6cd2 to PR head 6dd20d5). Trees not truncated.
|
|
Topology’s primary Query / covering All scope is preserved: the earlier |
Summary
Topology validation reports unreadable primary-query fallback, preserving Query primary inputs and All resident covering inputs. Primary selection, display filters and time windows do not narrow that query-only input. Query evaluation, coordinate conversion and issue construction now run on its existing worker; landing checks captured metadata and map identity.
Similar ranks all resident rows, refuses an unusable reference or overflowing standardization, and counts candidates missing compared values. Output selection follows the definition query, time window and active display filters, with counted fallback/exclusion notices. Exclusion counts apply to this request’s returned matches and reference, rather than every row in the layer. Time filtering converts only result/reference rows after cancellable date-kind detection.
Explicit invalid Similar parameters are refused before selection changes:
rowmust be a zero-based integer in the layer, andcountmust be an integer from 1 to 1000. Omitted/nullrowuses the selected reference; omitted/nullcountuses 10. Errors preserve selection and Undo; supplied values no longer silently fall back or clamp. Command help and the analysis guide state these bounds.Desktop Find Similar uses the existing read queue with progress/Cancel. Its final ranking reaches the requesting Workflows pane, and desktop scripts replay prepared results before their next command, including scripts that first set up topology rules. Scripts and models reserve their ordering epoch at admission; inner Similar requests retain that epoch through replay. The newer-intent guard applies to computed Similar selections. Explicit
select.*steps keep their ordinary execution semantics: they apply their requested selection when the live script reaches them, including after a user selection made while the script was queued. Those steps can supply selected inputs for following tools. Similar completions preserve later queued requests and user selections in either completion order. Successful Undo/Redo restores also take precedence: a still-current ranking returns without replacing the restored selection. Failed history actions leave selection intent unchanged. Closing and reopening the same Similar section retains pending work and its ranking; changing section or layer transfers display ownership. The admitted command still completes and may apply its guarded selection; Cancel stops the computation. External clears from pop-up browsing are protected without adding an Undo step. Other background workflows, including Trend Analysis, keep pane output in their originating section. Data Engineering, Exploratory Analysis and Similar retain their documented All-resident populations. Command ids/parameters, project schema, CRS policy and row-storage APIs are unchanged.A tool-created layer in a prepared script retains its recorded-data identity through replay, including when a later script step removes it. This reuses the output record captured when the tool installs its result; unrelated replacements still invalidate results. Current main’s source-coordinate handling and datum-grid invalidation are preserved in queued topology validation.
Desktop compatibility: Similar and topology validation in an unprepared script with a file/network setup prefix are refused on the window thread. Run setup separately, then run the prepared analysis/validation script, or use Find Similar, Error Inspector or the direct MCP command. Prepared scripts and synchronous CLI/Python remain supported. The diagnostic and analysis guide explain this restriction.
Automatic fallback after removing Similar's target layer clears the old request, ranking and error only when the chosen layer changes. Unchanged redraws preserve current output.
Successful project replacement clears cached workflow results and errors for every section, plus Similar's pending request, through both User and peer-import entry points; failed opens keep the current output. Exhausting a script's prepared prefix reaches the ordinary desktop guard or headless execution, while mismatched recorded reads still fail. Conservative selection refusals accurately name selection or data changes.
Current-main integration preserves both image-grid and Similar/topology read callbacks, scoped admission and typed script replay. Image-grid stale-input invalidation and Similar’s replay-created identity/selection/memory bookkeeping both remain active.
Testing
6dd20d51f, retaining both appended test blocks and the complete background-read diagnostics. All 66 focused engine checks and five UI lifecycle/queue checks passed, along with engine/UI Clippy, strict UI wasm and guarded hooks.Memory for resident feature/table rows: direct Similar capture adds 0×L full-row copies for source rows occupying L bytes. After copy-on-write, one captured old version can retain 1×L beyond the live version; the budget counts each unique allocation once across live data, history and readers.
Native script/model preparation shares a snapshot of all resident project rows, not only one input layer. Let P be the estimated bytes of unique row allocations across its maps, offline areas and tables. One such snapshot retains 1×P (or P/L times a nonempty target layer), with 0×P initial row copies. Multiple snapshots share unchanged allocations and add only distinct retained versions. Clearing history cannot evict rows a queued script still owns; edit admission counts those rows, and completion/cancellation/drop releases the reader registration.
The replay ledger holds only runtime identity metadata proportional to recorded tool outputs, including outputs removed later in the script. It reuses existing worker output records and adds no feature copies.
Topology holds the current rule’s matched-row index vector. With capacity C and primary-row storage L bytes, its allocation is
size_of::<usize>() × C / Lof that layer (8C/Lon 64-bit targets); its length is the number of matched primary rows.The existing
Dataset::in_lonlat()conversion borrows longitude/latitude inputs (0×L extra full-row copies). For a projected input it copies every row, including attributes and geometry: 1×L extra full-row storage while converting coordinates. A projected primary and covering input coexist during a rule (1×Lp + 1×Lc beyond their shared source rows); the same source in both roles can therefore have 2×L extra copies. These pre-existing conversion copies are separate from the Undo/read-retention budget. The row-index vector and converted datasets are released before the next rule.Metadata and ranking working memory are separate from those shared row allocations. Similar has no full timestamp/mask cache; ranking scratch and topology coordinate-conversion allocations retain their existing algorithms. Linux memory CI passes and no memory limit changes.
The stable ranking sort, one row’s query/conversion, a projected dataset’s initial full-row copy, each complete latitude-validation pass and a topology gaps union remain indivisible library steps, checked around them. Query, coordinate-conversion and geometric loops otherwise check Cancel between rows or row batches; wide numeric vectors check too.
Surfaces
Desktop UI and direct scoped MCP use the background queue and refuse inline fallback on worker-start failure. Native desktop scripts use existing read-ahead/replay; synchronous CLI/Python and browser callers retain their caller-thread contract. Shared engine policies reach phone, plugin and Assistant consumers. Selection changes only after successful current-input validation, with newer user selections preserved. No source reload, ribbon placement or saved-data change.
Merge Danger
Door: two-way
Blast Radius: analysis
Changes topology fallback reporting and Similar selection/execution/completion. Inputs with finite standardization statistics preserve ranking bits and resident populations; overflowing statistics are refused.
UI evidence
Actual headless UI using a synthetic layer; images are hosted outside this repository.
Before the request:

Running, with progress and Cancel:

Completed ranking and selected rows:

The same Similar section retains the completed ranking after closing and reopening:

Before New Project:

After New Project, the old ranking is cleared:

Layer removal clears the old ranking
Before removing the target layer:

After automatic fallback to other:

Related issue
Continues the row-policy work from #2421 and #2458, covering topology and the remaining resident-data workflows.
Summary by CodeRabbit