Skip to content

⚡ Bolt: [performance improvement] Defer PathBuf allocations during DAG traversal#178

Open
bashandbone wants to merge 1 commit intomainfrom
bolt-defer-pathbuf-allocs-15373065001613403940
Open

⚡ Bolt: [performance improvement] Defer PathBuf allocations during DAG traversal#178
bashandbone wants to merge 1 commit intomainfrom
bolt-defer-pathbuf-allocs-15373065001613403940

Conversation

@bashandbone
Copy link
Copy Markdown
Contributor

@bashandbone bashandbone commented Apr 26, 2026

💡 What: Refactored tarjan_dfs in crates/flow/src/incremental/invalidation.rs to compute v.to_path_buf() only once when initializing the node, and subsequently used the borrowed v (&Path) reference for all inner-loop lookups in HashMaps (state.lowlinks.get_mut(v) and state.indices.get(v)).

🎯 Why: In the hot loop traversing all edges of the dependency graph (O(E)), v.to_path_buf() was previously called repeatedly. This meant that for every edge, a new PathBuf was being heap-allocated just to do a map lookup, causing high memory churn and severely degrading traversal performance on large graphs.

📊 Impact: This drastically reduces string allocation churn during the dependency graph traversal, turning O(E) heap allocations into O(V) or effectively zero allocations inside the traversal loop. This directly speeds up the incremental invalidation cycle.

🔬 Measurement: Run the performance tests using cargo test -p thread-flow --test invalidation_tests and observe improved or consistently fast completion times for tests like test_large_graph_performance and test_wide_fanout_performance.

(Also included a minor cleanup to remove unnecessary explicit lifetimes in crates/rule-engine/src/check_var.rs that were throwing Clippy warnings).


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

Summary by Sourcery

Optimize Tarjan DFS invalidation traversal to reduce path allocations and perform minor cleanup in rule-engine variable checking utilities.

Enhancements:

  • Defer PathBuf allocations in the Tarjan DFS traversal by reusing a single owned path per node and relying on borrowed paths for hashmap lookups.
  • Simplify rule-engine helper function signatures by removing unnecessary explicit lifetimes on constraint and transform references.

…G traversal

- Compute PathBuf once during Tarjan DFS traversal instead of per map lookup
- Use borrowed &Path reference for Hash Map lookups inside tight loops
- Avoids O(E) redundant heap allocations
- Fixes minor clippy lifetime warnings in check_var.rs

Co-authored-by: bashandbone <89049923+bashandbone@users.noreply.github.com>
@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.

Copilot AI review requested due to automatic review settings April 26, 2026 18:00
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Apr 26, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Refactors the Tarjan DFS invalidation traversal to avoid repeated PathBuf allocations by computing an owned path once per node and using borrowed Path references for hot-loop lookups, along with a small Clippy-driven lifetime cleanup in the rule engine utilities.

Class diagram for Tarjan_dfs invalidation optimization

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

    class TarjanState {
        +indices: HashMap_PathBuf_usize_
        +lowlinks: HashMap_PathBuf_usize_
        +stack: Vec_PathBuf_
        +on_stack: HashSet_PathBuf_
        +index_counter: usize
    }

    class DependencyGraph {
        +get_dependencies(path: Path): Vec_Path_
    }

    InvalidationDetector --> DependencyGraph : uses
    InvalidationDetector --> TarjanState : mutates
    TarjanState o-- PathBuf : stores
    TarjanState o-- usize : stores

    %% Focus on optimized ownership and borrowing inside tarjan_dfs
    class TarjanDfsFlow {
        +v: Path
        +v_buf: PathBuf
        +initialize_node()
        +update_lowlinks_with_borrowed_v()
        +compute_root_and_emit_scc()
    }

    TarjanDfsFlow --> TarjanState : writes_indices_lowlinks_stack_on_stack
    TarjanDfsFlow --> DependencyGraph : reads_dependencies
    TarjanDfsFlow --> Path : borrows_v
    TarjanDfsFlow --> PathBuf : owns_v_buf
Loading

Flow diagram for optimized Tarjan_dfs PathBuf allocation

