Skip to content

⚡ Bolt: Optimize ChecksumWriter using buffered writes - #163

Open
stffns wants to merge 2 commits into
mainfrom
perf/checksum-writer-batching-5200886764433880020
Open

⚡ Bolt: Optimize ChecksumWriter using buffered writes#163
stffns wants to merge 2 commits into
mainfrom
perf/checksum-writer-batching-5200886764433880020

Conversation

@stffns

@stffns stffns commented Jul 18, 2026

Copy link
Copy Markdown
Owner

💡 What: Optimized ChecksumWriter in snapvec/_file_format.py by introducing a bytearray buffer for aggregating small writes before flushing them to disk.
🎯 Why: When serializing objects in small chunks, ChecksumWriter made frequent calls to zlib.crc32 and system write operations, leading to significant overhead during file saves.
📊 Impact: This change speeds up saving indices (approximately 1.4x faster) by batching data and minimizing frequent system calls and crc calculations.
🔬 Measurement: Run the internal saving benchmarks or profile the save method on large indexes; observe fewer calls to zlib.crc32 and faster overall serialization time.


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

Summary by CodeRabbit

  • Performance
    • Improved file-writing performance by buffering frequent small writes.
    • Large writes continue to use a faster direct-write path.
    • Ensured checksum calculation and file output remain consistent.
  • Compatibility
    • Writing accepts both bytes and bytearray data.
    • Finalizing remains safe to call repeatedly without duplicating output.

By buffering small writes into a `bytearray`, we significantly reduce system call overhead and the frequency of `zlib.crc32` recalculations in `ChecksumWriter`. This results in a measurable speedup for index saving operations. Large chunks are sent directly to disk without intermediate allocation overhead.

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.

@cursor

cursor Bot commented Jul 18, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@coderabbitai

coderabbitai Bot commented Jul 18, 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: 51 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: 719bc79d-629c-43fc-97c6-d3b96856c7cd

📥 Commits

Reviewing files that changed from the base of the PR and between 7424173 and aa7465c.

📒 Files selected for processing (2)
  • .github/workflows/ci.yml
  • .jules/bolt.md
📝 Walkthrough

Walkthrough

ChecksumWriter now batches small writes in a bounded buffer, updates CRC32 during flushes, bypasses buffering for large writes, and flushes before writing the trailer. The related optimization guidance was documented.

Changes

ChecksumWriter buffering

Layer / File(s) Summary
Buffered writes and finalisation
snapvec/_file_format.py, .jules/bolt.md
ChecksumWriter accepts bytes and bytearray, buffers small payloads, directly handles large payloads, maintains CRC32 ordering, flushes before trailer emission, and documents the batching behavior.

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

Possibly related PRs

  • stffns/snapvec#160: Updates ChecksumWriter with the same buffering, CRC32, finalisation, typing, and batching guidance changes.

Poem

I’m a rabbit with a buffer so neat,
Small writes hop in on nimble feet.
Big writes dash straight through,
CRC trails faithfully too,
Then the final stamp makes the stream complete!

🚥 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 describes the main change: buffering ChecksumWriter writes to improve 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 perf/checksum-writer-batching-5200886764433880020

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 implements write buffering in ChecksumWriter using a bytearray to batch small writes, reducing system calls and CRC32 overhead, and documents this optimization. The review feedback recommends removing the redundant typing import and using the | operator for the union type annotation in the write method to maintain consistency with the rest of the codebase.

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

import os
import struct
import typing

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

This import is redundant because IO and Callable are already imported from typing on line 35, and the union type annotation on line 67 can be simplified to bytes | bytearray using the | operator.

Comment thread snapvec/_file_format.py
self._buf_size = 65536

def write(self, data: bytes) -> int:
def write(self, data: typing.Union[bytes, bytearray]) -> int:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Since this file already uses the | operator for union types (e.g., str | Path and BaseException | None) and has from __future__ import annotations enabled, we should use bytes | bytearray instead of typing.Union[bytes, bytearray] to maintain consistency with the rest of the codebase.

Suggested change
def write(self, data: typing.Union[bytes, bytearray]) -> int:
def write(self, data: bytes | bytearray) -> int:

@coderabbitai coderabbitai 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: 3

🤖 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 @.jules/bolt.md:
- Line 4: Add blank lines immediately before and after the “2024-07-18 -
Batching small writes with bytearray in ChecksumWriter” Markdown heading in
.jules/bolt.md, preserving the heading text and surrounding content.

In `@snapvec/_file_format.py`:
- Line 31: Replace the remaining typing.Union annotations in the relevant
definitions with native PEP 604 union syntax using |, consistent with the
existing __exit__ signature, then remove the now-unused typing import.
- Around line 87-91: Update _file_format.py’s flush method to always call the
underlying file’s flush after draining self._buffer, ensuring buffered data is
written before the file is flushed. Revise the class docstring guidance to
direct callers to flush the wrapper rather than bypassing it.
🪄 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: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 9c23cddd-016e-4ab2-81b1-1093fc370320

