diff --git a/changelog.d/ITL-1502.md b/changelog.d/ITL-1502.md index e1e25eb69..4bd45510e 100644 --- a/changelog.d/ITL-1502.md +++ b/changelog.d/ITL-1502.md @@ -1,6 +1,6 @@ ### Changed -- Writable SpiralDB jobs reuse lease verification, stored-key and completion +- Writable SpiralDB jobs reuse stored-key and completion lookups, and stale-table discovery across a run, shared by every connector and thread of the run. Connections reuse resolved table IDs within each write scope. - A job node's `run()` commits a function node's writes every 100 rows and at its diff --git a/changelog.d/ITL-1899.md b/changelog.d/ITL-1899.md new file mode 100644 index 000000000..1c45fddfb --- /dev/null +++ b/changelog.d/ITL-1899.md @@ -0,0 +1,22 @@ +### Changed + +- Writable SpiralDB databases assume one writer process per keyed dataset at a + time. Concurrent writers are unsupported and can store duplicate results, + deliver side effects twice, or overwrite a cached source instead of refusing + the conflicting write. Orcapod no longer creates or checks writer lease + generation tables. +- A run opens one write scope per dataset. A write outside a run opens a fresh + scope for that call. A second open scope on the same dataset in the process + raises `SpiralDBScopeOpenError`. +- Each run lists the dataset once and shares its catalog, key index and kept + reads across connectors in the run. That avoids rescanning keys on each flush, + opening tables known to be absent, and reading back newly created tables. + Whole-table reads are kept within a 256 MiB budget. + +### Added + +- Writable `SpiralDBConnector` accepts a `WriteLock` provider from + `orcapod.databases.write_lock`. The default + `NoWriteLock` performs no cross-process coordination. A scope acquires its + lock before the first write or side effect and releases its handle when the + scope ends, including on failure. diff --git a/docs/api/databases.md b/docs/api/databases.md index 9806c28b7..045e29661 100644 --- a/docs/api/databases.md +++ b/docs/api/databases.md @@ -29,3 +29,9 @@ the underlying database classes (ITL-1539), so its public form may change. ::: orcapod.databases.PostgreSQLConnector ::: orcapod.databases.SpiralDBConnector + +::: orcapod.databases.write_lock.WriteLock + +::: orcapod.databases.write_lock.WriteLockHandle + +::: orcapod.databases.write_lock.NoWriteLock diff --git a/docs/api/errors.md b/docs/api/errors.md index 506ae657c..6f519beb4 100644 --- a/docs/api/errors.md +++ b/docs/api/errors.md @@ -136,7 +136,7 @@ These exceptions and warnings report storage, schema, and connector problems. ::: orcapod.errors.SpiralDBObserverNotSupportedError -::: orcapod.errors.SpiralDBLeaseRequiredError +::: orcapod.errors.SpiralDBScopeOpenError ::: orcapod.errors.SpiralDBSignInError diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index a0de9b152..332c7d138 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -6,7 +6,7 @@ records, operator caches, cached sources and side-effect logs. Open the dataset !!! warning "Provisional in 0.4.0" The writable SpiralDB database is provisional. The format of its tables (how a table is named, - what its metadata records, how values are encoded) and its writer lease may change in + what its metadata records, how values are encoded) may change in a later version, and a later version may not read tables written now. Nothing of the database enters a hash: a job's hashes, ids and stored paths are the same on SpiralDB as on Delta. @@ -40,50 +40,42 @@ and writes only the tables it made: it does not take over a table it did not wri ## One writer at a time -The SpiralDB database has one writer at a time. Every run of a job (`job.run()`, `job.run_async()`, -a job node's `run()`, and a load-only run that reads a cached source) takes the -dataset's **writer lease** before it checks a source, computes or writes anything, and -releases it when it ends, also when it fails. A run whose database and result database -are on one dataset takes one lease. - -While one run holds the lease, a second writer, in this process or another, is refused -when its run starts, with `LeaseBusyError`. Nothing of its run has happened then: no -source was checked, nothing computed, no data table made. (A run that writes -several datasets takes their leases one after another, so a dataset whose lease it took -before the refusal may hold a new lease table, released.) The error names the lease's table -id and who holds it. The lease is refuse-only: the second writer does not wait and never -takes the lease over, and a lease does not expire. - - -```python -from orcapod.databases.spiraldb_lease import LeaseBusyError - -try: - job.run() -except LeaseBusyError as refused: - print(refused) - # SpiralDB dataset 'pipeline_results' has a conflicting writer lease (owner ..., table ID ...). ... -``` - -Only a job run writes the SpiralDB database, through the writable connectors it holds the -lease with (those of its databases and of the cached sources it reads). A write through -any other writable connector (a cached source read outside a run, a `ConnectorArrowDatabase` over a -connector of its own or over a `share_client()` copy, flushed directly) raises `SpiralDBLeaseRequiredError` before -anything is written, also while a run holds the dataset's lease. A write through a -running job's own databases from outside the run (another thread, an observer) is not -told apart from the run's own: do not write through them while the job runs. A -load-only run of a job writes no node's table, so it takes a lease only for a cached -source it reads. A run takes one lease per dataset of one service: writable connectors -whose client reaches the same service share it, whether their address was left to the -default or given (`overrides={"server.url": ...}`). - -The run checks for stored keys using an index shared by its writable connectors. -Every write any of them commits, from any thread, updates it, and so does the run's -listing of the dataset's tables: a side-effect receipt or a table written during the -run is seen at once by every later lookup of the run. After an append whose outcome -is unknown (a lost reply), the index is read again from the table as it is then. -Every writer must respect the dataset's lease. Writes from outside the lease can -invalidate the index and are unsupported. +Orcapod assumes **one writer process per keyed dataset at a time**. Concurrent +writers are unsupported. If two processes write to the same dataset, they can +store duplicate results, deliver side effects twice, or overwrite a cached +source where a conflicting write would previously have been refused. + +Within one process, starting a second independent execution on the same dataset +while a run holds its write scope is also unsupported. This includes starting it +inside a function or a task it starts, or calling `execute()` directly on another +job's sink. Orcapod does not always refuse the second execution. + +A job run opens one write scope per writable dataset before checking sources. +Connectors in the run that reach the same service, project and dataset share the +scope. A second scope for the same project and dataset in the process raises +`SpiralDBScopeOpenError`, including when another thread tries to flush during a +run. A direct flush or a cache write outside a run opens a scope just for that +call and discards its state afterward. A standalone async pod execution +shares one scope per dataset across its nested caches and concurrent rows. + +The scope lists the dataset once on first use. Its connectors share the table +catalog, stored key index and recent whole-table reads. A commit updates +the shared state so subsequent reads see new tables and receipts. After an +append with an unknown outcome, the next key lookup refreshes the affected +index from the service. + +### Optional write lock + +`SpiralDBConnector(..., write_lock=provider)` accepts a `WriteLock` provider +from `orcapod.databases.write_lock`. +`None` uses `NoWriteLock`, which performs no coordination across processes. +When several connectors share a scope, give them the same custom provider. +A scope calls `provider.acquire(project_id, dataset)` before the first table +create or append. It also acquires the lock before a tracked side effect's +first delivery or a context-taking function's first call. The call returns a +handle whose `release()` method runs when the scope ends, including on failure. +An acquisition error reaches the caller unchanged and prevents the write or +delivery. A scope that has no writes or effects to perform never acquires the lock. A function job node's `run()` can commit every 100 rows and at the end of the node. Batching requires an attached pipeline database and a pod that takes no invocation @@ -96,15 +88,18 @@ context-taking function node commits each result before starting the next call. If a batched result append fails, the node retries the rows one at a time in order. It stops at the first failing row and raises that row's error. A read or validation -failure before the append stops the run immediately. After a definite -append failure, the results and pipeline records for the successful prefix stay -stored, as they do with per-row commits. After an ambiguous reply (the service may -have accepted some of the batch's rows), the ordered retry publishes a pipeline record -for every row before the first failing row, including a row the service had already -accepted (the retry finds it stored and does not append it again). Only a row the -service accepted beyond that prefix, from the failing row on, can stay stored with -no pipeline record pointing to it; a later run finds it by input hash as a cached -result. No pipeline record ever points to a result that is not stored. +failure before the append stops the run immediately. If the ordered retry runs +to completion, including when it stops on an ordinary append error, the results +and pipeline records for the successful prefix stay stored. After an ambiguous +reply (the service may have accepted some of the batch's rows), this prefix +includes results the retry finds already stored. An already accepted result +beyond the prefix can stay stored without its pipeline record. + +If a `KeyboardInterrupt` or another `BaseException` interrupts the ordered +retry, even a result confirmed earlier in the retry can remain stored without +its pipeline record. A later run can reuse stored results by input hash and +write their missing pipeline records. No pipeline record ever points to a +result that is not stored. A failed batched pipeline-record append also retries the records in order. The records before the first permanent failure stay published. The results were @@ -116,39 +111,6 @@ A connection resolves a table by name and checks its recorded path when it finds the table. Later operations use the resolved table ID. Each new write scope resolves the names it uses again, so a replacement between runs is picked up. -### A lease left behind - -A process that stops in the middle of a run (killed, or a lost connection) leaves its -lease held, and every later run is refused. Once you are sure that writer has stopped, -and every write it sent has settled, clear the lease by the project, dataset and table -id the refusal named (its message spells out the call): - - -```python -import spiral - -from orcapod.databases import spiraldb_lease - -spiraldb_lease.clear( - spiral.Client(), - "", - "", - "", - confirm_writer_stopped=True, -) -``` - -`spiral.Client()` connects to the default service. When the job's connector was made -for another service address (`SpiralDBConnector(..., overrides={"server.url": ...})`), -make the client for that same address, with a sign-in allowed to update the dataset: -a client of another service does not find the table id. Only the dataset's newest lease -table can be cleared: any other table id is refused and nothing is written. - -The run verifies each acquired lease at its first write. Clearing a lease while its -writer is still running is unsupported and can let a second writer in while the first -is still writing. Each lease is a small keyed table of the dataset. Keep all generations, -including released ones, because removing a generation by hand can let two writers in. - ## Saving and loading a job A job saved on the SpiralDB database records the connector (`connector_type`, project, @@ -172,14 +134,13 @@ read different tables. ## Limits -- In a writable run, the first key check for an existing table reads its whole - key column if the lease has yet to index it. The next check after index - invalidation scans it again. Routine checks use the lease's key index, which - successful appends update without a rescan. Each read of stored rows reads the - whole table, so these reads grow with the table's history. -- Only a job run writes the SpiralDB database: a cached source over it is read within a - run. A - way to hold the lease outside a run is planned (ITL-1849). +- In a write scope, a key check scans the whole key column of a table with rows + when the scope has neither an index nor reusable keys from an earlier read or + append. This can happen on the first check or after a failed append invalidates + the index. Successful appends update the index, and later checks reuse it + across flushes. Outside a write scope, every check for one or more keys in a + table with rows scans the key column. Reads of stored rows load the whole + table and can be reused within a write scope under a 256 MiB budget. - Status and logging observers do not write to SpiralDB: they raise `SpiralDBObserverNotSupportedError` at setup; give them another database such as Delta. diff --git a/docs/dev/scripts/itl_1844_database_evaluation.py b/docs/dev/scripts/itl_1844_database_evaluation.py index 7bf6606a6..4abf5220c 100644 --- a/docs/dev/scripts/itl_1844_database_evaluation.py +++ b/docs/dev/scripts/itl_1844_database_evaluation.py @@ -8,7 +8,8 @@ Scenarios: a first run (sync), a second run with one more input row, a REPLAY run of the operator, an async run (``run_async``) and a node run on fresh job names, a separate result database on the same dataset, a saved job loaded with the database and read back, a -load-only run, and a second writer refused while a lease is held. +load-only run, and a second write scope refused while the same process holds a scope +for that dataset. uv run python docs/dev/scripts/itl_1844_database_evaluation.py fake uv run python docs/dev/scripts/itl_1844_database_evaluation.py live \\ @@ -16,8 +17,8 @@ ``live`` needs a sign-in spiral-sdk finds (the ``SPIRAL_*`` environment variables) and writes into the given dataset only: database tables of job names starting with -``itl1844_eval_``, and one lease table per run. spiral-sdk cannot drop a keyed -table, so they stay; the report lists every one. Prints a JSON report. +``itl1844_eval_``. spiral-sdk cannot drop a keyed table, so they stay. +The JSON report includes the scenario outcomes and an inventory of those database tables. """ from __future__ import annotations @@ -48,11 +49,9 @@ DeltaTableDatabase, SpiralDBConnector, ) -from orcapod.databases import spiraldb_lease # noqa: E402 from orcapod.databases.spiral_database_identity import spiral_table_name # noqa: E402 -from orcapod.databases.spiraldb_connector import _open_keyed_table # noqa: E402 -from orcapod.databases.spiraldb_write_scope import take_lease # noqa: E402 -from orcapod.databases.store_table_names import spiral_lease_table_name # noqa: E402 +from orcapod.errors import SpiralDBScopeOpenError # noqa: E402 +from orcapod.databases.spiraldb_write_scope import database_writes # noqa: E402 from orcapod.side_effects import SideEffectPod, sink_pod # noqa: E402 from orcapod.sources import ArrowTableSource # noqa: E402 from orcapod.types import CacheMode # noqa: E402 @@ -265,7 +264,7 @@ def spiral_db() -> ConnectorArrowDatabase: _ = run(build(fresh, delta, n=6)) s[label] = compare(spiral_db(), delta, (fresh,)) - # 6. a separate result database on the same dataset (one lease). + # 6. a separate result database on the same dataset (one scope). fresh = f"itl1844_eval_{stamp}_results" results_delta = DeltaTableDatabase(work / "delta_results") _ = build( @@ -294,19 +293,15 @@ def spiral_db() -> ConnectorArrowDatabase: loaded.nodes["select"].as_table().num_rows, ) - # 8. a second writer is refused while another holds the lease. - _, release = take_lease( - SpiralDBConnector(project, dataset, writable=True), "evaluation: another writer" - ) + # 8. A concurrent scope is refused within this process. fresh = f"itl1844_eval_{stamp}_refused" - try: - build(fresh, spiral_db(), n=6).run() - refused = False - except spiraldb_lease.LeaseBusyError: - refused = True - finally: - release() - s["second writer"] = { + with database_writes([spiral_db()]): + try: + build(fresh, spiral_db(), n=6).run() + refused = False + except SpiralDBScopeOpenError: + refused = True + s["second scope"] = { "refused": refused, "nothing_written": spiral_db().list_table_paths((fresh,)) == [], } @@ -350,12 +345,12 @@ def succeeded(scenarios: dict[str, Any]) -> bool: The first run computes all six rows; the new row is the only one computed and delivered; the database flag is saved; the load-only run loads seven rows; a refused - writer wrote nothing. + scope wrote nothing. """ first, new = scenarios.get("first run", {}), scenarios.get("new row", {}) saved, second = ( scenarios.get("save and load", {}), - scenarios.get("second writer", {}), + scenarios.get("second scope", {}), ) return ( all(v.get("ok", True) for v in scenarios.values()) @@ -389,21 +384,6 @@ def database_tables(project: str, dataset: str, stamp: str) -> list[dict[str, st ] -def lease_tables(project: str, dataset: str) -> list[dict[str, str]]: - """The dataset's lease generation tables (contiguous from 1), by name and id.""" - connector = SpiralDBConnector(project, dataset) - client = connector._client # pyright: ignore[reportPrivateUsage] # a listing for the report - found: list[dict[str, str]] = [] - generation = 1 - while True: - name = spiral_lease_table_name(generation) - table = _open_keyed_table(client, project, dataset, name) - if table is None: - return found - found.append({"name": name, "id": str(table.resource_id)}) - generation += 1 - - def inventory( report: dict[str, Any], label: str, listing: Callable[[], list[dict[str, str]]] ) -> list[dict[str, str]] | None: @@ -440,11 +420,6 @@ def main() -> int: stack.enter_context(fake_service(work)) report: dict[str, Any] = {"stamp": stamp, "scenarios": {}, "ok": False} print(f"stamp {stamp}", file=sys.stderr) - before = inventory( - report, - "lease tables before", - lambda: lease_tables(args.project, args.dataset), - ) try: evaluate(args.project, args.dataset, stamp, work, report) except Exception as exc: # reported with every table made so far @@ -457,16 +432,6 @@ def main() -> int: "database tables", lambda: database_tables(args.project, args.dataset, stamp), ) - after = inventory( - report, - "lease tables after", - lambda: lease_tables(args.project, args.dataset), - ) - if before is not None and after is not None: - known = {t["name"] for t in before} - report["lease_tables_created"] = [ - t for t in after if t["name"] not in known - ] if "inventory_errors" in report: # the tables made are not all known report["ok"] = False report["mode"] = args.mode diff --git a/scripts/migrate_spiral_schemas.py b/scripts/migrate_spiral_schemas.py index 3d58723d5..7429e634d 100644 --- a/scripts/migrate_spiral_schemas.py +++ b/scripts/migrate_spiral_schemas.py @@ -284,8 +284,8 @@ def dry_run(args: argparse.Namespace) -> None: for dataset in sorted(set(args.dataset)) if dataset in tables or dataset in reserved } - # A reserved name holds a writer lease generation, which is not migrated, or a - # table the upgraded connector no longer reads: refuse before planning anything. + # Skip retired writer lease generations. Require an explicit rename of any + # legacy table using the same naming convention with a different key. generations: dict[str, list[str]] = {} collisions: dict[str, list[str]] = {} for dataset, connector in connectors.items(): @@ -300,7 +300,7 @@ def dry_run(args: argparse.Namespace) -> None: ] message = ( f"table(s) {named} have names reserved for writer lease generations but " - "are not lease generations; Orcapod on spiral-sdk does not read them. " + "are not lease generations. " "Rename them before migrating" ) if migrated := [d for d in collisions if d in schema_tables]: @@ -415,7 +415,7 @@ def require_unchanged( ) -> None: """Refuse unless every table of the dataset is as the plan found it.""" from orcapod.databases.spiraldb_connector import ( - _list_keyed_tables, + _list_dataset, _open_keyed_table, ) from orcapod.databases.spiraldb_schema_table import ( @@ -424,8 +424,20 @@ def require_unchanged( ) # Not the connector's listing: it refuses a dataset whose migration was interrupted. - listed = _list_keyed_tables(client, project, dataset) - names = sorted(name for name in listed.values() if name != SCHEMA_TABLE) + listed = _list_dataset(client, project, dataset) + names: list[str] = [] + for name in sorted(listed.values()): + if name == SCHEMA_TABLE: + continue + if LEASE_TABLE_PATTERN.fullmatch(name) is not None: + handle = _open_keyed_table(client, project, dataset, name) + if handle is not None: + schema = handle.schema() + if is_lease_generation( + [(key, schema.field(key).type) for key in handle.key_columns] + ): + continue + names.append(name) planned = sorted(row.table_name for row in rows) if names != planned: raise MigrationError( diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index bed3f05ec..e0834351b 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -6,6 +6,7 @@ import dataclasses import logging from datetime import datetime, timezone +from contextlib import nullcontext from collections.abc import Iterator from functools import partial from typing import TYPE_CHECKING, Any, TypeAlias @@ -14,6 +15,7 @@ from orcapod.core.data_function import CachedDataFunction from orcapod.core.datagrams import Datagram from orcapod.core.function_pod import ( + _FunctionPodBase, # pyright: ignore[reportPrivateUsage] # delegated work within a pod AsyncRowInvoker, FunctionPodStream, WrappedFunctionPod, @@ -34,6 +36,7 @@ pod_timestamp_type, ) from orcapod.hooks import InvocationStatus +from orcapod.protocols.spiraldb_run import invocation_write_database from orcapod.protocols.core_protocols import ( FunctionPodProtocol, DataProtocol, @@ -224,7 +227,7 @@ def _cache_hit_output(self, cached: DataProtocol) -> DataProtocol: require_names_not_system(cached.keys()) return cached.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: False}) - def process_data( + def _process_data( self, tag: TagProtocol, data: DataProtocol, @@ -256,39 +259,54 @@ def process_data( module_logger.info("Pod-level cache hit") return tag, cached - tag, output = self._function_pod.process_data( - tag, data, logger=logger, run_id=run_id - ) - if output is not None: - pf = self._function_pod.data_function - var_dg = Datagram( - pf.get_function_variation_data(), - python_schema=pf.get_function_variation_data_schema(), - _inherited_schema=True, - data_context=pf.data_context, - ) - exec_dg = Datagram( - pf.get_execution_data(), - python_schema=pf.get_execution_data_schema(), - _inherited_schema=True, - data_context=pf.data_context, + with ( + invocation_write_database(self.result_database) + if self.ctx_arg_name is not None + else nullcontext() + ): + pod = self._function_pod + process = ( + pod._row_processor # pyright: ignore[reportPrivateUsage] # delegated work in the same execution + if isinstance(pod, _FunctionPodBase) + else pod.process_data ) - # Write if missing (ITL-1503): a result stored for this input since the - # lookup above (an equal input computed at the same moment) is used and - # this one discarded, reported as a cache hit. - stored = self._cache.store_if_missing( - data, output, var_dg, exec_dg, data_context_key=self.data_context_key - ) - if stored is not None: - module_logger.info( - "A result for this input was stored meanwhile; using it" + tag, output = process(tag, data, logger=logger, run_id=run_id) + if output is not None: + pf = self._function_pod.data_function + var_dg = Datagram( + pf.get_function_variation_data(), + python_schema=pf.get_function_variation_data_schema(), + _inherited_schema=True, + data_context=self.data_context, ) - output = self._cache_hit_output(stored) - else: - output = output.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: True}) + exec_dg = Datagram( + pf.get_execution_data(), + python_schema=pf.get_execution_data_schema(), + _inherited_schema=True, + data_context=self.data_context, + ) + # Write if missing (ITL-1503): a result stored for this input since the + # lookup above (an equal input computed at the same moment) is used and + # this one discarded, reported as a cache hit. + stored = self._cache.store_if_missing( + data, + output, + var_dg, + exec_dg, + data_context_key=self.data_context_key, + ) + if stored is not None: + module_logger.info( + "A result for this input was stored meanwhile; using it" + ) + output = self._cache_hit_output(stored) + else: + output = output.with_meta_columns( + **{self.RESULT_COMPUTED_FLAG: True} + ) return tag, output - async def async_process_data( + async def _async_process_data( self, tag: TagProtocol, data: DataProtocol, @@ -327,36 +345,51 @@ async def _async_compute_and_store( run_id: str | None, ) -> tuple[TagProtocol, DataProtocol | None]: """Run one invocation after a cache miss and conditionally store its result.""" - tag, output = await self._function_pod.async_process_data( - tag, data, logger=logger, run_id=run_id - ) - if output is not None: - pf = self._function_pod.data_function - var_dg = Datagram( - pf.get_function_variation_data(), - python_schema=pf.get_function_variation_data_schema(), - _inherited_schema=True, - data_context=pf.data_context, - ) - exec_dg = Datagram( - pf.get_execution_data(), - python_schema=pf.get_execution_data_schema(), - _inherited_schema=True, - data_context=pf.data_context, + with ( + invocation_write_database(self.result_database) + if self.ctx_arg_name is not None + else nullcontext() + ): + pod = self._function_pod + process = ( + pod._async_row_processor # pyright: ignore[reportPrivateUsage] # delegated work in the same execution + if isinstance(pod, _FunctionPodBase) + else pod.async_process_data ) - # Write if missing (ITL-1503): a result stored for this input since the - # lookup above (an equal input computed at the same moment) is used and - # this one discarded, reported as a cache hit. - stored = self._cache.store_if_missing( - data, output, var_dg, exec_dg, data_context_key=self.data_context_key - ) - if stored is not None: - module_logger.info( - "A result for this input was stored meanwhile; using it" + tag, output = await process(tag, data, logger=logger, run_id=run_id) + if output is not None: + pf = self._function_pod.data_function + var_dg = Datagram( + pf.get_function_variation_data(), + python_schema=pf.get_function_variation_data_schema(), + _inherited_schema=True, + data_context=self.data_context, ) - output = self._cache_hit_output(stored) - else: - output = output.with_meta_columns(**{self.RESULT_COMPUTED_FLAG: True}) + exec_dg = Datagram( + pf.get_execution_data(), + python_schema=pf.get_execution_data_schema(), + _inherited_schema=True, + data_context=self.data_context, + ) + # Write if missing (ITL-1503): a result stored for this input since the + # lookup above (an equal input computed at the same moment) is used and + # this one discarded, reported as a cache hit. + stored = self._cache.store_if_missing( + data, + output, + var_dg, + exec_dg, + data_context_key=self.data_context_key, + ) + if stored is not None: + module_logger.info( + "A result for this input was stored meanwhile; using it" + ) + output = self._cache_hit_output(stored) + else: + output = output.with_meta_columns( + **{self.RESULT_COMPUTED_FLAG: True} + ) return tag, output def _invoke_with_hooks( @@ -371,7 +404,7 @@ def _invoke_with_hooks( When ``_post_run_hooks`` is empty, delegates directly to ``process_data`` with zero overhead. Otherwise calls - ``self.process_data()`` (which owns all cache lookup and store logic), + ``self._process_data()`` (which owns all cache lookup and store logic), reads ``RESULT_COMPUTED_FLAG`` from the output data meta to determine ``InvocationStatus.HIT`` vs ``InvocationStatus.COMPUTED``, and fires registered hooks. @@ -387,14 +420,14 @@ def _invoke_with_hooks( A ``(tag, output_data)`` tuple. """ if not self._post_run_hooks: - return self.process_data(tag, data, logger=logger, run_id=run_id) + return self._process_data(tag, data, logger=logger, run_id=run_id) started_at = datetime.now(timezone.utc) out_tag = tag output_data: DataProtocol | None = None try: - out_tag, output_data = self.process_data( + out_tag, output_data = self._process_data( tag, data, logger=logger, run_id=run_id ) if output_data is not None: @@ -514,7 +547,7 @@ async def _async_invoke_with_hooks( Returns: A ``(tag, output_data)`` tuple. """ - process = self.async_process_data if process is None else process + process = self._async_process_data if process is None else process if not self._post_run_hooks: return await process(tag, data, logger=logger, run_id=run_id) diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 28600be21..3953a8e41 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -11,7 +11,7 @@ import uuid from abc import abstractmethod from collections.abc import Callable, Iterable, Iterator, Sequence -from contextlib import contextmanager +from contextlib import contextmanager, nullcontext import typing from typing import TYPE_CHECKING, Any, ClassVar, Generic, Literal, TypeVar @@ -23,6 +23,7 @@ from orcapod.contexts.stored import require_same_data_context from orcapod.core.base import TraceableBase from orcapod.core.data_function_types import DataFunctionTypeDeclaration, StoredColumn +from orcapod.core.executors.local import run_sync_in_thread from orcapod.core.provisional_pods import CONTEXT_FUNCTION_POD, warn_provisional_pod from orcapod.core.datagrams import Datagram, Data from orcapod.hashing.semantic_hashing.builtin_handlers import ( @@ -41,6 +42,10 @@ OutputTypeError, UnstorableDatetimeError, ) +from orcapod.protocols.spiraldb_run import ( + acquire_invocation_write_locks, + invocation_write_database, +) from orcapod.protocols.core_protocols import DataFunctionProtocol, DataProtocol from orcapod.protocols.core_protocols.executor import ( DataFunctionExecutorProtocol, @@ -1288,6 +1293,7 @@ def call( if self._executor is not None: if not self._active: return None + acquire_invocation_write_locks() with _log_validated_outcome(logger) as execution_logger: try: raw = self._executor.execute_callable( @@ -1307,7 +1313,10 @@ def call( "capture will not occur. Set an executor to enable logging.", stacklevel=2, ) - return self.direct_call(data, **kwargs) + direct_call = self.direct_call + if getattr(direct_call, "__func__", None) is not PythonDataFunction.direct_call: + acquire_invocation_write_locks() + return direct_call(data, **kwargs) async def async_call( self, @@ -1320,6 +1329,7 @@ async def async_call( if self._executor is not None: if not self._active: return None + acquire_invocation_write_locks() with _log_validated_outcome(logger) as execution_logger: try: raw = await self._executor.async_execute_callable( @@ -1339,7 +1349,13 @@ async def async_call( "capture will not occur. Set an executor to enable logging.", stacklevel=2, ) - return await self.direct_async_call(data, **kwargs) + direct_async_call = self.direct_async_call + if ( + getattr(direct_async_call, "__func__", None) + is not PythonDataFunction.direct_async_call + ): + acquire_invocation_write_locks() + return await direct_async_call(data, **kwargs) def direct_call(self, data: DataProtocol, **kwargs: Any) -> DataProtocol | None: """Execute the function on *data* synchronously (no executor path). @@ -1356,6 +1372,7 @@ def direct_call(self, data: DataProtocol, **kwargs: Any) -> DataProtocol | None: if not self._active: return None + acquire_invocation_write_locks() if self._is_async: raw_result = self._call_async_function_sync(data, **kwargs) else: @@ -1376,28 +1393,15 @@ async def direct_async_call( **kwargs: Extra keyword arguments merged with ``data.as_dict()`` before invoking the function. """ - import asyncio - if not self._active: return None + acquire_invocation_write_locks() call_dict = {**data.as_dict(), **kwargs} if self._is_async: raw_result = await self._function(**call_dict) else: - import contextvars - import functools - - loop = asyncio.get_running_loop() - task_ctx = contextvars.copy_context() - raw_result = await loop.run_in_executor( - None, - functools.partial( - task_ctx.run, - self._function, - **call_dict, - ), - ) + raw_result = await run_sync_in_thread(self._function, call_dict) return self._build_output_data(raw_result) def to_config(self) -> dict[str, Any]: @@ -1635,6 +1639,7 @@ def __init__( super().__init__(data_function, **kwargs) self._result_database = result_database self._record_path_prefix = record_path_prefix + self._takes_context: bool = context_parameter is not None if context_parameter is not None: warn_provisional_pod(CONTEXT_FUNCTION_POD) record_path_prefix += ("side_effect_function",) @@ -1719,21 +1724,30 @@ def call( return output_data else: self._cache.check_before_side_effect(self.data_context_key) - output_data = self._data_function.call(data, logger=logger, **kwargs) - if output_data is not None: - schema_utils.require_names_not_system(output_data.keys()) - if not skip_cache_insert: - var_dg, exec_dg = self._build_metadata_datagrams() - self._cache.store( - data, - output_data, - var_dg, - exec_dg, - data_context_key=self.data_context_key, + with ( + invocation_write_database(self.result_database) + if self._takes_context and not skip_cache_insert + else nullcontext() + ): + call = self._data_function.call + # The standard method acquires after checking whether it is active. + if getattr(call, "__func__", None) is not PythonDataFunction.call: + acquire_invocation_write_locks() + output_data = call(data, logger=logger, **kwargs) + if output_data is not None: + schema_utils.require_names_not_system(output_data.keys()) + if not skip_cache_insert: + var_dg, exec_dg = self._build_metadata_datagrams() + self._cache.store( + data, + output_data, + var_dg, + exec_dg, + data_context_key=self.data_context_key, + ) + output_data = output_data.with_meta_columns( + **{self.RESULT_COMPUTED_FLAG: True} ) - output_data = output_data.with_meta_columns( - **{self.RESULT_COMPUTED_FLAG: True} - ) return output_data async def async_call( @@ -1766,23 +1780,29 @@ async def async_call( return output_data else: self._cache.check_before_side_effect(self.data_context_key) - output_data = await self._data_function.async_call( - data, logger=logger, **kwargs - ) - if output_data is not None: - schema_utils.require_names_not_system(output_data.keys()) - if not skip_cache_insert: - var_dg, exec_dg = self._build_metadata_datagrams() - self._cache.store( - data, - output_data, - var_dg, - exec_dg, - data_context_key=self.data_context_key, + with ( + invocation_write_database(self.result_database) + if self._takes_context and not skip_cache_insert + else nullcontext() + ): + call = self._data_function.async_call + if getattr(call, "__func__", None) is not PythonDataFunction.async_call: + acquire_invocation_write_locks() + output_data = await call(data, logger=logger, **kwargs) + if output_data is not None: + schema_utils.require_names_not_system(output_data.keys()) + if not skip_cache_insert: + var_dg, exec_dg = self._build_metadata_datagrams() + self._cache.store( + data, + output_data, + var_dg, + exec_dg, + data_context_key=self.data_context_key, + ) + output_data = output_data.with_meta_columns( + **{self.RESULT_COMPUTED_FLAG: True} ) - output_data = output_data.with_meta_columns( - **{self.RESULT_COMPUTED_FLAG: True} - ) return output_data def get_cached_output_for_data( diff --git a/src/orcapod/core/executors/local.py b/src/orcapod/core/executors/local.py index 983e2e3ff..9fa40be71 100644 --- a/src/orcapod/core/executors/local.py +++ b/src/orcapod/core/executors/local.py @@ -2,17 +2,71 @@ import asyncio import atexit +import contextvars +import functools import inspect +import threading import traceback -from collections.abc import Callable +from collections.abc import Awaitable, Callable from typing import TYPE_CHECKING, Any from orcapod.core.executors.base import PythonFunctionExecutorBase +from orcapod.protocols.spiraldb_run import has_invocation_write_scope if TYPE_CHECKING: from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol +def run_sync_in_thread( + fn: Callable[..., Any], kwargs: dict[str, Any] +) -> Awaitable[Any]: + """Run a sync callable with its invocation context on the default executor.""" + loop = asyncio.get_running_loop() + context = contextvars.copy_context() + call = functools.partial(context.run, fn, **kwargs) + if not has_invocation_write_scope(): + return loop.run_in_executor(None, call) + return _run_guarded_sync_in_thread(loop, call) + + +async def _run_guarded_sync_in_thread( + loop: asyncio.AbstractEventLoop, call: Callable[[], Any] +) -> Any: + """Keep the write scope open across cancellation of a started call.""" + gate = threading.Lock() + started = False + cancelled = False + + def call_unless_cancelled() -> Any: + """Agree with cancellation on whether the callable may start.""" + nonlocal started + with gate: + if cancelled: + return None + started = True + return call() + + work = loop.run_in_executor(None, call_unless_cancelled) + try: + return await asyncio.shield(work) + except asyncio.CancelledError: + with gate: + if not started: + cancelled = True + _ = work.cancel() + raise + # The write scope must outlive a callable that can still deliver effects. + # Wait without propagating further cancellation to the worker. + while not work.done(): + try: + _ = await asyncio.wait((work,)) + except asyncio.CancelledError: + continue + if not work.cancelled(): + _ = work.exception() + raise + + class LocalPythonFunctionExecutor(PythonFunctionExecutorBase): """Default executor -- runs the data function directly in the current process. @@ -107,15 +161,7 @@ async def async_execute_callable( if inspect.iscoroutinefunction(fn): raw_result = await fn(**kwargs) else: - import contextvars - import functools - - loop = asyncio.get_running_loop() - task_ctx = contextvars.copy_context() - raw_result = await loop.run_in_executor( - None, - functools.partial(task_ctx.run, fn, **kwargs), - ) + raw_result = await run_sync_in_thread(fn, kwargs) except Exception: tb = traceback.format_exc() captured = ctx.get_captured(success=False, tb=tb) diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 1c4dd7087..c9557da57 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -13,6 +13,8 @@ Iterator, Sequence, ) +from contextlib import AbstractContextManager, contextmanager, nullcontext +from contextvars import ContextVar from functools import update_wrapper, wraps from typing import TYPE_CHECKING, Any, Literal, Protocol, cast @@ -37,6 +39,7 @@ require_current_bindings, require_current_outputs, ) +from orcapod.core.pod_result_databases import result_databases_of_pods from orcapod.core.provisional_pods import CONTEXT_FUNCTION_POD, warn_provisional_pod from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, @@ -124,6 +127,11 @@ def _executor_supports_concurrent( return executor is not None and executor.supports_concurrent_execution +_dispatched_row_override: ContextVar[_FunctionPodBase | None] = ContextVar( + "dispatched_row_override", default=None +) + + class _FunctionPodBase(TraceableBase): """Base pod that applies a data function to each input data.""" @@ -388,6 +396,18 @@ def process_data( *, logger: DataExecutionLoggerProtocol | None = None, run_id: str | None = None, + ) -> tuple[TagProtocol, DataProtocol | None]: + """Process one row, sharing the invocation when a dispatched override delegates.""" + with self._row_writes(): + return self._process_data(tag, data, logger=logger, run_id=run_id) + + def _process_data( + self, + tag: TagProtocol, + data: DataProtocol, + *, + logger: DataExecutionLoggerProtocol | None = None, + run_id: str | None = None, ) -> tuple[TagProtocol, DataProtocol | None]: """Process a single data using the pod's data function. @@ -425,6 +445,89 @@ async def async_process_data( *, logger: DataExecutionLoggerProtocol | None = None, run_id: str | None = None, + ) -> tuple[TagProtocol, DataProtocol | None]: + """Process one async row, sharing a dispatched override's invocation.""" + with self._row_writes(): + return await self._async_process_data( + tag, data, logger=logger, run_id=run_id + ) + + def _standalone_writes(self) -> AbstractContextManager[None]: + """Give this standalone execution its own writable dataset scopes.""" + from orcapod.databases.spiraldb_write_scope import database_writes + + return database_writes(result_databases_of_pods(self)) + + @contextmanager + def _row_writes(self) -> Iterator[None]: + """Reuse the engine's scope for a call through the dispatched override.""" + delegated = _dispatched_row_override.get() + if delegated is None: + with self._standalone_writes(): + yield + return + # Consume the delegation before running user code. A direct call from + # that code starts its own execution, including on this same pod. + token = _dispatched_row_override.set(None) + try: + with nullcontext() if delegated is self else self._standalone_writes(): + yield + finally: + _dispatched_row_override.reset(token) + + @property + def _row_processor( + self, + ) -> Callable[..., tuple[TagProtocol, DataProtocol | None]]: + """Use a custom row processor when the pod overrides the public method.""" + process = self.process_data + if getattr(process, "__func__", None) is _FunctionPodBase.process_data: + return self._process_data + + def invoke( + tag: TagProtocol, + data: DataProtocol, + *, + logger: DataExecutionLoggerProtocol | None = None, + run_id: str | None = None, + ) -> tuple[TagProtocol, DataProtocol | None]: + token = _dispatched_row_override.set(self) + try: + return process(tag, data, logger=logger, run_id=run_id) + finally: + _dispatched_row_override.reset(token) + + return invoke + + @property + def _async_row_processor(self) -> AsyncRowInvoker: + """Use a custom async row processor when the pod overrides the public method.""" + process = self.async_process_data + if getattr(process, "__func__", None) is _FunctionPodBase.async_process_data: + return self._async_process_data + + async def invoke( + tag: TagProtocol, + data: DataProtocol, + *, + logger: DataExecutionLoggerProtocol | None = None, + run_id: str | None = None, + ) -> tuple[TagProtocol, DataProtocol | None]: + token = _dispatched_row_override.set(self) + try: + return await process(tag, data, logger=logger, run_id=run_id) + finally: + _dispatched_row_override.reset(token) + + return invoke + + async def _async_process_data( + self, + tag: TagProtocol, + data: DataProtocol, + *, + logger: DataExecutionLoggerProtocol | None = None, + run_id: str | None = None, ) -> tuple[TagProtocol, DataProtocol | None]: """Async counterpart of ``process_data``. @@ -582,14 +685,14 @@ def _invoke_with_hooks( A ``(tag, output_data)`` tuple. """ if not self._post_run_hooks: - return self.process_data(tag, data, logger=logger, run_id=run_id) + return self._row_processor(tag, data, logger=logger, run_id=run_id) started_at = datetime.now(timezone.utc) out_tag = tag output_data: DataProtocol | None = None try: - out_tag, output_data = self.process_data( + out_tag, output_data = self._row_processor( tag, data, logger=logger, run_id=run_id ) except Exception as exc: @@ -648,7 +751,7 @@ async def _async_invoke_with_hooks( A ``(tag, output_data)`` tuple. """ if not self._post_run_hooks: - return await self.async_process_data( + return await self._async_row_processor( tag, data, logger=logger, run_id=run_id ) @@ -657,7 +760,7 @@ async def _async_invoke_with_hooks( output_data: DataProtocol | None = None try: - out_tag, output_data = await self.async_process_data( + out_tag, output_data = await self._async_row_processor( tag, data, logger=logger, run_id=run_id ) except Exception as exc: @@ -746,6 +849,29 @@ async def async_execute( function raised, inside the ``ExceptionGroup`` of the pod's task group. OrcapodDatabaseError: A failed database read or write, whatever ``error_policy`` is. """ + await self._async_execute( + inputs, + output, + pipeline_config, + observer=observer, + error_policy=error_policy, + run_id=run_id, + standalone=True, + ) + + async def _async_execute( + self, + inputs: Sequence[ReadableChannel[tuple[TagProtocol, DataProtocol]]], + output: WritableChannel[tuple[TagProtocol, DataProtocol]], + pipeline_config: PipelineConfig | None = None, + *, + observer: ExecutionObserverProtocol | None = None, + error_policy: Literal["continue", "fail_fast"] = "continue", + run_id: str | None = None, + standalone: bool = False, + ) -> None: + """Stream rows in a new execution or as work delegated by a job node.""" + from orcapod.databases.spiraldb_write_scope import invocation_writes from orcapod.pipeline.observer import NoOpObserver try: @@ -796,18 +922,23 @@ async def process_one(tag: TagProtocol, data: DataProtocol) -> None: if sem is not None: sem.release() - async with asyncio.TaskGroup() as tg: - first_row = True - async for tag, data in inputs[0]: - if first_row: - # The sync path checks the input's schema; here the first - # tag is the schema. Raised outside process_one, whose - # handler would skip the row silently. - first_row = False - self._validate_output_keys(tag.keys()) - if sem is not None: - await sem.acquire() - tg.create_task(process_one(tag, data)) + with ( + self._standalone_writes() + if standalone + else invocation_writes(result_databases_of_pods(self)) + ): + async with asyncio.TaskGroup() as tg: + first_row = True + async for tag, data in inputs[0]: + if first_row: + # The sync path checks the input's schema; here the first + # tag is the schema. Raised outside process_one, whose + # handler would skip the row silently. + first_row = False + self._validate_output_keys(tag.keys()) + if sem is not None: + await sem.acquire() + tg.create_task(process_one(tag, data)) finally: await output.close() @@ -1505,6 +1636,12 @@ def _pod_base(self) -> "_FunctionPodBase": assert isinstance(pod, _FunctionPodBase), type(pod) return pod + def _write_scope(self, pod: _FunctionPodBase) -> AbstractContextManager[None]: + """Use the job's scope for a delegated source stream.""" + from orcapod.databases.spiraldb_write_scope import stream_writes + + return stream_writes(self, result_databases_of_pods(pod)) + def _iter_data_sequential( self, ) -> Iterator[tuple[TagProtocol, DataProtocol]]: @@ -1548,7 +1685,9 @@ def _iter_data_sequential( # An input opened again yields the rows this stream already cached. continue try: - out_tag, output_data = self._pod_base()._invoke_with_hooks(tag, data) + pod = self._pod_base() + with self._write_scope(pod): + out_tag, output_data = pod._invoke_with_hooks(tag, data) except BaseException: # The row was taken from the input but not computed: put it back, so # the next read computes it instead of skipping it. @@ -1597,12 +1736,14 @@ def _iter_data_concurrent( except RuntimeError: loop = None + pod = self._pod_base() if loop is not None: # Already in event loop — fall back to sequential sync for i, tag, pkt in to_compute: - self._cached_output_datas[i] = ( - self._pod_base()._invoke_with_hooks(tag, pkt) - ) + with self._write_scope(pod): + self._cached_output_datas[i] = pod._invoke_with_hooks( + tag, pkt + ) else: async def _gather() -> list[ @@ -1611,23 +1752,24 @@ async def _gather() -> list[ return list( await asyncio.gather( *[ - self._pod_base()._async_invoke_with_hooks(tag, pkt) + pod._async_invoke_with_hooks(tag, pkt) for _, tag, pkt in to_compute ], return_exceptions=True, ) ) - first_error: BaseException | None = None - for (i, _, _), result in zip( - to_compute, asyncio.run(_gather()), strict=True - ): - if isinstance(result, BaseException): - first_error = first_error or result - else: - self._cached_output_datas[i] = result - if first_error is not None: - raise first_error + with self._write_scope(pod): + first_error: BaseException | None = None + for (i, _, _), result in zip( + to_compute, asyncio.run(_gather()), strict=True + ): + if isinstance(result, BaseException): + first_error = first_error or result + else: + self._cached_output_datas[i] = result + if first_error is not None: + raise first_error finally: remaining = [ (i, (tag, pkt)) @@ -2367,7 +2509,7 @@ def process( function_pod=self, input_stream=input_stream, label=label )._mark_recorded(self.tracker_manager) - def process_data( + def _process_data( self, tag: TagProtocol, data: DataProtocol, @@ -2375,12 +2517,12 @@ def process_data( logger: DataExecutionLoggerProtocol | None = None, run_id: str | None = None, ) -> tuple[TagProtocol, DataProtocol | None]: - tag, output = self._plain_pod.process_data( + tag, output = self._plain_pod._row_processor( # pyright: ignore[reportPrivateUsage] # delegated work in the same execution tag, self.function_input(data), logger=logger, run_id=run_id ) return tag, self.with_fall_through(data, output) - async def async_process_data( + async def _async_process_data( self, tag: TagProtocol, data: DataProtocol, @@ -2388,7 +2530,7 @@ async def async_process_data( logger: DataExecutionLoggerProtocol | None = None, run_id: str | None = None, ) -> tuple[TagProtocol, DataProtocol | None]: - tag, output = await self._plain_pod.async_process_data( + tag, output = await self._plain_pod._async_row_processor( # pyright: ignore[reportPrivateUsage] # delegated work in the same execution tag, self.function_input(data), logger=logger, run_id=run_id ) return tag, self.with_fall_through(data, output) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index f60283ded..5b2ce6a51 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -42,6 +42,7 @@ ) from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.core.function_pod import ( + _FunctionPodBase, # pyright: ignore[reportPrivateUsage] # function pod dispatch within a node fall_through_tags, function_input, function_input_schema, @@ -86,6 +87,7 @@ exclude_unpublished_result, track_database_write, ) +from orcapod.core.pod_result_databases import result_databases_of_pods from orcapod.core.provisional_pods import CONTEXT_FUNCTION_POD, warn_provisional_pod from orcapod.errors import ( EphemeralResultMissingError, @@ -126,7 +128,10 @@ ) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.hashing_protocols import IdentityWalkProtocol -from orcapod.protocols.spiraldb_run import InOrderFlushProtocol +from orcapod.protocols.spiraldb_run import ( + InOrderFlushProtocol, + invocation_write_database, +) from orcapod.protocols.observability_protocols import ( DataExecutionLoggerProtocol, ExecutionObserverProtocol, @@ -391,9 +396,8 @@ def run_job_node( # source, is refused before any source is checked and before anything is # computed or written (ITL-1218). refuse_restriction_conflicts([node]) - # The writer leases of the writable SpiralDB databases the run may write are held - # from the source check to the end of the run; a second writer is refused - # (ITL-1844). + # The write scopes of the writable SpiralDB databases the run may write are held + # from the source check to the end of the run. with database_write_scope([node], load_only=load_only): # Every source feeding the run first takes in any new data (ITL-1102). unchecked = check_sources([node]) @@ -1635,6 +1639,12 @@ def _begin_run(self) -> None: self._current_tables_checked = False self._account_for_stale_tables() + def _invocation_write_database(self) -> contextlib.AbstractContextManager[None]: + """Register the pipeline store when the node can deliver side effects.""" + if self._delivers_side_effects: + return invocation_write_database(self._pipeline_database) + return contextlib.nullcontext() + def _refresh_stored_tables(self) -> None: """Read this node's stored tables from the store's current version (ITL-1408). @@ -2767,6 +2777,7 @@ def execute( than this node; raised before any row is processed, whatever the error policy. """ + from orcapod.databases.spiraldb_write_scope import invocation_writes from orcapod.pipeline.observer import NoOpObserver try: @@ -2822,6 +2833,15 @@ def execute( # successful computation), one per input: the node's rows afterwards. emitted_entry_ids: list[bytes] = [] failed_rows = 0 + execution_pod = ( + self._ephemeral_cached_pod + if self._node_config.is_result_ephemeral + else self._cached_function_pod or self._function_pod + ) + databases = [ + self._pipeline_database, + *result_databases_of_pods(execution_pod), + ] for tag, data, instance_id in upstream_entries: ctx_obs.on_data_start(node_label, tag, data) @@ -2836,47 +2856,50 @@ def execute( continue pkt_logger = ctx_obs.create_data_logger(tag, data) - try: - tag_out, result = self._process_data_internal( - tag, - data, - logger=pkt_logger, - run_id=run_id, - instance_id=instance_id, - ) - except OrcapodDatabaseError as exc: - # A failed database read or write fails the run whatever the error - # policy: error_policy only decides about rows whose function - # raised. - exc.add_context(node_label=node_label, tag=tag.as_dict()) - with keep_database_error(exc, "Observer on_data_crash"): - ctx_obs.on_data_crash(node_label, tag, data, exc) - with keep_database_error(exc, "Observer on_node_end"): - ctx_obs.on_node_end(node_label, node_hash) - raise - except TypeIdentityError as exc: - # A stored row that cannot be decoded as its class is never - # skipped as a row failure, whatever the error policy (ITL-881). - with keep_database_error(exc, "Observer on_data_crash"): - ctx_obs.on_data_crash(node_label, tag, data, exc) - with keep_database_error(exc, "Observer on_node_end"): - ctx_obs.on_node_end(node_label, node_hash) - raise - except Exception as exc: - # Reported at the end of a job run (RunSummary, RowFailuresWarning), - # so one traceback per failed row is only for debugging. - logger.debug( - "Data execution failed in %s, skipping: %s", - node_label, - exc, - exc_info=True, - ) - ctx_obs.on_data_crash(node_label, tag, data, exc) - if error_policy == "fail_fast": - ctx_obs.on_node_end(node_label, node_hash) + # Let the fatal database handler see a lock refusal before the + # enclosing scope restores the provider's original exception. + with invocation_writes(databases): + try: + tag_out, result = self._process_data_internal( + tag, + data, + logger=pkt_logger, + run_id=run_id, + instance_id=instance_id, + ) + except OrcapodDatabaseError as exc: + # A failed database read or write fails the run whatever the error + # policy: error_policy only decides about rows whose function + # raised. + exc.add_context(node_label=node_label, tag=tag.as_dict()) + with keep_database_error(exc, "Observer on_data_crash"): + ctx_obs.on_data_crash(node_label, tag, data, exc) + with keep_database_error(exc, "Observer on_node_end"): + ctx_obs.on_node_end(node_label, node_hash) raise - failed_rows += 1 - continue + except TypeIdentityError as exc: + # A stored row that cannot be decoded as its class is never + # skipped as a row failure, whatever the error policy (ITL-881). + with keep_database_error(exc, "Observer on_data_crash"): + ctx_obs.on_data_crash(node_label, tag, data, exc) + with keep_database_error(exc, "Observer on_node_end"): + ctx_obs.on_node_end(node_label, node_hash) + raise + except Exception as exc: + # Reported at the end of a job run (RunSummary, RowFailuresWarning), + # so one traceback per failed row is only for debugging. + logger.debug( + "Data execution failed in %s, skipping: %s", + node_label, + exc, + exc_info=True, + ) + ctx_obs.on_data_crash(node_label, tag, data, exc) + if error_policy == "fail_fast": + ctx_obs.on_node_end(node_label, node_hash) + raise + failed_rows += 1 + continue ctx_obs.on_data_end(node_label, tag, data, result, cached=False) emitted_entry_ids.append(instance_id) @@ -3072,12 +3095,13 @@ def _process_data_internal( if from_persistent: tag_out = tag else: - tag_out, output_data = self._ephemeral_cached_pod.process_data( - tag, - function_input(self._function_pod, data), - logger=logger, - run_id=run_id, - ) + with self._invocation_write_database(): + tag_out, output_data = self._ephemeral_cached_pod._process_data( # pyright: ignore[reportPrivateUsage] # delegated work in the same execution + tag, + function_input(self._function_pod, data), + logger=logger, + run_id=run_id, + ) if output_data is not None: result_computed = bool( output_data.get_meta_value( @@ -3096,12 +3120,13 @@ def _process_data_internal( run_id=run_id, ) elif self._cached_function_pod is not None: - tag_out, output_data = self._cached_function_pod.process_data( - tag, - function_input(self._function_pod, data), - logger=logger, - run_id=run_id, - ) + with self._invocation_write_database(): + tag_out, output_data = self._cached_function_pod._process_data( # pyright: ignore[reportPrivateUsage] # delegated work in the same execution + tag, + function_input(self._function_pod, data), + logger=logger, + run_id=run_id, + ) if output_data is not None: result_computed = bool( output_data.get_meta_value( @@ -3118,9 +3143,14 @@ def _process_data_internal( run_id=run_id, ) else: - tag_out, output_data = self._function_pod.process_data( - tag, data, logger=logger, run_id=run_id - ) + with self._invocation_write_database(): + pod = self._function_pod + process = ( + pod._row_processor # pyright: ignore[reportPrivateUsage] # delegated work in the same execution + if isinstance(pod, _FunctionPodBase) + else pod.process_data + ) + tag_out, output_data = process(tag, data, logger=logger, run_id=run_id) if ephemeral_result or self._cached_function_pod is not None: # The stored result is the function's; the row's data-tag columns fall @@ -3217,12 +3247,13 @@ async def _async_process_data_internal( if from_persistent: tag_out = tag else: - ( - tag_out, - output_data, - ) = await self._ephemeral_cached_pod.async_process_data( - tag, function_input(self._function_pod, data), logger=logger - ) + with self._invocation_write_database(): + ( + tag_out, + output_data, + ) = await self._ephemeral_cached_pod._async_process_data( # pyright: ignore[reportPrivateUsage] # delegated work in the same execution + tag, function_input(self._function_pod, data), logger=logger + ) if output_data is not None: result_computed = bool( output_data.get_meta_value( @@ -3240,9 +3271,13 @@ async def _async_process_data_internal( output_data_hash=output_data.content_hash(), ) elif self._cached_function_pod is not None: - tag_out, output_data = await self._cached_function_pod.async_process_data( - tag, function_input(self._function_pod, data), logger=logger - ) + with self._invocation_write_database(): + ( + tag_out, + output_data, + ) = await self._cached_function_pod._async_process_data( # pyright: ignore[reportPrivateUsage] # delegated work in the same execution + tag, function_input(self._function_pod, data), logger=logger + ) if output_data is not None: result_computed = bool( output_data.get_meta_value( @@ -3258,9 +3293,16 @@ async def _async_process_data_internal( output_data_hash=output_data.content_hash(), ) else: - tag_out, output_data = await self._function_pod.async_process_data( - tag, data, logger=logger - ) + with self._invocation_write_database(): + pod = self._function_pod + process = ( + pod._async_row_processor # pyright: ignore[reportPrivateUsage] # delegated work in the same execution + if isinstance(pod, _FunctionPodBase) + else pod.async_process_data + ) + tag_out, output_data = await process( + tag, data, logger=logger, run_id=None + ) if ephemeral_result or self._cached_function_pod is not None: # The stored result is the function's; the row's data-tag columns fall @@ -5107,18 +5149,23 @@ def create_data_logger(self, tag: Any, data: Any) -> Any: ) return ctx_obs.create_data_logger(clean, data) - async with asyncio.TaskGroup() as tg: - tg.create_task(route_inputs()) - tg.create_task( - execution_pod.async_execute( - [compute_channel.reader], - result_channel.writer, - observer=_NodeLabelObserver(), - error_policy=error_policy, - run_id=run_id, + with self._invocation_write_database(): + async with asyncio.TaskGroup() as tg: + tg.create_task(route_inputs()) + tg.create_task( + execution_pod._async_execute( # pyright: ignore[reportPrivateUsage] # delegated work of this node's execution + [compute_channel.reader], + result_channel.writer, + # The adapter forwards the pod observer callbacks. + observer=cast( + ExecutionObserverProtocol, + cast(object, _NodeLabelObserver()), + ), + error_policy=error_policy, + run_id=run_id, + ) ) - ) - tg.create_task(record_and_forward()) + tg.create_task(record_and_forward()) # Commit the last rows inside a job (ITL-919); a no-op otherwise. self._commit_at_node_end() # The node's rows are those of this run's inputs, as the sync path's: @@ -5128,7 +5175,14 @@ def create_data_logger(self, tag: Any, data: Any) -> Any: # No-DB path: delegate dispatch entirely to the pod. The pod closes # the writer it is given; that close waits for the finally below, so # the node is stamped before its downstream nodes see the end. - await self._function_pod.async_execute( + pod = self._function_pod + execute = ( + pod._async_execute # pyright: ignore[reportPrivateUsage] # delegated work of this node's execution + if isinstance(pod, _FunctionPodBase) + and type(pod).async_execute is _FunctionPodBase.async_execute + else getattr(pod, "async_execute") + ) + await execute( [input_channel], _CloseDeferredWriter(output), observer=ctx_obs, diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 89f54667f..7e9d08317 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -2118,17 +2118,16 @@ def run(self, *, load_only: bool = False) -> StreamView: # source, is refused before any source is checked and before anything is # computed or written (ITL-1218). refuse_restriction_conflicts([self]) - # The writer leases of the writable SpiralDB databases the run may write are - # held from the source check to the end of the run; a second writer is refused - # (ITL-1844). + # The write scopes of the writable SpiralDB databases the run may write are + # held from the source check to the end of the run. with database_write_scope([self], load_only=load_only): - return self._run_holding_leases( + return self._run_in_write_scope( load_only=load_only, caller=sys._getframe(1), # pyright: ignore[reportPrivateUsage] # the caller's line is where the warning is shown ) - def _run_holding_leases(self, *, load_only: bool, caller: Any) -> StreamView: - """``run`` from its source check on, the run's writer leases held. + def _run_in_write_scope(self, *, load_only: bool, caller: Any) -> StreamView: + """``run`` from its source check on, the run's write scopes held. Args: load_only: As for ``run``. diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 77a7fbb2b..5d68668ca 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -9,6 +9,7 @@ import asyncio +import contextvars import contextlib import dataclasses import functools @@ -2230,7 +2231,7 @@ def run(self, *, load_only: bool = False) -> StreamView: require_live_source_bindings([self]) require_consistent_sources([(f"node {self.label!r}", self)]) # A cached source writes its cache when checked or read: its store's writer - # lease is held for the run (ITL-1844). + # scope is held for the run. with database_write_scope([self], load_only=load_only): _ = check_sources([self]) if load_only: @@ -3112,11 +3113,16 @@ async def _send_batches( The number of rows sent. """ owner = ThreadPoolExecutor(max_workers=1, thread_name_prefix="source-read") + context = contextvars.copy_context() loop = asyncio.get_running_loop() sent = 0 + + def next_batch() -> StreamProtocol | None: + return context.run(lambda: next(streams, None)) + try: while True: - stream = await loop.run_in_executor(owner, next, streams, None) + stream = await loop.run_in_executor(owner, next_batch) if stream is None: break for pair in stream.iter_data(): @@ -3173,6 +3179,7 @@ async def _send_record_batches( The number of rows sent. """ owner = ThreadPoolExecutor(max_workers=1, thread_name_prefix="source-read") + context = contextvars.copy_context() loop = asyncio.get_running_loop() def next_table() -> pa.Table | None: @@ -3188,7 +3195,7 @@ def next_table() -> pa.Table | None: sent = 0 try: while True: - table = await loop.run_in_executor(owner, next_table) + table = await loop.run_in_executor(owner, context.run, next_table) if table is None: break if kept is not None: diff --git a/src/orcapod/core/pod_result_databases.py b/src/orcapod/core/pod_result_databases.py new file mode 100644 index 000000000..958b69fc5 --- /dev/null +++ b/src/orcapod/core/pod_result_databases.py @@ -0,0 +1,50 @@ +"""The result databases a function node's own pods write on a cache miss. + +Used for both a job's run scope and a standalone pod execution. +""" + +from __future__ import annotations + +from typing import Any + + +def pod_result_databases(node: Any) -> list[Any]: # pyright: ignore[reportExplicitAny] # any node kind + """The result databases a function node's own pod writes on a cache miss. + + The result database of each pod the node's function pod is or wraps + (``@function_pod(pod_cache_database=...)``), of each data function under them + (``@function_pod(result_database=...)``), and the node's ephemeral result database + (``set_ephemeral_database``, through the pod that writes it). Not the job's result + database (``_databases``); not committed at the end of a run, only included in the write scope. + """ + return result_databases_of_pods( + getattr(node, "_function_pod", None), + getattr(node, "_ephemeral_cached_pod", None), + ) + + +def result_databases_of_pods(*roots: object) -> list[object]: + """Find caches attached to the given pods and the functions they wrap.""" + return [ + getattr(owner, "result_database", None) for owner in result_cache_owners(*roots) + ] + + +def result_cache_owners(*roots: object) -> list[object]: + """Find the pods and data functions that can own a result database.""" + found: list[object] = [] + pods = list(roots) + visited: set[int] = set() + while pods: + pod = pods.pop(0) + if pod is None or id(pod) in visited: + continue + visited.add(id(pod)) + found.append(pod) + pods.append(getattr(pod, "_function_pod", None)) # a wrapping pod's inner pod + function = getattr(pod, "data_function", None) + while function is not None and id(function) not in visited: + visited.add(id(function)) + found.append(function) + function = getattr(function, "_data_function", None) # a wrapper's inner + return found diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index b3f61949a..867b57fd0 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -192,6 +192,24 @@ def wrapped( return wrapped +def _spiral_write_call( + method: Callable[Concatenate[ConnectorArrowDatabase, _P], _R], +) -> Callable[Concatenate[ConnectorArrowDatabase, _P], _R]: + """Group a direct flush and its retries in one write scope.""" + + @wraps(method) + def wrapped( + self: ConnectorArrowDatabase, *args: _P.args, **kwargs: _P.kwargs + ) -> _R: + tables = self._spiral # pyright: ignore[reportPrivateUsage] # wrapper for this class + if tables is None or not self._pending_batches: # pyright: ignore[reportPrivateUsage] # wrapper for this class + return method(self, *args, **kwargs) + with tables.write_scope(), tables.operation(): + return method(self, *args, **kwargs) + + return wrapped + + def _alike(parts: list[pa.Table]) -> list[pa.Table]: """Stored and queued rows under one schema when they differ only in a column's nullability: a store may read a column back ``NOT NULL`` (PostgreSQL's primary @@ -232,7 +250,7 @@ class ConnectorArrowDatabase: A writable SpiralDB database, ``SpiralDBConnector(..., writable=True)`` (provisional in 0.4.0), is read and written through its database tables (``spiraldb_tables``): names computed from the full path, identity and manifest in each table's metadata, - rows through the database codec. Its writes need the writer lease a job run holds + rows through the database codec. Its writes use a write scope (``spiraldb_write_scope``). A plain ``SpiralDBConnector`` refuses every write, as before. @@ -1217,7 +1235,7 @@ def guard_table_schema( self._get_record_key(record_path), check ) - @_one_spiral_operation + @_spiral_write_call def flush(self) -> None: """Insert all ready batches into the connector.""" for record_key in list(self._pending_batches): @@ -1232,17 +1250,17 @@ def flush_result_batch( """Commit a durable result table even if no pipeline records are stored.""" self.flush_batch(record_path) - @_one_spiral_operation + @_spiral_write_call def flush_batch(self, record_path: tuple[str, ...]) -> None: """Commit one table's ready records.""" self._flush_by_key(self._get_record_key(record_path)) - @_one_spiral_operation + @_spiral_write_call def flush_batch_in_order(self, record_path: tuple[str, ...]) -> None: """Commit ready pipeline records, retrying a failed append in row order.""" self._flush_by_key(self._get_record_key(record_path), in_order=True) - @_one_spiral_operation + @_spiral_write_call def flush_result_batch_in_order( self, record_path: tuple[str, ...], *, publish_records: bool ) -> None: @@ -1403,7 +1421,7 @@ def _write_rows_in_order( batch_error: The failed write's error. Raises: - BaseException: The first failing row's error, noted with ``batch_error``; + BaseException: The first failing row's error, noted with the batch error's type; the rows from it on are failed as the batch would have been. """ row_ids = cast("list[bytes]", pending[self.RECORD_ID_COLUMN].to_pylist()) @@ -1413,16 +1431,16 @@ def _write_rows_in_order( record_key, pending.slice(position, 1), queued_schema ) except BaseException as row_error: - row_error.add_note( - f"Writing the {pending.num_rows} rows as one batch failed first " - f"({type(batch_error).__name__}: {batch_error}); the " - f"{position} rows before this one were written one at a time." - ) self._pending_commits.fail_batch( record_key, pending.slice(position), ids.difference(row_ids[:position]), ) + row_error.add_note( + f"Writing the {pending.num_rows} rows as one batch failed first " + f"({type(batch_error).__name__}). The " + f"{position} rows before this one were written one at a time." + ) raise self._pending_commits.forget( record_key, {record_id}, keep_schema_check=True @@ -1509,7 +1527,7 @@ def _fmt(cols: Mapping[str, pa.DataType]) -> str: # Another writer can commit an ID after it was checked at add time. # Use the connector's atomic insert-if-missing for both modes. if tables is not None: - # Write only keys that are absent from the lease's key index. + # Write only keys that are absent from the scope's key index. tables.write(table_name, pending, on_append_error=on_append_error) elif self._sql_store is None: self._connector.create_table_if_not_exists( @@ -1568,16 +1586,33 @@ def spiral_records_match_context( pending is None or tables.data_context(pending) == current ) + @property + def spiral_writable(self) -> bool: + """Whether this database uses writable SpiralDB scopes.""" + return self._spiral_connector is not None + + def spiral_write_scope(self) -> AbstractContextManager[None]: + """Use this writable database's run scope or open a direct one.""" + tables = self._spiral + return ( + tables.write_scope(invocation=True) if tables is not None else nullcontext() + ) + + def spiral_acquire_write_lock(self) -> None: + """Acquire the active write scope's lock for this writable SpiralDB database.""" + if (tables := self._spiral) is not None: + tables.acquire_write_lock() + def spiral_completion_lookup( self, record_path: tuple[str, ...] ) -> Callable[[bytes], bool] | None: """Create a completion lookup for one execution of a side-effect node. Each lookup consults this database's pending receipts, then the committed - receipts as the run's lease-wide key index has them. Every connector of the - dataset under the run's lease updates that index as it commits, so a receipt + receipts as the run's shared key index has them. Every connector of the + dataset in the run's scope updates that index as it commits, so a receipt committed during the execution, by any of them, is seen at once. Without a - lease (no write can happen then) the committed ids are read once, at the + write scope the committed ids are read once, at the first lookup that needs them. Args: diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index e28eeb65a..6804a1cfb 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -26,6 +26,8 @@ from typing import TYPE_CHECKING, Any, cast +from contextlib import nullcontext + from orcapod.logical_types.database_hooks import register_discovered_logical_types from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.spiraldb_run import ( @@ -105,6 +107,24 @@ def spiral_completion_lookup( return self._db.spiral_completion_lookup(record_path) return None + @property + def spiral_writable(self) -> bool: + """Whether the wrapped database uses writable SpiralDB scopes.""" + return ( + isinstance(self._db, SpiralDBRunLookupProtocol) and self._db.spiral_writable + ) + + def spiral_write_scope(self) -> AbstractContextManager[None]: + """Delegate the write scope when the wrapped store supports it.""" + if isinstance(self._db, SpiralDBRunLookupProtocol): + return self._db.spiral_write_scope() + return nullcontext() + + def spiral_acquire_write_lock(self) -> None: + """Delegate write lock acquisition when the wrapped store supports it.""" + if isinstance(self._db, SpiralDBRunLookupProtocol): + self._db.spiral_acquire_write_lock() + def get_record_by_id( self, record_path: tuple[str, ...], @@ -387,7 +407,7 @@ def unwrap_database_views(database: object) -> object: """The database under every ``ExtensionAwareDatabase`` wrapping ``database``. The one unwrap of the library's database views, for code that must see the - backend: which SpiralDB connector a database writes through (its writer lease) and + backend: which SpiralDB connector a database writes through (its write scope) and in which mode (a saved job's binding). Args: diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 0a40bf185..ad6031c7c 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -30,7 +30,7 @@ from copy import copy from threading import Lock, local from typing import TYPE_CHECKING, Any, cast -from weakref import WeakValueDictionary +from weakref import WeakValueDictionary, proxy import pyarrow as pa import pyarrow.compute as pc @@ -51,7 +51,7 @@ from orcapod.databases.spiraldb_sign_in import require_sign_in, saved_login_path from orcapod.databases.spiraldb_writable_registry import register_writable_connector from orcapod.databases.spiraldb_tables import SpiralDBTables -from orcapod.databases.store_table_names import is_spiral_lease_table_name +from orcapod.databases.write_lock import NoWriteLock, WriteLock from orcapod.errors import ( NullInNonNullableColumnError, SpiralDBWriteNotSupportedError, @@ -553,8 +553,8 @@ def _service_address(client: Any) -> str: return address.rstrip("/") -def _list_keyed_tables(client: Any, project_id: str, dataset: str) -> dict[str, str]: - """Return keyed table names by ID, omitting writer lease generations. +def _list_dataset(client: Any, project_id: str, dataset: str) -> dict[str, str]: + """Return every keyed table name of a dataset by ID. spiral-sdk offers no listing of keyed tables, so this is the documented endpoint (docs.spiraldb.com, "List Keyed tables"), called with the client's address and @@ -583,10 +583,8 @@ def _list_keyed_tables(client: Any, project_id: str, dataset: str) -> dict[str, # A page can be empty before the last one. entries = cast("list[dict[str, str]]", page["items"]) for entry in entries: - name = entry["table"] - if entry["dataset"] != dataset or is_spiral_lease_table_name(name): - continue - names[entry["id"]] = name + if entry["dataset"] == dataset: + names[entry["id"]] = entry["table"] following = page.get("nextPageToken") if following is None: return names @@ -1048,11 +1046,16 @@ class SpiralDBConnector: of the service. Any other key is refused. writable: Open the dataset as a writable SpiralDB database, a job's database (ITL-1844), for ``ConnectorArrowDatabase``: tables named from their paths, - rows through the database codec, one writer at a time (a job run takes the - dataset's writer lease, and a second writer is refused). Its tables are read - and written only through ``ConnectorArrowDatabase``, and only a job run - writes them. Provisional in 0.4.0: the table format and the lease may change - in a later version, which may not read tables written now. + rows through the database codec. Its tables are read and written only + through ``ConnectorArrowDatabase``. One writer process per dataset at a time + is assumed, not checked (ITL-1899): concurrent writers are not supported, + and with two a run can store results twice, deliver side effects twice and + overwrite a cached source instead of refusing (``spiraldb_write_scope``). + Provisional in 0.4.0: the table format may change in a later version, + which may not read tables written now. + write_lock: Optional, for a writable connector: the ``WriteLock`` acquired + before a scope's first write to the dataset and released when the scope + ends (``write_lock``). ``None``: ``NoWriteLock``, which takes no lock. """ def __init__( @@ -1062,13 +1065,23 @@ def __init__( overrides: dict[str, str] | None = None, *, writable: bool = False, + write_lock: WriteLock | None = None, ) -> None: if not isinstance(writable, bool): # pyright: ignore[reportUnnecessaryIsInstance] # a saved or user value raise TypeError(f"writable must be True or False, got {writable!r}") + if write_lock is not None and not writable: + raise ValueError("write_lock is for a writable SpiralDB connector only") + if write_lock is not None and not callable( + getattr(write_lock, "acquire", None) + ): + raise TypeError(f"write_lock must have acquire(), got {write_lock!r}") + self._write_lock: WriteLock = ( + NoWriteLock() if write_lock is None else write_lock + ) self._project_id = project_id self._dataset = dataset # A copy: a later change to the caller's mapping must not change the service - # this connector reads, saves or leases. + # this connector reads, saves or writes. overrides = None if overrides is None else dict(overrides) self._overrides = overrides self._closed = False @@ -1095,18 +1108,21 @@ def __init__( self._writable = writable self._tables: SpiralDBTables | None = None if writable: - # A run looks for writer leases only while a writable connector exists. + # A run opens write scopes only while a writable connector exists. register_writable_connector(self) self._tables = self._new_tables() def _new_tables(self) -> SpiralDBTables: """The database tables of this connector's dataset, over its SDK client. - Each writable connector has its own, so the writer lease a run attaches to one - connector's tables never lets another connector write (``share_client`` too). + Each writable connector has its own, so a run's write scope attached to one + connector's tables is not another connector's (``share_client`` too). """ + from orcapod.databases.spiraldb_write_scope import one_call_scope + client, health = self._client, self._health project_id, dataset = self._project_id, self._dataset + connector = proxy(self) # the tables must not own their connector return SpiralDBTables( sp, project_id, @@ -1116,10 +1132,17 @@ def _new_tables(self) -> SpiralDBTables: lambda name, key: _create_keyed_table( client, project_id, dataset, name, key, exist_ok=False ), - lambda: _list_keyed_tables(client, project_id, dataset), + lambda: _list_dataset(client, project_id, dataset), lambda doing: _service_call(f"{doing} of {project_id}/{dataset}", health), + lambda invocation: one_call_scope(connector, invocation=invocation), ) + @property + def write_lock(self) -> WriteLock: + """The ``WriteLock`` a write scope of this connector's dataset acquires before + its first write (``NoWriteLock`` unless one was given).""" + return self._write_lock + def _require_open(self) -> None: """Raise RuntimeError if this connector has been closed.""" if self._closed: @@ -1139,27 +1162,19 @@ def _writable_tables(self) -> SpiralDBTables | None: self._require_open() return self._tables - def _writer_lease_key(self) -> tuple[str, str, str]: - """The dataset a writer lease is taken for: service address, project, dataset. + def _write_scope_key(self) -> tuple[str, str, str]: + """The dataset a write scope is opened for: service address, project, dataset. The address is the one the client resolved, so connectors that reach one - service share one lease however their address was given (none, or the + service share one scope however their address was given (none, or the default's). Raises: - RuntimeError: If the client does not expose its resolved address. - """ - return (_service_address(self._client), self._project_id, self._dataset) - - def _writer_lease_target(self) -> tuple[Any, str, str]: - """What ``spiraldb_write_scope`` takes the writer lease with: the SDK client, - project and dataset. - - Raises: - RuntimeError: If this connector has been closed. + RuntimeError: If this connector is closed or its client does not expose + its resolved address. """ self._require_open() - return (self._client, self._project_id, self._dataset) + return (_service_address(self._client), self._project_id, self._dataset) def _refuse_if_writable(self) -> None: """Refuse an operation on raw tables of a writable connector.""" @@ -1172,10 +1187,9 @@ def _refuse_if_writable(self) -> None: def share_client(self) -> SpiralDBConnector: """Return an independently closable connector in the same SDK client scope. - A writable connector's copy is writable too, registered as one, so a run on it - takes the dataset's writer lease also after the original is gone. It has its own - tables: a run's lease held through one of the two never lets - the other write. + A writable connector's copy is writable too, registered as one, with the same + ``WriteLock``. It has its own tables: a run's write scope attached through one + of the two is not the other's. """ self._require_open() shared = copy(self) @@ -1199,13 +1213,11 @@ def _require_user_table(self, table_name: str) -> None: f"{SCHEMA_TABLE!r} is reserved: it is where Orcapod keeps the schemas of " f"the tables of dataset {self._dataset!r}" ) - if is_spiral_lease_table_name(table_name): - raise ValueError(f"{table_name!r} is reserved for SpiralDB writer leases") def get_table_names(self) -> list[str]: """Return all table names in this connector's dataset, sorted alphabetically. - The listing excludes internal schema and lease tables. A table recorded in + The listing excludes the internal schema table. A table recorded in the schema table that the dataset no longer holds is warned about. Raises: @@ -1217,16 +1229,12 @@ def get_table_names(self) -> list[str]: self._require_open() self._refuse_if_writable() with self._service_call("list the tables of", "*"): - listed = _list_keyed_tables(self._client, self._project_id, self._dataset) + listed = _list_dataset(self._client, self._project_id, self._dataset) with _about_table(f"{self._project_id}/{self._dataset}"): recorded = ( (self._schemas.rows() or {}) if SCHEMA_TABLE in listed.values() else {} ) - gone = sorted( - row.table_name - for i, row in recorded.items() - if i not in listed and not is_spiral_lease_table_name(row.table_name) - ) + gone = sorted(row.table_name for i, row in recorded.items() if i not in listed) if gone: _warn_once( (f"{self._project_id}/{self._dataset}", str(gone)), @@ -1246,7 +1254,7 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: Raises: SpiralDBTableNotFoundError: If there is no such table. - ValueError: If the table is an internal schema or lease table, or this + ValueError: If the table is the internal schema table, or this connector is writable. """ self._require_open() diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py deleted file mode 100644 index 329fe9872..000000000 --- a/src/orcapod/databases/spiraldb_lease.py +++ /dev/null @@ -1,528 +0,0 @@ -"""Internal one-writer leases for writable SpiralDB databases. - -Generation discovery requires a contiguous sequence. Deleting a generation -table by hand can admit a second holder while a newer generation is still -held. Keep every generation table and use ``clear`` by ID to release a stale -newest generation. -""" - -from __future__ import annotations - -import os -from collections.abc import Callable -from dataclasses import dataclass -from datetime import datetime, timezone -from typing import Protocol, cast -from uuid import uuid4 - -import pyarrow as pa - -from orcapod.databases import spiraldb_connector as sdk -from orcapod.databases.store_table_names import ( - SPIRAL_LEASE_KEY_PREFIX, - spiral_lease_key_column, - spiral_lease_table_name, -) -from orcapod.errors import OrcapodDatabaseError - -_CLAIM = "claim" -_RELEASED = "released" - - -class _Scan(Protocol): - """The SDK scan interface used to read lease rows.""" - - def to_table(self) -> pa.Table: - """Read the scan as Arrow.""" - ... - - -class _KeyedTable(Protocol): - """The SDK snapshot operations used by the lease.""" - - @property - def resource_id(self) -> str: - """Return the immutable table ID.""" - ... - - @property - def key_columns(self) -> tuple[str, ...]: - """Return the ordered primary-key names.""" - ... - - def scan(self, *, limit: int) -> _Scan: - """Plan a scan of the lease rows.""" - ... - - def append(self, data: pa.Table, /) -> _KeyedTable: - """Publish a keyed row and return a new snapshot.""" - ... - - -class _Project(Protocol): - """The SDK project operation used to claim a generation.""" - - def create_keyed_table( - self, dataset: str, name: str, key_schema: pa.Schema, /, *, exist_ok: bool - ) -> _KeyedTable: - """Create a keyed table.""" - ... - - -class _Client(Protocol): - """The SDK client operations used by the lease.""" - - def project(self, id: str, /) -> _Project: - """Select a project.""" - ... - - def keyed_table(self, project: str, dataset: str, name: str, /) -> _KeyedTable: - """Open the latest table snapshot by name.""" - ... - - def keyed_table_by_id(self, table_id: str, /) -> _KeyedTable: - """Open the latest table snapshot by immutable ID.""" - ... - - -class LeaseError(OrcapodDatabaseError): - """A writer lease operation could not be completed or verified.""" - - -class LeaseBusyError(LeaseError): - """Another claim took the generation this writer needs. - - Attributes: - table_id: Immutable ID of the conflicting generation. - """ - - table_id: str - - def __init__( - self, - project_id: str, - dataset: str, - table_id: str, - owner: str | None, - *, - released: bool = False, - ) -> None: - """Identify the conflicting generation and explain how to proceed. - - Args: - project_id: Project containing the dataset. - dataset: Dataset where acquisition was refused. - table_id: Immutable ID of the conflicting generation. - owner: Owner details if recorded. - released: Whether the conflicting generation has already been released. - """ - self.table_id = table_id - description = f"owner {owner!r}" if owner is not None else "owner unknown" - how_to_clear = ( - f"spiraldb_lease.clear(client, {project_id!r}, {dataset!r}, {table_id!r}, " - "confirm_writer_stopped=True)" - ) - conflict = f"SpiralDB dataset {dataset!r} has a conflicting writer lease" - recovery = ( - "The conflicting lease was released. Retry acquisition." - if released - else ( - "If the lease is stale, confirm that the writer has stopped and all " - f"its pending writes have settled, then call {how_to_clear}." - ) - ) - super().__init__( - f"{conflict} ({description}, table ID {table_id!r}). {recovery}" - ) - - -@dataclass(frozen=True) -class Lease: - """A claim on one immutable generation table, held in the acquiring process.""" - - table_id: str - key: str - pid: int - - -@dataclass(frozen=True) -class _State: - """Owner information and the independent release marker.""" - - owner: str | None - released: bool - - -def _open( - client: _Client, project_id: str, dataset: str, generation: int -) -> _KeyedTable | None: - """Open the latest snapshot of a generation by name.""" - return cast( - "_KeyedTable | None", - sdk._open_keyed_table( - client, project_id, dataset, spiral_lease_table_name(generation) - ), - ) - - -def _newest( - client: _Client, project_id: str, dataset: str -) -> tuple[int, _KeyedTable | None]: - """Bracket the end of the contiguous generation sequence, then bisect.""" - low, high = 0, 1 - newest = None - while (table := _open(client, project_id, dataset, high)) is not None: - low, newest = high, table - high *= 2 - while high - low > 1: - mid = (low + high) // 2 - table = _open(client, project_id, dataset, mid) - if table is None: - high = mid - else: - low, newest = mid, table - return low, newest - - -def _key(table: _KeyedTable) -> str: - """Validate the reserved primary key before reading or mutating a lease.""" - key = spiral_lease_key_column(table.key_columns) - if key is None: - raise LeaseError( - f"SpiralDB table ID {table.resource_id!r} lacks the expected lease key" - ) - return key - - -def _state(table: _KeyedTable, key: str) -> _State: - """Read the two possible states from a snapshot, including a bare claim.""" - owner = None - released = False - rows = cast("list[dict[str, object]]", table.scan(limit=3).to_table().to_pylist()) - for row in rows: - if row[key] == _CLAIM and isinstance(recorded_owner := row.get("owner"), str): - owner = recorded_owner - elif row[key] == _RELEASED: - released = True - else: - raise LeaseError( - f"Invalid lease state in SpiralDB table ID {table.resource_id!r}" - ) - return _State(owner, released) - - -def _row( - key: str, state: str, owner: str | None = None, started_at: str | None = None -) -> pa.Table: - """Make one keyed write for a claim or release.""" - schema = pa.schema( - [ - pa.field(key, pa.large_string(), nullable=False), - pa.field("owner", pa.large_string()), - pa.field("started_at", pa.large_string()), - ] - ) - return pa.Table.from_arrays( - [pa.array([value], pa.large_string()) for value in (state, owner, started_at)], - schema=schema, - ) - - -def _claim_generation( - client: _Client, project_id: str, dataset: str, generation: int, key: str -) -> _KeyedTable: - """Make one exclusive create attempt and reconcile a lost reply by token. - - Any exit other than returning the caller's claim, by an error or an - interruption at any step (the create, a lost-reply lookup, the token check), - releases the generation after a fresh lookup by name, and only if that table - carries the caller's token. Another writer's claim is left untouched. - """ - try: - return _create_and_verify(client, project_id, dataset, generation, key) - except BaseException as exc: - _release_if_claimed(client, project_id, dataset, generation, key, exc) - raise - - -def _create_and_verify( - client: _Client, project_id: str, dataset: str, generation: int, key: str -) -> _KeyedTable: - """Create the generation exclusively and confirm it carries the caller's token.""" - name = spiral_lease_table_name(generation) - key_schema = pa.schema([pa.field(key, pa.large_string(), nullable=False)]) - try: - claimed = cast( - "_KeyedTable", - sdk._create_keyed_table( - client, project_id, dataset, name, key_schema, exist_ok=False - ), - ) - except Exception as exc: - location = f"dataset {dataset!r} at generation {generation}" - recovery = "Inspect that generation before clearing it by ID." - uncertain = LeaseError( - f"Could not confirm writer lease creation in {location}. {recovery}" - ) - try: - found = _open(client, project_id, dataset, generation) - except Exception as lookup_error: - uncertain.add_note(f"Generation lookup also failed: {lookup_error}") - raise uncertain from exc - if found is None: - raise uncertain from exc - found_key = _key(found) - if found_key == key: - return found - state = _state(found, found_key) - raise LeaseBusyError( - project_id, dataset, found.resource_id, state.owner, released=state.released - ) from exc - if _key(claimed) != key: - raise LeaseError(f"Unexpected claim token in table ID {claimed.resource_id!r}") - return claimed - - -def _release_if_claimed( - client: _Client, - project_id: str, - dataset: str, - generation: int, - key: str, - interrupted: BaseException, -) -> None: - """Release the generation if a fresh lookup shows the caller's token. - - Used when claiming a generation stops before the claim is returned. A generation that - carries another token is left untouched. A failure of this cleanup is noted on - ``interrupted``, which the caller re-raises. - """ - claimed_id: str | None = None - try: - found = _open(client, project_id, dataset, generation) - if found is not None and spiral_lease_key_column(found.key_columns) == key: - claimed_id = found.resource_id - _write_release(client, found, key) - except BaseException as cleanup_error: - where = ( - f"writer lease table ID {claimed_id!r}" - if claimed_id is not None - else f"generation {generation}" - ) - interrupted.add_note( - f"Reconciling interrupted writer lease creation ({where}) also " - f"failed: {cleanup_error!r}" - ) - - -def acquire( - client: _Client, - project_id: str, - dataset: str, - *, - owner: str, - on_claim: Callable[[Lease], None] | None = None, -) -> Lease: - """Claim a dataset for one writer or raise before any database data can be written. - - Args: - client: SDK client used for the lease. - project_id: Project containing the dataset. - dataset: Dataset to claim. - owner: Operator-visible description of the writer. - on_claim: Optional: given the lease once its claim is verified, inside the - guard: if it raises or is interrupted, the claim is released before the - error propagates. A caller records the lease for its own cleanup there, so - no point after the verified claim leaves it unrecorded and unreleased. - - Returns: - The verified lease for this process. - - Raises: - LeaseBusyError: If another claim prevents acquisition. - LeaseError: If the claim or its state cannot be verified. - TimeoutError: If the generation lookup before the claim, or a state read - of a generation, times out. Other SDK errors from those calls also - propagate unchanged. A failed create and a failed reopen by ID are - wrapped as ``LeaseError``. After claiming, - acquisition attempts release before re-raising. The one unguarded point - is between the claim's return and its assignment: an interruption there - leaves the generation held until it is cleared. - """ - generation, latest = _newest(client, project_id, dataset) - if latest is not None: - state = _state(latest, _key(latest)) - if not state.released: - raise LeaseBusyError(project_id, dataset, latest.resource_id, state.owner) - - key = f"{SPIRAL_LEASE_KEY_PREFIX}{uuid4().hex}" - row = _row(key, _CLAIM, owner, datetime.now(timezone.utc).isoformat()) - claimed: _KeyedTable | None = None - # Once the claim is confirmed as this caller's, every exit but a verified lease - # releases it. Owner details and release are different keys, so an operator's - # release survives even if the owner write publishes after it. - try: - claimed = _claim_generation(client, project_id, dataset, generation + 1, key) - lease = Lease(claimed.resource_id, key, os.getpid()) - try: - _ = claimed.append(row) - except Exception as exc: - try: - check(client, lease) - except Exception as verification_error: - verification_error.add_note( - f"Writing lease owner details also failed: {exc}" - ) - raise - else: - check(client, lease) - if on_claim is not None: - on_claim(lease) - except BaseException as exc: - if claimed is None: - raise - # The claim token was verified and no database writes could start. The release - # row can be written even if reading the current lease state failed. - try: - _write_release(client, claimed, key) - except BaseException as cleanup_error: - exc.add_note( - f"Releasing the failed acquisition also failed (writer lease table ID " - f"{claimed.resource_id!r}): {cleanup_error!r}" - ) - raise - return lease - - -def _held_table(client: _Client, lease: Lease) -> _KeyedTable: - """Reopen the lease by ID and verify that it belongs to this process and token.""" - sdk.require_same_process(lease.pid) - try: - table = cast("_KeyedTable", sdk._open_keyed_table_by_id(client, lease.table_id)) - except Exception as exc: - raise LeaseError( - f"Could not reopen SpiralDB lease table ID {lease.table_id!r}" - ) from exc - if table.resource_id != lease.table_id or _key(table) != lease.key: - raise LeaseError(f"SpiralDB lease table ID {lease.table_id!r} changed identity") - return table - - -def check(client: _Client, lease: Lease) -> None: - """Verify a claim immediately before use. - - Args: - client: SDK client for the service that issued the lease. - lease: Claim returned by ``acquire``. - - Raises: - LeaseError: If the lease is released, lacks an owner, or changed identity. - RuntimeError: If the lease belongs to a different process. - """ - table = _held_table(client, lease) - state = _state(table, lease.key) - if state.released: - raise LeaseError(f"SpiralDB lease table ID {lease.table_id!r} was released") - if state.owner is None: - raise LeaseError( - f"SpiralDB lease table ID {lease.table_id!r} has no owner record" - ) - - -def _write_release(client: _Client, table: _KeyedTable, key: str) -> None: - """Upsert the release marker and settle ambiguous replies by the exact ID.""" - table_id = table.resource_id - try: - _ = table.append(_row(key, _RELEASED)) - except Exception as exc: - try: - latest = cast("_KeyedTable", sdk._open_keyed_table_by_id(client, table_id)) - if ( - latest.resource_id == table_id - and _key(latest) == key - and _state(latest, key).released - ): - return - except Exception as lookup_error: - exc.add_note(f"Lease release verification also failed: {lookup_error}") - raise LeaseError( - f"Could not confirm release of SpiralDB lease table ID {table_id!r}" - ) from exc - - -def _mark_released(client: _Client, table: _KeyedTable, key: str) -> None: - """Write a release marker if this snapshot does not already show one.""" - try: - released = _state(table, key).released - except LeaseError: - raise - except Exception as exc: - raise LeaseError( - f"Could not read the state of SpiralDB lease table ID {table.resource_id!r}" - ) from exc - if not released: - _write_release(client, table, key) - - -def release(client: _Client, lease: Lease) -> None: - """Release exactly this claim after the writer and all pending writes have stopped. - - Args: - client: SDK client for the service that issued the lease. - lease: Claim returned by ``acquire``. - - Raises: - LeaseError: If the claim's identity or release cannot be verified. - RuntimeError: If the lease belongs to a different process. - """ - # The table ID and claim key identify this generation. Upserting the - # same release marker again leaves the owner and release state intact. - _write_release(client, _held_table(client, lease), lease.key) - - -def clear( - client: _Client, - project_id: str, - dataset: str, - table_id: str, - *, - confirm_writer_stopped: bool, -) -> None: - """Manually release a stale newest generation, named by its immutable table ID. - - Only the newest generation of a dataset can block acquisition, so only it can be - cleared. It is found by its reserved name, which proves that the table is a lease - generation (a table opened by ID has no name); a table ID that is not the newest - generation of the dataset is refused and nothing is written. - - Args: - client: SDK client for the service holding the generation table. - project_id: Project containing the dataset. - dataset: Dataset reported in the refusal. - table_id: Immutable ID reported in the refusal. - confirm_writer_stopped: Whether the previous writer and all pending - writes have stopped. - - Raises: - ValueError: If the operator did not confirm the writer has stopped. - LeaseError: If the table is not the dataset's newest generation, or the - generation's identity, state or release cannot be verified. - """ - if confirm_writer_stopped is not True: - raise ValueError( - "Confirm that the writer has stopped and all its pending writes have " - "settled before clearing its lease" - ) - try: - _, newest = _newest(client, project_id, dataset) - except Exception as exc: - raise LeaseError( - f"Could not look up the writer lease generations of SpiralDB dataset " - f"{dataset!r} to verify table ID {table_id!r}" - ) from exc - if newest is None or newest.resource_id != table_id: - raise LeaseError( - f"SpiralDB table ID {table_id!r} is not the newest writer lease " - f"generation of dataset {dataset!r}; nothing was cleared" - ) - _mark_released(client, newest, _key(newest)) diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index 300c11e37..6dff9f955 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -6,7 +6,9 @@ carried from PR 595 onto ``main``'s database structure. - A table's name is computed from its full record path (``spiral_database_identity``); a - table is found by opening that name, never by listing. + table is found by opening that name. In a write scope, a name the run's listing of + the dataset does not show is absent without an open (ITL-1899): the listing is updated + as the run creates and writes tables. - Its metadata holds its identity record and its manifest (``spiral_database_codec``): the record path, layout, data context, and the logical schema with the stored names. They are @@ -26,12 +28,20 @@ metadata of each candidate (cached by table id): that is how stale layouts are found (ITL-954). -One writer at a time (ITL-1844): every write needs the dataset's writer lease -(``spiraldb_lease``), handed in by the run that holds it (``spiraldb_write_scope``) and -checked at the first write; every write with no attached lease is refused -(``SpiralDBLeaseRequiredError``) before anything is created or written. A first write -still re-reads the table just before recording it and never overwrites what that read -shows. +One writer process per dataset is assumed (ITL-1899), not checked: every write happens +inside a scope of the dataset (``spiraldb_write_scope``), a job run's or, for a write +outside a run, one of its own for that call, and at most one scope of a dataset is open +in a process. The scope's ``WriteLock`` (``write_lock``; a no-op by default) is acquired +at its first create or append. A first write still re-reads the table just before +recording it and never overwrites what that read shows, unless this write's own +exclusive create made the table. + +With one writer, nothing but the scope writes the dataset, so what it read is kept for +the scope and shared by its connectors (``RunState``, ITL-1899): what each table holding +rows records, the id each name resolved to, the keys each table holds, and the rows of a +whole read of a table until an append to it starts. A table holding rows whose record is +known is opened by id only when a call needs the service (``_LazySnapshot``). All of it is +forgotten when the scope ends. """ from __future__ import annotations @@ -40,6 +50,7 @@ import threading from collections.abc import Callable, Collection, Iterator, Mapping from contextlib import AbstractContextManager, contextmanager, nullcontext +from contextvars import ContextVar from dataclasses import dataclass, field from typing import Any, Protocol, cast @@ -50,7 +61,7 @@ import orcapod.databases.spiral_database_identity as identity from orcapod.databases.spiral_database_identity import SpiralTableCollisionError from orcapod.databases.store_table_names import require_store_path_domain -from orcapod.errors import InputValidationError, SpiralDBLeaseRequiredError +from orcapod.errors import InputValidationError from orcapod.logical_types.canonical_form import ( EXTENSION_METADATA_KEY, EXTENSION_NAME_KEY, @@ -70,48 +81,124 @@ @dataclass class _Catalog: - """One run's view of a dataset, updated as the run writes new tables.""" + """One run's view of a dataset, updated as the run creates and writes tables. + + Attributes: + names: The listed tables' names by table id. + records: The record of each listed table that holds rows, and the table format + it names, by table id. + metadata: The metadata read from each listed table of this format that holds + rows, by table id: what it records never changes once it holds rows. + """ names: dict[str, str] records: dict[str, tuple[identity.TableRecord, str]] = field(default_factory=dict) + metadata: dict[str, dict[str, bytes]] = field(default_factory=dict) + _listed: set[str] = field(init=False, default_factory=set) + def __post_init__(self) -> None: + self._listed.update(self.names.values()) -@dataclass -class WriterLease: - """A run's state for one dataset, shared by the dataset's connectors under the - lease: the lease verification, the key index and the catalog. + def add(self, table_id: str, table_name: str) -> None: + """List a table the run created or wrote (kept when listed already).""" + if table_id not in self.names: + self.names[table_id] = table_name + self._listed.add(table_name) + + def shows_absent(self, table_name: str) -> bool: + """Whether no listed table has this name.""" + return table_name not in self._listed + + +KEPT_ROWS_BUDGET_BYTES = 256 * 1024 * 1024 +"""The most bytes (``pa.Table.nbytes``) of whole reads a scope keeps (ITL-1899): a read that does not fit is not kept, and the oldest kept reads are dropped +to make room. A dropped read is read again from the service when needed, so the budget +changes no result, only how often a table is read.""" - Every connector of the dataset that the run attached the lease to reads and - updates the key index and the catalog under ``lock``, from whichever thread it - is called on: a write from any thread under the run's lease is seen by every - later lookup of the run. + +active_run_states: ContextVar[frozenset[RunState]] = ContextVar( + "spiraldb_active_run_states", default=frozenset() +) +"""The write scopes visible to work in the current execution context.""" + + +@dataclass(eq=False) +class RunState: + """A scope's state for one dataset (``spiraldb_write_scope``), shared by the + dataset's connectors in the scope: the write lock's acquisition, the key index, the + catalog and the kept reads. It holds only while the scope's process is the + dataset's one writer (the single-writer assumption, ITL-1899). + + Every connector the scope attached it to reads and updates it under ``lock``, from + whichever thread it is called on: a write from any thread in the scope is seen by + every later lookup of the scope. Attributes: - verify: Verifies the lease on its first use. + acquire_lock: Acquires the scope's write lock, on first use only. lock: Guards the key index and the catalog, and serializes writes. - keys_by_table: The keys each table holds, by table id: filled from a snapshot - taken under ``lock`` and updated by every committed append. + keys_by_table: The keys each table holds, by table id. A first append keeps + its Arrow key column. The first lookup builds a set from that column, + kept rows or a current snapshot. Later appends update the set. table_ids: The id of the table under each name that ``holds_record_id`` has looked up, ``None`` for a name that held no rows then: updated by every committed append, forgotten by a failed one. - catalog: The dataset's listing, taken at the first listing of the run and - updated by every committed append; a failed append lists its table - unjudged, since it may hold rows; ``None`` until then. + catalog: The dataset's listing, loaded on first use and updated by every + committed append. A failed append lists its table unjudged since it may + hold rows. The catalog is ``None`` until a listing succeeds. + catalog_attempted: Whether a listing has already been attempted in the scope. commits: Counts every append's start and its end (odd while one is in flight): a snapshot opened at an even count equal to the count now holds - every append the lease's connectors made. + every append the scope's connectors made. + rows_by_table: The stored rows of each table a read of the run read whole + (oldest first, within ``KEPT_ROWS_BUDGET_BYTES``), + by table id, as the service returned them: kept only from a snapshot that + held every append of the run, and dropped when an append to the table + starts (ITL-1899), so a read from here is what a fresh read would give. + found_by_id: What each table holding rows records, by table id, shared by + the scope's connectors (a table's key, record and manifest never change once + it holds rows). + ids_by_name: The table id each name was resolved to in the run. """ - verify: Callable[[], None] + acquire_lock: Callable[[], None] lock: threading.RLock = field(default_factory=threading.RLock) - keys_by_table: dict[str, set[bytes]] = field(default_factory=dict) + keys_by_table: dict[str, set[bytes] | pa.ChunkedArray[Any]] = field( + default_factory=dict + ) table_ids: dict[str, str | None] = field(default_factory=dict) catalog: _Catalog | None = None + catalog_attempted: bool = False commits: int = 0 - - def __call__(self) -> None: - """Verify the writer lease on first use.""" - self.verify() + rows_by_table: dict[str, pa.Table] = field(default_factory=dict) + found_by_id: dict[str, _Found] = field(default_factory=dict) + ids_by_name: dict[str, str] = field(default_factory=dict) + + def get_catalog( + self, listing: Callable[[], dict[str, str]], *, required: bool = False + ) -> _Catalog | None: + """List tables on first use. An explicit listing can retry a failed preload.""" + with self.lock: + if self.catalog is None and (required or not self.catalog_attempted): + self.catalog_attempted = True + try: + self.catalog = _Catalog(listing()) + except Exception: # noqa: BLE001 # ordinary lookups can fall back to a name + if required: + raise + return self.catalog + + def forget_reads(self) -> None: + """Forget everything the scope read (``RunState`` attributes): the key index, + the catalog, the rows read and what the tables record.""" + with self.lock: + self.keys_by_table.clear() + self.table_ids.clear() + self.catalog = None + self.catalog_attempted = False + self.commits = 0 + self.rows_by_table.clear() + self.found_by_id.clear() + self.ids_by_name.clear() class _Scan(Protocol): @@ -187,6 +274,67 @@ class _Opened: table: _KeyedTable +class _LazySnapshot: + """A table resolved to its id, opened by id at its first use (ITL-1899). + + Used in a write scope for a table that holds rows and whose record is known: + an operation that answers from the run's key index or rows read opens nothing. A + snapshot opened at its first use is at least as recent as one opened when the table + was judged, so it holds every append the judgment's snapshot held. + + Args: + table_id: The table's id. + open_by_id: Opens a table by id. + """ + + def __init__(self, table_id: str, open_by_id: Callable[[str], _KeyedTable]) -> None: + self._table_id: str = table_id + self._open_by_id: Callable[[str], _KeyedTable] = open_by_id + self._opened: _KeyedTable | None = None + + def open(self) -> _KeyedTable: + """Return the SDK snapshot, opening it by ID on first use.""" + if self._opened is None: + self._opened = self._open_by_id(self._table_id) + return self._opened + + @property + def resource_id(self) -> str: + """Return the known table ID without opening the snapshot.""" + return self._table_id + + @property + def key_columns(self) -> tuple[str, ...]: + """Return the key columns, opening the snapshot on first use.""" + return self.open().key_columns + + def schema(self) -> pa.Schema: + """Return the schema, opening the snapshot on first use.""" + return self.open().schema() + + def get_metadata(self) -> dict[str, bytes]: + """The table's metadata entries, as stored.""" + return self.open().get_metadata() + + def set_metadata(self, metadata: dict[str, bytes]) -> None: + """Record metadata entries (an upsert of the given keys).""" + self.open().set_metadata(metadata) + + def scan( + self, + columns: list[str] | None = None, + *, + filter: Any = None, # pyright: ignore[reportExplicitAny] # an SDK expression + limit: int | None = None, + ) -> _Scan: + """A read of the snapshot (``_KeyedTable.scan``).""" + return self.open().scan(columns, filter=filter, limit=limit) + + def append(self, data: pa.Table) -> _KeyedTable: + """Write rows (``_KeyedTable.append``).""" + return self.open().append(data) + + _Seen = tuple[str, object] """What a table recorded when judged: ``("none", None)``, ``("manifest", manifest)``, or ``("unreadable", header bytes)`` for a manifest that cannot be decoded (never equal to @@ -225,9 +373,12 @@ class SpiralDBTables: dataset: The dataset. open_table: Opens a keyed table by name; ``None`` when there is none. open_table_by_id: Opens a keyed table by its id. - create_table: Creates a keyed table in the dataset, by name and key schema. + create_table: Creates a keyed table in the dataset, by name and key schema, + and returns it. list_tables: Lists the dataset's keyed tables: names by table id. service_call: A context that notes on a failing SDK call what it was doing. + one_call_scope: Opens a scope for a direct write. Pass ``True`` to join the + enclosing invocation's scope when it has one. """ def __init__( @@ -237,18 +388,23 @@ def __init__( dataset: str, open_table: Callable[[str], _KeyedTable | None], open_table_by_id: Callable[[str], _KeyedTable], - create_table: Callable[[str, pa.Schema], object], + create_table: Callable[[str, pa.Schema], _KeyedTable], list_tables: Callable[[], dict[str, str]], service_call: Callable[[str], AbstractContextManager[None]], + one_call_scope: Callable[[bool], AbstractContextManager[None]], ) -> None: self._sdk: Any = sdk # pyright: ignore[reportExplicitAny] self._project_id: str = project_id self._dataset: str = dataset self._open_table: Callable[[str], _KeyedTable | None] = open_table self._open_table_by_id: Callable[[str], _KeyedTable] = open_table_by_id - self._create_table: Callable[[str, pa.Schema], object] = create_table + self._create_table: Callable[[str, pa.Schema], _KeyedTable] = create_table self._list_tables: Callable[[], dict[str, str]] = list_tables self._service_call: Callable[[str], AbstractContextManager[None]] = service_call + # Opens a scope of these tables alone, for a write outside a run. + self._one_call_scope: Callable[[bool], AbstractContextManager[None]] = ( + one_call_scope + ) self._paths: dict[str, tuple[str, ...]] = {} self._ids_by_name: dict[str, str] = {} # What a table that holds rows records, by its id: a table's key, record and @@ -263,9 +419,9 @@ def __init__( # can change what this one judged (a table with no rows stays one, and what it # recorded stays what its first write compares with). self._now: threading.local = threading.local() - # The check of the writer lease a run holds for this dataset - # (``spiraldb_write_scope``); ``None`` when no run holds one. - self._lease_check: WriterLease | None = None + # The state of the scope these tables are written in + # (``spiraldb_write_scope``); ``None`` outside one. + self._attached_run: RunState | None = None key_column: str = codec.KEY_COLUMN """The key column of every database table.""" @@ -447,25 +603,25 @@ def _forget_opened(self, table_name: str) -> None: _ = commits.pop(table_name, None) def _commits_now(self) -> dict[str, int | None] | None: - """The lease's commit count when each name was judged in this thread's - operation (``WriterLease.commits``); ``None`` outside one.""" + """The run's commit count when each name was judged in this thread's + operation (``RunState.commits``); ``None`` outside one.""" return cast("dict[str, int | None] | None", getattr(self._now, "commits", None)) def _snapshot_is_current(self, table_name: str) -> bool: """Whether the snapshot this operation holds for a name was opened after every - append the lease's connectors have made (called under the lease's lock). + append the scope's connectors have made (called under the scope's lock). Args: table_name: A name this operation judged. """ - lease = self._lease_check + run = self._run_state commits = self._commits_now() opened_at = None if commits is None else commits.get(table_name) return ( - lease is not None + run is not None and opened_at is not None and opened_at % 2 == 0 - and opened_at == lease.commits + and opened_at == run.commits ) # ── finding a table ────────────────────────────────────────────────────── @@ -484,7 +640,7 @@ def _judge(self, table_name: str) -> _Opened | None: judgment = self._judgment(table_name) return judgment if isinstance(judgment, _Opened) else None - def _judgment(self, table_name: str) -> _Judgment: + def _judgment(self, table_name: str, *, refresh: bool = False) -> _Judgment: """What the name holds now: a table with rows of this path, a table with none (``_New``, with what it recorded), or no table (``None``). @@ -493,6 +649,7 @@ def _judgment(self, table_name: str) -> _Judgment: Args: table_name: A name ``table_name`` returned. + refresh: Judge the name independently of the current operation's snapshots. Returns: The judgment. @@ -501,12 +658,14 @@ def _judgment(self, table_name: str) -> _Judgment: SpiralTableCollisionError: If the table's key is not the database's, it records another path or format, or it holds rows without a manifest. """ - judged = self._judged_now() + judged = None if refresh else self._judged_now() if judged is not None and table_name in judged: return judged[table_name] - lease = self._lease_check + run = self._run_state + if run is not None: + _ = run.get_catalog(self._list_dataset) # Read before the snapshot is opened (``_snapshot_is_current``). - commits_before = None if lease is None else lease.commits + commits_before = None if run is None else run.commits with self._about(table_name): judgment = self._judge_table(table_name, self._path_of(table_name)) if judged is not None: @@ -526,24 +685,39 @@ def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Judgment: Returns: The judgment. """ + run = self._run_state + resolved = self._resolved_id(table_name) + if run is not None and resolved is not None: + known = self._known(resolved) + if known is not None and known.record.path == path: + # With one writer nothing but the scope writes it: opened when used. + return _Opened(known, _LazySnapshot(resolved, self._open_table_by_id)) table = self._open_snapshot(table_name) if table is None: return None table_id = str(table.resource_id) - known = self._found_by_id.get(table_id) + known = self._known(table_id) if known is not None and known.record.path == path: - self._ids_by_name[table_name] = table_id + self._resolve(table_name, table_id) return _Opened(known, table) _require_key(table, self._service_call) - with self._service_call("read the metadata of a database table"): - metadata = table.get_metadata() + catalog = None if run is None else run.catalog + listed = None if catalog is None else catalog.metadata.get(table_id) + if listed is not None: + # The run's listing read it, and found it holding rows. + metadata = listed + else: + with self._service_call("read the metadata of a database table"): + metadata = table.get_metadata() record = identity.read_table_identity_metadata(metadata) if record is not None: identity.require_table_path(record, path) - if not _holds_rows(table, self._service_call, [codec.KEY_COLUMN], metadata): + if listed is None and not _holds_rows( + table, self._service_call, [codec.KEY_COLUMN], metadata + ): # New: its first write records it, unless what it saw here changed. new = _New(_seen_manifest(metadata, path), record) - self._ids_by_name[table_name] = table_id + self._resolve(table_name, table_id) return new try: manifest = None if record is None else codec.read_manifest(metadata, path) @@ -552,14 +726,58 @@ def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Judgment: if record is None or manifest is None: raise SpiralTableCollisionError("it holds rows but no table manifest") found = _Found(table_id, record, manifest) - self._found_by_id[found.table_id] = found - self._ids_by_name[table_name] = table_id + self._remember(found) + self._resolve(table_name, table_id) return _Opened(found, table) + def _resolved_id(self, table_name: str) -> str | None: + """The id a name was resolved to, by this database or the run.""" + table_id = self._ids_by_name.get(table_name) + run = self._run_state + if table_id is None and run is not None: + table_id = run.ids_by_name.get(table_name) + return table_id + + def _resolve(self, table_name: str, table_id: str) -> None: + """Record the id a name resolved to, here and for the run.""" + self._ids_by_name[table_name] = table_id + if (run := self._run_state) is not None: + run.ids_by_name[table_name] = table_id + + def _known(self, table_id: str) -> _Found | None: + """What a table holding rows records, as this database or the run read it.""" + known = self._found_by_id.get(table_id) + run = self._run_state + if known is None and run is not None: + known = run.found_by_id.get(table_id) + return known + + def _remember(self, found: _Found) -> None: + """Keep what a table holding rows records, here and for the run.""" + self._found_by_id[found.table_id] = found + if (run := self._run_state) is not None: + run.found_by_id[found.table_id] = found + + def _forget(self, table_id: str) -> None: + """Forget what a table records, here and for the run.""" + _ = self._found_by_id.pop(table_id, None) + if (run := self._run_state) is not None: + _ = run.found_by_id.pop(table_id, None) + + def _shows_absent(self, table_name: str) -> bool: + """Whether the run's listing shows no table under the name (ITL-1899): a + table the run creates or writes is listed as it is made.""" + run = self._run_state + catalog = None if run is None else run.catalog + return catalog is not None and catalog.shows_absent(table_name) + def _open_snapshot(self, table_name: str) -> _KeyedTable | None: - """Open by name until it is resolved, then open snapshots by ID.""" - if (table_id := self._ids_by_name.get(table_name)) is not None: + """Open by name until it is resolved, then open snapshots by ID; nothing for a + name the run's listing shows absent.""" + if (table_id := self._resolved_id(table_name)) is not None: return self._open_table_by_id(table_id) + if self._shows_absent(table_name): + return None return self._open_table(table_name) def has_table(self, table_name: str) -> bool: @@ -606,16 +824,15 @@ def table_paths( """ start = identity.spiral_table_name_prefix(prefix) found = {p for p in pending if p[: len(prefix)] == prefix} - lease = self._lease_check - with lease.lock if lease is not None else nullcontext(): - if lease is None: + run = self._run_state + with run.lock if run is not None else nullcontext(): + if run is None: catalog = _Catalog(self._list_dataset()) else: - # The run's one listing, kept with the lease: every connector of the + # The run's one listing, kept with the run: every connector of the # dataset under it, on any thread, updates it as it writes. - if lease.catalog is None: - lease.catalog = _Catalog(self._list_dataset()) - catalog = lease.catalog + catalog = run.get_catalog(self._list_dataset, required=True) + assert catalog is not None self._collect_paths(catalog, start, prefix, found) return sorted(found) @@ -639,7 +856,7 @@ def _collect_paths( if not table_name.startswith(start): continue with self._about(table_name): - read = self._record_of(table_id, table_name, catalog.records) + read = self._record_of(table_id, table_name, catalog) if read is None: continue record, table_format = read @@ -652,6 +869,7 @@ def _collect_paths( found.add((*record.path[:-1], last)) def _list_dataset(self) -> dict[str, str]: + """List the dataset's table names by ID from the service.""" with self._service_call("list the database tables"): return self._list_tables() @@ -659,7 +877,7 @@ def _record_of( self, table_id: str, table_name: str, - run_records: dict[str, tuple[identity.TableRecord, str]], + catalog: _Catalog, ) -> tuple[identity.TableRecord, str] | None: """The record of a listed table and the table format it names, read once per id; ``None`` without one, or when the table holds no rows. @@ -671,9 +889,15 @@ def _record_of( Args: table_id: The listed table's id. table_name: The name it is listed under. - run_records: Records already judged on another connector this run. + catalog: The listing it is in, with the records already judged on + another connector this run; the metadata read here of a table of this + format that holds rows is kept there for the run's judgment. """ + run_records = catalog.records read = self._records_by_id.get(table_id) or run_records.get(table_id) + if read is None and (known := self._known(table_id)) is not None: + # Judged holding rows already (ITL-1899). + read = (known.record, identity.TABLE_FORMAT) table: _KeyedTable | None = None metadata: dict[str, bytes] = {} if read is None: @@ -703,6 +927,8 @@ def _record_of( metadata if columns is not None else {}, ): return None # never kept: its rows may be written later + if columns is not None: + catalog.metadata[table_id] = metadata self._records_by_id[table_id] = run_records[table_id] = read return read @@ -769,6 +995,11 @@ def scan(self, table_name: str) -> Iterator[pa.RecordBatch]: Args: table_name: A name ``table_name`` returned. + In a write scope the rows a read returned are kept for the scope and read + from there again, until an append to the table starts (``RunState``, + ITL-1899): they are kept only from a snapshot that held every append the run + made, so a read from them gives what a fresh read would. + Raises: KeyError: If there is no table at the name. """ @@ -779,13 +1010,46 @@ def scan(self, table_name: str) -> Iterator[pa.RecordBatch]: return # it exists, with no rows found = opened.found schema = _live(found.manifest.schema, found.record.data_context_key) - with self._about(table_name), self._service_call("read a database table"): - stored = opened.table.scan().to_table() + run = self._run_state + stored = None + if run is not None: + with run.lock: + stored = run.rows_by_table.get(found.table_id) + if stored is None: + with self._about(table_name), self._service_call("read a database table"): + stored = opened.table.scan().to_table() + if run is not None: + self._keep_read(table_name, found.table_id, stored) if stored.num_rows == 0: return rows = codec.decode_rows(stored, found.manifest, schema) yield from rows.to_batches() + def _keep_read(self, table_name: str, table_id: str, stored: pa.Table) -> None: + """Keep the rows a whole read of a table returned for the run, + when the snapshot read held every append the run made (``scan``). + + Args: + table_name: The name the operation judged. + table_id: The table's id. + stored: The rows, as the service returned them. + """ + run = self._run_state + assert run is not None + with run.lock: + if not self._snapshot_is_current(table_name): + return + if stored.nbytes > KEPT_ROWS_BUDGET_BYTES: + return # read again when needed + kept = run.rows_by_table + _ = kept.pop(table_id, None) + total = sum(rows.nbytes for rows in kept.values()) + stored.nbytes + for oldest in list(kept): + if total <= KEPT_ROWS_BUDGET_BYTES: + break + total -= kept.pop(oldest).nbytes + kept[table_id] = stored + def existing_record_ids( self, table_name: str, ids: Collection[bytes] ) -> set[bytes]: @@ -807,14 +1071,23 @@ def existing_record_ids( """ if not ids: return set() - lease = self._lease_check + run = self._run_state with ( - lease.lock if lease is not None else nullcontext(), + run.lock if run is not None else nullcontext(), self._about(table_name), ): judged = self._judged_now() reused = judged is not None and table_name in judged opened = self._judge(table_name) + if opened is None and reused and run is not None: + if (table_id := run.table_ids.get(table_name)) is not None: + return self._indexed_keys(run, table_id).intersection(ids) + if not self._snapshot_is_current(table_name): + # An append with a lost reply can leave no key index. Recheck + # without replacing the operation's snapshot for other readers. + judgment = self._judgment(table_name, refresh=True) + opened = judgment if isinstance(judgment, _Opened) else None + reused = False if opened is None: return set() # A snapshot this operation opened earlier can predate another @@ -824,12 +1097,12 @@ def existing_record_ids( def holds_record_id(self, table_name: str, record_id: bytes) -> bool | None: """Whether the table at ``table_name`` holds a committed row of ``record_id``, - as the run's lease-wide key index has it; ``None`` when no lease is attached. + as the scope's key index has it; ``None`` outside a scope. - The index is updated by every append any connector of the lease commits, on + The index is updated by every append any connector of the run commits, on any thread, so a row committed during the run is seen at once. A name or a key set the index does not hold yet is read from a snapshot opened under the - lease's lock: one open of the name, and one read of its key column when it + run's lock: one open of the name, and one read of its key column when it holds rows. Args: @@ -837,154 +1110,178 @@ def holds_record_id(self, table_name: str, record_id: bytes) -> bool | None: record_id: A record id. Returns: - Whether it is held, or ``None`` without a lease. + Whether it is held, or ``None`` without a run. """ - lease = self._lease_check - if lease is None: + run = self._run_state + if run is None: return None - with lease.lock, self._about(table_name): - if table_name not in lease.table_ids: + with run.lock, self._about(table_name): + if table_name not in run.table_ids: self._forget_opened(table_name) opened = self._judge(table_name) if opened is None: - lease.table_ids[table_name] = None + run.table_ids[table_name] = None return False - lease.table_ids[table_name] = opened.found.table_id + run.table_ids[table_name] = opened.found.table_id return bool(self._held_ids(opened.table, (record_id,), fresh=True)) - table_id = lease.table_ids[table_name] + table_id = run.table_ids[table_name] if table_id is None: return False - held = lease.keys_by_table.get(table_id) - if held is None: - # Forgotten after an ambiguous append: read again from a snapshot - # opened now, under the lock. - held = self._scan_keys(self._open_table_by_id(table_id)) - lease.keys_by_table[table_id] = held - return record_id in held + return record_id in self._indexed_keys(run, table_id) def _held_ids( self, table: _KeyedTable, ids: Collection[bytes], *, fresh: bool ) -> set[bytes]: """The ids among ``ids`` the table holds (``existing_record_ids``). - Under a lease, the answer comes from the lease-wide key index, which every - committed append of the lease's connectors updates. On a miss the index is - filled from a snapshot taken under the lease's lock: ``table`` itself when the - caller opened it under that lock (``fresh``), a newly opened one otherwise. + Under a run, the answer comes from the run-wide key index, which every + committed append of the scope's connectors updates. On a miss the index is + filled from kept rows or a snapshot taken under the scope's lock: ``table`` + itself when the caller opened it under that lock (``fresh``), a newly opened + one otherwise. Args: table: The snapshot opened under the table's name. ids: Record ids. - fresh: Whether ``table`` was opened while the caller held the lease's lock, - after every append the lease's connectors have committed. + fresh: Whether ``table`` was opened while the caller held the run's lock, + after every append the scope's connectors have committed. Returns: The ids it holds. """ - lease = self._lease_check - if lease is None: + run = self._run_state + if run is None: return self._scan_keys(table).intersection(ids) table_id = str(table.resource_id) - with lease.lock: - held = lease.keys_by_table.get(table_id) - if held is None: - # The lease-wide index is filled from a snapshot opened now, under - # the lock: never from one this operation opened earlier, which - # can predate a commit (an ambiguous append) by another connector. - current = table if fresh else self._open_table_by_id(table_id) - held = self._scan_keys(current) - lease.keys_by_table[table_id] = held - return held.intersection(ids) + with run.lock: + return self._indexed_keys( + run, table_id, table if fresh else None + ).intersection(ids) + + def _indexed_keys( + self, run: RunState, table_id: str, fresh: _KeyedTable | None = None + ) -> set[bytes]: + """Build a missing key index on demand while the caller holds the run lock.""" + keys = run.keys_by_table.get(table_id) + if isinstance(keys, set): + return keys + if keys is None: + stored = run.rows_by_table.get(table_id) + if stored is not None: + held = _keys_of(stored.column(codec.KEY_COLUMN)) + else: + snapshot = ( + fresh if fresh is not None else self._open_table_by_id(table_id) + ) + held = self._scan_keys(snapshot) + else: + held = _keys_of(keys) + run.keys_by_table[table_id] = held + return held def _scan_keys(self, table: _KeyedTable) -> set[bytes]: """Every key a snapshot holds: one read of the key column alone.""" with self._service_call("read the keys of a database table"): stored = table.scan([codec.KEY_COLUMN]).to_table() - return set( - cast( - "list[bytes]", - stored.column(codec.KEY_COLUMN).cast(pa.large_binary()).to_pylist(), - ) - ) + return _keys_of(stored.column(codec.KEY_COLUMN)) # ── writing ────────────────────────────────────────────────────────────── - def hold_lease(self, check: WriterLease) -> None: - """Let this dataset be written under a lease a run holds (``spiraldb_write_scope``). + @property + def _run_state(self) -> RunState | None: + state = self._attached_run + return state if state in active_run_states.get() else None + + @contextmanager + def write_scope(self, *, invocation: bool = False) -> Iterator[None]: + """Use the current run scope or open one for this write call.""" + if self._run_state is not None: + yield + else: + with self._one_call_scope(invocation): + yield + + def attach_run(self, state: RunState) -> None: + """Write these tables in a scope (``spiraldb_write_scope``). Args: - check: Verifies the lease at its first use; raises if it is not held. + state: The scope's state of this dataset. Raises: - RuntimeError: If a lease is held for these tables already. + RuntimeError: If these tables are in a scope already. """ - if self._lease_check is not None: - raise RuntimeError( - "these database tables are already written under a lease" - ) + if self._attached_run is not None: + raise RuntimeError("these database tables are already in a write scope") # A table may have been replaced since this connector last used its name. self._ids_by_name.clear() - self._lease_check = check + self._attached_run = state + + def acquire_write_lock(self) -> None: + """Acquire the scope's write lock before an invocation.""" + with self.write_scope(invocation=True): + state = self._run_state + assert state is not None + state.acquire_lock() - def let_go_of_lease(self, check: WriterLease) -> None: - """Stop writing under the lease ``hold_lease`` was given ``check`` for. + def detach_run(self, state: RunState) -> None: + """Leave the scope ``attach_run`` was given ``state`` for. Args: - check: The check given to ``hold_lease``; any other leaves the lease held. + state: The state given to ``attach_run``; any other is left attached. """ - if self._lease_check is check: - self._lease_check = None - - def _require_lease(self) -> WriterLease: - """Require an attached writer lease and verify it at its first use. + if self._attached_run is state: + self._attached_run = None - The lease is held by the writable connectors of the run that took it: a write - through any other connector to the dataset is refused, also while that run - holds the lease. A write through the run's own connectors is the run's (its - databases, its cached sources); the lease does not tell its callers apart. + def _acquire_lock(self) -> None: + """Acquire the scope's write lock before a create or an append (once).""" + state = self._run_state + assert state is not None # ``write`` runs in a scope + state.acquire_lock() - Raises: - SpiralDBLeaseRequiredError: If no run holds the lease. - LeaseError: If the lease is no longer held (``spiraldb_lease.check``). - """ - check = self._lease_check - if check is None: - raise SpiralDBLeaseRequiredError( - f"this writable SpiralDB connector holds no writer lease of dataset " - f"{self._project_id}/{self._dataset}: a writable SpiralDB database is " - "written only through the connectors of a job run (job.run(), job.run_async() or a " - "job node's run()), which takes the lease; nothing was written" - ) - check() - return check - - def _create_or_open(self, table_name: str) -> _KeyedTable: + def _create_or_open(self, table_name: str) -> tuple[_KeyedTable, bool]: """The table at a computed name, created now if absent. + A name the run's listing shows absent is created without opening it first + (ITL-1899): the create is exclusive, so a table made meanwhile is still found. + Args: table_name: A name ``table_name`` returned. Returns: - The table, as opened under the name after any creation. + The table, and whether this call created it: then it is the table the + create returned, new (no metadata, no rows); otherwise as opened under the + name. Raises: KeyError: If no table is under the name even after it was created. """ table = self._open_snapshot(table_name) if table is not None: - return table + return table, False key = pa.schema([pa.field(codec.KEY_COLUMN, pa.large_binary(), nullable=False)]) try: with self._service_call(f"create {table_name}"): - _ = self._create_table(table_name, key) + created = self._create_table(table_name, key) except self._sdk.SpiralError as exc: # pyright: ignore[reportAny] if "status 409" not in str(exc): # pyright: ignore[reportAny] raise # Made meanwhile: the caller compares it with what it judged. - table = self._open_snapshot(table_name) + else: + self._listed(str(created.resource_id), table_name) + return created, True + # Opened by name: a table the listing missed is resolved here. + table = self._open_table(table_name) if table is None: raise KeyError(f"no database table {self._qualified(table_name)}") - return table + self._listed(str(table.resource_id), table_name) + return table, False + + def _listed(self, table_id: str, table_name: str) -> None: + """List a table this run created or found under a name in the run's listing.""" + run = self._run_state + if run is not None and run.catalog is not None: + with run.lock: + run.catalog.add(table_id, table_name) def _unchanged_since_judged( self, @@ -1001,7 +1298,7 @@ def _unchanged_since_judged( never overwritten. It narrows, and cannot close, the window in which two writers race: spiral-sdk has no compare-and-set, so another writer can still record the table between this read and the write. Concurrent writers are not - supported until the lease (ITL-1452). + supported (ITL-1899: one writer process per dataset is assumed). Args: table: The table, opened under its name. @@ -1071,9 +1368,9 @@ def write( on_append_error: Callable[[], None] | None = None, ) -> None: """Write rows whose keys the table does not hold yet; the first write creates the - table and records its identity and manifest. The lease keeps an index of the + table and records its identity and manifest. The run keeps an index of the keys already stored and the keys appended during the run. Concurrent writes - through different handles under a shared lease use the same index. + through different handles in one scope use the same index. What a table records is kept only once an append to it succeeded; a write that fails forgets it, so the next call judges the table again as the service has it @@ -1093,16 +1390,18 @@ def write( or not the one the table records (checked when they are buffered too). SpiralTableCollisionError: If the table under the name is not this path's database table. - SpiralDBLeaseRequiredError: If no job run holds the dataset's writer - lease; nothing is written. - LeaseError: If the lease the run took is no longer held. + SpiralDBScopeOpenError: If this write needs a scope of its own and another + scope of the dataset is open in this process; nothing is written. + Exception: Whatever the scope's ``WriteLock`` raises, before anything is + written. """ path = self._path_of(table_name) context = _one_data_context(records) - # Before anything is created or written: one writer per dataset (ITL-1844). - lease = self._require_lease() - with lease.lock: - self._write(table_name, path, context, records, on_append_error) + with self.write_scope(): + run = self._run_state + assert run is not None + with run.lock: + self._write(table_name, path, context, records, on_append_error) def _write( self, @@ -1112,7 +1411,7 @@ def _write( records: pa.Table, on_append_error: Callable[[], None] | None, ) -> None: - """Write records while holding the lease's lock.""" + """Write records while holding the run's lock.""" # A caller's schema check may have written rows since the earlier snapshot # in this operation. Open a current snapshot under the resolved identity. self._forget_opened(table_name) @@ -1155,7 +1454,8 @@ def _write( held = self._held_ids(opened.table, _ids(records), fresh=True) encoded = _encoded(_without_ids(records, held)) if encoded.num_rows == 0: - return # a write of no rows is never sent + return # a write of no rows is never sent, and takes no lock + self._acquire_lock() self._forget_opened(table_name) self._append(opened.table, found, encoded, on_append_error) @@ -1189,11 +1489,18 @@ def _write_first( } encoded = _encoded(records) if encoded.num_rows == 0: - return # nothing to write, so nothing is created + return # nothing to write, so nothing is created or locked + self._acquire_lock() self._forget_opened(table_name) - table = self._create_or_open(table_name) - _require_key(table, self._service_call) - first_append = self._unchanged_since_judged(table, path, seen, seen_record) + table, created = self._create_or_open(table_name) + if created and seen == ("none", None) and seen_record is None: + # Judged absent and made by this write's exclusive create: new, with the + # key it was given, so as judged; nothing to read back (ITL-1899). + first_append = True + else: + if not created: + _require_key(table, self._service_call) + first_append = self._unchanged_since_judged(table, path, seen, seen_record) if first_append: with self._service_call("record a database table"): table.set_metadata(metadata) @@ -1235,40 +1542,49 @@ def _append( encoded: The rows, encoded. on_append_error: Called if the SDK append of the rows raises. """ - lease = self._lease_check - assert lease is not None + run = self._run_state + assert run is not None # A full slice can still hold a nonzero offset on an empty string or # binary child of a list. Arrow's take copies the physical columns and # rebases their children before handing the batch to spiral-sdk 0.16. batch = encoded.take(pa.array(range(encoded.num_rows), pa.int64())) - lease.commits += 1 # odd while the append is in flight + # A failed snapshot read must not trigger ordered append retries. + if isinstance(table, _LazySnapshot): + with self._service_call("open a database table snapshot"): + table = table.open() + # The rows a read kept no longer are the table's, whatever the append does. + _ = run.rows_by_table.pop(found.table_id, None) + run.commits += 1 # odd while the append is in flight try: with self._service_call("write a database table"): _ = table.append(batch) except BaseException: # The service may hold the rows, some, or none: judged again next call. - _ = self._found_by_id.pop(found.table_id, None) - _ = lease.keys_by_table.pop(found.table_id, None) - _ = lease.table_ids.pop(identity.spiral_table_name(found.record.path), None) - if (catalog := lease.catalog) is not None: + self._forget(found.table_id) + _ = run.keys_by_table.pop(found.table_id, None) + _ = run.table_ids.pop(identity.spiral_table_name(found.record.path), None) + if (catalog := run.catalog) is not None: # A first append that committed before its reply was lost leaves a # table the run's listing has not seen: list it, unjudged, so the # next listing asks whether it holds rows. - _ = catalog.names.setdefault( + catalog.add( found.table_id, identity.spiral_table_name(found.record.path) ) if on_append_error is not None: on_append_error() raise finally: - lease.commits += 1 - lease.keys_by_table.setdefault(found.table_id, set()).update(_ids(encoded)) - lease.table_ids[identity.spiral_table_name(found.record.path)] = found.table_id - self._found_by_id[found.table_id] = found - if (catalog := lease.catalog) is not None: - _ = catalog.names.setdefault( - found.table_id, identity.spiral_table_name(found.record.path) - ) + run.commits += 1 + keys = run.keys_by_table.get(found.table_id) + if isinstance(keys, set): + keys.update(_ids(encoded)) + else: + # The first append has no stored keys to merge. + run.keys_by_table[found.table_id] = batch.column(codec.KEY_COLUMN) + run.table_ids[identity.spiral_table_name(found.record.path)] = found.table_id + self._remember(found) + if (catalog := run.catalog) is not None: + catalog.add(found.table_id, identity.spiral_table_name(found.record.path)) catalog.records[found.table_id] = (found.record, identity.TABLE_FORMAT) @@ -1356,6 +1672,11 @@ def _holds_rows( return keys.num_rows > 0 +def _keys_of(column: pa.ChunkedArray[Any]) -> set[bytes]: + """Convert a stored key column to a membership set.""" + return set(cast("list[bytes]", column.cast(pa.large_binary()).to_pylist())) + + def _ids(records: pa.Table) -> list[bytes]: """The record ids of rows, in row order.""" return cast("list[bytes]", records.column(codec.KEY_COLUMN).to_pylist()) diff --git a/src/orcapod/databases/spiraldb_writable_registry.py b/src/orcapod/databases/spiraldb_writable_registry.py index e6f125881..1c7e52ff3 100644 --- a/src/orcapod/databases/spiraldb_writable_registry.py +++ b/src/orcapod/databases/spiraldb_writable_registry.py @@ -1,6 +1,6 @@ """Which writable SpiralDB connectors exist in this process (ITL-1844). -A run takes the writer lease of every writable SpiralDB database it may write +A run opens a write scope for every writable SpiralDB database it may write (``spiraldb_write_scope.database_writes``), found by walking the run's graph. A writable database always holds its writable connector, so when no writable connector exists in the process no run can write one, and the run skips the walk diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index 201a01807..ce9d53a66 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -1,32 +1,66 @@ -"""The writer leases a job run holds on the writable SpiralDB databases it writes -(ITL-1844). - -A writable SpiralDB database (``SpiralDBConnector(..., writable=True)``) has one writer -at a time. A job run (``job.run()``, ``job.run_async()`` or a job node's ``run()``) -takes the writer lease of every writable dataset it may write (``database_writes``) -before it checks a source, computes or writes anything, and releases each lease when it -ends, also when it fails. A second writer is refused when it asks for the lease -(``LeaseBusyError``), so before it writes. A database write with no lease held is -refused (``SpiralDBLeaseRequiredError``, raised by ``spiraldb_tables``). - -One lease per dataset: several writable connectors on one dataset (a job's database and -its result database, a cached source's database) share the one lease the run takes. The -lease is refuse-only: no waiting, no taking over, no expiry (``spiraldb_lease``). +"""The write scopes of writable SpiralDB databases (ITL-1899). + +A writable SpiralDB database (``SpiralDBConnector(..., writable=True)``) is written by +one writer process at a time: Orcapod assumes it and does not check it. Concurrent +writers in several processes are not supported; with two, a run can store results +twice, deliver side effects twice, and overwrite a cached source instead of refusing. + +Every write happens in a scope of its dataset. A job run (``job.run()``, +``job.run_async()`` or a job node's ``run()``) opens one scope per writable dataset it +may write (``database_writes``), for the whole run; a write outside a run (a +``CachedSource`` read outside a run, a ``ConnectorArrowDatabase`` flushed directly) +opens one of its own for that call (``one_call_scope``). A scope's state +(``spiraldb_tables.RunState``) holds what the scope read of the dataset: the key index, +the catalog (one listing of the dataset on first use) and the kept reads. It is +shared by the scope's connectors of the dataset, and forgotten when the scope ends. + +At most one scope of a dataset is open in a process. Cache stores used in the same +invocation join its open scope and share its key index and lock. A different execution +opening a scope on the same dataset raises ``SpiralDBScopeOpenError`` before it reads +or writes that dataset. + +Each scope calls its dataset's ``WriteLock`` (``write_lock``; ``NoWriteLock`` by +default): ``acquire`` before the scope's first create or append to the dataset, and +before a side-effect node's first delivery or a context-taking function's first call +(``SpiralDBRunLookupProtocol.spiral_acquire_write_lock``); ``release`` when the scope +ends, also when it fails, only after an ``acquire`` that returned. A scope that writes +nothing acquires nothing. An error ``acquire`` raises is what the run raises, unchanged, +whichever error wrapped it on the way (a node's commit). """ from __future__ import annotations import contextlib import threading -from collections.abc import Callable, Iterable, Iterator -from typing import TYPE_CHECKING, Any +from asyncio import CancelledError +from collections.abc import Iterable, Iterator +from contextvars import ContextVar +from typing import TYPE_CHECKING -from orcapod.databases import spiraldb_lease -from orcapod.databases.spiraldb_connector import require_same_process -from orcapod.databases.spiraldb_tables import WriterLease +from orcapod.databases.spiraldb_tables import RunState, active_run_states +from orcapod.databases.write_lock import NoWriteLock, WriteLockHandle +from orcapod.errors import OrcapodDatabaseWriteError, SpiralDBScopeOpenError +from orcapod.protocols.spiraldb_run import invocation_boundary if TYPE_CHECKING: from orcapod.databases.spiraldb_connector import SpiralDBConnector + from orcapod.databases.spiraldb_tables import SpiralDBTables + +_open_scopes: dict[tuple[str, str], _DatasetScope] = {} +"""Open scopes by (project, dataset) in this process.""" + +_open_scopes_lock = threading.Lock() + + +_invocation_scopes: ContextVar[dict[tuple[str, str, str], _DatasetScope]] = ContextVar( + "spiraldb_invocation_scopes", default={} +) +"""The dataset scopes that cache writes can join in their current execution.""" + +_source_streams: ContextVar[frozenset[int]] = ContextVar( + "spiraldb_source_streams", default=frozenset() +) +"""The source streams delegated by the current execution's job graph.""" def writable_connectors(databases: Iterable[object]) -> list[SpiralDBConnector]: @@ -44,177 +78,336 @@ def writable_connectors(databases: Iterable[object]) -> list[SpiralDBConnector]: found: list[SpiralDBConnector] = [] for given in databases: - database = unwrap_database_views( - given - ) # a writable database under a library view is leased too + database = unwrap_database_views(given) # a library view's database too if not isinstance(database, ConnectorArrowDatabase): continue - connector = database._spiral_connector # pyright: ignore[reportPrivateUsage] # the database's connector, read by the one module that leases it + connector = database._spiral_connector # pyright: ignore[reportPrivateUsage] # the database's connector, read by the one module that scopes it if connector is not None and not any(connector is c for c in found): found.append(connector) return found @contextlib.contextmanager -def database_writes(databases: Iterable[object], *, owner: str) -> Iterator[None]: - """Hold the writer lease of every writable SpiralDB database dataset among - ``databases``. - - Every lease is acquired before the body runs; a refused one releases those already - taken and raises. Each lease is released when the body ends, also when it raises - (or is cancelled or interrupted). Every release is attempted, also after one fails - or is interrupted (also while letting go of the lease locally). An interruption of - a release (``KeyboardInterrupt``, ``CancelledError``, ``SystemExit``) is never - swallowed: it raises once every release was attempted, ahead of any ordinary - release failure, after a body that raised or was itself interrupted too (chained - from the body's error, which is its ``__cause__``). A release that fails with an error after the body raised is - added as a note to the body's error; after a body that succeeded the first failure - raises. +def database_writes( + databases: Iterable[object], *, source_streams: Iterable[object] = () +) -> Iterator[None]: + """Open one write scope per writable SpiralDB dataset among ``databases`` for the + body, attached to each of its connectors there. + + Each dataset is listed once on first use (the scope's catalog; a listing + that fails leaves the scope without one, and tables are then found by name). Its + ``WriteLock`` is acquired at the body's first write to it and released when the + body ends, also when it raises (or is cancelled or interrupted). Every release is + attempted, also after one fails or is interrupted. An interruption of a release + (``KeyboardInterrupt``, ``CancelledError``, ``SystemExit``) is never swallowed: it + raises once every release was attempted, ahead of any ordinary failure, chained from + the body's error when the body failed. A release that fails with an error after the + body raised is a note on the body's error; after a body that succeeded the first + failure raises. A body that failed because a lock's ``acquire`` raised raises that + error, whichever error wrapped it on the way. Args: databases: The databases the run may write. Nothing happens when none is a writable SpiralDB database. - owner: Who holds the leases, shown to a refused second writer. + source_streams: Live pod streams the job delegates to for its source rows. Raises: - LeaseBusyError: If another writer holds one of the datasets; nothing of the - body ran. - LeaseError: If a lease cannot be verified, or released after the body - succeeded (the run's writes are committed then; the message says how to - clear the lease). + SpiralDBScopeOpenError: If a scope of one of the datasets is open in this + process already; nothing of the body ran. + Exception: Whatever a ``WriteLock`` raises, unchanged; nothing was written to + that dataset after it. """ - groups: dict[tuple[str, str, str], list[SpiralDBConnector]] = {} - for connector in writable_connectors(databases): - groups.setdefault(connector._writer_lease_key(), []).append(connector) # pyright: ignore[reportPrivateUsage] # the lease is taken by this module only - held: list[tuple[list[Any], WriterLease, Callable[[], None]]] = [] # pyright: ignore[reportExplicitAny] # SpiralDBTables + token = _source_streams.set(frozenset(map(id, source_streams))) try: - for connectors in groups.values(): - # The database tables holding this lease, each once (every writable - # connector has its own, ``share_client`` copies too; a repeat is skipped - # all the same). - holding: list[Any] = [] # pyright: ignore[reportExplicitAny] # SpiralDBTables - - def register( - check: WriterLease, - release: Callable[[], None], - holding: list[Any] = holding, # pyright: ignore[reportExplicitAny] # SpiralDBTables - ) -> None: - held.append((holding, check, release)) - - # The claim is recorded in ``held`` inside the acquisition's guard: an - # interruption either finds it there or is reconciled by the acquisition. - check, _ = take_lease(connectors[0], owner, on_taken=register) - for connector in connectors: - tables = _tables(connector) - if not any(tables is t for t in holding): - # Recorded first, so an interruption once the lease is attached - # still lets go of it (a let-go clears only this check). - holding.append(tables) - tables.hold_lease(check) - except BaseException as error: - _release_all(held, error) - raise - try: - yield - except BaseException as error: - _release_all(held, error) - raise - _release_all(held, None) + with invocation_boundary(), _connector_scopes(writable_connectors(databases)): + yield + finally: + _source_streams.reset(token) + + +def stream_writes( + stream: object, databases: Iterable[object] +) -> contextlib.AbstractContextManager[None]: + """Join only for streams delegated by the current job's graph.""" + if id(stream) in _source_streams.get(): + return invocation_writes(databases) + return database_writes(databases) -def take_lease( - connector: SpiralDBConnector, - owner: str, - *, - on_taken: Callable[[WriterLease, Callable[[], None]], None] | None = None, -) -> tuple[WriterLease, Callable[[], None]]: - """Acquire the writer lease of a writable connector's dataset (``spiraldb_lease``). +@contextlib.contextmanager +def one_call_scope( + connector: SpiralDBConnector, *, invocation: bool = False +) -> Iterator[None]: + """Open a scope for one direct call, or join the enclosing invocation's scope. Args: connector: A writable SpiralDB connector. - owner: Who holds it, shown to a refused second writer. - on_taken: Optional: given ``(check, release)`` once the claim is acquired, - inside the acquisition's guard (``spiraldb_lease.acquire``'s ``on_claim``): - if it raises or is interrupted, the claim is released before the error - propagates. - - Returns: - ``(check, release)``: verifies the lease on first use; releases it. + invocation: Whether the call may join its execution's scope. Raises: - LeaseBusyError: If another writer holds the dataset. - LeaseError: If the claim cannot be verified. + SpiralDBScopeOpenError: If a scope of the dataset is open in this process. + Exception: Whatever its ``WriteLock`` raises, unchanged. """ - client, project_id, dataset = connector._writer_lease_target() # pyright: ignore[reportPrivateUsage] # the lease is taken by this module only - taken: list[tuple[WriterLease, Callable[[], None]]] = [] - - def claimed(lease: spiraldb_lease.Lease) -> None: - checked = False - lock = threading.Lock() + with _connector_scopes([connector], join=invocation): + yield - def check() -> None: - nonlocal checked - require_same_process(lease.pid) - with lock: - if not checked: - spiraldb_lease.check(client, lease) - checked = True - def release() -> None: - spiraldb_lease.release(client, lease) +def invocation_writes( + databases: Iterable[object], +) -> contextlib.AbstractContextManager[None]: + """Give an invocation one scope per dataset across all of its cache stores.""" + return _connector_scopes(writable_connectors(databases), join=True) - writer = WriterLease(check) - taken.append((writer, release)) - if on_taken is not None: - on_taken(writer, release) - _ = spiraldb_lease.acquire( - client, project_id, dataset, owner=owner, on_claim=claimed - ) - return taken[0] +@contextlib.contextmanager +def _connector_scopes( + writable: list[SpiralDBConnector], *, join: bool = False +) -> Iterator[None]: + """``database_writes`` over writable connectors.""" + groups: dict[tuple[str, str, str], list[SpiralDBConnector]] = {} + for connector in writable: + groups.setdefault(connector._write_scope_key(), []).append(connector) # pyright: ignore[reportPrivateUsage] # scopes are opened by this module only + inherited = _invocation_scopes.get() if join else {} + owned: dict[tuple[str, str, str], _DatasetScope] = {} + scopes: list[_DatasetScope] = [] + try: + for key, connectors in groups.items(): + enclosing = inherited.get(key) + if enclosing is not None and enclosing.join(connectors): + continue + scope = _DatasetScope(key, connectors) + owned[key] = scope + scopes.append(scope) + scope.open(connectors) + except BaseException as error: + _close_all(scopes, error) + raise + if join and not owned: + yield + return + invocation_token = _invocation_scopes.set(inherited | owned) + states = frozenset(s.state for s in scopes) + if join: + states |= active_run_states.get() + token = active_run_states.set(states) + try: + try: + yield + except BaseException as error: + refused = _refusal_behind(error, scopes) + _close_all(scopes, error if refused is None else refused) + if refused is None or refused is error: + raise + raise refused from None + _close_all(scopes, None) + finally: + active_run_states.reset(token) + _invocation_scopes.reset(invocation_token) + + +def _refusal_behind( + error: BaseException, scopes: list[_DatasetScope] +) -> BaseException | None: + """Recover a provider error when every exception leads to the same refusal.""" + refusals = [scope.refused for scope in scopes if scope.refused is not None] + + def find(current: BaseException, seen: set[int]) -> BaseException | None: + """Match every leaf of a group, guarding against cycles in chaining.""" + if id(current) in seen: + return None + if any(current is refusal for refusal in refusals): + return current + seen = seen | {id(current)} + if isinstance(current, BaseExceptionGroup): + first, *rest = current.exceptions + refusal = find(first, seen) + if refusal is not None and all( + find(child, seen) is refusal for child in rest + ): + return refusal + return None + cause = current.__cause__ + if cause is None and not current.__suppress_context__: + # Async orchestration can raise out of a task group's handler. + # A plain implicit context can just be an earlier, handled error. + context = current.__context__ + if isinstance(context, BaseExceptionGroup): + cause = context + return None if cause is None else find(cause, seen) + + if not refusals or not isinstance(error, Exception): + return None + return find(error, set()) + + +class _DatasetScope: + """One open write scope of a dataset in this process.""" + + def __init__( + self, key: tuple[str, str, str], connectors: list[SpiralDBConnector] + ) -> None: + _, self._project_id, self._dataset = key + providers = [ + connector.write_lock + for connector in connectors + if type(connector.write_lock) is not NoWriteLock + ] + self._lock = providers[0] if providers else connectors[0].write_lock + if any(provider is not self._lock for provider in providers): + raise ValueError( + f"Conflicting write lock providers for SpiralDB dataset " + f"{self._project_id}/{self._dataset}" + ) + self._reservation = (self._project_id, self._dataset) + self._handle: WriteLockHandle | None = None + self._holding: list[SpiralDBTables] = [] + self._registered = False + self._accepting_joins = False + self.refused: BaseException | None = None + self.state = RunState(self._acquire) + + def open(self, connectors: list[SpiralDBConnector]) -> None: + """Reserve the dataset and attach each tables object.""" + with _open_scopes_lock: + if self._reservation in _open_scopes: + raise SpiralDBScopeOpenError( + f"A write scope for SpiralDB dataset " + f"{self._project_id}/{self._dataset} is already open in this process" + ) + self._registered = True + _open_scopes[self._reservation] = self + for connector in connectors: + self._attach(_tables(connector)) + self._accepting_joins = True + + def join(self, connectors: list[SpiralDBConnector]) -> bool: + """Attach cache stores in the same invocation to this scope.""" + with self.state.lock: + if not self._accepting_joins: + return False + providers = [ + connector.write_lock + for connector in connectors + if type(connector.write_lock) is not NoWriteLock + ] + provider = self._lock + if ( + type(provider) is NoWriteLock + and self._handle is None + and self.refused is None + and providers + ): + provider = providers[0] + if any(given is not provider for given in providers): + raise ValueError( + f"Conflicting write lock providers for SpiralDB dataset " + f"{self._project_id}/{self._dataset}" + ) + self._lock = provider + for connector in connectors: + self._attach(_tables(connector)) + return True + + def _attach(self, tables: SpiralDBTables) -> None: + """Write ``tables`` in this scope (each object once).""" + if not any(tables is t for t in self._holding): + # Recorded first, so an interruption once attached still detaches it. + self._holding.append(tables) + tables.attach_run(self.state) + + def _acquire(self) -> None: + """Acquire the write lock on first use (under the state's lock, so racing + first writes on other threads acquire it once).""" + with self.state.lock: + if self.refused is not None: + raise OrcapodDatabaseWriteError(()) from self.refused + if self._handle is not None: + return + try: + self._handle = self._lock.acquire(self._project_id, self._dataset) + except (Exception, CancelledError) as refusal: + self.refused = refusal + # The orchestrators must treat a lock refusal as a database failure + # even when acquisition happens in a function's per-row path. + raise OrcapodDatabaseWriteError(()) from refusal + + def close(self) -> list[BaseException]: + """Detach every tables object, forget what the scope read, release the lock if + it was acquired and close the scope; every step attempted. + + Returns: + The failures, in order. + """ + failures: list[BaseException] = [] + try: + with self.state.lock: + self._accepting_joins = False + except BaseException as exc: # noqa: BLE001 # still attempt all cleanup + failures.append(exc) + self._accepting_joins = False + for tables in self._holding: + try: + tables.detach_run(self.state) + except BaseException as exc: # noqa: BLE001 # an interruption too: every step is attempted + failures.append(exc) + self._holding.clear() + try: + self.state.forget_reads() + except BaseException as exc: # noqa: BLE001 # reported with the others + failures.append(exc) + handle, self._handle = self._handle, None + if handle is not None: + try: + handle.release() + except BaseException as exc: # noqa: BLE001 # reported with the others + failures.append(exc) + while self._registered: + try: + with _open_scopes_lock: + # A retry can follow an interruption after removal and another + # scope may have reserved the dataset in the meantime. + if _open_scopes.get(self._reservation) is self: + del _open_scopes[self._reservation] + self._registered = False + except (KeyboardInterrupt, InterruptedError) as exc: + failures.append(exc) + return failures -def _tables(connector: SpiralDBConnector) -> Any: # pyright: ignore[reportExplicitAny] # SpiralDBTables; a writable connector always has them while open - tables = connector._writable_tables() # pyright: ignore[reportPrivateUsage] # the lease is handed to the database by this module only +def _tables(connector: SpiralDBConnector) -> SpiralDBTables: + tables = connector._writable_tables() # pyright: ignore[reportPrivateUsage] # scopes are opened by this module only if tables is None: raise RuntimeError("not a writable SpiralDB connector") return tables -def _release_all( - held: list[tuple[list[Any], WriterLease, Callable[[], None]]], # pyright: ignore[reportExplicitAny] # SpiralDBTables - error: BaseException | None, -) -> None: - """Let go of and release every lease in ``held``, each attempted whatever failed. +def _cleanup_failure_message(failure: BaseException) -> str: + """Describe a cleanup failure without masking the primary error.""" + try: + return str(failure) + except BaseException: # noqa: BLE001 # formatting must preserve the primary error + return type(failure).__name__ + + +def _close_all(scopes: list[_DatasetScope], error: BaseException | None) -> None: + """Close every scope in ``scopes``, each attempted whatever failed. Args: - held: The leases taken, with the database tables that hold each. + scopes: The scopes opened. error: The body's error, ``None`` when the body succeeded. Raises: BaseException: The first interruption (``KeyboardInterrupt``, - ``CancelledError``, ``SystemExit``) of a let-go or release, chained from - the body's error when the body failed (with an error or itself - interrupted); otherwise, after a successful body, the first failed - release. Any other failure is a note on the error raised (on the body's + ``CancelledError``, ``SystemExit``) while closing, chained from the body's + error when the body failed; otherwise, after a successful body, the first + failure. Any other failure is a note on the error raised (on the body's error when the body failed and nothing was interrupted). """ failures: list[BaseException] = [] - for holding, check, release in reversed(held): - for tables in holding: - try: - tables.let_go_of_lease(check) - except BaseException as exc: # noqa: BLE001 # an interruption too: the remote release is still attempted - failures.append(exc) - # Let go again (idempotent), so the next run on these tables is not - # refused for a lease still attached. - try: - tables.let_go_of_lease(check) - except BaseException as again: # noqa: BLE001 # reported with the others - failures.append(again) + for scope in reversed(scopes): try: - release() - except BaseException as exc: # noqa: BLE001 # an interrupted release too: every lease is released; failures are reported below + failures.extend(scope.close()) + except BaseException as exc: # noqa: BLE001 # close the remaining scopes failures.append(exc) if not failures: return @@ -223,7 +416,8 @@ def _release_all( # The body's error is raised by the caller; every failure is a note on it. for failure in failures: error.add_note( - f"Releasing the SpiralDB writer lease also failed: {failure}" + "Closing a SpiralDB write scope also failed: " + + _cleanup_failure_message(failure) ) return # An interruption outranks an ordinary failure: it stops the program. @@ -231,10 +425,9 @@ def _release_all( for failure in failures: if failure is not primary: primary.add_note( - f"Releasing another SpiralDB writer lease failed: {failure}" + "Closing another SpiralDB write scope failed: " + + _cleanup_failure_message(failure) ) if error is not None: - # An interruption after a body that failed (an error, or interrupted itself): - # the body's error is its cause. raise primary from error raise primary diff --git a/src/orcapod/databases/store_table_names.py b/src/orcapod/databases/store_table_names.py index 5d92b100b..25ee8e604 100644 --- a/src/orcapod/databases/store_table_names.py +++ b/src/orcapod/databases/store_table_names.py @@ -4,34 +4,12 @@ import hashlib import json -import re from collections.abc import Sequence SPIRAL_TABLE_NAME_LABEL = "spiral_table_name_v1" """The digest algorithm shared with SpiralDB. The name's grammar carries its version.""" STORE_TABLE_NAME_PREFIX = "o1_" -SPIRAL_LEASE_KEY_PREFIX = "orcapod_lease_v1_" -_SPIRAL_LEASE_TABLE_PREFIX = "orcapod_lease_v1_g" -_SPIRAL_LEASE_TABLE_PATTERN = re.compile(rf"{_SPIRAL_LEASE_TABLE_PREFIX}[1-9][0-9]*") -_SPIRAL_LEASE_KEY_PATTERN = re.compile(rf"{SPIRAL_LEASE_KEY_PREFIX}[0-9a-f]{{32}}") - - -def spiral_lease_table_name(generation: int) -> str: - """Return the reserved SpiralDB name for a writer lease generation.""" - return f"{_SPIRAL_LEASE_TABLE_PREFIX}{generation}" - - -def is_spiral_lease_table_name(name: str) -> bool: - """Return whether the name is reserved for a numbered lease generation.""" - return _SPIRAL_LEASE_TABLE_PATTERN.fullmatch(name) is not None - - -def spiral_lease_key_column(keys: Sequence[str]) -> str | None: - """Return the key bearing the lease signature, when present.""" - if len(keys) == 1 and _SPIRAL_LEASE_KEY_PATTERN.fullmatch(keys[0]) is not None: - return keys[0] - return None def require_store_path_domain(path: Sequence[str]) -> tuple[str, ...]: diff --git a/src/orcapod/databases/write_lock.py b/src/orcapod/databases/write_lock.py new file mode 100644 index 000000000..ef9570ae4 --- /dev/null +++ b/src/orcapod/databases/write_lock.py @@ -0,0 +1,38 @@ +"""The optional write lock for a writable SpiralDB dataset.""" + +from __future__ import annotations + +from typing import Protocol + + +class WriteLockHandle(Protocol): + """The acquisition of a write lock for one scope.""" + + def release(self) -> None: + """Release the lock acquired for this scope.""" + ... + + +class WriteLock(Protocol): + """Acquire a lock before the scope's first write or side effect. + + An acquisition error propagates to the caller. The scope releases a returned + handle once when it ends, including on failure. + """ + + def acquire(self, project_id: str, dataset: str) -> WriteLockHandle: + """Acquire a lock on the given project and dataset.""" + ... + + +class NoWriteLock: + """The default provider, which assumes one writer process per dataset.""" + + def acquire(self, project_id: str, dataset: str) -> WriteLockHandle: + """Return a handle that has no lock to release.""" + return _NoWriteLockHandle() + + +class _NoWriteLockHandle: + def release(self) -> None: + """Finish a no-op acquisition.""" diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index f72432023..f7f69a6fd 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -749,15 +749,8 @@ class SpiralDBWriteNotSupportedError(NotImplementedError): """ -class SpiralDBLeaseRequiredError(RuntimeError): - """A writable SpiralDB database was written outside a job run (ITL-1844). - - A writable SpiralDB database (``SpiralDBConnector(..., writable=True)``) is written - only while a job run (``job.run()``, ``job.run_async()`` or a job node's ``run()``) - holds the dataset's writer lease. A write anywhere else (a ``CachedSource`` read - outside a run, a ``ConnectorArrowDatabase`` flushed directly) is refused before - anything is written. - """ +class SpiralDBScopeOpenError(RuntimeError): + """A write scope for the SpiralDB dataset is already open in this process.""" class SpiralDBObserverNotSupportedError(SpiralDBWriteNotSupportedError): diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index ab7acde6a..a503219da 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -53,7 +53,6 @@ check_sources, clear_run_rows, plan_run, - run_owner, database_write_scope, ) from orcapod.pipeline.observer_losses import RunLosses @@ -1408,18 +1407,14 @@ def run( whatever the orchestrator's ``error_policy``, also when the read was needed to write a node's results. Its rows are not recomputed and the table is not overwritten. - LeaseBusyError: If another writer holds a writable SpiralDB database the - run would write (ITL-1844): refused before any source is checked and - before anything is computed or written. The leases a run takes are - released when it ends, also when it fails. - LeaseError: If a SpiralDB writer lease cannot be verified, or released - at the end of a run that succeeded (its writes are committed). + SpiralDBScopeOpenError: If a writable dataset already has an open + write scope in this process. """ - # The writer leases of the writable SpiralDB databases the run writes are held + # The write scopes of the writable SpiralDB databases the run writes are held # from the source check to the end of the run (ITL-1844). - with contextlib.ExitStack() as leases: + with contextlib.ExitStack() as write_scopes: summary = self._run_holding( - leases, + write_scopes, orchestrator, observer, materialize_results, @@ -1433,7 +1428,7 @@ def run( def _run_holding( self, - leases: contextlib.ExitStack, + write_scopes: contextlib.ExitStack, orchestrator: "SyncPipelineOrchestrator | AsyncPipelineOrchestrator | None", observer: "ExecutionObserverProtocol | None", materialize_results: bool, @@ -1441,11 +1436,11 @@ def _run_holding( *, load_only: bool, ) -> RunSummary: - """``run``, with the run's writer leases entered on ``leases``.""" + """``run``, with the run's write scopes entered on ``write_scopes``.""" from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator prepared = self._prepare_run( - commit_every_rows, load_only=load_only, leases=leases + commit_every_rows, load_only=load_only, write_scopes=write_scopes ) # The state rule (ITL-1095): a node that holds a current run is not run again. plan = prepared.plan @@ -1526,8 +1521,7 @@ async def run_async( RuntimeError: As for ``run``. OrcapodDatabaseWriteError: As for ``run``. OrcapodDatabaseReadError: As for ``run``. - LeaseBusyError: As for ``run``. - LeaseError: As for ``run``. + SpiralDBScopeOpenError: As for ``run``. """ from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator @@ -1539,11 +1533,11 @@ async def run_async( f"{type(orchestrator).__name__}. Use job.run(orchestrator=...) to run " "it." ) - # The writer leases of the writable SpiralDB databases the run writes + # The write scopes of the writable SpiralDB databases the run writes # (ITL-1844). - with contextlib.ExitStack() as leases: + with contextlib.ExitStack() as write_scopes: summary = await self._run_async_holding( - leases, + write_scopes, orchestrator, observer, materialize_results, @@ -1557,7 +1551,7 @@ async def run_async( async def _run_async_holding( self, - leases: contextlib.ExitStack, + write_scopes: contextlib.ExitStack, orchestrator: "AsyncPipelineOrchestrator", observer: "ExecutionObserverProtocol | None", materialize_results: bool, @@ -1565,9 +1559,9 @@ async def _run_async_holding( *, load_only: bool, ) -> RunSummary: - """``run_async``, with the run's writer leases entered on ``leases``.""" + """``run_async``, with the run's write scopes entered on ``write_scopes``.""" prepared = self._prepare_run( - commit_every_rows, load_only=load_only, leases=leases + commit_every_rows, load_only=load_only, write_scopes=write_scopes ) # The state rule (ITL-1095): a node that holds a current run is not run again. plan = prepared.plan @@ -1600,14 +1594,14 @@ def _prepare_run( commit_every_rows: int, *, load_only: bool = False, - leases: contextlib.ExitStack | None = None, + write_scopes: contextlib.ExitStack | None = None, ) -> "_PreparedRun": """Check the job can run and build what a run needs; shared by both run forms. Args: commit_every_rows: As for ``run``. load_only: As for ``run``: a loaded job can run only this way. - leases: Where the run's SpiralDB writer leases are entered (ITL-1844), + write_scopes: Where the run's SpiralDB write scopes are entered (ITL-1844), just before its sources are checked; ``None`` takes none. Returns: @@ -1809,12 +1803,9 @@ def _prepare_run( # source, is refused before any source is checked and before anything is # computed or written (ITL-1218). refuse_restriction_conflicts(exec_dag.nodes()) - # One writer per SpiralDB database (ITL-1844): the run takes the writer lease of - # every database it may write before a source is checked (a cached source writes - # its cache then) and before anything is computed or written. A second writer - # is refused here. - if leases is not None: - leases.enter_context( + # Open the scopes before source checks, which can write cached source rows. + if write_scopes is not None: + write_scopes.enter_context( database_write_scope( list(exec_dag.nodes()), load_only=load_only, @@ -1827,11 +1818,10 @@ def _prepare_run( self._database, *(r.database for r in self._retry_attachment_flushes.values()), ), - owner=run_owner("/".join(self._name)), ) ) - # Once preflight passes and the leases are held, stored row counts may change - # during the run. A run refused its lease keeps the last run's save state. + # Once preflight passes and the write scopes are open, stored row counts may change + # during the run. self._last_run_finished = False # Every source first takes in any new data, moving its modified time, before # the state rule judges any node (ITL-1102). diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 75d5409a1..1efaf9be3 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -26,6 +26,7 @@ collect_database_writes, shared_database_queue, ) +from orcapod.core.pod_result_databases import pod_result_databases, result_cache_owners from orcapod.errors import ( CachedSourceChangedRowError, OrcapodDatabaseError, @@ -136,7 +137,7 @@ def refuse_unloadable_source_checks(streams: Iterable[Any]) -> None: source that reads another stream live (``live_source_inputs``: a ``CachedSource`` over a source that reads a function pod's stream) reads that input when checked. So a load-only run is refused, as ``refuse_unloadable_inputs`` refuses a node, - before any lease is taken, any source checked or anything written. + before a write scope opens, a source is checked or anything is written. Args: streams: The nodes of the run, or the node whose ``run()`` it is. @@ -208,50 +209,11 @@ def _databases(nodes: Iterable[Any]) -> list[ArrowDatabaseProtocol]: return found -def _pod_result_databases(node: Any) -> list[Any]: - """The result databases a function node's own pod writes on a cache miss. - - The result database of each pod the node's function pod is or wraps - (``@function_pod(pod_cache_database=...)``), of each data function under them - (``@function_pod(result_database=...)``), and the node's ephemeral result database - (``set_ephemeral_database``, through the pod that writes it). Not the job's result - database (``_databases``); not committed at the end of a run, only leased. - """ - return [getattr(owner, "result_database", None) for owner in _result_owners(node)] - - -def _result_owners(node: Any) -> list[Any]: - """The pods and data functions under ``node`` that may own a result database. - - Each has ``result_database`` (``None`` when it writes none) and, when it has one, - the ``record_path`` of its result table. See ``_pod_result_databases``. - """ - found: list[Any] = [] - pods: list[Any] = [ - getattr(node, "_function_pod", None), - getattr(node, "_ephemeral_cached_pod", None), - ] - visited: set[int] = set() - while pods: - pod = pods.pop(0) - if pod is None or id(pod) in visited: - continue - visited.add(id(pod)) - found.append(pod) - pods.append(getattr(pod, "_function_pod", None)) # a wrapping pod's inner pod - function = getattr(pod, "data_function", None) - while function is not None and id(function) not in visited: - visited.add(id(function)) - found.append(function) - function = getattr(function, "_data_function", None) # a wrapper's inner - return found - - def _require_storable_result_paths(stream: Any) -> None: """Refuse a function pod stream or function job node whose result table paths are deeper than their databases allow (ITL-1871). - Every result database the stream's or node's own pods write (``_result_owners``) + Every result database the stream's or node's own pods write is checked; the caller names the stream or node. Nothing is read or written. Raises: @@ -259,11 +221,17 @@ def _require_storable_result_paths(stream: Any) -> None: """ from orcapod.contexts.stored import require_storable_record_path - for owner in _result_owners(stream): + for owner in result_cache_owners( + getattr(stream, "_function_pod", None), + getattr(stream, "_ephemeral_cached_pod", None), + ): database = getattr(owner, "result_database", None) if database is None: continue - require_storable_record_path(database, lambda: owner.record_path) # noqa: B023 # called at once + require_storable_record_path( + database, + lambda: getattr(owner, "record_path"), # noqa: B009, B023 # dynamic cache owner, called at once + ) def _job_name(node: Any) -> str: @@ -370,31 +338,37 @@ def _source_side_streams( return found -def _source_side_databases(streams: Iterable[Any], *, load_only: bool) -> list[Any]: +def _source_side_databases( + streams: Iterable[Any], *, load_only: bool, source_streams: list[Any] | None +) -> list[Any]: """The databases written by what feeds ``streams`` from outside the job's nodes (``_source_side_streams``): the cache of every ``CachedSource`` and the result - databases of every function pod stream a run reads (``_pod_result_databases``). + databases of every function pod stream a run reads. Collect those live pod streams + in ``source_streams`` when provided. """ + from orcapod.core.function_pod import FunctionPodStream from orcapod.core.sources.cached_source import CachedSource found: list[Any] = [] for stream, reads_pods in _source_side_streams(streams, load_only=load_only): if isinstance(stream, CachedSource): - found.append(stream._cache_database) # pyright: ignore[reportPrivateUsage] # the database a run must hold the lease of + found.append(stream._cache_database) # pyright: ignore[reportPrivateUsage] # the database the run may write if reads_pods: - found.extend(db for db in _pod_result_databases(stream) if db is not None) + found.extend(db for db in pod_result_databases(stream) if db is not None) + if source_streams is not None and isinstance(stream, FunctionPodStream): + source_streams.append(stream) return found def preflight_run_writes(streams: Sequence[Any], *, load_only: bool) -> None: - """Refuse a run that would write a table its database cannot store, before it takes - a lease, checks a source or writes anything (ITL-1871). + """Refuse a run that would write a table its database cannot store, before it opens + a write scope, checks a source or writes anything (ITL-1871). Whatever the backends, and whether or not a writable SpiralDB connector exists: every cache table of a ``CachedSource`` the run checks (``CachedSource.require_storable_cache``) and every result table of a function pod stream outside the job the run reads (``_require_storable_result_paths``), found by - the walk the writer leases use (``_source_side_streams``), and, for a full run, the + the walk the write scopes use (``_source_side_streams``), and, for a full run, the result tables of every job node's own pods (``function_pod(result_database=)``, ``pod_cache_database``, an ephemeral result database): a job checks them when it attaches its databases (``require_storable_tables``), a job node built on its own @@ -450,9 +424,13 @@ def _job_nodes_under(targets: Iterable[Any]) -> list[Any]: def write_scope_databases( - streams: Sequence[Any], *, load_only: bool, databases: Iterable[Any] = () + streams: Sequence[Any], + *, + load_only: bool, + databases: Iterable[Any] = (), + source_streams: list[Any] | None = None, ) -> list[Any]: - """The databases a run may write, for its writer leases (``database_write_scope``). + """The databases a run may write, for its write scopes (``database_write_scope``). A full run may write ``databases`` (a job's database and result database), the databases of the job nodes in ``streams`` and of every job node they depend on @@ -467,6 +445,7 @@ def write_scope_databases( streams: The nodes of the run, or the node whose ``run()`` it is. load_only: Whether the run is load-only. databases: The job's own databases, for a full run. + source_streams: If provided, collect the live pod streams the job reads. Returns: The databases, in the order met (repeats are left to ``database_writes``). @@ -478,9 +457,13 @@ def write_scope_databases( written.extend(_databases(nodes)) # A function pod's own result databases are written on a cache miss too. written.extend( - db for node in nodes for db in _pod_result_databases(node) if db is not None + db for node in nodes for db in pod_result_databases(node) if db is not None ) - written.extend(_source_side_databases(streams, load_only=load_only)) + written.extend( + _source_side_databases( + streams, load_only=load_only, source_streams=source_streams + ) + ) return written @@ -489,28 +472,24 @@ def database_write_scope( *, load_only: bool, databases: Iterable[Any] = (), - owner: str | None = None, ) -> AbstractContextManager[None]: - """The writer leases a run holds on the writable SpiralDB databases it may write - (ITL-1844). + """The write scopes a run holds on the writable SpiralDB databases it may write. The run may write the databases ``write_scope_databases`` lists. Entered before the run checks its sources (``spiraldb_write_scope.database_writes``). A load-only run whose source check would read an input that computes or delivers is refused first (``refuse_unloadable_source_checks``). When no writable SpiralDB connector exists in the process, no run can write one: nothing is walked - for leases and the scope holds nothing. Either way, the run's preflight first + for scopes and the scope holds nothing. Either way, the run's preflight first refuses a table its database cannot store (``preflight_run_writes``). Args: streams: The nodes of the run, or the node whose ``run()`` it is. load_only: Whether the run is load-only. databases: The job's own databases, for a full run. - owner: Who holds the leases, shown to a refused second writer; by default - the job of the first of ``streams`` (``run_owner``). Returns: - The context manager that holds the leases. + The context manager that holds the scopes. Raises: ValueError: As ``refuse_unloadable_source_checks``, for a load-only run; as @@ -520,26 +499,20 @@ def database_write_scope( from orcapod.databases.spiraldb_writable_registry import any_writable_connector if load_only: - # Before any lease is taken or source checked: a load-only run never reads an - # input that computes or delivers, also through a source's live inputs. + # Reject inputs that compute or deliver before opening scopes or checking + # sources, including when they are reached through a source's live inputs. refuse_unloadable_source_checks(streams) - # The run's preflight, whatever the backends (ITL-1871), before a lease is taken. + # The run's preflight, whatever the backends (ITL-1871), before a scope is opened. preflight_run_writes(streams, load_only=load_only) if not any_writable_connector(): return contextlib.nullcontext() from orcapod.databases.spiraldb_write_scope import database_writes - written = write_scope_databases(streams, load_only=load_only, databases=databases) - if owner is None: - owner = run_owner(_job_name(streams[0]) if streams else "") - return database_writes(written, owner=owner) - - -def run_owner(name: str) -> str: - """The owner text of a run's writer leases: the job and the process.""" - import os - - return f"orcapod job {name or '(unnamed)'} run, process {os.getpid()}" + source_streams: list[Any] = [] + written = write_scope_databases( + streams, load_only=load_only, databases=databases, source_streams=source_streams + ) + return database_writes(written, source_streams=source_streams) def check_sources(streams: Iterable[Any]) -> tuple[str, ...]: diff --git a/src/orcapod/protocols/core_protocols/function_pod.py b/src/orcapod/protocols/core_protocols/function_pod.py index bc9f851c8..9423375b0 100644 --- a/src/orcapod/protocols/core_protocols/function_pod.py +++ b/src/orcapod/protocols/core_protocols/function_pod.py @@ -1,4 +1,6 @@ -from typing import Any, Protocol, runtime_checkable +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable from orcapod.protocols.core_protocols.datagrams import DataProtocol, TagProtocol from orcapod.protocols.core_protocols.data_function import DataFunctionProtocol @@ -6,6 +8,9 @@ from orcapod.protocols.hashing_protocols import PipelineElementProtocol from orcapod.types import PodConfig +if TYPE_CHECKING: + from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol + @runtime_checkable class FunctionPodProtocol(PodProtocol, PipelineElementProtocol, Protocol): @@ -29,11 +34,21 @@ def ctx_arg_name(self) -> str | None: ... def process_data( - self, tag: TagProtocol, data: DataProtocol + self, + tag: TagProtocol, + data: DataProtocol, + *, + logger: DataExecutionLoggerProtocol | None = None, + run_id: str | None = None, ) -> tuple[TagProtocol, DataProtocol | None]: ... async def async_process_data( - self, tag: TagProtocol, data: DataProtocol + self, + tag: TagProtocol, + data: DataProtocol, + *, + logger: DataExecutionLoggerProtocol | None = None, + run_id: str | None = None, ) -> tuple[TagProtocol, DataProtocol | None]: ... def to_config(self) -> dict[str, Any]: diff --git a/src/orcapod/protocols/spiraldb_run.py b/src/orcapod/protocols/spiraldb_run.py index c55a1f8ce..ed7a15199 100644 --- a/src/orcapod/protocols/spiraldb_run.py +++ b/src/orcapod/protocols/spiraldb_run.py @@ -1,6 +1,8 @@ """Run capabilities of writable SpiralDB stores and their database views.""" -from collections.abc import Callable +from collections.abc import Callable, Iterator +from contextlib import AbstractContextManager, contextmanager, nullcontext +from contextvars import ContextVar from typing import Protocol, runtime_checkable @@ -8,6 +10,11 @@ class SpiralDBRunLookupProtocol(Protocol): """Optional metadata and completion lookups for a run.""" + @property + def spiral_writable(self) -> bool: + """Whether the database has writable SpiralDB scopes.""" + ... + def spiral_records_match_context( self, record_path: tuple[str, ...], current: str ) -> bool: @@ -20,6 +27,65 @@ def spiral_completion_lookup( """Return an execution-scoped lookup for a writable SpiralDB invocation log.""" ... + def spiral_write_scope(self) -> AbstractContextManager[None]: + """Use the current scope or open one for a direct invocation.""" + ... + + def spiral_acquire_write_lock(self) -> None: + """Acquire the run's write lock before delivering effects or calling a + context-taking function.""" + ... + + +_invocation_databases: ContextVar[tuple[SpiralDBRunLookupProtocol, ...]] = ContextVar( + "spiraldb_invocation_databases", default=() +) + + +@contextmanager +def invocation_boundary() -> Iterator[None]: + """Start an independent execution without inheriting registered stores.""" + token = _invocation_databases.set(()) + try: + yield + finally: + _invocation_databases.reset(token) + + +def invocation_write_scope(database: object) -> AbstractContextManager[None]: + """Keep the write scope open through a delivery or cached invocation.""" + if isinstance(database, SpiralDBRunLookupProtocol): + return database.spiral_write_scope() + return nullcontext() + + +@contextmanager +def invocation_write_database(database: object) -> Iterator[None]: + """Register a store the enclosing invocation may need to write after a call.""" + if ( + not isinstance(database, SpiralDBRunLookupProtocol) + or not database.spiral_writable + ): + yield + return + with database.spiral_write_scope(): + token = _invocation_databases.set((*_invocation_databases.get(), database)) + try: + yield + finally: + _invocation_databases.reset(token) + + +def acquire_invocation_write_locks() -> None: + """Acquire the registered stores' write locks before calling the user function.""" + for database in _invocation_databases.get(): + database.spiral_acquire_write_lock() + + +def has_invocation_write_scope() -> bool: + """Whether the current invocation has registered a writable SpiralDB store.""" + return bool(_invocation_databases.get()) + @runtime_checkable class InOrderFlushProtocol(Protocol): diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 6b4e93acb..b21901ebd 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -65,7 +65,10 @@ TRACKING_DB_SCHEMA_VERSION, constants, ) -from orcapod.protocols.spiraldb_run import SpiralDBRunLookupProtocol +from orcapod.protocols.spiraldb_run import ( + SpiralDBRunLookupProtocol, + invocation_write_scope, +) from orcapod.types import ColumnConfig from orcapod.utils import arrow_utils from orcapod.utils.database_errors import flush_best_effort @@ -423,6 +426,7 @@ def _execute_side_effect_row( pipeline_database: ArrowDatabaseProtocol | None = None, table_path: tuple[str, ...] | None = None, completion_lookup: Callable[[bytes], bool] | None = None, + before_delivery: Callable[[], None] | None = None, ) -> tuple[TagProtocol, DataProtocol] | None: """Execute delivery for one (tag, data) row. @@ -450,6 +454,8 @@ def _execute_side_effect_row( pipeline_database: Attached DB (or ``None`` for standalone mode). table_path: Path tuple for the invocation log table. completion_lookup: Optional execution-scoped lookup for a SpiralDB log. + before_delivery: Optional: called before the row is delivered (the writer + write lock); not called for a row already delivered. Returns: ``(tag, data)`` to emit downstream, or ``None`` to drop the row. @@ -481,6 +487,9 @@ def _execute_side_effect_row( if completed: return (tag, data) # already completed — re-emit without re-delivery + if before_delivery is not None: + before_delivery() + # 3. Build InvocationContext (invocation_hash derived lazily via format_id()). ctx = InvocationContext( pod_name=pod_name, @@ -1304,28 +1313,37 @@ def _deliver_rows( self, input_stream: StreamProtocol, *, run_id: str | None ) -> list[tuple[TagProtocol, DataProtocol]]: """Deliver every row of ``input_stream``; return the rows passed on.""" - self._refuse_log_of_another_data_context() - lookup = self._completion_lookup() - results: list[tuple[TagProtocol, DataProtocol]] = [] - for tag, data in input_stream.iter_data(): - result = _execute_side_effect_row( - fn=self._pod._fn, - tag=tag, - data=data, - pod_config=self._pod.pod_config, - pipeline_hash_ch=self.pipeline_hash(), - pod_name=self._pod.label, - run_id=run_id, - arrow_hasher=self._pod.data_context.arrow_hasher, - data_context_key=self._pod.data_context_key, - ctx_arg_name=self._pod.ctx_arg_name, - pipeline_database=self._pipeline_database, - table_path=self._table_path, - completion_lookup=lookup, - ) - if result is not None: - results.append(result) - return results + with invocation_write_scope(self._pipeline_database): + self._refuse_log_of_another_data_context() + lookup = self._completion_lookup() + results: list[tuple[TagProtocol, DataProtocol]] = [] + for tag, data in input_stream.iter_data(): + result = _execute_side_effect_row( + fn=self._pod._fn, + tag=tag, + data=data, + pod_config=self._pod.pod_config, + pipeline_hash_ch=self.pipeline_hash(), + pod_name=self._pod.label, + run_id=run_id, + arrow_hasher=self._pod.data_context.arrow_hasher, + data_context_key=self._pod.data_context_key, + ctx_arg_name=self._pod.ctx_arg_name, + pipeline_database=self._pipeline_database, + table_path=self._table_path, + completion_lookup=lookup, + before_delivery=self._acquire_write_lock, + ) + if result is not None: + results.append(result) + return results + + def _acquire_write_lock(self) -> None: + """Acquire the run's write lock for a writable SpiralDB invocation log before a + delivery, after reading the log.""" + database = self._pipeline_database + if isinstance(database, SpiralDBRunLookupProtocol): + database.spiral_acquire_write_lock() def _completion_lookup(self) -> Callable[[bytes], bool] | None: """Index a writable SpiralDB invocation log for this execution.""" @@ -1575,42 +1593,44 @@ async def async_execute( # the order downstream received. Never held across the delivery itself. send_lock = asyncio.Lock() try: - self._refuse_log_of_another_data_context() - lookup = self._completion_lookup() - - async def process_one(tag: TagProtocol, data: DataProtocol) -> None: - try: - result = _execute_side_effect_row( - fn=self._pod._fn, - tag=tag, - data=data, - pod_config=self._pod.pod_config, - pipeline_hash_ch=self.pipeline_hash(), - pod_name=self._pod.label, - run_id=run_id, - arrow_hasher=self._pod.data_context.arrow_hasher, - data_context_key=self._pod.data_context_key, - ctx_arg_name=self._pod.ctx_arg_name, - pipeline_database=self._pipeline_database, - table_path=self._table_path, - completion_lookup=lookup, - ) - if result is not None: - async with send_lock: - passed_on.append(result) - await output.send(result) - finally: - if sem is not None: - sem.release() - - async with asyncio.TaskGroup() as tg: - async for tag, data in inputs[0]: - if sem is not None: - await sem.acquire() - tg.create_task(process_one(tag, data)) - # Held and stamped before the output closes, so every downstream node, which - # stamps after it has seen that close, is newer than this one (ITL-1042). - self._hold(passed_on) + with invocation_write_scope(self._pipeline_database): + self._refuse_log_of_another_data_context() + lookup = self._completion_lookup() + + async def process_one(tag: TagProtocol, data: DataProtocol) -> None: + try: + result = _execute_side_effect_row( + fn=self._pod._fn, + tag=tag, + data=data, + pod_config=self._pod.pod_config, + pipeline_hash_ch=self.pipeline_hash(), + pod_name=self._pod.label, + run_id=run_id, + arrow_hasher=self._pod.data_context.arrow_hasher, + data_context_key=self._pod.data_context_key, + ctx_arg_name=self._pod.ctx_arg_name, + pipeline_database=self._pipeline_database, + table_path=self._table_path, + completion_lookup=lookup, + before_delivery=self._acquire_write_lock, + ) + if result is not None: + async with send_lock: + passed_on.append(result) + await output.send(result) + finally: + if sem is not None: + sem.release() + + async with asyncio.TaskGroup() as tg: + async for tag, data in inputs[0]: + if sem is not None: + await sem.acquire() + tg.create_task(process_one(tag, data)) + # Held and stamped before the output closes, so every downstream node, which + # stamps after it has seen that close, is newer than this one (ITL-1042). + self._hold(passed_on) except BaseException: # A run that raised or was cancelled defines no rows (ITL-1095). self.clear_cache() diff --git a/tests/test_channels/test_node_async_execute.py b/tests/test_channels/test_node_async_execute.py index a581f602b..60cc6a334 100644 --- a/tests/test_channels/test_node_async_execute.py +++ b/tests/test_channels/test_node_async_execute.py @@ -719,9 +719,10 @@ async def patched(tag, data, **kwargs): await feed_stream_to_channel(make_stream(3), input_ch) await node.async_execute(input_ch.reader, output_ch.writer) - await output_ch.reader.collect() + results = await output_ch.reader.collect() assert len(call_log) == 3 + assert sorted(data.as_dict()["result"] for _, data in results) == [0, 2, 4] # --------------------------------------------------------------------------- diff --git a/tests/test_core/sources/test_cached_source_changed_rows.py b/tests/test_core/sources/test_cached_source_changed_rows.py index 39eb950c3..0c06cbe89 100644 --- a/tests/test_core/sources/test_cached_source_changed_rows.py +++ b/tests/test_core/sources/test_cached_source_changed_rows.py @@ -413,7 +413,7 @@ def test_writable_cache_freshness_refuses_a_mixed_delivery(tmp_path: Path) -> No path = tmp_path / "readings.csv" _write(path, ROWS) with fake.install(tmp_path): - cache = ConnectorArrowDatabase(writable_connector(held=False)) + cache = ConnectorArrowDatabase(writable_connector()) source = _cached(path, cache) results = InMemoryArrowDatabase() job = _job(source, results) diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index 5ebeaf084..32d02f6f0 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -1014,8 +1014,6 @@ def __init__(self, store: _Store, table: dict[str, Any]) -> None: """Hold the parts it is made of.""" self._store, self._table = store, table self._parts: list[pa.Table] = [] - self._keys_to_delete: list[pa.Table] = [] - self._drop: list[str] = [] self.aborted = False def append(self, data: pa.Table) -> None: @@ -1023,14 +1021,6 @@ def append(self, data: pa.Table) -> None: latest = self._latest() self._parts.append(_staged(data, self._table["keys"], latest.schema)) - def delete_keys(self, data: pa.Table) -> None: - """Stage the deletion of rows.""" - self._keys_to_delete.append(data) - - def alter_schema(self, changes: list[str]) -> None: - """Stage column drops (``drop_column`` gives the name here).""" - self._drop.extend(changes) - def finish(self) -> FakeKeyedTable: """Publish what was staged (``zero-rows``).""" self._store.by_id(self._table["id"]) @@ -1040,15 +1030,6 @@ def finish(self) -> FakeKeyedTable: for part in self._parts: if part.num_rows: rows = _upserted(rows, part, keys) - for dropped in self._keys_to_delete: - gone = set(zip(*(dropped.column(k).to_pylist() for k in keys))) - kept = [ - key not in gone - for key in zip(*(rows.column(k).to_pylist() for k in keys)) - ] - rows = rows.filter(pa.array(kept, pa.bool_())) - if self._drop: - rows = rows.drop_columns(self._drop) if rows is not before: self._store.write(self._table["id"], rows) return _open(self._store, self._table, None) @@ -1064,11 +1045,6 @@ def _latest(self) -> pa.Table: return self._store.read(self._table["id"], max([0, *versions])) -def drop_column(name: str) -> str: - """Stand in for ``spiral.drop_column``.""" - return name - - def _open(store: _Store, table: dict[str, Any], asof: int | None) -> FakeKeyedTable: """Open a table at ``asof`` or its latest version (``asof``, ``version-0``).""" versions = store.versions(table["id"]) @@ -1213,7 +1189,6 @@ def fake_http_get_json(url: str, token: str | None) -> dict[str, Any]: gt=gt, gte=gte, and_=and_, - drop_column=drop_column, ) diff --git a/tests/test_databases/test_fake_spiral_sdk.py b/tests/test_databases/test_fake_spiral_sdk.py index 7f2105f85..61e98a31b 100644 --- a/tests/test_databases/test_fake_spiral_sdk.py +++ b/tests/test_databases/test_fake_spiral_sdk.py @@ -15,6 +15,7 @@ def test_keyed_append_refuses_a_sliced_list_child( tmp_path: Path, kind: pa.DataType ) -> None: + """Reject an empty string or binary list child with a nonzero Arrow offset.""" ignored = b"prefix" if pa.types.is_large_binary(kind) else "prefix" empty_child = pa.array([ignored], type=kind).slice(1) lists = pa.LargeListArray.from_arrays(pa.array([0, 0, 0], pa.int64()), empty_child) diff --git a/tests/test_databases/test_migrate_spiral_schemas.py b/tests/test_databases/test_migrate_spiral_schemas.py index d4ed204ca..aae3c2926 100644 --- a/tests/test_databases/test_migrate_spiral_schemas.py +++ b/tests/test_databases/test_migrate_spiral_schemas.py @@ -14,15 +14,10 @@ import pyarrow as pa import pytest +from orcapod.databases.store_table_names import store_table_name from orcapod.databases import SpiralDBConnector from orcapod.databases import spiraldb_schema_table as st -from orcapod.databases.store_table_names import ( - SPIRAL_LEASE_KEY_PREFIX, - is_spiral_lease_table_name, - spiral_lease_key_column, - spiral_lease_table_name, - store_table_name, -) + from orcapod.errors import TableSchemaError from orcapod.sources import SpiralDBTableSource from tests.test_databases import fake_spiral_sdk as fake @@ -41,6 +36,14 @@ ) +# Fixtures from the retired keyed writer lease. +SPIRAL_LEASE_KEY_PREFIX = "orcapod_lease_v1_" + + +def spiral_lease_table_name(generation: int) -> str: + return f"orcapod_lease_v1_g{generation}" + + def _rows(keys: list[str]) -> pa.Table: return pa.table( { @@ -177,7 +180,6 @@ def test_lease_name_recognizers_agree(tool: ModuleType) -> None: assert (tool.LEASE_TABLE_PATTERN.fullmatch(name) is not None) == expected, repr( name ) - assert is_spiral_lease_table_name(name) == expected, repr(name) keys = [ (f"{SPIRAL_LEASE_KEY_PREFIX}{'a' * 32}", True), (f"{SPIRAL_LEASE_KEY_PREFIX}{'A' * 32}", False), @@ -189,7 +191,6 @@ def test_lease_name_recognizers_agree(tool: ModuleType) -> None: assert tool.is_lease_generation([(key, pa.large_string())]) == expected, repr( key ) - assert (spiral_lease_key_column([key]) is not None) == expected, repr(key) lease_key = keys[0][0] assert tool.is_lease_generation([(lease_key, pa.string())]) assert not tool.is_lease_generation([(lease_key, pa.int64())]) @@ -197,7 +198,6 @@ def test_lease_name_recognizers_agree(tool: ModuleType) -> None: assert not tool.is_lease_generation( [(lease_key, pa.large_string()), ("k", pa.large_string())] ) - assert spiral_lease_key_column([lease_key, "k"]) is None def _legacy_listing( @@ -481,6 +481,13 @@ def _add_table(project: Any) -> None: ) +def _add_lease_lookalike(project: Any) -> None: + name = spiral_lease_table_name(1) + project.create_table(f"two.{name}", key_schema=[("k", pa.string())]).write( + pa.table({"k": ["a"], "v": [1]}) + ) + + def _drop_table(project: Any) -> None: project.drop_table("two.units") @@ -495,6 +502,7 @@ def _recreate_table(project: Any) -> None: _DRIFTS: dict[str, Callable[[Any], None]] = { "rows written": _write_rows, "table added": _add_table, + "lease lookalike added": _add_lease_lookalike, "table dropped": _drop_table, "table created again": _recreate_table, } diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py deleted file mode 100644 index fcddbb905..000000000 --- a/tests/test_databases/test_spiral_lease.py +++ /dev/null @@ -1,968 +0,0 @@ -"""Exercise generation leases against the local SDK fake.""" - -from __future__ import annotations - -import warnings -from collections.abc import Iterator, Sequence -from pathlib import Path - -import pyarrow as pa -import pytest - -from orcapod.databases import spiraldb_lease -from orcapod.databases.spiraldb_connector import SpiralDBConnector -from orcapod.databases.spiraldb_lease import ( - LeaseBusyError, - Lease, - LeaseError, - acquire, - check, - clear, - release, -) -from orcapod.databases.store_table_names import ( - SPIRAL_LEASE_KEY_PREFIX, - STORE_TABLE_NAME_PREFIX, - is_spiral_lease_table_name, - spiral_lease_table_name, - store_table_name, -) -from tests.test_databases import fake_spiral_sdk as fake - -_PROJECT = "project" -_DATASET = "dataset" - - -@pytest.fixture -def client(tmp_path: Path) -> Iterator[fake.FakeClient]: - """Install the fake for one test and return its SDK-shaped client.""" - with fake.install(tmp_path): - yield fake.FakeClient() - - -def test_take_check_release_and_retake(client: fake.FakeClient) -> None: - """A released lease can be released again, and a new acquire takes the next generation.""" - first = acquire(client, _PROJECT, _DATASET, owner="first run") - check(client, first) - release(client, first) - release(client, first) - second = acquire(client, _PROJECT, _DATASET, owner="second run") - assert second.table_id != first.table_id - release(client, first) - check(client, second) - with pytest.raises(LeaseError, match="released"): - check(client, first) - - -def test_lease_operations_raise_no_keyed_table_deprecation( - client: fake.FakeClient, -) -> None: - """Lease operations raise no keyed-table deprecation warning. - - Every keyed-table open and create of a lease goes through the connector's helpers, - which ignore the SDK's keyed-table deprecation for their own calls, also after an - earlier open made before the error filter. - """ - earlier = acquire(client, _PROJECT, _DATASET, owner="earlier run") - release(client, earlier) - with warnings.catch_warnings(): - warnings.simplefilter("error", DeprecationWarning) - lease = acquire(client, _PROJECT, _DATASET, owner="checked run") - check(client, lease) - release(client, lease) - clear(client, _PROJECT, _DATASET, lease.table_id, confirm_writer_stopped=True) - with pytest.raises(LeaseError, match="released"): - check(client, lease) - - -def test_crashed_holder_refuses_until_manually_cleared(client: fake.FakeClient) -> None: - """A held lease refuses others, naming the clear call, until it is cleared by ID.""" - first = acquire(client, _PROJECT, _DATASET, owner="same owner") - other = fake.FakeClient() - for _ in range(2): - with pytest.raises(LeaseBusyError) as refused: - _ = acquire(other, _PROJECT, _DATASET, owner="same owner") - message = str(refused.value) - assert _DATASET in message - assert first.table_id in message - assert "same owner" in message - assert ( - f"spiraldb_lease.clear(client, {_PROJECT!r}, {_DATASET!r}, " - f"{first.table_id!r}, confirm_writer_stopped=True)" - ) in message - assert "all its pending writes have settled" in message - with pytest.raises(ValueError, match="stopped and all its pending writes have"): - clear(other, _PROJECT, _DATASET, first.table_id, confirm_writer_stopped=False) - check(client, first) - clear(other, _PROJECT, _DATASET, first.table_id, confirm_writer_stopped=True) - second = acquire(other, _PROJECT, _DATASET, owner="next run") - with pytest.raises(LeaseError, match="not the newest"): - clear(other, _PROJECT, _DATASET, first.table_id, confirm_writer_stopped=True) - check(other, second) - with pytest.raises(LeaseError, match="released"): - check(client, first) - - -@pytest.mark.parametrize("winner_releases", [False, True]) -def test_two_writers_that_observed_the_same_generation( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, winner_releases: bool -) -> None: - """Two writers racing for one generation: the loser is refused, told to retry if - the winner already released.""" - create = fake.FakeProject.create_keyed_table - attempted: list[str] = [] - - def racing_create( - project: fake.FakeProject, - dataset: str, - name: str, - key_schema: pa.Schema, - *, - exist_ok: bool = False, - ) -> fake.FakeKeyedTable: - attempted.append(name) - if len(attempted) == 1: - other = fake.FakeClient() - winner = acquire(other, _PROJECT, _DATASET, owner="winner") - check(other, winner) - if winner_releases: - release(other, winner) - return create(project, dataset, name, key_schema, exist_ok=exist_ok) - - monkeypatch.setattr(fake.FakeProject, "create_keyed_table", racing_create) - with pytest.raises(LeaseBusyError, match="winner") as refused: - _ = acquire(client, _PROJECT, _DATASET, owner="loser") - assert attempted == [spiral_lease_table_name(1)] * 2 - if winner_releases: - assert "Retry acquisition" in str(refused.value) - assert "confirm_writer_stopped=True" not in str(refused.value) - check(client, acquire(client, _PROJECT, _DATASET, owner="loser retry")) - else: - assert "confirm_writer_stopped=True" in str(refused.value) - - -def test_crash_between_create_and_owner_record(client: fake.FakeClient) -> None: - """A bare claim with no owner row refuses others until it is cleared.""" - # A process that stops after exclusive creation leaves only its claim key. - key = f"{SPIRAL_LEASE_KEY_PREFIX}{'a' * 32}" - _ = client.project(_PROJECT).create_keyed_table( - _DATASET, - spiral_lease_table_name(1), - pa.schema([pa.field(key, pa.large_string(), nullable=False)]), - ) - with pytest.raises(LeaseBusyError, match="owner unknown") as refused: - _ = acquire(client, _PROJECT, _DATASET, owner="second") - clear( - client, _PROJECT, _DATASET, refused.value.table_id, confirm_writer_stopped=True - ) - check(client, acquire(client, _PROJECT, _DATASET, owner="third")) - - -def test_stale_clear_cannot_be_overwritten_by_late_owner_record( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch -) -> None: - """A clear that lands before the owner row keeps the lease released. - - The hook runs before the owner write commits; that write then commits. - """ - append = fake.FakeKeyedTable.append - ids: list[str] = [] - - def clear_before_append( - table: fake.FakeKeyedTable, rows: pa.Table - ) -> fake.FakeKeyedTable: - if not ids: - ids.append(table.resource_id) - clear( - client, - _PROJECT, - _DATASET, - table.resource_id, - confirm_writer_stopped=True, - ) - next_lease = acquire(client, _PROJECT, _DATASET, owner="next") - ids.append(next_lease.table_id) - return append(table, rows) - - monkeypatch.setattr(fake.FakeKeyedTable, "append", clear_before_append) - with pytest.raises(LeaseError, match="released"): - _ = acquire(client, _PROJECT, _DATASET, owner="old") - with pytest.raises(LeaseBusyError) as refused: - _ = acquire(client, _PROJECT, _DATASET, owner="third") - assert refused.value.table_id == ids[-1] - - -@pytest.mark.parametrize("reply", ["timeout", "conflict"]) -def test_create_reply_reconciles_the_callers_token( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, reply: str -) -> None: - """A create whose reply is lost (timeout) or answered 409 is the caller's claim. - - ``lose_reply`` commits the create before it raises or creates again. - """ - create = fake.FakeProject.create_keyed_table - - def lose_reply( - project: fake.FakeProject, - dataset: str, - name: str, - key_schema: pa.Schema, - *, - exist_ok: bool = False, - ) -> fake.FakeKeyedTable: - _ = create(project, dataset, name, key_schema, exist_ok=exist_ok) - if reply == "conflict": - return create(project, dataset, name, key_schema, exist_ok=exist_ok) - raise TimeoutError("lost reply") - - monkeypatch.setattr(fake.FakeProject, "create_keyed_table", lose_reply) - holder = acquire(client, _PROJECT, _DATASET, owner="holder") - check(client, holder) - - -def test_create_reply_reports_an_unexpected_claim_token( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch -) -> None: - """A create that returns a table with another claim key is refused.""" - create = fake.FakeProject.create_keyed_table - other_key = f"{SPIRAL_LEASE_KEY_PREFIX}{'a' * 32}" - - def return_another_claim( - project: fake.FakeProject, - dataset: str, - name: str, - _key_schema: pa.Schema, - *, - exist_ok: bool = False, - ) -> fake.FakeKeyedTable: - schema = pa.schema([pa.field(other_key, pa.large_string(), nullable=False)]) - return create(project, dataset, name, schema, exist_ok=exist_ok) - - monkeypatch.setattr(fake.FakeProject, "create_keyed_table", return_another_claim) - with pytest.raises(LeaseError, match="Unexpected claim token"): - _ = acquire(client, _PROJECT, _DATASET, owner="first") - - -@pytest.mark.parametrize("own_claim", [True, False]) -def test_create_interruption_releases_only_the_callers_claim( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, own_claim: bool -) -> None: - """An interrupted create releases the generation only when it carries the caller's - key. ``interrupt_create`` commits the create before it raises.""" - create = fake.FakeProject.create_keyed_table - interrupted = KeyboardInterrupt("create reply interrupted") - - def interrupt_create( - project: fake.FakeProject, - dataset: str, - name: str, - key_schema: pa.Schema, - *, - exist_ok: bool = False, - ) -> fake.FakeKeyedTable: - if not own_claim: - other_key = f"{SPIRAL_LEASE_KEY_PREFIX}{'a' * 32}" - key_schema = pa.schema( - [pa.field(other_key, pa.large_string(), nullable=False)] - ) - _ = create(project, dataset, name, key_schema, exist_ok=exist_ok) - raise interrupted - - with monkeypatch.context() as patch: - patch.setattr(fake.FakeProject, "create_keyed_table", interrupt_create) - with pytest.raises(KeyboardInterrupt) as caught: - _ = acquire(client, _PROJECT, _DATASET, owner="first") - assert caught.value is interrupted - - if own_claim: - check(client, acquire(client, _PROJECT, _DATASET, owner="next")) - else: - with pytest.raises(LeaseBusyError, match="owner unknown"): - _ = acquire(client, _PROJECT, _DATASET, owner="next") - - -@pytest.mark.parametrize("owner_reply", ["lost", "failed", "interrupted"]) -def test_acquire_recovers_or_releases_after_owner_write_error( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, owner_reply: str -) -> None: - """A failed owner write releases the claim; a lost reply that committed holds. - - ``fail_owner_write`` commits the owner row before raising only for ``lost``. - """ - append = fake.FakeKeyedTable.append - - def fail_owner_write( - table: fake.FakeKeyedTable, rows: pa.Table - ) -> fake.FakeKeyedTable: - if rows.column("owner").null_count == rows.num_rows: - return append(table, rows) - if owner_reply == "lost": - _ = append(table, rows) - if owner_reply == "interrupted": - raise KeyboardInterrupt - raise TimeoutError("owner write reply unavailable") - - with monkeypatch.context() as patch: - patch.setattr(fake.FakeKeyedTable, "append", fail_owner_write) - if owner_reply == "lost": - holder = acquire(client, _PROJECT, _DATASET, owner="writer") - check(client, holder) - release(client, holder) - elif owner_reply == "interrupted": - with pytest.raises(KeyboardInterrupt): - _ = acquire(client, _PROJECT, _DATASET, owner="interrupted") - else: - with pytest.raises(LeaseError, match="no owner record"): - _ = acquire(client, _PROJECT, _DATASET, owner="failed") - - check(client, acquire(client, _PROJECT, _DATASET, owner="next")) - - -@pytest.mark.parametrize("failed_call", ["open", "scan", "scan_after_write_error"]) -def test_acquire_releases_after_verification_error( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, failed_call: str -) -> None: - """A verification failure after the claim releases it and keeps the error. - - ``lose_owner_reply`` commits the owner row before it raises. - """ - append = fake.FakeKeyedTable.append - unavailable_error = TimeoutError("verification unavailable") - - def unavailable(*_args: object, **_kwargs: object) -> None: - raise unavailable_error - - def lose_owner_reply( - table: fake.FakeKeyedTable, rows: pa.Table - ) -> fake.FakeKeyedTable: - result = append(table, rows) - if rows.column("owner").null_count == 0: - raise TimeoutError("owner write reply unavailable") - return result - - with monkeypatch.context() as patch: - if failed_call == "open": - patch.setattr(fake.FakeClient, "keyed_table_by_id", unavailable) - else: - patch.setattr(fake.FakeKeyedTable, "scan", unavailable) - if failed_call == "scan_after_write_error": - patch.setattr(fake.FakeKeyedTable, "append", lose_owner_reply) - if failed_call == "open": - with pytest.raises(LeaseError, match="Could not reopen") as reopened: - _ = acquire(client, _PROJECT, _DATASET, owner="first") - assert reopened.value.__cause__ is unavailable_error - else: - with pytest.raises( - TimeoutError, match="verification unavailable" - ) as caught: - _ = acquire(client, _PROJECT, _DATASET, owner="first") - assert caught.value is unavailable_error - check(client, acquire(client, _PROJECT, _DATASET, owner="next")) - - -def test_acquire_reports_cleanup_failure_with_generation_id( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch -) -> None: - """When the release after a failed acquire also fails, the note names the table ID. - No write commits.""" - - def unavailable(*_args: object) -> None: - raise TimeoutError("writes unavailable") - - with monkeypatch.context() as patch: - patch.setattr(fake.FakeKeyedTable, "append", unavailable) - with pytest.raises(LeaseError, match="no owner record") as failed: - _ = acquire(client, _PROJECT, _DATASET, owner="first") - - with pytest.raises(LeaseBusyError) as refused: - _ = acquire(client, _PROJECT, _DATASET, owner="next") - assert any( - "Releasing the failed acquisition also failed" in note - and refused.value.table_id in note - for note in failed.value.__notes__ - ) - clear( - client, _PROJECT, _DATASET, refused.value.table_id, confirm_writer_stopped=True - ) - check(client, acquire(client, _PROJECT, _DATASET, owner="next")) - - -def test_release_reports_a_failed_reopen_as_a_lease_error( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch -) -> None: - """A failed reopen on release is a chained ``LeaseError`` naming the table ID.""" - holder = acquire(client, _PROJECT, _DATASET, owner="holder") - cause = TimeoutError("reopen unavailable") - - def unavailable(*_args: object, **_kwargs: object) -> None: - raise cause - - with monkeypatch.context() as patch: - patch.setattr(fake.FakeClient, "keyed_table_by_id", unavailable) - with pytest.raises(LeaseError, match=holder.table_id) as failed: - release(client, holder) - assert failed.value.__cause__ is cause - release(client, holder) - check(client, acquire(client, _PROJECT, _DATASET, owner="next")) - - -def test_release_from_another_process_is_refused_before_the_reopen( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch -) -> None: - """Another process's release is refused before the table is reopened.""" - holder = acquire(client, _PROJECT, _DATASET, owner="holder") - elsewhere = Lease(holder.table_id, holder.key, holder.pid + 1) - - def unexpected_open(*_args: object, **_kwargs: object) -> None: - raise AssertionError("the lease table was reopened") - - with monkeypatch.context() as patch: - patch.setattr(fake.FakeClient, "keyed_table_by_id", unexpected_open) - with pytest.raises(RuntimeError) as refused: - release(client, elsewhere) - assert not isinstance(refused.value, LeaseError) - release(client, holder) - - -def test_interrupted_cleanup_keeps_the_acquisition_error( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch -) -> None: - """An interrupted release after a failed acquire keeps the acquisition error. - - ``interrupt_release`` commits the owner row and raises before the release commits. - """ - append = fake.FakeKeyedTable.append - verification_error = TimeoutError("verification unavailable") - - def interrupt_release( - table: fake.FakeKeyedTable, rows: pa.Table - ) -> fake.FakeKeyedTable: - if rows.column("owner").null_count == 0: - return append(table, rows) - raise KeyboardInterrupt - - def unavailable(*_args: object, **_kwargs: object) -> None: - raise verification_error - - with monkeypatch.context() as patch: - patch.setattr(fake.FakeKeyedTable, "append", interrupt_release) - patch.setattr(fake.FakeKeyedTable, "scan", unavailable) - with pytest.raises(TimeoutError) as failed: - _ = acquire(client, _PROJECT, _DATASET, owner="first") - assert failed.value is verification_error - with pytest.raises(LeaseBusyError) as refused: - _ = acquire(client, _PROJECT, _DATASET, owner="next") - assert any( - "Releasing the failed acquisition also failed" in note - and refused.value.table_id in note - and "KeyboardInterrupt" in note - for note in failed.value.__notes__ - ) - clear( - client, _PROJECT, _DATASET, refused.value.table_id, confirm_writer_stopped=True - ) - - -@pytest.mark.parametrize("landed", [True, False]) -def test_release_reply_lost( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, landed: bool -) -> None: - """A release whose reply is lost holds if it committed and raises if it did not. - - ``lose_reply`` commits the release before raising only when ``landed``. - """ - holder = acquire(client, _PROJECT, _DATASET, owner="holder") - append = fake.FakeKeyedTable.append - - def lose_reply(table: fake.FakeKeyedTable, rows: pa.Table) -> fake.FakeKeyedTable: - if landed: - _ = append(table, rows) - raise TimeoutError("lost reply") - - with monkeypatch.context() as patch: - patch.setattr(fake.FakeKeyedTable, "append", lose_reply) - if landed: - release(client, holder) - else: - with pytest.raises(LeaseError, match=holder.table_id): - release(client, holder) - if landed: - check(client, acquire(client, _PROJECT, _DATASET, owner="next")) - else: - with pytest.raises(LeaseBusyError): - _ = acquire(client, _PROJECT, _DATASET, owner="next") - - -@pytest.mark.parametrize("reverse", [False, True]) -def test_numbered_lease_tables_are_hidden_but_database_tables_are_visible( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, reverse: bool -) -> None: - """Generations are hidden from listings; database and look-alike tables stay visible - and cannot be cleared.""" - holder = acquire(client, _PROJECT, _DATASET, owner="holder") - lease_name = spiral_lease_table_name(1) - full_path = [lease_name, "records"] - names = [ - store_table_name(path, hint_length=96, digest_length=64) - for path in (full_path, full_path[::-1]) - ] - assert names[0] != names[1] - lookalike = f"{lease_name}report" - assert is_spiral_lease_table_name(lease_name) - assert not lease_name.startswith(STORE_TABLE_NAME_PREFIX) - assert not is_spiral_lease_table_name(lookalike) - key_schema = pa.schema([pa.field("id", pa.int64())]) - for name in reversed(names) if reverse else names: - assert not is_spiral_lease_table_name(name) - data = client.project(_PROJECT).create_keyed_table(_DATASET, name, key_schema) - with pytest.raises(LeaseError, match=data.resource_id): - clear( - client, - _PROJECT, - _DATASET, - data.resource_id, - confirm_writer_stopped=True, - ) - _ = client.project(_PROJECT).create_keyed_table(_DATASET, lookalike, key_schema) - - monkeypatch.setattr(fake, "list_page_size", 1) - with SpiralDBConnector(_PROJECT, dataset=_DATASET) as connector: - assert connector.get_table_names() == sorted([*names, lookalike]) - for name in [*names, lookalike]: - assert connector.lookup_table(name).key_columns == ["id"] - with pytest.raises(ValueError, match="reserved"): - _ = connector.lookup_table(lease_name) - check(client, holder) - - -def test_release_and_clear_keep_the_generation_sequence_contiguous( - client: fake.FakeClient, -) -> None: - """Release and clear keep every generation, so the sequence stays contiguous.""" - first = acquire(client, _PROJECT, _DATASET, owner="first") - release(client, first) - second = acquire(client, _PROJECT, _DATASET, owner="second") - clear(client, _PROJECT, _DATASET, second.table_id, confirm_writer_stopped=True) - third = acquire(client, _PROJECT, _DATASET, owner="third") - assert [ - client.keyed_table(_PROJECT, _DATASET, spiral_lease_table_name(i)).resource_id - for i in range(1, 4) - ] == [first.table_id, second.table_id, third.table_id] - with pytest.raises(LeaseBusyError, match=third.table_id): - _ = acquire(client, _PROJECT, _DATASET, owner="fourth") - - -def test_connector_reserves_generation_names_even_without_a_claim_key( - client: fake.FakeClient, -) -> None: - """The connector reserves generation names; a non-lease table under one blocks - acquire and cannot be cleared.""" - name = spiral_lease_table_name(1) - with SpiralDBConnector(_PROJECT, dataset=_DATASET) as connector: - with pytest.raises(ValueError, match="reserved"): - connector.create_table_if_not_exists(name, [], "id") - with pytest.raises(ValueError, match="reserved"): - _ = connector.lookup_table(name) - table = client.project(_PROJECT).create_keyed_table( - _DATASET, name, pa.schema([pa.field("id", pa.int64())]) - ) - with SpiralDBConnector(_PROJECT, dataset=_DATASET) as connector: - assert connector.get_table_names() == [] - with pytest.raises(ValueError, match="reserved"): - _ = connector.lookup_table(name) - with pytest.raises(LeaseError, match=table.resource_id): - _ = acquire(client, _PROJECT, _DATASET, owner="writer") - with pytest.raises(LeaseError, match=table.resource_id): - clear( - client, _PROJECT, _DATASET, table.resource_id, confirm_writer_stopped=True - ) - assert client.keyed_table_by_id(table.resource_id).version_id == table.version_id - - -@pytest.mark.parametrize("past_generations", [0, 40]) -def test_listing_skips_generations_without_any_sdk_table_opens( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, past_generations: int -) -> None: - """A listing skips generations by name without opening any table.""" - for _ in range(past_generations): - release(client, acquire(client, _PROJECT, _DATASET, owner="past")) - name = store_table_name(["records"], hint_length=96, digest_length=64) - _ = client.project(_PROJECT).create_keyed_table( - _DATASET, name, pa.schema([pa.field("id", pa.int64())]) - ) - - def unexpected_open(*_args: object, **_kwargs: object) -> None: - pytest.fail("listing opened a keyed table") - - monkeypatch.setattr(fake.FakeClient, "keyed_table_by_id", unexpected_open) - monkeypatch.setattr(fake.FakeClient, "keyed_table", unexpected_open) - with SpiralDBConnector(_PROJECT, dataset=_DATASET) as connector: - assert connector.get_table_names() == [name] - - -@pytest.mark.parametrize("dropped_generation", [1, 2]) -def test_manual_deletion_can_admit_a_second_holder( - client: fake.FakeClient, dropped_generation: int -) -> None: - """Dropping a generation by hand breaks the sequence and admits a second holder.""" - for _ in range(3): - release(client, acquire(client, _PROJECT, _DATASET, owner="past")) - first = acquire(client, _PROJECT, _DATASET, owner="first") - name = spiral_lease_table_name(dropped_generation) - fake.ExternalProject(_PROJECT).drop_table(f"{_DATASET}.{name}") - second = acquire(client, _PROJECT, _DATASET, owner="second") - check(client, first) - check(client, second) - assert first.table_id != second.table_id - - -def test_other_datasets_have_independent_leases(client: fake.FakeClient) -> None: - """Each dataset has its own generation sequence.""" - first = acquire(client, _PROJECT, _DATASET, owner="first") - second = acquire(client, _PROJECT, "other", owner="second") - assert first.table_id != second.table_id - check(client, first) - check(client, second) - - -@pytest.mark.parametrize("late_create_wins", [False, True]) -def test_create_that_arrives_after_timeout_never_grants_a_second_lease( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, late_create_wins: bool -) -> None: - """A create that commits after its timeout never yields two holders. - - ``delay_create`` commits nothing; the test commits the pending create later. - """ - create = fake.FakeProject.create_keyed_table - pending: list[tuple[fake.FakeProject, str, str, pa.Schema]] = [] - - def delay_create( - project: fake.FakeProject, - dataset: str, - name: str, - key_schema: pa.Schema, - *, - exist_ok: bool = False, - ) -> fake.FakeKeyedTable: - assert not exist_ok - pending.append((project, dataset, name, key_schema)) - raise TimeoutError("request still in flight") - - with monkeypatch.context() as patch: - patch.setattr(fake.FakeProject, "create_keyed_table", delay_create) - with pytest.raises(LeaseError, match="Could not confirm"): - _ = acquire(client, _PROJECT, _DATASET, owner="delayed") - - other = fake.FakeClient() - if late_create_wins: - table = create(*pending[0]) - with pytest.raises(LeaseBusyError, match=table.resource_id): - _ = acquire(other, _PROJECT, _DATASET, owner="second") - else: - holder = acquire(other, _PROJECT, _DATASET, owner="second") - with pytest.raises(fake.SpiralError, match="409"): - _ = create(*pending[0]) - check(other, holder) - - -def test_generation_search_uses_logarithmic_probes( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch -) -> None: - """Finding the newest of 19 generations takes a logarithmic number of opens.""" - for _ in range(19): - release(client, acquire(client, _PROJECT, _DATASET, owner="past")) - open_by_name = fake.FakeClient.keyed_table - probes: list[str] = [] - - def count_open( - instance: fake.FakeClient, - project: str, - dataset: str, - name: str, - *, - asof: int | None = None, - ) -> fake.FakeKeyedTable: - probes.append(name) - return open_by_name(instance, project, dataset, name, asof=asof) - - monkeypatch.setattr(fake.FakeClient, "keyed_table", count_open) - current = acquire(client, _PROJECT, _DATASET, owner="current") - assert len(probes) <= 11 - assert ( - client.keyed_table(_PROJECT, _DATASET, spiral_lease_table_name(20)).resource_id - == current.table_id - ) - - -def test_lookup_error_never_licenses_creation( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch -) -> None: - """A failed generation lookup never leads to a create.""" - - def unavailable(*_args: object) -> fake.FakeKeyedTable: - raise fake.SpiralError("remote service returned an unknown error (status 404)") - - def never_create(*_args: object, **_kwargs: object) -> fake.FakeKeyedTable: - pytest.fail("acquire attempted creation without a confirmed missing generation") - - monkeypatch.setattr(fake.FakeClient, "keyed_table", unavailable) - monkeypatch.setattr(fake.FakeProject, "create_keyed_table", never_create) - with pytest.raises(fake.SpiralError, match="404"): - _ = acquire(client, _PROJECT, _DATASET, owner="writer") - - -def test_interrupted_create_cleanup_failure_names_the_table_id( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch -) -> None: - """A second interruption during the cleanup of an interrupted create keeps the - first and notes the claimed table ID. ``interrupt_create`` commits the create - before it raises; ``interrupt_release`` commits nothing.""" - create = fake.FakeProject.create_keyed_table - interrupted = KeyboardInterrupt("create reply interrupted") - - def interrupt_create( - project: fake.FakeProject, - dataset: str, - name: str, - key_schema: pa.Schema, - *, - exist_ok: bool = False, - ) -> fake.FakeKeyedTable: - _ = create(project, dataset, name, key_schema, exist_ok=exist_ok) - raise interrupted - - def interrupt_release(*_args: object) -> fake.FakeKeyedTable: - raise KeyboardInterrupt - - with monkeypatch.context() as patch: - patch.setattr(fake.FakeProject, "create_keyed_table", interrupt_create) - patch.setattr(fake.FakeKeyedTable, "append", interrupt_release) - with pytest.raises(KeyboardInterrupt) as caught: - _ = acquire(client, _PROJECT, _DATASET, owner="first") - assert caught.value is interrupted - claimed = client.keyed_table(_PROJECT, _DATASET, spiral_lease_table_name(1)) - assert any( - "Reconciling interrupted writer lease creation" in note - and claimed.resource_id in note - and "KeyboardInterrupt" in note - for note in caught.value.__notes__ - ) - - -def test_interrupt_after_the_claim_releases_it( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch -) -> None: - """An interruption after the claim is confirmed, before the owner write, releases - the claim, so the next writer is not refused.""" - interrupted = KeyboardInterrupt("interrupted after the claim") - - def interrupt(*_args: object) -> Lease: - raise interrupted - - with monkeypatch.context() as patch: - patch.setattr(spiraldb_lease, "Lease", interrupt) - with pytest.raises(KeyboardInterrupt) as caught: - _ = acquire(client, _PROJECT, _DATASET, owner="first") - assert caught.value is interrupted - check(client, acquire(client, _PROJECT, _DATASET, owner="next")) - - -@pytest.mark.parametrize("raised", [KeyboardInterrupt, RuntimeError]) -def test_a_failure_of_on_claim_releases_the_claim( - client: fake.FakeClient, raised: type[BaseException] -) -> None: - """``on_claim`` is given the verified lease inside the guard: when it raises or is - interrupted, the claim is released before the error propagates, also after it - recorded the lease (a second release of it is harmless).""" - recorded: list[Lease] = [] - failure = raised("stopped while recording the claim") - - def on_claim(lease: Lease) -> None: - recorded.append(lease) - raise failure - - with pytest.raises(raised) as caught: - _ = acquire(client, _PROJECT, _DATASET, owner="first", on_claim=on_claim) - assert caught.value is failure - assert len(recorded) == 1 - # Released by acquire itself, before any release of the caller's. - with pytest.raises(LeaseError, match="released"): - check(client, recorded[0]) - # A caller that recorded the lease releases it again: harmless. - release(client, recorded[0]) - with pytest.raises(LeaseError, match="released"): - check(client, recorded[0]) - check(client, acquire(client, _PROJECT, _DATASET, owner="next")) - - -def test_on_claim_is_given_the_lease_acquire_returns(client: fake.FakeClient) -> None: - """``on_claim`` is called once, with the lease ``acquire`` then returns.""" - recorded: list[Lease] = [] - lease = acquire(client, _PROJECT, _DATASET, owner="first", on_claim=recorded.append) - assert recorded == [lease] - check(client, lease) - - -def test_release_appends_the_claim_marker_without_reading_state( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch -) -> None: - holder = acquire(client, _PROJECT, _DATASET, owner="holder") - append = fake.FakeKeyedTable.append - markers: list[pa.Table] = [] - - def counted(table: fake.FakeKeyedTable, data: pa.Table) -> fake.FakeKeyedTable: - markers.append(data) - return append(table, data) - - monkeypatch.setattr(fake.FakeKeyedTable, "append", counted) - fake.scan_log.clear() - release(client, holder) - assert fake.scan_log == [] - assert len(markers) == 1 - assert markers[0][holder.key].to_pylist() == ["released"] - assert markers[0]["owner"].to_pylist() == [None] - - -def test_a_failed_state_read_before_clear_is_a_lease_error( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch -) -> None: - """An ordinary failure reading the state before a release marker is a chained - ``LeaseError`` naming the table ID; an interruption propagates unchanged.""" - holder = acquire(client, _PROJECT, _DATASET, owner="holder") - cause = TimeoutError("scan unavailable") - interrupted = KeyboardInterrupt("scan interrupted") - - def run() -> None: - clear(client, _PROJECT, _DATASET, holder.table_id, confirm_writer_stopped=True) - - def unavailable(*_args: object, **_kwargs: object) -> None: - raise cause - - def interrupt(*_args: object, **_kwargs: object) -> None: - raise interrupted - - with monkeypatch.context() as patch: - patch.setattr(fake.FakeKeyedTable, "scan", unavailable) - with pytest.raises(LeaseError, match=holder.table_id) as failed: - run() - patch.setattr(fake.FakeKeyedTable, "scan", interrupt) - with pytest.raises(KeyboardInterrupt) as caught: - run() - assert failed.value.__cause__ is cause - assert caught.value is interrupted - check(client, holder) - - -def test_clear_reports_a_failed_lookup_as_a_lease_error( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch -) -> None: - """A failed lookup in ``clear`` is a chained ``LeaseError`` and writes nothing.""" - holder = acquire(client, _PROJECT, _DATASET, owner="holder") - cause = TimeoutError("lookup unavailable") - - def unavailable(*_args: object, **_kwargs: object) -> None: - raise cause - - with monkeypatch.context() as patch: - patch.setattr(fake.FakeClient, "keyed_table", unavailable) - patch.setattr(fake.FakeClient, "keyed_table_by_id", unavailable) - with pytest.raises(LeaseError, match=holder.table_id) as failed: - clear( - client, _PROJECT, _DATASET, holder.table_id, confirm_writer_stopped=True - ) - assert failed.value.__cause__ is cause - check(client, holder) - - -def test_clear_refuses_a_table_that_is_not_the_newest_generation( - client: fake.FakeClient, -) -> None: - """``clear`` refuses, writing nothing, a user table with a lease-shaped key, an - older generation and a generation of another dataset.""" - older = acquire(client, _PROJECT, _DATASET, owner="older") - release(client, older) - holder = acquire(client, _PROJECT, _DATASET, owner="holder") - elsewhere = acquire(client, _PROJECT, "other", owner="elsewhere") - key = f"{SPIRAL_LEASE_KEY_PREFIX}{'b' * 32}" - user = client.project(_PROJECT).create_keyed_table( - _DATASET, "example", pa.schema([pa.field(key, pa.large_string(), False)]) - ) - for table_id in (user.resource_id, older.table_id, elsewhere.table_id): - before = client.keyed_table_by_id(table_id).version_id - with pytest.raises(LeaseError, match="not the newest") as refused: - clear(client, _PROJECT, _DATASET, table_id, confirm_writer_stopped=True) - assert table_id in str(refused.value) - assert client.keyed_table_by_id(table_id).version_id == before - check(client, holder) - check(client, elsewhere) - - -def test_interrupt_during_token_verification_releases_the_claim( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch -) -> None: - """An interruption while the created claim's token is verified releases the claim - after a fresh lookup confirms the token, and the interruption propagates.""" - recognize = spiraldb_lease.spiral_lease_key_column - interrupted = KeyboardInterrupt("interrupted during token verification") - calls: list[int] = [] - - def interrupt_first(keys: Sequence[str]) -> str | None: - calls.append(1) - if len(calls) == 1: - raise interrupted - return recognize(keys) - - with monkeypatch.context() as patch: - patch.setattr(spiraldb_lease, "spiral_lease_key_column", interrupt_first) - with pytest.raises(KeyboardInterrupt) as caught: - _ = acquire(client, _PROJECT, _DATASET, owner="first") - assert caught.value is interrupted - check(client, acquire(client, _PROJECT, _DATASET, owner="next")) - - -def test_interrupted_lost_reply_lookup_releases_the_claim( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch -) -> None: - """A create that commits but loses its reply, followed by an interruption during - the lost-reply lookup, releases the claim after a fresh lookup confirms the - caller's token; the interruption propagates. ``lose_reply`` commits the create - before it raises.""" - create = fake.FakeProject.create_keyed_table - open_by_name = fake.FakeClient.keyed_table - interrupted = KeyboardInterrupt("lost-reply lookup interrupted") - created: list[str] = [] - lookups: list[str] = [] - - def lose_reply( - project: fake.FakeProject, - dataset: str, - name: str, - key_schema: pa.Schema, - *, - exist_ok: bool = False, - ) -> fake.FakeKeyedTable: - _ = create(project, dataset, name, key_schema, exist_ok=exist_ok) - created.append(name) - raise TimeoutError("lost reply") - - def interrupt_first_lookup( - instance: fake.FakeClient, - project: str, - dataset: str, - name: str, - *, - asof: int | None = None, - ) -> fake.FakeKeyedTable: - if created and not lookups: - lookups.append(name) - raise interrupted - return open_by_name(instance, project, dataset, name, asof=asof) - - with monkeypatch.context() as patch: - patch.setattr(fake.FakeProject, "create_keyed_table", lose_reply) - patch.setattr(fake.FakeClient, "keyed_table", interrupt_first_lookup) - with pytest.raises(KeyboardInterrupt) as caught: - _ = acquire(client, _PROJECT, _DATASET, owner="first") - assert caught.value is interrupted - assert lookups == [spiral_lease_table_name(1)] - check(client, acquire(client, _PROJECT, _DATASET, owner="next")) diff --git a/tests/test_databases/test_spiraldb_round_trips.py b/tests/test_databases/test_spiraldb_round_trips.py new file mode 100644 index 000000000..71bd018aa --- /dev/null +++ b/tests/test_databases/test_spiraldb_round_trips.py @@ -0,0 +1,506 @@ +"""The SDK calls a job run makes on a writable SpiralDB database (ITL-1899). + +On the fake (``fake_spiral_sdk``): every call the run makes is recorded, and the calls +the run already has the answer to are not made. The counts in the comments are those of +the same run before ITL-1899. +""" + +from __future__ import annotations + +from collections import Counter +from collections.abc import Iterator +from dataclasses import dataclass +from typing import Any, cast + +import pyarrow as pa +import pytest + +from orcapod.databases import ( + ConnectorArrowDatabase, + spiral_database_identity, + spiraldb_connector, +) +from orcapod.databases.spiraldb_tables import RunState, SpiralDBTables +from orcapod.databases.spiraldb_write_scope import database_writes +from orcapod.types import CacheMode +from tests.test_databases import fake_spiral_sdk as fake +from tests.test_databases.test_spiraldb_writable_runs import ( + ENTRIES, + _database, # pyright: ignore[reportPrivateUsage] + _job, # pyright: ignore[reportPrivateUsage] + _rows, # pyright: ignore[reportPrivateUsage] + _run, # pyright: ignore[reportPrivateUsage] + root, # noqa: F401 # pyright: ignore[reportUnusedImport] # the fixture +) + +pytestmark = [ + pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning"), + pytest.mark.filterwarnings( + "ignore::orcapod.core.data_tags.DataTagMaterializationWarning" + ), +] + + +@dataclass(frozen=True) +class Call: + """One SDK call on a database table. + + Attributes: + kind: What it did: ``open by name``, ``open by id``, ``create``, + ``metadata read``, ``metadata write``, ``key schema read``, ``full read``, + ``key read``, ``one-row read``, ``append`` or ``listing``. + table: The table's name (``""`` for a listing). + ok: Whether it succeeded. + """ + + kind: str + table: str + ok: bool = True + + +def _name(table: fake.FakeKeyedTable) -> str: + """Return the name of a fake table from its listing record.""" + return table._table["name"] # pyright: ignore[reportPrivateUsage] + + +@pytest.fixture +def sdk_calls(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[Call]]: + """Record every SDK call on a database table, in order.""" + calls: list[Call] = [] + + def record(cls: Any, method: str, kind: str, table_of: Any) -> None: # pyright: ignore[reportExplicitAny] + """Wrap an SDK method to record its successes and failures.""" + original = getattr(cls, method) + + def recorded(self: Any, *args: Any, **kwargs: Any) -> Any: # pyright: ignore[reportExplicitAny] + """Record the call and its outcome, then return or raise as usual.""" + try: + result = original(self, *args, **kwargs) + except Exception: + name = table_of(self, args, None) + calls.append(Call(kind, name, ok=False)) + raise + name = table_of(self, args, result) + calls.append(Call(kind, name)) + return result + + monkeypatch.setattr(cls, method, recorded) + + record(fake.FakeClient, "keyed_table", "open by name", lambda s, a, r: a[2]) + record( + fake.FakeClient, + "keyed_table_by_id", + "open by id", + lambda s, a, r: "" if r is None else _name(r), + ) + record(fake.FakeProject, "create_keyed_table", "create", lambda s, a, r: a[1]) + record( + fake.FakeKeyedTable, "get_metadata", "metadata read", lambda s, a, r: _name(s) + ) + record( + fake.FakeKeyedTable, "set_metadata", "metadata write", lambda s, a, r: _name(s) + ) + record(fake.FakeKeyedTable, "schema", "key schema read", lambda s, a, r: _name(s)) + record(fake.FakeKeyedTable, "append", "append", lambda s, a, r: _name(s)) + scan = fake.FakeKeyedTable.scan + + def scanned( + table: fake.FakeKeyedTable, + *args: Any, + **kwargs: Any, # pyright: ignore[reportExplicitAny] + ) -> Any: # pyright: ignore[reportExplicitAny] + """Record a whole-table, projected key, or one-row scan.""" + columns = args[0] if args else kwargs.get("columns") + kind = ( + "one-row read" + if kwargs.get("limit") is not None + else "full read" + if columns is None + else "key read" + ) + try: + result = scan(table, *args, **kwargs) + except Exception: + calls.append(Call(kind, _name(table), ok=False)) + raise + calls.append(Call(kind, _name(table))) + return result + + monkeypatch.setattr(fake.FakeKeyedTable, "scan", scanned) + # Every listing of a dataset: the scope's catalog. + listing = spiraldb_connector._list_dataset # pyright: ignore[reportPrivateUsage] + + def listed(client: Any, project: str, dataset: str) -> dict[str, str]: # pyright: ignore[reportExplicitAny] + """Record the outcome of a dataset listing.""" + try: + result = listing(client, project, dataset) + except Exception: + calls.append(Call("listing", "", ok=False)) + raise + calls.append(Call("listing", "")) + return result + + monkeypatch.setattr(spiraldb_connector, "_list_dataset", listed) + yield calls + + +def _counts(calls: list[Call]) -> Counter[str]: + """Count the successful and failed calls of each kind separately.""" + return Counter(c.kind if c.ok else f"{c.kind} (failed)" for c in calls) + + +def _first_run(entry: str, calls: list[Call], rows: int = 3) -> None: + """Seed the dataset and discard the SDK calls made during seeding.""" + _ = _run(_job(_database(), table=_rows(rows)), entry) + calls.clear() + + +@pytest.mark.usefixtures("root") +def test_sdk_call_profile_records_a_failed_scan(sdk_calls: list[Call]) -> None: + db = _database() + path = ("fn", "rdb_v1") + db.add_records(path, _key_rows("a"), record_id_column="__record_id", flush=True) + table = fake.FakeClient().keyed_table( + "p", "d", spiral_database_identity.spiral_table_name(path) + ) + sdk_calls.clear() + with pytest.raises(KeyError, match="missing"): + _ = table.scan(["missing"]) + assert _counts(sdk_calls) == {"key read (failed)": 1} + + +@pytest.mark.usefixtures("root") +def test_sdk_call_profile_records_a_failed_listing_and_fallback( + sdk_calls: list[Call], monkeypatch: pytest.MonkeyPatch +) -> None: + _first_run("sync", sdk_calls) + get_json = spiraldb_connector._http_get_json # pyright: ignore[reportPrivateUsage] + + def fail_once(url: str, token: str | None) -> dict[str, Any]: + """Fail the implicit catalog listing and allow later explicit listings.""" + monkeypatch.setattr(spiraldb_connector, "_http_get_json", get_json) + raise TimeoutError("listing timed out") + + monkeypatch.setattr(spiraldb_connector, "_http_get_json", fail_once) + assert _run(_job(_database(), table=_rows(4)), "sync").ok + assert sdk_calls[0] == Call("listing", "", ok=False) + assert _counts(sdk_calls)["open by name"] > 0 + + +# ── item 2: names the run's listing shows absent ───────────────────────────── + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ENTRIES) +def test_a_first_run_opens_no_name_its_listing_shows_absent( + entry: str, sdk_calls: list[Call] +) -> None: + """The run lists its dataset once, at first use, + and never opens a name that listing does not show: it is created at once + (exclusive create), and judged absent until then. Before ITL-1899 the first run + failed 28 opens by name on the fake, one or more per computed row and table.""" + _ = _run(_job(_database(), table=_rows(3)), entry) + assert sdk_calls[0].kind == "listing" + # The node route runs two nodes separately, with a scope per run. + assert _counts(sdk_calls)["listing"] == (2 if entry == "node run" else 1) + assert [c for c in sdk_calls if c.kind == "open by name"] == [] + assert _counts(sdk_calls)["create"] == 5 + + +@pytest.mark.usefixtures("root") +def test_a_table_the_run_creates_is_found_after_its_listing_showed_it_absent() -> None: + """The run's listing is updated as the run creates a table: a later lookup of the + name finds it, through any connector of the run.""" + db, other = _database(), _database() + path = ("fn", "rdb_v1") + with database_writes([db, other]): + assert db.list_table_paths(("fn",)) == [] + assert not other.table_exists(path) + db.add_records( + path, + pa.table( + { + "__record_id": pa.array([b"r0"], pa.large_binary()), + "x": pa.array([1], pa.int64()), + "__data_context": ["std:v1:default"], + } + ), + record_id_column="__record_id", + flush=True, + ) + assert other.table_exists(path) + assert other.list_table_paths(("fn",)) == [path] + + +# ── item 3: a table read whole once per batch of writes ────────────────────── + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ENTRIES) +def test_new_rows_read_each_table_whole_once_per_batch_of_writes( + entry: str, sdk_calls: list[Call] +) -> None: + """Three new rows: every lookup of a row reads the run's kept rows, not the table + (10 whole reads before ITL-1899, two per computed row, growing with the rows). + A table is read again only after an append to it.""" + _first_run(entry, sdk_calls, rows=1) + _ = _run(_job(_database(), table=_rows(4)), entry) + reads = Counter(c.table for c in sdk_calls if c.kind == "full read") + assert sum(reads.values()) == 4 + # The cached source's table is read before and after its new rows are appended; + # every other table once. + assert sorted(reads.values()) == [1, 1, 2] + + +def _key_rows(*ids: str) -> pa.Table: + """Make one database row for each synthetic ID.""" + return pa.table( + { + "__record_id": pa.array([i.encode() for i in ids], pa.large_binary()), + "x": pa.array(range(len(ids)), pa.int64()), + "__data_context": ["std:v1:default"] * len(ids), + } + ) + + +@pytest.mark.usefixtures("root") +def test_kept_rows_are_what_a_fresh_read_gives() -> None: + """Rows kept by a read in the scope are what a read of the service gives, also + after another connector of the run appends to the table: an append drops them.""" + db, other = _database(), _database() + path = ("fn", "rdb_v1") + + def fresh() -> list[bytes]: + """Read IDs from the service through a connector outside the scope.""" + read = ConnectorArrowDatabase( + spiraldb_connector.SpiralDBConnector("p", "d", writable=True) + ).get_all_records(path, record_id_column="__record_id") + assert read is not None + return sorted(cast("list[bytes]", read.column("__record_id").to_pylist())) + + def kept(database: ConnectorArrowDatabase) -> list[bytes]: + """Read IDs through a scoped connector that can reuse the kept rows.""" + read = database.get_all_records(path, record_id_column="__record_id") + assert read is not None + return sorted(cast("list[bytes]", read.column("__record_id").to_pylist())) + + with database_writes([db, other]): + db.add_records(path, _key_rows("a"), record_id_column="__record_id", flush=True) + assert kept(db) == kept(other) == fresh() == [b"a"] + other.add_records( + path, _key_rows("b"), record_id_column="__record_id", flush=True + ) + assert kept(db) == kept(other) == fresh() == [b"a", b"b"] + db.add_records(path, _key_rows("c"), record_id_column="__record_id", flush=True) + assert kept(other) == kept(db) == fresh() == [b"a", b"b", b"c"] + + +@pytest.mark.usefixtures("root") +def test_rows_read_from_a_snapshot_older_than_an_append_are_not_kept( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A read whose snapshot was opened before an append of the run committed keeps + nothing: the next read reads the table again.""" + db, other = _database(), _database() + path = ("fn", "rdb_v1") + db.add_records(path, _key_rows("a"), record_id_column="__record_id", flush=True) + scan = fake.FakeKeyedTable.scan + + def scan_then_append( + table: fake.FakeKeyedTable, columns: list[str] | None = None, **kwargs: Any + ) -> fake.FakeScan: + """Hold the first whole scan at its original version while the peer appends.""" + old = scan(table, columns, **kwargs) + if columns is None and kwargs.get("limit") is None: + monkeypatch.setattr(fake.FakeKeyedTable, "scan", scan) + other.add_records( + path, _key_rows("b"), record_id_column="__record_id", flush=True + ) + return old + + with database_writes([db, other]): + tables = db._spiral # pyright: ignore[reportPrivateUsage] + assert isinstance(tables, SpiralDBTables) + state = tables._run_state # pyright: ignore[reportPrivateUsage] + assert isinstance(state, RunState) + monkeypatch.setattr(fake.FakeKeyedTable, "scan", scan_then_append) + old = db.get_all_records(path, record_id_column="__record_id") + assert old is not None and old["__record_id"].to_pylist() == [b"a"] + assert state.rows_by_table == {} + current = db.get_all_records(path, record_id_column="__record_id") + assert current is not None + assert sorted(cast("list[bytes]", current["__record_id"].to_pylist())) == [ + b"a", + b"b", + ] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("empty_table", [False, True]) +def test_key_checks_see_peer_appends_after_a_negative_judgment( + empty_table: bool, sdk_calls: list[Call] +) -> None: + db, peer = _database(), _database() + path = ("fn", "rdb_v1") + tables = db._spiral # pyright: ignore[reportPrivateUsage] + assert isinstance(tables, SpiralDBTables) + name = tables.table_name(path) + if empty_table: + key = pa.field("__record_id", pa.large_binary(), nullable=False) + _ = ( + fake.FakeClient() + .project("p") + .create_keyed_table("d", name, pa.schema([key])) + ) + + with database_writes([db, peer]), tables.operation(): + ids = [b"a", b"b", b"missing"] + assert tables.existing_record_ids(name, ids) == set() + sdk_calls.clear() + assert tables.existing_record_ids(name, ids) == set() + assert sdk_calls == [] + peer.add_records( + path, _key_rows("a", "b"), record_id_column="__record_id", flush=True + ) + sdk_calls.clear() + assert tables.existing_record_ids(name, ids) == {b"a", b"b"} + assert sdk_calls == [] + + +@pytest.mark.usefixtures("root") +def test_key_refresh_after_a_lost_reply_preserves_other_table_judgments( + monkeypatch: pytest.MonkeyPatch, +) -> None: + db, peer = _database(), _database() + left, right = ("left", "rdb_v1"), ("right", "rdb_v1") + tables = db._spiral # pyright: ignore[reportPrivateUsage] + assert isinstance(tables, SpiralDBTables) + left_name, right_name = tables.table_name(left), tables.table_name(right) + append = fake.FakeKeyedTable.append + + def lose_reply(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: + """Lose the reply after the fake service commits the new key.""" + _ = append(table, batch) + raise fake.SpiralError("the reply was lost") + + with database_writes([db, peer]): + with tables.operation(): + assert not tables.has_table(left_name) + assert not tables.has_table(right_name) + peer.add_records( + right, _key_rows("b"), record_id_column="__record_id", flush=True + ) + with monkeypatch.context() as patch: + patch.setattr(fake.FakeKeyedTable, "append", lose_reply) + with pytest.raises(Exception, match="the reply was lost"): + peer.add_records( + left, _key_rows("a"), record_id_column="__record_id", flush=True + ) + assert tables.existing_record_ids(left_name, [b"a"]) == {b"a"} + assert not tables.has_table(right_name) + assert tables.has_table(right_name) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("new_table", [False, True]) +def test_the_first_key_lookup_indexes_keys_without_a_second_read( + new_table: bool, sdk_calls: list[Call] +) -> None: + """Kept rows and first appends supply keys without allocating an eager Python set.""" + db = _database() + path = ("fn", "rdb_v1") + if not new_table: + db.add_records(path, _key_rows("a"), record_id_column="__record_id", flush=True) + with database_writes([db]): + tables = db._spiral # pyright: ignore[reportPrivateUsage] + assert isinstance(tables, SpiralDBTables) + state = tables._run_state # pyright: ignore[reportPrivateUsage] + assert isinstance(state, RunState) + if new_table: + db.add_records( + path, _key_rows("a"), record_id_column="__record_id", flush=True + ) + (keys,) = state.keys_by_table.values() + assert isinstance(keys, pa.ChunkedArray) + else: + assert db.get_all_records(path, record_id_column="__record_id") is not None + assert state.rows_by_table and not state.keys_by_table + name = tables.table_name(path) + sdk_calls.clear() + assert tables.holds_record_id(name, b"a") is True + assert list(state.keys_by_table.values()) == [{b"a"}] + assert not [ + c for c in sdk_calls if c.kind in {"full read", "key read", "one-row read"} + ] + db.add_records(path, _key_rows("b"), record_id_column="__record_id", flush=True) + assert tables.holds_record_id(name, b"b") is True + + +# ── item 4: what the run already knows ─────────────────────────────────────── + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ENTRIES) +def test_a_table_the_run_creates_is_not_read_back( + entry: str, sdk_calls: list[Call] +) -> None: + """A table this run's exclusive create made is used as the create returned it: no + reopen, no metadata or key schema read, no one-row read (before ITL-1899: 5 of + each on the fake).""" + _ = _run(_job(_database(), table=_rows(3)), entry) + counts = _counts(sdk_calls) + for kind in ("metadata read", "key schema read", "one-row read", "open by name"): + assert counts[kind] == 0, kind + # The manifest, then the holds-rows marker after the first append. + assert counts["metadata write"] == 10 + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ENTRIES) +@pytest.mark.parametrize("scenario", ["new row", "held rerun", "REPLAY"]) +def test_each_existing_table_is_identified_once_per_run( + entry: str, scenario: str, sdk_calls: list[Call] +) -> None: + """Each existing table is opened by name, and its key schema and metadata read, + once per run, shared by the run's connectors and its listing (before ITL-1899: + 9 or 10 metadata reads for 5 tables, and 9 to 34 opens by id).""" + _first_run(entry, sdk_calls, rows=1 if scenario == "new row" else 4) + cache_mode = CacheMode.REPLAY if scenario == "REPLAY" else CacheMode.LOG + _ = _run(_job(_database(), table=_rows(4), cache_mode=cache_mode), entry) + counts = _counts(sdk_calls) + tables = {c.table for c in sdk_calls if c.kind == "open by name"} + assert len(tables) == counts["open by name"] == 5 + assert counts["key schema read"] == 5 + assert counts["metadata read"] == 5 + # Cold cache freshness checks make one additional projected source-table read. + assert ( + counts["open by id"] <= {"new row": 11, "held rerun": 6, "REPLAY": 5}[scenario] + ) + assert counts["key read"] <= 2 + + +@pytest.mark.usefixtures("root") +def test_what_a_run_read_is_forgotten_when_its_scope_ends() -> None: + """The run's shared reads (key index, listing, rows, records) end with the run.""" + db = _database() + path = ("fn", "rdb_v1") + rows = pa.table( + { + "__record_id": pa.array([b"a"], pa.large_binary()), + "x": pa.array([1], pa.int64()), + "__data_context": ["std:v1:default"], + } + ) + tables = db._spiral # pyright: ignore[reportPrivateUsage] + assert isinstance(tables, SpiralDBTables) + with database_writes([db]): + db.add_records(path, rows, record_id_column="__record_id", flush=True) + _ = db.list_table_paths(("fn",)) + _ = db.get_all_records(path) + state = tables._run_state # pyright: ignore[reportPrivateUsage] + assert isinstance(state, RunState) + assert state.rows_by_table and state.found_by_id and state.catalog + assert tables._run_state is None # pyright: ignore[reportPrivateUsage] + assert not state.rows_by_table and not state.found_by_id + assert not state.keys_by_table and not state.ids_by_name + assert state.catalog is None diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index 489fcbadb..93c8cb106 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -1,8 +1,7 @@ """A SpiralDB connector in writable mode, under ``ConnectorArrowDatabase`` (ITL-1840). On the fake (``fake_spiral_sdk``); no live SpiralDB. A ``SpiralDBConnector`` built -with ``writable=True``. Direct writes hold the dataset's writer lease for the whole test -(``writable_connector(held=True)``), as a job run does for its own (ITL-1844). The tests cover each +with ``writable=True``. The tests cover each table kind's layout written and read back, the write rules of ITL-1386, refusals of tables that are not the database's, the data-context checks and the listing the stale-layout check uses. @@ -13,6 +12,7 @@ import datetime as dt import json from collections.abc import Iterator +from contextlib import nullcontext from decimal import Decimal from pathlib import Path from typing import Any, cast @@ -33,8 +33,7 @@ from orcapod.databases import spiral_database_identity as identity from orcapod.databases.spiral_database_identity import SpiralTableCollisionError from orcapod.databases.spiraldb_tables import SpiralDBTables -from orcapod.databases.spiraldb_write_scope import database_writes, take_lease -from orcapod.databases.store_table_names import is_spiral_lease_table_name +from orcapod.databases.spiraldb_write_scope import database_writes from orcapod.errors import ( InputValidationError, OrcapodDatabaseReadError, @@ -54,47 +53,15 @@ utc = dt.timezone.utc -# The writer lease each dataset written directly holds for the test: (check, release). -_test_leases: dict[tuple[str, str], tuple[Any, Any]] = {} - - @pytest.fixture def root(tmp_path: Path) -> Iterator[Path]: with fake.install(tmp_path): - try: - yield tmp_path - finally: - _release_test_leases() - - -def _release_test_leases() -> None: - """Release every test lease, each attempted, and forget them all; then raise the - first failed release, so a later test never inherits a lease of this one.""" - leases = list(_test_leases.values()) - _test_leases.clear() - failure: BaseException | None = None - for _, release in leases: - try: - release() - except BaseException as exc: # noqa: BLE001 # every lease is released; the first failure is raised below - failure = failure or exc - if failure is not None: - raise failure - - -def writable_connector( - project: str = "p", dataset: str = "d", *, held: bool = True -) -> SpiralDBConnector: - """A writable connector; ``held`` writes it directly under the dataset's writer lease, - taken once per test (a job run takes its own: pass ``held=False``).""" - connector = SpiralDBConnector(project, dataset, writable=True) - if held: - lease = _test_leases.get((project, dataset)) - if lease is None: - lease = take_lease(connector, "test") - _test_leases[(project, dataset)] = lease - tables_of(connector).hold_lease(lease[0]) - return connector + yield tmp_path + + +def writable_connector(project: str = "p", dataset: str = "d") -> SpiralDBConnector: + """A writable connector on the fake service.""" + return SpiralDBConnector(project, dataset, writable=True) def tables_of(connector: SpiralDBConnector) -> SpiralDBTables: @@ -132,12 +99,8 @@ def _table(name: str) -> Any: def _tables() -> list[dict[str, Any]]: - """The dataset tables, without the writer lease's generation tables.""" - return [ - t - for t in fake.FakeClient()._store.tables() # pyright: ignore[reportPrivateUsage] - if not is_spiral_lease_table_name(t["name"]) - ] + """The dataset tables.""" + return fake.FakeClient()._store.tables() # pyright: ignore[reportPrivateUsage] # ------------------------------------------------------------------ write and read @@ -327,7 +290,7 @@ def test_stored_ids_are_answered_by_one_key_column_read(asked: list[bytes]) -> N RESULT, rows(["r0", "r1", "r2", "r3"]), record_id_column="__record_id" ) db.flush() - tables = tables_of(writable_connector(held=False)) + tables = tables_of(writable_connector()) name = tables.table_name(RESULT) fake.scan_log.clear() fake.count_log.clear() @@ -807,6 +770,7 @@ def test_stale_layouts_are_found_by_their_recorded_paths() -> None: @pytest.mark.usefixtures("root") @pytest.mark.parametrize("kind", ["absent", "empty", "pending", "stored"]) def test_stale_context_counts_match_the_rows(kind: str) -> None: + """Count pending and stored rows for a stale context and omit empty tables.""" db = ConnectorArrowDatabase(writable_connector()) if kind == "empty": _make_table( @@ -842,9 +806,7 @@ def test_a_listed_table_recording_a_path_of_another_name_is_refused() -> None: with_rows=True, ) with pytest.raises(SpiralTableCollisionError, match="another name"): - _ = ConnectorArrowDatabase(writable_connector(held=False)).list_table_paths( - ("my_fn",) - ) + _ = ConnectorArrowDatabase(writable_connector()).list_table_paths(("my_fn",)) OTHER_FORMAT = "orcapod.spiral_database.v1" @@ -1084,9 +1046,9 @@ def _rename(table_name: str, new_name: str) -> None: @pytest.mark.usefixtures("root") def test_a_listed_table_renamed_since_its_record_was_read_is_refused() -> None: - # Listed outside a run: a run lists the dataset once, with its lease. - db = ConnectorArrowDatabase(writable_connector(held=False)) - with database_writes([db], owner="seed"): + # Listed outside a run: a run lists the dataset once, at first use. + db = ConnectorArrowDatabase(writable_connector()) + with database_writes([db]): db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) assert db.list_table_paths(("my_fn",)) == [RESULT] other = (*RESULT[:-1], "rdb_v9") @@ -1097,9 +1059,7 @@ def test_a_listed_table_renamed_since_its_record_was_read_is_refused() -> None: with pytest.raises(SpiralTableCollisionError, match="another name"): _ = db.list_table_paths(("my_fn",)) with pytest.raises(SpiralTableCollisionError, match="another name"): - _ = ConnectorArrowDatabase(writable_connector(held=False)).list_table_paths( - ("my_fn",) - ) + _ = ConnectorArrowDatabase(writable_connector()).list_table_paths(("my_fn",)) # ------------------------------------------------------ concurrent first writers @@ -1118,20 +1078,24 @@ def other_first(table_name: str) -> Any: tables._create_or_open = other_first # pyright: ignore[reportPrivateUsage] -def _interleaved(first_rows: pa.Table, second_rows: pa.Table) -> Any: +def _interleaved( + first_rows: pa.Table, second_rows: pa.Table +) -> tuple[ConnectorArrowDatabase, ConnectorArrowDatabase]: """Writer 1 judges the table absent; writer 2 then creates and fills it; then - writer 1 goes on. Returns writer 1's database.""" + writer 1 goes on. Both use the same write scope.""" first = writable_connector() db1 = ConnectorArrowDatabase(first) db1.add_records(RESULT, first_rows, record_id_column="__record_id") + peer = ConnectorArrowDatabase(writable_connector()) + def the_other_writer(_: str) -> None: - ConnectorArrowDatabase(writable_connector()).add_records( + peer.add_records( RESULT, second_rows, record_id_column="__record_id", flush=True ) _made_meanwhile(first, the_other_writer) - return db1 + return db1, peer def _reordered(table: pa.Table) -> pa.Table: @@ -1141,8 +1105,8 @@ def _reordered(table: pa.Table) -> pa.Table: @pytest.mark.usefixtures("root") def test_a_writer_never_overwrites_another_writers_manifest() -> None: other_schema = rows(["b0"]).drop_columns(["s"]) - db1 = _interleaved(rows(["a0"]), other_schema) - with pytest.raises(SpiralTableCollisionError): + db1, peer = _interleaved(rows(["a0"]), other_schema) + with database_writes([db1, peer]), pytest.raises(SpiralTableCollisionError): db1.flush() got = ConnectorArrowDatabase(writable_connector()).get_all_records( RESULT, record_id_column="__record_id" @@ -1161,8 +1125,9 @@ def test_a_writer_of_an_equivalent_manifest_appends_beside_another( other = rows(["b0"]).replace_schema_metadata({"y": "2", "x": "1"}) elif second == "column order": other = _reordered(other) - db1 = _interleaved(first, other) - db1.flush() + db1, peer = _interleaved(first, other) + with database_writes([db1, peer]): + db1.flush() got = ConnectorArrowDatabase(writable_connector()).get_all_records( RESULT, record_id_column="__record_id" ) @@ -1204,13 +1169,16 @@ def test_a_first_writer_keeps_the_rows_another_writer_stored_meanwhile( skip_duplicates=skip_duplicates, ) + peer = ConnectorArrowDatabase(writable_connector()) + def the_other_writer(_: str) -> None: - ConnectorArrowDatabase(writable_connector()).add_records( + peer.add_records( RESULT, rows(["r1"]), record_id_column="__record_id", flush=True ) _made_meanwhile(connector, the_other_writer) - db.flush() + with database_writes([db, peer]): + db.flush() got = ConnectorArrowDatabase(writable_connector()).get_all_records( RESULT, record_id_column="__record_id" ) @@ -1274,8 +1242,6 @@ def test_a_closed_writable_connector_refuses_every_call_and_releases_its_tables( with pytest.raises(RuntimeError, match="closed"): _ = call() # the connector sharing its client keeps its own reference; it has its own - # database tables, so the test's lease is attached to them too (as a run attaches it) - tables_of(shared).hold_lease(_test_leases[("p", "d")][0]) other = ConnectorArrowDatabase(shared) other.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) assert other.table_exists(RESULT) @@ -1359,14 +1325,14 @@ def _cleared() -> Iterator[None]: @pytest.mark.parametrize("orchestrator", ["sync", "async"]) def test_every_table_kind_is_written_and_read_back(orchestrator: str) -> None: run = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} - database = ConnectorArrowDatabase(writable_connector(held=False)) + database = ConnectorArrowDatabase(writable_connector()) _ = _job(database, SOURCE_ROWS).run(orchestrator=run[orchestrator]()) - # A cached source read outside a job run writes under a lease held here. - with database_writes([database], owner="test"): + # A cached source read outside a job run writes under the scope opened here. + with database_writes([database]): cached = _cached(database).as_table() assert sorted(calls) == [1, 2, 3] and sorted(delivered) == [2, 4, 6] - fresh = ConnectorArrowDatabase(writable_connector(held=False)) + fresh = ConnectorArrowDatabase(writable_connector()) paths = fresh.list_table_paths() assert sorted(p[-1] for p in paths) == sorted(LAYOUTS) for path in paths: @@ -1382,7 +1348,7 @@ def test_every_table_kind_is_written_and_read_back(orchestrator: str) -> None: assert calls == [] and delivered == [] assert sorted(again.nodes["dbl"].as_table()["double"].to_pylist()) == [2, 4, 6] assert sorted(again.nodes["sel"].as_table()["double"].to_pylist()) == [2, 4, 6] - with database_writes([fresh], owner="test"): + with database_writes([fresh]): assert _cached(fresh).as_table().equals(cached) @@ -1392,7 +1358,7 @@ def test_a_new_input_adds_rows_to_every_table_and_keeps_the_others( orchestrator: str, ) -> None: run = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} - database = ConnectorArrowDatabase(writable_connector(held=False)) + database = ConnectorArrowDatabase(writable_connector()) _ = _job(database, SOURCE_ROWS[:2]).run(orchestrator=run[orchestrator]()) before = { p: database.get_all_records(p, record_id_column="__rid") @@ -1403,7 +1369,7 @@ def test_a_new_input_adds_rows_to_every_table_and_keeps_the_others( assert sorted(p[-1] for p in before) == sorted(k for k in LAYOUTS if k != "sdb_v2") calls.clear() delivered.clear() - fresh = ConnectorArrowDatabase(writable_connector(held=False)) + fresh = ConnectorArrowDatabase(writable_connector()) _ = _job(fresh, SOURCE_ROWS).run(orchestrator=run[orchestrator]()) assert calls == [3] and delivered == [6] for path, earlier in before.items(): @@ -1480,6 +1446,7 @@ def _failing_append(monkeypatch: pytest.MonkeyPatch, *, after_commit: bool) -> N append = fake.FakeKeyedTable.append def fail(self: Any, data: pa.Table) -> Any: + """Raise before storage, or after the service commits when requested.""" if after_commit: _ = append(self, data) raise fake.SpiralError("injected append failure") @@ -1551,8 +1518,8 @@ def recorded(table: fake.FakeKeyedTable, metadata: dict[str, bytes]) -> None: assert sets[1] == {mark: b"1"} fake.count_log.clear() - by_name = ConnectorArrowDatabase(writable_connector(held=False)) - by_listing = ConnectorArrowDatabase(writable_connector(held=False)) + by_name = ConnectorArrowDatabase(writable_connector()) + by_listing = ConnectorArrowDatabase(writable_connector()) assert by_name.get_table_schema(RESULT) is not None assert by_listing.list_table_paths(("my_fn",)) == [RESULT] assert len([scan for scan in fake.count_log if scan.limit == 1]) == ( @@ -1703,20 +1670,21 @@ def test_an_older_identifier_found_only_at_flush_is_refused( def test_a_resolved_table_is_read_and_written_by_its_id( through: str, ) -> None: - """A connection keeps the original ID. A fresh connection checks the current name.""" + """A scope keeps its resolved ID. A fresh connection checks the current name.""" db = ConnectorArrowDatabase(writable_connector()) - _add(db, rows(["r0"]), flush=True) - name = identity.spiral_table_name(RESULT) - _rename(name, "renamed_away") - fake.FakeClient().project("p").create_keyed_table( - "d", name, pa.schema([pa.field("foreign", pa.int64(), nullable=False)]) - ) - with pytest.raises(SpiralTableCollisionError): - _get(ConnectorArrowDatabase(writable_connector())) - db.refresh_table(RESULT) - if through == "write": - _add(db, rows(["r1"]), flush=True) - got = _get(db) + with database_writes([db]): + _add(db, rows(["r0"]), flush=True) + name = identity.spiral_table_name(RESULT) + _rename(name, "renamed_away") + fake.FakeClient().project("p").create_keyed_table( + "d", name, pa.schema([pa.field("foreign", pa.int64(), nullable=False)]) + ) + with pytest.raises(SpiralTableCollisionError): + _get(ConnectorArrowDatabase(writable_connector())) + db.refresh_table(RESULT) + if through == "write": + _add(db, rows(["r1"]), flush=True) + got = _get(db) assert got is not None assert sorted(_record_ids(got)) == ( [b"r0", b"r1"] if through == "write" else [b"r0"] @@ -1725,7 +1693,7 @@ def test_a_resolved_table_is_read_and_written_by_its_id( @pytest.mark.usefixtures("root") def test_a_fresh_connection_resolves_a_replacement_by_name() -> None: - """Only a fresh connection resolves the name to the replacement.""" + """A fresh connection resolves the name while an unscoped read keeps its ID.""" db = ConnectorArrowDatabase(writable_connector()) _add(db, rows(["r0"]), flush=True) name = identity.spiral_table_name(RESULT) @@ -1819,7 +1787,7 @@ def test_a_database_backed_job_holds_its_rows_and_reports_observer_losses( _database, # pyright: ignore[reportPrivateUsage] ) - database = ConnectorArrowDatabase(writable_connector(held=False)) + database = ConnectorArrowDatabase(writable_connector()) job = _job(database, SOURCE_ROWS) def run(**kwargs: Any) -> Any: @@ -1910,7 +1878,7 @@ def test_rows_with_the_same_older_identifier_append( def _counted(monkeypatch: pytest.MonkeyPatch) -> dict[str, int]: - """Count the fake's name opens, ID opens and full key reads.""" + """Count the fake's name opens, ID opens and full key reads of database tables.""" counts = {"names": 0, "ids": 0, "key_reads": 0} keyed_table = fake.FakeClient.keyed_table keyed_table_by_id = fake.FakeClient.keyed_table_by_id @@ -1921,8 +1889,9 @@ def open_by_name(self: Any, *args: Any, **kwargs: Any) -> Any: return keyed_table(self, *args, **kwargs) def open_by_id(self: Any, *args: Any, **kwargs: Any) -> Any: + table = keyed_table_by_id(self, *args, **kwargs) counts["ids"] += 1 - return keyed_table_by_id(self, *args, **kwargs) + return table def counted_scan(self: Any, *args: Any, **kwargs: Any) -> Any: if args and kwargs.get("limit") is None: @@ -1939,19 +1908,20 @@ def counted_scan(self: Any, *args: Any, **kwargs: Any) -> Any: def test_flush_reuses_keys_and_opens_by_id_after_resolving_the_name( monkeypatch: pytest.MonkeyPatch, ) -> None: - """The first add indexes stored keys. Later flushes reuse and update the index.""" - db = ConnectorArrowDatabase(writable_connector(held=False)) - with database_writes([db], owner="seed"): + """The first add indexes stored keys. Later flushes reuse and update the index, and + open the table by id only to append to it (ITL-1899).""" + db = ConnectorArrowDatabase(writable_connector()) + with database_writes([db]): _add(db, rows(["r0", "r1"]), flush=True) - db = ConnectorArrowDatabase(writable_connector(held=False)) - with database_writes([db], owner="append"): + db = ConnectorArrowDatabase(writable_connector()) + with database_writes([db]): counts = _counted(monkeypatch) _add(db, rows(["r2", "r3"], offset=2)) assert counts == {"names": 1, "ids": 0, "key_reads": 1} db.flush() - assert counts == {"names": 1, "ids": 3, "key_reads": 1} + assert counts == {"names": 1, "ids": 1, "key_reads": 1} _add(db, rows(["r3", "r4"], offset=3), skip_duplicates=True, flush=True) - assert counts == {"names": 1, "ids": 5, "key_reads": 1} + assert counts == {"names": 1, "ids": 2, "key_reads": 1} got = _get(db) assert got is not None assert sorted(_record_ids(got)) == [ @@ -1967,7 +1937,7 @@ def test_flush_reuses_keys_and_opens_by_id_after_resolving_the_name( def test_name_misses_are_retried_until_the_table_exists( monkeypatch: pytest.MonkeyPatch, ) -> None: - reader = ConnectorArrowDatabase(writable_connector(held=False)) + reader = ConnectorArrowDatabase(writable_connector()) with monkeypatch.context() as patch: counts = _counted(patch) assert _get(reader) is None @@ -1983,18 +1953,23 @@ def test_name_misses_are_retried_until_the_table_exists( @pytest.mark.usefixtures("root") +@pytest.mark.parametrize("shared_scope", [False, True], ids=["direct", "shared"]) def test_ids_checked_by_two_handles_are_written_once( - monkeypatch: pytest.MonkeyPatch, + monkeypatch: pytest.MonkeyPatch, shared_scope: bool ) -> None: - """Two databases on one connector both find an ID absent. The second flush sees - the ID written by the first in the shared lease index and keeps its value.""" + """Keep the first value for a duplicate ID and reuse keys in a shared scope.""" connector = writable_connector() first, second = ConnectorArrowDatabase(connector), ConnectorArrowDatabase(connector) _add(first, rows(["r0"]), flush=True) - _add(first, rows(["r1"], offset=1)) - _add(second, rows(["r1"], offset=50)) - first.flush() - second.flush() + counts = _counted(monkeypatch) + with database_writes([first, second]) if shared_scope else nullcontext(): + _add(first, rows(["r1"], offset=1)) + _add(second, rows(["r1"], offset=50)) + first.flush() + key_reads_before_second_flush = counts["key_reads"] + second.flush() + if shared_scope: + assert counts["key_reads"] == key_reads_before_second_flush == 1 got = _get(ConnectorArrowDatabase(writable_connector())) assert got is not None assert {r["__record_id"]: r["a.b"] for r in got.to_pylist()} == { @@ -2054,7 +2029,7 @@ def test_a_key_committed_during_the_schema_check_is_kept() -> None: def commit_first(_schema: pa.Schema) -> None: _add(peer, rows(["r1"], offset=10), flush=True) - with db.guard_table_schema(RESULT, commit_first): + with database_writes([db, peer]), db.guard_table_schema(RESULT, commit_first): db.flush() got = _get(peer) assert got is not None @@ -2124,6 +2099,7 @@ def test_append_copies_sliced_empty_string_and_binary_list_children( written: list[pa.Table] = [] def captured(table: fake.FakeKeyedTable, batch: pa.Table) -> fake.FakeKeyedTable: + """Capture the Arrow buffers the SDK receives for database records.""" if "__record_id" in batch.column_names: written.append(batch) return append(table, batch) @@ -2140,6 +2116,27 @@ def captured(table: fake.FakeKeyedTable, batch: pa.Table) -> fake.FakeKeyedTable buf.address for buf in written[0]["__record_id"].chunks[0].buffers() if buf } assert not before & after + + def child_buffers(table: pa.Table) -> tuple[set[int], ...]: + """Return the buffer addresses of each sliced list's string or binary child.""" + nested = table["nested"].chunks[0] + assert isinstance(nested, pa.StructArray) + lists = ( + table["texts"].chunks[0], + nested.field("blobs"), + nested.field("optional"), + ) + addresses: list[set[int]] = [] + for column in lists: + assert isinstance(column, pa.LargeListArray) + addresses.append({buf.address for buf in column.values.buffers() if buf}) + return tuple(addresses) + + for original, appended in zip( + child_buffers(given), child_buffers(written[0]), strict=True + ): + assert original and appended + assert not original & appended got = _get(ConnectorArrowDatabase(connector)) assert got is not None assert by_id(got.select(given.column_names)).equals(by_id(given)) @@ -2372,7 +2369,7 @@ def test_a_stored_table_a_lookup_cannot_read_fails_a_continue_run( def build() -> Any: job = PipelineJob( - name=JOB, database=ConnectorArrowDatabase(writable_connector(held=False)) + name=JOB, database=ConnectorArrowDatabase(writable_connector()) ) with job: source = DictSource( @@ -2408,6 +2405,7 @@ def test_a_table_left_empty_by_a_failed_first_write_is_not_listed( db = ConnectorArrowDatabase(writable_connector()) def failing(table: fake.FakeKeyedTable, batch: pa.Table) -> fake.FakeKeyedTable: + """Reject the append without storing any rows.""" raise RuntimeError("the append failed") with monkeypatch.context() as patched: @@ -2498,11 +2496,14 @@ def test_a_partial_flush_releases_only_the_written_rows() -> None: @pytest.mark.usefixtures("root") +@pytest.mark.parametrize("existing", [False, True]) def test_the_schema_guard_checks_each_ordered_retry( - monkeypatch: pytest.MonkeyPatch, + monkeypatch: pytest.MonkeyPatch, existing: bool ) -> None: """A schema guard can reject the next retry after the first row commits.""" db = ConnectorArrowDatabase(writable_connector()) + if existing: + _add(db, rows(["stored"]), flush=True) _add(db, rows(["first", "second", "third"])) first = db.pending_result(RESULT, b"first") second = db.pending_result(RESULT, b"second") @@ -2510,6 +2511,7 @@ def test_the_schema_guard_checks_each_ordered_retry( append = fake.FakeKeyedTable.append def refuse_batch(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: + """Reject a multirow append before storage so single-row retries run.""" if batch.num_rows > 1: raise fake.SpiralError("retry each row") return append(table, batch) @@ -2529,7 +2531,59 @@ def check(schema: pa.Schema) -> None: assert not second.committed fresh = ConnectorArrowDatabase(writable_connector()) assert (stored := _get(fresh)) is not None - assert stored["__record_id"].to_pylist() == [b"first"] + expected = [b"first", b"stored"] if existing else [b"first"] + assert sorted(_record_ids(stored)) == expected + + +@pytest.mark.usefixtures("root") +def test_an_unprintable_append_error_does_not_strand_the_ordered_retry( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The failing row's error survives and its suffix's dependents are withdrawn.""" + + class UnprintableError(fake.SpiralError): + """An SDK append error whose message cannot be formatted.""" + + def __str__(self) -> str: + """Simulate a failing SDK error formatter.""" + raise RuntimeError("the append error cannot be formatted") + + db = ConnectorArrowDatabase(writable_connector()) + dependent_store = ConnectorArrowDatabase(writable_connector(dataset="dependents")) + ids = ["first", "second", "third"] + _add(db, rows(ids)) + for item in ids: + dependency = db.pending_result(RESULT, item.encode()) + assert dependency is not None + with dependent_store.guard_record(RESULT, item.encode(), dependency): + _add(dependent_store, rows([item])) + + append = fake.FakeKeyedTable.append + row_error = fake.SpiralError("the second row failed") + + def fail(table: fake.FakeKeyedTable, batch: pa.Table) -> fake.FakeKeyedTable: + """Refuse the batch and second row after allowing the first row to commit.""" + if batch.num_rows > 1: + raise UnprintableError() + if batch["__record_id"][0].as_py() == b"second": + raise row_error + return append(table, batch) + + with monkeypatch.context() as patched: + patched.setattr(fake.FakeKeyedTable, "append", fail) + with pytest.raises(fake.SpiralError) as raised: + db.flush_result_batch_in_order(RESULT, publish_records=True) + assert raised.value is row_error + + dependent_store.flush() + fresh = ConnectorArrowDatabase(writable_connector()) + assert (results := _get(fresh)) is not None + assert _record_ids(results) == [b"first"] + fresh_dependents = ConnectorArrowDatabase(writable_connector(dataset="dependents")) + assert (dependents := _get(fresh_dependents)) is not None + assert _record_ids(dependents) == [b"first"] + assert (queued_view := _get(dependent_store)) is not None + assert _record_ids(queued_view) == [b"first"] @pytest.mark.usefixtures("root") @@ -2563,6 +2617,69 @@ def check(schema: pa.Schema) -> None: assert sorted(_record_ids(stored)) == sorted(item.encode() for item in ids) +@pytest.mark.usefixtures("root") +def test_an_ordered_flush_propagates_a_lazy_snapshot_open_failure( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A one-shot open failure stops an ordered flush before it appends any rows.""" + db = ConnectorArrowDatabase(writable_connector()) + open_by_id = fake.FakeClient.keyed_table_by_id + error = fake.SpiralError("could not open the snapshot") + attempts: list[str] = [] + + def fail_once( + client: fake.FakeClient, table_id: str, *, asof: int | None = None + ) -> fake.FakeKeyedTable: + """Allow subsequent opens so an accidental ordered retry can succeed.""" + attempts.append(table_id) + if len(attempts) == 1: + raise error + return open_by_id(client, table_id, asof=asof) + + with database_writes([db]): + # Keep the manifest and key index in the same scope as the ordered flush. + _add(db, rows(["stored"]), flush=True) + _add(db, rows(["first", "second"])) + with monkeypatch.context() as patched: + patched.setattr(fake.FakeClient, "keyed_table_by_id", fail_once) + with pytest.raises(fake.SpiralError) as raised: + db.flush_result_batch_in_order(RESULT, publish_records=True) + + assert raised.value is error + assert len(attempts) == 1 + assert (stored := _get(ConnectorArrowDatabase(writable_connector()))) is not None + assert _record_ids(stored) == [b"stored"] + + +@pytest.mark.usefixtures("root") +def test_an_ordered_flush_propagates_a_failure_recording_a_new_table( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An SDK metadata error before the append must not start ordered retries.""" + db = ConnectorArrowDatabase(writable_connector()) + _add(db, rows(["first", "second"])) + error = fake.SpiralError("could not record table metadata") + set_metadata = fake.FakeKeyedTable.set_metadata + attempts = 0 + + def fail_once(table: fake.FakeKeyedTable, metadata: dict[str, bytes]) -> None: + """Fail on the first metadata write so an accidental retry can succeed.""" + nonlocal attempts + attempts += 1 + if attempts == 1: + raise error + set_metadata(table, metadata) + + with monkeypatch.context() as patched: + patched.setattr(fake.FakeKeyedTable, "set_metadata", fail_once) + with pytest.raises(fake.SpiralError) as raised: + db.flush_result_batch_in_order(RESULT, publish_records=True) + + assert raised.value is error + assert attempts == 1 + assert _get(ConnectorArrowDatabase(writable_connector())) is None + + # ------------------------------------- review round 7 (PR 692): CodeRabbit, final head @@ -2663,23 +2780,24 @@ def test_an_ambiguous_append_never_lets_another_connector_overwrite_its_key( monkeypatch: pytest.MonkeyPatch, order: str ) -> None: """Review B1: connector B checks a key from a snapshot opened before connector A, - under the same lease, appended it and lost the reply. B's check and flush read - the keys again under the lease's lock, so A's stored row is kept, as on main. + in the same scope, appended it and lost the reply. B's check and flush read + the keys again under the scope's lock, so A's stored row is kept, as on main. The pause is placed before B's key check through ``existing_record_ids``, the timing hook the reviewer's reproduction used; every act is a public call. """ import threading from concurrent.futures import ThreadPoolExecutor + from contextvars import copy_context - first = ConnectorArrowDatabase(writable_connector(held=False)) - second = ConnectorArrowDatabase(writable_connector(held=False)) + first = ConnectorArrowDatabase(writable_connector()) + second = ConnectorArrowDatabase(writable_connector()) ready, appended = threading.Event(), threading.Event() append = fake.FakeKeyedTable.append check = SpiralDBTables.existing_record_ids def lost_reply(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: - """Store the rows before losing the reply for the selected append.""" + """Commit the rows before simulating a lost reply for the selected key.""" result = append(table, batch) if b"r1" in batch.column("__record_id").to_pylist(): raise fake.SpiralError("the reply was lost") @@ -2699,12 +2817,12 @@ def peer() -> str: return "refused" return "accepted" - with database_writes([first, second], owner="test"): + with database_writes([first, second]): _add(first, rows(["r0"]), flush=True) _add(first, rows(["r1"], offset=10), skip_duplicates=True) with monkeypatch.context() as patch, ThreadPoolExecutor(1) as threads: patch.setattr(SpiralDBTables, "existing_record_ids", paused) - future = threads.submit(peer) + future = threads.submit(copy_context().run, peer) assert ready.wait(10) try: with monkeypatch.context() as lost: @@ -2713,9 +2831,9 @@ def peer() -> str: first.flush() finally: appended.set() - _ = future.result() + assert future.result() == "refused" second.flush() - got = _get(ConnectorArrowDatabase(writable_connector(held=False))) + got = _get(ConnectorArrowDatabase(writable_connector())) assert got is not None assert sorted(zip(_record_ids(got), got["a.b"].to_pylist())) == [ (b"r0", 0), @@ -2728,30 +2846,39 @@ def peer() -> str: def test_a_table_written_from_another_thread_is_reported_stale_at_once( revisions: tuple[str, ...], ) -> None: - """Review B3: the run's dataset listing is kept with its lease, so a table that - another connector of the run writes from a plain thread is in the next stale - report, as main reports it.""" + """A peer connector writing from a thread with the copied run context updates + the run's dataset listing, so the next stale report includes the table.""" from concurrent.futures import ThreadPoolExecutor + from contextvars import copy_context - first = ConnectorArrowDatabase(writable_connector(held=False)) - second = ConnectorArrowDatabase(writable_connector(held=False)) + first = ConnectorArrowDatabase(writable_connector()) + connector = writable_connector() + second = ConnectorArrowDatabase(connector) paths = [(*RESULT[:-2], revision, "rdb_v1") for revision in revisions] def stale() -> list[tuple[str, ...]]: found = find_stale_tables(first, name_path=RESULT[:1], result_revision="rev1") return sorted(entry.record_path for entry in found.tables) - with database_writes([first, second], owner="test"): + with database_writes([first, second]): + state = tables_of(connector)._run_state # pyright: ignore[reportPrivateUsage] + assert state is not None + + def write_in_run(path: tuple[str, ...]) -> None: + """Verify the worker reuses the caller's run state before writing. + + Args: + path: Record path to write from the worker. + """ + assert tables_of(connector)._run_state is state # pyright: ignore[reportPrivateUsage] + second.add_records( + path, rows(["key"]), record_id_column="__record_id", flush=True + ) + assert stale() == [] with ThreadPoolExecutor(1) as threads: for path in reversed(paths): - threads.submit( - second.add_records, - path, - rows(["key"]), - record_id_column="__record_id", - flush=True, - ).result() + threads.submit(copy_context().run, write_in_run, path).result() assert stale() == sorted(paths) assert stale() == sorted(paths) @@ -2804,13 +2931,13 @@ def test_an_ambiguous_first_append_is_reported_stale_at_once( import asyncio first, second, third = ( - ConnectorArrowDatabase(writable_connector(held=False)) for _ in range(3) + ConnectorArrowDatabase(writable_connector()) for _ in range(3) ) paths = [(*RESULT[:-2], revision, "rdb_v1") for revision in ("rev0", "rev2")] append = fake.FakeKeyedTable.append def lost_reply(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: - """Store the rows before losing the reply for a database table append.""" + """Commit the keyed rows before simulating a lost reply.""" result = append(table, batch) if "__record_id" in batch.column_names: raise fake.SpiralError("the reply was lost") @@ -2841,7 +2968,7 @@ async def exercise() -> None: await asyncio.create_task(asyncio.to_thread(write, third, paths[1])) assert stale() == sorted(paths) - with database_writes([first, second, third], owner="test"): + with database_writes([first, second, third]): asyncio.run(exercise()) assert stale() == sorted(paths) @@ -2849,18 +2976,18 @@ async def exercise() -> None: @pytest.mark.usefixtures("root") def test_reused_connector_resolves_replaced_table_on_next_write_scope() -> None: """A replacement between write scopes receives the next scope's writes.""" - database = ConnectorArrowDatabase(writable_connector(held=False)) - with database_writes([database], owner="initial write"): + database = ConnectorArrowDatabase(writable_connector()) + with database_writes([database]): _add(database, rows(["old"]), flush=True) name = identity.spiral_table_name(RESULT) client = fake.FakeClient() retired_id = client.keyed_table("p", "d", name).resource_id _rename(name, "retired") - replacement = ConnectorArrowDatabase(writable_connector(held=False)) - with database_writes([replacement], owner="replace table"): + replacement = ConnectorArrowDatabase(writable_connector()) + with database_writes([replacement]): _add(replacement, rows(["replacement"]), flush=True) - with database_writes([database], owner="write to replacement"): + with database_writes([database]): _add(database, rows(["new"]), flush=True) retired = client.keyed_table_by_id(retired_id).scan().to_table() diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index be2df8009..5d29fe1f4 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -1,4 +1,4 @@ -"""Job runs on a writable SpiralDB database: every table kind, the writer lease, save +"""Job runs on a writable SpiralDB database: every table kind, the writer scope, save and load (ITL-1844). On the fake (``fake_spiral_sdk``); no live SpiralDB. Each job is run on a writable @@ -41,20 +41,19 @@ from orcapod.databases import ( spiral_database_identity, spiraldb_connector, - spiraldb_lease, spiraldb_writable_registry, spiraldb_write_scope, ) from orcapod.databases.extension_aware_database import ExtensionAwareDatabase -from orcapod.databases.spiraldb_write_scope import database_writes, take_lease -from orcapod.databases.store_table_names import is_spiral_lease_table_name +from orcapod.databases.spiraldb_write_scope import database_writes +from orcapod.databases.write_lock import NoWriteLock, WriteLock, WriteLockHandle from orcapod.errors import ( RowFailuresWarning, - SpiralDBLeaseRequiredError, + SpiralDBScopeOpenError, UnboundSourceError, UnstorableColumnError, ) -from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.pipeline import AsyncPipelineOrchestrator from orcapod.pipeline import node_run from orcapod.pipeline.execution_context import ExecutionContext from orcapod.semantic_types.universal_converter import UniversalTypeConverter @@ -184,23 +183,32 @@ def root(tmp_path: Path) -> Iterator[Path]: delivered.clear() -def _database(dataset: str = "d") -> ConnectorArrowDatabase: - return ConnectorArrowDatabase(SpiralDBConnector("p", dataset, writable=True)) +def _database( + dataset: str = "d", *, write_lock: WriteLock | None = None +) -> ConnectorArrowDatabase: + """Open a fresh writable database handle with an optional lock provider.""" + return ConnectorArrowDatabase( + SpiralDBConnector("p", dataset, writable=True, write_lock=write_lock) + ) -def _database_tables(dataset: str = "d") -> list[str]: - return sorted( - t["name"] - for t in fake.FakeClient()._store.tables() # pyright: ignore[reportPrivateUsage] - if t["dataset"] == dataset and not is_spiral_lease_table_name(t["name"]) - ) +class _RecordingWriteLock(NoWriteLock): + """Record any attempt to acquire a write lock.""" + def __init__(self) -> None: + self.acquisitions: list[tuple[str, str]] = [] -def _lease_tables(dataset: str = "d") -> list[str]: + @override + def acquire(self, project_id: str, dataset: str) -> WriteLockHandle: + self.acquisitions.append((project_id, dataset)) + return super().acquire(project_id, dataset) + + +def _database_tables(dataset: str = "d") -> list[str]: return sorted( t["name"] for t in fake.FakeClient()._store.tables() # pyright: ignore[reportPrivateUsage] - if t["dataset"] == dataset and is_spiral_lease_table_name(t["name"]) + if t["dataset"] == dataset ) @@ -246,8 +254,6 @@ def _run(job: PipelineJob, entry: str, **kwargs: Any) -> Any: ENTRIES = ["sync", "async orchestrator", "run_async", "node run"] -# Leases one run of an entry takes: a node run runs two nodes, each with its own. -LEASES = {"sync": 1, "async orchestrator": 1, "run_async": 1, "node run": 2} # ------------------------------------------------------------ every table kind @@ -256,10 +262,11 @@ def _run(job: PipelineJob, entry: str, **kwargs: Any) -> Any: @pytest.mark.usefixtures("root") @pytest.mark.parametrize("entry", ["sync", "run_async"]) def test_overdeep_pipeline_path_is_refused_before_writes(entry: str) -> None: - database = _database().at("a", "b", "c", "d", "e") + lock = _RecordingWriteLock() + database = _database(write_lock=lock).at("a", "b", "c", "d", "e") with pytest.raises(ValueError, match=r"combine.*depth \d+ exceeds maximum 10"): _run(_job(database, result_database=_database("results")), entry) - assert _database_tables() == [] and _lease_tables() == [] + assert _database_tables() == [] and lock.acquisitions == [] assert calls == [] @@ -285,7 +292,8 @@ def test_sqlite_job_checks_the_pipeline_path_at_compile_time() -> None: def test_unsupported_job_column_is_refused_before_writes( entry: str, storage: str, name: str, values: pa.Array[Any] ) -> None: - database = _database() + lock = _RecordingWriteLock() + database = _database(write_lock=lock) tags = ["unit", "trial"] if storage == "pipeline tag": tags.append(name) @@ -311,7 +319,7 @@ def test_unsupported_job_column_is_refused_before_writes( pipeline_database=database.at(JOB), cache_mode=CacheMode.LOG ) _run(job, entry) - assert _database_tables() == [] and _lease_tables() == [] + assert _database_tables() == [] and lock.acquisitions == [] assert calls == [] @@ -327,8 +335,6 @@ def test_every_table_kind_is_stored_as_on_delta( _ = _run(_job(database, order=order), entry) assert sorted(p[-1] for p in spiral_db.list_table_paths()) == sorted(LAYOUTS) _same_tables(spiral_db, delta) - # Each run took the database's lease once and released it. - assert len(_lease_tables()) == LEASES[entry] @pytest.mark.usefixtures("root") @@ -337,8 +343,8 @@ def test_every_table_kind_is_stored_as_on_delta( def test_a_separate_result_database_is_stored_as_on_delta( root: Path, entry: str, dataset: str ) -> None: - """Results in a separate result database, on another dataset (two leases) or on - the same dataset through another connector (one lease), table by table as on + """Results in a separate result database, on another dataset (two scopes) or on + the same dataset through another connector (one scope), table by table as on Delta.""" spiral_db, results = _database(), _database("r" if dataset == "other" else "d") delta = DeltaTableDatabase(root / "delta") @@ -348,8 +354,6 @@ def test_a_separate_result_database_is_stored_as_on_delta( if dataset == "other": _same_tables(spiral_db, delta) _same_tables(results, delta_results) - assert len(_lease_tables("d")) == LEASES[entry] - assert len(_lease_tables("r")) == LEASES[entry] else: on_delta = sorted( [*delta.list_table_paths(), *delta_results.list_table_paths()] @@ -365,7 +369,6 @@ def test_a_separate_result_database_is_stored_as_on_delta( assert on_spiral.schema.names == expected.schema.names, path assert _types(on_spiral) == _types(expected), path assert _comparable(on_spiral) == _comparable(expected), path - assert len(_lease_tables("d")) == LEASES[entry] @pytest.mark.usefixtures("root") @@ -417,7 +420,7 @@ def counted(table_handle: fake.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any monkeypatch.setattr(fake.FakeKeyedTable, "scan", counted) _ = _run(job, entry) - # One read of the log, of its key column alone (the lease's key index). + # One read of the log, of its key column alone (the scope's key index). assert reads == [["__record_id"]] assert delivered == [] assert job.nodes["sink"].as_table().num_rows == 3 @@ -428,20 +431,22 @@ def counted(table_handle: fake.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any def test_stale_checks_share_the_dataset_listing_during_each_run( monkeypatch: pytest.MonkeyPatch, entry: str ) -> None: + """Every listing of the dataset in a run: the one the run makes on first use + (the run's catalog) serves every stale check (ITL-1899).""" listings: list[tuple[str, str]] = [] - list_tables = spiraldb_connector._list_keyed_tables # pyright: ignore[reportPrivateUsage] + list_tables = spiraldb_connector._list_dataset # pyright: ignore[reportPrivateUsage] def counted(client: Any, project: str, dataset: str) -> dict[str, str]: listings.append((project, dataset)) return list_tables(client, project, dataset) - monkeypatch.setattr(spiraldb_connector, "_list_keyed_tables", counted) + monkeypatch.setattr(spiraldb_connector, "_list_dataset", counted) for order in ORDERS: listings.clear() database = _database() separate_connector = _database().at(JOB, "results") _ = _run(_job(database, result_database=separate_connector, order=order), entry) - assert listings == [("p", "d")] * LEASES[entry] + assert listings == [("p", "d")] * (2 if entry == "node run" else 1) @pytest.mark.usefixtures("root") @@ -552,7 +557,7 @@ def partial_results(x: int, y: int) -> tuple[int, float]: @pytest.mark.usefixtures("root") -def test_a_loaded_job_reads_and_load_only_runs_take_no_lease(root: Path) -> None: +def test_a_loaded_job_reads_and_runs_load_only(root: Path) -> None: spiral_db = _database() job = _job(spiral_db) _ = job.run() @@ -561,28 +566,24 @@ def test_a_loaded_job_reads_and_load_only_runs_take_no_lease(root: Path) -> None text = saved.read_text() assert '"writable": true' in text assert not any(word in text.lower() for word in ("secret", "token", "private")) - leases = _lease_tables() loaded = PipelineJob.load(saved, database=_database()) for label in ("combine", "select"): stored = loaded.nodes[label].as_source().as_table() assert stored.num_rows == 3, label - # A load-only run of the loaded job writes nothing: it takes no lease. (Its cached - # source, over a connector database, is not rebuilt from the file.) + # Loading a saved job does not rebuild its cached source over the connector. _ = loaded.run(load_only=True) - assert _lease_tables() == leases @pytest.mark.usefixtures("root") @pytest.mark.parametrize("entry", ENTRIES) -def test_a_load_only_run_over_a_cached_source_holds_its_lease(entry: str) -> None: - """A cached source writes its cache when checked or read, so a load-only run takes - the lease of the cache's database; it writes no node's table.""" +def test_a_load_only_run_writes_new_cached_source_rows(entry: str) -> None: + """A load-only run can write new cached source rows while leaving node tables + unchanged.""" spiral_db = _database() _ = _job(spiral_db).run() before = {p: spiral_db.get_all_records(p) for p in spiral_db.list_table_paths()} job = _job(spiral_db, table=_rows(4)) _ = _run(job, entry, load_only=True) - assert len(_lease_tables()) == 1 + LEASES[entry] for path, rows in before.items(): now = spiral_db.get_all_records(path) assert now is not None and rows is not None @@ -698,7 +699,7 @@ def test_the_writable_flag_is_saved_without_credentials() -> None: _ = SpiralDBConnector("p", "d", writable="yes") # pyright: ignore[reportArgumentType] -# ------------------------------------------------------------------ the lease +# ------------------------------------------------------------------ the scope def _count_source_checks(job: PipelineJob) -> list[None]: @@ -709,6 +710,7 @@ def _count_source_checks(job: PipelineJob) -> list[None]: check = source.check_for_new_data def counted() -> bool: + """Record the source check before running it.""" checks.append(None) return check() @@ -716,152 +718,99 @@ def counted() -> bool: return checks -def _held_by_another_writer(dataset: str = "d") -> Callable[[], None]: - """Hold the dataset's lease as another writer would; returns its release.""" - _, release = take_lease( - SpiralDBConnector("p", dataset, writable=True), "another writer" - ) - return release - - @pytest.mark.usefixtures("root") @pytest.mark.parametrize("entry", ENTRIES) @pytest.mark.parametrize("load_only", [False, True]) -def test_a_second_writer_is_refused_before_anything( +def test_an_open_write_scope_refuses_a_run_before_checking_sources( entry: str, load_only: bool ) -> None: - release = _held_by_another_writer() - job = _job(_database()) + lock = _RecordingWriteLock() + database = _database(write_lock=lock) + job = _job(database) checks = _count_source_checks(job) - with pytest.raises(spiraldb_lease.LeaseBusyError, match="another writer"): - _ = _run(job, entry, load_only=load_only) + with database_writes([database]): + database.spiral_acquire_write_lock() + with pytest.raises(SpiralDBScopeOpenError): + _ = _run(job, entry, load_only=load_only) + assert lock.acquisitions == [("p", "d")] + assert checks == [] assert _database_tables() == [] assert calls == [] and delivered == [] - # Refused before any source was checked (a cached source writes its cache then). - assert checks == [] - # Once the other writer releases, the run goes ahead. - release() if not load_only: _ = _run(job, entry) assert len(calls) == 3 - assert checks != [] # the counter sees the checks a run makes - - -@pytest.mark.usefixtures("root") -def test_a_second_writer_on_the_result_database_is_refused() -> None: - release = _held_by_another_writer("r") - job = _job(_database(), result_database=_database("r")) - with pytest.raises(spiraldb_lease.LeaseBusyError): - _ = job.run() - assert _database_tables("d") == [] and _database_tables("r") == [] - # The lease the run took on its own database was released. - _, own = take_lease(SpiralDBConnector("p", "d", writable=True), "check") - own() - release() + assert checks @pytest.mark.usefixtures("root") -@pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) -def test_the_lease_is_released_when_a_run_fails(entry: str) -> None: - @function_pod(output_keys="z") - def boom(x: int) -> int: - raise RuntimeError("boom") - - spiral_db = _database() - job = PipelineJob(name=JOB, database=spiral_db) - with job: - source = _cached(spiral_db, _rows()) - boom.pod(source.select_data_columns(["x"]), label="boom") - orchestrator = ( - SyncPipelineOrchestrator(error_policy="fail_fast") - if entry == "sync" - else AsyncPipelineOrchestrator(error_policy="fail_fast") - ) - with pytest.raises(Exception, match="boom"): - if entry == "run_async": - assert isinstance(orchestrator, AsyncPipelineOrchestrator) - _ = asyncio.run(job.run_async(orchestrator=orchestrator)) - else: - _ = job.run(orchestrator=orchestrator) - # Released: another writer can take it. - _held_by_another_writer()() - - -@pytest.mark.usefixtures("root") -def test_a_failed_release_after_a_run_raises_and_the_tables_are_complete( - root: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - spiral_db = _database() - - def failing(client: Any, lease: Any) -> None: - raise spiraldb_lease.LeaseError("release lost") - - monkeypatch.setattr(spiraldb_lease, "release", failing) - with pytest.raises(spiraldb_lease.LeaseError, match="release lost"): - _ = _job(spiral_db).run() - monkeypatch.undo() - delta = DeltaTableDatabase(root / "delta") - _ = _job(delta).run() - fresh = _database() - assert sorted(p[-1] for p in fresh.list_table_paths()) == sorted(LAYOUTS) - _same_tables(fresh, delta) +def test_an_open_result_scope_refuses_a_run_and_releases_its_pipeline_scope() -> None: + pipeline = _database() + results = _database("r", write_lock=_RecordingWriteLock()) + job = _job(pipeline, result_database=results) + checks = _count_source_checks(job) + with database_writes([results]): + results.spiral_acquire_write_lock() + with pytest.raises(SpiralDBScopeOpenError): + _ = job.run() + with database_writes([pipeline]): + pass + assert checks == [] + assert _database_tables() == [] and _database_tables("r") == [] @pytest.mark.usefixtures("root") -def test_a_release_whose_reopen_fails_after_a_run_raises_lease_error( - root: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """The service fails while the release reopens the lease table: the run raises - ``LeaseError`` (not the SDK's error), and its tables are complete.""" - real_release = spiraldb_lease.release - - def release_with_reopen_lost(client: Any, lease: Any) -> None: - def lost(*args: Any, **kwargs: Any) -> Any: - raise TimeoutError("the service did not answer") - - with monkeypatch.context() as patch: - patch.setattr(spiraldb_connector, "_open_keyed_table_by_id", lost) - real_release(client, lease) - - monkeypatch.setattr(spiraldb_lease, "release", release_with_reopen_lost) - with pytest.raises(spiraldb_lease.LeaseError) as raised: - _ = _job(_database()).run() - assert isinstance(raised.value.__cause__, TimeoutError) - monkeypatch.undo() - delta = DeltaTableDatabase(root / "delta") - _ = _job(delta).run() - _same_tables(_database(), delta) +def test_a_record_batch_reader_flushes_under_the_jobs_write_scope() -> None: + lock = _RecordingWriteLock() + database = _database(write_lock=lock) + path = ("snapshot", "rdb_v1") + reads: list[None] = [] + database.add_records( + path, + pa.table( + { + "__record_id": pa.array([b"snapshot"], pa.large_binary()), + "__data_context": [get_default_context().context_key], + "value": [1], + } + ), + record_id_column="__record_id", + ) + class SnapshotSource(ArrowTableSource): + TABLE_IS_ROWS = True -@pytest.mark.usefixtures("root") -def test_a_failed_release_after_a_failed_run_is_noted_on_its_error( - monkeypatch: pytest.MonkeyPatch, -) -> None: - @function_pod(output_keys="z") - def boom(x: int) -> int: - raise RuntimeError("boom") + @override + def pinned_snapshot(self) -> SnapshotSource: + """Keep this instrumented snapshot for the reader.""" + return self - def failing(client: Any, lease: Any) -> None: - raise spiraldb_lease.LeaseError("release lost") + @override + def snapshot_batch_streams(self) -> Iterator[StreamProtocol]: + """Flush from the reader before yielding the instrumented batch.""" + reads.append(None) + database.flush() + assert database.get_all_records(path) is not None + yield self - spiral_db = _database() - job = PipelineJob(name=JOB, database=spiral_db) - with job: - boom.pod(_cached(spiral_db, _rows()).select_data_columns(["x"]), label="boom") - monkeypatch.setattr(spiraldb_lease, "release", failing) - with pytest.raises(RuntimeError, match="boom") as raised: - _ = job.run(orchestrator=SyncPipelineOrchestrator(error_policy="fail_fast")) - assert any("release lost" in note for note in raised.value.__notes__) + source = SnapshotSource( + _rows(), + tag_columns=["unit", "trial"], + tag_only_columns=True, + source_id="snapshot", + ) + with PipelineJob(name=JOB, database=database) as job: + combine.pod(source, label="combine") + assert asyncio.run(job.run_async()).ok + assert reads == [None] + assert len(calls) == 3 + assert database.get_all_records(path) is not None + assert lock.acquisitions == [("p", "d")] @pytest.mark.usefixtures("root") -def test_a_database_write_outside_a_run_is_refused_before_anything() -> None: +def test_a_database_write_outside_a_run_uses_its_own_scope() -> None: spiral_db = _database() - with pytest.raises( - SpiralDBLeaseRequiredError, - match=r"through the connectors of a job run \(job\.run\(\)", - ): - _ = _cached(spiral_db, _rows()).as_table() + assert _cached(spiral_db, _rows()).as_table().num_rows == 3 spiral_db.add_records( ("t", "rdb_v1"), pa.table( @@ -873,9 +822,8 @@ def test_a_database_write_outside_a_run_is_refused_before_anything() -> None: ), record_id_column="__record_id", ) - with pytest.raises(SpiralDBLeaseRequiredError): - spiral_db.flush() - assert _database_tables() == [] and _lease_tables() == [] + spiral_db.flush() + assert spiral_db.get_all_records(("t", "rdb_v1")) is not None # ------------------------------------------- spiral-sdk's keyed-table deprecation @@ -884,50 +832,23 @@ def test_a_database_write_outside_a_run_is_refused_before_anything() -> None: @pytest.mark.usefixtures("root") @pytest.mark.parametrize("entry", ENTRIES) def test_a_job_run_on_a_database_raises_no_keyed_table_deprecation(entry: str) -> None: - """Every keyed-table open and create of a run (database tables, the schema table and - the lease generations) goes through the connector's helpers, which ignore the + """Every keyed-table open and create of a run (database tables, the schema table + and their associated metadata) goes through the connector's helpers, which ignore the SDK's keyed-table deprecation; a second run reopens every table.""" with warnings.catch_warnings(): warnings.simplefilter("error", DeprecationWarning) for _ in range(2): _ = _run(_job(_database(), result_database=_database("r")), entry) assert sorted(p[-1] for p in _database().list_table_paths()) != [] - assert len(_lease_tables("d")) == 2 * LEASES[entry] - - -@pytest.mark.usefixtures("root") -def test_the_lease_raises_no_keyed_table_deprecation() -> None: - """Acquire, check, release, a refused second writer and a clear by id: each open - and create of a generation table is the connector's.""" - connector = SpiralDBConnector("p", "d", writable=True) - with warnings.catch_warnings(): - warnings.simplefilter("error", DeprecationWarning) - check, release = take_lease(connector, "first") - check() - with pytest.raises(spiraldb_lease.LeaseBusyError) as refused: - _ = take_lease(connector, "second") - spiraldb_lease.clear( - fake.FakeClient(), - "p", - "d", - refused.value.table_id, - confirm_writer_stopped=True, - ) - _, again = take_lease(connector, "third") - again() - release() # cleared already: writing the same marker is harmless - # The SDK itself still warns on an open Orcapod did not make. - with pytest.warns(DeprecationWarning, match="Keyed tables are deprecated"): - _ = fake.FakeClient().keyed_table("p", "d", _lease_tables()[0]) # ------------------------------------------------ review round 1 (CodeRabbit, #693) @pytest.mark.usefixtures("root") -def test_a_retried_attachment_flush_runs_under_its_dataset_lease() -> None: +def test_a_retried_attachment_flush_runs_under_its_dataset_scope() -> None: """An attachment whose flush failed is retried by the next run, also after the node - was attached elsewhere; that run leases the old attachment's dataset too.""" + was attached elsewhere; that run scopes the old attachment's dataset too.""" job = _job(_database()) old = _database("a").at(JOB) job.nodes["select"].attach_databases( @@ -937,6 +858,7 @@ def test_a_retried_attachment_flush_runs_under_its_dataset_lease() -> None: failures: list[None] = [] def failing_once() -> None: + """Leave the first flush queued and delegate later attempts.""" if not failures: failures.append(None) raise RuntimeError("flush lost") @@ -949,10 +871,16 @@ def failing_once() -> None: job.nodes["select"].attach_databases( pipeline_database=_database("b").at(JOB), cache_mode=CacheMode.LOG ) + checks = _count_source_checks(job) + with database_writes([_database("a")]): + with pytest.raises(SpiralDBScopeOpenError): + _ = job.run() + assert checks == [] + assert _database_tables("a") == [] _ = job.run() - # The retry wrote the old attachment's operator cache, under a lease of its dataset. + assert checks + # The retry wrote the old attachment's operator cache, under a scope of its dataset. assert [p[-1] for p in _database("a").list_table_paths()] == ["odb_v3"] - assert len(_lease_tables("a")) == 2 def _wrapped(database: Any) -> ExtensionAwareDatabase: @@ -997,85 +925,77 @@ def test_a_wrapped_database_of_the_same_kind_loads(root: Path) -> None: @pytest.mark.usefixtures("root") -def test_a_job_on_a_wrapped_database_holds_its_lease_and_stores_as_on_delta( +def test_a_job_on_a_wrapped_database_holds_its_scope_and_stores_as_on_delta( root: Path, ) -> None: - """Lease discovery sees a writable SpiralDB database under an ``ExtensionAwareDatabase`` view: the run - takes the dataset's lease, writes every table kind, and a second writer waits on it.""" + """Scope discovery sees a writable SpiralDB database under an ``ExtensionAwareDatabase`` view: the run + takes the dataset's scope, writes every table kind, and shares its state across views.""" spiral_db = _database() delta = DeltaTableDatabase(root / "delta") _ = _job(_wrapped(spiral_db)).run() _ = _job(delta).run() - assert len(_lease_tables()) == 1 _same_tables(spiral_db, delta) - release = _held_by_another_writer() - with pytest.raises(spiraldb_lease.LeaseBusyError): - _ = _job(_wrapped(_database())).run() - release() + with database_writes([spiral_db]): + with pytest.raises(SpiralDBScopeOpenError): + _ = _job(_wrapped(_database()), table=_rows(4)).run() @pytest.mark.usefixtures("root") -def test_the_lease_key_keeps_the_service_address_of_construction() -> None: +def test_the_scope_key_keeps_the_service_address_of_construction() -> None: """Changing the caller's overrides after construction moves neither the client, the - lease nor the saved configuration to another service.""" + scope nor the saved configuration to another service.""" overrides = {"server.url": "https://one.example"} connector = SpiralDBConnector("p", "d", writable=True, overrides=overrides) - key = connector._writer_lease_key() # pyright: ignore[reportPrivateUsage] + key = connector._write_scope_key() # pyright: ignore[reportPrivateUsage] overrides["server.url"] = "https://two.example" - assert connector._writer_lease_key() == key # pyright: ignore[reportPrivateUsage] + assert connector._write_scope_key() == key # pyright: ignore[reportPrivateUsage] assert key[0] == "https://one.example" saved = connector.to_config() assert saved["overrides"] == {"server.url": "https://one.example"} saved["overrides"]["server.url"] = "https://three.example" assert connector.to_config()["overrides"] == {"server.url": "https://one.example"} loaded = SpiralDBConnector.from_config(connector.to_config()) - assert loaded._writer_lease_key() == key # pyright: ignore[reportPrivateUsage] + assert loaded._write_scope_key() == key # pyright: ignore[reportPrivateUsage] @pytest.mark.usefixtures("root") @pytest.mark.parametrize( "given", ["https://api.fake.invalid", "https://api.fake.invalid/"] ) -def test_connectors_reaching_one_service_share_one_lease(given: str) -> None: +def test_connectors_reaching_one_service_share_one_scope(given: str) -> None: """A writable connector with no address and one given the default address (also with - a final slash) reach one service: a run over both takes one lease, held by both - databases; another service keeps its own lease.""" + a final slash) reach one service and share scope state. A connector to another + service has a different identity and cannot open a competing scope for the pair.""" plain = SpiralDBConnector("p", "d", writable=True) addressed = SpiralDBConnector("p", "d", {"server.url": given}, writable=True) other = SpiralDBConnector( "p", "d", {"server.url": "https://other.invalid"}, writable=True ) databases = [ConnectorArrowDatabase(c) for c in (plain, addressed, other)] - key = plain._writer_lease_key() # pyright: ignore[reportPrivateUsage] - assert addressed._writer_lease_key() == key # pyright: ignore[reportPrivateUsage] - assert other._writer_lease_key() != key # pyright: ignore[reportPrivateUsage] - with spiraldb_write_scope.database_writes(databases[:2], owner="test"): - assert len(_lease_tables()) == 1 - held = [c._writable_tables()._lease_check for c in (plain, addressed)] # pyright: ignore[reportPrivateUsage, reportOptionalMemberAccess] + key = plain._write_scope_key() # pyright: ignore[reportPrivateUsage] + assert addressed._write_scope_key() == key # pyright: ignore[reportPrivateUsage] + assert other._write_scope_key() != key # pyright: ignore[reportPrivateUsage] + with spiraldb_write_scope.database_writes(databases[:2]): + with pytest.raises(SpiralDBScopeOpenError, match="p/d"): + with database_writes(databases[2:]): + pass + for database in databases[:2]: + database.spiral_acquire_write_lock() + held = [c._writable_tables()._run_state for c in (plain, addressed)] # pyright: ignore[reportPrivateUsage, reportOptionalMemberAccess] assert held[0] is not None and held[0] is held[1] - assert all(c._writable_tables()._lease_check is None for c in (plain, addressed)) # pyright: ignore[reportPrivateUsage, reportOptionalMemberAccess] + assert all(c._writable_tables()._run_state is None for c in (plain, addressed)) # pyright: ignore[reportPrivateUsage, reportOptionalMemberAccess] @pytest.mark.usefixtures("root") -def test_first_write_checks_a_shared_lease_once( - monkeypatch: pytest.MonkeyPatch, -) -> None: - """Count the state reads after acquisition across connectors and successive runs.""" - reads: list[str] = [] - scan = fake.FakeKeyedTable.scan - - def counted(table: fake.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any: - if kwargs.get("limit") == 3: - reads.append(table.resource_id) - return scan(table, *args, **kwargs) - - monkeypatch.setattr(fake.FakeKeyedTable, "scan", counted) - first, second = _database(), _database() +def test_first_write_acquires_the_shared_lock_once_per_scope() -> None: + """Only the first write acquires the lock across handles, anew for each run.""" + lock = _RecordingWriteLock() + first, second = _database(write_lock=lock), _database(write_lock=lock) for count, ids in enumerate((["a", "b"], ["d", "c"])): - with database_writes([first, second], owner="test"): - reads.clear() - for database in (first, second, first): - path = (f"table_{count}_{len(_database_tables())}", "rdb_v1") + with database_writes([first, second]): + assert lock.acquisitions == [("p", "d")] * count + for index, database in enumerate((first, second, first)): + path = (f"table_{count}_{index}", "rdb_v1") database.add_records( path, pa.table( @@ -1090,19 +1010,11 @@ def counted(table: fake.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any: record_id_column="__record_id", flush=True, ) - assert len(reads) == 1 - - checks: list[str] = [] - check = spiraldb_lease.check + assert lock.acquisitions == [("p", "d")] * (count + 1) - def counted_check(client: Any, lease: spiraldb_lease.Lease) -> None: - checks.append(lease.table_id) - check(client, lease) - - monkeypatch.setattr(spiraldb_lease, "check", counted_check) - with database_writes([first, second], owner="no writes"): + with database_writes([first, second]): pass - assert len(checks) == 1 # acquisition only + assert lock.acquisitions == [("p", "d")] * 2 @pytest.mark.usefixtures("root") @@ -1111,7 +1023,7 @@ def test_a_client_without_its_resolved_address_is_refused( monkeypatch: pytest.MonkeyPatch, native: str ) -> None: """A client that does not expose the address it resolved is refused when a run - takes the lease: no address is guessed, and no lease is taken.""" + takes the scope: no address is guessed, and no scope is taken.""" from types import SimpleNamespace connector = SpiralDBConnector("p", "d", writable=True) @@ -1123,15 +1035,14 @@ def test_a_client_without_its_resolved_address_is_refused( ) monkeypatch.setattr(connector, "_client", stand_in) with pytest.raises(RuntimeError, match="resolved"): - with database_writes([ConnectorArrowDatabase(connector)], owner="test"): + with database_writes([ConnectorArrowDatabase(connector)]): pass - assert _lease_tables() == [] monkeypatch.setattr(connector, "_client", client) @pytest.mark.usefixtures("root") def test_a_write_through_another_connector_during_a_run_is_refused() -> None: - """While a run holds the dataset's lease, a writable connector of its own (not one the + """While a run holds the dataset's scope, a writable connector of its own (not one the run holds) is still refused, and writes nothing.""" seen: list[BaseException] = [] @@ -1147,7 +1058,7 @@ def write_elsewhere(x: int) -> int: other.add_record(("elsewhere",), b"r", row, flush=False) try: other.flush() - except SpiralDBLeaseRequiredError as exc: + except SpiralDBScopeOpenError as exc: seen.append(exc) return x @@ -1160,46 +1071,10 @@ def write_elsewhere(x: int) -> int: assert _database().list_table_paths(("elsewhere",)) == [] -@pytest.mark.usefixtures("root") -@pytest.mark.parametrize("body_fails", [False, True]) -def test_an_interrupted_release_still_releases_every_other_lease( - monkeypatch: pytest.MonkeyPatch, body_fails: bool -) -> None: - """A release interrupted (KeyboardInterrupt) does not skip the other leases, and the - interruption raises once every release was attempted: after a failed body too, - chained from the body's error (never only a note on it).""" - real = spiraldb_lease.release - interrupted: list[None] = [] - - def interrupt_first(client: Any, lease: Any) -> None: - if not interrupted: - interrupted.append(None) - raise KeyboardInterrupt - real(client, lease) - - monkeypatch.setattr(spiraldb_lease, "release", interrupt_first) - databases = [_database("d"), _database("r")] - if body_fails: - with pytest.raises(KeyboardInterrupt) as raised: - with database_writes(databases, owner="test"): - raise RuntimeError("body") - cause = raised.value.__cause__ - assert isinstance(cause, RuntimeError) and str(cause) == "body" - else: - with pytest.raises(KeyboardInterrupt): - with database_writes(databases, owner="test"): - pass - monkeypatch.undo() - # The lease released after the interruption (the first one taken, released last - # in reverse order) can be taken again. - _, again = take_lease(SpiralDBConnector("p", "d", writable=True), "after") - again() - - -def test_a_job_with_no_writable_connector_in_the_process_takes_no_lease_and_walks_nothing( +def test_a_job_with_no_writable_connector_in_the_process_takes_no_scope_and_walks_nothing( monkeypatch: pytest.MonkeyPatch, ) -> None: - """With no writable SpiralDB connector in the process, a run builds no lease scope and + """With no writable SpiralDB connector in the process, a run builds no write scope and walks no graph for one: every entry (sync, async, node run, load-only) on a job with a cached source, a function node, a logged operator node and a sink.""" monkeypatch.setattr( @@ -1212,11 +1087,11 @@ def counting_walk(*args: Any, **kwargs: Any) -> list[Any]: walks.append(None) return real_walk(*args, **kwargs) - def no_lease(*args: Any, **kwargs: Any) -> Any: - raise AssertionError("a lease scope was built") + def no_scope(*args: Any, **kwargs: Any) -> Any: + raise AssertionError("a write scope was built") monkeypatch.setattr(node_run, "write_scope_databases", counting_walk) - monkeypatch.setattr(spiraldb_write_scope, "database_writes", no_lease) + monkeypatch.setattr(spiraldb_write_scope, "database_writes", no_scope) calls.clear() delivered.clear() job = _job(InMemoryArrowDatabase()) @@ -1230,11 +1105,11 @@ def no_lease(*args: Any, **kwargs: Any) -> Any: assert calls != [] -def test_a_writable_connector_in_the_process_makes_the_run_walk_for_leases( +def test_a_writable_connector_in_the_process_makes_the_run_walk_for_scopes( root: Path, monkeypatch: pytest.MonkeyPatch ) -> None: """The early return is only for a process without a writable connector: with one, the - run walks its graph (and takes the database's lease, as the other tests show).""" + run walks its graph (and takes the database's scope, as the other tests show).""" walks: list[None] = [] real_walk = node_run.write_scope_databases @@ -1247,7 +1122,6 @@ def counting_walk(*args: Any, **kwargs: Any) -> list[Any]: assert spiraldb_writable_registry.any_writable_connector() _ = _job(spiral_db).run() assert len(walks) == 1 - assert len(_lease_tables()) == 1 def _select_chain(n: int, database: Any) -> PipelineJob: @@ -1263,10 +1137,10 @@ def _select_chain(n: int, database: Any) -> PipelineJob: @pytest.mark.parametrize("load_only", [False, True]) -def test_the_lease_walk_visits_each_node_a_bounded_number_of_times( +def test_the_scope_walk_visits_each_node_a_bounded_number_of_times( monkeypatch: pytest.MonkeyPatch, load_only: bool ) -> None: - """The walk for a run's leases is linear in the graph: its attribute reads per node + """The walk for a run's scopes is linear in the graph: its attribute reads per node stay the same from a 51-node chain to a 401-node one (it was quadratic).""" def reads_per_node(n: int) -> float: @@ -1291,12 +1165,12 @@ def counting_getattr(obj: Any, name: str, *default: Any) -> Any: # ------------------------------------------------- review of 291798da3 (ITL-1844) -def test_a_job_on_a_shared_writable_connector_takes_the_lease_after_its_original_is_gone( +def test_a_job_on_a_shared_writable_connector_takes_the_scope_after_its_original_is_gone( root: Path, monkeypatch: pytest.MonkeyPatch ) -> None: """A writable connector's ``share_client`` copy is a registered writable connector: with the original closed and collected (and no other writable connector in the process), - a job on the copy still takes the lease and stores as on Delta.""" + a job on the copy still takes the scope and stores as on Delta.""" import gc monkeypatch.setattr( @@ -1307,6 +1181,7 @@ def test_a_job_on_a_shared_writable_connector_takes_the_lease_after_its_original original.close() del original _ = gc.collect() + assert spiraldb_writable_registry.any_writable_connector() spiral_db = ConnectorArrowDatabase(shared) delta = DeltaTableDatabase(root / "delta") assert _job(spiral_db).run().ok @@ -1319,7 +1194,7 @@ def test_a_job_on_a_writable_connector_and_its_shared_copy_runs( monkeypatch: pytest.MonkeyPatch, ) -> None: """A connector and its ``share_client`` copy bound in one run: the run takes ONE - lease of the dataset and attaches it to the database tables of both.""" + scope of the dataset and attaches it to the database tables of both.""" from orcapod.databases.spiraldb_tables import SpiralDBTables connector = SpiralDBConnector("p", "d", writable=True) @@ -1327,88 +1202,26 @@ def test_a_job_on_a_writable_connector_and_its_shared_copy_runs( shared = connector.share_client() results = ConnectorArrowDatabase(shared) held: list[tuple[object, object]] = [] - real_hold = SpiralDBTables.hold_lease + real_hold = SpiralDBTables.attach_run def recording_hold(self: Any, check: Any) -> None: held.append((self, check)) real_hold(self, check) - monkeypatch.setattr(SpiralDBTables, "hold_lease", recording_hold) + monkeypatch.setattr(SpiralDBTables, "attach_run", recording_hold) assert _job(spiral_db, result_database=results.at("results")).run().ok assert results.list_table_paths(("results",)) != [] - assert len(_lease_tables()) == 1 tables = [connector._writable_tables(), shared._writable_tables()] # pyright: ignore[reportPrivateUsage] assert len(held) == 2 and held[0][1] is held[1][1] assert {id(t) for t, _ in held} == {id(t) for t in tables} - # Released at the end: another writer can take the lease. - _, again = take_lease(SpiralDBConnector("p", "d", writable=True), "after") - again() - - -@pytest.mark.usefixtures("root") -@pytest.mark.parametrize("body_fails", [False, True]) -def test_an_interrupted_let_go_still_releases_every_lease( - monkeypatch: pytest.MonkeyPatch, body_fails: bool -) -> None: - """An interruption while a lease is let go of locally does not skip its remote - release nor the other leases': every lease can be taken again, and the - interruption raises (chained from a failed body's error).""" - from orcapod.databases.spiraldb_tables import SpiralDBTables - - real = SpiralDBTables.let_go_of_lease - interrupted: list[None] = [] - - def interrupt_first(self: Any, check: Any) -> None: - if not interrupted: - interrupted.append(None) - raise KeyboardInterrupt - real(self, check) - - monkeypatch.setattr(SpiralDBTables, "let_go_of_lease", interrupt_first) - databases = [_database("d"), _database("r")] - with pytest.raises(KeyboardInterrupt) as raised: - with database_writes(databases, owner="test"): - if body_fails: - raise RuntimeError("body") - if body_fails: - cause = raised.value.__cause__ - assert isinstance(cause, RuntimeError) and str(cause) == "body" - monkeypatch.undo() - for dataset in ("d", "r"): - _, again = take_lease(SpiralDBConnector("p", dataset, writable=True), "after") - again() - # The same databases run again: no lease was left attached to their tables. - with database_writes(databases, owner="next run"): + # A new scope can open after the run. + with database_writes([spiral_db]): pass -@pytest.mark.usefixtures("root") -def test_a_release_interruption_outranks_an_earlier_release_error( - monkeypatch: pytest.MonkeyPatch, -) -> None: - """After a successful body, a release that fails with an error and a later one - interrupted raise the interruption, with the error as a note on it.""" - real = spiraldb_lease.release - seen: list[None] = [] - - def fail_then_interrupt(client: Any, lease: Any) -> None: - seen.append(None) - real(client, lease) - if len(seen) == 1: - raise spiraldb_lease.LeaseError("first release failed") - raise KeyboardInterrupt - - monkeypatch.setattr(spiraldb_lease, "release", fail_then_interrupt) - with pytest.raises(KeyboardInterrupt) as raised: - with database_writes([_database("d"), _database("r")], owner="test"): - pass - assert len(seen) == 2 - assert any("first release failed" in note for note in raised.value.__notes__) - - -def test_a_decorator_result_database_on_a_database_is_leased(root: Path) -> None: +def test_a_decorator_result_database_on_a_database_is_scoped(root: Path) -> None: """A function pod's own result database (``@function_pod(result_database=...)``) - on a writable SpiralDB database is written under the run's lease on a cache miss, and a pod cache + on a writable SpiralDB database is written under the run's scope on a cache miss, and a pod cache database (``pod_cache_database``) too.""" on_spiral = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) pod_cache = ConnectorArrowDatabase(SpiralDBConnector("p", "g", writable=True)) @@ -1432,7 +1245,7 @@ def add(x: int, y: int) -> int: @pytest.mark.usefixtures("root") def test_a_write_through_a_shared_copy_outside_the_run_is_refused() -> None: - """A ``share_client`` copy is another connector: while a run holds the lease + """A ``share_client`` copy is another connector: while a run holds the scope through the original, a write through the copy (not part of the run) is refused and nothing is written.""" connector = SpiralDBConnector("p", "d", writable=True) @@ -1443,9 +1256,9 @@ def test_a_write_through_a_shared_copy_outside_the_run_is_refused() -> None: "v": pa.array([1], pa.int64()), } ) - with database_writes([ConnectorArrowDatabase(connector)], owner="run"): + with database_writes([ConnectorArrowDatabase(connector)]): outside.add_record(("elsewhere",), b"r", row, flush=False) - with pytest.raises(SpiralDBLeaseRequiredError): + with pytest.raises(SpiralDBScopeOpenError): outside.flush() assert _database().list_table_paths(("elsewhere",)) == [] @@ -1453,12 +1266,12 @@ def test_a_write_through_a_shared_copy_outside_the_run_is_refused() -> None: @pytest.mark.usefixtures("root") @pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) @pytest.mark.parametrize("cache", ["result_database", "pod_cache_database"]) -def test_a_bound_function_pod_stream_built_outside_the_job_is_leased( +def test_a_bound_function_pod_stream_built_outside_the_job_is_scoped( entry: str, cache: str ) -> None: """A function pod stream built outside the job (it becomes a bound slot) whose pod caches on a writable SpiralDB database (``result_database``, or a ``CachedFunctionPod`` through - ``pod_cache_database``) writes under the run's lease.""" + ``pod_cache_database``) writes under the run's scope.""" on_spiral = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) def add(x: int, y: int) -> int: @@ -1495,8 +1308,8 @@ def test_a_load_only_run_over_an_outside_function_pod_stream_is_refused_not_busy entry: str, ) -> None: """A load-only run reads no function pod stream built outside the job, so it takes - no lease of that pod's database: on a busy dataset it gives the refusal that says - how to run the input, never ``LeaseBusyError`` (review of de39bbc4c).""" + no scope of that pod's database: on a busy dataset it gives the refusal that says + how to run the input, never ``SpiralDBScopeOpenError`` (review of de39bbc4c).""" on_spiral = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) def add(x: int, y: int) -> int: @@ -1517,13 +1330,9 @@ def add(x: int, y: int) -> int: job = PipelineJob(name=JOB, database=_database()) with job: SelectDataColumns(["total"])(outside, label="select") - release = _held_by_another_writer("f") - try: - with pytest.raises(ValueError, match="function pod") as refused: + with database_writes([on_spiral]): + with pytest.raises(ValueError, match="function pod"): _ = _run(job, entry, load_only=True) - assert not isinstance(refused.value, spiraldb_lease.LeaseBusyError) - finally: - release() assert on_spiral.list_table_paths(("outside",)) == [] @@ -1566,8 +1375,8 @@ def test_a_load_only_run_reading_an_outside_pod_through_a_live_wrapper_is_refuse ) -> None: """A load-only run whose cached source reads an outside function pod's stream live (through a source's ``live_source_inputs``) is refused, as for a direct input, - before any lease is taken, any source checked or anything written (delta review of - 047dbe290: it reached an unleased write of the pod's results).""" + before any scope is taken, any source checked or anything written (delta review of + 047dbe290: it reached an unscoped write of the pod's results).""" on_pod = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) cache = ConnectorArrowDatabase(SpiralDBConnector("p", "c", writable=True)) @@ -1601,28 +1410,27 @@ def add(x: int, y: int) -> int: assert computed == [] for dataset in ("d", "f", "c"): assert _database_tables(dataset) == [], dataset - assert _lease_tables(dataset) == [], dataset @pytest.mark.usefixtures("root") -def test_a_run_refused_its_lease_keeps_the_last_runs_save_state(root: Path) -> None: - """A run refused with ``LeaseBusyError`` changes nothing: a save afterwards records - the last completed run's row counts as a save before it did (review of - de39bbc4c).""" +def test_a_run_refused_a_write_scope_keeps_the_last_runs_save_state(root: Path) -> None: + """A scope conflict stops run preparation before changing its saved row counts.""" job = _job(_database()) _ = job.run() before, after = root / "before.json", root / "after.json" + job.nodes["select"].attach_databases( + pipeline_database=_database("x").at(JOB), cache_mode=CacheMode.LOG + ) job.save(before) - expected = json.loads(before.read_text())["run"]["expected_rows"] - assert expected - release = _held_by_another_writer() - try: - with pytest.raises(spiraldb_lease.LeaseBusyError): + kept = json.loads(before.read_text())["run"] + assert kept["expected_rows"] + delivered.clear() + with database_writes([_database("x")]): + with pytest.raises(SpiralDBScopeOpenError): _ = job.run() - finally: - release() job.save(after) - assert json.loads(after.read_text())["run"].get("expected_rows") == expected + assert json.loads(after.read_text())["run"] == kept + assert delivered == [] # ------------------------------------------------- review of e1581afe9 (ITL-1844) @@ -1630,12 +1438,12 @@ def test_a_run_refused_its_lease_keeps_the_last_runs_save_state(root: Path) -> N @pytest.mark.usefixtures("root") def test_an_interrupted_hold_is_let_go_of(monkeypatch: pytest.MonkeyPatch) -> None: - """An interruption once a lease is attached to a database's tables (before the scope + """An interruption once a scope is attached to a database's tables (before the scope has recorded them) still lets go of it: the next run on the same databases is not refused.""" from orcapod.databases.spiraldb_tables import SpiralDBTables - real = SpiralDBTables.hold_lease + real = SpiralDBTables.attach_run interrupted: list[None] = [] def attach_then_interrupt(self: Any, check: Any) -> None: @@ -1644,86 +1452,24 @@ def attach_then_interrupt(self: Any, check: Any) -> None: interrupted.append(None) raise KeyboardInterrupt - monkeypatch.setattr(SpiralDBTables, "hold_lease", attach_then_interrupt) + monkeypatch.setattr(SpiralDBTables, "attach_run", attach_then_interrupt) databases = [_database("d")] with pytest.raises(KeyboardInterrupt): - with database_writes(databases, owner="interrupted"): + with database_writes(databases): pass monkeypatch.undo() - with database_writes(databases, owner="next run"): + with database_writes(databases): pass -@pytest.mark.usefixtures("root") -@pytest.mark.parametrize("datasets", [("d",), ("d", "r")]) -def test_an_interruption_once_the_lease_is_taken_still_releases_it( - monkeypatch: pytest.MonkeyPatch, datasets: tuple[str, ...] -) -> None: - """An interruption right after the lease is acquired (before the scope goes on) - still releases it: the claim was recorded inside the acquisition. Every dataset is - free afterwards.""" - real = spiraldb_write_scope.take_lease - taken: list[None] = [] - - def take_then_interrupt(*args: Any, **kwargs: Any) -> Any: - result = real(*args, **kwargs) - taken.append(None) - if len(taken) == len(datasets): - raise KeyboardInterrupt - return result - - monkeypatch.setattr(spiraldb_write_scope, "take_lease", take_then_interrupt) - databases = [_database(dataset) for dataset in datasets] - with pytest.raises(KeyboardInterrupt): - with database_writes(databases, owner="interrupted"): - pass - monkeypatch.undo() - for dataset in datasets: - _, release = take_lease(SpiralDBConnector("p", dataset, writable=True), "after") - release() - - -@pytest.mark.usefixtures("root") -@pytest.mark.parametrize("body", [asyncio.CancelledError, KeyboardInterrupt]) -def test_a_release_interruption_after_an_interrupted_body_is_raised( - monkeypatch: pytest.MonkeyPatch, body: type[BaseException] -) -> None: - """A body cancelled or interrupted, then a release interrupted: the release's - interruption is raised, chained from the body's, with an ordinary release error as - a note; every lease is released.""" - real = spiraldb_lease.release - seen: list[None] = [] - released = KeyboardInterrupt("release interrupted") - - def fail_then_interrupt(client: Any, lease: Any) -> None: - seen.append(None) - real(client, lease) - if len(seen) == 1: - raise spiraldb_lease.LeaseError("first release failed") - raise released - - monkeypatch.setattr(spiraldb_lease, "release", fail_then_interrupt) - stopped = body("body stopped") - with pytest.raises(KeyboardInterrupt) as raised: - with database_writes([_database("d"), _database("r")], owner="test"): - raise stopped - assert raised.value is released - assert raised.value.__cause__ is stopped - assert any("first release failed" in note for note in raised.value.__notes__) - monkeypatch.undo() - for dataset in ("d", "r"): - _, release = take_lease(SpiralDBConnector("p", dataset, writable=True), "after") - release() - - @pytest.mark.usefixtures("root") @pytest.mark.parametrize("job_database", ["in-memory", "spiral"]) -def test_an_ephemeral_result_database_on_a_database_is_leased( +def test_an_ephemeral_result_database_on_a_database_is_scoped( job_database: str, ) -> None: """A job's ephemeral result database (``set_ephemeral_database``) on a writable SpiralDB database is - written under the run's lease: the run succeeds, its results are stored there, and - the lease is released.""" + written under the run's scope: the run succeeds, its results are stored there, and + the scope is closed.""" from orcapod.types import NodeConfig database = InMemoryArrowDatabase() if job_database == "in-memory" else _database() @@ -1739,8 +1485,8 @@ def test_an_ephemeral_result_database_on_a_database_is_leased( assert len(paths) == 1 stored = fresh.get_all_records(paths[0]) assert stored is not None and stored.num_rows == len(_rows()) - _, release = take_lease(SpiralDBConnector("p", "e", writable=True), "after") - release() + with database_writes([fresh]): + pass def _held_table_over(upstream: Any) -> Any: @@ -1765,9 +1511,9 @@ def twice(x: int) -> int: @pytest.mark.usefixtures("root") -def test_a_held_table_does_not_lease_its_upstream_pods_database() -> None: +def test_a_held_table_does_not_scope_its_upstream_pods_database() -> None: """A run over a table that holds its rows reads no pod behind it (ITL-1121), so it - takes no lease of that pod's database: it runs while another writer holds it, and the + takes no scope of that pod's database: it runs while another writer holds it, and the pod is not called.""" on_spiral = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) called: list[int] = [] @@ -1789,25 +1535,22 @@ def add(x: int, y: int) -> int: ) ) node = _twice_over(_held_table_over(behind)) - _, release = take_lease(SpiralDBConnector("p", "f", writable=True), "another") - try: + with database_writes([on_spiral]): _ = node.run() - finally: - release() assert node.as_table().num_rows == 3 assert called == [] @pytest.mark.usefixtures("root") -def test_a_cached_source_behind_a_held_table_is_still_leased() -> None: +def test_a_cached_source_behind_a_held_table_is_still_scoped() -> None: """A run checks every source it finds, also behind a held table, and a check can - write a cached source's cache: its database stays among the run's leased databases.""" + write a cached source's cache: its database stays among the run's scoped databases.""" connector = SpiralDBConnector("p", "g", writable=True) cache = ConnectorArrowDatabase(connector) node = _twice_over(_held_table_over(_cached(cache.at("c"), _rows()))) databases = node_run.write_scope_databases([node], load_only=False) - leased = spiraldb_write_scope.writable_connectors(databases) - assert any(c is connector for c in leased) + scoped = spiraldb_write_scope.writable_connectors(databases) + assert any(c is connector for c in scoped) # ----------------------------------------------- independent review of 48aa8c871 @@ -1857,7 +1600,7 @@ def _receipt_rows(items: list[int]) -> pa.Table: def test_a_receipt_committed_during_the_run_is_not_delivered_again( entry: str, items: list[int] ) -> None: - """Review B2: a receipt the run's leased database commits during the execution + """Review B2: a receipt the run's scoped database commits during the execution (here from the first delivery, for the row not delivered yet) is seen by the completion lookup, as main's per-row lookup sees it: that row is not delivered again.""" @@ -1910,6 +1653,7 @@ def test_two_sinks_sharing_a_tracking_table_deliver_each_row_once( completion_lookup = SideEffectJobNode._completion_lookup # pyright: ignore[reportPrivateUsage] def trace_lookup(node: SideEffectJobNode) -> Callable[[bytes], bool] | None: + """Trace the table and receipt IDs each sink checks.""" lookup = completion_lookup(node) if lookup is None: return None @@ -1917,6 +1661,7 @@ def trace_lookup(node: SideEffectJobNode) -> Callable[[bytes], bool] | None: assert path is not None def trace(record_id: bytes) -> bool: + """Record a receipt lookup and return its actual result.""" checked.setdefault(node.label, []).append((path, record_id)) return lookup(record_id) @@ -2060,19 +1805,21 @@ def test_a_standalone_ephemeral_node_commits_results_one_at_a_time( @pytest.mark.usefixtures("root") @pytest.mark.parametrize("order", ORDERS) @pytest.mark.parametrize("target", ["combine", "select"]) +@pytest.mark.parametrize("separate_results", [False, True]) def test_a_permanent_result_failure_keeps_the_rows_before_it( - monkeypatch: pytest.MonkeyPatch, order: str, target: str + monkeypatch: pytest.MonkeyPatch, order: str, target: str, separate_results: bool ) -> None: """Review S1: a node run whose batched result append fails permanently writes the batch's rows one at a time, in order, up to the failing row: the results and pipeline records before it stay, as a node committing every row keeps them, the - run fails with the row's error, and the lease is released.""" + run fails with the row's error, and the scope is closed.""" from orcapod.errors import OrcapodDatabaseWriteError append = fake.FakeKeyedTable.append attempted: list[list[int]] = [] def trace_results(table: fake.FakeKeyedTable, batch: pa.Table) -> list[int]: + """Extract the fixture's totals from a result-table append.""" record = spiral_database_identity.read_table_identity_metadata( table.get_metadata() ) @@ -2088,12 +1835,14 @@ def trace_results(table: fake.FakeKeyedTable, batch: pa.Table) -> list[int]: def record_per_row_append( table: fake.FakeKeyedTable, batch: pa.Table ) -> fake.FakeKeyedTable: + """Record result order for the per-row reference run.""" totals = trace_results(table, batch) if totals: attempted.append(totals) return append(table, batch) def refuse_total_8(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: + """Fail any result append that includes the chosen row.""" totals = trace_results(table, batch) if totals: attempted.append(totals) @@ -2110,7 +1859,11 @@ def refuse_total_8(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: assert sorted(reference) == [6, 8, 10] attempted.clear() - job = _job(_database(), order=order) + job = _job( + _database(), + result_database=_database("results") if separate_results else None, + order=order, + ) with monkeypatch.context() as patch: patch.setattr(fake.FakeKeyedTable, "append", refuse_total_8) with pytest.raises(OrcapodDatabaseWriteError, match="total=8"): @@ -2129,6 +1882,16 @@ def refuse_total_8(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: is not None } results = stored.get("rdb_v1") + if separate_results: + assert results is None + result_store = _database("results") + result_paths = result_store.list_table_paths() + if result_paths: + [result_path] = result_paths + assert result_path[-1] == "rdb_v1" + results = result_store.get_all_records( + result_path, record_id_column="result_id" + ) totals = [] if results is None else cast("list[int]", results["total"].to_pylist()) assert sorted(totals) == kept records = stored.get("pdb_v2") @@ -2140,8 +1903,9 @@ def refuse_total_8(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: ) assert sorted(referenced_ids) == sorted(result_ids) assert stored["sdb_v2"].num_rows == 3 - with database_writes([fresh], owner="recovery"): - pass + # A recovery run can open a new scope after the failure. + with database_writes([fresh]): + fresh.spiral_acquire_write_lock() @pytest.mark.usefixtures("root") @@ -2203,20 +1967,23 @@ def partly_accept(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: @pytest.mark.usefixtures("root") @pytest.mark.parametrize("order", ORDERS) -def test_an_ambiguous_batch_reply_publishes_the_accepted_prefix( - monkeypatch: pytest.MonkeyPatch, order: str +@pytest.mark.parametrize("interrupt", [False, True], ids=["error", "interrupt"]) +def test_an_ambiguous_batch_reply_keeps_the_accepted_prefix_recoverable( + monkeypatch: pytest.MonkeyPatch, order: str, interrupt: bool ) -> None: """Delta review of cb56f9f88: the service accepts the first and last rows of a batched result append and loses the reply; the row-by-row retry then finds the first row stored (no second append), publishes its pipeline record, and fails permanently on the middle row. Only the last row, accepted beyond the retried prefix, stays without a pipeline record; no record dangles, and a later run - reuses it as a cached result, appending only the middle row.""" + reuses it as a cached result, appending only the middle row. An interrupt + leaves publication of the first row's record to that recovery run.""" from orcapod.errors import OrcapodDatabaseWriteError append = fake.FakeKeyedTable.append attempted: list[list[int]] = [] batch_order: list[int] = [] + interruption = KeyboardInterrupt("interrupted on the middle row") def totals_of(table: fake.FakeKeyedTable, batch: pa.Table) -> list[int] | None: record = spiral_database_identity.read_table_identity_metadata( @@ -2240,6 +2007,8 @@ def accept_the_edges(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: _ = append(table, batch.take(pa.array([0, len(totals) - 1]))) raise fake.SpiralError("the reply was lost after a partial append") if totals == batch_order[1:2]: + if interrupt: + raise interruption raise fake.SpiralError("permanent failure on the middle row") return append(table, batch) @@ -2273,8 +2042,13 @@ def referenced_totals(tables: dict[str, pa.Table]) -> list[int]: job = _job(_database(), order=order) with monkeypatch.context() as patch: patch.setattr(fake.FakeKeyedTable, "append", accept_the_edges) - with pytest.raises(OrcapodDatabaseWriteError, match="middle row"): - _ = job.nodes["combine"].run() + if interrupt: + with pytest.raises(KeyboardInterrupt) as raised: + _ = job.nodes["combine"].run() + assert raised.value is interruption + else: + with pytest.raises(OrcapodDatabaseWriteError, match="middle row"): + _ = job.nodes["combine"].run() first, middle, last = batch_order # The batch, then only the middle row: the accepted first row is not appended again. assert attempted == [batch_order, [middle]] @@ -2282,7 +2056,7 @@ def referenced_totals(tables: dict[str, pa.Table]) -> list[int]: assert sorted(cast("list[int]", tables["rdb_v1"]["total"].to_pylist())) == sorted( [first, last] ) - assert referenced_totals(tables) == [first] + assert referenced_totals(tables) == ([] if interrupt else [first]) recovery: list[list[int]] = [] @@ -2292,10 +2066,12 @@ def record_appends(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: recovery.append(totals) return append(table, batch) + calls.clear() with monkeypatch.context() as patch: patch.setattr(fake.FakeKeyedTable, "append", record_appends) _ = _job(_database(), order=order).nodes["combine"].run() assert recovery == [[middle]] + assert [x + y for x, y in calls] == [middle] tables = stored() assert sorted(cast("list[int]", tables["rdb_v1"]["total"].to_pylist())) == [ 6, @@ -2350,6 +2126,7 @@ class _SQLiteForCachePathTests(SQLiteConnector): def unstorable_column_reason( self, name: str, arrow_type: pa.DataType, *, primary_key: bool ) -> str | None: + """Allow the cache timestamp while retaining SQLite's other checks.""" if name == SOURCE_RECORDED_AT_COL: return None return super().unstorable_column_reason( @@ -2359,14 +2136,15 @@ def unstorable_column_reason( @pytest.mark.usefixtures("root") @pytest.mark.parametrize(("entry", "kwargs"), PREFLIGHT_ENTRIES) -def test_an_overdeep_sql_cache_path_is_refused_before_any_lease_or_write( +def test_an_overdeep_sql_cache_path_is_refused_before_any_lock_or_write( entry: str, kwargs: dict[str, Any] ) -> None: """A cached source whose cache is on a SQL connector database too deep for its path is refused by the run's preflight, naming the cached source, before any - lease is taken or any table written, in a job that also writes a writable + write lock is acquired or any table written, in a job that also writes a writable SpiralDB database.""" - database = _database() + lock = _RecordingWriteLock() + database = _database(write_lock=lock) deep = ConnectorArrowDatabase(_SQLiteForCachePathTests()).at(*"abcdefgh") with PipelineJob(name=JOB, database=database) as job: combine.pod(_cached(database, _rows()), label="first") @@ -2374,9 +2152,14 @@ def test_an_overdeep_sql_cache_path_is_refused_before_any_lease_or_write( CachedSource(_other_source(), label="deep cache", cache_database=deep), label="second", ) - with pytest.raises(ValueError, match=r"'deep cache'.*depth 11 exceeds maximum 10"): - _start(job, entry, **kwargs) - assert _database_tables() == [] and _lease_tables() == [] + checks = _count_source_checks(job) + with database_writes([database]): + with pytest.raises( + ValueError, match=r"'deep cache'.*depth 11 exceeds maximum 10" + ): + _start(job, entry, **kwargs) + assert checks == [] + assert _database_tables() == [] and lock.acquisitions == [] assert deep.list_table_paths() == [] assert calls == [] @@ -2407,6 +2190,7 @@ def _second_pod(cache: str, database: Any) -> Any: """A second function over the first's outputs, caching in ``database``.""" def second(total: int, ratio: float) -> tuple[float, float]: + """Return two outputs for the nested cache.""" return total + ratio, total - ratio return function_pod(output_keys=("sum", "difference"), **{cache: database})(second) @@ -2422,18 +2206,19 @@ def test_an_overdeep_function_result_path_is_refused_before_any_write( too deep for the result table's path (six components under a base of five) is refused with the job's own result database, naming the node, before anything is computed or written.""" - database = _database() + lock = _RecordingWriteLock() + database = _database(write_lock=lock) if backend == "SQLite": own: Any = ConnectorArrowDatabase(SQLiteConnector()) else: - own = _database("own") + own = _database("own", write_lock=lock) pod = _second_pod(cache, own.at(*"abcde")) with pytest.raises(ValueError, match=r"'second'.*depth 11 exceeds maximum 10"): with PipelineJob(name=JOB, database=database) as job: first = combine.pod(_cached(database, _rows()), label="first") pod.pod(first, label="second") _ = job.run() - assert _database_tables() == [] and _lease_tables() == [] + assert _database_tables() == [] and lock.acquisitions == [] assert own.list_table_paths() == [] assert calls == [] @@ -2451,10 +2236,11 @@ def test_an_overdeep_result_path_of_a_pod_built_outside_the_job_is_refused( ) -> None: """A function pod stream built outside the job and passed in caches in a database too deep for its result table: the run's preflight refuses it, naming the stream, - before any lease is taken or anything computed or written, whichever order its + before any write lock is acquired or anything computed or written, whichever order its two selected data columns are named in.""" - database = _database() - own = _database("own") + lock = _RecordingWriteLock() + database = _database(write_lock=lock) + own = _database("own", write_lock=lock) outside = _second_pod(cache, own.at(*"abcde")).pod( combine.pod(_other_source(), label="outside first"), label="outside second" ) @@ -2469,7 +2255,7 @@ def test_an_overdeep_result_path_of_a_pod_built_outside_the_job_is_refused( else: _run(job, entry) assert _database_tables() == [] and _database_tables("own") == [] - assert _lease_tables() == [] and _lease_tables("own") == [] + assert lock.acquisitions == [] assert calls == [] @@ -2614,6 +2400,7 @@ def test_bind_checks_the_replacement_content_scoped_path( refuse_new_path = True def check_path(db: InMemoryArrowDatabase, record_path: tuple[str, ...]) -> None: + """Record the candidate path and optionally refuse a replacement.""" identity_path = record_path[:-1] if not any(part.startswith("instance:") for part in identity_path): return @@ -2720,6 +2507,7 @@ def test_bind_hashes_match_fresh_jobs( candidate_paths: list[tuple[str, ...]] = [] def check_path(_db: InMemoryArrowDatabase, path: tuple[str, ...]) -> None: + """Capture the candidate's paths and hashes while they are visible.""" if any(part.startswith("instance:") for part in path): candidate_paths.append(path[:-1]) assert slot == slot_b @@ -2768,6 +2556,7 @@ def test_refused_candidate_does_not_fill_unbound_python_hash( monkeypatch.setattr(operator, "_pipeline_hash_cache", pipeline_memo) def check_path(_db: InMemoryArrowDatabase, _path: tuple[str, ...]) -> None: + """Exercise both hash lookups before refusing the candidate.""" # The earlier source consistency check can hash the replacement. Make # its live memo cold again to detect writes made by the storage check. replacement_memo.clear() @@ -2823,6 +2612,7 @@ def test_refused_candidate_preserves_protocol_binding_python_hash( monkeypatch.setattr(slot, "_content_hash_cache", slot_memo) def check_path(_db: InMemoryArrowDatabase, path: tuple[str, ...]) -> None: + """Compare the protocol binding's Python hash before refusing it.""" if any(part.startswith("instance:") for part in path): assert slot == candidate_slot assert hash(slot) == expected_candidate @@ -2847,6 +2637,7 @@ def test_refused_bind_preserves_bindings_and_corrected_retry_attaches_databases( """A storage refusal at the second operator leaves both slots and attachments intact.""" def source(source_id: str, table: pa.Table) -> ArrowTableSource: + """Build a source in the requested fixture column order.""" tags = ["unit", "trial"] if order[0] == "second": table = _arranged(table, True) @@ -2916,6 +2707,7 @@ def predict_output( slot: SourceJobNode = slots[name], normal: Callable[[], pa.Table | None] = node._typed_zero_row_table, # pyright: ignore[reportPrivateUsage] ) -> pa.Table | None: + """Synthesize a duration output when the candidate asks for one.""" zero_rows = typed_zero_row_table(slot) if zero_rows is None: return None @@ -2973,7 +2765,7 @@ def test_a_polling_sources_declared_unstorable_column_is_refused_at_attachment( """A polling source declaring ``large_list`` feeds a logging operator on a writable SpiralDB database: its declared schema types the operator's output before any poll, so attaching the cache refuses the column, - and nothing is polled, leased or written, in either arrangement of its tags and + and nothing is polled, locked or written, in either arrangement of its tags and data columns.""" reverse, tags, selected = POLLING_ARRANGEMENTS[arrangement] from orcapod.sources import PollingSource @@ -2985,7 +2777,8 @@ def test_a_polling_sources_declared_unstorable_column_is_refused_at_attachment( ), reverse, ) - database = _database() + lock = _RecordingWriteLock() + database = _database(write_lock=lock) source = PollingSource( _NeverPolled(table), tag_columns=tags, record_id_columns=tags @@ -2998,7 +2791,7 @@ def test_a_polling_sources_declared_unstorable_column_is_refused_at_attachment( job.nodes["second"].attach_databases( pipeline_database=database.at(JOB), cache_mode=CacheMode.LOG ) - assert _database_tables() == [] and _lease_tables() == [] + assert _database_tables() == [] and lock.acquisitions == [] assert calls == [] @@ -3027,10 +2820,12 @@ class _CountedPolling(_DeclaredPolling): fetched = 0 async def fetch(self, cursor: Any = None) -> Any: + """Count actual polls so schema inspection can be checked separately.""" _CountedPolling.fetched += 1 return await super().fetch(cursor) def build() -> PollingSource[int]: + """Build a fresh polling source with a declared schema.""" return PollingSource( _CountedPolling(table), tag_columns=tags, record_id_columns=tags ) @@ -3057,15 +2852,16 @@ def test_an_overdeep_result_path_of_a_standalone_function_node_is_refused( ) -> None: """A function job node built on its own (no pipeline, no ephemeral database), whose function caches in a database too deep for its result table, is refused by - its run's preflight, naming the node and the depth, before any lease is taken, + its run's preflight, naming the node and the depth, before any write lock is acquired, the function called or any table written (its input's cache included).""" from orcapod.core.nodes.function_node import FunctionJobNode + lock = _RecordingWriteLock() if backend == "SQLite": root_database: Any = ConnectorArrowDatabase(SQLiteConnector()) cache_database = InMemoryArrowDatabase() else: - root_database = _database("own") + root_database = _database("own", write_lock=lock) cache_database = root_database node = FunctionJobNode( function_pod=_second_pod(cache, root_database.at(*"abcde")).pod, @@ -3078,7 +2874,7 @@ def test_an_overdeep_result_path_of_a_standalone_function_node_is_refused( _ = node.run() assert root_database.list_table_paths() == [] assert cache_database.list_table_paths() == [] - assert _database_tables("own") == [] and _lease_tables("own") == [] + assert _database_tables("own") == [] and lock.acquisitions == [] assert calls == [] @@ -3123,6 +2919,7 @@ def test_a_cache_path_set_aside_by_a_rebind_is_not_checked_by_the_preflight( origin = _origin_job(rows, tags) def build() -> tuple[CachedSource, Any, PipelineJob]: + """Attach a cache with the unsupported path and return its consumer job.""" from orcapod import Pipeline, SourceNode if unstorable == "overdeep SQLite path": @@ -3285,7 +3082,7 @@ def result_paths(store: ArrowDatabaseProtocol) -> set[tuple[str, ...]]: } assert bool(result_paths(result_store)) == (before == "pdb_v2") - with database_writes([database], owner="subsequent caller"): + with database_writes([database]): result_store.flush() if result_store is not database: database.flush() diff --git a/tests/test_databases/test_spiraldb_write_lock.py b/tests/test_databases/test_spiraldb_write_lock.py new file mode 100644 index 000000000..942734ada --- /dev/null +++ b/tests/test_databases/test_spiraldb_write_lock.py @@ -0,0 +1,1298 @@ +"""Write scope and optional lock behavior on the fake SpiralDB SDK.""" + +from __future__ import annotations + +import asyncio +from collections.abc import Callable +from concurrent.futures import Future, ThreadPoolExecutor +from contextvars import copy_context +from threading import Event +from typing import Any, Literal, cast + +import pyarrow as pa +import pytest +from typing_extensions import override + +from orcapod import PipelineJob, function_pod +from orcapod.channels import Channel +from orcapod.contexts import get_default_context +from orcapod.core.data_function import CachedDataFunction, PythonDataFunction +from orcapod.core.datagrams import Data +from orcapod.core.executors.local import LocalPythonFunctionExecutor +from orcapod.core.function_pod import FunctionPod +from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.core.operators import SelectDataColumns +from orcapod.databases import ( + ConnectorArrowDatabase, + SpiralDBConnector, + spiral_database_identity, + spiraldb_connector, + spiraldb_write_scope, +) +from orcapod.databases.spiraldb_tables import SpiralDBTables +from orcapod.databases.spiraldb_write_scope import database_writes +from orcapod.errors import OrcapodDatabaseWriteError, SpiralDBScopeOpenError +from orcapod.invocation import InvocationContext +from orcapod.protocols.core_protocols import ( + DataFunctionProtocol, + DataProtocol, + TagProtocol, +) +from orcapod.protocols.observability_protocols import DataExecutionLoggerProtocol +from orcapod.side_effects import SideEffectJobNode, SideEffectPod, sink_pod +from orcapod.sources import ArrowTableSource +from orcapod.types import CacheMode, NodeConfig +from tests.test_databases import fake_spiral_sdk as fake +from tests.test_databases.test_spiraldb_writable_runs import ( + ENTRIES, + JOB, + _cached, # pyright: ignore[reportPrivateUsage] + _comparable, # pyright: ignore[reportPrivateUsage] + _job, # pyright: ignore[reportPrivateUsage] + _rows, # pyright: ignore[reportPrivateUsage] + _run, # pyright: ignore[reportPrivateUsage] + calls, + combine, + delivered, + root, # noqa: F401 +) + +pytestmark = [ + pytest.mark.usefixtures("root"), + pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning"), +] + + +class RecordingLock: + """Record calls and optionally refuse or fail release.""" + + def __init__( + self, + events: list[str], + refusal: BaseException | None = None, + release_error: BaseException | None = None, + ) -> None: + self.events = events + self.refusal = refusal + self.release_error = release_error + self.targets: list[tuple[str, str]] = [] + + def acquire(self, project_id: str, dataset: str) -> RecordingHandle: + self.targets.append((project_id, dataset)) + self.events.append("acquire") + if self.refusal is not None: + raise self.refusal + return RecordingHandle(self.events, self.release_error) + + +class RecordingHandle: + def __init__(self, events: list[str], error: BaseException | None) -> None: + self.events = events + self.error = error + + def release(self) -> None: + self.events.append("release") + if self.error is not None: + raise self.error + + +def _database( + dataset: str = "d", lock: RecordingLock | None = None +) -> ConnectorArrowDatabase: + return ConnectorArrowDatabase( + SpiralDBConnector("p", dataset, writable=True, write_lock=lock) + ) + + +def _versions(dataset: str = "d") -> dict[str, str]: + """Each database table of the dataset (no lease table) by name, with its version: + an append moves it, so equal versions mean nothing was written.""" + client = fake.FakeClient() + return { + t["name"]: client.keyed_table_by_id(t["id"]).version_id + for t in client._store.tables() # pyright: ignore[reportPrivateUsage] + if t["dataset"] == dataset + } + + +def _source(n: int = 3) -> ArrowTableSource: + """The rows as a plain source: reading it writes nothing.""" + return ArrowTableSource( + _rows(n), + tag_columns=["unit", "trial"], + tag_only_columns=True, + source_id="trials", + record_id_columns=["unit", "trial"], + ) + + +EVENTS: list[str] = [] + + +def _deliver(x: int) -> None: + EVENTS.append("deliver") + delivered.append(x) + + +def _sink_job(database: Any, n: int) -> PipelineJob: + """A tracked sink over a plain source: its log is the only table written.""" + job = PipelineJob(name=JOB, database=database) + with job: + sink = sink_pod(lambda x, y, ctx: _deliver(x)) + assert isinstance(sink, SideEffectPod) + sink.process(_source(n), label="sink") + return job + + +def _context_job(database: Any, n: int) -> PipelineJob: + """A function pod taking the invocation context over a plain source.""" + + @function_pod(output_keys="z", ctx_arg="ctx") + def act(x: int, ctx: InvocationContext) -> int: + _deliver(x) + return x + + job = PipelineJob(name=JOB, database=database) + with job: + act.pod(_source(n).select_data_columns(["x"]), label="act") + return job + + +SIDE_EFFECTS = {"sink": _sink_job, "context function": _context_job} + + +def _run_side_effect(job: PipelineJob, entry: str) -> None: + """Run ``job`` by ``entry``; a node run runs its one side-effect node on its own.""" + if entry == "node run": + (label,) = (k for k in job.nodes if k in ("sink", "act")) + _ = job.nodes[label].run() + else: + _ = _run(job, entry) + + +# The tables a side-effect node reads to decide what it delivers: a sink's invocation +# log; a context-taking function's pipeline and result tables. +LOG_LAYOUTS = ("tdb_v2", "pdb_v2", "rdb_v1") + + +def _operator_cache_job(database: Any) -> PipelineJob: + """A logged operator node over a plain source: its cache is the only table.""" + job = PipelineJob(name=JOB, database=database) + with job: + SelectDataColumns(["x"])(_source(), label="select") + job.nodes["select"].attach_databases( + pipeline_database=database.at(JOB), cache_mode=CacheMode.LOG + ) + return job + + +def _result_database_job(database: Any) -> PipelineJob: + """A job whose function results go to ``database``, its pipeline tables elsewhere.""" + job = PipelineJob(name=JOB, database=_database("other"), result_database=database) + with job: + combine.pod(_source(), label="combine") + return job + + +def _ephemeral_job(database: Any) -> PipelineJob: + """A job whose function results are ephemeral, kept in ``database``.""" + job = PipelineJob(name=JOB, database=_database("other")) + with job: + combine.pod(_source(), label="combine") + job.set_ephemeral_database(database) + job.nodes["combine"].node_config = NodeConfig(is_result_ephemeral=True) + return job + + +def _cached_source_job(database: Any) -> PipelineJob: + """A job reading a cached source stored in ``database``, its own tables elsewhere.""" + job = PipelineJob(name=JOB, database=_database("other")) + with job: + combine.pod(_cached(database, _rows()), label="combine") + return job + + +ROUTES: dict[str, Callable[[Any], PipelineJob]] = { + "job tables": lambda database: _job(database), + "cached source": _cached_source_job, + "side-effect log": lambda database: _sink_job(database, 3), + "operator cache": _operator_cache_job, + "separate result database": _result_database_job, + "ephemeral result database": _ephemeral_job, +} + + +def _two_tables(database: ConnectorArrowDatabase) -> list[tuple[str, ...]]: + """Write two tables of one row each; return their paths.""" + paths = [("kept_a", "rdb_v1"), ("kept_b", "rdb_v1")] + for path in paths: + database.add_records( + path, + pa.table( + { + "__record_id": pa.array([b"r"], pa.large_binary()), + "value": [1], + "__data_context": [get_default_context().context_key], + } + ), + record_id_column="__record_id", + flush=True, + ) + return paths + + +@pytest.mark.usefixtures("root") +def test_kept_reads_stay_within_their_byte_budget( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Finding M2: a run keeps whole reads within ``KEPT_ROWS_BUDGET_BYTES``: the + oldest is dropped to make room, a read that does not fit is not kept, and a + dropped table is read again with the same rows.""" + from orcapod.databases import spiraldb_tables + + database = _database() + with database_writes([database]): + paths = _two_tables(database) + kept_sizes: list[int] = [] + real_keep = spiraldb_tables.SpiralDBTables._keep_read # pyright: ignore[reportPrivateUsage] + + def keep(self: Any, name: str, table_id: str, stored: pa.Table) -> None: + kept_sizes.append(stored.nbytes) + real_keep(self, name, table_id, stored) + + monkeypatch.setattr(spiraldb_tables.SpiralDBTables, "_keep_read", keep) + with database_writes([database]): + first = [database.get_all_records(p) for p in paths] + one = max(kept_sizes) + for budget, expected in ((10 * one, 2), (one, 3), (0, 4)): + monkeypatch.setattr(spiraldb_tables, "KEPT_ROWS_BUDGET_BYTES", budget) + kept_sizes.clear() # one entry per read from the service + reader = _database() + with database_writes([reader]): + order = [paths[0], paths[1], paths[1], paths[0]] + got = [reader.get_all_records(p) for p in order] + # Within budget both stay kept; at one table's size the first is dropped + # for the second (kept for its second read) and read again; with none, + # every read goes to the service. + assert len(kept_sizes) == expected, budget + assert [_comparable(t) for t in got if t is not None] == [ + _comparable(t) + for t in (first[0], first[1], first[1], first[0]) + if t is not None + ] + + +@pytest.fixture +def sdk_events(monkeypatch: pytest.MonkeyPatch) -> list[str]: + EVENTS.clear() + create = fake.FakeProject.create_keyed_table + append = fake.FakeKeyedTable.append + scan = fake.FakeKeyedTable.scan + + def create_table(project: fake.FakeProject, *args: Any, **kwargs: Any) -> Any: + EVENTS.append("create") + return create(project, *args, **kwargs) + + def append_rows(table: fake.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any: + EVENTS.append("append") + return append(table, *args, **kwargs) + + def read(table: fake.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any: + record = spiral_database_identity.read_table_identity_metadata( + table.get_metadata() + ) + if record is not None and record.path[-1] in LOG_LAYOUTS: + EVENTS.append("log read") + return scan(table, *args, **kwargs) + + monkeypatch.setattr(fake.FakeProject, "create_keyed_table", create_table) + monkeypatch.setattr(fake.FakeKeyedTable, "append", append_rows) + monkeypatch.setattr(fake.FakeKeyedTable, "scan", read) + return EVENTS + + +@pytest.mark.parametrize("entry", ENTRIES) +def test_storage_acquires_before_creates_and_appends( + entry: str, sdk_events: list[str] +) -> None: + lock = RecordingLock(sdk_events) + for n, operation in ((3, "create"), (4, "append")): + sdk_events.clear() + lock.targets.clear() + job = PipelineJob(name=JOB, database=_database(lock=lock)) + with job: + combine.pod(_source(n), label="combine") + if entry == "node run": + _ = job.nodes["combine"].run() + else: + _ = _run(job, entry) + assert lock.targets == [("p", "d")] + assert sdk_events.index("acquire") < sdk_events.index(operation) + assert sdk_events[-1] == "release" + assert sdk_events.count("release") == 1 + + +@pytest.mark.parametrize("entry", ENTRIES) +@pytest.mark.parametrize("kind", SIDE_EFFECTS) +def test_side_effect_reads_log_then_acquires_before_delivery( + entry: str, kind: str, sdk_events: list[str] +) -> None: + build = SIDE_EFFECTS[kind] + _run_side_effect(build(_database(), 3), entry) + delivered.clear() + sdk_events.clear() + lock = RecordingLock(sdk_events) + _run_side_effect(build(_database(lock=lock), 4), entry) + assert delivered == [4] + assert ( + sdk_events.index("log read") + < sdk_events.index("acquire") + < sdk_events.index("deliver") + ) + assert sdk_events[-1] == "release" + sdk_events.clear() + _run_side_effect(build(_database(lock=lock), 4), entry) + assert "log read" in sdk_events + assert "acquire" not in sdk_events and "deliver" not in sdk_events + + +@pytest.mark.parametrize("entry", ENTRIES) +@pytest.mark.parametrize("kind", SIDE_EFFECTS) +def test_raising_provider_prevents_side_effects_and_writes( + entry: str, kind: str, sdk_events: list[str] +) -> None: + build = SIDE_EFFECTS[kind] + _run_side_effect(build(_database(), 3), entry) + before = _versions() + delivered.clear() + sdk_events.clear() + refusal = OSError("write lock refused") + with pytest.raises(OSError) as raised: + _run_side_effect( + build(_database(lock=RecordingLock(sdk_events, refusal)), 4), entry + ) + assert raised.value is refusal + assert delivered == [] + assert _versions() == before + assert not {"create", "append", "release"}.intersection(sdk_events) + + +@pytest.mark.parametrize("route", ROUTES) +@pytest.mark.parametrize("entry", ENTRIES[:3]) +def test_lock_refuses_each_write_route(route: str, entry: str) -> None: + refusal = OSError("write lock refused") + lock = RecordingLock([], refusal) + with pytest.raises(OSError) as raised: + _run(ROUTES[route](_database(lock=lock)), entry) + assert raised.value is refusal + assert _versions() == {} + assert delivered == [] + assert lock.targets == [("p", "d")] + assert lock.events == ["acquire"] + + +@pytest.mark.parametrize("entry", ENTRIES[:3]) +def test_context_function_acquires_its_nested_store_before_call(entry: str) -> None: + refusal = OSError("nested write lock refused") + nested = _database("n", RecordingLock([], refusal)) + + @function_pod(output_keys="z", ctx_arg="ctx", result_database=nested.at("own")) + def act(x: int, ctx: InvocationContext) -> int: + _deliver(x) + return x + + job = PipelineJob(name=JOB, database=_database()) + with job: + act.pod(_source().select_data_columns(["x"]), label="act") + with pytest.raises(OSError) as raised: + _run(job, entry) + assert raised.value is refusal + assert not delivered and not _versions("n") + + +@pytest.mark.parametrize("async_execute", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("error_policy", ["continue", "fail_fast"]) +def test_node_execution_propagates_write_lock_refusal( + async_execute: bool, error_policy: Literal["continue", "fail_fast"] +) -> None: + """An acquisition failure is fatal even when execution can skip failed rows.""" + refusal = OSError("write lock refused") + lock = RecordingLock([], refusal) + job = _context_job(_database(lock=lock), 3) + node = job.nodes["act"] + assert isinstance(node, FunctionJobNode) + stream = _source().select_data_columns(["x"]) + + async def execute() -> None: + """Feed and execute the same rows as on the synchronous path.""" + inputs: Channel[tuple[TagProtocol, DataProtocol]] = Channel(8) + outputs: Channel[tuple[TagProtocol, DataProtocol]] = Channel(8) + for row in stream.iter_data(): + await inputs.writer.send(row) + await inputs.writer.close() + await node.async_execute( + inputs.reader, outputs.writer, error_policy=error_policy + ) + + with pytest.raises(OSError) as raised: + if async_execute: + asyncio.run(execute()) + else: + _ = node.execute(stream, error_policy=error_policy) + assert raised.value is refusal + assert lock.events == ["acquire"] + assert delivered == [] + assert _versions() == {} + + +def _queue(database: ConnectorArrowDatabase, path: tuple[str, ...], key: bytes) -> None: + """Buffer a row for the test to flush separately.""" + database.add_records( + path, + pa.table( + { + "__record_id": pa.array([key], pa.large_binary()), + "__data_context": [get_default_context().context_key], + "value": [1], + } + ), + record_id_column="__record_id", + ) + + +def test_direct_flush_has_one_fresh_scope_per_call(sdk_events: list[str]) -> None: + lock = RecordingLock(sdk_events) + database = _database(lock=lock) + for key in (b"first", b"second"): + sdk_events.clear() + for p in ("example_a", "example_b"): + _queue(database, (p, "rdb_v1"), key) + database.flush() + assert sdk_events.index("acquire") < sdk_events.index("append") + assert sdk_events[-1] == "release" + assert sdk_events.count("acquire") == sdk_events.count("release") == 1 + assert lock.targets == [("p", "d")] * 2 + + +@pytest.mark.parametrize("same_connector", [False, True]) +def test_thread_cannot_open_second_scope_or_flush_during_run( + same_connector: bool, +) -> None: + database = _database() + other = database.at("other") if same_connector else _database().at("other") + _queue(other, ("example", "rdb_v1"), b"r") + + def open_scope() -> None: + with database_writes([other]): + pass + + with database_writes([database]), ThreadPoolExecutor(max_workers=1) as pool: + for action in (open_scope, other.flush): + with pytest.raises(SpiralDBScopeOpenError, match="p/d"): + pool.submit(action).result() + assert _versions() == {} + other.flush() + assert _versions() + + +def test_release_runs_on_failure_and_scope_can_reopen() -> None: + events: list[str] = [] + database = _database(lock=RecordingLock(events)) + failure = RuntimeError("body failed") + with pytest.raises(RuntimeError) as raised: + with database_writes([database]): + database.spiral_acquire_write_lock() + raise failure + assert raised.value is failure + assert events == ["acquire", "release"] + events.clear() + with database_writes([database]): + pass + assert events == [] + + +def test_all_handles_release_even_if_a_release_fails() -> None: + events: list[str] = [] + error = RuntimeError("first release failed") + first = _database("first", RecordingLock(events)) + second = _database("second", RecordingLock(events, release_error=error)) + with pytest.raises(RuntimeError) as raised: + with database_writes([first, second]): + first.spiral_acquire_write_lock() + second.spiral_acquire_write_lock() + assert raised.value is error + assert events == ["acquire", "acquire", "release", "release"] + with database_writes([first, second]): + pass + + +@pytest.mark.parametrize("body_fails", [True, False], ids=["body", "cleanup"]) +def test_unprintable_cleanup_error_preserves_the_primary_error( + body_fails: bool, +) -> None: + """Keep the selected error even when a secondary failure cannot be formatted.""" + + class UnprintableError(Exception): + """A cleanup error whose message cannot be displayed.""" + + @override + def __str__(self) -> str: + raise ValueError("cannot format the cleanup error") + + events: list[str] = [] + primary = RuntimeError("primary failure") + first = _database("first", RecordingLock(events, release_error=UnprintableError())) + second = _database( + "second", RecordingLock(events, release_error=None if body_fails else primary) + ) + with pytest.raises(RuntimeError) as raised: + with database_writes([first, second]): + first.spiral_acquire_write_lock() + second.spiral_acquire_write_lock() + if body_fails: + raise primary + + assert raised.value is primary + prefix = ( + "Closing a SpiralDB write scope also failed" + if body_fails + else "Closing another SpiralDB write scope failed" + ) + assert primary.__notes__ == [f"{prefix}: UnprintableError"] + assert events == ["acquire", "acquire", "release", "release"] + + +@pytest.mark.parametrize("interrupt_at", ["state lock", "scope close", "registry lock"]) +def test_scope_cleanup_continues_after_an_interruption( + monkeypatch: pytest.MonkeyPatch, interrupt_at: str +) -> None: + first, second = RecordingLock([]), RecordingLock([]) + first_db, second_db = _database("first", first), _database("second", second) + interruption = KeyboardInterrupt("interrupted while closing") + body_error = RuntimeError("run failed") + + with pytest.raises(KeyboardInterrupt) as raised, monkeypatch.context() as patch: + with database_writes([first_db, second_db]): + first_db.spiral_acquire_write_lock() + second_db.spiral_acquire_write_lock() + if interrupt_at != "scope close": + if interrupt_at == "state lock": + tables = second_db._spiral # pyright: ignore[reportPrivateUsage] + assert isinstance(tables, SpiralDBTables) + state = tables._run_state # pyright: ignore[reportPrivateUsage] + assert state is not None + real_lock = state.lock + owner, attribute = state, "lock" + else: + real_lock = spiraldb_write_scope._open_scopes_lock # pyright: ignore[reportPrivateUsage] # interrupt registry lock entry + owner, attribute = spiraldb_write_scope, "_open_scopes_lock" + + class InterruptOnce: + """Interrupt the next entry, then use the original lock.""" + + interrupted: bool = False + + def __enter__(self) -> None: + if not self.interrupted: + self.interrupted = True + raise interruption + _ = real_lock.__enter__() + + def __exit__(self, *_exc: object) -> None: + real_lock.release() + + patch.setattr(owner, attribute, InterruptOnce()) + else: + scope_class = spiraldb_write_scope._DatasetScope # pyright: ignore[reportPrivateUsage] + close = scope_class.close + + def close_then_interrupt( + scope: spiraldb_write_scope._DatasetScope, # pyright: ignore[reportPrivateUsage] + ) -> list[BaseException]: + failures = close(scope) + if "release" not in first.events and second.events[-1] == "release": + raise interruption + return failures + + patch.setattr(scope_class, "close", close_then_interrupt) + raise body_error + + assert raised.value is interruption + assert raised.value.__cause__ is body_error + assert first.events == second.events == ["acquire", "release"] + with database_writes([first_db, second_db]): + pass + + +@pytest.mark.parametrize( + "second_error", ["refusal", "independent", "implicit", "suppressed"] +) +def test_provider_refusal_unwrap_preserves_other_task_failures( + second_error: str, +) -> None: + refusal = OSError("provider refused") + independent = ValueError("another task failed") + database = _database(lock=RecordingLock([], refusal)) + errors: list[Exception] = [] + + async def fail(kind: str) -> None: + if kind == "independent": + raise independent + try: + database.spiral_acquire_write_lock() + except OrcapodDatabaseWriteError: + if kind == "implicit": + raise independent + if kind == "suppressed": + raise independent from None + raise + + async def run() -> None: + with database_writes([database]): + try: + async with asyncio.TaskGroup() as tasks: + _ = tasks.create_task(fail("refusal")) + _ = tasks.create_task(fail(second_error)) + except ExceptionGroup as group: + errors.append(group) + raise + + if second_error != "refusal": + with pytest.raises(ExceptionGroup) as raised: + asyncio.run(run()) + assert raised.value is errors[0] + assert independent in raised.value.exceptions + assert any( + isinstance(exc, OrcapodDatabaseWriteError) + for exc in raised.value.exceptions + ) + else: + with pytest.raises(OSError) as raised: + asyncio.run(run()) + assert raised.value is refusal + + +@pytest.mark.parametrize("chain", ["implicit", "explicit", "group"]) +def test_provider_refusal_unwrap_distinguishes_exception_chains(chain: str) -> None: + """Keep an independent failure and unwrap explicit or all-refusal group chains.""" + refusal = OSError("provider refused") + failure = ValueError("handler failed") + database = _database(lock=RecordingLock([], refusal)) + + def acquire() -> None: + """Raise a group of write refusals for the grouped path.""" + try: + database.spiral_acquire_write_lock() + except OrcapodDatabaseWriteError as error: + if chain == "group": + raise ExceptionGroup("task failures", [error]) from None + raise + + expected = failure if chain == "implicit" else refusal + with pytest.raises(type(expected)) as raised: + with database_writes([database]): + try: + acquire() + except (OrcapodDatabaseWriteError, ExceptionGroup) as error: + if chain == "explicit": + raise failure from error + raise failure + + assert raised.value is expected + + +def test_listing_failure_falls_back_to_resolving_names( + monkeypatch: pytest.MonkeyPatch, +) -> None: + _run(_job(_database()), "sync") + + def fail_listing(client: Any, project: str, dataset: str) -> dict[str, str]: + """Fail the implicit listing once and let explicit listings proceed.""" + monkeypatch.setattr(spiraldb_connector, "_list_dataset", listing) + raise TimeoutError("listing timed out") + + listing = spiraldb_connector._list_dataset # pyright: ignore[reportPrivateUsage] + monkeypatch.setattr(spiraldb_connector, "_list_dataset", fail_listing) + _run(_job(_database(), table=_rows(4)), "sync") + assert calls[-1] == (4, 8) + + +@pytest.mark.parametrize("entry", ENTRIES) +@pytest.mark.parametrize("mode", ["held", "replay", "load-only"]) +def test_no_write_run_does_not_acquire(entry: str, mode: str) -> None: + lock = RecordingLock([]) + database = _database(lock=lock) + _run(_job(database), entry) + lock.events.clear() + _run( + _job( + database, cache_mode=CacheMode.REPLAY if mode == "replay" else CacheMode.LOG + ), + entry, + load_only=mode == "load-only", + ) + assert lock.events == [] + + +def test_first_writes_in_one_scope_share_one_handle() -> None: + lock = RecordingLock([]) + first, second = (_database(lock=lock) for _ in range(2)) + for db, p in ((first, "example_a"), (second, "example_b")): + _queue(db, (p, "rdb_v1"), b"r") + + with database_writes([first, second]), ThreadPoolExecutor(max_workers=2) as pool: + writes = [pool.submit(copy_context().run, db.flush) for db in (first, second)] + for write in writes: + write.result() + assert lock.events == ["acquire"] + assert lock.events == ["acquire", "release"] + assert len(_versions()) == 2 + + +@pytest.mark.parametrize("entry", ENTRIES[:3]) +@pytest.mark.parametrize("cache", ["result_database", "pod_cache_database"]) +def test_live_context_pod_stream_acquires_before_call(entry: str, cache: str) -> None: + refusal = OSError("live pod cache refused") + lock = RecordingLock([], refusal) + shared = _database("cache", lock) + + def act(x: int, ctx: InvocationContext) -> int: + _deliver(x) + return x + + pod = function_pod( + output_keys="total", + ctx_arg="ctx", + result_database=shared if cache == "result_database" else None, + pod_cache_database=shared if cache == "pod_cache_database" else None, + )(act) + outside = pod.pod(_source().select_data_columns(["x"])) + job = PipelineJob(name=JOB, database=_database()) + with job: + SelectDataColumns(["total"])(outside, label="select") + with pytest.raises(OSError) as raised: + _run(job, entry) + assert raised.value is refusal + assert delivered == [] + assert _versions("cache") == {} + assert lock.events == ["acquire"] + + +@pytest.mark.parametrize("entry", ENTRIES[:3]) +@pytest.mark.parametrize("cache", ["result_database", "pod_cache_database"]) +def test_shared_context_cache_hit_skips_its_provider(entry: str, cache: str) -> None: + lock = RecordingLock([]) + shared = _database("cache", lock) + + def act(x: int, ctx: InvocationContext) -> int: + _deliver(x) + return x + + pod = function_pod( + output_keys="total", + ctx_arg="ctx", + result_database=shared if cache == "result_database" else None, + pod_cache_database=shared if cache == "pod_cache_database" else None, + )(act) + + def build(dataset: str) -> PipelineJob: + job = PipelineJob(name=JOB, database=_database(dataset)) + with job: + pod.pod(_source().select_data_columns(["x"]), label="act") + return job + + _ = _run(build("first"), entry) + assert sorted(delivered) == [1, 2, 3] + assert lock.events == ["acquire", "release"] + lock.refusal = OSError("the populated cache should never be written") + lock.events.clear() + delivered.clear() + replay = build("second") + _ = _run(replay, entry) + assert replay.nodes["act"].as_table().num_rows == 3 + assert delivered == [] + assert lock.events == [] + + +@pytest.mark.parametrize("refuse", [False, True]) +def test_direct_sink_execute_uses_one_scope_before_delivering(refuse: bool) -> None: + refusal = OSError("direct sink refused") + lock = RecordingLock([], refusal if refuse else None) + database = _database(lock=lock) + node = _sink_job(database, 3).nodes["sink"] + assert isinstance(node, SideEffectJobNode) + if refuse: + with pytest.raises(OSError) as raised: + _ = node.execute(_source()) + assert raised.value is refusal + assert not delivered and not _versions() + assert lock.events == ["acquire"] + else: + _ = node.execute(_source()) + assert sorted(delivered) == [1, 2, 3] + assert lock.events == ["acquire", "release"] + database.flush() + + +@pytest.mark.parametrize("entry", ["async orchestrator", "run_async"]) +def test_async_sink_raises_cancelled_provider_error_once(entry: str) -> None: + refusal = asyncio.CancelledError("provider cancelled acquisition") + lock = RecordingLock([], refusal) + with pytest.raises(asyncio.CancelledError) as raised: + _run_side_effect(_sink_job(_database(lock=lock), 3), entry) + assert raised.value is refusal + assert lock.events == ["acquire"] + assert not delivered and not _versions() + + +@pytest.mark.parametrize("cache", ["result_database", "pod_cache_database"]) +def test_direct_context_cache_keeps_its_lock_through_storage( + cache: str, sdk_events: list[str] +) -> None: + lock = RecordingLock(sdk_events) + database = _database(lock=lock) + + def act(x: int, ctx: InvocationContext) -> int: + _deliver(x) + return x + + pod = function_pod( + output_keys="total", + ctx_arg="ctx", + result_database=database if cache == "result_database" else None, + pod_cache_database=database if cache == "pod_cache_database" else None, + )(act) + assert pod.pod(_source(1).select_data_columns(["x"])).as_table().num_rows == 1 + assert delivered == [1] + assert sdk_events.count("acquire") == sdk_events.count("release") == 1 + assert ( + sdk_events.index("acquire") + < sdk_events.index("deliver") + < sdk_events.index("append") + < sdk_events.index("release") + ) + + +def test_direct_nested_context_caches_share_one_dataset_scope( + sdk_events: list[str], +) -> None: + lock = RecordingLock(sdk_events) + pod_cache = _database().at("outer") + result_cache = _database(lock=lock).at("inner") + + def act(x: int, ctx: InvocationContext) -> int: + _deliver(x) + return x + + pod = function_pod( + output_keys="total", + ctx_arg="ctx", + pod_cache_database=pod_cache, + result_database=result_cache, + )(act) + assert pod.pod(_source(1).select_data_columns(["x"])).as_table().num_rows == 1 + assert delivered == [1] + assert pod_cache.list_table_paths() + assert result_cache.list_table_paths() + assert sdk_events.count("acquire") == sdk_events.count("release") == 1 + assert sdk_events.index("acquire") < sdk_events.index("deliver") + assert sdk_events[-1] == "release" + + sdk_events.clear() + lock.refusal = OSError("a cache hit must skip acquisition") + assert pod.pod(_source(1).select_data_columns(["x"])).as_table().num_rows == 1 + assert delivered == [1] + assert "acquire" not in sdk_events + + +@pytest.mark.parametrize("async_call", [False, True]) +@pytest.mark.parametrize("override_native", [False, True], ids=["public", "native"]) +def test_custom_cached_function_acquires_the_lock_before_invocation( + async_call: bool, + override_native: bool, +) -> None: + refusal = OSError("cache lock refused") + lock = RecordingLock([], refusal) + + def shape(x: int) -> int: + return x + + class NativeFunction(PythonDataFunction): + """Override the executor-free invocation methods.""" + + @override + def direct_call(self, data: DataProtocol, **kwargs: object) -> DataProtocol: + lock.events.append("call") + return Data({"total": data.as_dict()["x"]}) + + @override + async def direct_async_call( + self, data: DataProtocol, **kwargs: object + ) -> DataProtocol: + return self.direct_call(data, **kwargs) + + class CustomFunction(NativeFunction): + """Supply the invocation directly through the data function protocol.""" + + @override + def call( + self, + data: DataProtocol, + *, + logger: DataExecutionLoggerProtocol | None = None, + **kwargs: object, + ) -> DataProtocol: + return self.direct_call(data, **kwargs) + + @override + async def async_call( + self, + data: DataProtocol, + *, + logger: DataExecutionLoggerProtocol | None = None, + **kwargs: object, + ) -> DataProtocol: + return self.call(data, logger=logger, **kwargs) + + function_class = NativeFunction if override_native else CustomFunction + native_function = function_class(shape, output_keys="total") + native_function.executor = None + function = cast(object, native_function) + assert isinstance(function, DataFunctionProtocol) + cached = CachedDataFunction(function, _database(lock=lock), context_parameter="ctx") + + def call() -> DataProtocol | None: + row = Data({"x": 3}) + return asyncio.run(cached.async_call(row)) if async_call else cached.call(row) + + with pytest.raises(OSError) as raised: + _ = call() + assert raised.value is refusal + assert lock.events == ["acquire"] + assert not _versions() + + lock.refusal = None + lock.events.clear() + got = call() + assert got is not None and got.as_dict() == {"total": 3} + assert lock.events == ["acquire", "call", "release"] + + lock.refusal = refusal + lock.events.clear() + got = call() + assert got is not None and got.as_dict() == {"total": 3} + assert lock.events == [] + + +@pytest.mark.parametrize("entry", ["sync", "async"]) +def test_pod_row_override_can_delegate_to_super_in_its_write_scope(entry: str) -> None: + lock = RecordingLock([]) + + def contextual(x: int, ctx: InvocationContext) -> int: + lock.events.append("call") + return x + + class DelegatingPod(FunctionPod): + """Customize the row processors and delegate the work to the base pod.""" + + @override + def process_data( + self, + tag: TagProtocol, + data: DataProtocol, + *, + logger: DataExecutionLoggerProtocol | None = None, + run_id: str | None = None, + ) -> tuple[TagProtocol, DataProtocol | None]: + lock.events.append("override") + return super().process_data(tag, data, logger=logger, run_id=run_id) + + @override + async def async_process_data( + self, + tag: TagProtocol, + data: DataProtocol, + *, + logger: DataExecutionLoggerProtocol | None = None, + run_id: str | None = None, + ) -> tuple[TagProtocol, DataProtocol | None]: + lock.events.append("override") + return await super().async_process_data( + tag, data, logger=logger, run_id=run_id + ) + + data_function = cast( + object, PythonDataFunction(contextual, output_keys="total", _ctx_arg_name="ctx") + ) + assert isinstance(data_function, DataFunctionProtocol) + database = _database(lock=lock) + pod = DelegatingPod( + CachedDataFunction(data_function, database, context_parameter="ctx"), + ctx_arg_name="ctx", + ) + source = _source(1).select_data_columns(["x"]) + + async def execute() -> list[dict[str, Any]]: + inputs: Channel[tuple[TagProtocol, DataProtocol]] = Channel(8) + outputs: Channel[tuple[TagProtocol, DataProtocol]] = Channel(8) + await inputs.writer.send(next(source.iter_data())) + await inputs.writer.close() + await pod.async_execute([inputs.reader], outputs.writer) + return [data.as_dict() async for _, data in outputs.reader] + + if entry == "sync": + assert pod(source).as_table().column("total").to_pylist() == [1] + else: + assert asyncio.run(execute()) == [{"total": 1}] + assert lock.events == ["override", "acquire", "call", "release"] + + +def test_sync_pod_stream_uses_an_instance_row_processor( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def unchanged(x: int) -> int: + return x + + seen: list[int] = [] + + def override( + tag: TagProtocol, data: DataProtocol, **_kwargs: object + ) -> tuple[TagProtocol, DataProtocol]: + x = data.as_dict()["x"] + assert isinstance(x, int) + seen.append(x) + return tag, Data({"total": x * 10}) + + pod = FunctionPod.from_fn(unchanged, output_keys="total") + monkeypatch.setattr(pod, "process_data", override) + rows = pod(_source(3).select_data_columns(["x"])).iter_data() + assert {row.as_dict()["total"] for _, row in rows} == {10, 20, 30} + assert sorted(seen) == [1, 2, 3] + + +@pytest.mark.parametrize("cache", ["result_database", "pod_cache_database"]) +@pytest.mark.parametrize("takes_context", [False, True]) +@pytest.mark.parametrize("refusal_type", [None, OSError, asyncio.CancelledError]) +def test_standalone_async_cache_shares_scope_and_raises_provider_error( + cache: str, takes_context: bool, refusal_type: type[BaseException] | None +) -> None: + refusal = refusal_type("cache lock refused") if refusal_type is not None else None + lock = RecordingLock([], refusal) + database = _database(lock=lock) + + async def act(x: int) -> int: + await asyncio.sleep(0) + _deliver(x) + return x + + async def contextual_act(x: int, ctx: InvocationContext) -> int: + return await act(x) + + pod = function_pod( + output_keys="total", + ctx_arg="ctx" if takes_context else None, + result_database=database if cache == "result_database" else None, + pod_cache_database=database if cache == "pod_cache_database" else None, + )(contextual_act if takes_context else act) + + async def run() -> list[int]: + inputs: Channel[tuple[TagProtocol, DataProtocol]] = Channel(8) + outputs: Channel[tuple[TagProtocol, DataProtocol]] = Channel(8) + for item in _source().select_data_columns(["x"]).iter_data(): + await inputs.writer.send(item) + await inputs.writer.close() + await pod.pod.async_execute([inputs.reader], outputs.writer) + totals: list[int] = [] + async for _, data in outputs.reader: + total = data.as_dict()["total"] + assert isinstance(total, int) + totals.append(total) + return totals + + if refusal is not None: + with pytest.raises(type(refusal)) as raised: + _ = asyncio.run(run()) + assert raised.value is refusal + assert not _versions() + if takes_context: + assert not delivered + assert lock.events == ["acquire"] + else: + assert sorted(asyncio.run(run())) == [1, 2, 3] + assert sorted(delivered) == [1, 2, 3] + assert len(_versions()) == 1 + assert lock.events == ["acquire", "release"] + + +@pytest.mark.parametrize("entry", ["task", "thread", "sync row", "async row", "stream"]) +def test_a_nested_standalone_pod_cannot_share_an_execution_scope( + entry: str, +) -> None: + """A copied context cannot let a separate pod deliver under the first lock.""" + lock = RecordingLock([]) + refused: list[bool] = [] + + async def execute(pod: Any) -> list[dict[str, Any]]: + """Execute one standalone row through an input and output channel.""" + inputs: Channel[tuple[TagProtocol, DataProtocol]] = Channel(8) + outputs: Channel[tuple[TagProtocol, DataProtocol]] = Channel(8) + await inputs.writer.send( + next(_source(1).select_data_columns(["x"]).iter_data()) + ) + await inputs.writer.close() + await pod.async_execute([inputs.reader], outputs.writer) + return [data.as_dict() async for _, data in outputs.reader] + + @function_pod( + output_keys="inner", + ctx_arg="ctx", + result_database=_database(lock=lock).at("inner"), + ) + def inner(x: int, ctx: InvocationContext) -> int: + _deliver(x) + return x + + @function_pod( + output_keys="outer", + ctx_arg="ctx", + result_database=_database(lock=lock).at("outer"), + ) + async def outer(x: int, ctx: InvocationContext) -> int: + source = _source(1).select_data_columns(["x"]) + tag, data = next(source.iter_data()) + try: + if entry == "task": + _ = await asyncio.create_task(execute(inner.pod)) + elif entry == "thread": + _ = await asyncio.to_thread(lambda: asyncio.run(execute(inner.pod))) + elif entry == "sync row": + _ = inner.pod.process_data(tag, data) + elif entry == "async row": + _ = await inner.pod.async_process_data(tag, data) + else: + _ = inner.pod(source).as_table() + except SpiralDBScopeOpenError: + refused.append(True) + return x + + assert asyncio.run(execute(outer.pod)) == [{"outer": 1}] + assert refused == [True] + assert delivered == [] + assert lock.events == ["acquire", "release"] + assert len(_versions()) == 1 + + +@pytest.mark.parametrize("use_executor", [True, False], ids=["local", "direct"]) +@pytest.mark.parametrize("queued", [False, True], ids=["running", "queued"]) +def test_cancelled_context_call_keeps_its_scope_until_running_work_ends( + monkeypatch: pytest.MonkeyPatch, use_executor: bool, queued: bool +) -> None: + events: list[str] = [] + lock = RecordingLock(events) + finish = Event() + + async def run() -> None: + loop = asyncio.get_running_loop() + entered = asyncio.Event() + submitted = asyncio.Event() + + def effect(x: int, ctx: InvocationContext) -> int: + loop.call_soon_threadsafe(entered.set) + assert finish.wait(5) + events.append("effect") + return x + + native_function = PythonDataFunction( + effect, output_keys="total", _ctx_arg_name="ctx" + ) + native_function.executor = ( + LocalPythonFunctionExecutor() if use_executor else None + ) + function = cast(object, native_function) + assert isinstance(function, DataFunctionProtocol) + cached = CachedDataFunction( + function, _database(lock=lock), context_parameter="ctx" + ) + executor = ThreadPoolExecutor(max_workers=1) + loop.set_default_executor(executor) + blocker = loop.run_in_executor(None, finish.wait) if queued else None + if queued: + submit = executor.submit + + def record_submission(fn: Callable[[], object]) -> Future[object]: + """Signal once the callable is queued behind the blocked worker.""" + future = submit(fn) + submitted.set() + return future + + monkeypatch.setattr(executor, "submit", record_submission) + task = asyncio.create_task(cached.async_call(Data({"x": 1}), ctx=None)) + successor = _database(lock=lock) + try: + if queued: + await asyncio.wait_for(submitted.wait(), timeout=5) + else: + await asyncio.wait_for(entered.wait(), timeout=5) + assert events == ["acquire"] + for _ in range(2): + _ = task.cancel() + await asyncio.sleep(0) + if not queued: + assert events == ["acquire"] + with pytest.raises(SpiralDBScopeOpenError): + with database_writes([successor]): + pytest.fail("successor entered before the worker finished") + if queued: + assert task.done() + finally: + finish.set() + if blocker is not None: + _ = await blocker + with pytest.raises(asyncio.CancelledError): + _ = await task + + assert events == ( + ["acquire", "release"] if queued else ["acquire", "effect", "release"] + ) + assert not _versions() + with database_writes([successor]): + successor.spiral_acquire_write_lock() + assert events[-2:] == ["acquire", "release"] + + asyncio.run(run()) + assert ("effect" in events) is not queued + + +def test_empty_standalone_async_cache_makes_no_sdk_calls( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Closing an empty input reaches no SDK method and never invokes the function.""" + + @function_pod(output_keys="total", result_database=_database()) + async def act(x: int) -> int: + _deliver(x) + return x + + def unexpected(*args: Any, **kwargs: Any) -> Any: + """Fail if an empty execution talks to the fake service.""" + pytest.fail("empty execution made an SDK call") + + monkeypatch.setattr(spiraldb_connector, "_list_dataset", unexpected) + for cls, methods in ( + (fake.FakeClient, ("keyed_table", "keyed_table_by_id", "project")), + (fake.FakeProject, ("create_keyed_table",)), + (fake.FakeKeyedTable, ("get_metadata", "scan", "set_metadata", "append")), + ): + for method in methods: + monkeypatch.setattr(cls, method, unexpected) + + async def execute() -> None: + """Run the pod with no rows and check that its output closes empty.""" + inputs: Channel[tuple[TagProtocol, DataProtocol]] = Channel(1) + outputs: Channel[tuple[TagProtocol, DataProtocol]] = Channel(1) + await inputs.writer.close() + await act.pod.async_execute([inputs.reader], outputs.writer) + assert not [data async for _, data in outputs.reader] + + asyncio.run(execute()) + assert delivered == [] diff --git a/tests/test_dev_scripts/test_itl_1844_database_evaluation.py b/tests/test_dev_scripts/test_itl_1844_database_evaluation.py index f489e132d..7e4b700b1 100644 --- a/tests/test_dev_scripts/test_itl_1844_database_evaluation.py +++ b/tests/test_dev_scripts/test_itl_1844_database_evaluation.py @@ -39,7 +39,7 @@ def _expected() -> dict[str, dict[str, Any]]: "replay": {"ok": True}, "separate results": {"ok": True}, "save and load": {"ok": True, "writable_flag_saved": True, "load_only_rows": 7}, - "second writer": {"refused": True, "nothing_written": True}, + "second scope": {"refused": True, "nothing_written": True}, } @@ -56,8 +56,8 @@ def test_the_expected_outcomes_succeed(script: ModuleType) -> None: ("save and load", "writable_flag_saved", False), ("save and load", "load_only_rows", 0), ("separate results", "ok", False), - ("second writer", "refused", False), - ("second writer", "nothing_written", False), + ("second scope", "refused", False), + ("second scope", "nothing_written", False), ("replay", "ok", False), ], ) @@ -137,8 +137,7 @@ def test_a_failing_inventory_still_prints_the_report( monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], ) -> None: - """With the service down (every inventory raises after a scenario failed), the - JSON report is printed with the scenario's error and the inventory errors apart.""" + """A failed table listing still yields a JSON report with both errors.""" def down(*args: object) -> list[dict[str, str]]: raise ConnectionError("service down") @@ -146,7 +145,6 @@ def down(*args: object) -> list[dict[str, str]]: def failing(*args: object) -> None: raise ConnectionError("scenario failed") - monkeypatch.setattr(script, "lease_tables", down) monkeypatch.setattr(script, "database_tables", down) monkeypatch.setattr(script, "evaluate", failing) monkeypatch.setattr(sys, "argv", ["itl_1844_database_evaluation.py", "fake"]) @@ -154,8 +152,7 @@ def failing(*args: object) -> None: report = json.loads(capsys.readouterr().out) assert report["ok"] is False assert report["error"] == "ConnectionError: scenario failed" - assert set(report["inventory_errors"]) == { - "lease tables before", - "database tables", - "lease tables after", + assert report["database_tables"] is None + assert report["inventory_errors"] == { + "database tables": "ConnectionError: service down", } diff --git a/tests/test_docs/test_doc_samples.py b/tests/test_docs/test_doc_samples.py index 5de4a94b7..ccf38dfb6 100644 --- a/tests/test_docs/test_doc_samples.py +++ b/tests/test_docs/test_doc_samples.py @@ -284,10 +284,16 @@ def test_spiraldb_limits_describe_when_key_scans_are_needed(): ) limits = " ".join(page.split("## Limits\n", 1)[1].split("\n## ", 1)[0].split()) - assert "first key check" in limits - assert "after index invalidation" in limits - assert "use the lease's key index" in limits - assert "read of stored rows reads the whole table" in limits + assert "scans the whole key column of a table with rows" in limits + assert "neither an index nor reusable keys from an earlier read or append" in limits + assert "after a failed append invalidates the index" in limits + assert "Successful appends update the index" in limits + assert ( + "Outside a write scope, every check for one or more keys in a table with rows scans the key column" + in limits + ) + assert "Reads of stored rows load the whole table" in limits + assert "lease" not in limits @pytest.mark.parametrize("page", DOC_PAGES) diff --git a/tests/test_pipeline/test_observer_main_compatibility.py b/tests/test_pipeline/test_observer_main_compatibility.py index 99b57f22a..b9caf69b6 100644 --- a/tests/test_pipeline/test_observer_main_compatibility.py +++ b/tests/test_pipeline/test_observer_main_compatibility.py @@ -234,7 +234,15 @@ def add_record( values[f"{prefix}_timestamp"] = "" traceback_text = values.get("_log_traceback") if isinstance(traceback_text, str): - values["_log_traceback"] = traceback_text.replace(str(PACKAGE), "orcapod") + traceback_text = traceback_text.replace(str(PACKAGE), "orcapod") + # Compare executor and user frame names, while allowing the executor + # source to move or call a different thread submission helper. + values["_log_traceback"] = re.sub( + r'(?m)^ File "orcapod/core/executors/local\.py", line \d+, in ([^\n]+)\n' + r"(?: [^\n]*\n)*", + ' File "orcapod/core/executors/local.py", in \\1\n', + traceback_text, + ) self.calls.append( ["store.add_record", self.path, path, str(row.schema), values, flush] )