Skip to content

fix(analysis): Kriging merges coincident points in linear work and looks at Cancel as it prepares - #2500

Merged
pick2510 merged 2 commits into
opengeos:mainfrom
pick2510:fix/kriging-dedupe-cancel
Nov 20, 2026
Merged

pick2510 merged 2 commits into
opengeos:mainfrom
pick2510:fix/kriging-dedupe-cancel

Conversation

@pick2510

@pick2510 pick2510 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Ordinary Kriging merges sample points at the same place (within 1e-9 in x and y) before it works out its grid. It sorted the points by x and then y. Each new point then scanned back through the points kept until it found one more than 1e-9 to its left.

The problem: points sharing an x made every new point rescan all earlier points with that x. That is O(n²) on one line, and O(n·√n) on a square grid's columns. Survey lines and gridded samples are exactly that shape. Nothing before the grid looked at Cancel (not reading the rows, not the merge), so Cancel waited for all of it.

The fix (crates/analysis/src/tools.rs):

  • Linear merge: merge_coincident first scans back up to 8 kept points, as the merge always did. That settles nearly every point (a near point found, or one more than 1e-9 to the left), so a typical layer costs what it did. Only a point in a longer run within 1e-9 to its left (a shared x) looks in cells of 4e-9 (four times the tolerance): its own cell and 5 neighbours (a kept point is never to its right).
    • Only such runs are filed in the cells, lazily, and only from the first kept point within 1e-9 to the left, since none before it can be near this point or a later one. A cell holds its latest point, and each point the one filed before it, with no list per cell.
    • It keeps the old rule exactly: a point joins the latest point kept before it that is less than 1e-9 to its left and less than 1e-9 above or below.
    • Two coordinates within 1e-9 that aren't equal are both below 2^23. There a cell number is off by a fraction of a cell at most, so such a pair is never more than one cell apart.
    • From 2^24 on, where only equal coordinates are that close, a coordinate is filed under its own bits (coincident_cell). Huge coordinates don't all share the last cell, which would make the merge quadratic again.
  • Cancel: reading the rows, projecting the points into a projected system (points_in, which IDW and the Geostatistical Wizard share) and merging look at Cancel every 4,096 points. points_in still projects in the points' own storage. The sort is one short step without a look, and the comment says so.

Measured in release, merging only (median of a few runs):

Points Shape Before After
10,000 all on one x (the old worst case) 27–31 ms 1.3 ms
40,000 all on one x 450–510 ms 5.3 ms
100,000 random, no shared x (the typical case) 6.1–6.4 ms 7.6 ms
1,000,000 random, no shared x 66–79 ms 85 ms

Memory (Size for real data): what the merge holds besides the points read (24 bytes each), per point:

  • Before: 32 bytes (each kept point and its count).
  • After: 48 bytes (the same, plus its link). A point in a run within 1e-9 to its left adds about 40 bytes for its cell entry; a typical layer files none.
  • As a multiple of the layer: a point layer's row with one value is about 100 bytes (a 64-byte feature, plus its values' storage). The merge's working set goes from about 0.55× to 0.7× of the layer (up to about 1.1× when every point is in such a run). It is freed once the grid is made, and the grid's own work is far larger.

Reach every surface

  • Desktop, browser, command line, Python, phone: Ordinary Kriging runs the same analysis code everywhere. Its output is unchanged.
  • Geostatistical Wizard, the Assistant, MCP, plugins: they run the same tool. No parameter or description changes.
  • The way back: no change. The tool's output layers are added and undone as before.

Testing

  • cargo fmt, clippy -D warnings on rustgis-analysis, the rustgis-analysis tests, the engine's cancellation tests, cargo xtask test-hygiene, and RUSTFLAGS='-D warnings' cargo build --locked --target wasm32-unknown-unknown -p rustgis-web.
  • New tests:
    • kriging_merges_coincident_points_as_before: the old scan is kept in the test as the reference. The new merge must give the same points and values, bit for bit, on:
      • exact repeats;
      • pairs just inside and just outside 1e-9;
      • chains of points each within 1e-9 of the last;
      • 20 sets of columns sharing an x with near repeats;
      • either side of 2^23 and 2^24;
      • both zeros and a tiny negative beside them;
      • 2,000 coordinates up to ±1e300.
    • kriging_files_huge_coordinates_in_cells_of_their_own: 10,000 different coordinates past 1e11 get 10,000 cells, apart from every cell near 2^24 and zero, and 100,000 of them merge.
    • kriging_looks_at_cancel_while_it_projects_its_points: the same in Web Mercator. Ten looks each reading, projecting and merging, and it stops at its 15th look.
    • kriging_preparation_looks_at_cancel_as_it_goes: 40,000 points on one x.
      • The preparation looks at Cancel 20 times (ten while reading, ten while merging) before the grid's few.
      • Cancelled at the merge's fifth look, after 16,384 points, it stops there.
      • On the old code the run never looks before the grid.

