Skip to content

Write and read checkpoint text columns without a loop over each value - #1803

Draft
anth-volk wants to merge 10 commits into
mainfrom
claude/checkpoint-text-codec-buffers-55acca
Draft

anth-volk wants to merge 10 commits into
mainfrom
claude/checkpoint-text-codec-buffers-55acca

Conversation

@anth-volk

Copy link
Copy Markdown
Contributor

Tracker task 1.5 · 9 (project "15. US build memory, CPU and run time"). This carries out part B2 of decision 1.5 · 6: no new checkpoint format and no dictionary encoding. Instead, the checkpoint writer and reader build and parse today's bytes for text without a Python loop over each value.

What changes

Text columns, string index values and strata are stored with the object_scalars_v1 encoding:

  • each value is a tag byte (7 for a string) followed by its UTF-8 bytes;
  • the offsets are a leading 0 and then the end of every value, as int64.

Before this change, _encode_object_values and _decode_object_values converted the values one at a time in Python. Now _write_series and _read_series try a conversion without that loop first.

  • Writing pyarrow-backed str and string columns: the column's Arrow chunks are widened to 64-bit offsets and joined. The tag bytes and the UTF-8 bytes are then placed with NumPy masks, each covering about 1 MiB of whole values.
  • Writing object and python-backed columns:
    • A value takes the new path only if its type is exactly str or np.str_, compared by id. Subclasses are excluded because the old code calls each value's own encode(), which a subclass can override.
    • Values are encoded with str.encode through map, 8,192 at a time. Each batch is joined with bytes.join, and the batches are joined once at the end.
    • Arrow is not used for these values. It reads Python strings with PyUnicode_AsUTF8AndSize, which attaches a cached UTF-8 copy to every non-ASCII string for the rest of its life.
  • Reading:
    • The offsets are checked exactly as before.
    • The text is then moved to the front of the payload array that HDF5 filled, dropping each tag byte, about 1 MiB of whole values at a time. The offsets are converted to the text's own offsets in place.
    • Arrow checks UTF-8 and builds the column. The declared dtype, string storage and NA marker are restored as before.

Everything else goes through today's per-value loop, unchanged, and raises the same errors:

  • a column with a missing value, a value that is not a string, or a str subclass;
  • a string with a lone surrogate, or a stored value that is not valid UTF-8;
  • tags other than the string tag;
  • offsets that lie outside the payload (their differences wrap around int64 and pass the boundary check);
  • a declared dtype that is not text;
  • a pyarrow-backed column that pandas refuses to build from one Arrow array.

Unchanged: checkpoint bytes, format versions 2 and 3 (version 3 only when a frame has a nullable boolean column), and every recorded file digest. That covers the US base steps, the QRF donor and recipient files, the ASEC raw-stage checkpoint, the multispine pool and UK stage checkpoints.

Tests

The new file packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py produces its expected bytes and values with today's loop, which is kept as the fallback.

  • Whole frames with pyarrow- and python-backed str and string columns, an object column of strings, string index values and string strata:
    • written and read without calling the loop;
    • a file byte-identical to the loop's;
    • the same loaded frame: values, dtype, string storage, NA marker, index, strata, Python value types, Arrow type and chunk count;
    • the same bytes when the loaded frame is written again;
    • format version 2.
  • Edge cases for every text dtype: empty columns, empty strings, non-ASCII UTF-8 including NUL and non-BMP characters, one value throughout, a 3-million-character string, and two whole encoding batches plus one value.
  • Arrow layouts: two chunks, chunks starting at an offset, chunks built with 32-bit offsets, and an offsets buffer with spare bytes. np.str_ values in an object column.
  • Values that must use the loop: missing values (None, NaN, pd.NA) in every dtype; object integers, floats, bytes and booleans; str subclasses, including ones whose type hashes like str or cannot be hashed; floats whose type cannot be hashed.
  • Errors match the loop's: lone surrogates, invalid UTF-8, malformed offsets, offsets whose differences wrap around, and tags other than the string tag.
  • Side effects and memory:
    • writing leaves the in-memory size of non-ASCII strings unchanged;
    • peak traced memory of writing Python strings is at most the loop's;
    • peak traced memory of reading each conversion path, with and without a missing value, is within 2% of the old reader's.
  • Opt-in test with a payload past 231 bytes** (MICROCOSM_FRAME_CHECKPOINT_LARGE_TEXT_TEST=1, about 4 GB of memory) for pyarrow str and object columns. Skipped in CI.

