Skip to content

⚡ Bolt: [D1 SQL generation optimization]#203

Open
bashandbone wants to merge 1 commit intomainfrom
bolt-d1-sql-alloc-optimization-10287299905955204933
Open

⚡ Bolt: [D1 SQL generation optimization]#203
bashandbone wants to merge 1 commit intomainfrom
bolt-d1-sql-alloc-optimization-10287299905955204933

Conversation

@bashandbone
Copy link
Copy Markdown
Contributor

@bashandbone bashandbone commented May 7, 2026

💡 What: Replaced intermediate string vector allocations (columns, placeholders, update_clauses) and .join() calls with pre-allocated String buffers (using String::with_capacity) and incremental std::fmt::Write logic inside build_upsert_stmt and build_delete_stmt in crates/flow/src/targets/d1.rs.

🎯 Why: The original implementation caused multiple string heap allocations per query loop (via format!()) and further allocation overhead when executing .join(", "). This adds up especially when doing bulk processing.

📊 Impact: Significantly reduces O(N) memory allocations per target SQL string generated, lowering garbage and improving loop efficiency.

🔬 Measurement: Verified with cargo test -p thread-flow --test d1_target_tests. Code correctness holds true and intermediate memory allocations are deferred.


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

Summary by Sourcery

Optimize SQL statement generation for D1 targets to reduce string allocations and capture the performance pattern in project documentation.

Enhancements:

  • Replace intermediate string vectors and joins in D1 upsert/delete builders with pre-allocated String buffers and incremental fmt::Write assembly.
  • Tidy several Rust code paths for readability and consistency in AST and rule engine modules.

Documentation:

  • Add a Bolt performance note documenting SQL generation pre-allocation practices.

…queries

Replaces intermediate string `Vec` allocations and `.join()` operations
with pre-allocated `String` buffers (`String::with_capacity`) and
incremental `write!` formatting in `build_upsert_stmt` and
`build_delete_stmt` to lower heap allocations during bulk operations.

Co-authored-by: bashandbone <[email protected]>
@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 7, 2026 18:28
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented May 7, 2026

Reviewer's Guide

Optimizes D1 SQL statement generation by replacing intermediate Vec assemblies and format!/join calls with preallocated String buffers and std::fmt::Write, plus a few minor style/formatting cleanups in other crates and an addition to the Bolt performance notes.

Class diagram for optimized D1ExportContext SQL generation

classDiagram
    class D1ExportContext {
        String table_name
        KeyFieldSchema[] key_fields_schema
        ValueFieldSchema[] value_fields_schema
        +build_upsert_stmt(key: KeyValue, values: FieldValues) Result~(String, Vec_serde_json_Value_) , RecocoError~
        +build_delete_stmt(key: KeyValue) Result~(String, Vec_serde_json_Value_) , RecocoError~
    }

    class KeyValue {
        KeyPart[] 0
    }

    class FieldValues {
        ValueField[] fields
    }

    class KeyFieldSchema {
        String name
    }

    class ValueFieldSchema {
        String name
    }

    class KeyPart
    class ValueField
    class serde_json_Value
    class RecocoError

    D1ExportContext --> KeyValue : uses
    D1ExportContext --> FieldValues : uses
    D1ExportContext --> serde_json_Value : params
    D1ExportContext --> RecocoError : error
    D1ExportContext --> KeyFieldSchema : reads
    D1ExportContext --> ValueFieldSchema : reads
    KeyValue --> KeyPart : wraps
    FieldValues --> ValueField : contains
Loading

File-Level Changes

Change Details Files
Optimize D1 upsert SQL generation to avoid intermediate string allocations and joins.
  • Replace Vec-based column, placeholder, and update clause accumulation with preallocated String buffers using String::with_capacity
  • Use std::fmt::Write::write! to incrementally build INSERT INTO ... ON CONFLICT DO UPDATE SET SQL, tracking first/next elements via booleans instead of join
  • Preserve parameter vector construction logic while reordering control flow to align with streaming SQL construction
