From 3672d586c43a187da86c179e3d741ca4807174cc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 18:05:28 -0800 Subject: [PATCH 1/6] perf(spiraldb): use one SDK client per address and sign-in (ITL-1457) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/spiraldb_connector.py | 167 +++++++++++++++++--- 1 file changed, 145 insertions(+), 22 deletions(-) diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index bd72e28fe..0c43a3392 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -16,6 +16,7 @@ from __future__ import annotations +import hashlib import json import logging import math @@ -27,8 +28,9 @@ from collections.abc import Iterator, Mapping from contextlib import contextmanager from copy import copy -from threading import local +from threading import Lock, local from typing import TYPE_CHECKING, Any, cast +from weakref import WeakValueDictionary import pyarrow as pa import pyarrow.compute as pc @@ -45,7 +47,7 @@ compared_columns, describe_difference, ) -from orcapod.databases.spiraldb_sign_in import require_sign_in +from orcapod.databases.spiraldb_sign_in import require_sign_in, saved_login_path from orcapod.errors import ( NullInNonNullableColumnError, SpiralDBWriteNotSupportedError, @@ -135,13 +137,20 @@ class SpiralDBTableNotFoundError(ValueError): """An exact table lookup found no matching table.""" +class _Health: + """Whether a call of one SDK client failed (``_SharedClient``).""" + + failed = False + + @contextmanager -def _service_call(doing: str) -> Iterator[None]: +def _service_call(doing: str, health: _Health | None = None) -> Iterator[None]: """Note on a failing SDK call what Orcapod was doing: SpiralDB's errors often hold a - status only. + status only. A client with a failed call is handed to no new connector. Args: doing: What the call does, and to what. + health: The client's, if it is shared. """ try: yield @@ -149,11 +158,17 @@ def _service_call(doing: str) -> Iterator[None]: # The SDK's own error class is not named here: it may not be installed. if not isinstance(exc, (TableSchemaError, NullInNonNullableColumnError)): exc.add_note(f"SpiralDB: could not {doing}") + if health is not None: + health.failed = True raise def _open_keyed_table( - client: Any, project_id: str, dataset: str, name: str + client: Any, + project_id: str, + dataset: str, + name: str, + health: _Health | None = None, ) -> Any | None: """Return the latest snapshot of a keyed table, or ``None`` if there is none. @@ -161,7 +176,7 @@ def _open_keyed_table( name means "no such table"; a missing project, a refused sign-in or a transport failure has another and is raised. """ - with _service_call(f"open table {project_id}/{dataset}/{name}"): + with _service_call(f"open table {project_id}/{dataset}/{name}", health): try: return client.keyed_table(project_id, dataset, name) except sp.SpiralError as exc: @@ -258,10 +273,11 @@ def _api_url(overrides: Mapping[str, str] | None) -> str | None: return api_url -def _new_client(overrides: Mapping[str, str] | None) -> Any: - """Return a spiral-sdk client. +def _client_options(overrides: Mapping[str, str] | None) -> tuple[str | None, Any]: + """Return the service address and the SDK's client class, a sign-in being present. Raises: + ValueError: As ``_api_url``. SpiralDBSignInError: If spiral-sdk would have to ask a person to sign in. ImportError: If spiral-sdk is not installed, or another package provides the ``spiral`` module (``pyspiral``, which must not be installed beside it). @@ -276,7 +292,112 @@ def _new_client(overrides: Mapping[str, str] | None) -> Any: 'install "orcapod[spiraldb]"' ) from exc require_sign_in() - return client_class(api_url=api_url) + return api_url, client_class + + +class _SharedClient: + """One SDK client, used by every connector of one address and sign-in (ITL-1457). + + Connectors hold it, and the registry of clients does not: it is released when the + last connector that uses it is closed. + + Attributes: + sdk: spiral-sdk's client. + pid: The process that made it. + health: Whether a call of it failed. + """ + + def __init__(self, sdk: Any) -> None: + """Hold a client made in this process.""" + self.sdk = sdk + self.pid = os.getpid() + self.health = _Health() + self._schemas: dict[tuple[str, str], SchemaTable] = {} + self._lock = Lock() + + def schema_table(self, project_id: str, dataset: str) -> SchemaTable: + """Return the schema table of a dataset: one object, whose rows every connector + on this client uses.""" + sdk, health = self.sdk, self.health + with self._lock: + return self._schemas.setdefault( + (project_id, dataset), + SchemaTable( + project_id, + dataset, + lambda: _open_keyed_table( + sdk, project_id, dataset, SCHEMA_TABLE, health + ), + lambda doing: _service_call( + f"{doing} of {project_id}/{dataset}", health + ), + ), + ) + + +_clients: WeakValueDictionary[Any, _SharedClient] = WeakValueDictionary() +_clients_lock = Lock() # held for the registry's own operations only + + +def _forget_clients() -> None: + """In a forked child: leave the parent's clients, and a lock a thread of it held.""" + global _clients, _clients_lock + _clients = WeakValueDictionary() + _clients_lock = Lock() + + +if hasattr(os, "register_at_fork"): + os.register_at_fork(after_in_child=_forget_clients) + + +def _sign_in_key() -> Any | None: + """Return what decides who a new client signs in as, without reading a credential. + + It is a digest of the whole environment (the SDK documents ``SPIRAL_*``, and takes + more: proxies, a home folder, a CI's identity token) and the state of the saved + login's file. ``None`` when it cannot be told: the client is then not shared. + """ + try: + environ = dict(os.environ) + path = saved_login_path(environ) + digest = hashlib.sha256(repr(sorted(environ.items())).encode()).hexdigest() + except (KeyError, RuntimeError, UnicodeError): + return None # changed while it was read, or no home folder + try: + found = path.stat() + state = (found.st_dev, found.st_ino, found.st_size) + state = (*state, found.st_mtime_ns, found.st_ctime_ns) + except OSError: + state = None + return digest, str(path), state + + +def _client_for(overrides: Mapping[str, str] | None) -> _SharedClient: + """Return this process's client of one address and sign-in, made on first use. + + Connectors built at the same time may each make one; they all use the first that was + made. No lock is held while a client signs in. + + Raises: + ValueError: As ``_client_options``, as are ``ImportError`` and + ``SpiralDBSignInError``. + """ + api_url, client_class = _client_options(overrides) + sign_in = _sign_in_key() + key = (os.getpid(), client_class, api_url, sign_in) + with _clients_lock: + shared = None if sign_in is None else _clients.get(key) + if shared is not None and not shared.health.failed: + return shared + made = _SharedClient(client_class(api_url=api_url)) + if sign_in is None or sign_in != _sign_in_key(): + return made # the sign-in changed meanwhile: whose it is is not known + with _clients_lock: + other = _clients.get(key) + if other is not None and not other.health.failed: + return other + _clients[key] = made + return made class _NoRedirect(urllib.request.HTTPRedirectHandler): @@ -636,17 +757,13 @@ def __init__( self._dataset = dataset self._overrides = overrides self._closed = False - self._client = _new_client(overrides) - self._pid = os.getpid() - # Shared by every connector on this client (``share_client``). + self._shared = _client_for(overrides) + self._client = self._shared.sdk + self._health = self._shared.health # kept: a read may end after close() + self._pid = self._shared.pid + # Shared by the connectors ``share_client`` gives. self._counts: dict[tuple[str, str], tuple[int, bool]] = {} - client = self._client - self._schemas = SchemaTable( - project_id, - dataset, - lambda: _open_keyed_table(client, project_id, dataset, SCHEMA_TABLE), - lambda doing: _service_call(f"{doing} of {project_id}/{dataset}"), - ) + self._schemas = self._shared.schema_table(project_id, dataset) def _require_open(self) -> None: """Raise RuntimeError if this connector has been closed.""" @@ -665,7 +782,7 @@ def _qualified(self, table_name: str) -> str: def _service_call(self, doing: str, table_name: str) -> Any: """Return a context that notes on a failing SDK call what it was doing.""" - return _service_call(f"{doing} {self._qualified(table_name)}") + return _service_call(f"{doing} {self._qualified(table_name)}", self._health) def _require_user_table(self, table_name: str) -> None: """Refuse the reserved name of the dataset's schema table.""" @@ -727,7 +844,11 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: ): raise SpiralDBTableNotFoundError(missing) table = _open_keyed_table( - self._client, self._project_id, self._dataset, table_name + self._client, + self._project_id, + self._dataset, + table_name, + self._health, ) if table is None: raise SpiralDBTableNotFoundError(missing) @@ -1052,7 +1173,9 @@ def close(self) -> None: """Close this connector and release its SDK client. Idempotent.""" if not self._closed: self._closed = True - # spiral-sdk's client has no close method. Drop the owning references. + # spiral-sdk's client has no close method. Drop the owning references: the + # client goes with the last connector that uses it. + del self._shared del self._client del self._schemas From c1e60b3fcbf42858adc5e7d3ba012c4989569392 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 18:13:15 -0800 Subject: [PATCH 2/6] perf(spiraldb): read a schema table once and check sources at the same time (ITL-1457) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1457.md | 10 + src/orcapod/core/sources/base.py | 10 + .../core/sources/spiraldb_table_source.py | 51 +- src/orcapod/databases/spiraldb_connector.py | 124 ++- .../databases/spiraldb_schema_table.py | 10 - src/orcapod/pipeline/node_run.py | 47 +- .../test_spiraldb_repeated_calls.py | 760 ++++++++++++++++++ 7 files changed, 979 insertions(+), 33 deletions(-) create mode 100644 changelog.d/ITL-1457.md create mode 100644 tests/test_databases/test_spiraldb_repeated_calls.py diff --git a/changelog.d/ITL-1457.md b/changelog.d/ITL-1457.md new file mode 100644 index 000000000..8c34389da --- /dev/null +++ b/changelog.d/ITL-1457.md @@ -0,0 +1,10 @@ +### Changed + +- SpiralDB sources repeat fewer service calls (ITL-1457). The sources of one process that + use one service address and one sign-in share an SDK client, and a dataset's schema table + is read once for all of them while its version has not moved. Its version is still checked + at every lookup that prepares a read, now at the same time as the table's own schema is + fetched, and the checks of neighbouring SpiralDB sources before a run are made at the same + time. Rows, order, hashes, refusals and warnings are unchanged. A changed environment or + saved login, or a client whose call failed, gives a new source a new client; closing a + source affects no other. diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 07221924c..6a9ad14f6 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -564,6 +564,16 @@ def check_for_new_data(self) -> bool: """ return False + def _begin_check(self) -> "Callable[[], Callable[[], bool]] | None": + """Return the part of ``check_for_new_data`` a run may do at the same time as that + of the sources beside it; ``None``, the default, for none. + + It changes nothing, warns of nothing and raises nothing a caller could see: it + returns the rest of the check, which does. The run calls that in its own thread, + in the sources' order, in place of ``check_for_new_data``. + """ + return None + # A source's rows are its own, not computed: a run() view says "all N rows". _RUN_ORIGIN: str = "held" diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 6312a677f..35f3fc947 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -8,9 +8,10 @@ Requires the ``spiraldb`` optional extra: ``pip install orcapod[spiraldb]``. Authentication is spiral-sdk's: ``SPIRAL_*`` environment variables, or the credentials ``spiral login`` saved. -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. +The SDK client is used by every source of one service address and sign-in in a process +(ITL-1457), and by its restricted copies. Use a new source after changing the SDK +endpoint, credentials or options: it signs in again. Use the source as a context manager +or call ``close()`` after its reads and jobs have finished; no other source is affected. Example:: @@ -42,8 +43,15 @@ import copy import dataclasses import os -from collections.abc import AsyncIterator, Collection, Generator, Iterator, Mapping -from concurrent.futures import ThreadPoolExecutor +from collections.abc import ( + AsyncIterator, + Callable, + Collection, + Generator, + Iterator, + Mapping, +) +from concurrent.futures import Future, ThreadPoolExecutor from threading import Lock from types import TracebackType from typing import Any, ClassVar, NamedTuple, TYPE_CHECKING @@ -778,11 +786,37 @@ def check_for_new_data(self) -> bool: ValueError: If the table was dropped and created again (another table id) or its columns changed: build the source again to read it. """ + return self._given_asof is None and self._pin_newer(self._lookup_table()) + + @override + def _begin_check(self) -> Callable[[], Callable[[], bool]] | None: + """Return the service calls of the check (ITL-1457), unless a subclass or a + caller replaced ``check_for_new_data``: what that does is not known.""" + if getattr(self.check_for_new_data, "__func__", None) is not _OWN_CHECK: + return None + return self._fetch_for_check + + def _fetch_for_check(self) -> Callable[[], bool]: + """Make the service calls of ``check_for_new_data`` and return the rest of it.""" + looked_up: Future[SpiralDBTable] = Future() if self._given_asof is not None: - return False + return lambda: False + try: + table = self._lookup_table() + table.fetch() + looked_up.set_result(table) + except BaseException as exc: + looked_up.set_exception(exc) + return lambda: self._pin_newer(looked_up.result()) + + def _pin_newer(self, table: SpiralDBTable) -> bool: + """Pin the version of ``table`` when it is newer (``check_for_new_data``). + + Args: + table: This source's table, looked up by this check. + """ # 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() schema = arrow_utils.drop_system_columns( table.arrow_schema().empty_table() ).schema @@ -1220,3 +1254,6 @@ def from_config( f"{source.table_id!r}: it is a different table." ) return source + + +_OWN_CHECK = SpiralDBTableSource.check_for_new_data diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 0c43a3392..f0945607f 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -25,11 +25,12 @@ import urllib.parse import urllib.request import warnings -from collections.abc import Iterator, Mapping +from collections.abc import Callable, Iterator, Mapping +from concurrent.futures import Future from contextlib import contextmanager from copy import copy -from threading import Lock, local -from typing import TYPE_CHECKING, Any, cast +from threading import Lock, Thread, local +from typing import TYPE_CHECKING, Any, NamedTuple, TypeVar, cast from weakref import WeakValueDictionary import pyarrow as pa @@ -43,6 +44,7 @@ ) from orcapod.databases.spiraldb_schema_table import ( SCHEMA_TABLE, + SchemaRow, SchemaTable, compared_columns, describe_difference, @@ -466,6 +468,53 @@ def _list_keyed_tables(client: Any, project_id: str, dataset: str) -> dict[str, token = following +_T = TypeVar("_T") + + +def _work(call: Callable[[], _T], future: Future[_T]) -> None: + """Give ``future`` the outcome of ``call``.""" + try: + future.set_result(call()) + except BaseException as exc: + future.set_exception(exc) + finally: + # A kept error holds this frame: without these it would hold itself. + del call, future + + +def _start(call: Callable[[], _T]) -> Future[_T]: + """Make a service call in a thread of its own. + + Only the call: what it finds is judged, and warned about, by the thread that waits for + it, so warning filters and the line a warning names do not depend on this. + + Args: + call: The call. + + Returns: + Its outcome. + """ + future: Future[_T] = Future() + try: + Thread(target=_work, args=(call, future), name="spiraldb-call").start() + except RuntimeError: # no thread can be started (the interpreter is ending) + _work(call, future) + return future + + +class _Fetched(NamedTuple): + """What the service says about how a snapshot is read, fetched but not judged. + + Attributes: + found: The snapshot's schema, as SpiralDB reports it. + rows: The rows of the dataset's schema table as stored now, seen after the + snapshot was opened. + """ + + found: Future[pa.Schema] + rows: Future[Mapping[str, SchemaRow] | None] + + def _literal(value: Any, arrow_type: pa.DataType) -> Any: """Return ``value`` as a scan literal of exactly ``arrow_type`` (the service refuses another type), or ``None`` when the SDK has no literal that filters as Orcapod does. @@ -540,15 +589,29 @@ def __init__( self._table = table self._table_name = table_name self._readings: dict[str, _Reading] = {} + self._fetched: _Fetched | None = None def _reading(self, table: Any) -> _Reading: """Return how a snapshot of this table is read, worked out once per version.""" 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 + fetched, self._fetched = ( + (self._fetched, None) if table is self._table else (None, self._fetched) + ) + self._readings[version] = self._connector._reading( # pyright: ignore[reportPrivateUsage] # owns the handle + table, self._table_name, fetched + ) return self._readings[version] + def fetch(self) -> None: + """Fetch what ``arrow_schema`` needs and judge nothing: no refusal and no warning. + + The next ``arrow_schema`` judges it, in its own thread. For a check that fetches + several tables at the same time. + """ + self._fetched = self._connector._fetch(self._table, self._table_name) # pyright: ignore[reportPrivateUsage] # owns the handle + @property def table_id(self) -> str: """SpiralDB's own id of the table (no round trip).""" @@ -855,7 +918,11 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: return SpiralDBTable(self, table, table_name) def _recorded_schema( - self, table: Any, table_name: str, found: pa.Schema + self, + table: Any, + table_name: str, + found: pa.Schema, + rows: Mapping[str, SchemaRow] | None, ) -> pa.Schema | None: """Return the schema recorded for an opened table; ``None``: as SpiralDB reports. @@ -863,12 +930,12 @@ def _recorded_schema( table: The SDK's handle. table_name: Plain table name. found: The handle's schema, as SpiralDB reports it. + rows: The rows of the dataset's schema table; ``None`` when it has none. Raises: - TableSchemaError: If the dataset's schema table cannot be read or is not - complete, or the table's row disagrees with the table. + TableSchemaError: If the table's row disagrees with the table. """ - row = self._schemas.row(str(table.resource_id)) + row = None if rows is None else rows.get(str(table.resource_id)) if row is None: _warn_unrecorded(self._qualified(table_name), str(table.resource_id)) return None @@ -890,18 +957,49 @@ def _recorded_schema( ) return row.schema - def _reading(self, table: Any, table_name: str) -> _Reading: + def _fetch(self, table: Any, table_name: str) -> _Fetched: + """Fetch how an opened snapshot of ``table_name`` is read, judging nothing. + + Both calls are made after the snapshot was opened, at the same time: no read uses + a schema whose schema table was not seen, complete, after its table was opened. + Both have ended when this returns. + """ + self._require_open() + rows = _start(self._schemas.rows) + found: Future[pa.Schema] = Future() + + def schema() -> pa.Schema: + with self._service_call("read the schema of", table_name): + return table.schema() + + try: + _work(schema, found) + finally: + _ = rows.exception() # waits + return _Fetched(found, rows) + + def _reading( + self, table: Any, table_name: str, fetched: _Fetched | None = None + ) -> _Reading: """Return how an opened snapshot of ``table_name`` is read. + Args: + table: The SDK's handle. + table_name: Plain table name. + fetched: What was fetched for it; fetched now when not given. + Raises: - TableSchemaError: If the table's row cannot be read or disagrees with it. + TableSchemaError: If the dataset's schema table cannot be read or is not + complete, or the table's row disagrees with the table. """ self._require_open() qualified = self._qualified(table_name) - with self._service_call("read the schema of", table_name): - found = table.schema() + if fetched is None: + fetched = self._fetch(table, table_name) + found = fetched.found.result() with _about_table(qualified): - recorded = self._recorded_schema(table, table_name, found) + rows = fetched.rows.result() + recorded = self._recorded_schema(table, table_name, found, rows) return _Reading(found, recorded, qualified) def get_pk_columns(self, table_name: str) -> list[str]: diff --git a/src/orcapod/databases/spiraldb_schema_table.py b/src/orcapod/databases/spiraldb_schema_table.py index 01e5731d1..9f1359271 100644 --- a/src/orcapod/databases/spiraldb_schema_table.py +++ b/src/orcapod/databases/spiraldb_schema_table.py @@ -434,16 +434,6 @@ def __init__( self._lock = Lock() self._kept: tuple[tuple[str, int], dict[str, SchemaRow]] | None = None - def row(self, table_id: str) -> SchemaRow | None: - """Return the row of ``table_id`` as stored now; ``None`` when the dataset has no - schema table, or a complete one without that table. - - Raises: - TableSchemaError: If the table cannot be read in full or is not complete. - """ - rows = self.rows() - return None if rows is None else rows.get(table_id) - def rows(self) -> Mapping[str, SchemaRow] | None: """Return every row by table id, as stored now; ``None`` when the dataset has no schema table. diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index b1799c170..7c7830184 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -14,8 +14,10 @@ from __future__ import annotations -from collections.abc import Iterable, Iterator, Mapping, Sequence +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass +from itertools import groupby from typing import TYPE_CHECKING, Any from orcapod.errors import OrcapodDatabaseError, OrcapodDatabaseWriteError @@ -206,6 +208,45 @@ def run_sources(streams: Iterable[Any]) -> list[Any]: return found +# The most sources whose checks fetch at the same time. +_CHECK_THREADS = 8 + + +def _checks(sources: Sequence[Any]) -> Iterator[tuple[Any, Callable[[], bool]]]: + """Yield each source with its check, in order (ITL-1457). + + Sources next to each other that offer the fetching part of their check + (``_begin_check``) do it at the same time; the rest of each check, which takes in + data, warns and raises, is the caller's to call, one after another. No such part is + moved before or after the check of a source that offers none: what that does is the + source's own. + + Args: + sources: The sources, in the order they are checked. + """ + for offers, group in groupby( + ((source, source._begin_check()) for source in sources), + key=lambda item: item[1] is not None, + ): + items = list(group) + if not offers or len(items) == 1: + for source, _ in items: + yield source, source.check_for_new_data + continue + with ThreadPoolExecutor( + min(_CHECK_THREADS, len(items)), thread_name_prefix="source-check" + ) as pool: + try: + fetched = [pool.submit(begin) for _, begin in items if begin] + except RuntimeError: # no thread can be started (the interpreter is ending) + fetched = [] + for index, (source, _) in enumerate(items): + yield ( + source, + fetched[index].result() if fetched else source.check_for_new_data, + ) + + def check_sources(streams: Iterable[Any]) -> tuple[str, ...]: """Ask each source feeding ``streams`` once whether its data changed (ITL-1102). @@ -229,9 +270,9 @@ def check_sources(streams: Iterable[Any]) -> tuple[str, ...]: from orcapod.utils.warning_utils import outside_orcapod_stacklevel, warn_at_frame unchecked: list[str] = [] - for source in run_sources(streams): + for source, check in _checks(run_sources(streams)): try: - source.check_for_new_data() + _ = check() except Exception as exc: name = source_name(source) unchecked.append(name) diff --git a/tests/test_databases/test_spiraldb_repeated_calls.py b/tests/test_databases/test_spiraldb_repeated_calls.py new file mode 100644 index 000000000..eb376c4d6 --- /dev/null +++ b/tests/test_databases/test_spiraldb_repeated_calls.py @@ -0,0 +1,760 @@ +"""What SpiralDB sources share, and what they may never share (ITL-1457), on the fake. + +One client per service address and sign-in, one state of a dataset's schema table per +client, and the checks before a run made at the same time. The results, refusals and +warnings are those of sources that share nothing. +""" + +from __future__ import annotations + +import collections +import gc +import os +import threading +import warnings +import weakref +from collections.abc import Callable, Iterator +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.databases import InMemoryArrowDatabase, SpiralDBConnector +from orcapod.databases import spiraldb_connector as connector_module +from orcapod.databases import spiraldb_schema_table as st +from orcapod.errors import ( + SourceCheckFailedWarning, + TableSchemaError, + UnrecordedTableSchemaWarning, +) +from orcapod.operators import SelectColumns +from orcapod.pipeline import node_run +from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.sources import DictSource, SpiralDBTableSource +from tests.test_databases import fake_spiral_sdk as fake + +_SCHEMA = pa.schema( + [ + pa.field("k", pa.int64(), False), + pa.field("j", pa.large_string(), False), + pa.field("x", pa.float64(), False), + pa.field("y", pa.large_string()), + ] +) +_TABLES = ("a", "b", "c") + + +def _rows(offset: int) -> pa.Table: + return pa.Table.from_pylist( + [ + {"k": i + offset, "j": f"j{i % 2}", "x": 0.5 * i, "y": None} + for i in range(4) + ], + schema=_SCHEMA, + ) + + +def _make(project: str, dataset: str) -> None: + made = fake.ExternalProject(project) + for offset, name in enumerate(_TABLES): + made.create_table( + f"{dataset}.{name}", key_schema=[_SCHEMA.field("k"), _SCHEMA.field("j")] + ).write(_rows(10 * offset)) + fake.migrate(project, dict.fromkeys(_TABLES, _SCHEMA), dataset) + + +@pytest.fixture() +def root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]: + """Two projects with two datasets of three tables each, and nothing shared yet.""" + monkeypatch.setattr(connector_module, "_warned_unrecorded", set()) + monkeypatch.setenv("SPIRAL_AUTH_FILE", str(tmp_path / "auth.json")) + with fake.install(tmp_path / "spiral"): + for project in ("p", "q"): + for dataset in ("default", "other"): + _make(project, dataset) + yield tmp_path + + +class _Calls: + """The SDK calls made, by kind, in order.""" + + def __init__(self) -> None: + """Start with none.""" + self.log: list[str] = [] + self.clients: list[weakref.ReferenceType[Any]] = [] + self.lock = threading.Lock() + + def add(self, what: str) -> None: + """Log a call.""" + with self.lock: + self.log.append(what) + + def take(self) -> dict[str, int]: + """Return the counts since the last time, and start again.""" + with self.lock: + counts = dict(collections.Counter(self.log)) + self.log.clear() + return counts + + +@pytest.fixture() +def calls(root: Path, monkeypatch: pytest.MonkeyPatch) -> _Calls: + """Every SDK call, logged.""" + made = _Calls() + init, opened = fake.FakeClient.__init__, fake.FakeClient.keyed_table + by_id = fake.FakeClient.keyed_table_by_id + schema, scan = fake.FakeKeyedTable.schema, fake.FakeKeyedTable.scan + + def is_schemas(table: Any) -> bool: + return table._table["name"] == st.SCHEMA_TABLE + + def new_init(self: Any, **given: Any) -> None: + made.add("client") + made.clients.append(weakref.ref(self)) + init(self, **given) + + def new_opened(self: Any, project: str, dataset: str, name: str, **given: Any): + made.add("open schemas" if name == st.SCHEMA_TABLE else "open") + return opened(self, project, dataset, name, **given) + + def new_by_id(self: Any, *args: Any, **given: Any): + made.add("open by id") + return by_id(self, *args, **given) + + def new_schema(self: Any): + if not is_schemas(self): + made.add("schema") + return schema(self) + + def new_scan(self: Any, *args: Any, **given: Any): + made.add("read schemas" if is_schemas(self) else "scan") + return scan(self, *args, **given) + + monkeypatch.setattr(fake.FakeClient, "__init__", new_init) + monkeypatch.setattr(fake.FakeClient, "keyed_table", new_opened) + monkeypatch.setattr(fake.FakeClient, "keyed_table_by_id", new_by_id) + monkeypatch.setattr(fake.FakeKeyedTable, "schema", new_schema) + monkeypatch.setattr(fake.FakeKeyedTable, "scan", new_scan) + return made + + +def _source( + name: str = "a", project: str = "p", dataset: str = "default", **given: Any +): + return SpiralDBTableSource( + project, name, dataset=dataset, tag_only_columns=True, **given + ) + + +def _ks(source: SpiralDBTableSource) -> list[Any]: + return source.as_table()["k"].to_pylist() + + +# ---------------------------------------------------------------------- the one client + + +def test_one_client_and_one_read_of_a_schema_table_serve_every_source( + calls: _Calls, +) -> None: + sources = [ + _source(n, p, d) for p in "pq" for d in ("default", "other") for n in "abc" + ] + assert calls.take() == { + "client": 1, + "open": 12, + "schema": 12, + "open schemas": 12, # checked at each lookup + "read schemas": 4, # read once per dataset + } + assert [_ks(s) for s in sources] == [ + [10 * i + j for j in range(4)] for _ in range(4) for i in range(3) + ] + + +def test_sharing_changes_no_result(root: Path) -> None: + """Sources that share everything and sources that share nothing are equal.""" + + def facts(source: SpiralDBTableSource) -> list[Any]: + return [ + source.source_id, + source.content_hash().to_string(), + source.pipeline_hash().to_string(), + source.output_schema(), + source.as_table(all_info=True), + [t.as_dict() for t, _ in source.iter_data()], + source.head(2).table, + source.row_count_estimate, + ] + + shared = [_source(n, d) for n, d in (("a", "p"), ("b", "p"), ("a", "q"))] + apart = [] + for name, project in (("a", "p"), ("b", "p"), ("a", "q")): + connector_module._forget_clients() # pyright: ignore[reportPrivateUsage] # so nothing is shared + apart.append(_source(name, project)) + assert [facts(s) for s in shared] == [facts(s) for s in apart] + + +def test_closing_a_source_breaks_no_other_and_the_last_releases_the_client( + calls: _Calls, +) -> None: + first, second = _source("a"), _source("b") + copy = first.where(j="j0") + first.close() + assert _ks(copy) == [0, 2] and _ks(second) == [10, 11, 12, 13] + with pytest.raises(RuntimeError, match="closed"): + first.as_table() + copy.close() + assert _ks(second) == [10, 11, 12, 13] + second.close() + gc.collect() + assert [c() for c in calls.clients] == [None] + assert _ks(_source("a")) == [0, 1, 2, 3] + assert len(calls.clients) == 2 + + +def test_a_scan_in_progress_survives_the_close_of_another_source(root: Path) -> None: + first, second = _source("a", batch_rows=1), _source("b") + rows = first.iter_data() + next(rows) + second.close() + assert len(list(rows)) == 3 + + +def test_a_failure_after_close_is_the_services_error( + root: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A read may go on after ``close``, and its errors are still noted.""" + source = _source("a") + batches = SpiralDBConnector("p").lookup_table("a") + connector = batches._connector # pyright: ignore[reportPrivateUsage] # closed below + started = threading.Event() + + def fail(*_args: Any, **_given: Any) -> Any: + connector.close() + started.set() + raise fake.SpiralError("status 500") + + monkeypatch.setattr(fake.FakeKeyedTable, "scan", fail) + with pytest.raises(fake.SpiralError, match="500") as raised: + list(batches.scan_batches()) + assert started.is_set() + assert raised.value.__notes__ == ["SpiralDB: could not read p/default/a"] + source.close() + + +@pytest.mark.parametrize( + "change", + [ + {"SPIRAL_CLIENT_ID": "work_other"}, + {"SPIRAL_PRIVATE_KEY": "other"}, + {"SPIRAL_TOKEN": "t"}, + {"SPIRAL_WORKLOAD_ID": "w"}, + {"SPIRAL_AUTH_FILE": "elsewhere"}, + {"HOME": "elsewhere"}, + {"ACTIONS_ID_TOKEN_REQUEST_URL": "u"}, + {"HTTPS_PROXY": "http://localhost:1"}, + ], + ids=lambda c: next(iter(c)), +) +def test_a_changed_environment_is_another_client( + calls: _Calls, monkeypatch: pytest.MonkeyPatch, change: dict[str, str] +) -> None: + first = _source("a") + for name, value in change.items(): + monkeypatch.setenv(name, value) + second = _source("a") + assert calls.take()["client"] == 2 + # The second read the schema table with its own sign-in. + assert _ks(first) == _ks(second) + + +def test_a_changed_saved_login_is_another_client(calls: _Calls, root: Path) -> None: + kept = [_source("a")] + login = root / "auth.json" + for write in ( + lambda: login.write_text("one"), + lambda: login.write_text("two"), # another account, the same size + lambda: login.replace(root / "away"), + ): + write() + kept.append(_source("a")) + kept.append(_source("b")) + # No login, the first, the second; then none again, which is the first client's state. + assert calls.take()["client"] == 3 + assert {tuple(_ks(s)) for s in kept} == { + (0, 1, 2, 3), + (10, 11, 12, 13), + } + + +def test_another_address_is_another_client(calls: _Calls) -> None: + kept = [ + _source("a", overrides=overrides) + for overrides in ( + None, + {"server.url": "https://one.example"}, + {"server.url": "https://two.example"}, + {"server.url": "https://one.example"}, + None, + ) + ] + assert calls.take()["client"] == 3 + assert {tuple(_ks(s)) for s in kept} == {(0, 1, 2, 3)} + + +def test_a_sign_in_that_changes_while_connecting_is_not_shared( + calls: _Calls, root: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + init = fake.FakeClient.__init__ + writes = iter("xy") + + def renewing(self: Any, **given: Any) -> None: + init(self, **given) + if (text := next(writes, None)) is not None: + (root / "auth.json").write_text(text * len(calls.clients)) + + monkeypatch.setattr(fake.FakeClient, "__init__", renewing) + kept = [_source("a") for _ in range(4)] + assert calls.take()["client"] == 3 # two unknown, then one that is shared + assert {tuple(_ks(s)) for s in kept} == {(0, 1, 2, 3)} + + +def test_an_unknown_sign_in_is_not_shared( + calls: _Calls, monkeypatch: pytest.MonkeyPatch +) -> None: + def no_home(_environ: Any) -> Path: + raise RuntimeError("no home folder") + + monkeypatch.setattr(connector_module, "saved_login_path", no_home) + kept = [_source("a"), _source("a")] + assert calls.take()["client"] == 2 + assert {tuple(_ks(s)) for s in kept} == {(0, 1, 2, 3)} + + +@pytest.mark.parametrize("failing", ["open", "schema", "scan"]) +def test_a_client_whose_call_failed_is_given_to_no_new_source( + calls: _Calls, monkeypatch: pytest.MonkeyPatch, failing: str +) -> None: + """An expired or ended sign-in: a new source signs in again, as it always did.""" + source = _source("a") + cls, name = { + "open": (fake.FakeClient, "keyed_table"), + "schema": (fake.FakeKeyedTable, "schema"), + "scan": (fake.FakeKeyedTable, "scan"), + }[failing] + with monkeypatch.context() as broken: + + def denied(*_args: Any, **_given: Any) -> Any: + raise fake.SpiralError("status 401") + + broken.setattr(cls, name, denied) + with pytest.raises(fake.SpiralError, match="401"): + source.as_table() + again = _source("b") + assert calls.take()["client"] == 2 + _ = _source("c") + assert "client" not in calls.take() + # What was built keeps its own client, and recovers with it. + assert _ks(source) == [0, 1, 2, 3] and _ks(again) == [10, 11, 12, 13] + + +def test_a_missing_table_is_no_failure_of_the_client(calls: _Calls) -> None: + kept = _source("a") + with pytest.raises(ValueError, match="not found"): + _source("absent") + _ = _source("b") + assert calls.take()["client"] == 1 + kept.close() + + +def test_a_failed_connection_is_raised_by_each_source( + calls: _Calls, monkeypatch: pytest.MonkeyPatch +) -> None: + def refuse(self: Any, **_given: Any) -> None: + raise fake.SpiralError("sign-in refused") + + with monkeypatch.context() as broken: + broken.setattr(fake.FakeClient, "__init__", refuse) + for _ in range(2): + with pytest.raises(fake.SpiralError, match="refused"): + _source("a") + assert _ks(_source("a")) == [0, 1, 2, 3] + + +def test_many_threads_on_first_use_end_with_one_client(calls: _Calls) -> None: + ready = threading.Barrier(16) + + def build(index: int) -> tuple[SpiralDBTableSource, list[Any]]: + ready.wait(30) + source = _source("abc"[index % 3]) + return source, _ks(source) + + with ThreadPoolExecutor(16) as pool: + built = list(pool.map(build, range(16))) + assert [ks for _, ks in built] == [ + [10 * (i % 3) + j for j in range(4)] for i in range(16) + ] + used = {id(s._connection._client) for s, _ in built if s._connection} # pyright: ignore[reportPrivateUsage] # which client each holds + assert len(used) == 1 + calls.take() + _ = _source("a") + assert "client" not in calls.take() + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="os.fork is POSIX") +def test_a_forked_child_makes_its_own_client_and_never_waits( + root: Path, +) -> None: + """The registry's lock may be held by a thread that the child does not have.""" + parent = _source("a") + taken, release = threading.Event(), threading.Event() + lock = connector_module._clients_lock # pyright: ignore[reportPrivateUsage] # the inherited lock is the subject + + def hold() -> None: + with lock: + taken.set() + release.wait(30) + + holder = threading.Thread(target=hold) + holder.start() + assert taken.wait(10) + try: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") # Python warns of a fork with threads + pid = os.fork() + if pid == 0: # the child: never returns to pytest + code = 3 + try: + import signal + + signal.alarm(20) + with pytest.raises(RuntimeError, match="after a fork"): + parent.as_table() + child = SpiralDBConnector("p") + same = child._client is parent._connection._client # pyright: ignore[reportPrivateUsage, reportOptionalMemberAccess] # must differ + code = int(same) + finally: + os._exit(code) + _, status = os.waitpid(pid, 0) + assert os.waitstatus_to_exitcode(status) == 0 + finally: + release.set() + holder.join(10) + assert _ks(parent) == [0, 1, 2, 3] + + +# ------------------------------------------------------------ the schema table's state + + +def _damage(project: str = "p", dataset: str = "default", **change: Any) -> None: + table = fake.FakeClient().keyed_table(project, dataset, st.SCHEMA_TABLE) + (marker,) = [ + r for r in table.scan().to_table().to_pylist() if r["table_id"] == st.MARKER_KEY + ] + table.append(pa.Table.from_pylist([{**marker, **change}], schema=st.ROW_SCHEMA)) + + +def test_every_source_refuses_a_schema_table_withdrawn_since(root: Path) -> None: + """At every read that opens a table, as without sharing; another dataset is read.""" + sources = [_source(n) for n in _TABLES] + other = [_source("a", "q"), _source("a", "p", "other")] + asof = _source("a", asof=sources[0]._asof) # pyright: ignore[reportPrivateUsage] # its version + copy = sources[0].where(j="j0") + marker = {"rows_digest": "withdrawn"} + kept = fake.FakeClient().keyed_table("p", "default", st.SCHEMA_TABLE) + kept = kept.scan().to_table() + _damage(**marker) + for source in (*sources, asof, copy): + for read in ( + source.as_table, + lambda source=source: list(source.iter_data()), + source.head, + lambda source=source: source.row_count_estimate, + ): + with pytest.raises(TableSchemaError, match="withdrawn"): + read() + assert [_ks(s) for s in other] == [[0, 1, 2, 3]] * 2 + with pytest.raises(TableSchemaError): + _source("a") + # Restored: every one of them reads again. + fake.FakeClient().keyed_table("p", "default", st.SCHEMA_TABLE).append(kept) + assert [_ks(s) for s in sources] == [ + [0, 1, 2, 3], + [10, 11, 12, 13], + [20, 21, 22, 23], + ] + assert _ks(copy) == [0, 2] + + +def test_a_changed_schema_table_is_read_again_once(calls: _Calls) -> None: + sources = [_source(n) for n in _TABLES] + calls.take() + made = fake.ExternalProject("p") + made.create_table("default.d", key_schema=[_SCHEMA.field("k")]).write( + _rows(0).drop_columns(["j"]) + ) + fake.migrate("p", {}) + calls.take() + for _ in range(2): + for source in sources: + assert len(_ks(source)) == 4 + counts = calls.take() + assert counts["read schemas"] == 1 and counts["open schemas"] == 6 + + +def test_the_schema_table_is_seen_after_the_open_and_before_any_scan( + calls: _Calls, +) -> None: + source = _source("a", max_rows=None) + for read in (source.as_table, source.head, lambda: source.row_count_estimate): + calls.take() + read() + log = calls.log + assert log[0] == "open" + assert set(log[1:3]) == {"schema", "open schemas"} + assert set(log[3:]) <= {"scan"} + + +def test_the_schema_table_and_the_tables_schema_are_fetched_at_the_same_time( + root: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + both = threading.Barrier(2) + opened, schema = fake.FakeClient.keyed_table, fake.FakeKeyedTable.schema + + def new_opened(self: Any, project: str, dataset: str, name: str, **given: Any): + if name == st.SCHEMA_TABLE: + both.wait(10) + return opened(self, project, dataset, name, **given) + + def new_schema(self: Any): + if self._table["name"] != st.SCHEMA_TABLE: + both.wait(10) + return schema(self) + + monkeypatch.setattr(fake.FakeClient, "keyed_table", new_opened) + monkeypatch.setattr(fake.FakeKeyedTable, "schema", new_schema) + assert _ks(_source("a")) == [0, 1, 2, 3] + + +def test_the_tables_own_error_comes_before_the_schema_tables( + root: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + source = _source("a") + _damage(table_count=9) + schema = fake.FakeKeyedTable.schema + + def new_schema(self: Any): + if self._table["name"] != st.SCHEMA_TABLE: + raise fake.SpiralError("status 503") + return schema(self) + + with monkeypatch.context() as broken: + broken.setattr(fake.FakeKeyedTable, "schema", new_schema) + with pytest.raises(fake.SpiralError, match="503") as raised: + source.as_table() + assert raised.value.__notes__ == [ + "SpiralDB: could not read the schema of p/default/a" + ] + with pytest.raises(TableSchemaError, match="p/default/a"): + source.as_table() + + +def test_two_sign_ins_never_share_what_one_may_read( + root: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + allowed = _source("a") + assert _ks(allowed) == [0, 1, 2, 3] + original = fake.FakeClient.keyed_table + trusted = allowed._connection._client # pyright: ignore[reportPrivateUsage, reportOptionalMemberAccess] # the first sign-in's + + def opened(self: Any, project: str, dataset: str, name: str, **given: Any): + if self is not trusted and name == st.SCHEMA_TABLE: + raise fake.SpiralError("status 403") + return original(self, project, dataset, name, **given) + + monkeypatch.setattr(fake.FakeClient, "keyed_table", opened) + monkeypatch.setenv("SPIRAL_CLIENT_ID", "work_second") + with pytest.raises(fake.SpiralError, match="403"): + _source("a") + assert _ks(allowed) == [0, 1, 2, 3] + + +def test_a_warning_is_issued_by_the_reading_thread(root: Path) -> None: + """So its filters and the line it names are the caller's.""" + made = fake.ExternalProject("p") + made.create_table("default.raw", key_schema=[_SCHEMA.field("k")]).write( + _rows(0).drop_columns(["j"]) + ) + with pytest.warns(UnrecordedTableSchemaWarning, match="raw has no row") as seen: + _source("raw") + assert [w.filename for w in seen] == [__file__] + + +def test_reads_work_where_no_thread_can_be_started( + root: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + def no_thread(*_args: Any, **_given: Any) -> None: + raise RuntimeError("can't start new thread") + + monkeypatch.setattr(threading.Thread, "start", no_thread) + sources = [_source(n) for n in _TABLES] + assert _ks(sources[0]) == [0, 1, 2, 3] + assert node_run.check_sources(sources) == () + + +# --------------------------------------------------------------- the checks before a run + + +def _job(sources: list[Any]) -> PipelineJob: + job = PipelineJob(name="checks", database=InMemoryArrowDatabase()) + with job: + for index, source in enumerate(sources): + SelectColumns(["k", "j", "x"])(source, label=f"n{index}") + return job + + +def _write(name: str, k: int) -> None: + fake.ExternalProject("p").table(f"default.{name}").write(_rows(k).slice(0, 1)) + + +def test_neighbouring_checks_are_made_at_the_same_time( + root: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + sources = [_source(n) for n in _TABLES] + job = _job(sources) + job.run() + _write("b", 77) + together = threading.Barrier(3) + opened = fake.FakeClient.keyed_table + + def new_opened(self: Any, project: str, dataset: str, name: str, **given: Any): + if name in _TABLES: + together.wait(10) + return opened(self, project, dataset, name, **given) + + modified = [s.last_modified for s in sources] + with monkeypatch.context() as slow: + slow.setattr(fake.FakeClient, "keyed_table", new_opened) + assert node_run.check_sources(sources) == () + moved = [s.last_modified != m for s, m in zip(sources, modified, strict=True)] + assert moved == [False, True, False] + job.run() + assert 77 in job.nodes["n1"].as_table()["k"].to_pylist() + + +def test_failing_checks_warn_in_the_sources_order(root: Path) -> None: + sources = [_source(n) for n in _TABLES] + made = fake.ExternalProject("p") + for name in ("a", "c"): + made.drop_table(f"default.{name}") + _write("b", 77) + with pytest.warns(SourceCheckFailedWarning) as seen: + unchecked = node_run.check_sources(sources) + assert [w.filename for w in seen] == [__file__] * 2 + assert "default.a" in str(seen[0].message) and "not found" in str(seen[0].message) + assert "default.c" in str(seen[1].message) + assert len(unchecked) == 2 + assert 77 in _ks(sources[1]) + + +def test_a_warning_made_an_error_leaves_the_later_sources_unchecked( + root: Path, +) -> None: + sources = [_source(n) for n in _TABLES] + fake.ExternalProject("p").drop_table("default.b") + _write("a", 77) + _write("c", 78) + with warnings.catch_warnings(): + warnings.simplefilter("error", SourceCheckFailedWarning) + with pytest.raises(SourceCheckFailedWarning): + node_run.check_sources(sources) + assert 77 in _ks(sources[0]) and 78 not in _ks(sources[2]) + + +def test_another_sources_check_keeps_its_place(root: Path) -> None: + """What a check of another kind does is its own: no fetch moves across it.""" + + class Writes(DictSource): + """Writes to a SpiralDB table when it is checked.""" + + def check_for_new_data(self) -> bool: + """Write a row the next source must find.""" + _write("c", 91) + return False + + class Counts(SpiralDBTableSource): + """Replaces the check.""" + + checked = 0 + + def check_for_new_data(self) -> bool: + """Count, then check.""" + type(self).checked += 1 + return super().check_for_new_data() + + writes = Writes([{"k": 1, "x": 1.0}], tag_columns=["k"], tag_only_columns=True) + counts = Counts("p", "b", tag_only_columns=True) + sources = [_source("a"), _source("b"), counts, writes, _source("c"), _source("a")] + assert node_run.check_sources(sources) == () + assert Counts.checked == 1 + last = sources[4] + assert isinstance(last, SpiralDBTableSource) and 91 in _ks(last) + + +def test_a_source_with_a_given_version_makes_no_call(calls: _Calls) -> None: + sources = [_source("a"), _source("b", asof=1), _source("c")] + calls.take() + _write("b", 5) + calls.take() + assert node_run.check_sources(sources) == () + assert calls.take() == {"open": 2, "schema": 2, "open schemas": 2} + + +def test_a_closed_source_is_reported_like_any_failing_check(root: Path) -> None: + sources = [_source("a"), _source("b")] + sources[0].close() + with pytest.warns(SourceCheckFailedWarning, match="is closed"): + assert len(node_run.check_sources(sources)) == 1 + + +# ------------------------------------------------------------------------------ budgets + + +def test_the_calls_each_action_makes(calls: _Calls) -> None: + """A call more is a call repeated.""" + read = {"open": 1, "schema": 1, "open schemas": 1, "scan": 1} + sources = [_source(n) for n in _TABLES] + assert calls.take() == { + "client": 1, + "open": 3, + "schema": 3, + "open schemas": 3, + "read schemas": 1, + } + first = sources[0] + actions: dict[str, tuple[Callable[[], Any], dict[str, int]]] = { + "first preview": (lambda: first.head(2), read | {"scan": 2}), + "preview": (lambda: first.head(2), read), + "run, the cap's count": (first.run, read), + "run": (first.run, read), + "where": (lambda: first.where(j="j0"), {}), + "restricted read": (lambda: first.where(j="j0").as_table(), read), + "count": ( + lambda: first.row_count_estimate, + {"open": 1, "schema": 1, "open schemas": 1}, + ), + } + for name, (action, budget) in actions.items(): + action() + assert calls.take() == budget, name + job = _job(sources) + for runner, budget in ( + (None, {"open": 6, "schema": 6, "open schemas": 6, "scan": 5}), + (None, {"open": 3, "schema": 3, "open schemas": 3}), + (AsyncPipelineOrchestrator(), {"open": 3, "schema": 3, "open schemas": 3}), + ): + job.run(orchestrator=runner) + assert calls.take() == budget From 6b8f11dcb79e4cdbff8f66cd1e9ba2975120638b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 18:33:08 -0800 Subject: [PATCH 3/6] perf(spiraldb): read a source's pinned snapshot again through its opened handle (ITL-1457) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1457.md | 9 +- .../core/sources/spiraldb_table_source.py | 70 ++++- src/orcapod/databases/spiraldb_connector.py | 161 ++++++++-- .../sources/test_spiraldb_lookups.py | 24 +- .../test_spiraldb_repeated_calls.py | 295 +++++++++++++++++- 5 files changed, 493 insertions(+), 66 deletions(-) diff --git a/changelog.d/ITL-1457.md b/changelog.d/ITL-1457.md index 8c34389da..fbbdcd82e 100644 --- a/changelog.d/ITL-1457.md +++ b/changelog.d/ITL-1457.md @@ -5,6 +5,9 @@ is read once for all of them while its version has not moved. Its version is still checked at every lookup that prepares a read, now at the same time as the table's own schema is fetched, and the checks of neighbouring SpiralDB sources before a run are made at the same - time. Rows, order, hashes, refusals and warnings are unchanged. A changed environment or - saved login, or a client whose call failed, gives a new source a new client; closing a - source affects no other. + time. A changed environment or saved login, or a client whose call failed, gives a new + source a new client; closing a source affects no other. A source keeps the opened snapshot + of its pinned version: each read still opens the table by name and checks the schema table, + both before anything is scanned, and reads through the kept snapshot only when the name + leads to that same id and version. Rows, order, hashes, refusals and warnings are + unchanged. diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 35f3fc947..bf5a02844 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -73,6 +73,7 @@ from orcapod.core.streams.base import check_head_size from orcapod.core.streams.view import ViewStatus, StreamView from orcapod.databases.spiraldb_connector import ( + OpenedSnapshot, SpiralDBConnector, SpiralDBTable, SpiralDBTableNotFoundError, @@ -359,6 +360,7 @@ def __init__( self._overrides = None if overrides is None else dict(overrides) self._connection: SpiralDBConnector | None = None self._connection_lock = Lock() + self._kept: OpenedSnapshot | None = None # of the pinned version, or of none self._pid = os.getpid() self._closed = False self._condition = Condition() @@ -391,6 +393,7 @@ def __init__( # 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) + self._keep(table) # The default tags are the primary key, whatever identifies the rows. resolved_tags = ( @@ -722,6 +725,7 @@ def close(self) -> None: if self._connection is not None: self._connection.close() self._connection = None + self._kept = None def __enter__(self) -> SpiralDBTableSource: """Return this source for use as a context manager.""" @@ -741,9 +745,37 @@ 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) + def _keep(self, table: SpiralDBTable) -> None: + """Keep the snapshot of ``table`` for reading it again, if it is the pinned one. + + Args: + table: This source's table, its schema accepted. + """ + snapshot = table.opened_snapshot() + if ( + snapshot is not None + and self._asof is not None + and snapshot.id_and_version == (self._table_id, str(self._asof)) + ): + # No lock: a read that ends in a forked child must not wait for one. + self._kept = snapshot + if self._closed: + self._kept = None + + def _lookup_table(self, asof: int | None) -> SpiralDBTable: + """Resolve the name and check that it still identifies this source's table. + + Args: + asof: The version that is to be read. Its kept snapshot is read again if the + table still has that version; every refusal is judged afresh (ITL-1457). + """ + kept = self._kept + if kept is not None and kept.id_and_version != (self._table_id, str(asof)): + kept = None + table = self._connector().lookup_table(self._table_name, kept) + if kept is not None and table.version() != asof: + # Versions only move on: it cannot be read through again. + self._kept = None table_id = table.table_id if table_id != self._table_id: raise ValueError( @@ -763,7 +795,10 @@ def row_count_estimate(self) -> int: cost grows with the table. """ asof = self._asof - return self._lookup_table().row_count_estimate(asof=asof) + table = self._lookup_table(asof) + count = table.row_count_estimate(asof=asof) + self._keep(table) + return count @override def check_for_new_data(self) -> bool: @@ -786,7 +821,9 @@ def check_for_new_data(self) -> bool: ValueError: If the table was dropped and created again (another table id) or its columns changed: build the source again to read it. """ - return self._given_asof is None and self._pin_newer(self._lookup_table()) + return self._given_asof is None and self._pin_newer( + self._lookup_table(self._asof) + ) @override def _begin_check(self) -> Callable[[], Callable[[], bool]] | None: @@ -802,7 +839,7 @@ def _fetch_for_check(self) -> Callable[[], bool]: if self._given_asof is not None: return lambda: False try: - table = self._lookup_table() + table = self._lookup_table(self._asof) table.fetch() looked_up.set_result(table) except BaseException as exc: @@ -828,8 +865,10 @@ def _pin_newer(self, table: SpiralDBTable) -> bool: ) version = table.version() or None if version is None or (self._asof is not None and version <= self._asof): + self._keep(table) return False self._asof = version + self._keep(table) self._update_modified_time() return True @@ -871,10 +910,13 @@ def _batch_streams(self) -> Generator["ArrowTableStream", None, None]: key column holds a null. """ asof = self._asof - table = self._lookup_table() - yield from self._read_batches( - table, asof=asof, limit=self._limit, max_rows=self._max_rows - ) + table = self._lookup_table(asof) + try: + yield from self._read_batches( + table, asof=asof, limit=self._limit, max_rows=self._max_rows + ) + finally: + self._keep(table) def _read_batches( self, @@ -1046,12 +1088,13 @@ 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._lookup_table(asof) rows = self._whole_table( self._read_batches(table, asof=asof, limit=head_limit, max_rows=None), columns=columns, all_info=all_info, ) + self._keep(table) if rows.num_rows < head_limit or head_limit == limit: return _Head(rows, True, rows.num_rows, False) bound, total = self._bounded_count(n, table) @@ -1077,8 +1120,9 @@ def _bounded_count( 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 - total = handle.count_rows(asof=self._asof, at_most=bound + 1) + asof = self._asof + handle = self._lookup_table(asof) if table is None else table + total = handle.count_rows(asof=asof, at_most=bound + 1) return bound, (None if total > bound else total) def _head_note(self, head: "_Head", sorted_by_tags: bool = False) -> str: diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index f0945607f..3c1288196 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -25,7 +25,7 @@ import urllib.parse import urllib.request import warnings -from collections.abc import Callable, Iterator, Mapping +from collections.abc import Callable, Generator, Iterator, Mapping from concurrent.futures import Future from contextlib import contextmanager from copy import copy @@ -469,6 +469,7 @@ def _list_keyed_tables(client: Any, project_id: str, dataset: str) -> dict[str, _T = TypeVar("_T") +_Rows = Mapping[str, SchemaRow] | None # of a dataset's schema table def _work(call: Callable[[], _T], future: Future[_T]) -> None: @@ -512,7 +513,7 @@ class _Fetched(NamedTuple): """ found: Future[pa.Schema] - rows: Future[Mapping[str, SchemaRow] | None] + rows: Future[_Rows] def _literal(value: Any, arrow_type: pa.DataType) -> Any: @@ -570,6 +571,24 @@ def _equals(array: Any, value: Any) -> Any: return compute.fill_null(mask, False) +class OpenedSnapshot(NamedTuple): + """A table's snapshot that was opened and whose schema was fetched, kept for reading it + again (``SpiralDBConnector.lookup_table``, ITL-1457). A snapshot never changes. + + Attributes: + handle: The SDK's handle. + found: The snapshot's schema, as SpiralDB reports it. + """ + + handle: Any + found: pa.Schema + + @property + def id_and_version(self) -> tuple[str, str]: + """Which snapshot it is.""" + return str(self.handle.resource_id), str(self.handle.version_id) + + class SpiralDBTable: """One SpiralDB table, looked up once (``SpiralDBConnector.lookup_table``). @@ -590,6 +609,35 @@ def __init__( self._table_name = table_name self._readings: dict[str, _Reading] = {} self._fetched: _Fetched | None = None + # The handle this lookup opened, while a kept one is read in its place. + self._opened_now: Any | None = None + + def _read_kept(self, kept: OpenedSnapshot, rows: Future[_Rows]) -> None: + """Read the snapshot this lookup opened through a handle of it opened before. + + Args: + kept: The same snapshot. + rows: The schema table's rows, seen during this lookup. + """ + found: Future[pa.Schema] = Future() + found.set_result(kept.found) + self._fetched = _Fetched(found, rows) + self._opened_now, self._table = self._table, kept.handle + + def _leave_kept(self) -> bool: + """Go back from the kept handle to the one this lookup opened, as if none had been + kept; return whether there was one to leave.""" + if self._opened_now is None: + return False + self._table, self._opened_now = self._opened_now, None + self._fetched = None + self._readings.clear() + return True + + def opened_snapshot(self) -> OpenedSnapshot | None: + """Return this lookup's snapshot to keep, once its schema was accepted.""" + reading = self._readings.get(str(self._table.version_id)) + return None if reading is None else OpenedSnapshot(self._table, reading.found) def _reading(self, table: Any) -> _Reading: """Return how a snapshot of this table is read, worked out once per version.""" @@ -610,6 +658,8 @@ def fetch(self) -> None: The next ``arrow_schema`` judges it, in its own thread. For a check that fetches several tables at the same time. """ + if self._fetched is not None: + return self._fetched = self._connector._fetch(self._table, self._table_name) # pyright: ignore[reportPrivateUsage] # owns the handle @property @@ -653,8 +703,41 @@ def scan_batches( 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 + """Yield prepared Arrow batches from this resolved table in key order. + + Of a kept handle that fails before it gave a batch nothing was used: the snapshot + is then read through the handle this lookup opened, as if none had been kept. + """ + batches = self._scan(where=where, limit=limit, asof=asof) + if self._opened_now is None or self._at(asof) is not self._table: + yield from batches + return + # Judged outside the attempt: a refusal is a refusal. + _ = self._reading(self._table) + try: + first = next(batches, None) + except (TableSchemaError, NullInNonNullableColumnError): + raise + except Exception as exc: + if not self._leave_kept(): + raise + logger.debug("a kept SpiralDB snapshot could not be read again: %s", exc) + batches, first = self._scan(where=where, limit=limit, asof=asof), None + try: + if first is not None: + yield first + yield from batches + finally: + batches.close() + + def _scan( + self, + *, + where: Mapping[str, object] | None, + limit: int | None, + asof: int | None, + ) -> Generator[pa.RecordBatch, None, None]: + """Yield the batches of ``scan_batches``.""" table = self._at(asof) reading = self._reading(table) predicate = None @@ -671,7 +754,7 @@ def scan_batches( continue equals = sp.eq(sp.column(column), literal) predicate = equals if predicate is None else sp.and_(predicate, equals) - with connector._service_call("read", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle + with self._connector._service_call("read", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle reader = table.scan( filter=predicate, # The limit counts rows that match every condition. @@ -681,7 +764,7 @@ def scan_batches( left = limit try: while left is None or left > 0: - with connector._service_call("read", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle + with self._connector._service_call("read", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle batch = next(reader, None) if batch is None: return @@ -718,18 +801,32 @@ def count_rows(self, *, asof: int | None = None, at_most: int | None = None) -> known = (self.table_id, str(table.version_id)) counted, exact = counts.get(known, (0, False)) if not exact and (at_most is None or counted < at_most): - with connector._service_call("count the rows of", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle - reader = table.scan( - [self.key_columns[0]], limit=at_most, batch_rows=_SCAN_BATCH_ROWS - ).to_reader() - try: - counted = sum(batch.num_rows for batch in reader) - finally: - reader.close() + try: + counted = self._count_keys(table, at_most) + except Exception as exc: + if table is not self._table or not self._leave_kept(): + raise + logger.debug("a kept SpiralDB snapshot could not be counted: %s", exc) + counted = None + if counted is None: + table = self._table + _ = self._reading(table) + counted = self._count_keys(table, at_most) exact = at_most is None or counted < at_most counts[known] = (counted, exact) return counted if at_most is None else min(counted, at_most) + def _count_keys(self, table: Any, at_most: int | None) -> int: + """Count the keys of a snapshot, at most ``at_most`` of them.""" + with self._connector._service_call("count the rows of", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle + reader = table.scan( + [self.key_columns[0]], limit=at_most, batch_rows=_SCAN_BATCH_ROWS + ).to_reader() + try: + return sum(batch.num_rows for batch in reader) + finally: + reader.close() + def row_count_estimate(self, asof: int | None = None) -> int: """Return the table's row count, exact, by reading every key (``count_rows``).""" return self.count_rows(asof=asof) @@ -883,11 +980,20 @@ def get_table_names(self) -> list[str]: ) return sorted(name for name in listed.values() if name != SCHEMA_TABLE) - def lookup_table(self, table_name: str) -> SpiralDBTable: + def lookup_table( + self, table_name: str, kept: OpenedSnapshot | None = None + ) -> SpiralDBTable: """Look the table up once, for several items of its metadata (ITL-1350). + The table is opened by name, and its dataset's schema table is checked before + anything is read from it, also when a snapshot was kept. If the name leads to that + very snapshot (one id and one version), the returned table reads through its + handle, whose schema and plan need not be fetched again; if not, ``kept`` plays no + part. + Args: table_name: Plain table name (no dataset prefix). + kept: A snapshot opened before, by a connector on this client. Returns: The table: its id and key columns, and its schema and version when asked. @@ -906,16 +1012,25 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: or "." in table_name ): raise SpiralDBTableNotFoundError(missing) - table = _open_keyed_table( - self._client, - self._project_id, - self._dataset, - table_name, - self._health, - ) + rows = None if kept is None else _start(self._schemas.rows) + try: + table = _open_keyed_table( + self._client, + self._project_id, + self._dataset, + table_name, + self._health, + ) + finally: + if rows is not None: + _ = rows.exception() # waits if table is None: raise SpiralDBTableNotFoundError(missing) - return SpiralDBTable(self, table, table_name) + found = SpiralDBTable(self, table, table_name) + if kept is not None and rows is not None: + if kept.id_and_version == (found.table_id, str(table.version_id)): + found._read_kept(kept, rows) # pyright: ignore[reportPrivateUsage] # made here + return found def _recorded_schema( self, diff --git a/tests/test_core/sources/test_spiraldb_lookups.py b/tests/test_core/sources/test_spiraldb_lookups.py index 8c8e91e4e..911ce0e99 100644 --- a/tests/test_core/sources/test_spiraldb_lookups.py +++ b/tests/test_core/sources/test_spiraldb_lookups.py @@ -202,7 +202,8 @@ def test_each_check_looks_the_table_up_once( 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} + # And its schema is that of the kept snapshot (ITL-1457). + assert calls == {"lookup": 1, "open_schemas": 1} sync, async_ = _sync_and_async_rows(source) assert sorted(sync) == sorted(async_) == _expected_rows([0, 1, 2]) @@ -221,8 +222,9 @@ def test_a_check_still_finds_a_table_created_again( 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} + # Refused on the id, before the new table's schema or version is read. The schema table + # is checked at the same time as the open (ITL-1457), and what it said plays no part. + assert calls == {"lookup": 1, "open_schemas": 1, "read_schemas": 1} def test_missing_table_matches_source_diagnostic( @@ -261,7 +263,7 @@ 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} + assert calls == {"lookup": 1, "open_schemas": 1, "scan": 1} restricted.close() @@ -315,7 +317,7 @@ 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} | ( + assert calls == {"lookup": 1, "open_schemas": 1, "scan": 1} | ( {} if restricted or round_ else {"count": 1} ) @@ -327,7 +329,6 @@ async def collect() -> list[int]: assert calls == { "lookup": 1, "open_schemas": 1, - "schema": 1, "scan": 1, } | ({"count": 1} if restricted else {}) @@ -411,7 +412,8 @@ def test_each_read_refuses_a_replacement_before_scanning( calls.clear() with pytest.raises(ValueError, match="dropped and created again"): reads[mode]() - assert calls == {"lookup": 1} + # Nothing is scanned. The schema table is checked at the same time as the open. + assert calls == {"lookup": 1, "open_schemas": 1, "read_schemas": 1} def test_two_async_job_readers_use_the_restricted_sources_endpoint( @@ -452,14 +454,13 @@ def test_job_reuses_client_but_refreshes_table_each_run( assert calls == { "lookup": 2, "open_schemas": 2, - "schema": 2, "count": 1, "scan": 1, } 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( @@ -478,7 +479,7 @@ 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} + assert calls == {"lookup": 1, "open_schemas": 1, "read_schemas": 1} def test_freshness_pins_newer_version(calls: collections.Counter[str]) -> None: @@ -487,7 +488,8 @@ def test_freshness_pins_newer_version(calls: collections.Counter[str]) -> None: table.write(_rows(_ARRANGED["layout"], [3])) calls.clear() assert source.check_for_new_data() - assert calls == {"lookup": 1, "open_schemas": 1, "schema": 1} + # The kept snapshot is another version: the schema table is seen again, after the open. + assert calls == {"lookup": 1, "open_schemas": 2, "schema": 1} assert sorted(cast("list[int]", source.as_table()["k"].to_pylist())) == [0, 1, 2, 3] diff --git a/tests/test_databases/test_spiraldb_repeated_calls.py b/tests/test_databases/test_spiraldb_repeated_calls.py index eb376c4d6..2321fc277 100644 --- a/tests/test_databases/test_spiraldb_repeated_calls.py +++ b/tests/test_databases/test_spiraldb_repeated_calls.py @@ -7,13 +7,15 @@ from __future__ import annotations +import asyncio import collections import gc import os import threading +import types import warnings import weakref -from collections.abc import Callable, Iterator +from collections.abc import Callable, Generator, Iterator from concurrent.futures import ThreadPoolExecutor from pathlib import Path from typing import Any @@ -26,6 +28,7 @@ from orcapod.databases import spiraldb_connector as connector_module from orcapod.databases import spiraldb_schema_table as st from orcapod.errors import ( + NullInNonNullableColumnError, SourceCheckFailedWarning, TableSchemaError, UnrecordedTableSchemaWarning, @@ -334,7 +337,7 @@ def no_home(_environ: Any) -> Path: assert {tuple(_ks(s)) for s in kept} == {(0, 1, 2, 3)} -@pytest.mark.parametrize("failing", ["open", "schema", "scan"]) +@pytest.mark.parametrize("failing", ["open", "scan"]) def test_a_client_whose_call_failed_is_given_to_no_new_source( calls: _Calls, monkeypatch: pytest.MonkeyPatch, failing: str ) -> None: @@ -342,7 +345,6 @@ def test_a_client_whose_call_failed_is_given_to_no_new_source( source = _source("a") cls, name = { "open": (fake.FakeClient, "keyed_table"), - "schema": (fake.FakeKeyedTable, "schema"), "scan": (fake.FakeKeyedTable, "scan"), }[failing] with monkeypatch.context() as broken: @@ -505,17 +507,25 @@ def test_a_changed_schema_table_is_read_again_once(calls: _Calls) -> None: assert counts["read schemas"] == 1 and counts["open schemas"] == 6 +def _moved_on(source: SpiralDBTableSource) -> None: + """Write the source's table, and read once: no kept snapshot is its current one.""" + _write("a", 60) + _ = source.head() + + def test_the_schema_table_is_seen_after_the_open_and_before_any_scan( calls: _Calls, ) -> None: source = _source("a", max_rows=None) + _moved_on(source) for read in (source.as_table, source.head, lambda: source.row_count_estimate): calls.take() read() log = calls.log - assert log[0] == "open" - assert set(log[1:3]) == {"schema", "open schemas"} - assert set(log[3:]) <= {"scan"} + assert log[:2] == ["open", "open by id"] + first = log.index("scan") if "scan" in log else len(log) + assert set(log[2:first]) <= {"schema", "open schemas", "open by id"} + assert log.count("open schemas") == 1 def test_the_schema_table_and_the_tables_schema_are_fetched_at_the_same_time( @@ -536,13 +546,14 @@ def new_schema(self: Any): monkeypatch.setattr(fake.FakeClient, "keyed_table", new_opened) monkeypatch.setattr(fake.FakeKeyedTable, "schema", new_schema) - assert _ks(_source("a")) == [0, 1, 2, 3] + assert _source("a").table_id def test_the_tables_own_error_comes_before_the_schema_tables( root: Path, monkeypatch: pytest.MonkeyPatch ) -> None: source = _source("a") + _moved_on(source) _damage(table_count=9) schema = fake.FakeKeyedTable.schema @@ -710,7 +721,7 @@ def test_a_source_with_a_given_version_makes_no_call(calls: _Calls) -> None: _write("b", 5) calls.take() assert node_run.check_sources(sources) == () - assert calls.take() == {"open": 2, "schema": 2, "open schemas": 2} + assert calls.take() == {"open": 2, "open schemas": 2} def test_a_closed_source_is_reported_like_any_failing_check(root: Path) -> None: @@ -725,7 +736,7 @@ def test_a_closed_source_is_reported_like_any_failing_check(root: Path) -> None: def test_the_calls_each_action_makes(calls: _Calls) -> None: """A call more is a call repeated.""" - read = {"open": 1, "schema": 1, "open schemas": 1, "scan": 1} + read = {"open": 1, "open schemas": 1, "scan": 1} sources = [_source(n) for n in _TABLES] assert calls.take() == { "client": 1, @@ -742,19 +753,271 @@ def test_the_calls_each_action_makes(calls: _Calls) -> None: "run": (first.run, read), "where": (lambda: first.where(j="j0"), {}), "restricted read": (lambda: first.where(j="j0").as_table(), read), - "count": ( - lambda: first.row_count_estimate, - {"open": 1, "schema": 1, "open schemas": 1}, - ), + "count": (lambda: first.row_count_estimate, {"open": 1, "open schemas": 1}), } for name, (action, budget) in actions.items(): action() assert calls.take() == budget, name job = _job(sources) for runner, budget in ( - (None, {"open": 6, "schema": 6, "open schemas": 6, "scan": 5}), - (None, {"open": 3, "schema": 3, "open schemas": 3}), - (AsyncPipelineOrchestrator(), {"open": 3, "schema": 3, "open schemas": 3}), + (None, {"open": 6, "open schemas": 6, "scan": 5}), + (None, {"open": 3, "open schemas": 3}), + (AsyncPipelineOrchestrator(), {"open": 3, "open schemas": 3}), ): job.run(orchestrator=runner) assert calls.take() == budget + + +# ------------------------------------------------------------------- the kept snapshot + + +def _reads(source: SpiralDBTableSource) -> dict[str, Callable[[], Any]]: + async def collect() -> list[Any]: + return [t.as_dict()["k"] async for t, _ in source.async_iter_data()] + + return { + "table": lambda: source.as_table()["k"].to_pylist(), + "iter": lambda: [t.as_dict()["k"] for t, _ in source.iter_data()], + "async": lambda: sorted(asyncio.run(collect())), + "head": lambda: source.head(9).table["k"].to_pylist(), + "run": lambda: source.run().table["k"].to_pylist(), + "count": lambda: list(range(source.row_count_estimate)), + } + + +_READS = ["table", "iter", "async", "head", "run", "count"] +_CHANGES: dict[str, Callable[[], Any]] = { + "dropped": lambda: fake.ExternalProject("p").drop_table("default.a"), + "recreated": lambda: ( + fake.ExternalProject("p").drop_table("default.a"), + fake.ExternalProject("p") + .create_table("default.a", key_schema=[_SCHEMA.field("k"), _SCHEMA.field("j")]) + .write(_rows(0)), + ), + "withdrawn": lambda: _damage(rows_digest="withdrawn"), + "incomplete": lambda: _damage(table_count=9), + "re-recorded": lambda: fake.migrate("p", {"a": _other_flags()}), + "new rows": lambda: _write("a", 60), + "new column": lambda: ( + fake.ExternalProject("p") + .table("default.a") + .write(_rows(60).append_column("w", pa.array([1] * 4))) + ), + "nothing": lambda: None, +} + + +def _other_flags() -> pa.Schema: + return pa.schema([f.with_nullable(True) if f.name == "x" else f for f in _SCHEMA]) + + +def _outcome(read: Callable[[], Any]) -> tuple[str, str]: + """What a read gives or raises, without the parts that name this run's ids.""" + with warnings.catch_warnings(record=True) as seen: + warnings.simplefilter("always") + try: + result = repr(read()) + except Exception as exc: + result = f"{type(exc).__name__}: {exc} {getattr(exc, '__notes__', [])}" + return result, repr([str(w.message) for w in seen]) + + +@pytest.mark.parametrize("read", _READS) +@pytest.mark.parametrize("change", sorted(_CHANGES)) +@pytest.mark.parametrize("restricted", [False, True]) +def test_a_kept_snapshot_changes_no_outcome( + calls: _Calls, change: str, read: str, restricted: bool +) -> None: + """Two sources on one table, one of which keeps nothing: equal rows and refusals, + before and after a check.""" + keeping, plain = _source("a"), _source("a") + if restricted: + keeping, plain = keeping.where(j="j0"), plain.where(j="j0") + + def forget() -> None: + plain._kept = None # pyright: ignore[reportPrivateUsage] # keeps nothing + + for _ in range(2): + forget() + assert _outcome(_reads(keeping)[read]) == _outcome(_reads(plain)[read]) + _CHANGES[change]() + steps: list[Callable[[SpiralDBTableSource], Any]] = [ + lambda source: _reads(source)[read](), + lambda source: source.check_for_new_data(), + lambda source: _reads(source)[read](), + lambda source: source.where(k=1).as_table().to_pydict(), + ] + for step in steps: + forget() + expected = _outcome(lambda step=step: step(plain)) + calls.take() + assert _outcome(lambda step=step: step(keeping)) == expected + if change in ("dropped", "recreated", "withdrawn", "incomplete"): + assert "scan" not in calls.take() + + +def test_a_kept_snapshot_is_read_only_after_both_confirm(calls: _Calls) -> None: + source = _source("a", max_rows=None) + for read in _READS[:-1]: + calls.take() + _reads(source)[read]() + assert set(calls.log[:2]) == {"open", "open schemas"} + assert set(calls.log[2:]) == {"scan"} + + +def test_the_open_and_the_schema_table_are_checked_at_the_same_time( + root: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + source = _source("a") + both = threading.Barrier(2) + opened = fake.FakeClient.keyed_table + + def new_opened(self: Any, project: str, dataset: str, name: str, **given: Any): + both.wait(10) + return opened(self, project, dataset, name, **given) + + monkeypatch.setattr(fake.FakeClient, "keyed_table", new_opened) + assert _ks(source) == [0, 1, 2, 3] + + +def test_the_opens_error_comes_before_the_schema_tables( + root: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + source = _source("a") + + def denied(self: Any, project: str, dataset: str, name: str, **given: Any): + raise fake.SpiralError(f"status 403 {name}") + + monkeypatch.setattr(fake.FakeClient, "keyed_table", denied) + with pytest.raises(fake.SpiralError, match="403 a\n") as raised: + source.as_table() + assert raised.value.__notes__ == ["SpiralDB: could not open table p/default/a"] + + +@pytest.mark.parametrize("read", _READS) +@pytest.mark.parametrize("when", ["plan", "first batch"]) +def test_a_kept_snapshot_that_fails_is_read_afresh( + calls: _Calls, monkeypatch: pytest.MonkeyPatch, read: str, when: str +) -> None: + """A grant or credential that a handle holds may expire.""" + source, kept = _source("a"), [] + expected = _reads(_source("a"))[read]() + kept.append(source._kept.handle) # pyright: ignore[reportPrivateUsage, reportOptionalMemberAccess] # the handle that fails + scan = fake.FakeKeyedTable.scan + + class Expired: + """A scan whose reader fails at its first batch.""" + + def to_reader(self) -> Any: + """Return itself.""" + return self + + def __iter__(self) -> Any: + return self + + def __next__(self) -> Any: + raise fake.SpiralError("grant expired") + + def close(self) -> None: + """Nothing to close.""" + + def new_scan(self: Any, *args: Any, **given: Any) -> Any: + if self is not kept[0]: + return scan(self, *args, **given) + if when == "plan": + raise fake.SpiralError("grant expired") + return Expired() + + monkeypatch.setattr(fake.FakeKeyedTable, "scan", new_scan) + assert _reads(source)[read]() == expected + # The snapshot opened afresh is the one that is kept now. + assert source._kept is not None and source._kept.handle is not kept[0] # pyright: ignore[reportPrivateUsage] # the subject + calls.take() + assert _reads(source)[read]() == expected + assert "schema" not in calls.take() + + +def test_a_kept_snapshot_that_fails_later_fails_the_read( + root: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """No row may be given twice, or of two reads.""" + source = _source("a", max_rows=None) + scan = fake.FakeKeyedTable.scan + + def new_scan(self: Any, *args: Any, **given: Any) -> Any: + rows = scan(self, *args, **given).to_table() + + def batches() -> Iterator[Any]: + yield rows.slice(0, 2).to_batches()[0] + raise fake.SpiralError("status 500") + + reader = batches() + return types.SimpleNamespace(to_reader=lambda: reader) + + monkeypatch.setattr(fake.FakeKeyedTable, "scan", new_scan) + rows = source.iter_data() + assert [next(rows)[0].as_dict()["k"] for _ in range(2)] == [0, 1] + with pytest.raises(fake.SpiralError, match="500") as raised: + next(rows) + assert raised.value.__notes__ == ["SpiralDB: could not read p/default/a"] + + +def test_a_null_in_a_kept_snapshot_is_refused_and_not_read_afresh( + calls: _Calls, +) -> None: + source = _source("a", max_rows=None) + bad = _rows(0).to_pylist() + bad[0]["x"] = None + fake.ExternalProject("p").table("default.a").write( + pa.Table.from_pylist( + bad, schema=pa.schema([f.with_nullable(True) for f in _SCHEMA]) + ) + ) + assert source.check_for_new_data() + for _ in range(2): + calls.take() + with pytest.raises(NullInNonNullableColumnError, match="p/default/a"): + source.as_table() + assert calls.take()["scan"] == 1 + + +def test_a_check_keeps_the_version_it_pins(calls: _Calls) -> None: + source = _source("a") + copy = source.where(j="j0") + _write("a", 60) + assert source.check_for_new_data() + calls.take() + assert _ks(source) == [0, 1, 2, 3, 60] + assert "schema" not in calls.take() + # A copy pins its own version still. + assert _ks(copy) == [0, 2] + + +def test_a_closed_source_keeps_nothing(root: Path) -> None: + source = _source("a") + rows = source.iter_data() + _ = next(rows) + source.close() + assert source._kept is None # pyright: ignore[reportPrivateUsage] # the subject + assert len(list(rows)) == 3 + assert source._kept is None # pyright: ignore[reportPrivateUsage] # the subject + + +def test_threads_read_one_kept_snapshot(root: Path) -> None: + source = _source("a") + reads = [ + _reads(source.where(j="j0") if i % 2 else source)["table"] for i in range(32) + ] + with ThreadPoolExecutor(8) as pool: + found = list(pool.map(lambda read: read(), reads)) + assert found == [[0, 1, 2, 3], [0, 2]] * 16 + + +def test_an_early_stop_closes_the_reader(root: Path) -> None: + table = SpiralDBConnector("p").lookup_table("a") + _ = table.arrow_schema() + again = SpiralDBConnector("p").lookup_table("a", table.opened_snapshot()) + batches = again.scan_batches() + _ = next(batches) + assert isinstance(batches, Generator) + batches.close() From ddc153875cc21abcf423c20ee9c76d8c43becdca Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 19:10:55 -0800 Subject: [PATCH 4/6] refactor(spiraldb): keep a snapshot only, in the order calls were made before (ITL-1457) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1457.md | 16 +- src/orcapod/core/sources/base.py | 10 - .../core/sources/spiraldb_table_source.py | 78 +- src/orcapod/databases/spiraldb_connector.py | 329 ++------- .../databases/spiraldb_schema_table.py | 10 + src/orcapod/pipeline/node_run.py | 47 +- .../sources/test_spiraldb_lookups.py | 11 +- .../test_spiraldb_repeated_calls.py | 671 ++++-------------- 8 files changed, 214 insertions(+), 958 deletions(-) diff --git a/changelog.d/ITL-1457.md b/changelog.d/ITL-1457.md index fbbdcd82e..72f80d989 100644 --- a/changelog.d/ITL-1457.md +++ b/changelog.d/ITL-1457.md @@ -1,13 +1,7 @@ ### Changed -- SpiralDB sources repeat fewer service calls (ITL-1457). The sources of one process that - use one service address and one sign-in share an SDK client, and a dataset's schema table - is read once for all of them while its version has not moved. Its version is still checked - at every lookup that prepares a read, now at the same time as the table's own schema is - fetched, and the checks of neighbouring SpiralDB sources before a run are made at the same - time. A changed environment or saved login, or a client whose call failed, gives a new - source a new client; closing a source affects no other. A source keeps the opened snapshot - of its pinned version: each read still opens the table by name and checks the schema table, - both before anything is scanned, and reads through the kept snapshot only when the name - leads to that same id and version. Rows, order, hashes, refusals and warnings are - unchanged. +- A SpiralDB source keeps the opened snapshot of its pinned version, so that reading it + again does not fetch its schema and plan again (ITL-1457). Every read and check still opens + the table by name and then checks the dataset's schema table before anything is scanned, + and reads through the kept snapshot only when the name leads to that same id and version. + Rows, order, hashes, refusals and warnings are unchanged. diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 6a9ad14f6..07221924c 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -564,16 +564,6 @@ def check_for_new_data(self) -> bool: """ return False - def _begin_check(self) -> "Callable[[], Callable[[], bool]] | None": - """Return the part of ``check_for_new_data`` a run may do at the same time as that - of the sources beside it; ``None``, the default, for none. - - It changes nothing, warns of nothing and raises nothing a caller could see: it - returns the rest of the check, which does. The run calls that in its own thread, - in the sources' order, in place of ``check_for_new_data``. - """ - return None - # A source's rows are its own, not computed: a run() view says "all N rows". _RUN_ORIGIN: str = "held" diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index bf5a02844..3f5bfe918 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -8,10 +8,9 @@ Requires the ``spiraldb`` optional extra: ``pip install orcapod[spiraldb]``. Authentication is spiral-sdk's: ``SPIRAL_*`` environment variables, or the credentials ``spiral login`` saved. -The SDK client is used by every source of one service address and sign-in in a process -(ITL-1457), and by its restricted copies. Use a new source after changing the SDK -endpoint, credentials or options: it signs in again. Use the source as a context manager -or call ``close()`` after its reads and jobs have finished; no other source is affected. +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. Example:: @@ -43,15 +42,8 @@ import copy import dataclasses import os -from collections.abc import ( - AsyncIterator, - Callable, - Collection, - Generator, - Iterator, - Mapping, -) -from concurrent.futures import Future, ThreadPoolExecutor +from collections.abc import AsyncIterator, Collection, Generator, Iterator, Mapping +from concurrent.futures import ThreadPoolExecutor from threading import Lock from types import TracebackType from typing import Any, ClassVar, NamedTuple, TYPE_CHECKING @@ -762,20 +754,16 @@ def _keep(self, table: SpiralDBTable) -> None: if self._closed: self._kept = None - def _lookup_table(self, asof: int | None) -> SpiralDBTable: + def _lookup_table(self) -> SpiralDBTable: """Resolve the name and check that it still identifies this source's table. - Args: - asof: The version that is to be read. Its kept snapshot is read again if the - table still has that version; every refusal is judged afresh (ITL-1457). + A kept snapshot is read again if the name still leads to it; every refusal is + judged afresh (ITL-1457). """ kept = self._kept - if kept is not None and kept.id_and_version != (self._table_id, str(asof)): - kept = None table = self._connector().lookup_table(self._table_name, kept) - if kept is not None and table.version() != asof: - # Versions only move on: it cannot be read through again. - self._kept = None + if kept is not None and not table.reads(kept): + self._kept = None # versions only move on: it is not read again table_id = table.table_id if table_id != self._table_id: raise ValueError( @@ -795,7 +783,7 @@ def row_count_estimate(self) -> int: cost grows with the table. """ asof = self._asof - table = self._lookup_table(asof) + table = self._lookup_table() count = table.row_count_estimate(asof=asof) self._keep(table) return count @@ -821,39 +809,11 @@ def check_for_new_data(self) -> bool: ValueError: If the table was dropped and created again (another table id) or its columns changed: build the source again to read it. """ - return self._given_asof is None and self._pin_newer( - self._lookup_table(self._asof) - ) - - @override - def _begin_check(self) -> Callable[[], Callable[[], bool]] | None: - """Return the service calls of the check (ITL-1457), unless a subclass or a - caller replaced ``check_for_new_data``: what that does is not known.""" - if getattr(self.check_for_new_data, "__func__", None) is not _OWN_CHECK: - return None - return self._fetch_for_check - - def _fetch_for_check(self) -> Callable[[], bool]: - """Make the service calls of ``check_for_new_data`` and return the rest of it.""" - looked_up: Future[SpiralDBTable] = Future() if self._given_asof is not None: - return lambda: False - try: - table = self._lookup_table(self._asof) - table.fetch() - looked_up.set_result(table) - except BaseException as exc: - looked_up.set_exception(exc) - return lambda: self._pin_newer(looked_up.result()) - - def _pin_newer(self, table: SpiralDBTable) -> bool: - """Pin the version of ``table`` when it is newer (``check_for_new_data``). - - Args: - table: This source's table, looked up by this check. - """ + 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() schema = arrow_utils.drop_system_columns( table.arrow_schema().empty_table() ).schema @@ -910,7 +870,7 @@ def _batch_streams(self) -> Generator["ArrowTableStream", None, None]: key column holds a null. """ asof = self._asof - table = self._lookup_table(asof) + table = self._lookup_table() try: yield from self._read_batches( table, asof=asof, limit=self._limit, max_rows=self._max_rows @@ -1088,7 +1048,7 @@ def _head( limit = self._limit head_limit = n if limit is None else min(n, limit) asof = self._asof - table = self._lookup_table(asof) + table = self._lookup_table() rows = self._whole_table( self._read_batches(table, asof=asof, limit=head_limit, max_rows=None), columns=columns, @@ -1120,9 +1080,8 @@ def _bounded_count( return shown, None allowed = min(self._max_rows or DEFAULT_MAX_ROWS, DEFAULT_MAX_ROWS) bound = max(allowed, shown) - asof = self._asof - handle = self._lookup_table(asof) if table is None else table - total = handle.count_rows(asof=asof, at_most=bound + 1) + handle = self._lookup_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) def _head_note(self, head: "_Head", sorted_by_tags: bool = False) -> str: @@ -1298,6 +1257,3 @@ def from_config( f"{source.table_id!r}: it is a different table." ) return source - - -_OWN_CHECK = SpiralDBTableSource.check_for_new_data diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 3c1288196..683847643 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -16,7 +16,6 @@ from __future__ import annotations -import hashlib import json import logging import math @@ -25,13 +24,11 @@ import urllib.parse import urllib.request import warnings -from collections.abc import Callable, Generator, Iterator, Mapping -from concurrent.futures import Future +from collections.abc import Generator, Iterator, Mapping from contextlib import contextmanager from copy import copy -from threading import Lock, Thread, local -from typing import TYPE_CHECKING, Any, NamedTuple, TypeVar, cast -from weakref import WeakValueDictionary +from threading import local +from typing import TYPE_CHECKING, Any, NamedTuple, cast import pyarrow as pa import pyarrow.compute as pc @@ -44,12 +41,11 @@ ) from orcapod.databases.spiraldb_schema_table import ( SCHEMA_TABLE, - SchemaRow, SchemaTable, compared_columns, describe_difference, ) -from orcapod.databases.spiraldb_sign_in import require_sign_in, saved_login_path +from orcapod.databases.spiraldb_sign_in import require_sign_in from orcapod.errors import ( NullInNonNullableColumnError, SpiralDBWriteNotSupportedError, @@ -139,20 +135,13 @@ class SpiralDBTableNotFoundError(ValueError): """An exact table lookup found no matching table.""" -class _Health: - """Whether a call of one SDK client failed (``_SharedClient``).""" - - failed = False - - @contextmanager -def _service_call(doing: str, health: _Health | None = None) -> Iterator[None]: +def _service_call(doing: str) -> Iterator[None]: """Note on a failing SDK call what Orcapod was doing: SpiralDB's errors often hold a - status only. A client with a failed call is handed to no new connector. + status only. Args: doing: What the call does, and to what. - health: The client's, if it is shared. """ try: yield @@ -160,17 +149,11 @@ def _service_call(doing: str, health: _Health | None = None) -> Iterator[None]: # The SDK's own error class is not named here: it may not be installed. if not isinstance(exc, (TableSchemaError, NullInNonNullableColumnError)): exc.add_note(f"SpiralDB: could not {doing}") - if health is not None: - health.failed = True raise def _open_keyed_table( - client: Any, - project_id: str, - dataset: str, - name: str, - health: _Health | None = None, + client: Any, project_id: str, dataset: str, name: str ) -> Any | None: """Return the latest snapshot of a keyed table, or ``None`` if there is none. @@ -178,7 +161,7 @@ def _open_keyed_table( name means "no such table"; a missing project, a refused sign-in or a transport failure has another and is raised. """ - with _service_call(f"open table {project_id}/{dataset}/{name}", health): + with _service_call(f"open table {project_id}/{dataset}/{name}"): try: return client.keyed_table(project_id, dataset, name) except sp.SpiralError as exc: @@ -275,11 +258,10 @@ def _api_url(overrides: Mapping[str, str] | None) -> str | None: return api_url -def _client_options(overrides: Mapping[str, str] | None) -> tuple[str | None, Any]: - """Return the service address and the SDK's client class, a sign-in being present. +def _new_client(overrides: Mapping[str, str] | None) -> Any: + """Return a spiral-sdk client. Raises: - ValueError: As ``_api_url``. SpiralDBSignInError: If spiral-sdk would have to ask a person to sign in. ImportError: If spiral-sdk is not installed, or another package provides the ``spiral`` module (``pyspiral``, which must not be installed beside it). @@ -294,112 +276,7 @@ def _client_options(overrides: Mapping[str, str] | None) -> tuple[str | None, An 'install "orcapod[spiraldb]"' ) from exc require_sign_in() - return api_url, client_class - - -class _SharedClient: - """One SDK client, used by every connector of one address and sign-in (ITL-1457). - - Connectors hold it, and the registry of clients does not: it is released when the - last connector that uses it is closed. - - Attributes: - sdk: spiral-sdk's client. - pid: The process that made it. - health: Whether a call of it failed. - """ - - def __init__(self, sdk: Any) -> None: - """Hold a client made in this process.""" - self.sdk = sdk - self.pid = os.getpid() - self.health = _Health() - self._schemas: dict[tuple[str, str], SchemaTable] = {} - self._lock = Lock() - - def schema_table(self, project_id: str, dataset: str) -> SchemaTable: - """Return the schema table of a dataset: one object, whose rows every connector - on this client uses.""" - sdk, health = self.sdk, self.health - with self._lock: - return self._schemas.setdefault( - (project_id, dataset), - SchemaTable( - project_id, - dataset, - lambda: _open_keyed_table( - sdk, project_id, dataset, SCHEMA_TABLE, health - ), - lambda doing: _service_call( - f"{doing} of {project_id}/{dataset}", health - ), - ), - ) - - -_clients: WeakValueDictionary[Any, _SharedClient] = WeakValueDictionary() -_clients_lock = Lock() # held for the registry's own operations only - - -def _forget_clients() -> None: - """In a forked child: leave the parent's clients, and a lock a thread of it held.""" - global _clients, _clients_lock - _clients = WeakValueDictionary() - _clients_lock = Lock() - - -if hasattr(os, "register_at_fork"): - os.register_at_fork(after_in_child=_forget_clients) - - -def _sign_in_key() -> Any | None: - """Return what decides who a new client signs in as, without reading a credential. - - It is a digest of the whole environment (the SDK documents ``SPIRAL_*``, and takes - more: proxies, a home folder, a CI's identity token) and the state of the saved - login's file. ``None`` when it cannot be told: the client is then not shared. - """ - try: - environ = dict(os.environ) - path = saved_login_path(environ) - digest = hashlib.sha256(repr(sorted(environ.items())).encode()).hexdigest() - except (KeyError, RuntimeError, UnicodeError): - return None # changed while it was read, or no home folder - try: - found = path.stat() - state = (found.st_dev, found.st_ino, found.st_size) - state = (*state, found.st_mtime_ns, found.st_ctime_ns) - except OSError: - state = None - return digest, str(path), state - - -def _client_for(overrides: Mapping[str, str] | None) -> _SharedClient: - """Return this process's client of one address and sign-in, made on first use. - - Connectors built at the same time may each make one; they all use the first that was - made. No lock is held while a client signs in. - - Raises: - ValueError: As ``_client_options``, as are ``ImportError`` and - ``SpiralDBSignInError``. - """ - api_url, client_class = _client_options(overrides) - sign_in = _sign_in_key() - key = (os.getpid(), client_class, api_url, sign_in) - with _clients_lock: - shared = None if sign_in is None else _clients.get(key) - if shared is not None and not shared.health.failed: - return shared - made = _SharedClient(client_class(api_url=api_url)) - if sign_in is None or sign_in != _sign_in_key(): - return made # the sign-in changed meanwhile: whose it is is not known - with _clients_lock: - other = _clients.get(key) - if other is not None and not other.health.failed: - return other - _clients[key] = made - return made + return client_class(api_url=api_url) class _NoRedirect(urllib.request.HTTPRedirectHandler): @@ -468,54 +345,6 @@ def _list_keyed_tables(client: Any, project_id: str, dataset: str) -> dict[str, token = following -_T = TypeVar("_T") -_Rows = Mapping[str, SchemaRow] | None # of a dataset's schema table - - -def _work(call: Callable[[], _T], future: Future[_T]) -> None: - """Give ``future`` the outcome of ``call``.""" - try: - future.set_result(call()) - except BaseException as exc: - future.set_exception(exc) - finally: - # A kept error holds this frame: without these it would hold itself. - del call, future - - -def _start(call: Callable[[], _T]) -> Future[_T]: - """Make a service call in a thread of its own. - - Only the call: what it finds is judged, and warned about, by the thread that waits for - it, so warning filters and the line a warning names do not depend on this. - - Args: - call: The call. - - Returns: - Its outcome. - """ - future: Future[_T] = Future() - try: - Thread(target=_work, args=(call, future), name="spiraldb-call").start() - except RuntimeError: # no thread can be started (the interpreter is ending) - _work(call, future) - return future - - -class _Fetched(NamedTuple): - """What the service says about how a snapshot is read, fetched but not judged. - - Attributes: - found: The snapshot's schema, as SpiralDB reports it. - rows: The rows of the dataset's schema table as stored now, seen after the - snapshot was opened. - """ - - found: Future[pa.Schema] - rows: Future[_Rows] - - def _literal(value: Any, arrow_type: pa.DataType) -> Any: """Return ``value`` as a scan literal of exactly ``arrow_type`` (the service refuses another type), or ``None`` when the SDK has no literal that filters as Orcapod does. @@ -608,29 +437,24 @@ def __init__( self._table = table self._table_name = table_name self._readings: dict[str, _Reading] = {} - self._fetched: _Fetched | None = None - # The handle this lookup opened, while a kept one is read in its place. + # The handle this lookup opened, while ``_kept`` is read in its place. self._opened_now: Any | None = None + self._kept: OpenedSnapshot | None = None - def _read_kept(self, kept: OpenedSnapshot, rows: Future[_Rows]) -> None: - """Read the snapshot this lookup opened through a handle of it opened before. + def _read_kept(self, kept: OpenedSnapshot) -> None: + """Read the snapshot this lookup opened through a handle of it opened before.""" + self._opened_now, self._table, self._kept = self._table, kept.handle, kept - Args: - kept: The same snapshot. - rows: The schema table's rows, seen during this lookup. - """ - found: Future[pa.Schema] = Future() - found.set_result(kept.found) - self._fetched = _Fetched(found, rows) - self._opened_now, self._table = self._table, kept.handle + def reads(self, kept: OpenedSnapshot) -> bool: + """Whether this lookup reads through ``kept``.""" + return self._kept is kept def _leave_kept(self) -> bool: """Go back from the kept handle to the one this lookup opened, as if none had been kept; return whether there was one to leave.""" if self._opened_now is None: return False - self._table, self._opened_now = self._opened_now, None - self._fetched = None + self._table, self._opened_now, self._kept = self._opened_now, None, None self._readings.clear() return True @@ -644,24 +468,12 @@ def _reading(self, table: Any) -> _Reading: self._connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle version = str(table.version_id) if version not in self._readings: - fetched, self._fetched = ( - (self._fetched, None) if table is self._table else (None, self._fetched) - ) + kept = self._kept if table is self._table else None self._readings[version] = self._connector._reading( # pyright: ignore[reportPrivateUsage] # owns the handle - table, self._table_name, fetched + table, self._table_name, None if kept is None else kept.found ) return self._readings[version] - def fetch(self) -> None: - """Fetch what ``arrow_schema`` needs and judge nothing: no refusal and no warning. - - The next ``arrow_schema`` judges it, in its own thread. For a check that fetches - several tables at the same time. - """ - if self._fetched is not None: - return - self._fetched = self._connector._fetch(self._table, self._table_name) # pyright: ignore[reportPrivateUsage] # owns the handle - @property def table_id(self) -> str: """SpiralDB's own id of the table (no round trip).""" @@ -917,13 +729,17 @@ def __init__( self._dataset = dataset self._overrides = overrides self._closed = False - self._shared = _client_for(overrides) - self._client = self._shared.sdk - self._health = self._shared.health # kept: a read may end after close() - self._pid = self._shared.pid - # Shared by the connectors ``share_client`` gives. + self._client = _new_client(overrides) + self._pid = os.getpid() + # Shared by every connector on this client (``share_client``). self._counts: dict[tuple[str, str], tuple[int, bool]] = {} - self._schemas = self._shared.schema_table(project_id, dataset) + client = self._client + self._schemas = SchemaTable( + project_id, + dataset, + lambda: _open_keyed_table(client, project_id, dataset, SCHEMA_TABLE), + lambda doing: _service_call(f"{doing} of {project_id}/{dataset}"), + ) def _require_open(self) -> None: """Raise RuntimeError if this connector has been closed.""" @@ -942,7 +758,7 @@ def _qualified(self, table_name: str) -> str: def _service_call(self, doing: str, table_name: str) -> Any: """Return a context that notes on a failing SDK call what it was doing.""" - return _service_call(f"{doing} {self._qualified(table_name)}", self._health) + return _service_call(f"{doing} {self._qualified(table_name)}") def _require_user_table(self, table_name: str) -> None: """Refuse the reserved name of the dataset's schema table.""" @@ -1012,32 +828,21 @@ def lookup_table( or "." in table_name ): raise SpiralDBTableNotFoundError(missing) - rows = None if kept is None else _start(self._schemas.rows) - try: - table = _open_keyed_table( - self._client, - self._project_id, - self._dataset, - table_name, - self._health, - ) - finally: - if rows is not None: - _ = rows.exception() # waits + table = _open_keyed_table( + self._client, self._project_id, self._dataset, table_name + ) if table is None: raise SpiralDBTableNotFoundError(missing) found = SpiralDBTable(self, table, table_name) - if kept is not None and rows is not None: - if kept.id_and_version == (found.table_id, str(table.version_id)): - found._read_kept(kept, rows) # pyright: ignore[reportPrivateUsage] # made here + if kept is not None and kept.id_and_version == ( + found.table_id, + str(table.version_id), + ): + found._read_kept(kept) # pyright: ignore[reportPrivateUsage] # made here return found def _recorded_schema( - self, - table: Any, - table_name: str, - found: pa.Schema, - rows: Mapping[str, SchemaRow] | None, + self, table: Any, table_name: str, found: pa.Schema ) -> pa.Schema | None: """Return the schema recorded for an opened table; ``None``: as SpiralDB reports. @@ -1045,12 +850,12 @@ def _recorded_schema( table: The SDK's handle. table_name: Plain table name. found: The handle's schema, as SpiralDB reports it. - rows: The rows of the dataset's schema table; ``None`` when it has none. Raises: - TableSchemaError: If the table's row disagrees with the table. + TableSchemaError: If the dataset's schema table cannot be read or is not + complete, or the table's row disagrees with the table. """ - row = None if rows is None else rows.get(str(table.resource_id)) + row = self._schemas.row(str(table.resource_id)) if row is None: _warn_unrecorded(self._qualified(table_name), str(table.resource_id)) return None @@ -1072,49 +877,29 @@ def _recorded_schema( ) return row.schema - def _fetch(self, table: Any, table_name: str) -> _Fetched: - """Fetch how an opened snapshot of ``table_name`` is read, judging nothing. - - Both calls are made after the snapshot was opened, at the same time: no read uses - a schema whose schema table was not seen, complete, after its table was opened. - Both have ended when this returns. - """ - self._require_open() - rows = _start(self._schemas.rows) - found: Future[pa.Schema] = Future() - - def schema() -> pa.Schema: - with self._service_call("read the schema of", table_name): - return table.schema() - - try: - _work(schema, found) - finally: - _ = rows.exception() # waits - return _Fetched(found, rows) - def _reading( - self, table: Any, table_name: str, fetched: _Fetched | None = None + self, table: Any, table_name: str, found: pa.Schema | None = None ) -> _Reading: """Return how an opened snapshot of ``table_name`` is read. + The dataset's schema table is looked at last, after the table was opened and its + schema is known, and before anything is read: every time, also for a kept snapshot. + Args: table: The SDK's handle. table_name: Plain table name. - fetched: What was fetched for it; fetched now when not given. + found: The snapshot's schema, if it was fetched before; it never changes. Raises: - TableSchemaError: If the dataset's schema table cannot be read or is not - complete, or the table's row disagrees with the table. + TableSchemaError: If the table's row cannot be read or disagrees with it. """ self._require_open() qualified = self._qualified(table_name) - if fetched is None: - fetched = self._fetch(table, table_name) - found = fetched.found.result() + if found is None: + with self._service_call("read the schema of", table_name): + found = table.schema() with _about_table(qualified): - rows = fetched.rows.result() - recorded = self._recorded_schema(table, table_name, found, rows) + recorded = self._recorded_schema(table, table_name, found) return _Reading(found, recorded, qualified) def get_pk_columns(self, table_name: str) -> list[str]: @@ -1386,9 +1171,7 @@ def close(self) -> None: """Close this connector and release its SDK client. Idempotent.""" if not self._closed: self._closed = True - # spiral-sdk's client has no close method. Drop the owning references: the - # client goes with the last connector that uses it. - del self._shared + # spiral-sdk's client has no close method. Drop the owning references. del self._client del self._schemas diff --git a/src/orcapod/databases/spiraldb_schema_table.py b/src/orcapod/databases/spiraldb_schema_table.py index 9f1359271..01e5731d1 100644 --- a/src/orcapod/databases/spiraldb_schema_table.py +++ b/src/orcapod/databases/spiraldb_schema_table.py @@ -434,6 +434,16 @@ def __init__( self._lock = Lock() self._kept: tuple[tuple[str, int], dict[str, SchemaRow]] | None = None + def row(self, table_id: str) -> SchemaRow | None: + """Return the row of ``table_id`` as stored now; ``None`` when the dataset has no + schema table, or a complete one without that table. + + Raises: + TableSchemaError: If the table cannot be read in full or is not complete. + """ + rows = self.rows() + return None if rows is None else rows.get(table_id) + def rows(self) -> Mapping[str, SchemaRow] | None: """Return every row by table id, as stored now; ``None`` when the dataset has no schema table. diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 7c7830184..b1799c170 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -14,10 +14,8 @@ from __future__ import annotations -from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence -from concurrent.futures import ThreadPoolExecutor +from collections.abc import Iterable, Iterator, Mapping, Sequence from dataclasses import dataclass -from itertools import groupby from typing import TYPE_CHECKING, Any from orcapod.errors import OrcapodDatabaseError, OrcapodDatabaseWriteError @@ -208,45 +206,6 @@ def run_sources(streams: Iterable[Any]) -> list[Any]: return found -# The most sources whose checks fetch at the same time. -_CHECK_THREADS = 8 - - -def _checks(sources: Sequence[Any]) -> Iterator[tuple[Any, Callable[[], bool]]]: - """Yield each source with its check, in order (ITL-1457). - - Sources next to each other that offer the fetching part of their check - (``_begin_check``) do it at the same time; the rest of each check, which takes in - data, warns and raises, is the caller's to call, one after another. No such part is - moved before or after the check of a source that offers none: what that does is the - source's own. - - Args: - sources: The sources, in the order they are checked. - """ - for offers, group in groupby( - ((source, source._begin_check()) for source in sources), - key=lambda item: item[1] is not None, - ): - items = list(group) - if not offers or len(items) == 1: - for source, _ in items: - yield source, source.check_for_new_data - continue - with ThreadPoolExecutor( - min(_CHECK_THREADS, len(items)), thread_name_prefix="source-check" - ) as pool: - try: - fetched = [pool.submit(begin) for _, begin in items if begin] - except RuntimeError: # no thread can be started (the interpreter is ending) - fetched = [] - for index, (source, _) in enumerate(items): - yield ( - source, - fetched[index].result() if fetched else source.check_for_new_data, - ) - - def check_sources(streams: Iterable[Any]) -> tuple[str, ...]: """Ask each source feeding ``streams`` once whether its data changed (ITL-1102). @@ -270,9 +229,9 @@ def check_sources(streams: Iterable[Any]) -> tuple[str, ...]: from orcapod.utils.warning_utils import outside_orcapod_stacklevel, warn_at_frame unchecked: list[str] = [] - for source, check in _checks(run_sources(streams)): + for source in run_sources(streams): try: - _ = check() + source.check_for_new_data() except Exception as exc: name = source_name(source) unchecked.append(name) diff --git a/tests/test_core/sources/test_spiraldb_lookups.py b/tests/test_core/sources/test_spiraldb_lookups.py index 911ce0e99..255f16290 100644 --- a/tests/test_core/sources/test_spiraldb_lookups.py +++ b/tests/test_core/sources/test_spiraldb_lookups.py @@ -222,9 +222,8 @@ def test_a_check_still_finds_a_table_created_again( 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. The schema table - # is checked at the same time as the open (ITL-1457), and what it said plays no part. - assert calls == {"lookup": 1, "open_schemas": 1, "read_schemas": 1} + # Refused on the id, before the new table's schema or version is read. + assert calls == {"lookup": 1} def test_missing_table_matches_source_diagnostic( @@ -412,8 +411,7 @@ def test_each_read_refuses_a_replacement_before_scanning( calls.clear() with pytest.raises(ValueError, match="dropped and created again"): reads[mode]() - # Nothing is scanned. The schema table is checked at the same time as the open. - assert calls == {"lookup": 1, "open_schemas": 1, "read_schemas": 1} + assert calls == {"lookup": 1} def test_two_async_job_readers_use_the_restricted_sources_endpoint( @@ -488,8 +486,7 @@ def test_freshness_pins_newer_version(calls: collections.Counter[str]) -> None: table.write(_rows(_ARRANGED["layout"], [3])) calls.clear() assert source.check_for_new_data() - # The kept snapshot is another version: the schema table is seen again, after the open. - assert calls == {"lookup": 1, "open_schemas": 2, "schema": 1} + assert calls == {"lookup": 1, "open_schemas": 1, "schema": 1} assert sorted(cast("list[int]", source.as_table()["k"].to_pylist())) == [0, 1, 2, 3] diff --git a/tests/test_databases/test_spiraldb_repeated_calls.py b/tests/test_databases/test_spiraldb_repeated_calls.py index 2321fc277..56c913eda 100644 --- a/tests/test_databases/test_spiraldb_repeated_calls.py +++ b/tests/test_databases/test_spiraldb_repeated_calls.py @@ -1,15 +1,13 @@ -"""What SpiralDB sources share, and what they may never share (ITL-1457), on the fake. +"""What a SpiralDB source reads again without fetching it again (ITL-1457), on the fake. -One client per service address and sign-in, one state of a dataset's schema table per -client, and the checks before a run made at the same time. The results, refusals and -warnings are those of sources that share nothing. +A source keeps the opened snapshot of its pinned version. The rows, refusals, warnings and +what is looked at in which order are those of a source that keeps nothing. """ from __future__ import annotations import asyncio import collections -import gc import os import threading import types @@ -31,12 +29,11 @@ NullInNonNullableColumnError, SourceCheckFailedWarning, TableSchemaError, - UnrecordedTableSchemaWarning, ) from orcapod.operators import SelectColumns from orcapod.pipeline import node_run from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator -from orcapod.sources import DictSource, SpiralDBTableSource +from orcapod.sources import SpiralDBTableSource from tests.test_databases import fake_spiral_sdk as fake _SCHEMA = pa.schema( @@ -156,581 +153,180 @@ def _ks(source: SpiralDBTableSource) -> list[Any]: return source.as_table()["k"].to_pylist() -# ---------------------------------------------------------------------- the one client +# ------------------------------------------------------------ the schema table's state -def test_one_client_and_one_read_of_a_schema_table_serve_every_source( - calls: _Calls, -) -> None: - sources = [ - _source(n, p, d) for p in "pq" for d in ("default", "other") for n in "abc" - ] - assert calls.take() == { - "client": 1, - "open": 12, - "schema": 12, - "open schemas": 12, # checked at each lookup - "read schemas": 4, # read once per dataset - } - assert [_ks(s) for s in sources] == [ - [10 * i + j for j in range(4)] for _ in range(4) for i in range(3) +def _damage(project: str = "p", dataset: str = "default", **change: Any) -> None: + table = fake.FakeClient().keyed_table(project, dataset, st.SCHEMA_TABLE) + (marker,) = [ + r for r in table.scan().to_table().to_pylist() if r["table_id"] == st.MARKER_KEY ] + table.append(pa.Table.from_pylist([{**marker, **change}], schema=st.ROW_SCHEMA)) -def test_sharing_changes_no_result(root: Path) -> None: - """Sources that share everything and sources that share nothing are equal.""" - - def facts(source: SpiralDBTableSource) -> list[Any]: - return [ - source.source_id, - source.content_hash().to_string(), - source.pipeline_hash().to_string(), - source.output_schema(), - source.as_table(all_info=True), - [t.as_dict() for t, _ in source.iter_data()], - source.head(2).table, - source.row_count_estimate, - ] - - shared = [_source(n, d) for n, d in (("a", "p"), ("b", "p"), ("a", "q"))] - apart = [] - for name, project in (("a", "p"), ("b", "p"), ("a", "q")): - connector_module._forget_clients() # pyright: ignore[reportPrivateUsage] # so nothing is shared - apart.append(_source(name, project)) - assert [facts(s) for s in shared] == [facts(s) for s in apart] +def _moved_on(source: SpiralDBTableSource) -> None: + """Write the source's table, and read once: no kept snapshot is its current one.""" + _write("a", 60) + _ = source.head() -def test_closing_a_source_breaks_no_other_and_the_last_releases_the_client( - calls: _Calls, -) -> None: - first, second = _source("a"), _source("b") - copy = first.where(j="j0") - first.close() - assert _ks(copy) == [0, 2] and _ks(second) == [10, 11, 12, 13] - with pytest.raises(RuntimeError, match="closed"): - first.as_table() - copy.close() - assert _ks(second) == [10, 11, 12, 13] - second.close() - gc.collect() - assert [c() for c in calls.clients] == [None] - assert _ks(_source("a")) == [0, 1, 2, 3] - assert len(calls.clients) == 2 - - -def test_a_scan_in_progress_survives_the_close_of_another_source(root: Path) -> None: - first, second = _source("a", batch_rows=1), _source("b") - rows = first.iter_data() - next(rows) - second.close() - assert len(list(rows)) == 3 +def _write(name: str, k: int) -> None: + fake.ExternalProject("p").table(f"default.{name}").write(_rows(k).slice(0, 1)) -def test_a_failure_after_close_is_the_services_error( - root: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """A read may go on after ``close``, and its errors are still noted.""" - source = _source("a") - batches = SpiralDBConnector("p").lookup_table("a") - connector = batches._connector # pyright: ignore[reportPrivateUsage] # closed below - started = threading.Event() - - def fail(*_args: Any, **_given: Any) -> Any: - connector.close() - started.set() - raise fake.SpiralError("status 500") +def _job(sources: list[Any]) -> PipelineJob: + job = PipelineJob(name="checks", database=InMemoryArrowDatabase()) + with job: + for index, source in enumerate(sources): + SelectColumns(["k", "j", "x"])(source, label=f"n{index}") + return job - monkeypatch.setattr(fake.FakeKeyedTable, "scan", fail) - with pytest.raises(fake.SpiralError, match="500") as raised: - list(batches.scan_batches()) - assert started.is_set() - assert raised.value.__notes__ == ["SpiralDB: could not read p/default/a"] - source.close() +def _refuse_kinds() -> dict[str, Callable[[], None]]: + def incomplete() -> None: + fake.ExternalProject("p").drop_table(f"default.{st.SCHEMA_TABLE}") + fake.migrate("p", dict.fromkeys(_TABLES, _SCHEMA), complete=False) -@pytest.mark.parametrize( - "change", - [ - {"SPIRAL_CLIENT_ID": "work_other"}, - {"SPIRAL_PRIVATE_KEY": "other"}, - {"SPIRAL_TOKEN": "t"}, - {"SPIRAL_WORKLOAD_ID": "w"}, - {"SPIRAL_AUTH_FILE": "elsewhere"}, - {"HOME": "elsewhere"}, - {"ACTIONS_ID_TOKEN_REQUEST_URL": "u"}, - {"HTTPS_PROXY": "http://localhost:1"}, - ], - ids=lambda c: next(iter(c)), -) -def test_a_changed_environment_is_another_client( - calls: _Calls, monkeypatch: pytest.MonkeyPatch, change: dict[str, str] -) -> None: - first = _source("a") - for name, value in change.items(): - monkeypatch.setenv(name, value) - second = _source("a") - assert calls.take()["client"] == 2 - # The second read the schema table with its own sign-in. - assert _ks(first) == _ks(second) - - -def test_a_changed_saved_login_is_another_client(calls: _Calls, root: Path) -> None: - kept = [_source("a")] - login = root / "auth.json" - for write in ( - lambda: login.write_text("one"), - lambda: login.write_text("two"), # another account, the same size - lambda: login.replace(root / "away"), - ): - write() - kept.append(_source("a")) - kept.append(_source("b")) - # No login, the first, the second; then none again, which is the first client's state. - assert calls.take()["client"] == 3 - assert {tuple(_ks(s)) for s in kept} == { - (0, 1, 2, 3), - (10, 11, 12, 13), + return { + "withdrawn": lambda: _damage(rows_digest="withdrawn"), + "incomplete": incomplete, + "damaged": lambda: _damage(table_count=100), + "other scope": lambda: _damage(dataset="other"), } -def test_another_address_is_another_client(calls: _Calls) -> None: - kept = [ - _source("a", overrides=overrides) - for overrides in ( - None, - {"server.url": "https://one.example"}, - {"server.url": "https://two.example"}, - {"server.url": "https://one.example"}, - None, - ) - ] - assert calls.take()["client"] == 3 - assert {tuple(_ks(s)) for s in kept} == {(0, 1, 2, 3)} - - -def test_a_sign_in_that_changes_while_connecting_is_not_shared( - calls: _Calls, root: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - init = fake.FakeClient.__init__ - writes = iter("xy") - - def renewing(self: Any, **given: Any) -> None: - init(self, **given) - if (text := next(writes, None)) is not None: - (root / "auth.json").write_text(text * len(calls.clients)) - - monkeypatch.setattr(fake.FakeClient, "__init__", renewing) - kept = [_source("a") for _ in range(4)] - assert calls.take()["client"] == 3 # two unknown, then one that is shared - assert {tuple(_ks(s)) for s in kept} == {(0, 1, 2, 3)} - - -def test_an_unknown_sign_in_is_not_shared( - calls: _Calls, monkeypatch: pytest.MonkeyPatch -) -> None: - def no_home(_environ: Any) -> Path: - raise RuntimeError("no home folder") - - monkeypatch.setattr(connector_module, "saved_login_path", no_home) - kept = [_source("a"), _source("a")] - assert calls.take()["client"] == 2 - assert {tuple(_ks(s)) for s in kept} == {(0, 1, 2, 3)} - - -@pytest.mark.parametrize("failing", ["open", "scan"]) -def test_a_client_whose_call_failed_is_given_to_no_new_source( - calls: _Calls, monkeypatch: pytest.MonkeyPatch, failing: str +@pytest.mark.parametrize("kind", sorted(_refuse_kinds())) +@pytest.mark.parametrize("during", ["open", "schema"]) +def test_a_schema_table_changed_during_the_call_before_it_is_refused_by_that_read( + root: Path, monkeypatch: pytest.MonkeyPatch, kind: str, during: str ) -> None: - """An expired or ended sign-in: a new source signs in again, as it always did.""" + """Review of #553, finding 1: the schema table is looked at last.""" source = _source("a") - cls, name = { - "open": (fake.FakeClient, "keyed_table"), - "scan": (fake.FakeKeyedTable, "scan"), - }[failing] - with monkeypatch.context() as broken: - - def denied(*_args: Any, **_given: Any) -> Any: - raise fake.SpiralError("status 401") - - broken.setattr(cls, name, denied) - with pytest.raises(fake.SpiralError, match="401"): - source.as_table() - again = _source("b") - assert calls.take()["client"] == 2 - _ = _source("c") - assert "client" not in calls.take() - # What was built keeps its own client, and recovers with it. - assert _ks(source) == [0, 1, 2, 3] and _ks(again) == [10, 11, 12, 13] - - -def test_a_missing_table_is_no_failure_of_the_client(calls: _Calls) -> None: - kept = _source("a") - with pytest.raises(ValueError, match="not found"): - _source("absent") - _ = _source("b") - assert calls.take()["client"] == 1 - kept.close() + if during == "schema": + _moved_on(source) + changed: list[bool] = [] + def change() -> None: + if not changed: + changed.append(True) + _refuse_kinds()[kind]() -def test_a_failed_connection_is_raised_by_each_source( - calls: _Calls, monkeypatch: pytest.MonkeyPatch -) -> None: - def refuse(self: Any, **_given: Any) -> None: - raise fake.SpiralError("sign-in refused") - - with monkeypatch.context() as broken: - broken.setattr(fake.FakeClient, "__init__", refuse) - for _ in range(2): - with pytest.raises(fake.SpiralError, match="refused"): - _source("a") - assert _ks(_source("a")) == [0, 1, 2, 3] - - -def test_many_threads_on_first_use_end_with_one_client(calls: _Calls) -> None: - ready = threading.Barrier(16) - - def build(index: int) -> tuple[SpiralDBTableSource, list[Any]]: - ready.wait(30) - source = _source("abc"[index % 3]) - return source, _ks(source) - - with ThreadPoolExecutor(16) as pool: - built = list(pool.map(build, range(16))) - assert [ks for _, ks in built] == [ - [10 * (i % 3) + j for j in range(4)] for i in range(16) - ] - used = {id(s._connection._client) for s, _ in built if s._connection} # pyright: ignore[reportPrivateUsage] # which client each holds - assert len(used) == 1 - calls.take() - _ = _source("a") - assert "client" not in calls.take() - - -@pytest.mark.skipif(not hasattr(os, "fork"), reason="os.fork is POSIX") -def test_a_forked_child_makes_its_own_client_and_never_waits( - root: Path, -) -> None: - """The registry's lock may be held by a thread that the child does not have.""" - parent = _source("a") - taken, release = threading.Event(), threading.Event() - lock = connector_module._clients_lock # pyright: ignore[reportPrivateUsage] # the inherited lock is the subject - - def hold() -> None: - with lock: - taken.set() - release.wait(30) - - holder = threading.Thread(target=hold) - holder.start() - assert taken.wait(10) - try: - with warnings.catch_warnings(): - warnings.simplefilter("ignore") # Python warns of a fork with threads - pid = os.fork() - if pid == 0: # the child: never returns to pytest - code = 3 - try: - import signal - - signal.alarm(20) - with pytest.raises(RuntimeError, match="after a fork"): - parent.as_table() - child = SpiralDBConnector("p") - same = child._client is parent._connection._client # pyright: ignore[reportPrivateUsage, reportOptionalMemberAccess] # must differ - code = int(same) - finally: - os._exit(code) - _, status = os.waitpid(pid, 0) - assert os.waitstatus_to_exitcode(status) == 0 - finally: - release.set() - holder.join(10) - assert _ks(parent) == [0, 1, 2, 3] - - -# ------------------------------------------------------------ the schema table's state - + opened, schema = fake.FakeClient.keyed_table, fake.FakeKeyedTable.schema -def _damage(project: str = "p", dataset: str = "default", **change: Any) -> None: - table = fake.FakeClient().keyed_table(project, dataset, st.SCHEMA_TABLE) - (marker,) = [ - r for r in table.scan().to_table().to_pylist() if r["table_id"] == st.MARKER_KEY - ] - table.append(pa.Table.from_pylist([{**marker, **change}], schema=st.ROW_SCHEMA)) + def new_opened(self: Any, project: str, dataset: str, name: str, **given: Any): + table = opened(self, project, dataset, name, **given) + if name == "a" and during == "open": + change() + return table + def new_schema(self: Any): + found = schema(self) + if self._table["name"] == "a" and during == "schema": + change() + return found -def test_every_source_refuses_a_schema_table_withdrawn_since(root: Path) -> None: - """At every read that opens a table, as without sharing; another dataset is read.""" - sources = [_source(n) for n in _TABLES] - other = [_source("a", "q"), _source("a", "p", "other")] - asof = _source("a", asof=sources[0]._asof) # pyright: ignore[reportPrivateUsage] # its version - copy = sources[0].where(j="j0") - marker = {"rows_digest": "withdrawn"} - kept = fake.FakeClient().keyed_table("p", "default", st.SCHEMA_TABLE) - kept = kept.scan().to_table() - _damage(**marker) - for source in (*sources, asof, copy): - for read in ( - source.as_table, - lambda source=source: list(source.iter_data()), - source.head, - lambda source=source: source.row_count_estimate, - ): - with pytest.raises(TableSchemaError, match="withdrawn"): - read() - assert [_ks(s) for s in other] == [[0, 1, 2, 3]] * 2 + monkeypatch.setattr(fake.FakeClient, "keyed_table", new_opened) + monkeypatch.setattr(fake.FakeKeyedTable, "schema", new_schema) with pytest.raises(TableSchemaError): - _source("a") - # Restored: every one of them reads again. - fake.FakeClient().keyed_table("p", "default", st.SCHEMA_TABLE).append(kept) - assert [_ks(s) for s in sources] == [ - [0, 1, 2, 3], - [10, 11, 12, 13], - [20, 21, 22, 23], - ] - assert _ks(copy) == [0, 2] - - -def test_a_changed_schema_table_is_read_again_once(calls: _Calls) -> None: - sources = [_source(n) for n in _TABLES] - calls.take() - made = fake.ExternalProject("p") - made.create_table("default.d", key_schema=[_SCHEMA.field("k")]).write( - _rows(0).drop_columns(["j"]) - ) - fake.migrate("p", {}) - calls.take() - for _ in range(2): - for source in sources: - assert len(_ks(source)) == 4 - counts = calls.take() - assert counts["read schemas"] == 1 and counts["open schemas"] == 6 + source.as_table() + assert changed -def _moved_on(source: SpiralDBTableSource) -> None: - """Write the source's table, and read once: no kept snapshot is its current one.""" - _write("a", 60) - _ = source.head() +def test_each_source_has_its_own_sign_in( + calls: _Calls, monkeypatch: pytest.MonkeyPatch +) -> None: + """Review of #553, finding 2: a client is never taken for another account's.""" + init = fake.FakeClient.__init__ + def bind(self: Any, **given: Any) -> None: + init(self, **given) + self.account = os.environ["SPIRAL_TOKEN"] + if ( + len(calls.clients) == 1 + ): # another account while the first was made, and back + self.account = "b" -def test_the_schema_table_is_seen_after_the_open_and_before_any_scan( - calls: _Calls, -) -> None: - source = _source("a", max_rows=None) - _moved_on(source) - for read in (source.as_table, source.head, lambda: source.row_count_estimate): - calls.take() - read() - log = calls.log - assert log[:2] == ["open", "open by id"] - first = log.index("scan") if "scan" in log else len(log) - assert set(log[2:first]) <= {"schema", "open schemas", "open by id"} - assert log.count("open schemas") == 1 + monkeypatch.setattr(fake.FakeClient, "__init__", bind) + monkeypatch.setenv("SPIRAL_TOKEN", "a") + made = [SpiralDBConnector("p") for _ in range(3)] + assert [c._client.account for c in made] == ["b", "a", "a"] # pyright: ignore[reportPrivateUsage] # which each signed in as -def test_the_schema_table_and_the_tables_schema_are_fetched_at_the_same_time( +def test_checks_look_at_one_source_after_another( root: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - both = threading.Barrier(2) - opened, schema = fake.FakeClient.keyed_table, fake.FakeKeyedTable.schema - - def new_opened(self: Any, project: str, dataset: str, name: str, **given: Any): - if name == st.SCHEMA_TABLE: - both.wait(10) - return opened(self, project, dataset, name, **given) + """Review of #553, finding 3: a row written during one check is in the next.""" + a, b = _source("a"), _source("b") + _write("a", 60) # so that a's check fetches its schema + schema = fake.FakeKeyedTable.schema + wrote: list[bool] = [] def new_schema(self: Any): - if self._table["name"] != st.SCHEMA_TABLE: - both.wait(10) + if self._table["name"] == "a" and not wrote: + wrote.append(True) + _write("b", 99) return schema(self) - monkeypatch.setattr(fake.FakeClient, "keyed_table", new_opened) monkeypatch.setattr(fake.FakeKeyedTable, "schema", new_schema) - assert _source("a").table_id + assert node_run.check_sources([a, b]) == () + assert wrote and 99 in _ks(b) -def test_the_tables_own_error_comes_before_the_schema_tables( - root: Path, monkeypatch: pytest.MonkeyPatch +def test_a_failing_schema_is_raised_without_looking_at_the_schema_table( + calls: _Calls, monkeypatch: pytest.MonkeyPatch ) -> None: + """Review of #553, finding 4.""" source = _source("a") _moved_on(source) - _damage(table_count=9) - schema = fake.FakeKeyedTable.schema + calls.take() - def new_schema(self: Any): - if self._table["name"] != st.SCHEMA_TABLE: - raise fake.SpiralError("status 503") - return schema(self) + def failing(self: Any): + raise fake.SpiralError("status 503") - with monkeypatch.context() as broken: - broken.setattr(fake.FakeKeyedTable, "schema", new_schema) - with pytest.raises(fake.SpiralError, match="503") as raised: - source.as_table() - assert raised.value.__notes__ == [ - "SpiralDB: could not read the schema of p/default/a" - ] - with pytest.raises(TableSchemaError, match="p/default/a"): + monkeypatch.setattr(fake.FakeKeyedTable, "schema", failing) + with pytest.raises(fake.SpiralError, match="503"): source.as_table() + assert "open schemas" not in calls.take() -def test_two_sign_ins_never_share_what_one_may_read( - root: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - allowed = _source("a") - assert _ks(allowed) == [0, 1, 2, 3] - original = fake.FakeClient.keyed_table - trusted = allowed._connection._client # pyright: ignore[reportPrivateUsage, reportOptionalMemberAccess] # the first sign-in's - - def opened(self: Any, project: str, dataset: str, name: str, **given: Any): - if self is not trusted and name == st.SCHEMA_TABLE: - raise fake.SpiralError("status 403") - return original(self, project, dataset, name, **given) - - monkeypatch.setattr(fake.FakeClient, "keyed_table", opened) - monkeypatch.setenv("SPIRAL_CLIENT_ID", "work_second") - with pytest.raises(fake.SpiralError, match="403"): - _source("a") - assert _ks(allowed) == [0, 1, 2, 3] - - -def test_a_warning_is_issued_by_the_reading_thread(root: Path) -> None: - """So its filters and the line it names are the caller's.""" - made = fake.ExternalProject("p") - made.create_table("default.raw", key_schema=[_SCHEMA.field("k")]).write( - _rows(0).drop_columns(["j"]) - ) - with pytest.warns(UnrecordedTableSchemaWarning, match="raw has no row") as seen: - _source("raw") - assert [w.filename for w in seen] == [__file__] - - -def test_reads_work_where_no_thread_can_be_started( - root: Path, monkeypatch: pytest.MonkeyPatch +def test_a_failing_open_is_raised_without_looking_at_the_schema_table( + calls: _Calls, ) -> None: - def no_thread(*_args: Any, **_given: Any) -> None: - raise RuntimeError("can't start new thread") - - monkeypatch.setattr(threading.Thread, "start", no_thread) - sources = [_source(n) for n in _TABLES] - assert _ks(sources[0]) == [0, 1, 2, 3] - assert node_run.check_sources(sources) == () - - -# --------------------------------------------------------------- the checks before a run - - -def _job(sources: list[Any]) -> PipelineJob: - job = PipelineJob(name="checks", database=InMemoryArrowDatabase()) - with job: - for index, source in enumerate(sources): - SelectColumns(["k", "j", "x"])(source, label=f"n{index}") - return job - + source = _source("a") + fake.ExternalProject("p").drop_table("default.a") + calls.take() + with pytest.raises(ValueError, match="not found"): + source.as_table() + assert calls.take() == {"open": 1} -def _write(name: str, k: int) -> None: - fake.ExternalProject("p").table(f"default.{name}").write(_rows(k).slice(0, 1)) +def test_a_subclass_looks_its_table_up_in_the_calling_thread(root: Path) -> None: + """Review of #553, finding 5.""" + here = threading.get_ident() -def test_neighbouring_checks_are_made_at_the_same_time( - root: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - sources = [_source(n) for n in _TABLES] - job = _job(sources) - job.run() - _write("b", 77) - together = threading.Barrier(3) - opened = fake.FakeClient.keyed_table + class ThreadBound(SpiralDBTableSource): + """Its lookup works in one thread only.""" - def new_opened(self: Any, project: str, dataset: str, name: str, **given: Any): - if name in _TABLES: - together.wait(10) - return opened(self, project, dataset, name, **given) + def _lookup_table(self) -> Any: + assert threading.get_ident() == here + return super()._lookup_table() - modified = [s.last_modified for s in sources] - with monkeypatch.context() as slow: - slow.setattr(fake.FakeClient, "keyed_table", new_opened) - assert node_run.check_sources(sources) == () - moved = [s.last_modified != m for s, m in zip(sources, modified, strict=True)] - assert moved == [False, True, False] - job.run() - assert 77 in job.nodes["n1"].as_table()["k"].to_pylist() + bound = ThreadBound("p", "a", tag_only_columns=True) + assert node_run.check_sources([bound, _source("b")]) == () + assert _ks(bound) == [0, 1, 2, 3] def test_failing_checks_warn_in_the_sources_order(root: Path) -> None: sources = [_source(n) for n in _TABLES] - made = fake.ExternalProject("p") for name in ("a", "c"): - made.drop_table(f"default.{name}") + fake.ExternalProject("p").drop_table(f"default.{name}") _write("b", 77) with pytest.warns(SourceCheckFailedWarning) as seen: - unchecked = node_run.check_sources(sources) - assert [w.filename for w in seen] == [__file__] * 2 - assert "default.a" in str(seen[0].message) and "not found" in str(seen[0].message) - assert "default.c" in str(seen[1].message) - assert len(unchecked) == 2 + assert len(node_run.check_sources(sources)) == 2 + assert ["default.a" in str(w.message) for w in seen] == [True, False] assert 77 in _ks(sources[1]) -def test_a_warning_made_an_error_leaves_the_later_sources_unchecked( - root: Path, -) -> None: - sources = [_source(n) for n in _TABLES] - fake.ExternalProject("p").drop_table("default.b") - _write("a", 77) - _write("c", 78) - with warnings.catch_warnings(): - warnings.simplefilter("error", SourceCheckFailedWarning) - with pytest.raises(SourceCheckFailedWarning): - node_run.check_sources(sources) - assert 77 in _ks(sources[0]) and 78 not in _ks(sources[2]) - - -def test_another_sources_check_keeps_its_place(root: Path) -> None: - """What a check of another kind does is its own: no fetch moves across it.""" - - class Writes(DictSource): - """Writes to a SpiralDB table when it is checked.""" - - def check_for_new_data(self) -> bool: - """Write a row the next source must find.""" - _write("c", 91) - return False - - class Counts(SpiralDBTableSource): - """Replaces the check.""" - - checked = 0 - - def check_for_new_data(self) -> bool: - """Count, then check.""" - type(self).checked += 1 - return super().check_for_new_data() - - writes = Writes([{"k": 1, "x": 1.0}], tag_columns=["k"], tag_only_columns=True) - counts = Counts("p", "b", tag_only_columns=True) - sources = [_source("a"), _source("b"), counts, writes, _source("c"), _source("a")] - assert node_run.check_sources(sources) == () - assert Counts.checked == 1 - last = sources[4] - assert isinstance(last, SpiralDBTableSource) and 91 in _ks(last) - - -def test_a_source_with_a_given_version_makes_no_call(calls: _Calls) -> None: - sources = [_source("a"), _source("b", asof=1), _source("c")] - calls.take() - _write("b", 5) - calls.take() - assert node_run.check_sources(sources) == () - assert calls.take() == {"open": 2, "open schemas": 2} - - -def test_a_closed_source_is_reported_like_any_failing_check(root: Path) -> None: - sources = [_source("a"), _source("b")] - sources[0].close() - with pytest.warns(SourceCheckFailedWarning, match="is closed"): - assert len(node_run.check_sources(sources)) == 1 - - # ------------------------------------------------------------------------------ budgets @@ -739,11 +335,11 @@ def test_the_calls_each_action_makes(calls: _Calls) -> None: read = {"open": 1, "open schemas": 1, "scan": 1} sources = [_source(n) for n in _TABLES] assert calls.take() == { - "client": 1, + "client": 3, "open": 3, "schema": 3, "open schemas": 3, - "read schemas": 1, + "read schemas": 3, } first = sources[0] actions: dict[str, tuple[Callable[[], Any], dict[str, int]]] = { @@ -861,39 +457,10 @@ def test_a_kept_snapshot_is_read_only_after_both_confirm(calls: _Calls) -> None: for read in _READS[:-1]: calls.take() _reads(source)[read]() - assert set(calls.log[:2]) == {"open", "open schemas"} + assert calls.log[:2] == ["open", "open schemas"] assert set(calls.log[2:]) == {"scan"} -def test_the_open_and_the_schema_table_are_checked_at_the_same_time( - root: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - source = _source("a") - both = threading.Barrier(2) - opened = fake.FakeClient.keyed_table - - def new_opened(self: Any, project: str, dataset: str, name: str, **given: Any): - both.wait(10) - return opened(self, project, dataset, name, **given) - - monkeypatch.setattr(fake.FakeClient, "keyed_table", new_opened) - assert _ks(source) == [0, 1, 2, 3] - - -def test_the_opens_error_comes_before_the_schema_tables( - root: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - source = _source("a") - - def denied(self: Any, project: str, dataset: str, name: str, **given: Any): - raise fake.SpiralError(f"status 403 {name}") - - monkeypatch.setattr(fake.FakeClient, "keyed_table", denied) - with pytest.raises(fake.SpiralError, match="403 a\n") as raised: - source.as_table() - assert raised.value.__notes__ == ["SpiralDB: could not open table p/default/a"] - - @pytest.mark.parametrize("read", _READS) @pytest.mark.parametrize("when", ["plan", "first batch"]) def test_a_kept_snapshot_that_fails_is_read_afresh( From 169926a1cec3d373536fc280fe9f2b7842424bab Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 19:14:36 -0800 Subject: [PATCH 5/6] test(spiraldb): regression tests of the review of #553 (ITL-1457) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/spiraldb_connector.py | 9 +++++---- tests/test_databases/test_spiraldb_repeated_calls.py | 4 ++-- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 683847643..35e0bc462 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -878,7 +878,7 @@ def _recorded_schema( return row.schema def _reading( - self, table: Any, table_name: str, found: pa.Schema | None = None + self, table: Any, table_name: str, known: pa.Schema | None = None ) -> _Reading: """Return how an opened snapshot of ``table_name`` is read. @@ -888,16 +888,17 @@ def _reading( Args: table: The SDK's handle. table_name: Plain table name. - found: The snapshot's schema, if it was fetched before; it never changes. + known: The snapshot's schema, if it was fetched before; it never changes. Raises: TableSchemaError: If the table's row cannot be read or disagrees with it. """ self._require_open() qualified = self._qualified(table_name) - if found is None: + if known is None: with self._service_call("read the schema of", table_name): - found = table.schema() + known = table.schema() + found: pa.Schema = known with _about_table(qualified): recorded = self._recorded_schema(table, table_name, found) return _Reading(found, recorded, qualified) diff --git a/tests/test_databases/test_spiraldb_repeated_calls.py b/tests/test_databases/test_spiraldb_repeated_calls.py index 56c913eda..507fde4aa 100644 --- a/tests/test_databases/test_spiraldb_repeated_calls.py +++ b/tests/test_databases/test_spiraldb_repeated_calls.py @@ -156,8 +156,8 @@ def _ks(source: SpiralDBTableSource) -> list[Any]: # ------------------------------------------------------------ the schema table's state -def _damage(project: str = "p", dataset: str = "default", **change: Any) -> None: - table = fake.FakeClient().keyed_table(project, dataset, st.SCHEMA_TABLE) +def _damage(**change: Any) -> None: + table = fake.FakeClient().keyed_table("p", "default", st.SCHEMA_TABLE) (marker,) = [ r for r in table.scan().to_table().to_pylist() if r["table_id"] == st.MARKER_KEY ] From b586c6f8abbd403fd6f28dbde4f41f2f74121b17 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 19:16:55 -0800 Subject: [PATCH 6/6] fix(spiraldb): type a snapshot's known schema (ITL-1457) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/spiraldb_connector.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 35e0bc462..8b9e98870 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -895,10 +895,12 @@ def _reading( """ self._require_open() qualified = self._qualified(table_name) - if known is None: + found: pa.Schema + if known is not None: + found = known + else: with self._service_call("read the schema of", table_name): - known = table.schema() - found: pa.Schema = known + found = table.schema() with _about_table(qualified): recorded = self._recorded_schema(table, table_name, found) return _Reading(found, recorded, qualified)