diff --git a/changelog.d/ITL-1457.md b/changelog.d/ITL-1457.md new file mode 100644 index 000000000..47dac05b8 --- /dev/null +++ b/changelog.d/ITL-1457.md @@ -0,0 +1,16 @@ +### Changed + +- SpiralDB sources sign in and read a dataset's schema table less often (ITL-1457). The + sources of one process that use one service address and one sign-in share one spiral-sdk + client, and the rows of a dataset's schema table are kept for the version they were read + from: a new source of an already-read dataset opens the schema table to see its version + and reads it again only when the version moved. A changed environment or saved login, or + a client one of whose calls failed, gives the next new source a new client; closing a + source affects no other, and a forked process starts with none. A second source in a + process builds about 3x faster. Rows, order, hashes, source ids, refusals and warnings + are unchanged. +- `SpiralDBTableSource.as_table()` with `max_rows` no longer counts the table's keys first + (ITL-1457): it reads at most one row past the cap and raises the same + `SourceTooLargeError`. A read that hands rows on as it goes (`iter_data`, an async read) + still counts first. On a table over the cap the refusal now costs a read of `max_rows + 1` + rows instead of a read of one key column. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 64012062f..46c83a745 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -546,6 +546,13 @@ from the saved login. With neither, Orcapod raises `SpiralDBSignInError` instead the client start a sign-in. A saved login that has expired is not detected: the client may then print a sign-in prompt and wait. Stop it and run `uv run spiral login` again. +The SpiralDB sources of one process that use one service address and one sign-in share one +spiral-sdk client, and a dataset's schema table is read once for each of its versions: a new +source of an already-read dataset opens the schema table to see its version, and reads it +again only when the version moved. A changed environment or saved login, or a client one of +whose calls failed, gives the next new source a new client. Closing a source affects no other; +the client goes with the last source that uses it, and a forked process starts with none. + Orcapod only reads SpiralDB for now. Writing a SpiralDB table (`SpiralDBConnector`, or a job whose database is on one) raises `SpiralDBWriteNotSupportedError`; store a job's results in another database, such as `DeltaTableDatabase`. @@ -645,7 +652,9 @@ would return more raises `SourceTooLargeError`, which says so and gives the ways `limit=`, `where=`, or a larger `max_rows` (`max_rows=None` removes the cap). When nothing but `limit=` bounds the read, the source decides before it hands on any row, by counting the table's keys. SpiralDB keeps no row count of a keyed table, so the count is a read of one key -column; it stops one past the cap and is remembered for the version. The cap is there +column; it stops one past the cap and is remembered for the version. `as_table()` hands on no +row before it ends, so it does not count first: it reads at most one row past the cap and +raises the same error. The cap is there because a pipeline job keeps every row it processes in memory, about 5 KB per row for each node, so 100,000 rows cost about 0.5 GB per node. A table of millions of rows can be iterated with `max_rows=None`, but it cannot yet be run through a job on a laptop. diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index ca1f243e2..1a48e88a5 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:: @@ -980,7 +981,7 @@ def _key_tokens(self, table: "pa.Table") -> list[str]: ) from exc def _batch_streams( - self, *, with_source_info: bool = True + self, *, with_source_info: bool = True, count_first: bool = True ) -> Generator["ArrowTableStream", None, None]: """Scan the table once and yield its rows as streams of at most ``batch_rows`` rows. @@ -988,6 +989,7 @@ def _batch_streams( Args: with_source_info: As for ``_read_batches``. + count_first: As for ``_read_batches``. Raises: SourceTooLargeError: If the read would return, or returns, more than @@ -1003,6 +1005,7 @@ def _batch_streams( limit=self._limit, max_rows=self._max_rows, with_source_info=with_source_info, + count_first=count_first, ) def _read_batches( @@ -1013,6 +1016,7 @@ def _read_batches( limit: int | None, max_rows: int | None, with_source_info: bool = True, + count_first: bool = True, ) -> Generator["ArrowTableStream", None, None]: """Scan the table once, reading at most ``limit`` rows, in streams of ``batch_rows``. @@ -1026,6 +1030,11 @@ def _read_batches( with_source_info: Whether each stream holds its rows' source-info tokens. ``False`` only where the caller returns no source-info column and hashes no row (``_whole_table``): the streams then hold null tokens. + count_first: Whether an unrestricted read that ``limit`` does not keep under + ``max_rows`` counts the table's rows before it hands any row on. A + caller that hands no row on before the read ends (``as_table``) passes + ``False``: the scan then stops one row past ``max_rows`` and raises the + same error, with no separate count (ITL-1457). Raises: SourceTooLargeError: If the read would return, or returns, more than @@ -1033,26 +1042,30 @@ def _read_batches( ValueError: If a batch's columns differ from the source's schema, or a key column holds a null. """ - if ( - max_rows is not None - and self._condition.is_empty - and (limit is None or limit > max_rows) - ): - # Nothing but limit bounds the read, and the limit does not keep it - # under the cap: the table's row count decides, before any row is - # handed on (so no row reaches a function of a job that would fail). - # Counting stops one past the cap. - if table.count_rows(asof=asof, at_most=max_rows + 1) > max_rows: - bound = "" if limit is None else f" (limit={limit:,})" - raise self._too_large( - f"the table has more than {max_rows:,} rows{bound}" - ) + # Nothing but limit bounds the read, and the limit does not keep it under the + # cap: the table's row count decides. + cap = ( + max_rows + if self._condition.is_empty and (limit is None or limit > (max_rows or 0)) + else None + ) + bound = "" if limit is None else f" (limit={limit:,})" + too_many = f"the table has more than {cap or 0:,} rows{bound}" + scan_limit = limit + if cap is not None and count_first: + # Before any row is handed on (so no row reaches a function of a job that + # would fail). Counting stops one past the cap. + if table.count_rows(asof=asof, at_most=cap + 1) > cap: + raise self._too_large(too_many) + elif cap is not None: + # The rows are held until the read ends: read one past the cap and count. + scan_limit = cap + 1 seen = 0 # Keys must be unique across the whole read, not only within a slice. identifiers: set[str] = set() for batch in table.scan_batches( where=None if self._condition.is_empty else self._condition, - limit=limit, + limit=scan_limit, asof=asof, ): for start in range(0, max(batch.num_rows, 1), self._batch_rows): @@ -1072,7 +1085,11 @@ def _read_batches( ) seen += rows.num_rows if max_rows is not None and seen > max_rows: - raise self._too_large("the read returned more rows") + raise self._too_large( + too_many + if cap is not None and not count_first + else "the read returned more rows" + ) # Tokens first: they refuse a null key before it is copied into # a non-nullable column. tokens = self._key_tokens(rows) @@ -1133,7 +1150,10 @@ def as_table( """Scan the table and return its rows as one PyArrow table (all held in memory).""" config = ColumnConfig.handle_config(columns, all_info=all_info) return self._whole_table( - self._batch_streams(with_source_info=_reads_source_info(config)), + # The rows are held until the read ends: no separate count (ITL-1457). + self._batch_streams( + with_source_info=_reads_source_info(config), count_first=False + ), columns=columns, all_info=all_info, ) diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index db3a0b45c..7b53c6a47 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 @@ -41,11 +43,12 @@ ) from orcapod.databases.spiraldb_schema_table import ( SCHEMA_TABLE, + KeptRows, SchemaTable, 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, @@ -144,12 +147,14 @@ class SpiralDBTableNotFoundError(ValueError): @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. Args: doing: What the call does, and to what. + health: That of the client the call is made through: a failing call keeps the + client from new connectors (``_client_for``). """ try: yield @@ -157,11 +162,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. @@ -169,7 +180,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: @@ -266,10 +277,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_class(overrides: Mapping[str, str] | None) -> tuple[str | None, Any]: + """Return the service address and spiral-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). @@ -284,7 +296,111 @@ 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 _Health: + """Whether a call of one SDK client failed (``_SharedClient``).""" + + failed = False + + +class _SharedClient: + """One spiral-sdk client, used by every connector of one service address and sign-in + in a process (ITL-1457). + + Connectors hold it; the registry of clients does not, so it is released when the last + connector that uses it is closed. + + Attributes: + sdk: spiral-sdk's client. + health: Whether a call through it failed: it is then given to no new connector, + which signs in again. + counts: The row counts taken through it, by table id and version + (``SpiralDBTable.count_rows``): a version never changes. + """ + + def __init__(self, sdk: Any) -> None: + self.sdk = sdk + self.health = _Health() + self.counts: dict[tuple[str, str], tuple[int, bool]] = {} + + +# The clients of this process, and the rows of the schema tables it read. A forked child +# starts with neither (``_forget_in_child``): a client of the parent hangs there, and a +# lock a thread of the parent held stays locked. +_clients: WeakValueDictionary[Any, _SharedClient] = WeakValueDictionary() +_kept_rows: dict[tuple[str | None, str, str], KeptRows] = {} +_registry_lock = Lock() # held for the registries' own operations only + + +def _forget_in_child() -> None: + """In a forked child: leave the parent's clients, kept rows and lock.""" + global _clients, _kept_rows, _registry_lock + _clients = WeakValueDictionary() + _kept_rows = {} + _registry_lock = Lock() + + +if hasattr(os, "register_at_fork"): + os.register_at_fork(after_in_child=_forget_in_child) + + +def _sign_in_key() -> Any | None: + """Return what decides whom a new client signs in as, without keeping a credential. + + It is a digest of the whole environment (spiral-sdk documents ``SPIRAL_*`` and takes + more: proxies, a home folder) and the state of the saved login's file, whose content + is not read. ``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 service address and sign-in, made on first + use (ITL-1457). + + Connectors built at the same time may each make one; they all use the first that was + registered. No lock is held while a client is made. + + Raises: + ValueError: As ``_api_url``; ``ImportError`` and ``SpiralDBSignInError`` as + ``_client_class``. + """ + api_url, client_class = _client_class(overrides) + sign_in = _sign_in_key() + key = (os.getpid(), client_class, api_url, sign_in) + with _registry_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 _registry_lock: + other = _clients.get(key) + if other is not None and not other.health.failed: + return other + _clients[key] = made + return made + + +def _kept_rows_for(api_url: str | None, project_id: str, dataset: str) -> KeptRows: + """Return where this process keeps the rows of a dataset's schema table (ITL-1457).""" + with _registry_lock: + return _kept_rows.setdefault((api_url, project_id, dataset), KeptRows()) class _NoRedirect(urllib.request.HTTPRedirectHandler): @@ -741,16 +857,23 @@ def __init__( self._dataset = dataset self._overrides = overrides self._closed = False - self._client = _new_client(overrides) + # One client per service address and sign-in in the process (ITL-1457). + shared = _client_for(overrides) + self._shared = shared + self._client = client = shared.sdk + # Kept after close(): a read may end after it. + self._health = health = shared.health self._pid = os.getpid() - # Shared by every connector on this client (``share_client``). - self._counts: dict[tuple[str, str], tuple[int, bool]] = {} - client = self._client + # Shared by every connector on this client. + self._counts = shared.counts 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}"), + lambda: _open_keyed_table( + client, project_id, dataset, SCHEMA_TABLE, health + ), + lambda doing: _service_call(f"{doing} of {project_id}/{dataset}", health), + _kept_rows_for(_api_url(overrides), project_id, dataset), ) def _require_open(self) -> None: @@ -770,7 +893,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.""" @@ -832,7 +955,7 @@ 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) @@ -1165,8 +1288,10 @@ 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._client + del self._shared del self._schemas def __enter__(self) -> SpiralDBConnector: diff --git a/src/orcapod/databases/spiraldb_schema_table.py b/src/orcapod/databases/spiraldb_schema_table.py index 01e5731d1..908cf8b1b 100644 --- a/src/orcapod/databases/spiraldb_schema_table.py +++ b/src/orcapod/databases/spiraldb_schema_table.py @@ -405,6 +405,37 @@ def require_schema_table(table: Any) -> bool: # ---------------------------------------------------------------------------- the table +class KeptRows: + """The rows of one dataset's schema table, kept for the snapshot (id and version) + they were read from (ITL-1457). + + A snapshot never changes, so its rows serve every connector of the process that opens + that same snapshot; a connector that opens another reads it again. The rows kept are + those of the newest snapshot read. + """ + + def __init__(self) -> None: + self._lock = Lock() + self._kept: tuple[tuple[str, int], dict[str, SchemaRow]] | None = None + + def get(self, snapshot: tuple[str, int]) -> dict[str, SchemaRow] | None: + """Return the rows read from exactly ``snapshot``, if they are kept.""" + with self._lock: + kept = self._kept + return kept[1] if kept is not None and kept[0] == snapshot else None + + def keep(self, snapshot: tuple[str, int], rows: dict[str, SchemaRow]) -> None: + """Keep the rows read from ``snapshot``, unless newer rows of that table are.""" + with self._lock: + # An older read that ends late does not replace a newer one. + if ( + self._kept is None + or self._kept[0][0] != snapshot[0] + or self._kept[0][1] < snapshot[1] + ): + self._kept = (snapshot, rows) + + class SchemaTable: """The schema table of one dataset, read through one client. @@ -418,6 +449,8 @@ class SchemaTable: open_table: Opens the schema table's latest snapshot; ``None`` when the dataset has none. Any other failure is raised. service_call: A context that says what a failing service call was doing. + kept: Where the rows read are kept; shared by the connectors of one service + address and dataset in a process. A new one when not given. """ def __init__( @@ -426,13 +459,13 @@ def __init__( dataset: str, open_table: Callable[[], Any | None], service_call: Callable[[str], AbstractContextManager[None]], + kept: KeptRows | None = None, ) -> None: self._project = project self._dataset = dataset self._open = open_table self._service_call = service_call - self._lock = Lock() - self._kept: tuple[tuple[str, int], dict[str, SchemaRow]] | None = None + self._kept = KeptRows() if kept is None else kept def row(self, table_id: str) -> SchemaRow | None: """Return the row of ``table_id`` as stored now; ``None`` when the dataset has no @@ -455,21 +488,12 @@ def rows(self) -> Mapping[str, SchemaRow] | None: if table is None: return None snapshot = (str(table.resource_id), int(table.version_id)) - with self._lock: - kept = self._kept - if kept is None or kept[0] != snapshot: + rows = self._kept.get(snapshot) + if rows is None: with self._service_call("read the schema table"): written = require_schema_table(table) stored = table.scan().to_table().to_pylist() if written else [] rows, marker = read_rows(stored) require_complete(self._project, self._dataset, rows, marker) - kept = (snapshot, rows) - with self._lock: - # An older read that ends late does not replace a newer one. - if ( - self._kept is None - or self._kept[0][0] != snapshot[0] - or self._kept[0][1] < snapshot[1] - ): - self._kept = kept - return kept[1] + self._kept.keep(snapshot, rows) + return rows diff --git a/tests/test_core/sources/test_spiraldb_lookups.py b/tests/test_core/sources/test_spiraldb_lookups.py index 7d67e07a9..1aac79b95 100644 --- a/tests/test_core/sources/test_spiraldb_lookups.py +++ b/tests/test_core/sources/test_spiraldb_lookups.py @@ -22,6 +22,7 @@ import pytest from orcapod import PipelineJob +from orcapod.databases import spiraldb_connector as connector_module from orcapod.databases import ( InMemoryArrowDatabase, SpiralDBConnector, @@ -320,15 +321,19 @@ async def collect() -> list[int]: else cast("list[int]", source.as_table()["k"].to_pylist()) ) assert sorted(keys) == expected - # No lookup, schema or schema-table read: the pinned handle is reused. - assert calls == {"scan": 1} | ({} if restricted or round_ else {"count": 1}) + # No lookup, schema or schema-table read: the pinned handle is reused. Only a + # read that hands rows on before it ends counts first; as_table counts as it + # reads (ITL-1457). + counted = async_read and not restricted and not round_ + assert calls == {"scan": 1} | ({"count": 1} if counted else {}) calls.clear() head = source.head(1) assert head.table.num_rows == 1 assert head.total_rows == 3 - # The count was made by the reads above (or is made here, after a restricted read). - assert calls == {"scan": 1} | ({"count": 1} if restricted else {}) + # The count was made by the reads above, or is made here. + counted = async_read and not restricted + assert calls == {"scan": 1} | ({} if counted else {"count": 1}) @pytest.mark.parametrize( @@ -507,14 +512,14 @@ def test_job_reuses_client_but_refreshes_table_each_run( calls.clear() job.run(orchestrator=runner) assert job.nodes["read"].as_table().num_rows == 3 - # The run's check looks the table up once; its read reuses the pinned handle. + # The run's check looks the table up once; its read reuses the pinned handle. The + # sync run reads the whole table at once and counts as it reads (ITL-1457). assert calls == { "lookup": 1, "open_schemas": 1, "schema": 1, - "count": 1, "scan": 1, - } + } | ({"count": 1} if orchestrator is not None else {}) calls.clear() job.run(orchestrator=runner) @@ -798,3 +803,163 @@ def test_a_given_older_version_is_prepared_at_build( assert keys == [0, 1, 2] assert "schema" not in calls and "read_schemas" not in calls assert "open_schemas" not in calls and "lookup" not in calls + + +# ----------------------------------------------- one client and schema table per process +# ITL-1457: the sources of one process that use one service address and sign-in share an +# SDK client, and the rows of a dataset's schema table are read once per snapshot of it. + + +def _sdk_client(source: SpiralDBTableSource) -> object: + return source._connector()._client # pyright: ignore[reportPrivateUsage] # the test is about it + + +@pytest.mark.parametrize("role", sorted(ROLES)) +def test_a_second_source_signs_in_and_reads_the_schema_table_no_more( + calls: collections.Counter[str], role: str +) -> None: + first = _source(role) + calls.clear() + second = _source(role, record_id_columns=["k", "subject"]) + # One snapshot check of the schema table remains: its open. + assert calls == {"lookup": 1, "schema": 1, "open_schemas": 1} + assert _sdk_client(first) is _sdk_client(second) + for source in (first, second): + sync, async_ = _sync_and_async_rows(source) + assert sorted(sync) == sorted(async_) == _expected_rows([0, 1, 2]) + # Closing one source leaves the other's client and reads as they were. + first.close() + assert sorted(cast("list[int]", second.as_table()["k"].to_pylist())) == [0, 1, 2] + + +def test_a_new_snapshot_of_the_schema_table_is_read_again( + calls: collections.Counter[str], +) -> None: + first = _source("plain") + layout = _ARRANGED["layout"] + project = fake_spiral_sdk.ExternalProject(_PROJECT) + other = project.create_table("default.u", key_schema=_keys(["k"])) + other.write(_rows(layout, [5])) + other.record(_schema(layout)) + calls.clear() + second = SpiralDBTableSource( + project_id=_PROJECT, table_name="u", tag_only_columns=True + ) + # The schema table moved: its rows are read again, never served from the older one. + assert calls == {"lookup": 1, "schema": 1, "open_schemas": 1, "read_schemas": 1} + assert second.as_table()["k"].to_pylist() == [5] + assert first.check_for_new_data() is False + + +def test_a_damaged_schema_table_is_refused_after_rows_were_kept( + calls: collections.Counter[str], +) -> None: + _source("plain") + layout = _ARRANGED["layout"] + project = fake_spiral_sdk.ExternalProject(_PROJECT) + other = project.create_table("default.u", key_schema=_keys(["k"])) + other.write(_rows(layout, [5])) + # An interrupted migration: rows without a marker that fits them. + fake_spiral_sdk.migrate(_PROJECT, {"u": _schema(layout)}, complete=False) + for _ in range(2): + with pytest.raises(ValueError, match="does not fit its completion marker"): + _source("plain") + + +def test_a_changed_environment_signs_in_again( + calls: collections.Counter[str], monkeypatch: pytest.MonkeyPatch +) -> None: + first = _source("plain") + monkeypatch.setenv("SPIRAL_TOKEN_TEST_ONLY", "another-account") + calls.clear() + second = _source("plain") + assert calls["client"] == 1 + assert _sdk_client(first) is not _sdk_client(second) + + +def test_a_client_whose_call_failed_is_given_to_no_new_source( + calls: collections.Counter[str], monkeypatch: pytest.MonkeyPatch +) -> None: + first = _source("plain") + original = fake_spiral_sdk.FakeClient.keyed_table + + def failing(*args: Any, **kwargs: Any) -> Any: # pyright: ignore[reportExplicitAny] + raise RuntimeError("status 503") + + monkeypatch.setattr(fake_spiral_sdk.FakeClient, "keyed_table", failing) + with pytest.raises(RuntimeError, match="status 503"): + first.check_for_new_data() + monkeypatch.setattr(fake_spiral_sdk.FakeClient, "keyed_table", original) + calls.clear() + second = _source("plain") + assert calls["client"] == 1 + assert _sdk_client(first) is not _sdk_client(second) + assert sorted(cast("list[int]", second.as_table()["k"].to_pylist())) == [0, 1, 2] + + +def test_the_client_goes_with_the_last_source_that_uses_it( + calls: collections.Counter[str], +) -> None: + first, second = _source("plain"), _source("plain") + client = weakref.ref(_sdk_client(first)) + first.close() + gc.collect() + assert client() is not None + second.close() + gc.collect() + assert client() is None + calls.clear() + _source("plain") + assert calls["client"] == 1 + + +def test_sources_built_in_threads_share_one_client_and_read_alike( + calls: collections.Counter[str], +) -> None: + anchor = _source("plain") # holds the client, so the threads find it + built: list[SpiralDBTableSource] = [] + errors: list[BaseException] = [] + start = threading.Barrier(6) + + def build() -> None: + try: + start.wait() + built.append(_source("data_tags")) + except BaseException as exc: # pragma: no cover - reported below + errors.append(exc) + + calls.clear() + threads = [threading.Thread(target=build) for _ in range(6)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert errors == [] and len(built) == 6 + assert calls["client"] == 0 and calls["read_schemas"] == 0 + assert {id(_sdk_client(s)) for s in built} == {id(_sdk_client(anchor))} + for source in built: + sync, async_ = _sync_and_async_rows(source) + assert sorted(sync) == sorted(async_) == _expected_rows([0, 1, 2]) + + +def test_a_forked_child_keeps_no_client_or_rows_of_its_parent( + calls: collections.Counter[str], +) -> None: + """The fork hook itself (``os.register_at_fork``): the child starts empty.""" + source = _source("plain") + assert len(connector_module._clients) == 1 # pyright: ignore[reportPrivateUsage] + assert connector_module._kept_rows # pyright: ignore[reportPrivateUsage] + clients, kept = connector_module._clients, connector_module._kept_rows # pyright: ignore[reportPrivateUsage] + lock = connector_module._registry_lock # pyright: ignore[reportPrivateUsage] + try: + connector_module._forget_in_child() # pyright: ignore[reportPrivateUsage] + assert len(connector_module._clients) == 0 # pyright: ignore[reportPrivateUsage] + assert connector_module._kept_rows == {} # pyright: ignore[reportPrivateUsage] + calls.clear() + _source("plain") + assert calls["client"] == 1 and calls["read_schemas"] == 1 + finally: + connector_module._clients = clients # pyright: ignore[reportPrivateUsage] + connector_module._kept_rows = kept # pyright: ignore[reportPrivateUsage] + connector_module._registry_lock = lock # pyright: ignore[reportPrivateUsage] + assert sorted(cast("list[int]", source.as_table()["k"].to_pylist())) == [0, 1, 2] diff --git a/tests/test_core/sources/test_spiraldb_table_source_streaming.py b/tests/test_core/sources/test_spiraldb_table_source_streaming.py index 6a920cc12..24ea0dc65 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_streaming.py +++ b/tests/test_core/sources/test_spiraldb_table_source_streaming.py @@ -325,13 +325,14 @@ class TestRowCap: """``max_rows`` refuses a read that could exceed it.""" def test_a_read_over_the_cap_is_refused_before_scanning(self, project): - """A read over ``max_rows`` fails before any scan, saying how to narrow it.""" + """A read that hands rows on over ``max_rows`` fails before any scan, saying + how to narrow it.""" source = SpiralDBTableSource( _PROJECT, "event", max_rows=3, tag_only_columns=True ) with pytest.raises(SourceTooLargeError) as raised: - source.as_table() + next(source.iter_data()) assert fake_spiral_sdk.scan_log == [] message = str(raised.value) @@ -339,8 +340,24 @@ def test_a_read_over_the_cap_is_refused_before_scanning(self, project): # Counting stopped one past the cap. assert [c.limit for c in fake_spiral_sdk.count_log] == [4] assert "limit=" in message and "where=" in message - with pytest.raises(SourceTooLargeError): - list(source.iter_data()) + + def test_a_whole_table_over_the_cap_is_refused_without_a_count(self, project): + """``as_table`` hands no row on before it ends: it reads one row past the cap + and refuses with the error a counted read gives, with no separate count + (ITL-1457).""" + source = SpiralDBTableSource( + _PROJECT, "event", max_rows=3, tag_only_columns=True + ) + + with pytest.raises(SourceTooLargeError) as raised: + source.as_table() + + assert fake_spiral_sdk.count_log == [] + assert [s.limit for s in fake_spiral_sdk.scan_log] == [4] + with pytest.raises(SourceTooLargeError) as counted: + next(source.iter_data()) + assert [c.limit for c in fake_spiral_sdk.count_log] == [4] + assert str(raised.value) == str(counted.value) def test_a_limit_within_the_cap_is_read(self, project): """A ``limit`` within ``max_rows`` lets a larger table be read.""" diff --git a/tests/test_databases/test_spiraldb_reading.py b/tests/test_databases/test_spiraldb_reading.py index de0d1b0df..60f44e226 100644 --- a/tests/test_databases/test_spiraldb_reading.py +++ b/tests/test_databases/test_spiraldb_reading.py @@ -6,6 +6,7 @@ from __future__ import annotations +import gc import asyncio import datetime as dt import math @@ -438,6 +439,11 @@ def test_a_preview_counts_no_further_than_its_bound( assert head.total_rows == 3 monkeypatch.setattr(SpiralDBTableSource, "_preview_reads_rows", True) fake.count_log.clear() + # The count above is kept by the client of the process while a source holds it + # (ITL-1457): release it, so this preview counts. + source.close() + del source, head + gc.collect() head = SpiralDBTableSource("p", "units", max_rows=1, tag_only_columns=True).head(2) assert [c.limit for c in fake.count_log] == [3] assert (head.total_rows, "more than 2" in head.header()) == (None, True)