Skip to content

⚡ Bolt: [performance improvement] Optimize D1 SQL string allocation#275

Open
bashandbone wants to merge 1 commit into
mainfrom
bolt/optimize-d1-sql-allocation-16231611141592875904
Open

⚡ Bolt: [performance improvement] Optimize D1 SQL string allocation#275
bashandbone wants to merge 1 commit into
mainfrom
bolt/optimize-d1-sql-allocation-16231611141592875904

Conversation

@bashandbone
Copy link
Copy Markdown
Contributor

@bashandbone bashandbone commented May 29, 2026

💡 What:
Replaced dynamic String format and .join(", ") loop logic with String::with_capacity and std::fmt::Write to construct the SQL query directly into a pre-allocated String buffer inside crates/flow/src/targets/d1.rs (build_upsert_stmt).

🎯 Why:
The original approach created multiple intermediate Vec collections and String allocations (via format!) for generating parameter lists and update clauses. By constructing the SQL string sequentially, we avoid these unnecessary intermediate heap allocations and string copy operations, directly reducing O(n) memory churn for every upsert call on high-throughput database paths.

📊 Impact:
Reduces heap allocation per query building substantially. This eliminates intermediate Vec<String> instances when generating lists of keys and update values.

🔬 Measurement:
Run cargo bench -p thread-flow --bench d1_profiling --features caching to measure latency, though running it requires caching feature. Tests were verified with cargo test -p thread-flow --test d1_target_tests --test d1_minimal_tests --test d1_cache_integration.


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

Summary by Sourcery

Optimize D1 upsert SQL construction to reduce allocations and perform minor API and formatting cleanups across AST and rule engine modules.

Enhancements:

  • Build D1 upsert INSERT/ON CONFLICT SQL directly into a pre-allocated String buffer to avoid intermediate String and Vec allocations.
  • Simplify rule-engine helper function signatures by removing unnecessary lifetimes and tightening references for constraints and transforms.
  • Tidy AST engine and rule-engine code formatting and error handling for clearer, more consistent style.

Documentation:

  • Extend Bolt performance notes with guidance on direct SQL string formatting for high-frequency paths.

Co-authored-by: bashandbone <89049923+bashandbone@users.noreply.github.com>
Copilot AI review requested due to automatic review settings May 29, 2026 17:50
@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 May 29, 2026

Reviewer's Guide

Optimizes D1 upsert SQL construction to reduce heap allocations while also making minor readability and lifetime-related cleanup in AST and rule engine modules, and documenting the performance pattern in .jules/bolt.md.

File-Level Changes

Change Details Files
Optimize D1 upsert SQL construction to avoid intermediate Vec and String allocations
  • Replace column/name accumulation Vecs and format!/join usage with direct writes into a pre-allocated SQL String using std::fmt::Write
  • Pre-allocate params vector based on key and value schema lengths to avoid repeated reallocations
  • Build ON CONFLICT update clause incrementally into a String instead of a Vec joined at the end
  • Generate the VALUES placeholder list by pushing '?' characters directly into the SQL buffer
crates/flow/src/targets/d1.rs
Minor cleanup of string replacement and test formatting in AST engine
  • Refactor String::from_utf8 error handling into a more compact unwrap_or_else expression while preserving behavior
  • Reformat a long assert_eq! in tests into multi-line style for readability
crates/ast-engine/src/tree_sitter/mod.rs
Simplify rule-engine helper function signatures and small formatting tweaks
  • Remove unnecessary lifetime parameters from check_var_in_constraints and check_var_in_transform and adjust their reference types
  • Reformat Rule::Pattern defined_vars mapping into multi-line chained iterator calls for readability
  • Compact Registration::read locking and unwrap_or_else chain onto a single line without behavior change
crates/rule-engine/src/check_var.rs
crates/rule-engine/src/rule/mod.rs
crates/rule-engine/src/rule/referent_rule.rs
Document new performance guideline for SQL string formatting
  • Add a Bolt performance note describing direct SQL string formatting with preallocated String and std::fmt::Write for high-frequency paths
.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:

  • In build_upsert_stmt, all write! calls currently discard their Result; consider at least using expect or propagating the error so that formatting failures don’t get silently ignored.
  • The changes to rule-engine lifetimes (check_var_in_constraints, check_var_in_transform) and formatting tweaks in other modules seem orthogonal to the D1 SQL performance optimization; consider keeping such refactors in a separate PR to keep diffs focused.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `build_upsert_stmt`, all `write!` calls currently discard their `Result`; consider at least using `expect` or propagating the error so that formatting failures don’t get silently ignored.
- The changes to rule-engine lifetimes (`check_var_in_constraints`, `check_var_in_transform`) and formatting tweaks in other modules seem orthogonal to the D1 SQL performance optimization; consider keeping such refactors in a separate PR to keep diffs focused.

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

Optimizes SQL statement construction in the D1 export target to reduce heap allocations on high-throughput upsert paths, alongside small refactors/formatting cleanups in the rule engine and AST engine, plus a Bolt note update.

Changes:

  • Reworked D1ExportContext::build_upsert_stmt to build SQL into a preallocated String using std::fmt::Write, avoiding intermediate Vec<String>/.join() allocations.
  • Minor rule-engine signature cleanup (remove unnecessary lifetimes) and formatting-only adjustments.
  • Added a Bolt note describing the direct SQL formatting optimization.

Reviewed changes

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

Show a summary per file
File Description
crates/rule-engine/src/rule/referent_rule.rs Formatting-only change to condense read() implementation.
crates/rule-engine/src/rule/mod.rs Formatting-only change for defined_vars() mapping/collection.
crates/rule-engine/src/check_var.rs Removes unnecessary lifetimes from helper function signatures.
crates/flow/src/targets/d1.rs Core change: optimized upsert SQL string construction to reduce allocations.
crates/ast-engine/src/tree_sitter/mod.rs Formatting-only adjustments in string conversion and a test assertion.
.jules/bolt.md Adds a new Bolt performance note about direct SQL string formatting.

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

Comment on lines +340 to 348
sql.push_str(") VALUES (");
for i in 0..params.len() {
if i > 0 {
sql.push_str(", ");
}
sql.push('?');
}
let _ = write!(sql, ") ON CONFLICT DO UPDATE SET {}", update_clauses);

Comment thread .jules/bolt.md
Comment on lines +5 to +7
## 2026-04-10 - [Performance: Direct SQL String Formatting]
**Learning:** In D1 target components (`build_upsert_stmt`), dynamically generating SQL using intermediate `Vec` allocations combined with `.join()` operations causes unnecessary heap allocations and copying. Constructing the raw SQL query directly via `std::fmt::Write` to a single pre-allocated `String` significantly reduces memory overhead.
**Action:** For dynamic SQL generation on high-frequency paths, use `String::with_capacity` and `write!` instead of intermediate arrays and `.join()`.
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