From d6618a3f802aed03dd6384468b7a1f787632782f Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:15:00 +0400 Subject: [PATCH 01/10] Test checkpoint text conversion without a loop over each value 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 --- .../test_frame_checkpoint_text_columns.py | 621 ++++++++++++++++++ 1 file changed, 621 insertions(+) create mode 100644 packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py diff --git a/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py new file mode 100644 index 0000000000..274f0546de --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py @@ -0,0 +1,621 @@ +"""Text columns in frame checkpoints, against today's per-value loop. + +A checkpoint stores text with the ``object_scalars_v1`` encoding: for each +value, one tag byte (7 for a string) followed by the value's UTF-8 bytes, and +one int64 offset per value. ``_encode_object_values`` and +``_decode_object_values`` convert one value at a time. They stay as the +fallback for a column with a missing value or a value that is not a string, +and these tests call them to produce the expected bytes and values. +""" + +from __future__ import annotations + +import hashlib +import json +import os +from collections.abc import Callable, Iterator +from pathlib import Path + +import numpy as np +import pandas as pd +import pyarrow as pa +import pytest + +import microcosm.build.frame_checkpoint as frame_checkpoint_module +from microcosm.build.frame_checkpoint import ( + load_frame_checkpoint, + write_frame_checkpoint, +) +from microcosm.frame import EntitySchema, Frame, WeightKind, Weights + +h5py = pytest.importorskip("h5py") + +PYARROW_STR = pd.StringDtype(storage="pyarrow", na_value=np.nan) +PYARROW_STRING = pd.StringDtype(storage="pyarrow", na_value=pd.NA) +PYTHON_STR = pd.StringDtype(storage="python", na_value=np.nan) +PYTHON_STRING = pd.StringDtype(storage="python", na_value=pd.NA) +TEXT_DTYPES: dict[str, pd.StringDtype | str] = { + "pyarrow_str": PYARROW_STR, + "pyarrow_string": PYARROW_STRING, + "python_str": PYTHON_STR, + "python_string": PYTHON_STRING, + "object": "object", +} + +# Today's per-value loop, held before any test replaces the module attributes. +PER_VALUE_ENCODE = frame_checkpoint_module._encode_object_values +PER_VALUE_DECODE = frame_checkpoint_module._decode_object_values + +_PERSON_TEXT = ["alpha", "", "é中😀", "alpha", "x" * 70_000] + + +def _text_frame( + *, person_index_dtype: pd.StringDtype | str, strata_dtype: pd.StringDtype | str +) -> Frame: + """A frame with text in every place a checkpoint stores it, none missing. + + Persons are keyed by string index values of ``person_index_dtype``, and + households by an object index of strings. The person table holds one + text column per string dtype plus an object column of strings, and the + strata are strings of ``strata_dtype``. + """ + + person_index = pd.Index( + ["p-0", "p-1", "p-2", "p-3", "p-4"], + dtype=person_index_dtype, + name="person_key", + ) + person = pd.DataFrame( + { + "person_id": np.arange(5, dtype=np.int64), + "person_household_id": np.asarray([10, 10, 20, 20, 20], dtype=np.int64), + **{ + f"label_{dtype_name}": pd.Series( + _PERSON_TEXT, index=person_index, dtype=dtype + ) + for dtype_name, dtype in TEXT_DTYPES.items() + }, + }, + index=person_index, + ) + household_index = pd.Index(["h-10", "h-20"], dtype=object, name="household_key") + household = pd.DataFrame( + { + "household_id": np.asarray([10, 20], dtype=np.int64), + "tenure_type": pd.Series( + ["OWNED", "RENTED"], index=household_index, dtype=PYARROW_STR + ), + }, + index=household_index, + ) + strata = pd.Series( + ["asec", "asec", "puf", "puf", "acs"], + index=person_index, + name="stratum", + dtype=strata_dtype, + ) + return Frame( + {"person": person, "household": household}, + EntitySchema(group_entities=("household",)), + {"household": Weights(np.asarray([1.0, 2.0]), WeightKind.DESIGN)}, + strata, + ) + + +_FRAME_CASES = { + "pyarrow str index, object strata": { + "person_index_dtype": PYARROW_STR, + "strata_dtype": "object", + }, + "python string index, pyarrow str strata": { + "person_index_dtype": PYTHON_STRING, + "strata_dtype": PYARROW_STR, + }, + "object index, python str strata": { + "person_index_dtype": "object", + "strata_dtype": PYTHON_STR, + }, +} + + +@pytest.fixture(params=list(_FRAME_CASES), ids=list(_FRAME_CASES)) +def text_frame(request: pytest.FixtureRequest) -> Frame: + return _text_frame(**_FRAME_CASES[request.param]) + + +def _refuse_per_value_loop(monkeypatch: pytest.MonkeyPatch) -> None: + def refuse(*_arguments: object, **_keywords: object) -> None: + raise AssertionError("A text column went through the per-value loop.") + + monkeypatch.setattr(frame_checkpoint_module, "_encode_object_values", refuse) + monkeypatch.setattr(frame_checkpoint_module, "_decode_object_values", refuse) + + +def _use_only_per_value_loop(monkeypatch: pytest.MonkeyPatch) -> None: + """Send every text column through today's loop, as before the change.""" + + def no_conversion(*_arguments: object, **_keywords: object) -> None: + return None + + monkeypatch.setattr(frame_checkpoint_module, "_encode_string_values", no_conversion) + monkeypatch.setattr(frame_checkpoint_module, "_decode_string_values", no_conversion) + + +class _LoopCalls: + """Counts the values each per-value loop converts, then runs that loop.""" + + def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: + self.encoded: list[int] = [] + self.decoded: list[int] = [] + + def counting_encode(values: np.ndarray) -> tuple[np.ndarray, bytes]: + self.encoded.append(len(values)) + return PER_VALUE_ENCODE(values) + + def counting_decode( + offsets: np.ndarray, payload: bytes, *, path: Path, label: str + ) -> np.ndarray: + self.decoded.append(len(offsets) - 1) + return PER_VALUE_DECODE(offsets, payload, path=path, label=label) + + monkeypatch.setattr( + frame_checkpoint_module, "_encode_object_values", counting_encode + ) + monkeypatch.setattr( + frame_checkpoint_module, "_decode_object_values", counting_decode + ) + + +def _metadata(path: Path) -> dict[str, object]: + with h5py.File(path, mode="r") as h5: + raw = np.asarray(h5["_populace_frame_checkpoint/metadata_json"]).tobytes() + return json.loads(raw.decode("utf-8")) + + +def _object_encoded_series( + frame: Frame, metadata: dict[str, object] +) -> Iterator[tuple[str, pd.Series]]: + """Each object-encoded series of ``frame`` with its HDF5 group path.""" + + tables = dict(frame_checkpoint_module._frame_tables(frame)) + for table_position, table_spec in enumerate(metadata["tables"]): + table = tables[table_spec["name"]] + table_path = f"_populace_frame_checkpoint/tables/t{table_position:05d}" + index_spec = table_spec["index"] + if index_spec.get("encoding") == "object_scalars_v1": + yield f"{table_path}/index", pd.Series(table.index.array, copy=False) + for column_position, column_spec in enumerate(table_spec["columns"]): + if column_spec["encoding"] == "object_scalars_v1": + yield ( + f"{table_path}/columns/c{column_position:05d}", + table[column_spec["name"]], + ) + if metadata["strata"]["encoding"] == "object_scalars_v1": + yield "_populace_frame_checkpoint/strata", frame.strata + + +def _assert_same_text_storage( + actual: pd.Series | pd.Index, expected: pd.Series | pd.Index, label: str +) -> None: + """Same dtype, string storage, NA marker, Arrow layout and value types.""" + + assert actual.dtype == expected.dtype, label + if isinstance(expected.dtype, pd.StringDtype): + assert actual.dtype.storage == expected.dtype.storage, label + assert (actual.dtype.na_value is pd.NA) == (expected.dtype.na_value is pd.NA), ( + label + ) + if isinstance(expected.dtype, pd.StringDtype) and ( + expected.dtype.storage == "pyarrow" + ): + actual_chunks = actual.array.__arrow_array__() + expected_chunks = expected.array.__arrow_array__() + assert actual_chunks.type == expected_chunks.type, label + assert actual_chunks.num_chunks == expected_chunks.num_chunks, label + elif expected.dtype == object or isinstance(expected.dtype, pd.StringDtype): + actual_types = [type(value) for value in actual.to_numpy(dtype=object)] + expected_types = [type(value) for value in expected.to_numpy(dtype=object)] + assert actual_types == expected_types, label + + +def _assert_same_frame(actual: Frame, expected: Frame) -> None: + actual_tables = dict(frame_checkpoint_module._frame_tables(actual)) + expected_tables = dict(frame_checkpoint_module._frame_tables(expected)) + assert list(actual_tables) == list(expected_tables) + for name, expected_table in expected_tables.items(): + actual_table = actual_tables[name] + pd.testing.assert_frame_equal( + actual_table, + expected_table, + check_dtype=True, + check_index_type=True, + check_column_type=True, + check_exact=True, + ) + _assert_same_text_storage( + actual_table.index, expected_table.index, f"{name}.index" + ) + for column in expected_table.columns: + _assert_same_text_storage( + actual_table[column], expected_table[column], f"{name}.{column}" + ) + pd.testing.assert_series_equal( + actual.strata, + expected.strata, + check_dtype=True, + check_index_type=True, + check_exact=True, + ) + _assert_same_text_storage(actual.strata, expected.strata, "strata") + + +def test_text_columns_are_written_and_read_without_the_per_value_loop( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, text_frame: Frame +) -> None: + path = tmp_path / "text.h5" + _refuse_per_value_loop(monkeypatch) + + write_frame_checkpoint(path, text_frame) + load_frame_checkpoint(path) + + +def test_text_columns_write_the_bytes_of_the_per_value_loop( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, text_frame: Frame +) -> None: + converted_path = tmp_path / "converted.h5" + loop_path = tmp_path / "loop.h5" + + write_frame_checkpoint(converted_path, text_frame) + with monkeypatch.context() as patch: + _use_only_per_value_loop(patch) + write_frame_checkpoint(loop_path, text_frame) + + assert converted_path.read_bytes() == loop_path.read_bytes() + metadata = _metadata(converted_path) + assert metadata["schema_version"] == 2 + compared: list[str] = [] + with h5py.File(converted_path, mode="r") as h5: + for group_path, series in _object_encoded_series(text_frame, metadata): + offsets, payload = PER_VALUE_ENCODE( + series.to_numpy(dtype=object, copy=False) + ) + stored_offsets = np.asarray(h5[f"{group_path}/offsets"]) + stored_payload = np.asarray(h5[f"{group_path}/payload"]) + assert stored_offsets.dtype == np.dtype(np.int64), group_path + assert stored_payload.dtype == np.dtype(np.uint8), group_path + np.testing.assert_array_equal(stored_offsets, offsets, err_msg=group_path) + assert stored_payload.tobytes() == payload, group_path + compared.append(group_path) + # Five person text columns, the household text column, both indexes + # and the strata. + assert len(compared) == 9 + + +def test_text_columns_load_the_frame_of_the_per_value_loop( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, text_frame: Frame +) -> None: + path = tmp_path / "text.h5" + rewrite_path = tmp_path / "rewrite.h5" + write_frame_checkpoint(path, text_frame) + + converted = load_frame_checkpoint(path).frame + with monkeypatch.context() as patch: + _use_only_per_value_loop(patch) + by_loop = load_frame_checkpoint(path).frame + + _assert_same_frame(converted, by_loop) + write_frame_checkpoint(rewrite_path, converted) + assert rewrite_path.read_bytes() == path.read_bytes() + + +def _round_trip_series( + path: Path, series: pd.Series +) -> tuple[np.ndarray, np.ndarray, pd.Series, dict[str, object]]: + """Write ``series`` with the checkpoint writer, then read it back.""" + + spec = frame_checkpoint_module._series_spec(series, label="column") + with h5py.File(path, mode="w") as h5: + group = h5.create_group("column", track_times=False) + frame_checkpoint_module._write_series(group, series, spec) + with h5py.File(path, mode="r") as h5: + offsets = np.asarray(h5["column/offsets"]) + payload = np.asarray(h5["column/payload"]) + restored = frame_checkpoint_module._read_series( + h5["column"], spec, path, label="column" + ) + return offsets, payload, restored, spec + + +def _expected_by_loop( + path: Path, series: pd.Series, spec: dict[str, object] +) -> tuple[np.ndarray, bytes, pd.Series]: + """Today's offsets, payload and restored series for ``series``.""" + + offsets, payload = PER_VALUE_ENCODE(series.to_numpy(dtype=object, copy=False)) + restore_dtype = frame_checkpoint_module._declared_dtype( + spec, path=path, label="column" + ) + values = PER_VALUE_DECODE(offsets, payload, path=path, label="column") + return offsets, payload, pd.Series(values, dtype=restore_dtype, copy=False) + + +def _assert_matches_loop(path: Path, series: pd.Series) -> pd.Series: + offsets, payload, restored, spec = _round_trip_series(path, series) + expected_offsets, expected_payload, expected = _expected_by_loop(path, series, spec) + assert offsets.dtype == np.dtype(np.int64) + assert payload.dtype == np.dtype(np.uint8) + np.testing.assert_array_equal(offsets, expected_offsets) + assert payload.tobytes() == expected_payload + pd.testing.assert_series_equal(restored, expected, check_exact=True) + _assert_same_text_storage(restored, expected, "column") + return restored + + +_EDGE_CASE_VALUES: dict[str, list[str]] = { + "empty column": [], + "empty strings": ["", "", ""], + "non-ASCII UTF-8": ["é", "中文", "😀", "a\x00b", "ÿĀ߿ࠀ￿"], + "one value throughout": ["same"] * 1_000, + "very long string": ["short", "é" * 3_000_000, "tail"], +} + + +@pytest.mark.parametrize("dtype_name", list(TEXT_DTYPES)) +@pytest.mark.parametrize("case", list(_EDGE_CASE_VALUES)) +def test_text_edge_cases_keep_the_per_value_loop_bytes_and_values( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, case: str, dtype_name: str +) -> None: + series = pd.Series(_EDGE_CASE_VALUES[case], dtype=TEXT_DTYPES[dtype_name]) + calls = _LoopCalls(monkeypatch) + + restored = _assert_matches_loop(tmp_path / "column.h5", series) + + assert calls.encoded == [] and calls.decoded == [] + assert restored.tolist() == _EDGE_CASE_VALUES[case] + + +def _concatenated_pyarrow_series() -> pd.Series: + return pd.concat( + [ + pd.Series(["first", "é"], dtype=PYARROW_STR), + pd.Series(["", "third"], dtype=PYARROW_STR), + ], + ignore_index=True, + ) + + +def _sliced_pyarrow_series() -> pd.Series: + return _concatenated_pyarrow_series().iloc[1:].reset_index(drop=True) + + +def _narrow_offset_pyarrow_series() -> pd.Series: + chunks = pa.chunked_array( + [pa.array(["thirty", "two"], pa.string()), pa.array(["bit"], pa.string())] + ) + return pd.Series(pd.arrays.ArrowStringArray(chunks), copy=False) + + +_PYARROW_LAYOUTS: dict[str, Callable[[], pd.Series]] = { + "two chunks": _concatenated_pyarrow_series, + "chunks starting at an offset": _sliced_pyarrow_series, + "32-bit offset chunks": _narrow_offset_pyarrow_series, +} + + +@pytest.mark.parametrize("layout", list(_PYARROW_LAYOUTS)) +def test_pyarrow_text_layouts_keep_the_per_value_loop_bytes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, layout: str +) -> None: + series = _PYARROW_LAYOUTS[layout]() + assert series.array.__arrow_array__().num_chunks >= 1 + calls = _LoopCalls(monkeypatch) + + _assert_matches_loop(tmp_path / "column.h5", series) + + assert calls.encoded == [] and calls.decoded == [] + + +def test_numpy_strings_in_an_object_column_keep_the_per_value_loop_bytes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + series = pd.Series( + np.asarray([np.str_("numpy"), "python", np.str_("é")], dtype=object), + dtype=object, + ) + calls = _LoopCalls(monkeypatch) + + restored = _assert_matches_loop(tmp_path / "column.h5", series) + + assert calls.encoded == [] and calls.decoded == [] + assert [type(value) for value in restored] == [str, str, str] + + +_FALLBACK_COLUMNS: dict[str, Callable[[], pd.Series]] = { + "object strings with None": lambda: pd.Series(["a", None, "c"], dtype=object), + "object strings with NaN": lambda: pd.Series(["a", np.nan], dtype=object), + "object strings with pd.NA": lambda: pd.Series(["a", pd.NA], dtype=object), + "object None only": lambda: pd.Series([None, None], dtype=object), + "object integers": lambda: pd.Series([1, 2], dtype=object), + "object floats": lambda: pd.Series([1.5, np.nan], dtype=object), + "object bytes": lambda: pd.Series([b"x", b"y"], dtype=object), + "object booleans": lambda: pd.Series([True, False], dtype=object), + **{ + f"{dtype_name} with a missing value": ( + lambda dtype=dtype: pd.Series(["a", None, "c"], dtype=dtype) + ) + for dtype_name, dtype in TEXT_DTYPES.items() + if dtype != "object" + }, +} + + +@pytest.mark.parametrize("case", list(_FALLBACK_COLUMNS)) +def test_missing_and_non_string_values_go_through_the_per_value_loop( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, case: str +) -> None: + series = _FALLBACK_COLUMNS[case]() + calls = _LoopCalls(monkeypatch) + + _assert_matches_loop(tmp_path / "column.h5", series) + + assert calls.encoded == [len(series)] + assert calls.decoded == [len(series)] + + +@pytest.mark.parametrize("dtype_name", ["python_str", "python_string", "object"]) +def test_unencodable_strings_raise_the_per_value_loop_error( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, dtype_name: str +) -> None: + series = pd.Series(["fine", "\ud800"], dtype=TEXT_DTYPES[dtype_name]) + calls = _LoopCalls(monkeypatch) + + with pytest.raises(UnicodeEncodeError, match="surrogates not allowed"): + _round_trip_series(tmp_path / "column.h5", series) + + assert calls.encoded == [2] + + +def _read_stored( + path: Path, + dtype_name: str, + offsets: np.ndarray, + payload: np.ndarray, +) -> pd.Series: + spec = frame_checkpoint_module._series_spec( + pd.Series(["a"], dtype=TEXT_DTYPES[dtype_name]), label="column" + ) + with h5py.File(path, mode="w") as h5: + group = h5.create_group("column", track_times=False) + group.create_dataset("offsets", data=offsets, track_times=False) + group.create_dataset("payload", data=payload, track_times=False) + with h5py.File(path, mode="r") as h5: + return frame_checkpoint_module._read_series( + h5["column"], spec, path, label="column" + ) + + +def _bytes(*parts: bytes) -> np.ndarray: + return np.frombuffer(b"".join(parts), dtype=np.uint8) + + +@pytest.mark.parametrize("dtype_name", list(TEXT_DTYPES)) +def test_invalid_utf8_raises_the_per_value_loop_error( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, dtype_name: str +) -> None: + calls = _LoopCalls(monkeypatch) + + with pytest.raises(ValueError, match="invalid object value at row 1"): + _read_stored( + tmp_path / "column.h5", + dtype_name, + np.asarray([0, 3, 5], dtype=np.int64), + _bytes(b"\x07ok", b"\x07\xff"), + ) + + assert calls.decoded == [2] + + +_MALFORMED_OFFSETS = { + "int32 offsets": ( + np.asarray([0, 2], dtype=np.int32), + _bytes(b"\x07a"), + "malformed object offsets", + ), + "no offsets": ( + np.asarray([], dtype=np.int64), + _bytes(b""), + "malformed object offsets", + ), + "first offset not zero": ( + np.asarray([1, 2], dtype=np.int64), + _bytes(b"\x07a"), + "invalid object boundaries", + ), + "last offset short of the payload": ( + np.asarray([0, 2], dtype=np.int64), + _bytes(b"\x07ab"), + "invalid object boundaries", + ), + "value without its tag byte": ( + np.asarray([0, 2, 2], dtype=np.int64), + _bytes(b"\x07a"), + "invalid object boundaries", + ), +} + + +@pytest.mark.parametrize("dtype_name", list(TEXT_DTYPES)) +@pytest.mark.parametrize("case", list(_MALFORMED_OFFSETS)) +def test_malformed_offsets_raise_the_per_value_loop_error( + tmp_path: Path, case: str, dtype_name: str +) -> None: + offsets, payload, message = _MALFORMED_OFFSETS[case] + + with pytest.raises(ValueError, match=message): + _read_stored(tmp_path / "column.h5", dtype_name, offsets, payload) + + +def test_object_tags_other_than_string_go_through_the_per_value_loop( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + calls = _LoopCalls(monkeypatch) + + restored = _read_stored( + tmp_path / "column.h5", + "object", + np.asarray([0, 2, 3], dtype=np.int64), + _bytes(b"\x07a", b"\x00"), + ) + + assert restored.tolist() == ["a", None] + assert calls.decoded == [2] + + +_LARGE_TEXT_VARIABLE = "MICROCOSM_FRAME_CHECKPOINT_LARGE_TEXT_TEST" + + +@pytest.mark.slow +@pytest.mark.skipif( + os.environ.get(_LARGE_TEXT_VARIABLE) != "1", + reason=f"set {_LARGE_TEXT_VARIABLE}=1 to run; it needs about 10 GB of memory", +) +@pytest.mark.parametrize("dtype_name", ["pyarrow_str", "object"]) +def test_text_payload_over_two_gibibytes_keeps_the_per_value_loop_bytes( + dtype_name: str, +) -> None: + """Offsets past 2**31, where 32-bit Arrow offsets would overflow.""" + + long_length = 2**30 + 7 + values = ["a" * long_length, "b" * long_length, "after-é", "", "z"] + series = pd.Series(values, dtype=TEXT_DTYPES[dtype_name]) + del values + expected_offsets = [0] + expected_digest = hashlib.sha256() + for position in range(len(series)): + offsets, payload = PER_VALUE_ENCODE( + np.asarray([series.iloc[position]], dtype=object) + ) + expected_offsets.append(expected_offsets[-1] + int(offsets[-1])) + expected_digest.update(payload) + del offsets, payload + + encoded = frame_checkpoint_module._encode_string_values(series) + assert encoded is not None + offsets, payload = encoded + assert offsets.dtype == np.dtype(np.int64) + assert int(offsets[-2]) > 2**31 + np.testing.assert_array_equal(offsets, np.asarray(expected_offsets)) + assert hashlib.sha256(payload).hexdigest() == expected_digest.hexdigest() + + restore_dtype = frame_checkpoint_module._declared_dtype( + frame_checkpoint_module._series_spec(series, label="column"), + path=Path("large.h5"), + label="column", + ) + restored = frame_checkpoint_module._decode_string_values( + offsets, payload, restore_dtype + ) + del payload + assert restored is not None + assert restored.dtype == series.dtype + assert restored.equals(series) From faee6c67b9962e3dfccb9dd1d935f9a3b77104b3 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:19:41 +0400 Subject: [PATCH 02/10] Convert checkpoint text columns with Arrow buffers, not a per-value loop 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 --- .../src/microcosm/build/frame_checkpoint.py | 150 ++++++++++++++++-- .../test_frame_checkpoint_text_columns.py | 30 +++- 2 files changed, 157 insertions(+), 23 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py b/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py index 44c2f42c29..1635ccfbff 100644 --- a/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py +++ b/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py @@ -8,6 +8,10 @@ Object columns use a small deterministic scalar codec. Checkpoints are local build artifacts and must not be loaded from untrusted sources. + +A column of strings with no missing value is converted with Arrow buffers +instead of one value at a time; it produces and parses the same bytes as the +per-value codec, which still handles every other column. """ from __future__ import annotations @@ -23,6 +27,7 @@ import numpy as np import pandas as pd +import pyarrow as pa from microcosm.frame import ( EntitySchema, @@ -562,9 +567,10 @@ def _write_series(group: Any, series: pd.Series, spec: Mapping[str, object]) -> _write_numpy_dataset(group, "values", values) return if encoding == _ENCODING_OBJECT: - offsets, payload = _encode_object_values( - series.to_numpy(dtype=object, copy=False) - ) + encoded = _encode_string_values(series) + if encoded is None: + encoded = _encode_object_values(series.to_numpy(dtype=object, copy=False)) + offsets, payload = encoded _write_numpy_dataset(group, "offsets", offsets) _write_bytes_dataset(group, "payload", payload) return @@ -604,9 +610,14 @@ def _read_series( series = pd.Series(values.view(np.dtype(dtype)), copy=False) elif encoding == _ENCODING_OBJECT: offsets = _read_numpy_dataset(group, "offsets", path) - payload = _read_bytes_dataset(group, "payload", path) - values = _decode_object_values(offsets, payload, path=path, label=label) - series = pd.Series(values, dtype=restore_dtype, copy=False) + payload = _read_uint8_dataset(group, "payload", path) + _check_object_offsets(offsets, len(payload), path=path, label=label) + series = _decode_string_values(offsets, payload, restore_dtype) + if series is None: + values = _decode_object_values( + offsets, payload.tobytes(), path=path, label=label + ) + series = pd.Series(values, dtype=restore_dtype, copy=False) elif encoding == _ENCODING_NULLABLE_BOOLEAN: if dtype != "boolean": raise ValueError( @@ -759,21 +770,126 @@ def _encode_object_scalar(value: object) -> bytes: ) -def _decode_object_values( +def _encode_string_values(series: pd.Series) -> tuple[np.ndarray, np.ndarray] | None: + """The per-value codec's offsets and payload, built from Arrow buffers. + + The per-value codec stores each value as the string tag byte followed by + its UTF-8 bytes, and ``offsets[i + 1]`` is where value ``i`` ends. An + Arrow string array holds the same UTF-8 bytes back to back with its own + end offsets, so in the payload value ``i`` ends ``i + 1`` tag bytes later. + Returns ``None`` when a value is missing or is not a string; the + per-value codec writes those columns. + """ + + strings = _string_values_as_arrow(series) + if strings is None: + return None + value_count = len(strings) + if value_count == 0: + return np.zeros(1, dtype=np.int64), np.empty(0, dtype=np.uint8) + _validity, offsets_buffer, data_buffer = strings.buffers() + string_offsets = np.frombuffer(offsets_buffer, dtype=np.int64)[ + strings.offset : strings.offset + value_count + 1 + ] + first, last = int(string_offsets[0]), int(string_offsets[-1]) + offsets = string_offsets - first + np.arange(value_count + 1, dtype=np.int64) + payload = np.empty(int(offsets[-1]), dtype=np.uint8) + tag_positions = offsets[:-1] + payload[tag_positions] = _TAG_STRING + if last > first: + is_value_byte = np.ones(len(payload), dtype=np.bool_) + is_value_byte[tag_positions] = False + payload[is_value_byte] = np.frombuffer(data_buffer, dtype=np.uint8)[first:last] + return offsets, payload + + +def _string_values_as_arrow(series: pd.Series) -> pa.LargeStringArray | None: + """The values as one Arrow large-string array, or ``None``. + + ``None`` when a value is missing or is not a ``str``, or when Arrow + refuses a value (a lone surrogate, or stored bytes that are not UTF-8), + so the per-value codec handles the column and raises its own error. + """ + + dtype = series.dtype + try: + if isinstance(dtype, pd.StringDtype) and dtype.storage == "pyarrow": + stored = pa.array(series.array) + if stored.null_count: + return None + # Widen each chunk to 64-bit offsets before joining the chunks, + # so text past 2**31 bytes never passes through 32-bit offsets. + strings = stored.cast(pa.large_string()) + if isinstance(strings, pa.ChunkedArray): + strings = strings.combine_chunks() + strings.validate(full=True) + return strings + values = series.to_numpy(dtype=object, copy=False) + if pd.api.types.infer_dtype(values, skipna=False) not in ("string", "empty"): + return None + return pa.array(values, type=pa.large_string()) + except (pa.ArrowInvalid, pa.ArrowTypeError, UnicodeEncodeError): + return None + + +def _decode_string_values( offsets: np.ndarray, - payload: bytes, - *, - path: Path, - label: str, -) -> np.ndarray: + payload: np.ndarray, + restore_dtype: str | pd.BooleanDtype | pd.StringDtype, +) -> pd.Series | None: + """Parse checked offsets and payload in which every value is a string. + + Returns ``None`` when the declared dtype is not text, when a value's tag + is not the string tag, or when a value is not valid UTF-8; the per-value + codec reads those columns and raises its own error for invalid values. + """ + + is_object = isinstance(restore_dtype, str) and restore_dtype == "object" + if not (is_object or isinstance(restore_dtype, pd.StringDtype)): + return None + tag_positions = offsets[:-1] + if not (payload[tag_positions] == _TAG_STRING).all(): + return None + is_value_byte = np.ones(len(payload), dtype=np.bool_) + is_value_byte[tag_positions] = False + string_offsets = offsets - np.arange(len(offsets), dtype=np.int64) + strings = pa.LargeStringArray.from_buffers( + len(tag_positions), + pa.py_buffer(string_offsets), + pa.py_buffer(payload[is_value_byte]), + ) + try: + strings.validate(full=True) # UTF-8, as the per-value decode checks + except pa.ArrowInvalid: + return None + if isinstance(restore_dtype, pd.StringDtype) and restore_dtype.storage == "pyarrow": + return pd.Series(pd.array(strings, dtype=restore_dtype), copy=False) + return pd.Series( + strings.to_numpy(zero_copy_only=False), dtype=restore_dtype, copy=False + ) + + +def _check_object_offsets( + offsets: np.ndarray, payload_size: int, *, path: Path, label: str +) -> None: if offsets.ndim != 1 or offsets.dtype != np.dtype(np.int64) or len(offsets) < 1: raise ValueError( f"Frame checkpoint {path} {label!r} has malformed object offsets." ) - if offsets[0] != 0 or offsets[-1] != len(payload) or (np.diff(offsets) < 1).any(): + if offsets[0] != 0 or offsets[-1] != payload_size or (np.diff(offsets) < 1).any(): raise ValueError( f"Frame checkpoint {path} {label!r} has invalid object boundaries." ) + + +def _decode_object_values( + offsets: np.ndarray, + payload: bytes, + *, + path: Path, + label: str, +) -> np.ndarray: + _check_object_offsets(offsets, len(payload), path=path, label=label) values = np.empty(len(offsets) - 1, dtype=object) for index, (start, stop) in enumerate(zip(offsets[:-1], offsets[1:], strict=True)): chunk = payload[int(start) : int(stop)] @@ -812,7 +928,7 @@ def _write_numpy_dataset(group: Any, name: str, values: np.ndarray) -> None: group.create_dataset(name, data=np.asarray(values), track_times=False) -def _write_bytes_dataset(group: Any, name: str, value: bytes) -> None: +def _write_bytes_dataset(group: Any, name: str, value: bytes | np.ndarray) -> None: group.create_dataset( name, data=np.frombuffer(value, dtype=np.uint8), @@ -826,12 +942,16 @@ def _read_numpy_dataset(group: Any, name: str, path: Path) -> np.ndarray: def _read_bytes_dataset(group: Any, name: str, path: Path) -> bytes: + return _read_uint8_dataset(group, name, path).tobytes() + + +def _read_uint8_dataset(group: Any, name: str, path: Path) -> np.ndarray: values = _read_numpy_dataset(group, name, path) if values.ndim != 1 or values.dtype != np.dtype(np.uint8): raise ValueError( f"Frame checkpoint {path} HDF dataset {name!r} must be uint8 bytes." ) - return values.tobytes() + return values def _read_metadata(root: Any, path: Path) -> dict[str, Any]: diff --git a/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py index 274f0546de..d893371148 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py @@ -384,10 +384,15 @@ def _concatenated_pyarrow_series() -> pd.Series: ) -def _sliced_pyarrow_series() -> pd.Series: +def _sliced_chunks_pyarrow_series() -> pd.Series: return _concatenated_pyarrow_series().iloc[1:].reset_index(drop=True) +def _sliced_chunk_pyarrow_series() -> pd.Series: + series = pd.Series(["dropped", "é", "", "kept"], dtype=PYARROW_STR) + return series.iloc[1:].reset_index(drop=True) + + def _narrow_offset_pyarrow_series() -> pd.Series: chunks = pa.chunked_array( [pa.array(["thirty", "two"], pa.string()), pa.array(["bit"], pa.string())] @@ -395,10 +400,16 @@ def _narrow_offset_pyarrow_series() -> pd.Series: return pd.Series(pd.arrays.ArrowStringArray(chunks), copy=False) -_PYARROW_LAYOUTS: dict[str, Callable[[], pd.Series]] = { - "two chunks": _concatenated_pyarrow_series, - "chunks starting at an offset": _sliced_pyarrow_series, - "32-bit offset chunks": _narrow_offset_pyarrow_series, +# Each layout's builder, chunk count and the first chunk's starting offset. +_PYARROW_LAYOUTS: dict[str, tuple[Callable[[], pd.Series], int, int]] = { + "two chunks": (_concatenated_pyarrow_series, 2, 0), + "two chunks, the first starting at an offset": ( + _sliced_chunks_pyarrow_series, + 2, + 1, + ), + "one chunk starting at an offset": (_sliced_chunk_pyarrow_series, 1, 1), + "chunks built with 32-bit offsets": (_narrow_offset_pyarrow_series, 2, 0), } @@ -406,8 +417,11 @@ def _narrow_offset_pyarrow_series() -> pd.Series: def test_pyarrow_text_layouts_keep_the_per_value_loop_bytes( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, layout: str ) -> None: - series = _PYARROW_LAYOUTS[layout]() - assert series.array.__arrow_array__().num_chunks >= 1 + build_series, chunk_count, first_chunk_offset = _PYARROW_LAYOUTS[layout] + series = build_series() + chunks = series.array.__arrow_array__() + assert chunks.num_chunks == chunk_count + assert chunks.chunk(0).offset == first_chunk_offset calls = _LoopCalls(monkeypatch) _assert_matches_loop(tmp_path / "column.h5", series) @@ -577,7 +591,7 @@ def test_object_tags_other_than_string_go_through_the_per_value_loop( @pytest.mark.slow @pytest.mark.skipif( os.environ.get(_LARGE_TEXT_VARIABLE) != "1", - reason=f"set {_LARGE_TEXT_VARIABLE}=1 to run; it needs about 10 GB of memory", + reason=f"set {_LARGE_TEXT_VARIABLE}=1 to run; it needs about 6 GB of memory", ) @pytest.mark.parametrize("dtype_name", ["pyarrow_str", "object"]) def test_text_payload_over_two_gibibytes_keeps_the_per_value_loop_bytes( From e39b67372a8ee6a55c451db9a7fcebb06cbde882 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:45:36 +0400 Subject: [PATCH 03/10] Test the text conversion against review round 1's failures 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 --- .../test_frame_checkpoint_text_columns.py | 103 ++++++++++++++++++ 1 file changed, 103 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py index d893371148..d3a695bffc 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py @@ -13,6 +13,7 @@ import hashlib import json import os +import sys from collections.abc import Callable, Iterator from pathlib import Path @@ -400,6 +401,21 @@ def _narrow_offset_pyarrow_series() -> pd.Series: return pd.Series(pd.arrays.ArrowStringArray(chunks), copy=False) +def _padded_offsets_pyarrow_series() -> pd.Series: + """One chunk whose offsets buffer is not a whole number of int64 values. + + Arrow accepts an offsets buffer larger than its values need; here it has + three spare bytes after the three offsets. + """ + + offsets = np.asarray([0, 1, 3], dtype=np.int64).tobytes() + b"\0\0\0" + chunk = pa.LargeStringArray.from_buffers( + 2, pa.py_buffer(offsets), pa.py_buffer(b"abc") + ) + chunk.validate(full=True) + return pd.Series(pd.arrays.ArrowStringArray(pa.chunked_array([chunk])), copy=False) + + # Each layout's builder, chunk count and the first chunk's starting offset. _PYARROW_LAYOUTS: dict[str, tuple[Callable[[], pd.Series], int, int]] = { "two chunks": (_concatenated_pyarrow_series, 2, 0), @@ -410,6 +426,7 @@ def _narrow_offset_pyarrow_series() -> pd.Series: ), "one chunk starting at an offset": (_sliced_chunk_pyarrow_series, 1, 1), "chunks built with 32-bit offsets": (_narrow_offset_pyarrow_series, 2, 0), + "offsets buffer with spare bytes": (_padded_offsets_pyarrow_series, 1, 0), } @@ -444,6 +461,56 @@ def test_numpy_strings_in_an_object_column_keep_the_per_value_loop_bytes( assert [type(value) for value in restored] == [str, str, str] +class _EncodeOverridingStr(str): + """A string whose ``encode`` returns other bytes than its UTF-8.""" + + def encode(self, *_arguments: object, **_keywords: object) -> bytes: + return b"OVERRIDDEN" + + +@pytest.mark.parametrize("dtype_name", ["python_str", "python_string", "object"]) +def test_string_subclasses_go_through_the_per_value_loop( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, dtype_name: str +) -> None: + """The per-value loop calls each value's own ``encode``; keep its bytes.""" + + values = np.asarray(["plain", _EncodeOverridingStr("odd")], dtype=object) + series = pd.Series(values, dtype=TEXT_DTYPES[dtype_name]) + assert type(series.to_numpy(dtype=object)[1]) is _EncodeOverridingStr + calls = _LoopCalls(monkeypatch) + + restored = _assert_matches_loop(tmp_path / "column.h5", series) + + assert calls.encoded == [2] + assert restored.tolist() == ["plain", "OVERRIDDEN"] + + +@pytest.mark.parametrize("dtype_name", ["python_str", "python_string", "object"]) +def test_writing_python_strings_leaves_their_memory_size_unchanged( + tmp_path: Path, dtype_name: str +) -> None: + """Writing must not attach a cached UTF-8 copy to non-ASCII strings. + + CPython's ``PyUnicode_AsUTF8AndSize``, which Arrow uses to read a + ``str``, keeps a UTF-8 copy inside every non-ASCII string it reads, for + the rest of that string's life. ``str.encode``, which the per-value loop + calls, keeps nothing. + """ + + values = np.asarray( + ["".join(["caf", "é-", str(position)]) for position in range(3)] + + ["".join(["中文-", str(position)]) for position in range(3)], + dtype=object, + ) + series = pd.Series(values, dtype=TEXT_DTYPES[dtype_name], copy=False) + stored_values = series.to_numpy(dtype=object, copy=False) + sizes_before = [sys.getsizeof(value) for value in stored_values] + + _round_trip_series(tmp_path / "column.h5", series) + + assert [sys.getsizeof(value) for value in stored_values] == sizes_before + + _FALLBACK_COLUMNS: dict[str, Callable[[], pd.Series]] = { "object strings with None": lambda: pd.Series(["a", None, "c"], dtype=object), "object strings with NaN": lambda: pd.Series(["a", np.nan], dtype=object), @@ -569,6 +636,42 @@ def test_malformed_offsets_raise_the_per_value_loop_error( _read_stored(tmp_path / "column.h5", dtype_name, offsets, payload) +def _read_error( + path: Path, dtype_name: str, offsets: np.ndarray, payload: np.ndarray +) -> tuple[type[BaseException], str]: + with pytest.raises(Exception) as raised: + _read_stored(path, dtype_name, offsets, payload) + return raised.type, str(raised.value) + + +# The differences of these offsets overflow int64 and wrap around, so they +# pass the boundary check although two of them lie outside the payload. +_WRAPPING_OFFSETS = np.asarray([0, 2**63 - 1, -3, 5], dtype=np.int64) +_WRAPPING_PAYLOADS = { + "first value invalid": _bytes(b"\x00abcd"), + "first value valid": _bytes(b"\x07ab\x07c"), +} + + +@pytest.mark.parametrize("dtype_name", list(TEXT_DTYPES)) +@pytest.mark.parametrize("case", list(_WRAPPING_PAYLOADS)) +def test_wrapping_offsets_raise_the_per_value_loop_error( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, case: str, dtype_name: str +) -> None: + payload = _WRAPPING_PAYLOADS[case] + with monkeypatch.context() as patch: + _use_only_per_value_loop(patch) + expected = _read_error( + tmp_path / "loop.h5", dtype_name, _WRAPPING_OFFSETS, payload + ) + + actual = _read_error( + tmp_path / "converted.h5", dtype_name, _WRAPPING_OFFSETS, payload + ) + + assert actual == expected + + def test_object_tags_other_than_string_go_through_the_per_value_loop( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: From 8c80a03e20b3ad263e5abb9d8af0c68d6ff01920 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:47:51 +0400 Subject: [PATCH 04/10] Fix the text conversion's round 1 review failures - 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 --- .../src/microcosm/build/frame_checkpoint.py | 107 ++++++++++++------ .../test_frame_checkpoint_text_columns.py | 9 +- 2 files changed, 74 insertions(+), 42 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py b/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py index 1635ccfbff..fda4e03e16 100644 --- a/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py +++ b/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py @@ -72,6 +72,10 @@ _TAG_STRING = 7 _TAG_BYTES = 8 +_STRING_TAG_BYTE = bytes([_TAG_STRING]) +# The value types whose bytes the per-value codec takes from ``str.encode``. +_PLAIN_STRING_TYPES = frozenset({str, np.str_}) + _SUPPORTED_OBJECT_INFERRED_DTYPES = frozenset( { "boolean", @@ -771,26 +775,52 @@ def _encode_object_scalar(value: object) -> bytes: def _encode_string_values(series: pd.Series) -> tuple[np.ndarray, np.ndarray] | None: - """The per-value codec's offsets and payload, built from Arrow buffers. + """The per-value codec's offsets and payload, without a loop over values. The per-value codec stores each value as the string tag byte followed by - its UTF-8 bytes, and ``offsets[i + 1]`` is where value ``i`` ends. An - Arrow string array holds the same UTF-8 bytes back to back with its own + its UTF-8 bytes, and ``offsets[i + 1]`` is where value ``i`` ends. + Returns ``None`` when a value is missing or is not a string, or when a + value cannot be converted; the per-value codec writes those columns and + raises its own errors. + """ + + dtype = series.dtype + if isinstance(dtype, pd.StringDtype) and dtype.storage == "pyarrow": + return _encode_arrow_strings(series) + return _encode_python_strings(series.to_numpy(dtype=object, copy=False)) + + +def _encode_arrow_strings(series: pd.Series) -> tuple[np.ndarray, np.ndarray] | None: + """Offsets and payload from a pyarrow-backed column's Arrow buffers. + + The Arrow array holds the values' UTF-8 bytes back to back with its own end offsets, so in the payload value ``i`` ends ``i + 1`` tag bytes later. - Returns ``None`` when a value is missing or is not a string; the - per-value codec writes those columns. """ - strings = _string_values_as_arrow(series) - if strings is None: + try: + stored = pa.array(series.array) + if stored.null_count: + return None + # Widen each chunk to 64-bit offsets before joining the chunks, so + # text past 2**31 bytes never passes through 32-bit offsets. + strings = stored.cast(pa.large_string()) + if isinstance(strings, pa.ChunkedArray): + strings = strings.combine_chunks() + strings.validate(full=True) # UTF-8, as the per-value encode requires + except (pa.ArrowInvalid, pa.ArrowTypeError): return None value_count = len(strings) if value_count == 0: return np.zeros(1, dtype=np.int64), np.empty(0, dtype=np.uint8) _validity, offsets_buffer, data_buffer = strings.buffers() - string_offsets = np.frombuffer(offsets_buffer, dtype=np.int64)[ - strings.offset : strings.offset + value_count + 1 - ] + # Arrow allows spare bytes after the offsets, so read exactly the + # array's own offsets rather than the whole buffer. + string_offsets = np.frombuffer( + offsets_buffer, + dtype=np.int64, + count=value_count + 1, + offset=strings.offset * np.dtype(np.int64).itemsize, + ) first, last = int(string_offsets[0]), int(string_offsets[-1]) offsets = string_offsets - first + np.arange(value_count + 1, dtype=np.int64) payload = np.empty(int(offsets[-1]), dtype=np.uint8) @@ -799,37 +829,37 @@ def _encode_string_values(series: pd.Series) -> tuple[np.ndarray, np.ndarray] | if last > first: is_value_byte = np.ones(len(payload), dtype=np.bool_) is_value_byte[tag_positions] = False - payload[is_value_byte] = np.frombuffer(data_buffer, dtype=np.uint8)[first:last] + payload[is_value_byte] = np.frombuffer( + data_buffer, dtype=np.uint8, count=last - first, offset=first + ) return offsets, payload -def _string_values_as_arrow(series: pd.Series) -> pa.LargeStringArray | None: - """The values as one Arrow large-string array, or ``None``. +def _encode_python_strings(values: np.ndarray) -> tuple[np.ndarray, np.ndarray] | None: + """Offsets and payload for an object array of ``str`` values. - ``None`` when a value is missing or is not a ``str``, or when Arrow - refuses a value (a lone surrogate, or stored bytes that are not UTF-8), - so the per-value codec handles the column and raises its own error. + Only exact ``str`` and ``np.str_`` values qualify. The per-value codec + calls each value's own ``encode``, which a subclass can override; these + two types use ``str.encode`` and take no instance attributes. The values + are encoded with ``str.encode`` through ``map`` and joined with + ``bytes.join``, not converted by Arrow: Arrow reads a ``str`` with + CPython's ``PyUnicode_AsUTF8AndSize``, which keeps a UTF-8 copy inside + every non-ASCII string for the rest of that string's life. """ - dtype = series.dtype + if not set(map(type, values)) <= _PLAIN_STRING_TYPES: + return None try: - if isinstance(dtype, pd.StringDtype) and dtype.storage == "pyarrow": - stored = pa.array(series.array) - if stored.null_count: - return None - # Widen each chunk to 64-bit offsets before joining the chunks, - # so text past 2**31 bytes never passes through 32-bit offsets. - strings = stored.cast(pa.large_string()) - if isinstance(strings, pa.ChunkedArray): - strings = strings.combine_chunks() - strings.validate(full=True) - return strings - values = series.to_numpy(dtype=object, copy=False) - if pd.api.types.infer_dtype(values, skipna=False) not in ("string", "empty"): - return None - return pa.array(values, type=pa.large_string()) - except (pa.ArrowInvalid, pa.ArrowTypeError, UnicodeEncodeError): + encoded = list(map(str.encode, values)) + except UnicodeEncodeError: return None + lengths = np.fromiter(map(len, encoded), dtype=np.int64, count=len(encoded)) + offsets = np.zeros(len(encoded) + 1, dtype=np.int64) + np.cumsum(lengths + 1, out=offsets[1:]) + # Joining after a leading empty value puts the tag byte before each value. + encoded.insert(0, b"") + payload = _STRING_TAG_BYTE.join(encoded) + return offsets, np.frombuffer(payload, dtype=np.uint8) def _decode_string_values( @@ -847,16 +877,21 @@ def _decode_string_values( is_object = isinstance(restore_dtype, str) and restore_dtype == "object" if not (is_object or isinstance(restore_dtype, pd.StringDtype)): return None + # The boundary check compares differences, which wrap around when + # offsets far outside the payload overflow int64; the per-value codec + # reads such offsets and raises its own error. + if offsets.min() < 0 or offsets.max() > len(payload): + return None tag_positions = offsets[:-1] if not (payload[tag_positions] == _TAG_STRING).all(): return None is_value_byte = np.ones(len(payload), dtype=np.bool_) is_value_byte[tag_positions] = False + string_bytes = payload[is_value_byte] + del is_value_byte string_offsets = offsets - np.arange(len(offsets), dtype=np.int64) strings = pa.LargeStringArray.from_buffers( - len(tag_positions), - pa.py_buffer(string_offsets), - pa.py_buffer(payload[is_value_byte]), + len(tag_positions), pa.py_buffer(string_offsets), pa.py_buffer(string_bytes) ) try: strings.validate(full=True) # UTF-8, as the per-value decode checks diff --git a/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py index d3a695bffc..075f0a9478 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py @@ -659,15 +659,12 @@ def test_wrapping_offsets_raise_the_per_value_loop_error( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, case: str, dtype_name: str ) -> None: payload = _WRAPPING_PAYLOADS[case] + path = tmp_path / "column.h5" # error messages name the file with monkeypatch.context() as patch: _use_only_per_value_loop(patch) - expected = _read_error( - tmp_path / "loop.h5", dtype_name, _WRAPPING_OFFSETS, payload - ) + expected = _read_error(path, dtype_name, _WRAPPING_OFFSETS, payload) - actual = _read_error( - tmp_path / "converted.h5", dtype_name, _WRAPPING_OFFSETS, payload - ) + actual = _read_error(path, dtype_name, _WRAPPING_OFFSETS, payload) assert actual == expected From f41fa03d2e03c09b5b2891e2ee70be592bc2c596 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:18:28 +0400 Subject: [PATCH 05/10] Test the text conversion against review round 2's failures 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 --- .../test_frame_checkpoint_text_columns.py | 119 +++++++++++++++++- 1 file changed, 114 insertions(+), 5 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py index 075f0a9478..320e637643 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py @@ -14,6 +14,7 @@ import json import os import sys +import tracemalloc from collections.abc import Callable, Iterator from pathlib import Path @@ -395,6 +396,8 @@ def _sliced_chunk_pyarrow_series() -> pd.Series: def _narrow_offset_pyarrow_series() -> pd.Series: + """Chunks given with 32-bit offsets; pandas stores them widened to 64-bit.""" + chunks = pa.chunked_array( [pa.array(["thirty", "two"], pa.string()), pa.array(["bit"], pa.string())] ) @@ -468,21 +471,93 @@ def encode(self, *_arguments: object, **_keywords: object) -> bytes: return b"OVERRIDDEN" +class _EqualToStrMeta(type): + """Makes a class hash like ``str`` and compare equal to it.""" + + def __eq__(cls, other: object) -> bool: + return other is str or other is cls + + def __hash__(cls) -> int: + return hash(str) + + +class _StrLookalike(str, metaclass=_EqualToStrMeta): + def encode(self, *_arguments: object, **_keywords: object) -> bytes: + return b"OVERRIDDEN" + + +class _UnhashableTypeMeta(type): + """Makes a class that cannot be hashed, so it cannot go into a set.""" + + __hash__ = None # type: ignore[assignment] + + +class _UnhashableTypeStr(str, metaclass=_UnhashableTypeMeta): + pass + + +class _UnhashableTypeFloat(float, metaclass=_UnhashableTypeMeta): + pass + + +_STRING_SUBCLASSES = { + "overrides encode": _EncodeOverridingStr, + "type compares equal to str": _StrLookalike, + "type cannot be hashed": _UnhashableTypeStr, +} + + @pytest.mark.parametrize("dtype_name", ["python_str", "python_string", "object"]) +@pytest.mark.parametrize("subclass", list(_STRING_SUBCLASSES)) def test_string_subclasses_go_through_the_per_value_loop( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, dtype_name: str + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, subclass: str, dtype_name: str ) -> None: """The per-value loop calls each value's own ``encode``; keep its bytes.""" - values = np.asarray(["plain", _EncodeOverridingStr("odd")], dtype=object) + string_type = _STRING_SUBCLASSES[subclass] + values = np.asarray(["plain", string_type("odd")], dtype=object) series = pd.Series(values, dtype=TEXT_DTYPES[dtype_name]) - assert type(series.to_numpy(dtype=object)[1]) is _EncodeOverridingStr + assert type(series.to_numpy(dtype=object)[1]) is string_type calls = _LoopCalls(monkeypatch) - restored = _assert_matches_loop(tmp_path / "column.h5", series) + _assert_matches_loop(tmp_path / "column.h5", series) assert calls.encoded == [2] - assert restored.tolist() == ["plain", "OVERRIDDEN"] + + +@pytest.mark.parametrize("dtype_name", ["python_str", "python_string", "object"]) +def test_writing_python_strings_needs_no_more_memory_than_the_per_value_loop( + dtype_name: str, +) -> None: + """Peak traced memory of encoding short strings, against the loop's. + + The loop holds the offsets, a growing ``bytearray`` and its final + ``bytes`` copy. Encoding every value at once would also hold one + ``bytes`` object per value and ``bytes.join``'s buffer table, about six + times the loop's peak for short strings. + """ + + values = np.asarray( + ["".join(["v", str(position % 1_000).zfill(6)]) for position in range(300_000)], + dtype=object, + ) + series = pd.Series(values, dtype=TEXT_DTYPES[dtype_name], copy=False) + stored_values = series.to_numpy(dtype=object, copy=False) + + def traced_peak(encode: Callable[[], object]) -> int: + tracemalloc.start() + try: + encode() + return tracemalloc.get_traced_memory()[1] + finally: + tracemalloc.stop() + + loop_peak = traced_peak(lambda: PER_VALUE_ENCODE(stored_values)) + converted_peak = traced_peak( + lambda: frame_checkpoint_module._encode_string_values(series) + ) + + assert converted_peak <= loop_peak @pytest.mark.parametrize("dtype_name", ["python_str", "python_string", "object"]) @@ -520,6 +595,12 @@ def test_writing_python_strings_leaves_their_memory_size_unchanged( "object floats": lambda: pd.Series([1.5, np.nan], dtype=object), "object bytes": lambda: pd.Series([b"x", b"y"], dtype=object), "object booleans": lambda: pd.Series([True, False], dtype=object), + "object floats whose type cannot be hashed": lambda: pd.Series( + np.asarray( + [_UnhashableTypeFloat(1.5), _UnhashableTypeFloat(2.0)], dtype=object + ), + dtype=object, + ), **{ f"{dtype_name} with a missing value": ( lambda dtype=dtype: pd.Series(["a", None, "c"], dtype=dtype) @@ -669,6 +750,34 @@ def test_wrapping_offsets_raise_the_per_value_loop_error( assert actual == expected +@pytest.mark.parametrize("dtype_name", ["pyarrow_str", "pyarrow_string"]) +def test_reading_falls_back_when_pandas_refuses_the_arrow_array( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, dtype_name: str +) -> None: + """A pandas that casts one Arrow array to 32-bit offsets refuses 2 GiB. + + pandas 2.2's ``ArrowStringArray._from_sequence`` casts an Arrow array to + ``pa.string()``, which refuses 2**31 or more bytes of text, while the + per-value loop's object values are split into chunks. The reader then + uses the loop. + """ + + series = pd.Series(["a", "é", ""], dtype=TEXT_DTYPES[dtype_name]) + original_array = pd.array + + def refusing_array(data: object, *arguments: object, **keywords: object): + if isinstance(data, pa.Array): + raise pa.ArrowInvalid("input array too large") + return original_array(data, *arguments, **keywords) + + monkeypatch.setattr(pd, "array", refusing_array) + calls = _LoopCalls(monkeypatch) + + _assert_matches_loop(tmp_path / "column.h5", series) + + assert calls.decoded == [3] + + def test_object_tags_other_than_string_go_through_the_per_value_loop( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: From 216db3afbb655b12323278088ce6bce3cc4ce2c4 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:23:35 +0400 Subject: [PATCH 06/10] Fix the text conversion's round 2 review failures - 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 --- .../src/microcosm/build/frame_checkpoint.py | 59 ++++++++++++++----- .../test_frame_checkpoint_text_columns.py | 19 ++++-- 2 files changed, 58 insertions(+), 20 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py b/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py index fda4e03e16..e556ab6bde 100644 --- a/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py +++ b/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py @@ -73,8 +73,13 @@ _TAG_BYTES = 8 _STRING_TAG_BYTE = bytes([_TAG_STRING]) -# The value types whose bytes the per-value codec takes from ``str.encode``. -_PLAIN_STRING_TYPES = frozenset({str, np.str_}) +# The identities of the value types whose bytes the per-value codec takes +# from ``str.encode``. Types are compared by identity: a metaclass can make +# another type hash like ``str`` and compare equal to it, or not hash at all. +_PLAIN_STRING_TYPE_IDS = np.asarray([id(str), id(np.str_)], dtype=np.uintp) +# How many Python strings are encoded at a time, which bounds the temporary +# ``bytes`` objects and ``bytes.join``'s buffer table. +_STRING_ENCODE_BATCH = 8_192 _SUPPORTED_OBJECT_INFERRED_DTYPES = frozenset( { @@ -840,25 +845,41 @@ def _encode_python_strings(values: np.ndarray) -> tuple[np.ndarray, np.ndarray] Only exact ``str`` and ``np.str_`` values qualify. The per-value codec calls each value's own ``encode``, which a subclass can override; these - two types use ``str.encode`` and take no instance attributes. The values - are encoded with ``str.encode`` through ``map`` and joined with - ``bytes.join``, not converted by Arrow: Arrow reads a ``str`` with - CPython's ``PyUnicode_AsUTF8AndSize``, which keeps a UTF-8 copy inside - every non-ASCII string for the rest of that string's life. + two types use ``str.encode`` and take no instance attributes. + + The values are encoded with ``str.encode`` through ``map``, a batch at a + time, and each batch is joined with ``bytes.join`` into one + ``bytearray``. Arrow is not used: it reads a ``str`` with CPython's + ``PyUnicode_AsUTF8AndSize``, which keeps a UTF-8 copy inside every + non-ASCII string for the rest of that string's life. """ - if not set(map(type, values)) <= _PLAIN_STRING_TYPES: + value_count = len(values) + type_ids = np.fromiter( + map(id, map(type, values)), dtype=np.uintp, count=value_count + ) + if not np.isin(type_ids, _PLAIN_STRING_TYPE_IDS).all(): return None + del type_ids + # Each value's UTF-8 length goes to offsets[i + 1]; adding the tag byte + # to each and summing in place then gives the end of every value. + offsets = np.zeros(value_count + 1, dtype=np.int64) + payload = bytearray() try: - encoded = list(map(str.encode, values)) + for start in range(0, value_count, _STRING_ENCODE_BATCH): + encoded = list( + map(str.encode, values[start : start + _STRING_ENCODE_BATCH]) + ) + offsets[start + 1 : start + 1 + len(encoded)] = np.fromiter( + map(len, encoded), dtype=np.int64, count=len(encoded) + ) + # Joining after a leading empty value puts a tag before each value. + encoded.insert(0, b"") + payload += _STRING_TAG_BYTE.join(encoded) except UnicodeEncodeError: return None - lengths = np.fromiter(map(len, encoded), dtype=np.int64, count=len(encoded)) - offsets = np.zeros(len(encoded) + 1, dtype=np.int64) - np.cumsum(lengths + 1, out=offsets[1:]) - # Joining after a leading empty value puts the tag byte before each value. - encoded.insert(0, b"") - payload = _STRING_TAG_BYTE.join(encoded) + offsets[1:] += 1 + np.cumsum(offsets, out=offsets) return offsets, np.frombuffer(payload, dtype=np.uint8) @@ -898,7 +919,13 @@ def _decode_string_values( except pa.ArrowInvalid: return None if isinstance(restore_dtype, pd.StringDtype) and restore_dtype.storage == "pyarrow": - return pd.Series(pd.array(strings, dtype=restore_dtype), copy=False) + try: + restored = pd.array(strings, dtype=restore_dtype) + except pa.ArrowInvalid: + # pandas 2.2 casts one Arrow array to 32-bit offsets, which + # refuses 2**31 or more bytes of text. + return None + return pd.Series(restored, copy=False) return pd.Series( strings.to_numpy(zero_copy_only=False), dtype=restore_dtype, copy=False ) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py index 320e637643..ebd832c874 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py @@ -500,6 +500,19 @@ class _UnhashableTypeFloat(float, metaclass=_UnhashableTypeMeta): pass +def _object_array(*values: object) -> np.ndarray: + """An object array holding ``values`` as given. + + ``np.asarray`` keys a dict by each value's type, which fails for a type + that cannot be hashed. + """ + + array = np.empty(len(values), dtype=object) + for position, value in enumerate(values): + array[position] = value + return array + + _STRING_SUBCLASSES = { "overrides encode": _EncodeOverridingStr, "type compares equal to str": _StrLookalike, @@ -515,7 +528,7 @@ def test_string_subclasses_go_through_the_per_value_loop( """The per-value loop calls each value's own ``encode``; keep its bytes.""" string_type = _STRING_SUBCLASSES[subclass] - values = np.asarray(["plain", string_type("odd")], dtype=object) + values = _object_array("plain", string_type("odd")) series = pd.Series(values, dtype=TEXT_DTYPES[dtype_name]) assert type(series.to_numpy(dtype=object)[1]) is string_type calls = _LoopCalls(monkeypatch) @@ -596,9 +609,7 @@ def test_writing_python_strings_leaves_their_memory_size_unchanged( "object bytes": lambda: pd.Series([b"x", b"y"], dtype=object), "object booleans": lambda: pd.Series([True, False], dtype=object), "object floats whose type cannot be hashed": lambda: pd.Series( - np.asarray( - [_UnhashableTypeFloat(1.5), _UnhashableTypeFloat(2.0)], dtype=object - ), + _object_array(_UnhashableTypeFloat(1.5), _UnhashableTypeFloat(2.0)), dtype=object, ), **{ From 77dc3e4f9bf61340068a5f29c748d83b3579d44b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:56:18 +0400 Subject: [PATCH 07/10] Test the text conversion against review round 3's findings 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 --- .../test_frame_checkpoint_text_columns.py | 130 +++++++++++++++--- 1 file changed, 109 insertions(+), 21 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py index ebd832c874..8010f753df 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py @@ -113,7 +113,9 @@ def _text_frame( "person_index_dtype": PYTHON_STRING, "strata_dtype": PYARROW_STR, }, - "object index, python str strata": { + # The writer stores an object index of strings as a pyarrow-backed str + # index, as it did before this change. + "object index (stored as pyarrow str), python str strata": { "person_index_dtype": "object", "strata_dtype": PYTHON_STR, }, @@ -359,6 +361,12 @@ def _assert_matches_loop(path: Path, series: pd.Series) -> pd.Series: "non-ASCII UTF-8": ["é", "中文", "😀", "a\x00b", "ÿĀ߿ࠀ￿"], "one value throughout": ["same"] * 1_000, "very long string": ["short", "é" * 3_000_000, "tail"], + # Two whole encoding batches and one value more, with lengths 0 to 3 and + # non-ASCII text, so each batch's offsets and bytes land in their place. + "across encoding batches": [ + "é" * (position % 4) + for position in range(2 * frame_checkpoint_module._STRING_ENCODE_BATCH + 1) + ], } @@ -538,41 +546,121 @@ def test_string_subclasses_go_through_the_per_value_loop( assert calls.encoded == [2] +def _traced_peak(operation: Callable[[], object]) -> int: + """Peak memory traced by ``tracemalloc`` while ``operation`` runs.""" + + tracemalloc.start() + try: + operation() + return tracemalloc.get_traced_memory()[1] + finally: + tracemalloc.stop() + + +def _short_strings(count: int) -> list[str]: + return ["".join(["v", str(position % 1_000).zfill(6)]) for position in range(count)] + + +def _long_strings(count: int, length: int) -> list[str]: + return [ + "".join([str(position % 10), "é" * (length - 1)]) for position in range(count) + ] + + +# Values for the memory comparisons, built fresh for each test. +_MEMORY_CASES: dict[str, Callable[[], list[str | None]]] = { + "300,000 short strings": lambda: _short_strings(300_000), + "1,000 strings of 16 KiB": lambda: _long_strings(1_000, 8_192), + "20,000 strings of 400 characters": lambda: _long_strings(20_000, 400), +} + + @pytest.mark.parametrize("dtype_name", ["python_str", "python_string", "object"]) +@pytest.mark.parametrize("case", list(_MEMORY_CASES)) def test_writing_python_strings_needs_no_more_memory_than_the_per_value_loop( - dtype_name: str, + case: str, dtype_name: str ) -> None: - """Peak traced memory of encoding short strings, against the loop's. + """Peak traced memory of encoding Python strings, against the loop's. - The loop holds the offsets, a growing ``bytearray`` and its final - ``bytes`` copy. Encoding every value at once would also hold one - ``bytes`` object per value and ``bytes.join``'s buffer table, about six - times the loop's peak for short strings. + The loop's peak is about twice the payload: its growing ``bytearray`` + and the final ``bytes`` copy. Encoding every value at once would also + hold one ``bytes`` object per value and ``bytes.join``'s buffer table; + holding a batch's encoded values, their join and the ``bytearray`` at + once would reach three times a batch's text. """ - values = np.asarray( - ["".join(["v", str(position % 1_000).zfill(6)]) for position in range(300_000)], - dtype=object, - ) + values = np.asarray(_MEMORY_CASES[case](), dtype=object) series = pd.Series(values, dtype=TEXT_DTYPES[dtype_name], copy=False) stored_values = series.to_numpy(dtype=object, copy=False) - def traced_peak(encode: Callable[[], object]) -> int: - tracemalloc.start() - try: - encode() - return tracemalloc.get_traced_memory()[1] - finally: - tracemalloc.stop() - - loop_peak = traced_peak(lambda: PER_VALUE_ENCODE(stored_values)) - converted_peak = traced_peak( + loop_peak = _traced_peak(lambda: PER_VALUE_ENCODE(stored_values)) + converted_peak = _traced_peak( lambda: frame_checkpoint_module._encode_string_values(series) ) assert converted_peak <= loop_peak +def _read_as_before(group: object, spec: dict[str, object], path: Path) -> pd.Series: + """How ``_read_series`` read an object-encoded series before the change. + + ``_read_bytes_dataset`` returns the payload as ``bytes`` and drops the + array HDF5 filled, then the per-value loop decodes it. + """ + + restore_dtype = frame_checkpoint_module._declared_dtype( + spec, path=path, label="column" + ) + offsets = frame_checkpoint_module._read_numpy_dataset(group, "offsets", path) + payload = frame_checkpoint_module._read_bytes_dataset(group, "payload", path) + values = PER_VALUE_DECODE(offsets, payload, path=path, label="column") + return pd.Series(values, dtype=restore_dtype, copy=False) + + +# Allocations of their own that ``_read_series`` makes, such as its checks. +_READ_PEAK_ALLOWANCE = 64 * 1024 +# The new reader of Python strings peaks about one byte per value above the +# old one (1.4% for short strings); a second copy of the text, as an earlier +# version of the change held, would be well above this. +_READ_PEAK_RATIO = 1.02 + + +@pytest.mark.parametrize("missing_value", [False, True], ids=["complete", "missing"]) +@pytest.mark.parametrize("dtype_name", list(TEXT_DTYPES)) +@pytest.mark.parametrize("case", list(_MEMORY_CASES)) +def test_reading_text_needs_no_more_memory_than_before( + tmp_path: Path, case: str, dtype_name: str, missing_value: bool +) -> None: + """Peak traced memory of reading a text column, against the old reader's. + + A column with a missing value goes through the per-value loop in both. + ``tracemalloc`` counts NumPy arrays but not Arrow's own allocations, so + for pyarrow-backed columns it counts all of the new reader's text and + none of the old reader's Arrow copy. + """ + + values: list[str | None] = _MEMORY_CASES[case]() + if missing_value: + values[len(values) // 2] = None + series = pd.Series(values, dtype=TEXT_DTYPES[dtype_name]) + path = tmp_path / "column.h5" + spec = frame_checkpoint_module._series_spec(series, label="column") + with h5py.File(path, mode="w") as h5: + group = h5.create_group("column", track_times=False) + frame_checkpoint_module._write_series(group, series, spec) + del series, values + + with h5py.File(path, mode="r") as h5: + before_peak = _traced_peak(lambda: _read_as_before(h5["column"], spec, path)) + converted_peak = _traced_peak( + lambda: frame_checkpoint_module._read_series( + h5["column"], spec, path, label="column" + ) + ) + + assert converted_peak <= before_peak * _READ_PEAK_RATIO + _READ_PEAK_ALLOWANCE + + @pytest.mark.parametrize("dtype_name", ["python_str", "python_string", "object"]) def test_writing_python_strings_leaves_their_memory_size_unchanged( tmp_path: Path, dtype_name: str From ff7ec5dc37e6760a1cfd5fcec422241768aa2f06 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:56:18 +0400 Subject: [PATCH 08/10] Fix the text conversion's round 3 memory findings - 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 --- .../src/microcosm/build/frame_checkpoint.py | 168 +++++++++++++----- 1 file changed, 124 insertions(+), 44 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py b/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py index e556ab6bde..6a496bf1d5 100644 --- a/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py +++ b/packages/microcosm-build/src/microcosm/build/frame_checkpoint.py @@ -9,9 +9,11 @@ Object columns use a small deterministic scalar codec. Checkpoints are local build artifacts and must not be loaded from untrusted sources. -A column of strings with no missing value is converted with Arrow buffers -instead of one value at a time; it produces and parses the same bytes as the -per-value codec, which still handles every other column. +A column of strings with no missing value is converted without a Python loop +over each value: pyarrow-backed columns through their Arrow buffers, Python +strings with ``str.encode`` and ``bytes.join``, and reading with NumPy and +Arrow. It produces and parses the same bytes as the per-value codec, which +still handles every other column. """ from __future__ import annotations @@ -20,7 +22,7 @@ import math import os import struct -from collections.abc import Mapping +from collections.abc import Iterator, Mapping from dataclasses import dataclass from pathlib import Path from typing import Any @@ -80,6 +82,9 @@ # How many Python strings are encoded at a time, which bounds the temporary # ``bytes`` objects and ``bytes.join``'s buffer table. _STRING_ENCODE_BATCH = 8_192 +# About how many payload bytes each step of placing or removing the tag bytes +# covers, which bounds that step's temporary mask and copy. +_TAG_BYTE_STEP_BYTES = 1 << 20 _SUPPORTED_OBJECT_INFERRED_DTYPES = frozenset( { @@ -618,15 +623,7 @@ def _read_series( ) series = pd.Series(values.view(np.dtype(dtype)), copy=False) elif encoding == _ENCODING_OBJECT: - offsets = _read_numpy_dataset(group, "offsets", path) - payload = _read_uint8_dataset(group, "payload", path) - _check_object_offsets(offsets, len(payload), path=path, label=label) - series = _decode_string_values(offsets, payload, restore_dtype) - if series is None: - values = _decode_object_values( - offsets, payload.tobytes(), path=path, label=label - ) - series = pd.Series(values, dtype=restore_dtype, copy=False) + series = _read_object_series(group, restore_dtype, path=path, label=label) elif encoding == _ENCODING_NULLABLE_BOOLEAN: if dtype != "boolean": raise ValueError( @@ -829,14 +826,18 @@ def _encode_arrow_strings(series: pd.Series) -> tuple[np.ndarray, np.ndarray] | first, last = int(string_offsets[0]), int(string_offsets[-1]) offsets = string_offsets - first + np.arange(value_count + 1, dtype=np.int64) payload = np.empty(int(offsets[-1]), dtype=np.uint8) - tag_positions = offsets[:-1] - payload[tag_positions] = _TAG_STRING + payload[offsets[:-1]] = _TAG_STRING if last > first: - is_value_byte = np.ones(len(payload), dtype=np.bool_) - is_value_byte[tag_positions] = False - payload[is_value_byte] = np.frombuffer( + text = np.frombuffer( data_buffer, dtype=np.uint8, count=last - first, offset=first ) + for first_value, stop_value in _value_steps(offsets): + start_byte, stop_byte = int(offsets[first_value]), int(offsets[stop_value]) + is_value_byte = np.ones(stop_byte - start_byte, dtype=np.bool_) + is_value_byte[offsets[first_value:stop_value] - start_byte] = False + payload[start_byte:stop_byte][is_value_byte] = text[ + start_byte - first_value : stop_byte - stop_value + ] return offsets, payload @@ -848,12 +849,16 @@ def _encode_python_strings(values: np.ndarray) -> tuple[np.ndarray, np.ndarray] two types use ``str.encode`` and take no instance attributes. The values are encoded with ``str.encode`` through ``map``, a batch at a - time, and each batch is joined with ``bytes.join`` into one - ``bytearray``. Arrow is not used: it reads a ``str`` with CPython's - ``PyUnicode_AsUTF8AndSize``, which keeps a UTF-8 copy inside every - non-ASCII string for the rest of that string's life. + time; each batch is joined with ``bytes.join``, and the batches are + joined once at the end. Arrow is not used: it reads a ``str`` with + CPython's ``PyUnicode_AsUTF8AndSize``, which keeps a UTF-8 copy inside + every non-ASCII string for the rest of that string's life. """ + # infer_dtype refuses most other columns cheaply; the identity check + # then refuses str subclasses, which infer_dtype counts as strings. + if pd.api.types.infer_dtype(values, skipna=False) not in ("string", "empty"): + return None value_count = len(values) type_ids = np.fromiter( map(id, map(type, values)), dtype=np.uintp, count=value_count @@ -864,7 +869,7 @@ def _encode_python_strings(values: np.ndarray) -> tuple[np.ndarray, np.ndarray] # Each value's UTF-8 length goes to offsets[i + 1]; adding the tag byte # to each and summing in place then gives the end of every value. offsets = np.zeros(value_count + 1, dtype=np.int64) - payload = bytearray() + batches: list[bytes] = [] try: for start in range(0, value_count, _STRING_ENCODE_BATCH): encoded = list( @@ -875,44 +880,119 @@ def _encode_python_strings(values: np.ndarray) -> tuple[np.ndarray, np.ndarray] ) # Joining after a leading empty value puts a tag before each value. encoded.insert(0, b"") - payload += _STRING_TAG_BYTE.join(encoded) + joined = _STRING_TAG_BYTE.join(encoded) + del encoded + batches.append(joined) + del joined except UnicodeEncodeError: return None offsets[1:] += 1 np.cumsum(offsets, out=offsets) + payload = batches[0] if len(batches) == 1 else b"".join(batches) + del batches return offsets, np.frombuffer(payload, dtype=np.uint8) -def _decode_string_values( +def _value_steps(offsets: np.ndarray) -> Iterator[tuple[int, int]]: + """Consecutive ranges of whole values, each about one step of bytes. + + Each range ``(first, stop)`` covers values ``first`` to ``stop - 1``, + payload bytes ``offsets[first]`` to ``offsets[stop]``. A value longer + than a step makes its range longer. + """ + + value_count = len(offsets) - 1 + targets = np.arange( + _TAG_BYTE_STEP_BYTES, int(offsets[-1]), _TAG_BYTE_STEP_BYTES, dtype=np.int64 + ) + inner = np.searchsorted(offsets, targets).clip(1, max(value_count - 1, 1)) + boundaries = np.unique(np.concatenate([[0], inner, [value_count]])) + return zip(boundaries[:-1].tolist(), boundaries[1:].tolist(), strict=True) + + +def _read_object_series( + group: Any, + restore_dtype: str | pd.BooleanDtype | pd.StringDtype, + *, + path: Path, + label: str, +) -> pd.Series: + """Read an ``object_scalars_v1`` series, without the per-value loop if able. + + The per-value loop gets the payload as ``bytes``, with the array HDF5 + filled dropped first, as before. + """ + + offsets = _read_numpy_dataset(group, "offsets", path) + payload = _read_uint8_dataset(group, "payload", path) + _check_object_offsets(offsets, len(payload), path=path, label=label) + if _holds_only_strings(offsets, payload, restore_dtype): + series = _decode_string_values(offsets, payload, restore_dtype) + del payload + if series is not None: + return series + # The conversion rewrote both arrays in place; read the stored ones + # again for the per-value loop, which reports the invalid value. + offsets = _read_numpy_dataset(group, "offsets", path) + payload = _read_uint8_dataset(group, "payload", path) + payload_bytes = payload.tobytes() + del payload + values = _decode_object_values(offsets, payload_bytes, path=path, label=label) + return pd.Series(values, dtype=restore_dtype, copy=False) + + +def _holds_only_strings( offsets: np.ndarray, payload: np.ndarray, restore_dtype: str | pd.BooleanDtype | pd.StringDtype, -) -> pd.Series | None: - """Parse checked offsets and payload in which every value is a string. +) -> bool: + """Whether checked offsets and payload hold only strings of a text dtype. - Returns ``None`` when the declared dtype is not text, when a value's tag - is not the string tag, or when a value is not valid UTF-8; the per-value - codec reads those columns and raises its own error for invalid values. + False when the declared dtype is not text, when an offset lies outside + the payload, or when a value's tag is not the string tag. The boundary + check compares differences, which wrap around when offsets far outside + the payload overflow int64; the per-value codec reads such offsets and + raises its own error. """ is_object = isinstance(restore_dtype, str) and restore_dtype == "object" if not (is_object or isinstance(restore_dtype, pd.StringDtype)): - return None - # The boundary check compares differences, which wrap around when - # offsets far outside the payload overflow int64; the per-value codec - # reads such offsets and raises its own error. + return False if offsets.min() < 0 or offsets.max() > len(payload): - return None - tag_positions = offsets[:-1] - if not (payload[tag_positions] == _TAG_STRING).all(): - return None - is_value_byte = np.ones(len(payload), dtype=np.bool_) - is_value_byte[tag_positions] = False - string_bytes = payload[is_value_byte] - del is_value_byte - string_offsets = offsets - np.arange(len(offsets), dtype=np.int64) + return False + return bool((payload[offsets[:-1]] == _TAG_STRING).all()) + + +def _decode_string_values( + offsets: np.ndarray, + payload: np.ndarray, + restore_dtype: str | pd.StringDtype, +) -> pd.Series | None: + """Parse offsets and payload for which ``_holds_only_strings`` holds. + + Rewrites both arrays in place, so neither holds the stored values + afterwards: the text moves to the front of ``payload``, without the tag + bytes, and ``offsets`` become the text's own end offsets. A restored + pyarrow-backed column keeps both arrays. Returns ``None`` when a value is not + valid UTF-8, or when pandas refuses to build a pyarrow-backed column + from the Arrow array; the per-value codec then reads the column. + """ + + value_count = len(offsets) - 1 + for first_value, stop_value in _value_steps(offsets): + start_byte, stop_byte = int(offsets[first_value]), int(offsets[stop_value]) + is_value_byte = np.ones(stop_byte - start_byte, dtype=np.bool_) + is_value_byte[offsets[first_value:stop_value] - start_byte] = False + # Every earlier step wrote below this step's bytes, and this step + # writes from its own start downwards, so no unread byte is lost. + payload[start_byte - first_value : stop_byte - stop_value] = payload[ + start_byte:stop_byte + ][is_value_byte] + offsets -= np.arange(value_count + 1, dtype=np.int64) strings = pa.LargeStringArray.from_buffers( - len(tag_positions), pa.py_buffer(string_offsets), pa.py_buffer(string_bytes) + value_count, + pa.py_buffer(offsets), + pa.py_buffer(payload[: len(payload) - value_count]), ) try: strings.validate(full=True) # UTF-8, as the per-value decode checks From d67f150a2e695e93ac9ef47926cc69fd22b0084d Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:00:41 +0400 Subject: [PATCH 09/10] Pass writable arrays in the large text test; trim memory test dtypes - 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 --- .../test_frame_checkpoint_text_columns.py | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py index 8010f753df..436f0b3e55 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_frame_checkpoint_text_columns.py @@ -567,7 +567,11 @@ def _long_strings(count: int, length: int) -> list[str]: ] -# Values for the memory comparisons, built fresh for each test. +# Values for the memory comparisons, built fresh for each test. Each case is +# large against the fixed temporaries of one encoding batch or one step of +# placing tag bytes (about 1 MiB); the memory tests take one dtype for each +# conversion path, since str and string storage share one. +_MEMORY_DTYPES = ["pyarrow_str", "python_str", "object"] _MEMORY_CASES: dict[str, Callable[[], list[str | None]]] = { "300,000 short strings": lambda: _short_strings(300_000), "1,000 strings of 16 KiB": lambda: _long_strings(1_000, 8_192), @@ -575,7 +579,7 @@ def _long_strings(count: int, length: int) -> list[str]: } -@pytest.mark.parametrize("dtype_name", ["python_str", "python_string", "object"]) +@pytest.mark.parametrize("dtype_name", ["python_str", "object"]) @pytest.mark.parametrize("case", list(_MEMORY_CASES)) def test_writing_python_strings_needs_no_more_memory_than_the_per_value_loop( case: str, dtype_name: str @@ -626,7 +630,7 @@ def _read_as_before(group: object, spec: dict[str, object], path: Path) -> pd.Se @pytest.mark.parametrize("missing_value", [False, True], ids=["complete", "missing"]) -@pytest.mark.parametrize("dtype_name", list(TEXT_DTYPES)) +@pytest.mark.parametrize("dtype_name", _MEMORY_DTYPES) @pytest.mark.parametrize("case", list(_MEMORY_CASES)) def test_reading_text_needs_no_more_memory_than_before( tmp_path: Path, case: str, dtype_name: str, missing_value: bool @@ -934,10 +938,14 @@ def test_text_payload_over_two_gibibytes_keeps_the_per_value_loop_bytes( path=Path("large.h5"), label="column", ) + # The reader rewrites the arrays HDF5 fills in place; the encoder's + # payload can be read-only, so pass writable copies as HDF5 would. + stored_offsets, stored_payload = offsets.copy(), payload.copy() + del offsets, payload restored = frame_checkpoint_module._decode_string_values( - offsets, payload, restore_dtype + stored_offsets, stored_payload, restore_dtype ) - del payload + del stored_payload assert restored is not None assert restored.dtype == series.dtype assert restored.equals(series) From 29126a42ed8eabbd286a5f59abf4de0175f0beef Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:03:18 +0400 Subject: [PATCH 10/10] Add a changelog fragment for the checkpoint text conversion Co-Authored-By: Claude Opus 5.5 --- ...int-text-without-per-value-loop.changed.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 changelog.d/checkpoint-text-without-per-value-loop.changed.md diff --git a/changelog.d/checkpoint-text-without-per-value-loop.changed.md b/changelog.d/checkpoint-text-without-per-value-loop.changed.md new file mode 100644 index 0000000000..341dc6a779 --- /dev/null +++ b/changelog.d/checkpoint-text-without-per-value-loop.changed.md @@ -0,0 +1,24 @@ +Frame checkpoints (`microcosm.build.frame_checkpoint`) now write and read a text column, string index or strata whose values are all strings, none missing, without a Python loop over each value. They produce and parse the same `object_scalars_v1` bytes as before: a tag byte before each value's UTF-8 bytes, and the end offset of every value after a leading 0. + +- **pyarrow-backed `str` and `string` columns:** written from the column's Arrow buffers with NumPy, after widening every chunk to 64-bit offsets. +- **Object and python-backed columns:** a value takes the new path only if its type is exactly `str` or `np.str_`. + - 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. + - Arrow is not used for these values, because it attaches a cached UTF-8 copy to every non-ASCII Python string it reads. +- **Reading:** checks the offsets as before, then moves the text in place in the array HDF5 fills, about 1 MiB at a time, dropping the tag bytes. It checks UTF-8 with Arrow and restores the declared dtype, string storage and NA marker. + +These still use the per-value code, which raises the same errors as before: +- columns with a missing value, a value that is not a string, or a `str` subclass; +- a string that cannot be encoded as UTF-8, or a stored value that is not valid UTF-8; +- offsets outside the payload; +- a pyarrow-backed column that pandas refuses to build from one Arrow array. + +Checkpoint files, format versions 2 and 3, and recorded file digests are unchanged. Loaded frames hold the same values, dtypes, string storage and NA markers. + +Peak memory, measured with `tracemalloc`: +- **Writing Python strings:** at most the per-value code's (0.96–1.00 times). +- **Reading object and python-backed columns:** within 1% of before. +- **pyarrow-backed columns:** both directions now hold the text in NumPy arrays instead of Python strings plus an Arrow copy. + +Timings on a synthetic copy of the 15 text series of one post-clone US base checkpoint (9.85 million values), on a 10-core Mac at load 14–17: +- **Converting the text:** writing went from 8.78 s to 0.59 s, and reading from 4.89 s to 0.39 s. +- **A whole 253 MB checkpoint of those series:** writing went from 7.76 s to 1.02 s, and loading from 6.67 s to 1.86 s.