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
33 changes: 33 additions & 0 deletions changelog.d/ITL-1774.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
### Added

- `SpiralDBTableSource.pinned_version` (the table version every read scans) and
`SpiralDBTableSource.has_newer_version()`, which says whether the table has a newer
version. It makes one metadata lookup, reads no row, and moves nothing.
`check_for_new_data()`, which every run calls first, moves the pin. `head()` and the
notebook preview never call either.

### Changed

- A `SpiralDBTableSource` read makes no metadata round trip (ITL-1774). It reuses the table
handle of the pinned version, its schema and its recorded schema, kept from the build.
spiral-sdk's keyed table handle is an immutable snapshot, so a read still returns
exactly the pinned version's rows. Rows, types and order are unchanged on every route.
Before, each read opened the table by name again and read the dataset's schema record
again. Measured on a test project, a one-row restricted read went from about 3.2 s to
about 2.1 s. `check_for_new_data()` still looks the table up, pins a newer version and
replaces the handle with it.
- A table dropped and created again, a table that is gone, a table whose columns changed,
and a schema record that cannot be read are now found by `check_for_new_data()`. Every
run calls it first. A source built with `asof` is checked too: one lookup, plus its own
version's schema record. Its pin never moves. Before, its check read nothing.
After a check refuses the table, every read of the source refuses too, before scanning,
until a later check accepts the table. A read outside a run (`as_table()`,
`iter_data()`, `head()`) of a table replaced since the last check now reads the pinned
version of the original table, or raises the store's error if that version is gone.
Before, it refused with "dropped and created again". A table that now has a column
in the system-tag namespace is refused and held the same way.
- A `SpiralDBTableSource` built with `asof` takes its columns from that version, prepared
at build, so its first read also makes no metadata round trip. On `main`, a source
configured with `asof=0` (the version before the table's first write, with only key
columns) built with the latest version's columns and returned zero rows on reads,
and now the build rejects `asof=0` because that version has no data columns.
23 changes: 19 additions & 4 deletions docs/concepts/sources.md
Original file line number Diff line number Diff line change
Expand Up @@ -595,7 +595,10 @@ Things to know about Spiral tables:
Building a `SpiralDBTableSource` reads no rows. It reads the table's schema, key columns and
table id, which takes about a second whatever the table's size. `output_schema()`, `keys()`,
`content_hash()` and `pipeline_hash()` read no rows either. Rows are read when you ask for
them, and every read scans the table again:
them, and every read scans the table again. What the build read about the table (the table
of the pinned version, its schema and its recorded schema) is kept and reused, so a read
makes no metadata round trip and reads only the pinned version; a check
([What a source does at a run](#what-a-source-does-at-a-run)) reads the metadata again:

- `iter_data()` and a pipeline job hand the rows on in batches of at most `batch_rows`
rows (default 8,192). SpiralDB sends a scan in batches that follow its stored fragments,
Expand Down Expand Up @@ -624,7 +627,11 @@ print(first.row_count_estimate) # rows in the whole table; reads every key to c
- `asof=` reads the table as of an earlier version, and keeps reading it. Without it, a
source reads the version the table had when the source was built, in every read, until a
run finds a newer one (see [What a source does at a run](#what-a-source-does-at-a-run)):
`head()`, `as_table()` and the preview outside a run never move it.
`head()`, `as_table()` and the preview outside a run never move it. To know, outside a
run, whether the reads are behind the table: `source.pinned_version` is the version every
read scans, and `source.has_newer_version()` says whether the table has a newer one (one
metadata lookup; it reads no row and moves nothing). `check_for_new_data()`, which every
run calls first, moves the pin. `head()` and the preview never ask.

**The row cap.** One read returns at most `max_rows` rows (default 100,000). A read that
would return more raises `SourceTooLargeError`, which says so and gives the ways out:
Expand Down Expand Up @@ -995,7 +1002,9 @@ every depth and metadata. The name is reserved, and listings leave it out.
and dataset, how many tables, and a digest of their rows. When it is missing or does not
fit, every read that opens a table of the dataset raises `TableSchemaError`, and so does a
schema table that cannot be read. A connector's table handle that has already read one
version keeps the schema it read it with.
version keeps the schema it read it with, and so does a `SpiralDBTableSource`: it reads
the record when it is built and at each check, and refuses every read after a check that
raised `TableSchemaError`, until a check accepts the table again.
- **Joins are type strict.** A key column that is `T` in a recorded table and `T | None` in one
that is not is an error, not a conversion.

Expand Down Expand Up @@ -1204,7 +1213,13 @@ only the table's metadata.
A table or file whose columns changed (a CSV file's types are inferred again on each read,
so a null in a column that had none is a change of type), a table that is gone or empty, or a
SpiralDB table dropped and created again, fails the check: the source's schema and table are
part of its identity, so build a new source to read it. A column that loses its nulls keeps
part of its identity, so build a new source to read it. A SpiralDB source whose check failed
this way (or because the table is gone) refuses every read after it too, before scanning; a
source built with `asof` is checked the same way, and its pin never moves. A SpiralDB read
outside a run
(`as_table()`, `iter_data()`, `head()`) makes no lookup of its own: it reads the pinned
version of the table the source was built on, and finds a replaced table only at the next
check. A column that loses its nulls keeps
its nullable type (where nullability is inferred from the rows: a CSV file read without
`schema=`, a database whose connector gives no column information), so it is not a
change of columns.
Expand Down
145 changes: 132 additions & 13 deletions src/orcapod/core/sources/spiraldb_table_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,12 @@ class SpiralDBTableSource(RootSource):
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.
``as_table`` and the dataframe methods hold every row they return. Nothing is
cached: every read scans again.
``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):
a read makes no metadata round trip, and reads the pinned version only. A table
dropped and created again under the same name is found by ``check_for_new_data``,
which every run calls first, not by a plain read.

Display. ``head(n)`` and the notebook display (its ``head()``) read only the first
``n`` rows (``PREVIEW_ROWS``, 10, by default), in one scan to which ``max_rows`` does
Expand Down Expand Up @@ -367,6 +371,8 @@ def __init__(
self._overrides = None if overrides is None else dict(overrides)
self._connection: SpiralDBConnector | None = None
self._connection_lock = Lock()
# Checks of one source run one at a time: the refusal is the latest's verdict.
self._check_lock = Lock()
self._pid = os.getpid()
self._closed = False
self._condition = Condition()
Expand Down Expand Up @@ -397,12 +403,21 @@ def __init__(
"record_id_columns=[...]."
)
self._table_id = table.table_id
schema = table.arrow_schema()
# The version every read scans is prepared now (its schema and schema
# record), also a given older one, so a read makes no metadata call.
schema = table.arrow_schema(asof=asof)
require_names_not_system_tags(schema.names)
require_supported_nullable_types(schema)
# One version for every read of this source object. A given version is
# used as it is; a table that was never written has no version to pin.
self._asof = asof if asof is not None else (table.version() or None)
# Every read scans this handle at the pinned version: a snapshot, so it
# serves exactly that version. A check that pins a newer one replaces it.
self._handle = table
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
# What the latest check refused the table for (replaced, other columns,
# a schema record that cannot be read): every read refuses with it, before
# scanning, until a check accepts the table again.
self._refusal: ValueError | InputValidationError | None = None

# The default tags are the primary key, whatever identifies the rows.
resolved_tags = (
Expand Down Expand Up @@ -642,11 +657,13 @@ def _copy(self) -> "SpiralDBTableSource":
raise RuntimeError("SpiralDBTableSource is closed")
duplicate = copy.copy(self)
duplicate._connection = connection.share_client()
duplicate._handle = self._handle.with_connector(duplicate._connection)
duplicate._tags_as_data = dict(self._tags_as_data)
duplicate._overrides = (
None if self._overrides is None else dict(self._overrides)
)
duplicate._connection_lock = Lock()
duplicate._check_lock = Lock()
duplicate._content_hash_cache = {}
duplicate._pipeline_hash_cache = {}
return duplicate
Expand Down Expand Up @@ -763,8 +780,36 @@ def _qualified(self) -> str:
"""The table as error messages name it."""
return f"{self._project_id}/{self._dataset}.{self._table_name}"

def _pinned_table(self) -> SpiralDBTable:
"""Return the table handle every read scans, kept from the build (ITL-1774).

spiral-sdk's handle is an immutable snapshot, and a read scans the pinned
version only, so no read looks the table up again; ``check_for_new_data``
replaces the handle when it pins a newer version.

Raises:
RuntimeError: If the source is closed, or this is another process than
the one that built it.
ValueError: If the latest check refused the table: dropped and created
again, other columns (build the source again to read it), or a schema
record that cannot be read (``TableSchemaError``).
InputValidationError: If the latest check refused the table for a column
in the system-tag namespace.
"""
self._connector() # the source is open, and in the process that made it
refusal = self._refusal
if refusal is not None:
raise refusal.with_traceback(None)
return self._handle

def _lookup_table(self) -> SpiralDBTable:
"""Resolve the name and check that it still identifies this source's table."""
"""Look the table up by name (a round trip) and check that it is still this
source's table: for a check, never for a read.

Raises:
ValueError: If the name now identifies another table (dropped and created
again), or none.
"""
table = self._connector().lookup_table(self._table_name)
table_id = table.table_id
if table_id != self._table_id:
Expand All @@ -785,7 +830,41 @@ def row_count_estimate(self) -> int:
cost grows with the table.
"""
asof = self._asof
return self._lookup_table().row_count_estimate(asof=asof)
return self._pinned_table().row_count_estimate(asof=asof)

@property
def pinned_version(self) -> int | None:
"""The table version every read of this source scans (no round trip).

The version the table had when the source was built, or the ``asof`` given;
``check_for_new_data`` (which every run calls first) moves it to a newer one.
``None`` for a table that was never written. Compare it with the table's latest
version with ``has_newer_version``.
"""
return self._asof

def has_newer_version(self) -> bool:
"""Return whether the table has a version newer than ``pinned_version``.

Tells, outside a run, whether this source's reads are behind the table: one
metadata lookup, no row read, and nothing moves (the pin, the modified time and
what a read returns stay as they are). ``check_for_new_data`` moves the pin, and
every run calls it first. ``head()``, the notebook preview and the reads never
call this.

Returns:
``True`` if the table's latest version is newer than the pinned one (also
for a source built with ``asof``, whose pin never moves).

Raises:
ValueError: If the table was dropped and created again under the same name
(another table id), or is gone: build the source again to read it.
"""
table = self._lookup_table()
latest = table.version() or None
if latest is None:
return False
return self._asof is None or latest > self._asof

@override
def check_for_new_data(self) -> bool:
Expand All @@ -801,19 +880,56 @@ def check_for_new_data(self) -> bool:
moved without changing the rows (if SpiralDB moves it on compaction) makes the
nodes below run again and reuse every stored result.

A read makes no metadata call of its own (ITL-1774), and a run checks its
sources first: a table this check refuses (dropped and created again, other
columns, a schema record that cannot be read) is refused by every read of this
source too, before it scans, until a later check accepts the table. A
column in the system-tag namespace is refused and held the same way.
A source built with ``asof`` is checked too (the table id, and its own
version's schema record), and its pin never moves. A missing table is refused
the same way. ``has_newer_version`` tells whether a newer version exists
without moving anything.

Returns:
``True`` if the pinned version moved.

Raises:
ValueError: If the table was dropped and created again (another table id)
or its columns changed: build the source again to read it.
TableSchemaError: If the table's row in the dataset's schema table cannot
be read, or disagrees with the table.
InputValidationError: If the table now has a column in the system-tag
namespace.
"""
require_same_process(self._pid) # before a lock inherited by a fork
with self._check_lock:
try:
moved = self._check_table()
# Every refusal is held: TableSchemaError and a missing table are
# ValueErrors, a reserved system-tag column an InputValidationError.
except (ValueError, InputValidationError) as exc:
self._refusal = exc
raise
self._refusal = None
return moved

def _check_table(self) -> bool:
"""Look the table up and pin its newer version: ``check_for_new_data``'s work.

Raises:
ValueError: If the table was dropped and created again, or its columns
changed.
TableSchemaError: If its schema record cannot be read.
InputValidationError: If the table now has a column in the system-tag
namespace.
"""
if self._given_asof is not None:
return False
# One lookup per check (ITL-1350): a table dropped and created again since
# is found by this lookup, and its schema and version come from it.
table = self._lookup_table()
raw_schema = table.arrow_schema()
# A given asof never moves: its own version's record is read again (a new
# handle reads it afresh) and compared, as reads used to do before ITL-1774.
given = self._given_asof
raw_schema = table.arrow_schema(asof=given)
require_names_not_system_tags(raw_schema.names)
schema = arrow_utils.drop_system_columns(raw_schema.empty_table()).schema
if not schema.equals(self._table_schema, check_metadata=True):
Expand All @@ -822,10 +938,13 @@ def check_for_new_data(self) -> bool:
f"{_schema_difference(schema, self._table_schema)}. Build the "
"source again to read it as it is now."
)
if given is not None:
return False
version = table.version() or None
if version is None or (self._asof is not None and version <= self._asof):
return False
self._asof = version
# The handle and the version move together: a read scans this snapshot.
self._handle, self._asof = table, version
self._update_modified_time()
return True

Expand Down Expand Up @@ -881,7 +1000,7 @@ def _batch_streams(
key column holds a null.
"""
asof = self._asof
table = self._lookup_table()
table = self._pinned_table()
yield from self._read_batches(
table,
asof=asof,
Expand Down Expand Up @@ -1073,7 +1192,7 @@ def _head(
limit = self._limit
head_limit = n if limit is None else min(n, limit)
asof = self._asof
table = self._lookup_table()
table = self._pinned_table()
rows = self._whole_table(
self._read_batches(table, asof=asof, limit=head_limit, max_rows=None),
columns=columns,
Expand All @@ -1098,13 +1217,13 @@ def _bounded_count(

Args:
shown: The rows the preview shows.
table: The handle resolved for this read; looked up when not given.
table: The handle of this read; the pinned table's when not given.
"""
if shown > DEFAULT_MAX_ROWS:
return shown, None
allowed = min(self._max_rows or DEFAULT_MAX_ROWS, DEFAULT_MAX_ROWS)
bound = max(allowed, shown)
handle = self._lookup_table() if table is None else table
handle = self._pinned_table() if table is None else table
total = handle.count_rows(asof=self._asof, at_most=bound + 1)
return bound, (None if total > bound else total)

Expand Down
Loading
Loading