diff --git a/changelog.d/ITL-1799.md b/changelog.d/ITL-1799.md new file mode 100644 index 000000000..6a31f1b64 --- /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), 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 + `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 1a48e88a5..6d0de9279 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 @@ -142,6 +152,16 @@ 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 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() + + 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: @@ -210,8 +230,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 +290,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 +1008,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``. @@ -1060,29 +1084,14 @@ 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 - # Keys must be unique across the whole read, not only within a slice. - 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 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." - ) + + 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( @@ -1090,32 +1099,106 @@ def _read_batches( 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, + yield rows + + # Keys must be unique across the whole read, not only within a chunk. + identifiers: set[str] = set() + for rows in self._chunks( + counted( + table.scan_batches( + where=None if self._condition.is_empty else self._condition, + limit=scan_limit, + asof=asof, ) + ) + ): + # 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, tables: Iterable["pa.Table"] + ) -> Generator["pa.Table", None, None]: + """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). 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 rows in tables: + if not rows.num_rows: + continue + 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 + 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 24ea0dc65..d094821d1 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,27 @@ 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() + ] + + +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.""" @@ -89,7 +111,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 +122,29 @@ 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 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( _PROJECT, "event", batch_rows=3, tag_only_columns=True @@ -110,6 +155,205 @@ def test_batches_handed_on_hold_at_most_batch_rows(self, project, monkeypatch): 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).""" + 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 + 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. + + 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_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 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] + 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 == [3, 2] + assert joins == [[3], [2]] + + 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.""" nothing = SpiralDBTableSource( @@ -389,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")) @@ -876,6 +1144,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")