Skip to content

⚡ Bolt: [performance improvement] Optimize D1 target SQL statement building#248

Open
bashandbone wants to merge 1 commit into
mainfrom
bolt-perf-d1-sql-generation-10239718748718497456
Open

⚡ Bolt: [performance improvement] Optimize D1 target SQL statement building#248
bashandbone wants to merge 1 commit into
mainfrom
bolt-perf-d1-sql-generation-10239718748718497456

Conversation

@bashandbone
Copy link
Copy Markdown
Contributor

@bashandbone bashandbone commented May 20, 2026

💡 What
Refactored build_upsert_stmt and build_delete_stmt in crates/flow/src/targets/d1.rs to construct dynamic SQL queries directly into pre-allocated String buffers using std::fmt::Write. This replaces the previous pattern of collecting query parts into intermediate vectors (vec![]) and using format! with .join(). Query parameter vectors are also now pre-allocated with exact capacities.

🎯 Why
The previous implementation performed multiple heap allocations per query to create intermediate strings and vectors, causing unnecessary memory churn on a hot path during data export to Cloudflare D1 targets.

📊 Impact
Significantly reduces heap allocations and string copying overhead per generated SQL query, which improves memory efficiency and query generation throughput during bulk data exports.

🔬 Measurement
Verify the optimizations by running cargo test -p thread-flow --test d1_target_tests --test d1_minimal_tests to ensure that identical, correct SQL queries are still being generated under the new, faster implementation.


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

Summary by Sourcery

Optimize SQL statement construction for D1 exports and perform minor API and formatting cleanups across supporting crates.

Enhancements:

  • Build D1 upsert and delete SQL statements directly into pre-allocated string buffers while pre-sizing parameter vectors to reduce allocations on a hot path.
  • Simplify lifetime usage in variable checking helpers by removing unnecessary explicit lifetimes from function signatures.
  • Tidy up string and assertion formatting for improved readability in AST and rule engine modules.

Documentation:

  • Add a Bolt engineering note documenting the performance pattern of direct string formatting for dynamic SQL query construction.

Refactors `build_upsert_stmt` and `build_delete_stmt` in the D1 target
to use `String::with_capacity` and direct `write!` formatting instead
of repeatedly creating intermediate vectors and strings using `format!`
and `.join()`. Also pre-allocates query parameters vectors to their
exact required length. This drastically reduces heap allocations and
improves SQL string generation throughput.

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

Reviewer's Guide

Optimizes SQL statement construction for D1 exports by building queries directly into preallocated String buffers and parameter vectors, plus a few minor API-signature and formatting cleanups elsewhere in the codebase.

File-Level Changes

Change Details Files
Optimize D1 upsert SQL statement construction to avoid intermediate allocations.
  • Replace intermediate column, placeholder, and update-clause vectors with direct writes into a preallocated SQL String using std::fmt::Write.
  • Preallocate the params Vec based on key and value schema lengths to avoid repeated reallocations.
  • Build the VALUES placeholder list and ON CONFLICT update-clause list directly from the accumulated params and value_fields_schema, maintaining original query semantics.
crates/flow/src/targets/d1.rs
Optimize D1 delete SQL statement construction to build the WHERE clause directly into a String buffer.
  • Replace collection of where_clauses strings with direct writes into a preallocated SQL String using std::fmt::Write.
  • Preallocate the params Vec to the number of key fields.
  • Maintain logical conjunction of key-field predicates while reducing temporary allocations.
crates/flow/src/targets/d1.rs
Minor cleanup of string UTF-8 recovery and test formatting in the AST engine.
  • Refactor a from_utf8 unwrap_or_else call into a single line without changing behavior.
  • Reformat a multi-line assert_eq! for clarity while keeping the test logic identical.
crates/ast-engine/src/tree_sitter/mod.rs
Simplify lifetimes in rule-engine helper functions and slightly tidy registration reads.
  • Remove unused explicit lifetime parameters from check_var_in_constraints and check_var_in_transform and take references directly, simplifying signatures.
  • Keep behavior identical while improving readability of the Registration::read method’s unwrap_or_else call.
  • Reformat Rule::Pattern defined_vars mapping into a multi-line chain for clarity.
crates/rule-engine/src/check_var.rs
crates/rule-engine/src/rule/mod.rs
crates/rule-engine/src/rule/referent_rule.rs
Document the new performance pattern for SQL query building in the Bolt notes.
  • Add a Bolt log entry describing the motivation and pattern for direct String formatting and exact-capacity Vec allocations when building dynamic SQL queries.
.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 both build_upsert_stmt and build_delete_stmt, you repeatedly use use std::fmt::Write; let _ = write!(...); since String writes are infallible, consider either pulling the import to the module level and using write! directly (without let _ =) or adding a small helper to avoid the repeated boilerplate.
  • The String::with_capacity calls in the D1 SQL builders use fairly opaque constants (e.g., 128, 64, and per-field multipliers); adding a brief comment explaining how these were chosen or tying them to typical query shapes would make future maintenance and tuning easier.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In both `build_upsert_stmt` and `build_delete_stmt`, you repeatedly use `use std::fmt::Write; let _ = write!(...)`; since `String` writes are infallible, consider either pulling the import to the module level and using `write!` directly (without `let _ =`) or adding a small helper to avoid the repeated boilerplate.
- The `String::with_capacity` calls in the D1 SQL builders use fairly opaque constants (e.g., `128`, `64`, and per-field multipliers); adding a brief comment explaining how these were chosen or tying them to typical query shapes would make future maintenance and tuning easier.

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 D1 SQL statement generation in thread-flow to reduce heap allocations on a hot path by building SQL directly into pre-allocated String buffers and pre-sizing parameter vectors.

Changes:

  • Optimized build_upsert_stmt / build_delete_stmt in crates/flow/src/targets/d1.rs to avoid intermediate Vec<String>/format! allocations.
  • Minor formatting-only refactors across rule-engine and ast-engine modules.
  • Added a new performance “learning/action” entry to .jules/bolt.md.

Reviewed changes

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

Show a summary per file
File Description
crates/flow/src/targets/d1.rs Builds INSERT/DELETE SQL directly into pre-allocated buffers; pre-allocates params vec capacity.
crates/rule-engine/src/rule/referent_rule.rs Formatting-only refactor of a read-lock chain.
crates/rule-engine/src/rule/mod.rs Formatting-only refactor for defined_vars chain readability.
crates/rule-engine/src/check_var.rs Removes unnecessary explicit lifetimes in helper functions.
crates/ast-engine/src/tree_sitter/mod.rs Formatting-only refactors in string splice and a test assert.
.jules/bolt.md Adds a new entry describing the SQL string-building optimization.

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

Comment thread .jules/bolt.md
Comment on lines +5 to +8

## 2026-05-20 - [Performance: Direct String Formatting for SQL Queries]
**Learning:** In hot paths building dynamic strings (like SQL query generators `build_upsert_stmt`), repeatedly using `format!` and creating intermediate vectors for `.join()` results in high memory churn and excessive heap allocations per query.
**Action:** Use `String::with_capacity` paired with the `write!` macro (`std::fmt::Write`) and exact-capacity `Vec` pre-allocations to build dynamic strings directly into a single buffer, drastically reducing intermediate allocations.
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