Skip to content

perf(analysis): reuse the routing graph between routes on the same network (#1998) - #2247

Merged
Mavrick-F merged 1 commit into
opengeos:mainfrom
Mavrick-F:fix/reuse-routing-graph
Nov 16, 2026
Merged

Mavrick-F merged 1 commit into
opengeos:mainfrom
Mavrick-F:fix/reuse-routing-graph

Conversation

@Mavrick-F

@Mavrick-F Mavrick-F commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Summary

Routing rebuilt the line network for every route. In the trial in #1998, 190 origin–destination pairs run as 190 analysis.route calls took 35 times the reference: each call recomputed every edge's ellipsoidal length before searching.

The last graph built is now kept and reused by the next route on the same network:

  • It's reused only while the layer's features, its visible rows and their order, and the cost field are the same. An edit replaces the layer's feature data, which ends the reuse; the cache holds the features weakly, so it never keeps a removed layer's data alive.
  • It's kept only up to 256 MiB; a larger graph is rebuilt each time, as before. A graph under that size stays in memory after routing, until a route on another network replaces it.
  • Each route still snaps its own endpoints and works on its own copy of the adjacency, so results are the same, bit for bit. Where a run can be cancelled (models, scripts), building, snapping and searching check Cancel.

On the trial's 190 routes: 201 s → 33 s wall time, 139 s → 27 s CPU, with all 190 answers and exported GeoJSON files identical byte for byte.

Reaches: every surface that runs analysis.route (the app, the command line, Python, scripts and models, the Assistant and MCP); nothing in the interface or saved files changes.

Testing

  • route_graph_reuse_preserves_results_and_follows_network_edits: a reused graph gives bit-identical routes, endpoints don't leak between routes, an edit, a changed row set or a different cost field rebuilds, the cache doesn't keep feature data alive, and Cancel reaches both building and cached routes.
  • cargo test -p rustgis-analysis (613 passed); the 190-route replay above.
  • cargo xtask ci on the fork's CI.

UI evidence

No UI change.

Related issue

Part of #1998 (the routing graph line; service area and OD matrix stay on the roadmap).

@coderabbitai

coderabbitai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Routing now reuses eligible network graphs across route requests. Each request validates and snaps its endpoints, then searches a query-specific graph copy. The change also adds cancellation checks and reports skipped invalid segments in applicable errors.

Changes: Network routing

Layer / File(s) Summary
Graph construction and cache
crates/analysis/src/network.rs, docs/user-guide/analysis.md
The code builds network topology and caches a graph when its estimated size is at most 256 MiB. The cache key includes feature allocation identity, ordered rows, and cost field. The documentation describes cache reuse and invalidation conditions.
Per-request validation and route search
crates/analysis/src/network.rs
Each request validates its snap distance and route-end coordinates, then searches cloned graph nodes and adjacency. Cancellation checks cover nearest-segment scans, Dijkstra traversal, and path reconstruction. Tests cover cache reuse, query isolation, invalidation, and cancellation.

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

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant shortest_route_with
  participant NetworkCache
  participant NetworkBuild
  participant route_on
  Caller->>shortest_route_with: Provide route ends and snap distance
  shortest_route_with->>NetworkCache: Get graph for features, rows, and cost field
  NetworkCache->>NetworkBuild: Build graph on cache miss
  NetworkCache-->>shortest_route_with: Return graph
  shortest_route_with->>route_on: Search cloned graph for route
Loading

Possibly related issues

  • opengeos/RustGIS issue 1998: This change reuses the routing graph across routes, addressing the issue’s reported repeated graph-rebuild cost.

Suggested reviewers: giswqs, flight1973

Merge Risk: Minimal · up to 7b39a

Repeated routes on an unchanged network now reuse the routing graph instead of rebuilding it, and edits, row changes or a different cost field trigger a rebuild. No concrete defect was found, and the change is easy to revert because it adds no interface or saved-file changes.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: the routing graph is now reused between routes on the same network, which matches the raw summary, the PR description, and the objectives. The conventional-commit pref…
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.
Description check Passed The description follows the template's Summary, Testing, UI evidence, and Related issue sections. The Summary explains the problem (per-call recomputation of edge lengths, 35x slower than reference), …
Full details: Title check

Explanation

The title names the main change: the routing graph is now reused between routes on the same network, which matches the raw summary, the PR description, and the objectives. The conventional-commit prefix 'perf(analysis)' fits the performance goal. The title is 82 characters, slightly above a typical short-title length, but it stays clear and specific. The '(#1998)' reference points to the trial issue and is not noise.

Full details: Description check

Explanation

The description follows the template's Summary, Testing, UI evidence, and Related issue sections. The Summary explains the problem (per-call recomputation of edge lengths, 35x slower than reference), the cache rules (reuse only while features, visible rows and their order, and cost field are unchanged; 256 MiB limit; weak feature references), and per-route endpoint snapping with cancellation support. Testing lists a named test, cargo test results, a 190-route replay with timings, and CI. The UI evidence section states no UI change, as the template allows. The Related issue section links Part of #1998. The description is specific and covers the required information.

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 maps the winding way,
And keeps the graph for another day.
New endpoints hop onto the track,
While checks keep cancellation at their back.
If rows or costs shift out of view,
The rabbit builds a graph anew.

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: fae631f9-9ca6-4a66-8046-95f02385cc80
Commits

Reviewing files that changed from the base of the PR and between 7203e31 and 7b39a99.

Files selected for processing: 2

  • crates/analysis/src/network.rs
  • docs/user-guide/analysis.md

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

fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64) -> Result<Route, String> {
crate::control::check()?;
let mut nodes = graph.nodes.clone();
let mut adj = graph.adj.clone();

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.

Performance / memory (medium confidence): every route_on call clones the whole nodes and adj vectors. When the cached graph is near the 256 MiB cap, each route transiently allocates about the same again, and concurrent routes on one network each make their own copy. That copy isn't counted against the cache budget or memory::thread_scratch, and the doc comment on shortest_route only describes the cache. Endpoint attachments could go in a small overlay (extra node ids and edges appended after the shared graph) so the shared graph is never copied. If the copy stays, document the transient peak next to the 256 MiB claim.

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.

Before this PR each route built the whole graph and computed every edge's length, so the per-route copy costs less than before, not more. An overlay for the endpoints instead of a copy is left for the release quality pass.

}
}

