From 27d4d6fd578c0d5ac3621dab1473b16f5f45d91d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 30 Nov 2026 00:52:56 -0800 Subject: [PATCH 1/5] perf(spiraldb): join small reader batches before provenance is added (ITL-1799) SpiralDB may send a scan in ~1,000-row batches; provenance (record ids, system tags, source-info tokens) was added to each one separately. Reader batches are now joined into chunks of up to batch_rows rows (or 64 MiB) before provenance, in order, values unchanged. Each reader batch is still checked against the schema as it is taken. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1799.md | 8 + .../core/sources/spiraldb_table_source.py | 175 ++++++++++++------ .../test_spiraldb_table_source_streaming.py | 86 ++++++++- 3 files changed, 212 insertions(+), 57 deletions(-) create mode 100644 changelog.d/ITL-1799.md diff --git a/changelog.d/ITL-1799.md b/changelog.d/ITL-1799.md new file mode 100644 index 000000000..d88783411 --- /dev/null +++ b/changelog.d/ITL-1799.md @@ -0,0 +1,8 @@ +### Changed + +- `SpiralDBTableSource` joins the small batches SpiralDB may send a scan in (about 1,000 + rows each) into chunks of up to `batch_rows` rows (or 64 MiB) before it adds + provenance, instead of adding it to each batch separately. Rows, record ids, system + tags and source-info tokens are unchanged; a read of a table sent in small batches is + faster. An iterating read may now read up to `batch_rows` rows ahead of the row it hands + on (ITL-1799). diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 1a48e88a5..3c083f4aa 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -48,7 +48,14 @@ import copy import dataclasses import os -from collections.abc import AsyncIterator, Collection, Generator, Iterator, Mapping +from collections.abc import ( + AsyncIterator, + Collection, + Generator, + Iterable, + Iterator, + Mapping, +) from concurrent.futures import ThreadPoolExecutor from threading import Lock from types import TracebackType @@ -95,6 +102,9 @@ DEFAULT_MAX_ROWS = 100_000 DEFAULT_BATCH_ROWS = 8_192 +# The most bytes of small reader batches joined into one chunk before ``batch_rows`` +# rows are reached (ITL-1799): bounds what a read of wide rows holds. +_CHUNK_BYTES = 64 * 1024 * 1024 # The most rows a notebook display of the source reads. PREVIEW_ROWS = 10 @@ -210,8 +220,10 @@ class SpiralDBTableSource(RootSource): Rows are read when asked for (``iter_data``, ``async_iter_data``, ``as_table`` and the dataframe methods). Each read is one scan of the table in key order. SpiralDB sends it in batches whose sizes follow its stored fragments (they cannot be - chosen); the source hands each on in slices of at most ``batch_rows`` rows, so - iterating holds one SpiralDB batch, and the slice being processed, at a time. + chosen); the source hands the rows on, in order, in chunks of at most + ``batch_rows`` rows: it slices a larger batch and joins smaller ones (up to a + bound in bytes too, ITL-1799), so iterating holds one chunk, and the SpiralDB + batch being taken, at a time. ``as_table`` and the dataframe methods hold every row they return. No row is cached: every read scans again. The table handle of the pinned version, its schema and its recorded schema are kept from the build and reused by every read (ITL-1774): @@ -268,7 +280,8 @@ class SpiralDBTableSource(RootSource): ``SourceTooLargeError``. A pipeline job keeps every row it processes in memory, about 5 KB per row and node. batch_rows: The most rows handed on at once while iterating (default 8,192). - A SpiralDB batch larger than this is held while its slices are handed on. + A SpiralDB batch larger than this is held while its slices are handed on; + smaller ones are joined until this many rows (or a bound in bytes). source_id: The source's name; its id is ``spiraldb_table_v1:`` (ITL-1425). The name defaults to ``..@``. @@ -985,7 +998,8 @@ def _batch_streams( ) -> Generator["ArrowTableStream", None, None]: """Scan the table once and yield its rows as streams of at most ``batch_rows`` rows. - Each SpiralDB batch is held while its slices are yielded. + The rows of SpiralDB's batches are joined or sliced into these streams + (``_chunks``). Args: with_source_info: As for ``_read_batches``. @@ -1061,58 +1075,111 @@ def _read_batches( # The rows are held until the read ends: read one past the cap and count. scan_limit = cap + 1 seen = 0 - # Keys must be unique across the whole read, not only within a slice. + # Keys must be unique across the whole read, not only within a chunk. identifiers: set[str] = set() - for batch in table.scan_batches( - where=None if self._condition.is_empty else self._condition, - limit=scan_limit, - asof=asof, + for rows in self._chunks( + table.scan_batches( + where=None if self._condition.is_empty else self._condition, + limit=scan_limit, + asof=asof, + ) ): - for start in range(0, max(batch.num_rows, 1), self._batch_rows): - raw = pa.Table.from_batches([batch.slice(start, self._batch_rows)]) - require_source_column_names(raw.column_names) - require_supported_nullable_types(raw.schema) - require_live_logical_types(raw.schema) - rows = arrow_utils.drop_system_columns(raw) - # Metadata too: field metadata is how a column's logical type is - # recorded, and the schema hash was computed at construction. - if not rows.schema.equals(self._table_schema, check_metadata=True): - raise ValueError( - f"SpiralDB table {self._qualified!r}: " - f"{_schema_difference(rows.schema, self._table_schema)}. " - "The table changed after the source was built; build the " - "source again to read it as it is now." - ) - seen += rows.num_rows - if max_rows is not None and seen > max_rows: - raise self._too_large( - too_many - if cap is not None and not count_first - else "the read returned more rows" - ) - # Tokens first: they refuse a null key before it is copied into - # a non-nullable column. - tokens = self._key_tokens(rows) - repeated = identifiers.intersection(tokens) - if repeated: - raise RowIdentifierError( - f"SpiralDB table {self._qualified!r}: key " - f"{sorted(repeated)[0]} appears in two rows; key values " - "must be unique, so each row has its own identifier" - ) - rows = self._with_tag_copies(rows) - if not rows.num_rows: - continue - identifiers.update(tokens) - yield self._builder._attach_provenance( - rows, - tag_columns=self._tag_columns, - schema_hash=self._schema_hash, - source_id=self.source_id, - row_identifiers=tokens, - data_tags=self._data_tags, - with_source_info=with_source_info, + seen += rows.num_rows + if max_rows is not None and seen > max_rows: + raise self._too_large( + too_many + if cap is not None and not count_first + else "the read returned more rows" + ) + # Tokens first: they refuse a null key before it is copied into + # a non-nullable column. + tokens = self._key_tokens(rows) + repeated = identifiers.intersection(tokens) + if repeated: + raise RowIdentifierError( + f"SpiralDB table {self._qualified!r}: key " + f"{sorted(repeated)[0]} appears in two rows; key values " + "must be unique, so each row has its own identifier" ) + rows = self._with_tag_copies(rows) + identifiers.update(tokens) + yield self._builder._attach_provenance( + rows, + tag_columns=self._tag_columns, + schema_hash=self._schema_hash, + source_id=self.source_id, + row_identifiers=tokens, + data_tags=self._data_tags, + with_source_info=with_source_info, + ) + + def _checked_rows(self, batch: "pa.RecordBatch") -> "pa.Table": + """Return the source's columns of one reader batch, checked against its schema. + + Raises: + ValueError: If the batch's columns differ from the source's schema. + """ + raw = pa.Table.from_batches([batch]) + require_source_column_names(raw.column_names) + require_supported_nullable_types(raw.schema) + require_live_logical_types(raw.schema) + rows = arrow_utils.drop_system_columns(raw) + # Metadata too: field metadata is how a column's logical type is recorded, + # and the schema hash was computed at construction. + if not rows.schema.equals(self._table_schema, check_metadata=True): + raise ValueError( + f"SpiralDB table {self._qualified!r}: " + f"{_schema_difference(rows.schema, self._table_schema)}. " + "The table changed after the source was built; build the " + "source again to read it as it is now." + ) + return rows + + def _chunks( + self, batches: Iterable["pa.RecordBatch"] + ) -> Generator["pa.Table", None, None]: + """Yield the rows of ``batches`` in order, in chunks of at most ``batch_rows`` rows. + + SpiralDB may send a scan in batches much smaller than asked for (about 1,000 + rows), and provenance has a fixed cost per chunk, so small reader batches are + joined (ITL-1799) and large ones sliced. A chunk is handed on once it holds + ``batch_rows`` rows or ``_CHUNK_BYTES`` bytes, or the scan ends, so a streamed + read holds at most one chunk and the reader batch being taken. Rows and values + are the reader's, in its order; no row is read that the scan would not read. + Each reader batch is checked when it is taken, before it joins a chunk. + + Raises: + ValueError: If a batch's columns differ from the source's schema. + """ + size = self._batch_rows + held: list[pa.Table] = [] + held_rows = 0 + held_bytes = 0 + for batch in batches: + rows = self._checked_rows(batch) + if not rows.num_rows: + continue + held.append(rows) + held_rows += rows.num_rows + held_bytes += rows.nbytes + if held_rows < size and held_bytes < _CHUNK_BYTES: + continue + joined = pa.concat_tables(held) if len(held) > 1 else held[0] + start = 0 + # Full chunks of ``size`` rows; a part below ``size`` is kept for the next + # chunk, unless the bytes bound was reached. + while joined.num_rows - start >= size: + yield joined.slice(start, size) + start += size + rest = joined.slice(start) + if rest.num_rows and held_bytes >= _CHUNK_BYTES: + yield rest + rest = rest.slice(rest.num_rows) + held = [rest] if rest.num_rows else [] + held_rows = rest.num_rows + held_bytes = rest.nbytes if rest.num_rows else 0 + if held: + yield pa.concat_tables(held) if len(held) > 1 else held[0] def iter_data(self) -> Iterator["tuple[TagProtocol, DataProtocol]"]: """Scan the table and yield its ``(tag, data)`` pairs, one batch held at a time.""" diff --git a/tests/test_core/sources/test_spiraldb_table_source_streaming.py b/tests/test_core/sources/test_spiraldb_table_source_streaming.py index 24ea0dc65..235dd3a3a 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_streaming.py +++ b/tests/test_core/sources/test_spiraldb_table_source_streaming.py @@ -20,6 +20,7 @@ from orcapod.errors import RowIdentifierError, SourceTooLargeError from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.serialization import resolve_source_from_config +from orcapod.core.sources import spiraldb_table_source from orcapod.sources import SpiralDBTableSource from tests.test_databases import fake_spiral_sdk @@ -72,6 +73,14 @@ def _record_ids(source: SpiralDBTableSource) -> dict[int, bytes]: return dict(zip(timestamps, record_ids, strict=True)) +def _streamed(source: SpiralDBTableSource) -> list[tuple[pa.Table, pa.Table]]: + """Return every ``(tag, data)`` pair ``iter_data`` yields, all columns as tables.""" + return [ + (tag.as_table(all_info=True), data.as_table(all_info=True)) + for tag, data in source.iter_data() + ] + + class TestNoRowIsReadUntilAsked: """A source reads no rows until they are asked for, then reads in batches.""" @@ -89,7 +98,9 @@ def test_construction_and_identity_read_no_rows(self, project): def test_iter_data_reads_batches_only_as_rows_are_consumed(self, project): """``iter_data`` takes a batch from the scan only as its rows are consumed.""" - source = SpiralDBTableSource(_PROJECT, "event", tag_only_columns=True) + source = SpiralDBTableSource( + _PROJECT, "event", batch_rows=2, tag_only_columns=True + ) rows = iter(source.iter_data()) next(rows) @@ -98,8 +109,28 @@ def test_iter_data_reads_batches_only_as_rows_are_consumed(self, project): assert sum(1 for _ in rows) == _ROWS - 1 assert [scan.batches_read for scan in fake_spiral_sdk.scan_log] == [3] + def test_iter_data_reads_ahead_at_most_batch_rows(self, project): + """Small scan batches are joined up to ``batch_rows`` rows, read no further. + + The 5 rows come 2 per scan batch: with ``batch_rows=3`` the first row is + handed on once 2 batches (4 rows) are read, never the third (ITL-1799). + """ + source = SpiralDBTableSource( + _PROJECT, "event", batch_rows=3, tag_only_columns=True + ) + rows = iter(source.iter_data()) + + next(rows) + assert [scan.batches_read for scan in fake_spiral_sdk.scan_log] == [2] + + assert sum(1 for _ in rows) == _ROWS - 1 + assert [scan.batches_read for scan in fake_spiral_sdk.scan_log] == [3] + def test_batches_handed_on_hold_at_most_batch_rows(self, project, monkeypatch): - """Batches handed on hold at most ``batch_rows`` rows, whatever is scanned.""" + """Batches handed on hold at most ``batch_rows`` rows, whatever is scanned. + + A scan batch of 4 rows is sliced; what is left is joined with the next. + """ monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 4) source = SpiralDBTableSource( _PROJECT, "event", batch_rows=3, tag_only_columns=True @@ -108,7 +139,48 @@ def test_batches_handed_on_hold_at_most_batch_rows(self, project, monkeypatch): # About the non-public batching: no public method shows the batch sizes. sizes = [s.as_table().num_rows for s in source._batch_streams()] # pyright: ignore[reportPrivateUsage] - assert sizes == [3, 1, 1] + assert sizes == [3, 2] + + def test_small_scan_batches_are_joined(self, project): + """Scan batches of 2 rows are handed on as one batch of all 5 (ITL-1799).""" + source = SpiralDBTableSource(_PROJECT, "event", tag_only_columns=True) + + # About the non-public batching: no public method shows the batch sizes. + sizes = [s.as_table().num_rows for s in source._batch_streams()] # pyright: ignore[reportPrivateUsage] + + assert sizes == [5] + assert [scan.batches_read for scan in fake_spiral_sdk.scan_log] == [3] + + @pytest.mark.parametrize("batch_rows", [1, 2, 3, 4, 5, 8_192]) + @pytest.mark.parametrize("scan_batch_rows", [1, 2, 3, 5]) + def test_rows_and_provenance_do_not_depend_on_the_batching( + self, project, monkeypatch, batch_rows, scan_batch_rows + ): + """Every scan and hand-on batch size gives one table, provenance included.""" + reference = SpiralDBTableSource( + _PROJECT, "event", batch_rows=1, tag_only_columns=True + ) + expected = reference.as_table(all_info=True) + expected_rows = _streamed(reference) + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", scan_batch_rows) + source = SpiralDBTableSource( + _PROJECT, "event", batch_rows=batch_rows, tag_only_columns=True + ) + + assert source.as_table(all_info=True).equals(expected, check_metadata=True) + assert _streamed(source) == expected_rows + + def test_a_byte_bound_hands_on_wide_rows_before_batch_rows( + self, project, monkeypatch + ): + """Joining stops at the byte bound too, so wide rows are not held by thousands.""" + monkeypatch.setattr(spiraldb_table_source, "_CHUNK_BYTES", 1) + source = SpiralDBTableSource(_PROJECT, "event", tag_only_columns=True) + + # About the non-public batching: no public method shows the batch sizes. + sizes = [s.as_table().num_rows for s in source._batch_streams()] # pyright: ignore[reportPrivateUsage] + + assert sizes == [2, 2, 1] def test_a_read_that_matches_nothing_has_the_schema_of_one_that_does(self, project): """A read matching no row yields nothing, with the schema of a full read.""" @@ -876,6 +948,14 @@ def test_a_key_repeated_in_another_slice_is_refused(self, project): with pytest.raises(RowIdentifierError, match="appears in two rows"): list(source.iter_data()) + def test_a_key_repeated_in_another_scan_batch_of_one_chunk_is_refused( + self, project + ): + """Scan batches joined into one chunk still refuse a repeated key (ITL-1799).""" + source = SpiralDBTableSource(_PROJECT, "event", record_id_columns="subject_id") + with pytest.raises(RowIdentifierError, match="SpiralDB table .* appears in"): + list(source.iter_data()) + def test_named_keys_leave_the_primary_key_as_the_tags(self, project): """The default tags are the primary key, whatever identifies the rows.""" source = SpiralDBTableSource(_PROJECT, "event", record_id_columns="timestamp") From d841b6bb709a49d46885b2b03e04d772fb206da7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 30 Nov 2026 01:57:14 -0800 Subject: [PATCH 2/5] perf(spiraldb): hand on each joined chunk as one Arrow chunk (ITL-1799) Rows handed on one by one are sliced from a single array, so iterating a joined chunk costs no more than iterating the reader's own batches. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/sources/spiraldb_table_source.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 3c083f4aa..bb558cdd8 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -152,6 +152,15 @@ def _reads_source_info(config: ColumnConfig) -> bool: return bool(config.source or config.content_hash) +def _joined(tables: list["pa.Table"]) -> "pa.Table": + """Return ``tables`` (one schema) as one table of one chunk per column, in order. + + One chunk, so that the rows handed on one by one are sliced from a single array + (ITL-1799). The copy is of one chunk of a read, at most ``batch_rows`` rows. + """ + return tables[0] if len(tables) == 1 else pa.concat_tables(tables).combine_chunks() + + def _schema_difference(found: "pa.Schema", expected: "pa.Schema") -> str: """Describe how the table's columns as found differ from the ones the source expects.""" if found.names != expected.names: @@ -1164,7 +1173,7 @@ def _chunks( held_bytes += rows.nbytes if held_rows < size and held_bytes < _CHUNK_BYTES: continue - joined = pa.concat_tables(held) if len(held) > 1 else held[0] + joined = _joined(held) start = 0 # Full chunks of ``size`` rows; a part below ``size`` is kept for the next # chunk, unless the bytes bound was reached. @@ -1179,7 +1188,7 @@ def _chunks( held_rows = rest.num_rows held_bytes = rest.nbytes if rest.num_rows else 0 if held: - yield pa.concat_tables(held) if len(held) > 1 else held[0] + yield _joined(held) def iter_data(self) -> Iterator["tuple[TagProtocol, DataProtocol]"]: """Scan the table and yield its ``(tag, data)`` pairs, one batch held at a time.""" From 455ca65df7b058262c0d70fa2b71945b3f866c65 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 30 Nov 2026 02:39:26 -0800 Subject: [PATCH 3/5] fix(spiraldb): keep joined chunks within the byte bound; copy one chunk at most (ITL-1799) Held rows are handed on before a reader batch that would take them past the byte bound, a reader batch gives a joined chunk only the rows that fill it, and the rest of the batch is handed on in slices of it. The changelog states the read-ahead as batch_rows plus one SpiralDB batch. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1799.md | 4 +- .../core/sources/spiraldb_table_source.py | 58 ++++++++++------- .../test_spiraldb_table_source_streaming.py | 63 +++++++++++++++++++ 3 files changed, 100 insertions(+), 25 deletions(-) diff --git a/changelog.d/ITL-1799.md b/changelog.d/ITL-1799.md index d88783411..8073ef19b 100644 --- a/changelog.d/ITL-1799.md +++ b/changelog.d/ITL-1799.md @@ -4,5 +4,5 @@ rows each) into chunks of up to `batch_rows` rows (or 64 MiB) before it adds provenance, instead of adding it to each batch separately. Rows, record ids, system tags and source-info tokens are unchanged; a read of a table sent in small batches is - faster. An iterating read may now read up to `batch_rows` rows ahead of the row it hands - on (ITL-1799). + faster. An iterating read may now read ahead of the row it hands on by up to + `batch_rows` rows plus one SpiralDB batch (ITL-1799). diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index bb558cdd8..948172682 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -156,7 +156,8 @@ def _joined(tables: list["pa.Table"]) -> "pa.Table": """Return ``tables`` (one schema) as one table of one chunk per column, in order. One chunk, so that the rows handed on one by one are sliced from a single array - (ITL-1799). The copy is of one chunk of a read, at most ``batch_rows`` rows. + (ITL-1799). The copy is of one joined chunk of a read (``_chunks``): at most + ``batch_rows`` rows and ``_CHUNK_BYTES`` bytes. """ return tables[0] if len(tables) == 1 else pa.concat_tables(tables).combine_chunks() @@ -1151,11 +1152,15 @@ def _chunks( SpiralDB may send a scan in batches much smaller than asked for (about 1,000 rows), and provenance has a fixed cost per chunk, so small reader batches are - joined (ITL-1799) and large ones sliced. A chunk is handed on once it holds - ``batch_rows`` rows or ``_CHUNK_BYTES`` bytes, or the scan ends, so a streamed - read holds at most one chunk and the reader batch being taken. Rows and values - are the reader's, in its order; no row is read that the scan would not read. - Each reader batch is checked when it is taken, before it joins a chunk. + joined (ITL-1799) and large ones sliced. A joined chunk holds at most + ``batch_rows`` rows and ``_CHUNK_BYTES`` bytes: rows held are handed on before + a reader batch that would take them over the byte bound, and a reader batch + gives a joined chunk only the rows that fill it. The rest of a reader batch is + handed on in slices of it, never copied, so a reader batch larger than the byte + bound is handed on as it was before. A streamed read holds at most one joined + chunk and the reader batch being taken. Rows and values are the reader's, in + its order; no row is read that the scan would not read. Each reader batch is + checked when it is taken, before any of its rows is handed on. Raises: ValueError: If a batch's columns differ from the source's schema. @@ -1168,25 +1173,32 @@ def _chunks( rows = self._checked_rows(batch) if not rows.num_rows: continue - held.append(rows) - held_rows += rows.num_rows - held_bytes += rows.nbytes - if held_rows < size and held_bytes < _CHUNK_BYTES: - continue - joined = _joined(held) + if held and held_bytes + rows.nbytes > _CHUNK_BYTES: + yield _joined(held) + held, held_rows, held_bytes = [], 0, 0 start = 0 - # Full chunks of ``size`` rows; a part below ``size`` is kept for the next - # chunk, unless the bytes bound was reached. - while joined.num_rows - start >= size: - yield joined.slice(start, size) + if held: + # Only the rows that fill the held chunk; the batch is within the + # byte bound with them (above). + part = rows.slice(0, min(size - held_rows, rows.num_rows)) + held.append(part) + held_rows += part.num_rows + held_bytes += part.nbytes + start = part.num_rows + if held_rows == size: + yield _joined(held) + held, held_rows, held_bytes = [], 0, 0 + # Whatever is left of the batch: full chunks as slices of it, the rest held + # (nothing is held here unless the whole batch went into the held chunk). + while rows.num_rows - start >= size: + yield rows.slice(start, size) start += size - rest = joined.slice(start) - if rest.num_rows and held_bytes >= _CHUNK_BYTES: - yield rest - rest = rest.slice(rest.num_rows) - held = [rest] if rest.num_rows else [] - held_rows = rest.num_rows - held_bytes = rest.nbytes if rest.num_rows else 0 + if start < rows.num_rows: + rest = rows.slice(start) + if rest.nbytes >= _CHUNK_BYTES: + yield rest + else: + held, held_rows, held_bytes = [rest], rest.num_rows, rest.nbytes if held: yield _joined(held) diff --git a/tests/test_core/sources/test_spiraldb_table_source_streaming.py b/tests/test_core/sources/test_spiraldb_table_source_streaming.py index 235dd3a3a..4e93509e5 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_streaming.py +++ b/tests/test_core/sources/test_spiraldb_table_source_streaming.py @@ -170,6 +170,69 @@ def test_rows_and_provenance_do_not_depend_on_the_batching( assert source.as_table(all_info=True).equals(expected, check_metadata=True) assert _streamed(source) == expected_rows + def test_two_batches_are_not_joined_past_the_byte_bound(self, project, monkeypatch): + """Held rows are handed on before a batch that would take them past the bound. + + The bound is one and a half 2-row scan batches: the first two are not joined, + the last (1 row) joins the second, and no joined chunk exceeds the bound. + """ + source = SpiralDBTableSource(_PROJECT, "event", tag_only_columns=True) + checked = source._checked_rows # pyright: ignore[reportPrivateUsage] + sizes: list[int] = [] + + def record(batch: pa.RecordBatch) -> pa.Table: + """Check ``batch`` as the source does, recording its size in bytes.""" + rows = checked(batch) + sizes.append(rows.nbytes) + return rows + + monkeypatch.setattr(source, "_checked_rows", record) + list(source._batch_streams()) # pyright: ignore[reportPrivateUsage] + bound = max(sizes) * 3 // 2 + monkeypatch.setattr(spiraldb_table_source, "_CHUNK_BYTES", bound) + joined = spiraldb_table_source._joined # pyright: ignore[reportPrivateUsage] + joined_bytes: list[int] = [] + + def join(tables: list[pa.Table]) -> pa.Table: + """Join ``tables`` as the source does, recording the joined size.""" + result = joined(tables) + joined_bytes.append(result.nbytes) + return result + + monkeypatch.setattr(spiraldb_table_source, "_joined", join) + + # About the non-public batching: no public method shows the batch sizes. + chunks = [s.as_table().num_rows for s in source._batch_streams()] # pyright: ignore[reportPrivateUsage] + + assert chunks == [2, 3] + assert joined_bytes and max(joined_bytes) <= bound + + def test_a_join_copies_only_the_rows_of_one_chunk(self, project, monkeypatch): + """A batch that completes a chunk gives it only the rows it lacks. + + Scan batches of 3 rows, ``batch_rows=4``: the first chunk joins 3 rows and 1, + never the whole second batch. + """ + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 3) + joined = spiraldb_table_source._joined # pyright: ignore[reportPrivateUsage] + joins: list[list[int]] = [] + + def record(tables: list[pa.Table]) -> pa.Table: + """Join ``tables`` as the source does, recording their row counts.""" + joins.append([t.num_rows for t in tables]) + return joined(tables) + + monkeypatch.setattr(spiraldb_table_source, "_joined", record) + source = SpiralDBTableSource( + _PROJECT, "event", batch_rows=4, tag_only_columns=True + ) + + # About the non-public batching: no public method shows the batch sizes. + chunks = [s.as_table().num_rows for s in source._batch_streams()] # pyright: ignore[reportPrivateUsage] + + assert chunks == [4, 1] + assert joins == [[3, 1], [1]] + def test_a_byte_bound_hands_on_wide_rows_before_batch_rows( self, project, monkeypatch ): From e3c1df449fb2840fdb5be16bb5946cc375cfac6e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 30 Nov 2026 03:28:36 -0800 Subject: [PATCH 4/5] test(spiraldb): batching invariance over several tags and data, sync and async (ITL-1799) Release a reader batch's slices once they are held, so a flush releases the batch. Co-Authored-By: Claude Opus 5.5 --- .../core/sources/spiraldb_table_source.py | 3 + .../test_spiraldb_table_source_streaming.py | 73 +++++++++++++++++++ 2 files changed, 76 insertions(+) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 948172682..b9a50765a 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -1185,6 +1185,8 @@ def _chunks( held_rows += part.num_rows held_bytes += part.nbytes start = part.num_rows + # Held in ``held`` only: a flush below then releases the batch. + del part if held_rows == size: yield _joined(held) held, held_rows, held_bytes = [], 0, 0 @@ -1199,6 +1201,7 @@ def _chunks( yield rest else: held, held_rows, held_bytes = [rest], rest.num_rows, rest.nbytes + del rest if held: yield _joined(held) diff --git a/tests/test_core/sources/test_spiraldb_table_source_streaming.py b/tests/test_core/sources/test_spiraldb_table_source_streaming.py index 4e93509e5..a1919ecac 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_streaming.py +++ b/tests/test_core/sources/test_spiraldb_table_source_streaming.py @@ -81,6 +81,19 @@ def _streamed(source: SpiralDBTableSource) -> list[tuple[pa.Table, pa.Table]]: ] +def _async_streamed(source: SpiralDBTableSource) -> list[tuple[pa.Table, pa.Table]]: + """Return every ``(tag, data)`` pair ``async_iter_data`` yields, as ``_streamed``.""" + + async def collect() -> list[tuple[pa.Table, pa.Table]]: + """The pairs, all columns as tables.""" + return [ + (tag.as_table(all_info=True), data.as_table(all_info=True)) + async for tag, data in source.async_iter_data() + ] + + return asyncio.run(collect()) + + class TestNoRowIsReadUntilAsked: """A source reads no rows until they are asked for, then reads in batches.""" @@ -169,6 +182,66 @@ def test_rows_and_provenance_do_not_depend_on_the_batching( assert source.as_table(all_info=True).equals(expected, check_metadata=True) assert _streamed(source) == expected_rows + assert _async_streamed(source) == expected_rows + + @pytest.mark.parametrize( + "key_order", [("subject_id", "timestamp"), ("timestamp", "subject_id")] + ) + @pytest.mark.parametrize( + "data_order", [("amplitude", "label"), ("label", "amplitude")] + ) + @pytest.mark.parametrize("tag_only_columns", [True, False]) + @pytest.mark.parametrize( + ("batch_rows", "scan_batch_rows"), [(3, 2), (4, 3), (8_192, 2)] + ) + def test_rows_of_several_tags_and_data_do_not_depend_on_the_batching( + self, + project, + monkeypatch, + key_order, + data_order, + tag_only_columns, + batch_rows, + scan_batch_rows, + ): + """Two key tags and two data columns, in several arrangements and roles. + + Each arrangement is its own table: sync and async rows and the whole table, + provenance included, are those of one row per batch (ITL-1799). + """ + fields = { + "subject_id": pa.field("subject_id", pa.string()), + "timestamp": pa.field("timestamp", pa.uint64()), + } + rows = pa.table( + { + "subject_id": ["m1", "m2", "m1", "m2", "m1"], + "timestamp": pa.array([1, 1, 2, 2, 3], pa.uint64()), + "amplitude": pa.array([0.5, 1.5, 2.5, 3.5, 4.5], pa.float32()), + "label": ["a", "b", "c", "d", "e"], + } + ).select([*key_order, *data_order]) + rows = rows.cast( + pa.schema([pa.field(f.name, f.type, True) for f in rows.schema]) + ) + project.create_table( + "default.wide", key_schema=pa.schema([fields[k] for k in key_order]) + ).write(rows) + reference = SpiralDBTableSource( + _PROJECT, "wide", batch_rows=1, tag_only_columns=tag_only_columns + ) + expected = reference.as_table(all_info=True) + expected_rows = _streamed(reference) + assert len(reference.keys()[0]) == 2 + assert len(reference.keys()[1]) >= 2 + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", scan_batch_rows) + source = SpiralDBTableSource( + _PROJECT, "wide", batch_rows=batch_rows, tag_only_columns=tag_only_columns + ) + + assert source.as_table(all_info=True).equals(expected, check_metadata=True) + assert _streamed(source) == expected_rows + assert _async_streamed(source) == expected_rows def test_two_batches_are_not_joined_past_the_byte_bound(self, project, monkeypatch): """Held rows are handed on before a batch that would take them past the bound. From 4dbed8bca31617b4ee50ff284f33a0c51646894f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 30 Nov 2026 05:06:02 -0800 Subject: [PATCH 5/5] fix(spiraldb): join whole reader batches only; check max_rows as each batch is taken (ITL-1799) A held rest of a sliced reader batch kept the whole batch's buffers alive while the next batch was read, and a restricted read took further batches after the rows seen were already over max_rows. Now only whole small reader batches are joined; a batch of batch_rows rows or more (or over the byte bound) is handed on in slices before the next batch is taken, as on main. The max_rows count is checked on each reader batch as it is taken. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1799.md | 2 +- .../core/sources/spiraldb_table_source.py | 104 ++++++++---------- .../test_spiraldb_table_source_streaming.py | 76 +++++++++++-- 3 files changed, 117 insertions(+), 65 deletions(-) diff --git a/changelog.d/ITL-1799.md b/changelog.d/ITL-1799.md index 8073ef19b..6a31f1b64 100644 --- a/changelog.d/ITL-1799.md +++ b/changelog.d/ITL-1799.md @@ -1,7 +1,7 @@ ### Changed - `SpiralDBTableSource` joins the small batches SpiralDB may send a scan in (about 1,000 - rows each) into chunks of up to `batch_rows` rows (or 64 MiB) before it adds + rows each), whole, into chunks of up to `batch_rows` rows (or 64 MiB) before it adds provenance, instead of adding it to each batch separately. Rows, record ids, system tags and source-info tokens are unchanged; a read of a table sent in small batches is faster. An iterating read may now read ahead of the row it hands on by up to diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index b9a50765a..6d0de9279 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -1084,23 +1084,34 @@ def _read_batches( elif cap is not None: # The rows are held until the read ends: read one past the cap and count. scan_limit = cap + 1 - seen = 0 + + def counted( + batches: Iterable["pa.RecordBatch"], + ) -> Generator["pa.Table", None, None]: + """Check each reader batch, and the cap on the rows seen, as it is taken.""" + seen = 0 + for batch in batches: + rows = self._checked_rows(batch) + seen += rows.num_rows + if max_rows is not None and seen > max_rows: + raise self._too_large( + too_many + if cap is not None and not count_first + else "the read returned more rows" + ) + yield rows + # Keys must be unique across the whole read, not only within a chunk. identifiers: set[str] = set() for rows in self._chunks( - table.scan_batches( - where=None if self._condition.is_empty else self._condition, - limit=scan_limit, - asof=asof, + counted( + table.scan_batches( + where=None if self._condition.is_empty else self._condition, + limit=scan_limit, + asof=asof, + ) ) ): - seen += rows.num_rows - if max_rows is not None and seen > max_rows: - raise self._too_large( - too_many - if cap is not None and not count_first - else "the read returned more rows" - ) # Tokens first: they refuse a null key before it is copied into # a non-nullable column. tokens = self._key_tokens(rows) @@ -1146,67 +1157,48 @@ def _checked_rows(self, batch: "pa.RecordBatch") -> "pa.Table": return rows def _chunks( - self, batches: Iterable["pa.RecordBatch"] + self, tables: Iterable["pa.Table"] ) -> Generator["pa.Table", None, None]: - """Yield the rows of ``batches`` in order, in chunks of at most ``batch_rows`` rows. + """Yield the rows of ``tables`` in order, in chunks of at most ``batch_rows`` rows. SpiralDB may send a scan in batches much smaller than asked for (about 1,000 rows), and provenance has a fixed cost per chunk, so small reader batches are - joined (ITL-1799) and large ones sliced. A joined chunk holds at most - ``batch_rows`` rows and ``_CHUNK_BYTES`` bytes: rows held are handed on before - a reader batch that would take them over the byte bound, and a reader batch - gives a joined chunk only the rows that fill it. The rest of a reader batch is - handed on in slices of it, never copied, so a reader batch larger than the byte - bound is handed on as it was before. A streamed read holds at most one joined - chunk and the reader batch being taken. Rows and values are the reader's, in - its order; no row is read that the scan would not read. Each reader batch is - checked when it is taken, before any of its rows is handed on. - - Raises: - ValueError: If a batch's columns differ from the source's schema. + joined (ITL-1799). Only whole reader batches are joined, into a chunk of at most + ``batch_rows`` rows and ``_CHUNK_BYTES`` bytes; held rows are handed on before a + batch that would take them over either bound. A reader batch of ``batch_rows`` + rows or more, or of ``_CHUNK_BYTES`` bytes or more, is handed on as before, in + slices of it, all before the next batch is taken: a slice shares its batch's + buffers, so none is ever held. A streamed read holds at most one joined chunk + and the reader batch being taken. Rows and values are the reader's, in its + order. """ size = self._batch_rows held: list[pa.Table] = [] held_rows = 0 held_bytes = 0 - for batch in batches: - rows = self._checked_rows(batch) + for rows in tables: if not rows.num_rows: continue - if held and held_bytes + rows.nbytes > _CHUNK_BYTES: + large = rows.num_rows >= size or rows.nbytes >= _CHUNK_BYTES + if held and ( + large + or held_rows + rows.num_rows > size + or held_bytes + rows.nbytes > _CHUNK_BYTES + ): yield _joined(held) held, held_rows, held_bytes = [], 0, 0 - start = 0 - if held: - # Only the rows that fill the held chunk; the batch is within the - # byte bound with them (above). - part = rows.slice(0, min(size - held_rows, rows.num_rows)) - held.append(part) - held_rows += part.num_rows - held_bytes += part.nbytes - start = part.num_rows - # Held in ``held`` only: a flush below then releases the batch. - del part - if held_rows == size: - yield _joined(held) - held, held_rows, held_bytes = [], 0, 0 - # Whatever is left of the batch: full chunks as slices of it, the rest held - # (nothing is held here unless the whole batch went into the held chunk). - while rows.num_rows - start >= size: - yield rows.slice(start, size) - start += size - if start < rows.num_rows: - rest = rows.slice(start) - if rest.nbytes >= _CHUNK_BYTES: - yield rest - else: - held, held_rows, held_bytes = [rest], rest.num_rows, rest.nbytes - del rest + if large: + for start in range(0, rows.num_rows, size): + yield rows.slice(start, size) + else: + held.append(rows) + held_rows += rows.num_rows + held_bytes += rows.nbytes if held: yield _joined(held) def iter_data(self) -> Iterator["tuple[TagProtocol, DataProtocol]"]: - """Scan the table and yield its ``(tag, data)`` pairs, one batch held at a time.""" + """Scan the table and yield its ``(tag, data)`` pairs, one chunk held at a time.""" for stream in self._batch_streams(): yield from stream.iter_data() diff --git a/tests/test_core/sources/test_spiraldb_table_source_streaming.py b/tests/test_core/sources/test_spiraldb_table_source_streaming.py index a1919ecac..d094821d1 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_streaming.py +++ b/tests/test_core/sources/test_spiraldb_table_source_streaming.py @@ -142,7 +142,8 @@ def test_iter_data_reads_ahead_at_most_batch_rows(self, project): def test_batches_handed_on_hold_at_most_batch_rows(self, project, monkeypatch): """Batches handed on hold at most ``batch_rows`` rows, whatever is scanned. - A scan batch of 4 rows is sliced; what is left is joined with the next. + A scan batch of 4 rows is sliced and its rest handed on alone (a slice + shares its batch's buffers, so it is never held), then the last row. """ monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 4) source = SpiralDBTableSource( @@ -152,7 +153,42 @@ def test_batches_handed_on_hold_at_most_batch_rows(self, project, monkeypatch): # About the non-public batching: no public method shows the batch sizes. sizes = [s.as_table().num_rows for s in source._batch_streams()] # pyright: ignore[reportPrivateUsage] - assert sizes == [3, 2] + assert sizes == [3, 1, 1] + + @pytest.mark.parametrize("read", ["sync", "async"]) + def test_the_rest_of_a_sliced_batch_is_handed_on_before_the_next_is_taken( + self, project, monkeypatch, read + ): + """No part of a sliced scan batch waits for the next one (ITL-1799). + + A slice shares its scan batch's buffers, so a held rest would keep the whole + batch alive while the next is read. 3-row scan batches, ``batch_rows=2``: the + third row is handed on with only the first batch taken. + """ + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 3) + source = SpiralDBTableSource( + _PROJECT, "event", batch_rows=2, tag_only_columns=True + ) + taken: list[int] = [] + + def note(timestamp: object) -> None: + """Record how many scan batches were taken when row 3 is handed on.""" + if timestamp == 3: + taken.extend(scan.batches_read for scan in fake_spiral_sdk.scan_log) + + if read == "sync": + for tag, _ in source.iter_data(): + note(tag.as_dict()["timestamp"]) + else: + + async def consume() -> None: + """Read every row.""" + async for tag, _ in source.async_iter_data(): + note(tag.as_dict()["timestamp"]) + + asyncio.run(consume()) + + assert taken == [1] def test_small_scan_batches_are_joined(self, project): """Scan batches of 2 rows are handed on as one batch of all 5 (ITL-1799).""" @@ -280,11 +316,11 @@ def join(tables: list[pa.Table]) -> pa.Table: assert chunks == [2, 3] assert joined_bytes and max(joined_bytes) <= bound - def test_a_join_copies_only_the_rows_of_one_chunk(self, project, monkeypatch): - """A batch that completes a chunk gives it only the rows it lacks. + def test_only_whole_scan_batches_are_joined(self, project, monkeypatch): + """A batch that would take a chunk past ``batch_rows`` starts the next one. - Scan batches of 3 rows, ``batch_rows=4``: the first chunk joins 3 rows and 1, - never the whole second batch. + Scan batches of 3 and 2 rows, ``batch_rows=4``: the batches are handed on + whole, never split to fill a chunk (ITL-1799). """ monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 3) joined = spiraldb_table_source._joined # pyright: ignore[reportPrivateUsage] @@ -303,8 +339,8 @@ def record(tables: list[pa.Table]) -> pa.Table: # About the non-public batching: no public method shows the batch sizes. chunks = [s.as_table().num_rows for s in source._batch_streams()] # pyright: ignore[reportPrivateUsage] - assert chunks == [4, 1] - assert joins == [[3, 1], [1]] + assert chunks == [3, 2] + assert joins == [[3], [2]] def test_a_byte_bound_hands_on_wide_rows_before_batch_rows( self, project, monkeypatch @@ -597,6 +633,30 @@ def test_a_filtered_read_over_the_cap_stops_while_reading(self, project): with pytest.raises(SourceTooLargeError, match="max_rows=3"): list(source.iter_data()) + @pytest.mark.parametrize("route", ["as_table", "iter_data"]) + def test_a_filtered_read_over_the_cap_takes_no_further_scan_batch( + self, project, route + ): + """The cap is checked on each scan batch as it is taken (ITL-1799). + + ``max_rows=1`` and 2-row scan batches: the first batch is over the cap, so no + second batch is taken, however many rows a chunk could still join. + """ + source = SpiralDBTableSource( + _PROJECT, + "event", + max_rows=1, + where={"subject_id": "m1"}, + tag_only_columns=True, + ) + + with pytest.raises(SourceTooLargeError, match="max_rows=1"): + if route == "as_table": + source.as_table() + else: + list(source.iter_data()) + assert [scan.batches_read for scan in fake_spiral_sdk.scan_log] == [1] + def test_a_filtered_read_within_the_cap_is_read(self, project): """A ``where`` read matching no more than ``max_rows`` rows is read.""" project.table("default.event").write(_rows([7, 8], subject="m2"))