Skip to content

⚡ Bolt: [performance improvement] Pre-allocate string instead of vector join in D1 UPSERTs#222

Open
bashandbone wants to merge 1 commit into
mainfrom
bolt/d1-upsert-sql-generation-optimization-342063582730952543
Open

⚡ Bolt: [performance improvement] Pre-allocate string instead of vector join in D1 UPSERTs#222
bashandbone wants to merge 1 commit into
mainfrom
bolt/d1-upsert-sql-generation-optimization-342063582730952543

Conversation

@bashandbone
Copy link
Copy Markdown
Contributor

@bashandbone bashandbone commented May 11, 2026

💡 What
Optimized the build_upsert_stmt function in crates/flow/src/targets/d1.rs by refactoring it to directly write to a single pre-allocated String buffer using std::fmt::Write. This replaces the previous implementation that allocated multiple intermediate vectors (columns, placeholders, update_clauses) and created temporary Strings before joining them all at the end.

🎯 Why
Generating D1 queries happens on a very hot codepath when writing data back to Cloudflare D1 endpoints. The existing approach created multiple intermediate string allocations and vector resize churn per statement. For large tables or frequent updates, these unnecessary heap allocations create measurable memory overhead and GC pressure (if tracking). Writing directly to a buffer with pre-calculated capacity prevents this bottleneck.

📊 Impact
Reduces memory allocation overhead for UPSERT generation from O(N) intermediate structures (where N is the number of keys + values) down to O(1) buffer allocations per query.

🔬 Measurement
Verified functionality using cargo test -p thread-flow to ensure the dynamically generated SQL exactly matches the expected format, and verified performance improvement theoretically by preventing at least 4 vectors and ~3N string allocations per call. Recorded performance learnings in .jules/bolt.md.


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

Summary by Sourcery

Optimize D1 UPSERT SQL generation to reduce string allocations and improve performance on a hot path.

Enhancements:

  • Refactor D1 UPSERT statement builder to write directly into a pre-allocated SQL String buffer instead of constructing and joining intermediate vectors.
  • Pre-size parameter and SQL buffers based on schema to minimize heap allocations during UPSERT generation.

Documentation:

  • Document performance learnings about SQL generation without intermediate strings in .jules/bolt.md.

…or join in D1 UPSERTs

Optimizes D1 UPSERT SQL generation by replacing multiple intermediate String/Vec allocations and string joins with a single pre-allocated String buffer using `std::fmt::Write`. This prevents O(N) heap allocations for hot network-bound codepaths writing to Cloudflare D1.

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 11, 2026 18:24
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented May 11, 2026

Reviewer's Guide

Refactors D1 UPSERT SQL generation to build the statement directly into a single pre-allocated String buffer and pre-allocates the parameters vector, eliminating intermediate vectors and join operations, and documents the performance learning in the Bolt notes.

File-Level Changes

Change Details Files
Optimize D1 UPSERT SQL construction by writing directly into a pre-allocated String and pre-sizing the params vector.
  • Introduce use of std::fmt::Write and a pre-allocated String buffer for SQL generation.
  • Pre-compute expected parameter count from key and value schemas and initialize the params Vec with that capacity.
  • Inline column list construction by appending key and value field names directly into the SQL buffer while simultaneously pushing their JSON-converted values into params.
  • Generate the VALUES placeholder list by appending '?' characters directly based on params length instead of building a separate placeholders vector.
  • Generate ON CONFLICT DO UPDATE SET clauses directly into the SQL buffer using the value field schema instead of building an intermediate update_clauses vector.
crates/flow/src/targets/d1.rs
Record performance learning about SQL generation without intermediate strings in Bolt documentation.
  • Add a dated note describing the cost of SQL generation with Vec::join for Cloudflare D1 targets.
  • Recommend using std::fmt::Write with a pre-allocated String instead of intermediate strings for performance-critical SQL generation 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:

  • The write! calls currently use .unwrap(), which will panic on formatting errors; consider either ignoring the fmt::Result (since writing to a String can't fail) or using expect with a clear message to avoid hidden panics.
  • You iterate over values.fields twice (once to build columns/params and once for the update clauses); consider building the ON CONFLICT DO UPDATE fragments in the same loop that processes values.fields to avoid the second pass.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `write!` calls currently use `.unwrap()`, which will panic on formatting errors; consider either ignoring the `fmt::Result` (since writing to a `String` can't fail) or using `expect` with a clear message to avoid hidden panics.
- You iterate over `values.fields` twice (once to build columns/params and once for the update clauses); consider building the `ON CONFLICT DO UPDATE` fragments in the same loop that processes `values.fields` to avoid the second pass.

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 optimizes D1 UPSERT SQL generation in thread-flow by replacing vector/string assembly + joins with direct writes into a single pre-allocated String, reducing allocations on a hot path.

Changes:

  • Refactor D1ExportContext::build_upsert_stmt to build SQL via std::fmt::Write into a pre-sized String and pre-size the params vector.
  • Record the performance optimization learning in .jules/bolt.md.

Reviewed changes

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

File Description
crates/flow/src/targets/d1.rs Refactors UPSERT SQL construction to reduce intermediate allocations by writing directly into a pre-allocated String.
.jules/bolt.md Adds a short performance note describing the SQL generation optimization approach.

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

Comment on lines +335 to +339
sql.push_str(") ON CONFLICT DO UPDATE SET ");
let mut first = true;
for (idx, _value) in values.fields.iter().enumerate() {
if let Some(value_field) = self.value_fields_schema.get(idx) {
if !first { sql.push_str(", "); }
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