What I ran, under Python 3.14.6, pandas 3.0.3, pyarrow 25.0.0, numpy 2.4.6 and h5py 3.16.0:

  • the new test file, which holds only tests this PR adds: 140 passed, 2 skipped;
  • both opt-in tests with a payload past 2**31 bytes, by node ID: passed.

I did not run the existing test_frame_checkpoint.py or any other suite; CI runs them. Each round of review fixes was committed as failing tests first, then the change.

Timings

The timing script uses a synthetic copy of the 15 text series of one post-clone US base checkpoint, built as in the 1.5 · 6 timing script: 9.85 million values, with the real row counts, distinct counts and string lengths. Best of 3, on a 10-core Mac at load average 14–17.

  • Converting the text:
    • writing: 8.78 s → 0.59 s;
    • reading: 4.89 s → 0.39 s.
  • A whole 253 MB checkpoint of those series (write_frame_checkpoint / load_frame_checkpoint; files byte-identical):
    • writing: 7.76 s → 1.02 s;
    • loading: 6.67 s → 1.86 s.

An earlier revision timed at load 7–8 ran at about 2.5 times these speeds: 3.13 → 0.28 s to write and 2.09 → 0.14 s to read the text. The ratios are similar.

Peak memory with tracemalloc, compared side by side with the old code:

  • Writing Python strings: 0.96–1.00 times the old peak. Examples: one 64 MiB string; 8,000 strings of 8 KiB; 300,000 strings of 7 characters.
  • Reading object and python-backed text: 1.00–1.01 times, at 1 million short values and at 200,000 strings of 200 characters. Reads that use the loop: 1.00 times.
  • pyarrow-backed columns: both directions hold the text in NumPy arrays instead of Python strings plus an Arrow copy.

Adversarial review: three rounds, each fixed with failing tests first

  • Round 1:
    • a str subclass overriding encode() got different bytes;
    • pa.array attached cached UTF-8 copies to the frame's non-ASCII strings;
    • an Arrow offsets buffer with spare bytes made the write raise;
    • offsets wrapping around int64 raised IndexError where the old code raised ValueError.
  • Round 2:
    • the type check hashed types, so a metaclass could pass it or make it raise;
    • encoding short Python strings took about six times the loop's peak memory;
    • pandas 2.2 may refuse to build a pyarrow-backed column from one Arrow array of 2 GiB or more.
  • Round 3: no input with different bytes, values or errors. Its findings:
    • reads held a second copy of the text, and fallback reads held two copies of the payload;
    • long-string writes peaked at 1.5 times the old code;
    • no test compared bytes past one encoding batch;
    • some docstrings did not match the code.
  • Not used: pyarrow.compute.binary_slice. Under pyarrow 25.0.0 it fails with "Negative buffer resize" on ordinary large-binary arrays.