crates/flow/src/targets/d1.rs
Optimize D1 delete SQL generation to build WHERE clause in a single string buffer.
  • Replace Vec-based where_clauses collection and join with a preallocated SQL String buffer
  • Use std::fmt::Write::write! with an " AND " separator controlled by a first flag while keeping parameter extraction logic unchanged
crates/flow/src/targets/d1.rs
Minor code-style and readability adjustments in AST and rule engine modules.
  • Collapse unwrap_or_else call for UTF-8 recovery in String ContentExt implementation into a single chained expression
  • Reformat tree-sitter test assertion for multi-line readability
  • Reformat Rule::defined_vars Pattern arm into a multi-line iterator chain
  • Inline Registration::read lock error handling into a single expression
crates/ast-engine/src/tree_sitter/mod.rs
crates/rule-engine/src/rule/mod.rs
crates/rule-engine/src/rule/referent_rule.rs
Document the new SQL generation optimization in Bolt performance notes.
  • Add a new dated entry describing the cost of Vec + join-based SQL generation and the preferred preallocated String + write! pattern
.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 SQL builders now rely on multiple write!(...).unwrap() calls; since fmt::Write for String is infallible you can either ignore the Result or use expect once in a small helper to avoid scattering unwrap()s and make panics more intentional.
  • The new entry in .jules/bolt.md embeds literal \n characters inside the markdown line, which will render oddly; consider splitting this into actual newlines so the “Learning” and “Action” sections format consistently with the previous entry.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The SQL builders now rely on multiple `write!(...).unwrap()` calls; since `fmt::Write` for `String` is infallible you can either ignore the `Result` or use `expect` once in a small helper to avoid scattering `unwrap()`s and make panics more intentional.
- The new entry in `.jules/bolt.md` embeds literal `\n` characters inside the markdown line, which will render oddly; consider splitting this into actual newlines so the “Learning” and “Action” sections format consistently with the previous entry.

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 Cloudflare D1 target SQL generation by reducing intermediate allocations during upsert/delete statement construction in thread-flow, aiming to improve performance in bulk export loops.

Changes:

  • Reworked build_upsert_stmt and build_delete_stmt to build SQL via pre-allocated String buffers and incremental write! calls (avoids Vec<String> + .join() allocations).
  • Minor formatting-only refactors in rule-engine and ast-engine code.
  • Added a performance “Bolt” log entry describing the optimization.

Reviewed changes

Copilot reviewed 5 out of 5 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 refactor (no behavioral change).
crates/rule-engine/src/rule/mod.rs Formatting-only refactor (no behavioral change).
crates/flow/src/targets/d1.rs Implements allocation-reduced SQL string assembly for upsert/delete.
crates/ast-engine/src/tree_sitter/mod.rs Formatting-only refactor (no behavioral change).
.jules/bolt.md Adds a learning-log entry for the SQL generation pre-allocation change.

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

Comment thread .jules/bolt.md
## 2026-04-08 - [Performance: Defer Allocation during Traversal]
**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.
## 2026-05-07 - [Performance: SQL Generation Pre-allocation]\n**Learning:** Generating SQL string with intermediate `vec![]` string arrays, pushing `format!` results, and calling `.join(",")` incurs unnecessary string and heap allocations, especially during bulk upsert or deletes.\n**Action:** Use pre-allocated Strings with `String::with_capacity` and leverage `std::fmt::Write` directly (`write!`) to assemble complex SQL queries with no intermediate array joining.
Comment on lines 28 to 31
impl<R> Registration<R> {
fn read(&self) -> Arc<RapidMap<String, R>> {
self.0
.read()
.unwrap_or_else(|e| e.into_inner())
.clone()
self.0.read().unwrap_or_else(|e| e.into_inner()).clone()
}
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