Skip to content

⚡ Bolt: [Performance: Defer Allocation during Traversal]#190

Open
bashandbone wants to merge 1 commit intomainfrom
bolt/optimization-defer-allocation-traversal-16640234953718659717
Open

⚡ Bolt: [Performance: Defer Allocation during Traversal]#190
bashandbone wants to merge 1 commit intomainfrom
bolt/optimization-defer-allocation-traversal-16640234953718659717

Conversation

@bashandbone
Copy link
Copy Markdown
Contributor

@bashandbone bashandbone commented May 2, 2026

💡 What: Optimized performance-critical DAG traversals and map lookups by avoiding unconditional `PathBuf` allocations. In `tarjan_dfs`, the `&Path` is now used to perform lookups against `RapidSet` and `RapidMap`, and multiple clones of `PathBuf` are minimized into single instances. In `ensure_node`, a simple `contains_key` avoids allocating when nodes already exist. Also fixed lifetime clippy errors in `check_var.rs`.
🎯 Why: Creating `PathBuf` triggers heap allocations which represent a major O(E) or O(V) overhead during traversal paths of the `thread-flow` execution.
📊 Impact: Reduces memory churn substantially during topological sorting and graph dependency building.
🔬 Measurement: Verify memory utilization drops when processing large dependency graphs. Tested via `cargo test -p thread-flow`.


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

Summary by Sourcery

Optimize graph traversal and dependency management to reduce unnecessary allocations and clean up rule-engine lifetimes and formatting.

Enhancements:

  • Avoid repeated PathBuf allocations and reuse path references during Tarjan DFS traversal in the invalidation detector.
  • Prevent unnecessary node allocations in the dependency graph by checking for existing entries before inserting.
  • Relax lifetimes on rule-engine constraint and transform parameters to simplify usage and satisfy Clippy.
  • Tidy up string handling, assertion formatting, and registration map access for clearer and more consistent code.

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 May 2, 2026 17:41
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented May 2, 2026

Reviewer's Guide

Optimizes DAG traversal and dependency graph operations by reducing PathBuf allocations, updates rule-engine APIs to use simpler reference lifetimes, and includes minor formatting and Clippy cleanups across several modules.

Class diagram for incremental graph and Tarjan traversal changes

classDiagram
    class DependencyGraph {
        +RapidMap~PathBuf, AnalysisDefFingerprint~ nodes
        +fn ensure_node(file: &Path)
        +fn get_dependencies(file: &Path) Vec~PathBuf~
    }

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

    class TarjanState {
        +RapidMap~PathBuf, usize~ indices
        +RapidMap~PathBuf, usize~ lowlinks
        +Vec~PathBuf~ stack
        +RapidSet~PathBuf~ on_stack
        +usize index_counter
    }

    DependencyGraph --> InvalidationDetector : used_by
    InvalidationDetector --> TarjanState : mutates
    InvalidationDetector --> DependencyGraph : queries_dependencies

    %% Highlighted behavioral changes
Loading

Class diagram for rule engine variable checking and registration changes

classDiagram
    class Rule {
        +fn defined_vars() RapidSet~String~
    }

    class RuleRegistration {
        +RapidMap~String, Rule~ rules
    }

    class Registration_R_ {
        +Arc~RwLock~RapidMap~String, R~~~ inner
        +fn read() Arc~RapidMap~String, R~~
        +fn contains_key(key: &str) bool
    }

    class CheckHint_r_ {
        <<enum>>
    }

    class CheckVarAPI {
        +fn check_rule_with_hint_r_(rule: &Rule, utils: &RuleRegistration, constraints: &RapidMap~MetaVariableID, Rule~, transform: &Option~Transform~, fixer: &Vec~Fixer~, hint: CheckHint_r_) RResult~()~
        +fn check_vars_in_rewriter_r_(rule: &Rule, utils: &RuleRegistration, constraints: &RapidMap~MetaVariableID, Rule~, transform: &Option~Transform~, fixer: &Vec~Fixer~, upper_var: &RapidSet~String~) RResult~()~
        +fn check_vars_r_(rule: &Rule, utils: &RuleRegistration, constraints: &RapidMap~MetaVariableID, Rule~, transform: &Option~Transform~, fixer: &Vec~Fixer~) RResult~()~
        +fn check_var_in_constraints(vars: RapidSet~String~, constraints: &RapidMap~MetaVariableID, Rule~) RResult~RapidSet~String~~
        +fn check_var_in_transform(vars: RapidSet~String~, transform: &Option~Transform~) RResult~RapidSet~String~~
    }

    RuleRegistration --> Rule : contains
    Registration_R_ --> Rule : value_type_R
    CheckVarAPI --> Rule : analyzes
    CheckVarAPI --> RuleRegistration : uses
    CheckVarAPI --> Registration_R_ : uses_constraints
    CheckVarAPI --> CheckHint_r_ : parameter
    Rule --> CheckVarAPI : provides_defined_vars
