Skip to content

⚡ Bolt: Batch ChecksumWriter writes for faster saves - #160

Open
stffns wants to merge 2 commits into
mainfrom
bolt-batch-checksumwriter-writes-1360409113642053305
Open

stffns wants to merge 2 commits into
mainfrom
bolt-batch-checksumwriter-writes-1360409113642053305

Conversation

@stffns

@stffns stffns commented Jul 15, 2026 •

Copy link
Copy Markdown
Owner

💡 What: Added a bytearray buffer (self._buf) bounded to 65536 bytes inside ChecksumWriter. Small .write() calls append to this buffer. The buffer is flushed to disk (and zlib.crc32 updated) once it hits the limit. Writes >= the buffer limit bypass the buffer entirely.
🎯 Why: Index saving routines repeatedly call ChecksumWriter.write for every string ID in the dataset, which caused extreme iteration overhead due to repeated zlib.crc32 updates and frequent disk syscalls.
📊 Impact: Expected to speed up index serializations (e.g. idx.save()) by ~1.3-1.4x depending on the number of IDs and platform properties.
🔬 Measurement: Verify using an ad-hoc timing script writing ~100k short strings, or observe speedups natively by persisting heavily populated indices.


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

Summary by CodeRabbit

  • Performance
    • Improved file-writing efficiency by batching small writes, reducing overhead during data generation and storage.
    • Added support for writing both byte strings and mutable byte buffers.
  • Reliability
    • Ensured buffered data is flushed before final checksums are written, preserving file integrity.

…call overhead

Batches data writes up to 64KB before applying crc32 and flushing to the underlying
disk, significantly improving performance when writing high volumes of small strings
such as vector IDs during index persistence. Large data chunks are bypassed entirely
and written straight to disk, preventing large unnecessary allocations.

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 15, 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 15, 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: 52 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: 876b0188-4c76-4b92-b25e-1c3e2e5611a4

📥 Commits

Reviewing files that changed from the base of the PR and between d309993 and 6263490.

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

Walkthrough

ChecksumWriter now batches small bytes and bytearray writes, updates CRC32 during flushes, and flushes remaining data before writing the final CRC trailer. The knowledge log records related NumPy and filesystem batching techniques.

Changes

Checksum write buffering

Layer / File(s) Summary
Buffered ChecksumWriter write path
snapvec/_file_format.py, .jules/bolt.md
ChecksumWriter.write accepts bytes or bytearray, buffers small payloads, flushes them for CRC32 and file output, and preserves finalisation behavior. The knowledge log adds related performance notes.

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

Poem

A rabbit packs bytes in a soft little queue,
Then flushes them neatly when work is due.
CRC hops along, the trailer shines bright,
Small writes now travel in batches of light.
“Thump-thump!” says the burrow—everything’s right!

🚥 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 accurately reflects the main change: batching ChecksumWriter writes to improve save 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-batch-checksumwriter-writes-1360409113642053305

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 optimizes the ChecksumWriter in snapvec/_file_format.py by introducing a 64KB buffer (bytearray) to batch small writes, reducing syscall and CRC calculation overhead. A corresponding entry documenting this optimization was also added to .jules/bolt.md. The review feedback suggests using the modern union type syntax bytes | bytearray instead of importing and using typing.Union 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
from pathlib import Path
from types import TracebackType
from typing import IO, Callable
from typing import IO, Callable, Union

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 uses from __future__ import annotations and uses the modern | operator for union types elsewhere (e.g., str | Path), we can use bytes | bytearray instead of Union[bytes, bytearray]. This allows us to avoid importing Union from typing entirely, keeping the imports clean and consistent with the rest of the codebase.

Suggested change
from typing import IO, Callable, Union
from typing import IO, Callable

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

