diff --git a/changelog.d/ITL-1791.md b/changelog.d/ITL-1791.md new file mode 100644 index 000000000..e95cc830c --- /dev/null +++ b/changelog.d/ITL-1791.md @@ -0,0 +1,7 @@ +### Changed + +- `SpiralDBTableSource.check_for_new_data()`, which every job run calls first, no + longer reads the table's schema again when the table's version has not moved: it + reuses the pinned snapshot's schema, so an unchanged check makes two round trips + (the table lookup and the schema table's check) instead of three. A schema + recorded again since the last check is still refused at the next check. diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index fe4c37a41..eeb02259d 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -934,7 +934,12 @@ def _check_table(self) -> bool: # 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) + # The snapshot this check reads, when the pinned handle opened it, costs no + # further round trip for its schema as SpiralDB reports it (ITL-1791). Only + # that exact version is taken over, so a moving source keeps one snapshot. + # Its recorded schema is still read again, so a schema recorded again since + # is refused here. + raw_schema = table.arrow_schema(asof=given, reuse_snapshot_of=self._handle) require_source_column_names(raw_schema.names) schema = arrow_utils.drop_system_columns(raw_schema.empty_table()).schema if not schema.equals(self._table_schema, check_metadata=True): diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index b5cbbd75f..dd71942bd 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -711,12 +711,19 @@ def with_connector(self, connector: SpiralDBConnector) -> SpiralDBTable: 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.""" + def _reading(self, table: Any, *, found: pa.Schema | None = None) -> _Reading: + """Return how a snapshot of this table is read, worked out once per version. + + Args: + table: The SDK's handle of the snapshot. + found: The snapshot's schema as SpiralDB reports it, if already known. + """ self._connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle version = str(table.version_id) if version not in self._readings: - self._readings[version] = self._connector._reading(table, self._table_name) # pyright: ignore[reportPrivateUsage] # owns the handle + self._readings[version] = self._connector._reading( # pyright: ignore[reportPrivateUsage] # owns the handle + table, self._table_name, found=found + ) return self._readings[version] @property @@ -729,17 +736,46 @@ 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, asof: int | None = None) -> pa.Schema: + def arrow_schema( + self, asof: int | None = None, *, reuse_snapshot_of: SpiralDBTable | 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. + reuse_snapshot_of: An earlier lookup by the same connector. Reuse the + exact snapshot's reported schema and, for an older version, its SDK + handle if the requested version already existed (ITL-1791). This + lookup still validates the recorded schema. Raises: TableSchemaError: If the table's row in the schema table cannot be read, or disagrees with the table. """ - return self._reading(self._at(asof)).schema + found = None + earlier = reuse_snapshot_of + if ( + earlier is not None + and earlier._connector is self._connector + and earlier.table_id == self.table_id + ): + own = str(self._table.version_id) + version = own if asof is None else str(asof) + earlier_latest = str(earlier._table.version_id) + opened = None + if version == earlier_latest: + opened = earlier._table + elif int(version) < int(earlier_latest): + # An asof ahead of the earlier lookup can have resolved to an + # empty snapshot that reports the requested version anyway. + opened = earlier._versions.get(version) + if opened is not None and str(opened.version_id) == version: + if version != own: + self._versions.setdefault(version, opened) + reading = earlier._readings.get(version) + if reading is not None: + found = reading.found + return self._reading(self._at(asof), found=found).schema def version(self) -> int: """The table's version at the lookup (``get_table_version``).""" @@ -1189,16 +1225,26 @@ def _recorded_schema( ) return row.schema - def _reading(self, table: Any, table_name: str) -> _Reading: + def _reading( + self, table: Any, table_name: str, found: pa.Schema | None = None + ) -> _Reading: """Return how an opened snapshot of ``table_name`` is read. + Args: + table: The SDK's handle of the snapshot. + table_name: Plain table name. + found: The snapshot's schema as SpiralDB reports it, when known already; + ``None`` reads it (a round trip). + Raises: TableSchemaError: If the table's row cannot be read or disagrees with it. """ self._require_open() qualified = self._qualified(table_name) - with self._service_call("read the schema of", table_name): - found = table.schema() + if found is None: + with self._service_call("read the schema of", table_name): + reported: pa.Schema = table.schema() + found = reported with _about_table(qualified): recorded = self._recorded_schema(table, table_name, found) return _Reading(found, recorded, qualified) diff --git a/tests/test_core/sources/test_spiraldb_lookups.py b/tests/test_core/sources/test_spiraldb_lookups.py index 31f80cd9e..9f1455738 100644 --- a/tests/test_core/sources/test_spiraldb_lookups.py +++ b/tests/test_core/sources/test_spiraldb_lookups.py @@ -52,7 +52,8 @@ } # What is counted: "client" built; "lookup" of the user's table by name; "open_schemas" and # "read_schemas", the opening of the dataset's schema table and the reads of its rows; -# "schema" of the user's table; "scan" of its rows and "count" of its keys. +# "schema" of the user's table; "open_version", the opening of another version of it by +# id; "scan" of its rows and "count" of its keys. def _schema(layout: list[str]) -> pa.Schema: @@ -100,6 +101,9 @@ def label(args: tuple[Any, ...], kwargs: Any) -> str | None: # pyright: ignore[ counted: dict[tuple[type, str], Callable[..., str | None]] = { (fake_spiral_sdk.FakeClient, "__init__"): lambda args, kwargs: "client", (fake_spiral_sdk.FakeClient, "keyed_table"): lookup_label, + (fake_spiral_sdk.FakeClient, "keyed_table_by_id"): lambda args, kwargs: ( + "open_version" + ), (fake_spiral_sdk.FakeKeyedTable, "schema"): handle_label("schema"), (fake_spiral_sdk.FakeKeyedTable, "scan"): handle_label("scan"), } @@ -206,8 +210,159 @@ def test_each_check_looks_the_table_up_once( for _ in range(2): calls.clear() assert source.check_for_new_data() is False - # Before ITL-1350: 3 lookups (id, schema, version). - assert calls == {"lookup": 1, "schema": 1, "open_schemas": 1} + # Before ITL-1350: 3 lookups (id, schema, version). Before ITL-1791 the + # unchanged version's schema was read again too ("schema": 1); the schema + # table is still opened, so a schema recorded again is found. + assert calls == {"lookup": 1, "open_schemas": 1} + sync, async_ = _sync_and_async_rows(source) + assert sorted(sync) == sorted(async_) == _expected_rows([0, 1, 2]) + + +@pytest.mark.parametrize("role", sorted(ROLES)) +def test_an_unchanged_check_reuses_the_pinned_schema( + calls: collections.Counter[str], role: str +) -> None: + """ITL-1791: a check of an unchanged version reads no schema of the table; a check + that pins a newer version reads that version's schema once.""" + source = _source(role) + for _ in range(3): + calls.clear() + assert source.check_for_new_data() is False + assert calls == {"lookup": 1, "open_schemas": 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 True + assert calls == {"lookup": 1, "open_schemas": 1, "schema": 1} + for _ in range(2): + calls.clear() + assert source.check_for_new_data() is False + assert calls == {"lookup": 1, "open_schemas": 1} + sync, async_ = _sync_and_async_rows(source) + assert sorted(sync) == sorted(async_) == _expected_rows([0, 1, 2, 3]) + + +@pytest.mark.parametrize("already_historical", [False, True]) +@pytest.mark.parametrize("role", sorted(ROLES)) +def test_a_check_of_a_given_version_reuses_its_snapshot( + calls: collections.Counter[str], role: str, already_historical: bool +) -> None: + """ITL-1791: a source built with ``asof`` keeps its version's handle and schema + across checks, also once the table has a newer version; its record is read again.""" + table = fake_spiral_sdk.ExternalProject(_PROJECT).table("default.t") + if already_historical: + table.write(_rows(_ARRANGED["layout"], [3])) + source = _source(role, asof=1) + table.write(_rows(_ARRANGED["layout"], [4])) + for _ in range(2): + calls.clear() + assert source.check_for_new_data() is False + assert calls == {"lookup": 1, "open_schemas": 1} + assert source.pinned_version == 1 + sync, async_ = _sync_and_async_rows(source) + assert sorted(sync) == sorted(async_) == _expected_rows([0, 1, 2]) + + +@pytest.mark.parametrize("arrangement", sorted(ARRANGEMENTS)) +@pytest.mark.parametrize("initial_version", [0, 1], ids=["empty", "written"]) +def test_a_check_reopens_an_asof_that_was_ahead_of_the_latest_version( + tmp_path: Path, arrangement: str, initial_version: int +) -> None: + """Refuse a schema change at the requested version and keep refusing after it.""" + keys, layout = ARRANGEMENTS[arrangement] + requested = initial_version + 1 + with fake_spiral_sdk.install(tmp_path / "spiral"): + table = fake_spiral_sdk.ExternalProject(_PROJECT).create_table( + "default.t", key_schema=_keys(keys) + ) + if initial_version: + table.write(_rows(layout, [1])) + with _source("data_tags", asof=requested) as source: + assert source.check_for_new_data() is False + assert source.pinned_version == requested + if initial_version: + sync, async_ = _sync_and_async_rows(source) + assert sync == async_ == _expected_rows([1]) + for key in (2, 3): + widened = _rows(layout, [key]).append_column("extra", pa.array([key])) + table.write(widened) + with pytest.raises(ValueError, match="the table has columns") as check: + _ = source.check_for_new_data() + for read in _bare_reads(source).values(): + with pytest.raises( + ValueError, match="the table has columns" + ) as held: + _ = read() + assert held.value is check.value + + +def test_a_moving_source_retains_only_its_pinned_snapshot( + calls: collections.Counter[str], monkeypatch: pytest.MonkeyPatch +) -> None: + """ITL-1791: reuse is bounded to the snapshot a check reads. Across many version + advances a source keeps the SDK handle of its pinned version only, as before + ITL-1791, and an unchanged check still reads no schema of the table.""" + handles: list[weakref.ReferenceType[fake_spiral_sdk.FakeKeyedTable]] = [] + original = fake_spiral_sdk.FakeKeyedTable.__init__ + + def track( + handle: fake_spiral_sdk.FakeKeyedTable, *args: Any, **kwargs: Any + ) -> None: # pyright: ignore[reportExplicitAny] # passed through + original(handle, *args, **kwargs) + handles.append(weakref.ref(handle)) + + monkeypatch.setattr(fake_spiral_sdk.FakeKeyedTable, "__init__", track) + source = _source("plain") + external = fake_spiral_sdk.ExternalProject(_PROJECT).table("default.t") + table_id = external.table_id + + def retained() -> list[str]: + gc.collect() + alive = (ref() for ref in handles) + return sorted( + h.version_id for h in alive if h is not None and h.resource_id == table_id + ) + + first = source.pinned_version + for advance in range(12): + external.write(_rows(_ARRANGED["layout"], [3 + advance])) + assert source.check_for_new_data() is True + calls.clear() + assert source.check_for_new_data() is False + assert calls == {"lookup": 1, "open_schemas": 1} + assert retained() == [str(source.pinned_version)] + assert source.pinned_version is not None and first is not None + assert source.pinned_version == first + 12 + sync, async_ = _sync_and_async_rows(source) + assert sorted(sync) == sorted(async_) == _expected_rows(list(range(15))) + + +def test_a_refusal_of_a_recorded_schema_is_held_until_a_check_accepts_it( + calls: collections.Counter[str], +) -> None: + """ITL-1791 keeps ITL-1774's held refusals: a schema recorded again (no row written, + so the table's version is unchanged) is refused by the next check and by every + read; once the record is put back, a check accepts the table and reads work.""" + source = _source("plain") + layout = _ARRANGED["layout"] + table = fake_spiral_sdk.ExternalProject(_PROJECT).table("default.t") + table.record( + pa.schema( + [ + _FIELDS[name].with_nullable(True) if name == "x" else _FIELDS[name] + for name in layout + ] + ) + ) + with pytest.raises(ValueError, match="the table has column .x."): + source.check_for_new_data() + for read in _bare_reads(source).values(): + with pytest.raises(ValueError, match="the table has column .x."): + read() + table.record(_schema(layout)) + calls.clear() + assert source.check_for_new_data() is False + assert calls == {"lookup": 1, "open_schemas": 1, "read_schemas": 1} sync, async_ = _sync_and_async_rows(source) assert sorted(sync) == sorted(async_) == _expected_rows([0, 1, 2]) @@ -517,18 +672,18 @@ 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. The - # sync run reads the whole table at once and counts as it reads (ITL-1457). + # The run's check looks the table up once; its read reuses the pinned handle, and + # the unchanged version's schema is the pinned handle's (ITL-1791). The sync run + # reads the whole table at once and counts as it reads (ITL-1457). assert calls == { "lookup": 1, "open_schemas": 1, - "schema": 1, "scan": 1, } | ({"count": 1} if orchestrator is not None else {}) calls.clear() job.run(orchestrator=runner) - assert calls == {"lookup": 1, "open_schemas": 1, "schema": 1} + assert calls == {"lookup": 1, "open_schemas": 1} def test_freshness_catches_metadata_schema_changes( @@ -547,7 +702,9 @@ def test_freshness_catches_metadata_schema_changes( calls.clear() 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} + # The recorded schema is read again; the unchanged version's own schema is the + # pinned handle's (ITL-1791). + assert calls == {"lookup": 1, "open_schemas": 1, "read_schemas": 1} # Every later read refuses too, before it scans (ITL-1774). calls.clear() for read in _bare_reads(source).values():