Loading

File-Level Changes

Change Details Files
Reduce PathBuf allocations during Tarjan SCC traversal and graph node management to lower memory churn.
  • Cache a single PathBuf per node in tarjan_dfs and reuse it for indices, lowlinks, stack, and on_stack tracking instead of repeatedly calling to_path_buf
  • Use &Path as the key for RapidMap/RapidSet lookups in tarjan_dfs, removing redundant PathBuf conversions
  • Change ensure_node to perform a contains_key check and only insert a new PathBuf key and default AnalysisDefFingerprint when the node is missing
crates/flow/src/incremental/invalidation.rs
crates/flow/src/incremental/graph.rs
Simplify lifetimes and references in rule checking functions to satisfy Clippy and make signatures less restrictive.
  • Remove explicit lifetime parameters on constraints and transform references in check_var helpers, replacing &'r RapidMap / &'r Option with &RapidMap / &Option
  • Adjust helper function signatures (e.g., check_var_in_constraints, check_var_in_transform) to match the simplified reference types
crates/rule-engine/src/check_var.rs
Minor readability and style cleanups in string transformation and rule/registration helpers.
  • Reformat String::replace_slice implementation to a single chained unwrap_or_else for FromUtf8Error handling
  • Expand defined_vars for Rule::Pattern into a multi-line iterator chain for clarity
  • Inline the registration read() unwrap_or_else chain into a single line
  • Reformat a test assertion to multi-line assert_eq for consistency
crates/ast-engine/src/tree_sitter/mod.rs
crates/rule-engine/src/rule/mod.rs
crates/rule-engine/src/rule/referent_rule.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 DependencyGraph::ensure_node, the change from entry(...).or_insert_with(...) to a separate contains_key check followed by insert introduces an extra map lookup; you can keep using entry to avoid the double lookup while still deferring PathBuf allocation by only calling file.to_path_buf() inside the or_insert_with closure.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `DependencyGraph::ensure_node`, the change from `entry(...).or_insert_with(...)` to a separate `contains_key` check followed by `insert` introduces an extra map lookup; you can keep using `entry` to avoid the double lookup while still deferring `PathBuf` allocation by only calling `file.to_path_buf()` inside the `or_insert_with` closure.

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 allocation overhead in performance-sensitive graph traversal and node creation paths by leveraging borrowed &Path lookups and minimizing repeated PathBuf conversions, alongside small refactors to address clippy lifetime warnings and formatting.

Changes:

  • Update Tarjan SCC DFS to avoid v.to_path_buf() allocations during map/set lookups by using borrowed &Path.
  • Optimize ensure_node to skip PathBuf allocation when the node already exists.
  • Fix lifetime/clippy issues in check_var.rs and apply minor formatting cleanups.

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 Minor refactor/formatting for RwLock read+clone path.
crates/rule-engine/src/rule/mod.rs Formatting-only change to defined_vars() for Rule::Pattern.
crates/rule-engine/src/check_var.rs Remove unnecessary explicit lifetimes on some parameters to satisfy clippy.
crates/flow/src/incremental/invalidation.rs Use borrowed &Path for Tarjan state lookups to avoid repeated PathBuf allocations.
crates/flow/src/incremental/graph.rs Avoid allocating PathBuf in ensure_node when a node is already present.
crates/ast-engine/src/tree_sitter/mod.rs Formatting-only adjustments in UTF-8 recovery and a test assertion.

💡 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