UI evidence

No change to the interface.

Related issue

None; found in a review of long-running work and Cancel.

Summary by CodeRabbit

  • Bug Fixes
    • Kriging now responds to cancellation while collecting inputs, projecting coordinates, and processing coincident samples, so cancelled operations can stop sooner.
    • Improved handling of coincident samples while preserving the established matching and averaging behavior, including for large coordinate values.

…oks at Cancel as it prepares

Points sharing an x made each new point scan every earlier one; they are
now found through cells around each point, with the same result. Huge
coordinates each get a cell of their own. Reading and merging look at
Cancel every 4,096 points.
@coderabbitai

coderabbitai Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Ordinary Kriging checks for cancellation during selected-row collection, projected-CRS point preparation, and coincident-sample merging. It replaces the full backward scan with a neighboring-cell lookup while preserving the former matching rules and averaging behavior. Tests compare merge results with the previous implementation.

Changes: Kriging Sample Preparation

Layer / File(s) Summary
Cancellation during input preparation
crates/analysis/src/tools.rs
Selected-row collection and projected-CRS point preparation check for cancellation every 4096 items, including the first.
Coincident-sample merge
crates/analysis/src/tools.rs
The merge checks recent retained points and neighboring coordinate cells. It preserves the former matching rules and averaging behavior. Tests compare results with the former scan and cover large coordinates, distinct samples, and cancellation.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Possibly related issues

Possibly related PRs

Suggested reviewers: mavrick-f, giswqs

Merge Risk: Minimal · up to 8c5e1

Ordinary Kriging now merges coincident samples in near-linear time and can be cancelled while it prepares its input. Merge results are intended to match the previous behavior exactly, and equivalence tests are included. I found no concrete merge-blocking risk.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: Kriging coincident-point merge is changed to linear work, and cancellation checks are added during preparation. It is specific and follows the conventional type(scope)…
Description check Passed The description follows the template. It has Summary, Testing, UI evidence, and Related issue sections. The UI evidence section correctly states 'No change to the interface.' The Summary explains the …
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: Kriging coincident-point merge is changed to linear work, and cancellation checks are added during preparation. It is specific and follows the conventional type(scope) format. The title is 97 characters, which is long, but it stays on topic.

Full details: Description check

Explanation

The description follows the template. It has Summary, Testing, UI evidence, and Related issue sections. The UI evidence section correctly states 'No change to the interface.' The Summary explains the problem, the fix, and the measured results. The Testing section lists commands and new tests. The Related issue section says 'None; found in a review of long-running work and Cancel.' The template comment asks for a related issue reference such as 'Closes #123' or 'Part of #456', but the PR objectives reference PR #2500 and the author states no issue exists, so this is acceptable. The description is thorough and mostly complete.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit checks each row in flight,
And watches projected points just right.
Nearby samples join their kin,
With former rules preserved within.
Tests trace the old scan’s way,
While cancel checks guard the day.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 8268f518-97ae-4bb0-919d-d494cb7522bb
Commits

Reviewing files that changed from the base of the PR and between e048128 and 8c5e1ac.

Files selected for processing: 1

  • crates/analysis/src/tools.rs

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.

Comment thread crates/analysis/src/tools.rs Outdated
let cell = coincident_cell;
points.sort_by(|a, b| a.0.x.total_cmp(&b.0.x).then_with(|| a.0.y.total_cmp(&b.0.y)));
let mut kept: Vec<(Coord, f64, usize)> = Vec::with_capacity(points.len());
let mut cells: HashMap<(i64, i64), Vec<usize>> = HashMap::new();

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.

Size for real data / performance, confidence ~70% on the magnitude. The cell index allocates a Vec<usize> per occupied cell and a hash entry for it. Distinct points each get their own cell, so the merge's working set moves from about 56 B per point (raw 24 + accum 32) to roughly 170 B or more per point, around 3× the old peak. Per point the merge also does nine HashMap::get calls with SipHash and one heap allocation. Without shared x values the old sorted scan did about one comparison per point, so the common case may slow down. The PR body gives no multiple of the layer and no timing for that case, and AGENTS.md asks for both when a change stores layer data.

