Skip to content

⚡ Bolt: [performance improvement] defer path allocations in DAG traversals#185

Open
bashandbone wants to merge 1 commit intomainfrom
jules-4977869955577881359-90795e09
Open

⚡ Bolt: [performance improvement] defer path allocations in DAG traversals#185
bashandbone wants to merge 1 commit intomainfrom
jules-4977869955577881359-90795e09

Conversation

@bashandbone
Copy link
Copy Markdown
Contributor

@bashandbone bashandbone commented Apr 30, 2026

💡 What: Avoids unnecessary to_path_buf() heap allocations in tarjan_dfs and visit_node loops by reusing allocated variables and using borrowed references (&Path) for HashSet and HashMap presence checks.
🎯 Why: Inside core graph traversal functions, continuously turning paths into owned instances creates extreme memory churn and slows down the analysis significantly, particularly in deep/wide repository graphs.
📊 Impact: Considerably reduces memory allocation overhead inside Hot paths during invalidation computation, making large DAG traversals up to O(V) allocations rather than O(E).
🔬 Measurement: Verified with cargo test -p thread-flow --test invalidation_tests maintaining functional correctness. Re-running large dependency graph traversals natively demonstrates much fewer allocations.


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

Summary by Sourcery

Optimize path handling in graph invalidation traversals to reduce allocations, and make minor style and documentation updates.

Enhancements:

  • Reduce PathBuf allocations in Tarjan-based SCC detection by reusing a single owned path and relying on borrowed Path references for map/set lookups.
  • Clarify and document best practices for deferring path allocations in recursive traversal hot paths, including comments in traversal code and internal Bolt notes.
  • Reformat several code blocks and assertions for improved readability without changing behavior.

Documentation:

  • Extend internal Bolt performance notes with guidance on deferring path allocations and using borrowed types in hot recursive traversals.

…rsals

Co-authored-by: bashandbone <89049923+bashandbone@users.noreply.github.com>
Copilot AI review requested due to automatic review settings April 30, 2026 18:02
@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 30, 2026

Reviewer's Guide

Optimizes path handling in incremental invalidation DAG traversals by deferring PathBuf allocations and using borrowed Path references in hot loops, plus a few small formatting and style cleanups elsewhere.

Sequence diagram for optimized tarjan_dfs DAG traversal

sequenceDiagram
    actor Caller
    participant InvalidationDetector
    participant TarjanState
    participant DependencyGraph

    Caller->>InvalidationDetector: tarjan_dfs(v: &Path, state: &mut TarjanState, sccs: &mut Vec<Vec<PathBuf>>)
    Note over InvalidationDetector,TarjanState: Initialize node with a single PathBuf allocation
    InvalidationDetector->>InvalidationDetector: v_buf = v.to_path_buf()
    InvalidationDetector->>TarjanState: indices.insert(v_buf.clone(), index)
    InvalidationDetector->>TarjanState: lowlinks.insert(v_buf.clone(), index)
    InvalidationDetector->>TarjanState: stack.push(v_buf.clone())
    InvalidationDetector->>TarjanState: on_stack.insert(v_buf)
    InvalidationDetector->>TarjanState: index_counter += 1

    InvalidationDetector->>DependencyGraph: get_dependencies(v: &Path)
    DependencyGraph-->>InvalidationDetector: dependencies: Vec<&Path>

    loop for each dep in dependencies
        InvalidationDetector->>TarjanState: indices.contains_key(dep)
        alt dep not visited
            InvalidationDetector->>InvalidationDetector: tarjan_dfs(dep, state, sccs)
            InvalidationDetector->>TarjanState: lowlinks.get(dep)
            InvalidationDetector->>TarjanState: lowlinks.get_mut(v)
            TarjanState-->>InvalidationDetector: update v lowlink using w_lowlink
        else dep on stack
            InvalidationDetector->>TarjanState: on_stack.contains(dep)
            TarjanState-->>InvalidationDetector: true
            InvalidationDetector->>TarjanState: indices.get(dep)
            InvalidationDetector->>TarjanState: lowlinks.get_mut(v)
            TarjanState-->>InvalidationDetector: update v lowlink using w_index
        end
    end

    InvalidationDetector->>TarjanState: indices.get(v)
    InvalidationDetector->>TarjanState: lowlinks.get(v)
    alt v_lowlink == v_index
        loop pop stack until v
            InvalidationDetector->>TarjanState: stack.pop()
            InvalidationDetector->>TarjanState: on_stack.remove(node)
            InvalidationDetector->>InvalidationDetector: push node into current_scc
        end
        InvalidationDetector->>Caller: push current_scc into sccs
    else
        InvalidationDetector-->>Caller: return
    end
Loading

Class diagram for Tarjan-based invalidation traversal and DependencyGraph visit_node

