Skip to content
Merged
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
16 changes: 16 additions & 0 deletions changelog.d/ITL-1457.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
### Changed

- SpiralDB sources sign in and read a dataset's schema table less often (ITL-1457). The
sources of one process that use one service address and one sign-in share one spiral-sdk
client, and the rows of a dataset's schema table are kept for the version they were read
from: a new source of an already-read dataset opens the schema table to see its version
and reads it again only when the version moved. A changed environment or saved login, or
a client one of whose calls failed, gives the next new source a new client; closing a
source affects no other, and a forked process starts with none. A second source in a
process builds about 3x faster. Rows, order, hashes, source ids, refusals and warnings
are unchanged.
- `SpiralDBTableSource.as_table()` with `max_rows` no longer counts the table's keys first
(ITL-1457): it reads at most one row past the cap and raises the same
`SourceTooLargeError`. A read that hands rows on as it goes (`iter_data`, an async read)
still counts first. On a table over the cap the refusal now costs a read of `max_rows + 1`
rows instead of a read of one key column.
11 changes: 10 additions & 1 deletion docs/concepts/sources.md
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,13 @@ from the saved login. With neither, Orcapod raises `SpiralDBSignInError` instead
the client start a sign-in. A saved login that has expired is not detected: the client may
then print a sign-in prompt and wait. Stop it and run `uv run spiral login` again.

The SpiralDB sources of one process that use one service address and one sign-in share one
spiral-sdk client, and a dataset's schema table is read once for each of its versions: a new
source of an already-read dataset opens the schema table to see its version, and reads it
again only when the version moved. A changed environment or saved login, or a client one of
whose calls failed, gives the next new source a new client. Closing a source affects no other;
the client goes with the last source that uses it, and a forked process starts with none.

Orcapod only reads SpiralDB for now. Writing a SpiralDB table (`SpiralDBConnector`, or a job
whose database is on one) raises `SpiralDBWriteNotSupportedError`; store a job's results in
another database, such as `DeltaTableDatabase`.
Expand Down Expand Up @@ -645,7 +652,9 @@ would return more raises `SourceTooLargeError`, which says so and gives the ways
`limit=`, `where=`, or a larger `max_rows` (`max_rows=None` removes the cap). When nothing
but `limit=` bounds the read, the source decides before it hands on any row, by counting the
table's keys. SpiralDB keeps no row count of a keyed table, so the count is a read of one key
column; it stops one past the cap and is remembered for the version. The cap is there
column; it stops one past the cap and is remembered for the version. `as_table()` hands on no
row before it ends, so it does not count first: it reads at most one row past the cap and
raises the same error. The cap is there
because a pipeline job keeps every row it processes in memory, about 5 KB per row for each
node, so 100,000 rows cost about 0.5 GB per node. A table of millions of rows can be iterated
with `max_rows=None`, but it cannot yet be run through a job on a laptop.
Expand Down
62 changes: 41 additions & 21 deletions src/orcapod/core/sources/spiraldb_table_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@
Requires the ``spiraldb`` optional extra: ``pip install orcapod[spiraldb]``.
Authentication is spiral-sdk's: ``SPIRAL_*`` environment variables, or the credentials
``spiral login`` saved.
The SDK client is reused for reads and freshness checks, including on restricted copies.
Use a new source after changing the SDK endpoint, credentials or options. Use the source
as a context manager or call ``close()`` after its reads and jobs have finished.
The SDK client is used by every source of one service address and sign-in in a process
(ITL-1457), and by its restricted copies. Use a new source after changing the SDK
endpoint, credentials or options: it signs in again. Use the source as a context manager
or call ``close()`` after its reads and jobs have finished; no other source is affected.

Example::

Expand Down Expand Up @@ -980,14 +981,15 @@ def _key_tokens(self, table: "pa.Table") -> list[str]:
) from exc

def _batch_streams(
self, *, with_source_info: bool = True
self, *, with_source_info: bool = True, count_first: bool = True
) -> 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.

Args:
with_source_info: As for ``_read_batches``.
count_first: As for ``_read_batches``.

Raises:
SourceTooLargeError: If the read would return, or returns, more than
Expand All @@ -1003,6 +1005,7 @@ def _batch_streams(
limit=self._limit,
max_rows=self._max_rows,
with_source_info=with_source_info,
count_first=count_first,
)

def _read_batches(
Expand All @@ -1013,6 +1016,7 @@ def _read_batches(
limit: int | None,
max_rows: int | None,
with_source_info: bool = True,
count_first: bool = True,
) -> Generator["ArrowTableStream", None, None]:
"""Scan the table once, reading at most ``limit`` rows, in streams of ``batch_rows``.

Expand All @@ -1026,33 +1030,42 @@ def _read_batches(
with_source_info: Whether each stream holds its rows' source-info tokens.
``False`` only where the caller returns no source-info column and
hashes no row (``_whole_table``): the streams then hold null tokens.
count_first: Whether an unrestricted read that ``limit`` does not keep under
``max_rows`` counts the table's rows before it hands any row on. A
caller that hands no row on before the read ends (``as_table``) passes
``False``: the scan then stops one row past ``max_rows`` and raises the
same error, with no separate count (ITL-1457).

Raises:
SourceTooLargeError: If the read would return, or returns, more than
``max_rows`` rows.
ValueError: If a batch's columns differ from the source's schema, or a
key column holds a null.
"""
if (
max_rows is not None
and self._condition.is_empty
and (limit is None or limit > max_rows)
):
# Nothing but limit bounds the read, and the limit does not keep it
# under the cap: the table's row count decides, before any row is
# handed on (so no row reaches a function of a job that would fail).
# Counting stops one past the cap.
if table.count_rows(asof=asof, at_most=max_rows + 1) > max_rows:
bound = "" if limit is None else f" (limit={limit:,})"
raise self._too_large(
f"the table has more than {max_rows:,} rows{bound}"
)
# Nothing but limit bounds the read, and the limit does not keep it under the
# cap: the table's row count decides.
cap = (
max_rows
if self._condition.is_empty and (limit is None or limit > (max_rows or 0))
else None
)
bound = "" if limit is None else f" (limit={limit:,})"
too_many = f"the table has more than {cap or 0:,} rows{bound}"
scan_limit = limit
if cap is not None and count_first:
# Before any row is handed on (so no row reaches a function of a job that
# would fail). Counting stops one past the cap.
if table.count_rows(asof=asof, at_most=cap + 1) > cap:
raise self._too_large(too_many)
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=limit,
limit=scan_limit,
asof=asof,
):
for start in range(0, max(batch.num_rows, 1), self._batch_rows):
Expand All @@ -1072,7 +1085,11 @@ def _read_batches(
)
seen += rows.num_rows
if max_rows is not None and seen > max_rows:
raise self._too_large("the read returned more 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)
Expand Down Expand Up @@ -1133,7 +1150,10 @@ def as_table(
"""Scan the table and return its rows as one PyArrow table (all held in memory)."""
config = ColumnConfig.handle_config(columns, all_info=all_info)
return self._whole_table(
self._batch_streams(with_source_info=_reads_source_info(config)),
# The rows are held until the read ends: no separate count (ITL-1457).
self._batch_streams(
with_source_info=_reads_source_info(config), count_first=False
),
columns=columns,
all_info=all_info,
)
Expand Down
Loading
Loading