Suggestions: measure with cargo xtask memory and state the multiple in the PR. Consider a flat index, such as a HashMap<(i64, i64), u32> head plus a Vec<u32> of next links, which avoids one allocation per cell. Time the typical case as well as the worst case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8c5e1ac, and measured.

  • The common case: each point first scans back up to 8 kept points, as the old merge did, which settles nearly every point. A typical layer never files a point in the cells.
  • Cells: only a longer run within 1e-9 to the left (a shared x) is filed, lazily, from the first kept point inside that window. A cell holds a head index, and each point a link to the one before it, with no Vec per cell. The lookup reads 6 cells, not 9.
  • Timings (release): random points with no shared x take 7.6 ms per 100,000 against 6.1–6.4 ms before, and 85 ms per million against 66–79 ms. 40,000 points on one x take 5.3 ms against about 450–510 ms.
  • Memory: the merge holds 48 bytes per point besides the points read, against 32 before, plus about 40 per point only for points in such runs. That's about 0.7× of a point layer's rows, against 0.55× (up to about 1.1× when every point is in a run), freed once the grid is made.
    The PR description now gives the timings and the multiple.

accum.push((c, v, 1));
}
let pts: Vec<(Coord, f64)> = accum.into_iter().map(|(c, sum, count)| (c, sum / count as f64)).collect();
let (raw_pts, beyond_note) = points_in(crs, raw_pts)?;

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.

Bug (Cancel gap), confidence ~85%. points_in (unchanged, line 4966) reprojects every point in one loop with no control::check(). It runs between the reading loop and merge_coincident, and for any non-LonLat CRS it is an unchecked pass over all points. That is the stretch this PR says it makes responsive. The new test kriging_preparation_looks_at_cancel_as_it_goes sets no CRS, so it most likely takes points_in's LonLat early return and never reaches that loop.

Suggested fix: in points_in, count the points with enumerate() and call crate::control::check()? when i % LOOK_EVERY == 0. Then add a projected-CRS variant of the test that counts looks.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8c5e1ac. points_in now looks at Cancel every 4,096 points while it projects, and it still projects in the points' own storage (a filtered collect through Result), so it holds no second copy. This also covers IDW and the Geostatistical Wizard, which share it. New test kriging_looks_at_cancel_while_it_projects_its_points: 40,000 points in Web Mercator look at Cancel ten times each while reading, projecting and merging, then a few times for the grid. Without the projection's ten, the count is about 20.

@github-actions

Copy link
Copy Markdown
Contributor

Code review

Bugs

  • Unchecked reprojection pass in points_in. The new merge and reading loops look at Cancel, but points_in (run between them, unchanged) reprojects every point with no check for any non-LonLat CRS. The new Cancel test uses no CRS, so it misses this path. Posted inline at crates/analysis/src/tools.rs:4762, with the fix described. Confidence ~85%.
  • I checked the merge's correctness and found no bug. The cell neighbourhood is complete (points within 1e-9 are at most one cell apart), the 2^23 and 2^24 boundaries are handled, and it keeps the latest-kept match, as the old scan did. The reference-scan test also covers this.

Security

  • None found. The change adds no parsing or external input handling.

Performance

  • The cell index does nine HashMap::get calls with SipHash per point and allocates a Vec per occupied cell. Without shared x values the old sorted scan did about one comparison per point, so the common case may slow down. The PR only times the worst case. Posted inline at crates/analysis/src/tools.rs:4856. Confidence ~40% that it is a noticeable slowdown; the kriging solve probably dominates.

Quality

  • The new reading and merge loops don't call crate::control::begin(total), which the other long loops in this file do. Cancel works, but the progress count stays empty during those phases. AGENTS.md asks for a count where progress can be measured. Confidence ~50%.
  • The doc comment on coincident_cell is garbled ("which 4e-9 of the axis, numbered from zero"). Left for the release quality pass.

AGENTS.md

  • Size for real data: the PR body gives no memory multiple for the new cell index, which the rule requires for changes that store layer data. My estimate is about 3× the old merge's peak working set per point, unmeasured. Posted with the Performance comment at line 4856. Confidence ~70% on the magnitude; the missing multiple is certain.
  • Never silent (pre-existing, not raised inline): coincident points are averaged without a count in any note. The old code did the same, so I left it out of the inline comments.
  • The other rules I checked look satisfied: no unwrap/panic in non-test code, Dataset::push matches its use elsewhere, and there are no timer waits.

