diff --git a/changelog.d/ITL-1774.md b/changelog.d/ITL-1774.md new file mode 100644 index 000000000..810a60ba6 --- /dev/null +++ b/changelog.d/ITL-1774.md @@ -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. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 2a54f0213..b5006822e 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -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, @@ -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: @@ -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. @@ -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. diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 7f82008ab..d2bf49437 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -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 @@ -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() @@ -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 + # 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 = ( @@ -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 @@ -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: @@ -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: @@ -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): @@ -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 @@ -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, @@ -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, @@ -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) diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index f3e3726a4..db3a0b45c 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -470,6 +470,10 @@ class SpiralDBTable: each (ITL-1350). The handle is a snapshot: the id, key columns and version come with the lookup, and the schema and rows are those of that version. Look the table up again to see a newer version, or a table dropped and created again since. + + spiral-sdk's keyed table handle is an exact, immutable snapshot, so what is worked + out for one version (the SDK's handle of it, its schema and its recorded schema) is + kept and reused by every later read of that version (ITL-1774). """ def __init__( @@ -480,6 +484,20 @@ def __init__( self._table = table self._table_name = table_name self._readings: dict[str, _Reading] = {} + # The SDK's handle of each other version opened (``_at``), by version. + self._versions: dict[str, Any] = {} + + def with_connector(self, connector: SpiralDBConnector) -> SpiralDBTable: + """Return this table read through ``connector``, which shares its SDK client. + + What was worked out per version is shared: a snapshot never changes. + + Args: + connector: A connector on the same SDK client (``share_client``). + """ + duplicate = copy(self) + duplicate._connector = connector + return duplicate def _reading(self, table: Any) -> _Reading: """Return how a snapshot of this table is read, worked out once per version.""" @@ -499,14 +517,17 @@ def key_columns(self) -> list[str]: """The primary-key column names in declaration order (no round trip).""" return list(self._table.key_columns) - def arrow_schema(self) -> pa.Schema: + def arrow_schema(self, asof: int | None = None) -> pa.Schema: """The schema of the batches ``scan_batches`` yields (``get_arrow_schema``). + Args: + asof: Of this version; ``None`` for the version of the lookup. + Raises: TableSchemaError: If the table's row in the schema table cannot be read, or disagrees with the table. """ - return self._reading(self._table).schema + return self._reading(self._at(asof)).schema def version(self) -> int: """The table's version at the lookup (``get_table_version``).""" @@ -518,10 +539,14 @@ def _at(self, asof: int | None) -> Any: self._connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle if asof is None or str(asof) == str(self._table.version_id): return self._table - with self._connector._service_call("open a version of", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle - return self._connector._client.keyed_table_by_id( # pyright: ignore[reportPrivateUsage] # owns the handle - self.table_id, asof=asof - ) + opened = self._versions.get(str(asof)) + if opened is None: + with self._connector._service_call("open a version of", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle + opened = self._connector._client.keyed_table_by_id( # pyright: ignore[reportPrivateUsage] # owns the handle + self.table_id, asof=asof + ) + self._versions[str(asof)] = opened + return opened def scan_batches( self, diff --git a/tests/test_core/sources/test_source_arrow_validation.py b/tests/test_core/sources/test_source_arrow_validation.py index 032fad18f..ad702e872 100644 --- a/tests/test_core/sources/test_source_arrow_validation.py +++ b/tests/test_core/sources/test_source_arrow_validation.py @@ -1309,12 +1309,11 @@ def test_spiral_validates_reserved_null_in_an_empty_scan_batch( external.write(table) external.record(schema) source = SpiralDBTableSource("project", "rows", tag_only_columns=True) - handle = source._lookup_table() # pyright: ignore[reportPrivateUsage] # intercept the scan boundary + handle = source._pinned_table() # pyright: ignore[reportPrivateUsage] # intercept the scan boundary invalid = schema.append(pa.field("__unused", pa.null())) batch = pa.RecordBatch.from_arrays( [pa.array([], f.type) for f in invalid], schema=invalid ) - monkeypatch.setattr(source, "_lookup_table", lambda: handle) monkeypatch.setattr(handle, "scan_batches", lambda **kwargs: iter([batch])) with pytest.raises( InputValidationError, match=r"'__unused'.*declare a supported nullable type" diff --git a/tests/test_core/sources/test_spiraldb_lookups.py b/tests/test_core/sources/test_spiraldb_lookups.py index 8c8e91e4e..47ae155ea 100644 --- a/tests/test_core/sources/test_spiraldb_lookups.py +++ b/tests/test_core/sources/test_spiraldb_lookups.py @@ -1,8 +1,9 @@ """Count SDK calls for sources and jobs using the repository's spiral-sdk fake. Construction and each freshness check get metadata from one lookup (ITL-1350). -Each read has its own table lookup, including reads that also count rows, -and the source reuses its SDK client (ITL-1431). +A read makes no metadata call: it scans the table handle kept from the build, a +snapshot of the pinned version, which a check replaces when it pins a newer one +(ITL-1774). The source reuses its SDK client (ITL-1431). """ from __future__ import annotations @@ -10,6 +11,8 @@ import asyncio import collections import gc +import threading +import time import weakref from collections.abc import Callable, Iterator from pathlib import Path @@ -24,6 +27,7 @@ SpiralDBConnector, ) from orcapod.databases.spiraldb_schema_table import SCHEMA_TABLE +from orcapod.errors import InputValidationError from orcapod.operators import SelectColumns from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.sources import SpiralDBTableSource @@ -261,7 +265,8 @@ def test_restricted_copy_keeps_client_after_parent_closes( source.close() calls.clear() assert sorted(cast("list[int]", restricted.as_table()["k"].to_pylist())) == [0, 2] - assert calls == {"lookup": 1, "open_schemas": 1, "schema": 1, "scan": 1} + # The copy reads the parent's pinned handle through its own connector. + assert calls == {"scan": 1} restricted.close() @@ -315,21 +320,15 @@ async def collect() -> list[int]: else cast("list[int]", source.as_table()["k"].to_pylist()) ) assert sorted(keys) == expected - assert calls == {"lookup": 1, "open_schemas": 1, "schema": 1, "scan": 1} | ( - {} if restricted or round_ else {"count": 1} - ) + # No lookup, schema or schema-table read: the pinned handle is reused. + assert calls == {"scan": 1} | ({} if restricted or round_ else {"count": 1}) calls.clear() head = source.head(1) assert head.table.num_rows == 1 assert head.total_rows == 3 # The count was made by the reads above (or is made here, after a restricted read). - assert calls == { - "lookup": 1, - "open_schemas": 1, - "schema": 1, - "scan": 1, - } | ({"count": 1} if restricted else {}) + assert calls == {"scan": 1} | ({"count": 1} if restricted else {}) @pytest.mark.parametrize( @@ -389,29 +388,88 @@ def test_copy_keeps_its_original_endpoint(tmp_path: Path, async_read: bool) -> N assert restricted.as_table()["x"].to_pylist() == [14] -@pytest.mark.parametrize("asof", [None, 1]) -@pytest.mark.parametrize("mode", ["table", "iter", "async", "head", "count"]) -def test_each_read_refuses_a_replacement_before_scanning( - calls: collections.Counter[str], asof: int | None, mode: str -) -> None: - source = _source("plain", asof=asof) +def _replace_the_table() -> None: + """Drop ``default.t`` and create it again under the same name, with one row.""" project = fake_spiral_sdk.ExternalProject(_PROJECT) project.drop_table("default.t") keys, layout = _ARRANGED["keys"], _ARRANGED["layout"] replacement = project.create_table("default.t", key_schema=_keys(keys)) replacement.write(_rows(layout, [0])) replacement.record(_schema(layout)) - reads: dict[str, Callable[[], object]] = { + + +def _bare_reads(source: SpiralDBTableSource) -> dict[str, Callable[[], object]]: + """Every public read of a source on its own, outside a run.""" + return { "table": source.as_table, "iter": lambda: list(source.iter_data()), "async": lambda: asyncio.run(_async_x(source)), "head": lambda: source.head(1), "count": lambda: source.row_count_estimate, } + + +@pytest.mark.parametrize("asof", [None, 1]) +@pytest.mark.parametrize("mode", ["table", "iter", "async", "head", "count"]) +def test_a_bare_read_of_a_replaced_table_reads_only_the_pinned_snapshot( + calls: collections.Counter[str], asof: int | None, mode: str +) -> None: + """ITL-1774: a read outside a run scans the pinned snapshot of the source's own + table id, never the table now under the name. The fake removes a dropped table's + versions, so the pinned snapshot cannot be read: the read raises an error that + names the table, and returns no row.""" + source = _source("plain", asof=asof) + _replace_the_table() + calls.clear() + with pytest.raises(Exception) as raised: # noqa: B017 # the store's own error + reads = _bare_reads(source)[mode]() + pytest.fail(f"a gone snapshot was read as {reads!r}") + assert f"{_PROJECT}/default/t" in " ".join(getattr(raised.value, "__notes__", [])) + # No lookup: the replacement under the name is never opened by a read. + assert "lookup" not in calls + + +@pytest.mark.parametrize("mode", ["table", "iter", "async", "head", "count"]) +def test_a_bare_read_never_sees_a_version_newer_than_the_pinned_one( + calls: collections.Counter[str], mode: str +) -> None: + """ITL-1774: rows written after the source pinned its version are read only after + a check pins the newer version (the handle is replaced with it).""" + source = _source("plain") + table = fake_spiral_sdk.ExternalProject(_PROJECT).table("default.t") + table.write(_rows(_ARRANGED["layout"], [3])) + calls.clear() + _bare_reads(source)[mode]() + assert "lookup" not in calls + assert sorted(cast("list[int]", source.as_table()["k"].to_pylist())) == [0, 1, 2] + assert source.row_count_estimate == 3 + assert source.check_for_new_data() + assert sorted(cast("list[int]", source.as_table()["k"].to_pylist())) == [0, 1, 2, 3] + assert source.row_count_estimate == 4 + + +@pytest.mark.parametrize("run", ["sync", "async", "node", "load_only"]) +def test_a_run_over_a_replaced_table_refuses_before_scanning( + calls: collections.Counter[str], run: str +) -> None: + """A run checks its sources first, and the check refuses a table dropped and + created again before any row is scanned (ITL-1774 moved the refusal from each + read to the check).""" + source = _source("plain") + job = PipelineJob(name="lookups", database=InMemoryArrowDatabase()) + with job: + SelectColumns(["subject", "k", "x", "y"])(source, label="read") + _replace_the_table() + runs: dict[str, Callable[[], object]] = { + "sync": job.run, + "async": lambda: job.run(orchestrator=AsyncPipelineOrchestrator()), + "node": job.nodes["read"].run, + "load_only": lambda: job.run(load_only=True), + } calls.clear() with pytest.raises(ValueError, match="dropped and created again"): - reads[mode]() - assert calls == {"lookup": 1} + runs[run]() + assert "scan" not in calls and "count" not in calls def test_two_async_job_readers_use_the_restricted_sources_endpoint( @@ -449,10 +507,11 @@ def test_job_reuses_client_but_refreshes_table_each_run( calls.clear() job.run(orchestrator=runner) assert job.nodes["read"].as_table().num_rows == 3 + # The run's check looks the table up once; its read reuses the pinned handle. assert calls == { - "lookup": 2, - "open_schemas": 2, - "schema": 2, + "lookup": 1, + "open_schemas": 1, + "schema": 1, "count": 1, "scan": 1, } @@ -479,6 +538,12 @@ def test_freshness_catches_metadata_schema_changes( with pytest.raises(ValueError, match="the table has column .x."): source.check_for_new_data() assert calls == {"lookup": 1, "open_schemas": 1, "read_schemas": 1, "schema": 1} + # Every later read refuses too, before it scans (ITL-1774). + calls.clear() + for read in _bare_reads(source).values(): + with pytest.raises(ValueError, match="the table has column .x."): + read() + assert calls == {} def test_freshness_pins_newer_version(calls: collections.Counter[str]) -> None: @@ -534,3 +599,206 @@ def test_the_arrangements_give_the_same_rows_and_pipeline_hash( assert sorted(sync) == sorted(async_) == _expected_rows([0, 1, 2]) assert first.pipeline_hash() == second.pipeline_hash() assert first.content_hash() != second.content_hash() + + +def test_has_newer_version_tells_staleness_without_moving_anything( + calls: collections.Counter[str], +) -> None: + """ITL-1774: ``has_newer_version`` makes one lookup, reads no row and moves + nothing; ``check_for_new_data`` moves the pin, after which it reports current.""" + source = _source("plain") + pinned = source.pinned_version + assert pinned is not None + calls.clear() + assert source.has_newer_version() is False + assert calls == {"lookup": 1} + + table = fake_spiral_sdk.ExternalProject(_PROJECT).table("default.t") + table.write(_rows(_ARRANGED["layout"], [3])) + modified = source.last_modified + calls.clear() + assert source.has_newer_version() is True + assert calls == {"lookup": 1} + # Nothing moved: the pin, the modified time and what a read returns. + assert source.pinned_version == pinned + assert source.last_modified == modified + assert sorted(cast("list[int]", source.as_table()["k"].to_pylist())) == [0, 1, 2] + + assert source.check_for_new_data() is True + assert source.pinned_version is not None and source.pinned_version > pinned + assert source.has_newer_version() is False + assert sorted(cast("list[int]", source.as_table()["k"].to_pylist())) == [0, 1, 2, 3] + + +def test_a_given_version_never_moves_but_reports_a_newer_one( + calls: collections.Counter[str], +) -> None: + source = _source("plain", asof=1) + assert source.pinned_version == 1 + assert source.has_newer_version() is False + table = fake_spiral_sdk.ExternalProject(_PROJECT).table("default.t") + table.write(_rows(_ARRANGED["layout"], [3])) + assert source.has_newer_version() is True + assert source.check_for_new_data() is False + assert source.pinned_version == 1 + + +def test_has_newer_version_refuses_a_replaced_table( + calls: collections.Counter[str], +) -> None: + source = _source("plain") + _replace_the_table() + with pytest.raises(ValueError, match="dropped and created again"): + source.has_newer_version() + # A query, not a check: a read still scans the pinned snapshot (which the fake + # removed with the dropped table), rather than raising the check's refusal. + with pytest.raises(Exception) as raised: # noqa: B017 # the store's own error + source.as_table() + assert "dropped and created again" not in str(raised.value) + + +def test_head_and_the_preview_never_ask_for_a_newer_version( + calls: collections.Counter[str], +) -> None: + source = _source("plain") + calls.clear() + source.head(1) + source._repr_html_() # pyright: ignore[reportPrivateUsage] # the notebook preview + assert "lookup" not in calls + + +def test_a_check_of_a_given_version_reads_its_record_again_without_moving( + calls: collections.Counter[str], +) -> None: + """CodeRabbit on #675: a source built with ``asof`` reads its own version's schema + record again at each check (reads reuse the build's), refuses on a record that + cannot be read, and never moves its pin.""" + source = _source("plain", asof=1) + table = fake_spiral_sdk.ExternalProject(_PROJECT).table("default.t") + table.write(_rows(_ARRANGED["layout"], [3])) + calls.clear() + assert source.check_for_new_data() is False + assert source.pinned_version == 1 + assert calls["lookup"] == 1 and calls["read_schemas"] == 0 + assert sorted(cast("list[int]", source.as_table()["k"].to_pylist())) == [0, 1, 2] + + changed = pa.schema( + [ + _FIELDS[n].with_nullable(True) if n == "x" else _FIELDS[n] + for n in _ARRANGED["layout"] + ] + ) + table.record(changed) + with pytest.raises(ValueError, match="the table has column .x."): + source.check_for_new_data() + calls.clear() + for read in _bare_reads(source).values(): + with pytest.raises(ValueError, match="the table has column .x."): + read() + assert calls == {} + assert source.pinned_version == 1 + + +def test_a_check_of_a_given_version_refuses_a_replaced_table( + calls: collections.Counter[str], +) -> None: + source = _source("plain", asof=1) + _replace_the_table() + with pytest.raises(ValueError, match="dropped and created again"): + source.check_for_new_data() + calls.clear() + with pytest.raises(ValueError, match="dropped and created again"): + source.as_table() + assert calls == {} + + +@pytest.mark.parametrize("asof", [None, 1]) +def test_a_missing_table_found_by_a_check_is_refused_by_every_read( + calls: collections.Counter[str], asof: int | None +) -> None: + """CodeRabbit on #675: a table dropped (and not created again) is refused by the + check and then by every read, before scanning.""" + source = _source("plain", asof=asof) + fake_spiral_sdk.ExternalProject(_PROJECT).drop_table("default.t") + with pytest.raises(ValueError, match="not found"): + source.check_for_new_data() + calls.clear() + for read in _bare_reads(source).values(): + with pytest.raises(ValueError, match="not found"): + read() + assert calls == {} + + +def test_checks_of_one_source_run_one_at_a_time( + calls: collections.Counter[str], monkeypatch: pytest.MonkeyPatch +) -> None: + """CodeRabbit on #675: overlapping checks of one source are serialized, so the + refusal reads always hold the verdict of the check that finished last.""" + source = _source("plain") + inside = 0 + most = 0 + guard = threading.Lock() + original = SpiralDBTableSource._check_table # pyright: ignore[reportPrivateUsage] # the serialized step + + def slow(self: SpiralDBTableSource) -> bool: + nonlocal inside, most + with guard: + inside += 1 + most = max(most, inside) + time.sleep(0.05) + try: + return original(self) + finally: + with guard: + inside -= 1 + + monkeypatch.setattr(SpiralDBTableSource, "_check_table", slow) + threads = [threading.Thread(target=source.check_for_new_data) for _ in range(4)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert most == 1 + + +def test_a_check_refusing_a_reserved_system_tag_column_is_held_by_every_read( + calls: collections.Counter[str], +) -> None: + """CodeRabbit on #675: a check that refuses because the table now has a column in + the system-tag namespace (an ``InputValidationError``, not a ``ValueError``) is + held like every other refusal: every later read refuses with it, before + scanning, until a check accepts the table again.""" + source = _source("plain") + layout = _ARRANGED["layout"] + reserved = "_tag_source_id::x" + table = fake_spiral_sdk.ExternalProject(_PROJECT).table("default.t") + widened = _rows(layout, [0, 1, 2]).append_column( + pa.field(reserved, pa.large_string()), pa.array(["r"] * 3, pa.large_string()) + ) + table.write(widened) + table.record(widened.schema) + with pytest.raises(InputValidationError, match="reserved for Orcapod system tags"): + source.check_for_new_data() + calls.clear() + for read in _bare_reads(source).values(): + with pytest.raises( + InputValidationError, match="reserved for Orcapod system tags" + ): + read() + assert calls == {} + + +def test_a_given_older_version_is_prepared_at_build( + calls: collections.Counter[str], +) -> None: + """CodeRabbit on #675: a source built with an ``asof`` older than the table's + latest version prepares that version's schema and schema record at build, so its + first read makes no metadata read (ITL-1774).""" + table = fake_spiral_sdk.ExternalProject(_PROJECT).table("default.t") + table.write(_rows(_ARRANGED["layout"], [3])) + source = _source("plain", asof=1) + calls.clear() + keys = sorted(cast("list[int]", source.as_table()["k"].to_pylist())) + assert keys == [0, 1, 2] + assert "schema" not in calls and "read_schemas" not in calls + assert "open_schemas" not in calls and "lookup" not in calls 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 2b91d9b74..6a920cc12 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_streaming.py +++ b/tests/test_core/sources/test_spiraldb_table_source_streaming.py @@ -123,7 +123,8 @@ def test_a_read_that_matches_nothing_has_the_schema_of_one_that_does(self, proje assert empty.schema == rows.as_table(all_info=True).schema def test_a_metadata_change_after_construction_is_refused(self, project): - """Field metadata changed after construction fails the read: rebuild needed.""" + """Field metadata changed after construction fails the check, and every read + after it (ITL-1774: a read reuses the schema the build read): rebuild needed.""" source = SpiralDBTableSource(_PROJECT, "event", tag_only_columns=True) marked = _rows([1]).cast( pa.schema( @@ -136,10 +137,11 @@ def test_a_metadata_change_after_construction_is_refused(self, project): ) project.table("default.event").record(marked.schema) - with pytest.raises( - ValueError, match="column 'amplitude'.*build the source again" - ): - source.as_table() + for read in (source.check_for_new_data, source.as_table): + with pytest.raises( + ValueError, match="(?i)column 'amplitude'.*build the source again" + ): + read() def test_a_table_with_key_columns_only_is_refused(self, project): """A table never written, holding key columns only, is refused.""" @@ -308,13 +310,15 @@ def test_a_given_version_is_used(self, project): assert source.to_config()["asof"] == 1 def test_a_given_version_zero_is_used(self, project): - """An ``asof`` of ``0`` is passed to the scan and saved, not taken as unset.""" - source = SpiralDBTableSource(_PROJECT, "event", asof=0, tag_only_columns=True) - - source.as_table() + """An ``asof`` of ``0`` is used, not taken as unset. - assert fake_spiral_sdk.scan_log[-1].kwargs["asof"] == 0 - assert source.to_config()["asof"] == 0 + The source is built from the version it reads (CodeRabbit on #675), and + version 0 is the table before its first write: key columns only, so the + source is refused for having no data column. Taken as unset, it would + read the latest version and be built. + """ + with pytest.raises(ValueError, match="No data columns"): + SpiralDBTableSource(_PROJECT, "event", asof=0, tag_only_columns=True) class TestRowCap: @@ -425,8 +429,11 @@ def test_a_recreated_table_is_a_different_source(self, project): # The record id is the row's key, not the source: the same key, the same id # (ITL-1154); the source-id system tag tells the two tables' rows apart. assert _record_ids(after)[1] == before_ids[1] - with pytest.raises(ValueError, match="dropped and created again"): - before.as_table() + # The check (which every run makes first) refuses the old source, and so does + # every read after it (ITL-1774). + for read in (before.check_for_new_data, before.as_table): + with pytest.raises(ValueError, match="dropped and created again"): + read() def test_restrictions_do_not_change_identity(self, project): """Restrictions on the read leave the source id and both hashes unchanged.""" diff --git a/tests/test_databases/test_spiraldb_schema_table.py b/tests/test_databases/test_spiraldb_schema_table.py index 5885ec4df..07987076d 100644 --- a/tests/test_databases/test_spiraldb_schema_table.py +++ b/tests/test_databases/test_spiraldb_schema_table.py @@ -294,6 +294,10 @@ def test_open_readers_refuse_too(project: Any, name: str, tag_only: bool) -> Non source = SpiralDBTableSource("p", name, tag_only_columns=tag_only) assert len(asyncio.run(_collect(source))) == len(list(source.iter_data())) == 2 _edit_schema_table(table_count=9) + # A read reuses what the build checked (ITL-1774); the check, which every run + # makes first, reads the record again and refuses, and so does every read after it. + with pytest.raises(TableSchemaError): + source.check_for_new_data() for read in ( source.as_table, lambda: list(source.iter_data()), @@ -306,10 +310,36 @@ def test_open_readers_refuse_too(project: Any, name: str, tag_only: bool) -> Non read() +def test_a_check_that_accepts_the_table_again_lifts_the_refusal(project: Any) -> None: + """ITL-1774: reads refuse while the latest check refused, and read again once a + later check accepts the table (the record was completed again).""" + fake.migrate("p", {"units": _WRITTEN, "trials": _WRITTEN}) + source = SpiralDBTableSource("p", "units", tag_only_columns=True) + client = fake.FakeClient() + (marker,) = [ + r + for r in client.keyed_table("p", "default", st.SCHEMA_TABLE) + .scan() + .to_table() + .to_pylist() + if r["table_id"] == st.MARKER_KEY + ] + _edit_schema_table(table_count=9) + with pytest.raises(TableSchemaError): + source.check_for_new_data() + with pytest.raises(TableSchemaError): + source.as_table() + _edit_schema_table(table_count=marker["table_count"]) + assert source.check_for_new_data() is False + assert source.as_table().num_rows == 2 + + def test_a_display_names_the_refusal_and_shows_no_row(project: Any) -> None: fake.migrate("p", {"units": _WRITTEN}) source = SpiralDBTableSource("p", "units", tag_only_columns=True) _edit_schema_table(table_count=9) + with pytest.raises(TableSchemaError): + source.check_for_new_data() html = source._repr_html_() assert "could not read" in html and "completion marker" in html assert "