|
| 1 | +# Copyright The Marin Authors |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +"""Opaque chunked row format for zephyr spill files. |
| 5 | +
|
| 6 | +SpillWriter and SpillReader hide the on-disk representation from callers. |
| 7 | +Items are pickled into an opaque binary payload and written as chunks of a |
| 8 | +chunked row format. Callers do not see the schema, serialization, or storage |
| 9 | +format — they append items and read back items (or chunks of items) in the |
| 10 | +same order. |
| 11 | +
|
| 12 | +Currently backed by Parquet with a single binary payload column, a background |
| 13 | +I/O thread, and byte-budgeted row groups. The file format is an implementation |
| 14 | +detail; do not rely on it outside this module. |
| 15 | +""" |
| 16 | + |
| 17 | +import logging |
| 18 | +import pickle |
| 19 | +from collections.abc import Iterable, Iterator |
| 20 | +from typing import Any |
| 21 | + |
| 22 | +import fsspec |
| 23 | +import pyarrow as pa |
| 24 | +import pyarrow.parquet as pq |
| 25 | + |
| 26 | +from zephyr.writers import ThreadedBatchWriter |
| 27 | + |
| 28 | +logger = logging.getLogger(__name__) |
| 29 | + |
| 30 | +# Single binary payload column. Not part of the public API. |
| 31 | +_PAYLOAD_COL = "_zephyr_payload" |
| 32 | +_SCHEMA = pa.schema([pa.field(_PAYLOAD_COL, pa.binary())]) |
| 33 | + |
| 34 | + |
| 35 | +class _TableAccumulator: |
| 36 | + """Accumulates Arrow tables and yields merged results when a byte threshold is reached. |
| 37 | +
|
| 38 | + Byte-budgeted batching produces uniformly-sized output regardless of row |
| 39 | + width, which matters for write performance and memory predictability. |
| 40 | + """ |
| 41 | + |
| 42 | + def __init__(self, byte_threshold: int) -> None: |
| 43 | + self._byte_threshold = byte_threshold |
| 44 | + self._tables: list[pa.Table] = [] |
| 45 | + self._nbytes: int = 0 |
| 46 | + |
| 47 | + def add(self, table: pa.Table) -> pa.Table | None: |
| 48 | + self._tables.append(table) |
| 49 | + self._nbytes += table.nbytes |
| 50 | + if self._nbytes >= self._byte_threshold: |
| 51 | + return self._take() |
| 52 | + return None |
| 53 | + |
| 54 | + def flush(self) -> pa.Table | None: |
| 55 | + if not self._tables: |
| 56 | + return None |
| 57 | + return self._take() |
| 58 | + |
| 59 | + def _take(self) -> pa.Table: |
| 60 | + result = pa.concat_tables(self._tables, promote_options="default") |
| 61 | + self._tables.clear() |
| 62 | + self._nbytes = 0 |
| 63 | + return result |
| 64 | + |
| 65 | + |
| 66 | +def _items_to_table(items: Iterable[Any]) -> pa.Table: |
| 67 | + payloads = [pickle.dumps(item, protocol=pickle.HIGHEST_PROTOCOL) for item in items] |
| 68 | + return pa.table({_PAYLOAD_COL: pa.array(payloads, type=pa.binary())}) |
| 69 | + |
| 70 | + |
| 71 | +class SpillWriter: |
| 72 | + """Writes items to an opaque chunked row-format spill file. |
| 73 | +
|
| 74 | + Use ``write`` to stream items; the writer accumulates a byte budget and |
| 75 | + emits chunks when the budget is exceeded. Use ``write_chunk`` to commit |
| 76 | + a batch of items as its own chunk immediately (no accumulation) — useful |
| 77 | + when the caller wants each logical batch to round-trip as one chunk. |
| 78 | +
|
| 79 | + Writes are offloaded to a :class:`ThreadedBatchWriter` so one write can be |
| 80 | + in-flight while the caller produces the next batch. Backpressure, error |
| 81 | + propagation, and clean teardown on the exception path are delegated to it. |
| 82 | + """ |
| 83 | + |
| 84 | + def __init__( |
| 85 | + self, |
| 86 | + path: str, |
| 87 | + *, |
| 88 | + row_group_bytes: int = 8 * 1024 * 1024, |
| 89 | + compression: str = "zstd", |
| 90 | + compression_level: int = 1, |
| 91 | + ) -> None: |
| 92 | + self._writer = pq.ParquetWriter(path, _SCHEMA, compression=compression, compression_level=compression_level) |
| 93 | + self._accumulator = _TableAccumulator(row_group_bytes) |
| 94 | + |
| 95 | + def _drain(tables: Iterable[pa.Table]) -> None: |
| 96 | + for table in tables: |
| 97 | + self._writer.write_table(table) |
| 98 | + |
| 99 | + # maxsize=1: at most one chunk in-flight so memory stays bounded while |
| 100 | + # the producer keeps working on the next batch. |
| 101 | + self._threaded = ThreadedBatchWriter(_drain, maxsize=1) |
| 102 | + self._closed = False |
| 103 | + |
| 104 | + def write(self, items: Iterable[Any]) -> None: |
| 105 | + """Append items. Emits a chunk when the accumulated byte budget is exceeded.""" |
| 106 | + table = _items_to_table(items) |
| 107 | + if len(table) == 0: |
| 108 | + return |
| 109 | + merged = self._accumulator.add(table) |
| 110 | + if merged is not None: |
| 111 | + self._threaded.submit(merged) |
| 112 | + |
| 113 | + def write_chunk(self, items: Iterable[Any]) -> None: |
| 114 | + """Commit items as their own chunk immediately (no accumulation).""" |
| 115 | + table = _items_to_table(items) |
| 116 | + if len(table) == 0: |
| 117 | + return |
| 118 | + self._threaded.submit(table) |
| 119 | + |
| 120 | + def close(self) -> None: |
| 121 | + """Flush remaining buffered items and wait for the background writer.""" |
| 122 | + if self._closed: |
| 123 | + return |
| 124 | + self._closed = True |
| 125 | + try: |
| 126 | + remaining = self._accumulator.flush() |
| 127 | + if remaining is not None: |
| 128 | + self._threaded.submit(remaining) |
| 129 | + self._threaded.close() |
| 130 | + finally: |
| 131 | + self._writer.close() |
| 132 | + |
| 133 | + def __enter__(self) -> "SpillWriter": |
| 134 | + return self |
| 135 | + |
| 136 | + def __exit__(self, exc_type, exc_val, exc_tb) -> None: |
| 137 | + if self._closed: |
| 138 | + return |
| 139 | + self._closed = True |
| 140 | + try: |
| 141 | + if exc_type is not None: |
| 142 | + # Error path: skip final flush (partial file will never be read) |
| 143 | + # and let ThreadedBatchWriter.__exit__ tear down the thread |
| 144 | + # without blocking the caller. |
| 145 | + self._threaded.__exit__(exc_type, exc_val, exc_tb) |
| 146 | + else: |
| 147 | + remaining = self._accumulator.flush() |
| 148 | + if remaining is not None: |
| 149 | + self._threaded.submit(remaining) |
| 150 | + self._threaded.close() |
| 151 | + finally: |
| 152 | + self._writer.close() |
| 153 | + |
| 154 | + |
| 155 | +class SpillReader: |
| 156 | + """Reads items from an opaque chunked row-format spill file. |
| 157 | +
|
| 158 | + Iteration yields items one at a time in write order. ``iter_chunks`` yields |
| 159 | + lists of items grouped by the on-disk chunks; callers that want a specific |
| 160 | + batch size can pass ``batch_size`` to re-batch. |
| 161 | + """ |
| 162 | + |
| 163 | + def __init__(self, path: str, *, batch_size: int | None = None) -> None: |
| 164 | + self._path = path |
| 165 | + self._batch_size = batch_size |
| 166 | + |
| 167 | + @property |
| 168 | + def path(self) -> str: |
| 169 | + return self._path |
| 170 | + |
| 171 | + @property |
| 172 | + def num_rows(self) -> int: |
| 173 | + with fsspec.open(self._path, "rb") as f: |
| 174 | + return pq.ParquetFile(f).metadata.num_rows |
| 175 | + |
| 176 | + @property |
| 177 | + def approx_item_bytes(self) -> int: |
| 178 | + """Uncompressed payload bytes per item, read from file metadata. |
| 179 | +
|
| 180 | + Returns 0 for an empty spill. Useful as a memory-budgeting hint without |
| 181 | + exposing the underlying format. |
| 182 | + """ |
| 183 | + with fsspec.open(self._path, "rb") as f: |
| 184 | + md = pq.ParquetFile(f).metadata |
| 185 | + if md.num_rows <= 0: |
| 186 | + return 0 |
| 187 | + total = sum(md.row_group(i).column(0).total_uncompressed_size for i in range(md.num_row_groups)) |
| 188 | + return total // md.num_rows |
| 189 | + |
| 190 | + def iter_chunks(self) -> Iterator[list[Any]]: |
| 191 | + """Yield chunks of items (lists). |
| 192 | +
|
| 193 | + Chunk boundaries follow the on-disk layout unless ``batch_size`` was |
| 194 | + set on the reader, in which case items are re-batched to approximately |
| 195 | + that size. |
| 196 | + """ |
| 197 | + with fsspec.open(self._path, "rb") as f: |
| 198 | + pf = pq.ParquetFile(f) |
| 199 | + if self._batch_size is None: |
| 200 | + for i in range(pf.num_row_groups): |
| 201 | + table = pf.read_row_group(i, columns=[_PAYLOAD_COL]) |
| 202 | + payloads = table.column(_PAYLOAD_COL).to_pylist() |
| 203 | + yield [pickle.loads(p) for p in payloads] |
| 204 | + else: |
| 205 | + for record_batch in pf.iter_batches(batch_size=self._batch_size, columns=[_PAYLOAD_COL]): |
| 206 | + payloads = record_batch.column(_PAYLOAD_COL).to_pylist() |
| 207 | + yield [pickle.loads(p) for p in payloads] |
| 208 | + |
| 209 | + def __iter__(self) -> Iterator[Any]: |
| 210 | + for chunk in self.iter_chunks(): |
| 211 | + yield from chunk |
0 commit comments