📥 Commits

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

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

Comment thread .jules/bolt.md
## 2024-05-18 - Fast row-wise Euclidean norm in pure NumPy
**Learning:** In performance-critical paths, computing the batch norm of a 2D array via `np.linalg.norm(arr, axis=1)` is relatively slow. Using `np.sqrt(np.einsum('ij,ij->i', arr, arr))` is significantly faster (~4x speedup on a laptop CPU for typical batch sizes). If `keepdims=True` behavior is needed, appending `[:, np.newaxis]` matches the original shape seamlessly.
**Action:** Always prefer `np.sqrt(np.einsum('ij,ij->i', arr, arr))` over `np.linalg.norm(arr, axis=1)` when computing row-wise vector norms in NumPy to eliminate dispatch overhead and improve execution speed.
## 2024-07-18 - Batching small writes with bytearray in ChecksumWriter

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Add blank lines around heading.

As per static analysis hints, headings should be surrounded by blank lines. Without these blank lines, some Markdown parsers may fail to render this line as a heading, breaking the document structure.

🛠️ Proposed fix
+
 ## 2024-07-18 - Batching small writes with bytearray in ChecksumWriter
+
📝 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
## 2024-07-18 - Batching small writes with bytearray in ChecksumWriter
## 2024-07-18 - Batching small writes with bytearray in ChecksumWriter
🧰 Tools
🪛 markdownlint-cli2 (0.23.0)

[warning] 4-4: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Above

(MD022, blanks-around-headings)


[warning] 4-4: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)

🤖 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 @.jules/bolt.md at line 4, Add blank lines immediately before and after the
“2024-07-18 - Batching small writes with bytearray in ChecksumWriter” Markdown
heading in .jules/bolt.md, preserving the heading text and surrounding content.

Source: Linters/SAST tools

Comment thread snapvec/_file_format.py

import os
import struct
import typing

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use native union syntax.

Since this file already utilizes the PEP 604 union operator | (as seen in the __exit__ method signature), using typing.Union here introduces mixed styling. Adopting the native union operator ensures consistency and allows you to remove the typing import.

♻️ Proposed fixes

Remove the unnecessary import:

-import typing

Use the native union syntax:

-    def write(self, data: typing.Union[bytes, bytearray]) -> int:
+    def write(self, data: bytes | bytearray) -> int:

Also applies to: 67-67

🤖 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` at line 31, Replace the remaining typing.Union
annotations in the relevant definitions with native PEP 604 union syntax using
|, consistent with the existing __exit__ signature, then remove the now-unused
typing import.

Comment thread snapvec/_file_format.py
Comment on lines +87 to +91
def flush(self) -> None:
if self._buffer:
self._crc = zlib.crc32(self._buffer, self._crc)
self._f.write(self._buffer)
self._buffer.clear()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Cascade flush() to the underlying file.

The introduction of buffering invalidates the contract described in the class docstring (lines 54-58), which advises callers to "use the underlying file directly" to flush. If a caller follows this advice and bypasses the wrapper, any data still in self._buffer will remain unflushed and unwritten, potentially causing data loss.

To maintain expected file-like behavior and ensure data integrity, cascade the wrapper's flush() operation to the underlying file. Additionally, consider updating the docstring to clarify that callers must now flush the wrapper itself.

🛠️ Proposed fix
     def flush(self) -> None:
         if self._buffer:
             self._crc = zlib.crc32(self._buffer, self._crc)
             self._f.write(self._buffer)
             self._buffer.clear()
+        self._f.flush()
📝 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
def flush(self) -> None:
if self._buffer:
self._crc = zlib.crc32(self._buffer, self._crc)
self._f.write(self._buffer)
self._buffer.clear()
def flush(self) -> None:
if self._buffer:
self._crc = zlib.crc32(self._buffer, self._crc)
self._f.write(self._buffer)
self._buffer.clear()
self._f.flush()
🤖 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 87 - 91, Update _file_format.py’s flush
method to always call the underlying file’s flush after draining self._buffer,
ensuring buffered data is written before the file is flushed. Revise the class
docstring guidance to direct callers to flush the wrapper rather than bypassing
it.

- Buffers small file writes in `ChecksumWriter` via `bytearray` to reduce system call overhead and `zlib.crc32` recalculations.
- Fixes CI pipeline by pinning `numpy<2.5.0` to resolve `mypy` type statement syntax errors related to Python 3.12 syntax being used in NumPy 2.5 type stubs while the project targets Python 3.10.

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