const GRAPH_CACHE_BYTES: usize = 256 << 20;

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.

Memory retention (low-medium confidence): the cache holds the graph in a process-wide static for as long as the process runs, even after the project that owns the layer is closed. The Weak keeps feature data from being retained, but the graph can still be up to 256 MiB. The PR body discloses this, but nothing releases it on project close, and a Python or embedded process with several projects keeps one graph alive. Consider clearing the cache when a session drops, or making the cap smaller.

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.

Yes, as the PR body says: up to 256 MiB stays until a route on another network replaces it. Dropping it when the project closes is left for the release quality pass.

let bytes = graph.bytes().saturating_add(rows.len().saturating_mul(size_of::<usize>()));
crate::control::check()?;
let mut cached = cache.lock().unwrap_or_else(|e| e.into_inner());
*cached = (bytes <= GRAPH_CACHE_BYTES).then(|| CachedNetwork { features, rows: rows.to_vec(), cost_field, graph: graph.clone() });

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.

Test gap (AGENTS "test both ways"): the over-cap branch (bytes <= GRAPH_CACHE_BYTES).then(...) has no test. A graph above the cap should be rebuilt on each call and must not be published. Lowering the cap for a test would cover it, for example by making GRAPH_CACHE_BYTES a parameter of network_for. Also, the cold-build path and the cache-hit path both return identical results, but nothing checks that a rebuild after an over-cap call still returns the same route.

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.

An extra test for working code; left for the release quality pass.

