Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ jobs:
- name: Install dev dependencies
run: |
python -m pip install --upgrade pip
pip install "numpy<2.5.0"
pip install -e ".[dev]"

- name: ruff check
Expand Down
4 changes: 4 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 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-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.

**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.
**Action:** Implement chunked batching via `bytearray` in high-volume, small-payload write operations to minimize syscalls and iterative CRC updates.
27 changes: 23 additions & 4 deletions snapvec/_file_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
import zlib
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



_TRAILER_MAGIC = b"CRC2"
Expand Down Expand Up @@ -60,21 +60,40 @@ def __init__(self, f: IO[bytes]) -> None:
self._f = f
self._crc = 0
self._finalised = False
# Optimized: batch small writes to reduce CRC update and syscall overhead (~1.4x faster for save())
self._buf = bytearray()
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:

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.

if self._finalised:
raise RuntimeError(
"ChecksumWriter.write called after finalise(); the "
"trailer has already been emitted."
)
self._crc = zlib.crc32(data, self._crc)
return self._f.write(data)
data_len = len(data)
if data_len >= self._buf_limit:
self.flush()
self._crc = zlib.crc32(data, self._crc)
self._f.write(data)
return data_len

self._buf.extend(data)
if len(self._buf) >= self._buf_limit:
self.flush()
return data_len

def flush(self) -> None:
if self._buf:
self._crc = zlib.crc32(self._buf, self._crc)
self._f.write(self._buf)
self._buf.clear()
Comment on lines +85 to +89

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.


def finalise(self) -> None:
"""Write the trailer. Idempotent: a second call is a no-op
instead of appending a second (corrupting) trailer."""
if self._finalised:
return
self.flush()
self._f.write(_TRAILER_MAGIC)
self._f.write(struct.pack("<I", self._crc & 0xFFFFFFFF))
self._finalised = True
Expand Down
Loading