Skip to content

⚡ Bolt: [performance improvement] Optimize D1 SQL string generation#278

Open
bashandbone wants to merge 1 commit into
mainfrom
bolt-optimize-d1-sql-generation-17539559843041150798
Open

⚡ Bolt: [performance improvement] Optimize D1 SQL string generation#278
bashandbone wants to merge 1 commit into
mainfrom
bolt-optimize-d1-sql-generation-17539559843041150798

Conversation

@bashandbone
Copy link
Copy Markdown
Contributor

@bashandbone bashandbone commented May 30, 2026

⚡ Bolt: [performance improvement] Optimize D1 SQL string generation

💡 What:
Refactored SQL query string generation and cache key creation in crates/flow/src/targets/d1.rs to use pre-allocated String capacities (String::with_capacity) and std::fmt::Write (the write! macro).

🎯 Why:
The previous implementation used intermediate Vec<String> collections and format! in loops, or repeatedly concatenated strings, resulting in unnecessary heap allocations and memory copying for every SQL statement constructed. This optimization significantly reduces memory churn and improves execution latency.

📊 Impact:
Reduces dynamic heap allocations to 1-2 per query (down from one per field and intermediate vector join) and noticeably lowers the latency overhead for statement generation, especially during heavy upsert/delete batches.

🔬 Measurement:
Verified via d1_profiling benchmark and general cargo test -p thread-flow. Tests pass successfully and benchmark traces show improved latencies.


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

Summary by Sourcery

Optimize D1 SQL generation and cache key creation to reduce heap allocations and improve query construction performance.

Enhancements:

  • Refactor D1 upsert and delete SQL construction to use preallocated strings and direct formatted writes instead of intermediate collections and repeated formatting.
  • Streamline cache key generation for D1 queries to reuse the SQL string buffer and minimize allocations.

Documentation:

  • Add a Bolt performance note documenting best practices for using preallocated strings and direct writes over format-based string construction.

💡 What:
Refactored SQL query string generation and cache key creation in `crates/flow/src/targets/d1.rs` to use pre-allocated `String` capacities (`String::with_capacity`) and `std::fmt::Write` (the `write!` macro).

🎯 Why:
The previous implementation used intermediate `Vec<String>` collections and `format!` in loops, or repeatedly concatenated strings, resulting in unnecessary heap allocations and memory copying for every SQL statement constructed. This optimization significantly reduces memory churn and improves execution latency.

📊 Impact:
Reduces dynamic heap allocations to 1-2 per query (down from one per field and intermediate vector join) and noticeably lowers the latency overhead for statement generation, especially during heavy upsert/delete batches.

🔬 Measurement:
Verified via `d1_profiling` benchmark and general `cargo test -p thread-flow`. Tests pass successfully and benchmark traces show improved latencies.

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

sourcery-ai Bot commented May 30, 2026

Reviewer's Guide

Optimizes D1 SQL generation and cache-key construction by replacing allocation-heavy format!/Vec-based string building with preallocated String buffers and std::fmt::Write, plus documents the performance pattern in .jules/bolt.md.

File-Level Changes

Change Details Files
Optimize cache key construction for SQL + params under the caching feature to minimize allocations.
  • Replace format!-based cache key construction with manual String::with_capacity and write! usage
  • Preallocate cache key capacity based on SQL length and estimated parameter size
  • Append SQL and formatted params directly into a single String buffer
crates/flow/src/targets/d1.rs
Refactor UPSERT (insert/update-on-conflict) SQL statement generation to build into a single preallocated String using write!.
  • Replace Vec collections for columns, placeholders, and update clauses with direct writing into a preallocated SQL String
  • Estimate capacities for SQL String and params Vec based on key/value schema sizes
  • Use a boolean first flag and write! calls to stream column names, placeholders, and ON CONFLICT update clauses directly into the SQL buffer
  • Maintain params Vec in parallel without changing its logical contents
crates/flow/src/targets/d1.rs
Refactor DELETE SQL statement generation to avoid intermediate Vec allocations and use a preallocated String.
  • Replace where_clauses Vec + join with direct write! into a preallocated SQL String
  • Precompute capacity based on table name and key count and reserve params capacity accordingly
  • Use a first flag to correctly place AND separators between WHERE predicates
crates/flow/src/targets/d1.rs
Document the performance pattern of direct string writing over format!/joins in the Bolt playbook.
  • Add a Bolt note describing the costs of format!/Vec-join based string building for SQL queries
  • Recommend using String::with_capacity with std::fmt::Write for loop-heavy string construction 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 repeated let _ = write!(...) calls silently discard potential formatting errors; consider either using a small helper that expects on failure or otherwise centralizing handling so failures are not silently ignored in multiple places.
  • The SQL construction logic is now duplicated in several places with similar write! patterns (e.g., comma/AND joining); extracting small helpers for writing delimited column lists and placeholders would reduce duplication and make future changes less error-prone.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The repeated `let _ = write!(...)` calls silently discard potential formatting errors; consider either using a small helper that `expect`s on failure or otherwise centralizing handling so failures are not silently ignored in multiple places.
- The SQL construction logic is now duplicated in several places with similar `write!` patterns (e.g., comma/`AND` joining); extracting small helpers for writing delimited column lists and placeholders would reduce duplication and make future changes less error-prone.

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 SQL/cache-key string generation in thread-flow by replacing intermediate string collections and repeated formatting with preallocated buffers and direct writes.

Changes:

  • Reworked D1 cache-key, upsert SQL, and delete SQL construction to use String::with_capacity and write!.
  • Preallocated parameter vectors for D1 statement builders.
  • Added a Bolt note documenting the string-construction performance pattern.

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 Optimizes D1 SQL and cache-key string construction in hot paths.
.jules/bolt.md Adds a performance learning note for direct string writing.

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

Comment thread .jules/bolt.md
**Learning:** During DAG traversals, creating owned variants of identifiers (like `file.to_path_buf()`) *before* checking `visited` HashSets results in heap allocations (O(E)) for every edge instead of every visited node (O(V)). By moving the `&PathBuf` allocation strictly *after* all HashSet `contains` checks using the borrowed reference (`&Path`), we drastically reduce memory churn.
**Action:** Always check `HashSet::contains` with a borrowed reference *before* creating the owned version required by `HashSet::insert`, especially in performance-critical graph traversal paths.

## 2024-05-30 - [Performance: Direct String Writing over Format]
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