Prior reviews: none on this PR, so no concerns were skipped as already raised.

Change size

Compared with the base branch: the whole PR, merge base 3687eef to head e048128.

Metric Value
Files changed 1 (added 0, modified 1, removed 0, renamed 0)
Size before 870.2 KB
Size after 879.2 KB
Total size change +9.1 KB
Path Before After Change
crates/analysis/src/tools.rs 870.2 KB 879.2 KB +9.1 KB

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

📖 Docs preview

Item Value
Preview https://preview.rustgis.app/pr-2500/
Web app https://preview.rustgis.app/pr-2500/app/
Commit 8c5e1ac

GitHub Pages takes a minute or two to publish a new commit.

…ls, and projecting points looks at Cancel

Most points settle in a short scan back, as before, so a typical layer
never files points in cells; only runs within 1e-9 to the left are
filed, as a head per cell and links, with no list per cell. points_in
looks at Cancel every 4,096 points, keeping the points' own storage.
let fi = find_field_case_insensitive(ds, field)?;
let mut raw_pts: Vec<(Coord, f64)> = Vec::new();
for r in rows(inp, p, "input", ds) {
for (n, r) in rows(inp, p, "input", ds).into_iter().enumerate() {

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.

AGENTS.md (progress not counted), confidence ~65%. The new Cancel checks here, in merge_coincident's loop, and in points_in look at Cancel but count no progress. AGENTS.md's "Never hold the window" asks long loops to count their progress; a busy indicator without a count is allowed only where progress can't be measured. Here it can: rows(...) gives the total and the merge gets points.len().

Suggested shape: before this loop, let input_rows = rows(inp, p, "input", ds); crate::control::begin(input_rows.len());, then crate::control::reached(n); next to each crate::control::check()?; (reached takes the index at the top of each loop, as in control.rs). Do the same around the merge loop with begin(points.len()). Mind that points_in runs between these two loops, so either begin again there or count only the reading and merge phases.

@github-actions

Copy link
Copy Markdown
Contributor

Code review

Summary. The merge is sound. I traced the cell lookup against the old scan, and the tests check it bit for bit against the old code. I found no correctness, crash, or security bugs. One repository rule is not met, and there are a few minor nits.

Bugs: None found. I checked the window and filing logic, the dx ∈ {-1, 0} bound, the 2^23/2^24 cell boundary, and the coincident_cell cast. Non-finite coordinates are filtered before the merge, so NaN never reaches it. Both earlier threads (the points_in Cancel gap, and the memory concern) are fixed in 8c5e1ac and I did not re-raise them.

Security: None.

Performance: Nothing blocking. The before vector is grown without with_capacity, so it reallocates by doubling. This is a transient cost of about 16 B per point. Pre-sizing it would make the 48 B/point figure in the PR hold at peak as well.

Quality (grouped nits, for the release quality pass):

  • for dx in (-1..=0).filter(|_| !settled) is harder to read than if !settled { for dx in -1..=0 { … } }.
  • The test assertion assert_eq!(coincident_cell(f), coincident_cell(f)); is a tautology.
  • The merge_coincident doc comment has one very long line and is dense enough to be hard to follow.

AGENTS.md:

  • Progress not counted, confidence ~65%. The new Cancel-checking loops in kriging's reading phase and merge, and in points_in, do not call control::begin or control::reached, though the total is known. This is the inline comment posted at crates/analysis/src/tools.rs:4731.

Already raised, left alone: 2 earlier threads. The points_in Cancel gap (fixed in 8c5e1ac) and the cell-index memory concern (answered by the author, with the 48 B/point figure).

Change size

Compared with the base branch: the whole PR against main (merge base 3687eef to PR head 8c5e1ac).

Measure Value
Files changed 1 (modified 1, added 0, removed 0, renamed 0)
Size before 870.1 KB
Size after 882.2 KB
Total size change +13.0 KB
Path Before After Change
crates/analysis/src/tools.rs 870.1 KB 882.2 KB +13.0 KB

@pick2510

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor
Action not completed

Already reviewed the last commit. Use @coderabbitai full review to rerun a review of the entire changeset.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@pick2510
pick2510 added this pull request to the merge queue Nov 20, 2026
Merged via the queue into opengeos:main with commit 20945cd Nov 20, 2026
27 checks passed
@pick2510
pick2510 deleted the fix/kriging-dedupe-cancel branch November 20, 2026 16:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant