Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions changelog.d/ITL-1799.md
Original file line number Diff line number Diff line change
@@ -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).
185 changes: 134 additions & 51 deletions src/orcapod/core/sources/spiraldb_table_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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:<name>``
(ITL-1425). The name defaults to
``<project_id>.<dataset>.<table_name>@<table id>``.
Expand Down Expand Up @@ -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``.
Expand Down Expand Up @@ -1060,62 +1084,121 @@ 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(
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,
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()

Expand Down
Loading
Loading