Not covered, and things noticed outside this change

  • No real checkpoint was checked. That needs a download from Modal, which needs Anthony's approval, so the tests use synthetic data. On the 3 November pre-clone checkpoint, the 1.5 · 6 prototype wrote byte-identical offsets and payloads for the six pyarrow-backed columns.
  • The base bit-equivalence test (test_us_puf_support_base_equivalence.py) was not run. Task 1.5 · 8, which would have made it runnable at reduced size, is cancelled.
  • pandas 2.3 is allowed by microcosm-frame's pandas>=2.3, but was not tested. The lock pins 3.0.3, and the CI and Modal images sync the lock. pyarrow is a dependency of microcosm-build (pyarrow>=15), and every pyarrow call used exists in 15.
  • Behaviour that exists before this change and is unchanged by it:
    • An object-dtype index of strings is recorded and restored as a pyarrow-backed str index. Under pandas 3, pd.Series(index.array) infers str, and that conversion attaches cached UTF-8 copies to the index's non-ASCII strings.
    • _check_object_offsets compares offset differences, which wrap around int64 for offsets far outside the payload.

Environment variables

None in production code. MICROCOSM_FRAME_CHECKPOINT_LARGE_TEXT_TEST only lets the opt-in large-payload test run; nothing provides it, so CI skips that test.

🤖 Generated with Claude Code

anth-volk and others added 10 commits November 27, 2026 23:15
Add tests that compare the checkpoint writer and reader for text columns
with today's per-value loop (_encode_object_values and
_decode_object_values), which stays as the fallback:

- a frame with pyarrow- and python-backed str and string columns, an
  object column of strings, string index values and string strata writes
  and reads without calling the per-value loop, writes the same file as
  the loop, and loads the same frame (values, dtypes, string storage, NA
  marker, Arrow type and chunk count);
- empty columns, empty strings, non-ASCII UTF-8, one value throughout and
  a very long string, for each text dtype; multi-chunk, sliced and 32-bit
  offset Arrow layouts; NumPy strings in an object column;
- columns with a missing or non-string value still go through the loop,
  and unencodable strings, invalid UTF-8 and malformed offsets raise the
  loop's errors;
- an opt-in test (MICROCOSM_FRAME_CHECKPOINT_LARGE_TEXT_TEST=1) for a
  payload past 2**31 bytes.

The tests that need the new conversion fail until it exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
write_frame_checkpoint and load_frame_checkpoint converted every text
value with a Python loop (_encode_object_values, _decode_object_values).
A text column, string index or strata whose values are all strings, none
missing, now goes through NumPy and Arrow buffers instead, producing and
parsing the same object_scalars_v1 bytes: a tag byte 7 before each
value's UTF-8 bytes and one int64 offset per value.

- Writing takes the column's values as one Arrow large-string array
  (64-bit offsets), from the stored chunks for pyarrow-backed str and
  string columns or from the object values for python-backed and object
  columns, and places the tag bytes and the UTF-8 bytes with NumPy.
- Reading checks the offsets as before, checks every tag is the string
  tag, removes the tag bytes with NumPy, validates UTF-8 with Arrow and
  restores the declared dtype, string storage and NA marker.
- A column with a missing value, a value that is not a string, a value
  Arrow refuses (a lone surrogate, invalid UTF-8) or a declared dtype that
  is not text goes through today's loop, which raises today's errors.

Format versions, checkpoint bytes and recorded digests are unchanged.
pyarrow.compute.binary_slice is not used: under pyarrow 25.0.0 it fails
with "Negative buffer resize" on ordinary large-binary arrays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add failing tests for what the first adversarial review found:

- a str subclass that overrides encode() is written with the bytes its
  own encode() returns, as the per-value loop writes it;
- writing object and python-backed string columns leaves the size of
  their non-ASCII str objects unchanged (pa.array attaches a cached
  UTF-8 copy to each one);
- a pyarrow chunk whose offsets buffer has spare bytes beyond a whole
  number of int64 values is written like any other;
- offsets whose differences overflow int64 raise the loop's error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Object and python-backed string columns: only exact str and np.str_
  values take the fast path, since the per-value loop calls each value's
  own encode(), which a subclass can override. Their bytes now come from
  str.encode through map and one bytes.join, not pa.array: Arrow reads a
  str with PyUnicode_AsUTF8AndSize, which attaches a cached UTF-8 copy to
  every non-ASCII str it reads for the rest of that str's life, so
  writing a checkpoint made a frame's non-ASCII strings larger.
