From f64d5e42920692a6d552625f4ed5437b360c4889 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 10:59:53 -0800 Subject: [PATCH 1/3] perf(spiraldb): reuse source clients and resolved read handles --- changelog.d/ITL-1431.md | 3 + .../core/sources/spiraldb_table_source.py | 412 ++++++++++-------- src/orcapod/databases/spiraldb_connector.py | 75 +++- .../sources/test_spiraldb_lookups.py | 158 ++++++- .../sources/test_spiraldb_table_source.py | 23 +- tests/test_databases/fake_pyspiral.py | 16 +- 6 files changed, 460 insertions(+), 227 deletions(-) create mode 100644 changelog.d/ITL-1431.md diff --git a/changelog.d/ITL-1431.md b/changelog.d/ITL-1431.md new file mode 100644 index 000000000..d447c57b8 --- /dev/null +++ b/changelog.d/ITL-1431.md @@ -0,0 +1,3 @@ +### Changed + +- SpiralDB table sources reuse their SDK client and resolve the table once per read, including reads that also need a manifest row count. Construction looks up the requested table directly. diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 9f0bccaed..c46f2534f 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -9,6 +9,9 @@ Authentication is handled externally — run ``spiral login`` once; pyspiral keeps the credentials in its per-user application directory (``~/Library/Application Support/pyspiral/`` on macOS, ``~/.config/pyspiral/`` on Linux). +The SDK client belongs to this source and is reused for its reads and freshness checks. +Use a new source after changing the SDK endpoint, credentials or options. Use the source +as a context manager or call ``close()`` after its reads and jobs have finished. Example:: @@ -40,7 +43,8 @@ import copy import dataclasses from collections.abc import AsyncIterator, Collection, Generator, Iterator, Mapping -from contextlib import contextmanager +from threading import Lock +from types import TracebackType from typing import Any, ClassVar, NamedTuple, TYPE_CHECKING import pyarrow as pa @@ -59,7 +63,11 @@ from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import check_head_size from orcapod.core.streams.view import ViewStatus, StreamView -from orcapod.databases.spiraldb_connector import SpiralDBConnector +from orcapod.databases.spiraldb_connector import ( + SpiralDBConnector, + SpiralDBTable, + SpiralDBTableNotFoundError, +) from orcapod.errors import InputValidationError, RowIdentifierError, SourceTooLargeError from orcapod.types import ColumnConfig, Condition from orcapod.types.condition import check_equality_conditions @@ -331,7 +339,10 @@ def __init__( self._project_id = project_id self._dataset = dataset self._table_name = table_name - self._overrides = overrides + self._overrides = None if overrides is None else dict(overrides) + self._connection: SpiralDBConnector | None = None + self._connection_lock = Lock() + self._closed = False self._condition = Condition() self._limit = limit self._max_rows = max_rows @@ -340,13 +351,13 @@ def __init__( self._tags_as_data: dict[str, str] = dict(tags_as_data) if tags_as_data else {} location = f"SpiralDB project {project_id!r}, dataset {dataset!r}" - with self._connector() as connector: - if table_name not in connector.get_table_names(): + try: + try: + table = self._connector().lookup_table(table_name) + except SpiralDBTableNotFoundError as exc: raise ValueError( f"{location}: Table {table_name!r} not found in database." - ) - # One lookup for the key, id, schema and version (ITL-1350). - table = connector.lookup_table(table_name) + ) from exc primary_key = tuple(table.key_columns) self._key_columns: tuple[str, ...] = ( given_key if given_key is not None else primary_key @@ -363,77 +374,82 @@ def __init__( # 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) - # The default tags are the primary key, whatever identifies the rows. - resolved_tags = ( - list(primary_key or self._key_columns) - if tag_columns is None - else _normalize_column_list(tag_columns) - ) - key_problems = [ - f"{c!r} is not a column" - if c not in schema.names - else f"{c!r} has type {schema.field(c).type}" - for c in self._key_columns - if c not in schema.names - or not key_column_type_allowed(schema.field(c).type) - ] - if key_problems: - raise ValueError( - f"{location}: table {table_name!r} cannot identify its rows by key " - f"columns {list(self._key_columns)}: {'; '.join(key_problems)}. A key " - "column must hold strings, integers, booleans, timestamps or dates." - ) - self._record_id_columns = given_key - if self._source_id is None: - self._source_id = location_source_id( - self.SOURCE_KIND, - spiraldb_table_address(project_id, dataset, table_name, self._table_id), + # The default tags are the primary key, whatever identifies the rows. + resolved_tags = ( + list(primary_key or self._key_columns) + if tag_columns is None + else _normalize_column_list(tag_columns) ) - # Every declared tag is a data-tag unless kept tag-only (ITL-1023). - self._data_tags = source_data_tags(resolved_tags, tag_only_columns) + key_problems = [ + f"{c!r} is not a column" + if c not in schema.names + else f"{c!r} has type {schema.field(c).type}" + for c in self._key_columns + if c not in schema.names + or not key_column_type_allowed(schema.field(c).type) + ] + if key_problems: + raise ValueError( + f"{location}: table {table_name!r} cannot identify its rows by key " + f"columns {list(self._key_columns)}: {'; '.join(key_problems)}. A key " + "column must hold strings, integers, booleans, timestamps or dates." + ) + self._record_id_columns = given_key + if self._source_id is None: + self._source_id = location_source_id( + self.SOURCE_KIND, + spiraldb_table_address( + project_id, dataset, table_name, self._table_id + ), + ) + # Every declared tag is a data-tag unless kept tag-only (ITL-1023). + self._data_tags = source_data_tags(resolved_tags, tag_only_columns) - # A zero-row stream with the table's columns answers every schema question. - self._builder = SourceStreamBuilder(self.data_context, self.orcapod_config) - try: - template = self._builder.build( - schema.empty_table(), - tag_columns=resolved_tags, - source_id=self._source_id, - system_tag_columns=system_tag_columns, - data_tags=self._data_tags, - ) - except ValueError as exc: - raise ValueError(f"{location}, table {table_name!r}: {exc}") from exc - self._table_schema: pa.Schema = arrow_utils.drop_system_columns( - schema.empty_table() - ).schema - if requested: - try: - self._apply_restriction(requested) - except (ValueError, TypeError) as exc: - raise type(exc)(f"{location}, table {table_name!r}: {exc}") from exc - if self._tags_as_data: + # A zero-row stream with the table's columns answers every schema question. + self._builder = SourceStreamBuilder(self.data_context, self.orcapod_config) try: - self._check_tags_as_data(template.stream.keys()) - except InputValidationError as exc: - raise InputValidationError( - f"{location}, table {table_name!r}: {exc}" - ) from exc - # The copies are columns of the schema: build the template with them. - template = self._builder.build( - self._with_tag_copies(self._table_schema.empty_table()), - tag_columns=template.tag_columns, - source_id=self._source_id, - system_tag_columns=template.system_tag_columns, - data_tags=self._data_tags, + template = self._builder.build( + schema.empty_table(), + tag_columns=resolved_tags, + source_id=self._source_id, + system_tag_columns=system_tag_columns, + data_tags=self._data_tags, + ) + except ValueError as exc: + raise ValueError(f"{location}, table {table_name!r}: {exc}") from exc + self._table_schema: pa.Schema = arrow_utils.drop_system_columns( + schema.empty_table() + ).schema + if requested: + try: + self._apply_restriction(requested) + except (ValueError, TypeError) as exc: + raise type(exc)(f"{location}, table {table_name!r}: {exc}") from exc + if self._tags_as_data: + try: + self._check_tags_as_data(template.stream.keys()) + except InputValidationError as exc: + raise InputValidationError( + f"{location}, table {table_name!r}: {exc}" + ) from exc + # The copies are columns of the schema: build the template with them. + template = self._builder.build( + self._with_tag_copies(self._table_schema.empty_table()), + tag_columns=template.tag_columns, + source_id=self._source_id, + system_tag_columns=template.system_tag_columns, + data_tags=self._data_tags, + ) + self._stream = template.stream + self._schema_hash = template.schema_hash + self._tag_columns = template.tag_columns + self._tag_only_columns = tuple( + c for c in self._tag_columns if c not in self._data_tags ) - self._stream = template.stream - self._schema_hash = template.schema_hash - self._tag_columns = template.tag_columns - self._tag_only_columns = tuple( - c for c in self._tag_columns if c not in self._data_tags - ) - self._system_tag_columns = template.system_tag_columns + self._system_tag_columns = template.system_tag_columns + except BaseException: + self.close() + raise def _check_tags_as_data( self, keys: tuple[tuple[str, ...], tuple[str, ...]] @@ -561,8 +577,9 @@ def _copy(self) -> "SpiralDBTableSource": the data context and config, the condition (immutable) and limit, the tuples of tag, data-tag and key columns and the pinned version. Copied: the ``tags_as_data`` and ``overrides`` mappings. Reset: the content and pipeline - hash caches (they are recomputed, equal, on first use). The modified time is - carried over; ``_apply_restriction`` moves it. A SpiralDB source holds no row + hash caches (they are recomputed, equal, on first use) and the SDK client + (the copy opens its own on demand). The modified time is carried over; + ``_apply_restriction`` moves it. A SpiralDB source holds no row it read, so there is nothing else to reset. """ duplicate = copy.copy(self) @@ -570,6 +587,8 @@ def _copy(self) -> "SpiralDBTableSource": duplicate._overrides = ( None if self._overrides is None else dict(self._overrides) ) + duplicate._connection = None + duplicate._connection_lock = Lock() duplicate._content_hash_cache = {} duplicate._pipeline_hash_cache = {} return duplicate @@ -655,18 +674,39 @@ def identity_structure(self) -> Any: # Reading # ------------------------------------------------------------------------- - @contextmanager - def _connector(self) -> Iterator[SpiralDBConnector]: - """Open a connector to the source's dataset and close it afterwards.""" - connector = SpiralDBConnector( - project_id=self._project_id, - dataset=self._dataset, - overrides=self._overrides, - ) - try: - yield connector - finally: - connector.close() + def _connector(self) -> SpiralDBConnector: + """Return the connector owned by this source.""" + with self._connection_lock: + if self._closed: + raise RuntimeError("SpiralDBTableSource is closed") + if self._connection is None: + self._connection = SpiralDBConnector( + project_id=self._project_id, + dataset=self._dataset, + overrides=self._overrides, + ) + return self._connection + + def close(self) -> None: + """Release this source's SDK client after its reads have finished.""" + with self._connection_lock: + self._closed = True + if self._connection is not None: + self._connection.close() + self._connection = None + + def __enter__(self) -> SpiralDBTableSource: + """Return this source for use as a context manager.""" + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + """Release the client at context exit.""" + self.close() @property def _qualified(self) -> str: @@ -682,8 +722,9 @@ def row_count_estimate(self) -> int: account, and the count can be above what a scan returns when rows were deleted or overwritten and not yet compacted. """ - with self._connector() as connector: - return connector.get_row_count_estimate(self._table_name, asof=self._asof) + return self._connector().get_row_count_estimate( + self._table_name, asof=self._asof + ) @override def check_for_new_data(self) -> bool: @@ -708,27 +749,26 @@ def check_for_new_data(self) -> bool: """ if self._given_asof is not None: return False - with self._connector() as connector: - # 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 " - f"{table_id!r}; the source reads {self._table_id!r}): it was " - "dropped and created again. Build the source again to read it." - ) - schema = arrow_utils.drop_system_columns( - table.arrow_schema().empty_table() - ).schema - if not schema.equals(self._table_schema, check_metadata=True): - raise ValueError( - f"SpiralDB table {self._qualified!r}: " - f"{_schema_difference(schema, self._table_schema)}. Build the " - "source again to read it as it is now." - ) - version = table.version() or None + # 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._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 " + f"{table_id!r}; the source reads {self._table_id!r}): it was " + "dropped and created again. Build the source again to read it." + ) + schema = arrow_utils.drop_system_columns( + table.arrow_schema().empty_table() + ).schema + if not schema.equals(self._table_schema, check_metadata=True): + raise ValueError( + f"SpiralDB table {self._qualified!r}: " + f"{_schema_difference(schema, self._table_schema)}. Build the " + "source again to read it as it is now." + ) + version = table.version() or None if version is None or (self._asof is not None and version <= self._asof): return False self._asof = version @@ -772,16 +812,27 @@ def _batch_streams(self) -> Generator["ArrowTableStream", None, None]: ValueError: If a batch's columns differ from the source's schema, or a key column holds a null. """ - return self._read_batches(limit=self._limit, max_rows=self._max_rows) + asof = self._asof + table = self._connector().lookup_table(self._table_name) + yield from self._read_batches( + table, asof=asof, limit=self._limit, max_rows=self._max_rows + ) def _read_batches( - self, *, limit: int | None, max_rows: int | None + self, + table: SpiralDBTable, + *, + asof: int | None, + limit: int | None, + max_rows: int | None, ) -> Generator["ArrowTableStream", None, None]: """Scan the table once, reading at most ``limit`` rows, in streams of ``batch_rows``. ``where`` and the pinned version apply as for every read. Args: + table: The handle resolved for this read, also used for the count. + asof: The pinned version for both the count and the scan. limit: Read at most this many rows, the first in key order. max_rows: Raise when the read would return more rows; ``None`` for no cap. @@ -791,71 +842,67 @@ def _read_batches( ValueError: If a batch's columns differ from the source's schema, or a key column holds a null. """ - with self._connector() as connector: - if ( - max_rows is not None - and not self._condition - and (limit is None or limit > max_rows) - ): - # Nothing but limit bounds the read, and the limit does not keep it - # under the cap: the table's recorded row count decides, before any - # row is read (so no row reaches a function of a job that would fail). - # The count can be above the rows a scan returns, never below. - recorded = connector.get_row_count_estimate( - self._table_name, asof=self._asof + if ( + max_rows is not None + and not self._condition + and (limit is None or limit > max_rows) + ): + # Nothing but limit bounds the read, and the limit does not keep it + # under the cap: the table's recorded row count decides, before any + # row is read (so no row reaches a function of a job that would fail). + # The count can be above the rows a scan returns, never below. + recorded = table.row_count_estimate(asof=asof) + bound = recorded if limit is None else min(limit, recorded) + if bound > max_rows: + raise self._too_large( + f"the read may return up to {bound:,} rows: the table records " + f"about {recorded:,} rows (SpiralDB's count, which can include " + "deleted rows not yet compacted)" ) - bound = recorded if limit is None else min(limit, recorded) - if bound > max_rows: - raise self._too_large( - f"the read may return up to {bound:,} rows: the table records " - f"about {recorded:,} rows (SpiralDB's count, which can include " - "deleted rows not yet compacted)" - ) - seen = 0 - # Keys must be unique across the whole read, not only within a slice. - identifiers: set[str] = set() - for batch in connector.scan_batches( - self._table_name, - where=dict(self._condition.equalities) or None, - limit=limit, - asof=self._asof, - ): - for start in range(0, batch.num_rows, self._batch_rows): - rows = arrow_utils.drop_system_columns( - pa.Table.from_batches([batch.slice(start, self._batch_rows)]) + seen = 0 + # Keys must be unique across the whole read, not only within a slice. + identifiers: set[str] = set() + for batch in table.scan_batches( + where=dict(self._condition.equalities) or None, + limit=limit, + asof=asof, + ): + for start in range(0, batch.num_rows, self._batch_rows): + rows = arrow_utils.drop_system_columns( + pa.Table.from_batches([batch.slice(start, self._batch_rows)]) + ) + # Metadata too: field metadata is how a column's logical type is + # recorded, and the schema hash was computed at construction. + if not rows.schema.equals(self._table_schema, check_metadata=True): + raise ValueError( + f"SpiralDB table {self._qualified!r}: " + f"{_schema_difference(rows.schema, self._table_schema)}. " + "The table changed after the source was built; build the " + "source again to read it as it is now." ) - # Metadata too: field metadata is how a column's logical type is - # recorded, and the schema hash was computed at construction. - if not rows.schema.equals(self._table_schema, check_metadata=True): - raise ValueError( - f"SpiralDB table {self._qualified!r}: " - f"{_schema_difference(rows.schema, self._table_schema)}. " - "The table changed after the source was built; build the " - "source again to read it as it is now." - ) - seen += rows.num_rows - if max_rows is not None and seen > max_rows: - raise self._too_large("the read returned more rows") - # Tokens first: they refuse a null key before it is copied into - # a non-nullable column. - tokens = self._key_tokens(rows) - repeated = identifiers.intersection(tokens) - if repeated: - raise RowIdentifierError( - f"SpiralDB table {self._qualified!r}: key " - f"{sorted(repeated)[0]} appears in two rows; key values " - "must be unique, so each row has its own identifier" - ) - identifiers.update(tokens) - yield self._builder.attach_provenance( - self._with_tag_copies(rows), - tag_columns=self._tag_columns, - system_tag_columns=self._system_tag_columns, - schema_hash=self._schema_hash, - source_id=self.source_id, - row_identifiers=tokens, - data_tags=self._data_tags, + seen += rows.num_rows + if max_rows is not None and seen > max_rows: + raise self._too_large("the read returned more rows") + # Tokens first: they refuse a null key before it is copied into + # a non-nullable column. + tokens = self._key_tokens(rows) + repeated = identifiers.intersection(tokens) + if repeated: + raise RowIdentifierError( + f"SpiralDB table {self._qualified!r}: key " + f"{sorted(repeated)[0]} appears in two rows; key values " + "must be unique, so each row has its own identifier" ) + identifiers.update(tokens) + yield self._builder.attach_provenance( + self._with_tag_copies(rows), + tag_columns=self._tag_columns, + system_tag_columns=self._system_tag_columns, + schema_hash=self._schema_hash, + source_id=self.source_id, + row_identifiers=tokens, + data_tags=self._data_tags, + ) def iter_data(self) -> Iterator["tuple[TagProtocol, DataProtocol]"]: """Scan the table and yield its ``(tag, data)`` pairs, one batch held at a time.""" @@ -939,14 +986,16 @@ def _head( return _Head(schema_only, False, self.row_count_estimate, True) limit = self._limit head_limit = n if limit is None else min(n, limit) + asof = self._asof + table = self._connector().lookup_table(self._table_name) rows = self._whole_table( - self._read_batches(limit=head_limit, max_rows=None), + self._read_batches(table, asof=asof, limit=head_limit, max_rows=None), columns=columns, all_info=all_info, ) if rows.num_rows < head_limit or head_limit == limit: return _Head(rows, True, rows.num_rows, False) - recorded = self.row_count_estimate + recorded = table.row_count_estimate(asof=asof) if limit is not None and not self._condition: recorded = min(limit, recorded) return _Head(rows, True, recorded, True) @@ -1023,8 +1072,8 @@ def run(self) -> StreamView: """Read the whole table into memory and return a ``StreamView`` of every row. Does what ``as_table()`` does: one scan of every row the source reads (``where``, - ``limit``, ``max_rows`` and the pinned version applied), held in memory. Nothing - is kept on the source, so every call scans again. ``head(n)`` and the notebook + ``limit``, ``max_rows`` and the pinned version applied), held in memory. The + source holds no rows, so every call scans again. ``head(n)`` and the notebook preview are the bounded read: they read only the first ``n`` rows. """ return super().run() @@ -1050,7 +1099,7 @@ def to_config(self, db_registry=None) -> dict[str, Any]: "source_type": self.SOURCE_KIND, "project_id": self._project_id, "dataset": self._dataset, - "overrides": self._overrides, + "overrides": None if self._overrides is None else dict(self._overrides), "table_name": self._table_name, "table_id": self._table_id, "tag_columns": list(self._tag_columns), @@ -1107,6 +1156,7 @@ def from_config( ) saved_id = config.get("table_id") if saved_id is not None and saved_id != source.table_id: + source.close() raise ValueError( f"SpiralDB table {source._qualified!r} was saved with table id " f"{saved_id!r} but that name now leads to table id " diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 8fed86396..88e5a725e 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -448,6 +448,10 @@ def _holds_nested_field_metadata(arrow_type: pa.DataType) -> bool: ) +class SpiralDBTableNotFoundError(ValueError): + """An exact table lookup found no matching table.""" + + class SpiralDBTable: """One SpiralDB table, looked up once (``SpiralDBConnector.lookup_table``). @@ -487,6 +491,7 @@ def arrow_schema(self) -> pa.Schema: """ import pyarrow as _pa # noqa: PLC0415 + self._connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle 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 @@ -494,8 +499,39 @@ def arrow_schema(self) -> pa.Schema: def version(self) -> int: """The table's current version (``get_table_version``).""" + self._connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle return int(self._table.last_modified_at()) + def scan_batches( + self, + *, + where: Mapping[str, object] | None = None, + limit: int | None = None, + asof: int | None = None, + ) -> Iterator[pa.RecordBatch]: + """Yield prepared Arrow batches from this resolved table in key order.""" + connector = self._connector + connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle + table = self._table + prepare = connector._batch_preparer(table, self._table_name) # pyright: ignore[reportPrivateUsage] # owns the handle + predicate = None + for column, value in (where or {}).items(): + equals = table[column] == value + predicate = equals if predicate is None else predicate & equals + scan = connector._spiral.scan( # pyright: ignore[reportPrivateUsage] # owns the handle + table.select(), where=predicate, limit=limit, asof=asof + ) + for batch in scan.to_record_batches(): + yield prepare(batch) + + def row_count_estimate(self, asof: int | None = None) -> int: + """Return this resolved table's manifest row count at the requested version.""" + connector = self._connector + connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle + snapshot = self._table.core.get_snapshot(asof=asof) + stats = connector._spiral.core.manifest_stats(snapshot) # pyright: ignore[reportPrivateUsage] # owns the handle + return int(stats.key_space_stats.total_rows) + class SpiralDBConnector: """DBConnectorProtocol implementation backed by SpiralDB (pyspiral). @@ -563,9 +599,16 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: 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 - ) + identifier = self._table_id(table_name) + try: + table = self._project.table(identifier) + except ValueError as exc: + # pyspiral raises this exact ValueError for an empty name lookup. Preserve + # other failures, including errors in loading the returned table handle. + if str(exc) != f"Table not found: {self._project_id}.{identifier}": + raise + raise SpiralDBTableNotFoundError(str(exc)) from exc + return SpiralDBTable(self, table, table_name) def get_pk_columns(self, table_name: str) -> list[str]: """Return primary-key column names in declaration order. @@ -783,16 +826,9 @@ def scan_batches( NullInNonNullableColumnError: If a batch holds a null in a recorded non-nullable column (naming the table and the column). """ - self._require_open() - tbl = self._project.table(self._table_id(table_name)) - prepare = self._batch_preparer(tbl, table_name) - predicate = None - for column, value in (where or {}).items(): - equals = tbl[column] == value - predicate = equals if predicate is None else predicate & equals - scan = self._spiral.scan(tbl.select(), where=predicate, limit=limit, asof=asof) - for batch in scan.to_record_batches(): - yield prepare(batch) + yield from self.lookup_table(table_name).scan_batches( + where=where, limit=limit, asof=asof + ) def get_arrow_schema(self, table_name: str) -> pa.Schema: """Return the schema of the batches ``scan_batches`` yields, without scanning. @@ -850,10 +886,7 @@ def get_row_count_estimate(self, table_name: str, asof: int | None = None) -> in Returns: The recorded row count. """ - self._require_open() - tbl = self._project.table(self._table_id(table_name)) - stats = self._spiral.core.manifest_stats(tbl.core.get_snapshot(asof=asof)) - return int(stats.key_space_stats.total_rows) + return self.lookup_table(table_name).row_count_estimate(asof=asof) def delete_table(self, table_name: str) -> None: """Drop a table from SpiralDB, if it exists. @@ -1181,8 +1214,12 @@ def validate_records(self, records: pa.Table) -> None: """No-op: ``SpiralDBConnector`` preserves Arrow field metadata via the native KV store.""" def close(self) -> None: - """Mark this connector as closed. Idempotent. No network teardown needed.""" - self._closed = True + """Close this connector and release its SDK client. Idempotent.""" + if not self._closed: + self._closed = True + # pyspiral exposes no close method. Drop both owning references. + del self._project + del self._spiral def __enter__(self) -> SpiralDBConnector: return self diff --git a/tests/test_core/sources/test_spiraldb_lookups.py b/tests/test_core/sources/test_spiraldb_lookups.py index 1b485b27b..c167f5a89 100644 --- a/tests/test_core/sources/test_spiraldb_lookups.py +++ b/tests/test_core/sources/test_spiraldb_lookups.py @@ -1,10 +1,8 @@ -"""A SpiralDB source looks its table up once to build and once per check (ITL-1350). +"""Count SDK calls for sources and jobs using the repository's pyspiral fake. -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. +Construction and each freshness check get metadata from one lookup (ITL-1350). +Each read has its own table lookup, including reads that also use a manifest count, +and the source reuses its SDK client (ITL-1431). """ from __future__ import annotations @@ -13,12 +11,19 @@ import collections from collections.abc import Callable, Iterator from pathlib import Path -from typing import Any +from typing import Any, cast import pyarrow as pa import pytest -from orcapod.databases import SpiralDBConnector, write_nullability_record +from orcapod import PipelineJob +from orcapod.databases import ( + InMemoryArrowDatabase, + SpiralDBConnector, + write_nullability_record, +) +from orcapod.operators import SelectColumns +from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.sources import SpiralDBTableSource from tests.test_databases import fake_pyspiral @@ -39,6 +44,9 @@ "y": pa.field("y", pa.large_string(), nullable=True), } COUNTED = { + (fake_pyspiral.FakeSpiral, "__init__"): "client", + (fake_pyspiral.FakeSpiral, "manifest_stats"): "manifest", + (fake_pyspiral.FakeSpiral, "scan"): "scan", (fake_pyspiral.FakeProject, "table"): "lookup", (fake_pyspiral.FakeProject, "list_tables"): "list_tables", (fake_pyspiral.FakeTable, "schema"): "schema", @@ -136,7 +144,7 @@ def test_a_source_looks_its_table_up_once_to_build( source = _source(role) # Before ITL-1350: 4 lookups (key, id, schema, version). assert calls == { - "list_tables": 1, + "client": 1, "lookup": 1, "schema": 1, "metadata": 1, @@ -157,7 +165,7 @@ def test_a_source_with_a_given_version_reads_no_version( ) -> None: _source(role, asof=1) # Before ITL-1350: 3 lookups (key, id, schema). - assert calls == {"list_tables": 1, "lookup": 1, "schema": 1, "metadata": 1} + assert calls == {"client": 1, "lookup": 1, "schema": 1, "metadata": 1} @pytest.mark.parametrize("role", sorted(ROLES)) @@ -192,6 +200,136 @@ def test_a_check_still_finds_a_table_created_again( assert calls == {"lookup": 1} +def test_missing_table_matches_source_diagnostic( + calls: collections.Counter[str], +) -> None: + with pytest.raises(ValueError) as exc: + SpiralDBTableSource(project_id=_PROJECT, table_name="missing") + assert type(exc.value) is ValueError + assert str(exc.value) == ( + f"SpiralDB project {_PROJECT!r}, dataset 'default': " + "Table 'missing' not found in database." + ) + assert calls == {"lookup": 1, "client": 1} + + +def test_lookup_preserves_unrelated_sdk_errors( + calls: collections.Counter[str], monkeypatch: pytest.MonkeyPatch +) -> None: + error = ValueError("Invalid SDK configuration") + + def fail(_project: fake_pyspiral.FakeProject, _identifier: str) -> None: + raise error + + monkeypatch.setattr(fake_pyspiral.FakeProject, "table", fail) + with pytest.raises(ValueError) as exc: + _source("plain") + assert exc.value is error + assert calls == {"client": 1} + + +def test_restricted_copy_owns_its_client(calls: collections.Counter[str]) -> None: + source = _source("plain") + restricted = source.where(subject="s0") + source.close() + calls.clear() + assert sorted(cast("list[int]", restricted.as_table()["k"].to_pylist())) == [0, 2] + assert calls == {"client": 1, "lookup": 1, "metadata": 1, "scan": 1} + restricted.close() + + +@pytest.mark.parametrize("restricted", [False, True]) +@pytest.mark.parametrize("async_read", [False, True]) +def test_each_read_resolves_once_and_reuses_its_client( + calls: collections.Counter[str], restricted: bool, async_read: bool +) -> None: + source = _source("data_tags", where={"subject": "s0"} if restricted else None) + expected = [0, 2] if restricted else [0, 1, 2] + + async def collect() -> list[int]: + keys: list[int] = [] + async for tag, _ in source.async_iter_data(): + key = tag.as_dict()["k"] + assert isinstance(key, int) + keys.append(key) + return keys + + for _ in range(2): + calls.clear() + keys = ( + asyncio.run(collect()) + if async_read + else cast("list[int]", source.as_table()["k"].to_pylist()) + ) + assert sorted(keys) == expected + assert calls == {"lookup": 1, "metadata": 1, "scan": 1} | ( + {} if restricted else {"manifest": 1} + ) + + calls.clear() + head = source.head(1) + assert head.table.num_rows == 1 + assert head.total_rows == 3 + assert calls == {"lookup": 1, "metadata": 1, "scan": 1, "manifest": 1} + + +@pytest.mark.parametrize("orchestrator", [None, AsyncPipelineOrchestrator]) +def test_job_reuses_client_but_refreshes_table_each_run( + calls: collections.Counter[str], + orchestrator: type[AsyncPipelineOrchestrator] | None, +) -> None: + source = _source("data_tags") + job = PipelineJob(name="lookups", database=InMemoryArrowDatabase()) + with job: + SelectColumns(["subject", "k", "x", "y"])(source, label="read") + runner = orchestrator() if orchestrator is not None else None + + calls.clear() + job.run(orchestrator=runner) + assert job.nodes["read"].as_table().num_rows == 3 + assert calls == { + "lookup": 2, + "metadata": 2, + "schema": 1, + "version": 1, + "manifest": 1, + "scan": 1, + } + + calls.clear() + job.run(orchestrator=runner) + assert calls == {"lookup": 1, "metadata": 1, "schema": 1, "version": 1} + + +def test_freshness_catches_metadata_schema_changes( + calls: collections.Counter[str], +) -> None: + source = _source("plain") + layout = _ARRANGED["layout"] + table = fake_pyspiral.FakeSpiral().project(_PROJECT).table("default.t") + changed = pa.schema( + [ + _FIELDS[name].with_nullable(True) if name == "x" else _FIELDS[name] + for name in layout + ] + ) + write_nullability_record(table, changed) + calls.clear() + with pytest.raises(ValueError, match="the table has column .x."): + source.check_for_new_data() + assert calls == {"lookup": 1, "metadata": 1, "schema": 1} + + +def test_freshness_pins_newer_version(calls: collections.Counter[str]) -> None: + source = _source("plain") + table = fake_pyspiral.FakeSpiral().project(_PROJECT).table("default.t") + table.write(_rows(_ARRANGED["layout"], [3])) + calls.clear() + assert source.check_for_new_data() + assert calls == {"lookup": 1, "metadata": 1, "schema": 1, "version": 1} + assert sorted(cast("list[int]", source.as_table()["k"].to_pylist())) == [0, 1, 2, 3] + + def test_the_connector_getters_answer_as_the_handle_does( calls: collections.Counter[str], ) -> None: diff --git a/tests/test_core/sources/test_spiraldb_table_source.py b/tests/test_core/sources/test_spiraldb_table_source.py index 9bcca9bbf..ba4538a87 100644 --- a/tests/test_core/sources/test_spiraldb_table_source.py +++ b/tests/test_core/sources/test_spiraldb_table_source.py @@ -267,7 +267,7 @@ def test_dataset_and_overrides_forwarded_to_connector(self): ) def test_every_connector_is_closed(self): - """Every connector is closed: build, full read, unfinished read, error.""" + """Close the shared connector at context exit or failed construction.""" _make_table() opened: list[SpiralDBConnector] = [] @@ -277,17 +277,22 @@ def connect(**kwargs): return opened[-1] with patch(_CONNECTOR, side_effect=connect): - src = SpiralDBTableSource(_PROJECT_ID, _TABLE_NAME, tag_only_columns=True) - src.as_table() - # iter_data is a generator function, so the read can be closed. - unfinished = cast("Generator[Any, None, None]", src.iter_data()) - next(unfinished) # a read that is not finished - unfinished.close() + with SpiralDBTableSource( + _PROJECT_ID, _TABLE_NAME, tag_only_columns=True + ) as src: + src.as_table() + unfinished = cast("Generator[Any, None, None]", src.iter_data()) + next(unfinished) + unfinished.close() + assert src.as_table().num_rows == 3 + src.close() + with pytest.raises(RuntimeError, match="SpiralDBTableSource is closed"): + src.as_table() with pytest.raises(ValueError): SpiralDBTableSource(_PROJECT_ID, "no_such_table", tag_only_columns=True) - assert len(opened) == 4 + assert len(opened) == 2 # About the connector's own closed flag: nothing public reports it. - assert [c._closed for c in opened] == [True] * 4 # pyright: ignore[reportPrivateUsage] + assert [c._closed for c in opened] == [True] * 2 # pyright: ignore[reportPrivateUsage] # =========================================================================== diff --git a/tests/test_databases/fake_pyspiral.py b/tests/test_databases/fake_pyspiral.py index 874ec8220..323cb215a 100644 --- a/tests/test_databases/fake_pyspiral.py +++ b/tests/test_databases/fake_pyspiral.py @@ -473,7 +473,7 @@ class FakeTable: def __init__(self, store: _Store, project_id: str, identifier: str) -> None: """Open table ``identifier`` of ``project_id`` in ``store``.""" if not store.exists(project_id, identifier): - raise ValueError(f"Table not found: {project_id}/{identifier}") + raise ValueError(f"Table not found: {project_id}.{identifier}") self._store = store self._project_id = project_id self._identifier = identifier @@ -821,14 +821,14 @@ def scan(self, *projections: Any, **kwargs: Any) -> FakeScan: def core(self) -> Any: """The client's low-level handle; only ``manifest_stats`` is modelled.""" - def manifest_stats(snapshot: FakeTable) -> Any: - """Return stats whose ``key_space_stats.total_rows`` counts rows.""" - rows = snapshot._read_all().num_rows - return types.SimpleNamespace( - key_space_stats=types.SimpleNamespace(total_rows=rows) - ) + return types.SimpleNamespace(manifest_stats=self.manifest_stats) - return types.SimpleNamespace(manifest_stats=manifest_stats) + def manifest_stats(self, snapshot: FakeTable) -> Any: + """Return stats whose ``key_space_stats.total_rows`` counts rows.""" + rows = snapshot._read_all().num_rows + return types.SimpleNamespace( + key_space_stats=types.SimpleNamespace(total_rows=rows) + ) fake_spiral_module = types.SimpleNamespace(Spiral=FakeSpiral) From 1757b9f9d5d9a7166e7cc763b03939112c296011 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 11:17:01 -0800 Subject: [PATCH 2/3] fix(spiraldb): bind source reads to the original scope --- .../core/sources/spiraldb_table_source.py | 52 +++++---- src/orcapod/databases/spiraldb_connector.py | 16 +++ .../sources/test_spiraldb_lookups.py | 109 +++++++++++++++++- .../test_spiraldb_table_source_streaming.py | 5 +- tests/test_databases/fake_pyspiral.py | 35 +++++- 5 files changed, 188 insertions(+), 29 deletions(-) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index c46f2534f..db845a053 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -9,7 +9,7 @@ Authentication is handled externally — run ``spiral login`` once; pyspiral keeps the credentials in its per-user application directory (``~/Library/Application Support/pyspiral/`` on macOS, ``~/.config/pyspiral/`` on Linux). -The SDK client belongs to this source and is reused for its reads and freshness checks. +The SDK client is reused for reads and freshness checks, including on restricted copies. Use a new source after changing the SDK endpoint, credentials or options. Use the source as a context manager or call ``close()`` after its reads and jobs have finished. @@ -569,7 +569,7 @@ def where( return restricted def _copy(self) -> "SpiralDBTableSource": - """Return a new source object on the same table, sharing no mutable state. + """Return a new source on the same table and configured client. The future ``copy()`` (ITL-1219). No metadata is read again, so the copy reads the version this source pinned. Shared, because immutable: the table @@ -577,17 +577,21 @@ def _copy(self) -> "SpiralDBTableSource": the data context and config, the condition (immutable) and limit, the tuples of tag, data-tag and key columns and the pinned version. Copied: the ``tags_as_data`` and ``overrides`` mappings. Reset: the content and pipeline - hash caches (they are recomputed, equal, on first use) and the SDK client - (the copy opens its own on demand). The modified time is carried over; - ``_apply_restriction`` moves it. A SpiralDB source holds no row - it read, so there is nothing else to reset. + hash caches (they are recomputed, equal, on first use). Each source owns + a connector that holds the same SDK client and can be closed independently. + The modified time is carried over until ``_apply_restriction`` moves it. + A SpiralDB source holds no rows it read. """ - duplicate = copy.copy(self) + with self._connection_lock: + connection = self._connection + if connection is None: + raise RuntimeError("SpiralDBTableSource is closed") + duplicate = copy.copy(self) + duplicate._connection = connection.share_client() duplicate._tags_as_data = dict(self._tags_as_data) duplicate._overrides = ( None if self._overrides is None else dict(self._overrides) ) - duplicate._connection = None duplicate._connection_lock = Lock() duplicate._content_hash_cache = {} duplicate._pipeline_hash_cache = {} @@ -688,7 +692,7 @@ def _connector(self) -> SpiralDBConnector: return self._connection def close(self) -> None: - """Release this source's SDK client after its reads have finished.""" + """Release this source's reference to the SDK client after its reads finish.""" with self._connection_lock: self._closed = True if self._connection is not None: @@ -713,6 +717,18 @@ def _qualified(self) -> str: """The table as error messages name it.""" return f"{self._project_id}/{self._dataset}.{self._table_name}" + def _lookup_table(self) -> SpiralDBTable: + """Resolve the name and check that it still identifies this source's table.""" + table = self._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 " + f"{table_id!r}; the source reads {self._table_id!r}): it was " + "dropped and created again. Build the source again to read it." + ) + return table + @property def row_count_estimate(self) -> int: """The whole table's row count as SpiralDB's manifests record it. @@ -722,9 +738,8 @@ def row_count_estimate(self) -> int: account, and the count can be above what a scan returns when rows were deleted or overwritten and not yet compacted. """ - return self._connector().get_row_count_estimate( - self._table_name, asof=self._asof - ) + asof = self._asof + return self._lookup_table().row_count_estimate(asof=asof) @override def check_for_new_data(self) -> bool: @@ -751,14 +766,7 @@ def check_for_new_data(self) -> bool: 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._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 " - f"{table_id!r}; the source reads {self._table_id!r}): it was " - "dropped and created again. Build the source again to read it." - ) + table = self._lookup_table() schema = arrow_utils.drop_system_columns( table.arrow_schema().empty_table() ).schema @@ -813,7 +821,7 @@ def _batch_streams(self) -> Generator["ArrowTableStream", None, None]: key column holds a null. """ asof = self._asof - table = self._connector().lookup_table(self._table_name) + table = self._lookup_table() yield from self._read_batches( table, asof=asof, limit=self._limit, max_rows=self._max_rows ) @@ -987,7 +995,7 @@ def _head( limit = self._limit head_limit = n if limit is None else min(n, limit) asof = self._asof - table = self._connector().lookup_table(self._table_name) + table = self._lookup_table() rows = self._whole_table( self._read_batches(table, asof=asof, limit=head_limit, max_rows=None), columns=columns, diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 88e5a725e..be80d8919 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -24,6 +24,7 @@ import re from collections.abc import Callable, Iterator, Mapping from contextlib import contextmanager +from copy import copy from typing import TYPE_CHECKING, Any import pyarrow as pa @@ -567,6 +568,11 @@ def _require_open(self) -> None: if self._closed: raise RuntimeError("SpiralDBConnector is closed") + def share_client(self) -> SpiralDBConnector: + """Return an independently closable connector in the same SDK client scope.""" + self._require_open() + return copy(self) + def _table_id(self, table_name: str) -> str: """Return the dataset-qualified table identifier for a plain table name.""" return f"{self._dataset}.{table_name}" @@ -600,6 +606,16 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: """ self._require_open() identifier = self._table_id(table_name) + if ( + not self._dataset + or not table_name + or "." in self._dataset + or "." in table_name + ): + # The SDK omits empty filters and treats dots as identifier separators. + raise SpiralDBTableNotFoundError( + f"Table not found: {self._project_id}.{identifier}" + ) try: table = self._project.table(identifier) except ValueError as exc: diff --git a/tests/test_core/sources/test_spiraldb_lookups.py b/tests/test_core/sources/test_spiraldb_lookups.py index c167f5a89..9be3f289f 100644 --- a/tests/test_core/sources/test_spiraldb_lookups.py +++ b/tests/test_core/sources/test_spiraldb_lookups.py @@ -228,13 +228,15 @@ def fail(_project: fake_pyspiral.FakeProject, _identifier: str) -> None: assert calls == {"client": 1} -def test_restricted_copy_owns_its_client(calls: collections.Counter[str]) -> None: +def test_restricted_copy_keeps_client_after_parent_closes( + calls: collections.Counter[str], +) -> None: source = _source("plain") restricted = source.where(subject="s0") source.close() calls.clear() assert sorted(cast("list[int]", restricted.as_table()["k"].to_pylist())) == [0, 2] - assert calls == {"client": 1, "lookup": 1, "metadata": 1, "scan": 1} + assert calls == {"lookup": 1, "metadata": 1, "scan": 1} restricted.close() @@ -273,6 +275,109 @@ async def collect() -> list[int]: assert calls == {"lookup": 1, "metadata": 1, "scan": 1, "manifest": 1} +@pytest.mark.parametrize( + ("dataset", "name"), + [("default", ""), ("", "t"), ("default", "default.t"), ("default.extra", "t")], +) +def test_source_rejects_malformed_names_before_sdk_lookup( + calls: collections.Counter[str], dataset: str, name: str +) -> None: + """Empty or already qualified names keep the source's missing-table diagnostic.""" + with pytest.raises(ValueError) as exc: + SpiralDBTableSource( + _PROJECT, name, dataset=dataset, source_id="explicit-source" + ) + assert type(exc.value) is ValueError + assert str(exc.value) == ( + f"SpiralDB project {_PROJECT!r}, dataset {dataset!r}: " + f"Table {name!r} not found in database." + ) + assert calls["lookup"] == calls["metadata"] == calls["scan"] == 0 + + +def _write_scope_table(root_layout: list[str], value: int) -> str: + """Write the same-shaped table with a recognizable value in this fake endpoint.""" + project = fake_pyspiral.FakeSpiral().project(_PROJECT) + table = project.create_table("default.t", key_schema=_keys(["subject", "k"])) + rows = _rows(root_layout, [0]) + rows = rows.set_column( + rows.schema.get_field_index("x"), + _FIELDS["x"], + pa.array([value], type=pa.int64()), + ) + table.write(rows) + write_nullability_record(table, rows.schema) + return table.table_id + + +async def _async_x(source: SpiralDBTableSource) -> list[object]: + """Return the x values from a public asynchronous source read.""" + return [data.as_dict()["x"] async for _, data in source.async_iter_data()] + + +@pytest.mark.parametrize("async_read", [False, True]) +def test_copy_keeps_its_original_endpoint(tmp_path: Path, async_read: bool) -> None: + layout = ["subject", "k", "x", "y"] + with fake_pyspiral.install(tmp_path / "endpoint-a"): + original_id = _write_scope_table(layout, 14) + source = _source("plain", asof=1) + restricted = source.where(subject="s0") + assert restricted.table_id == original_id + + with fake_pyspiral.install(tmp_path / "endpoint-b"): + assert _write_scope_table(layout, 29) != original_id + if async_read: + assert asyncio.run(_async_x(restricted)) == [14] + else: + 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) + project = fake_pyspiral.FakeSpiral().project(_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])) + write_nullability_record(replacement, _schema(layout)) + reads: dict[str, Callable[[], object]] = { + "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, + } + calls.clear() + with pytest.raises(ValueError, match="dropped and created again"): + reads[mode]() + assert calls == {"lookup": 1} + + +def test_two_async_job_readers_use_the_restricted_sources_endpoint( + tmp_path: Path, +) -> None: + layout = ["subject", "k", "x", "y"] + with fake_pyspiral.install(tmp_path / "endpoint-a"): + _write_scope_table(layout, 14) + restricted = _source("plain", asof=1).where(subject="s0") + with fake_pyspiral.install(tmp_path / "endpoint-b"): + _write_scope_table(layout, 29) + job = PipelineJob(name="two-readers", database=InMemoryArrowDatabase()) + with job: + SelectColumns(["subject", "x"])(restricted, label="left") + SelectColumns(["k", "x"])(restricted, label="right") + start = len(fake_pyspiral.scan_log) + job.run(orchestrator=AsyncPipelineOrchestrator()) + assert job.nodes["left"].as_table()["x"].to_pylist() == [14] + assert job.nodes["right"].as_table()["x"].to_pylist() == [14] + # The async job fans one scan out to both readers of this source. + assert len(fake_pyspiral.scan_log) - start == 1 + + @pytest.mark.parametrize("orchestrator", [None, AsyncPipelineOrchestrator]) def test_job_reuses_client_but_refreshes_table_each_run( calls: collections.Counter[str], 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 48e690183..4d16ae807 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_streaming.py +++ b/tests/test_core/sources/test_spiraldb_table_source_streaming.py @@ -413,6 +413,7 @@ def test_a_given_source_id_is_used_as_it_is(self, project): def test_a_recreated_table_is_a_different_source(self, project): """A recreated table is a new source; only its pipeline hash is unchanged.""" before = SpiralDBTableSource(_PROJECT, "event", tag_only_columns=True) + before_ids = _record_ids(before) project.drop_table("default.event") project.create_table("default.event", key_schema=_KEYS).write( _rows([1, 2, 3, 4, 5]) @@ -424,7 +425,9 @@ def test_a_recreated_table_is_a_different_source(self, project): assert after.pipeline_hash() == before.pipeline_hash() # 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] == _record_ids(before)[1] + assert _record_ids(after)[1] == before_ids[1] + with pytest.raises(ValueError, match="dropped and created again"): + before.as_table() 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/fake_pyspiral.py b/tests/test_databases/fake_pyspiral.py index 323cb215a..9bc7a0fb1 100644 --- a/tests/test_databases/fake_pyspiral.py +++ b/tests/test_databases/fake_pyspiral.py @@ -705,16 +705,43 @@ def __init__(self, store: _Store, project_id: str) -> None: def list_tables(self) -> list[TableResource]: """Return every table of the project, in every dataset.""" + return self._list_tables() + + def _list_tables( + self, dataset: str | None = None, table: str | None = None + ) -> list[TableResource]: + """Apply the SDK's project API filters, which omit empty values.""" out = [] for ident in self._store.identifiers(self._project_id): - dataset, _, table = ident.partition(".") + found_dataset, _, found_table = ident.partition(".") + if (dataset and dataset != found_dataset) or ( + table and table != found_table + ): + continue table_id = self._store.table_id(self._project_id, ident) - out.append(TableResource(table_id, self._project_id, dataset, table)) + out.append( + TableResource(table_id, self._project_id, found_dataset, found_table) + ) return out def table(self, identifier: str) -> FakeTable: - """Open the table ``"."``.""" - return FakeTable(self._store, self._project_id, identifier) + """Parse and resolve a name as pyspiral does, including omitted filters.""" + parts = identifier.split(".") + if len(parts) == 1: + dataset, table = "default", parts[0] + elif len(parts) == 2: + dataset, table = parts + else: + raise ValueError( + f"Invalid table identifier: {self._project_id}.{identifier}" + ) + resources = self._list_tables(dataset, table) + if not resources: + raise ValueError(f"Table not found: {self._project_id}.{dataset}.{table}") + resolved = resources[0] + return FakeTable( + self._store, self._project_id, f"{resolved.dataset}.{resolved.table}" + ) def create_table( self, From e5b6aa64dd54ae6ea6fdbe45f3acfc9a82cad310 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Mon, 23 Nov 2026 11:21:27 -0800 Subject: [PATCH 3/3] fix(spiraldb): close rejected source restrictions --- .../core/sources/spiraldb_table_source.py | 1 + .../sources/test_spiraldb_lookups.py | 29 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index db845a053..c01234856 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -565,6 +565,7 @@ def where( try: restricted._apply_restriction(condition) except (ValueError, TypeError) as exc: + restricted.close() raise type(exc)(f"SpiralDB table {self._qualified!r}: {exc}") from exc return restricted diff --git a/tests/test_core/sources/test_spiraldb_lookups.py b/tests/test_core/sources/test_spiraldb_lookups.py index 9be3f289f..417cbbcd1 100644 --- a/tests/test_core/sources/test_spiraldb_lookups.py +++ b/tests/test_core/sources/test_spiraldb_lookups.py @@ -9,6 +9,8 @@ import asyncio import collections +import gc +import weakref from collections.abc import Callable, Iterator from pathlib import Path from typing import Any, cast @@ -240,6 +242,33 @@ def test_restricted_copy_keeps_client_after_parent_closes( restricted.close() +def test_invalid_where_releases_client_with_exception_retained( + calls: collections.Counter[str], monkeypatch: pytest.MonkeyPatch +) -> None: + clients: list[weakref.ReferenceType[fake_pyspiral.FakeSpiral]] = [] + original = fake_pyspiral.FakeSpiral.__init__ + + def track( + sdk: fake_pyspiral.FakeSpiral, + *, + config: object = None, + overrides: dict[str, str] | None = None, + ) -> None: + original(sdk, config=config, overrides=overrides) + clients.append(weakref.ref(sdk)) + + monkeypatch.setattr(fake_pyspiral.FakeSpiral, "__init__", track) + source = _source("plain") + assert len(clients) == 1 and clients[0]() is not None + with pytest.raises(ValueError, match="missing_column") as held: + source.where(missing_column=1) + + source.close() + gc.collect() + assert held.value.__traceback__ is not None + assert clients[0]() is None + + @pytest.mark.parametrize("restricted", [False, True]) @pytest.mark.parametrize("async_read", [False, True]) def test_each_read_resolves_once_and_reuses_its_client(