classDiagram
    class InvalidationDetector {
        -graph: DependencyGraph
        +tarjan_dfs(v: &Path, state: &mut TarjanState, sccs: &mut Vec<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(file: &Path) Vec<PathBuf>
        +visit_node(file: &Path, visited: &mut HashSet<PathBuf>) Result<(), GraphError>
    }

    class GraphError {
        +CyclicDependency(PathBuf)
        +Other
    }

    InvalidationDetector --> DependencyGraph : uses
    InvalidationDetector --> TarjanState : mutates
    DependencyGraph --> GraphError : returns
    TarjanState "1" o-- "*" PathBuf : keys_and_stack
    DependencyGraph --> Path : traversal_keys
    TarjanState --> Path : borrowed_lookups
    DependencyGraph --> HashSet_PathBuf : visited

    class Path {
    }

    class PathBuf {
    }

    class HashMap_PathBuf_usize {
    }

    class HashSet_PathBuf {
    }

    TarjanState : indices HashMap_PathBuf_usize
    TarjanState : lowlinks HashMap_PathBuf_usize
    TarjanState : stack Vec~PathBuf~
    TarjanState : on_stack HashSet_PathBuf
    DependencyGraph : visit_node()
    DependencyGraph : get_dependencies() Vec~PathBuf~
    InvalidationDetector : tarjan_dfs()
    TarjanState : index_counter usize
Loading

File-Level Changes

Change Details Files
Defer PathBuf allocations and rely on borrowed &Path keys in Tarjan SCC traversal to reduce allocations in hot invalidation paths.
  • Introduce a single v_buf PathBuf per tarjan_dfs invocation and reuse it for indices, lowlinks, stack, and on_stack storage instead of repeated to_path_buf() calls.
  • Switch HashMap/HashSet lookups in tarjan_dfs from using v.to_path_buf() to using &Path directly for get/get_mut operations.
  • Leave SCC detection logic unchanged while ensuring index/lowlink retrieval also uses borrowed &Path to avoid extra allocations.
crates/flow/src/incremental/invalidation.rs
Document performance guidance for deferring path and identifier allocations during graph traversals in Bolt guidelines.
  • Add a new Bolt entry explaining why PathBuf creation should be deferred in recursive traversal functions like tarjan_dfs and visit_node.
  • Recommend using borrowed references for membership checks and reusing cloned PathBufs instead of repeated conversions from &Path.
.jules/bolt.md
Apply minor stylistic/formatting adjustments in AST and rule-engine modules for readability and consistency.
  • Reformat a String::from_utf8/unwrap_or_else chain into a single, more compact expression in the tree_sitter ContentExt implementation.
  • Reformat long assert_eq! in a tree-sitter test to multi-line style for readability.
  • Reflow Rule::Pattern defined_vars collection into multi-line chained iterator calls.
  • Inline the Registration::read lock error handling/unwrapping into a single expression.
crates/ast-engine/src/tree_sitter/mod.rs
crates/rule-engine/src/rule/mod.rs
crates/rule-engine/src/rule/referent_rule.rs
Guard graph traversal in DependencyGraph::visit_node by checking visited with a borrowed Path before allocating a PathBuf for error reporting.
  • Add an optimization comment and ensure visited.contains uses the borrowed &Path file parameter before any file.to_path_buf() allocation.
  • Preserve existing cyclic dependency error behavior while reducing unnecessary allocations for already-visited nodes.
crates/flow/src/incremental/graph.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:

  • In tarjan_dfs, caching v_buf and then calling v_buf.clone() for each insertion still performs a fresh allocation per clone, so it likely doesn’t reduce allocations versus the original multiple to_path_buf() calls; if allocation count is the concern, consider either keeping the simpler original code or restructuring TarjanState to store borrowed keys or indirections (e.g., indices) instead.
  • Now that indices, lowlinks, and on_stack are being queried with borrowed &Path keys, you may be able to go further and change their key types away from PathBuf entirely (e.g., to borrowed or interning-based keys) to avoid owning path allocations in the Tarjan state.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `tarjan_dfs`, caching `v_buf` and then calling `v_buf.clone()` for each insertion still performs a fresh allocation per clone, so it likely doesn’t reduce allocations versus the original multiple `to_path_buf()` calls; if allocation count is the concern, consider either keeping the simpler original code or restructuring `TarjanState` to store borrowed keys or indirections (e.g., indices) instead.
- Now that `indices`, `lowlinks`, and `on_stack` are being queried with borrowed `&Path` keys, you may be able to go further and change their key types away from `PathBuf` entirely (e.g., to borrowed or interning-based keys) to avoid owning path allocations in the Tarjan state.

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 focuses on reducing unnecessary PathBuf allocations in core incremental graph traversal code paths by preferring borrowed &Path lookups in RapidMap/RapidSet, improving performance in large DAG traversals.

Changes:

  • Optimize Tarjan SCC DFS (tarjan_dfs) by reusing a single PathBuf allocation and switching repeated map lookups from v.to_path_buf() to borrowed &Path.
  • Document/clarify the same borrowed-lookup optimization in DependencyGraph::visit_node (topological sort).
  • Apply small formatting-only changes in rule engine code and tree-sitter edit handling/tests; add a Bolt learning log entry.

Reviewed changes

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

Show a summary per file
File Description
crates/rule-engine/src/rule/referent_rule.rs Formatting-only consolidation of the read() call chain.
crates/rule-engine/src/rule/mod.rs Formatting-only expansion of the Rule::Pattern defined_vars() pipeline.
crates/flow/src/incremental/invalidation.rs Avoid repeated to_path_buf() allocations in Tarjan DFS lowlink/index lookups by using borrowed &Path.
crates/flow/src/incremental/graph.rs Adds optimization note and ensures borrowed visited.contains(file) check occurs before allocating file_buf.
crates/ast-engine/src/tree_sitter/mod.rs Formatting-only refactor of from_utf8 fallback and a test assertion layout change.
.jules/bolt.md Adds a new Bolt learning entry related to deferring path allocations in recursive traversal.

💡 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