/// Heap storage retained by the cache, including spare capacity in every adjacency list.
fn bytes(&self) -> usize {
size_of::<Network>()
.saturating_add(2 * size_of::<usize>())

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.

Nit (quality pass): 2 * size_of::<usize>() is an unexplained constant. It appears to account for the Arc strong and weak counters, so a comment saying so would help. The doc comment says "heap storage", but size_of::<Network>() is the inline struct and not heap. Left for the release quality pass.

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.

Left for the release quality pass.

@github-actions

Copy link
Copy Markdown
Contributor

Code review

Confidence is in brackets. I posted four inline comments on crates/analysis/src/network.rs. The Cancel gap below is not on a diff line, so it appears here only.

Bugs

  • Desktop Cancel may not reach analysis.route [medium]. The PR says Cancel is checked while building, snapping and searching. But analysis.route is registered as a plain synchronous command (crates/engine/src/cmd/workflows.rs:72, route at line 1657). It isn't in cancel_tools or long_commands_stop_when_cancelled_while_they_run, and I found no background path for it in this diff. control::check() is a no-op when no run control is installed, so on a thread without one Cancel does nothing. I did not confirm how the UI dispatches this command, so please verify. If it runs on the UI thread, it breaks the "never hold the window" rule, and the new checks give no protection in the app.

Security

  • None found. The change has no unsafe, no new input paths, and no panicking calls in non-test code. Mutex poisoning is handled with into_inner.

Performance

  • Full graph copy per route [medium] (network.rs:213). Each route_on clones nodes and adj. Near the 256 MiB cap, each route transiently allocates about the same again, and concurrent routes each copy it. The copy isn't counted against the cache budget or memory::thread_scratch. An overlay for endpoint attachments would avoid it.
  • Concurrent cold builds [low]. Two threads that miss at the same time both build the full graph and then publish, last writer wins. Peak memory can reach twice the cap.

Quality

  • Process-wide retention [low-medium] (network.rs:126). The static cache keeps up to 256 MiB for the life of the process, even after a project closes. The Weak stops feature data from being kept, but not the graph. The PR body discloses this.
  • Over-cap branch untested [medium, AGENTS "test both ways"] (network.rs:158). Nothing covers a graph above the cap being rebuilt each time and not published.
  • Unexplained constant (network.rs:118). The 2 * size_of::<usize>() term and the "heap storage" wording need a comment. Left for the release quality pass.

AGENTS.md

  • The new route_on doc comment does disclose the unchecked clone step, as the rule requires.
  • The Cancel claim above would need analysis.route on the background path, or a test in the cancel lists, to satisfy the rule.
  • The docs change and the "Reach every surface" section of the PR body are consistent with the code.

Checked, not raised: the cache-identity logic. Features::allocation_key returns a Weak, and Arc::make_mut runs on every mutation while the cache holds a Weak. So an edit always changes the identity, and the allocation can't be reused under a live Weak. Cache-hit paths still emit the skipped_segments notice.

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

Change size

Compared: the whole PR against main (merge base ff3ae0e to PR head 7b39a99).

Measure Value
Files changed 2 (added 0, modified 2, removed 0, renamed 0)
Size before 213.9 KB
Size after 223.6 KB
Total size change +9.8 KB
Path Before After Change
crates/analysis/src/network.rs 59.1 KB 68.7 KB +9.5 KB
docs/user-guide/analysis.md 154.7 KB 155.0 KB +241 B

@Mavrick-F

Copy link
Copy Markdown
Member Author

On the Cancel point: whether analysis.route runs on the app's frame is how it was before this PR, which only makes each route faster; the checks it adds apply where a run control is installed (models, scripts, the background paths). I've reworded the PR body so it doesn't claim more. Moving analysis.route onto a background path is a separate change, left for the release quality pass along with the concurrent-build note.

@github-actions

Copy link
Copy Markdown
Contributor

📖 Docs preview

Item Value
Preview https://preview.rustgis.app/pr-2247/
Web app https://preview.rustgis.app/pr-2247/app/
Commit 7b39a99

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 preview label (once per commit).

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