flowchart TD
    A[start tarjan_dfs with v Path] --> B[compute v_buf PathBuf once]
    B --> C[insert v_buf clone into state.indices]
    C --> D[insert v_buf clone into state.lowlinks]
    D --> E[push v_buf clone onto state.stack]
    E --> F[insert v_buf into state.on_stack]

    F --> G[for each dependency dep from graph.get_dependencies v]
    G --> H{dep in state.indices?}
    H -->|no| I[recurse tarjan_dfs dep]
    I --> J[update v_lowlink using state.lowlinks.get_mut v]
    H -->|yes and dep on_stack| K[update v_lowlink using state.lowlinks.get_mut v]

    J --> L[continue loop]
    K --> L
    L --> G

    G -->|done| M[read v_index from state.indices.get v]
    M --> N[read v_lowlink from state.lowlinks.get v]
    N --> O{v_lowlink == v_index?}
    O -->|yes| P[pop from state.stack until v reached]
    P --> Q[emit SCC into sccs]
    O -->|no| R[end tarjan_dfs frame]
Loading

File-Level Changes

Change Details Files
Optimize Tarjan DFS invalidation traversal to eliminate repeated PathBuf allocations in the hot edge-traversal loop.
  • Compute a single owned PathBuf (v_buf) at node initialization and reuse it for all insertions into indices, lowlinks, stack, and on_stack.
  • Change lowlinks and indices lookups during DFS to use the borrowed &Path key v instead of allocating new PathBufs for each lookup.
  • Add brief inline comments documenting the performance motivation for the new PathBuf handling and borrowed lookups.
crates/flow/src/incremental/invalidation.rs
Simplify function signatures in rule engine variable checking helpers by removing unnecessary explicit lifetimes that triggered Clippy warnings.
  • Remove the explicit 'r lifetime parameter from check_var_in_constraints and accept a shared reference to RapidMap directly.
  • Remove the explicit 'r lifetime parameter from check_var_in_transform and accept a shared reference to Option directly.
crates/rule-engine/src/check_var.rs

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 still pay for multiple PathBuf clones when initializing tarjan_dfs; consider storing &Path in stack/on_stack and only materializing PathBufs when emitting SCCs if lifetimes allow, to eliminate almost all per-node allocations.
  • The inline // ⚡ Bolt Optimization comments are quite verbose and largely restate the diff; trimming them down to a short, neutral explanation (or relying on the PR description) would make this hot-path code easier to scan.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- You still pay for multiple `PathBuf` clones when initializing `tarjan_dfs`; consider storing `&Path` in `stack`/`on_stack` and only materializing `PathBuf`s when emitting SCCs if lifetimes allow, to eliminate almost all per-node allocations.
- The inline `// ⚡ Bolt Optimization` comments are quite verbose and largely restate the diff; trimming them down to a short, neutral explanation (or relying on the PR description) would make this hot-path code easier to scan.

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

Refactors Tarjan DFS in incremental invalidation to avoid repeated PathBuf allocations during dependency graph traversal, and cleans up unnecessary explicit lifetimes that triggered Clippy warnings.

Changes:

  • Cache v.to_path_buf() once during Tarjan node initialization and switch inner-loop map lookups to use borrowed &Path keys.
  • Remove explicit lifetimes from check_var_in_constraints / check_var_in_transform signatures.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
crates/rule-engine/src/check_var.rs Removes redundant explicit lifetimes to satisfy Clippy / simplify signatures.
crates/flow/src/incremental/invalidation.rs Reduces allocation churn in Tarjan SCC traversal by avoiding per-edge PathBuf creation for map lookups.

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

let index = state.index_counter;
state.indices.insert(v.to_path_buf(), index);
state.lowlinks.insert(v.to_path_buf(), index);
// ⚡ Bolt Optimization: Compute owned PathBuf once for insertion to avoid redundant O(E) allocations
Copy link

Copilot AI Apr 26, 2026

Choose a reason for hiding this comment

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

The comment claims this avoids redundant "O(E) allocations", but this initialization block runs once per visited vertex (O(V)), and the clone() calls still allocate per owned PathBuf stored in each collection. Consider rewording to describe the actual win here (avoiding per-edge temporary PathBuf allocations during lookups), or just remove the complexity discussion from this line-level comment.

Suggested change
// ⚡ Bolt Optimization: Compute owned PathBuf once for insertion to avoid redundant O(E) allocations
// ⚡ Bolt Optimization: Materialize one owned `PathBuf` up front for the
// inserts/push below, while later lookups can continue to use borrowed `&Path`s.

Copilot uses AI. Check for mistakes.
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