Skip to content

⚡ [performance improvement] Defer PathBuf allocations in Tarjan's SCC DFS#149

Open
bashandbone wants to merge 1 commit intomainfrom
bolt-tarjan-dfs-allocations-17336176359170230244
Open

⚡ [performance improvement] Defer PathBuf allocations in Tarjan's SCC DFS#149
bashandbone wants to merge 1 commit intomainfrom
bolt-tarjan-dfs-allocations-17336176359170230244

Conversation

@bashandbone
Copy link
Copy Markdown
Contributor

@bashandbone bashandbone commented Apr 14, 2026

💡 What
Replaced unnecessary owned PathBuf allocations (.to_path_buf()) within the tarjan_dfs graph traversal loop with borrowed &Path lookups inside state.indices, state.lowlinks, and state.on_stack.

🎯 Why
When dealing with HashMap/HashSet lookups in Rust, one should pass borrowed references if possible, rather than heap-allocating an owned item. In deeply recursive DAG invalidation scenarios (like Tarjan's algorithm finding SCCs), calling v.to_path_buf() strictly for .get() or .contains() calls added unnecessary O(E) heap allocations (since an edge lookup triggers it). Utilizing std::collections::HashMap capability to take a &Path drops these allocations to 0, deferring any allocation solely to when nodes are first pushed to a stack or registered O(V).

📊 Measured Improvement
Eliminates O(E) unnecessary heap allocations of PathBuf during strongly connected component detection in dependency graph invalidations.

🔬 Measurement
Verify via cargo test -p thread-flow --test invalidation_tests and benchmark improvements during graph SCC searches.


PR created automatically by Jules for task 17336176359170230244 started by @bashandbone

Summary by Sourcery

Optimize Tarjan SCC DFS invalidation traversal to eliminate redundant path allocations during hash lookups.

Enhancements:

  • Reuse a single PathBuf per node visit in tarjan_dfs and perform HashMap/HashSet lookups using borrowed &Path keys to reduce allocation overhead.
  • Expand internal performance notes in .jules/bolt.md with guidance on avoiding unnecessary owned path allocations in recursive graph algorithms.

… DFS

Co-authored-by: bashandbone <89049923+bashandbone@users.noreply.github.com>
Copilot AI review requested due to automatic review settings April 14, 2026 17:46
@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Apr 14, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Optimizes Tarjan's SCC DFS by eliminating redundant PathBuf allocations during hashmap/set lookups and documents the performance pattern in the project’s bolt notes.

Class diagram for TarjanState and InvalidationDetector tarjan_dfs changes

classDiagram
    class InvalidationDetector {
        +graph: DependencyGraph
        +tarjan_dfs(v: Path, state: TarjanState, sccs: Vec~Vec~PathBuf~~)
    }

    class TarjanState {
        +indices: HashMap~PathBuf, usize~
        +lowlinks: HashMap~PathBuf, usize~
        +on_stack: HashSet~PathBuf~
        +stack: Vec~PathBuf~
        +index_counter: usize
    }

    class DependencyGraph {
        +get_dependencies(v: Path): Vec~Path~
    }

    InvalidationDetector --> DependencyGraph : uses
    InvalidationDetector --> TarjanState : mutates

    %% Inner behavior of tarjan_dfs related to allocation
    class tarjan_dfs_inner {
        +v_buf: PathBuf
        +initialize_node(v: Path, state: TarjanState)
        +update_lowlink_from_child(v: Path, dep: Path, state: TarjanState)
    }

    InvalidationDetector ..> tarjan_dfs_inner : calls
    TarjanState o-- PathBuf
    TarjanState o-- usize
    DependencyGraph o-- Path
    TarjanState ..> HashMap
    TarjanState ..> HashSet
    TarjanState ..> Vec
Loading

Flow diagram for tarjan_dfs PathBuf allocation and HashMap lookups

flowchart TD
    A["Start tarjan_dfs with v: &Path"] --> B["Create v_buf = v.to_path_buf"]
    B --> C["Insert (v_buf.clone, index) into state.indices"]
    C --> D["Insert (v_buf.clone, index) into state.lowlinks"]
    D --> E["Increment state.index_counter"]
    E --> F["Push v_buf.clone onto state.stack"]
    F --> G["Insert v_buf into state.on_stack"]

    G --> H["Get dependencies = graph.get_dependencies(v)"]
    H --> I{For each dep in dependencies}

    I --> J{dep not in state.indices?}
    J -->|Yes| K["Recurse tarjan_dfs(dep, state, sccs)"]
    J -->|No| L{dep in state.on_stack?}

    K --> M["Read w_lowlink = state.lowlinks[dep]"]
    M --> N["Borrowed lookup: v_lowlink = state.lowlinks.get_mut(v)"]
    N --> O["Update *v_lowlink = min(*v_lowlink, w_lowlink)"]
    O --> I

    L -->|Yes| P["Read w_index = state.indices[dep]"]
    P --> Q["Borrowed lookup: v_lowlink = state.lowlinks.get_mut(v)"]
    Q --> R["Update *v_lowlink = min(*v_lowlink, w_index)"]
    R --> I
    L -->|No| I

    I -->|Done| S["v_index = state.indices[v]"]
    S --> T["v_lowlink = state.lowlinks[v]"]
    T --> U{v_lowlink == v_index?}

    U -->|No| V["Return from tarjan_dfs"]
    U -->|Yes| W["Pop stack until v reached, build SCC"]
    W --> X["Push SCC into sccs"]
    X --> V

    %% Key change: lookups now use borrowed v: &Path instead of repeatedly calling v.to_path_buf()
Loading

File-Level Changes

Change Details Files
Optimize tarjan_dfs to avoid repeated PathBuf allocations during DFS by reusing a single owned PathBuf and using &Path for hashmap/set lookups.
  • Introduce a single v_buf PathBuf allocation at the top of tarjan_dfs for the current node.
  • Use v_buf.clone() only when inserting into indices, lowlinks, stack, and on_stack collections.
  • Change lowlinks and indices lookups to use the borrowed &Path key v instead of allocating a new PathBuf for get/get_mut operations.
crates/flow/src/incremental/invalidation.rs
Document the performance lesson about avoiding redundant to_path_buf allocations in hashmap/set lookups.
  • Add a new dated note describing the cost of calling to_path_buf in recursive Tarjan SCC DFS.
  • Record guidance to use borrowed lookup keys and allocate owned values only once per node when inserting into hash collections.
.jules/bolt.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey - I've left some high level feedback:

  • You can further reduce allocations by avoiding repeated v_buf.clone(); for example, insert v_buf.clone() into indices, move v_buf into lowlinks (or vice versa), and then rely solely on &Path for all subsequent lookups instead of cloning again for stack/on_stack if those collections can also take borrowed keys.
  • Consider explicitly documenting or enforcing (via type alias or a comment near the TarjanState definition) that the indices/lowlinks maps are keyed by PathBuf but intentionally use &Path for lookups, to make the use of Borrow-based lookups clear to future readers.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- You can further reduce allocations by avoiding repeated `v_buf.clone()`; for example, insert `v_buf.clone()` into `indices`, move `v_buf` into `lowlinks` (or vice versa), and then rely solely on `&Path` for all subsequent lookups instead of cloning again for `stack`/`on_stack` if those collections can also take borrowed keys.
- Consider explicitly documenting or enforcing (via type alias or a comment near the `TarjanState` definition) that the `indices`/`lowlinks` maps are keyed by `PathBuf` but intentionally use `&Path` for lookups, to make the use of `Borrow`-based lookups clear to future readers.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR optimizes Tarjan’s strongly-connected-components DFS used by InvalidationDetector by avoiding repeated PathBuf heap allocations during hash lookups, keeping allocations to the per-node initialization path.

Changes:

  • Replaced repeated v.to_path_buf() calls inside SCC traversal lookups with borrowed &Path lookups into RapidMap<PathBuf, _> / RapidSet<PathBuf>.
  • Consolidated per-node PathBuf creation into a single v_buf used for initial inserts/pushes.
  • Added a .jules/bolt.md entry documenting the performance lesson/pattern.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
crates/flow/src/incremental/invalidation.rs Removes per-edge PathBuf allocations in Tarjan DFS by using borrowed &Path for map/set lookups.
.jules/bolt.md Documents the allocation-avoidance pattern for hash lookups in traversal code.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

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.

2 participants