Skip to content

⚡ Bolt: Batching file writes in ChecksumWriter - #156

Open
stffns wants to merge 2 commits into
mainfrom
bolt/optimize-checksum-writer-997483946065271324
Open

stffns wants to merge 2 commits into
mainfrom
bolt/optimize-checksum-writer-997483946065271324

Conversation

@stffns

@stffns stffns commented Jul 11, 2026 •

Copy link
Copy Markdown
Owner

💡 What: Added a chunked batching strategy using bytearray buffer for ChecksumWriter.write.
🎯 Why: Writing many small strings to a file sequentially introduces significant system call overhead and frequent zlib.crc32 updates.
📊 Impact: ~1.36x speedup for saving an index.
🔬 Measurement: Run a serialization performance benchmark on _index.save() before and after.


PR created automatically by Jules for task 997483946065271324 started by @stffns

Summary by CodeRabbit

  • Performance Improvements

    • Improved file writing performance by batching small writes before processing and saving them.
    • Added support for writing data provided as either bytes or byte arrays.
    • Preserved accurate checksums and reliable finalization of written files.
  • Documentation

    • Added a learning note describing the write-performance optimization.

Writing many small strings to a file sequentially introduces significant
system call overhead and frequent `zlib.crc32` updates. This adds a
`bytearray` buffer to `ChecksumWriter.write` to chunk and batch writes
(flushing at 64KB), providing a ~1.36x speedup for saving an index.

Co-authored-by: stffns <70039235+stffns@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.

@coderabbiteu

coderabbiteu Bot commented Jul 11, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@stffns, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 54 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 211a0836-b2b1-4d06-87c8-2c65151952f6

📥 Commits

Reviewing files that changed from the base of the PR and between 9cf0c65 and d4dc5f4.

📒 Files selected for processing (1)
  • .github/workflows/ci.yml
📝 Walkthrough

Walkthrough

ChecksumWriter now batches small writes in an internal bytearray, updates CRCs and the underlying file during flushes, and flushes remaining data during finalization. Its write type accepts both bytes and bytearray, with documentation updated accordingly.

Changes

ChecksumWriter batching

Layer / File(s) Summary
Buffered checksum write path
snapvec/_file_format.py, .jules/bolt.md
ChecksumWriter.write() accepts bytes or bytearray, buffers data up to a configured limit, flushes buffered bytes to the file and CRC calculation, and finalization flushes pending data before emitting the trailer. The batching note documents the change.

Estimated code review effort: 2 (Simple) | ~10 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: batching file writes in ChecksumWriter for performance.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch bolt/optimize-checksum-writer-997483946065271324

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai

coderabbitai Bot commented Jul 11, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@stffns, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 53 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 517759ab-a303-4ec9-9071-3f76e1e0633f

📥 Commits

Reviewing files that changed from the base of the PR and between 9cf0c65 and d4dc5f4.

📒 Files selected for processing (1)
  • .github/workflows/ci.yml
📝 Walkthrough

Walkthrough

ChecksumWriter now batches small writes in a bytearray, updates CRCs during flushes, writes remaining data during finalisation, and accepts both bytes and bytearray.

Changes

ChecksumWriter buffering

Layer / File(s) Summary
Buffered checksum write path
snapvec/_file_format.py, .jules/bolt.md
ChecksumWriter.write accepts bytes or bytearray, buffers data, flushes CRC and file writes at the configured threshold, and flushes remaining data before emitting the trailer. The learning note documents this batching approach.

Estimated code review effort: 2 (Simple) | ~10 minutes

Poem

I’m a bunny with bytes in a row,
Through a buffer they quietly go.
CRC hops when the flush bells ring,
Fewer writes make the fast files sing.
Thump-thump—finalise seals the spring!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: batching file writes in ChecksumWriter for performance.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch bolt/optimize-checksum-writer-997483946065271324

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces write batching in ChecksumWriter using an internal bytearray buffer to reduce system call overhead and optimize zlib.crc32 updates. The feedback suggests a performance improvement to bypass the buffer entirely when writing large chunks of data, preventing unnecessary in-memory copies and memory spikes.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread snapvec/_file_format.py
Comment on lines +72 to +74
self._buf.extend(data)
if len(self._buf) >= self._max_buf:
self._flush()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