def write(self, data: bytes) -> int:
def write(self, data: 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

Use the modern | operator for union types instead of Union to maintain consistency with the rest of the file's type annotations.

Suggested change
def write(self, data: 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 5: Add a blank line immediately after the “2024-05-23 - Batch file writes
in Python” heading in the changelog section of bolt.md, before its body content,
to satisfy Markdown heading-spacing requirements.

In `@snapvec/_file_format.py`:
- Around line 85-89: Rename the wrapper’s flush method to _flush to preserve the
class’s public API contract and avoid implying an OS-level flush. Update every
internal self.flush() call, including those in the write and close-related
paths, to use self._flush() instead.
- Line 67: Update the write method’s data annotation from Union[bytes,
bytearray] to bytes | bytearray, and remove the now-unused Union import from the
typing imports.
🪄 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: 5b8a1096-abfc-4f99-90b9-e089942b8c17

📥 Commits

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

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

Comment thread .jules/bolt.md
**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-05-23 - Batch file writes in Python

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 | 💤 Low value

Add a blank line below the heading.

To comply with standard markdown formatting (MD022) and resolve the static analysis warning, add a blank line between the heading and the body text.

♻️ Proposed fix
 ## 2024-05-23 - Batch file writes in Python
+
 **Learning:** Batching multiple small file writes into a single `bytearray` before writing to disk and updating checksums (e.g. `zlib.crc32`) reduces overhead significantly (~1.4x speedup for saving models with many strings), but care must be taken to flush the buffer and skip batching for large blocks to avoid unbounded memory allocation.
🧰 Tools
🪛 markdownlint-cli2 (0.23.0)

[warning] 5-5: 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 5, Add a blank line immediately after the “2024-05-23
- Batch file writes in Python” heading in the changelog section of bolt.md,
before its body content, to satisfy Markdown heading-spacing requirements.

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

def write(self, data: bytes) -> int:
def write(self, data: 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.

📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use the | operator for type unions.

This file already uses modern Python 3.10+ union syntax (type[BaseException] | None on line 106). For consistency, use bytes | bytearray here and remove the newly added Union from the typing imports on line 34.

♻️ Proposed fix
-    def write(self, data: Union[bytes, bytearray]) -> int:
+    def write(self, data: bytes | bytearray) -> int:
📝 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 write(self, data: Union[bytes, bytearray]) -> int:
def write(self, data: bytes | bytearray) -> int:
🤖 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 67, Update the write method’s data
annotation from Union[bytes, bytearray] to bytes | bytearray, and remove the
now-unused Union import from the typing imports.

Comment thread snapvec/_file_format.py
Comment on lines +85 to +89
def flush(self) -> None:
if self._buf:
self._crc = zlib.crc32(self._buf, self._crc)
self._f.write(self._buf)
self._buf.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.

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

Make flush a private method.

The class docstring explicitly states: "The wrapper exposes only write; callers that need flush / close use the underlying file directly".

Exposing flush() as a public method violates this contract. Furthermore, because this flush only writes to the underlying Python file object and does not call self._f.flush(), users calling it might falsely believe they are flushing data all the way to the OS/disk. Rename this to _flush to hide it from the public API.

♻️ Proposed fix
-    def flush(self) -> None:
+    def _flush(self) -> None:
         if self._buf:
             self._crc = zlib.crc32(self._buf, self._crc)
             self._f.write(self._buf)
             self._buf.clear()

(Note: Be sure to also update the internal self.flush() calls on lines 75, 82, and 96 to self._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._buf:
self._crc = zlib.crc32(self._buf, self._crc)
self._f.write(self._buf)
self._buf.clear()
def _flush(self) -> None:
if self._buf:
self._crc = zlib.crc32(self._buf, self._crc)
self._f.write(self._buf)
self._buf.clear()
🤖 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 85 - 89, Rename the wrapper’s flush
method to _flush to preserve the class’s public API contract and avoid implying
an OS-level flush. Update every internal self.flush() call, including those in
the write and close-related paths, to use self._flush() instead.

…call overhead

Batches data writes up to 64KB before applying crc32 and flushing to the underlying
disk, significantly improving performance when writing high volumes of small strings
such as vector IDs during index persistence. Large data chunks are bypassed entirely
and written straight to disk, preventing large unnecessary allocations. Pin numpy < 2.5.0 in CI to fix mypy parsing issues.

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