diff --git a/changelog.d/ITL-1350.md b/changelog.d/ITL-1350.md new file mode 100644 index 000000000..964573c20 --- /dev/null +++ b/changelog.d/ITL-1350.md @@ -0,0 +1,11 @@ +### Changed + +- A `SpiralDBTableSource` looks its table up once when it is built and once per new-data + check (ITL-1350). Every lookup of a table by name is a round trip to SpiralDB; the + source used to look the table up for each item it needed (key, id, schema and + version: four lookups to build, three per check). `SpiralDBConnector.lookup_table` + returns the table once, with its id and key columns, and reads its schema and version + when asked, in the same order and under the same conditions as before, so a check + still finds a table dropped and created again since. Measured on a live project: + building a source about 1.5 s -> 0.9 s, a check about 1.2 s -> 0.8 s. The connector's + other methods are unchanged. diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 57dfe86d8..823790b52 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -449,7 +449,9 @@ def __init__( raise ValueError( f"{location}: Table {table_name!r} not found in database." ) - primary_key = tuple(connector.get_pk_columns(table_name)) + # One lookup for the key, id, schema and version (ITL-1350). + table = connector.lookup_table(table_name) + primary_key = tuple(table.key_columns) self._key_columns: tuple[str, ...] = ( given_key if given_key is not None else primary_key ) @@ -459,15 +461,11 @@ def __init__( "its rows cannot be identified: name key columns with " "record_id_columns=[...]." ) - self._table_id = connector.get_spiral_table_id(table_name) - schema = connector.get_arrow_schema(table_name) + self._table_id = table.table_id + schema = table.arrow_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 (connector.get_table_version(table_name) or None) - ) + self._asof = asof if asof is not None else (table.version() or None) # The default tags are the primary key, whatever identifies the rows. resolved_tags = ( @@ -796,7 +794,10 @@ def check_for_new_data(self) -> bool: if self._given_asof is not None: return False with self._connector() as connector: - table_id = connector.get_spiral_table_id(self._table_name) + # 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 = connector.lookup_table(self._table_name) + table_id = table.table_id if table_id != self._table_id: raise ValueError( f"SpiralDB table {self._qualified!r} is now another table (id " @@ -804,7 +805,7 @@ def check_for_new_data(self) -> bool: "dropped and created again. Build the source again to read it." ) schema = arrow_utils.drop_system_columns( - connector.get_arrow_schema(self._table_name).empty_table() + table.arrow_schema().empty_table() ).schema if not schema.equals(self._table_schema, check_metadata=True): raise ValueError( @@ -812,7 +813,7 @@ 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." ) - version = connector.get_table_version(self._table_name) or None + version = table.version() or None if version is None or (self._asof is not None and version <= self._asof): return False self._asof = version diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index cd0679ef6..0386d2716 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -396,6 +396,55 @@ def _holds_zone_aware_timestamp(arrow_type: pa.DataType) -> bool: ) +class SpiralDBTable: + """One SpiralDB table, looked up once (``SpiralDBConnector.lookup_table``). + + Every lookup of a table by name is a round trip to SpiralDB, and so is each item of + metadata. A caller that needs several items of one table (a source's id, key, schema + and version when it is built, and each run's check) takes them from one handle + instead of looking the table up for each (ITL-1350). The id and the key columns come + with the lookup; the schema and the version are read when asked, in the caller's + order, from the table the lookup found. The handle reads the table as it was when + looked up: look it up again to see a table dropped and created again since. + """ + + def __init__( + self, connector: SpiralDBConnector, table: Any, table_name: str + ) -> None: + """Wrap the pyspiral ``table`` that ``connector`` looked up as ``table_name``.""" + self._connector = connector + self._table = table + self._table_name = table_name + + @property + def table_id(self) -> str: + """SpiralDB's own id of the table (no round trip).""" + return str(self._table.table_id) + + @property + def key_columns(self) -> list[str]: + """The primary-key column names in declaration order (no round trip).""" + return list(self._table.key_schema.names) + + def arrow_schema(self) -> pa.Schema: + """The schema of the batches ``scan_batches`` yields (``get_arrow_schema``). + + Raises: + NullabilityRecordError: If the table's nullability record cannot be read or + names a column the table does not have. + """ + import pyarrow as _pa # noqa: PLC0415 + + declared = self._table.schema().to_arrow() + empty = _pa.RecordBatch.from_pylist([], schema=declared) + preparer = self._connector._batch_preparer(self._table, self._table_name) # pyright: ignore[reportPrivateUsage] # the connector's own preparer + return preparer(empty).schema + + def version(self) -> int: + """The table's current version (``get_table_version``).""" + return int(self._table.last_modified_at()) + + class SpiralDBConnector: """DBConnectorProtocol implementation backed by SpiralDB (pyspiral). @@ -452,6 +501,20 @@ def get_table_names(self) -> list[str]: resources = self._project.list_tables() return sorted(r.table for r in resources if r.dataset == self._dataset) + def lookup_table(self, table_name: str) -> SpiralDBTable: + """Look the table up once, for several items of its metadata (ITL-1350). + + Args: + table_name: Plain table name (no dataset prefix). + + Returns: + The table: its id and key columns, and its schema and version when asked. + """ + self._require_open() + return SpiralDBTable( + self, self._project.table(self._table_id(table_name)), table_name + ) + def get_pk_columns(self, table_name: str) -> list[str]: """Return primary-key column names in declaration order. @@ -461,8 +524,7 @@ def get_pk_columns(self, table_name: str) -> list[str]: Returns: List of PK column names; empty list if the table has no key schema. """ - self._require_open() - return list(self._project.table(self._table_id(table_name)).key_schema.names) + return self.lookup_table(table_name).key_columns def get_column_info(self, table_name: str) -> list[ColumnInfo]: """Return column metadata with Arrow types. @@ -694,13 +756,7 @@ def get_arrow_schema(self, table_name: str) -> pa.Schema: NullabilityRecordError: If the table's nullability record cannot be read or names a column the table does not have. """ - import pyarrow as _pa # noqa: PLC0415 - - self._require_open() - tbl = self._project.table(self._table_id(table_name)) - declared = tbl.schema().to_arrow() - empty = _pa.RecordBatch.from_pylist([], schema=declared) - return self._batch_preparer(tbl, table_name)(empty).schema + return self.lookup_table(table_name).arrow_schema() def get_spiral_table_id(self, table_name: str) -> str: """Return SpiralDB's own id of the table (for example ``table_W7C01nkLTmEJ``). @@ -714,8 +770,7 @@ def get_spiral_table_id(self, table_name: str) -> str: Returns: The table id. """ - self._require_open() - return str(self._project.table(self._table_id(table_name)).table_id) + return self.lookup_table(table_name).table_id def get_table_version(self, table_name: str) -> int: """Return the table's current version, usable as ``asof`` in ``scan_batches``. @@ -727,8 +782,7 @@ def get_table_version(self, table_name: str) -> int: The time of the table's last change, in microseconds; ``0`` for a table that was never written. """ - self._require_open() - return int(self._project.table(self._table_id(table_name)).last_modified_at()) + return self.lookup_table(table_name).version() def get_row_count_estimate(self, table_name: str, asof: int | None = None) -> int: """Return the table's row count as SpiralDB's manifests record it, without scanning. diff --git a/tests/test_core/sources/test_spiraldb_lookups.py b/tests/test_core/sources/test_spiraldb_lookups.py new file mode 100644 index 000000000..314cfdaad --- /dev/null +++ b/tests/test_core/sources/test_spiraldb_lookups.py @@ -0,0 +1,232 @@ +"""A SpiralDB source looks its table up once to build and once per check (ITL-1350). + +Every lookup of a table by name is a round trip to SpiralDB (0.2-0.9 s each in a +workshop-scale profile). A source used to look the table up for each item it needs: four +times to build (key, id, schema, version), three times per new-data check (id, schema, +version). It now takes them from one lookup (``SpiralDBConnector.lookup_table``). The +calls are counted on the repository's pyspiral fake; what the source decides is unchanged. +""" + +from __future__ import annotations + +import asyncio +import collections +from collections.abc import Callable, Iterator +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.databases import SpiralDBConnector, write_nullability_record +from orcapod.sources import SpiralDBTableSource +from tests.test_databases import fake_pyspiral + +_PROJECT = "lookups" +# Two key columns (tags) and two data columns, in two arrangements: the key order of the +# table and the column layout of its rows (CodeRabbit on #479, the several-items rule). +ARRANGEMENTS: dict[str, tuple[list[str], list[str]]] = { + # name: (key columns in key order, column layout) + "keys_first": (["subject", "k"], ["subject", "k", "x", "y"]), + "reversed": (["k", "subject"], ["y", "x", "k", "subject"]), +} +# The source's tag roles: every key a plain tag, or every key a data-tag (the default). +ROLES: dict[str, bool | tuple[str, ...]] = {"plain": True, "data_tags": ()} +_FIELDS = { + "subject": pa.field("subject", pa.large_string(), nullable=False), + "k": pa.field("k", pa.int64(), nullable=False), + "x": pa.field("x", pa.int64(), nullable=False), + "y": pa.field("y", pa.large_string(), nullable=True), +} +COUNTED = { + (fake_pyspiral.FakeProject, "table"): "lookup", + (fake_pyspiral.FakeProject, "list_tables"): "list_tables", + (fake_pyspiral.FakeTable, "schema"): "schema", + (fake_pyspiral.FakeTable, "last_modified_at"): "version", + (fake_pyspiral.FakeTable, "get_metadata"): "metadata", +} + + +def _schema(layout: list[str]) -> pa.Schema: + return pa.schema([_FIELDS[name] for name in layout]) + + +def _keys(keys: list[str]) -> pa.Schema: + return pa.schema([_FIELDS[name] for name in keys]) + + +def _rows(layout: list[str], ks: list[int]) -> pa.Table: + values = { + "subject": [f"s{k % 2}" for k in ks], + "k": ks, + "x": [10 * k for k in ks], + "y": [f"v{k}" for k in ks], + } + return pa.table({name: values[name] for name in layout}, schema=_schema(layout)) + + +@pytest.fixture(params=sorted(ARRANGEMENTS)) +def calls( + request: pytest.FixtureRequest, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> Iterator[collections.Counter[str]]: + """A fake project with table ``default.t`` in one arrangement; counts the pyspiral + calls made on it.""" + keys, layout = ARRANGEMENTS[request.param] + counts: collections.Counter[str] = collections.Counter() + for (cls, name), label in COUNTED.items(): + original: Callable[..., Any] = getattr(cls, name) # pyright: ignore[reportExplicitAny] # the fake's method + + def wrapper( + *args: Any, # pyright: ignore[reportExplicitAny] # passed through + _original: Callable[..., Any] = original, # pyright: ignore[reportExplicitAny] + _label: str = label, + **kwargs: Any, # pyright: ignore[reportExplicitAny] + ) -> Any: # pyright: ignore[reportExplicitAny] + counts[_label] += 1 + return _original(*args, **kwargs) + + monkeypatch.setattr(cls, name, wrapper) + with fake_pyspiral.install(tmp_path / "spiral"): + project = fake_pyspiral.FakeSpiral().project(_PROJECT) + table = project.create_table("default.t", key_schema=_keys(keys)) + table.write(_rows(layout, [0, 1, 2])) + write_nullability_record(table, _schema(layout)) + _ARRANGED["keys"], _ARRANGED["layout"] = keys, layout + counts.clear() + yield counts + + +# The arrangement the current ``calls`` fixture built (for the recreation test). +_ARRANGED: dict[str, list[str]] = {} + + +def _source(role: str, **kwargs: Any) -> SpiralDBTableSource: # pyright: ignore[reportExplicitAny] # options + return SpiralDBTableSource( + project_id=_PROJECT, table_name="t", tag_only_columns=ROLES[role], **kwargs + ) + + +def _sync_and_async_rows(source: SpiralDBTableSource) -> tuple[list[Any], list[Any]]: # pyright: ignore[reportExplicitAny] # rows + """Every row through the public sync and async reads, tags and data merged.""" + + def merged(tag: Any, data: Any) -> tuple[tuple[str, Any], ...]: # pyright: ignore[reportExplicitAny] + return tuple(sorted({**tag.as_dict(), **data.as_dict()}.items())) + + async def collect() -> list[Any]: # pyright: ignore[reportExplicitAny] + return [merged(t, d) async for t, d in source.async_iter_data()] + + sync = [merged(t, d) for t, d in source.iter_data()] + return sync, asyncio.run(collect()) + + +def _expected_rows(ks: list[int]) -> list[Any]: # pyright: ignore[reportExplicitAny] # rows + """The rows of ``_rows(..., ks)``, written out independently, tags and data merged.""" + return sorted( + tuple( + sorted({"subject": f"s{k % 2}", "k": k, "x": 10 * k, "y": f"v{k}"}.items()) + ) + for k in ks + ) + + +@pytest.mark.parametrize("role", sorted(ROLES)) +def test_a_source_looks_its_table_up_once_to_build( + calls: collections.Counter[str], role: str +) -> None: + source = _source(role) + # Before ITL-1350: 4 lookups (key, id, schema, version). + assert calls == { + "list_tables": 1, + "lookup": 1, + "schema": 1, + "metadata": 1, + "version": 1, + } + # Its reads are those of every source: the key order, layout and role it has. + tags, data = source.keys() + assert set(tags) == {"subject", "k"} + assert {"x", "y"} <= set(data) + assert (set(tags) <= set(data)) == (role == "data_tags") + 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_a_source_with_a_given_version_reads_no_version( + calls: collections.Counter[str], role: str +) -> None: + _source(role, asof=1) + # Before ITL-1350: 3 lookups (key, id, schema). + assert calls == {"list_tables": 1, "lookup": 1, "schema": 1, "metadata": 1} + + +@pytest.mark.parametrize("role", sorted(ROLES)) +def test_each_check_looks_the_table_up_once( + calls: collections.Counter[str], role: str +) -> None: + source = _source(role) + 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, "metadata": 1, "version": 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_a_check_still_finds_a_table_created_again( + calls: collections.Counter[str], role: str +) -> None: + source = _source(role) + keys, layout = _ARRANGED["keys"], _ARRANGED["layout"] + project = fake_pyspiral.FakeSpiral().project(_PROJECT) + project.drop_table("default.t") + again = project.create_table("default.t", key_schema=_keys(keys)) + again.write(_rows(layout, [0, 1, 2, 3])) + write_nullability_record(again, _schema(layout)) + calls.clear() + with pytest.raises(ValueError, match="dropped and created again"): + source.check_for_new_data() + # Refused on the id, before the new table's schema or version is read. + assert calls == {"lookup": 1} + + +def test_the_connector_getters_answer_as_the_handle_does( + calls: collections.Counter[str], +) -> None: + with SpiralDBConnector(project_id=_PROJECT) as connector: + table = connector.lookup_table("t") + # The key columns in the table's key order. + assert connector.get_pk_columns("t") == table.key_columns == _ARRANGED["keys"] + assert connector.get_spiral_table_id("t") == table.table_id + assert connector.get_arrow_schema("t").equals( + table.arrow_schema(), check_metadata=True + ) + assert table.arrow_schema().names == _ARRANGED["layout"] + assert connector.get_table_version("t") == table.version() + + +@pytest.mark.parametrize("role", sorted(ROLES)) +def test_the_arrangements_give_the_same_rows_and_pipeline_hash( + tmp_path: Path, role: str +) -> None: + """Two tables holding the same rows in the two arrangements: the same rows and the + same pipeline hash (a schema, in no column order); different content hashes, since + they are two tables (two table ids) and the key order is part of a row's record id.""" + with fake_pyspiral.install(tmp_path / "spiral"): + project = fake_pyspiral.FakeSpiral().project(_PROJECT) + sources = {} + for name, (keys, layout) in ARRANGEMENTS.items(): + table = project.create_table(f"default.{name}", key_schema=_keys(keys)) + table.write(_rows(layout, [0, 1, 2])) + write_nullability_record(table, _schema(layout)) + sources[name] = SpiralDBTableSource( + project_id=_PROJECT, table_name=name, tag_only_columns=ROLES[role] + ) + first, second = sources.values() + for source in (first, second): + sync, async_ = _sync_and_async_rows(source) + assert sorted(sync) == sorted(async_) == _expected_rows([0, 1, 2]) + assert first.pipeline_hash() == second.pipeline_hash() + assert first.content_hash() != second.content_hash() diff --git a/tests/test_core/sources/test_spiraldb_table_source.py b/tests/test_core/sources/test_spiraldb_table_source.py index 8dad21588..9bcca9bbf 100644 --- a/tests/test_core/sources/test_spiraldb_table_source.py +++ b/tests/test_core/sources/test_spiraldb_table_source.py @@ -24,13 +24,14 @@ from collections.abc import Generator from pathlib import Path from typing import Any, cast -from unittest.mock import patch +from unittest.mock import PropertyMock, patch import pyarrow as pa import pytest from orcapod.core.sources import SpiralDBTableSource from orcapod.databases import SpiralDBConnector +from orcapod.databases.spiraldb_connector import SpiralDBTable from tests.test_databases import fake_pyspiral _TABLE_NAME = "spike_data" @@ -228,7 +229,10 @@ def test_missing_table_raises_value_error(self): def test_a_table_without_a_key_schema_raises(self, tag_columns): """Rows are identified by their primary key, so a key schema is required.""" _make_table() - with patch.object(SpiralDBConnector, "get_pk_columns", return_value=[]): + # The source reads the key from its one lookup of the table (ITL-1350). + with patch.object( + SpiralDBTable, "key_columns", new_callable=PropertyMock, return_value=[] + ): with pytest.raises(ValueError, match="no primary key"): SpiralDBTableSource( _PROJECT_ID,