When writing large chunks of data (such as serialized index arrays, which can be tens or hundreds of megabytes), appending them to self._buf via extend() creates an unnecessary in-memory copy of the entire payload. This leads to a significant memory spike and CPU overhead, which contradicts the optimization goals of this PR.

To optimize this, we can bypass the buffer entirely for writes that are already larger than or equal to _max_buf. We first flush any existing buffered data to preserve write ordering, and then directly update the CRC and write the large chunk to the underlying file.

Suggested change
self._buf.extend(data)
if len(self._buf) >= self._max_buf:
self._flush()
if len(data) >= self._max_buf:
self._flush()
self._crc = zlib.crc32(data, self._crc)
self._f.write(data)
else:
self._buf.extend(data)
if len(self._buf) >= self._max_buf:
self._flush()

@coderabbiteu coderabbiteu Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
snapvec/_file_format.py (1)

66-94: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add buffering boundary tests.

Cover exact 64 KiB, 64 KiB + 1, oversized writes, bytearray input, CRC/trailer contents, and repeated finalise() calls.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@snapvec/_file_format.py` around lines 66 - 94, Add tests for
ChecksumWriter.write and finalise covering exact 64 KiB, 64 KiB-plus-one,
oversized writes, and bytearray input; verify buffered output, CRC, and trailer
contents, and assert repeated finalise() calls do not append duplicate trailers.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@snapvec/_file_format.py`:
- Around line 72-75: Update the write method containing self._buf.extend(data)
to flush existing buffered data before handling an input larger than _max_buf,
then write oversized bytes/bytearray data directly or in bounded chunks without
copying the entire payload into _buf. Preserve the return value and normal
buffering behavior for smaller writes.

---

Nitpick comments:
In `@snapvec/_file_format.py`:
- Around line 66-94: Add tests for ChecksumWriter.write and finalise covering
exact 64 KiB, 64 KiB-plus-one, oversized writes, and bytearray input; verify
buffered output, CRC, and trailer contents, and assert repeated finalise() calls
do not append duplicate trailers.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ddadba3f-e3a8-4385-9398-24549b8b8859

📥 Commits

Reviewing files that changed from the base of the PR and between 66cbe33 and 9cf0c65.

📒 Files selected for processing (2)
  • .jules/bolt.md
  • snapvec/_file_format.py

Comment thread snapvec/_file_format.py
Comment on lines +72 to +75
self._buf.extend(data)
if len(self._buf) >= self._max_buf:
self._flush()
return len(data)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Keep _buf bounded for oversized writes.

extend(data) copies the entire input before checking _max_buf, so one large bytes/bytearray can temporarily allocate an arbitrarily large second copy of the payload. Flush existing data first, then write oversized inputs directly or process them in bounded chunks.

Proposed fix
-        self._buf.extend(data)
-        if len(self._buf) >= self._max_buf:
+        data_len = len(data)
+        if data_len >= self._max_buf:
+            self._flush()
+            self._crc = zlib.crc32(data, self._crc)
+            self._f.write(data)
+            return data_len
+        if len(self._buf) + data_len > self._max_buf:
             self._flush()
-        return len(data)
+        self._buf.extend(data)
+        if len(self._buf) == self._max_buf:
+            self._flush()
+        return data_len
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
self._buf.extend(data)
if len(self._buf) >= self._max_buf:
self._flush()
return len(data)
data_len = len(data)
if data_len >= self._max_buf:
self._flush()
self._crc = zlib.crc32(data, self._crc)
self._f.write(data)
return data_len
if len(self._buf) + data_len > self._max_buf:
self._flush()
self._buf.extend(data)
if len(self._buf) == self._max_buf:
self._flush()
return data_len
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@snapvec/_file_format.py` around lines 72 - 75, Update the write method
containing self._buf.extend(data) to flush existing buffered data before
handling an input larger than _max_buf, then write oversized bytes/bytearray
data directly or in bounded chunks without copying the entire payload into _buf.
Preserve the return value and normal buffering behavior for smaller writes.

A recent NumPy release (>=2.5.0) introduced `type` statements in its
stubs (`__init__.pyi`) that are only supported in Python 3.12+. Since
`mypy` is configured to run with `python_version = "3.10"`, it fails
with syntax errors during the CI check. Pinning NumPy avoids the
issue without modifying the project's core configuration files.

Co-authored-by: stffns <70039235+stffns@users.noreply.github.com>

This branch has not been deployed

No deployments
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.

1 participant