- pyarrow-backed columns: read exactly the array's own offsets from the
  Arrow offsets buffer, which may hold spare bytes beyond a whole number
  of int64 values.
- Reading: offsets outside the payload, which pass the boundary check
  when their differences overflow int64, go to the per-value loop, which
  raises the same error as before; the byte mask is freed before the
  strings are built.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add failing tests for what the second adversarial review found:

- a str subclass whose type hashes like str and compares equal to it,
  and one whose type cannot be hashed, are written by the per-value
  loop; an object column of floats whose type cannot be hashed is
  written at all;
- encoding short strings from an object or python-backed column peaks
  at no more traced memory than the per-value loop (today about six
  times as much: one bytes object per value plus bytes.join's buffer
  table);
- when pandas refuses to build a pyarrow-backed column from one Arrow
  array, as pandas 2.2 does for 2 GiB of text, the reader uses the loop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Python strings: compare each value's type with str and np.str_ by
  identity (id), not through a set. A metaclass can make another type
  hash like str and compare equal to it, which let a str subclass with
  its own encode() through, or make a type unhashable, which made the
  write raise even for an object column of floats.
- Python strings: encode 8,192 values at a time into one bytearray and
  compute the offsets in place. Encoding every value at once held one
  bytes object per value and bytes.join's buffer table, about six times
  the per-value loop's peak memory for short strings. The peak is now
  below the loop's: 31.9 MiB against 47.3 MiB for 2 million strings of 7
  characters, 46.2 against 79.9 MiB for 200,000 strings of 200.
- Reading pyarrow-backed columns: if pandas refuses to build the column
  from one Arrow array (pandas 2.2 casts it to 32-bit offsets, which
  refuses 2 GiB of text), use the per-value loop.
- Tests: build the object arrays of values with unhashable types element
  by element, since np.asarray keys a dict by each value's type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add tests for what the third adversarial review found:

- byte comparison of Python-string columns across two whole encoding
  batches and one value more; no earlier test passed one batch, so a
  version that put every batch's lengths in the first batch's place
  passed them all;
- peak traced memory of writing Python strings against the per-value
  loop, now also for 1,000 strings of 16 KiB and 20,000 of 400 characters
  (a batch's encoded values, their join and the bytearray were held at
  once, about 1.5 times the loop's peak);
- peak traced memory of reading every text dtype, with and without a
  missing value, against the reader before the change (the new reader
  held the payload, a second copy of the text and a byte mask; its
  fallback held the payload array and its bytes copy together);
- the frame case with an object index is relabelled: the writer stores
  an object index of strings as a pyarrow-backed str index, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Reading: remove the tag bytes by moving the text to the front of the
  payload array in place, about 1 MiB of whole values at a time, and turn
  the offsets into the text's own offsets in place, so no second copy of
  the text, payload-sized mask or second offsets array is held while the
  values are built. When a value is not valid UTF-8, or pandas refuses
  the Arrow array, both arrays are read again for the per-value loop.
  Before the loop, the payload array is dropped once its bytes copy
  exists, as before the change.
- Writing Python strings: refuse non-string columns with infer_dtype
  before the type scan; drop each batch's encoded values before keeping
  its join, and join the batches once at the end (a single batch is used
  as it is) instead of appending to a bytearray.
- Writing pyarrow-backed columns: place the text with masks covering
  about 1 MiB of whole values at a time.
- Docstrings say which columns use Arrow buffers and which str.encode,
  and every reason the reader leaves a column to the per-value loop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The reader now rewrites the offsets and payload HDF5 fills in place,
  and the Python-string encoder's payload is read-only, so the test with
  a payload past 2**31 bytes passes writable copies, as HDF5 would.
- The memory tests take one dtype for each conversion path (str and
  string storage share one), and explain why each case is large against
  the fixed temporaries of one encoding batch or one step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.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