From b7d7355c73b5687a92d07c13f70c72c9b5a38fcc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 19:15:34 -0800 Subject: [PATCH 01/46] perf(spiraldb): check the writer lease on its first write --- docs/concepts/spiraldb-database.md | 7 ++-- src/orcapod/databases/spiraldb_tables.py | 6 +-- src/orcapod/databases/spiraldb_write_scope.py | 16 ++++++-- .../test_spiraldb_writable_runs.py | 41 +++++++++++++++++++ 4 files changed, 61 insertions(+), 9 deletions(-) diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index d5eefe25e..5caf4578c 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -105,9 +105,10 @@ make the client for that same address, with a sign-in allowed to update the data 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. -Clearing the lease of a writer that is still running lets a second writer in while the -first is still writing. Each lease is a small keyed table of the dataset; keep every -one, also released ones: removing one by hand can let two writers in. +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 diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index 8987861d2..e08406ccc 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -29,7 +29,7 @@ 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 before each write; a write with none is refused +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. @@ -704,7 +704,7 @@ def hold_lease(self, check: Callable[[], None]) -> None: """Let this dataset be written under a lease a run holds (``spiraldb_write_scope``). Args: - check: Verifies the lease is still held; raises if it is not. + check: Verifies the lease at its first use; raises if it is not held. Raises: RuntimeError: If a lease is held for these tables already. @@ -725,7 +725,7 @@ def let_go_of_lease(self, check: Callable[[], None]) -> None: self._lease_check = None def _require_lease(self) -> None: - """Refuse a write unless a run holds the dataset's writer lease, and check it. + """Require an attached writer lease and verify it at its first use. 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 diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index ac03ae498..e3be54ca8 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -17,10 +17,12 @@ from __future__ import annotations import contextlib +import threading from collections.abc import Callable, Iterable, Iterator from typing import TYPE_CHECKING, Any from orcapod.databases import spiraldb_lease +from orcapod.databases.spiraldb_connector import require_same_process if TYPE_CHECKING: from orcapod.databases.spiraldb_connector import SpiralDBConnector @@ -130,13 +132,13 @@ def take_lease( 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 verified, + 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 is still held; releases it. + ``(check, release)``: verifies the lease on first use; releases it. Raises: LeaseBusyError: If another writer holds the dataset. @@ -146,8 +148,16 @@ def take_lease( taken: list[tuple[Callable[[], None], Callable[[], None]]] = [] def claimed(lease: spiraldb_lease.Lease) -> None: + checked = False + lock = threading.Lock() + def check() -> None: - spiraldb_lease.check(client, lease) + 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) diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 77cd3f4a4..eadf49089 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -806,6 +806,47 @@ def test_connectors_reaching_one_service_share_one_lease(given: str) -> None: assert all(c._writable_tables()._lease_check 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() + 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") + database.add_records( + path, + pa.table( + { + "__record_id": pa.array( + [item.encode() for item in ids], pa.large_binary() + ), + "value": [1, 2], + "__data_context": [get_default_context().context_key] * 2, + } + ), + record_id_column="__record_id", + flush=True, + ) + assert len(reads) == 1 + + with database_writes([first, second], owner="no writes"): + reads.clear() + assert reads == [] + + @pytest.mark.usefixtures("root") @pytest.mark.parametrize("native", ["missing", "no address"]) def test_a_client_without_its_resolved_address_is_refused( From 1d7af3592bfd34ba6816aa88eda5f9e919e20de3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 19:17:33 -0800 Subject: [PATCH 02/46] perf(spiraldb): index stored side-effect completions once per execution --- .../databases/connector_arrow_database.py | 43 +++++++++++++++++++ src/orcapod/side_effects.py | 27 +++++++++++- .../test_spiraldb_writable_runs.py | 30 +++++++++++++ 3 files changed, 98 insertions(+), 2 deletions(-) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index db796bf55..5090ab757 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1399,6 +1399,49 @@ def _fmt(cols: Mapping[str, pa.DataType]) -> str: # ── Read methods ────────────────────────────────────────────────────────── + 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. + + Keep stored IDs from the first lookup that needs them and consult the live + queue for each lookup. Receipts added during delivery enter that queue. + + Args: + record_path: The invocation log's path. + + Returns: + An existence lookup for a writable SpiralDB log, or None for other stores. + """ + tables = self._spiral + if tables is None: + return None + record_key = self._get_record_key(record_path) + stored_ids: set[bytes] | None = None + + def completed(record_id: bytes) -> bool: + nonlocal stored_ids + if record_id in self._pending_record_ids.get(record_key, ()): + return True + if stored_ids is None: + with tables.operation(): + committed = self._get_committed_table(record_path, schema=None) + stored_ids = ( + set() + if committed is None + else set( + cast( + "list[bytes]", committed[self.RECORD_ID_COLUMN].to_pylist() + ) + ) + ) + if record_id in stored_ids: + report_records(record_key, added=set(), durable={record_id}) + return True + return False + + return completed + @_one_spiral_operation def get_record_by_id( self, diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 46d70d5f3..b5059cb4b 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -420,6 +420,7 @@ def _execute_side_effect_row( ctx_arg_name: str = "ctx", pipeline_database: ArrowDatabaseProtocol | None = None, table_path: tuple[str, ...] | None = None, + completion_lookup: Callable[[bytes], bool] | None = None, ) -> tuple[TagProtocol, DataProtocol] | None: """Execute delivery for one (tag, data) row. @@ -446,6 +447,7 @@ def _execute_side_effect_row( data_context_key: Key of the pod's data context, stored on the log 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. Returns: ``(tag, data)`` to emit downstream, or ``None`` to drop the row. @@ -464,12 +466,17 @@ def _execute_side_effect_row( ): try: with track_completion_lookup(pipeline_database, table_path): - prior = pipeline_database.get_record_by_id(table_path, entry_id) + completed = ( + completion_lookup(entry_id) + if completion_lookup is not None + else pipeline_database.get_record_by_id(table_path, entry_id) + is not None + ) except OrcapodDatabaseError as exc: # A failed lookup fails the run like a failed write: name pod and row. exc.add_context(node_label=pod_name, tag=tag.as_dict()) raise - if prior is not None: + if completed: return (tag, data) # already completed — re-emit without re-delivery # 3. Build InvocationContext (invocation_hash derived lazily via format_id()). @@ -1286,6 +1293,7 @@ def _deliver_rows( ) -> 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( @@ -1301,11 +1309,24 @@ def _deliver_rows( 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 + def _completion_lookup(self) -> Callable[[bytes], bool] | None: + """Index a writable SpiralDB invocation log for this execution.""" + if not self._pod.pod_config.track_completion or self._table_path is None: + return None + from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase + from orcapod.databases.extension_aware_database import unwrap_database_views + + database = unwrap_database_views(self._pipeline_database) + if isinstance(database, ConnectorArrowDatabase): + return database.spiral_completion_lookup(self._table_path) + return None + def _hold( self, rows: list[tuple[TagProtocol, DataProtocol]], *, load_only: bool = False ) -> None: @@ -1546,6 +1567,7 @@ async def async_execute( 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: @@ -1562,6 +1584,7 @@ async def process_one(tag: TagProtocol, data: DataProtocol) -> None: 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: diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index eadf49089..422afd7cf 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -33,6 +33,7 @@ ) from orcapod.contexts import get_default_context from orcapod.databases import ( + spiral_database_identity, spiraldb_connector, spiraldb_lease, spiraldb_writable_registry, @@ -299,6 +300,35 @@ def test_a_new_input_and_a_replay_are_stored_as_on_delta( _same_tables(spiral_db, delta) +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ENTRIES) +@pytest.mark.parametrize("order", ["as given", "reversed"]) +def test_replayed_completions_read_the_tracking_table_once( + monkeypatch: pytest.MonkeyPatch, entry: str, order: str +) -> None: + database = _database() + job = _job(database, order=order) + _ = _run(job, entry) + delivered.clear() + job.nodes["sink"].clear_cache() + tracking_path = next(p for p in database.list_table_paths() if p[-1] == "tdb_v2") + name = spiral_database_identity.spiral_table_name(tracking_path) + table_id = fake.ExternalProject("p").table(f"d.{name}").table_id + scan = fake.FakeKeyedTable.scan + reads: list[str] = [] + + def counted(table_handle: fake.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any: + if table_handle.resource_id == table_id and not args and not kwargs: + reads.append(table_handle.resource_id) + return scan(table_handle, *args, **kwargs) + + monkeypatch.setattr(fake.FakeKeyedTable, "scan", counted) + _ = _run(job, entry) + assert len(reads) == 1 + assert delivered == [] + assert job.nodes["sink"].as_table().num_rows == 3 + + # ------------------------------------------------------------------ load only From eb0be80baf398797cb57b52d5074f052fa663678 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 19:19:12 -0800 Subject: [PATCH 03/46] perf(spiraldb): reuse the writer lease key index at flush --- docs/concepts/spiraldb-database.md | 4 + .../databases/connector_arrow_database.py | 5 +- src/orcapod/databases/spiraldb_tables.py | 90 +++++++++++++------ src/orcapod/databases/spiraldb_write_scope.py | 18 ++-- .../test_spiraldb_writable_mode.py | 34 ++++--- 5 files changed, 92 insertions(+), 59 deletions(-) diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index 5caf4578c..25b601616 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -77,6 +77,10 @@ source it reads. A run takes one lease per dataset of one service: writable conn 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 writer must respect the dataset's lease. Writes from outside the lease can +invalidate the index and are unsupported. + ### A lease left behind A process that stops in the middle of a run (killed, or a lost connection) leaves its diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 5090ab757..490d12521 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1359,10 +1359,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: - # Writes only the keys the write's fresh key read does not show: a row - # visible then is never overwritten (SpiralDB's append replaces a row of - # the same key). A key another writer stores after that read can still - # be replaced until the one-writer lease (ITL-1452). + # Write only keys that are absent from the lease's key index. tables.write(table_name, pending) elif self._sql_store is None: self._connector.create_table_if_not_exists( diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index e08406ccc..d152f3111 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -39,8 +39,8 @@ import threading from collections.abc import Callable, Collection, Iterator, Mapping -from contextlib import AbstractContextManager, contextmanager -from dataclasses import dataclass +from contextlib import AbstractContextManager, contextmanager, nullcontext +from dataclasses import dataclass, field from typing import Any, Protocol, cast import pyarrow as pa @@ -65,6 +65,19 @@ """The column every stored row's data context is in.""" +@dataclass +class WriterLease: + """A run's verification and key index, shared by its dataset's connectors.""" + + verify: Callable[[], None] + lock: threading.RLock = field(default_factory=threading.RLock) + keys_by_table: dict[str, set[bytes]] = field(default_factory=dict) + + def __call__(self) -> None: + """Verify the writer lease on first use.""" + self.verify() + + class _Scan(Protocol): """The part of spiral-sdk's scan the database uses.""" @@ -216,7 +229,7 @@ def __init__( 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: Callable[[], None] | None = None + self._lease_check: WriterLease | None = None key_column: str = codec.KEY_COLUMN """The key column of every database table.""" @@ -674,10 +687,14 @@ def existing_record_ids( """ if not ids: return set() - opened = self._judge(table_name) - if opened is None: - return set() - with self._about(table_name): + lease = self._lease_check + with ( + lease.lock if lease is not None else nullcontext(), + self._about(table_name), + ): + opened = self._judge(table_name) + if opened is None: + return set() return self._held_ids(opened.table, ids) def _held_ids(self, table: _KeyedTable, ids: Collection[bytes]) -> set[bytes]: @@ -690,17 +707,25 @@ def _held_ids(self, table: _KeyedTable, ids: Collection[bytes]) -> set[bytes]: Returns: The ids it holds. """ - with self._service_call("read the keys of a database table"): - stored = table.scan([codec.KEY_COLUMN]).to_table() - held = cast( - "list[bytes]", - stored.column(codec.KEY_COLUMN).cast(pa.large_binary()).to_pylist(), - ) - return set(ids).intersection(held) + lease = self._lease_check + table_id = str(table.resource_id) + held = None if lease is None else lease.keys_by_table.get(table_id) + if held is None: + with self._service_call("read the keys of a database table"): + stored = table.scan([codec.KEY_COLUMN]).to_table() + held = set( + cast( + "list[bytes]", + stored.column(codec.KEY_COLUMN).cast(pa.large_binary()).to_pylist(), + ) + ) + if lease is not None: + lease.keys_by_table[table_id] = held + return held.intersection(ids) # ── writing ────────────────────────────────────────────────────────────── - def hold_lease(self, check: Callable[[], None]) -> None: + def hold_lease(self, check: WriterLease) -> None: """Let this dataset be written under a lease a run holds (``spiraldb_write_scope``). Args: @@ -715,7 +740,7 @@ def hold_lease(self, check: Callable[[], None]) -> None: ) self._lease_check = check - def let_go_of_lease(self, check: Callable[[], None]) -> None: + def let_go_of_lease(self, check: WriterLease) -> None: """Stop writing under the lease ``hold_lease`` was given ``check`` for. Args: @@ -724,7 +749,7 @@ def let_go_of_lease(self, check: Callable[[], None]) -> None: if self._lease_check is check: self._lease_check = None - def _require_lease(self) -> None: + def _require_lease(self) -> WriterLease: """Require an attached writer lease and verify it at its first use. The lease is held by the writable connectors of the run that took it: a write @@ -745,6 +770,7 @@ def _require_lease(self) -> None: "job node's run()), which takes the lease; nothing was written" ) check() + return check def _create_or_open(self, table_name: str) -> _KeyedTable: """The table at a computed name, created now if absent. @@ -853,13 +879,9 @@ def _require_same_manifest( def write(self, table_name: str, records: pa.Table) -> None: """Write rows whose keys the table does not hold yet; the first write creates the - table and records its identity and manifest. Every check runs before anything is - created or written. A row the write's fresh key read shows is never overwritten: - ``ConnectorArrowDatabase`` refuses a stored id when the rows are added (unless - asked to skip it), and a key another writer stored before that read is left as - that writer stored it. A key another writer stores after that read can still be - replaced (SpiralDB's append replaces a row of the same key) until the one-writer - lease (ITL-1452). + table and records its identity and manifest. The lease 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. 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 @@ -885,7 +907,18 @@ def write(self, table_name: str, records: pa.Table) -> None: path = self._path_of(table_name) context = _one_data_context(records) # Before anything is created or written: one writer per dataset (ITL-1844). - self._require_lease() + lease = self._require_lease() + with lease.lock: + self._write(table_name, path, context, records) + + def _write( + self, + table_name: str, + path: tuple[str, ...], + context: str, + records: pa.Table, + ) -> None: + """Write records while holding the lease's lock.""" # Opened by name afresh at the write, never through a handle opened earlier in # the operation: a caller's check may have run since (``outside_operation``), # and another writer may have stored a key, or the table may have been renamed @@ -919,9 +952,6 @@ def write(self, table_name: str, records: pa.Table) -> None: f"the table stores its columns under other names ({difference}): " + "an append would write columns its manifest does not record" ) - # The keys are read again at every write, also for ids the add found - # absent: the lease keeps other Orcapod writers out, but not a hand-made - # write, and an append would replace its row (fewer reads: ITL-1841). held = self._held_ids(opened.table, _ids(records)) encoded = _encoded(_without_ids(records, held)) if encoded.num_rows == 0: @@ -986,13 +1016,17 @@ def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: found: What it records. encoded: The rows, encoded. """ + lease = self._lease_check + assert lease is not None try: with self._service_call("write a database table"): _ = table.append(encoded) 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) raise + lease.keys_by_table.setdefault(found.table_id, set()).update(_ids(encoded)) self._found_by_id[found.table_id] = found diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index e3be54ca8..201a01807 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -23,6 +23,7 @@ from orcapod.databases import spiraldb_lease from orcapod.databases.spiraldb_connector import require_same_process +from orcapod.databases.spiraldb_tables import WriterLease if TYPE_CHECKING: from orcapod.databases.spiraldb_connector import SpiralDBConnector @@ -85,7 +86,7 @@ def database_writes(databases: Iterable[object], *, owner: str) -> Iterator[None 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], Callable[[], None], Callable[[], None]]] = [] # pyright: ignore[reportExplicitAny] # SpiralDBTables + held: list[tuple[list[Any], WriterLease, Callable[[], None]]] = [] # pyright: ignore[reportExplicitAny] # SpiralDBTables try: for connectors in groups.values(): # The database tables holding this lease, each once (every writable @@ -94,7 +95,7 @@ def database_writes(databases: Iterable[object], *, owner: str) -> Iterator[None holding: list[Any] = [] # pyright: ignore[reportExplicitAny] # SpiralDBTables def register( - check: Callable[[], None], + check: WriterLease, release: Callable[[], None], holding: list[Any] = holding, # pyright: ignore[reportExplicitAny] # SpiralDBTables ) -> None: @@ -125,8 +126,8 @@ def take_lease( connector: SpiralDBConnector, owner: str, *, - on_taken: Callable[[Callable[[], None], Callable[[], None]], None] | None = None, -) -> tuple[Callable[[], None], Callable[[], None]]: + 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``). Args: @@ -145,7 +146,7 @@ def take_lease( LeaseError: If the claim cannot be verified. """ client, project_id, dataset = connector._writer_lease_target() # pyright: ignore[reportPrivateUsage] # the lease is taken by this module only - taken: list[tuple[Callable[[], None], Callable[[], None]]] = [] + taken: list[tuple[WriterLease, Callable[[], None]]] = [] def claimed(lease: spiraldb_lease.Lease) -> None: checked = False @@ -162,9 +163,10 @@ def check() -> None: def release() -> None: spiraldb_lease.release(client, lease) - taken.append((check, release)) + writer = WriterLease(check) + taken.append((writer, release)) if on_taken is not None: - on_taken(check, release) + on_taken(writer, release) _ = spiraldb_lease.acquire( client, project_id, dataset, owner=owner, on_claim=claimed @@ -180,7 +182,7 @@ def _tables(connector: SpiralDBConnector) -> Any: # pyright: ignore[reportExpli def _release_all( - held: list[tuple[list[Any], Callable[[], None], Callable[[], None]]], # pyright: ignore[reportExplicitAny] # SpiralDBTables + 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. diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index aa02a2d07..f9d8a3d8d 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -326,7 +326,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(connector) + tables = tables_of(writable_connector(held=False)) name = tables.table_name(RESULT) fake.scan_log.clear() fake.count_log.clear() @@ -1809,20 +1809,18 @@ def counted_scan(self: Any, *args: Any, **kwargs: Any) -> Any: def test_one_operation_opens_the_name_once( monkeypatch: pytest.MonkeyPatch, ) -> None: - """Round 2, P2: an add opens the table's name once and reads its keys once. The - flush that follows opens it once to check the rows and once more at the write, - after the caller's schema check, and reads the keys again from that last - snapshot (another writer may have stored one since: an append would replace its - row).""" - db = ConnectorArrowDatabase(writable_connector()) - _add(db, rows(["r0", "r1"]), flush=True) - counts = _counted(monkeypatch) - _add(db, rows(["r2", "r3"], offset=2)) - assert counts == {"opens": 1, "key_reads": 1} - db.flush() - assert counts == {"opens": 3, "key_reads": 2} - _add(db, rows(["r3", "r4"], offset=3), skip_duplicates=True, flush=True) - assert counts == {"opens": 5, "key_reads": 3} + """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"): + _add(db, rows(["r0", "r1"]), flush=True) + with database_writes([db], owner="append"): + counts = _counted(monkeypatch) + _add(db, rows(["r2", "r3"], offset=2)) + assert counts == {"opens": 1, "key_reads": 1} + db.flush() + assert counts == {"opens": 3, "key_reads": 1} + _add(db, rows(["r3", "r4"], offset=3), skip_duplicates=True, flush=True) + assert counts == {"opens": 5, "key_reads": 1} got = _get(db) assert got is not None assert sorted(_record_ids(got)) == [ @@ -1838,10 +1836,8 @@ def test_one_operation_opens_the_name_once( def test_ids_checked_by_two_handles_are_written_once( monkeypatch: pytest.MonkeyPatch, ) -> None: - """Round 2, P2: two databases on one connector both find an id absent; the first - flush writes it, and the second reads the keys again and keeps the first row, - never replacing it (the handle reused within an operation is never an earlier - operation's).""" + """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.""" connector = writable_connector() first, second = ConnectorArrowDatabase(connector), ConnectorArrowDatabase(connector) _add(first, rows(["r0"]), flush=True) From 723cbf4064efd46be02156c372eb19c045e29422 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 19:20:08 -0800 Subject: [PATCH 04/46] perf(spiraldb): release a claim without scanning its state --- src/orcapod/databases/spiraldb_lease.py | 4 ++- tests/test_databases/test_spiral_lease.py | 32 +++++++++++++------ .../test_spiraldb_writable_runs.py | 2 +- 3 files changed, 27 insertions(+), 11 deletions(-) diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py index 9f708a216..329fe9872 100644 --- a/src/orcapod/databases/spiraldb_lease.py +++ b/src/orcapod/databases/spiraldb_lease.py @@ -475,7 +475,9 @@ def release(client: _Client, lease: Lease) -> None: LeaseError: If the claim's identity or release cannot be verified. RuntimeError: If the lease belongs to a different process. """ - _mark_released(client, _held_table(client, lease), lease.key) + # 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( diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py index 424ce80b8..fcddbb905 100644 --- a/tests/test_databases/test_spiral_lease.py +++ b/tests/test_databases/test_spiral_lease.py @@ -803,9 +803,28 @@ def test_on_claim_is_given_the_lease_acquire_returns(client: fake.FakeClient) -> check(client, lease) -@pytest.mark.parametrize("operation", ["release", "clear"]) -def test_a_failed_state_read_before_release_is_a_lease_error( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, operation: str +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.""" @@ -814,12 +833,7 @@ def test_a_failed_state_read_before_release_is_a_lease_error( interrupted = KeyboardInterrupt("scan interrupted") def run() -> None: - if operation == "release": - release(client, holder) - else: - clear( - client, _PROJECT, _DATASET, holder.table_id, confirm_writer_stopped=True - ) + clear(client, _PROJECT, _DATASET, holder.table_id, confirm_writer_stopped=True) def unavailable(*_args: object, **_kwargs: object) -> None: raise cause diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 422afd7cf..94131dc91 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -695,7 +695,7 @@ def test_the_lease_raises_no_keyed_table_deprecation() -> None: ) _, again = take_lease(connector, "third") again() - release() # cleared already: its release reopens it by id and finds it released + 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]) From fd3f70142940c8799bb64ee6290fae8c19240b0c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 19:22:07 -0800 Subject: [PATCH 05/46] perf(spiraldb): share stale-table discovery across a run --- src/orcapod/contexts/stored.py | 10 +++ .../databases/connector_arrow_database.py | 22 ++++++ src/orcapod/databases/spiraldb_connector.py | 1 + src/orcapod/databases/spiraldb_tables.py | 72 +++++++++++++++++-- src/orcapod/databases/spiraldb_write_scope.py | 5 +- .../test_spiraldb_writable_mode.py | 30 ++++++++ .../test_spiraldb_writable_runs.py | 21 ++++++ 7 files changed, 152 insertions(+), 9 deletions(-) diff --git a/src/orcapod/contexts/stored.py b/src/orcapod/contexts/stored.py index 3369233a3..266ebf299 100644 --- a/src/orcapod/contexts/stored.py +++ b/src/orcapod/contexts/stored.py @@ -502,7 +502,17 @@ def find_stale_tables( ) ) if current is not None: + from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase + from orcapod.databases.extension_aware_database import unwrap_database_views + current_path, current_context = current + store = unwrap_database_views(database) + # SpiralDB records a single data context for the table. Read rows only + # when the report needs to count them under another context. + if isinstance( + store, ConnectorArrowDatabase + ) and store.spiral_records_match_context(current_path, current_context): + return found for key, rows in sorted(stored_data_contexts(database, current_path).items()): if key != current_context: found.tables.append( diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 490d12521..9a1795fe1 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1396,6 +1396,28 @@ def _fmt(cols: Mapping[str, pa.DataType]) -> str: # ── Read methods ────────────────────────────────────────────────────────── + @_one_spiral_operation + def spiral_records_match_context( + self, record_path: tuple[str, ...], current: str + ) -> bool: + """Whether a writable SpiralDB path has no rows of another data context.""" + tables = self._spiral + if tables is None: + return False + full_path = self._path_prefix + record_path + name = self._path_to_table_name(full_path) + self._require_table_name(name) + try: + stored = tables.recorded_data_context(name) + except (OrcapodDatabaseError, SpiralTableCollisionError): + raise + except Exception as exc: + raise OrcapodDatabaseReadError(name, full_path) from exc + pending = self._pending_batches.get(self._get_record_key(record_path)) + return (stored is None or stored == current) and ( + pending is None or tables.data_context(pending) == current + ) + def spiral_completion_lookup( self, record_path: tuple[str, ...] ) -> Callable[[bytes], bool] | None: diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 0a40bf185..be1ce327f 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -1118,6 +1118,7 @@ def _new_tables(self) -> SpiralDBTables: ), lambda: _list_keyed_tables(client, project_id, dataset), lambda doing: _service_call(f"{doing} of {project_id}/{dataset}", health), + lambda: _service_address(client), ) def _require_open(self) -> None: diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index d152f3111..2749e904d 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -40,6 +40,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 @@ -65,6 +66,29 @@ """The column every stored row's data context is in.""" +@dataclass +class _Catalog: + """One run's view of a dataset, updated as the run writes new tables.""" + + names: dict[str, str] + records: dict[str, tuple[identity.TableRecord, str]] = field(default_factory=dict) + + +_run_catalogs: ContextVar[dict[tuple[str, str, str], _Catalog] | None] = ContextVar( + "spiral_run_catalogs", default=None +) + + +@contextmanager +def run_catalog() -> Iterator[None]: + """Share each SpiralDB dataset's first listing for a pipeline run.""" + token = _run_catalogs.set({}) + try: + yield + finally: + _run_catalogs.reset(token) + + @dataclass class WriterLease: """A run's verification and key index, shared by its dataset's connectors.""" @@ -192,6 +216,7 @@ class SpiralDBTables: create_table: Creates a keyed table in the dataset, by name and key schema. 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. + service_address: Returns the resolved URL of the dataset's service. """ def __init__( @@ -204,6 +229,7 @@ def __init__( create_table: Callable[[str, pa.Schema], object], list_tables: Callable[[], dict[str, str]], service_call: Callable[[str], AbstractContextManager[None]], + service_address: Callable[[], str], ) -> None: self._sdk: Any = sdk # pyright: ignore[reportExplicitAny] self._project_id: str = project_id @@ -213,6 +239,7 @@ def __init__( self._create_table: Callable[[str, pa.Schema], object] = create_table self._list_tables: Callable[[], dict[str, str]] = list_tables self._service_call: Callable[[str], AbstractContextManager[None]] = service_call + self._service_address = service_address self._paths: dict[str, tuple[str, ...]] = {} # What a table that holds rows records, by its id: a table's key, record and # manifest never change once it holds rows. Which table a name opens is asked @@ -531,13 +558,19 @@ def table_paths( """ start = identity.spiral_table_name_prefix(prefix) found = {p for p in pending if p[: len(prefix)] == prefix} - with self._service_call("list the database tables"): - listed = self._list_tables() - for table_id, table_name in listed.items(): + catalogs = _run_catalogs.get() + if catalogs is None: + catalog = _Catalog(self._list_dataset()) + else: + key = self._catalog_key() + catalog = catalogs.get(key) + if catalog is None: + catalog = catalogs[key] = _Catalog(self._list_dataset()) + for table_id, table_name in tuple(catalog.names.items()): if not table_name.startswith(start): continue with self._about(table_name): - read = self._record_of(table_id, table_name) + read = self._record_of(table_id, table_name, catalog.records) if read is None: continue record, table_format = read @@ -550,8 +583,18 @@ def table_paths( found.add((*record.path[:-1], last)) return sorted(found) + def _catalog_key(self) -> tuple[str, str, str]: + return self._service_address(), self._project_id, self._dataset + + def _list_dataset(self) -> dict[str, str]: + with self._service_call("list the database tables"): + return self._list_tables() + def _record_of( - self, table_id: str, table_name: str + self, + table_id: str, + table_name: str, + run_records: dict[str, tuple[identity.TableRecord, str]], ) -> 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. @@ -563,8 +606,9 @@ 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. """ - read = self._records_by_id.get(table_id) + read = self._records_by_id.get(table_id) or run_records.get(table_id) table: _KeyedTable | None = None if read is None: table = self._open_table_by_id(table_id) @@ -588,7 +632,7 @@ def _record_of( ) if not _holds_rows(table, self._service_call, columns): return None # never kept: its rows may be written later - self._records_by_id[table_id] = read + self._records_by_id[table_id] = run_records[table_id] = read return read # ── reading ────────────────────────────────────────────────────────────── @@ -619,6 +663,11 @@ def recorded_schema(self, table_name: str) -> pa.Schema: """ return self._require(table_name).manifest.schema + def recorded_data_context(self, table_name: str) -> str | None: + """Return the recorded data context of a table with committed rows.""" + opened = self._judge(table_name) + return None if opened is None else opened.found.record.data_context_key + def arrow_schema(self, table_name: str) -> pa.Schema: """The schema rows of the table are read with: logical types live, field and schema metadata as recorded. @@ -1028,6 +1077,15 @@ def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: raise lease.keys_by_table.setdefault(found.table_id, set()).update(_ids(encoded)) self._found_by_id[found.table_id] = found + catalogs = _run_catalogs.get() + if ( + catalogs is not None + and (catalog := catalogs.get(self._catalog_key())) is not None + ): + _ = catalog.names.setdefault( + found.table_id, identity.spiral_table_name(found.record.path) + ) + catalog.records[found.table_id] = (found.record, identity.TABLE_FORMAT) def _stored_names_difference( diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index 201a01807..d622161c3 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -23,7 +23,7 @@ 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 WriterLease, run_catalog if TYPE_CHECKING: from orcapod.databases.spiraldb_connector import SpiralDBConnector @@ -115,7 +115,8 @@ def register( _release_all(held, error) raise try: - yield + with run_catalog(): + yield except BaseException as error: _release_all(held, error) raise diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index f9d8a3d8d..dc2029d78 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -752,6 +752,36 @@ 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: + db = ConnectorArrowDatabase(writable_connector()) + if kind == "empty": + _make_table( + identity.spiral_table_name(RESULT), + identity.table_identity_metadata(RESULT, CONTEXT), + with_rows=False, + ) + if kind in {"pending", "stored"}: + _add(db, rows(["r0", "r1"]), flush=kind == "stored") + fake.scan_log.clear() + + assert find_stale_tables(db, current=(RESULT, CONTEXT)).tables == [] + assert not [scan for scan in fake.scan_log if scan.limit is None] + + found = find_stale_tables(db, current=(RESULT, "other")) + if kind in {"pending", "stored"}: + assert len(found.tables) == 1 + stale = found.tables[0] + assert (stale.record_path, stale.data_context, stale.rows) == ( + RESULT, + CONTEXT, + 2, + ) + else: + assert found.tables == [] + + @pytest.mark.usefixtures("root") def test_a_listed_table_recording_a_path_of_another_name_is_refused() -> None: _make_table( diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 94131dc91..6bd1fed73 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -329,6 +329,27 @@ def counted(table_handle: fake.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any assert job.nodes["sink"].as_table().num_rows == 3 +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ENTRIES) +def test_stale_checks_share_the_dataset_listing_during_each_run( + monkeypatch: pytest.MonkeyPatch, entry: str +) -> None: + listings: list[tuple[str, str]] = [] + list_tables = spiraldb_connector._list_keyed_tables # 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) + for order in ("as given", "reversed"): + 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] + + # ------------------------------------------------------------------ load only From 4d2b272af545f9d64e2b2f92e7af6d672a9ab4db Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 19:23:48 -0800 Subject: [PATCH 06/46] perf(spiraldb): mark tables after their first successful append --- src/orcapod/databases/spiraldb_tables.py | 31 +++++++++++++--- .../test_spiraldb_writable_mode.py | 35 +++++++++++++++++++ 2 files changed, 62 insertions(+), 4 deletions(-) diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index 2749e904d..6566b4176 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -37,6 +37,7 @@ from __future__ import annotations +import logging import threading from collections.abc import Callable, Collection, Iterator, Mapping from contextlib import AbstractContextManager, contextmanager, nullcontext @@ -65,6 +66,9 @@ DATA_CONTEXT_COLUMN = constants.DATA_CONTEXT_COL """The column every stored row's data context is in.""" +_HOLDS_ROWS = "orcapod.holds_rows" +logger = logging.getLogger(__name__) + @dataclass class _Catalog: @@ -501,7 +505,7 @@ def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Judgment: 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]): + if not _holds_rows(table, self._service_call, [codec.KEY_COLUMN], metadata): # New: its first write records it, unless what it saw here changed. return _New(_seen_manifest(metadata, path), record) try: @@ -610,6 +614,7 @@ def _record_of( """ read = self._records_by_id.get(table_id) or run_records.get(table_id) table: _KeyedTable | None = None + metadata: dict[str, bytes] = {} if read is None: table = self._open_table_by_id(table_id) with self._service_call("read the metadata of a database table"): @@ -630,7 +635,12 @@ def _record_of( columns = ( [codec.KEY_COLUMN] if table_format == identity.TABLE_FORMAT else None ) - if not _holds_rows(table, self._service_call, columns): + if not _holds_rows( + table, + self._service_call, + columns, + metadata if columns is not None else {}, + ): return None # never kept: its rows may be written later self._records_by_id[table_id] = run_records[table_id] = read return read @@ -889,7 +899,7 @@ def _unchanged_since_judged( return ( record == seen_record and _same_seen(now, seen) - and not _holds_rows(table, self._service_call, [codec.KEY_COLUMN]) + and not _holds_rows(table, self._service_call, [codec.KEY_COLUMN], metadata) ) def _require_same_manifest( @@ -1040,7 +1050,8 @@ def _write_first( self._forget_opened(table_name) table = self._create_or_open(table_name) _require_key(table, self._service_call) - if self._unchanged_since_judged(table, path, seen, seen_record): + 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) recorded = _Found( @@ -1056,6 +1067,14 @@ def _write_first( encoded = _encoded(_without_ids(records, held)) if encoded.num_rows > 0: self._append(table, recorded, encoded) + if first_append: + try: + with self._service_call("mark a database table as holding rows"): + table.set_metadata({_HOLDS_ROWS: b"1"}) + except Exception: # noqa: BLE001 # the append committed and legacy reads can check for rows + logger.debug( + "Could not mark SpiralDB table as holding rows", exc_info=True + ) def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: """Append encoded rows; keep what the table records only once that succeeded. @@ -1155,6 +1174,7 @@ def _holds_rows( table: _KeyedTable, service_call: Callable[[str], AbstractContextManager[None]], columns: list[str] | None, + metadata: Mapping[str, bytes], ) -> bool: """Whether a keyed table has a row. @@ -1162,7 +1182,10 @@ def _holds_rows( table: The table. service_call: The database's ``service_call``. columns: The columns of the one row read (``None`` for all of them). + metadata: Metadata of a database table using this format. """ + if metadata.get(_HOLDS_ROWS) == b"1": + return True with service_call("read a key of a database table"): keys = table.scan(columns, limit=1).to_table() return keys.num_rows > 0 diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index dc2029d78..04c130208 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -1469,6 +1469,41 @@ def test_a_failed_first_append_leaves_no_table_known( assert not db.table_exists(RESULT) and not fresh.table_exists(RESULT) +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("mark_succeeds", [True, False]) +def test_first_append_marks_that_the_table_holds_rows( + monkeypatch: pytest.MonkeyPatch, mark_succeeds: bool +) -> None: + mark = "orcapod.holds_rows" + set_metadata = fake.FakeKeyedTable.set_metadata + sets: list[dict[str, bytes]] = [] + + def recorded(table: fake.FakeKeyedTable, metadata: dict[str, bytes]) -> None: + sets.append(metadata) + if mark in metadata and not mark_succeeds: + raise fake.SpiralError("metadata write failed") + set_metadata(table, metadata) + + monkeypatch.setattr(fake.FakeKeyedTable, "set_metadata", recorded) + db = ConnectorArrowDatabase(writable_connector()) + _add(db, rows(["r0", "r1"]), flush=True) + _add(db, rows(["r3", "r2"]), flush=True) + assert len(sets) == 2 + assert mark not in sets[0] + assert sets[1] == {mark: b"1"} + + fake.count_log.clear() + by_name = ConnectorArrowDatabase(writable_connector(held=False)) + by_listing = ConnectorArrowDatabase(writable_connector(held=False)) + 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]) == ( + 0 if mark_succeeds else 2 + ) + got = _get(by_name) + assert got is not None and len(got) == 4 + + @pytest.mark.usefixtures("root") def test_a_failed_first_append_lets_another_writer_record_the_table_anew( monkeypatch: pytest.MonkeyPatch, From 1096bf20fe3191d14bc6ce268682d265a3bc85d0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 19:25:34 -0800 Subject: [PATCH 07/46] perf(spiraldb): batch function result commits during node runs --- src/orcapod/core/nodes/function_node.py | 12 ++-- src/orcapod/pipeline/job.py | 10 +-- src/orcapod/pipeline/node_run.py | 32 ++++++++- .../test_spiraldb_writable_runs.py | 68 ++++++++++++++++++- 4 files changed, 110 insertions(+), 12 deletions(-) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 33bb2ef69..33c9c9fd2 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -2432,8 +2432,9 @@ def _batched_commits(self, rows_per_commit: int) -> Iterator[None]: ``PipelineJob.run`` runs each function node inside this block. Its result caches stop committing after every stored result, and the node commits its pending writes (ephemeral results, then its result table, then the pipeline - records) every ``rows_per_commit`` rows and at its end. Outside the block - (a node run on its own) every result is committed as it is stored. + records) every ``rows_per_commit`` rows and at its end. A node run writing + to SpiralDB uses the same block. Outside it every result is committed as + it is stored. Args: rows_per_commit: How many processed rows' writes one commit holds. @@ -4506,7 +4507,7 @@ def _run_alone( """ from dataclasses import replace - from orcapod.pipeline.node_run import commit_run + from orcapod.pipeline.node_run import batch_spiral_node_commits, commit_run from orcapod.pipeline.restrictions import restrictions_in_force from orcapod.pipeline.run_summary import RunCountingObserver, RunSummary from orcapod.utils.database_errors import flush_best_effort @@ -4525,7 +4526,10 @@ def _run_alone( if database is not None ] try: - _ = self.execute(self._input_stream, observer=counter, load_only=load_only) + with batch_spiral_node_commits([self], databases, load_only=load_only): + _ = self.execute( + self._input_stream, observer=counter, load_only=load_only + ) except Exception as run_error: if not load_only: # Commit what succeeded; a load-only run writes nothing (ITL-1095). diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 12d289a7d..f7bf2d511 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -45,6 +45,7 @@ shared_node_hash_error, ) from orcapod.pipeline.node_run import ( + DEFAULT_COMMIT_EVERY_ROWS, RunPlan, check_sources, clear_run_rows, @@ -1304,7 +1305,7 @@ def run( orchestrator: "SyncPipelineOrchestrator | AsyncPipelineOrchestrator | None" = None, observer: "ExecutionObserverProtocol | None" = None, materialize_results: bool = True, - commit_every_rows: int = 100, + commit_every_rows: int = DEFAULT_COMMIT_EVERY_ROWS, *, load_only: bool = False, ) -> RunSummary: @@ -1357,8 +1358,9 @@ def run( process) loses at most the rows of the running node since its last commit; re-running the job recomputes only those. A larger value commits less often (faster, fewer files); ``1`` commits - after every row. A node run on its own, outside ``run()``, - commits after every row. It must be smaller than the database's + after every row. A node run on its own commits every 100 rows + and at node end when writing to SpiralDB, and otherwise commits + after every row. It must be smaller than the database's ``batch_size`` when the database has one (``DeltaTableDatabase``, default 1000): the database commits every pending table by itself once one table's pending rows reach that size, which would @@ -1494,7 +1496,7 @@ async def run_async( orchestrator: "AsyncPipelineOrchestrator | None" = None, observer: "ExecutionObserverProtocol | None" = None, materialize_results: bool = True, - commit_every_rows: int = 100, + commit_every_rows: int = DEFAULT_COMMIT_EVERY_ROWS, *, load_only: bool = False, ) -> RunSummary: diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index f6e5a0680..37824aac4 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -38,6 +38,8 @@ if TYPE_CHECKING: from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +DEFAULT_COMMIT_EVERY_ROWS = 100 + def _is_job_node(stream: Any) -> bool: """Whether ``stream`` is a node of a job (as opposed to a stream outside any job).""" @@ -627,6 +629,29 @@ def commit_run(databases: Sequence[ArrowDatabaseProtocol], ran: Sequence[Any]) - raise +@contextlib.contextmanager +def batch_spiral_node_commits( + nodes: Sequence[Any], databases: Sequence[ArrowDatabaseProtocol], *, load_only: bool +) -> Iterator[None]: + """Use the job's commit cadence when a node run writes to SpiralDB.""" + from orcapod.core.nodes.function_node import FunctionJobNode + from orcapod.databases.spiraldb_writable_registry import any_writable_connector + from orcapod.databases.spiraldb_write_scope import writable_connectors + + with contextlib.ExitStack() as stack: + if ( + not load_only + and any_writable_connector() + and writable_connectors(databases) + ): + for node in nodes: + if isinstance(node, FunctionJobNode): + stack.enter_context( + node._batched_commits(DEFAULT_COMMIT_EVERY_ROWS) # pyright: ignore[reportPrivateUsage] # the run sets the commit cadence + ) + yield + + def run_with_dependencies( target: Any, *, load_only: bool, unchecked_sources: Sequence[str] = () ) -> RunSummary: @@ -689,9 +714,10 @@ def visit(node: Any) -> None: databases = _databases(plan.to_run) counter = RunCountingObserver() try: - _ = SyncPipelineOrchestrator().run( - plan.dag, observer=counter, load_only=load_only, held=plan.held - ) + with batch_spiral_node_commits(plan.to_run, databases, load_only=load_only): + _ = SyncPipelineOrchestrator().run( + plan.dag, observer=counter, load_only=load_only, held=plan.held + ) except BaseException as run_error: if isinstance(run_error, Exception) and not load_only: # Commit the writes that succeeded before the failure, as job.run() does; diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 6bd1fed73..94f63220b 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -42,7 +42,7 @@ 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.errors import SpiralDBLeaseRequiredError +from orcapod.errors import RowFailuresWarning, SpiralDBLeaseRequiredError from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.pipeline import node_run from orcapod.semantic_types.universal_converter import UniversalTypeConverter @@ -350,6 +350,72 @@ def counted(client: Any, project: str, dataset: str) -> dict[str, str]: assert listings == [("p", "d")] * LEASES[entry] +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("order", ["as given", "reversed"]) +@pytest.mark.parametrize("target", ["combine", "select"]) +def test_node_run_appends_function_results_as_one_batch( + monkeypatch: pytest.MonkeyPatch, order: str, target: str +) -> None: + database = _database() + job = _job(database, order=order) + append = fake.FakeKeyedTable.append + appended: list[int] = [] + + def counted(table: fake.FakeKeyedTable, batch: pa.Table) -> fake.FakeKeyedTable: + record = spiral_database_identity.read_table_identity_metadata( + table.get_metadata() + ) + if record is not None and record.path[-1] == "rdb_v1": + appended.append(batch.num_rows) + return append(table, batch) + + monkeypatch.setattr(fake.FakeKeyedTable, "append", counted) + fake.scan_log.clear() + _ = job.nodes[target].run() + result_path = next(p for p in database.list_table_paths() if p[-1] == "rdb_v1") + result_name = spiral_database_identity.spiral_table_name(result_path) + reads = [s for s in fake.scan_log if s.identifier == f"d.{result_name}"] + assert (appended, len(reads)) == ([3], 0) + assert job.nodes[target].as_table().num_rows == 3 + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "run_async", "node run"]) +@pytest.mark.parametrize("order", ["as given", "reversed"]) +def test_a_failed_row_keeps_the_same_results_and_run_counts( + root: Path, entry: str, order: str +) -> None: + @function_pod(output_keys=("total", "ratio")) + def partial_results(x: int, y: int) -> tuple[int, float]: + if x == 2: + raise ValueError("one row fails") + return x + y, x / y + + spiral_db, delta, memory = ( + _database(), + DeltaTableDatabase(root / "delta"), + InMemoryArrowDatabase(), + ) + for database in (spiral_db, delta, memory): + job = PipelineJob(name=JOB, database=database) + with job: + cache = _cached(database, _rows(), order=order) + result = partial_results.pod(cache, label="compute") + SelectDataColumns(["total", "ratio"])(result, label="select") + with pytest.warns(RowFailuresWarning): + if entry == "node run": + _ = job.nodes["select"].run() + summary = job.nodes["select"].last_run + else: + summary = _run(job, entry) + assert summary is not None + counts = summary.nodes["compute"] + assert (counts.computed, counts.reused, counts.failed) == (2, 0, 1) + assert sorted(job.nodes["select"].as_table()["total"].to_pylist()) == [6, 10] + _same_tables(spiral_db, delta) + _same_tables(spiral_db, memory) + + # ------------------------------------------------------------------ load only From 6aeaf09e9f7cfb61ccc087d52131e2cbeed9eb44 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 19:27:45 -0800 Subject: [PATCH 08/46] perf(spiraldb): use table IDs after name resolution --- docs/concepts/spiraldb-database.md | 3 + .../databases/connector_arrow_database.py | 4 +- src/orcapod/databases/spiraldb_tables.py | 60 ++++++------ .../test_spiraldb_writable_mode.py | 92 ++++++++++++------- 4 files changed, 93 insertions(+), 66 deletions(-) diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index 25b601616..caf336e7b 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -81,6 +81,9 @@ The run checks for stored keys using an index shared by its writable connectors. Every writer must respect the dataset's lease. Writes from outside the lease can invalidate the index and are unsupported. +A connection resolves a table by name and checks its recorded path when it finds +the table. Later operations use the resolved table ID for that connection. + ### A lease left behind A process that stops in the middle of a run (killed, or a lost connection) leaves its diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 9a1795fe1..dd90a89b2 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1319,8 +1319,8 @@ def _write_ready_batch( if tables is None: check(schema_now) else: - # The caller's check runs outside this operation: a public call it - # makes looks every name up again, and the write opens its table again. + # The caller's check runs outside this operation. Its public calls + # and the following write each open a fresh snapshot. with tables.outside_operation(): check(schema_now) if existing is not None: diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index 6566b4176..6d0cd7c92 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -19,9 +19,8 @@ - Which of a set of record ids a table holds is answered by one read of the key column alone and a set intersection (``existing_record_ids``): never by a range of ids, which would rely on how the service orders binary values. -- A table's name is opened on every call (a table can be renamed and another made under - its name); what a table holding rows records is kept by its table id, and only once an - append to it succeeded or a read found its rows. +- A table is resolved by name until found and checked. Its ID is then used for + the life of the connection. What a table holding rows records is kept by ID. - The database's tables are listed by one listing of the dataset, narrowed by name, and the metadata of each candidate (cached by table id): that is how stale layouts are found @@ -245,9 +244,9 @@ def __init__( self._service_call: Callable[[str], AbstractContextManager[None]] = service_call self._service_address = service_address 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 - # manifest never change once it holds rows. Which table a name opens is asked - # on every call (a table can be renamed, and another made under its name). + # manifest never change once it holds rows. self._found_by_id: dict[str, _Found] = {} # The record of a listed table that holds rows and the table format it names, # by its id (a table that holds rows never loses them). @@ -393,11 +392,10 @@ def _about(self, table_name: str) -> Iterator[None]: @contextmanager def operation(self) -> Iterator[None]: """One public operation of ``ConnectorArrowDatabase`` (an add, a flush, a read): - each name is opened and judged once inside it, and that handle reused for - reads; a write always opens its name afresh. Operations nest; the handles are - forgotten when the outermost ends, so the next operation opens each name again - (a table can be renamed, and another made under its name, between them). Code - the database does not control runs ``outside_operation``. + each table is opened and judged once inside it, and that snapshot reused for + reads. A write opens a fresh snapshot. Operations nest and the snapshots are + forgotten when the outermost ends. Code the database does not control runs + ``outside_operation``. """ depth = cast(int, getattr(self._now, "depth", 0)) if depth == 0: @@ -412,11 +410,7 @@ def operation(self) -> Iterator[None]: @contextmanager def outside_operation(self) -> Iterator[None]: - """Run code this database does not control (a caller's callback) outside the - current operation: a public call it makes opens every name afresh in an - operation of its own, and the enclosing operation forgets every handle it held - once the code returns, since that code may have renamed or replaced a table. - """ + """Give a caller's callback its own operation and discard previous snapshots.""" depth = cast(int, getattr(self._now, "depth", 0)) judged = self._judged_now() self._now.depth = 0 @@ -459,10 +453,8 @@ def _judgment(self, table_name: str) -> _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``). - The name is opened once per public operation (``operation``; on every call - outside one), so a table renamed away, or replaced by another under the name, is - never read or written through an earlier operation's answer; what a table - holding rows records is read once per table id. + Open a fresh snapshot per public operation, by ID after the name has been + resolved. The record of a table holding rows is read once per table ID. Args: table_name: A name ``table_name`` returned. @@ -493,11 +485,13 @@ def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Judgment: Returns: The judgment. """ - table = self._open_table(table_name) + table = self._open_snapshot(table_name) if table is None: return None - known = self._found_by_id.get(str(table.resource_id)) + table_id = str(table.resource_id) + known = self._found_by_id.get(table_id) if known is not None and known.record.path == path: + self._ids_by_name[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"): @@ -507,17 +501,26 @@ def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Judgment: identity.require_table_path(record, path) if not _holds_rows(table, self._service_call, [codec.KEY_COLUMN], metadata): # New: its first write records it, unless what it saw here changed. - return _New(_seen_manifest(metadata, path), record) + new = _New(_seen_manifest(metadata, path), record) + self._ids_by_name[table_name] = table_id + return new try: manifest = None if record is None else codec.read_manifest(metadata, path) except codec.ManifestError as exc: raise SpiralTableCollisionError(str(exc)) from exc if record is None or manifest is None: raise SpiralTableCollisionError("it holds rows but no table manifest") - found = _Found(str(table.resource_id), record, manifest) + found = _Found(table_id, record, manifest) self._found_by_id[found.table_id] = found + self._ids_by_name[table_name] = table_id return _Opened(found, table) + 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: + return self._open_table_by_id(table_id) + return self._open_table(table_name) + def has_table(self, table_name: str) -> bool: """Whether the database table at a computed name holds rows (and a manifest). @@ -843,7 +846,7 @@ def _create_or_open(self, table_name: str) -> _KeyedTable: Raises: KeyError: If no table is under the name even after it was created. """ - table = self._open_table(table_name) + table = self._open_snapshot(table_name) if table is not None: return table key = pa.schema([pa.field(codec.KEY_COLUMN, pa.large_binary(), nullable=False)]) @@ -854,7 +857,7 @@ def _create_or_open(self, table_name: str) -> _KeyedTable: if "status 409" not in str(exc): # pyright: ignore[reportAny] raise # Made meanwhile: the caller compares it with what it judged. - table = self._open_table(table_name) + table = self._open_snapshot(table_name) if table is None: raise KeyError(f"no database table {self._qualified(table_name)}") return table @@ -978,10 +981,8 @@ def _write( records: pa.Table, ) -> None: """Write records while holding the lease's lock.""" - # Opened by name afresh at the write, never through a handle opened earlier in - # the operation: a caller's check may have run since (``outside_operation``), - # and another writer may have stored a key, or the table may have been renamed - # away and another made under its name. The keys are read from this snapshot. + # 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) opened = self._judgment(table_name) with self._about(table_name): @@ -1065,6 +1066,7 @@ def _write_first( # Another writer may have written these keys meanwhile. held = self._held_ids(table, _ids(records)) encoded = _encoded(_without_ids(records, held)) + self._ids_by_name[table_name] = recorded.table_id if encoded.num_rows > 0: self._append(table, recorded, encoded) if first_append: diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index 04c130208..106f037e3 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -1642,12 +1642,10 @@ def test_an_older_identifier_found_only_at_flush_is_refused( @pytest.mark.usefixtures("root") @pytest.mark.parametrize("through", ["read", "write"]) -def test_a_table_renamed_away_is_never_used_through_its_earlier_name( +def test_a_resolved_table_is_read_and_written_by_its_id( through: str, ) -> None: - """Finding 4: after the table is renamed and a foreign table made under its name, - the handle that knew it refuses the foreign table on read and on write, as a fresh - handle does: the name is resolved on every call.""" + """A connection keeps the original ID. A fresh connection checks the current name.""" db = ConnectorArrowDatabase(writable_connector()) _add(db, rows(["r0"]), flush=True) name = identity.spiral_table_name(RESULT) @@ -1658,17 +1656,18 @@ def test_a_table_renamed_away_is_never_used_through_its_earlier_name( with pytest.raises(SpiralTableCollisionError): _get(ConnectorArrowDatabase(writable_connector())) db.refresh_table(RESULT) - with pytest.raises(SpiralTableCollisionError): - if through == "read": - _get(db) - else: - _add(db, rows(["r1"]), flush=True) + 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"] + ) @pytest.mark.usefixtures("root") -def test_a_table_replaced_under_its_name_is_read_as_the_replacement() -> None: - """Finding 4: what a table records is kept by its id, never by its name: another - database table of the same path made under the name is read as itself.""" +def test_a_fresh_connection_resolves_a_replacement_by_name() -> None: + """Only a fresh connection resolves the name to the replacement.""" db = ConnectorArrowDatabase(writable_connector()) _add(db, rows(["r0"]), flush=True) name = identity.spiral_table_name(RESULT) @@ -1677,7 +1676,9 @@ def test_a_table_replaced_under_its_name_is_read_as_the_replacement() -> None: ConnectorArrowDatabase(writable_connector()), rows(["r5"], offset=5), flush=True ) got = _get(db) - assert got is not None and got.column("__record_id").to_pylist() == [b"r5"] + assert got is not None and _record_ids(got) == [b"r0"] + fresh = _get(ConnectorArrowDatabase(writable_connector())) + assert fresh is not None and _record_ids(fresh) == [b"r5"] @pytest.mark.usefixtures("root") @@ -1851,41 +1852,48 @@ def test_rows_with_the_same_older_identifier_append( def _counted(monkeypatch: pytest.MonkeyPatch) -> dict[str, int]: - """Count the fake's name opens and full key reads.""" - counts = {"opens": 0, "key_reads": 0} + """Count the fake's name opens, ID opens and full key reads.""" + counts = {"names": 0, "ids": 0, "key_reads": 0} keyed_table = fake.FakeClient.keyed_table + keyed_table_by_id = fake.FakeClient.keyed_table_by_id scan = fake.FakeKeyedTable.scan def open_by_name(self: Any, *args: Any, **kwargs: Any) -> Any: - counts["opens"] += 1 + counts["names"] += 1 return keyed_table(self, *args, **kwargs) + def open_by_id(self: Any, *args: Any, **kwargs: Any) -> Any: + counts["ids"] += 1 + return keyed_table_by_id(self, *args, **kwargs) + def counted_scan(self: Any, *args: Any, **kwargs: Any) -> Any: if args and kwargs.get("limit") is None: counts["key_reads"] += 1 return scan(self, *args, **kwargs) monkeypatch.setattr(fake.FakeClient, "keyed_table", open_by_name) + monkeypatch.setattr(fake.FakeClient, "keyed_table_by_id", open_by_id) monkeypatch.setattr(fake.FakeKeyedTable, "scan", counted_scan) return counts @pytest.mark.usefixtures("root") -def test_one_operation_opens_the_name_once( +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"): _add(db, rows(["r0", "r1"]), flush=True) + db = ConnectorArrowDatabase(writable_connector(held=False)) with database_writes([db], owner="append"): counts = _counted(monkeypatch) _add(db, rows(["r2", "r3"], offset=2)) - assert counts == {"opens": 1, "key_reads": 1} + assert counts == {"names": 1, "ids": 0, "key_reads": 1} db.flush() - assert counts == {"opens": 3, "key_reads": 1} + assert counts == {"names": 1, "ids": 3, "key_reads": 1} _add(db, rows(["r3", "r4"], offset=3), skip_duplicates=True, flush=True) - assert counts == {"opens": 5, "key_reads": 1} + assert counts == {"names": 1, "ids": 5, "key_reads": 1} got = _get(db) assert got is not None assert sorted(_record_ids(got)) == [ @@ -1897,6 +1905,25 @@ def test_one_operation_opens_the_name_once( ] +@pytest.mark.usefixtures("root") +def test_name_misses_are_retried_until_the_table_exists( + monkeypatch: pytest.MonkeyPatch, +) -> None: + reader = ConnectorArrowDatabase(writable_connector(held=False)) + with monkeypatch.context() as patch: + counts = _counted(patch) + assert _get(reader) is None + assert _get(reader) is None + assert counts["names"] == 2 and counts["ids"] == 0 + + writer = ConnectorArrowDatabase(writable_connector()) + _add(writer, rows(["r1", "r0"]), flush=True) + counts = _counted(monkeypatch) + assert _get(reader) is not None + assert _get(reader) is not None + assert counts["names"] == 1 and counts["ids"] == 1 + + @pytest.mark.usefixtures("root") def test_ids_checked_by_two_handles_are_written_once( monkeypatch: pytest.MonkeyPatch, @@ -1980,10 +2007,8 @@ def commit_first(_schema: pa.Schema) -> None: @pytest.mark.usefixtures("root") -def test_a_table_replaced_during_the_schema_check_is_refused() -> None: - """Round 3, finding 2: the table is renamed away and a foreign table made under - its name while the caller's schema check runs; the flush refuses the replacement - and never appends to the table renamed away.""" +def test_a_schema_check_does_not_change_the_resolved_table_id() -> None: + """A replacement made in a schema check does not redirect a flush.""" db = ConnectorArrowDatabase(writable_connector()) _add(db, rows(["r0"]), flush=True) _add(db, rows(["r1"], offset=1)) @@ -1992,32 +2017,29 @@ def replace_table(_schema: pa.Schema) -> None: _replace_with_a_foreign_table() with db.guard_table_schema(RESULT, replace_table): - with pytest.raises(SpiralTableCollisionError): - db.flush() + db.flush() old = fake.FakeClient().keyed_table("p", "d", "renamed_away") - assert old.scan().to_table().num_rows == 1 + assert old.scan().to_table().num_rows == 2 @pytest.mark.usefixtures("root") -def test_a_read_inside_the_schema_check_looks_the_name_up_again() -> None: - """Round 3, finding 3: a public read made by the caller's schema check never - reuses the enclosing flush's handle: after the table is replaced it refuses the - replacement, as a read after the flush does.""" +def test_a_read_inside_a_schema_check_uses_the_resolved_table_id() -> None: + """Reads in schema checks also open the resolved ID.""" db = ConnectorArrowDatabase(writable_connector()) _add(db, rows(["r0"]), flush=True) _add(db, rows(["r1"], offset=1)) def read_after_replacing(_schema: pa.Schema) -> None: _replace_with_a_foreign_table() - with pytest.raises(SpiralTableCollisionError): - _ = _get(db) + got = _get(db) + assert got is not None and _record_ids(got) == [b"r0"] raise RuntimeError("stop before the write") with db.guard_table_schema(RESULT, read_after_replacing): with pytest.raises(RuntimeError, match="stop before the write"): db.flush() - with pytest.raises(SpiralTableCollisionError): - _ = _get(db) + got = _get(db) + assert got is not None and _record_ids(got) == [b"r0"] # ------------------------------------------------- review of 6fb1b6e16 From b71d9421afcf401ca2feefa691f706bb644b9791 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 19:32:21 -0800 Subject: [PATCH 09/46] fix(spiraldb): copy nested Arrow buffers before appending --- changelog.d/ITL-1502.md | 10 +++++ src/orcapod/contexts/stored.py | 9 ++-- .../databases/extension_aware_database.py | 21 ++++++++- src/orcapod/databases/spiraldb_tables.py | 8 +++- src/orcapod/protocols/database_protocols.py | 17 +++++++ src/orcapod/side_effects.py | 8 ++-- tests/test_databases/fake_spiral_sdk.py | 31 +++++++++++++ tests/test_databases/test_fake_spiral_sdk.py | 20 +++++++++ .../test_spiraldb_writable_mode.py | 45 +++++++++++++++++++ 9 files changed, 155 insertions(+), 14 deletions(-) create mode 100644 changelog.d/ITL-1502.md diff --git a/changelog.d/ITL-1502.md b/changelog.d/ITL-1502.md new file mode 100644 index 000000000..b7f072ec8 --- /dev/null +++ b/changelog.d/ITL-1502.md @@ -0,0 +1,10 @@ +### Changed + +- Writable SpiralDB jobs reuse lease verification, stored-key and completion + lookups, and stale-table discovery across a run. Connections reuse resolved + table IDs, and node runs batch their function-result writes. + +### Fixed + +- Writable SpiralDB appends copy Arrow buffers before writing, including slices + that leave string or binary lists empty. diff --git a/src/orcapod/contexts/stored.py b/src/orcapod/contexts/stored.py index 266ebf299..100dd2cc2 100644 --- a/src/orcapod/contexts/stored.py +++ b/src/orcapod/contexts/stored.py @@ -43,6 +43,7 @@ OrcapodDatabaseContentWarning, TableListingNotSupportedError, ) +from orcapod.protocols.database_protocols import SpiralDBRunLookupProtocol from orcapod.system_constants import ( OPERATOR_DB_SCHEMA_VERSION, PIPELINE_DB_SCHEMA_VERSION, @@ -502,16 +503,12 @@ def find_stale_tables( ) ) if current is not None: - from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase - from orcapod.databases.extension_aware_database import unwrap_database_views - current_path, current_context = current - store = unwrap_database_views(database) # SpiralDB records a single data context for the table. Read rows only # when the report needs to count them under another context. if isinstance( - store, ConnectorArrowDatabase - ) and store.spiral_records_match_context(current_path, current_context): + database, SpiralDBRunLookupProtocol + ) and database.spiral_records_match_context(current_path, current_context): return found for key, rows in sorted(stored_data_contexts(database, current_path).items()): if key != current_context: diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index cdd34b130..cb014c58d 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -26,7 +26,10 @@ from typing import TYPE_CHECKING, Any, cast from orcapod.logical_types.database_hooks import register_discovered_logical_types -from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.protocols.database_protocols import ( + ArrowDatabaseProtocol, + SpiralDBRunLookupProtocol, +) if TYPE_CHECKING: from contextlib import AbstractContextManager @@ -83,6 +86,22 @@ def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: """Read the current stored schema from the wrapped database.""" return self._db.get_table_schema(record_path) + def spiral_records_match_context( + self, record_path: tuple[str, ...], current: str + ) -> bool: + """Delegate the metadata check when the wrapped store supports it.""" + return isinstance( + self._db, SpiralDBRunLookupProtocol + ) and self._db.spiral_records_match_context(record_path, current) + + def spiral_completion_lookup( + self, record_path: tuple[str, ...] + ) -> Callable[[bytes], bool] | None: + """Delegate the completion lookup when the wrapped store supports it.""" + if isinstance(self._db, SpiralDBRunLookupProtocol): + return self._db.spiral_completion_lookup(record_path) + return None + def get_record_by_id( self, record_path: tuple[str, ...], diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index 6d0cd7c92..5f40d5a3b 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -242,7 +242,7 @@ def __init__( self._create_table: Callable[[str, pa.Schema], object] = create_table self._list_tables: Callable[[], dict[str, str]] = list_tables self._service_call: Callable[[str], AbstractContextManager[None]] = service_call - self._service_address = service_address + self._service_address: Callable[[], str] = service_address 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 @@ -1088,9 +1088,13 @@ def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: """ lease = self._lease_check assert lease 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())) try: with self._service_call("write a database table"): - _ = table.append(encoded) + _ = 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) diff --git a/src/orcapod/protocols/database_protocols.py b/src/orcapod/protocols/database_protocols.py index b87eb12dc..1a5c22740 100644 --- a/src/orcapod/protocols/database_protocols.py +++ b/src/orcapod/protocols/database_protocols.py @@ -11,6 +11,23 @@ from orcapod.databases._pending_commits import PendingCommit +@runtime_checkable +class SpiralDBRunLookupProtocol(Protocol): + """Optional lookup shortcuts for writable SpiralDB databases and their views.""" + + def spiral_records_match_context( + self, record_path: tuple[str, ...], current: str + ) -> bool: + """Whether recorded metadata and pending rows rule out another data context.""" + ... + + def spiral_completion_lookup( + self, record_path: tuple[str, ...] + ) -> Callable[[bytes], bool] | None: + """Return an execution-scoped lookup for a writable SpiralDB invocation log.""" + ... + + @runtime_checkable class ArrowDatabaseProtocol(Protocol): """Internal Arrow store interface, including ordered function commits. diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index b5059cb4b..543fce0e7 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -64,6 +64,7 @@ TRACKING_DB_SCHEMA_VERSION, constants, ) +from orcapod.protocols.database_protocols import SpiralDBRunLookupProtocol from orcapod.types import ColumnConfig from orcapod.utils import arrow_utils from orcapod.utils.database_errors import flush_best_effort @@ -1319,11 +1320,8 @@ def _completion_lookup(self) -> Callable[[bytes], bool] | None: """Index a writable SpiralDB invocation log for this execution.""" if not self._pod.pod_config.track_completion or self._table_path is None: return None - from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase - from orcapod.databases.extension_aware_database import unwrap_database_views - - database = unwrap_database_views(self._pipeline_database) - if isinstance(database, ConnectorArrowDatabase): + database = self._pipeline_database + if isinstance(database, SpiralDBRunLookupProtocol): return database.spiral_completion_lookup(self._table_path) return None diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index c2c0cdba0..5ebeaf084 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -602,10 +602,41 @@ def write(self, table_id: str, rows: pa.Table) -> int: return version +def _check_list_child_offsets(array: Any) -> None: + """Model the keyed append bug for list children with sliced offsets.""" + t = array.type + if isinstance(array, pa.ExtensionArray): + _check_list_child_offsets(array.storage) + elif pa.types.is_struct(t): + for i in range(t.num_fields): + _check_list_child_offsets(array.field(i)) + elif pa.types.is_map(t): + _check_list_child_offsets(array.keys) + _check_list_child_offsets(array.items) + elif pa.types.is_dictionary(t): + _check_list_child_offsets(array.dictionary) + elif pa.types.is_run_end_encoded(t): + _check_list_child_offsets(array.values) + elif ( + pa.types.is_list(t) + or pa.types.is_large_list(t) + or pa.types.is_fixed_size_list(t) + ): + if array.values.offset: + raise SpiralError( + "Scandal:Internal: the offset of the new Buffer cannot exceed " + "the existing length (sliced list child)" + ) + _check_list_child_offsets(array.values) + + def _staged(rows: pa.Table, keys: list[str], stored: pa.Schema) -> pa.Table: """Validate ``rows`` and return them as they are stored (``stage``).""" names = [name.split("\0")[0] for name in rows.column_names] # nul rows = rows.rename_columns(names) + for column in rows.columns: + for chunk in column.chunks: + _check_list_child_offsets(chunk) for i, field in enumerate(rows.schema): # nul, at every depth if _needs_decoding(field.type): # Stored as its values (``types``): decoded first, so its names are cut. diff --git a/tests/test_databases/test_fake_spiral_sdk.py b/tests/test_databases/test_fake_spiral_sdk.py index 0e9131d9a..7f2105f85 100644 --- a/tests/test_databases/test_fake_spiral_sdk.py +++ b/tests/test_databases/test_fake_spiral_sdk.py @@ -11,6 +11,26 @@ from tests.test_databases import fake_spiral_sdk as fake +@pytest.mark.parametrize("kind", [pa.large_string(), pa.large_binary()]) +def test_keyed_append_refuses_a_sliced_list_child( + tmp_path: Path, kind: pa.DataType +) -> None: + 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) + rows = pa.table({"k": [1, 2], "lists": lists}) + with fake.install(tmp_path): + table = ( + fake.FakeClient() + .project("p") + .create_keyed_table( + "d", "lists", pa.schema([pa.field("k", pa.int64(), nullable=False)]) + ) + ) + with pytest.raises(fake.SpiralError, match="sliced list child"): + _ = table.append(rows) + + def test_a_run_end_encoded_slice_expands_only_its_own_rows() -> None: """Every slice decodes to its own values, and a slice of one row of a run of two billion values builds one index, not one per value of the run.""" diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index 106f037e3..bd475edef 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -2042,6 +2042,51 @@ def read_after_replacing(_schema: pa.Schema) -> None: assert got is not None and _record_ids(got) == [b"r0"] +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("order", ["forward", "reversed"]) +def test_append_copies_sliced_empty_string_and_binary_list_children( + monkeypatch: pytest.MonkeyPatch, order: str +) -> None: + base = rows(["unused", "r1", "r2", "after"]) + strings = pa.array( + [["prefix"], [], [], ["suffix"]], pa.large_list(pa.large_string()) + ) + blobs = pa.array( + [[b"prefix"], [], [], [b"suffix"]], pa.large_list(pa.large_binary()) + ) + nullable = pa.array([["prefix"], None, [], None], pa.large_list(pa.large_string())) + nested = pa.StructArray.from_arrays([blobs, nullable], names=["blobs", "optional"]) + given = ( + base.append_column("texts", strings).append_column("nested", nested).slice(1, 2) + ) + if order == "reversed": + given = _reordered(given) + + append = fake.FakeKeyedTable.append + written: list[pa.Table] = [] + + def captured(table: fake.FakeKeyedTable, batch: pa.Table) -> fake.FakeKeyedTable: + if "__record_id" in batch.column_names: + written.append(batch) + return append(table, batch) + + monkeypatch.setattr(fake.FakeKeyedTable, "append", captured) + connector = writable_connector() + tables = tables_of(connector) + # Exercise the store boundary with the slice intact. An Arrow database's + # multirow deduplication can copy the batch before forwarding it here. + tables.write(tables.table_name(RESULT), given) + assert len(written) == 1 + before = {buf.address for buf in given["__record_id"].chunks[0].buffers() if buf} + after = { + buf.address for buf in written[0]["__record_id"].chunks[0].buffers() if buf + } + assert not before & after + got = _get(ConnectorArrowDatabase(connector)) + assert got is not None + assert by_id(got.select(given.column_names)).equals(by_id(given)) + + # ------------------------------------------------- review of 6fb1b6e16 From 48aa8c87133259f58736f83f0e235f81cf9634b1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 19:36:45 -0800 Subject: [PATCH 10/46] fix(spiraldb): keep run lookup capabilities independent of database imports --- src/orcapod/contexts/stored.py | 2 +- .../databases/extension_aware_database.py | 6 ++---- src/orcapod/protocols/database_protocols.py | 17 --------------- src/orcapod/protocols/spiraldb_run.py | 21 +++++++++++++++++++ src/orcapod/side_effects.py | 2 +- 5 files changed, 25 insertions(+), 23 deletions(-) create mode 100644 src/orcapod/protocols/spiraldb_run.py diff --git a/src/orcapod/contexts/stored.py b/src/orcapod/contexts/stored.py index 100dd2cc2..d26f46c02 100644 --- a/src/orcapod/contexts/stored.py +++ b/src/orcapod/contexts/stored.py @@ -43,7 +43,7 @@ OrcapodDatabaseContentWarning, TableListingNotSupportedError, ) -from orcapod.protocols.database_protocols import SpiralDBRunLookupProtocol +from orcapod.protocols.spiraldb_run import SpiralDBRunLookupProtocol from orcapod.system_constants import ( OPERATOR_DB_SCHEMA_VERSION, PIPELINE_DB_SCHEMA_VERSION, diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index cb014c58d..979adb352 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -26,10 +26,8 @@ from typing import TYPE_CHECKING, Any, cast from orcapod.logical_types.database_hooks import register_discovered_logical_types -from orcapod.protocols.database_protocols import ( - ArrowDatabaseProtocol, - SpiralDBRunLookupProtocol, -) +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.protocols.spiraldb_run import SpiralDBRunLookupProtocol if TYPE_CHECKING: from contextlib import AbstractContextManager diff --git a/src/orcapod/protocols/database_protocols.py b/src/orcapod/protocols/database_protocols.py index 1a5c22740..b87eb12dc 100644 --- a/src/orcapod/protocols/database_protocols.py +++ b/src/orcapod/protocols/database_protocols.py @@ -11,23 +11,6 @@ from orcapod.databases._pending_commits import PendingCommit -@runtime_checkable -class SpiralDBRunLookupProtocol(Protocol): - """Optional lookup shortcuts for writable SpiralDB databases and their views.""" - - def spiral_records_match_context( - self, record_path: tuple[str, ...], current: str - ) -> bool: - """Whether recorded metadata and pending rows rule out another data context.""" - ... - - def spiral_completion_lookup( - self, record_path: tuple[str, ...] - ) -> Callable[[bytes], bool] | None: - """Return an execution-scoped lookup for a writable SpiralDB invocation log.""" - ... - - @runtime_checkable class ArrowDatabaseProtocol(Protocol): """Internal Arrow store interface, including ordered function commits. diff --git a/src/orcapod/protocols/spiraldb_run.py b/src/orcapod/protocols/spiraldb_run.py new file mode 100644 index 000000000..b538af631 --- /dev/null +++ b/src/orcapod/protocols/spiraldb_run.py @@ -0,0 +1,21 @@ +"""Lookup capabilities of writable SpiralDB stores and their database views.""" + +from collections.abc import Callable +from typing import Protocol, runtime_checkable + + +@runtime_checkable +class SpiralDBRunLookupProtocol(Protocol): + """Optional metadata and completion lookups for a run.""" + + def spiral_records_match_context( + self, record_path: tuple[str, ...], current: str + ) -> bool: + """Whether recorded metadata and pending rows rule out another data context.""" + ... + + def spiral_completion_lookup( + self, record_path: tuple[str, ...] + ) -> Callable[[bytes], bool] | None: + """Return an execution-scoped lookup for a writable SpiralDB invocation log.""" + ... diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 543fce0e7..1c1beb521 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -64,7 +64,7 @@ TRACKING_DB_SCHEMA_VERSION, constants, ) -from orcapod.protocols.database_protocols import SpiralDBRunLookupProtocol +from orcapod.protocols.spiraldb_run import SpiralDBRunLookupProtocol from orcapod.types import ColumnConfig from orcapod.utils import arrow_utils from orcapod.utils.database_errors import flush_best_effort From 1c7e530366c0d4c9b4d962a61d4ebe9267c2dc32 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 21:14:56 -0800 Subject: [PATCH 11/46] fix(spiraldb): keep run-shared state coherent and node batching to SpiralDB stores Address the independent review of PR 698: - Fill the lease-wide key index from a snapshot taken under the lease's lock, never from an operation snapshot opened before another connector's append (an ambiguous append can no longer let a second connector overwrite a key). - Answer side-effect completion lookups from the lease-wide key index, which every committed append updates, so a receipt committed during the run is seen. - Keep the run's dataset listing on the lease, under its lock, instead of a context variable, so writes from plain threads update it. - Batch a node run's commits only when every database the node commits to is writable SpiralDB or in-memory, with at least one SpiralDB (one rule, node_run.batches_node_commits); the ephemeral result store counts. - After a failed batched result append in a node run, write the batch's rows one at a time in order up to the first failing row, so the stored prefix equals the per-row cadence's. - Docs, changelog fragment and the stale-table docstring follow. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1502.md | 9 +- docs/concepts/spiraldb-database.md | 15 + src/orcapod/contexts/stored.py | 7 +- src/orcapod/core/nodes/function_node.py | 49 ++- src/orcapod/databases/_pending_commits.py | 43 ++- .../databases/connector_arrow_database.py | 215 ++++++++++--- .../databases/extension_aware_database.py | 16 +- src/orcapod/databases/spiraldb_connector.py | 1 - src/orcapod/databases/spiraldb_tables.py | 230 ++++++++++---- src/orcapod/databases/spiraldb_write_scope.py | 5 +- src/orcapod/pipeline/node_run.py | 63 +++- src/orcapod/protocols/spiraldb_run.py | 14 +- .../test_spiraldb_writable_mode.py | 151 ++++++++- .../test_spiraldb_writable_runs.py | 295 +++++++++++++++++- 14 files changed, 956 insertions(+), 157 deletions(-) diff --git a/changelog.d/ITL-1502.md b/changelog.d/ITL-1502.md index b7f072ec8..8d7e049e3 100644 --- a/changelog.d/ITL-1502.md +++ b/changelog.d/ITL-1502.md @@ -1,8 +1,13 @@ ### Changed - Writable SpiralDB jobs reuse lease verification, stored-key and completion - lookups, and stale-table discovery across a run. Connections reuse resolved - table IDs, and node runs batch their function-result writes. + lookups, and stale-table discovery across a run, shared by every connector and + thread of the run. Connections reuse resolved table IDs. +- A job node's `run()` commits a function node's writes every 100 rows and at its + end when every database the node commits to is a writable SpiralDB database or an + `InMemoryArrowDatabase`, at least one of them SpiralDB; any other store keeps the + per-row commits. A failed batched result append is retried one row at a time, in + order, so the results before the failing row stay stored. ### Fixed diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index caf336e7b..f0589b334 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -78,9 +78,24 @@ whose client reaches the same service share it, whether their address was left t 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. +A job node's `run()` commits a function node's writes in batches (every 100 rows and +at the node's end, as `job.run()` does) when every database the node commits to (its +pipeline database, its result database, and its ephemeral result database when its +results are ephemeral) is a writable SpiralDB database or an `InMemoryArrowDatabase`, +and at least one is a writable SpiralDB database. Any other store among them (Delta, +SQL, PostgreSQL) keeps the node committing after every row, so another reader of that +store sees each result as soon as it is stored. If a batched result append fails, its +rows are appended one at a time, in order, up to the first that fails: the results +before that row and their pipeline records stay stored, as a node committing after +every row keeps them, and the run stops with that row's error. + A connection resolves a table by name and checks its recorded path when it finds the table. Later operations use the resolved table ID for that connection. diff --git a/src/orcapod/contexts/stored.py b/src/orcapod/contexts/stored.py index d26f46c02..78814ce1a 100644 --- a/src/orcapod/contexts/stored.py +++ b/src/orcapod/contexts/stored.py @@ -467,8 +467,11 @@ def find_stale_tables( Args: database: The database the paths belong to. current: The table's current path and the current data context key, to also - look for rows of another data context in the current table (this reads - the whole table). ``None`` skips that search. + look for rows of another data context in the current table. This reads + the whole table, except on a writable SpiralDB database + whose table records the current data context and whose pending rows hold + it too (``spiral_records_match_context``): its metadata answers, and no + row is read. ``None`` skips that search. name_path: The beginning of the table's path up to the name of its function or pod, the part that holds no hash. ``None`` skips the listing. result_revision: For a result cache, the revision of its data function type's diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 33c9c9fd2..2a0da70c5 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -122,6 +122,7 @@ ) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.hashing_protocols import IdentityWalkProtocol +from orcapod.protocols.spiraldb_run import InOrderResultFlushProtocol from orcapod.protocols.observability_protocols import ( DataExecutionLoggerProtocol, ExecutionObserverProtocol, @@ -1536,6 +1537,7 @@ def __init__( self._row_count_checked: bool = False # Batched commits, set only while PipelineJob.run runs the node (ITL-919). self._commit_every_rows: int | None = None + self._results_in_order = False self._rows_since_commit = 0 self._commit_failed = False @@ -1979,6 +1981,7 @@ def from_descriptor( node._expected_row_count = expected_row_count node._row_count_checked = False node._commit_every_rows = None + node._results_in_order = False node._rows_since_commit = 0 node._commit_failed = False @@ -2425,19 +2428,41 @@ def _require_pipeline_database(self) -> ArrowDatabaseProtocol: # Batched commits (ITL-919) # ------------------------------------------------------------------ + def _committed_databases(self) -> list[ArrowDatabaseProtocol]: + """The databases this node's commits write: its pipeline database, its result + database, and its ephemeral result database when its results are ephemeral.""" + databases: list[ArrowDatabaseProtocol] = [] + if self._pipeline_database is not None: + databases.append(self._pipeline_database) + pod = self._cached_function_pod + if isinstance(pod, CachedFunctionPod): + databases.append(pod.result_database) + ephemeral = self._ephemeral_cached_pod + if self._node_config.is_result_ephemeral and isinstance( + ephemeral, CachedFunctionPod + ): + databases.append(ephemeral.result_database) + return databases + @contextlib.contextmanager - def _batched_commits(self, rows_per_commit: int) -> Iterator[None]: + def _batched_commits( + self, rows_per_commit: int, *, results_in_order: bool = False + ) -> Iterator[None]: """Commit this node's writes every ``rows_per_commit`` rows inside the block. ``PipelineJob.run`` runs each function node inside this block. Its result caches stop committing after every stored result, and the node commits its pending writes (ephemeral results, then its result table, then the pipeline - records) every ``rows_per_commit`` rows and at its end. A node run writing - to SpiralDB uses the same block. Outside it every result is committed as - it is stored. + records) every ``rows_per_commit`` rows and at its end. A node run uses the + same block when ``node_run.batches_node_commits`` says so. Outside it every + result is committed as it is stored. Args: rows_per_commit: How many processed rows' writes one commit holds. + results_in_order: Commit a failed result batch's rows one at a time, in + order, up to the first that fails, where the result store can + (``InOrderResultFlushProtocol``): the results before the failing + row, and their records, stay as a node committing every row keeps. Yields: Nothing; the node commits in batches while the block runs. @@ -2448,6 +2473,7 @@ def _batched_commits(self, rows_per_commit: int) -> Iterator[None]: if isinstance(pod, CachedFunctionPod) ] self._commit_every_rows = rows_per_commit + self._results_in_order = results_in_order self._rows_since_commit = 0 self._commit_failed = False for pod in pods: @@ -2456,6 +2482,7 @@ def _batched_commits(self, rows_per_commit: int) -> Iterator[None]: yield finally: self._commit_every_rows = None + self._results_in_order = False for pod in pods: pod.set_auto_flush(True) @@ -2469,7 +2496,15 @@ def _flush_node_table( ) -> None: """Flush one batch and withdraw dependent records if a result write fails.""" try: - if result: + if ( + result + and self._results_in_order + and isinstance(database, InOrderResultFlushProtocol) + ): + database.flush_result_batch_in_order( + path, publish_records=publish_records + ) + elif result: database.flush_result_batch(path, publish_records=publish_records) else: database.flush_batch(path) @@ -4507,7 +4542,7 @@ def _run_alone( """ from dataclasses import replace - from orcapod.pipeline.node_run import batch_spiral_node_commits, commit_run + from orcapod.pipeline.node_run import batch_node_commits, commit_run from orcapod.pipeline.restrictions import restrictions_in_force from orcapod.pipeline.run_summary import RunCountingObserver, RunSummary from orcapod.utils.database_errors import flush_best_effort @@ -4526,7 +4561,7 @@ def _run_alone( if database is not None ] try: - with batch_spiral_node_commits([self], databases, load_only=load_only): + with batch_node_commits([self], load_only=load_only): _ = self.execute( self._input_stream, observer=counter, load_only=load_only ) diff --git a/src/orcapod/databases/_pending_commits.py b/src/orcapod/databases/_pending_commits.py index 0e82b8a8e..29e1ad05d 100644 --- a/src/orcapod/databases/_pending_commits.py +++ b/src/orcapod/databases/_pending_commits.py @@ -46,6 +46,7 @@ def __init__( self._ids = ids self._on_empty = on_empty self._attempts: dict[str, PendingCommit] = {} + self._row_attempts: dict[str, dict[bytes, PendingCommit]] = {} self._guards: dict[str, dict[bytes, PendingCommit]] = {} self._schema_checks: dict[str, Callable[[pa.Schema], None]] = {} self._receipts: dict[str, set[bytes]] = {} @@ -114,18 +115,52 @@ def has_pending(self, key: str, ids: set[bytes]) -> bool: """Return whether any of the given IDs are still queued.""" return not ids.isdisjoint(self._ids.get(key, ())) - def attempt(self, key: str) -> PendingCommit: - """Get the attempt shared by all rows currently pending for a table.""" + def attempt(self, key: str, record_id: bytes | None = None) -> PendingCommit: + """Get the attempt to commit a table's pending rows. + + Args: + key: The table's record key. + record_id: A pending row whose own commit the attempt follows: a database + that can commit a batch's rows one at a time (``finish`` with ``ids``) + gives each row its own attempt. ``None`` for the attempt shared by + every row pending for the table. + """ + if record_id is not None: + rows = self._row_attempts.setdefault(key, {}) + attempt = rows.get(record_id) + if attempt is None: + attempt = rows[record_id] = PendingCommit() + return attempt attempt = self._attempts.get(key) if attempt is None: attempt = self._attempts[key] = PendingCommit() return attempt - def finish(self, key: str, *, committed: bool) -> None: - """Resolve an attempt before another flush can consider its dependents.""" + def finish( + self, key: str, *, committed: bool, ids: Set[bytes] | None = None + ) -> None: + """Resolve an attempt before another flush can consider its dependents. + + Args: + key: The table's record key. + committed: Whether the rows committed. + ids: Resolve only these rows' own attempts (``attempt`` with a record id); + ``None`` resolves every attempt of the table. + """ + rows = self._row_attempts.get(key, {}) + if ids is not None: + for record_id in ids: + row = rows.pop(record_id, None) + if row is not None: + row.finish(committed=committed) + if not rows: + _ = self._row_attempts.pop(key, None) + return attempt = self._attempts.pop(key, None) if attempt is not None: attempt.finish(committed=committed) + for row in self._row_attempts.pop(key, {}).values(): + row.finish(committed=committed) @contextmanager def guard( diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index dd90a89b2..ff52e6065 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1171,7 +1171,9 @@ def pending_result( """Return a commit dependency for a buffered result, or verify it is stored.""" key = self._get_record_key(record_path) if record_id in self._pending_record_ids.get(key, ()): - return self._pending_commits.attempt(key) + # Each result its own attempt: ``flush_result_batch_in_order`` can commit + # a batch's results one at a time and release only their records. + return self._pending_commits.attempt(key, record_id) if self.get_record_by_id(record_path, record_id) is None: raise ValueError("The referenced result is neither stored nor pending.") return None @@ -1219,8 +1221,39 @@ 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)) - def _flush_by_key(self, record_key: str) -> None: - """Commit the ready records at a key shared by all views.""" + @_one_spiral_operation + def flush_result_batch_in_order( + self, record_path: tuple[str, ...], *, publish_records: bool + ) -> None: + """Commit a result table's ready records; if the batch fails, commit its rows + one at a time, in order, up to the first that fails. + + A node run that batches its commits (``node_run.batch_node_commits``) uses + this for its result tables, so a permanent failure keeps the results before + the failing row durable, and their records publishable, as a node committing + after every row does. The failing row's and every later row's records are + withdrawn. A write of one row reads the keys the table holds again, so a + row the failed batch stored after all is never written twice. + + Args: + record_path: The result table's path. + publish_records: As for ``flush_result_batch`` (this store publishes + every committed result). + + Raises: + Exception: The first failing row's error, with the batch's error as a + note; nothing when every row commits on its own. + """ + self._flush_by_key(self._get_record_key(record_path), in_order=True) + + def _flush_by_key(self, record_key: str, *, in_order: bool = False) -> None: + """Commit the ready records at a key shared by all views. + + Args: + record_key: The table's record key. + in_order: After a failed write of several rows, write them one at a time + (``flush_result_batch_in_order``). + """ queued_schema = self._schema_from_record_key(record_key) if self._sql_store is not None: active_schema = self._sql_store.get_current_store_schema() @@ -1234,53 +1267,115 @@ def _flush_by_key(self, record_key: str) -> None: if ready is None: return pending, ids = ready - skip_duplicates = self._pending_skip_existing.get(record_key, False) try: - record_path = self._record_path_from_key(record_key) - table_name = self._path_to_table_name(record_path) - self._require_table_name(table_name) - if (tables := self._spiral) is not None: - transaction = nullcontext((None, tables.has_table(table_name))) - elif self._sql_store is None: - transaction = nullcontext( - (None, table_name in self._connector.get_table_names()) - ) - else: - assert queued_schema is not None - transaction = self._sql_store.store_table_transaction( - table_name, - store_table_path_json(record_path).decode(), - schema=queued_schema, - ) - with transaction as (schema, table_exists): - self._write_ready_batch( - record_key, - table_name, - pending, - skip_duplicates, - table_exists, - schema, - ) + self._write_pending(record_key, pending, queued_schema) + except Exception as batch_error: + if not in_order or pending.num_rows < 2: + self._pending_commits.fail_batch(record_key, pending, ids) + raise + # Raises, having failed the rows from the first failing one on. + self._write_rows_in_order( + record_key, pending, ids, queued_schema, batch_error + ) + self._committed(record_key, ids) except BaseException: self._pending_commits.fail_batch(record_key, pending, ids) raise else: - self._pending_commits.forget(record_key, ids) - self._pending_commits.finish(record_key, committed=True) - if self._receipt_peers is not None: - with _receipt_queue_lock: - peers = tuple(self._receipt_peers.items()) - for peer, connector in peers: - if peer is not self._pending_commits: - peer.note_peer_receipts( - record_key, - ids, - same_connection=connector is self._connector, - ) + self._committed(record_key, ids) finally: if record_key not in self._pending_batches: self._discard_pending_state(record_key) + def _committed(self, record_key: str, ids: set[bytes]) -> None: + """Release committed rows' dependents and tell the receipt peers.""" + self._pending_commits.forget(record_key, ids) + self._pending_commits.finish(record_key, committed=True) + if self._receipt_peers is not None: + with _receipt_queue_lock: + peers = tuple(self._receipt_peers.items()) + for peer, connector in peers: + if peer is not self._pending_commits: + peer.note_peer_receipts( + record_key, + ids, + same_connection=connector is self._connector, + ) + + def _write_pending( + self, record_key: str, pending: pa.Table, queued_schema: str | None + ) -> None: + """Write rows taken from a table's queue, in the table's transaction.""" + skip_duplicates = self._pending_skip_existing.get(record_key, False) + record_path = self._record_path_from_key(record_key) + table_name = self._path_to_table_name(record_path) + self._require_table_name(table_name) + if (tables := self._spiral) is not None: + transaction = nullcontext((None, tables.has_table(table_name))) + elif self._sql_store is None: + transaction = nullcontext( + (None, table_name in self._connector.get_table_names()) + ) + else: + assert queued_schema is not None + transaction = self._sql_store.store_table_transaction( + table_name, + store_table_path_json(record_path).decode(), + schema=queued_schema, + ) + with transaction as (schema, table_exists): + self._write_ready_batch( + record_key, + table_name, + pending, + skip_duplicates, + table_exists, + schema, + ) + + def _write_rows_in_order( + self, + record_key: str, + pending: pa.Table, + ids: set[bytes], + queued_schema: str | None, + batch_error: Exception, + ) -> None: + """Write a failed batch's rows one at a time, in order, up to the first that + fails (``flush_result_batch_in_order``); release each committed row's records. + + Args: + record_key: The table's record key. + pending: The rows the failed write held. + ids: Their record ids. + queued_schema: The store schema they were queued under. + batch_error: The failed write's error. + + Raises: + BaseException: The first failing row's error, noted with ``batch_error``; + 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()) + for position, record_id in enumerate(row_ids): + try: + self._write_pending( + 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]), + ) + raise + self._pending_commits.forget(record_key, {record_id}) + self._pending_commits.finish(record_key, committed=True, ids={record_id}) + def _write_ready_batch( self, record_key: str, @@ -1423,8 +1518,12 @@ def spiral_completion_lookup( ) -> Callable[[bytes], bool] | None: """Create a completion lookup for one execution of a side-effect node. - Keep stored IDs from the first lookup that needs them and consult the live - queue for each lookup. Receipts added during delivery enter that queue. + 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 + 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 + first lookup that needs them. Args: record_path: The invocation log's path. @@ -1436,25 +1535,37 @@ def spiral_completion_lookup( if tables is None: return None record_key = self._get_record_key(record_path) + full_path = self._path_prefix + record_path stored_ids: set[bytes] | None = None - def completed(record_id: bytes) -> bool: + def committed(record_id: bytes) -> bool: nonlocal stored_ids - if record_id in self._pending_record_ids.get(record_key, ()): - return True + table_name = self._path_to_table_name(full_path) + self._require_table_name(table_name) + try: + held = tables.holds_record_id(table_name, record_id) + except (OrcapodDatabaseError, SpiralTableCollisionError): + raise + except Exception as exc: + raise OrcapodDatabaseReadError(table_name, full_path) from exc + if held is not None: + return held if stored_ids is None: with tables.operation(): - committed = self._get_committed_table(record_path, schema=None) + table = self._get_committed_table(record_path, schema=None) stored_ids = ( set() - if committed is None + if table is None else set( - cast( - "list[bytes]", committed[self.RECORD_ID_COLUMN].to_pylist() - ) + cast("list[bytes]", table[self.RECORD_ID_COLUMN].to_pylist()) ) ) - if record_id in stored_ids: + return record_id in stored_ids + + def completed(record_id: bytes) -> bool: + if record_id in self._pending_record_ids.get(record_key, ()): + return True + if committed(record_id): report_records(record_key, added=set(), durable={record_id}) return True return False diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index 979adb352..380c1eaac 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -27,7 +27,10 @@ from orcapod.logical_types.database_hooks import register_discovered_logical_types from orcapod.protocols.database_protocols import ArrowDatabaseProtocol -from orcapod.protocols.spiraldb_run import SpiralDBRunLookupProtocol +from orcapod.protocols.spiraldb_run import ( + InOrderResultFlushProtocol, + SpiralDBRunLookupProtocol, +) if TYPE_CHECKING: from contextlib import AbstractContextManager @@ -239,6 +242,17 @@ def flush_result_batch( """Flush the wrapped result batch.""" self._db.flush_result_batch(record_path, publish_records=publish_records) + def flush_result_batch_in_order( + self, record_path: tuple[str, ...], *, publish_records: bool + ) -> None: + """Flush the wrapped result batch in order when the wrapped store can.""" + if isinstance(self._db, InOrderResultFlushProtocol): + self._db.flush_result_batch_in_order( + record_path, publish_records=publish_records + ) + else: + self._db.flush_result_batch(record_path, publish_records=publish_records) + def pending_result( self, record_path: tuple[str, ...], record_id: bytes ) -> PendingCommit | None: diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index be1ce327f..0a40bf185 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -1118,7 +1118,6 @@ def _new_tables(self) -> SpiralDBTables: ), lambda: _list_keyed_tables(client, project_id, dataset), lambda doing: _service_call(f"{doing} of {project_id}/{dataset}", health), - lambda: _service_address(client), ) def _require_open(self) -> None: diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index 5f40d5a3b..b725e53e4 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -40,7 +40,6 @@ 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 @@ -77,28 +76,37 @@ class _Catalog: records: dict[str, tuple[identity.TableRecord, str]] = field(default_factory=dict) -_run_catalogs: ContextVar[dict[tuple[str, str, str], _Catalog] | None] = ContextVar( - "spiral_run_catalogs", default=None -) - - -@contextmanager -def run_catalog() -> Iterator[None]: - """Share each SpiralDB dataset's first listing for a pipeline run.""" - token = _run_catalogs.set({}) - try: - yield - finally: - _run_catalogs.reset(token) - - @dataclass class WriterLease: - """A run's verification and key index, shared by its dataset's connectors.""" + """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. + + 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. + + Attributes: + verify: Verifies the lease on its first use. + 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. + 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; ``None`` until then. + 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. + """ verify: Callable[[], None] lock: threading.RLock = field(default_factory=threading.RLock) keys_by_table: dict[str, set[bytes]] = field(default_factory=dict) + table_ids: dict[str, str | None] = field(default_factory=dict) + catalog: _Catalog | None = None + commits: int = 0 def __call__(self) -> None: """Verify the writer lease on first use.""" @@ -219,7 +227,6 @@ class SpiralDBTables: create_table: Creates a keyed table in the dataset, by name and key schema. 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. - service_address: Returns the resolved URL of the dataset's service. """ def __init__( @@ -232,7 +239,6 @@ def __init__( create_table: Callable[[str, pa.Schema], object], list_tables: Callable[[], dict[str, str]], service_call: Callable[[str], AbstractContextManager[None]], - service_address: Callable[[], str], ) -> None: self._sdk: Any = sdk # pyright: ignore[reportExplicitAny] self._project_id: str = project_id @@ -242,7 +248,6 @@ def __init__( self._create_table: Callable[[str, pa.Schema], object] = create_table self._list_tables: Callable[[], dict[str, str]] = list_tables self._service_call: Callable[[str], AbstractContextManager[None]] = service_call - self._service_address: Callable[[], str] = service_address 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 @@ -400,6 +405,7 @@ def operation(self) -> Iterator[None]: depth = cast(int, getattr(self._now, "depth", 0)) if depth == 0: self._now.judged = {} + self._now.commits = {} self._now.depth = depth + 1 try: yield @@ -407,6 +413,7 @@ def operation(self) -> Iterator[None]: self._now.depth = depth if depth == 0: self._now.judged = None + self._now.commits = None @contextmanager def outside_operation(self) -> Iterator[None]: @@ -415,11 +422,13 @@ def outside_operation(self) -> Iterator[None]: judged = self._judged_now() self._now.depth = 0 self._now.judged = None + self._now.commits = None try: yield finally: self._now.depth = depth self._now.judged = None if judged is None else {} + self._now.commits = None if judged is None else {} def _judged_now(self) -> dict[str, _Judgment] | None: """What each name was judged in this thread's operation; ``None`` outside one.""" @@ -432,6 +441,31 @@ def _forget_opened(self, table_name: str) -> None: judged = self._judged_now() if judged is not None: _ = judged.pop(table_name, None) + commits = self._commits_now() + if commits is not 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.""" + 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). + + Args: + table_name: A name this operation judged. + """ + lease = self._lease_check + commits = self._commits_now() + opened_at = None if commits is None else commits.get(table_name) + return ( + lease is not None + and opened_at is not None + and opened_at % 2 == 0 + and opened_at == lease.commits + ) # ── finding a table ────────────────────────────────────────────────────── @@ -469,10 +503,16 @@ def _judgment(self, table_name: str) -> _Judgment: judged = self._judged_now() if judged is not None and table_name in judged: return judged[table_name] + lease = self._lease_check + # Read before the snapshot is opened (``_snapshot_is_current``). + commits_before = None if lease is None else lease.commits with self._about(table_name): judgment = self._judge_table(table_name, self._path_of(table_name)) if judged is not None: judged[table_name] = judgment + commits = self._commits_now() + if commits is not None: + commits[table_name] = commits_before return judgment def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Judgment: @@ -565,14 +605,35 @@ def table_paths( """ start = identity.spiral_table_name_prefix(prefix) found = {p for p in pending if p[: len(prefix)] == prefix} - catalogs = _run_catalogs.get() - if catalogs is None: - catalog = _Catalog(self._list_dataset()) - else: - key = self._catalog_key() - catalog = catalogs.get(key) - if catalog is None: - catalog = catalogs[key] = _Catalog(self._list_dataset()) + lease = self._lease_check + with lease.lock if lease is not None else nullcontext(): + if lease is None: + catalog = _Catalog(self._list_dataset()) + else: + # The run's one listing, kept with the lease: 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 + self._collect_paths(catalog, start, prefix, found) + return sorted(found) + + def _collect_paths( + self, + catalog: _Catalog, + start: str, + prefix: tuple[str, ...], + found: set[tuple[str, ...]], + ) -> None: + """Add to ``found`` the recorded paths of the catalog's tables under ``prefix`` + (``table_paths``). + + Args: + catalog: The listing to read. + start: The table name prefix of ``prefix``. + prefix: The full path prefix. + found: The paths found so far. + """ for table_id, table_name in tuple(catalog.names.items()): if not table_name.startswith(start): continue @@ -588,10 +649,6 @@ def table_paths( else: last = identity.other_format_last_component(record, table_format) found.add((*record.path[:-1], last)) - return sorted(found) - - def _catalog_key(self) -> tuple[str, str, str]: - return self._service_address(), self._project_id, self._dataset def _list_dataset(self) -> dict[str, str]: with self._service_call("list the database tables"): @@ -754,36 +811,100 @@ def existing_record_ids( lease.lock if lease 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: return set() - return self._held_ids(opened.table, ids) + # A snapshot this operation opened earlier can predate another + # connector's append; one opened now, under the lock, cannot. + fresh = not reused or self._snapshot_is_current(table_name) + return self._held_ids(opened.table, ids, fresh=fresh) + + 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. + + The index is updated by every append any connector of the lease 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 + holds rows. + + Args: + table_name: A name ``table_name`` returned. + record_id: A record id. + + Returns: + Whether it is held, or ``None`` without a lease. + """ + lease = self._lease_check + if lease is None: + return None + with lease.lock, self._about(table_name): + if table_name not in lease.table_ids: + self._forget_opened(table_name) + opened = self._judge(table_name) + if opened is None: + lease.table_ids[table_name] = None + return False + lease.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] + 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 - def _held_ids(self, table: _KeyedTable, ids: Collection[bytes]) -> set[bytes]: - """The ids among ``ids`` a snapshot holds (``existing_record_ids``). + 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. 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. Returns: The ids it holds. """ lease = self._lease_check + if lease is None: + return self._scan_keys(table).intersection(ids) table_id = str(table.resource_id) - held = None if lease is None else lease.keys_by_table.get(table_id) - if held is None: - with self._service_call("read the keys of a database table"): - stored = table.scan([codec.KEY_COLUMN]).to_table() - held = set( - cast( - "list[bytes]", - stored.column(codec.KEY_COLUMN).cast(pa.large_binary()).to_pylist(), - ) - ) - if lease is not None: + 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) + return held.intersection(ids) + + 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(), + ) + ) # ── writing ────────────────────────────────────────────────────────────── @@ -1012,7 +1133,7 @@ def _write( f"the table stores its columns under other names ({difference}): " + "an append would write columns its manifest does not record" ) - held = self._held_ids(opened.table, _ids(records)) + 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 @@ -1064,7 +1185,7 @@ def _write_first( recorded = self._require_same_manifest(table, path, manifest) _require_data_context(recorded, context) # Another writer may have written these keys meanwhile. - held = self._held_ids(table, _ids(records)) + held = self._held_ids(table, _ids(records), fresh=True) encoded = _encoded(_without_ids(records, held)) self._ids_by_name[table_name] = recorded.table_id if encoded.num_rows > 0: @@ -1092,6 +1213,7 @@ def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: # 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 try: with self._service_call("write a database table"): _ = table.append(batch) @@ -1099,14 +1221,14 @@ def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: # 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) 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 - catalogs = _run_catalogs.get() - if ( - catalogs is not None - and (catalog := catalogs.get(self._catalog_key())) is not None - ): + if (catalog := lease.catalog) is not None: _ = catalog.names.setdefault( found.table_id, identity.spiral_table_name(found.record.path) ) diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index d622161c3..201a01807 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -23,7 +23,7 @@ from orcapod.databases import spiraldb_lease from orcapod.databases.spiraldb_connector import require_same_process -from orcapod.databases.spiraldb_tables import WriterLease, run_catalog +from orcapod.databases.spiraldb_tables import WriterLease if TYPE_CHECKING: from orcapod.databases.spiraldb_connector import SpiralDBConnector @@ -115,8 +115,7 @@ def register( _release_all(held, error) raise try: - with run_catalog(): - yield + yield except BaseException as error: _release_all(held, error) raise diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 37824aac4..f69656681 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -629,25 +629,62 @@ def commit_run(databases: Sequence[ArrowDatabaseProtocol], ran: Sequence[Any]) - raise -@contextlib.contextmanager -def batch_spiral_node_commits( - nodes: Sequence[Any], databases: Sequence[ArrowDatabaseProtocol], *, load_only: bool -) -> Iterator[None]: - """Use the job's commit cadence when a node run writes to SpiralDB.""" +def batches_node_commits(node: Any) -> bool: + """Whether a node run (a job node's ``run()``, outside ``job.run()``) commits this + node's writes in batches; the one place this is decided. + + A function job node batches when every database its commits write (its pipeline + database, its result database, and its ephemeral result database when its results + are ephemeral) is either a writable SpiralDB database or an + ``InMemoryArrowDatabase``, and at least one is a writable SpiralDB database. Each + SpiralDB append is a service request, and an in-memory store has no reader outside + the process. Every other node keeps committing after every row: a Delta, SQL, + PostgreSQL or read-only store anywhere among its databases keeps its rows visible + to another reader as each is stored. + + Args: + node: A node the run executes. + + Returns: + Whether to run it inside ``FunctionJobNode._batched_commits``. + """ from orcapod.core.nodes.function_node import FunctionJobNode + from orcapod.databases.extension_aware_database import unwrap_database_views + from orcapod.databases.in_memory_databases import InMemoryArrowDatabase from orcapod.databases.spiraldb_writable_registry import any_writable_connector from orcapod.databases.spiraldb_write_scope import writable_connectors + if not isinstance(node, FunctionJobNode) or not any_writable_connector(): + return False + databases = node._committed_databases() # pyright: ignore[reportPrivateUsage] # the run sets the commit cadence + spiral = [bool(writable_connectors([database])) for database in databases] + return any(spiral) and all( + is_spiral or isinstance(unwrap_database_views(database), InMemoryArrowDatabase) + for database, is_spiral in zip(databases, spiral) + ) + + +@contextlib.contextmanager +def batch_node_commits(nodes: Sequence[Any], *, load_only: bool) -> Iterator[None]: + """Commit in batches the writes of the nodes ``batches_node_commits`` names. + + A failed result batch is committed one row at a time, in order, up to the + first failing row, so a permanent failure keeps the results and records a node + committing every row keeps (``FunctionJobNode._batched_commits``). + + Args: + nodes: The nodes the run executes. + load_only: Whether the run is load-only: it writes nothing, so nothing is + batched. + """ with contextlib.ExitStack() as stack: - if ( - not load_only - and any_writable_connector() - and writable_connectors(databases) - ): + if not load_only: for node in nodes: - if isinstance(node, FunctionJobNode): + if batches_node_commits(node): stack.enter_context( - node._batched_commits(DEFAULT_COMMIT_EVERY_ROWS) # pyright: ignore[reportPrivateUsage] # the run sets the commit cadence + node._batched_commits( # pyright: ignore[reportPrivateUsage] # the run sets the commit cadence + DEFAULT_COMMIT_EVERY_ROWS, results_in_order=True + ) ) yield @@ -714,7 +751,7 @@ def visit(node: Any) -> None: databases = _databases(plan.to_run) counter = RunCountingObserver() try: - with batch_spiral_node_commits(plan.to_run, databases, load_only=load_only): + with batch_node_commits(plan.to_run, load_only=load_only): _ = SyncPipelineOrchestrator().run( plan.dag, observer=counter, load_only=load_only, held=plan.held ) diff --git a/src/orcapod/protocols/spiraldb_run.py b/src/orcapod/protocols/spiraldb_run.py index b538af631..a69ff0e78 100644 --- a/src/orcapod/protocols/spiraldb_run.py +++ b/src/orcapod/protocols/spiraldb_run.py @@ -1,4 +1,4 @@ -"""Lookup capabilities of writable SpiralDB stores and their database views.""" +"""Run capabilities of writable SpiralDB stores and their database views.""" from collections.abc import Callable from typing import Protocol, runtime_checkable @@ -19,3 +19,15 @@ def spiral_completion_lookup( ) -> Callable[[bytes], bool] | None: """Return an execution-scoped lookup for a writable SpiralDB invocation log.""" ... + + +@runtime_checkable +class InOrderResultFlushProtocol(Protocol): + """A store that can commit a failed result batch's rows one at a time.""" + + def flush_result_batch_in_order( + self, record_path: tuple[str, ...], *, publish_records: bool + ) -> None: + """Commit a result table's ready rows; after a failed batch, one row at a + time, in order, up to the first that fails.""" + ... diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index bd475edef..347a754e6 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -790,7 +790,9 @@ 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()).list_table_paths(("my_fn",)) + _ = ConnectorArrowDatabase(writable_connector(held=False)).list_table_paths( + ("my_fn",) + ) OTHER_FORMAT = "orcapod.spiral_database.v1" @@ -1030,8 +1032,10 @@ 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: - db = ConnectorArrowDatabase(writable_connector()) - db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + # 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"): + 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") _rename( @@ -1041,7 +1045,9 @@ 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()).list_table_paths(("my_fn",)) + _ = ConnectorArrowDatabase(writable_connector(held=False)).list_table_paths( + ("my_fn",) + ) # ------------------------------------------------------ concurrent first writers @@ -2498,3 +2504,140 @@ def recorded_meanwhile(*args: Any, **kwargs: Any) -> codec.TableManifest: kept = identity.read_table_identity_metadata(_table(name).get_metadata()) assert kept is not None and kept.data_context_key == other_context assert _table(name).scan().to_table().num_rows == 0 + + +# ----------------------------------------------- independent review of 48aa8c871 + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("order", ["forward", "reversed"]) +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. + + 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 + + first = ConnectorArrowDatabase(writable_connector(held=False)) + second = ConnectorArrowDatabase(writable_connector(held=False)) + 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: + result = append(table, batch) + if b"r1" in batch.column("__record_id").to_pylist(): + raise fake.SpiralError("the reply was lost") + return result + + def paused(tables: SpiralDBTables, name: str, ids: Any) -> set[bytes]: + if b"r1" in ids: + ready.set() + assert appended.wait(10) + return check(tables, name, ids) + + def peer() -> str: + given = rows(["r1"], offset=99) + try: + _add(second, _reordered(given) if order == "reversed" else given) + except ValueError: + return "refused" + return "accepted" + + with database_writes([first, second], owner="test"): + _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) + assert ready.wait(10) + try: + with monkeypatch.context() as lost: + lost.setattr(fake.FakeKeyedTable, "append", lost_reply) + with pytest.raises(Exception, match="reply was lost"): + first.flush() + finally: + appended.set() + _ = future.result() + second.flush() + got = _get(ConnectorArrowDatabase(writable_connector(held=False))) + assert got is not None + assert sorted(zip(_record_ids(got), got["a.b"].to_pylist())) == [ + (b"r0", 0), + (b"r1", 10), + ] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("revisions", [("rev0",), ("rev0", "rev2")]) +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.""" + from concurrent.futures import ThreadPoolExecutor + + first = ConnectorArrowDatabase(writable_connector(held=False)) + second = ConnectorArrowDatabase(writable_connector(held=False)) + 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"): + 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() + assert stale() == sorted(paths) + assert stale() == sorted(paths) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("order", ["forward", "reversed"]) +def test_sliced_nested_lists_are_written_and_read_through_the_database( + order: str, +) -> None: + """The public form of ``test_append_copies_sliced_empty_string_and_binary_list_children``: + the same logical values, a slice with empty and null lists of strings and binary + nested in lists and structs, added and read back through the database.""" + base = rows(["unused", "r1", "r2", "after"]) + strings = pa.array( + [["prefix"], [], [], ["suffix"]], pa.large_list(pa.large_string()) + ) + blobs = pa.array( + [[b"prefix"], [], [], [b"suffix"]], pa.large_list(pa.large_binary()) + ) + nullable = pa.array([["prefix"], None, [], None], pa.large_list(pa.large_string())) + nested = pa.StructArray.from_arrays([blobs, nullable], names=["blobs", "optional"]) + lists = pa.array( + [[["prefix"]], [[]], [], [["suffix"]]], + pa.large_list(pa.large_list(pa.large_string())), + ) + given = ( + base.append_column("texts", strings) + .append_column("nested", nested) + .append_column("lists", lists) + .slice(1, 2) + ) + if order == "reversed": + given = _reordered(given) + db = ConnectorArrowDatabase(writable_connector()) + _add(db, given, flush=True) + got = _get(ConnectorArrowDatabase(writable_connector())) + assert got is not None + assert by_id(got.select(given.column_names)).equals(by_id(given)) diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 94f63220b..7ec413ee3 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -15,7 +15,7 @@ import weakref from collections.abc import Callable, Iterator from pathlib import Path -from typing import Any +from typing import Any, cast from typing_extensions import override @@ -52,7 +52,12 @@ from orcapod.types import CacheMode, ColumnConfig from tests.test_databases import fake_spiral_sdk as fake -pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +pytestmark = [ + pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning"), + pytest.mark.filterwarnings( + "ignore::orcapod.core.data_tags.DataTagMaterializationWarning" + ), +] JOB = "itl1844" LAYOUTS = ("odb_v3", "pdb_v2", "rdb_v1", "sdb_v2", "tdb_v2") @@ -105,13 +110,18 @@ def _rows(n: int = 3) -> pa.Table: def _cached(cache: Any, table: pa.Table, *, order: str = "as given") -> CachedSource: + """The rows as a cached source, in one of the ``ORDERS`` arrangements: the + columns as given or reversed, the tag argument in the other order, or the tags + also data columns (data-tags).""" if order == "reversed": table = table.select(list(reversed(table.column_names))) return CachedSource( ArrowTableSource( table, - tag_columns=["unit", "trial"], - tag_only_columns=True, + tag_columns=["trial", "unit"] + if order == "tags reversed" + else ["unit", "trial"], + tag_only_columns=order != "data-tags", source_id="trials", record_id_columns=["unit", "trial"], ), @@ -119,6 +129,9 @@ def _cached(cache: Any, table: pa.Table, *, order: str = "as given") -> CachedSo ) +ORDERS = ["as given", "reversed", "tags reversed", "data-tags"] + + def _job( database: Any, *, @@ -224,7 +237,7 @@ def _run(job: PipelineJob, entry: str, **kwargs: Any) -> Any: @pytest.mark.usefixtures("root") @pytest.mark.parametrize("entry", ENTRIES) -@pytest.mark.parametrize("order", ["as given", "reversed"]) +@pytest.mark.parametrize("order", ORDERS) def test_every_table_kind_is_stored_as_on_delta( root: Path, entry: str, order: str ) -> None: @@ -302,7 +315,7 @@ def test_a_new_input_and_a_replay_are_stored_as_on_delta( @pytest.mark.usefixtures("root") @pytest.mark.parametrize("entry", ENTRIES) -@pytest.mark.parametrize("order", ["as given", "reversed"]) +@pytest.mark.parametrize("order", ORDERS) def test_replayed_completions_read_the_tracking_table_once( monkeypatch: pytest.MonkeyPatch, entry: str, order: str ) -> None: @@ -315,16 +328,17 @@ def test_replayed_completions_read_the_tracking_table_once( name = spiral_database_identity.spiral_table_name(tracking_path) table_id = fake.ExternalProject("p").table(f"d.{name}").table_id scan = fake.FakeKeyedTable.scan - reads: list[str] = [] + reads: list[Any] = [] def counted(table_handle: fake.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any: - if table_handle.resource_id == table_id and not args and not kwargs: - reads.append(table_handle.resource_id) + if table_handle.resource_id == table_id: + reads.append(args[0] if args else kwargs.get("columns")) return scan(table_handle, *args, **kwargs) monkeypatch.setattr(fake.FakeKeyedTable, "scan", counted) _ = _run(job, entry) - assert len(reads) == 1 + # One read of the log, of its key column alone (the lease's key index). + assert reads == [["__record_id"]] assert delivered == [] assert job.nodes["sink"].as_table().num_rows == 3 @@ -342,7 +356,7 @@ def counted(client: Any, project: str, dataset: str) -> dict[str, str]: return list_tables(client, project, dataset) monkeypatch.setattr(spiraldb_connector, "_list_keyed_tables", counted) - for order in ("as given", "reversed"): + for order in ORDERS: listings.clear() database = _database() separate_connector = _database().at(JOB, "results") @@ -351,7 +365,7 @@ def counted(client: Any, project: str, dataset: str) -> dict[str, str]: @pytest.mark.usefixtures("root") -@pytest.mark.parametrize("order", ["as given", "reversed"]) +@pytest.mark.parametrize("order", ORDERS) @pytest.mark.parametrize("target", ["combine", "select"]) def test_node_run_appends_function_results_as_one_batch( monkeypatch: pytest.MonkeyPatch, order: str, target: str @@ -381,7 +395,7 @@ def counted(table: fake.FakeKeyedTable, batch: pa.Table) -> fake.FakeKeyedTable: @pytest.mark.usefixtures("root") @pytest.mark.parametrize("entry", ["sync", "run_async", "node run"]) -@pytest.mark.parametrize("order", ["as given", "reversed"]) +@pytest.mark.parametrize("order", ORDERS) def test_a_failed_row_keeps_the_same_results_and_run_counts( root: Path, entry: str, order: str ) -> None: @@ -1667,3 +1681,258 @@ def test_a_cached_source_behind_a_held_table_is_still_leased() -> None: 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) + + +# ----------------------------------------------- independent review of 48aa8c871 + + +def _receipt_job(database: Any, table: pa.Table, observe: Any, *labels: str) -> Any: + """A tracked sink per label over one source of two tags and two data columns.""" + source = ArrowTableSource( + table, + tag_columns=["group", "item"], + tag_only_columns=True, + source_id="input", + record_id_columns=["group", "item"], + ) + job = PipelineJob(name="receipt", database=database) + with job: + pod = sink_pod(observe) + assert isinstance(pod, SideEffectPod) + for label in labels: + pod.process(source, label=label) + return job + + +def _receipt_rows(items: list[int]) -> pa.Table: + schema = pa.schema( + [ + pa.field("group", pa.large_string(), nullable=False), + pa.field("item", pa.int64(), nullable=False), + pa.field("x", pa.int64(), nullable=False), + pa.field("y", pa.int64(), nullable=False), + ] + ) + return pa.table( + { + "group": ["g"] * len(items), + "item": items, + "x": [11 * i for i in items], + "y": [i + 1 for i in items], + }, + schema=schema, + ) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "async orchestrator"]) +@pytest.mark.parametrize("items", [[1, 2], [2, 1]]) +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 + (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.""" + observed: list[int] = [] + receipts: dict[int, pa.Table] = {} + database = _database() + tracking: list[tuple[str, ...]] = [] + armed: list[bool] = [] + + def observe(x: int, y: int, ctx: Any) -> None: + if not armed: + return # the seed runs + observed.append(x) + if len(observed) == 1: + later = 11 * items[1] + database.add_records( + tracking[0], + receipts[later], + record_id_column="__record_id", + skip_duplicates=True, + flush=True, + ) + + # The receipt of each row, as a run of that row alone records it. + for item in items: + seed = _database(f"seed{item}") + _ = _receipt_job(seed, _receipt_rows([item]), observe, "sink").run() + path = next(p for p in seed.list_table_paths() if p[-1] == "tdb_v2") + receipt = seed.get_all_records(path, record_id_column="__record_id") + assert receipt is not None and receipt.num_rows == 1 + receipts[11 * item] = receipt + tracking[:] = [path] + + armed.append(True) + job = _receipt_job(database, _receipt_rows(items), observe, "sink") + _ = _run(job, entry) + assert observed == [11 * items[0]] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) +@pytest.mark.parametrize("labels", [("first", "second"), ("second", "first")]) +def test_two_sinks_sharing_a_tracking_table_deliver_each_row_once( + root: Path, entry: str, labels: tuple[str, str] +) -> None: + """Two tracked sinks of one pod over one source share one invocation log; every + row is delivered once, as on Delta.""" + observed: dict[str, list[int]] = {} + for name, database in ( + ("spiral", _database()), + ("delta", DeltaTableDatabase(root / "delta")), + ): + found: list[int] = [] + + def observe(x: int, y: int, ctx: Any, found: list[int] = found) -> None: + found.append(x) + + job = _receipt_job(database, _receipt_rows([1, 2, 3]), observe, *labels) + _ = _run(job, entry) + observed[name] = sorted(found) + assert observed["spiral"] == observed["delta"] == [11, 22, 33] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("order", ORDERS) +def test_a_node_run_over_a_delta_result_store_commits_every_row( + root: Path, order: str +) -> None: + """Review B4: a function node whose pipeline database is SpiralDB and whose result + database is Delta keeps main's per-row commits: a fresh Delta reader sees each + result as soon as it is stored.""" + results_root = root / "delta-results" + visible: list[int] = [] + + @function_pod(output_keys=("total", "ratio")) + def counted(x: int, y: int) -> tuple[int, float]: + reader = DeltaTableDatabase(results_root) + visible.append( + sum( + stored.num_rows + for path in reader.list_table_paths() + if (stored := reader.get_all_records(path)) is not None + ) + ) + return x + y, x / y + + job = PipelineJob( + name=JOB, + database=_database(), + result_database=DeltaTableDatabase(results_root), + ) + with job: + source = _cached(InMemoryArrowDatabase(), _rows(), order=order) + counted.pod(source, label="compute") + _ = job.nodes["compute"].run() + assert visible == [0, 1, 2] + + +def _result_appends(monkeypatch: pytest.MonkeyPatch) -> list[int]: + """Record the row count of every append to a result table (``rdb_v1``).""" + append = fake.FakeKeyedTable.append + appended: list[int] = [] + + def counted(table: fake.FakeKeyedTable, batch: pa.Table) -> fake.FakeKeyedTable: + record = spiral_database_identity.read_table_identity_metadata( + table.get_metadata() + ) + if record is not None and record.path[-1] == "rdb_v1": + appended.append(batch.num_rows) + return append(table, batch) + + monkeypatch.setattr(fake.FakeKeyedTable, "append", counted) + return appended + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("order", ORDERS) +def test_a_node_run_over_an_ephemeral_spiral_result_store_appends_once( + monkeypatch: pytest.MonkeyPatch, order: str +) -> None: + """Review S2: an in-memory job with a writable SpiralDB ephemeral result store + batches its node run: the three results are one append, and the node shows the + rows and counts an in-memory ephemeral store gives.""" + from orcapod.types import NodeConfig + + outcomes: list[Any] = [] + for ephemeral in (_database(), InMemoryArrowDatabase()): + job = PipelineJob(name=JOB, database=InMemoryArrowDatabase()) + with job: + source = _cached(InMemoryArrowDatabase(), _rows(), order=order) + combine.pod(source, label="combine") + job.set_ephemeral_database(ephemeral) + job.nodes["combine"].node_config = NodeConfig(is_result_ephemeral=True) + with monkeypatch.context() as patch: + appended = _result_appends(patch) + _ = job.nodes["combine"].run() + if isinstance(ephemeral, ConnectorArrowDatabase): + assert appended == [3] + summary = job.nodes["combine"].last_run + assert summary is not None + node = summary.nodes["combine"] + outcomes.append( + ( + (node.computed, node.reused, node.failed), + _comparable(job.nodes["combine"].as_table()), + ) + ) + assert outcomes[0] == outcomes[1] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("order", ORDERS) +@pytest.mark.parametrize("target", ["combine", "select"]) +def test_a_permanent_result_failure_keeps_the_rows_before_it( + monkeypatch: pytest.MonkeyPatch, order: str, target: str +) -> 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.""" + from orcapod.errors import OrcapodDatabaseWriteError + + append = fake.FakeKeyedTable.append + attempted: list[list[int]] = [] + + def refuse_total_8(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: + record = spiral_database_identity.read_table_identity_metadata( + table.get_metadata() + ) + if record is not None and record.path[-1] == "rdb_v1": + totals = [ + value + for column in batch.columns + for value in column.to_pylist() + if value in (6, 8, 10) + ] + attempted.append(totals) + if 8 in totals: + raise fake.SpiralError("permanent failure writing total=8") + return append(table, batch) + + job = _job(_database(), order=order) + with monkeypatch.context() as patch: + patch.setattr(fake.FakeKeyedTable, "append", refuse_total_8) + with pytest.raises(OrcapodDatabaseWriteError, match="total=8"): + _ = job.nodes[target].run() + # One batch of three, then one row at a time up to the failing row. + batch, *single = attempted + assert sorted(batch) == [6, 8, 10] + assert [len(s) for s in single] == [1] * len(single) and single[-1] == [8] + kept = sorted(s[0] for s in single[:-1]) + fresh = _database() + stored = { + path[-1]: table + for path in fresh.list_table_paths() + if (table := fresh.get_all_records(path)) is not None + } + results = stored.get("rdb_v1") + totals = [] if results is None else cast("list[int]", results["total"].to_pylist()) + assert sorted(totals) == kept + records = stored.get("pdb_v2") + assert (0 if records is None else records.num_rows) == len(kept) + assert stored["sdb_v2"].num_rows == 3 + with database_writes([fresh], owner="recovery"): + pass From cb56f9f88a3420dc8d0660b7114932b86943bfd0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 22:01:53 -0800 Subject: [PATCH 12/46] fix(spiraldb): list a table after an ambiguous first append A first append whose reply was lost may have committed: the run's lease catalog now lists the table unjudged, so the next stale-table listing asks whether it holds rows, as main does. Qualify the in-order result retry: for a definite failure the durable rows are main's; after an ambiguous reply, results the service already accepted stay, unreferenced. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1502.md | 4 +- docs/concepts/spiraldb-database.md | 7 ++- .../databases/connector_arrow_database.py | 6 ++ src/orcapod/databases/spiraldb_tables.py | 10 +++- .../test_spiraldb_writable_mode.py | 53 +++++++++++++++++ .../test_spiraldb_writable_runs.py | 57 +++++++++++++++++++ 6 files changed, 134 insertions(+), 3 deletions(-) diff --git a/changelog.d/ITL-1502.md b/changelog.d/ITL-1502.md index 8d7e049e3..f58451034 100644 --- a/changelog.d/ITL-1502.md +++ b/changelog.d/ITL-1502.md @@ -7,7 +7,9 @@ end when every database the node commits to is a writable SpiralDB database or an `InMemoryArrowDatabase`, at least one of them SpiralDB; any other store keeps the per-row commits. A failed batched result append is retried one row at a time, in - order, so the results before the failing row stay stored. + order, so the results before the failing row stay stored. For a definite + failure, the stored rows are those of per-row commits; after an ambiguous reply, + results the service already accepted stay, unreferenced by any pipeline record. ### Fixed diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index f0589b334..a356fd781 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -94,7 +94,12 @@ SQL, PostgreSQL) keeps the node committing after every row, so another reader of store sees each result as soon as it is stored. If a batched result append fails, its rows are appended one at a time, in order, up to the first that fails: the results before that row and their pipeline records stay stored, as a node committing after -every row keeps them, and the run stops with that row's error. +every row keeps them, and the run stops with that row's error. For a definite +failure, the rows that stay stored are those a node committing after every row +keeps. After an ambiguous reply (the service may have accepted some of the batch's +rows before the reply was lost), results the service already accepted stay, +unreferenced: no pipeline record points to them, and a later run finds them by +input hash as cached results. A connection resolves a table by name and checks its recorded path when it finds the table. Later operations use the resolved table ID for that connection. diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index ff52e6065..29e11e9e0 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1235,6 +1235,12 @@ def flush_result_batch_in_order( withdrawn. A write of one row reads the keys the table holds again, so a row the failed batch stored after all is never written twice. + For a definite failure, the durable rows are those a node committing after + every row keeps. After an ambiguous reply, results the service already + accepted stay, unreferenced: a result after the first failing row may be + stored with no pipeline record pointing to it, which is harmless, since + results are a cache keyed by input hash and no pipeline record dangles. + Args: record_path: The result table's path. publish_records: As for ``flush_result_batch`` (this store publishes diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index b725e53e4..923aea908 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -95,7 +95,8 @@ class WriterLease: 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; ``None`` until then. + updated by every committed append; a failed append lists its table + unjudged, since it may hold rows; ``None`` until then. 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. @@ -1222,6 +1223,13 @@ def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: _ = 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: + # 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( + found.table_id, identity.spiral_table_name(found.record.path) + ) raise finally: lease.commits += 1 diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index 347a754e6..994ba0682 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -2641,3 +2641,56 @@ def test_sliced_nested_lists_are_written_and_read_through_the_database( got = _get(ConnectorArrowDatabase(writable_connector())) assert got is not None assert by_id(got.select(given.column_names)).equals(by_id(given)) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("order", ["forward", "reversed"]) +def test_an_ambiguous_first_append_is_reported_stale_at_once( + monkeypatch: pytest.MonkeyPatch, order: str +) -> None: + """Delta review of 1c7e53036: after the run's listing is taken, another connector + of the run makes the first append to a new table from a thread; the service + stores the rows and the reply is lost. The next stale report lists the table, + as main does, and so does a report after another table is written.""" + import asyncio + + first, second, third = ( + ConnectorArrowDatabase(writable_connector(held=False)) 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: + result = append(table, batch) + if "__record_id" in batch.column_names: + raise fake.SpiralError("the reply was lost") + return result + + 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) + + def write(db: ConnectorArrowDatabase, path: tuple[str, ...]) -> None: + given = rows(["key"]) + _ = db.add_records( + path, + _reordered(given) if order == "reversed" else given, + record_id_column="__record_id", + flush=True, + ) + + async def exercise() -> None: + assert stale() == [] + with monkeypatch.context() as lost: + lost.setattr(fake.FakeKeyedTable, "append", lost_reply) + with pytest.raises(Exception, match="reply was lost"): + await asyncio.to_thread(write, second, paths[0]) + assert (got := first.get_all_records(paths[0])) is not None + assert got.num_rows == 1 + assert stale() == [paths[0]] + await asyncio.create_task(asyncio.to_thread(write, third, paths[1])) + assert stale() == sorted(paths) + + with database_writes([first, second, third], owner="test"): + asyncio.run(exercise()) + assert stale() == sorted(paths) diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 7ec413ee3..5ebead7de 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -1936,3 +1936,60 @@ def refuse_total_8(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: assert stored["sdb_v2"].num_rows == 3 with database_writes([fresh], owner="recovery"): pass + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("order", ORDERS) +def test_a_partly_accepted_result_batch_leaves_no_dangling_pipeline_record( + monkeypatch: pytest.MonkeyPatch, order: str +) -> None: + """Delta review of 1c7e53036: the service accepts the last row of a batched + result append and loses the reply; the row-by-row retry then fails permanently + on the batch's first row. The accepted result stays, unreferenced: the run + fails with the first row's error, no pipeline record is written, so none + dangles, and the result is a cache entry keyed by its input hash.""" + from orcapod.errors import OrcapodDatabaseWriteError + + append = fake.FakeKeyedTable.append + attempted: list[list[int]] = [] + first_of_batch: list[int] = [] + + def partly_accept(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: + record = spiral_database_identity.read_table_identity_metadata( + table.get_metadata() + ) + if record is not None and record.path[-1] == "rdb_v1": + totals = [ + value + for column in batch.columns + for value in column.to_pylist() + if value in (6, 8, 10) + ] + attempted.append(totals) + if len(totals) > 1: + first_of_batch.append(totals[0]) + _ = append(table, batch.slice(len(totals) - 1, 1)) + raise fake.SpiralError("the reply was lost after a partial append") + if totals == first_of_batch: + raise fake.SpiralError("permanent failure on the first row") + return append(table, batch) + + job = _job(_database(), order=order) + with monkeypatch.context() as patch: + patch.setattr(fake.FakeKeyedTable, "append", partly_accept) + with pytest.raises(OrcapodDatabaseWriteError, match="first row"): + _ = job.nodes["combine"].run() + batch, *single = attempted + assert sorted(batch) == [6, 8, 10] + assert single == [batch[:1]] + fresh = _database() + stored = { + path[-1]: table + for path in fresh.list_table_paths() + if (table := fresh.get_all_records(path)) is not None + } + results = stored.get("rdb_v1") + assert results is not None + assert results["total"].to_pylist() == [batch[-1]] + records = stored.get("pdb_v2") + assert records is None or records.num_rows == 0 From 86b7d13402a17c4cf7c84438dd978601ca8c3bee Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 22:45:35 -0800 Subject: [PATCH 13/46] docs(spiraldb): state which accepted rows an ambiguous batch reply leaves unreferenced After an ambiguous batch reply the ordered retry publishes a pipeline record for every row before the first failing row, including rows the service had already accepted; only rows accepted beyond that prefix can stay without one. Pin it with a public node.run() test. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1502.md | 7 +- docs/concepts/spiraldb-database.md | 9 +- .../databases/connector_arrow_database.py | 11 +- .../test_spiraldb_writable_runs.py | 104 ++++++++++++++++++ 4 files changed, 122 insertions(+), 9 deletions(-) diff --git a/changelog.d/ITL-1502.md b/changelog.d/ITL-1502.md index f58451034..e09abfa91 100644 --- a/changelog.d/ITL-1502.md +++ b/changelog.d/ITL-1502.md @@ -8,8 +8,11 @@ `InMemoryArrowDatabase`, at least one of them SpiralDB; any other store keeps the per-row commits. A failed batched result append is retried one row at a time, in order, so the results before the failing row stay stored. For a definite - failure, the stored rows are those of per-row commits; after an ambiguous reply, - results the service already accepted stay, unreferenced by any pipeline record. + failure, the stored rows are those of per-row commits. After an ambiguous reply, + every row before the first failing row gets its pipeline record, including a row + the service had already accepted (it is not appended again); only a row the + service accepted beyond that prefix can stay stored without a pipeline record, + and a later run reuses it as a cached result. No pipeline record dangles. ### Fixed diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index a356fd781..fde9b26e6 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -97,9 +97,12 @@ before that row and their pipeline records stay stored, as a node committing aft every row keeps them, and the run stops with that row's error. For a definite failure, the rows that stay stored are those a node committing after every row keeps. After an ambiguous reply (the service may have accepted some of the batch's -rows before the reply was lost), results the service already accepted stay, -unreferenced: no pipeline record points to them, and a later run finds them by -input hash as cached results. +rows before the reply was lost), the ordered retry still 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. A connection resolves a table by name and checks its recorded path when it finds the table. Later operations use the resolved table ID for that connection. diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 29e11e9e0..847169d6b 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1236,10 +1236,13 @@ def flush_result_batch_in_order( row the failed batch stored after all is never written twice. For a definite failure, the durable rows are those a node committing after - every row keeps. After an ambiguous reply, results the service already - accepted stay, unreferenced: a result after the first failing row may be - stored with no pipeline record pointing to it, which is harmless, since - results are a cache keyed by input hash and no pipeline record dangles. + every row keeps. After an ambiguous reply, every row before the first + failing row is published, 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, which is harmless: results + are a cache keyed by input hash, a later run reuses it, and no pipeline + record dangles. Args: record_path: The result table's path. diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 5ebead7de..9051bfaf4 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -1993,3 +1993,107 @@ def partly_accept(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: assert results["total"].to_pylist() == [batch[-1]] records = stored.get("pdb_v2") assert records is None or records.num_rows == 0 + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("order", ORDERS) +def test_an_ambiguous_batch_reply_publishes_the_accepted_prefix( + monkeypatch: pytest.MonkeyPatch, order: str +) -> 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.""" + from orcapod.errors import OrcapodDatabaseWriteError + + append = fake.FakeKeyedTable.append + attempted: list[list[int]] = [] + batch_order: list[int] = [] + + def totals_of(table: fake.FakeKeyedTable, batch: pa.Table) -> list[int] | None: + record = spiral_database_identity.read_table_identity_metadata( + table.get_metadata() + ) + if record is None or record.path[-1] != "rdb_v1": + return None + return [ + value + for column in batch.columns + for value in column.to_pylist() + if value in (6, 8, 10) + ] + + def accept_the_edges(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: + totals = totals_of(table, batch) + if totals is not None: + attempted.append(totals) + if len(totals) > 1: + batch_order.extend(totals) + _ = 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]: + raise fake.SpiralError("permanent failure on the middle row") + return append(table, batch) + + def stored() -> dict[str, pa.Table]: + fresh = _database() + return { + path[-1]: table + for path in fresh.list_table_paths() + if (table := fresh.get_all_records(path, record_id_column="result_id")) + is not None + } + + def referenced_totals(tables: dict[str, pa.Table]) -> list[int]: + """The totals of the stored results that a pipeline record points to; every + pipeline record must point to a stored result.""" + by_id: dict[bytes, int] = dict( + zip( + cast("list[bytes]", tables["rdb_v1"]["result_id"].to_pylist()), + cast("list[int]", tables["rdb_v1"]["total"].to_pylist()), + ) + ) + records = tables.get("pdb_v2") + ids = ( + [] + if records is None + else cast("list[bytes]", records["__data_id"].to_pylist()) + ) + assert all(i in by_id for i in ids) + return sorted(by_id[i] for i in ids) + + 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() + 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]] + tables = stored() + assert sorted(cast("list[int]", tables["rdb_v1"]["total"].to_pylist())) == sorted( + [first, last] + ) + assert referenced_totals(tables) == [first] + + recovery: list[list[int]] = [] + + def record_appends(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: + totals = totals_of(table, batch) + if totals is not None: + recovery.append(totals) + return append(table, batch) + + with monkeypatch.context() as patch: + patch.setattr(fake.FakeKeyedTable, "append", record_appends) + _ = _job(_database(), order=order).nodes["combine"].run() + assert recovery == [[middle]] + tables = stored() + assert sorted(cast("list[int]", tables["rdb_v1"]["total"].to_pylist())) == [ + 6, + 8, + 10, + ] + assert referenced_totals(tables) == [6, 8, 10] From 11efa831f71e18569d2d98ed28d62879e262dbf1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 22:53:48 -0800 Subject: [PATCH 14/46] perf(spiraldb): find the newest writer lease generation from one dataset listing One listing of the dataset gives the end of the generation sequence; that generation and the next are opened by name, so a lagging listing still ends at the newest one. A listed generation that does not open falls back to the search by name. The exclusive-create claim is unchanged (ITL-1899). Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/spiraldb_connector.py | 38 +++++-- src/orcapod/databases/spiraldb_lease.py | 34 ++++++- tests/test_databases/test_spiral_lease.py | 104 ++++++++++++++++++-- 3 files changed, 157 insertions(+), 19 deletions(-) diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 0a40bf185..c01c611d3 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -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, writer lease generations too. 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 @@ -596,6 +594,34 @@ def _list_keyed_tables(client: Any, project_id: str, dataset: str) -> dict[str, token = following +def _list_keyed_tables(client: Any, project_id: str, dataset: str) -> dict[str, str]: + """Return keyed table names by ID, omitting writer lease generations. + + Args: + client: A spiral-sdk client. + project_id: The project. + dataset: The dataset; matched exactly by the service. + """ + return { + table_id: name + for table_id, name in _list_dataset(client, project_id, dataset).items() + if not is_spiral_lease_table_name(name) + } + + +def _list_lease_generations(client: Any, project_id: str, dataset: str) -> set[str]: + """Return the names of the writer lease generations a listing of the dataset shows. + + Args: + client: A spiral-sdk client. + project_id: The project. + dataset: The dataset. + """ + with _service_call(f"list the writer lease generations of {project_id}/{dataset}"): + listed = _list_dataset(client, project_id, dataset) + return {name for name in listed.values() if is_spiral_lease_table_name(name)} + + def _literal(value: Any, arrow_type: pa.DataType) -> Any: """Return ``value`` as a scan literal of exactly ``arrow_type`` (the service refuses another type), or ``None`` when the SDK has no literal that filters as Orcapod does. diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py index 329fe9872..0bc0c687b 100644 --- a/src/orcapod/databases/spiraldb_lease.py +++ b/src/orcapod/databases/spiraldb_lease.py @@ -1,6 +1,7 @@ """Internal one-writer leases for writable SpiralDB databases. -Generation discovery requires a contiguous sequence. Deleting a generation +Generation discovery requires a contiguous sequence: one listing of the dataset gives +where it ends, confirmed by opening that generation and the next ones by name. 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. @@ -168,7 +169,32 @@ def _open( def _newest( client: _Client, project_id: str, dataset: str ) -> tuple[int, _KeyedTable | None]: - """Bracket the end of the contiguous generation sequence, then bisect.""" + """Return the end of the contiguous generation sequence and its latest snapshot. + + One listing of the dataset gives a starting point: the end of the run of listed + generations from 1. That generation is opened by name, and the next ones are opened + by name while they exist, so a listing that lags the service still ends at the + newest generation. A listed generation that does not open falls back to the search + by name alone (``_search``). + """ + listed = sdk._list_lease_generations(client, project_id, dataset) + start = 0 + while spiral_lease_table_name(start + 1) in listed: + start += 1 + newest = None + if start > 0: + newest = _open(client, project_id, dataset, start) + if newest is None: + return _search(client, project_id, dataset) + while (table := _open(client, project_id, dataset, start + 1)) is not None: + start, newest = start + 1, table + return start, newest + + +def _search( + client: _Client, project_id: str, dataset: str +) -> tuple[int, _KeyedTable | None]: + """Bracket the end of the contiguous generation sequence by name, then bisect.""" low, high = 0, 1 newest = None while (table := _open(client, project_id, dataset, high)) is not None: @@ -341,8 +367,8 @@ def acquire( 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 + TimeoutError: If the generation lookup before the claim (a listing of the + dataset and opens by name), 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 diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py index fcddbb905..b789f1f42 100644 --- a/tests/test_databases/test_spiral_lease.py +++ b/tests/test_databases/test_spiral_lease.py @@ -9,7 +9,7 @@ import pyarrow as pa import pytest -from orcapod.databases import spiraldb_lease +from orcapod.databases import spiraldb_connector, spiraldb_lease from orcapod.databases.spiraldb_connector import SpiralDBConnector from orcapod.databases.spiraldb_lease import ( LeaseBusyError, @@ -665,12 +665,8 @@ def delay_create( 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")) +def _count_opens_by_name(monkeypatch: pytest.MonkeyPatch) -> list[str]: + """Record the name of every open by name from now on.""" open_by_name = fake.FakeClient.keyed_table probes: list[str] = [] @@ -686,14 +682,104 @@ def count_open( return open_by_name(instance, project, dataset, name, asof=asof) monkeypatch.setattr(fake.FakeClient, "keyed_table", count_open) + return probes + + +def _count_listings(monkeypatch: pytest.MonkeyPatch) -> list[str]: + """Record every page request of the dataset listing from now on.""" + listing = fake.fake_http_get_json + pages: list[str] = [] + + def count(url: str, token: str | None) -> dict[str, object]: + pages.append(url) + return listing(url, token) + + monkeypatch.setattr(spiraldb_connector, "_http_get_json", count) + return pages + + +@pytest.mark.parametrize("past_generations", [0, 1, 19, 40]) +def test_generation_search_opens_the_newest_and_probes_the_next( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, past_generations: int +) -> None: + """Finding the newest generation takes one listing of the dataset, an open of the + newest generation it shows and one probe of the next: never a search by name + (ITL-1899: 17 opens for about 380 generations before).""" + for _ in range(past_generations): + release(client, acquire(client, _PROJECT, _DATASET, owner="past")) + probes = _count_opens_by_name(monkeypatch) + pages = _count_listings(monkeypatch) current = acquire(client, _PROJECT, _DATASET, owner="current") - assert len(probes) <= 11 + newest = [spiral_lease_table_name(past_generations)] if past_generations else [] + assert probes == [*newest, spiral_lease_table_name(past_generations + 1)] + # One listing (of one or more pages), no other. + assert pages and all("pageToken" in page for page in pages[1:]) assert ( - client.keyed_table(_PROJECT, _DATASET, spiral_lease_table_name(20)).resource_id + client.keyed_table( + _PROJECT, _DATASET, spiral_lease_table_name(past_generations + 1) + ).resource_id == current.table_id ) +@pytest.mark.parametrize("hidden", [1, 3]) +def test_a_lagging_listing_still_finds_the_newest_generation( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, hidden: int +) -> None: + """A listing that does not show the newest generations yet ends where it ends: the + generations after it are found by name, so a held newest generation still refuses + and a released one is followed by the next.""" + for _ in range(4): + release(client, acquire(client, _PROJECT, _DATASET, owner="past")) + holder = acquire(client, _PROJECT, _DATASET, owner="holder") + listed = spiraldb_connector._list_dataset # pyright: ignore[reportPrivateUsage] + lagging = {spiral_lease_table_name(5 - i) for i in range(hidden)} + + def lag(client: object, project_id: str, dataset: str) -> dict[str, str]: + return { + table_id: name + for table_id, name in listed(client, project_id, dataset).items() + if name not in lagging + } + + monkeypatch.setattr(spiraldb_connector, "_list_dataset", lag) + other = fake.FakeClient() + with pytest.raises(LeaseBusyError, match=holder.table_id): + _ = acquire(other, _PROJECT, _DATASET, owner="second") + release(client, holder) + after = acquire(other, _PROJECT, _DATASET, owner="after") + assert ( + client.keyed_table(_PROJECT, _DATASET, spiral_lease_table_name(6)).resource_id + == after.table_id + ) + with pytest.raises(LeaseError, match="not the newest"): + clear(other, _PROJECT, _DATASET, holder.table_id, confirm_writer_stopped=True) + clear(other, _PROJECT, _DATASET, after.table_id, confirm_writer_stopped=True) + + +def test_a_listed_generation_that_does_not_open_falls_back_to_the_search( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch +) -> None: + """A listing that shows a generation the service then does not open is not trusted: + the generation sequence is searched by name, as before the listing.""" + for _ in range(3): + release(client, acquire(client, _PROJECT, _DATASET, owner="past")) + listed = spiraldb_connector._list_dataset # pyright: ignore[reportPrivateUsage] + + def ahead(client: object, project_id: str, dataset: str) -> dict[str, str]: + return { + **listed(client, project_id, dataset), + "table_ahead": spiral_lease_table_name(4), + } + + monkeypatch.setattr(spiraldb_connector, "_list_dataset", ahead) + lease = acquire(client, _PROJECT, _DATASET, owner="current") + assert ( + client.keyed_table(_PROJECT, _DATASET, spiral_lease_table_name(4)).resource_id + == lease.table_id + ) + + def test_lookup_error_never_licenses_creation( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch ) -> None: From d38289252de3a9ed03c5b3e4a287b2bc9f3ca0da Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 23:08:21 -0800 Subject: [PATCH 15/46] perf(spiraldb): keep what a run read under its writer lease Under the lease nothing but the run writes the dataset, so the run shares, across its connectors, what it read: - a name the run's listing does not show is absent without an open, and a name it creates is created at once (exclusive create) and listed; - the rows of a whole read of a table are kept until an append to it starts, only from a snapshot that held every append of the run, so each table is read whole once per batch of writes, not twice per computed row; the read also fills the key index; - what a table holding rows records, and the id each name resolved to, are shared by the run's connectors and its listing; such a table is opened by id only when a call needs the service; - a table this write's exclusive create made is used as the create returned it, with no reopen, metadata, key schema or one-row read. Everything is forgotten when the run's lease ends. Results, stored tables, record ids, events and summaries are unchanged (ITL-1899). Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/spiraldb_tables.py | 322 ++++++++++++++--- src/orcapod/databases/spiraldb_write_scope.py | 2 + .../test_spiraldb_round_trips.py | 340 ++++++++++++++++++ .../test_spiraldb_writable_mode.py | 19 +- 4 files changed, 637 insertions(+), 46 deletions(-) create mode 100644 tests/test_databases/test_spiraldb_round_trips.py diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index 923aea908..0503262ed 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. Under a writer lease, 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 @@ -31,7 +33,14 @@ 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. +shows, unless this write's own exclusive create made the table. + +Under the lease nothing but the run writes the dataset, so what the run read is kept for +the run and shared by its connectors (``WriterLease``, 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 run's lease ends. """ from __future__ import annotations @@ -70,10 +79,33 @@ @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()) + + 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 @dataclass @@ -100,6 +132,14 @@ class WriterLease: 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. + rows_by_table: The stored rows of each table a read of the run read whole, + 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 run'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] @@ -108,11 +148,25 @@ class WriterLease: table_ids: dict[str, str | None] = field(default_factory=dict) catalog: _Catalog | None = None commits: int = 0 + 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 __call__(self) -> None: """Verify the writer lease on first use.""" self.verify() + def forget_reads(self) -> None: + """Forget everything the run read (``WriterLease`` 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.rows_by_table.clear() + self.found_by_id.clear() + self.ids_by_name.clear() + class _Scan(Protocol): """The part of spiral-sdk's scan the database uses.""" @@ -187,6 +241,63 @@ class _Opened: table: _KeyedTable +class _LazySnapshot: + """A table resolved to its id, opened by id at its first use (ITL-1899). + + Used under a writer lease 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 _table(self) -> _KeyedTable: + if self._opened is None: + self._opened = self._open_by_id(self._table_id) + return self._opened + + @property + def resource_id(self) -> str: + return self._table_id + + @property + def key_columns(self) -> tuple[str, ...]: + return self._table().key_columns + + def schema(self) -> pa.Schema: + return self._table().schema() + + def get_metadata(self) -> dict[str, bytes]: + """The table's metadata entries, as stored.""" + return self._table().get_metadata() + + def set_metadata(self, metadata: dict[str, bytes]) -> None: + """Record metadata entries (an upsert of the given keys).""" + self._table().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._table().scan(columns, filter=filter, limit=limit) + + def append(self, data: pa.Table) -> _KeyedTable: + """Write rows (``_KeyedTable.append``).""" + return self._table().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,7 +336,8 @@ 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. """ @@ -237,7 +349,7 @@ 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]], ) -> None: @@ -246,7 +358,7 @@ def __init__( 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 self._paths: dict[str, tuple[str, ...]] = {} @@ -526,24 +638,39 @@ def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Judgment: Returns: The judgment. """ + lease = self._lease_check + resolved = self._resolved_id(table_name) + if lease is not None and resolved is not None: + known = self._known(resolved) + if known is not None and known.record.path == path: + # Under the lease nothing but the run 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 lease is None else lease.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 +679,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) + lease = self._lease_check + if table_id is None and lease is not None: + table_id = lease.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 (lease := self._lease_check) is not None: + lease.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) + lease = self._lease_check + if known is None and lease is not None: + known = lease.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 (lease := self._lease_check) is not None: + lease.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 (lease := self._lease_check) is not None: + _ = lease.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.""" + lease = self._lease_check + catalog = None if lease is None else lease.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: @@ -639,7 +810,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 @@ -659,7 +830,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 +842,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 +880,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 +948,11 @@ def scan(self, table_name: str) -> Iterator[pa.RecordBatch]: Args: table_name: A name ``table_name`` returned. + Under a writer lease the rows a read returned are kept for the run and read + from there again, until an append to the table starts (``WriterLease``, + 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 +963,39 @@ 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() + lease = self._lease_check + stored = None + if lease is not None: + with lease.lock: + stored = lease.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 lease 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, and its keys, 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. + """ + lease = self._lease_check + assert lease is not None + with lease.lock: + if not self._snapshot_is_current(table_name): + return + lease.rows_by_table[table_id] = stored + if table_id not in lease.keys_by_table: + lease.keys_by_table[table_id] = _keys_of(stored) + def existing_record_ids( self, table_name: str, ids: Collection[bytes] ) -> set[bytes]: @@ -900,12 +1110,7 @@ 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) # ── writing ────────────────────────────────────────────────────────────── @@ -956,33 +1161,50 @@ def _require_lease(self) -> WriterLease: 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.""" + lease = self._lease_check + if lease is not None and lease.catalog is not None: + with lease.lock: + lease.catalog.add(table_id, table_name) def _unchanged_since_judged( self, @@ -1171,9 +1393,15 @@ def _write_first( if encoded.num_rows == 0: return # nothing to write, so nothing is created 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) @@ -1214,20 +1442,22 @@ def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: # 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())) + # The rows a read kept no longer are the table's, whatever the append does. + _ = lease.rows_by_table.pop(found.table_id, None) lease.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) + self._forget(found.table_id) _ = 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: # 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) ) raise @@ -1235,11 +1465,9 @@ def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: 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 + self._remember(found) if (catalog := lease.catalog) is not None: - _ = catalog.names.setdefault( - found.table_id, identity.spiral_table_name(found.record.path) - ) + catalog.add(found.table_id, identity.spiral_table_name(found.record.path)) catalog.records[found.table_id] = (found.record, identity.TABLE_FORMAT) @@ -1327,6 +1555,16 @@ def _holds_rows( return keys.num_rows > 0 +def _keys_of(stored: pa.Table) -> set[bytes]: + """Every key of rows read from a database table.""" + return set( + cast( + "list[bytes]", + stored.column(codec.KEY_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_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index 201a01807..2c03e53d8 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -212,6 +212,8 @@ def _release_all( tables.let_go_of_lease(check) except BaseException as again: # noqa: BLE001 # reported with the others failures.append(again) + # What the run read under the lease ends with it (ITL-1899). + check.forget_reads() try: release() except BaseException as exc: # noqa: BLE001 # an interrupted release too: every lease is released; failures are reported below 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..5492ab6a4 --- /dev/null +++ b/tests/test_databases/test_spiraldb_round_trips.py @@ -0,0 +1,340 @@ +"""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, spiraldb_connector +from orcapod.databases.spiraldb_tables import SpiralDBTables, WriterLease +from orcapod.databases.spiraldb_write_scope import database_writes +from orcapod.databases.store_table_names import is_spiral_lease_table_name +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 (not a lease generation). + + 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 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] + original = getattr(cls, method) + + def recorded(self: Any, *args: Any, **kwargs: Any) -> Any: # pyright: ignore[reportExplicitAny] + try: + result = original(self, *args, **kwargs) + except Exception: + name = table_of(self, args, None) + if not is_spiral_lease_table_name(name): + calls.append(Call(kind, name, ok=False)) + raise + name = table_of(self, args, result) + if not is_spiral_lease_table_name(name): + 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] + columns = args[0] if args else kwargs.get("columns") + if not is_spiral_lease_table_name(_name(table)): + kind = ( + "one-row read" + if kwargs.get("limit") is not None + else "full read" + if columns is None + else "key read" + ) + calls.append(Call(kind, _name(table))) + return scan(table, *args, **kwargs) + + monkeypatch.setattr(fake.FakeKeyedTable, "scan", scanned) + listing = spiraldb_connector._list_keyed_tables # pyright: ignore[reportPrivateUsage] + + def listed(client: Any, project: str, dataset: str) -> dict[str, str]: # pyright: ignore[reportExplicitAny] + calls.append(Call("listing", "")) + return listing(client, project, dataset) + + monkeypatch.setattr(spiraldb_connector, "_list_keyed_tables", listed) + yield calls + + +def _counts(calls: list[Call]) -> Counter[str]: + 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: + _ = _run(_job(_database(), table=_rows(rows)), entry) + calls.clear() + + +# ── 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: + """After the run lists its dataset, a name the listing does not show is never + opened: 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) + listed = next(i for i, c in enumerate(sdk_calls) if c.kind == "listing") + after = sdk_calls[listed:] + assert [c for c in after if c.kind == "open by name"] == [] + # Before the listing: the cached source's first check of its table. + before = [c for c in sdk_calls[:listed] if c.kind == "open by name"] + assert all(not c.ok for c in before) and len(before) <= 2 + 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], owner="test"): + 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] + + +@pytest.mark.usefixtures("root") +def test_kept_rows_are_what_a_fresh_read_gives() -> None: + """Rows kept by a read under the lease 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 rows(*ids: str) -> pa.Table: + 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), + } + ) + + def fresh() -> list[bytes]: + 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 = 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], owner="test"): + db.add_records(path, rows("a"), record_id_column="__record_id", flush=True) + assert kept(db) == kept(other) == fresh() == [b"a"] + other.add_records(path, rows("b"), record_id_column="__record_id", flush=True) + assert kept(db) == kept(other) == fresh() == [b"a", b"b"] + db.add_records(path, 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 = _database() + path = ("fn", "rdb_v1") + first = pa.table( + { + "__record_id": pa.array([b"a"], pa.large_binary()), + "x": pa.array([1], pa.int64()), + "__data_context": ["std:v1:default"], + } + ) + with database_writes([db], owner="test"): + db.add_records(path, first, record_id_column="__record_id", flush=True) + tables = db._spiral # pyright: ignore[reportPrivateUsage] + assert isinstance(tables, SpiralDBTables) + lease = tables._lease_check # pyright: ignore[reportPrivateUsage] + assert isinstance(lease, WriterLease) + lease.rows_by_table.clear() + name = tables.table_name(path) + with tables.operation(): + _ = tables.has_table(name) + lease.commits += 2 # an append of the run committed meanwhile + assert len(list(tables.scan(name))) == 1 + assert lease.rows_by_table == {} + + +# ── 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 + assert ( + counts["open by id"] <= {"new row": 10, "held rerun": 5, "REPLAY": 4}[scenario] + ) + assert counts["key read"] <= 2 + + +@pytest.mark.usefixtures("root") +def test_what_a_run_read_is_forgotten_when_its_lease_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], owner="test"): + db.add_records(path, rows, record_id_column="__record_id", flush=True) + _ = db.list_table_paths(("fn",)) + _ = db.get_all_records(path) + lease = tables._lease_check # pyright: ignore[reportPrivateUsage] + assert isinstance(lease, WriterLease) + assert lease.rows_by_table and lease.found_by_id and lease.catalog + assert tables._lease_check is None # pyright: ignore[reportPrivateUsage] + assert not lease.rows_by_table and not lease.found_by_id + assert not lease.keys_by_table and not lease.ids_by_name + assert lease.catalog is None diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index 994ba0682..ceee14ebf 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -81,6 +81,13 @@ def _release_test_leases() -> None: raise failure +def _forget_run_reads(project: str = "p", dataset: str = "d") -> None: + """Forget what the test's run read under its lease, as a lease claimed after an + outside change does: the change was made by another writer, which a held lease + excludes, so a run sees it only when its lease starts (ITL-1899, ITL-1900).""" + _test_leases[(project, dataset)][0].forget_reads() + + def writable_connector( project: str = "p", dataset: str = "d", *, held: bool = True ) -> SpiralDBConnector: @@ -585,6 +592,7 @@ def test_rows_of_another_data_context_are_refused_before_they_are_buffered() -> _table(identity.spiral_table_name(RESULT)).set_metadata( identity.table_identity_metadata(RESULT, recorded) ) + _forget_run_reads() other = (*RESULT[:-1], "rdb_v9") db = ConnectorArrowDatabase(writable_connector()) db.add_records(other, rows(["valid"]), record_id_column="__record_id") @@ -615,6 +623,7 @@ def test_a_table_of_another_data_context_made_after_buffering_is_refused_at_flus _table(identity.spiral_table_name(RESULT)).set_metadata( identity.table_identity_metadata(RESULT, recorded) ) + _forget_run_reads() with pytest.raises(InputValidationError) as raised: db.flush() assert recorded in str(raised.value) and CONTEXT in str(raised.value) @@ -1887,7 +1896,8 @@ 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.""" + """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(held=False)) with database_writes([db], owner="seed"): _add(db, rows(["r0", "r1"]), flush=True) @@ -1897,9 +1907,9 @@ def test_flush_reuses_keys_and_opens_by_id_after_resolving_the_name( _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": 2, "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": 3, "key_reads": 1} got = _get(db) assert got is not None assert sorted(_record_ids(got)) == [ @@ -2157,6 +2167,7 @@ def test_an_append_to_a_table_recording_other_stored_names_is_refused() -> None: **codec.manifest_entries(other), } ) + _forget_run_reads() db = ConnectorArrowDatabase(writable_connector()) with pytest.raises(ValueError, match="other names") as raised: _add(db, rows(["r1", "r2"], offset=1), flush=True) @@ -2433,7 +2444,7 @@ def unreadable(self: Any) -> dict[str, bytes]: raise RuntimeError("the service could not read the metadata") monkeypatch.setattr(fake.FakeKeyedTable, "get_metadata", unreadable) - fresh = ConnectorArrowDatabase(writable_connector()) + fresh = ConnectorArrowDatabase(writable_connector(held=False)) with pytest.raises(OrcapodDatabaseReadError) as raised: if lookup == "by_id": _ = fresh.get_record_by_id(RESULT, b"r0", record_id_column="__record_id") From 2deae0f85d3918fe28ad1002c153eba9966ffd5e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 23:35:30 -0800 Subject: [PATCH 16/46] feat(spiraldb): take the writer lease at a run's first write (ITL-1900) - A run observes each writable dataset's newest lease generation and its snapshot version when its write scope opens (one listing, one open, no state read), and acquires the lease at its first create or append to the dataset. The claim is refused with LeaseChangedError (a LeaseBusyError) when the generation or version moved since the observation, and with LeaseBusyError when it is held; nothing is written by that write. - A write that sends no rows claims nothing, so a rerun with nothing new, a REPLAY run and a load-only run take no lease. - A side-effect node reads its invocation log without the lease and claims it just before its first delivery; a context-taking function node just before its function can be called for a row it does not hold, on the sync and async paths. - A refusal wrapped on its way out (a node's commit) is raised at the write-scope boundary as the lease error itself, with a note naming the wrapper. - Racing first writes on several threads take one lease (the run's lock). - Docs, changelog and the write scope's docstrings describe the rule. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1899.md | 25 + docs/concepts/spiraldb-database.md | 48 +- src/orcapod/core/nodes/function_node.py | 33 +- .../databases/connector_arrow_database.py | 7 + .../databases/extension_aware_database.py | 5 + src/orcapod/databases/spiraldb_lease.py | 79 +++ src/orcapod/databases/spiraldb_tables.py | 38 +- src/orcapod/databases/spiraldb_write_scope.py | 177 +++++-- src/orcapod/protocols/spiraldb_run.py | 6 + src/orcapod/side_effects.py | 18 + .../test_spiraldb_lazy_lease.py | 499 ++++++++++++++++++ .../test_spiraldb_writable_mode.py | 16 +- .../test_spiraldb_writable_runs.py | 89 +++- 13 files changed, 950 insertions(+), 90 deletions(-) create mode 100644 changelog.d/ITL-1899.md create mode 100644 tests/test_databases/test_spiraldb_lazy_lease.py diff --git a/changelog.d/ITL-1899.md b/changelog.d/ITL-1899.md new file mode 100644 index 000000000..5858ec025 --- /dev/null +++ b/changelog.d/ITL-1899.md @@ -0,0 +1,25 @@ +### Changed + +- A run on a writable SpiralDB database takes the dataset's writer lease at its first + write to the dataset, not when it starts (ITL-1900). When it starts, the run looks + at the dataset's newest lease (one listing and one open, about half a second on the + service). A run that writes nothing (a rerun with nothing new, a `REPLAY` run, a + load-only run) takes no lease. A side-effect node (a `SideEffectPod` node, or a + function node whose pod takes the invocation context) reads its invocation log + without the lease and takes it just before its first delivery or function call; + with nothing to deliver it takes none. +- A second writer is refused at its first write, with nothing written by that write + and nothing delivered: with `LeaseBusyError` when another run holds the lease, and + with the new `LeaseChangedError` (a `LeaseBusyError`) when another writer took the + lease after the run started, so what the run read may be out of date; run again. + Rows the run wrote to another dataset before the refusal stay stored. A refusal + reached through a node's commit is raised as the lease error itself, with a note + naming the commit error. +- A job saved after a run refused its lease no longer records the advisory stored + row counts (`expected_rows`): the refusal now stops a run that has started, as any + failed run does. +- Writable SpiralDB runs make fewer service calls (ITL-1899). The newest writer lease + generation is found from one listing of the dataset. A first run opens no table + that its listing shows absent, and reads back no table it created. A run reads each + table whole once per batch of writes and keeps what it read under its lease, instead + of twice per computed row, and identifies each existing table once. diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index fde9b26e6..0c7a464e1 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -40,19 +40,32 @@ 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. +The SpiralDB database has one writer at a time. Every run of a job (`job.run()`, +`job.run_async()`, a job node's `run()`) that writes the dataset holds its **writer +lease** while it writes, and releases it when the run ends, also when it fails. A run +whose database and result database are on one dataset takes one lease. + +The lease is taken at the run's first write, not when the run starts: + +- **When the run starts**, it looks at the dataset's newest lease (one listing of the + dataset and one open, about half a second on the service; nothing is read from the + lease). It reads the stored tables as it needs them, with no lease. +- **At its first write** to the dataset (a table created or rows appended), the run takes + the lease. A run that writes nothing (a rerun with nothing new, a `REPLAY` run, a + load-only run) takes no lease: only the look at the start. +- **A side-effect node** (a `SideEffectPod` node, or a function node whose pod takes the + invocation context) reads its invocation log without the lease and takes it just + before its first delivery, or its function's first call. With nothing to deliver it + takes no lease. + +The lease is refused, with nothing written by that write, nothing delivered and no +function called, in two cases. Another run holds it: `LeaseBusyError`, naming the +lease's table id and who holds it. Or another writer took the lease after this run +started (and may have written since): `LeaseChangedError`, a `LeaseBusyError`, because +what the run read may be out of date; run again. So what a run decided from its reads +is what the store held when it wrote. Rows the run wrote to another dataset before the +refusal stay stored, under that dataset's lease. The lease is refuse-only: the second +writer does not wait and never takes the lease over, and a lease does not expire. ```python @@ -72,8 +85,9 @@ connector of its own or over a `share_client()` copy, flushed directly) raises ` 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 +load-only run of a job writes no node's table, so it takes a lease only when a cached +source it reads stores new rows. A run takes one lease per dataset of one service, also +when several of its writes start at once on several threads: writable connectors whose client reaches the same service share it, whether their address was left to the default or given (`overrides={"server.url": ...}`). @@ -135,8 +149,8 @@ make the client for that same address, with a sign-in allowed to update the data 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 +The run verifies each lease when it takes it, and once more before 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. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 2a0da70c5..02869245d 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -122,7 +122,10 @@ ) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.hashing_protocols import IdentityWalkProtocol -from orcapod.protocols.spiraldb_run import InOrderResultFlushProtocol +from orcapod.protocols.spiraldb_run import ( + InOrderResultFlushProtocol, + SpiralDBRunLookupProtocol, +) from orcapod.protocols.observability_protocols import ( DataExecutionLoggerProtocol, ExecutionObserverProtocol, @@ -1623,6 +1626,20 @@ def _begin_run(self) -> None: self._current_tables_checked = False self._account_for_stale_tables() + def _claim_writer_leases(self) -> None: + """Claim the run's writer leases of the writable SpiralDB databases this node + writes, before its function is called for a row it does not hold (ITL-1900); + a later claim only verifies the lease once.""" + databases = [self._pipeline_database] + databases.extend( + pod.result_database + for pod in (self._cached_function_pod, self._ephemeral_cached_pod) + if pod is not None + ) + for database in databases: + if isinstance(database, SpiralDBRunLookupProtocol): + database.spiral_claim_writer_lease() + def _refresh_stored_tables(self) -> None: """Read this node's stored tables from the store's current version (ITL-1408). @@ -3029,6 +3046,11 @@ def _process_data_internal( if isinstance(data, EmptyData): return self._empty_data_cache_hit(tag, data, instance_id) + if self._delivers_side_effects: + # Before the function can be called (ITL-1900): the claim is refused if + # another writer wrote since the run observed the dataset, so what the + # run read to decide this call is still what the store holds. + self._claim_writer_leases() self._preflight_pipeline_write_schema() ephemeral_result = bool(self._node_config.is_result_ephemeral) @@ -3174,6 +3196,11 @@ async def _async_process_data_internal( if isinstance(data, EmptyData): return self._empty_data_cache_hit(tag, data, instance_id) + if self._delivers_side_effects: + # Before the function can be called (ITL-1900): the claim is refused if + # another writer wrote since the run observed the dataset, so what the + # run read to decide this call is still what the store holds. + self._claim_writer_leases() self._preflight_pipeline_write_schema() ephemeral_result = bool(self._node_config.is_result_ephemeral) @@ -4924,6 +4951,10 @@ async def route_inputs() -> None: (stamped_tag, found) ) continue + if self._delivers_side_effects: + # Before the function can be called for the + # row (ITL-1900), as on the sync path. + self._claim_writer_leases() # The function takes the row without its # fall-through columns (ITL-1023). await compute_channel.writer.send( diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 847169d6b..73ad7e01c 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1522,6 +1522,13 @@ def spiral_records_match_context( pending is None or tables.data_context(pending) == current ) + def spiral_claim_writer_lease(self) -> None: + """Claim the writer lease the run attached to this writable SpiralDB database + now, as its first write would (ITL-1900); nothing for another database or + without an attached lease.""" + if (tables := self._spiral) is not None: + tables.claim_lease() + def spiral_completion_lookup( self, record_path: tuple[str, ...] ) -> Callable[[bytes], bool] | None: diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index 380c1eaac..09777caaa 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -103,6 +103,11 @@ def spiral_completion_lookup( return self._db.spiral_completion_lookup(record_path) return None + def spiral_claim_writer_lease(self) -> None: + """Delegate the claim when the wrapped store supports it.""" + if isinstance(self._db, SpiralDBRunLookupProtocol): + self._db.spiral_claim_writer_lease() + def get_record_by_id( self, record_path: tuple[str, ...], diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py index 0bc0c687b..e48694dc4 100644 --- a/src/orcapod/databases/spiraldb_lease.py +++ b/src/orcapod/databases/spiraldb_lease.py @@ -51,6 +51,11 @@ def key_columns(self) -> tuple[str, ...]: """Return the ordered primary-key names.""" ... + @property + def version_id(self) -> object: + """Return the snapshot's version.""" + ... + def scan(self, *, limit: int) -> _Scan: """Plan a scan of the lease rows.""" ... @@ -137,6 +142,50 @@ def __init__( ) +class LeaseChangedError(LeaseBusyError): + """Another writer took the dataset's writer lease while a run read the dataset. + + A run reads before it claims the lease, at its first write (ITL-1900): it observed + the newest lease generation when it started (``observe``) and claims only if no + writer took or released a lease since, so nothing it read can have changed. The + run is refused at its first write, with nothing written, and is run again. + + Attributes: + table_id: Immutable ID of the newest generation found at the claim (``""`` + when the dataset has none). + """ + + def __init__(self, project_id: str, dataset: str, table_id: str) -> None: + """Explain that the dataset changed during the run and how to proceed. + + Args: + project_id: Project containing the dataset. + dataset: Dataset where the claim was refused. + table_id: Immutable ID of the newest generation found. + """ + self.table_id = table_id + LeaseError.__init__( + self, + f"Another writer wrote SpiralDB dataset {project_id}/{dataset} while this " + "run was reading it (its writer lease changed since the run started), so " + "what the run read may be out of date. Nothing was written. Run again.", + ) + + +@dataclass(frozen=True) +class Observed: + """The newest writer lease generation of a dataset as a run found it when it + started (``observe``). + + Attributes: + generation: The newest generation's number, 0 when there is none. + version: The version of its latest snapshot then; ``None`` without one. + """ + + generation: int + version: str | None + + @dataclass(frozen=True) class Lease: """A claim on one immutable generation table, held in the acquiring process.""" @@ -341,6 +390,22 @@ def _release_if_claimed( ) +def observe(client: _Client, project_id: str, dataset: str) -> Observed: + """Find the newest writer lease generation of a dataset and its snapshot version, + without reading its state: a run that claims later gives it to ``acquire``. + + Args: + client: SDK client used for the lease. + project_id: Project containing the dataset. + dataset: The dataset. + + Returns: + What was found. + """ + generation, latest = _newest(client, project_id, dataset) + return Observed(generation, None if latest is None else str(latest.version_id)) + + def acquire( client: _Client, project_id: str, @@ -348,6 +413,7 @@ def acquire( *, owner: str, on_claim: Callable[[Lease], None] | None = None, + expected: Observed | None = None, ) -> Lease: """Claim a dataset for one writer or raise before any database data can be written. @@ -360,11 +426,17 @@ def acquire( 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. + expected: Optional: the newest generation as the caller observed it before it + read the dataset (``observe``). If another generation is the newest now, + or the same one at another snapshot version (its writer released it, or a + writer took the lease meanwhile), nothing is claimed. Returns: The verified lease for this process. Raises: + LeaseChangedError: If ``expected`` is not what the dataset's newest + generation is now. LeaseBusyError: If another claim prevents acquisition. LeaseError: If the claim or its state cannot be verified. TimeoutError: If the generation lookup before the claim (a listing of the @@ -376,6 +448,13 @@ def acquire( leaves the generation held until it is cleared. """ generation, latest = _newest(client, project_id, dataset) + if expected is not None and ( + generation != expected.generation + or (None if latest is None else str(latest.version_id)) != expected.version + ): + raise LeaseChangedError( + project_id, dataset, "" if latest is None else latest.resource_id + ) if latest is not None: state = _state(latest, _key(latest)) if not state.released: diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index 0503262ed..ba367cf0d 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -1129,6 +1129,17 @@ def hold_lease(self, check: WriterLease) -> None: ) self._lease_check = check + def claim_lease(self) -> None: + """Claim the attached writer lease now, as a first write would (ITL-1900); + nothing when no lease is attached. + + Raises: + LeaseBusyError: If another writer holds the dataset. + LeaseError: If the lease cannot be claimed or verified. + """ + if (check := self._lease_check) is not None: + check() + def let_go_of_lease(self, check: WriterLease) -> None: """Stop writing under the lease ``hold_lease`` was given ``check`` for. @@ -1139,7 +1150,9 @@ def let_go_of_lease(self, check: WriterLease) -> None: self._lease_check = None def _require_lease(self) -> WriterLease: - """Require an attached writer lease and verify it at its first use. + """Require an attached writer lease; it is claimed by the write's first create + or append (``_claim``), so a write that sends nothing claims nothing + (ITL-1900). 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 @@ -1148,7 +1161,6 @@ def _require_lease(self) -> WriterLease: 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: @@ -1158,9 +1170,20 @@ def _require_lease(self) -> WriterLease: "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 _claim(self) -> None: + """Claim the attached lease, or verify it, before a create or an append. + + Raises: + LeaseBusyError: If another writer holds the dataset, or wrote it since the + run observed it (``LeaseChangedError``); nothing is written. + LeaseError: If the lease is no longer held (``spiraldb_lease.check``). + """ + check = self._lease_check + assert check is not None # required by ``write`` before + check() + def _create_or_open(self, table_name: str) -> tuple[_KeyedTable, bool]: """The table at a computed name, created now if absent. @@ -1312,7 +1335,8 @@ def write(self, table_name: str, records: pa.Table) -> None: """ path = self._path_of(table_name) context = _one_data_context(records) - # Before anything is created or written: one writer per dataset (ITL-1844). + # One writer per dataset (ITL-1844): the lease is required now and claimed + # by the first create or append (ITL-1900). lease = self._require_lease() with lease.lock: self._write(table_name, path, context, records) @@ -1359,7 +1383,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 claims nothing + self._claim() self._forget_opened(table_name) self._append(opened.table, found, encoded) @@ -1391,7 +1416,8 @@ 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 claimed + self._claim() self._forget_opened(table_name) table, created = self._create_or_open(table_name) if created and seen == ("none", None) and seen_record is None: diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index 2c03e53d8..43bf1fc5a 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -1,13 +1,25 @@ """The writer leases a job run holds on the writable SpiralDB databases it writes -(ITL-1844). +(ITL-1844, ITL-1900). 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``). +takes the writer lease of a writable dataset it may write (``database_writes``) lazily, +at its first write to the dataset, and releases it when the run ends, also when it +fails. A run that writes nothing takes no lease. + +Before it checks a source or reads anything, the run observes the dataset's newest lease +generation (``spiraldb_lease.observe``: one listing and one open, no state read). At its +first write it claims the lease only if that generation is still the newest, at the same +snapshot version: otherwise another writer took or released a lease while the run read +the dataset, and the run is refused with nothing written +(``spiraldb_lease.LeaseChangedError``). So what a run decided from its reads is what it +would have decided holding the lease from its start. A second writer is refused at its +first write (``LeaseBusyError``), before anything is written; it may compute before. A +node that delivers side effects reads its log without the lease and claims it just +before its first delivery (``SpiralDBRunLookupProtocol.spiral_claim_writer_lease``): +the claim's check of the observed generation is what makes that read current, so no +delivery follows a read another writer has made out of date. 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 @@ -17,6 +29,7 @@ from __future__ import annotations import contextlib +import os import threading from collections.abc import Callable, Iterable, Iterator from typing import TYPE_CHECKING, Any @@ -58,18 +71,25 @@ def writable_connectors(databases: Iterable[object]) -> list[SpiralDBConnector]: @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. + ``databases`` from the body's first write to each dataset (ITL-1900). + + On entry, each dataset's newest lease generation is observed (one listing and one + open; nothing is read from the lease). A dataset's lease is acquired at the body's + first write to it (a create or an append; a side-effect node's claim before its + first delivery), only if the generation and its snapshot version are still those + observed: otherwise ``LeaseChangedError``, since another writer may have written + what the body read. A body that writes nothing acquires nothing. Each acquired 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. A body that failed because a claim was refused raises that + refusal, whichever error wrapped it on the way (a node's commit), with a note + naming that error. Args: databases: The databases the run may write. Nothing happens when none is a @@ -77,51 +97,140 @@ def database_writes(databases: Iterable[object], *, owner: str) -> Iterator[None owner: Who holds the leases, shown to a refused second writer. Raises: - LeaseBusyError: If another writer holds one of the datasets; nothing of the - body ran. + LeaseBusyError: If another writer holds a dataset at the body's first write to + it, or wrote it since the observation (``LeaseChangedError``); nothing was + written by that write. 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). + Exception: As ``spiraldb_lease.observe``, if an observation fails; nothing of + the body ran. """ 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 + lazies: list[_LazyLease] = [] 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) + lazy = _LazyLease(connectors[0], owner) + lazies.append(lazy) + held.append((holding, lazy.writer, lazy.release)) 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) + tables.hold_lease(lazy.writer) except BaseException as error: _release_all(held, error) raise try: yield except BaseException as error: - _release_all(held, error) - raise + refused = _refusal_behind(error, lazies) + _release_all(held, error if refused is None else refused) + if refused is None: + raise + # The run stopped because a first write was refused its lease; whichever route + # wrapped the refusal (a node's commit, a flush), the refusal is what the + # caller sees (ITL-1900). + refused.add_note(f"The run stopped with: {type(error).__name__}: {error}") + raise refused from None _release_all(held, None) +def _refusal_behind( + error: BaseException, lazies: list[_LazyLease] +) -> spiraldb_lease.LeaseBusyError | None: + """The claim refusal of one of ``lazies`` that ``error`` is or was raised from, if + any; never for an interruption.""" + if not isinstance(error, Exception): + return None + refusals = [lazy.refused for lazy in lazies if lazy.refused is not None] + seen: list[BaseException] = [] + current: BaseException | None = error + while current is not None and not any(current is s for s in seen): + if any(current is r for r in refusals): + assert isinstance(current, spiraldb_lease.LeaseBusyError) + return current + seen.append(current) + current = current.__cause__ or current.__context__ + return None + + +class _LazyLease: + """A dataset's writer lease, claimed at the run's first write (ITL-1900). + + Made when the run starts: it observes the dataset's newest lease generation then + (``spiraldb_lease.observe``). The first call of ``writer`` (the first write, or a + side-effect node's claim) acquires the lease, only if that generation is unchanged, + and verifies it; later calls verify it once more, at the first write after the + claim, as an attached lease always was. + + Args: + connector: A writable connector of the dataset. + owner: Who holds the lease, shown to a refused second writer. + + Raises: + Exception: As ``spiraldb_lease.observe``, if the observation fails. + """ + + def __init__(self, connector: SpiralDBConnector, owner: str) -> None: + client, project_id, dataset = connector._writer_lease_target() # pyright: ignore[reportPrivateUsage] # the lease is taken by this module only + self._client: Any = client # pyright: ignore[reportExplicitAny] # the SDK client + self._project_id: str = project_id + self._dataset: str = dataset + self._owner: str = owner + self._pid: int = os.getpid() + self._observed: spiraldb_lease.Observed = spiraldb_lease.observe( + client, project_id, dataset + ) + self._lease: spiraldb_lease.Lease | None = None + self._checked: bool = False + # The refusal of the claim, if it was refused: nothing was written then. + self.refused: spiraldb_lease.LeaseBusyError | None = None + self.writer: WriterLease = WriterLease(self._claim) + + def _claim(self) -> None: + """Acquire the lease on first use, then verify it once.""" + require_same_process(self._pid) + # The run's lock: a racing first write on another thread waits for this one's + # claim, so the run takes one lease. + with self.writer.lock: + if self._lease is None: + + def claimed(lease: spiraldb_lease.Lease) -> None: + self._lease = lease + + try: + _ = spiraldb_lease.acquire( + self._client, + self._project_id, + self._dataset, + owner=self._owner, + on_claim=claimed, + expected=self._observed, + ) + except spiraldb_lease.LeaseBusyError as refusal: + self.refused = refusal + raise + if not self._checked: + assert self._lease is not None + spiraldb_lease.check(self._client, self._lease) + self._checked = True + + def release(self) -> None: + """Release the lease if it was claimed.""" + if self._lease is not None: + spiraldb_lease.release(self._client, self._lease) + + def take_lease( connector: SpiralDBConnector, owner: str, diff --git a/src/orcapod/protocols/spiraldb_run.py b/src/orcapod/protocols/spiraldb_run.py index a69ff0e78..f6ae49642 100644 --- a/src/orcapod/protocols/spiraldb_run.py +++ b/src/orcapod/protocols/spiraldb_run.py @@ -20,6 +20,12 @@ def spiral_completion_lookup( """Return an execution-scoped lookup for a writable SpiralDB invocation log.""" ... + def spiral_claim_writer_lease(self) -> None: + """Claim the writer lease a run attached to this database now, as its first + write would (ITL-1900): a node that delivers side effects claims before it + decides what to deliver. Nothing without an attached lease.""" + ... + @runtime_checkable class InOrderResultFlushProtocol(Protocol): diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 1c1beb521..9579abaf6 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -422,6 +422,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. @@ -449,6 +450,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 + lease's claim, ITL-1900); not called for a row already delivered. Returns: ``(tag, data)`` to emit downstream, or ``None`` to drop the row. @@ -480,6 +483,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, @@ -1311,11 +1317,22 @@ def _deliver_rows( pipeline_database=self._pipeline_database, table_path=self._table_path, completion_lookup=lookup, + before_delivery=self._claim_writer_lease, ) if result is not None: results.append(result) return results + def _claim_writer_lease(self) -> None: + """Claim the run's writer lease of a writable SpiralDB invocation log before a + delivery (ITL-1900). The log is read before the claim; the claim is refused if + another writer wrote the dataset since the run observed it, before any of the + run's reads, so a delivery is decided from what the store holds. A run with + nothing to deliver claims nothing.""" + database = self._pipeline_database + if isinstance(database, SpiralDBRunLookupProtocol): + database.spiral_claim_writer_lease() + def _completion_lookup(self) -> Callable[[bytes], bool] | None: """Index a writable SpiralDB invocation log for this execution.""" if not self._pod.pod_config.track_completion or self._table_path is None: @@ -1583,6 +1600,7 @@ async def process_one(tag: TagProtocol, data: DataProtocol) -> None: pipeline_database=self._pipeline_database, table_path=self._table_path, completion_lookup=lookup, + before_delivery=self._claim_writer_lease, ) if result is not None: async with send_lock: diff --git a/tests/test_databases/test_spiraldb_lazy_lease.py b/tests/test_databases/test_spiraldb_lazy_lease.py new file mode 100644 index 000000000..4f169e6f2 --- /dev/null +++ b/tests/test_databases/test_spiraldb_lazy_lease.py @@ -0,0 +1,499 @@ +"""The writer lease taken at the first write (ITL-1900), on the fake SDK. + +A run observes each leased dataset's newest lease generation when its write scope +opens, and claims the lease at its first write to that dataset (a side-effect node: +before it reads its invocation log). The claim is refused when the generation moved +since the observation (``LeaseChangedError``) or is held (``LeaseBusyError``), with +nothing written. A run that writes nothing takes no lease. +""" + +from __future__ import annotations + +import asyncio +import threading +import time +from collections.abc import Callable +from typing import Any + +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators import SelectDataColumns +from orcapod.databases import ConnectorArrowDatabase, SpiralDBConnector +from orcapod.databases import spiraldb_lease, spiraldb_write_scope +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.invocation import InvocationContext +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.side_effects import 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] + _database, # pyright: ignore[reportPrivateUsage] + _job, # pyright: ignore[reportPrivateUsage] + _lease_tables, # pyright: ignore[reportPrivateUsage] + _rows, # pyright: ignore[reportPrivateUsage] + _run, # pyright: ignore[reportPrivateUsage] + calls, + combine, + delivered, + root, # noqa: F401 # pyright: ignore[reportUnusedImport] # the fixture +) + + +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 and not is_spiral_lease_table_name(t["name"]) + } + + +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"], + ) + + +@pytest.fixture +def acquisitions(monkeypatch: pytest.MonkeyPatch) -> list[str]: + """The datasets of every lease acquisition.""" + seen: list[str] = [] + real = spiraldb_lease.acquire + + def counted(client: Any, project_id: str, dataset: str, *a: Any, **k: Any) -> Any: + seen.append(dataset) + return real(client, project_id, dataset, *a, **k) + + monkeypatch.setattr(spiraldb_lease, "acquire", counted) + return seen + + +def _another_writer_inside_the_window( + monkeypatch: pytest.MonkeyPatch, dataset: str = "d" +) -> list[None]: + """After the run's first observation of ``dataset``, another writer takes and + releases its lease: the generation the run observed is no longer the newest.""" + real = spiraldb_lease.observe + done: list[None] = [] + + def observe_then_write(client: Any, project_id: str, observed: str) -> Any: + result = real(client, project_id, observed) + if observed == dataset and not done: + done.append(None) + _, release = take_lease( + SpiralDBConnector("p", dataset, writable=True), "writer A" + ) + release() + return result + + monkeypatch.setattr(spiraldb_lease, "observe", observe_then_write) + return done + + +# --------------------------------------------- another writer inside the window + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ENTRIES) +def test_a_writer_releasing_inside_the_window_refuses_the_first_write( + monkeypatch: pytest.MonkeyPatch, entry: str +) -> None: + """Writer A takes and releases the lease after this run observed the dataset: the + run is refused at its first write, with nothing written, computed or delivered.""" + _ = _job(_database()).run() + calls.clear() + delivered.clear() + before = _versions() + leases = _lease_tables() + done = _another_writer_inside_the_window(monkeypatch) + job = _job(_database(), table=_rows(4)) + with pytest.raises(spiraldb_lease.LeaseChangedError, match="Run again"): + _ = _run(job, entry) + assert done + assert _versions() == before + assert calls == [] and delivered == [] + # Writer A's generation, and no claim of this run's. + assert len(_lease_tables()) == len(leases) + 1 + # Run again: the run goes ahead. + monkeypatch.undo() + _ = _run(job, entry) + assert calls == [(4, 8)] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ENTRIES) +def test_a_lease_held_from_start_to_claim_is_the_busy_refusal(entry: str) -> None: + """A generation held when the run starts and still held at its first write gives + the busy refusal (not the changed one), with nothing written.""" + _ = _job(_database()).run() + before = _versions() + _, release = take_lease(SpiralDBConnector("p", "d", writable=True), "writer A") + try: + with pytest.raises(spiraldb_lease.LeaseBusyError, match="writer A") as raised: + _ = _run(_job(_database(), table=_rows(4)), entry) + assert not isinstance(raised.value, spiraldb_lease.LeaseChangedError) + finally: + release() + assert _versions() == before + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ENTRIES) +def test_an_unchanged_generation_stores_what_an_eager_lease_stores( + monkeypatch: pytest.MonkeyPatch, entry: str +) -> None: + """With nobody else writing, the run's stored tables equal those of a run that + took its lease when its scope opened: here on dataset ``e``, claimed eagerly.""" + real_init = spiraldb_write_scope._LazyLease.__init__ # pyright: ignore[reportPrivateUsage] + + def eager_on_e(self: Any, connector: Any, owner: str) -> None: + real_init(self, connector, owner) + if self._dataset == "e": # pyright: ignore[reportPrivateUsage] + self._claim() + + monkeypatch.setattr(spiraldb_write_scope._LazyLease, "__init__", eager_on_e) # pyright: ignore[reportPrivateUsage] + lazy, eager = _database("d"), _database("e") + for table in (_rows(), _rows(4)): + _ = _run(_job(lazy, table=table), entry) + _ = _run(_job(eager, table=table), entry) + _ = _run(_job(lazy, table=_rows(4), cache_mode=CacheMode.REPLAY), entry) + _ = _run(_job(eager, table=_rows(4), cache_mode=CacheMode.REPLAY), entry) + paths = sorted(lazy.list_table_paths()) + assert paths == sorted(eager.list_table_paths()) + for path in paths: + on_lazy, on_eager = lazy.get_all_records(path), eager.get_all_records(path) + assert on_lazy is not None and on_eager is not None, path + assert on_lazy.schema == on_eager.schema, path + assert _comparable(on_lazy) == _comparable(on_eager), path + + +# ------------------------------------------------------- side-effect deliveries + + +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} + + +SIDE_EFFECT_ENTRIES = ["sync", "async orchestrator", "run_async", "node run"] + + +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) + + +def _recorded(monkeypatch: pytest.MonkeyPatch) -> list[str]: + """The run's observations, claims, reads of database tables and deliveries, in + order.""" + events = EVENTS + events.clear() + real_observe, real_acquire = spiraldb_lease.observe, spiraldb_lease.acquire + real_scan = fake.FakeKeyedTable.scan + + def observe(*args: Any, **kwargs: Any) -> Any: + events.append("observe") + return real_observe(*args, **kwargs) + + def acquire(*args: Any, **kwargs: Any) -> Any: + events.append("claim") + return real_acquire(*args, **kwargs) + + def scan(table: fake.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any: + if not is_spiral_lease_table_name(table._table["name"]): # pyright: ignore[reportPrivateUsage] + events.append("read") + return real_scan(table, *args, **kwargs) + + monkeypatch.setattr(spiraldb_lease, "observe", observe) + monkeypatch.setattr(spiraldb_lease, "acquire", acquire) + monkeypatch.setattr(fake.FakeKeyedTable, "scan", scan) + return events + + +@pytest.mark.usefixtures("root") +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +@pytest.mark.parametrize("kind", SIDE_EFFECTS) +@pytest.mark.parametrize("entry", SIDE_EFFECT_ENTRIES) +def test_a_side_effect_node_claims_just_before_its_first_delivery( + monkeypatch: pytest.MonkeyPatch, kind: str, entry: str +) -> None: + """The run observes the dataset before any read of it; a side-effect node reads + its log, then claims the lease just before its first delivery, and delivers each + new row once. With nothing to deliver it claims nothing.""" + build = SIDE_EFFECTS[kind] + _run_side_effect(build(_database(), 3), entry) + assert sorted(delivered) == [1, 2, 3] + delivered.clear() + events = _recorded(monkeypatch) + _run_side_effect(build(_database(), 4), entry) + assert sorted(delivered) == [4] + assert events[0] == "observe", events + assert "read" in events + assert events.count("claim") == 1, events + assert events.index("claim") < events.index("deliver"), events + assert events.count("deliver") == 1, events + # A fresh job with nothing new to deliver reads its log and claims nothing. + events.clear() + _run_side_effect(build(_database(), 4), entry) + assert events[0] == "observe" and "read" in events, events + assert "claim" not in events and "deliver" not in events, events + + +@pytest.mark.usefixtures("root") +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +@pytest.mark.parametrize("kind", SIDE_EFFECTS) +@pytest.mark.parametrize("entry", SIDE_EFFECT_ENTRIES) +def test_a_side_effect_node_never_delivers_when_another_writer_acts_in_the_window( + monkeypatch: pytest.MonkeyPatch, kind: str, entry: str +) -> None: + """Another writer takes and releases the lease after the run observed the + dataset: the side-effect node read its log before that, so its claim is refused + and it delivers nothing.""" + build = SIDE_EFFECTS[kind] + _run_side_effect(build(_database(), 3), entry) + delivered.clear() + before = _versions() + _ = _another_writer_inside_the_window(monkeypatch) + with pytest.raises(spiraldb_lease.LeaseChangedError): + _run_side_effect(build(_database(), 4), entry) + assert delivered == [] + assert _versions() == before + + +# ---------------------------------------------------------------- every route + + +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: + 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: + 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: + 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, +} + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("route", ROUTES) +@pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) +def test_every_route_is_refused_at_its_first_write(route: str, entry: str) -> None: + """Each kind of table a run writes, on a dataset another writer holds: the run is + refused at its first write there, with nothing written to that dataset.""" + _, release = take_lease(SpiralDBConnector("p", "d", writable=True), "writer A") + try: + with pytest.raises(spiraldb_lease.LeaseBusyError, match="writer A"): + _ = _run(ROUTES[route](_database()), entry) + finally: + release() + assert _versions() == {} + assert delivered == [] + _ = _run(ROUTES[route](_database()), entry) + assert _versions() != {} + + +@pytest.mark.usefixtures("root") +def test_node_runs_are_refused_at_their_first_write() -> None: + """``node.run()`` claims at the first write too, also for a side-effect node.""" + for route in ("job tables", "side-effect log", "operator cache"): + job = ROUTES[route](_database()) + label = {"job tables": "sink", "side-effect log": "sink"}.get(route, "select") + _, release = take_lease(SpiralDBConnector("p", "d", writable=True), "A") + try: + with pytest.raises(spiraldb_lease.LeaseBusyError): + _ = job.nodes[label].run() + finally: + release() + assert _versions() == {}, route + assert delivered == [], route + + +# ------------------------------------------------------------ runs that write none + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ENTRIES) +def test_a_run_that_writes_nothing_takes_no_lease( + acquisitions: list[str], entry: str +) -> None: + """A held rerun, a REPLAY run and a load-only run write nothing and acquire no + lease; they only observe the generation.""" + _ = _run(_job(_database()), entry) + _ = _run(_job(_database(), cache_mode=CacheMode.REPLAY), entry) + acquisitions.clear() + leases, before = _lease_tables(), _versions() + job = _job(_database()) + _ = _run(job, entry) + _ = _run(job, entry) # held + _ = _run(_job(_database(), cache_mode=CacheMode.REPLAY), entry) + _ = _run(_job(_database()), entry, load_only=True) + assert acquisitions == [] + assert _lease_tables() == leases + assert _versions() == before + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) +def test_a_run_failing_before_any_write_leaves_no_lease(entry: str) -> None: + @function_pod(output_keys="z") + def boom(x: int) -> int: + raise RuntimeError("boom") + + job = PipelineJob(name=JOB, database=_database()) + with job: + 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) + assert _lease_tables() == [] + + +# ------------------------------------------------------------------ racing claims + + +def _slow_acquire(monkeypatch: pytest.MonkeyPatch) -> list[None]: + """Acquisitions that take a while, so racing claims overlap.""" + seen: list[None] = [] + real = spiraldb_lease.acquire + + def slow(*args: Any, **kwargs: Any) -> Any: + seen.append(None) + time.sleep(0.05) + return real(*args, **kwargs) + + monkeypatch.setattr(spiraldb_lease, "acquire", slow) + return seen + + +@pytest.mark.usefixtures("root") +def test_racing_first_writes_from_threads_take_one_lease( + monkeypatch: pytest.MonkeyPatch, +) -> None: + seen = _slow_acquire(monkeypatch) + databases = [_database() for _ in range(4)] + with database_writes(databases, owner="test"): + start = threading.Barrier(len(databases)) + errors: list[BaseException] = [] + + def claim(database: ConnectorArrowDatabase) -> None: + try: + _ = start.wait() + database.spiral_claim_writer_lease() + except BaseException as exc: # pragma: no cover - reported below + errors.append(exc) + + threads = [threading.Thread(target=claim, args=(d,)) for d in databases] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert errors == [] + assert len(seen) == 1 + assert len(_lease_tables()) == 1 + + +@pytest.mark.usefixtures("root") +def test_racing_first_writes_from_tasks_take_one_lease( + monkeypatch: pytest.MonkeyPatch, +) -> None: + seen = _slow_acquire(monkeypatch) + databases = [_database() for _ in range(4)] + + async def race() -> None: + _ = await asyncio.gather( + *(asyncio.to_thread(d.spiral_claim_writer_lease) for d in databases) + ) + + with database_writes(databases, owner="test"): + asyncio.run(race()) + assert len(seen) == 1 + assert len(_lease_tables()) == 1 diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index ceee14ebf..8eacf6de6 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -1867,19 +1867,23 @@ 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 + (a writer lease generation's are the lease's, claimed at the first write).""" counts = {"names": 0, "ids": 0, "key_reads": 0} keyed_table = fake.FakeClient.keyed_table keyed_table_by_id = fake.FakeClient.keyed_table_by_id scan = fake.FakeKeyedTable.scan def open_by_name(self: Any, *args: Any, **kwargs: Any) -> Any: - counts["names"] += 1 + if not is_spiral_lease_table_name(args[2]): + counts["names"] += 1 return keyed_table(self, *args, **kwargs) def open_by_id(self: Any, *args: Any, **kwargs: Any) -> Any: - counts["ids"] += 1 - return keyed_table_by_id(self, *args, **kwargs) + table = keyed_table_by_id(self, *args, **kwargs) + if not is_spiral_lease_table_name(table._table["name"]): + counts["ids"] += 1 + return table def counted_scan(self: Any, *args: Any, **kwargs: Any) -> Any: if args and kwargs.get("limit") is None: @@ -1907,9 +1911,9 @@ def test_flush_reuses_keys_and_opens_by_id_after_resolving_the_name( _add(db, rows(["r2", "r3"], offset=2)) assert counts == {"names": 1, "ids": 0, "key_reads": 1} db.flush() - assert counts == {"names": 1, "ids": 2, "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": 3, "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)) == [ diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 9051bfaf4..bcae18123 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -13,7 +13,7 @@ import json import warnings import weakref -from collections.abc import Callable, Iterator +from collections.abc import Callable, Iterable, Iterator from pathlib import Path from typing import Any, cast @@ -269,7 +269,9 @@ def test_a_separate_result_database_is_stored_as_on_delta( _same_tables(spiral_db, delta) _same_tables(results, delta_results) assert len(_lease_tables("d")) == LEASES[entry] - assert len(_lease_tables("r")) == LEASES[entry] + # The lease is taken at a database's first write (ITL-1900): in node runs, only + # the function's node writes results. + assert len(_lease_tables("r")) == 1 else: on_delta = sorted( [*delta.list_table_paths(), *delta_results.list_table_paths()] @@ -458,13 +460,14 @@ def test_a_loaded_job_reads_and_load_only_runs_take_no_lease(root: Path) -> None @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.""" + the lease of the cache's database, once, at that write (ITL-1900); it writes no + node's table.""" 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] + assert len(_lease_tables()) == 2 # the first run's, then the cache write's for path, rows in before.items(): now = spiral_db.get_all_records(path) assert now is not None and rows is not None @@ -609,9 +612,12 @@ def _held_by_another_writer(dataset: str = "d") -> Callable[[], None]: @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_a_second_writer_is_refused_at_its_first_write( entry: str, load_only: bool ) -> None: + """The run claims the lease at its first write (ITL-1900): here the cached source + writing its cache when it is checked. It is refused there, with nothing written, + computed or delivered.""" release = _held_by_another_writer() job = _job(_database()) checks = _count_source_checks(job) @@ -619,8 +625,8 @@ def test_a_second_writer_is_refused_before_anything( _ = _run(job, entry, load_only=load_only) assert _database_tables() == [] assert calls == [] and delivered == [] - # Refused before any source was checked (a cached source writes its cache then). - assert checks == [] + # Refused at the source check, the cached source's first write. + assert checks == [None] # Once the other writer releases, the run goes ahead. release() if not load_only: @@ -631,11 +637,15 @@ def test_a_second_writer_is_refused_before_anything( @pytest.mark.usefixtures("root") def test_a_second_writer_on_the_result_database_is_refused() -> None: + """Each dataset's lease is taken at its first write (ITL-1900): the cached source + writes its cache on its own dataset, and the run is refused at its first write to + the result database, with nothing written there.""" 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") == [] + assert [p[-1] for p in _database().list_table_paths()] == ["sdb_v2"] + assert _database_tables("r") == [] # The lease the run took on its own database was released. _, own = take_lease(SpiralDBConnector("p", "d", writable=True), "check") own() @@ -773,7 +783,8 @@ def test_a_job_run_on_a_database_raises_no_keyed_table_deprecation(entry: str) - 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] + # The second run writes nothing, so takes no lease (ITL-1900). + assert len(_lease_tables("d")) == LEASES[entry] @pytest.mark.usefixtures("root") @@ -833,7 +844,14 @@ def failing_once() -> None: _ = job.run() # The retry wrote the old attachment's operator cache, under a lease of its dataset. assert [p[-1] for p in _database("a").list_table_paths()] == ["odb_v3"] - assert len(_lease_tables("a")) == 2 + # The failed flush wrote nothing, so took no lease (ITL-1900); the retry took one. + assert len(_lease_tables("a")) == 1 + + +def _claim(databases: Iterable[Any]) -> None: + """Claim each database's writer lease, as its first write would (ITL-1900).""" + for database in databases: + database.spiral_claim_writer_lease() def _wrapped(database: Any) -> ExtensionAwareDatabase: @@ -891,7 +909,7 @@ def test_a_job_on_a_wrapped_database_holds_its_lease_and_stores_as_on_delta( _same_tables(spiral_db, delta) release = _held_by_another_writer() with pytest.raises(spiraldb_lease.LeaseBusyError): - _ = _job(_wrapped(_database())).run() + _ = _job(_wrapped(_database()), table=_rows(4)).run() release() @@ -931,6 +949,10 @@ def test_connectors_reaching_one_service_share_one_lease(given: str) -> None: 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"): + # The lease is taken at the first write (ITL-1900): claim it from both. + assert _lease_tables() == [] + for database in databases[:2]: + database.spiral_claim_writer_lease() assert len(_lease_tables()) == 1 held = [c._writable_tables()._lease_check for c in (plain, addressed)] # pyright: ignore[reportPrivateUsage, reportOptionalMemberAccess] assert held[0] is not None and held[0] is held[1] @@ -971,7 +993,10 @@ def counted(table: fake.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any: record_id_column="__record_id", flush=True, ) - assert len(reads) == 1 + # The lease is claimed at the first write (ITL-1900), inside this count: + # the acquisition reads the previous generation's state (none at first) + # and verifies its claim, then the first write checks the claim once. + assert len(reads) == 2 + count with database_writes([first, second], owner="no writes"): reads.clear() @@ -1055,13 +1080,14 @@ def interrupt_first(client: Any, lease: Any) -> None: if body_fails: with pytest.raises(KeyboardInterrupt) as raised: with database_writes(databases, owner="test"): + _claim(databases) 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 + _claim(databases) monkeypatch.undo() # The lease released after the interruption (the first one taken, released last # in reverse order) can be taken again. @@ -1272,9 +1298,10 @@ def fail_then_interrupt(client: Any, lease: Any) -> None: raise KeyboardInterrupt monkeypatch.setattr(spiraldb_lease, "release", fail_then_interrupt) + databases = [_database("d"), _database("r")] with pytest.raises(KeyboardInterrupt) as raised: - with database_writes([_database("d"), _database("r")], owner="test"): - pass + with database_writes(databases, owner="test"): + _claim(databases) assert len(seen) == 2 assert any("first release failed" in note for note in raised.value.__notes__) @@ -1479,23 +1506,31 @@ def add(x: int, y: int) -> int: @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).""" + """A run refused with ``LeaseBusyError`` keeps the last run's save state (review of + de39bbc4c). The lease is claimed at the first write (ITL-1900), inside the run, so + the refusal is a failure of a started run: the advisory row counts (ITL-1043) are + no longer certain and are left out, as after any failed run; the rest is kept. A + held rerun writes nothing and takes no lease, so the operator node is attached + to another dataset, which the run writes and another writer holds.""" 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() + kept = json.loads(before.read_text())["run"] + assert kept.pop("expected_rows") + delivered.clear() + release = _held_by_another_writer("x") try: with pytest.raises(spiraldb_lease.LeaseBusyError): _ = 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) @@ -1535,7 +1570,7 @@ def test_an_interruption_once_the_lease_is_taken_still_releases_it( """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 + real = spiraldb_lease.acquire taken: list[None] = [] def take_then_interrupt(*args: Any, **kwargs: Any) -> Any: @@ -1545,11 +1580,11 @@ def take_then_interrupt(*args: Any, **kwargs: Any) -> Any: raise KeyboardInterrupt return result - monkeypatch.setattr(spiraldb_write_scope, "take_lease", take_then_interrupt) + monkeypatch.setattr(spiraldb_lease, "acquire", take_then_interrupt) databases = [_database(dataset) for dataset in datasets] with pytest.raises(KeyboardInterrupt): with database_writes(databases, owner="interrupted"): - pass + _claim(databases) monkeypatch.undo() for dataset in datasets: _, release = take_lease(SpiralDBConnector("p", dataset, writable=True), "after") @@ -1577,8 +1612,10 @@ def fail_then_interrupt(client: Any, lease: Any) -> None: monkeypatch.setattr(spiraldb_lease, "release", fail_then_interrupt) stopped = body("body stopped") + databases = [_database("d"), _database("r")] with pytest.raises(KeyboardInterrupt) as raised: - with database_writes([_database("d"), _database("r")], owner="test"): + with database_writes(databases, owner="test"): + _claim(databases) raise stopped assert raised.value is released assert raised.value.__cause__ is stopped From e82c9f276b28b4b36340ca4812347c95549ef471 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 23:39:02 -0800 Subject: [PATCH 17/46] perf(spiraldb): skip a lease verification made within 60 seconds (ITL-1901) The first write after a lease's acquisition verifies the lease again only when RECENTLY_VERIFIED_SECONDS (60 s) or more passed since the acquisition verified its claim; a lease claimed at the first write is so verified once. Interim until ITL-1901 decides how a lease is verified. Tests drive the write scope's clock. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1899.md | 2 + docs/concepts/spiraldb-database.md | 4 +- src/orcapod/databases/spiraldb_write_scope.py | 45 ++++++++- .../test_spiraldb_lazy_lease.py | 91 +++++++++++++++++++ .../test_spiraldb_writable_runs.py | 5 +- 5 files changed, 139 insertions(+), 8 deletions(-) diff --git a/changelog.d/ITL-1899.md b/changelog.d/ITL-1899.md index 5858ec025..690937aa5 100644 --- a/changelog.d/ITL-1899.md +++ b/changelog.d/ITL-1899.md @@ -15,6 +15,8 @@ Rows the run wrote to another dataset before the refusal stay stored. A refusal reached through a node's commit is raised as the lease error itself, with a note naming the commit error. +- A writer lease verified when it was taken is not verified again before the run's + first write unless 60 seconds or more passed since (interim, ITL-1901). - A job saved after a run refused its lease no longer records the advisory stored row counts (`expected_rows`): the refusal now stops a run that has started, as any failed run does. diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index 0c7a464e1..7f1cab80d 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -149,7 +149,9 @@ make the client for that same address, with a sign-in allowed to update the data 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 lease when it takes it, and once more before its first write. +The run verifies each lease when it takes it, and once more before its first write +when 60 seconds or more passed since (a lease taken at the first write is verified +once). This skip is interim, until ITL-1901 settles how a lease is verified. 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. diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index 43bf1fc5a..b05acb9ec 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -31,6 +31,7 @@ import contextlib import os import threading +import time from collections.abc import Callable, Iterable, Iterator from typing import TYPE_CHECKING, Any @@ -68,6 +69,29 @@ def writable_connectors(databases: Iterable[object]) -> list[SpiralDBConnector]: return found +RECENTLY_VERIFIED_SECONDS = 60.0 +"""A lease verified this many seconds ago or less recently is verified again before the +first write after its acquisition; one verified more recently is not (ITL-1901).""" + +_clock: Callable[[], float] = time.monotonic +"""The clock the time since a lease's verification is read from (tests replace it).""" + + +def _verify_unless_recent( + client: Any, lease: spiraldb_lease.Lease, verified_at: float +) -> None: # pyright: ignore[reportExplicitAny] # the SDK client + """Verify ``lease`` before the first write after its acquisition, unless its + acquisition verified it within ``RECENTLY_VERIFIED_SECONDS``. + + Interim (ITL-1901): the acquisition verifies the claim, so a second read of the + lease state moments later finds what it found, and costs a service call. A longer + gap verifies again, as every first write did before. + """ + if _clock() - verified_at < RECENTLY_VERIFIED_SECONDS: + return + spiraldb_lease.check(client, lease) + + @contextlib.contextmanager def database_writes(databases: Iterable[object], *, owner: str) -> Iterator[None]: """Hold the writer lease of every writable SpiralDB database dataset among @@ -170,8 +194,9 @@ class _LazyLease: Made when the run starts: it observes the dataset's newest lease generation then (``spiraldb_lease.observe``). The first call of ``writer`` (the first write, or a side-effect node's claim) acquires the lease, only if that generation is unchanged, - and verifies it; later calls verify it once more, at the first write after the - claim, as an attached lease always was. + and verifies it; the same call verifies it once more before the first write, + unless the acquisition verified it within ``RECENTLY_VERIFIED_SECONDS`` + (ITL-1901). Args: connector: A writable connector of the dataset. @@ -192,6 +217,7 @@ def __init__(self, connector: SpiralDBConnector, owner: str) -> None: client, project_id, dataset ) self._lease: spiraldb_lease.Lease | None = None + self._verified_at: float = 0.0 self._checked: bool = False # The refusal of the claim, if it was refused: nothing was written then. self.refused: spiraldb_lease.LeaseBusyError | None = None @@ -206,7 +232,9 @@ def _claim(self) -> None: if self._lease is None: def claimed(lease: spiraldb_lease.Lease) -> None: + # Called once the acquisition verified the claim. self._lease = lease + self._verified_at = _clock() try: _ = spiraldb_lease.acquire( @@ -222,7 +250,9 @@ def claimed(lease: spiraldb_lease.Lease) -> None: raise if not self._checked: assert self._lease is not None - spiraldb_lease.check(self._client, self._lease) + # Interim (ITL-1901): skipped within RECENTLY_VERIFIED_SECONDS of the + # acquisition's own verification. + _verify_unless_recent(self._client, self._lease, self._verified_at) self._checked = True def release(self) -> None: @@ -248,7 +278,8 @@ def take_lease( propagates. Returns: - ``(check, release)``: verifies the lease on first use; releases it. + ``(check, release)``: verifies the lease on first use, unless the acquisition + verified it within ``RECENTLY_VERIFIED_SECONDS`` (ITL-1901); releases it. Raises: LeaseBusyError: If another writer holds the dataset. @@ -260,13 +291,17 @@ def take_lease( def claimed(lease: spiraldb_lease.Lease) -> None: checked = False lock = threading.Lock() + # Called once the acquisition verified the claim. + verified_at = _clock() def check() -> None: nonlocal checked require_same_process(lease.pid) with lock: if not checked: - spiraldb_lease.check(client, lease) + # Interim (ITL-1901): skipped within RECENTLY_VERIFIED_SECONDS of + # the acquisition's own verification. + _verify_unless_recent(client, lease, verified_at) checked = True def release() -> None: diff --git a/tests/test_databases/test_spiraldb_lazy_lease.py b/tests/test_databases/test_spiraldb_lazy_lease.py index 4f169e6f2..07e2bf8d2 100644 --- a/tests/test_databases/test_spiraldb_lazy_lease.py +++ b/tests/test_databases/test_spiraldb_lazy_lease.py @@ -17,7 +17,10 @@ import pytest +import pyarrow as pa + from orcapod import PipelineJob, function_pod +from orcapod.contexts import get_default_context from orcapod.core.operators import SelectDataColumns from orcapod.databases import ConnectorArrowDatabase, SpiralDBConnector from orcapod.databases import spiraldb_lease, spiraldb_write_scope @@ -497,3 +500,91 @@ async def race() -> None: asyncio.run(race()) assert len(seen) == 1 assert len(_lease_tables()) == 1 + + +# ------------------------------------------- recently verified leases (ITL-1901) + + +def _clock(monkeypatch: pytest.MonkeyPatch, *times: float) -> None: + """The write scope's clock returns ``times`` in turn, then the last one.""" + left = list(times) + + def now() -> float: + return left.pop(0) if len(left) > 1 else left[0] + + monkeypatch.setattr(spiraldb_write_scope, "_clock", now) + + +@pytest.fixture +def verifications(monkeypatch: pytest.MonkeyPatch) -> list[None]: + """Every verification of a lease's claim (the acquisition's included).""" + seen: list[None] = [] + real = spiraldb_lease.check + + def counted(*args: Any, **kwargs: Any) -> Any: + seen.append(None) + return real(*args, **kwargs) + + monkeypatch.setattr(spiraldb_lease, "check", counted) + return seen + + +def _write(database: ConnectorArrowDatabase, key: bytes) -> None: + database.add_records( + ("recent", "rdb_v1"), + pa.table( + { + "__record_id": pa.array([key], pa.large_binary()), + "value": [1], + "__data_context": [get_default_context().context_key], + } + ), + record_id_column="__record_id", + flush=True, + ) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize( + ("elapsed", "expected"), + [ + (0.0, 1), + (59.9, 1), + (spiraldb_write_scope.RECENTLY_VERIFIED_SECONDS, 2), + (61.0, 2), + ], +) +def test_the_first_write_verifies_only_a_lease_not_verified_recently( + monkeypatch: pytest.MonkeyPatch, + verifications: list[None], + elapsed: float, + expected: int, +) -> None: + """The lazy claim verifies the lease when it acquires it; its first write verifies + it again only when 60 seconds or more passed since (ITL-1901).""" + _clock(monkeypatch, 100.0, 100.0 + elapsed) + database = _database() + with database_writes([database], owner="test"): + _write(database, b"a") + _write(database, b"b") + assert len(verifications) == expected + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize(("elapsed", "expected"), [(30.0, 1), (60.0, 2)]) +def test_a_lease_taken_at_once_verifies_at_its_first_write_after_60_seconds( + monkeypatch: pytest.MonkeyPatch, + verifications: list[None], + elapsed: float, + expected: int, +) -> None: + """A lease taken by ``take_lease`` follows the same rule: its first check after + the acquisition reads the lease state only after 60 seconds (ITL-1901).""" + _clock(monkeypatch, 100.0, 100.0 + elapsed) + check, release = take_lease(SpiralDBConnector("p", "d", writable=True), "test") + try: + check.verify() + check.verify() + finally: + release() + assert len(verifications) == expected diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index bcae18123..f8c764056 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -995,8 +995,9 @@ def counted(table: fake.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any: ) # The lease is claimed at the first write (ITL-1900), inside this count: # the acquisition reads the previous generation's state (none at first) - # and verifies its claim, then the first write checks the claim once. - assert len(reads) == 2 + count + # and verifies its claim; the first write does not verify it again so + # soon after (ITL-1901). + assert len(reads) == 1 + count with database_writes([first, second], owner="no writes"): reads.clear() From e5d2956e37f1cdd221eff5bcea84095c01bd67db Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 00:38:09 -0800 Subject: [PATCH 18/46] perf(spiraldb): list a dataset once per run (ITL-1899) The writer lease's observation lists the dataset once when the run's write scope opens; that listing finds the newest generation and becomes the run's catalog. The claim starts from the observed generation (open it, probe the next by name) instead of listing again: a newer generation or snapshot is the LeaseChangedError refusal, as before. The live measurement had shown two to three listings per run, each several pages long on a large dataset. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1899.md | 8 ++- src/orcapod/databases/spiraldb_connector.py | 18 +++++- src/orcapod/databases/spiraldb_lease.py | 63 ++++++++++++++----- src/orcapod/databases/spiraldb_tables.py | 6 ++ src/orcapod/databases/spiraldb_write_scope.py | 2 + .../test_spiraldb_lazy_lease.py | 26 ++++++++ .../test_spiraldb_round_trips.py | 21 +++---- .../test_spiraldb_writable_runs.py | 6 +- 8 files changed, 117 insertions(+), 33 deletions(-) diff --git a/changelog.d/ITL-1899.md b/changelog.d/ITL-1899.md index 690937aa5..b0aaa5623 100644 --- a/changelog.d/ITL-1899.md +++ b/changelog.d/ITL-1899.md @@ -20,8 +20,10 @@ - A job saved after a run refused its lease no longer records the advisory stored row counts (`expected_rows`): the refusal now stops a run that has started, as any failed run does. -- Writable SpiralDB runs make fewer service calls (ITL-1899). The newest writer lease - generation is found from one listing of the dataset. A first run opens no table - that its listing shows absent, and reads back no table it created. A run reads each +- Writable SpiralDB runs make fewer service calls (ITL-1899). A run lists its + dataset once, when it starts: that listing finds the newest writer lease generation + and is the run's view of the dataset's tables, and the lease is claimed from that + generation without listing again. A run opens no table that its listing shows + absent, and reads back no table it created. A run reads each table whole once per batch of writes and keeps what it read under its lease, instead of twice per computed row, and identifies each existing table once. diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index c01c611d3..872778af4 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -609,6 +609,21 @@ def _list_keyed_tables(client: Any, project_id: str, dataset: str) -> dict[str, } +def _list_dataset_for_lease( + client: Any, project_id: str, dataset: str +) -> dict[str, str]: + """Return every table name of the dataset by ID, lease generations included, as + the writer lease lists it. + + Args: + client: A spiral-sdk client. + project_id: The project. + dataset: The dataset. + """ + with _service_call(f"list the writer lease generations of {project_id}/{dataset}"): + return _list_dataset(client, project_id, dataset) + + def _list_lease_generations(client: Any, project_id: str, dataset: str) -> set[str]: """Return the names of the writer lease generations a listing of the dataset shows. @@ -617,8 +632,7 @@ def _list_lease_generations(client: Any, project_id: str, dataset: str) -> set[s project_id: The project. dataset: The dataset. """ - with _service_call(f"list the writer lease generations of {project_id}/{dataset}"): - listed = _list_dataset(client, project_id, dataset) + listed = _list_dataset_for_lease(client, project_id, dataset) return {name for name in listed.values() if is_spiral_lease_table_name(name)} diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py index e48694dc4..cfc118c89 100644 --- a/src/orcapod/databases/spiraldb_lease.py +++ b/src/orcapod/databases/spiraldb_lease.py @@ -11,7 +11,7 @@ import os from collections.abc import Callable -from dataclasses import dataclass +from dataclasses import dataclass, field from datetime import datetime, timezone from typing import Protocol, cast from uuid import uuid4 @@ -21,6 +21,7 @@ from orcapod.databases import spiraldb_connector as sdk from orcapod.databases.store_table_names import ( SPIRAL_LEASE_KEY_PREFIX, + is_spiral_lease_table_name, spiral_lease_key_column, spiral_lease_table_name, ) @@ -180,10 +181,13 @@ class Observed: Attributes: generation: The newest generation's number, 0 when there is none. version: The version of its latest snapshot then; ``None`` without one. + tables: The dataset's other tables, names by table id, as the listing the + observation made showed them: the run's first view of the dataset. """ generation: int version: str | None + tables: dict[str, str] = field(default_factory=dict, compare=False) @dataclass(frozen=True) @@ -216,7 +220,7 @@ def _open( def _newest( - client: _Client, project_id: str, dataset: str + client: _Client, project_id: str, dataset: str, listed: set[str] | None = None ) -> tuple[int, _KeyedTable | None]: """Return the end of the contiguous generation sequence and its latest snapshot. @@ -224,9 +228,11 @@ def _newest( generations from 1. That generation is opened by name, and the next ones are opened by name while they exist, so a listing that lags the service still ends at the newest generation. A listed generation that does not open falls back to the search - by name alone (``_search``). + by name alone (``_search``). ``listed``, when given, holds the generation names of + a listing the caller just made. """ - listed = sdk._list_lease_generations(client, project_id, dataset) + if listed is None: + listed = sdk._list_lease_generations(client, project_id, dataset) start = 0 while spiral_lease_table_name(start + 1) in listed: start += 1 @@ -400,10 +406,34 @@ def observe(client: _Client, project_id: str, dataset: str) -> Observed: dataset: The dataset. Returns: - What was found. + What was found, with the dataset's other tables from the same listing. """ - generation, latest = _newest(client, project_id, dataset) - return Observed(generation, None if latest is None else str(latest.version_id)) + listing = sdk._list_dataset_for_lease(client, project_id, dataset) + generations = {n for n in listing.values() if is_spiral_lease_table_name(n)} + generation, latest = _newest(client, project_id, dataset, generations) + return Observed( + generation, + None if latest is None else str(latest.version_id), + {i: n for i, n in listing.items() if not is_spiral_lease_table_name(n)}, + ) + + +def _observed_still_newest( + client: _Client, project_id: str, dataset: str, expected: Observed +) -> tuple[bool, _KeyedTable | None]: + """Whether the observed generation is still the newest, at the observed version, + with its snapshot now: opened by name, and the next generation probed by name + (no listing). A newer generation is a change, whatever else.""" + latest = None + if expected.generation > 0: + latest = _open(client, project_id, dataset, expected.generation) + if latest is None or str(latest.version_id) != expected.version: + return False, latest + elif expected.version is not None: + return False, None + if _open(client, project_id, dataset, expected.generation + 1) is not None: + return False, latest + return True, latest def acquire( @@ -447,14 +477,19 @@ def acquire( 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 expected is not None and ( - generation != expected.generation - or (None if latest is None else str(latest.version_id)) != expected.version - ): - raise LeaseChangedError( - project_id, dataset, "" if latest is None else latest.resource_id + if expected is None: + generation, latest = _newest(client, project_id, dataset) + else: + # From the observed generation, without listing again: a newer generation, or + # a newer snapshot of it, means another writer took a lease since. + unchanged, latest = _observed_still_newest( + client, project_id, dataset, expected ) + if not unchanged: + raise LeaseChangedError( + project_id, dataset, "" if latest is None else latest.resource_id + ) + generation = expected.generation if latest is not None: state = _state(latest, _key(latest)) if not state.released: diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index ba367cf0d..746f2207f 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -156,6 +156,12 @@ def __call__(self) -> None: """Verify the writer lease on first use.""" self.verify() + def start_catalog(self, names: dict[str, str]) -> None: + """Take a listing of the dataset's tables (names by table id), made when the + run started, as the run's catalog (ITL-1899).""" + with self.lock: + self.catalog = _Catalog(dict(names)) + def forget_reads(self) -> None: """Forget everything the run read (``WriterLease`` attributes): the key index, the catalog, the rows read and what the tables record.""" diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index b05acb9ec..266dbb25a 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -222,6 +222,8 @@ def __init__(self, connector: SpiralDBConnector, owner: str) -> None: # The refusal of the claim, if it was refused: nothing was written then. self.refused: spiraldb_lease.LeaseBusyError | None = None self.writer: WriterLease = WriterLease(self._claim) + # The observation's listing is the run's first view of the dataset. + self.writer.start_catalog(self._observed.tables) def _claim(self) -> None: """Acquire the lease on first use, then verify it once.""" diff --git a/tests/test_databases/test_spiraldb_lazy_lease.py b/tests/test_databases/test_spiraldb_lazy_lease.py index 07e2bf8d2..51c110221 100644 --- a/tests/test_databases/test_spiraldb_lazy_lease.py +++ b/tests/test_databases/test_spiraldb_lazy_lease.py @@ -588,3 +588,29 @@ def test_a_lease_taken_at_once_verifies_at_its_first_write_after_60_seconds( finally: release() assert len(verifications) == expected + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) +def test_a_run_lists_its_dataset_once_when_it_starts( + monkeypatch: pytest.MonkeyPatch, acquisitions: list[str], entry: str +) -> None: + """The observation's listing finds the newest generation and is the run's + catalog; the claim starts from the observed generation without listing again + (ITL-1899).""" + from orcapod.databases import spiraldb_connector + + listings: list[str] = [] + real = spiraldb_connector._list_dataset # pyright: ignore[reportPrivateUsage] + + def counted(client: Any, project: str, dataset: str) -> dict[str, str]: + listings.append(dataset) + return real(client, project, dataset) + + monkeypatch.setattr(spiraldb_connector, "_list_dataset", counted) + for table in (_rows(), _rows(4)): + listings.clear() + acquisitions.clear() + _ = _run(_job(_database(), table=table), entry) + assert acquisitions == ["d"] + assert listings == ["d"] diff --git a/tests/test_databases/test_spiraldb_round_trips.py b/tests/test_databases/test_spiraldb_round_trips.py index 5492ab6a4..a8fb57f1c 100644 --- a/tests/test_databases/test_spiraldb_round_trips.py +++ b/tests/test_databases/test_spiraldb_round_trips.py @@ -118,13 +118,14 @@ def scanned( return scan(table, *args, **kwargs) monkeypatch.setattr(fake.FakeKeyedTable, "scan", scanned) - listing = spiraldb_connector._list_keyed_tables # pyright: ignore[reportPrivateUsage] + # Every listing of a dataset: the lease's observation and the catalog's alike. + listing = spiraldb_connector._list_dataset # pyright: ignore[reportPrivateUsage] def listed(client: Any, project: str, dataset: str) -> dict[str, str]: # pyright: ignore[reportExplicitAny] calls.append(Call("listing", "")) return listing(client, project, dataset) - monkeypatch.setattr(spiraldb_connector, "_list_keyed_tables", listed) + monkeypatch.setattr(spiraldb_connector, "_list_dataset", listed) yield calls @@ -145,17 +146,13 @@ def _first_run(entry: str, calls: list[Call], rows: int = 3) -> None: def test_a_first_run_opens_no_name_its_listing_shows_absent( entry: str, sdk_calls: list[Call] ) -> None: - """After the run lists its dataset, a name the listing does not show is never - opened: 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.""" + """The run lists its dataset once, when it starts (the writer lease's observation), + 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) - listed = next(i for i, c in enumerate(sdk_calls) if c.kind == "listing") - after = sdk_calls[listed:] - assert [c for c in after if c.kind == "open by name"] == [] - # Before the listing: the cached source's first check of its table. - before = [c for c in sdk_calls[:listed] if c.kind == "open by name"] - assert all(not c.ok for c in before) and len(before) <= 2 + assert sdk_calls[0].kind == "listing" + assert [c for c in sdk_calls if c.kind == "open by name"] == [] assert _counts(sdk_calls)["create"] == 5 diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index f8c764056..f20498fff 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -350,14 +350,16 @@ 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 when it starts + (the writer lease's observation) 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() From c482765f67a4d7933d8fe11e658d513308ee6e81 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 00:50:01 -0800 Subject: [PATCH 19/46] fix(spiraldb): address the review of the lazy writer lease (ITL-1899) - The observation falls back to the name search when the dataset listing fails; the claim and its verification are unchanged. - Kept whole reads stay within KEPT_ROWS_BUDGET_BYTES (256 MiB), oldest dropped first; a dropped table is read again. - A function node that takes the invocation context claims the result stores of its pod's nested functions before the function is called. - A claim before a delivery marks the lease checked only when it verified it. - Forgetting the kept reads cannot skip the lease release. - LeaseChangedError and the docs say the check is per dataset and describe the observation (listing, newest open, successor probe). - Tests: one per finding, plus the log-read order, recovery claim and no-write scan count assertions. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1899.md | 12 +- docs/concepts/spiraldb-database.md | 15 +- src/orcapod/core/nodes/function_node.py | 4 + src/orcapod/core/pod_result_databases.py | 39 +++ src/orcapod/databases/spiraldb_lease.py | 29 ++- src/orcapod/databases/spiraldb_tables.py | 25 +- src/orcapod/databases/spiraldb_write_scope.py | 47 ++-- src/orcapod/pipeline/node_run.py | 37 +-- .../test_spiraldb_lazy_lease.py | 230 +++++++++++++++++- .../test_spiraldb_writable_runs.py | 10 +- 10 files changed, 362 insertions(+), 86 deletions(-) create mode 100644 src/orcapod/core/pod_result_databases.py diff --git a/changelog.d/ITL-1899.md b/changelog.d/ITL-1899.md index b0aaa5623..c67088d52 100644 --- a/changelog.d/ITL-1899.md +++ b/changelog.d/ITL-1899.md @@ -2,8 +2,8 @@ - A run on a writable SpiralDB database takes the dataset's writer lease at its first write to the dataset, not when it starts (ITL-1900). When it starts, the run looks - at the dataset's newest lease (one listing and one open, about half a second on the - service). A run that writes nothing (a rerun with nothing new, a `REPLAY` run, a + at the dataset's newest lease (one listing of the dataset, an open of the newest + lease table and a look for the next, about half a second or more on the service). A run that writes nothing (a rerun with nothing new, a `REPLAY` run, a load-only run) takes no lease. A side-effect node (a `SideEffectPod` node, or a function node whose pod takes the invocation context) reads its invocation log without the lease and takes it just before its first delivery or function call; @@ -12,7 +12,8 @@ and nothing delivered: with `LeaseBusyError` when another run holds the lease, and with the new `LeaseChangedError` (a `LeaseBusyError`) when another writer took the lease after the run started, so what the run read may be out of date; run again. - Rows the run wrote to another dataset before the refusal stay stored. A refusal + The check is per dataset: rows the run wrote to another dataset before the refusal + stay stored. A refusal reached through a node's commit is raised as the lease error itself, with a note naming the commit error. - A writer lease verified when it was taken is not verified again before the run's @@ -25,5 +26,6 @@ and is the run's view of the dataset's tables, and the lease is claimed from that generation without listing again. A run opens no table that its listing shows absent, and reads back no table it created. A run reads each - table whole once per batch of writes and keeps what it read under its lease, instead - of twice per computed row, and identifies each existing table once. + table whole once per batch of writes and keeps what it read under its lease (at most + 256 MiB; beyond that the oldest is dropped and read again when needed), instead of + twice per computed row, and identifies each existing table once. diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index 7f1cab80d..3307cf4be 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -47,9 +47,11 @@ whose database and result database are on one dataset takes one lease. The lease is taken at the run's first write, not when the run starts: -- **When the run starts**, it looks at the dataset's newest lease (one listing of the - dataset and one open, about half a second on the service; nothing is read from the - lease). It reads the stored tables as it needs them, with no lease. +- **When the run starts**, it looks at the dataset's newest lease: one listing of the + dataset (several requests for a dataset of many tables), an open of the newest + listed lease table and a look for the next one, about half a second or more on the + service; nothing is read from the lease. The same listing is the run's view of the + dataset's tables. The run reads the stored tables as it needs them, with no lease. - **At its first write** to the dataset (a table created or rows appended), the run takes the lease. A run that writes nothing (a rerun with nothing new, a `REPLAY` run, a load-only run) takes no lease: only the look at the start. @@ -62,9 +64,10 @@ The lease is refused, with nothing written by that write, nothing delivered and function called, in two cases. Another run holds it: `LeaseBusyError`, naming the lease's table id and who holds it. Or another writer took the lease after this run started (and may have written since): `LeaseChangedError`, a `LeaseBusyError`, because -what the run read may be out of date; run again. So what a run decided from its reads -is what the store held when it wrote. Rows the run wrote to another dataset before the -refusal stay stored, under that dataset's lease. The lease is refuse-only: the second +what the run read of that dataset may be out of date; run again. So what a run read of +a dataset is what that dataset held when the run first wrote it. The check is per +dataset: a refused write to one dataset does not undo the run's earlier writes to +another, which stay stored under that dataset's lease. The lease is refuse-only: the second writer does not wait and never takes the lease over, and a lease does not expire. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 02869245d..7a1db19c2 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -122,6 +122,7 @@ ) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.hashing_protocols import IdentityWalkProtocol +from orcapod.core.pod_result_databases import pod_result_databases from orcapod.protocols.spiraldb_run import ( InOrderResultFlushProtocol, SpiralDBRunLookupProtocol, @@ -1636,6 +1637,9 @@ def _claim_writer_leases(self) -> None: for pod in (self._cached_function_pod, self._ephemeral_cached_pod) if pod is not None ) + # The result stores of the pods and data functions it wraps too: they are + # written after the function returns (``pod_result_databases``). + databases.extend(pod_result_databases(self)) for database in databases: if isinstance(database, SpiralDBRunLookupProtocol): database.spiral_claim_writer_lease() diff --git a/src/orcapod/core/pod_result_databases.py b/src/orcapod/core/pod_result_databases.py new file mode 100644 index 000000000..7851254ed --- /dev/null +++ b/src/orcapod/core/pod_result_databases.py @@ -0,0 +1,39 @@ +"""The result databases a function node's own pods write on a cache miss. + +A leaf module, read by the run's write scope (``pipeline.node_run``) and by a function +node that claims its writer leases before its function is called (ITL-1900). +""" + +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 leased. + """ + 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(getattr(pod, "result_database", None)) + 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(getattr(function, "result_database", None)) + function = getattr(function, "_data_function", None) # a wrapper's inner + return found diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py index cfc118c89..33636d6d9 100644 --- a/src/orcapod/databases/spiraldb_lease.py +++ b/src/orcapod/databases/spiraldb_lease.py @@ -148,8 +148,9 @@ class LeaseChangedError(LeaseBusyError): A run reads before it claims the lease, at its first write (ITL-1900): it observed the newest lease generation when it started (``observe``) and claims only if no - writer took or released a lease since, so nothing it read can have changed. The - run is refused at its first write, with nothing written, and is run again. + writer took or released a lease since, so nothing it read of this dataset can have + changed. The write is refused, with nothing written to the dataset by it, and the + run is run again. Attributes: table_id: Immutable ID of the newest generation found at the claim (``""`` @@ -167,9 +168,11 @@ def __init__(self, project_id: str, dataset: str, table_id: str) -> None: self.table_id = table_id LeaseError.__init__( self, - f"Another writer wrote SpiralDB dataset {project_id}/{dataset} while this " - "run was reading it (its writer lease changed since the run started), so " - "what the run read may be out of date. Nothing was written. Run again.", + f"The writer lease of SpiralDB dataset {project_id}/{dataset} changed " + "since this run started reading it: another writer took the lease and may " + "have written the dataset, so what the run read may be out of date. This " + "write was refused and wrote nothing to the dataset (rows the run wrote to " + "other datasets stay stored). Run again.", ) @@ -182,12 +185,13 @@ class Observed: generation: The newest generation's number, 0 when there is none. version: The version of its latest snapshot then; ``None`` without one. tables: The dataset's other tables, names by table id, as the listing the - observation made showed them: the run's first view of the dataset. + observation made showed them: the run's first view of the dataset; + ``None`` when the listing failed and the generation was found by name. """ generation: int version: str | None - tables: dict[str, str] = field(default_factory=dict, compare=False) + tables: dict[str, str] | None = field(default=None, compare=False) @dataclass(frozen=True) @@ -406,9 +410,16 @@ def observe(client: _Client, project_id: str, dataset: str) -> Observed: dataset: The dataset. Returns: - What was found, with the dataset's other tables from the same listing. + What was found, with the dataset's other tables from the same listing. A + listing that fails leaves the generation to the search by name alone, with no + tables: the observation only finds where the claim starts, and the claim's + exclusive create and verification are the same either way. """ - listing = sdk._list_dataset_for_lease(client, project_id, dataset) + try: + listing = sdk._list_dataset_for_lease(client, project_id, dataset) + except Exception: # noqa: BLE001 # any listing failure: the name search remains + generation, latest = _search(client, project_id, dataset) + return Observed(generation, None if latest is None else str(latest.version_id)) generations = {n for n in listing.values() if is_spiral_lease_table_name(n)} generation, latest = _newest(client, project_id, dataset, generations) return Observed( diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index 746f2207f..e0f0fe912 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -108,6 +108,13 @@ def shows_absent(self, table_name: str) -> bool: return table_name not in self._listed +KEPT_ROWS_BUDGET_BYTES = 256 * 1024 * 1024 +"""The most bytes (``pa.Table.nbytes``) of whole reads a run keeps under its lease +(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.""" + + @dataclass class WriterLease: """A run's state for one dataset, shared by the dataset's connectors under the @@ -126,13 +133,14 @@ class WriterLease: 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 + catalog: The dataset's listing, taken when the run started (the writer + lease's observation) or at its first listing, and updated by every committed append; a failed append lists its table unjudged, since it may hold rows; ``None`` until then. 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. - rows_by_table: The stored rows of each table a read of the run read whole, + 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. @@ -998,7 +1006,16 @@ def _keep_read(self, table_name: str, table_id: str, stored: pa.Table) -> None: with lease.lock: if not self._snapshot_is_current(table_name): return - lease.rows_by_table[table_id] = stored + if stored.nbytes > KEPT_ROWS_BUDGET_BYTES: + return # read again when needed + kept = lease.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 if table_id not in lease.keys_by_table: lease.keys_by_table[table_id] = _keys_of(stored) diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index 266dbb25a..aae172022 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -8,12 +8,15 @@ fails. A run that writes nothing takes no lease. Before it checks a source or reads anything, the run observes the dataset's newest lease -generation (``spiraldb_lease.observe``: one listing and one open, no state read). At its +generation (``spiraldb_lease.observe``: one listing, possibly paged, an open of the +newest listed generation and a probe of the next; no state read). The listing is also +the run's catalog of the dataset's tables. At its first write it claims the lease only if that generation is still the newest, at the same snapshot version: otherwise another writer took or released a lease while the run read the dataset, and the run is refused with nothing written -(``spiraldb_lease.LeaseChangedError``). So what a run decided from its reads is what it -would have decided holding the lease from its start. A second writer is refused at its +(``spiraldb_lease.LeaseChangedError``). So what a run read of a dataset is what it +would have read holding that dataset's lease from its start. The check is per dataset: a +refused claim does not undo writes the run made to another dataset. A second writer is refused at its first write (``LeaseBusyError``), before anything is written; it may compute before. A node that delivers side effects reads its log without the lease and claims it just before its first delivery (``SpiralDBRunLookupProtocol.spiral_claim_writer_lease``): @@ -79,17 +82,23 @@ def writable_connectors(databases: Iterable[object]) -> list[SpiralDBConnector]: def _verify_unless_recent( client: Any, lease: spiraldb_lease.Lease, verified_at: float -) -> None: # pyright: ignore[reportExplicitAny] # the SDK client - """Verify ``lease`` before the first write after its acquisition, unless its - acquisition verified it within ``RECENTLY_VERIFIED_SECONDS``. +) -> bool: # pyright: ignore[reportExplicitAny] # the SDK client + """Verify ``lease`` before a write, unless its acquisition verified it within + ``RECENTLY_VERIFIED_SECONDS``. Interim (ITL-1901): the acquisition verifies the claim, so a second read of the lease state moments later finds what it found, and costs a service call. A longer gap verifies again, as every first write did before. + + Returns: + Whether it verified now: until it has, every later write asks again, so a + write made 60 seconds or more after the acquisition (after a side-effect + node's claim and a long delivery) still verifies once. """ if _clock() - verified_at < RECENTLY_VERIFIED_SECONDS: - return + return False spiraldb_lease.check(client, lease) + return True @contextlib.contextmanager @@ -97,8 +106,9 @@ def database_writes(databases: Iterable[object], *, owner: str) -> Iterator[None """Hold the writer lease of every writable SpiralDB database dataset among ``databases`` from the body's first write to each dataset (ITL-1900). - On entry, each dataset's newest lease generation is observed (one listing and one - open; nothing is read from the lease). A dataset's lease is acquired at the body's + On entry, each dataset's newest lease generation is observed (one listing, possibly + paged, an open of the newest listed generation and a probe of the next; nothing is + read from the lease). A dataset's lease is acquired at the body's first write to it (a create or an append; a side-effect node's claim before its first delivery), only if the generation and its snapshot version are still those observed: otherwise ``LeaseChangedError``, since another writer may have written @@ -223,7 +233,8 @@ def __init__(self, connector: SpiralDBConnector, owner: str) -> None: self.refused: spiraldb_lease.LeaseBusyError | None = None self.writer: WriterLease = WriterLease(self._claim) # The observation's listing is the run's first view of the dataset. - self.writer.start_catalog(self._observed.tables) + if self._observed.tables is not None: + self.writer.start_catalog(self._observed.tables) def _claim(self) -> None: """Acquire the lease on first use, then verify it once.""" @@ -254,8 +265,9 @@ def claimed(lease: spiraldb_lease.Lease) -> None: assert self._lease is not None # Interim (ITL-1901): skipped within RECENTLY_VERIFIED_SECONDS of the # acquisition's own verification. - _verify_unless_recent(self._client, self._lease, self._verified_at) - self._checked = True + self._checked = _verify_unless_recent( + self._client, self._lease, self._verified_at + ) def release(self) -> None: """Release the lease if it was claimed.""" @@ -303,8 +315,7 @@ def check() -> None: if not checked: # Interim (ITL-1901): skipped within RECENTLY_VERIFIED_SECONDS of # the acquisition's own verification. - _verify_unless_recent(client, lease, verified_at) - checked = True + checked = _verify_unless_recent(client, lease, verified_at) def release() -> None: spiraldb_lease.release(client, lease) @@ -358,8 +369,12 @@ def _release_all( tables.let_go_of_lease(check) except BaseException as again: # noqa: BLE001 # reported with the others failures.append(again) - # What the run read under the lease ends with it (ITL-1899). - check.forget_reads() + # What the run read under the lease ends with it (ITL-1899); an interruption + # here still lets the remote release be attempted. + try: + check.forget_reads() + except BaseException as exc: # noqa: BLE001 # reported with the others + failures.append(exc) try: release() except BaseException as exc: # noqa: BLE001 # an interrupted release too: every lease is released; failures are reported below diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index f69656681..41e2bfbbe 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -21,6 +21,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any +from orcapod.core.pod_result_databases import pod_result_databases from orcapod.errors import ( OrcapodDatabaseError, OrcapodDatabaseWriteError, @@ -202,36 +203,6 @@ 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. - """ - 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(getattr(pod, "result_database", None)) - 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(getattr(function, "result_database", None)) - function = getattr(function, "_data_function", None) # a wrapper's inner - return found - - def _job_name(node: Any) -> str: """The name of the job ``node`` belongs to: its pipeline database's location.""" database = getattr(node, "_pipeline_database", None) @@ -300,7 +271,7 @@ def _source_side_databases(streams: Iterable[Any], *, load_only: bool) -> list[A every source it finds, ``check_sources``), and the result databases of every function pod stream a run reads (a stream built outside the job and bound to a slot computes, and writes its pod's caches, when the run reads it; - ``_pod_result_databases``). Behind an ``ArrowTableStream`` no pod is read: the + ``pod_result_databases``). Behind an ``ArrowTableStream`` no pod is read: the table holds its rows, whatever its ``upstreams`` name (ITL-1121), so only the caches of the sources there are collected. A load-only run reads no function pod stream (``refuse_unloadable_inputs`` refuses one), so it leases none of their @@ -327,7 +298,7 @@ def _source_side_databases(streams: Iterable[Any], *, load_only: bool) -> list[A found.append(stream._cache_database) # pyright: ignore[reportPrivateUsage] # the database a run must hold the lease of if not load_only and not behind_table and not _is_job_node(stream): # A job node's pods: ``write_scope_databases``. - 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) behind = behind_table or isinstance(stream, ArrowTableStream) inputs = getattr(stream, "live_source_inputs", None) pending.extend((each, behind) for each in inputs or ()) @@ -384,7 +355,7 @@ 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)) return written diff --git a/tests/test_databases/test_spiraldb_lazy_lease.py b/tests/test_databases/test_spiraldb_lazy_lease.py index 51c110221..cd6008dd0 100644 --- a/tests/test_databases/test_spiraldb_lazy_lease.py +++ b/tests/test_databases/test_spiraldb_lazy_lease.py @@ -2,7 +2,7 @@ A run observes each leased dataset's newest lease generation when its write scope opens, and claims the lease at its first write to that dataset (a side-effect node: -before it reads its invocation log). The claim is refused when the generation moved +after it reads its invocation log, just before its first delivery). The claim is refused when the generation moved since the observation (``LeaseChangedError``) or is held (``LeaseBusyError``), with nothing written. A run that writes nothing takes no lease. """ @@ -31,6 +31,7 @@ from orcapod.side_effects import SideEffectPod, sink_pod from orcapod.sources import ArrowTableSource from orcapod.types import CacheMode, NodeConfig +from orcapod.databases import spiral_database_identity from tests.test_databases import fake_spiral_sdk as fake from tests.test_databases.test_spiraldb_writable_runs import ( ENTRIES, @@ -124,8 +125,15 @@ def test_a_writer_releasing_inside_the_window_refuses_the_first_write( leases = _lease_tables() done = _another_writer_inside_the_window(monkeypatch) job = _job(_database(), table=_rows(4)) - with pytest.raises(spiraldb_lease.LeaseChangedError, match="Run again"): + with pytest.raises( + spiraldb_lease.LeaseChangedError, + match="lease of SpiralDB dataset p/d changed since this run started", + ) as raised: _ = _run(job, entry) + # Review of e82c9f276: the message says the lease changed and this write wrote + # nothing, never that the other writer wrote. + assert "wrote nothing to the dataset" in str(raised.value) + assert "Another writer wrote" not in str(raised.value) assert done assert _versions() == before assert calls == [] and delivered == [] @@ -234,9 +242,14 @@ def _run_side_effect(job: PipelineJob, entry: str) -> None: _ = _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 _recorded(monkeypatch: pytest.MonkeyPatch) -> list[str]: - """The run's observations, claims, reads of database tables and deliveries, in - order.""" + """The run's observations, claims, reads of the side-effect node's log tables + (``"log read"``) and deliveries, in order.""" events = EVENTS events.clear() real_observe, real_acquire = spiraldb_lease.observe, spiraldb_lease.acquire @@ -252,7 +265,11 @@ def acquire(*args: Any, **kwargs: Any) -> Any: def scan(table: fake.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any: if not is_spiral_lease_table_name(table._table["name"]): # pyright: ignore[reportPrivateUsage] - events.append("read") + 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 real_scan(table, *args, **kwargs) monkeypatch.setattr(spiraldb_lease, "observe", observe) @@ -278,15 +295,15 @@ def test_a_side_effect_node_claims_just_before_its_first_delivery( events = _recorded(monkeypatch) _run_side_effect(build(_database(), 4), entry) assert sorted(delivered) == [4] + # Observe, read the log, claim, deliver: in that order, the claim once. assert events[0] == "observe", events - assert "read" in events - assert events.count("claim") == 1, events - assert events.index("claim") < events.index("deliver"), events - assert events.count("deliver") == 1, events + assert events.count("claim") == 1 and events.count("deliver") == 1, events + first_read = events.index("log read") + assert first_read < events.index("claim") < events.index("deliver"), events # A fresh job with nothing new to deliver reads its log and claims nothing. events.clear() _run_side_effect(build(_database(), 4), entry) - assert events[0] == "observe" and "read" in events, events + assert events[0] == "observe" and "log read" in events, events assert "claim" not in events and "deliver" not in events, events @@ -326,6 +343,7 @@ def _operator_cache_job(database: Any) -> PipelineJob: 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") @@ -333,6 +351,7 @@ def _result_database_job(database: Any) -> PipelineJob: 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") @@ -342,6 +361,7 @@ def _ephemeral_job(database: Any) -> PipelineJob: 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") @@ -530,6 +550,7 @@ def counted(*args: Any, **kwargs: Any) -> Any: def _write(database: ConnectorArrowDatabase, key: bytes) -> None: + """Write one row with record id ``key`` to a result table of ``database``.""" database.add_records( ("recent", "rdb_v1"), pa.table( @@ -614,3 +635,192 @@ def counted(client: Any, project: str, dataset: str) -> dict[str, str]: _ = _run(_job(_database(), table=table), entry) assert acquisitions == ["d"] assert listings == ["d"] + + +# ------------------------------------------------------ review of e82c9f276 (#701) + + +def _failing_lease_listing( + monkeypatch: pytest.MonkeyPatch, times: int | None = None +) -> list[None]: + """The writer lease's listing of the dataset fails (the first ``times`` calls, or + every call); opens by name still work.""" + from orcapod.databases import spiraldb_connector + + failed: list[None] = [] + real = spiraldb_connector._list_dataset_for_lease # pyright: ignore[reportPrivateUsage] + + def failing(*args: Any, **kwargs: Any) -> dict[str, str]: + if times is not None and len(failed) >= times: + return real(*args, **kwargs) + failed.append(None) + raise TimeoutError("the listing timed out") + + monkeypatch.setattr(spiraldb_connector, "_list_dataset_for_lease", failing) + return failed + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) +def test_a_failed_listing_leaves_the_observation_to_the_name_search( + monkeypatch: pytest.MonkeyPatch, entry: str +) -> None: + """Finding M1: a listing that fails does not block the run: the observation finds + the newest generation by name, and the run stores as it would.""" + _ = _run(_job(_database()), entry) + failed = _failing_lease_listing(monkeypatch) + _ = _run(_job(_database(), table=_rows(4)), entry) + assert failed + assert calls[-1] == (4, 8) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) +def test_a_failed_listing_still_refuses_a_writer_inside_the_window( + monkeypatch: pytest.MonkeyPatch, entry: str +) -> None: + """Finding M1: with the listing failing, a writer that takes the lease after the + observation still has the run refused at its first write, with nothing written; + one held all along still gives the busy refusal.""" + _ = _run(_job(_database()), entry) + before = _versions() + # The run's observation lists and fails; the other writer's own listing works. + failed = _failing_lease_listing(monkeypatch, times=1) + done = _another_writer_inside_the_window(monkeypatch) + with pytest.raises(spiraldb_lease.LeaseChangedError): + _ = _run(_job(_database(), table=_rows(4)), entry) + assert failed and done and _versions() == before + _, release = take_lease(SpiralDBConnector("p", "d", writable=True), "writer A") + try: + with pytest.raises(spiraldb_lease.LeaseBusyError, match="writer A"): + _ = _run(_job(_database(), table=_rows(4)), entry) + finally: + release() + assert _versions() == before + + +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], owner="seed"): + 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], owner="test"): + 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], owner="test"): + 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.mark.usefixtures("root") +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +@pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) +def test_a_context_function_claims_its_nested_result_store_before_it_is_called( + entry: str, +) -> None: + """Finding M4: the function's own result store (``result_database=``), on a + dataset another writer holds, is claimed before the function is called: the run + is refused with the function not called and nothing written there.""" + nested = _database("n") + + @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") + _, release = take_lease(SpiralDBConnector("p", "n", writable=True), "writer A") + try: + with pytest.raises(spiraldb_lease.LeaseBusyError, match="writer A"): + _ = _run(job, entry) + finally: + release() + assert delivered == [] + assert _versions("n") == {} + + +@pytest.mark.usefixtures("root") +def test_a_write_long_after_a_claim_verifies_the_lease( + monkeypatch: pytest.MonkeyPatch, verifications: list[None] +) -> None: + """Finding m4: a side-effect node's claim before a delivery does not stand in + for the write that follows 60 seconds or more later: that write verifies the + lease once; later writes do not.""" + _clock(monkeypatch, 100.0, 100.0, 161.0) + database = _database() + with database_writes([database], owner="test"): + database.spiral_claim_writer_lease() # the claim before a delivery + assert len(verifications) == 1 # the acquisition's own + _write(database, b"a") + _write(database, b"b") + assert len(verifications) == 2 + + +@pytest.mark.usefixtures("root") +def test_an_interrupted_cleanup_of_kept_reads_still_releases_the_lease( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Finding m8: an interruption while forgetting a run's kept reads does not skip + the lease's release.""" + from orcapod.databases import spiraldb_tables + + def interrupted(self: Any) -> None: + raise KeyboardInterrupt + + database = _database() + monkeypatch.setattr(spiraldb_tables.WriterLease, "forget_reads", interrupted) + with pytest.raises(KeyboardInterrupt): + with database_writes([database], owner="interrupted"): + database.spiral_claim_writer_lease() + monkeypatch.undo() + _, release = take_lease(SpiralDBConnector("p", "d", writable=True), "after") + release() diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index f20498fff..8758e035a 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -1001,9 +1001,12 @@ def counted(table: fake.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any: # soon after (ITL-1901). assert len(reads) == 1 + count + # A run that writes nothing takes no lease, so it reads no lease state, from + # opening the scope to closing it. + reads.clear() with database_writes([first, second], owner="no writes"): - reads.clear() - assert reads == [] + pass + assert reads == [] @pytest.mark.usefixtures("root") @@ -1974,8 +1977,9 @@ def refuse_total_8(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: records = stored.get("pdb_v2") assert (0 if records is None else records.num_rows) == len(kept) assert stored["sdb_v2"].num_rows == 3 + # The failed run released its lease: a recovery run can claim it. with database_writes([fresh], owner="recovery"): - pass + fresh.spiral_claim_writer_lease() @pytest.mark.usefixtures("root") From 449960e8e4e069a526c62b5c6ba19a3fb266c579 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 02:06:48 -0800 Subject: [PATCH 20/46] refactor(spiraldb): rename the keyed connector (ITL-1903) --- .basedpyright/baseline.json | 4 +- .github/workflows/run-tests.yml | 2 +- .zed/rules | 4 + CLAUDE.md | 4 + changelog.d/ITL-1023.md | 2 +- changelog.d/ITL-1186.md | 4 +- changelog.d/ITL-1334.md | 6 +- changelog.d/ITL-1350.md | 2 +- changelog.d/ITL-1840.md | 2 +- changelog.d/ITL-1844.md | 2 +- changelog.d/ITL-1903.md | 6 + changelog.d/ITL-998.md | 2 +- docs/api/databases.md | 6 +- docs/concepts/pipeline-job.md | 6 +- docs/concepts/sources.md | 12 +- ...database.md => spiraldb-keyed-database.md} | 28 +-- docs/dev/design_issues/ITL-1162-CA3.md | 2 +- docs/dev/design_issues/ITL-1367-CO1.md | 2 +- docs/dev/design_issues/ITL-936-SP3.md | 4 +- docs/dev/design_issues/PLT-1773-SP1.md | 2 +- docs/dev/design_issues/PLT-1795-CA1.md | 2 +- .../2026-03-26-postgresql-table-source.md | 4 +- .../2026-06-23-pyspiral-upgrade-plt-1773.md | 16 +- ...71-spiraldb-arrow-metadata-preservation.md | 58 +++--- .../2026-11-09-v0.2-release-checklist.md | 2 +- ...11-11-itl-936-spiral-nullability-record.md | 12 +- ...6-11-12-itl-186-streaming-spiral-source.md | 2 +- ...026-12-01-itl-1837-spiral-store-stage-a.md | 6 +- ...026-12-01-itl-1840-spiral-store-stage-b.md | 10 +- docs/dev/plans/itl-998-plan.md | 6 +- .../itl_1371_logical_identity_appends.py | 8 +- .../scripts/itl_1844_database_evaluation.py | 20 +- docs/dev/scripts/itl_1903/rename.py | 195 ++++++++++++++++++ ...-pyspiral-upgrade-fix-ci-header-signing.md | 8 +- ...aldb-arrow-metadata-preservation-design.md | 24 +-- .../2026-11-13-itl-1074-test-inventory.md | 2 +- ...2026-11-15-itl-1154-hash-site-inventory.md | 2 +- docs/dev/specs/itl-1186-switch.md | 2 +- .../dev/specs/itl-1367-stored-column-order.md | 2 +- docs/dev/specs/itl-926-live/FINDINGS.md | 6 +- .../specs/itl-936-live/live_nullability.py | 12 +- docs/dev/specs/itl-998-range-restriction.md | 2 +- docs/reference/database-types.md | 4 +- docs/reference/hashing.md | 2 +- scripts/migrate_spiral_schemas.py | 33 +-- site/astro.config.mjs | 2 +- .../core/sources/spiraldb_table_source.py | 12 +- src/orcapod/databases/__init__.py | 6 +- .../databases/connector_arrow_database.py | 22 +- .../databases/spiral_database_codec.py | 2 +- .../databases/spiraldb_keyed/__init__.py | 1 + .../connector.py} | 62 +++--- .../identity.py} | 0 .../nullability.py} | 2 +- .../schema_table.py} | 2 +- .../sign_in.py} | 0 .../tables.py} | 14 +- .../writable_registry.py} | 4 +- .../write_scope.py} | 16 +- src/orcapod/databases/spiraldb_lease.py | 2 +- src/orcapod/databases/store_table_names.py | 4 +- src/orcapod/errors.py | 6 +- src/orcapod/pipeline/_observer_database.py | 4 +- src/orcapod/pipeline/job.py | 9 +- src/orcapod/pipeline/node_run.py | 12 +- src/orcapod/pipeline/serialization.py | 62 +++--- src/orcapod/protocols/database_protocols.py | 5 +- .../protocols/db_connector_protocol.py | 8 +- .../data_tags/test_database_capability.py | 6 +- .../sources/test_spiraldb_lookups.py | 8 +- .../sources/test_spiraldb_table_source.py | 16 +- .../test_spiraldb_table_source_fake.py | 4 +- tests/test_core/test_result_cache.py | 9 +- tests/test_databases/fake_spiral_sdk.py | 13 +- .../test_migrate_spiral_schemas.py | 15 +- .../test_spiral_database_identity.py | 5 +- tests/test_databases/test_spiral_lease.py | 12 +- .../test_spiraldb_job_projection.py | 8 +- ...t_spiraldb_keyed_connector_integration.py} | 14 +- .../test_spiraldb_keyed_table_deprecation.py | 22 +- .../test_spiraldb_projection.py | 2 +- tests/test_databases/test_spiraldb_reading.py | 86 ++++---- .../test_spiraldb_schema_table.py | 22 +- tests/test_databases/test_spiraldb_sign_in.py | 9 +- .../test_spiraldb_writable_mode.py | 24 +-- .../test_spiraldb_writable_runs.py | 138 +++++++------ tests/test_databases/type_matrix.py | 8 +- .../test_load_connector_database.py | 27 ++- .../test_pipeline/test_observer_databases.py | 18 +- 89 files changed, 775 insertions(+), 490 deletions(-) create mode 100644 changelog.d/ITL-1903.md rename docs/concepts/{spiraldb-database.md => spiraldb-keyed-database.md} (84%) create mode 100644 docs/dev/scripts/itl_1903/rename.py create mode 100644 src/orcapod/databases/spiraldb_keyed/__init__.py rename src/orcapod/databases/{spiraldb_connector.py => spiraldb_keyed/connector.py} (96%) rename src/orcapod/databases/{spiral_database_identity.py => spiraldb_keyed/identity.py} (100%) rename src/orcapod/databases/{spiraldb_nullability.py => spiraldb_keyed/nullability.py} (99%) rename src/orcapod/databases/{spiraldb_schema_table.py => spiraldb_keyed/schema_table.py} (99%) rename src/orcapod/databases/{spiraldb_sign_in.py => spiraldb_keyed/sign_in.py} (100%) rename src/orcapod/databases/{spiraldb_tables.py => spiraldb_keyed/tables.py} (99%) rename src/orcapod/databases/{spiraldb_writable_registry.py => spiraldb_keyed/writable_registry.py} (84%) rename src/orcapod/databases/{spiraldb_write_scope.py => spiraldb_keyed/write_scope.py} (94%) rename tests/test_databases/{test_spiraldb_connector_integration.py => test_spiraldb_keyed_connector_integration.py} (98%) diff --git a/.basedpyright/baseline.json b/.basedpyright/baseline.json index c2f72dcc7..b2f8ed0ae 100644 --- a/.basedpyright/baseline.json +++ b/.basedpyright/baseline.json @@ -27176,7 +27176,7 @@ } } ], - "./src/orcapod/databases/spiraldb_connector.py": [ + "./src/orcapod/databases/spiraldb_keyed/connector.py": [ { "code": "reportMissingImports", "range": { @@ -184110,7 +184110,7 @@ } } ], - "./tests/test_databases/test_spiraldb_connector_integration.py": [ + "./tests/test_databases/test_spiraldb_keyed_connector_integration.py": [ { "code": "reportUnknownParameterType", "range": { diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 483be75e2..8486cd0c9 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -191,7 +191,7 @@ jobs: SPIRAL_CLIENT_ID: ${{ secrets.SPIRAL_CLIENT_ID }} SPIRAL_PRIVATE_KEY: ${{ secrets.SPIRAL_PRIVATE_KEY }} # Serial (-n 0): the integration tests share one SpiralDB project (ITL-1181). - run: uv run --python "3.11" pytest -n 0 tests/test_databases/test_spiraldb_connector_integration.py -v + run: uv run --python "3.11" pytest -n 0 tests/test_databases/test_spiraldb_keyed_connector_integration.py -v license-check: uses: ./.github/workflows/_license-check.yml diff --git a/.zed/rules b/.zed/rules index c3fdd6a23..391f95ba1 100644 --- a/.zed/rules +++ b/.zed/rules @@ -61,6 +61,10 @@ This is a greenfield project pre-v0.1.0. Do NOT add backward-compatibility shims re-exports, aliases, or deprecation wrappers when making design or implementation changes. Just change the code and update all references directly. +The keyed backend is SpiralDBKeyedConnector (databases/spiraldb_keyed/). A saved +job uses connector_type: spiraldb_keyed. Loading the retired spiraldb connector +type raises an error naming spiraldb_keyed. The source kind stays spiraldb_table. + ## No sys.modules hacks Never manipulate sys.modules directly (e.g. sys.modules.setdefault). If a subpackage diff --git a/CLAUDE.md b/CLAUDE.md index 757761622..b05876567 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -65,6 +65,10 @@ This is a greenfield project pre-v0.1.0. Do **not** add backward-compatibility s re-exports, aliases, or deprecation wrappers when making design or implementation changes. Just change the code and update all references directly. +The keyed backend is `SpiralDBKeyedConnector` (`databases/spiraldb_keyed/`). A saved +job uses `connector_type: spiraldb_keyed`. Loading the retired `spiraldb` connector +type raises an error naming `spiraldb_keyed`. The source kind stays `spiraldb_table`. + ## No `sys.modules` hacks Never manipulate `sys.modules` directly (e.g. `sys.modules.setdefault`). If a subpackage diff --git a/changelog.d/ITL-1023.md b/changelog.d/ITL-1023.md index d66345a0f..9e8ac9bfa 100644 --- a/changelog.d/ITL-1023.md +++ b/changelog.d/ITL-1023.md @@ -85,7 +85,7 @@ - `FieldMetadataKeepingDatabaseProtocol` (`orcapod.protocols.database_protocols`): a database states with `keeps_field_metadata` whether it keeps Arrow field metadata. `InMemoryArrowDatabase`, `DeltaTableDatabase` and a `ConnectorArrowDatabase` over - `SpiralDBConnector` state `True`. The SQLite and PostgreSQL connector databases and + `SpiralDBKeyedConnector` state `True`. The SQLite and PostgreSQL connector databases and `NoOpArrowDatabase` state `False`. `ExtensionAwareDatabase` states what the database it wraps states, and a connector database what its connector states. A database without the member is treated as not keeping field metadata. diff --git a/changelog.d/ITL-1186.md b/changelog.d/ITL-1186.md index d7c59cc94..7c961545b 100644 --- a/changelog.d/ITL-1186.md +++ b/changelog.d/ITL-1186.md @@ -1,7 +1,7 @@ ### Breaking changes and migration - SpiralDB is read through `spiral-sdk` (the `spiraldb` extra pins `spiral-sdk==0.16.74`), and `pyspiral` is gone. Both packages provide a module named `spiral`: install into an environment without `pyspiral`. -- A plain `SpiralDBConnector` only reads. Every write of a plain connector (`create_table_if_not_exists`, `upsert_records`, `delete_table`) and every job whose database is on one raises `SpiralDBWriteNotSupportedError`, before anything is buffered or run. A job keeps its tables in SpiralDB through a writable SpiralDB database, `SpiralDBConnector(..., writable=True)` (ITL-1844). +- A plain `SpiralDBKeyedConnector` only reads. Every write of a plain connector (`create_table_if_not_exists`, `upsert_records`, `delete_table`) and every job whose database is on one raises `SpiralDBWriteNotSupportedError`, before anything is buffered or run. A job keeps its tables in SpiralDB through a writable SpiralDB database, `SpiralDBKeyedConnector(..., writable=True)` (ITL-1844). - A table's non-nullable columns and Arrow metadata are read from its dataset's schema table, `__orcapod_schemas__`, not from the table's metadata. Datasets written by an earlier release must be migrated once with `scripts/migrate_spiral_schemas.py` (`RELEASING.md`); then schemas, hashes and source ids are as before. Until then their tables read with every column nullable, with `UnrecordedTableSchemaWarning`, and their hashes differ. - `read_nullability_record` and `write_nullability_record` are removed, and `NullabilityRecordError` is replaced by `TableSchemaError`. - Row counts are counted from the keys: `row_count_estimate` is exact and reads every key, the `max_rows` check reads at most `max_rows + 1` keys, and a preview of more than 100,000 rows shows no total. @@ -21,4 +21,4 @@ ### Known limitations - A saved SpiralDB login that has expired is not detected: the client may print a sign-in prompt and wait. Run `uv run spiral login` again. -- A `SpiralDBConnector` cannot be used in a forked process (`spawn` works); it is refused there. +- A `SpiralDBKeyedConnector` cannot be used in a forked process (`spawn` works); it is refused there. diff --git a/changelog.d/ITL-1334.md b/changelog.d/ITL-1334.md index 8c05dec81..74a2edd7c 100644 --- a/changelog.d/ITL-1334.md +++ b/changelog.d/ITL-1334.md @@ -35,7 +35,7 @@ aggregate) reads every column nullable. (ITL-1276) - **`SQLiteConnector` refuses a `double` column holding a NaN or `-0.0`:** SQLite reads a NaN back as NULL and `-0.0` as `0.0`. (ITL-1334) -- **`SpiralDBConnector` refuses a logical (extension) type:** `File`, `Directory`, +- **`SpiralDBKeyedConnector` refuses a logical (extension) type:** `File`, `Directory`, `Path`, `UPath`, `UUID`, `list[T]` and `set[T]` of them, user classes and the library value types read back from SpiralDB as their plain storage type (SpiralDB drops the field metadata that names them). They are refused with `UnstorableColumnError` before @@ -76,7 +76,7 @@ an append makes nullable reads back nullable. (ITL-1334) - **`DeltaTableDatabase` refuses a struct with no fields at any depth:** a Parquet file stores values in leaf columns only, so the flush failed. (ITL-1334) -- **`SpiralDBConnector` refuses field metadata below a map, and Arrow's canonical extension +- **`SpiralDBKeyedConnector` refuses field metadata below a map, and Arrow's canonical extension types:** its metadata record does not descend into a map, so metadata on a map's key or item, or inside them, read back dropped. A `uuid` or `json` column (Arrow's own extension types) read back as its storage type. (ITL-1334) @@ -108,7 +108,7 @@ the recorded type or a logical column's extension name, so afterwards a list read back with its item named `element`, and a logical list (`set[int]`, `list[Path]`) as its plain storage type. (ITL-1334) -- **`SpiralDBConnector` reads back a fixed-size list with non-null items and a null row:** +- **`SpiralDBKeyedConnector` reads back a fixed-size list with non-null items and a null row:** the read cast every column to the restored schema, and pyarrow refuses that cast when a null row hides null item slots; only columns whose type changes are cast now. (ITL-1334) diff --git a/changelog.d/ITL-1350.md b/changelog.d/ITL-1350.md index 964573c20..8f6c3ee2c 100644 --- a/changelog.d/ITL-1350.md +++ b/changelog.d/ITL-1350.md @@ -3,7 +3,7 @@ - A `SpiralDBTableSource` looks its table up once when it is built and once per new-data check (ITL-1350). Every lookup of a table by name is a round trip to SpiralDB; the source used to look the table up for each item it needed (key, id, schema and - version: four lookups to build, three per check). `SpiralDBConnector.lookup_table` + version: four lookups to build, three per check). `SpiralDBKeyedConnector.lookup_table` returns the table once, with its id and key columns, and reads its schema and version when asked, in the same order and under the same conditions as before, so a check still finds a table dropped and created again since. Measured on a live project: diff --git a/changelog.d/ITL-1840.md b/changelog.d/ITL-1840.md index 5eec33a4a..cda19f732 100644 --- a/changelog.d/ITL-1840.md +++ b/changelog.d/ITL-1840.md @@ -1,6 +1,6 @@ ### Known limitations -- A writable SpiralDB database (`SpiralDBConnector(..., writable=True)`, ITL-1844) keeps every stored +- A writable SpiralDB database (`SpiralDBKeyedConnector(..., writable=True)`, ITL-1844) keeps every stored table kind through `ConnectorArrowDatabase`: one table per path, its identity and manifest in the table's metadata. Its format is provisional, outside the 0.4.0 freeze. (ITL-1840) diff --git a/changelog.d/ITL-1844.md b/changelog.d/ITL-1844.md index 5ccf68e3b..26d599966 100644 --- a/changelog.d/ITL-1844.md +++ b/changelog.d/ITL-1844.md @@ -1,7 +1,7 @@ ### Added - A SpiralDB dataset can be a job's database: a writable SpiralDB database, - `SpiralDBConnector(project_id, dataset, writable=True)` under `ConnectorArrowDatabase`, stores every table a job writes (function results and + `SpiralDBKeyedConnector(project_id, dataset, writable=True)` under `ConnectorArrowDatabase`, stores every table a job writes (function results and pipeline records, operator caches, cached sources, side-effect logs), also as a separate result database. Provisional in 0.4.0: the database's table format and its writer lease may change in a later version, which may not read tables written now. Nothing of the diff --git a/changelog.d/ITL-1903.md b/changelog.d/ITL-1903.md new file mode 100644 index 000000000..eaaf60d22 --- /dev/null +++ b/changelog.d/ITL-1903.md @@ -0,0 +1,6 @@ +### Changed + +- Renamed `SpiralDBConnector` to `SpiralDBKeyedConnector`. Saved jobs now use the + `spiraldb_keyed` connector type. Loading the retired `spiraldb` type raises an + error naming `spiraldb_keyed`. The `spiraldb_table` source kind and source IDs + stay the same. diff --git a/changelog.d/ITL-998.md b/changelog.d/ITL-998.md index be1ad55a4..7ad3d205c 100644 --- a/changelog.d/ITL-998.md +++ b/changelog.d/ITL-998.md @@ -18,7 +18,7 @@ a=2)` and `where(a=2, b=1)` save the same bytes. Saved jobs and configs written before load to the same condition; their bytes change only when two or more columns had been given out of that order. No hash, stored path or identity reads a saved condition. -- The `where` parameter of `SpiralDBConnector.scan_batches` is PROVISIONAL and takes a +- The `where` parameter of `SpiralDBKeyedConnector.scan_batches` is PROVISIONAL and takes a `Condition` (equalities and ranges). To pass a mapping, wrap it in `Condition.of(...)`. - For now, `SpiralDBTableSource.where(...)` and `where=` refuse an equality of a float column to `-0.0` or a NaN (`TypeError`, pointing to `filter`). SpiralDB matches them by their bits, diff --git a/docs/api/databases.md b/docs/api/databases.md index 9806c28b7..008eba163 100644 --- a/docs/api/databases.md +++ b/docs/api/databases.md @@ -7,9 +7,9 @@ code. See site/README.md. --> Database backends store pipeline results. The SQLite and PostgreSQL connectors support -reads and writes through `ConnectorArrowDatabase`. The SpiralDB connector reads, and writes +reads and writes through `ConnectorArrowDatabase`. `SpiralDBKeyedConnector` reads, and writes only when opened writable (`writable=True`, provisional; see -[SpiralDB as a Job's Database](../concepts/spiraldb-database.md)). +[Keyed SpiralDB as a Job's Database](../concepts/spiraldb-keyed-database.md)). **Provisional.** `ExtensionAwareDatabase` is expected to be integrated more closely with the underlying database classes (ITL-1539), so its public form may change. @@ -28,4 +28,4 @@ the underlying database classes (ITL-1539), so its public form may change. ::: orcapod.databases.PostgreSQLConnector -::: orcapod.databases.SpiralDBConnector +::: orcapod.databases.SpiralDBKeyedConnector diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 8104a8df8..5475e8ce2 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -277,9 +277,9 @@ refused. PostgreSQL also refuses column names and explicit table identifiers lon 63 bytes, which it would truncate (`UnstorableTableNameError` for a table). SQLite and PostgreSQL stores generate table names within 63 bytes from the node's path, using a readable hint and a digest of the full path. A database on -`SpiralDBConnector` refuses every write (`SpiralDBWriteNotSupportedError`) unless it is opened -writable, `SpiralDBConnector(..., writable=True)`: see -[SpiralDB as a Job's Database](spiraldb-database.md). The full list, +`SpiralDBKeyedConnector` refuses every write (`SpiralDBWriteNotSupportedError`) unless it is opened +writable, `SpiralDBKeyedConnector(..., writable=True)`: see +[Keyed SpiralDB as a Job's Database](spiraldb-keyed-database.md). The full list, type by type, is [Data types per database](../reference/database-types.md). Orcapod's own stored tables hold such columns. A function node's result table holds diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 88b049578..77a64b4be 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -567,19 +567,19 @@ again only when the version moved. A changed environment or saved login, or a cl whose calls failed, gives the next new source a new client. Closing a source affects no other; the client goes with the last source that uses it, and a forked process starts with none. -A plain `SpiralDBConnector` only reads: a write through it (or a job whose database is on +A plain `SpiralDBKeyedConnector` only reads: a write through it (or a job whose database is on one) raises `SpiralDBWriteNotSupportedError`. A job can keep its tables in SpiralDB through -a writable SpiralDB database, `SpiralDBConnector(..., writable=True)`: see -[SpiralDB as a Job's Database](spiraldb-database.md). +a writable SpiralDB database, `SpiralDBKeyedConnector(..., writable=True)`: see +[Keyed SpiralDB as a Job's Database](spiraldb-keyed-database.md). Replace the example project, dataset and table names with identifiers you can access. To find the tables of a dataset and their key columns: ```python -from orcapod.databases import SpiralDBConnector +from orcapod.databases import SpiralDBKeyedConnector -with SpiralDBConnector("my-project-123456", dataset="my_dataset") as spiral: +with SpiralDBKeyedConnector("my-project-123456", dataset="my_dataset") as spiral: print(spiral.get_table_names()) print(spiral.get_pk_columns("sensor_reading")) ``` @@ -893,7 +893,7 @@ print(Condition.of(day=day, started=started, recorded=recorded)) - **One mechanism.** `where()` adds to the conditions given with `where=` (a mapping or a `Condition`) when the source was built (`Condition.combined`), and SpiralDB applies them - in the scan. If you call `SpiralDBConnector.scan_batches` directly, its PROVISIONAL + in the scan. If you call `SpiralDBKeyedConnector.scan_batches` directly, its PROVISIONAL `where` parameter takes a `Condition`. Use `Condition.of(...)` to wrap a mapping. A column already restricted to another value is refused, as is a column the table does not have, `None` (a null equals nothing) and diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-keyed-database.md similarity index 84% rename from docs/concepts/spiraldb-database.md rename to docs/concepts/spiraldb-keyed-database.md index d5eefe25e..509af7bf1 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-keyed-database.md @@ -1,4 +1,4 @@ -# SpiralDB as a Job's Database +# Keyed SpiralDB as a Job's Database A job can keep everything it stores in a SpiralDB dataset: function results, pipeline records, operator caches, cached sources and side-effect logs. Open the dataset as a @@ -13,23 +13,23 @@ records, operator caches, cached sources and side-effect logs. Open the dataset ## Opening the SpiralDB database -`SpiralDBConnector(project_id, dataset, writable=True)` opens one dataset as a writable +`SpiralDBKeyedConnector(project_id, dataset, writable=True)` opens one dataset as a writable SpiralDB database. Wrap it in `ConnectorArrowDatabase` and use it as the job's database, its separate result database, or a cached source's database: ```python from orcapod import PipelineJob -from orcapod.databases import ConnectorArrowDatabase, SpiralDBConnector +from orcapod.databases import ConnectorArrowDatabase, SpiralDBKeyedConnector database = ConnectorArrowDatabase( - SpiralDBConnector("my-project-123456", "pipeline_results", writable=True) + SpiralDBKeyedConnector("my-project-123456", "pipeline_results", writable=True) ) job = PipelineJob(name="experiment", database=database) ``` Signing in is spiral-sdk's: the `SPIRAL_*` environment variables, or a saved -`spiral login`. Without `writable=True`, a `SpiralDBConnector` reads existing keyed tables +`spiral login`. Without `writable=True`, a `SpiralDBKeyedConnector` reads existing keyed tables (a `SpiralDBTableSource`) and writes nothing. Each stored table is one keyed table of the dataset, named from its path (a readable @@ -100,7 +100,7 @@ spiraldb_lease.clear( ``` `spiral.Client()` connects to the default service. When the job's connector was made -for another service address (`SpiralDBConnector(..., overrides={"server.url": ...})`), +for another service address (`SpiralDBKeyedConnector(..., 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. @@ -111,24 +111,24 @@ one, also released ones: removing one 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, -dataset, the service address and `writable: true`), never a credential. A connector is not rebuilt from -a saved file: give it again when loading, as for every connector database: +A job saved on the keyed SpiralDB database records `connector_type: spiraldb_keyed` +along with the project, dataset, service address and `writable: true`. It saves no +credentials. Pass the connector again when loading the job: ```python loaded = PipelineJob.load( "experiment.json", database=ConnectorArrowDatabase( - SpiralDBConnector("my-project-123456", "pipeline_results", writable=True) + SpiralDBKeyedConnector("my-project-123456", "pipeline_results", writable=True) ), ) ``` -A job saved on the SpiralDB database is loaded with a writable connector, and one saved -on a plain -`SpiralDBConnector` with a plain one: the load refuses the other kind, since the two -read different tables. +Use a writable connector for a job saved with `writable=True` and a plain connector +for a job saved with a plain `SpiralDBKeyedConnector`. The two modes read different +tables. Loading a job saved with the retired `spiraldb` type raises an error naming +`spiraldb_keyed`. ## Limits diff --git a/docs/dev/design_issues/ITL-1162-CA3.md b/docs/dev/design_issues/ITL-1162-CA3.md index 73e1c1ee6..45825be46 100644 --- a/docs/dev/design_issues/ITL-1162-CA3.md +++ b/docs/dev/design_issues/ITL-1162-CA3.md @@ -29,7 +29,7 @@ buffered. A function job node (its result table) and a side-effect job node (its log) ask the database when it is attached, so a job refuses them before anything runs, naming the node. An operator job node with a cache and a cached source ask about their bookkeeping columns (`__node_content_hash`, `__data_context`) when attached or built; their user columns -are checked at the write. `SpiralDBConnector` states its name rule the same way (developer +are checked at the write. `SpiralDBKeyedConnector` states its name rule the same way (developer ruling, November 16, 2026). `PostgreSQLConnector` also states which table names it holds (`unstorable_table_name_reason`, 63 bytes), checked at every table entry (`UnstorableTableNameError`). The connectors' silent TEXT fallback in `CREATE TABLE` now diff --git a/docs/dev/design_issues/ITL-1367-CO1.md b/docs/dev/design_issues/ITL-1367-CO1.md index dc2b40648..369749b02 100644 --- a/docs/dev/design_issues/ITL-1367-CO1.md +++ b/docs/dev/design_issues/ITL-1367-CO1.md @@ -56,7 +56,7 @@ A table keeps the order its database gave the first write (SpiralDB: its own ord SpiralDB fake now mirrors SpiralDB at the top level: it matches a write by name and stores the key columns, then the value columns by name. Tests: `tests/test_databases/test_append_by_name.py`; live: `TestColumnOrderLive` in -`tests/test_databases/test_spiraldb_connector_integration.py`. +`tests/test_databases/test_spiraldb_keyed_connector_integration.py`. Pre-existing on main and equal here, not changed: another connection that changes a SQLite table between the flush's check and its write (a DDL in that window) is not seen; a rename diff --git a/docs/dev/design_issues/ITL-936-SP3.md b/docs/dev/design_issues/ITL-936-SP3.md index 1161ccfc9..4ba748d07 100644 --- a/docs/dev/design_issues/ITL-936-SP3.md +++ b/docs/dev/design_issues/ITL-936-SP3.md @@ -1,4 +1,4 @@ -## `src/orcapod/databases/spiraldb_connector.py` — SpiralDB stores every column nullable (ITL-936) +## `src/orcapod/databases/spiraldb_keyed/connector.py` — SpiralDB stores every column nullable (ITL-936) ### SP3 — Non-nullable columns arrive as `T | None` from SpiralDB; a null in a non-null struct field is stored as 0 **Status:** in progress @@ -15,7 +15,7 @@ client. Writing `{k: 4, v: 40, g: {x: null, y: null}}` with `g.x` declared non-n **Fix:** Orcapod records each table's non-nullable paths in the table's key-value metadata (`__orcapod_nullability__`, format `orcapod.nullability` v1; `orcapod.databases. -write_nullability_record` / `read_nullability_record`). `SpiralDBConnector` writes the record +write_nullability_record` / `read_nullability_record`). `SpiralDBKeyedConnector` writes the record before the first rows of a table, checks every non-nullable path for nulls before any write, refuses a write that disagrees with the record, and on read restores the record in `get_column_info` and checks and restores every batch in `iter_batches` diff --git a/docs/dev/design_issues/PLT-1773-SP1.md b/docs/dev/design_issues/PLT-1773-SP1.md index 2ccd7f66c..2843f7618 100644 --- a/docs/dev/design_issues/PLT-1773-SP1.md +++ b/docs/dev/design_issues/PLT-1773-SP1.md @@ -15,7 +15,7 @@ Vortex file reads to return: AccessDenied: There were headers present in the request which were not signed ``` -All three `TestSpiralDBConnectorIntegration` tests failed on every CI push from +All three `TestSpiralDBKeyedConnectorIntegration` tests failed on every CI push from 2026-06-15 onward. The runner image version was identical between the last green and first red run, confirming this was a server-side enforcement change rather than a runner regression. diff --git a/docs/dev/design_issues/PLT-1795-CA1.md b/docs/dev/design_issues/PLT-1795-CA1.md index 0096304bb..6f9c5ea1b 100644 --- a/docs/dev/design_issues/PLT-1795-CA1.md +++ b/docs/dev/design_issues/PLT-1795-CA1.md @@ -14,7 +14,7 @@ back, the column is returned as the raw storage type (e.g. `large_string`, `larg **Interim fix (PLT-1659 / ITL-471):** `DBConnectorProtocol` now declares a `validate_records` hook. `SQLiteConnector` and `PostgreSQLConnector` implement it to reject extension-typed columns -at write time, surfacing the issue immediately rather than on a confusing read. `SpiralDBConnector` +at write time, surfacing the issue immediately rather than on a confusing read. `SpiralDBKeyedConnector` overrides it as a no-op because it preserves field metadata via the native KV store. Two representations are rejected by the SQL implementations: - In-memory extension types: `isinstance(field.type, pa.ExtensionType)`. diff --git a/docs/dev/plans/2026-03-26-postgresql-table-source.md b/docs/dev/plans/2026-03-26-postgresql-table-source.md index 5291990bf..6a7f81ea9 100644 --- a/docs/dev/plans/2026-03-26-postgresql-table-source.md +++ b/docs/dev/plans/2026-03-26-postgresql-table-source.md @@ -896,7 +896,7 @@ Expected: All tests PASS. ```bash pytest tests/ -v --ignore=tests/test_databases/test_postgresql_connector_integration.py \ --ignore=tests/test_databases/test_spiraldb_connector.py \ - --ignore=tests/test_databases/test_spiraldb_connector_integration.py \ + --ignore=tests/test_databases/test_spiraldb_keyed_connector_integration.py \ -m "not postgres" ``` @@ -1204,7 +1204,7 @@ Run the full unit test suite one last time to confirm everything is clean. pytest tests/ -v \ --ignore=tests/test_databases/test_postgresql_connector_integration.py \ --ignore=tests/test_databases/test_spiraldb_connector.py \ - --ignore=tests/test_databases/test_spiraldb_connector_integration.py \ + --ignore=tests/test_databases/test_spiraldb_keyed_connector_integration.py \ -m "not postgres" ``` diff --git a/docs/dev/plans/2026-06-23-pyspiral-upgrade-plt-1773.md b/docs/dev/plans/2026-06-23-pyspiral-upgrade-plt-1773.md index 537927681..0e7e7cad5 100644 --- a/docs/dev/plans/2026-06-23-pyspiral-upgrade-plt-1773.md +++ b/docs/dev/plans/2026-06-23-pyspiral-upgrade-plt-1773.md @@ -3,7 +3,7 @@ > **For agentic workers:** REQUIRED SUB-SKILL: Use sensei:subagent-driven-development (recommended) or sensei:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. **Goal:** Upgrade `pyspiral` from the broken `0.11.7` to `0.14.9` so that all three -`TestSpiralDBConnectorIntegration` tests pass green in CI again. +`TestSpiralDBKeyedConnectorIntegration` tests pass green in CI again. **Architecture:** Three targeted edits — bump the minimum version constraint in `pyproject.toml`, verify the `uv.lock` pin is at `0.14.9` (already updated during @@ -110,14 +110,14 @@ Closes PLT-1773" ### Task 2: Add breadcrumb to integration test module docstring **Files:** -- Modify: `tests/test_databases/test_spiraldb_connector_integration.py:1-19` +- Modify: `tests/test_databases/test_spiraldb_keyed_connector_integration.py:1-19` - [ ] **Step 1: Extend the module docstring** Replace the existing module docstring (lines 1–19) with: ```python -"""Integration tests for SpiralDBConnector against the live dev project. +"""Integration tests for SpiralDBKeyedConnector against the live dev project. These tests are skipped unless the ``SPIRAL_INTEGRATION_TESTS=1`` env var is set. They require a valid auth mechanism, either: @@ -160,7 +160,7 @@ uv run python -c " import importlib.util, sys spec = importlib.util.spec_from_file_location( 'test_mod', - 'tests/test_databases/test_spiraldb_connector_integration.py' + 'tests/test_databases/test_spiraldb_keyed_connector_integration.py' ) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) @@ -174,7 +174,7 @@ at module level is fine to execute). - [ ] **Step 3: Commit** ```bash -git add tests/test_databases/test_spiraldb_connector_integration.py +git add tests/test_databases/test_spiraldb_keyed_connector_integration.py git commit -m "docs(spiraldb): add PLT-1773 breadcrumb to integration test module docstring Explains the t3.storage.dev header-signing enforcement change (2026-06-15) @@ -214,7 +214,7 @@ Vortex file reads to return: AccessDenied: There were headers present in the request which were not signed ``` -All three `TestSpiralDBConnectorIntegration` tests failed on every CI push from +All three `TestSpiralDBKeyedConnectorIntegration` tests failed on every CI push from 2026-06-15 onward. The runner image version was identical between the last green and first red run, confirming this was a server-side enforcement change rather than a runner regression. @@ -233,7 +233,7 @@ covering routine version bumps. - [ ] **Step 2: Run a quick smoke test to confirm no other tests broke** ```bash -uv run pytest tests/test_databases/ -v --ignore=tests/test_databases/test_spiraldb_connector_integration.py +uv run pytest tests/test_databases/ -v --ignore=tests/test_databases/test_spiraldb_keyed_connector_integration.py ``` Expected: all tests PASS (the integration tests are excluded since they require @@ -308,7 +308,7 @@ EOF The `spiral-integration` job runs on push (not on PRs), so it will fire when the branch is pushed. Watch the Actions tab for the run. Expected outcome: all three -`TestSpiralDBConnectorIntegration` tests PASS. +`TestSpiralDBKeyedConnectorIntegration` tests PASS. If they fail with a different error (not the unsigned-headers `AccessDenied`), the pyspiral 0.14.9 API may have a breaking change not caught by the static inspection. diff --git a/docs/dev/plans/2026-07-08-itl-471-spiraldb-arrow-metadata-preservation.md b/docs/dev/plans/2026-07-08-itl-471-spiraldb-arrow-metadata-preservation.md index ee8eac306..48211a43a 100644 --- a/docs/dev/plans/2026-07-08-itl-471-spiraldb-arrow-metadata-preservation.md +++ b/docs/dev/plans/2026-07-08-itl-471-spiraldb-arrow-metadata-preservation.md @@ -14,7 +14,7 @@ | File | Action | What changes | |---|---|---| -| `src/orcapod/databases/spiraldb_connector.py` | Modify | Add 4 private helpers; modify `upsert_records` and `iter_batches`; add `validate_records` no-op | +| `src/orcapod/databases/spiraldb_keyed/connector.py` | Modify | Add 4 private helpers; modify `upsert_records` and `iter_batches`; add `validate_records` no-op | | `src/orcapod/protocols/db_connector_protocol.py` | Modify | Add abstract `validate_records` method | | `src/orcapod/databases/sqlite_connector.py` | Modify | Add rejecting `validate_records` method | | `src/orcapod/databases/postgresql_connector.py` | Modify | Add rejecting `validate_records` method | @@ -22,7 +22,7 @@ | `tests/test_databases/test_spiraldb_metadata_helpers.py` | Create | Pure-function tests for the 4 helpers | | `tests/test_databases/test_spiraldb_connector.py` | Modify | Add `TestUpsertRecordsMetadata`, `TestIterBatchesMetadata`, `TestValidateRecords` | | `tests/test_databases/test_connector_arrow_database.py` | Modify | Update `MockDBConnector` + `TestExtensionTypeWriteGuard` | -| `tests/test_databases/test_spiraldb_connector_integration.py` | Modify | Add `TestArrowMetadataRoundTrip` | +| `tests/test_databases/test_spiraldb_keyed_connector_integration.py` | Modify | Add `TestArrowMetadataRoundTrip` | --- @@ -67,7 +67,7 @@ Expected: all pass (integration tests skipped). Note the count — it's the base **Files:** - Create: `tests/test_databases/test_spiraldb_metadata_helpers.py` -- Modify: `src/orcapod/databases/spiraldb_connector.py` +- Modify: `src/orcapod/databases/spiraldb_keyed/connector.py` ### Step 1: Write failing tests for `_serialize_field_meta_tree` @@ -83,7 +83,7 @@ import json import pyarrow as pa import pytest -from orcapod.databases.spiraldb_connector import ( +from orcapod.databases.spiraldb_keyed.connector import ( _ARROW_METADATA_KEY, _load_arrow_metadata, _restore_field, @@ -247,7 +247,7 @@ Expected: `ImportError` or `ModuleNotFoundError` — helpers don't exist yet. - [ ] **Step 3: Implement `_ARROW_METADATA_KEY`, `_serialize_field_meta_tree`, `_serialize_arrow_metadata`** -Add immediately after the existing module-level `logger = logging.getLogger(__name__)` line in `src/orcapod/databases/spiraldb_connector.py`: +Add immediately after the existing module-level `logger = logging.getLogger(__name__)` line in `src/orcapod/databases/spiraldb_keyed/connector.py`: ```python import base64 @@ -353,7 +353,7 @@ Expected: all pass. - [ ] **Step 5: Commit** ```bash -git add src/orcapod/databases/spiraldb_connector.py tests/test_databases/test_spiraldb_metadata_helpers.py +git add src/orcapod/databases/spiraldb_keyed/connector.py tests/test_databases/test_spiraldb_metadata_helpers.py git commit -m "feat(spiraldb): add _serialize_field_meta_tree and _serialize_arrow_metadata helpers (ITL-471)" ``` @@ -363,7 +363,7 @@ git commit -m "feat(spiraldb): add _serialize_field_meta_tree and _serialize_arr **Files:** - Modify: `tests/test_databases/test_spiraldb_metadata_helpers.py` (append new test classes) -- Modify: `src/orcapod/databases/spiraldb_connector.py` (append new helpers) +- Modify: `src/orcapod/databases/spiraldb_keyed/connector.py` (append new helpers) - [ ] **Step 1: Write failing tests for `_load_arrow_metadata` and `_restore_field`** @@ -522,7 +522,7 @@ Expected: `ImportError` — `_load_arrow_metadata` and `_restore_field` not defi - [ ] **Step 3: Implement `_load_arrow_metadata`, `_restore_arrow_type`, and `_restore_field`** -Append to `src/orcapod/databases/spiraldb_connector.py` (after `_serialize_arrow_metadata`): +Append to `src/orcapod/databases/spiraldb_keyed/connector.py` (after `_serialize_arrow_metadata`): ```python def _load_arrow_metadata( @@ -669,7 +669,7 @@ Expected: all pass. - [ ] **Step 5: Commit** ```bash -git add src/orcapod/databases/spiraldb_connector.py tests/test_databases/test_spiraldb_metadata_helpers.py +git add src/orcapod/databases/spiraldb_keyed/connector.py tests/test_databases/test_spiraldb_metadata_helpers.py git commit -m "feat(spiraldb): add _load_arrow_metadata and _restore_field helpers (ITL-471)" ``` @@ -681,7 +681,7 @@ git commit -m "feat(spiraldb): add _load_arrow_metadata and _restore_field helpe - Modify: `src/orcapod/protocols/db_connector_protocol.py` - Modify: `src/orcapod/databases/sqlite_connector.py` - Modify: `src/orcapod/databases/postgresql_connector.py` -- Modify: `src/orcapod/databases/spiraldb_connector.py` +- Modify: `src/orcapod/databases/spiraldb_keyed/connector.py` - Modify: `src/orcapod/databases/connector_arrow_database.py` - Modify: `tests/test_databases/test_connector_arrow_database.py` - Modify: `tests/test_databases/test_spiraldb_connector.py` @@ -693,7 +693,7 @@ git commit -m "feat(spiraldb): add _load_arrow_metadata and _restore_field helpe ```python class TestValidateRecords: def test_no_op_for_plain_columns(self, connector): - """validate_records is a no-op on SpiralDBConnector for plain columns.""" + """validate_records is a no-op on SpiralDBKeyedConnector for plain columns.""" table = pa.table({ "id": pa.array([b"a"], type=pa.large_binary()), "value": pa.array([1], type=pa.int64()), @@ -701,7 +701,7 @@ class TestValidateRecords: connector.validate_records(table) # must not raise def test_no_op_for_extension_typed_columns(self, connector): - """SpiralDBConnector.validate_records allows extension-typed columns.""" + """SpiralDBKeyedConnector.validate_records allows extension-typed columns.""" ext_field = pa.field( "payload", pa.large_string(), @@ -758,7 +758,7 @@ Add a new test at the end of `TestExtensionTypeWriteGuard`: uv run pytest tests/test_databases/test_spiraldb_connector.py::TestValidateRecords tests/test_databases/test_connector_arrow_database.py::TestExtensionTypeWriteGuard::test_permissive_connector_allows_extension_types -v --tb=short ``` -Expected: `AttributeError: 'SpiralDBConnector' object has no attribute 'validate_records'` +Expected: `AttributeError: 'SpiralDBKeyedConnector' object has no attribute 'validate_records'` - [ ] **Step 3: Add `validate_records` to `DBConnectorProtocol`** @@ -860,13 +860,13 @@ In `src/orcapod/databases/postgresql_connector.py`, add after the `upsert_record ) ``` -- [ ] **Step 6: Add no-op `validate_records` to `SpiralDBConnector`** +- [ ] **Step 6: Add no-op `validate_records` to `SpiralDBKeyedConnector`** -In `src/orcapod/databases/spiraldb_connector.py`, add after the `upsert_records` method (before `def close`): +In `src/orcapod/databases/spiraldb_keyed/connector.py`, add after the `upsert_records` method (before `def close`): ```python def validate_records(self, records: "pa.Table") -> None: - """No-op: ``SpiralDBConnector`` preserves Arrow field metadata via the native KV store.""" + """No-op: ``SpiralDBKeyedConnector`` preserves Arrow field metadata via the native KV store.""" ``` - [ ] **Step 7: Add `validate_records` to `MockDBConnector` in the test file** @@ -957,7 +957,7 @@ git add \ src/orcapod/protocols/db_connector_protocol.py \ src/orcapod/databases/sqlite_connector.py \ src/orcapod/databases/postgresql_connector.py \ - src/orcapod/databases/spiraldb_connector.py \ + src/orcapod/databases/spiraldb_keyed/connector.py \ src/orcapod/databases/connector_arrow_database.py \ tests/test_databases/test_connector_arrow_database.py \ tests/test_databases/test_spiraldb_connector.py @@ -970,7 +970,7 @@ git commit -m "feat(spiraldb): add per-connector validate_records hook, replace **Files:** - Modify: `tests/test_databases/test_spiraldb_connector.py` (append new test class) -- Modify: `src/orcapod/databases/spiraldb_connector.py` +- Modify: `src/orcapod/databases/spiraldb_keyed/connector.py` - [ ] **Step 1: Write failing tests** @@ -1071,7 +1071,7 @@ Expected: `AssertionError` — `set_metadata` not called (feature not implemente - [ ] **Step 3: Modify `upsert_records` to write metadata** -In `src/orcapod/databases/spiraldb_connector.py`, find the `upsert_records` method. The current structure is: +In `src/orcapod/databases/spiraldb_keyed/connector.py`, find the `upsert_records` method. The current structure is: ```python if not skip_existing: @@ -1129,7 +1129,7 @@ Expected: all pass. - [ ] **Step 5: Commit** ```bash -git add src/orcapod/databases/spiraldb_connector.py tests/test_databases/test_spiraldb_connector.py +git add src/orcapod/databases/spiraldb_keyed/connector.py tests/test_databases/test_spiraldb_connector.py git commit -m "feat(spiraldb): persist Arrow metadata in upsert_records via KV store (ITL-471)" ``` @@ -1139,7 +1139,7 @@ git commit -m "feat(spiraldb): persist Arrow metadata in upsert_records via KV s **Files:** - Modify: `tests/test_databases/test_spiraldb_connector.py` (append new test class) -- Modify: `src/orcapod/databases/spiraldb_connector.py` +- Modify: `src/orcapod/databases/spiraldb_keyed/connector.py` - [ ] **Step 1: Write failing tests** @@ -1232,7 +1232,7 @@ Expected: `AssertionError` — metadata not reattached (feature not implemented) - [ ] **Step 3: Modify `iter_batches` to restore metadata** -In `src/orcapod/databases/spiraldb_connector.py`, find `iter_batches`. Replace the body starting from `table_name = _parse_table_name(query)` onward: +In `src/orcapod/databases/spiraldb_keyed/connector.py`, find `iter_batches`. Replace the body starting from `table_name = _parse_table_name(query)` onward: ```python table_name = _parse_table_name(query) @@ -1295,7 +1295,7 @@ Expected: all pass (integration tests skipped). - [ ] **Step 6: Commit** ```bash -git add src/orcapod/databases/spiraldb_connector.py tests/test_databases/test_spiraldb_connector.py +git add src/orcapod/databases/spiraldb_keyed/connector.py tests/test_databases/test_spiraldb_connector.py git commit -m "feat(spiraldb): restore Arrow metadata in iter_batches via recursive _restore_field (ITL-471)" ``` @@ -1304,11 +1304,11 @@ git commit -m "feat(spiraldb): restore Arrow metadata in iter_batches via recurs ## Task 7: Integration tests **Files:** -- Modify: `tests/test_databases/test_spiraldb_connector_integration.py` +- Modify: `tests/test_databases/test_spiraldb_keyed_connector_integration.py` - [ ] **Step 1: Append `TestArrowMetadataRoundTrip` class** -Append to `tests/test_databases/test_spiraldb_connector_integration.py`: +Append to `tests/test_databases/test_spiraldb_keyed_connector_integration.py`: ```python class TestArrowMetadataRoundTrip: @@ -1521,7 +1521,7 @@ class TestArrowMetadataRoundTrip: - [ ] **Step 2: Verify integration tests are skipped (no credentials)** ```bash -uv run pytest tests/test_databases/test_spiraldb_connector_integration.py -v --tb=short +uv run pytest tests/test_databases/test_spiraldb_keyed_connector_integration.py -v --tb=short ``` Expected: all skipped (`Set SPIRAL_INTEGRATION_TESTS=1 to run SpiralDB integration tests`). @@ -1529,7 +1529,7 @@ Expected: all skipped (`Set SPIRAL_INTEGRATION_TESTS=1 to run SpiralDB integrati - [ ] **Step 3: Commit** ```bash -git add tests/test_databases/test_spiraldb_connector_integration.py +git add tests/test_databases/test_spiraldb_keyed_connector_integration.py git commit -m "test(spiraldb): add TestArrowMetadataRoundTrip integration tests (ITL-471)" ``` @@ -1540,7 +1540,7 @@ git commit -m "test(spiraldb): add TestArrowMetadataRoundTrip integration tests - [ ] **Step 1: Run the complete unit test suite** ```bash -uv run pytest tests/ -v --tb=short -q --ignore=tests/test_databases/test_spiraldb_connector_integration.py +uv run pytest tests/ -v --tb=short -q --ignore=tests/test_databases/test_spiraldb_keyed_connector_integration.py ``` Expected: all pass. @@ -1572,7 +1572,7 @@ git push -u origin eywalker/itl-471-spiraldbconnector-preserve-arrow-table-and-c | `validate_records` on `DBConnectorProtocol` | Task 4 | | `SQLiteConnector.validate_records` rejecting | Task 4 | | `PostgreSQLConnector.validate_records` rejecting | Task 4 | -| `SpiralDBConnector.validate_records` no-op | Task 4 | +| `SpiralDBKeyedConnector.validate_records` no-op | Task 4 | | `ConnectorArrowDatabase` guard replaced | Task 4 | | Schema metadata integration test | Task 7 | | Field metadata integration test | Task 7 | diff --git a/docs/dev/plans/2026-11-09-v0.2-release-checklist.md b/docs/dev/plans/2026-11-09-v0.2-release-checklist.md index 15aa233b0..3539ec439 100644 --- a/docs/dev/plans/2026-11-09-v0.2-release-checklist.md +++ b/docs/dev/plans/2026-11-09-v0.2-release-checklist.md @@ -486,7 +486,7 @@ The 16 skips: - 7 in `tests/test_databases/test_delta_table_database_s3.py` — MinIO container could not be started (no Docker here; skipped in CI too, ITL-819). -- 9 in `tests/test_databases/test_spiraldb_connector_integration.py` — need +- 9 in `tests/test_databases/test_spiraldb_keyed_connector_integration.py` — need `SPIRAL_INTEGRATION_TESTS=1` and credentials. The 77 deselected are the `postgres`-marked tests, which the Release workflow also diff --git a/docs/dev/plans/2026-11-11-itl-936-spiral-nullability-record.md b/docs/dev/plans/2026-11-11-itl-936-spiral-nullability-record.md index cfe6c8241..34804d57f 100644 --- a/docs/dev/plans/2026-11-11-itl-936-spiral-nullability-record.md +++ b/docs/dev/plans/2026-11-11-itl-936-spiral-nullability-record.md @@ -8,9 +8,9 @@ records each table's non-nullable column paths in the table's key-value metadata when it writes, restores them on read, and checks every batch, so recorded columns arrive as `T`. -**Architecture:** A pure module `orcapod/databases/spiraldb_nullability.py` (no pyspiral import) +**Architecture:** A pure module `orcapod/databases/spiraldb_keyed/nullability.py` (no pyspiral import) encodes/decodes a versioned, chunked JSON record, applies it to an Arrow schema and checks a -batch against it. `SpiralDBConnector` calls it in `upsert_records` (write the record on a +batch against it. `SpiralDBKeyedConnector` calls it in `upsert_records` (write the record on a table's first write, refuse a disagreeing later write, refuse nulls in non-null paths before anything is written), `get_column_info` (schema) and `iter_batches` (check + restore per batch), wrapping errors with project/dataset/table. Tables without a record are untouched. @@ -86,7 +86,7 @@ into a struct of null fields ("SpiralDB doesn't allow struct-level nullability") -> dict[str, bytes]`; any writer does `table.set_metadata(nullability_record_metadata(schema))` with the Arrow schema it writes. `orcapod.databases.read_nullability_record(metadata) -> frozenset[tuple[str, ...]] | None` reads it back (for `verify`). -* `SpiralDBConnector.upsert_records(records)`: +* `SpiralDBKeyedConnector.upsert_records(records)`: 1. Check `records` has no null in any non-null path (else `NullInNonNullableColumnError`, nothing written: SpiralDB would store `0` in a struct field). 2. Table has a record: the incoming schema's non-null paths must equal it, else @@ -155,12 +155,12 @@ if read_nullability_record(table.get_metadata()) != read_nullability_record(kv): ## File structure -* Create `src/orcapod/databases/spiraldb_nullability.py`: record encode/decode, schema apply, +* Create `src/orcapod/databases/spiraldb_keyed/nullability.py`: record encode/decode, schema apply, batch enforce. Pure pyarrow. * Modify `src/orcapod/errors.py`: `NullabilityRecordError`, `NullabilityRecordMismatchError`, `NullInNonNullableColumnError` (all `ValueError` subclasses; the last two carry `column`/`table` attributes). -* Modify `src/orcapod/databases/spiraldb_connector.py`: write/read integration. +* Modify `src/orcapod/databases/spiraldb_keyed/connector.py`: write/read integration. * Modify `src/orcapod/databases/__init__.py`: export the two public helpers. * Modify `tests/test_databases/fake_pyspiral.py`: server nullability behaviour. * Tests: `tests/test_databases/test_spiraldb_nullability.py` (helpers), @@ -205,7 +205,7 @@ if read_nullability_record(table.get_metadata()) != read_nullability_record(kv): ### Task 4: Source end to end -- [ ] Rewrite `TestNonNullableColumns` to write through `SpiralDBConnector` (record) and show: +- [ ] Rewrite `TestNonNullableColumns` to write through `SpiralDBKeyedConnector` (record) and show: `T` schema, pod `x: float`/`int` runs, Join, save/load. Unrecorded table: pod refused. - [ ] Unrecorded table hashes pinned by explicit values (computed before the change). - [ ] `TestSourceId.test_explicit_source_id_keeps_its_hashes`: the table written through the diff --git a/docs/dev/plans/2026-11-12-itl-186-streaming-spiral-source.md b/docs/dev/plans/2026-11-12-itl-186-streaming-spiral-source.md index 9081c608e..d542e5b32 100644 --- a/docs/dev/plans/2026-11-12-itl-186-streaming-spiral-source.md +++ b/docs/dev/plans/2026-11-12-itl-186-streaming-spiral-source.md @@ -39,7 +39,7 @@ pyspiral fake, which gains a scan log. |---|---| | `tests/test_databases/fake_pyspiral.py` | fake: scan log, lazy batches, `limit` (Phase A); `where`, `asof`, `table_id`, `last_modified_at`, row count (Phase B) | | `tests/test_core/sources/test_spiraldb_table_source_streaming.py` | new: streaming behaviour through the public interface | -| `src/orcapod/databases/spiraldb_connector.py` | Phase B: metadata-only reads and a restricted scan | +| `src/orcapod/databases/spiraldb_keyed/connector.py` | Phase B: metadata-only reads and a restricted scan | | `src/orcapod/core/sources/spiraldb_table_source.py` | Phase B: the source | | `docs/concepts/sources.md`, `changelog.d/ITL-186.md`, `design_issues/ITL-186-SP4.md` | Phase B | diff --git a/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md b/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md index de7f31bdd..4b3bea8bc 100644 --- a/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md +++ b/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md @@ -4,7 +4,7 @@ Stage A of using SpiralDB as a job's pipeline and result database (ITL-1446). It the still-valid parts of PRs 589 (ITL-1495) and 590 (ITL-1497) onto current `main`, and the manifest-in-metadata part of PR 595 (ITL-1498). Those branches were sources to copy from; none is merged. Nothing here is public: no way to open a store exists, and -`SpiralDBConnector` still refuses every write (`SpiralDBWriteNotSupportedError`). +`SpiralDBKeyedConnector` still refuses every write (`SpiralDBWriteNotSupportedError`). ## The store format is provisional @@ -33,7 +33,7 @@ keyed tables deprecated: `Client.keyed_table`, `keyed_table_by_id` and DeprecationWarning, stacklevel=3)`, so the warning is attributed to the module that calls the SDK. 0.16.80 changes nothing else Orcapod uses (it removes the duration types, which the store already refuses). Orcapod's only module that opens or creates keyed tables is -`orcapod.databases.spiraldb_connector` (the schema migration script opens and creates +`orcapod.databases.spiraldb_keyed.connector` (the schema migration script opens and creates through its helpers `_open_keyed_table` and `_create_keyed_table`); before each open or creation it puts one filter FIRST in the filter list: action `ignore`, that exact message, `DeprecationWarning`, and that module only (`_ignore_keyed_table_deprecation`). First, not @@ -133,7 +133,7 @@ round trip of every other row in one manifest pass. ## What is left (later stages of ITL-1446) -Store mode in `SpiralDBConnector` and `ConnectorArrowDatabase` (create on first write, find +Store mode in `SpiralDBKeyedConnector` and `ConnectorArrowDatabase` (create on first write, find by name, the identity and manifest checks, data-context checks, listing for stale layouts), the write rules of ITL-1386 for the store, the one-writer lease, the public switch-on with save and load, and every table kind end to end. diff --git a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md index af817cf75..9f08239ab 100644 --- a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md +++ b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md @@ -8,8 +8,8 @@ collides with `main`'s SQL store catalog (`_sql_store.py`, ITL-1552) and is not Its `spiraldb_store_tables.py` and its tests are. Nothing is public. The store mode is a private constructor argument, -`SpiralDBConnector(project, dataset, _store=True)`, read and written only through -`ConnectorArrowDatabase`. A plain `SpiralDBConnector` behaves as on `main`: it reads and +`SpiralDBKeyedConnector(project, dataset, _store=True)`, read and written only through +`ConnectorArrowDatabase`. A plain `SpiralDBKeyedConnector` behaves as on `main`: it reads and refuses every write (`SpiralDBWriteNotSupportedError`). ## Structure @@ -19,7 +19,7 @@ refuses every write (`SpiralDBWriteNotSupportedError`). `store_table_names.require_store_path_domain`, the one path domain the identity record and the manifest apply). Each table's metadata holds its identity record and manifest, written in one upsert before its first rows. Rows go through the codec (`spiral_store`). -- `SpiralDBConnector` builds a `StoreTables` when `_store=True`, hands it out through the +- `SpiralDBKeyedConnector` builds a `StoreTables` when `_store=True`, hands it out through the private `_store_tables()`, and in store mode refuses raw access (`lookup_table`, `iter_batches`, `get_table_names` and every read built on them) with a `ValueError`. Its protocol write methods still raise `SpiralDBWriteNotSupportedError`. `to_config` refuses @@ -27,10 +27,10 @@ refuses every write (`SpiralDBWriteNotSupportedError`). - `ConnectorArrowDatabase` gets an internal store branch beside `_sql_store`: naming, finding, reading, the stored-id check, listing, column info, the stored schema, the storable-column check, validation and the write go to `StoreTables` when the connector - is a store-mode `SpiralDBConnector`. `DBConnectorProtocol` is unchanged. + is a store-mode `SpiralDBKeyedConnector`. `DBConnectorProtocol` is unchanged. The branch is taken only for a store-mode connector. For every other connector, the -plain `SpiralDBConnector` included, the code paths are `main`'s, with one exception: a +plain `SpiralDBKeyedConnector` included, the code paths are `main`'s, with one exception: a lookup of committed rows (`get_record_by_id`, `get_all_records` and the reads built on them) now raises `OrcapodDatabaseReadError` on every connector when finding or reading the stored table fails, as `get_table_schema` already did. For example, a SQLite diff --git a/docs/dev/plans/itl-998-plan.md b/docs/dev/plans/itl-998-plan.md index 536f41c43..9d910a534 100644 --- a/docs/dev/plans/itl-998-plan.md +++ b/docs/dev/plans/itl-998-plan.md @@ -52,9 +52,9 @@ ITL-1477, stays an isolated addition: one gate, one function and their tests, li `filter` (the docstring names ITL-1477 for floats; the error text does not). The sentence calling a range of the first key columns "the cheapest to read" is removed (not measured). -### `src/orcapod/databases/spiraldb_connector.py` +### `src/orcapod/databases/spiraldb_keyed/connector.py` -- The `where` parameter of `SpiralDBConnector.scan_batches` is PROVISIONAL and takes the source's +- The `where` parameter of `SpiralDBKeyedConnector.scan_batches` is PROVISIONAL and takes the source's `Condition` (its terms are the one list of `(column, operator, value)`) instead of a mapping; done this way rather than a new `terms=` argument, since `Condition` is the one restriction class. One loop builds the predicate: an equality as today (`_literal`; a `float16` equality still @@ -111,7 +111,7 @@ dicts, which ignore order, so they keep passing; one new test compares the JSON - `tests/test_core/sources/test_spiraldb_table_source_live.py` (`ORCAPOD_SPIRALDB_TEST_PROJECT`, read-only): a window, and a window with an equality, equal the local selection of the full read; record ids a subset; arguments reversed; `limit`; `head`; an empty window. -- `tests/test_databases/test_spiraldb_connector_integration.py` (`SPIRAL_INTEGRATION_TESTS`, writes its own +- `tests/test_databases/test_spiraldb_keyed_connector_integration.py` (`SPIRAL_INTEGRATION_TESTS`, writes its own tables and drops them): the kept form of the conformance probe for every type of section 2, against pyarrow, plus the float order the service uses (so a change in it shows, and ITL-1477 starts from it), run on the final code before ready (D12). The fake runs the same cases. diff --git a/docs/dev/scripts/itl_1371_logical_identity_appends.py b/docs/dev/scripts/itl_1371_logical_identity_appends.py index b874d36a9..a8105f52a 100644 --- a/docs/dev/scripts/itl_1371_logical_identity_appends.py +++ b/docs/dev/scripts/itl_1371_logical_identity_appends.py @@ -25,7 +25,7 @@ from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase -from orcapod.databases.spiraldb_connector import SpiralDBConnector +from orcapod.databases.spiraldb_keyed.connector import SpiralDBKeyedConnector from orcapod.databases.sqlite_connector import SQLiteConnector NAME = b"ARROW:extension:name" @@ -117,7 +117,7 @@ def open_db(kind: str, root: Path): if kind == "SQLite": return ConnectorArrowDatabase(SQLiteConnector(str(root / "s.db"))) if kind == "SpiralDB": - return ConnectorArrowDatabase(SpiralDBConnector("p")) + return ConnectorArrowDatabase(SpiralDBKeyedConnector("p")) raise AssertionError(kind) @@ -149,7 +149,9 @@ def main() -> None: warnings.simplefilter("ignore") kinds = ["in-memory", "Delta", "SQLite", "SpiralDB"] with tempfile.TemporaryDirectory() as tmp: - from tests.test_databases import fake_pyspiral # pyright: ignore[reportAttributeAccessIssue] # historical: ran on the pyspiral fake, removed in ITL-1186 + from tests.test_databases import ( + fake_pyspiral, # pyright: ignore[reportAttributeAccessIssue] # historical: ran on the pyspiral fake, removed in ITL-1186 + ) with fake_pyspiral.install(Path(tmp) / "spiral"): fake_pyspiral.FakeSpiral().project("p") diff --git a/docs/dev/scripts/itl_1844_database_evaluation.py b/docs/dev/scripts/itl_1844_database_evaluation.py index 7bf6606a6..cb4d09a01 100644 --- a/docs/dev/scripts/itl_1844_database_evaluation.py +++ b/docs/dev/scripts/itl_1844_database_evaluation.py @@ -46,18 +46,17 @@ from orcapod.databases import ( # noqa: E402 ConnectorArrowDatabase, DeltaTableDatabase, - SpiralDBConnector, + SpiralDBKeyedConnector, + spiraldb_lease, # noqa: E402 ) -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.spiraldb_keyed.connector import _open_keyed_table # noqa: E402 +from orcapod.databases.spiraldb_keyed.identity import spiral_table_name # noqa: E402 +from orcapod.databases.spiraldb_keyed.write_scope import take_lease # noqa: E402 from orcapod.databases.store_table_names import spiral_lease_table_name # 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 - VOLATILE = { "__data_id", "__pipeline_record_id", @@ -211,7 +210,7 @@ def evaluate( def spiral_db() -> ConnectorArrowDatabase: return ConnectorArrowDatabase( - SpiralDBConnector(project, dataset, writable=True) + SpiralDBKeyedConnector(project, dataset, writable=True) ) delta = DeltaTableDatabase(work / "delta") @@ -296,7 +295,8 @@ def spiral_db() -> ConnectorArrowDatabase: # 8. a second writer is refused while another holds the lease. _, release = take_lease( - SpiralDBConnector(project, dataset, writable=True), "evaluation: another writer" + SpiralDBKeyedConnector(project, dataset, writable=True), + "evaluation: another writer", ) fresh = f"itl1844_eval_{stamp}_refused" try: @@ -376,7 +376,7 @@ def database_tables(project: str, dataset: str, stamp: str) -> list[dict[str, st dataset holds a table of another table format under a database table name. """ spiral_db = ConnectorArrowDatabase( - SpiralDBConnector(project, dataset, writable=True) + SpiralDBKeyedConnector(project, dataset, writable=True) ) every = sorted( path @@ -391,7 +391,7 @@ 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) + connector = SpiralDBKeyedConnector(project, dataset) client = connector._client # pyright: ignore[reportPrivateUsage] # a listing for the report found: list[dict[str, str]] = [] generation = 1 diff --git a/docs/dev/scripts/itl_1903/rename.py b/docs/dev/scripts/itl_1903/rename.py new file mode 100644 index 000000000..ab172987a --- /dev/null +++ b/docs/dev/scripts/itl_1903/rename.py @@ -0,0 +1,195 @@ +"""Apply the keyed SpiralDB rename from a checkout, including after a merge. + +Run with `uv run python docs/dev/scripts/itl_1903/rename.py` and review the diff. +Run Ruff's import and format checks after applying it. Re-running the script +leaves previously renamed files alone and updates references added upstream. +""" + +from __future__ import annotations + +import os +import subprocess +from pathlib import Path + +DATABASES = Path("src/orcapod/databases") +KEYED_MODULES = { + "spiraldb_connector": "connector", + "spiraldb_nullability": "nullability", + "spiraldb_schema_table": "schema_table", + "spiraldb_sign_in": "sign_in", + "spiraldb_tables": "tables", + "spiraldb_writable_registry": "writable_registry", + "spiraldb_write_scope": "write_scope", + "spiral_database_identity": "identity", +} +# The lease may be deleted upstream. Its successor and the shared codec also +# retain their generic module paths. +GENERIC_MODULES = ("spiral_database_codec", "spiraldb_lease", "write_lock") +MOVES = { + **{ + DATABASES / f"{old}.py": DATABASES / "spiraldb_keyed" / f"{new}.py" + for old, new in KEYED_MODULES.items() + }, + Path("docs/concepts/spiraldb-database.md"): Path( + "docs/concepts/spiraldb-keyed-database.md" + ), + Path("tests/test_databases/test_spiraldb_connector_integration.py"): Path( + "tests/test_databases/test_spiraldb_keyed_connector_integration.py" + ), +} +TEXT_ROOTS = {"src", "tests", "scripts", "docs", "changelog.d"} +TEXT_SUFFIXES = {".py", ".md"} +EXTRA_TEXT = { + Path(".github/workflows/run-tests.yml"), + Path("site/astro.config.mjs"), + Path("CLAUDE.md"), + Path(".zed/rules"), +} +BASELINE = Path(".basedpyright/baseline.json") +SCRIPT_DIR = Path("docs/dev/scripts/itl_1903") +RENAME_FRAGMENT = Path("changelog.d/ITL-1903.md") +REPLACEMENTS = ( + ("SpiralDBConnector", "SpiralDBKeyedConnector"), + ('"connector_type": "spiraldb"', '"connector_type": "spiraldb_keyed"'), + ('"postgresql", "spiraldb")', '"postgresql", "spiraldb_keyed")'), + ('``"postgresql"``, ``"spiraldb"``', '``"postgresql"``, ``"spiraldb_keyed"``'), + ('``"postgresql"`` or ``"spiraldb"``', '``"postgresql"`` or ``"spiraldb_keyed"``'), + ( + 'connector_type`` is not ``"spiraldb"``', + 'connector_type`` is not ``"spiraldb_keyed"``', + ), + ( + 'config.get("connector_type") != "spiraldb"', + 'config.get("connector_type") != "spiraldb_keyed"', + ), + ("Expected connector_type 'spiraldb'", "Expected connector_type 'spiraldb_keyed'"), + ( + 'saved_connector_kind(config) != "spiraldb"', + 'saved_connector_kind(config) != "spiraldb_keyed"', + ), + ("# SpiralDB as a Job's", "# Keyed SpiralDB as a Job's"), + ("[SpiralDB as a Job's", "[Keyed SpiralDB as a Job's"), + (r"page('SpiralDB as a Job\'s", r"page('Keyed SpiralDB as a Job\'s"), + ("spiraldb-database", "spiraldb-keyed-database"), + ( + "test_spiraldb_connector_integration.py", + "test_spiraldb_keyed_connector_integration.py", + ), + ("from .spiraldb_connector import ", "from .spiraldb_keyed.connector import "), + ( + "from orcapod.databases import SpiralDBKeyedConnector, spiraldb_connector", + "from orcapod.databases import SpiralDBKeyedConnector\n" + "from orcapod.databases.spiraldb_keyed import connector as spiraldb_connector", + ), + ( + "from orcapod.databases import ConnectorArrowDatabase, spiraldb_connector", + "from orcapod.databases import ConnectorArrowDatabase\n" + "from orcapod.databases.spiraldb_keyed import connector as spiraldb_connector", + ), + ( + "from orcapod.databases import spiraldb_connector, spiraldb_lease", + "from orcapod.databases import spiraldb_lease\n" + "from orcapod.databases.spiraldb_keyed import connector as spiraldb_connector", + ), + ( + "from orcapod.databases import spiraldb_lease, spiraldb_write_scope", + "from orcapod.databases import spiraldb_lease\n" + "from orcapod.databases.spiraldb_keyed import write_scope as spiraldb_write_scope", + ), + ( + " spiraldb_connector,\n" + " spiraldb_lease,\n" + " spiraldb_writable_registry,\n" + " spiraldb_write_scope,\n" + ")", + " spiraldb_lease,\n" + ")\n" + "from orcapod.databases.spiraldb_keyed import (\n" + " connector as spiraldb_connector,\n" + " writable_registry as spiraldb_writable_registry,\n" + " write_scope as spiraldb_write_scope,\n" + ")", + ), +) + + +def git(*args: str) -> str: + return subprocess.run( + ["git", *args], check=True, stdout=subprocess.PIPE, text=True + ).stdout + + +def move_files() -> None: + for old, new in MOVES.items(): + if old.exists() == new.exists(): + raise SystemExit(f"Expected exactly one of {old} and {new} to exist.") + for old, new in MOVES.items(): + if old.exists(): + new.parent.mkdir(parents=True, exist_ok=True) + git("mv", "--", str(old), str(new)) + + +def replace_text(text: str) -> str: + for old, new in REPLACEMENTS: + text = text.replace(old, new) + for old, new in KEYED_MODULES.items(): + text = text.replace( + f"orcapod.databases.{old}", f"orcapod.databases.spiraldb_keyed.{new}" + ) + text = text.replace(f"databases/{old}.py", f"databases/spiraldb_keyed/{new}.py") + text = text.replace( + f"from orcapod.databases import {old} as ", + f"from orcapod.databases.spiraldb_keyed import {new} as ", + ) + text = text.replace( + f"from orcapod.databases import {old}\n", + f"from orcapod.databases.spiraldb_keyed import {new} as {old}\n", + ) + text = text.replace( + f"from orcapod.databases import {old} # noqa: E402 # after the skip\n", + "from orcapod.databases.spiraldb_keyed import ( # noqa: E402 # after the skip\n" + f" {new} as {old},\n" + ")\n", + ) + text = text.replace(f"``{old}``", f"``spiraldb_keyed.{new}``") + text = text.replace(f"``{old}.", f"``spiraldb_keyed.{new}.") + return text + + +def main() -> None: + os.chdir(Path(__file__).resolve().parents[4]) + move_files() + package = DATABASES / "spiraldb_keyed" / "__init__.py" + if not package.exists(): + package.write_text( + '"""The keyed-table backend for SpiralDB."""\n', encoding="utf-8" + ) + + generic_paths = {DATABASES / f"{module}.py" for module in GENERIC_MODULES} + for name in git("ls-files", "-z").split("\0"): + if not name: + continue + path = Path(name) + if path == BASELINE: + original = path.read_text(encoding="utf-8") + updated = original + for old, new in MOVES.items(): + updated = updated.replace(f'"./{old}":', f'"./{new}":') + elif path in EXTRA_TEXT or ( + path.parts[0] in TEXT_ROOTS + and path.suffix in TEXT_SUFFIXES + and not path.is_relative_to(SCRIPT_DIR) + and not path.is_relative_to("tests/test_hashing/golden") + and path != RENAME_FRAGMENT + and (path not in generic_paths or path.exists()) + ): + original = path.read_text(encoding="utf-8") + updated = replace_text(original) + else: + continue + if original != updated: + path.write_text(updated, encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/docs/dev/specs/2026-06-22-pyspiral-upgrade-fix-ci-header-signing.md b/docs/dev/specs/2026-06-22-pyspiral-upgrade-fix-ci-header-signing.md index b2e1079ff..394d5f595 100644 --- a/docs/dev/specs/2026-06-22-pyspiral-upgrade-fix-ci-header-signing.md +++ b/docs/dev/specs/2026-06-22-pyspiral-upgrade-fix-ci-header-signing.md @@ -8,7 +8,7 @@ ## Problem -All three `TestSpiralDBConnectorIntegration` tests have been failing in CI on every push to +All three `TestSpiralDBKeyedConnectorIntegration` tests have been failing in CI on every push to `extension-type-system` and `main` since approximately June 15, 2026 (between 04:04 and 20:57 UTC). The error is identical across all tests: @@ -59,7 +59,7 @@ downgrade. Full API compatibility check between 0.11.7 and 0.14.9: -| API call (in `SpiralDBConnector`) | Status | +| API call (in `SpiralDBKeyedConnector`) | Status | |---|---| | `sp.Spiral(overrides=...)` | ✅ unchanged | | `spiral.project(project_id)` | ✅ unchanged | @@ -77,7 +77,7 @@ Unit tests mock the `sp` module entirely and are unaffected by the version chang ### 4. Add breadcrumb comments -- **`tests/test_databases/test_spiraldb_connector_integration.py`** — extend the module +- **`tests/test_databases/test_spiraldb_keyed_connector_integration.py`** — extend the module docstring to document the t3.storage.dev enforcement change and explain that pyspiral must be kept up to date. - **`DESIGN_ISSUES.md`** — add a new entry recording the root cause, the symptom, and @@ -103,7 +103,7 @@ Unit tests mock the `sp` module entirely and are unaffected by the version chang - Breadcrumb documentation **Out of scope:** -- Changes to `SpiralDBConnector` logic (API is compatible — no edits needed) +- Changes to `SpiralDBKeyedConnector` logic (API is compatible — no edits needed) - Pinning the runner image or GitHub Actions environment - Any SpiralDB connector refactor diff --git a/docs/dev/specs/2026-07-08-itl-471-spiraldb-arrow-metadata-preservation-design.md b/docs/dev/specs/2026-07-08-itl-471-spiraldb-arrow-metadata-preservation-design.md index d84b0feb5..b945f84dd 100644 --- a/docs/dev/specs/2026-07-08-itl-471-spiraldb-arrow-metadata-preservation-design.md +++ b/docs/dev/specs/2026-07-08-itl-471-spiraldb-arrow-metadata-preservation-design.md @@ -1,4 +1,4 @@ -# ITL-471: SpiralDBConnector — Preserve Arrow Table- and Column-Level Metadata via Native KV Store +# ITL-471: SpiralDBKeyedConnector — Preserve Arrow Table- and Column-Level Metadata via Native KV Store **Date:** 2026-07-08 **Issue:** [ITL-471](https://linear.app/enigma-metamorphic/issue/ITL-471) @@ -8,12 +8,12 @@ ## Overview -`SpiralDBConnector` writes Arrow tables to SpiralDB via `tbl.write(records)` and reads them +`SpiralDBKeyedConnector` writes Arrow tables to SpiralDB via `tbl.write(records)` and reads them back via `self._spiral.scan(tbl.select()).to_record_batches()`. SpiralDB's Vortex columnar format silently drops all Arrow metadata — both schema-level (`schema.metadata`) and per-column (`field.metadata`) — on ingestion. This makes it impossible to round-trip Arrow extension types (Path, UUID, dataclass, etc.) through the SpiralDB backend, and prevents -`SpiralDBConnector` from participating in the peek-register-read pattern used for extension +`SpiralDBKeyedConnector` from participating in the peek-register-read pattern used for extension type auto-registration. SpiralDB exposes a native table-level KV metadata store (`Table.set_metadata` / @@ -29,13 +29,13 @@ guard and replaces it with a per-connector hook. ## Goals & Success Criteria -- On write, `SpiralDBConnector` serializes `schema.metadata` and per-field `field.metadata` +- On write, `SpiralDBKeyedConnector` serializes `schema.metadata` and per-field `field.metadata` from the incoming Arrow table into the SpiralDB native KV store. - On read (`iter_batches`), the connector loads stored metadata and reattaches it to the reconstructed Arrow schema and per-field `pa.Field` objects; the existing `large_string`/`large_binary` normalization is preserved. - Arrow extension types survive a full write→read cycle through `ConnectorArrowDatabase` + - `SpiralDBConnector`, enabling `register_discovered_extensions` / peek-register-read. + `SpiralDBKeyedConnector`, enabling `register_discovered_extensions` / peek-register-read. - The `ValueError` extension-type guard in `ConnectorArrowDatabase.add_records` no longer triggers for the SpiralDB backend. Other connectors (SQLite, PostgreSQL) continue to reject extension-typed records by default. @@ -55,7 +55,7 @@ In scope: - A single stable KV key encoding scheme under `"__arrow_metadata__"`. - Restoring metadata on read so extension-type discovery works. - Per-connector `validate_records` hook on `DBConnectorProtocol` (default rejects - extension types; `SpiralDBConnector` overrides to no-op). + extension types; `SpiralDBKeyedConnector` overrides to no-op). - Replacing `ConnectorArrowDatabase`'s inline extension-type guard with a delegation call to `self._connector.validate_records(records)`. - Unit tests and SpiralDB-backend integration tests. @@ -272,11 +272,11 @@ def validate_records(self, records: "pa.Table") -> None: ) ``` -`SpiralDBConnector` overrides it as a no-op: +`SpiralDBKeyedConnector` overrides it as a no-op: ```python def validate_records(self, records: "pa.Table") -> None: - """No-op: SpiralDBConnector preserves Arrow field metadata via the native KV store.""" + """No-op: SpiralDBKeyedConnector preserves Arrow field metadata via the native KV store.""" ``` `SQLiteConnector` and `PostgreSQLConnector` inherit the default-reject behavior without @@ -313,7 +313,7 @@ No other changes to `ConnectorArrowDatabase`. correct KV dict; skipped when records have no Arrow metadata; `skip_existing=True` path also calls `set_metadata`. - `TestValidateRecords`: default implementation raises for in-memory extension types and - metadata-only extension fields, passes for plain types; `SpiralDBConnector.validate_records` + metadata-only extension fields, passes for plain types; `SpiralDBKeyedConnector.validate_records` is a no-op for all inputs. ### Unit Tests (`tests/test_databases/test_connector_arrow_database.py`) @@ -322,7 +322,7 @@ No other changes to `ConnectorArrowDatabase`. `validate_records`; a mock connector with a permissive override allows extension-typed records; a mock connector with the default raises. -### Integration Tests (`tests/test_databases/test_spiraldb_connector_integration.py`) +### Integration Tests (`tests/test_databases/test_spiraldb_keyed_connector_integration.py`) New class `TestArrowMetadataRoundTrip` (gated on `SPIRAL_INTEGRATION_TESTS=1`): @@ -347,12 +347,12 @@ New class `TestArrowMetadataRoundTrip` (gated on `SPIRAL_INTEGRATION_TESTS=1`): | File | Change | |---|---| -| `src/orcapod/databases/spiraldb_connector.py` | Add `_serialize_arrow_metadata`, `_load_arrow_metadata` helpers; modify `upsert_records` (write metadata after data write); modify `iter_batches` (load + restore metadata); add `validate_records` no-op override | +| `src/orcapod/databases/spiraldb_keyed/connector.py` | Add `_serialize_arrow_metadata`, `_load_arrow_metadata` helpers; modify `upsert_records` (write metadata after data write); modify `iter_batches` (load + restore metadata); add `validate_records` no-op override | | `src/orcapod/protocols/db_connector_protocol.py` | Add `validate_records` concrete default method | | `src/orcapod/databases/connector_arrow_database.py` | Replace inline guard (~lines 247–273) with `self._connector.validate_records(records)` | | `tests/test_databases/test_spiraldb_connector.py` | New test classes for serialization helpers, metadata read/write, `validate_records` | | `tests/test_databases/test_connector_arrow_database.py` | Tests for delegated `validate_records` | -| `tests/test_databases/test_spiraldb_connector_integration.py` | New `TestArrowMetadataRoundTrip` class | +| `tests/test_databases/test_spiraldb_keyed_connector_integration.py` | New `TestArrowMetadataRoundTrip` class | --- diff --git a/docs/dev/specs/2026-11-13-itl-1074-test-inventory.md b/docs/dev/specs/2026-11-13-itl-1074-test-inventory.md index e6535dae4..56955609e 100644 --- a/docs/dev/specs/2026-11-13-itl-1074-test-inventory.md +++ b/docs/dev/specs/2026-11-13-itl-1074-test-inventory.md @@ -39,7 +39,7 @@ the same commit, the static marks in the tree, and local runs of the files that | Group | Count | Stated reason | Verified cause | Verdict | |---|---|---|---|---| | Live Spiral source: `tests/test_core/sources/test_spiraldb_table_source_live.py` | 8 | "Set ORCAPOD_SPIRALDB_TEST_PROJECT to run" | The variable is set nowhere in `.github/`. The tests need a configured project, dataset and keyed table, plus credentials and network. | Correct to skip in `Run Tests`. Could run in the `spiral-integration` job once that job works and a project with the table exists (needs a developer decision and Spiral data). | -| Spiral connector integration: `test_spiraldb_connector_integration.py` | 9 | "Set SPIRAL_INTEGRATION_TESTS=1" | Run by the `spiral-integration` job (push to `main` only), which sets the variable. In that job all 9 **fail** (section 3.2). | Correct to skip in `Run Tests`; the job that runs them is broken. | +| Spiral connector integration: `test_spiraldb_keyed_connector_integration.py` | 9 | "Set SPIRAL_INTEGRATION_TESTS=1" | Run by the `spiral-integration` job (push to `main` only), which sets the variable. In that job all 9 **fail** (section 3.2). | Correct to skip in `Run Tests`; the job that runs them is broken. | | S3 / MinIO: `test_delta_table_database_s3.py` (7), `test_list_table_paths.py::test_s3_lists_tables_and_nested_tables` (1) | 8 | "MinIO container could not be started: 404 ... pull access denied for minio/minio" | See 3.3. The fixture starts MinIO with testcontainers and skips on any exception; in CI the image cannot be pulled, so the S3 path is never tested. | Should run in CI but does not; needs a SpiralDB workload credential (3.3, ITL-1079, ITL-1008). | | Delta tables under special-character roots: `test_delta_native_fs_read.py` (`x#y`, `q?r`, two tests each) | 4 | "deltalake cannot write a table at ..." | `_write_or_skip` skips when `deltalake` itself cannot write a table under a root named `x#y` or `q?r`. The other six special names run and pass. | Correct to skip: a limit of `deltalake`, not of Orcapod. Re-check on each `deltalake` upgrade. | | GPU tensors: `test_tensor_round_trip.py` (MPS, CUDA), `test_tensor_conversion_warning.py` (CUDA or MPS) | 3 | "needs MPS / CUDA / a CUDA or MPS device" | GitHub's Ubuntu runners have no GPU and no MPS. | Correct to skip. Running them needs a GPU runner (a paid CI service): not recommended before v0.3.0. | diff --git a/docs/dev/specs/2026-11-15-itl-1154-hash-site-inventory.md b/docs/dev/specs/2026-11-15-itl-1154-hash-site-inventory.md index 7aa6811f5..2a97eb93c 100644 --- a/docs/dev/specs/2026-11-15-itl-1154-hash-site-inventory.md +++ b/docs/dev/specs/2026-11-15-itl-1154-hash-site-inventory.md @@ -63,7 +63,7 @@ frozenset); **decide** needs a decision (listed at the end). | P19 | `logical_types/user_class_identity.py` `identity_string` | a user class's identity record | SHA-256 hex prefix | the extension name `name@` | ok (in a name) | | P20 | `semantic_types/universal_converter.py` (synthesized struct class) *(code only)* | the field signature text | MD5 hex, 8 digits | a synthesized Python class name | ok (in a name) | | P21 | `pipeline/serialization.py` `DatabaseRegistry._make_key` | a database config, canonical JSON | SHA-256 hex, 8 digits | `db_` key in a saved job | ok (in a name) | -| P22 | `databases/spiraldb_nullability.py` `_encode` / `read_nullability_record` | the nullability path list | SHA-256 hex | chunk key and checksum of a stored metadata record | ok (in a name, checked on read) | +| P22 | `databases/spiraldb_keyed/nullability.py` `_encode` / `read_nullability_record` | the nullability path list | SHA-256 hex | chunk key and checksum of a stored metadata record | ok (in a name, checked on read) | | P23 | random ids: `job.py` `run_id` (`uuid4`), orchestrators' `run_id`, `datagram.py` `uuid7`, `data_function.py` record `uuid7`, observers' `uuid7`, `function_node.py` correlation key `uuid4` | nothing | random | ids | ok (not hashes) | | P24 | builtin `hash()`: `pipeline/graph.py` `_sanitize_node_id`, `core/streams/base.py` (config cache key), `ContentIdentifiableBase.__hash__` | Python objects | process-dependent | Graphviz node ids, in-memory keys | ok (display only) | | P25 | `hashing/arrow_utils.py` `get_pyarrow_table_hash`, `hashing/arrow_serialization.py` *(code only)* | Arrow tables | SHA-256, SHA3, BLAKE2b hex | **no caller anywhere in the library** | **decide** (D9) | diff --git a/docs/dev/specs/itl-1186-switch.md b/docs/dev/specs/itl-1186-switch.md index b340f6e16..b37391e74 100644 --- a/docs/dev/specs/itl-1186-switch.md +++ b/docs/dev/specs/itl-1186-switch.md @@ -3,7 +3,7 @@ Status: superseded in part. After an independent design review the first step is narrowed (November 24, 2026): **reading only**. The schema table is written by the migration tool alone, one row per table keyed by SpiralDB's table id, one schema per table, and a completion -marker last (`src/orcapod/databases/spiraldb_schema_table.py` is the statement). The connector +marker last (`src/orcapod/databases/spiraldb_keyed/schema_table.py` is the statement). The connector refuses writes; sections 1 and 2 below (a row per write, `earlier_schemas`) are not built. "Measured" means measured on the service with spiral-sdk 0.16.74 (and pyspiral 0.16.33 for comparison) on throwaway tables. diff --git a/docs/dev/specs/itl-1367-stored-column-order.md b/docs/dev/specs/itl-1367-stored-column-order.md index 763b978df..81bf32b4b 100644 --- a/docs/dev/specs/itl-1367-stored-column-order.md +++ b/docs/dev/specs/itl-1367-stored-column-order.md @@ -43,7 +43,7 @@ added column takes its place by name. Struct children are sorted by name too. The evidence, two live sessions as the agent workload on the test project, every table a throwaway one dropped at the end (the final listing showed none left). Each probe wrote -with pyspiral's `Table.write` (or `SpiralDBConnector.upsert_records`), then read the +with pyspiral's `Table.write` (or `SpiralDBKeyedConnector.upsert_records`), then read the table's schema (`Table.schema()`) and its rows (`SELECT *` through the connector): | Probe | Written | Schema and rows read back | diff --git a/docs/dev/specs/itl-926-live/FINDINGS.md b/docs/dev/specs/itl-926-live/FINDINGS.md index b448f8ed3..5569885a8 100644 --- a/docs/dev/specs/itl-926-live/FINDINGS.md +++ b/docs/dev/specs/itl-926-live/FINDINGS.md @@ -1,6 +1,6 @@ # ITL-926 — Phase 1 findings (November 11, 2026) -Audit of `SpiralDBTableSource` / `DBTableSource` / `SpiralDBConnector`, an end-to-end run of +Audit of `SpiralDBTableSource` / `DBTableSource` / `SpiralDBKeyedConnector`, an end-to-end run of the workshop path through a disk-backed pyspiral fake (`tests/test_databases/fake_pyspiral.py`), a pyspiral 0.14.9 → 0.16.33 API check, and a read-only live check. Repro scripts are in `docs/dev/specs/itl-926-live/`. @@ -114,7 +114,7 @@ Recommendation: move the lock to 0.16.33. Keep the floor at `>=0.14.0`, or raise ## Integration tests vs. the workshop path -`tests/test_databases/test_spiraldb_connector_integration.py` covers the connector and +`tests/test_databases/test_spiraldb_keyed_connector_integration.py` covers the connector and `ConnectorArrowDatabase` round trips plus ITL-471 metadata. It does not cover `SpiralDBTableSource`, `PipelineJob`, `Join`, caching, save/load, nullability, composite keys, timestamp keys, or large tables. The `spiral-integration` job needs the `SPIRAL_WORKLOAD_ID` @@ -157,7 +157,7 @@ secret (GitHub OIDC), `vars.SPIRAL_PROJECT_ID` and `vars.SPIRAL_SERVER_URL` * pandas turns `date32` into `datetime64[ms]`. * `fixed_size_list` tables fail before any of these methods can run (C2). 5. **Discovery.** There is no source-level helper. - `SpiralDBConnector(project).get_table_names()` and `.get_pk_columns(table)` are public + `SpiralDBKeyedConnector(project).get_table_names()` and `.get_pk_columns(table)` are public today (`orcapod.databases`) and are what the docs will show. A `SpiralDBTableSource.list_tables(project)` helper is a new-API decision. 6. **Setup.** `pip install "orcapod[spiraldb]"` installs the `spiral` CLI (pyspiral console diff --git a/docs/dev/specs/itl-936-live/live_nullability.py b/docs/dev/specs/itl-936-live/live_nullability.py index 449065e08..a4c7e8ba9 100644 --- a/docs/dev/specs/itl-936-live/live_nullability.py +++ b/docs/dev/specs/itl-936-live/live_nullability.py @@ -16,7 +16,7 @@ 1. ``fresh``: right after ``create_table`` the schema holds only the key columns (the connector's test for "a table with no rows yet", where it writes the record). -2. ``record``: ``SpiralDBConnector.upsert_records`` writes the record; SpiralDB's own schema +2. ``record``: ``SpiralDBKeyedConnector.upsert_records`` writes the record; SpiralDB's own schema is all nullable; ``get_column_info`` and ``iter_batches`` restore the written nullability at every depth; ``SpiralDBTableSource`` gives ``T``; a pod ``x: float`` runs; a ``Join`` of two recorded tables runs; the saved job loads in a fresh process, with every row and @@ -29,7 +29,7 @@ nullable struct field. Reports the rows and the child arrays as read back. ``struct_null_without_push_down``: a null struct written straight through pyspiral without ``push_down_nulls`` (refused, or what is stored); ``struct_null_connector``: the same rows - through ``SpiralDBConnector`` are refused by Orcapod before anything is written. + through ``SpiralDBKeyedConnector`` are refused by Orcapod before anything is written. 5. ``metadata``: several keys in one ``set_metadata`` call; a 400-column record (chunked); an entry over 8 KiB (expected refused). @@ -195,7 +195,7 @@ def write_mode(project: str, dataset: str, report: dict[str, Any]) -> bool: import spiral as sp # pyright: ignore[reportMissingImports] (spiraldb extra, absent in the type-check job) from orcapod.databases import ( - SpiralDBConnector, + SpiralDBKeyedConnector, read_nullability_record, # pyright: ignore[reportAttributeAccessIssue] # historical: measured with pyspiral, removed in ITL-1186 write_nullability_record, # pyright: ignore[reportAttributeAccessIssue] # historical: measured with pyspiral, removed in ITL-1186 ) @@ -217,7 +217,7 @@ def write_mode(project: str, dataset: str, report: dict[str, Any]) -> bool: created: list[str] = [] ok = True try: - connector = SpiralDBConnector(project, dataset=dataset) + connector = SpiralDBKeyedConnector(project, dataset=dataset) # 1. fresh key_info = [ColumnInfo("k", pa.int64(), nullable=False)] connector.create_table_if_not_exists(names["a"], key_info, pk_column="k") @@ -457,7 +457,9 @@ def read_mode( """ import spiral as sp # pyright: ignore[reportMissingImports] (spiraldb extra, absent in the type-check job) - from orcapod.databases import read_nullability_record # pyright: ignore[reportAttributeAccessIssue] # historical: measured with pyspiral, removed in ITL-1186 + from orcapod.databases import ( + read_nullability_record, # pyright: ignore[reportAttributeAccessIssue] # historical: measured with pyspiral, removed in ITL-1186 + ) from orcapod.sources import SpiralDBTableSource proj = sp.Spiral().project(project) # pyright: ignore[reportAttributeAccessIssue] # historical: measured with pyspiral, removed in ITL-1186 diff --git a/docs/dev/specs/itl-998-range-restriction.md b/docs/dev/specs/itl-998-range-restriction.md index b37994d72..9942642b2 100644 --- a/docs/dev/specs/itl-998-range-restriction.md +++ b/docs/dev/specs/itl-998-range-restriction.md @@ -336,7 +336,7 @@ Change: - **One list of terms** to `scan_batches` (`(column, operator, value)`, equality included) instead of `where=` plus `comparisons=`: one loop, and `Condition.equalities` (one value per column) is no longer how a scan is - described. The implemented `SpiralDBConnector.scan_batches` has a PROVISIONAL `where` + described. The implemented `SpiralDBKeyedConnector.scan_batches` has a PROVISIONAL `where` parameter that takes the `Condition` holding those terms. - `check_restriction` calls `check_equality_conditions` for a range bound: call the value check (`check_value_for_column`) under a neutral name; its "where names columns..." text stays. diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 197690290..721808fb5 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -61,8 +61,8 @@ The library value types (NumPy, pandas, Polars, torch) are The databases: `InMemoryArrowDatabase` (in-memory), `DeltaTableDatabase` (Delta), and `ConnectorArrowDatabase` over `SQLiteConnector` and `PostgreSQLConnector`. Orcapod reads -SpiralDB and writes it only as a writable SpiralDB database ([SpiralDB as a Job's -Database](../concepts/spiraldb-database.md)), not compared here. See [The +SpiralDB and writes it only as a writable SpiralDB database ([Keyed SpiralDB as a Job's +Database](../concepts/spiraldb-keyed-database.md)), not compared here. See [The database](../concepts/pipeline-job.md#the-database) for how a job uses one. Some refusals depend on the values or names as well as the type: diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 86f61f3eb..252de88a4 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -390,7 +390,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | run snapshot | sorted labelled sink hashes | SHA-256 hex, 16 digits | the run URI `@` (a name) | `pipeline/job.py:PipelineJob._prepare_run`, `pipeline/job.py:PipelineJob._prepare_run..` | | user-class identity | a class's identity record | SHA-256 hex prefix | extension name `name@` (a name) | `logical_types/user_class_identity.py:identity_string` | | database registry key | a database config, canonical JSON | SHA-256 hex, 8 digits | `db_` key in a saved job (a name) | `pipeline/serialization.py:DatabaseRegistry._make_key` | -| SpiralDB schema table digest | the scope and the rows of a dataset's schema table, canonical JSON with the stored schema bytes | SHA-256 hex | completion marker of the schema table (a checksum of stored rows) | `databases/spiraldb_schema_table.py:rows_digest` | +| SpiralDB schema table digest | the scope and the rows of a dataset's schema table, canonical JSON with the stored schema bytes | SHA-256 hex | completion marker of the schema table (a checksum of stored rows) | `databases/spiraldb_keyed/schema_table.py:rows_digest` | | SpiralDB database manifest checksum | a writable SpiralDB database table's manifest payload (record path and Arrow schemas, canonical JSON); its format is provisional | SHA-256 hex | the manifest header's check of its chunks in the table's metadata (a checksum of a stored record) | `databases/spiral_database_codec.py:_checksum` | | Connector store table name | the full store path, as a compact UTF-8 JSON array of path components | SHA-256 hex, `spiral_table_name_v1` (`SPIRAL_TABLE_NAME_LABEL`) | the bare hexadecimal suffix in a table name, with a length set by the backend | `databases/store_table_names.py:store_table_digest` | | synthesized struct class name | the field signature | MD5 hex, 8 digits | a Python class name (a name) | (not reached by a traced test) `semantic_types/universal_converter.py` | diff --git a/scripts/migrate_spiral_schemas.py b/scripts/migrate_spiral_schemas.py index 3d58723d5..d68d159cb 100644 --- a/scripts/migrate_spiral_schemas.py +++ b/scripts/migrate_spiral_schemas.py @@ -3,7 +3,7 @@ Orcapod on pyspiral kept each table's non-nullable columns and Arrow metadata in the table's key-value metadata, which spiral-sdk does not read. This tool records each table's schema in the dataset's schema table (``__orcapod_schemas__``), which Orcapod on spiral-sdk reads -(``orcapod.databases.spiraldb_schema_table``). It writes nothing else. +(``orcapod.databases.spiraldb_keyed.schema_table``). It writes nothing else. Three steps, each in an environment of its own (the two clients cannot be installed together); ``RELEASING.md`` has the exact commands: @@ -69,7 +69,7 @@ def spiral_module() -> Any: def require_credentials() -> None: """Stop unless the client can sign in without asking a person. - The rule of ``orcapod.databases.spiraldb_sign_in``, stated again: the dry run's + The rule of ``orcapod.databases.spiraldb_keyed.sign_in``, stated again: the dry run's Orcapod does not have it. """ env = os.environ @@ -252,7 +252,7 @@ def describe_table( def dry_run(args: argparse.Namespace) -> None: """Write the plan and print what each dataset's schema table would hold.""" - from orcapod.databases.spiraldb_connector import SpiralDBConnector + from orcapod.databases.spiraldb_keyed.connector import SpiralDBKeyedConnector sp = spiral_module() @@ -280,7 +280,7 @@ def dry_run(args: argparse.Namespace) -> None: # Every selected dataset that lists a table, a reserved name included: a dataset # whose only table is a reserved name reaches the reserved-name check below. connectors = { - dataset: SpiralDBConnector(args.project, dataset) + dataset: SpiralDBKeyedConnector(args.project, dataset) for dataset in sorted(set(args.dataset)) if dataset in tables or dataset in reserved } @@ -384,7 +384,7 @@ def sdk_client() -> Any: def planned_rows(tables: list[dict[str, Any]]) -> list[Any]: """Return the plan's rows, checked to say what the plan says.""" - from orcapod.databases.spiraldb_schema_table import SchemaRow + from orcapod.databases.spiraldb_keyed.schema_table import SchemaRow rows = [] for table in tables: @@ -414,11 +414,11 @@ def require_unchanged( rows: list[Any], ) -> None: """Refuse unless every table of the dataset is as the plan found it.""" - from orcapod.databases.spiraldb_connector import ( + from orcapod.databases.spiraldb_keyed.connector import ( _list_keyed_tables, _open_keyed_table, ) - from orcapod.databases.spiraldb_schema_table import ( + from orcapod.databases.spiraldb_keyed.schema_table import ( compared_columns, describe_difference, ) @@ -487,7 +487,7 @@ def require_own_schema_table( ) -> Any | None: """Return the dataset's schema table when this plan's write created it, ``None`` when there is none yet; refuse any other.""" - from orcapod.databases.spiraldb_connector import _open_keyed_table + from orcapod.databases.spiraldb_keyed.connector import _open_keyed_table if planned["schema_table"] is not None: raise MigrationError( @@ -522,8 +522,11 @@ def require_own_schema_table( def open_rows(client: Any, project: str, dataset: str) -> tuple[dict[str, Any], Any]: """Return the schema table's rows by table id and its marker, as stored now.""" - from orcapod.databases.spiraldb_connector import _open_keyed_table - from orcapod.databases.spiraldb_schema_table import read_rows, require_schema_table + from orcapod.databases.spiraldb_keyed.connector import _open_keyed_table + from orcapod.databases.spiraldb_keyed.schema_table import ( + read_rows, + require_schema_table, + ) table = _open_keyed_table(client, project, dataset, SCHEMA_TABLE) if table is None or not require_schema_table(table): @@ -535,8 +538,8 @@ def write(args: argparse.Namespace) -> None: """Write the planned rows, one by one, and the completion marker last.""" import pyarrow as pa - from orcapod.databases import spiraldb_schema_table as st - from orcapod.databases.spiraldb_connector import _create_keyed_table + from orcapod.databases.spiraldb_keyed import schema_table as st + from orcapod.databases.spiraldb_keyed.connector import _create_keyed_table plan = read_plan(args.plan) require_scope(plan, args) @@ -651,11 +654,11 @@ def put(dataset: str, values: dict[str, Any]) -> None: def verify(args: argparse.Namespace) -> None: """Check with spiral-sdk alone that every source is what the plan says.""" - from orcapod.databases.spiraldb_connector import SpiralDBConnector + from orcapod.databases.spiraldb_keyed.connector import SpiralDBKeyedConnector plan = read_plan(args.plan) require_scope(plan, args) - from orcapod.databases import spiraldb_schema_table as st + from orcapod.databases.spiraldb_keyed import schema_table as st client = sdk_client() project = plan["project"] @@ -663,7 +666,7 @@ def verify(args: argparse.Namespace) -> None: checked = refused = 0 for dataset, planned in plan["datasets"].items(): tables = planned["tables"] - connector = SpiralDBConnector(project, dataset) + connector = SpiralDBKeyedConnector(project, dataset) rows = planned_rows(tables) require_unchanged(client, project, dataset, tables, rows) present, marker = open_rows(client, project, dataset) diff --git a/site/astro.config.mjs b/site/astro.config.mjs index bc6e5326b..e31ad54ea 100644 --- a/site/astro.config.mjs +++ b/site/astro.config.mjs @@ -169,7 +169,7 @@ export default defineConfig({ page('Function Pods', 'concepts/function-pods'), page('Data-tags', 'concepts/data-tags'), page('Pipelines and Jobs', 'concepts/pipeline-job'), - page('SpiralDB as a Job\'s Database', 'concepts/spiraldb-database'), + page('Keyed SpiralDB as a Job\'s Database', 'concepts/spiraldb-keyed-database'), page('Provenance', 'concepts/provenance'), page('Working in Notebooks', 'concepts/notebooks'), page('Your Own Data Types', 'concepts/your-own-data-types'), diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index bdac7642e..d4577965c 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -83,8 +83,8 @@ ) from orcapod.core.streams.base import check_head_size from orcapod.core.streams.view import StreamView, ViewStatus -from orcapod.databases.spiraldb_connector import ( - SpiralDBConnector, +from orcapod.databases.spiraldb_keyed.connector import ( + SpiralDBKeyedConnector, SpiralDBTable, SpiralDBTableNotFoundError, require_same_process, @@ -284,7 +284,7 @@ class SpiralDBTableSource(RootSource): data_context: Data context governing type conversion and hashing. config: OrcaPod configuration. overrides: Optional: ``{"server.url": "https://api.spiraldb.dev"}``, the - address of the service, passed to ``SpiralDBConnector``. + address of the service, passed to ``SpiralDBKeyedConnector``. tag_only_columns: Tag columns kept as tags only, not data, exactly as in v0.3; ``True`` for all of them. Keyword-only. Every other tag column is a data-tag: also a data column of the same name (ITL-1023). @@ -376,7 +376,7 @@ def __init__( self._dataset = dataset self._table_name = table_name self._overrides = None if overrides is None else dict(overrides) - self._connection: SpiralDBConnector | None = None + self._connection: SpiralDBKeyedConnector | None = None self._connection_lock = Lock() # Checks of one source run one at a time: the refusal is the latest's verdict. self._check_lock = Lock() @@ -746,14 +746,14 @@ def identity_structure(self) -> Any: # Reading # ------------------------------------------------------------------------- - def _connector(self) -> SpiralDBConnector: + def _connector(self) -> SpiralDBKeyedConnector: """Return the connector owned by this source.""" require_same_process(self._pid) # before a lock inherited by a fork with self._connection_lock: if self._closed: raise RuntimeError("SpiralDBTableSource is closed") if self._connection is None: - self._connection = SpiralDBConnector( + self._connection = SpiralDBKeyedConnector( project_id=self._project_id, dataset=self._dataset, overrides=self._overrides, diff --git a/src/orcapod/databases/__init__.py b/src/orcapod/databases/__init__.py index ce7cfbdb2..f3ed6b908 100644 --- a/src/orcapod/databases/__init__.py +++ b/src/orcapod/databases/__init__.py @@ -4,7 +4,7 @@ from .in_memory_databases import InMemoryArrowDatabase from .noop_database import NoOpArrowDatabase from .postgresql_connector import PostgreSQLConnector -from .spiraldb_connector import SpiralDBConnector +from .spiraldb_keyed.connector import SpiralDBKeyedConnector from .sqlite_connector import SQLiteConnector __all__ = [ @@ -13,7 +13,7 @@ "ExtensionAwareDatabase", "InMemoryArrowDatabase", "NoOpArrowDatabase", - "SpiralDBConnector", + "SpiralDBKeyedConnector", "SQLiteConnector", "PostgreSQLConnector", ] @@ -25,7 +25,7 @@ # # SQLiteConnector -- PLT-1076 (stdlib sqlite3, zero extra deps) ✓ # PostgreSQLConnector -- PLT-1075 (psycopg3) ✓ -# SpiralDBConnector -- PLT-1074 +# SpiralDBKeyedConnector -- PLT-1074 # # ArrowDatabaseProtocol backends (existing, not connector-based): # diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index b29b0c4cf..f75264684 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -5,7 +5,7 @@ ``__record_id`` column convention, in-memory pending-batch management, deduplication and flush. -Connector implementations (SQLiteConnector, PostgreSQLConnector, SpiralDBConnector) +Connector implementations (SQLiteConnector, PostgreSQLConnector, SpiralDBKeyedConnector) need only satisfy DBConnectorProtocol; they do not implement ArrowDatabaseProtocol. Example:: @@ -43,16 +43,15 @@ stored_path, ) from orcapod.databases.postgresql_connector import PostgreSQLConnector -from orcapod.databases.spiraldb_connector import SpiralDBConnector -from orcapod.databases.spiral_database_identity import ( +from orcapod.databases.spiraldb_keyed.connector import SpiralDBKeyedConnector +from orcapod.databases.spiraldb_keyed.identity import ( SpiralTableCollisionError, refuse_other_format_path, ) -from orcapod.databases.spiraldb_tables import ( +from orcapod.databases.spiraldb_keyed.tables import ( SpiralDBTables, declared_keeping_identifier, ) -from orcapod.logical_types.canonical_form import storage_form_schema from orcapod.databases.store_table_names import ( STORE_TABLE_NAME_PREFIX, require_store_path_domain, @@ -74,6 +73,7 @@ UnstorableColumnError, UnstorableTableNameError, ) +from orcapod.logical_types.canonical_form import storage_form_schema from orcapod.protocols.db_connector_protocol import ColumnInfo, DBConnectorProtocol from orcapod.utils.arrow_utils import ( normalize_schema_to_large_types, @@ -229,11 +229,11 @@ class ConnectorArrowDatabase: on ``flush()``. SQLite and PostgreSQL table names use a readable path hint and a digest of the full path. A catalog records the original path. - A writable SpiralDB database, ``SpiralDBConnector(..., writable=True)`` (provisional - in 0.4.0), is read and written through its database tables (``spiraldb_tables``): + A writable SpiralDB database, ``SpiralDBKeyedConnector(..., writable=True)`` (provisional + in 0.4.0), is read and written through its database tables (``spiraldb_keyed.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 - (``spiraldb_write_scope``). A plain ``SpiralDBConnector`` refuses every write, as + (``spiraldb_keyed.write_scope``). A plain ``SpiralDBKeyedConnector`` refuses every write, as before. Args: @@ -267,9 +267,9 @@ def __init__( connector if isinstance(connector, SQLStoreConnector) else None ) # A writable SpiralDB connector; ``None`` for any other (ITL-1840). - self._spiral_connector: SpiralDBConnector | None = ( + self._spiral_connector: SpiralDBKeyedConnector | None = ( connector - if isinstance(connector, SpiralDBConnector) + if isinstance(connector, SpiralDBKeyedConnector) and connector._writable_tables() is not None # pyright: ignore[reportPrivateUsage] # the database's one reader and writer else None ) @@ -1121,7 +1121,7 @@ def _read_stored_schema( """The schema a read of the stored table gives, its field metadata included. Read without rows from a connector that offers ``get_arrow_schema`` - (``SpiralDBConnector``); from any other, the schema of its first batch. + (``SpiralDBKeyedConnector``); from any other, the schema of its first batch. """ if (tables := self._spiral) is not None: return tables.arrow_schema(table_name) diff --git a/src/orcapod/databases/spiral_database_codec.py b/src/orcapod/databases/spiral_database_codec.py index 92926c51e..91b70e559 100644 --- a/src/orcapod/databases/spiral_database_codec.py +++ b/src/orcapod/databases/spiral_database_codec.py @@ -17,7 +17,7 @@ no rows may be recorded again (``manifest_entries``, ``read_manifest``): the record path, the kind, the logical schema, and the stored names at every depth. It is kept in the table's own metadata, in chunks of at most 8 KiB, beside the table's - identity record (``spiral_database_identity``); never in the dataset's schema table, + identity record (``spiraldb_keyed.identity``); never in the dataset's schema table, which is all or nothing under one completion marker (decision of 2026-11-26). Logical types are handled by their identifier (extension name and metadata) alone, as diff --git a/src/orcapod/databases/spiraldb_keyed/__init__.py b/src/orcapod/databases/spiraldb_keyed/__init__.py new file mode 100644 index 000000000..b5b475910 --- /dev/null +++ b/src/orcapod/databases/spiraldb_keyed/__init__.py @@ -0,0 +1 @@ +"""The keyed-table backend for SpiralDB.""" diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_keyed/connector.py similarity index 96% rename from src/orcapod/databases/spiraldb_connector.py rename to src/orcapod/databases/spiraldb_keyed/connector.py index 0a40bf185..bbaa89c59 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_keyed/connector.py @@ -1,4 +1,4 @@ -"""SpiralDBConnector — DBConnectorProtocol implementation backed by SpiralDB (spiral-sdk). +"""SpiralDBKeyedConnector — DBConnectorProtocol implementation backed by SpiralDB (spiral-sdk). Requires the ``spiraldb`` optional extra: ``pip install orcapod[spiraldb]``. Authentication is spiral-sdk's: ``SPIRAL_*`` environment variables, or the credentials @@ -6,11 +6,11 @@ The connector is dataset-scoped: all tables are read from and written to a single ``(project_id, dataset)`` pair. They are SpiralDB's keyed tables. The schema each -is read with is in the dataset's schema table (``spiraldb_schema_table``). +is read with is in the dataset's schema table (``spiraldb_keyed.schema_table``). Example:: - connector = SpiralDBConnector(project_id="my-project-123456", dataset="default") + connector = SpiralDBKeyedConnector(project_id="my-project-123456", dataset="default") rows = pa.Table.from_batches(connector.scan_batches("units")) """ @@ -36,21 +36,23 @@ import pyarrow.compute as pc from typing_extensions import override -from orcapod.databases.spiraldb_nullability import ( +from orcapod.databases.spiraldb_keyed.nullability import ( cast_changed_columns, check_no_nulls, schema_paths, ) -from orcapod.databases.spiraldb_schema_table import ( +from orcapod.databases.spiraldb_keyed.schema_table import ( SCHEMA_TABLE, KeptRows, SchemaTable, compared_columns, describe_difference, ) -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.spiraldb_keyed.sign_in import require_sign_in, saved_login_path +from orcapod.databases.spiraldb_keyed.tables import SpiralDBTables +from orcapod.databases.spiraldb_keyed.writable_registry import ( + register_writable_connector, +) from orcapod.databases.store_table_names import is_spiral_lease_table_name from orcapod.errors import ( NullInNonNullableColumnError, @@ -83,9 +85,9 @@ _SCAN_BATCH_ROWS = 8_192 _LIST_TIMEOUT_S = 60 _NO_WRITES = ( - "a plain SpiralDBConnector only reads SpiralDB tables; nothing was written. A job " + "a plain SpiralDBKeyedConnector only reads SpiralDB tables; nothing was written. A job " "keeps its tables in SpiralDB through a writable SpiralDB database: " - "ConnectorArrowDatabase(SpiralDBConnector(..., writable=True))" + "ConnectorArrowDatabase(SpiralDBKeyedConnector(..., writable=True))" ) # Tables a warning was issued for in this process (``UnrecordedTableSchemaWarning``). _warned_unrecorded: set[tuple[str, str]] = set() @@ -141,7 +143,7 @@ def _about_table(table: str) -> Iterator[None]: # --------------------------------------------------------------------------- -# SpiralDBConnector +# SpiralDBKeyedConnector # --------------------------------------------------------------------------- @@ -525,7 +527,7 @@ def _http_get_json(url: str, token: str | None) -> dict[str, Any]: STORE_KEY_REFUSAL = ( "a SpiralDB connector configuration with a 'store' key is not read: the writable " - "SpiralDB database is SpiralDBConnector(..., writable=True), saved as " + "SpiralDB database is SpiralDBKeyedConnector(..., writable=True), saved as " "'writable': true" ) """The refusal of a saved SpiralDB connector configuration that names ``store``.""" @@ -705,7 +707,7 @@ def _equals(array: Any, value: Any) -> Any: class SpiralDBTable: - """One SpiralDB table, looked up once (``SpiralDBConnector.lookup_table``). + """One SpiralDB table, looked up once (``SpiralDBKeyedConnector.lookup_table``). Every lookup of a table by name is a round trip to SpiralDB. A caller that needs several items of one table (a source's id, key, schema and version when it is built, @@ -720,7 +722,7 @@ class SpiralDBTable: """ def __init__( - self, connector: SpiralDBConnector, table: Any, table_name: str + self, connector: SpiralDBKeyedConnector, table: Any, table_name: str ) -> None: """Wrap the keyed ``table`` that ``connector`` looked up as ``table_name``.""" self._connector = connector @@ -730,7 +732,7 @@ def __init__( # The SDK's handle of each other version opened (``_at``), by version. self._versions: dict[str, Any] = {} - def with_connector(self, connector: SpiralDBConnector) -> SpiralDBTable: + def with_connector(self, connector: SpiralDBKeyedConnector) -> SpiralDBTable: """Return this table read through ``connector``, which shares its SDK client. What was worked out per version is shared: a snapshot never changes. @@ -841,7 +843,7 @@ def scan_batches( Args: where: Equalities and ranges of columns, all of which must hold - (``SpiralDBConnector.scan_batches``). + (``SpiralDBKeyedConnector.scan_batches``). limit: Read at most this many matching rows. asof: Read this version. columns: The columns to read; ``None`` reads every column. Each batch @@ -1033,7 +1035,7 @@ def prepare(self, batch: pa.RecordBatch) -> pa.RecordBatch: return cast_changed_columns(batch, self.schema) -class SpiralDBConnector: +class SpiralDBKeyedConnector: """DBConnectorProtocol implementation backed by SpiralDB (spiral-sdk). Scoped to a single dataset within a SpiralDB project, and to its keyed tables. Auth @@ -1123,7 +1125,7 @@ def _new_tables(self) -> SpiralDBTables: def _require_open(self) -> None: """Raise RuntimeError if this connector has been closed.""" if self._closed: - raise RuntimeError("SpiralDBConnector is closed") + raise RuntimeError("SpiralDBKeyedConnector is closed") require_same_process(self._pid) def _writable_tables(self) -> SpiralDBTables | None: @@ -1152,7 +1154,7 @@ def _writer_lease_key(self) -> tuple[str, str, str]: 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, + """What ``spiraldb_keyed.write_scope`` takes the writer lease with: the SDK client, project and dataset. Raises: @@ -1169,7 +1171,7 @@ def _refuse_if_writable(self) -> None: "ConnectorArrowDatabase only, never as raw tables" ) - def share_client(self) -> SpiralDBConnector: + def share_client(self) -> SpiralDBKeyedConnector: """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 @@ -1402,13 +1404,13 @@ def iter_batches( self._refuse_if_writable() if params is not None: logger.warning( - "SpiralDBConnector does not support query parameters; " + "SpiralDBKeyedConnector does not support query parameters; " "ignoring params=%r", params, ) if batch_size != 1000: logger.warning( - "SpiralDBConnector does not support batch_size; " + "SpiralDBKeyedConnector does not support batch_size; " "batch sizing is controlled by the Spiral execution engine. " "Ignoring batch_size=%r", batch_size, @@ -1617,7 +1619,7 @@ def close(self) -> None: # ``share_client`` has its own. self._tables = None - def __enter__(self) -> SpiralDBConnector: + def __enter__(self) -> SpiralDBKeyedConnector: return self def __exit__(self, *args: Any) -> None: @@ -1638,7 +1640,7 @@ def to_config(self) -> dict[str, Any]: """ self._require_open() config: dict[str, Any] = { - "connector_type": "spiraldb", + "connector_type": "spiraldb_keyed", "project_id": self._project_id, "dataset": self._dataset, "overrides": None if self._overrides is None else dict(self._overrides), @@ -1648,23 +1650,23 @@ def to_config(self) -> dict[str, Any]: return config @classmethod - def from_config(cls, config: dict[str, Any]) -> SpiralDBConnector: - """Reconstruct a SpiralDBConnector from a config dict. + def from_config(cls, config: dict[str, Any]) -> SpiralDBKeyedConnector: + """Reconstruct a SpiralDBKeyedConnector from a config dict. Args: config: Dict with ``connector_type``, ``project_id``, and optionally ``dataset``, ``overrides`` and ``writable`` keys. Returns: - A new, open SpiralDBConnector instance. + A new, open SpiralDBKeyedConnector instance. Raises: - ValueError: If ``connector_type`` is not ``"spiraldb"``, or the config holds + ValueError: If ``connector_type`` is not ``"spiraldb_keyed"``, or the config holds a ``store`` key (not an option: ``writable``). """ - if config.get("connector_type") != "spiraldb": + if config.get("connector_type") != "spiraldb_keyed": raise ValueError( - f"Expected connector_type 'spiraldb', " + f"Expected connector_type 'spiraldb_keyed', " f"got {config.get('connector_type')!r}" ) if "store" in config: diff --git a/src/orcapod/databases/spiral_database_identity.py b/src/orcapod/databases/spiraldb_keyed/identity.py similarity index 100% rename from src/orcapod/databases/spiral_database_identity.py rename to src/orcapod/databases/spiraldb_keyed/identity.py diff --git a/src/orcapod/databases/spiraldb_nullability.py b/src/orcapod/databases/spiraldb_keyed/nullability.py similarity index 99% rename from src/orcapod/databases/spiraldb_nullability.py rename to src/orcapod/databases/spiraldb_keyed/nullability.py index c021ae80d..9c2742c44 100644 --- a/src/orcapod/databases/spiraldb_nullability.py +++ b/src/orcapod/databases/spiraldb_keyed/nullability.py @@ -2,7 +2,7 @@ SpiralDB reports every top-level column (key columns included) and every struct field as nullable, whatever was written; only list items keep a non-null flag (ITL-936). Orcapod -records each table's schema in the dataset's schema table (``spiraldb_schema_table``) and +records each table's schema in the dataset's schema table (``spiraldb_keyed.schema_table``) and enforces its non-nullable paths on read. A path starts with a top-level column name; each further segment is a struct field name, or diff --git a/src/orcapod/databases/spiraldb_schema_table.py b/src/orcapod/databases/spiraldb_keyed/schema_table.py similarity index 99% rename from src/orcapod/databases/spiraldb_schema_table.py rename to src/orcapod/databases/spiraldb_keyed/schema_table.py index 908cf8b1b..8b2ab2d7d 100644 --- a/src/orcapod/databases/spiraldb_schema_table.py +++ b/src/orcapod/databases/spiraldb_keyed/schema_table.py @@ -33,7 +33,7 @@ import pyarrow as pa -from orcapod.databases.spiraldb_nullability import ITEM, ColumnPath, field_members +from orcapod.databases.spiraldb_keyed.nullability import ITEM, ColumnPath, field_members from orcapod.errors import TableSchemaError from orcapod.logical_types.canonical_form import storage_form_schema from orcapod.utils import arrow_utils diff --git a/src/orcapod/databases/spiraldb_sign_in.py b/src/orcapod/databases/spiraldb_keyed/sign_in.py similarity index 100% rename from src/orcapod/databases/spiraldb_sign_in.py rename to src/orcapod/databases/spiraldb_keyed/sign_in.py diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_keyed/tables.py similarity index 99% rename from src/orcapod/databases/spiraldb_tables.py rename to src/orcapod/databases/spiraldb_keyed/tables.py index 8987861d2..f33bc8c8e 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_keyed/tables.py @@ -1,11 +1,11 @@ """The tables of a writable SpiralDB database, one dataset's (ITL-1840). What ``ConnectorArrowDatabase`` does with the tables of a writable SpiralDB database, -``SpiralDBConnector(..., writable=True)`` (public and provisional in 0.4.0, ITL-1844). +``SpiralDBKeyedConnector(..., writable=True)`` (public and provisional in 0.4.0, ITL-1844). The design is ``docs/dev/specs/itl-1446-round2-spiral-sdk.md`` (PR 588), section 2, carried from PR 595 onto ``main``'s database structure. -- A table's name is computed from its full record path (``spiral_database_identity``); a +- A table's name is computed from its full record path (``spiraldb_keyed.identity``); a table is found by opening that name, never by listing. - Its metadata holds its identity record and its manifest (``spiral_database_codec``): the record @@ -28,7 +28,7 @@ (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 +(``spiraldb_lease``), handed in by the run that holds it (``spiraldb_keyed.write_scope``) and checked before each write; a write with none 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 @@ -47,8 +47,8 @@ import pyarrow.compute as pc import orcapod.databases.spiral_database_codec as codec -import orcapod.databases.spiral_database_identity as identity -from orcapod.databases.spiral_database_identity import SpiralTableCollisionError +import orcapod.databases.spiraldb_keyed.identity as identity +from orcapod.databases.spiraldb_keyed.identity import SpiralTableCollisionError from orcapod.databases.store_table_names import require_store_path_domain from orcapod.errors import InputValidationError, SpiralDBLeaseRequiredError from orcapod.logical_types.canonical_form import ( @@ -215,7 +215,7 @@ def __init__( # 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. + # (``spiraldb_keyed.write_scope``); ``None`` when no run holds one. self._lease_check: Callable[[], None] | None = None key_column: str = codec.KEY_COLUMN @@ -701,7 +701,7 @@ def _held_ids(self, table: _KeyedTable, ids: Collection[bytes]) -> set[bytes]: # ── writing ────────────────────────────────────────────────────────────── def hold_lease(self, check: Callable[[], None]) -> None: - """Let this dataset be written under a lease a run holds (``spiraldb_write_scope``). + """Let this dataset be written under a lease a run holds (``spiraldb_keyed.write_scope``). Args: check: Verifies the lease is still held; raises if it is not. diff --git a/src/orcapod/databases/spiraldb_writable_registry.py b/src/orcapod/databases/spiraldb_keyed/writable_registry.py similarity index 84% rename from src/orcapod/databases/spiraldb_writable_registry.py rename to src/orcapod/databases/spiraldb_keyed/writable_registry.py index e6f125881..53f43b079 100644 --- a/src/orcapod/databases/spiraldb_writable_registry.py +++ b/src/orcapod/databases/spiraldb_keyed/writable_registry.py @@ -1,7 +1,7 @@ """Which writable SpiralDB connectors exist in this process (ITL-1844). A run takes the writer lease of every writable SpiralDB database it may write -(``spiraldb_write_scope.database_writes``), found by walking the run's graph. A writable +(``spiraldb_keyed.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 (``any_writable_connector``). @@ -19,7 +19,7 @@ def register_writable_connector(connector: object) -> None: """Record a writable connector, for as long as it exists. Args: - connector: A ``SpiralDBConnector`` made with ``writable=True``. + connector: A ``SpiralDBKeyedConnector`` made with ``writable=True``. """ _writable_connectors.add(connector) diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_keyed/write_scope.py similarity index 94% rename from src/orcapod/databases/spiraldb_write_scope.py rename to src/orcapod/databases/spiraldb_keyed/write_scope.py index ac03ae498..4582006e8 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_keyed/write_scope.py @@ -1,13 +1,13 @@ """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 +A writable SpiralDB database (``SpiralDBKeyedConnector(..., 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``). +refused (``SpiralDBLeaseRequiredError``, raised by ``spiraldb_keyed.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 @@ -23,10 +23,10 @@ from orcapod.databases import spiraldb_lease if TYPE_CHECKING: - from orcapod.databases.spiraldb_connector import SpiralDBConnector + from orcapod.databases.spiraldb_keyed.connector import SpiralDBKeyedConnector -def writable_connectors(databases: Iterable[object]) -> list[SpiralDBConnector]: +def writable_connectors(databases: Iterable[object]) -> list[SpiralDBKeyedConnector]: """The distinct writable SpiralDB connectors under ``databases``, in the order met. Args: @@ -39,7 +39,7 @@ def writable_connectors(databases: Iterable[object]) -> list[SpiralDBConnector]: from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase from orcapod.databases.extension_aware_database import unwrap_database_views - found: list[SpiralDBConnector] = [] + found: list[SpiralDBKeyedConnector] = [] for given in databases: database = unwrap_database_views( given @@ -80,7 +80,7 @@ def database_writes(databases: Iterable[object], *, owner: str) -> Iterator[None succeeded (the run's writes are committed then; the message says how to clear the lease). """ - groups: dict[tuple[str, str, str], list[SpiralDBConnector]] = {} + groups: dict[tuple[str, str, str], list[SpiralDBKeyedConnector]] = {} 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], Callable[[], None], Callable[[], None]]] = [] # pyright: ignore[reportExplicitAny] # SpiralDBTables @@ -120,7 +120,7 @@ def register( def take_lease( - connector: SpiralDBConnector, + connector: SpiralDBKeyedConnector, owner: str, *, on_taken: Callable[[Callable[[], None], Callable[[], None]], None] | None = None, @@ -162,7 +162,7 @@ def release() -> None: return taken[0] -def _tables(connector: SpiralDBConnector) -> Any: # pyright: ignore[reportExplicitAny] # SpiralDBTables; a writable connector always has them while open +def _tables(connector: SpiralDBKeyedConnector) -> 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 if tables is None: raise RuntimeError("not a writable SpiralDB connector") diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py index 9f708a216..72959f054 100644 --- a/src/orcapod/databases/spiraldb_lease.py +++ b/src/orcapod/databases/spiraldb_lease.py @@ -17,7 +17,7 @@ import pyarrow as pa -from orcapod.databases import spiraldb_connector as sdk +from orcapod.databases.spiraldb_keyed import connector as sdk from orcapod.databases.store_table_names import ( SPIRAL_LEASE_KEY_PREFIX, spiral_lease_key_column, diff --git a/src/orcapod/databases/store_table_names.py b/src/orcapod/databases/store_table_names.py index 5d92b100b..488d91aee 100644 --- a/src/orcapod/databases/store_table_names.py +++ b/src/orcapod/databases/store_table_names.py @@ -48,9 +48,9 @@ def require_store_path_domain(path: Sequence[str]) -> tuple[str, ...]: A path inside this syntax can still be refused for its size: each entry of the identity record is capped at SpiralDB's entry limit - (``spiral_database_identity.MAX_METADATA_ENTRY_BYTES``, 8,192 bytes), so an + (``spiraldb_keyed.identity.MAX_METADATA_ENTRY_BYTES``, 8,192 bytes), so an 8,192-character component is valid here, round-trips through the chunked manifest, - and is refused by ``spiral_database_identity.table_identity_metadata``. + and is refused by ``spiraldb_keyed.identity.table_identity_metadata``. Args: path: The store's base path followed by its record path. diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index f72432023..a41c05e6a 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -742,17 +742,17 @@ def __init__(self, reason: str, *, table: str | None = None) -> None: class SpiralDBWriteNotSupportedError(NotImplementedError): """A plain SpiralDB connector was asked to write: it only reads (ITL-1186). - Raised by every write of a plain ``SpiralDBConnector`` (creating or deleting a table, + Raised by every write of a plain ``SpiralDBKeyedConnector`` (creating or deleting a table, storing rows), so also by a job whose database is a ``ConnectorArrowDatabase`` on one. Nothing is written. A job keeps its tables in SpiralDB through a writable SpiralDB - database, ``SpiralDBConnector(..., writable=True)`` (ITL-1844). + database, ``SpiralDBKeyedConnector(..., writable=True)`` (ITL-1844). """ class SpiralDBLeaseRequiredError(RuntimeError): """A writable SpiralDB database was written outside a job run (ITL-1844). - A writable SpiralDB database (``SpiralDBConnector(..., writable=True)``) is written + A writable SpiralDB database (``SpiralDBKeyedConnector(..., 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 diff --git a/src/orcapod/pipeline/_observer_database.py b/src/orcapod/pipeline/_observer_database.py index 0ab42409b..2d8a9fd0d 100644 --- a/src/orcapod/pipeline/_observer_database.py +++ b/src/orcapod/pipeline/_observer_database.py @@ -9,7 +9,7 @@ from orcapod.databases import ( ConnectorArrowDatabase, ExtensionAwareDatabase, - SpiralDBConnector, + SpiralDBKeyedConnector, ) from orcapod.errors import SpiralDBObserverNotSupportedError @@ -52,7 +52,7 @@ def require_observer_database(database: ArrowDatabaseProtocol) -> None: return connector = _stored_reference(backend, "_connector") - if issubclass(type(connector), SpiralDBConnector): + if issubclass(type(connector), SpiralDBKeyedConnector): raise SpiralDBObserverNotSupportedError( "Observers cannot record to a SpiralDB database in this version. " + "Give the observer another database, for example Delta." diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 12d289a7d..ae5323bb4 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -48,9 +48,9 @@ RunPlan, check_sources, clear_run_rows, + database_write_scope, plan_run, run_owner, - database_write_scope, ) from orcapod.pipeline.observer_losses import RunLosses from orcapod.pipeline.restrictions import ( @@ -2380,7 +2380,7 @@ def load( the argument that gives it is missing: a connector is not rebuilt from a file. The message names each such binding. Also if a SpiralDB database was saved writable - (``SpiralDBConnector(..., writable=True)``) and the one given is a + (``SpiralDBKeyedConnector(..., writable=True)``) and the one given is a plain SpiralDB connector database, or the other way round (ITL-1844). Only a SpiralDB database of the other kind is refused: a database that is not a SpiralDB one may stand for a saved @@ -2423,9 +2423,8 @@ def load( exc.add_note(f"Loading the job file {path}") raise - # A saved SpiralDB connector configuration this version does not read (a - # ``store`` key, a ``writable`` that is not a boolean) is refused first, given - # a connector or not, so an old file is told about writable=True (ITL-1844). + # Report unsupported keyed SpiralDB configurations before reporting missing + # connectors, even if the caller supplies a connector for the affected slot. unreadable = [ f"bindings.{slot_name}: {reason}" for slot_name in ("database", "result_database") diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index bb2c4361e..4d8e1dbdd 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -27,13 +27,13 @@ OrcapodDatabaseWriteError, live_input_cycle_error, ) +from orcapod.pipeline.restrictions import restrictions_in_force, source_name +from orcapod.pipeline.result import StreamsOnRead from orcapod.pipeline.run_summary import ( RunCountingObserver, RunSummary, run_node_summaries, ) -from orcapod.pipeline.restrictions import restrictions_in_force, source_name -from orcapod.pipeline.result import StreamsOnRead from orcapod.utils.database_errors import flush_best_effort if TYPE_CHECKING: @@ -400,7 +400,7 @@ def database_write_scope( (ITL-1844). 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 + run checks its sources (``spiraldb_keyed.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 @@ -419,7 +419,9 @@ def database_write_scope( Raises: ValueError: As ``refuse_unloadable_source_checks``, for a load-only run. """ - from orcapod.databases.spiraldb_writable_registry import any_writable_connector + from orcapod.databases.spiraldb_keyed.writable_registry import ( + any_writable_connector, + ) if load_only: # Before any lease is taken or source checked: a load-only run never reads an @@ -427,7 +429,7 @@ def database_write_scope( refuse_unloadable_source_checks(streams) if not any_writable_connector(): return contextlib.nullcontext() - from orcapod.databases.spiraldb_write_scope import database_writes + from orcapod.databases.spiraldb_keyed.write_scope import database_writes written = write_scope_databases(streams, load_only=load_only, databases=databases) if owner is None: diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 7054094c3..0bd3edb5b 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -12,8 +12,6 @@ from functools import partial from typing import TYPE_CHECKING, Any, TypeAlias, cast -from orcapod.types import Schema -from orcapod.types.argument_groups import SymmetricGroup from orcapod.logical_types.canonical_form import ( declaration_form_field, declaration_form_schema, @@ -25,8 +23,9 @@ arrow_type_identifier, require_readable, ) - from orcapod.semantic_types._schema_conversion import arrow_schema_for_types +from orcapod.types import Schema +from orcapod.types.argument_groups import SymmetricGroup from orcapod.utils.schema_utils import ReservedColumnNameError, require_names_not_system if TYPE_CHECKING: @@ -276,9 +275,9 @@ def _build_source_registry() -> dict[str, type]: from orcapod.core.sources.derived_source import DerivedSource from orcapod.core.sources.dict_source import DictSource from orcapod.core.sources.list_source import ListSource + from orcapod.core.sources.postgresql_table_source import PostgreSQLTableSource from orcapod.core.sources.spiraldb_table_source import SpiralDBTableSource from orcapod.core.sources.sqlite_table_source import SQLiteTableSource - from orcapod.core.sources.postgresql_table_source import PostgreSQLTableSource return { CSVSource.SOURCE_KIND: CSVSource, @@ -354,8 +353,7 @@ def _build_data_function_registry() -> dict[str, type]: Returns: Dict mapping type ID strings to data function classes. """ - from orcapod.core.data_function import PythonDataFunction - from orcapod.core.data_function import PYTHON_FUNCTION + from orcapod.core.data_function import PYTHON_FUNCTION, PythonDataFunction return { PYTHON_FUNCTION.type_id: PythonDataFunction, @@ -377,9 +375,9 @@ def _build_data_function_registry() -> dict[str, type]: def _get_observer_registry() -> dict[str, type[_Observer]]: global _observer_registry if _observer_registry is None: - from orcapod.pipeline.status_observer import StatusObserver - from orcapod.pipeline.logging_observer import LoggingObserver from orcapod.pipeline.composite_observer import CompositeObserver + from orcapod.pipeline.logging_observer import LoggingObserver + from orcapod.pipeline.status_observer import StatusObserver _observer_registry = { "status": StatusObserver, @@ -507,7 +505,7 @@ def resolve_database_from_config( #: The kinds of connector a message may name. -_CONNECTOR_KINDS = ("sqlite", "postgresql", "spiraldb") +_CONNECTOR_KINDS = ("sqlite", "postgresql", "spiraldb_keyed") def saved_database_kind(config: Any) -> str: @@ -562,9 +560,9 @@ def saved_connector_kind(config: Any) -> str | None: config: A saved database configuration, or ``None``. Returns: - ``"sqlite"``, ``"postgresql"`` or ``"spiraldb"``, ``"unknown connector kind"`` - for anything else the file says, or ``None`` for a database that is not over - a connector. + ``"sqlite"``, ``"postgresql"`` or ``"spiraldb_keyed"`` for a known connector, + ``"unknown connector kind"`` for any other connector, or ``None`` for a database + that is not over a connector. """ from orcapod.databases.connector_arrow_database import CONNECTOR_DATABASE_TYPE @@ -585,10 +583,9 @@ def saved_connector_kind(config: Any) -> str | None: def spiraldb_saved_config_refusal(config: Any) -> str | None: """Why a saved SpiralDB connector configuration is not read, or ``None``. - A saved SpiralDB connector with a ``store`` key (not an option of this version: - ``writable`` is), or a ``writable`` that is not a boolean, is refused whatever - database is given, also when none is: ``PipelineJob.load`` checks it before it - asks for a missing connector, so an old file is told about ``writable=True``. + ``PipelineJob.load`` checks this before asking for a missing connector. It + refuses the retired ``spiraldb`` type, configurations with a ``store`` key, + and a ``writable`` value that is not a boolean. Args: config: The saved database configuration. @@ -597,11 +594,26 @@ def spiraldb_saved_config_refusal(config: Any) -> str | None: The reason, or ``None`` when the configuration is not a SpiralDB connector's or is one this version reads. """ - from orcapod.databases.spiraldb_connector import STORE_KEY_REFUSAL + from orcapod.databases.connector_arrow_database import CONNECTOR_DATABASE_TYPE + from orcapod.databases.spiraldb_keyed.connector import STORE_KEY_REFUSAL - if saved_connector_kind(config) != "spiraldb": + if not isinstance(config, dict): + return None + database = cast("dict[str, Any]", config) + connector = database.get("connector") + if database.get("type") != CONNECTOR_DATABASE_TYPE or not isinstance( + connector, dict + ): + return None + saved = cast("dict[str, Any]", connector) + kind = saved.get("connector_type") + if kind == "spiraldb": + return ( + "saved connector_type 'spiraldb' is unsupported; use 'spiraldb_keyed' " + "with SpiralDBKeyedConnector" + ) + if kind != "spiraldb_keyed": return None - saved = cast("dict[str, Any]", cast("dict[str, Any]", config)["connector"]) if "store" in saved: return STORE_KEY_REFUSAL writable = saved.get("writable", False) @@ -609,7 +621,7 @@ def spiraldb_saved_config_refusal(config: Any) -> str | None: return ( f"the saved SpiralDB connector's 'writable' is {writable!r}; it must be " "true or false (writable=True makes a writable SpiralDB database: " - "SpiralDBConnector(..., writable=True), saved as 'writable': true)" + "SpiralDBKeyedConnector(..., writable=True), saved as 'writable': true)" ) return None @@ -617,7 +629,7 @@ def spiraldb_saved_config_refusal(config: Any) -> str | None: def spiraldb_writable_mismatch(config: Any, given: Any) -> str | None: """Why a database given at load cannot stand for a saved SpiralDB one, or ``None``. - A job saved on a writable SpiralDB database (``SpiralDBConnector(..., + A job saved on a writable SpiralDB database (``SpiralDBKeyedConnector(..., writable=True)``, ITL-1844) is loaded with a writable connector, and one saved on a plain SpiralDB connector with a plain one: the two read different tables. The project and dataset are not compared (a job may be pointed at a copy). A saved @@ -634,18 +646,18 @@ def spiraldb_writable_mismatch(config: Any, given: Any) -> str | None: """ from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase from orcapod.databases.extension_aware_database import unwrap_database_views - from orcapod.databases.spiraldb_connector import SpiralDBConnector + from orcapod.databases.spiraldb_keyed.connector import SpiralDBKeyedConnector if (refusal := spiraldb_saved_config_refusal(config)) is not None: return refusal - if saved_connector_kind(config) != "spiraldb": + if saved_connector_kind(config) != "spiraldb_keyed": return None saved = cast("dict[str, Any]", cast("dict[str, Any]", config)["connector"]) given = unwrap_database_views(given) # a library view over the connector database if not isinstance(given, ConnectorArrowDatabase): return None connector = given._connector # pyright: ignore[reportPrivateUsage] # which connector the given database is over - if not isinstance(connector, SpiralDBConnector): + if not isinstance(connector, SpiralDBKeyedConnector): return None saved_writable = saved.get("writable", False) is True given_writable = connector._writable # pyright: ignore[reportPrivateUsage] # whether it opens the dataset as a writable database @@ -654,7 +666,7 @@ def spiraldb_writable_mismatch(config: Any, given: Any) -> str | None: if saved_writable: return ( "the job was saved on a writable SpiralDB database: pass a writable " - "connector, SpiralDBConnector(..., writable=True)" + "connector, SpiralDBKeyedConnector(..., writable=True)" ) return ( "the job was saved on a plain SpiralDB connector: pass one without " diff --git a/src/orcapod/protocols/database_protocols.py b/src/orcapod/protocols/database_protocols.py index 110c1f57f..96cf92d37 100644 --- a/src/orcapod/protocols/database_protocols.py +++ b/src/orcapod/protocols/database_protocols.py @@ -2,12 +2,13 @@ from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager -from typing import Any, Protocol, TYPE_CHECKING, runtime_checkable +from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable from orcapod.protocols.db_connector_protocol import ColumnInfo, DBConnectorProtocol if TYPE_CHECKING: import pyarrow as pa + from orcapod.databases._pending_commits import PendingCommit @@ -366,7 +367,7 @@ class FieldMetadataKeepingDatabaseProtocol(Protocol): ``InMemoryArrowDatabase`` and ``DeltaTableDatabase`` keep it. A ``ConnectorArrowDatabase`` keeps it when its connector does: a connector states it - with the same member (``SpiralDBConnector`` does; ``SQLiteConnector`` and + with the same member (``SpiralDBKeyedConnector`` does; ``SQLiteConnector`` and ``PostgreSQLConnector`` do not). ``ExtensionAwareDatabase`` states what the database it wraps states. ``NoOpArrowDatabase`` keeps nothing. """ diff --git a/src/orcapod/protocols/db_connector_protocol.py b/src/orcapod/protocols/db_connector_protocol.py index 1fd57380f..2a6bc0654 100644 --- a/src/orcapod/protocols/db_connector_protocol.py +++ b/src/orcapod/protocols/db_connector_protocol.py @@ -7,13 +7,13 @@ Planned implementations: SQLiteConnector -- PLT-1076 (stdlib sqlite3, zero extra deps) PostgreSQLConnector -- PLT-1075 (psycopg3) - SpiralDBConnector -- PLT-1074 + SpiralDBKeyedConnector -- PLT-1074 """ from __future__ import annotations from collections.abc import Iterator -from typing import Any, Protocol, TYPE_CHECKING, runtime_checkable +from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable from orcapod.types import ColumnInfo @@ -43,7 +43,7 @@ class DBConnectorProtocol(Protocol): DB-native type conversion internally. Planned implementations: ``SQLiteConnector`` (PLT-1076), - ``PostgreSQLConnector`` (PLT-1075), ``SpiralDBConnector`` (PLT-1074). + ``PostgreSQLConnector`` (PLT-1075), ``SpiralDBKeyedConnector`` (PLT-1074). """ # ── Schema introspection ────────────────────────────────────────────────── @@ -200,7 +200,7 @@ def to_config(self) -> dict[str, Any]: """Serialize connection configuration to a JSON-compatible dict. The returned dict must include a ``"connector_type"`` key - (e.g., ``"sqlite"``, ``"postgresql"``, ``"spiraldb"``) so that + (e.g., ``"sqlite"``, ``"postgresql"``, ``"spiraldb_keyed"``) so that a registry helper can dispatch to the correct ``from_config`` classmethod when deserializing. """ diff --git a/tests/test_core/data_tags/test_database_capability.py b/tests/test_core/data_tags/test_database_capability.py index 5cc6769e8..d11e718df 100644 --- a/tests/test_core/data_tags/test_database_capability.py +++ b/tests/test_core/data_tags/test_database_capability.py @@ -20,14 +20,14 @@ import orcapod as op from orcapod.contexts import resolve_context -from orcapod.core.operators import Join from orcapod.core.data_tags import mark_data_tags +from orcapod.core.operators import Join from orcapod.databases import ( ConnectorArrowDatabase, DeltaTableDatabase, InMemoryArrowDatabase, NoOpArrowDatabase, - SpiralDBConnector, + SpiralDBKeyedConnector, ) from orcapod.databases.extension_aware_database import ExtensionAwareDatabase from orcapod.databases.sqlite_connector import SQLiteConnector @@ -111,7 +111,7 @@ def _source() -> op.sources.DictSource: def test_each_database_states_the_capability(tmp_path: Path, spiral: None) -> None: sqlite = ConnectorArrowDatabase(SQLiteConnector(":memory:")) - spiraldb = ConnectorArrowDatabase(SpiralDBConnector("p")) + spiraldb = ConnectorArrowDatabase(SpiralDBKeyedConnector("p")) stated = { "in memory": InMemoryArrowDatabase(), "delta": DeltaTableDatabase(tmp_path / "delta"), diff --git a/tests/test_core/sources/test_spiraldb_lookups.py b/tests/test_core/sources/test_spiraldb_lookups.py index 9f1455738..2ea4f3ca6 100644 --- a/tests/test_core/sources/test_spiraldb_lookups.py +++ b/tests/test_core/sources/test_spiraldb_lookups.py @@ -22,12 +22,12 @@ import pytest from orcapod import PipelineJob -from orcapod.databases import spiraldb_connector as connector_module from orcapod.databases import ( InMemoryArrowDatabase, - SpiralDBConnector, + SpiralDBKeyedConnector, ) -from orcapod.databases.spiraldb_schema_table import SCHEMA_TABLE +from orcapod.databases.spiraldb_keyed import connector as connector_module +from orcapod.databases.spiraldb_keyed.schema_table import SCHEMA_TABLE from orcapod.errors import InputValidationError from orcapod.operators import SelectColumns from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator @@ -726,7 +726,7 @@ def test_freshness_pins_newer_version(calls: collections.Counter[str]) -> None: def test_the_connector_getters_answer_as_the_handle_does( calls: collections.Counter[str], ) -> None: - with SpiralDBConnector(project_id=_PROJECT) as connector: + with SpiralDBKeyedConnector(project_id=_PROJECT) as connector: table = connector.lookup_table("t") # The key columns in the table's key order. assert connector.get_pk_columns("t") == table.key_columns == _ARRANGED["keys"] diff --git a/tests/test_core/sources/test_spiraldb_table_source.py b/tests/test_core/sources/test_spiraldb_table_source.py index ed77d1387..ebe6ae7d5 100644 --- a/tests/test_core/sources/test_spiraldb_table_source.py +++ b/tests/test_core/sources/test_spiraldb_table_source.py @@ -2,7 +2,7 @@ SpiralDB needs network access and credentials, so these tests run against the disk-backed pyspiral fake (``tests/test_databases/fake_spiral_sdk.py``): the source goes -through the real ``SpiralDBConnector``. Reading in batches, restrictions, the row cap and +through the real ``SpiralDBKeyedConnector``. Reading in batches, restrictions, the row cap and record identity are in ``test_spiraldb_table_source_streaming.py``; the end-to-end test is in ``test_spiraldb_table_source_fake.py``. @@ -30,13 +30,13 @@ import pytest from orcapod.core.sources import SpiralDBTableSource -from orcapod.databases import SpiralDBConnector -from orcapod.databases.spiraldb_connector import SpiralDBTable +from orcapod.databases import SpiralDBKeyedConnector +from orcapod.databases.spiraldb_keyed.connector import SpiralDBTable from tests.test_databases import fake_spiral_sdk _TABLE_NAME = "spike_data" _PROJECT_ID = "test-project-123456" -_CONNECTOR = "orcapod.core.sources.spiraldb_table_source.SpiralDBConnector" +_CONNECTOR = "orcapod.core.sources.spiraldb_table_source.SpiralDBKeyedConnector" def _make_table( @@ -251,10 +251,10 @@ class TestConnector: """The source forwards its arguments to the connector and closes it.""" def test_dataset_and_overrides_forwarded_to_connector(self): - """``dataset`` and ``overrides`` are forwarded to ``SpiralDBConnector``.""" + """``dataset`` and ``overrides`` are forwarded to ``SpiralDBKeyedConnector``.""" overrides = {"server.url": "http://api.spiraldb.dev"} _make_table(dataset="prod") - with patch(_CONNECTOR, wraps=SpiralDBConnector) as connector_class: + with patch(_CONNECTOR, wraps=SpiralDBKeyedConnector) as connector_class: SpiralDBTableSource( _PROJECT_ID, _TABLE_NAME, @@ -269,11 +269,11 @@ def test_dataset_and_overrides_forwarded_to_connector(self): def test_every_connector_is_closed(self): """Close the shared connector at context exit or failed construction.""" _make_table() - opened: list[SpiralDBConnector] = [] + opened: list[SpiralDBKeyedConnector] = [] def connect(**kwargs): """Open a real connector with ``kwargs`` and record it in ``opened``.""" - opened.append(SpiralDBConnector(**kwargs)) + opened.append(SpiralDBKeyedConnector(**kwargs)) return opened[-1] with patch(_CONNECTOR, side_effect=connect): diff --git a/tests/test_core/sources/test_spiraldb_table_source_fake.py b/tests/test_core/sources/test_spiraldb_table_source_fake.py index 371dc9601..3d1d6bc7d 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_fake.py +++ b/tests/test_core/sources/test_spiraldb_table_source_fake.py @@ -259,7 +259,7 @@ class TestSourceId: def two_projects(self, tmp_path: Path): """Provide two fake projects holding the same one-row ``item_profile`` table. - Each is written through ``SpiralDBConnector``, which records its non-nullable + Each is written through ``SpiralDBKeyedConnector``, which records its non-nullable columns (ITL-936); ``default.unrecorded`` holds the same row without a record. """ with fake_spiral_sdk.install(tmp_path / "spiral"): @@ -400,7 +400,7 @@ class TestNonNullableColumns: SpiralDB reports every column and struct field nullable, so this holds only for tables that carry Orcapod's nullability record: here, tables written through - ``SpiralDBConnector``. The same rows written without the record read as ``T | None``. + ``SpiralDBKeyedConnector``. The same rows written without the record read as ``T | None``. """ _KEYS = pa.schema( diff --git a/tests/test_core/test_result_cache.py b/tests/test_core/test_result_cache.py index 8102f9555..ba3428816 100644 --- a/tests/test_core/test_result_cache.py +++ b/tests/test_core/test_result_cache.py @@ -14,21 +14,20 @@ from pathlib import Path import pyarrow as pa - import pytest from orcapod.contexts import get_default_context from orcapod.core import result_cache -from orcapod.core.datagrams import Datagram, Data -from orcapod.core.datagrams.tag_data import EmptyData from orcapod.core.data_function import PythonDataFunction +from orcapod.core.datagrams import Data, Datagram +from orcapod.core.datagrams.tag_data import EmptyData from orcapod.core.result_cache import ResultCache from orcapod.databases import ( ConnectorArrowDatabase, DeltaTableDatabase, ExtensionAwareDatabase, InMemoryArrowDatabase, - SpiralDBConnector, + SpiralDBKeyedConnector, ) from orcapod.errors import OrcapodDatabaseWriteError, UnrecordedTableSchemaWarning from orcapod.protocols.core_protocols.datagrams import DataProtocol @@ -184,7 +183,7 @@ def check(cache: ResultCache, expected: DataProtocol) -> None: # rows. The fake SDK's write API refuses Orcapod's reserved column names. key = ConnectorArrowDatabase.RECORD_ID_COLUMN name = "__".join(cache.record_path) - with fake_spiral_sdk.install(spiral_root), SpiralDBConnector("p") as connector: + with fake_spiral_sdk.install(spiral_root), SpiralDBKeyedConnector("p") as connector: project = fake_spiral_sdk.FakeClient().project("p") table = project.create_keyed_table( "default", diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index c2c0cdba0..5b473e17e 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -32,7 +32,7 @@ import pyarrow as pa import pyarrow.compute as pc -from orcapod.databases.spiraldb_schema_table import SCHEMA_TABLE +from orcapod.databases.spiraldb_keyed.schema_table import SCHEMA_TABLE RULES = { "missing": "a missing table or dataset: SpiralError 'resource not found: " @@ -1253,10 +1253,13 @@ def install(root: Path | str): """Route Orcapod's SpiralDB calls to the fake, with tables stored under ``root``.""" with ( patch.dict(os.environ, {_ROOT_ENV: str(root)}), - patch("orcapod.databases.spiraldb_connector.sp", fake_module), - patch("orcapod.databases.spiraldb_connector.require_sign_in", lambda: None), + patch("orcapod.databases.spiraldb_keyed.connector.sp", fake_module), patch( - "orcapod.databases.spiraldb_connector._http_get_json", fake_http_get_json + "orcapod.databases.spiraldb_keyed.connector.require_sign_in", lambda: None + ), + patch( + "orcapod.databases.spiraldb_keyed.connector._http_get_json", + fake_http_get_json, ), ): yield @@ -1280,7 +1283,7 @@ def migrate( dataset: The dataset. complete: Whether to write the marker. """ - from orcapod.databases import spiraldb_schema_table as st + from orcapod.databases.spiraldb_keyed import schema_table as st from orcapod.utils import arrow_utils store = _store() diff --git a/tests/test_databases/test_migrate_spiral_schemas.py b/tests/test_databases/test_migrate_spiral_schemas.py index d4ed204ca..94c21b5c3 100644 --- a/tests/test_databases/test_migrate_spiral_schemas.py +++ b/tests/test_databases/test_migrate_spiral_schemas.py @@ -14,8 +14,8 @@ import pyarrow as pa import pytest -from orcapod.databases import SpiralDBConnector -from orcapod.databases import spiraldb_schema_table as st +from orcapod.databases import SpiralDBKeyedConnector +from orcapod.databases.spiraldb_keyed import schema_table as st from orcapod.databases.store_table_names import ( SPIRAL_LEASE_KEY_PREFIX, is_spiral_lease_table_name, @@ -118,7 +118,7 @@ def args( # The reads the dry run makes, with the schemas in place; then they are taken away. for dataset in _DATASETS: fake.migrate("p", dict.fromkeys(_TABLES, _WRITTEN), dataset) - connector = SpiralDBConnector("p", dataset) + connector = SpiralDBKeyedConnector("p", dataset) for table in described[dataset]["tables"]: name = table["row"]["table_name"] table["source"] = tool.source_values("p", dataset, name) @@ -148,7 +148,7 @@ def test_write_then_verify(tool: ModuleType, args: argparse.Namespace) -> None: tool.verify(args) for dataset in _DATASETS: for name in _TABLES: - schema = SpiralDBConnector("p", dataset).get_arrow_schema(name) + schema = SpiralDBKeyedConnector("p", dataset).get_arrow_schema(name) assert schema.metadata == {b"who": b"test"} assert not schema.field("v").nullable assert schema.field("v").metadata == {b"unit": b"mV"} @@ -238,7 +238,7 @@ def _legacy_listing( ) opened: list[tuple[str, str]] = [] - class LegacyConnector(SpiralDBConnector): + class LegacyConnector(SpiralDBKeyedConnector): """The connector of one dataset, serving that dataset's reserved tables.""" def lookup_table(self, table_name: str) -> Any: # pyright: ignore[reportIncompatibleMethodOverride] # a stand-in handle @@ -265,7 +265,8 @@ def lookup_table(self, table_name: str) -> Any: # pyright: ignore[reportIncompa lambda _connector, _project, dataset, name: descriptions[dataset, name], ) monkeypatch.setattr( - "orcapod.databases.spiraldb_connector.SpiralDBConnector", LegacyConnector + "orcapod.databases.spiraldb_keyed.connector.SpiralDBKeyedConnector", + LegacyConnector, ) return plan, opened @@ -418,7 +419,7 @@ def test_the_dry_run_reads_raise_no_keyed_table_deprecation( """The dry run's reads of each table go through the connector, which ignores the SDK's keyed-table deprecation for its own opens, after an earlier open too.""" fake.migrate("p", dict.fromkeys(_TABLES, _WRITTEN), "one") - connector = SpiralDBConnector("p", "one") + connector = SpiralDBKeyedConnector("p", "one") _ = connector.lookup_table("trials") # an earlier open, before the error filter with warnings.catch_warnings(): warnings.simplefilter("error", DeprecationWarning) diff --git a/tests/test_databases/test_spiral_database_identity.py b/tests/test_databases/test_spiral_database_identity.py index 784e83aa3..9f858c526 100644 --- a/tests/test_databases/test_spiral_database_identity.py +++ b/tests/test_databases/test_spiral_database_identity.py @@ -16,9 +16,8 @@ import pyarrow as pa import pytest -from orcapod.databases import spiral_database_codec -from orcapod.databases import spiral_database_identity as names -from orcapod.databases import store_table_names +from orcapod.databases import spiral_database_codec, store_table_names +from orcapod.databases.spiraldb_keyed import identity as names H = "0123456789abcdef" * 4 RESULT = ("my_fn", H, "v0", "python.function.v1", "rev1", "rdb_v1") diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py index 424ce80b8..cf6a1ea5d 100644 --- a/tests/test_databases/test_spiral_lease.py +++ b/tests/test_databases/test_spiral_lease.py @@ -10,10 +10,10 @@ import pytest from orcapod.databases import spiraldb_lease -from orcapod.databases.spiraldb_connector import SpiralDBConnector +from orcapod.databases.spiraldb_keyed.connector import SpiralDBKeyedConnector from orcapod.databases.spiraldb_lease import ( - LeaseBusyError, Lease, + LeaseBusyError, LeaseError, acquire, check, @@ -526,7 +526,7 @@ def test_numbered_lease_tables_are_hidden_but_database_tables_are_visible( _ = client.project(_PROJECT).create_keyed_table(_DATASET, lookalike, key_schema) monkeypatch.setattr(fake, "list_page_size", 1) - with SpiralDBConnector(_PROJECT, dataset=_DATASET) as connector: + with SpiralDBKeyedConnector(_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"] @@ -558,7 +558,7 @@ def test_connector_reserves_generation_names_even_without_a_claim_key( """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 SpiralDBKeyedConnector(_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"): @@ -566,7 +566,7 @@ def test_connector_reserves_generation_names_even_without_a_claim_key( table = client.project(_PROJECT).create_keyed_table( _DATASET, name, pa.schema([pa.field("id", pa.int64())]) ) - with SpiralDBConnector(_PROJECT, dataset=_DATASET) as connector: + with SpiralDBKeyedConnector(_PROJECT, dataset=_DATASET) as connector: assert connector.get_table_names() == [] with pytest.raises(ValueError, match="reserved"): _ = connector.lookup_table(name) @@ -596,7 +596,7 @@ def unexpected_open(*_args: object, **_kwargs: object) -> None: 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: + with SpiralDBKeyedConnector(_PROJECT, dataset=_DATASET) as connector: assert connector.get_table_names() == [name] diff --git a/tests/test_databases/test_spiraldb_job_projection.py b/tests/test_databases/test_spiraldb_job_projection.py index 197c8597a..68b7f3bc4 100644 --- a/tests/test_databases/test_spiraldb_job_projection.py +++ b/tests/test_databases/test_spiraldb_job_projection.py @@ -26,17 +26,17 @@ RowsOnRead, _RowsOfStream, # pyright: ignore[reportPrivateUsage] # main's sync output class ) -from orcapod.core.streams.arrow_table_stream import pending_whole_read from orcapod.core.sources import spiraldb_table_source as source_module +from orcapod.core.streams.arrow_table_stream import pending_whole_read +from orcapod.core.streams.base import schema_requires_io, typed_zero_row_table +from orcapod.core.streams.view import display_name from orcapod.databases import InMemoryArrowDatabase -from orcapod.databases import spiraldb_connector as connector_module +from orcapod.databases.spiraldb_keyed import connector as connector_module from orcapod.pipeline import ( AsyncPipelineOrchestrator, SyncPipelineOrchestrator, column_demand, ) -from orcapod.core.streams.base import schema_requires_io, typed_zero_row_table -from orcapod.core.streams.view import display_name from orcapod.pipeline.dag import OrcaDAG from orcapod.protocols.core_protocols import SourceProtocol, StreamProtocol from orcapod.sources import SpiralDBTableSource diff --git a/tests/test_databases/test_spiraldb_connector_integration.py b/tests/test_databases/test_spiraldb_keyed_connector_integration.py similarity index 98% rename from tests/test_databases/test_spiraldb_connector_integration.py rename to tests/test_databases/test_spiraldb_keyed_connector_integration.py index bcfe89996..f506ff72e 100644 --- a/tests/test_databases/test_spiraldb_connector_integration.py +++ b/tests/test_databases/test_spiraldb_keyed_connector_integration.py @@ -31,10 +31,10 @@ import pyarrow.compute as pc import pytest -from orcapod.databases import SpiralDBConnector -from orcapod.databases import spiraldb_connector as connector_module -from orcapod.databases import spiraldb_schema_table as st -from orcapod.databases.spiraldb_connector import SpiralDBTableNotFoundError +from orcapod.databases import SpiralDBKeyedConnector +from orcapod.databases.spiraldb_keyed import connector as connector_module +from orcapod.databases.spiraldb_keyed import schema_table as st +from orcapod.databases.spiraldb_keyed.connector import SpiralDBTableNotFoundError from orcapod.sources import SpiralDBTableSource from orcapod.types import Condition, col from tests.test_databases import fake_spiral_sdk as fake @@ -163,9 +163,9 @@ class _Place: dataset: str overrides: dict[str, str] | None - def connector(self) -> SpiralDBConnector: + def connector(self) -> SpiralDBKeyedConnector: """Return a new connector.""" - return SpiralDBConnector(self.project, self.dataset, self.overrides) + return SpiralDBKeyedConnector(self.project, self.dataset, self.overrides) def source(self, name: str, **options: Any) -> SpiralDBTableSource: """Return a source on a table.""" @@ -368,7 +368,7 @@ def test_versions(place: _Place) -> None: def test_a_missing_table_and_dataset(place: _Place) -> None: with pytest.raises(SpiralDBTableNotFoundError): place.connector().lookup_table("absent") - missing = SpiralDBConnector(place.project, "absent_dataset", place.overrides) + missing = SpiralDBKeyedConnector(place.project, "absent_dataset", place.overrides) with pytest.raises(SpiralDBTableNotFoundError): missing.lookup_table("absent") assert missing.get_table_names() == [] diff --git a/tests/test_databases/test_spiraldb_keyed_table_deprecation.py b/tests/test_databases/test_spiraldb_keyed_table_deprecation.py index 48ce773b6..28df80117 100644 --- a/tests/test_databases/test_spiraldb_keyed_table_deprecation.py +++ b/tests/test_databases/test_spiraldb_keyed_table_deprecation.py @@ -16,9 +16,11 @@ sp = pytest.importorskip("spiral") -from orcapod.databases import spiraldb_connector # noqa: E402 # after the skip -from orcapod.databases.spiraldb_connector import ( # noqa: E402 # after the skip - SpiralDBConnector, +from orcapod.databases.spiraldb_keyed import ( # noqa: E402 # after the skip + connector as spiraldb_connector, +) +from orcapod.databases.spiraldb_keyed.connector import ( # noqa: E402 # after the skip + SpiralDBKeyedConnector, SpiralDBTableNotFoundError, ) @@ -65,19 +67,19 @@ class _SDK: @pytest.fixture -def connector() -> Iterator[SpiralDBConnector]: +def connector() -> Iterator[SpiralDBKeyedConnector]: """A connector on the real spiral-sdk client over the stub native client.""" with ( patch.object(spiraldb_connector, "sp", _SDK), patch.object(spiraldb_connector, "require_sign_in", lambda: None), ): - made = SpiralDBConnector("p", "d") + made = SpiralDBKeyedConnector("p", "d") yield made made.close() def test_orcapod_opens_keyed_tables_with_no_deprecation_warning( - connector: SpiralDBConnector, + connector: SpiralDBKeyedConnector, ) -> None: """With every warning an error, Orcapod's opens of a table (by name, found and not found) and of a version (by id) raise what the stub raises, never the deprecation.""" @@ -91,7 +93,7 @@ def test_orcapod_opens_keyed_tables_with_no_deprecation_warning( _ = table.arrow_schema(asof=2) -def test_a_direct_sdk_open_still_warns(connector: SpiralDBConnector) -> None: +def test_a_direct_sdk_open_still_warns(connector: SpiralDBKeyedConnector) -> None: """The filter Orcapod installs covers its own module only: an open called from another module (this test), by name or by id, still warns, after Orcapod's open.""" client = _Client() @@ -105,7 +107,7 @@ def test_a_direct_sdk_open_still_warns(connector: SpiralDBConnector) -> None: def test_an_error_filter_added_after_an_open_does_not_reach_orcapods_opens( - connector: SpiralDBConnector, + connector: SpiralDBKeyedConnector, ) -> None: """The first matching filter wins: an error filter added after Orcapod's first open ranks ahead of a filter that is merely present. Orcapod's later opens, by name and @@ -120,7 +122,7 @@ def test_an_error_filter_added_after_an_open_does_not_reach_orcapods_opens( def test_a_pytest_warns_block_after_an_open_records_no_deprecation( - connector: SpiralDBConnector, + connector: SpiralDBKeyedConnector, ) -> None: """``pytest.warns`` adds an "always" filter; Orcapod's opens inside it, after an earlier open, record nothing of the SDK's deprecation.""" @@ -135,7 +137,7 @@ def test_a_pytest_warns_block_after_an_open_records_no_deprecation( def test_the_filter_is_kept_once_however_often_orcapod_opens( - connector: SpiralDBConnector, + connector: SpiralDBKeyedConnector, ) -> None: """Moved to the front rather than added again: the filter list never grows.""" with warnings.catch_warnings(): diff --git a/tests/test_databases/test_spiraldb_projection.py b/tests/test_databases/test_spiraldb_projection.py index 65e148068..945a45ebf 100644 --- a/tests/test_databases/test_spiraldb_projection.py +++ b/tests/test_databases/test_spiraldb_projection.py @@ -19,7 +19,7 @@ from orcapod import PipelineJob, function_pod from orcapod.core.sources import spiraldb_table_source as source_module from orcapod.databases import InMemoryArrowDatabase -from orcapod.databases import spiraldb_connector as connector_module +from orcapod.databases.spiraldb_keyed import connector as connector_module from orcapod.sources import SpiralDBTableSource from orcapod.types import ColumnConfig, Condition from tests.test_databases import fake_spiral_sdk as fake diff --git a/tests/test_databases/test_spiraldb_reading.py b/tests/test_databases/test_spiraldb_reading.py index 453c57dd4..2e659af5b 100644 --- a/tests/test_databases/test_spiraldb_reading.py +++ b/tests/test_databases/test_spiraldb_reading.py @@ -6,9 +6,9 @@ from __future__ import annotations -import gc import asyncio import datetime as dt +import gc import math import os import signal @@ -25,9 +25,9 @@ import pytest from orcapod import PipelineJob, function_pod -from orcapod.databases import ConnectorArrowDatabase, SpiralDBConnector from orcapod.core.sources import spiraldb_table_source as source_module -from orcapod.databases import spiraldb_connector as connector_module +from orcapod.databases import ConnectorArrowDatabase, SpiralDBKeyedConnector +from orcapod.databases.spiraldb_keyed import connector as connector_module from orcapod.errors import ( NullInNonNullableColumnError, SpiralDBWriteNotSupportedError, @@ -36,8 +36,7 @@ ) from orcapod.nodes import FunctionJobNode from orcapod.sources import DictSource, SpiralDBTableSource -from orcapod.types import ColumnInfo -from orcapod.types import Condition +from orcapod.types import ColumnInfo, Condition from tests.test_databases import fake_spiral_sdk as fake _ITEM = pa.field("item", pa.float32(), False) @@ -90,7 +89,7 @@ def _keys(source: SpiralDBTableSource) -> list[tuple[Any, Any]]: def test_a_recorded_table_is_read_with_its_schema(project: Any) -> None: fake.migrate("p", {"units": _WRITTEN, "swapped": _WRITTEN}) - connector = SpiralDBConnector("p") + connector = SpiralDBKeyedConnector("p") schema = connector.get_arrow_schema("units") # SpiralDB's order: keys in key order, then by name, structs last, their fields too. assert schema.names == ["k2", "k1", "a", "z", "g"] @@ -126,7 +125,7 @@ def test_rows_come_in_key_order_and_values_are_kept(project: Any) -> None: (2, "a"), (1, "b"), ] - table = pa.Table.from_batches(SpiralDBConnector("p").scan_batches("units")) + table = pa.Table.from_batches(SpiralDBKeyedConnector("p").scan_batches("units")) expected = {(r["k2"], r["k1"]): r for r in _rows().to_pylist()} assert {(r["k2"], r["k1"]): r for r in table.to_pylist()} == expected @@ -160,7 +159,7 @@ def test_a_null_in_a_recorded_column_is_refused(project: Any) -> None: project.table("default.units").write(nulls) fake.migrate("p", {"units": _WRITTEN}) with pytest.raises(NullInNonNullableColumnError, match="units.*z|z.*units"): - list(SpiralDBConnector("p").scan_batches("units")) + list(SpiralDBKeyedConnector("p").scan_batches("units")) # ------------------------------------------------------------ a table that is not recorded @@ -183,11 +182,11 @@ def test_an_unrecorded_table_warns_once_and_reads_nullable( with pytest.warns(UnrecordedTableSchemaWarning, match=_unrecorded(name)) as seen: source = SpiralDBTableSource("p", name, tag_only_columns=True) _ = source.as_table() - _ = SpiralDBConnector("p").get_arrow_schema(name) + _ = SpiralDBKeyedConnector("p").get_arrow_schema(name) assert len(seen) == 1 assert "migrate_spiral_schemas.py" in str(seen[0].message) assert seen[0].filename == __file__ - schema = SpiralDBConnector("p").get_arrow_schema(name) + schema = SpiralDBKeyedConnector("p").get_arrow_schema(name) assert all(f.nullable and not f.metadata for f in schema) @@ -205,14 +204,14 @@ def test_a_recorded_table_warns_nothing(project: Any) -> None: with warnings.catch_warnings(): warnings.simplefilter("error") SpiralDBTableSource("p", "units", tag_only_columns=True).as_table() - assert SpiralDBConnector("p").get_table_names() == ["swapped", "units"] + assert SpiralDBKeyedConnector("p").get_table_names() == ["swapped", "units"] def test_a_recorded_table_that_is_gone_is_warned_about(project: Any) -> None: fake.migrate("p", {"units": _WRITTEN}) project.drop_table("default.swapped") with pytest.warns(UnrecordedTableSchemaWarning, match="no longer holds.*swapped"): - assert SpiralDBConnector("p").get_table_names() == ["units"] + assert SpiralDBKeyedConnector("p").get_table_names() == ["units"] # ------------------------------------------------------------------ a row that disagrees @@ -232,7 +231,7 @@ def test_an_older_version_with_other_columns_is_refused(project: Any) -> None: pa.table({"k2": pa.array([9], pa.int32()), "k1": ["z"], "new": [1]}) ) fake.migrate("p", {}) - connector = SpiralDBConnector("p") + connector = SpiralDBKeyedConnector("p") assert len(list(connector.scan_batches("units"))) > 0 with pytest.raises(TableSchemaError, match="not in the table: .'new'"): list(connector.scan_batches("units", asof=1)) @@ -257,7 +256,7 @@ def test_a_recreated_table_is_not_read_with_the_old_row(project: Any) -> None: pa.table({"k": ["a"], "v": [1]}) ) with pytest.warns(UnrecordedTableSchemaWarning, match="units has no row"): - schema = SpiralDBConnector("p").get_arrow_schema("units") + schema = SpiralDBKeyedConnector("p").get_arrow_schema("units") assert schema.names == ["k", "v"] @@ -366,7 +365,7 @@ def test_where_matches_as_the_service_does( project: Any, column: str, value: Any, expected: list[int] ) -> None: project.create_table("default.typed", key_schema=[("k", pa.int64())]).write(_TYPED) - batches = SpiralDBConnector("p").scan_batches( + batches = SpiralDBKeyedConnector("p").scan_batches( "typed", where=Condition.of({column: value}) ) assert [k for b in batches for k in b.column("k").to_pylist()] == expected @@ -383,7 +382,7 @@ def test_a_filter_applied_here_comes_before_the_limit(project: Any, limit: int) ) project.create_table("default.half", key_schema=[("k", pa.int64())]).write(rows) for where in ({"h": 2.0, "s": "x"}, {"s": "x", "h": 2.0}): - batches = SpiralDBConnector("p").scan_batches( + batches = SpiralDBKeyedConnector("p").scan_batches( "half", where=Condition.of(where), limit=limit ) found = [k for b in batches for k in b.column("k").to_pylist()] @@ -415,7 +414,9 @@ def test_every_equality_applied_here_holds( Condition.of(Condition.of(h=first), Condition.of(h=second)), Condition.of(Condition.of(h=first), Condition.of(s="x", h=second)), ): - batches = SpiralDBConnector("p").scan_batches("half", where=where, limit=limit) + batches = SpiralDBKeyedConnector("p").scan_batches( + "half", where=where, limit=limit + ) found = [k for b in batches for k in b.column("k").to_pylist()] if first != second: assert found == [] @@ -472,7 +473,7 @@ def test_warnings_from_many_threads_stop_once_shown(project: Any) -> None: def build(_: int) -> None: barrier.wait(10) - SpiralDBConnector("p").get_arrow_schema("units") + SpiralDBKeyedConnector("p").get_arrow_schema("units") def shown(seen: list[warnings.WarningMessage]) -> int: return len([w for w in seen if w.category is UnrecordedTableSchemaWarning]) @@ -496,7 +497,7 @@ def test_every_concurrent_reader_raises_with_the_warning_as_an_error( def build(_: int) -> str: barrier.wait(10) try: - SpiralDBConnector("p").get_arrow_schema("units") + SpiralDBKeyedConnector("p").get_arrow_schema("units") except UnrecordedTableSchemaWarning: return "raised" return "passed" @@ -519,7 +520,8 @@ def hook(*given: Any, **options: Any) -> None: if readers: return reader = threading.Thread( - target=lambda: SpiralDBConnector("p").get_arrow_schema(table), daemon=True + target=lambda: SpiralDBKeyedConnector("p").get_arrow_schema(table), + daemon=True, ) readers.append(reader) reader.start() @@ -529,7 +531,7 @@ def hook(*given: Any, **options: Any) -> None: with warnings.catch_warnings(): warnings.simplefilter("always", UnrecordedTableSchemaWarning) monkeypatch.setattr(warnings, "showwarning", hook) - SpiralDBConnector("p").get_arrow_schema("units") + SpiralDBKeyedConnector("p").get_arrow_schema("units") assert finished == [True] @@ -540,13 +542,13 @@ def test_a_warning_hook_may_read_the_table_itself( def hook(*given: Any, **options: Any) -> None: calls.append(1) - SpiralDBConnector("p").get_arrow_schema("units") + SpiralDBKeyedConnector("p").get_arrow_schema("units") with warnings.catch_warnings(): warnings.simplefilter("always", UnrecordedTableSchemaWarning) monkeypatch.setattr(warnings, "showwarning", hook) - SpiralDBConnector("p").get_arrow_schema("units") - SpiralDBConnector("p").get_arrow_schema("units") + SpiralDBKeyedConnector("p").get_arrow_schema("units") + SpiralDBKeyedConnector("p").get_arrow_schema("units") assert calls == [1] @@ -565,7 +567,7 @@ def slow(*given: Any, **options: Any) -> None: def build() -> str: try: - SpiralDBConnector("p").get_arrow_schema("units") + SpiralDBKeyedConnector("p").get_arrow_schema("units") except UnrecordedTableSchemaWarning: return "raised" return "passed" @@ -588,7 +590,7 @@ def second() -> str: def test_a_count_is_remembered_per_version(project: Any) -> None: fake.migrate("p", {"units": _WRITTEN}) fake.count_log.clear() - connector = SpiralDBConnector("p") + connector = SpiralDBKeyedConnector("p") assert connector.lookup_table("units").count_rows(at_most=2) == 2 assert connector.lookup_table("units").count_rows(at_most=1) == 1 assert connector.lookup_table("units").count_rows() == 3 @@ -611,7 +613,7 @@ def test_the_listing_reads_every_page(tmp_path: Path, count: int) -> None: for i in range(count): made.create_table(f"ds.t{i}", key_schema=[("k", pa.string())]) made.create_table(f"other.t{i}", key_schema=[("k", pa.string())]) - names = SpiralDBConnector("p q", "ds").get_table_names() + names = SpiralDBKeyedConnector("p q", "ds").get_table_names() assert names == sorted(f"t{i}" for i in range(count)) @@ -627,7 +629,7 @@ def test_a_listing_that_does_not_advance_is_refused( lambda url, token: {"items": [], "nextPageToken": next(tokens)}, ): with pytest.raises(RuntimeError, match="does not advance"): - SpiralDBConnector("p").get_table_names() + SpiralDBKeyedConnector("p").get_table_names() def test_the_token_is_never_sent_on_a_redirect() -> None: @@ -665,7 +667,7 @@ def log_message(self, format: str, *args: Any) -> None: def test_every_write_is_refused_and_writes_nothing(project: Any) -> None: - connector = SpiralDBConnector("p") + connector = SpiralDBKeyedConnector("p") columns = [ColumnInfo("k", pa.large_string(), False)] for write in ( lambda: connector.create_table_if_not_exists("new", columns, "k"), @@ -687,7 +689,7 @@ def test_a_database_refuses_rows_before_it_holds_them( project: Any, flush: bool ) -> None: """Review finding B3.""" - database = ConnectorArrowDatabase(SpiralDBConnector("p")) + database = ConnectorArrowDatabase(SpiralDBKeyedConnector("p")) rows = pa.table({"id": pa.array([b"1"], pa.large_binary()), "v": [1]}) with pytest.raises(SpiralDBWriteNotSupportedError): database.add_records(("t",), rows, record_id_column="id", flush=flush) @@ -705,7 +707,9 @@ def double(v: int) -> int: return 2 * v source = DictSource([{"k": 1, "v": 1}], tag_columns=["k"], source_id="s") - job = PipelineJob(name="j", database=ConnectorArrowDatabase(SpiralDBConnector("p"))) + job = PipelineJob( + name="j", database=ConnectorArrowDatabase(SpiralDBKeyedConnector("p")) + ) with pytest.raises(SpiralDBWriteNotSupportedError): with job: double.pod(source, label="double") @@ -754,20 +758,20 @@ def double(z: float) -> float: def test_the_one_override_is_the_address(project: Any) -> None: overrides = {"server.url": "https://api.example.invalid"} - connector = SpiralDBConnector("p", overrides=overrides) + connector = SpiralDBKeyedConnector("p", overrides=overrides) assert connector._client.api_url == "https://api.example.invalid" # pyright: ignore[reportPrivateUsage] # what the client was given - assert SpiralDBConnector.from_config(connector.to_config()).to_config() == { - "connector_type": "spiraldb", + assert SpiralDBKeyedConnector.from_config(connector.to_config()).to_config() == { + "connector_type": "spiraldb_keyed", "project_id": "p", "dataset": "default", "overrides": overrides, } with pytest.raises(ValueError, match="authn.token"): - SpiralDBConnector("p", overrides={"authn.token": "x", **overrides}) + SpiralDBKeyedConnector("p", overrides={"authn.token": "x", **overrides}) def test_a_closed_connector_reads_nothing(project: Any) -> None: - with SpiralDBConnector("p") as connector: + with SpiralDBKeyedConnector("p") as connector: shared = connector.share_client() handle = connector.lookup_table("units") connector.close() @@ -849,7 +853,7 @@ async def cancel() -> None: def test_many_threads_read_through_one_connector(project: Any) -> None: fake.migrate("p", {"units": _WRITTEN, "swapped": _WRITTEN}) - connector = SpiralDBConnector("p") + connector = SpiralDBKeyedConnector("p") def read(i: int) -> tuple[list[str], int]: name = ("units", "swapped")[i % 2] @@ -865,7 +869,7 @@ def read(i: int) -> tuple[list[str], int]: def test_a_forked_child_is_refused_instead_of_hanging( project: Any, monkeypatch: pytest.MonkeyPatch ) -> None: - connector = SpiralDBConnector("p") + connector = SpiralDBKeyedConnector("p") monkeypatch.setattr(os, "getpid", lambda: -1) with pytest.raises(RuntimeError, match="after a fork"): connector.lookup_table("units") @@ -938,7 +942,7 @@ def hold() -> None: def test_a_missing_table_is_told_apart_from_other_failures( project: Any, monkeypatch: pytest.MonkeyPatch ) -> None: - connector = SpiralDBConnector("p") + connector = SpiralDBKeyedConnector("p") with pytest.raises(connector_module.SpiralDBTableNotFoundError): connector.lookup_table("absent") @@ -955,10 +959,10 @@ def denied(*_given: Any, **_options: Any) -> None: "query", ['SELECT * FROM "units"', "select * from units", 'SELECT * FROM "units"'] ) def test_a_query_names_its_table(project: Any, query: str) -> None: - batches = list(SpiralDBConnector("p").iter_batches(query)) + batches = list(SpiralDBKeyedConnector("p").iter_batches(query)) assert sum(b.num_rows for b in batches) == 3 def test_a_query_without_a_table_is_refused(project: Any) -> None: with pytest.raises(ValueError, match="Cannot parse"): - list(SpiralDBConnector("p").iter_batches("SELECT 1")) + list(SpiralDBKeyedConnector("p").iter_batches("SELECT 1")) diff --git a/tests/test_databases/test_spiraldb_schema_table.py b/tests/test_databases/test_spiraldb_schema_table.py index 07987076d..e80f42f3b 100644 --- a/tests/test_databases/test_spiraldb_schema_table.py +++ b/tests/test_databases/test_spiraldb_schema_table.py @@ -15,8 +15,8 @@ import pyarrow as pa import pytest -from orcapod.databases import SpiralDBConnector -from orcapod.databases import spiraldb_schema_table as st +from orcapod.databases import SpiralDBKeyedConnector +from orcapod.databases.spiraldb_keyed import schema_table as st from orcapod.errors import TableSchemaError from orcapod.sources import SpiralDBTableSource from tests.test_databases import fake_spiral_sdk as fake @@ -237,15 +237,17 @@ def _edit_schema_table(**change: Any) -> None: # Every way a person reaches a table's rows or what is known of it. _PATHS = { "source": lambda: SpiralDBTableSource("p", "units", tag_only_columns=True), - "schema": lambda: SpiralDBConnector("p").get_arrow_schema("units"), - "columns": lambda: SpiralDBConnector("p").get_column_info("units"), - "batches": lambda: list(SpiralDBConnector("p").scan_batches("units")), - "query": lambda: list(SpiralDBConnector("p").iter_batches('SELECT * FROM "units"')), - "count": lambda: SpiralDBConnector("p").get_row_count_estimate("units"), + "schema": lambda: SpiralDBKeyedConnector("p").get_arrow_schema("units"), + "columns": lambda: SpiralDBKeyedConnector("p").get_column_info("units"), + "batches": lambda: list(SpiralDBKeyedConnector("p").scan_batches("units")), + "query": lambda: list( + SpiralDBKeyedConnector("p").iter_batches('SELECT * FROM "units"') + ), + "count": lambda: SpiralDBKeyedConnector("p").get_row_count_estimate("units"), "bounded count": lambda: ( - SpiralDBConnector("p").lookup_table("units").count_rows(at_most=1) + SpiralDBKeyedConnector("p").lookup_table("units").count_rows(at_most=1) ), - "listing": lambda: SpiralDBConnector("p").get_table_names(), + "listing": lambda: SpiralDBKeyedConnector("p").get_table_names(), } @@ -360,7 +362,7 @@ def test_a_foreign_table_at_the_reserved_name_is_refused(tmp_path: Path) -> None def test_the_reserved_name_is_refused_and_unlisted(project: Any) -> None: fake.migrate("p", {"units": _WRITTEN}) - connector = SpiralDBConnector("p") + connector = SpiralDBKeyedConnector("p") assert connector.get_table_names() == ["trials", "units"] for use in (connector.lookup_table, connector.get_column_info): with pytest.raises(ValueError, match="reserved"): diff --git a/tests/test_databases/test_spiraldb_sign_in.py b/tests/test_databases/test_spiraldb_sign_in.py index fdb488674..cb3d1eb2b 100644 --- a/tests/test_databases/test_spiraldb_sign_in.py +++ b/tests/test_databases/test_spiraldb_sign_in.py @@ -11,8 +11,9 @@ import pytest -from orcapod.databases import SpiralDBConnector, spiraldb_connector -from orcapod.databases.spiraldb_sign_in import require_sign_in, saved_login_path +from orcapod.databases import SpiralDBKeyedConnector +from orcapod.databases.spiraldb_keyed import connector as spiraldb_connector +from orcapod.databases.spiraldb_keyed.sign_in import require_sign_in, saved_login_path from orcapod.errors import SpiralDBSignInError from orcapod.sources import SpiralDBTableSource @@ -138,7 +139,7 @@ def Client(**_options: object) -> None: monkeypatch.setattr(spiraldb_connector, "sp", NoClient) with pytest.raises(SpiralDBSignInError): - SpiralDBConnector("p") + SpiralDBKeyedConnector("p") with pytest.raises(SpiralDBSignInError): SpiralDBTableSource("p", "t") @@ -151,4 +152,4 @@ class Pyspiral: monkeypatch.setattr(spiraldb_connector, "sp", Pyspiral) with pytest.raises(ImportError, match="pyspiral"): - SpiralDBConnector("p") + SpiralDBKeyedConnector("p") diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index aa02a2d07..8b37762dd 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -1,6 +1,6 @@ """A SpiralDB connector in writable mode, under ``ConnectorArrowDatabase`` (ITL-1840). -On the fake (``fake_spiral_sdk``); no live SpiralDB. A ``SpiralDBConnector`` built +On the fake (``fake_spiral_sdk``); no live SpiralDB. A ``SpiralDBKeyedConnector`` 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 table kind's layout written and read back, the write rules of ITL-1386, refusals of @@ -27,12 +27,12 @@ ) from orcapod.core.operators import SelectDataColumns from orcapod.core.sources.cached_source import CachedSource -from orcapod.databases import ConnectorArrowDatabase, SpiralDBConnector +from orcapod.databases import ConnectorArrowDatabase, SpiralDBKeyedConnector from orcapod.databases import spiral_database_codec as codec -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.spiraldb_keyed import identity as identity +from orcapod.databases.spiraldb_keyed.identity import SpiralTableCollisionError +from orcapod.databases.spiraldb_keyed.tables import SpiralDBTables +from orcapod.databases.spiraldb_keyed.write_scope import database_writes, take_lease from orcapod.databases.store_table_names import is_spiral_lease_table_name from orcapod.errors import ( InputValidationError, @@ -83,10 +83,10 @@ def _release_test_leases() -> None: def writable_connector( project: str = "p", dataset: str = "d", *, held: bool = True -) -> SpiralDBConnector: +) -> SpiralDBKeyedConnector: """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) + connector = SpiralDBKeyedConnector(project, dataset, writable=True) if held: lease = _test_leases.get((project, dataset)) if lease is None: @@ -96,7 +96,7 @@ def writable_connector( return connector -def tables_of(connector: SpiralDBConnector) -> SpiralDBTables: +def tables_of(connector: SpiralDBKeyedConnector) -> SpiralDBTables: tables = connector._writable_tables() # pyright: ignore[reportPrivateUsage] assert tables is not None return tables @@ -1017,7 +1017,7 @@ def test_a_listed_table_renamed_since_its_record_was_read_is_refused() -> None: # ------------------------------------------------------ concurrent first writers -def _made_meanwhile(connector: SpiralDBConnector, make: Any) -> None: +def _made_meanwhile(connector: SpiralDBKeyedConnector, make: Any) -> None: """Run ``make`` (another party's act) just before ``connector`` creates or opens a table for its first write.""" tables = tables_of(connector) @@ -1160,7 +1160,7 @@ def test_raw_access_is_refused_in_database_mode() -> None: @pytest.mark.usefixtures("root") def test_a_plain_connector_still_writes_nothing() -> None: """Main's behaviour: a database on a plain connector refuses every write.""" - db = ConnectorArrowDatabase(SpiralDBConnector("p", "d")) + db = ConnectorArrowDatabase(SpiralDBKeyedConnector("p", "d")) with pytest.raises(SpiralDBWriteNotSupportedError): db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") with pytest.raises(SpiralDBWriteNotSupportedError): @@ -2134,7 +2134,7 @@ def test_a_database_mode_add_flush_and_listing_raise_no_keyed_table_deprecation( and open one by id itself, and raised). A direct call from elsewhere still warns.""" import warnings - from orcapod.databases import spiraldb_connector + from orcapod.databases.spiraldb_keyed import connector as spiraldb_connector called: dict[str, int] = {} diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 77cd3f4a4..3ccca2b7a 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -2,7 +2,7 @@ and load (ITL-1844). On the fake (``fake_spiral_sdk``); no live SpiralDB. Each job is run on a writable -SpiralDB database (``SpiralDBConnector(..., writable=True)``) and on Delta, and every +SpiralDB database (``SpiralDBKeyedConnector(..., writable=True)``) and on Delta, and every stored table is compared: same paths, same rows, apart from the columns a run fills with its own time or a random id. """ @@ -17,37 +17,43 @@ from pathlib import Path from typing import Any -from typing_extensions import override - import pyarrow as pa import pytest +from typing_extensions import override from orcapod import PipelineJob, function_pod +from orcapod.contexts import get_default_context from orcapod.core.operators import SelectDataColumns from orcapod.core.sources.cached_source import CachedSource from orcapod.databases import ( ConnectorArrowDatabase, DeltaTableDatabase, InMemoryArrowDatabase, - SpiralDBConnector, -) -from orcapod.contexts import get_default_context -from orcapod.databases import ( - spiraldb_connector, + SpiralDBKeyedConnector, 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.spiraldb_keyed import ( + connector as spiraldb_connector, +) +from orcapod.databases.spiraldb_keyed import ( + writable_registry as spiraldb_writable_registry, +) +from orcapod.databases.spiraldb_keyed import ( + write_scope as spiraldb_write_scope, +) +from orcapod.databases.spiraldb_keyed.write_scope import database_writes, take_lease from orcapod.databases.store_table_names import is_spiral_lease_table_name from orcapod.errors import SpiralDBLeaseRequiredError -from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator -from orcapod.pipeline import node_run +from orcapod.pipeline import ( + AsyncPipelineOrchestrator, + SyncPipelineOrchestrator, + node_run, +) +from orcapod.protocols.core_protocols import StreamProtocol from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.side_effects import SideEffectPod, sink_pod from orcapod.sources import ArrowTableSource -from orcapod.protocols.core_protocols import StreamProtocol from orcapod.types import CacheMode, ColumnConfig from tests.test_databases import fake_spiral_sdk as fake @@ -153,7 +159,7 @@ def root(tmp_path: Path) -> Iterator[Path]: def _database(dataset: str = "d") -> ConnectorArrowDatabase: - return ConnectorArrowDatabase(SpiralDBConnector("p", dataset, writable=True)) + return ConnectorArrowDatabase(SpiralDBKeyedConnector("p", dataset, writable=True)) def _database_tables(dataset: str = "d") -> list[str]: @@ -310,6 +316,8 @@ def test_a_loaded_job_reads_and_load_only_runs_take_no_lease(root: Path) -> None saved = root / "job.json" job.save(saved) text = saved.read_text() + connector = json.loads(text)["bindings"]["database"]["connector"] + assert connector["connector_type"] == "spiraldb_keyed" assert '"writable": true' in text assert not any(word in text.lower() for word in ("secret", "token", "private")) leases = _lease_tables() @@ -356,10 +364,12 @@ def test_load_refuses_a_spiraldb_connector_of_the_other_kind( _job(delta).save(saved) data = json.loads(saved.read_text()) data["bindings"]["database"] = ConnectorArrowDatabase( - SpiralDBConnector("p", "d") + SpiralDBKeyedConnector("p", "d") ).to_config() saved.write_text(json.dumps(data)) - given = ConnectorArrowDatabase(SpiralDBConnector("p", "d", writable=given_writable)) + given = ConnectorArrowDatabase( + SpiralDBKeyedConnector("p", "d", writable=given_writable) + ) with pytest.raises(ValueError, match="bindings.database.*writable"): _ = PipelineJob.load(saved, database=given) @@ -383,7 +393,7 @@ def test_load_refuses_a_saved_spiraldb_connector_with_a_store_key( None if given_writable is None else ConnectorArrowDatabase( - SpiralDBConnector("p", "d", writable=given_writable) + SpiralDBKeyedConnector("p", "d", writable=given_writable) ) ) with pytest.raises(ValueError, match=r"'store' key.*writable=True"): @@ -411,7 +421,7 @@ def test_load_refuses_a_saved_writable_value_that_is_not_a_boolean( None if given_writable is None else ConnectorArrowDatabase( - SpiralDBConnector("p", "d", writable=given_writable) + SpiralDBKeyedConnector("p", "d", writable=given_writable) ) ) with pytest.raises( @@ -424,29 +434,29 @@ def test_load_refuses_a_saved_writable_value_that_is_not_a_boolean( @pytest.mark.usefixtures("root") def test_a_spiraldb_connector_config_with_a_store_key_is_refused() -> None: - config = SpiralDBConnector("p", "d", writable=True).to_config() + config = SpiralDBKeyedConnector("p", "d", writable=True).to_config() del config["writable"] config["store"] = True with pytest.raises(ValueError, match=r"'store' key.*writable=True"): - _ = SpiralDBConnector.from_config(config) + _ = SpiralDBKeyedConnector.from_config(config) @pytest.mark.usefixtures("root") def test_the_writable_flag_is_saved_without_credentials() -> None: - assert SpiralDBConnector("p", "d", writable=True).to_config() == { - "connector_type": "spiraldb", + assert SpiralDBKeyedConnector("p", "d", writable=True).to_config() == { + "connector_type": "spiraldb_keyed", "project_id": "p", "dataset": "d", "overrides": None, "writable": True, } - assert "writable" not in SpiralDBConnector("p", "d").to_config() - rebuilt = SpiralDBConnector.from_config( - SpiralDBConnector("p", "d", writable=True).to_config() + assert "writable" not in SpiralDBKeyedConnector("p", "d").to_config() + rebuilt = SpiralDBKeyedConnector.from_config( + SpiralDBKeyedConnector("p", "d", writable=True).to_config() ) assert rebuilt._writable_tables() is not None # pyright: ignore[reportPrivateUsage] with pytest.raises(TypeError, match="writable must be True or False"): - _ = SpiralDBConnector("p", "d", writable="yes") # pyright: ignore[reportArgumentType] + _ = SpiralDBKeyedConnector("p", "d", writable="yes") # pyright: ignore[reportArgumentType] # ------------------------------------------------------------------ the lease @@ -470,7 +480,7 @@ def counted() -> bool: 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" + SpiralDBKeyedConnector("p", dataset, writable=True), "another writer" ) return release @@ -506,7 +516,7 @@ def test_a_second_writer_on_the_result_database_is_refused() -> None: _ = 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 = take_lease(SpiralDBKeyedConnector("p", "d", writable=True), "check") own() release() @@ -649,7 +659,7 @@ def test_a_job_run_on_a_database_raises_no_keyed_table_deprecation(entry: str) - 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) + connector = SpiralDBKeyedConnector("p", "d", writable=True) with warnings.catch_warnings(): warnings.simplefilter("error", DeprecationWarning) check, release = take_lease(connector, "first") @@ -727,11 +737,13 @@ def test_load_refuses_a_wrapped_spiraldb_connector_of_the_other_kind( _job(DeltaTableDatabase(root / "delta")).save(saved) data = json.loads(saved.read_text()) data["bindings"]["database"] = ConnectorArrowDatabase( - SpiralDBConnector("p", "d") + SpiralDBKeyedConnector("p", "d") ).to_config() saved.write_text(json.dumps(data)) given = _wrapped( - ConnectorArrowDatabase(SpiralDBConnector("p", "d", writable=given_writable)) + ConnectorArrowDatabase( + SpiralDBKeyedConnector("p", "d", writable=given_writable) + ) ) with pytest.raises(ValueError, match="bindings.database.*writable"): _ = PipelineJob.load(saved, database=given) @@ -769,7 +781,7 @@ def test_the_lease_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.""" overrides = {"server.url": "https://one.example"} - connector = SpiralDBConnector("p", "d", writable=True, overrides=overrides) + connector = SpiralDBKeyedConnector("p", "d", writable=True, overrides=overrides) key = connector._writer_lease_key() # pyright: ignore[reportPrivateUsage] overrides["server.url"] = "https://two.example" assert connector._writer_lease_key() == key # pyright: ignore[reportPrivateUsage] @@ -778,7 +790,7 @@ def test_the_lease_key_keeps_the_service_address_of_construction() -> None: 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()) + loaded = SpiralDBKeyedConnector.from_config(connector.to_config()) assert loaded._writer_lease_key() == key # pyright: ignore[reportPrivateUsage] @@ -790,9 +802,9 @@ def test_connectors_reaching_one_service_share_one_lease(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.""" - plain = SpiralDBConnector("p", "d", writable=True) - addressed = SpiralDBConnector("p", "d", {"server.url": given}, writable=True) - other = SpiralDBConnector( + plain = SpiralDBKeyedConnector("p", "d", writable=True) + addressed = SpiralDBKeyedConnector("p", "d", {"server.url": given}, writable=True) + other = SpiralDBKeyedConnector( "p", "d", {"server.url": "https://other.invalid"}, writable=True ) databases = [ConnectorArrowDatabase(c) for c in (plain, addressed, other)] @@ -815,7 +827,7 @@ def test_a_client_without_its_resolved_address_is_refused( takes the lease: no address is guessed, and no lease is taken.""" from types import SimpleNamespace - connector = SpiralDBConnector("p", "d", writable=True) + connector = SpiralDBKeyedConnector("p", "d", writable=True) client = connector._client # pyright: ignore[reportPrivateUsage] stand_in = ( SimpleNamespace() @@ -838,7 +850,7 @@ def test_a_write_through_another_connector_during_a_run_is_refused() -> None: @function_pod(output_keys="z") def write_elsewhere(x: int) -> int: - other = ConnectorArrowDatabase(SpiralDBConnector("p", "d", writable=True)) + other = ConnectorArrowDatabase(SpiralDBKeyedConnector("p", "d", writable=True)) row = pa.table( { "__data_context": pa.array(["std:v1:default"], pa.large_string()), @@ -893,7 +905,7 @@ def interrupt_first(client: Any, lease: Any) -> None: 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 = take_lease(SpiralDBKeyedConnector("p", "d", writable=True), "after") again() @@ -1003,7 +1015,7 @@ def test_a_job_on_a_shared_writable_connector_takes_the_lease_after_its_original monkeypatch.setattr( spiraldb_writable_registry, "_writable_connectors", weakref.WeakSet() ) - original = SpiralDBConnector("p", "d", writable=True) + original = SpiralDBKeyedConnector("p", "d", writable=True) shared = original.share_client() original.close() del original @@ -1021,9 +1033,9 @@ def test_a_job_on_a_writable_connector_and_its_shared_copy_runs( ) -> 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.""" - from orcapod.databases.spiraldb_tables import SpiralDBTables + from orcapod.databases.spiraldb_keyed.tables import SpiralDBTables - connector = SpiralDBConnector("p", "d", writable=True) + connector = SpiralDBKeyedConnector("p", "d", writable=True) spiral_db = ConnectorArrowDatabase(connector) shared = connector.share_client() results = ConnectorArrowDatabase(shared) @@ -1042,7 +1054,7 @@ def recording_hold(self: Any, check: Any) -> None: 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 = take_lease(SpiralDBKeyedConnector("p", "d", writable=True), "after") again() @@ -1054,7 +1066,7 @@ def test_an_interrupted_let_go_still_releases_every_lease( """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 + from orcapod.databases.spiraldb_keyed.tables import SpiralDBTables real = SpiralDBTables.let_go_of_lease interrupted: list[None] = [] @@ -1076,7 +1088,9 @@ def interrupt_first(self: Any, check: Any) -> None: 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 = take_lease( + SpiralDBKeyedConnector("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"): @@ -1111,8 +1125,8 @@ def test_a_decorator_result_database_on_a_database_is_leased(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 database (``pod_cache_database``) too.""" - on_spiral = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) - pod_cache = ConnectorArrowDatabase(SpiralDBConnector("p", "g", writable=True)) + on_spiral = ConnectorArrowDatabase(SpiralDBKeyedConnector("p", "f", writable=True)) + pod_cache = ConnectorArrowDatabase(SpiralDBKeyedConnector("p", "g", writable=True)) @function_pod( output_keys=("total",), @@ -1136,7 +1150,7 @@ 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 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) + connector = SpiralDBKeyedConnector("p", "d", writable=True) outside = ConnectorArrowDatabase(connector.share_client()) row = pa.table( { @@ -1160,7 +1174,7 @@ def test_a_bound_function_pod_stream_built_outside_the_job_is_leased( """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.""" - on_spiral = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) + on_spiral = ConnectorArrowDatabase(SpiralDBKeyedConnector("p", "f", writable=True)) def add(x: int, y: int) -> int: return x + y @@ -1198,7 +1212,7 @@ def test_a_load_only_run_over_an_outside_function_pod_stream_is_refused_not_busy """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).""" - on_spiral = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) + on_spiral = ConnectorArrowDatabase(SpiralDBKeyedConnector("p", "f", writable=True)) def add(x: int, y: int) -> int: return x + y @@ -1269,8 +1283,8 @@ def test_a_load_only_run_reading_an_outside_pod_through_a_live_wrapper_is_refuse (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).""" - on_pod = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) - cache = ConnectorArrowDatabase(SpiralDBConnector("p", "c", writable=True)) + on_pod = ConnectorArrowDatabase(SpiralDBKeyedConnector("p", "f", writable=True)) + cache = ConnectorArrowDatabase(SpiralDBKeyedConnector("p", "c", writable=True)) computed: list[int] = [] @@ -1334,7 +1348,7 @@ def test_an_interrupted_hold_is_let_go_of(monkeypatch: pytest.MonkeyPatch) -> No """An interruption once a lease 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 + from orcapod.databases.spiraldb_keyed.tables import SpiralDBTables real = SpiralDBTables.hold_lease interrupted: list[None] = [] @@ -1380,7 +1394,9 @@ def take_then_interrupt(*args: Any, **kwargs: Any) -> Any: pass monkeypatch.undo() for dataset in datasets: - _, release = take_lease(SpiralDBConnector("p", dataset, writable=True), "after") + _, release = take_lease( + SpiralDBKeyedConnector("p", dataset, writable=True), "after" + ) release() @@ -1413,7 +1429,9 @@ def fail_then_interrupt(client: Any, lease: Any) -> None: 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 = take_lease( + SpiralDBKeyedConnector("p", dataset, writable=True), "after" + ) release() @@ -1440,7 +1458,7 @@ 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 = take_lease(SpiralDBKeyedConnector("p", "e", writable=True), "after") release() @@ -1470,7 +1488,7 @@ def test_a_held_table_does_not_lease_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 pod is not called.""" - on_spiral = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) + on_spiral = ConnectorArrowDatabase(SpiralDBKeyedConnector("p", "f", writable=True)) called: list[int] = [] def add(x: int, y: int) -> int: @@ -1490,7 +1508,7 @@ def add(x: int, y: int) -> int: ) ) node = _twice_over(_held_table_over(behind)) - _, release = take_lease(SpiralDBConnector("p", "f", writable=True), "another") + _, release = take_lease(SpiralDBKeyedConnector("p", "f", writable=True), "another") try: _ = node.run() finally: @@ -1503,7 +1521,7 @@ def add(x: int, y: int) -> int: def test_a_cached_source_behind_a_held_table_is_still_leased() -> 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.""" - connector = SpiralDBConnector("p", "g", writable=True) + connector = SpiralDBKeyedConnector("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) diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index e8f08384d..bac786e00 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -49,7 +49,9 @@ PostgreSQLConnector, SQLiteConnector, ) -from orcapod.databases.delta_arrow_types import _is_recorded # pyright: ignore[reportPrivateUsage] +from orcapod.databases.delta_arrow_types import ( + _is_recorded, # pyright: ignore[reportPrivateUsage] +) from orcapod.databases.utils import identity_node from orcapod.utils.arrow_utils import normalize_to_large_types @@ -1108,8 +1110,8 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: The databases: `InMemoryArrowDatabase` (in-memory), `DeltaTableDatabase` (Delta), and `ConnectorArrowDatabase` over `SQLiteConnector` and `PostgreSQLConnector`. Orcapod reads -SpiralDB and writes it only as a writable SpiralDB database ([SpiralDB as a Job's -Database](../concepts/spiraldb-database.md)), not compared here. See [The +SpiralDB and writes it only as a writable SpiralDB database ([Keyed SpiralDB as a Job's +Database](../concepts/spiraldb-keyed-database.md)), not compared here. See [The database](../concepts/pipeline-job.md#the-database) for how a job uses one. Some refusals depend on the values or names as well as the type: diff --git a/tests/test_pipeline/loaded_job/test_load_connector_database.py b/tests/test_pipeline/loaded_job/test_load_connector_database.py index 4cdae3771..63a149a8f 100644 --- a/tests/test_pipeline/loaded_job/test_load_connector_database.py +++ b/tests/test_pipeline/loaded_job/test_load_connector_database.py @@ -26,14 +26,14 @@ ConnectorArrowDatabase, DeltaTableDatabase, PostgreSQLConnector, - SpiralDBConnector, + SpiralDBKeyedConnector, SQLiteConnector, ) from orcapod.pipeline.serialization import SOURCE_REGISTRY from orcapod.sources import ArrowTableSource from tests.test_databases import fake_spiral_sdk -KINDS = ("sqlite", "postgresql", "spiraldb") +KINDS = ("sqlite", "postgresql", "spiraldb_keyed") MARKER = "marker-in-dsn" @@ -52,7 +52,7 @@ def make(self, kind: str, name: str) -> ConnectorArrowDatabase: return ConnectorArrowDatabase( PostgreSQLConnector(f"postgresql://u:{MARKER}@h/{name}") ) - return ConnectorArrowDatabase(SpiralDBConnector(name)) + return ConnectorArrowDatabase(SpiralDBKeyedConnector(name)) @pytest.fixture @@ -151,6 +151,27 @@ def test_load_without_the_database_names_the_slot_and_what_to_pass( assert MARKER not in message +@pytest.mark.parametrize("slot", ["database", "result_database"]) +@pytest.mark.parametrize("supply_connector", [False, True]) +def test_load_refuses_the_retired_connector_type( + databases: Databases, tmp_path: Path, slot: str, supply_connector: bool +) -> None: + path = tmp_path / "job.json" + _save(path, database=databases.make("sqlite", "a")) + supplied = databases.make("spiraldb_keyed", "b") + data = json.loads(path.read_text()) + config = supplied.to_config() + config["connector"]["connector_type"] = "spiraldb" + data["bindings"][slot] = config + path.write_text(json.dumps(data)) + + given = {slot: supplied} if supply_connector else {} + with pytest.raises( + ValueError, match=rf"bindings\.{slot}: .*'spiraldb'.*'spiraldb_keyed'" + ): + PipelineJob.load(path, **given) + + def test_legacy_connector_dsn_is_ignored_when_the_database_is_supplied( databases: Databases, tmp_path: Path ) -> None: diff --git a/tests/test_pipeline/test_observer_databases.py b/tests/test_pipeline/test_observer_databases.py index 508189494..acd055784 100644 --- a/tests/test_pipeline/test_observer_databases.py +++ b/tests/test_pipeline/test_observer_databases.py @@ -17,7 +17,7 @@ ExtensionAwareDatabase, InMemoryArrowDatabase, NoOpArrowDatabase, - SpiralDBConnector, + SpiralDBKeyedConnector, SQLiteConnector, ) from orcapod.errors import SpiralDBObserverNotSupportedError @@ -40,7 +40,7 @@ class _DerivedExtensionWrapper(ExtensionAwareDatabase): """An extension wrapper subclass must be unwrapped too.""" -class _DerivedSpiralConnector(SpiralDBConnector): +class _DerivedSpiralConnector(SpiralDBKeyedConnector): """A SpiralDB connector subclass still uses the same database.""" @@ -83,11 +83,11 @@ def __getattribute__(self, name: str) -> object: @pytest.fixture -def spiral_connector(tmp_path: Path) -> Iterator[SpiralDBConnector]: +def spiral_connector(tmp_path: Path) -> Iterator[SpiralDBKeyedConnector]: """Open a real connector backed by the fake SpiralDB SDK.""" with ( fake_spiral_sdk.install(tmp_path / "spiral"), - SpiralDBConnector("p") as connector, + SpiralDBKeyedConnector("p") as connector, ): yield connector @@ -101,7 +101,7 @@ def capture_install() -> Iterator[Mock]: @pytest.fixture(params=["wrapper-slot", "connector-slot"]) def slotted_spiral_database( - request: pytest.FixtureRequest, spiral_connector: SpiralDBConnector + request: pytest.FixtureRequest, spiral_connector: SpiralDBKeyedConnector ) -> ArrowDatabaseProtocol: """Build a SpiralDB database with one of the inspected references in a slot.""" if cast(str, request.param) == "wrapper-slot": @@ -151,7 +151,7 @@ def database_view( @pytest.mark.parametrize("observer_class", _OBSERVERS) def test_spiral_database_is_refused_at_setup( observer_class: type[StatusObserver] | type[LoggingObserver], - spiral_connector: SpiralDBConnector, + spiral_connector: SpiralDBKeyedConnector, database_view: Callable[[ArrowDatabaseProtocol], ArrowDatabaseProtocol], capture_install: Mock, ) -> None: @@ -287,7 +287,7 @@ def test_wrapper_without_stored_database_is_accepted( def test_composite_refusal_does_not_install_capture( logging_first: bool, nested: bool, - spiral_connector: SpiralDBConnector, + spiral_connector: SpiralDBKeyedConnector, monkeypatch: pytest.MonkeyPatch, capture_install: Mock, ) -> None: @@ -325,7 +325,7 @@ def resolve( @pytest.mark.parametrize("observer_class", _OBSERVERS) def test_spiral_database_resolved_from_config_is_refused( observer_class: type[StatusObserver] | type[LoggingObserver], - spiral_connector: SpiralDBConnector, + spiral_connector: SpiralDBKeyedConnector, monkeypatch: pytest.MonkeyPatch, capture_install: Mock, ) -> None: @@ -378,7 +378,7 @@ def test_every_database_class_exported_from_orcapod_databases_is_classified() -> "ExtensionAwareDatabase", "ConnectorArrowDatabase", # Connectors: SpiralDB is refused; SQLite and PostgreSQL pass. - "SpiralDBConnector", + "SpiralDBKeyedConnector", "SQLiteConnector", "PostgreSQLConnector", } From 1c70cbeaeafc27bc10e343177bbdc4f8e2b1b35a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 02:13:33 -0800 Subject: [PATCH 21/46] refactor(spiraldb): replace keyed writer leases with write scopes --- scripts/migrate_spiral_schemas.py | 12 +- src/orcapod/core/nodes/function_node.py | 30 +- src/orcapod/core/nodes/operator_node.py | 11 +- src/orcapod/core/nodes/source_node.py | 10 +- src/orcapod/core/pod_result_databases.py | 4 +- src/orcapod/databases/__init__.py | 3 + .../databases/connector_arrow_database.py | 42 +- .../databases/extension_aware_database.py | 8 +- src/orcapod/databases/spiraldb_connector.py | 134 +-- src/orcapod/databases/spiraldb_lease.py | 679 ----------- src/orcapod/databases/spiraldb_tables.py | 387 +++--- .../databases/spiraldb_writable_registry.py | 2 +- src/orcapod/databases/spiraldb_write_scope.py | 525 ++++---- src/orcapod/databases/store_table_names.py | 22 - src/orcapod/databases/write_lock.py | 38 + src/orcapod/errors.py | 11 +- src/orcapod/pipeline/job.py | 54 +- src/orcapod/pipeline/node_run.py | 35 +- src/orcapod/protocols/spiraldb_run.py | 7 +- src/orcapod/side_effects.py | 17 +- tests/test_databases/fake_spiral_sdk.py | 25 - .../test_migrate_spiral_schemas.py | 20 +- tests/test_databases/test_spiral_lease.py | 1054 ----------------- .../test_spiraldb_lazy_lease.py | 826 ------------- .../test_spiraldb_round_trips.py | 68 +- .../test_spiraldb_writable_mode.py | 187 ++- .../test_spiraldb_writable_runs.py | 661 ++--------- .../test_spiraldb_write_lock.py | 509 ++++++++ 28 files changed, 1349 insertions(+), 4032 deletions(-) delete mode 100644 src/orcapod/databases/spiraldb_lease.py create mode 100644 src/orcapod/databases/write_lock.py delete mode 100644 tests/test_databases/test_spiral_lease.py delete mode 100644 tests/test_databases/test_spiraldb_lazy_lease.py create mode 100644 tests/test_databases/test_spiraldb_write_lock.py diff --git a/scripts/migrate_spiral_schemas.py b/scripts/migrate_spiral_schemas.py index 3d58723d5..e32f4f70c 100644 --- a/scripts/migrate_spiral_schemas.py +++ b/scripts/migrate_spiral_schemas.py @@ -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,12 @@ 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 = sorted( + name + for name in listed.values() + if name != SCHEMA_TABLE and LEASE_TABLE_PATTERN.fullmatch(name) is None + ) planned = sorted(row.table_name for row in rows) if names != planned: raise MigrationError( diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 7a1db19c2..3a8adaad9 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -391,9 +391,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]) @@ -1627,10 +1626,9 @@ def _begin_run(self) -> None: self._current_tables_checked = False self._account_for_stale_tables() - def _claim_writer_leases(self) -> None: - """Claim the run's writer leases of the writable SpiralDB databases this node - writes, before its function is called for a row it does not hold (ITL-1900); - a later claim only verifies the lease once.""" + def _acquire_write_locks(self) -> None: + """Acquire the run's write locks before calling a context-taking function + for an uncached row.""" databases = [self._pipeline_database] databases.extend( pod.result_database @@ -1642,7 +1640,7 @@ def _claim_writer_leases(self) -> None: databases.extend(pod_result_databases(self)) for database in databases: if isinstance(database, SpiralDBRunLookupProtocol): - database.spiral_claim_writer_lease() + database.spiral_acquire_write_lock() def _refresh_stored_tables(self) -> None: """Read this node's stored tables from the store's current version (ITL-1408). @@ -3051,10 +3049,8 @@ def _process_data_internal( return self._empty_data_cache_hit(tag, data, instance_id) if self._delivers_side_effects: - # Before the function can be called (ITL-1900): the claim is refused if - # another writer wrote since the run observed the dataset, so what the - # run read to decide this call is still what the store holds. - self._claim_writer_leases() + # Acquire the write lock before the function can be called. + self._acquire_write_locks() self._preflight_pipeline_write_schema() ephemeral_result = bool(self._node_config.is_result_ephemeral) @@ -3201,10 +3197,8 @@ async def _async_process_data_internal( return self._empty_data_cache_hit(tag, data, instance_id) if self._delivers_side_effects: - # Before the function can be called (ITL-1900): the claim is refused if - # another writer wrote since the run observed the dataset, so what the - # run read to decide this call is still what the store holds. - self._claim_writer_leases() + # Acquire the write lock before the function can be called. + self._acquire_write_locks() self._preflight_pipeline_write_schema() ephemeral_result = bool(self._node_config.is_result_ephemeral) @@ -4957,8 +4951,8 @@ async def route_inputs() -> None: continue if self._delivers_side_effects: # Before the function can be called for the - # row (ITL-1900), as on the sync path. - self._claim_writer_leases() + # row, as on the sync path. + self._acquire_write_locks() # The function takes the row without its # fall-through columns (ITL-1023). await compute_channel.writer.send( diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 2e181370b..d173d2f82 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -2093,17 +2093,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 559623394..b85c8f2b3 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 @@ -1904,7 +1905,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: @@ -2749,11 +2750,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(): diff --git a/src/orcapod/core/pod_result_databases.py b/src/orcapod/core/pod_result_databases.py index 7851254ed..1afec9ca8 100644 --- a/src/orcapod/core/pod_result_databases.py +++ b/src/orcapod/core/pod_result_databases.py @@ -1,7 +1,7 @@ """The result databases a function node's own pods write on a cache miss. A leaf module, read by the run's write scope (``pipeline.node_run``) and by a function -node that claims its writer leases before its function is called (ITL-1900). +node that acquires its write locks before its function is called. """ from __future__ import annotations @@ -16,7 +16,7 @@ def pod_result_databases(node: Any) -> list[Any]: # pyright: ignore[reportExpli (``@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. + database (``_databases``); not committed at the end of a run, only included in the write scope. """ found: list[Any] = [] pods: list[Any] = [ diff --git a/src/orcapod/databases/__init__.py b/src/orcapod/databases/__init__.py index ce7cfbdb2..927505060 100644 --- a/src/orcapod/databases/__init__.py +++ b/src/orcapod/databases/__init__.py @@ -6,6 +6,7 @@ from .postgresql_connector import PostgreSQLConnector from .spiraldb_connector import SpiralDBConnector from .sqlite_connector import SQLiteConnector +from .write_lock import NoWriteLock, WriteLock __all__ = [ "ConnectorArrowDatabase", @@ -14,6 +15,8 @@ "InMemoryArrowDatabase", "NoOpArrowDatabase", "SpiralDBConnector", + "NoWriteLock", + "WriteLock", "SQLiteConnector", "PostgreSQLConnector", ] diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 73ad7e01c..e142e8216 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. @@ -1201,7 +1219,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): @@ -1216,12 +1234,12 @@ 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_result_batch_in_order( self, record_path: tuple[str, ...], *, publish_records: bool ) -> None: @@ -1463,7 +1481,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) elif self._sql_store is None: self._connector.create_table_if_not_exists( @@ -1522,12 +1540,10 @@ def spiral_records_match_context( pending is None or tables.data_context(pending) == current ) - def spiral_claim_writer_lease(self) -> None: - """Claim the writer lease the run attached to this writable SpiralDB database - now, as its first write would (ITL-1900); nothing for another database or - without an attached lease.""" + 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.claim_lease() + tables.acquire_write_lock() def spiral_completion_lookup( self, record_path: tuple[str, ...] @@ -1535,10 +1551,10 @@ def spiral_completion_lookup( """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 09777caaa..ba1846c64 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -103,10 +103,10 @@ def spiral_completion_lookup( return self._db.spiral_completion_lookup(record_path) return None - def spiral_claim_writer_lease(self) -> None: - """Delegate the claim when the wrapped store supports it.""" + 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_claim_writer_lease() + self._db.spiral_acquire_write_lock() def get_record_by_id( self, @@ -375,7 +375,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 872778af4..8db8ae6d6 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, @@ -554,7 +554,7 @@ def _service_address(client: Any) -> str: def _list_dataset(client: Any, project_id: str, dataset: str) -> dict[str, str]: - """Return every keyed table name of a dataset by ID, writer lease generations too. + """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 @@ -594,48 +594,6 @@ def _list_dataset(client: Any, project_id: str, dataset: str) -> dict[str, str]: token = following -def _list_keyed_tables(client: Any, project_id: str, dataset: str) -> dict[str, str]: - """Return keyed table names by ID, omitting writer lease generations. - - Args: - client: A spiral-sdk client. - project_id: The project. - dataset: The dataset; matched exactly by the service. - """ - return { - table_id: name - for table_id, name in _list_dataset(client, project_id, dataset).items() - if not is_spiral_lease_table_name(name) - } - - -def _list_dataset_for_lease( - client: Any, project_id: str, dataset: str -) -> dict[str, str]: - """Return every table name of the dataset by ID, lease generations included, as - the writer lease lists it. - - Args: - client: A spiral-sdk client. - project_id: The project. - dataset: The dataset. - """ - with _service_call(f"list the writer lease generations of {project_id}/{dataset}"): - return _list_dataset(client, project_id, dataset) - - -def _list_lease_generations(client: Any, project_id: str, dataset: str) -> set[str]: - """Return the names of the writer lease generations a listing of the dataset shows. - - Args: - client: A spiral-sdk client. - project_id: The project. - dataset: The dataset. - """ - listed = _list_dataset_for_lease(client, project_id, dataset) - return {name for name in listed.values() if is_spiral_lease_table_name(name)} - - def _literal(value: Any, arrow_type: pa.DataType) -> Any: """Return ``value`` as a scan literal of exactly ``arrow_type`` (the service refuses another type), or ``None`` when the SDK has no literal that filters as Orcapod does. @@ -1088,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__( @@ -1102,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 @@ -1135,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, @@ -1156,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: one_call_scope(connector), ) + @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: @@ -1179,27 +1162,31 @@ 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. + RuntimeError: If this connector is closed or its client does not expose + its resolved address. """ + self._require_open() 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. + def _list_tables_for_scope(self) -> dict[str, str]: + """List the dataset's tables (names by table id) once, for a write scope's + catalog (``spiraldb_write_scope``). Raises: RuntimeError: If this connector has been closed. """ self._require_open() - return (self._client, self._project_id, self._dataset) + project_id, dataset = self._project_id, self._dataset + with _service_call(f"list the tables of {project_id}/{dataset}", self._health): + return _list_dataset(self._client, project_id, dataset) def _refuse_if_writable(self) -> None: """Refuse an operation on raw tables of a writable connector.""" @@ -1212,10 +1199,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) @@ -1239,13 +1225,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: @@ -1257,16 +1241,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)), @@ -1286,7 +1266,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 33636d6d9..000000000 --- a/src/orcapod/databases/spiraldb_lease.py +++ /dev/null @@ -1,679 +0,0 @@ -"""Internal one-writer leases for writable SpiralDB databases. - -Generation discovery requires a contiguous sequence: one listing of the dataset gives -where it ends, confirmed by opening that generation and the next ones by name. 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, field -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, - is_spiral_lease_table_name, - 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.""" - ... - - @property - def version_id(self) -> object: - """Return the snapshot's version.""" - ... - - 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}" - ) - - -class LeaseChangedError(LeaseBusyError): - """Another writer took the dataset's writer lease while a run read the dataset. - - A run reads before it claims the lease, at its first write (ITL-1900): it observed - the newest lease generation when it started (``observe``) and claims only if no - writer took or released a lease since, so nothing it read of this dataset can have - changed. The write is refused, with nothing written to the dataset by it, and the - run is run again. - - Attributes: - table_id: Immutable ID of the newest generation found at the claim (``""`` - when the dataset has none). - """ - - def __init__(self, project_id: str, dataset: str, table_id: str) -> None: - """Explain that the dataset changed during the run and how to proceed. - - Args: - project_id: Project containing the dataset. - dataset: Dataset where the claim was refused. - table_id: Immutable ID of the newest generation found. - """ - self.table_id = table_id - LeaseError.__init__( - self, - f"The writer lease of SpiralDB dataset {project_id}/{dataset} changed " - "since this run started reading it: another writer took the lease and may " - "have written the dataset, so what the run read may be out of date. This " - "write was refused and wrote nothing to the dataset (rows the run wrote to " - "other datasets stay stored). Run again.", - ) - - -@dataclass(frozen=True) -class Observed: - """The newest writer lease generation of a dataset as a run found it when it - started (``observe``). - - Attributes: - generation: The newest generation's number, 0 when there is none. - version: The version of its latest snapshot then; ``None`` without one. - tables: The dataset's other tables, names by table id, as the listing the - observation made showed them: the run's first view of the dataset; - ``None`` when the listing failed and the generation was found by name. - """ - - generation: int - version: str | None - tables: dict[str, str] | None = field(default=None, compare=False) - - -@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, listed: set[str] | None = None -) -> tuple[int, _KeyedTable | None]: - """Return the end of the contiguous generation sequence and its latest snapshot. - - One listing of the dataset gives a starting point: the end of the run of listed - generations from 1. That generation is opened by name, and the next ones are opened - by name while they exist, so a listing that lags the service still ends at the - newest generation. A listed generation that does not open falls back to the search - by name alone (``_search``). ``listed``, when given, holds the generation names of - a listing the caller just made. - """ - if listed is None: - listed = sdk._list_lease_generations(client, project_id, dataset) - start = 0 - while spiral_lease_table_name(start + 1) in listed: - start += 1 - newest = None - if start > 0: - newest = _open(client, project_id, dataset, start) - if newest is None: - return _search(client, project_id, dataset) - while (table := _open(client, project_id, dataset, start + 1)) is not None: - start, newest = start + 1, table - return start, newest - - -def _search( - client: _Client, project_id: str, dataset: str -) -> tuple[int, _KeyedTable | None]: - """Bracket the end of the contiguous generation sequence by name, 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 observe(client: _Client, project_id: str, dataset: str) -> Observed: - """Find the newest writer lease generation of a dataset and its snapshot version, - without reading its state: a run that claims later gives it to ``acquire``. - - Args: - client: SDK client used for the lease. - project_id: Project containing the dataset. - dataset: The dataset. - - Returns: - What was found, with the dataset's other tables from the same listing. A - listing that fails leaves the generation to the search by name alone, with no - tables: the observation only finds where the claim starts, and the claim's - exclusive create and verification are the same either way. - """ - try: - listing = sdk._list_dataset_for_lease(client, project_id, dataset) - except Exception: # noqa: BLE001 # any listing failure: the name search remains - generation, latest = _search(client, project_id, dataset) - return Observed(generation, None if latest is None else str(latest.version_id)) - generations = {n for n in listing.values() if is_spiral_lease_table_name(n)} - generation, latest = _newest(client, project_id, dataset, generations) - return Observed( - generation, - None if latest is None else str(latest.version_id), - {i: n for i, n in listing.items() if not is_spiral_lease_table_name(n)}, - ) - - -def _observed_still_newest( - client: _Client, project_id: str, dataset: str, expected: Observed -) -> tuple[bool, _KeyedTable | None]: - """Whether the observed generation is still the newest, at the observed version, - with its snapshot now: opened by name, and the next generation probed by name - (no listing). A newer generation is a change, whatever else.""" - latest = None - if expected.generation > 0: - latest = _open(client, project_id, dataset, expected.generation) - if latest is None or str(latest.version_id) != expected.version: - return False, latest - elif expected.version is not None: - return False, None - if _open(client, project_id, dataset, expected.generation + 1) is not None: - return False, latest - return True, latest - - -def acquire( - client: _Client, - project_id: str, - dataset: str, - *, - owner: str, - on_claim: Callable[[Lease], None] | None = None, - expected: Observed | 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. - expected: Optional: the newest generation as the caller observed it before it - read the dataset (``observe``). If another generation is the newest now, - or the same one at another snapshot version (its writer released it, or a - writer took the lease meanwhile), nothing is claimed. - - Returns: - The verified lease for this process. - - Raises: - LeaseChangedError: If ``expected`` is not what the dataset's newest - generation is now. - LeaseBusyError: If another claim prevents acquisition. - LeaseError: If the claim or its state cannot be verified. - TimeoutError: If the generation lookup before the claim (a listing of the - dataset and opens by name), 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. - """ - if expected is None: - generation, latest = _newest(client, project_id, dataset) - else: - # From the observed generation, without listing again: a newer generation, or - # a newer snapshot of it, means another writer took a lease since. - unchanged, latest = _observed_still_newest( - client, project_id, dataset, expected - ) - if not unchanged: - raise LeaseChangedError( - project_id, dataset, "" if latest is None else latest.resource_id - ) - generation = expected.generation - 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 e0f0fe912..780e1bc47 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -6,7 +6,7 @@ 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. Under a writer lease, a name the run's listing of + 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``): @@ -28,19 +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, unless this write's own exclusive create made the table. +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. -Under the lease nothing but the run writes the dataset, so what the run read is kept for -the run and shared by its connectors (``WriterLease``, ITL-1899): what each table holding +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 run's lease ends. +forgotten when the scope ends. """ from __future__ import annotations @@ -49,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 @@ -59,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, @@ -109,48 +111,54 @@ def shows_absent(self, table_name: str) -> bool: KEPT_ROWS_BUDGET_BYTES = 256 * 1024 * 1024 -"""The most bytes (``pa.Table.nbytes``) of whole reads a run keeps under its lease -(ITL-1899): a read that does not fit is not kept, and the oldest kept reads are dropped +"""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.""" -@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. +active_run_states: ContextVar[frozenset[RunState]] = ContextVar( + "spiraldb_active_run_states", default=frozenset() +) +"""The write scopes visible to work in the current execution context.""" + - 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. +@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. 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 when the run started (the writer - lease's observation) or at its first listing, 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, taken when the scope opened (or at its first + listing), and updated by every committed append; a failed append lists + its table unjudged, since it may hold rows; ``None`` until then. 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 run's connectors (a table's key, record and manifest never change once + 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) table_ids: dict[str, str | None] = field(default_factory=dict) @@ -160,23 +168,20 @@ class WriterLease: found_by_id: dict[str, _Found] = field(default_factory=dict) ids_by_name: dict[str, str] = field(default_factory=dict) - def __call__(self) -> None: - """Verify the writer lease on first use.""" - self.verify() - def start_catalog(self, names: dict[str, str]) -> None: """Take a listing of the dataset's tables (names by table id), made when the - run started, as the run's catalog (ITL-1899).""" + scope opened, as its catalog (ITL-1899).""" with self.lock: self.catalog = _Catalog(dict(names)) def forget_reads(self) -> None: - """Forget everything the run read (``WriterLease`` attributes): the key index, + """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.commits = 0 self.rows_by_table.clear() self.found_by_id.clear() self.ids_by_name.clear() @@ -258,7 +263,7 @@ class _Opened: class _LazySnapshot: """A table resolved to its id, opened by id at its first use (ITL-1899). - Used under a writer lease for a table that holds rows and whose record is known: + 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. @@ -354,6 +359,8 @@ class SpiralDBTables: 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 of these tables alone, for a write outside a + run (``spiraldb_write_scope``). """ def __init__( @@ -366,6 +373,7 @@ def __init__( create_table: Callable[[str, pa.Schema], _KeyedTable], list_tables: Callable[[], dict[str, str]], service_call: Callable[[str], AbstractContextManager[None]], + one_call_scope: Callable[[], AbstractContextManager[None]], ) -> None: self._sdk: Any = sdk # pyright: ignore[reportExplicitAny] self._project_id: str = project_id @@ -375,6 +383,10 @@ def __init__( 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[[], 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 @@ -389,9 +401,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.""" @@ -573,25 +585,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 ────────────────────────────────────────────────────── @@ -630,9 +642,9 @@ def _judgment(self, table_name: str) -> _Judgment: judged = 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 # 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: @@ -652,12 +664,12 @@ def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Judgment: Returns: The judgment. """ - lease = self._lease_check + run = self._run_state resolved = self._resolved_id(table_name) - if lease is not None and resolved is not None: + if run is not None and resolved is not None: known = self._known(resolved) if known is not None and known.record.path == path: - # Under the lease nothing but the run writes it: opened when used. + # 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: @@ -668,7 +680,7 @@ def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Judgment: self._resolve(table_name, table_id) return _Opened(known, table) _require_key(table, self._service_call) - catalog = None if lease is None else lease.catalog + 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. @@ -700,42 +712,42 @@ def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Judgment: 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) - lease = self._lease_check - if table_id is None and lease is not None: - table_id = lease.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 (lease := self._lease_check) is not None: - lease.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) - lease = self._lease_check - if known is None and lease is not None: - known = lease.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 (lease := self._lease_check) is not None: - lease.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 (lease := self._lease_check) is not None: - _ = lease.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.""" - lease = self._lease_check - catalog = None if lease is None else lease.catalog + 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: @@ -791,16 +803,16 @@ 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 + if run.catalog is None: + run.catalog = _Catalog(self._list_dataset()) + catalog = run.catalog self._collect_paths(catalog, start, prefix, found) return sorted(found) @@ -962,8 +974,8 @@ def scan(self, table_name: str) -> Iterator[pa.RecordBatch]: Args: table_name: A name ``table_name`` returned. - Under a writer lease the rows a read returned are kept for the run and read - from there again, until an append to the table starts (``WriterLease``, + 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. @@ -977,15 +989,15 @@ 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) - lease = self._lease_check + run = self._run_state stored = None - if lease is not None: - with lease.lock: - stored = lease.rows_by_table.get(found.table_id) + 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 lease is not None: + if run is not None: self._keep_read(table_name, found.table_id, stored) if stored.num_rows == 0: return @@ -1001,14 +1013,14 @@ def _keep_read(self, table_name: str, table_id: str, stored: pa.Table) -> None: table_id: The table's id. stored: The rows, as the service returned them. """ - lease = self._lease_check - assert lease is not None - with lease.lock: + 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 = lease.rows_by_table + 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): @@ -1016,8 +1028,8 @@ def _keep_read(self, table_name: str, table_id: str, stored: pa.Table) -> None: break total -= kept.pop(oldest).nbytes kept[table_id] = stored - if table_id not in lease.keys_by_table: - lease.keys_by_table[table_id] = _keys_of(stored) + if table_id not in run.keys_by_table: + run.keys_by_table[table_id] = _keys_of(stored) def existing_record_ids( self, table_name: str, ids: Collection[bytes] @@ -1040,9 +1052,9 @@ 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() @@ -1057,12 +1069,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: @@ -1070,29 +1082,29 @@ 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) + held = run.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 + run.keys_by_table[table_id] = held return record_id in held def _held_ids( @@ -1100,33 +1112,33 @@ def _held_ids( ) -> 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 + 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 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) + with run.lock: + held = run.keys_by_table.get(table_id) if held is None: - # The lease-wide index is filled from a snapshot opened now, under + # The run-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 + run.keys_by_table[table_id] = held return held.intersection(ids) def _scan_keys(self, table: _KeyedTable) -> set[bytes]: @@ -1137,75 +1149,55 @@ def _scan_keys(self, table: _KeyedTable) -> set[bytes]: # ── 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 - Args: - check: Verifies the lease at its first use; raises if it is not held. + @contextmanager + def write_scope(self) -> 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(): + yield - Raises: - RuntimeError: If a lease is held for these tables already. - """ - if self._lease_check is not None: - raise RuntimeError( - "these database tables are already written under a lease" - ) - self._lease_check = check + def attach_run(self, state: RunState) -> None: + """Write these tables in a scope (``spiraldb_write_scope``). - def claim_lease(self) -> None: - """Claim the attached writer lease now, as a first write would (ITL-1900); - nothing when no lease is attached. + Args: + state: The scope's state of this dataset. Raises: - LeaseBusyError: If another writer holds the dataset. - LeaseError: If the lease cannot be claimed or verified. + RuntimeError: If these tables are in a scope already. """ - if (check := self._lease_check) is not None: - check() + if self._attached_run is not None: + raise RuntimeError("these database tables are already in a write scope") + self._attached_run = state - def let_go_of_lease(self, check: WriterLease) -> None: - """Stop writing under the lease ``hold_lease`` was given ``check`` for. + def acquire_write_lock(self) -> None: + """Acquire the scope's write lock now, as a first write would; nothing outside + a scope or once acquired. - Args: - check: The check given to ``hold_lease``; any other leaves the lease held. """ - if self._lease_check is check: - self._lease_check = None - - def _require_lease(self) -> WriterLease: - """Require an attached writer lease; it is claimed by the write's first create - or append (``_claim``), so a write that sends nothing claims nothing - (ITL-1900). + if (state := self._run_state) is not None: + state.acquire_lock() - 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 detach_run(self, state: RunState) -> None: + """Leave the scope ``attach_run`` was given ``state`` for. - Raises: - SpiralDBLeaseRequiredError: If no run holds the lease. + Args: + state: The state given to ``attach_run``; any other is left attached. """ - 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" - ) - return check - - def _claim(self) -> None: - """Claim the attached lease, or verify it, before a create or an append. + if self._attached_run is state: + self._attached_run = None - Raises: - LeaseBusyError: If another writer holds the dataset, or wrote it since the - run observed it (``LeaseChangedError``); nothing is written. - LeaseError: If the lease is no longer held (``spiraldb_lease.check``). - """ - check = self._lease_check - assert check is not None # required by ``write`` before - check() + 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() def _create_or_open(self, table_name: str) -> tuple[_KeyedTable, bool]: """The table at a computed name, created now if absent. @@ -1247,10 +1239,10 @@ def _create_or_open(self, table_name: str) -> tuple[_KeyedTable, bool]: 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.""" - lease = self._lease_check - if lease is not None and lease.catalog is not None: - with lease.lock: - lease.catalog.add(table_id, table_name) + 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, @@ -1267,7 +1259,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. @@ -1331,9 +1323,9 @@ def _require_same_manifest( def write(self, table_name: str, records: pa.Table) -> 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 @@ -1352,17 +1344,18 @@ def write(self, table_name: str, records: pa.Table) -> None: 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) - # One writer per dataset (ITL-1844): the lease is required now and claimed - # by the first create or append (ITL-1900). - lease = self._require_lease() - with lease.lock: - self._write(table_name, path, context, records) + with self.write_scope(): + run = self._run_state + assert run is not None + with run.lock: + self._write(table_name, path, context, records) def _write( self, @@ -1371,7 +1364,7 @@ def _write( context: str, records: pa.Table, ) -> 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) @@ -1406,8 +1399,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, and claims nothing - self._claim() + 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) @@ -1439,8 +1432,8 @@ def _write_first( } encoded = _encoded(records) if encoded.num_rows == 0: - return # nothing to write, so nothing is created or claimed - self._claim() + return # nothing to write, so nothing is created or locked + self._acquire_lock() self._forget_opened(table_name) table, created = self._create_or_open(table_name) if created and seen == ("none", None) and seen_record is None: @@ -1485,24 +1478,24 @@ def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: found: What it records. encoded: The rows, encoded. """ - 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())) # The rows a read kept no longer are the table's, whatever the append does. - _ = lease.rows_by_table.pop(found.table_id, None) - lease.commits += 1 # odd while the append is in flight + _ = 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._forget(found.table_id) - _ = 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: + _ = 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. @@ -1511,11 +1504,11 @@ def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: ) 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 + run.commits += 1 + run.keys_by_table.setdefault(found.table_id, set()).update(_ids(encoded)) + run.table_ids[identity.spiral_table_name(found.record.path)] = found.table_id self._remember(found) - if (catalog := lease.catalog) is not None: + 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) 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 aae172022..69ce9e34b 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -1,49 +1,52 @@ -"""The writer leases a job run holds on the writable SpiralDB databases it writes -(ITL-1844, ITL-1900). - -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 a writable dataset it may write (``database_writes``) lazily, -at its first write to the dataset, and releases it when the run ends, also when it -fails. A run that writes nothing takes no lease. - -Before it checks a source or reads anything, the run observes the dataset's newest lease -generation (``spiraldb_lease.observe``: one listing, possibly paged, an open of the -newest listed generation and a probe of the next; no state read). The listing is also -the run's catalog of the dataset's tables. At its -first write it claims the lease only if that generation is still the newest, at the same -snapshot version: otherwise another writer took or released a lease while the run read -the dataset, and the run is refused with nothing written -(``spiraldb_lease.LeaseChangedError``). So what a run read of a dataset is what it -would have read holding that dataset's lease from its start. The check is per dataset: a -refused claim does not undo writes the run made to another dataset. A second writer is refused at its -first write (``LeaseBusyError``), before anything is written; it may compute before. A -node that delivers side effects reads its log without the lease and claims it just -before its first delivery (``SpiralDBRunLookupProtocol.spiral_claim_writer_lease``): -the claim's check of the observed generation is what makes that read current, so no -delivery follows a read another writer has made out of date. 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 when the scope opens) 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: two would each hold their own key +index, and could store one key twice with no other writer involved. A second scope of a +dataset that is open raises ``SpiralDBScopeOpenError`` before it can read or write +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 os import threading -import time -from collections.abc import Callable, Iterable, Iterator -from typing import TYPE_CHECKING, Any +from collections.abc import Iterable, Iterator +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 if TYPE_CHECKING: from orcapod.databases.spiraldb_connector import SpiralDBConnector + from orcapod.databases.spiraldb_tables import SpiralDBTables + +_open_scopes: set[tuple[str, str]] = set() +"""The (project, dataset) pairs reserved by open scopes in this process.""" + +_open_scopes_lock = threading.Lock() def writable_connectors(databases: Iterable[object]) -> list[SpiralDBConnector]: @@ -61,343 +64,247 @@ 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 -RECENTLY_VERIFIED_SECONDS = 60.0 -"""A lease verified this many seconds ago or less recently is verified again before the -first write after its acquisition; one verified more recently is not (ITL-1901).""" - -_clock: Callable[[], float] = time.monotonic -"""The clock the time since a lease's verification is read from (tests replace it).""" - - -def _verify_unless_recent( - client: Any, lease: spiraldb_lease.Lease, verified_at: float -) -> bool: # pyright: ignore[reportExplicitAny] # the SDK client - """Verify ``lease`` before a write, unless its acquisition verified it within - ``RECENTLY_VERIFIED_SECONDS``. +@contextlib.contextmanager +def database_writes(databases: 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 when its scope opens (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. - Interim (ITL-1901): the acquisition verifies the claim, so a second read of the - lease state moments later finds what it found, and costs a service call. A longer - gap verifies again, as every first write did before. + Args: + databases: The databases the run may write. Nothing happens when none is a + writable SpiralDB database. - Returns: - Whether it verified now: until it has, every later write asks again, so a - write made 60 seconds or more after the acquisition (after a side-effect - node's claim and a long delivery) still verifies once. + Raises: + 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. """ - if _clock() - verified_at < RECENTLY_VERIFIED_SECONDS: - return False - spiraldb_lease.check(client, lease) - return True + with _connector_scopes(writable_connectors(databases)): + yield @contextlib.contextmanager -def database_writes(databases: Iterable[object], *, owner: str) -> Iterator[None]: - """Hold the writer lease of every writable SpiralDB database dataset among - ``databases`` from the body's first write to each dataset (ITL-1900). - - On entry, each dataset's newest lease generation is observed (one listing, possibly - paged, an open of the newest listed generation and a probe of the next; nothing is - read from the lease). A dataset's lease is acquired at the body's - first write to it (a create or an append; a side-effect node's claim before its - first delivery), only if the generation and its snapshot version are still those - observed: otherwise ``LeaseChangedError``, since another writer may have written - what the body read. A body that writes nothing acquires nothing. Each acquired 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. A body that failed because a claim was refused raises that - refusal, whichever error wrapped it on the way (a node's commit), with a note - naming that error. +def one_call_scope(connector: SpiralDBConnector) -> Iterator[None]: + """A write scope of one connector's dataset for one call outside a run: attached + to that connector only, its lock acquired at the call's first write and released + after, and nothing it read kept past the call. 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. + connector: A writable SpiralDB connector. Raises: - LeaseBusyError: If another writer holds a dataset at the body's first write to - it, or wrote it since the observation (``LeaseChangedError``); nothing was - written by that write. - 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). - Exception: As ``spiraldb_lease.observe``, if an observation fails; nothing of - the body ran. + SpiralDBScopeOpenError: If a scope of the dataset is open in this process. + Exception: Whatever its ``WriteLock`` raises, unchanged. """ + with _connector_scopes([connector]): + yield + + +@contextlib.contextmanager +def _connector_scopes(writable: list[SpiralDBConnector]) -> Iterator[None]: + """``database_writes`` over writable connectors.""" 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 - lazies: list[_LazyLease] = [] + for connector in writable: + groups.setdefault(connector._write_scope_key(), []).append(connector) # pyright: ignore[reportPrivateUsage] # scopes are opened by this module only + scopes: list[_DatasetScope] = [] 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 - lazy = _LazyLease(connectors[0], owner) - lazies.append(lazy) - held.append((holding, lazy.writer, lazy.release)) - 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(lazy.writer) + for key, connectors in groups.items(): + scope = _DatasetScope(key, connectors) + scopes.append(scope) + scope.open(connectors) except BaseException as error: - _release_all(held, error) + _close_all(scopes, error) raise + token = active_run_states.set(active_run_states.get() | {s.state for s in scopes}) try: - yield - except BaseException as error: - refused = _refusal_behind(error, lazies) - _release_all(held, error if refused is None else refused) - if refused is None: - raise - # The run stopped because a first write was refused its lease; whichever route - # wrapped the refusal (a node's commit, a flush), the refusal is what the - # caller sees (ITL-1900). - refused.add_note(f"The run stopped with: {type(error).__name__}: {error}") - raise refused from None - _release_all(held, None) + 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) def _refusal_behind( - error: BaseException, lazies: list[_LazyLease] -) -> spiraldb_lease.LeaseBusyError | None: - """The claim refusal of one of ``lazies`` that ``error`` is or was raised from, if - any; never for an interruption.""" + error: BaseException, scopes: list[_DatasetScope] +) -> Exception | None: + """The error a write lock of ``scopes`` raised that ``error`` is or was raised + from, if any; never for an interruption.""" if not isinstance(error, Exception): return None - refusals = [lazy.refused for lazy in lazies if lazy.refused is not None] + refusals = [scope.refused for scope in scopes if scope.refused is not None] seen: list[BaseException] = [] current: BaseException | None = error while current is not None and not any(current is s for s in seen): - if any(current is r for r in refusals): - assert isinstance(current, spiraldb_lease.LeaseBusyError) - return current + for refusal in refusals: + if current is refusal: + return refusal seen.append(current) current = current.__cause__ or current.__context__ return None -class _LazyLease: - """A dataset's writer lease, claimed at the run's first write (ITL-1900). - - Made when the run starts: it observes the dataset's newest lease generation then - (``spiraldb_lease.observe``). The first call of ``writer`` (the first write, or a - side-effect node's claim) acquires the lease, only if that generation is unchanged, - and verifies it; the same call verifies it once more before the first write, - unless the acquisition verified it within ``RECENTLY_VERIFIED_SECONDS`` - (ITL-1901). - - Args: - connector: A writable connector of the dataset. - owner: Who holds the lease, shown to a refused second writer. - - Raises: - Exception: As ``spiraldb_lease.observe``, if the observation fails. - """ - - def __init__(self, connector: SpiralDBConnector, owner: str) -> None: - client, project_id, dataset = connector._writer_lease_target() # pyright: ignore[reportPrivateUsage] # the lease is taken by this module only - self._client: Any = client # pyright: ignore[reportExplicitAny] # the SDK client - self._project_id: str = project_id - self._dataset: str = dataset - self._owner: str = owner - self._pid: int = os.getpid() - self._observed: spiraldb_lease.Observed = spiraldb_lease.observe( - client, project_id, dataset - ) - self._lease: spiraldb_lease.Lease | None = None - self._verified_at: float = 0.0 - self._checked: bool = False - # The refusal of the claim, if it was refused: nothing was written then. - self.refused: spiraldb_lease.LeaseBusyError | None = None - self.writer: WriterLease = WriterLease(self._claim) - # The observation's listing is the run's first view of the dataset. - if self._observed.tables is not None: - self.writer.start_catalog(self._observed.tables) - - def _claim(self) -> None: - """Acquire the lease on first use, then verify it once.""" - require_same_process(self._pid) - # The run's lock: a racing first write on another thread waits for this one's - # claim, so the run takes one lease. - with self.writer.lock: - if self._lease is None: - - def claimed(lease: spiraldb_lease.Lease) -> None: - # Called once the acquisition verified the claim. - self._lease = lease - self._verified_at = _clock() - - try: - _ = spiraldb_lease.acquire( - self._client, - self._project_id, - self._dataset, - owner=self._owner, - on_claim=claimed, - expected=self._observed, - ) - except spiraldb_lease.LeaseBusyError as refusal: - self.refused = refusal - raise - if not self._checked: - assert self._lease is not None - # Interim (ITL-1901): skipped within RECENTLY_VERIFIED_SECONDS of the - # acquisition's own verification. - self._checked = _verify_unless_recent( - self._client, self._lease, self._verified_at +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.refused: Exception | None = None + self.state = RunState(self._acquire) + + def open(self, connectors: list[SpiralDBConnector]) -> None: + """Reserve the dataset, seed the catalog 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" ) + _open_scopes.add(self._reservation) + self._registered = True + try: + # The scope's view of the dataset's tables: one listing (ITL-1899). + listing = connectors[0]._list_tables_for_scope() # pyright: ignore[reportPrivateUsage] # scopes are opened by this module only + except Exception: # noqa: BLE001 # without a catalog, tables are found by name + listing = None + if listing is not None: + self.state.start_catalog(listing) + for connector in connectors: + self._attach(_tables(connector)) + + 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 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] = [] + 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) + if self._registered: + with _open_scopes_lock: + _open_scopes.remove(self._reservation) + return failures - def release(self) -> None: - """Release the lease if it was claimed.""" - if self._lease is not None: - spiraldb_lease.release(self._client, self._lease) - - -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``). - - 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, unless the acquisition - verified it within ``RECENTLY_VERIFIED_SECONDS`` (ITL-1901); releases it. - Raises: - LeaseBusyError: If another writer holds the dataset. - LeaseError: If the claim cannot be verified. - """ - 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() - # Called once the acquisition verified the claim. - verified_at = _clock() - - def check() -> None: - nonlocal checked - require_same_process(lease.pid) - with lock: - if not checked: - # Interim (ITL-1901): skipped within RECENTLY_VERIFIED_SECONDS of - # the acquisition's own verification. - checked = _verify_unless_recent(client, lease, verified_at) - - def release() -> None: - spiraldb_lease.release(client, lease) - - 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] - - -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 _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) - # What the run read under the lease ends with it (ITL-1899); an interruption - # here still lets the remote release be attempted. - try: - check.forget_reads() - except BaseException as exc: # noqa: BLE001 # reported with the others - failures.append(exc) - try: - release() - except BaseException as exc: # noqa: BLE001 # an interrupted release too: every lease is released; failures are reported below - failures.append(exc) + for scope in reversed(scopes): + failures.extend(scope.close()) if not failures: return interruptions = [f for f in failures if not isinstance(f, Exception)] if error is not None and not interruptions: # 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}" - ) + error.add_note(f"Closing a SpiralDB write scope also failed: {failure}") return # An interruption outranks an ordinary failure: it stops the program. primary = interruptions[0] if interruptions else failures[0] for failure in failures: if failure is not primary: - primary.add_note( - f"Releasing another SpiralDB writer lease failed: {failure}" - ) + primary.add_note(f"Closing another SpiralDB write scope failed: {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 a298a05d9..90c887780 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 f7bf2d511..e29b32976 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -50,7 +50,6 @@ check_sources, clear_run_rows, plan_run, - run_owner, database_write_scope, ) from orcapod.pipeline.observer_losses import RunLosses @@ -1409,18 +1408,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, @@ -1434,7 +1429,7 @@ def run( def _run_holding( self, - leases: contextlib.ExitStack, + write_scopes: contextlib.ExitStack, orchestrator: "SyncPipelineOrchestrator | AsyncPipelineOrchestrator | None", observer: "ExecutionObserverProtocol | None", materialize_results: bool, @@ -1442,11 +1437,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 @@ -1527,8 +1522,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 @@ -1540,11 +1534,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, @@ -1558,7 +1552,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, @@ -1566,9 +1560,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 @@ -1601,14 +1595,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: @@ -1810,12 +1804,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, @@ -1828,11 +1819,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 41e2bfbbe..d4ca2f0d2 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -131,7 +131,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. @@ -274,9 +274,9 @@ def _source_side_databases(streams: Iterable[Any], *, load_only: bool) -> list[A ``pod_result_databases``). Behind an ``ArrowTableStream`` no pod is read: the table holds its rows, whatever its ``upstreams`` name (ITL-1121), so only the caches of the sources there are collected. A load-only run reads no function pod - stream (``refuse_unloadable_inputs`` refuses one), so it leases none of their - databases: the refusal is the error it gives, never a busy lease. Each stream is - visited at most twice, behind a table and not (linear in the size of the graph). + stream (``refuse_unloadable_inputs`` refuses one), so it opens no write scopes for + those databases. The walk visits each stream at most twice, depending on whether + it is behind a held table. """ from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.sources.cached_source import CachedSource @@ -295,7 +295,7 @@ def _source_side_databases(streams: Iterable[Any], *, load_only: bool) -> list[A pending.append((stream.bound_source, behind_table)) continue 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 not load_only and not behind_table and not _is_job_node(stream): # A job node's pods: ``write_scope_databases``. found.extend(db for db in pod_result_databases(stream) if db is not None) @@ -329,7 +329,7 @@ def _job_nodes_under(targets: Iterable[Any]) -> list[Any]: def write_scope_databases( streams: Sequence[Any], *, load_only: bool, databases: Iterable[Any] = () ) -> 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 @@ -366,10 +366,8 @@ 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 @@ -382,11 +380,9 @@ def database_write_scope( 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. @@ -394,24 +390,15 @@ 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) 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()}" + return database_writes(written) def check_sources(streams: Iterable[Any]) -> tuple[str, ...]: diff --git a/src/orcapod/protocols/spiraldb_run.py b/src/orcapod/protocols/spiraldb_run.py index f6ae49642..4584a9ccc 100644 --- a/src/orcapod/protocols/spiraldb_run.py +++ b/src/orcapod/protocols/spiraldb_run.py @@ -20,10 +20,9 @@ def spiral_completion_lookup( """Return an execution-scoped lookup for a writable SpiralDB invocation log.""" ... - def spiral_claim_writer_lease(self) -> None: - """Claim the writer lease a run attached to this database now, as its first - write would (ITL-1900): a node that delivers side effects claims before it - decides what to deliver. Nothing without an attached lease.""" + def spiral_acquire_write_lock(self) -> None: + """Acquire the run's write lock before delivering effects or calling a + context-taking function. Do nothing outside a write scope.""" ... diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 9579abaf6..742bd3a93 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -451,7 +451,7 @@ def _execute_side_effect_row( 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 - lease's claim, ITL-1900); not called for a row already delivered. + write lock); not called for a row already delivered. Returns: ``(tag, data)`` to emit downstream, or ``None`` to drop the row. @@ -1317,21 +1317,18 @@ def _deliver_rows( pipeline_database=self._pipeline_database, table_path=self._table_path, completion_lookup=lookup, - before_delivery=self._claim_writer_lease, + before_delivery=self._acquire_write_lock, ) if result is not None: results.append(result) return results - def _claim_writer_lease(self) -> None: - """Claim the run's writer lease of a writable SpiralDB invocation log before a - delivery (ITL-1900). The log is read before the claim; the claim is refused if - another writer wrote the dataset since the run observed it, before any of the - run's reads, so a delivery is decided from what the store holds. A run with - nothing to deliver claims nothing.""" + 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_claim_writer_lease() + database.spiral_acquire_write_lock() def _completion_lookup(self) -> Callable[[bytes], bool] | None: """Index a writable SpiralDB invocation log for this execution.""" @@ -1600,7 +1597,7 @@ async def process_one(tag: TagProtocol, data: DataProtocol) -> None: pipeline_database=self._pipeline_database, table_path=self._table_path, completion_lookup=lookup, - before_delivery=self._claim_writer_lease, + before_delivery=self._acquire_write_lock, ) if result is not None: async with send_lock: 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_migrate_spiral_schemas.py b/tests/test_databases/test_migrate_spiral_schemas.py index d4ed204ca..50988fecc 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( diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py deleted file mode 100644 index b789f1f42..000000000 --- a/tests/test_databases/test_spiral_lease.py +++ /dev/null @@ -1,1054 +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_connector, 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 _count_opens_by_name(monkeypatch: pytest.MonkeyPatch) -> list[str]: - """Record the name of every open by name from now on.""" - 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) - return probes - - -def _count_listings(monkeypatch: pytest.MonkeyPatch) -> list[str]: - """Record every page request of the dataset listing from now on.""" - listing = fake.fake_http_get_json - pages: list[str] = [] - - def count(url: str, token: str | None) -> dict[str, object]: - pages.append(url) - return listing(url, token) - - monkeypatch.setattr(spiraldb_connector, "_http_get_json", count) - return pages - - -@pytest.mark.parametrize("past_generations", [0, 1, 19, 40]) -def test_generation_search_opens_the_newest_and_probes_the_next( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, past_generations: int -) -> None: - """Finding the newest generation takes one listing of the dataset, an open of the - newest generation it shows and one probe of the next: never a search by name - (ITL-1899: 17 opens for about 380 generations before).""" - for _ in range(past_generations): - release(client, acquire(client, _PROJECT, _DATASET, owner="past")) - probes = _count_opens_by_name(monkeypatch) - pages = _count_listings(monkeypatch) - current = acquire(client, _PROJECT, _DATASET, owner="current") - newest = [spiral_lease_table_name(past_generations)] if past_generations else [] - assert probes == [*newest, spiral_lease_table_name(past_generations + 1)] - # One listing (of one or more pages), no other. - assert pages and all("pageToken" in page for page in pages[1:]) - assert ( - client.keyed_table( - _PROJECT, _DATASET, spiral_lease_table_name(past_generations + 1) - ).resource_id - == current.table_id - ) - - -@pytest.mark.parametrize("hidden", [1, 3]) -def test_a_lagging_listing_still_finds_the_newest_generation( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, hidden: int -) -> None: - """A listing that does not show the newest generations yet ends where it ends: the - generations after it are found by name, so a held newest generation still refuses - and a released one is followed by the next.""" - for _ in range(4): - release(client, acquire(client, _PROJECT, _DATASET, owner="past")) - holder = acquire(client, _PROJECT, _DATASET, owner="holder") - listed = spiraldb_connector._list_dataset # pyright: ignore[reportPrivateUsage] - lagging = {spiral_lease_table_name(5 - i) for i in range(hidden)} - - def lag(client: object, project_id: str, dataset: str) -> dict[str, str]: - return { - table_id: name - for table_id, name in listed(client, project_id, dataset).items() - if name not in lagging - } - - monkeypatch.setattr(spiraldb_connector, "_list_dataset", lag) - other = fake.FakeClient() - with pytest.raises(LeaseBusyError, match=holder.table_id): - _ = acquire(other, _PROJECT, _DATASET, owner="second") - release(client, holder) - after = acquire(other, _PROJECT, _DATASET, owner="after") - assert ( - client.keyed_table(_PROJECT, _DATASET, spiral_lease_table_name(6)).resource_id - == after.table_id - ) - with pytest.raises(LeaseError, match="not the newest"): - clear(other, _PROJECT, _DATASET, holder.table_id, confirm_writer_stopped=True) - clear(other, _PROJECT, _DATASET, after.table_id, confirm_writer_stopped=True) - - -def test_a_listed_generation_that_does_not_open_falls_back_to_the_search( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch -) -> None: - """A listing that shows a generation the service then does not open is not trusted: - the generation sequence is searched by name, as before the listing.""" - for _ in range(3): - release(client, acquire(client, _PROJECT, _DATASET, owner="past")) - listed = spiraldb_connector._list_dataset # pyright: ignore[reportPrivateUsage] - - def ahead(client: object, project_id: str, dataset: str) -> dict[str, str]: - return { - **listed(client, project_id, dataset), - "table_ahead": spiral_lease_table_name(4), - } - - monkeypatch.setattr(spiraldb_connector, "_list_dataset", ahead) - lease = acquire(client, _PROJECT, _DATASET, owner="current") - assert ( - client.keyed_table(_PROJECT, _DATASET, spiral_lease_table_name(4)).resource_id - == lease.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_lazy_lease.py b/tests/test_databases/test_spiraldb_lazy_lease.py deleted file mode 100644 index cd6008dd0..000000000 --- a/tests/test_databases/test_spiraldb_lazy_lease.py +++ /dev/null @@ -1,826 +0,0 @@ -"""The writer lease taken at the first write (ITL-1900), on the fake SDK. - -A run observes each leased dataset's newest lease generation when its write scope -opens, and claims the lease at its first write to that dataset (a side-effect node: -after it reads its invocation log, just before its first delivery). The claim is refused when the generation moved -since the observation (``LeaseChangedError``) or is held (``LeaseBusyError``), with -nothing written. A run that writes nothing takes no lease. -""" - -from __future__ import annotations - -import asyncio -import threading -import time -from collections.abc import Callable -from typing import Any - -import pytest - -import pyarrow as pa - -from orcapod import PipelineJob, function_pod -from orcapod.contexts import get_default_context -from orcapod.core.operators import SelectDataColumns -from orcapod.databases import ConnectorArrowDatabase, SpiralDBConnector -from orcapod.databases import spiraldb_lease, spiraldb_write_scope -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.invocation import InvocationContext -from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator -from orcapod.side_effects import SideEffectPod, sink_pod -from orcapod.sources import ArrowTableSource -from orcapod.types import CacheMode, NodeConfig -from orcapod.databases import spiral_database_identity -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] - _database, # pyright: ignore[reportPrivateUsage] - _job, # pyright: ignore[reportPrivateUsage] - _lease_tables, # pyright: ignore[reportPrivateUsage] - _rows, # pyright: ignore[reportPrivateUsage] - _run, # pyright: ignore[reportPrivateUsage] - calls, - combine, - delivered, - root, # noqa: F401 # pyright: ignore[reportUnusedImport] # the fixture -) - - -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 and not is_spiral_lease_table_name(t["name"]) - } - - -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"], - ) - - -@pytest.fixture -def acquisitions(monkeypatch: pytest.MonkeyPatch) -> list[str]: - """The datasets of every lease acquisition.""" - seen: list[str] = [] - real = spiraldb_lease.acquire - - def counted(client: Any, project_id: str, dataset: str, *a: Any, **k: Any) -> Any: - seen.append(dataset) - return real(client, project_id, dataset, *a, **k) - - monkeypatch.setattr(spiraldb_lease, "acquire", counted) - return seen - - -def _another_writer_inside_the_window( - monkeypatch: pytest.MonkeyPatch, dataset: str = "d" -) -> list[None]: - """After the run's first observation of ``dataset``, another writer takes and - releases its lease: the generation the run observed is no longer the newest.""" - real = spiraldb_lease.observe - done: list[None] = [] - - def observe_then_write(client: Any, project_id: str, observed: str) -> Any: - result = real(client, project_id, observed) - if observed == dataset and not done: - done.append(None) - _, release = take_lease( - SpiralDBConnector("p", dataset, writable=True), "writer A" - ) - release() - return result - - monkeypatch.setattr(spiraldb_lease, "observe", observe_then_write) - return done - - -# --------------------------------------------- another writer inside the window - - -@pytest.mark.usefixtures("root") -@pytest.mark.parametrize("entry", ENTRIES) -def test_a_writer_releasing_inside_the_window_refuses_the_first_write( - monkeypatch: pytest.MonkeyPatch, entry: str -) -> None: - """Writer A takes and releases the lease after this run observed the dataset: the - run is refused at its first write, with nothing written, computed or delivered.""" - _ = _job(_database()).run() - calls.clear() - delivered.clear() - before = _versions() - leases = _lease_tables() - done = _another_writer_inside_the_window(monkeypatch) - job = _job(_database(), table=_rows(4)) - with pytest.raises( - spiraldb_lease.LeaseChangedError, - match="lease of SpiralDB dataset p/d changed since this run started", - ) as raised: - _ = _run(job, entry) - # Review of e82c9f276: the message says the lease changed and this write wrote - # nothing, never that the other writer wrote. - assert "wrote nothing to the dataset" in str(raised.value) - assert "Another writer wrote" not in str(raised.value) - assert done - assert _versions() == before - assert calls == [] and delivered == [] - # Writer A's generation, and no claim of this run's. - assert len(_lease_tables()) == len(leases) + 1 - # Run again: the run goes ahead. - monkeypatch.undo() - _ = _run(job, entry) - assert calls == [(4, 8)] - - -@pytest.mark.usefixtures("root") -@pytest.mark.parametrize("entry", ENTRIES) -def test_a_lease_held_from_start_to_claim_is_the_busy_refusal(entry: str) -> None: - """A generation held when the run starts and still held at its first write gives - the busy refusal (not the changed one), with nothing written.""" - _ = _job(_database()).run() - before = _versions() - _, release = take_lease(SpiralDBConnector("p", "d", writable=True), "writer A") - try: - with pytest.raises(spiraldb_lease.LeaseBusyError, match="writer A") as raised: - _ = _run(_job(_database(), table=_rows(4)), entry) - assert not isinstance(raised.value, spiraldb_lease.LeaseChangedError) - finally: - release() - assert _versions() == before - - -@pytest.mark.usefixtures("root") -@pytest.mark.parametrize("entry", ENTRIES) -def test_an_unchanged_generation_stores_what_an_eager_lease_stores( - monkeypatch: pytest.MonkeyPatch, entry: str -) -> None: - """With nobody else writing, the run's stored tables equal those of a run that - took its lease when its scope opened: here on dataset ``e``, claimed eagerly.""" - real_init = spiraldb_write_scope._LazyLease.__init__ # pyright: ignore[reportPrivateUsage] - - def eager_on_e(self: Any, connector: Any, owner: str) -> None: - real_init(self, connector, owner) - if self._dataset == "e": # pyright: ignore[reportPrivateUsage] - self._claim() - - monkeypatch.setattr(spiraldb_write_scope._LazyLease, "__init__", eager_on_e) # pyright: ignore[reportPrivateUsage] - lazy, eager = _database("d"), _database("e") - for table in (_rows(), _rows(4)): - _ = _run(_job(lazy, table=table), entry) - _ = _run(_job(eager, table=table), entry) - _ = _run(_job(lazy, table=_rows(4), cache_mode=CacheMode.REPLAY), entry) - _ = _run(_job(eager, table=_rows(4), cache_mode=CacheMode.REPLAY), entry) - paths = sorted(lazy.list_table_paths()) - assert paths == sorted(eager.list_table_paths()) - for path in paths: - on_lazy, on_eager = lazy.get_all_records(path), eager.get_all_records(path) - assert on_lazy is not None and on_eager is not None, path - assert on_lazy.schema == on_eager.schema, path - assert _comparable(on_lazy) == _comparable(on_eager), path - - -# ------------------------------------------------------- side-effect deliveries - - -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} - - -SIDE_EFFECT_ENTRIES = ["sync", "async orchestrator", "run_async", "node run"] - - -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 _recorded(monkeypatch: pytest.MonkeyPatch) -> list[str]: - """The run's observations, claims, reads of the side-effect node's log tables - (``"log read"``) and deliveries, in order.""" - events = EVENTS - events.clear() - real_observe, real_acquire = spiraldb_lease.observe, spiraldb_lease.acquire - real_scan = fake.FakeKeyedTable.scan - - def observe(*args: Any, **kwargs: Any) -> Any: - events.append("observe") - return real_observe(*args, **kwargs) - - def acquire(*args: Any, **kwargs: Any) -> Any: - events.append("claim") - return real_acquire(*args, **kwargs) - - def scan(table: fake.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any: - if not is_spiral_lease_table_name(table._table["name"]): # pyright: ignore[reportPrivateUsage] - 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 real_scan(table, *args, **kwargs) - - monkeypatch.setattr(spiraldb_lease, "observe", observe) - monkeypatch.setattr(spiraldb_lease, "acquire", acquire) - monkeypatch.setattr(fake.FakeKeyedTable, "scan", scan) - return events - - -@pytest.mark.usefixtures("root") -@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") -@pytest.mark.parametrize("kind", SIDE_EFFECTS) -@pytest.mark.parametrize("entry", SIDE_EFFECT_ENTRIES) -def test_a_side_effect_node_claims_just_before_its_first_delivery( - monkeypatch: pytest.MonkeyPatch, kind: str, entry: str -) -> None: - """The run observes the dataset before any read of it; a side-effect node reads - its log, then claims the lease just before its first delivery, and delivers each - new row once. With nothing to deliver it claims nothing.""" - build = SIDE_EFFECTS[kind] - _run_side_effect(build(_database(), 3), entry) - assert sorted(delivered) == [1, 2, 3] - delivered.clear() - events = _recorded(monkeypatch) - _run_side_effect(build(_database(), 4), entry) - assert sorted(delivered) == [4] - # Observe, read the log, claim, deliver: in that order, the claim once. - assert events[0] == "observe", events - assert events.count("claim") == 1 and events.count("deliver") == 1, events - first_read = events.index("log read") - assert first_read < events.index("claim") < events.index("deliver"), events - # A fresh job with nothing new to deliver reads its log and claims nothing. - events.clear() - _run_side_effect(build(_database(), 4), entry) - assert events[0] == "observe" and "log read" in events, events - assert "claim" not in events and "deliver" not in events, events - - -@pytest.mark.usefixtures("root") -@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") -@pytest.mark.parametrize("kind", SIDE_EFFECTS) -@pytest.mark.parametrize("entry", SIDE_EFFECT_ENTRIES) -def test_a_side_effect_node_never_delivers_when_another_writer_acts_in_the_window( - monkeypatch: pytest.MonkeyPatch, kind: str, entry: str -) -> None: - """Another writer takes and releases the lease after the run observed the - dataset: the side-effect node read its log before that, so its claim is refused - and it delivers nothing.""" - build = SIDE_EFFECTS[kind] - _run_side_effect(build(_database(), 3), entry) - delivered.clear() - before = _versions() - _ = _another_writer_inside_the_window(monkeypatch) - with pytest.raises(spiraldb_lease.LeaseChangedError): - _run_side_effect(build(_database(), 4), entry) - assert delivered == [] - assert _versions() == before - - -# ---------------------------------------------------------------- every route - - -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, -} - - -@pytest.mark.usefixtures("root") -@pytest.mark.parametrize("route", ROUTES) -@pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) -def test_every_route_is_refused_at_its_first_write(route: str, entry: str) -> None: - """Each kind of table a run writes, on a dataset another writer holds: the run is - refused at its first write there, with nothing written to that dataset.""" - _, release = take_lease(SpiralDBConnector("p", "d", writable=True), "writer A") - try: - with pytest.raises(spiraldb_lease.LeaseBusyError, match="writer A"): - _ = _run(ROUTES[route](_database()), entry) - finally: - release() - assert _versions() == {} - assert delivered == [] - _ = _run(ROUTES[route](_database()), entry) - assert _versions() != {} - - -@pytest.mark.usefixtures("root") -def test_node_runs_are_refused_at_their_first_write() -> None: - """``node.run()`` claims at the first write too, also for a side-effect node.""" - for route in ("job tables", "side-effect log", "operator cache"): - job = ROUTES[route](_database()) - label = {"job tables": "sink", "side-effect log": "sink"}.get(route, "select") - _, release = take_lease(SpiralDBConnector("p", "d", writable=True), "A") - try: - with pytest.raises(spiraldb_lease.LeaseBusyError): - _ = job.nodes[label].run() - finally: - release() - assert _versions() == {}, route - assert delivered == [], route - - -# ------------------------------------------------------------ runs that write none - - -@pytest.mark.usefixtures("root") -@pytest.mark.parametrize("entry", ENTRIES) -def test_a_run_that_writes_nothing_takes_no_lease( - acquisitions: list[str], entry: str -) -> None: - """A held rerun, a REPLAY run and a load-only run write nothing and acquire no - lease; they only observe the generation.""" - _ = _run(_job(_database()), entry) - _ = _run(_job(_database(), cache_mode=CacheMode.REPLAY), entry) - acquisitions.clear() - leases, before = _lease_tables(), _versions() - job = _job(_database()) - _ = _run(job, entry) - _ = _run(job, entry) # held - _ = _run(_job(_database(), cache_mode=CacheMode.REPLAY), entry) - _ = _run(_job(_database()), entry, load_only=True) - assert acquisitions == [] - assert _lease_tables() == leases - assert _versions() == before - - -@pytest.mark.usefixtures("root") -@pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) -def test_a_run_failing_before_any_write_leaves_no_lease(entry: str) -> None: - @function_pod(output_keys="z") - def boom(x: int) -> int: - raise RuntimeError("boom") - - job = PipelineJob(name=JOB, database=_database()) - with job: - 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) - assert _lease_tables() == [] - - -# ------------------------------------------------------------------ racing claims - - -def _slow_acquire(monkeypatch: pytest.MonkeyPatch) -> list[None]: - """Acquisitions that take a while, so racing claims overlap.""" - seen: list[None] = [] - real = spiraldb_lease.acquire - - def slow(*args: Any, **kwargs: Any) -> Any: - seen.append(None) - time.sleep(0.05) - return real(*args, **kwargs) - - monkeypatch.setattr(spiraldb_lease, "acquire", slow) - return seen - - -@pytest.mark.usefixtures("root") -def test_racing_first_writes_from_threads_take_one_lease( - monkeypatch: pytest.MonkeyPatch, -) -> None: - seen = _slow_acquire(monkeypatch) - databases = [_database() for _ in range(4)] - with database_writes(databases, owner="test"): - start = threading.Barrier(len(databases)) - errors: list[BaseException] = [] - - def claim(database: ConnectorArrowDatabase) -> None: - try: - _ = start.wait() - database.spiral_claim_writer_lease() - except BaseException as exc: # pragma: no cover - reported below - errors.append(exc) - - threads = [threading.Thread(target=claim, args=(d,)) for d in databases] - for thread in threads: - thread.start() - for thread in threads: - thread.join() - assert errors == [] - assert len(seen) == 1 - assert len(_lease_tables()) == 1 - - -@pytest.mark.usefixtures("root") -def test_racing_first_writes_from_tasks_take_one_lease( - monkeypatch: pytest.MonkeyPatch, -) -> None: - seen = _slow_acquire(monkeypatch) - databases = [_database() for _ in range(4)] - - async def race() -> None: - _ = await asyncio.gather( - *(asyncio.to_thread(d.spiral_claim_writer_lease) for d in databases) - ) - - with database_writes(databases, owner="test"): - asyncio.run(race()) - assert len(seen) == 1 - assert len(_lease_tables()) == 1 - - -# ------------------------------------------- recently verified leases (ITL-1901) - - -def _clock(monkeypatch: pytest.MonkeyPatch, *times: float) -> None: - """The write scope's clock returns ``times`` in turn, then the last one.""" - left = list(times) - - def now() -> float: - return left.pop(0) if len(left) > 1 else left[0] - - monkeypatch.setattr(spiraldb_write_scope, "_clock", now) - - -@pytest.fixture -def verifications(monkeypatch: pytest.MonkeyPatch) -> list[None]: - """Every verification of a lease's claim (the acquisition's included).""" - seen: list[None] = [] - real = spiraldb_lease.check - - def counted(*args: Any, **kwargs: Any) -> Any: - seen.append(None) - return real(*args, **kwargs) - - monkeypatch.setattr(spiraldb_lease, "check", counted) - return seen - - -def _write(database: ConnectorArrowDatabase, key: bytes) -> None: - """Write one row with record id ``key`` to a result table of ``database``.""" - database.add_records( - ("recent", "rdb_v1"), - pa.table( - { - "__record_id": pa.array([key], pa.large_binary()), - "value": [1], - "__data_context": [get_default_context().context_key], - } - ), - record_id_column="__record_id", - flush=True, - ) - - -@pytest.mark.usefixtures("root") -@pytest.mark.parametrize( - ("elapsed", "expected"), - [ - (0.0, 1), - (59.9, 1), - (spiraldb_write_scope.RECENTLY_VERIFIED_SECONDS, 2), - (61.0, 2), - ], -) -def test_the_first_write_verifies_only_a_lease_not_verified_recently( - monkeypatch: pytest.MonkeyPatch, - verifications: list[None], - elapsed: float, - expected: int, -) -> None: - """The lazy claim verifies the lease when it acquires it; its first write verifies - it again only when 60 seconds or more passed since (ITL-1901).""" - _clock(monkeypatch, 100.0, 100.0 + elapsed) - database = _database() - with database_writes([database], owner="test"): - _write(database, b"a") - _write(database, b"b") - assert len(verifications) == expected - - -@pytest.mark.usefixtures("root") -@pytest.mark.parametrize(("elapsed", "expected"), [(30.0, 1), (60.0, 2)]) -def test_a_lease_taken_at_once_verifies_at_its_first_write_after_60_seconds( - monkeypatch: pytest.MonkeyPatch, - verifications: list[None], - elapsed: float, - expected: int, -) -> None: - """A lease taken by ``take_lease`` follows the same rule: its first check after - the acquisition reads the lease state only after 60 seconds (ITL-1901).""" - _clock(monkeypatch, 100.0, 100.0 + elapsed) - check, release = take_lease(SpiralDBConnector("p", "d", writable=True), "test") - try: - check.verify() - check.verify() - finally: - release() - assert len(verifications) == expected - - -@pytest.mark.usefixtures("root") -@pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) -def test_a_run_lists_its_dataset_once_when_it_starts( - monkeypatch: pytest.MonkeyPatch, acquisitions: list[str], entry: str -) -> None: - """The observation's listing finds the newest generation and is the run's - catalog; the claim starts from the observed generation without listing again - (ITL-1899).""" - from orcapod.databases import spiraldb_connector - - listings: list[str] = [] - real = spiraldb_connector._list_dataset # pyright: ignore[reportPrivateUsage] - - def counted(client: Any, project: str, dataset: str) -> dict[str, str]: - listings.append(dataset) - return real(client, project, dataset) - - monkeypatch.setattr(spiraldb_connector, "_list_dataset", counted) - for table in (_rows(), _rows(4)): - listings.clear() - acquisitions.clear() - _ = _run(_job(_database(), table=table), entry) - assert acquisitions == ["d"] - assert listings == ["d"] - - -# ------------------------------------------------------ review of e82c9f276 (#701) - - -def _failing_lease_listing( - monkeypatch: pytest.MonkeyPatch, times: int | None = None -) -> list[None]: - """The writer lease's listing of the dataset fails (the first ``times`` calls, or - every call); opens by name still work.""" - from orcapod.databases import spiraldb_connector - - failed: list[None] = [] - real = spiraldb_connector._list_dataset_for_lease # pyright: ignore[reportPrivateUsage] - - def failing(*args: Any, **kwargs: Any) -> dict[str, str]: - if times is not None and len(failed) >= times: - return real(*args, **kwargs) - failed.append(None) - raise TimeoutError("the listing timed out") - - monkeypatch.setattr(spiraldb_connector, "_list_dataset_for_lease", failing) - return failed - - -@pytest.mark.usefixtures("root") -@pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) -def test_a_failed_listing_leaves_the_observation_to_the_name_search( - monkeypatch: pytest.MonkeyPatch, entry: str -) -> None: - """Finding M1: a listing that fails does not block the run: the observation finds - the newest generation by name, and the run stores as it would.""" - _ = _run(_job(_database()), entry) - failed = _failing_lease_listing(monkeypatch) - _ = _run(_job(_database(), table=_rows(4)), entry) - assert failed - assert calls[-1] == (4, 8) - - -@pytest.mark.usefixtures("root") -@pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) -def test_a_failed_listing_still_refuses_a_writer_inside_the_window( - monkeypatch: pytest.MonkeyPatch, entry: str -) -> None: - """Finding M1: with the listing failing, a writer that takes the lease after the - observation still has the run refused at its first write, with nothing written; - one held all along still gives the busy refusal.""" - _ = _run(_job(_database()), entry) - before = _versions() - # The run's observation lists and fails; the other writer's own listing works. - failed = _failing_lease_listing(monkeypatch, times=1) - done = _another_writer_inside_the_window(monkeypatch) - with pytest.raises(spiraldb_lease.LeaseChangedError): - _ = _run(_job(_database(), table=_rows(4)), entry) - assert failed and done and _versions() == before - _, release = take_lease(SpiralDBConnector("p", "d", writable=True), "writer A") - try: - with pytest.raises(spiraldb_lease.LeaseBusyError, match="writer A"): - _ = _run(_job(_database(), table=_rows(4)), entry) - finally: - release() - assert _versions() == before - - -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], owner="seed"): - 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], owner="test"): - 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], owner="test"): - 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.mark.usefixtures("root") -@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") -@pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) -def test_a_context_function_claims_its_nested_result_store_before_it_is_called( - entry: str, -) -> None: - """Finding M4: the function's own result store (``result_database=``), on a - dataset another writer holds, is claimed before the function is called: the run - is refused with the function not called and nothing written there.""" - nested = _database("n") - - @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") - _, release = take_lease(SpiralDBConnector("p", "n", writable=True), "writer A") - try: - with pytest.raises(spiraldb_lease.LeaseBusyError, match="writer A"): - _ = _run(job, entry) - finally: - release() - assert delivered == [] - assert _versions("n") == {} - - -@pytest.mark.usefixtures("root") -def test_a_write_long_after_a_claim_verifies_the_lease( - monkeypatch: pytest.MonkeyPatch, verifications: list[None] -) -> None: - """Finding m4: a side-effect node's claim before a delivery does not stand in - for the write that follows 60 seconds or more later: that write verifies the - lease once; later writes do not.""" - _clock(monkeypatch, 100.0, 100.0, 161.0) - database = _database() - with database_writes([database], owner="test"): - database.spiral_claim_writer_lease() # the claim before a delivery - assert len(verifications) == 1 # the acquisition's own - _write(database, b"a") - _write(database, b"b") - assert len(verifications) == 2 - - -@pytest.mark.usefixtures("root") -def test_an_interrupted_cleanup_of_kept_reads_still_releases_the_lease( - monkeypatch: pytest.MonkeyPatch, -) -> None: - """Finding m8: an interruption while forgetting a run's kept reads does not skip - the lease's release.""" - from orcapod.databases import spiraldb_tables - - def interrupted(self: Any) -> None: - raise KeyboardInterrupt - - database = _database() - monkeypatch.setattr(spiraldb_tables.WriterLease, "forget_reads", interrupted) - with pytest.raises(KeyboardInterrupt): - with database_writes([database], owner="interrupted"): - database.spiral_claim_writer_lease() - monkeypatch.undo() - _, release = take_lease(SpiralDBConnector("p", "d", writable=True), "after") - release() diff --git a/tests/test_databases/test_spiraldb_round_trips.py b/tests/test_databases/test_spiraldb_round_trips.py index a8fb57f1c..4d56ff4d7 100644 --- a/tests/test_databases/test_spiraldb_round_trips.py +++ b/tests/test_databases/test_spiraldb_round_trips.py @@ -16,9 +16,8 @@ import pytest from orcapod.databases import ConnectorArrowDatabase, spiraldb_connector -from orcapod.databases.spiraldb_tables import SpiralDBTables, WriterLease +from orcapod.databases.spiraldb_tables import SpiralDBTables, RunState from orcapod.databases.spiraldb_write_scope import database_writes -from orcapod.databases.store_table_names import is_spiral_lease_table_name from orcapod.types import CacheMode from tests.test_databases import fake_spiral_sdk as fake from tests.test_databases.test_spiraldb_writable_runs import ( @@ -40,7 +39,7 @@ @dataclass(frozen=True) class Call: - """One SDK call on a database table (not a lease generation). + """One SDK call on a database table. Attributes: kind: What it did: ``open by name``, ``open by id``, ``create``, @@ -72,12 +71,10 @@ def recorded(self: Any, *args: Any, **kwargs: Any) -> Any: # pyright: ignore[re result = original(self, *args, **kwargs) except Exception: name = table_of(self, args, None) - if not is_spiral_lease_table_name(name): - calls.append(Call(kind, name, ok=False)) + calls.append(Call(kind, name, ok=False)) raise name = table_of(self, args, result) - if not is_spiral_lease_table_name(name): - calls.append(Call(kind, name)) + calls.append(Call(kind, name)) return result monkeypatch.setattr(cls, method, recorded) @@ -106,19 +103,18 @@ def scanned( **kwargs: Any, # pyright: ignore[reportExplicitAny] ) -> Any: # pyright: ignore[reportExplicitAny] columns = args[0] if args else kwargs.get("columns") - if not is_spiral_lease_table_name(_name(table)): - kind = ( - "one-row read" - if kwargs.get("limit") is not None - else "full read" - if columns is None - else "key read" - ) - calls.append(Call(kind, _name(table))) + kind = ( + "one-row read" + if kwargs.get("limit") is not None + else "full read" + if columns is None + else "key read" + ) + calls.append(Call(kind, _name(table))) return scan(table, *args, **kwargs) monkeypatch.setattr(fake.FakeKeyedTable, "scan", scanned) - # Every listing of a dataset: the lease's observation and the catalog's alike. + # 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] @@ -146,7 +142,7 @@ def _first_run(entry: str, calls: list[Call], rows: int = 3) -> None: 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, when it starts (the writer lease's observation), + """The run lists its dataset once, when it starts, 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.""" @@ -162,7 +158,7 @@ def test_a_table_the_run_creates_is_found_after_its_listing_showed_it_absent() - name finds it, through any connector of the run.""" db, other = _database(), _database() path = ("fn", "rdb_v1") - with database_writes([db, other], owner="test"): + with database_writes([db, other]): assert db.list_table_paths(("fn",)) == [] assert not other.table_exists(path) db.add_records( @@ -203,7 +199,7 @@ def test_new_rows_read_each_table_whole_once_per_batch_of_writes( @pytest.mark.usefixtures("root") def test_kept_rows_are_what_a_fresh_read_gives() -> None: - """Rows kept by a read under the lease are what a read of the service gives, also + """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") @@ -229,7 +225,7 @@ def kept(database: ConnectorArrowDatabase) -> list[bytes]: assert read is not None return sorted(cast("list[bytes]", read.column("__record_id").to_pylist())) - with database_writes([db, other], owner="test"): + with database_writes([db, other]): db.add_records(path, rows("a"), record_id_column="__record_id", flush=True) assert kept(db) == kept(other) == fresh() == [b"a"] other.add_records(path, rows("b"), record_id_column="__record_id", flush=True) @@ -253,19 +249,19 @@ def test_rows_read_from_a_snapshot_older_than_an_append_are_not_kept( "__data_context": ["std:v1:default"], } ) - with database_writes([db], owner="test"): + with database_writes([db]): db.add_records(path, first, record_id_column="__record_id", flush=True) tables = db._spiral # pyright: ignore[reportPrivateUsage] assert isinstance(tables, SpiralDBTables) - lease = tables._lease_check # pyright: ignore[reportPrivateUsage] - assert isinstance(lease, WriterLease) - lease.rows_by_table.clear() + state = tables._run_state # pyright: ignore[reportPrivateUsage] + assert isinstance(state, RunState) + state.rows_by_table.clear() name = tables.table_name(path) with tables.operation(): _ = tables.has_table(name) - lease.commits += 2 # an append of the run committed meanwhile + state.commits += 2 # an append of the run committed meanwhile assert len(list(tables.scan(name))) == 1 - assert lease.rows_by_table == {} + assert state.rows_by_table == {} # ── item 4: what the run already knows ─────────────────────────────────────── @@ -311,7 +307,7 @@ def test_each_existing_table_is_identified_once_per_run( @pytest.mark.usefixtures("root") -def test_what_a_run_read_is_forgotten_when_its_lease_ends() -> None: +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") @@ -324,14 +320,14 @@ def test_what_a_run_read_is_forgotten_when_its_lease_ends() -> None: ) tables = db._spiral # pyright: ignore[reportPrivateUsage] assert isinstance(tables, SpiralDBTables) - with database_writes([db], owner="test"): + 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) - lease = tables._lease_check # pyright: ignore[reportPrivateUsage] - assert isinstance(lease, WriterLease) - assert lease.rows_by_table and lease.found_by_id and lease.catalog - assert tables._lease_check is None # pyright: ignore[reportPrivateUsage] - assert not lease.rows_by_table and not lease.found_by_id - assert not lease.keys_by_table and not lease.ids_by_name - assert lease.catalog is None + 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 8eacf6de6..1d85b32c9 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. @@ -32,8 +31,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, @@ -53,54 +51,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 _forget_run_reads(project: str = "p", dataset: str = "d") -> None: - """Forget what the test's run read under its lease, as a lease claimed after an - outside change does: the change was made by another writer, which a held lease - excludes, so a run sees it only when its lease starts (ITL-1899, ITL-1900).""" - _test_leases[(project, dataset)][0].forget_reads() - - -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: @@ -138,12 +97,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 @@ -333,7 +288,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() @@ -592,7 +547,6 @@ def test_rows_of_another_data_context_are_refused_before_they_are_buffered() -> _table(identity.spiral_table_name(RESULT)).set_metadata( identity.table_identity_metadata(RESULT, recorded) ) - _forget_run_reads() other = (*RESULT[:-1], "rdb_v9") db = ConnectorArrowDatabase(writable_connector()) db.add_records(other, rows(["valid"]), record_id_column="__record_id") @@ -623,7 +577,6 @@ def test_a_table_of_another_data_context_made_after_buffering_is_refused_at_flus _table(identity.spiral_table_name(RESULT)).set_metadata( identity.table_identity_metadata(RESULT, recorded) ) - _forget_run_reads() with pytest.raises(InputValidationError) as raised: db.flush() assert recorded in str(raised.value) and CONTEXT in str(raised.value) @@ -799,9 +752,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" @@ -1041,9 +992,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 scope entry. + 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") @@ -1054,9 +1005,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 @@ -1075,20 +1024,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: @@ -1098,8 +1051,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" @@ -1118,8 +1071,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" ) @@ -1161,13 +1115,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" ) @@ -1231,8 +1188,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) @@ -1316,14 +1271,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: @@ -1339,7 +1294,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) @@ -1349,7 +1304,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") @@ -1360,7 +1315,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(): @@ -1508,8 +1463,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]) == ( @@ -1776,7 +1731,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: @@ -1867,22 +1822,19 @@ 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 of database tables - (a writer lease generation's are the lease's, claimed at the first write).""" + """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 scan = fake.FakeKeyedTable.scan def open_by_name(self: Any, *args: Any, **kwargs: Any) -> Any: - if not is_spiral_lease_table_name(args[2]): - counts["names"] += 1 + counts["names"] += 1 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) - if not is_spiral_lease_table_name(table._table["name"]): - counts["ids"] += 1 + counts["ids"] += 1 return table def counted_scan(self: Any, *args: Any, **kwargs: Any) -> Any: @@ -1902,11 +1854,11 @@ def test_flush_reuses_keys_and_opens_by_id_after_resolving_the_name( ) -> None: """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(held=False)) - with database_writes([db], owner="seed"): + 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} @@ -1929,7 +1881,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 @@ -1949,7 +1901,7 @@ def test_ids_checked_by_two_handles_are_written_once( monkeypatch: pytest.MonkeyPatch, ) -> 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.""" + the ID written by the first in the shared key index and keeps its value.""" connector = writable_connector() first, second = ConnectorArrowDatabase(connector), ConnectorArrowDatabase(connector) _add(first, rows(["r0"]), flush=True) @@ -2016,7 +1968,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 @@ -2171,7 +2123,6 @@ def test_an_append_to_a_table_recording_other_stored_names_is_refused() -> None: **codec.manifest_entries(other), } ) - _forget_run_reads() db = ConnectorArrowDatabase(writable_connector()) with pytest.raises(ValueError, match="other names") as raised: _add(db, rows(["r1", "r2"], offset=1), flush=True) @@ -2335,7 +2286,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( @@ -2448,7 +2399,7 @@ def unreadable(self: Any) -> dict[str, bytes]: raise RuntimeError("the service could not read the metadata") monkeypatch.setattr(fake.FakeKeyedTable, "get_metadata", unreadable) - fresh = ConnectorArrowDatabase(writable_connector(held=False)) + fresh = ConnectorArrowDatabase(writable_connector()) with pytest.raises(OrcapodDatabaseReadError) as raised: if lookup == "by_id": _ = fresh.get_record_by_id(RESULT, b"r0", record_id_column="__record_id") @@ -2530,8 +2481,8 @@ 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. @@ -2539,8 +2490,8 @@ def test_an_ambiguous_append_never_lets_another_connector_overwrite_its_key( import threading from concurrent.futures import ThreadPoolExecutor - 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 @@ -2565,7 +2516,7 @@ 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: @@ -2581,7 +2532,7 @@ def peer() -> str: appended.set() _ = future.result() 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), @@ -2594,24 +2545,26 @@ 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 + """Review B3: the run's dataset listing is kept at scope entry, so a table that another connector of the run writes from a plain thread is in the next stale report, as main reports it.""" 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()) 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]): assert stale() == [] with ThreadPoolExecutor(1) as threads: for path in reversed(paths): threads.submit( + copy_context().run, second.add_records, path, rows(["key"]), @@ -2670,7 +2623,7 @@ 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 @@ -2706,6 +2659,6 @@ 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) diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 8758e035a..de0dd6362 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 @@ -13,7 +13,7 @@ import json import warnings import weakref -from collections.abc import Callable, Iterable, Iterator +from collections.abc import Iterator from pathlib import Path from typing import Any, cast @@ -35,15 +35,13 @@ 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.errors import RowFailuresWarning, SpiralDBLeaseRequiredError -from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.databases.spiraldb_write_scope import database_writes +from orcapod.errors import RowFailuresWarning, SpiralDBScopeOpenError +from orcapod.pipeline import AsyncPipelineOrchestrator from orcapod.pipeline import node_run from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.side_effects import SideEffectPod, sink_pod @@ -174,15 +172,7 @@ 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"]) - ) - - -def _lease_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 ) @@ -228,8 +218,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 @@ -247,8 +235,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") @@ -257,8 +243,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") @@ -268,10 +254,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] - # The lease is taken at a database's first write (ITL-1900): in node runs, only - # the function's node writes results. - assert len(_lease_tables("r")) == 1 else: on_delta = sorted( [*delta.list_table_paths(), *delta_results.list_table_paths()] @@ -287,7 +269,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") @@ -339,7 +320,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 @@ -351,7 +332,7 @@ 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 when it starts - (the writer lease's observation) serves every stale check (ITL-1899).""" + (the run's catalog) serves every stale check (ITL-1899).""" listings: list[tuple[str, str]] = [] list_tables = spiraldb_connector._list_dataset # pyright: ignore[reportPrivateUsage] @@ -365,7 +346,7 @@ def counted(client: Any, project: str, dataset: str) -> dict[str, str]: 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") @@ -438,7 +419,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() @@ -447,29 +428,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, once, at that write (ITL-1900); 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()) == 2 # the first run's, then the cache write's for path, rows in before.items(): now = spiral_db.get_all_records(path) assert now is not None and rows is not None @@ -585,7 +561,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]: @@ -603,158 +579,10 @@ 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_at_its_first_write( - entry: str, load_only: bool -) -> None: - """The run claims the lease at its first write (ITL-1900): here the cached source - writing its cache when it is checked. It is refused there, with nothing written, - computed or delivered.""" - release = _held_by_another_writer() - job = _job(_database()) - checks = _count_source_checks(job) - with pytest.raises(spiraldb_lease.LeaseBusyError, match="another writer"): - _ = _run(job, entry, load_only=load_only) - assert _database_tables() == [] - assert calls == [] and delivered == [] - # Refused at the source check, the cached source's first write. - assert checks == [None] - # 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: - """Each dataset's lease is taken at its first write (ITL-1900): the cached source - writes its cache on its own dataset, and the run is refused at its first write to - the result database, with nothing written there.""" - release = _held_by_another_writer("r") - job = _job(_database(), result_database=_database("r")) - with pytest.raises(spiraldb_lease.LeaseBusyError): - _ = job.run() - assert [p[-1] for p in _database().list_table_paths()] == ["sdb_v2"] - assert _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() - - -@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) - - -@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) - - -@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") - - def failing(client: Any, lease: Any) -> None: - raise spiraldb_lease.LeaseError("release lost") - - 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__) - - @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="through the connectors of a 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( @@ -766,9 +594,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 @@ -777,51 +604,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()) != [] - # The second run writes nothing, so takes no lease (ITL-1900). - assert len(_lease_tables("d")) == 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( @@ -844,16 +643,8 @@ def failing_once() -> None: pipeline_database=_database("b").at(JOB), cache_mode=CacheMode.LOG ) _ = job.run() - # The retry wrote the old attachment's operator cache, under a lease of its dataset. + # 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"] - # The failed flush wrote nothing, so took no lease (ITL-1900); the retry took one. - assert len(_lease_tables("a")) == 1 - - -def _claim(databases: Iterable[Any]) -> None: - """Claim each database's writer lease, as its first write would (ITL-1900).""" - for database in databases: - database.spiral_claim_writer_lease() def _wrapped(database: Any) -> ExtensionAwareDatabase: @@ -898,115 +689,65 @@ 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()), table=_rows(4)).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"): - # The lease is taken at the first write (ITL-1900): claim it from both. - assert _lease_tables() == [] + 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_claim_writer_lease() - assert len(_lease_tables()) == 1 - held = [c._writable_tables()._lease_check for c in (plain, addressed)] # pyright: ignore[reportPrivateUsage, reportOptionalMemberAccess] + 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] - - -@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() - 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") - database.add_records( - path, - pa.table( - { - "__record_id": pa.array( - [item.encode() for item in ids], pa.large_binary() - ), - "value": [1, 2], - "__data_context": [get_default_context().context_key] * 2, - } - ), - record_id_column="__record_id", - flush=True, - ) - # The lease is claimed at the first write (ITL-1900), inside this count: - # the acquisition reads the previous generation's state (none at first) - # and verifies its claim; the first write does not verify it again so - # soon after (ITL-1901). - assert len(reads) == 1 + count - - # A run that writes nothing takes no lease, so it reads no lease state, from - # opening the scope to closing it. - reads.clear() - with database_writes([first, second], owner="no writes"): - pass - assert reads == [] + assert all(c._writable_tables()._run_state is None for c in (plain, addressed)) # pyright: ignore[reportPrivateUsage, reportOptionalMemberAccess] @pytest.mark.usefixtures("root") @@ -1015,7 +756,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) @@ -1027,15 +768,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] = [] @@ -1051,7 +791,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 @@ -1064,47 +804,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"): - _claim(databases) - 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"): - _claim(databases) - 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( @@ -1117,11 +820,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()) @@ -1135,11 +838,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 @@ -1152,7 +855,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: @@ -1168,10 +870,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: @@ -1196,12 +898,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( @@ -1224,7 +926,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) @@ -1232,89 +934,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) - databases = [_database("d"), _database("r")] - with pytest.raises(KeyboardInterrupt) as raised: - with database_writes(databases, owner="test"): - _claim(databases) - 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)) @@ -1338,7 +977,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) @@ -1349,9 +988,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",)) == [] @@ -1359,12 +998,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: @@ -1401,8 +1040,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: @@ -1423,13 +1062,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",)) == [] @@ -1472,8 +1107,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)) @@ -1507,17 +1142,11 @@ 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`` keeps the last run's save state (review of - de39bbc4c). The lease is claimed at the first write (ITL-1900), inside the run, so - the refusal is a failure of a started run: the advisory row counts (ITL-1043) are - no longer certain and are left out, as after any failed run; the rest is kept. A - held rerun writes nothing and takes no lease, so the operator node is attached - to another dataset, which the run writes and another writer holds.""" +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" @@ -1526,14 +1155,11 @@ def test_a_run_refused_its_lease_keeps_the_last_runs_save_state(root: Path) -> N ) job.save(before) kept = json.loads(before.read_text())["run"] - assert kept.pop("expected_rows") + assert kept["expected_rows"] delivered.clear() - release = _held_by_another_writer("x") - try: - with pytest.raises(spiraldb_lease.LeaseBusyError): + with database_writes([_database("x")]): + with pytest.raises(SpiralDBScopeOpenError): _ = job.run() - finally: - release() job.save(after) assert json.loads(after.read_text())["run"] == kept assert delivered == [] @@ -1544,12 +1170,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: @@ -1558,88 +1184,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_lease.acquire - 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_lease, "acquire", take_then_interrupt) - databases = [_database(dataset) for dataset in datasets] - with pytest.raises(KeyboardInterrupt): - with database_writes(databases, owner="interrupted"): - _claim(databases) - 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") - databases = [_database("d"), _database("r")] - with pytest.raises(KeyboardInterrupt) as raised: - with database_writes(databases, owner="test"): - _claim(databases) - 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() @@ -1655,8 +1217,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: @@ -1681,9 +1243,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] = [] @@ -1705,25 +1267,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 @@ -1773,7 +1332,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.""" @@ -1933,7 +1492,7 @@ def test_a_permanent_result_failure_keeps_the_rows_before_it( """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 @@ -1977,9 +1536,9 @@ def refuse_total_8(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: records = stored.get("pdb_v2") assert (0 if records is None else records.num_rows) == len(kept) assert stored["sdb_v2"].num_rows == 3 - # The failed run released its lease: a recovery run can claim it. - with database_writes([fresh], owner="recovery"): - fresh.spiral_claim_writer_lease() + # A recovery run can open a new scope after the failure. + with database_writes([fresh]): + fresh.spiral_acquire_write_lock() @pytest.mark.usefixtures("root") 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..b2305269e --- /dev/null +++ b/tests/test_databases/test_spiraldb_write_lock.py @@ -0,0 +1,509 @@ +"""Write scope and optional lock behavior on the fake SpiralDB SDK.""" + +from __future__ import annotations + +from concurrent.futures import ThreadPoolExecutor +from contextvars import copy_context +from collections.abc import Callable +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.contexts import get_default_context +from orcapod.core.operators import SelectDataColumns +from orcapod.databases import ( + ConnectorArrowDatabase, + SpiralDBConnector, + spiral_database_identity, +) +from orcapod.databases.spiraldb_write_scope import database_writes +from orcapod.errors import SpiralDBScopeOpenError +from orcapod.invocation import InvocationContext +from orcapod.side_effects import 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: Exception | 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_lock_wraps_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() + _run_side_effect(_context_job(_database(lock=lock), n), 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") + + +def _queue(database: ConnectorArrowDatabase, path: tuple[str, ...], key: bytes) -> None: + 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 + + +def test_listing_failure_falls_back_to_resolving_names( + monkeypatch: pytest.MonkeyPatch, +) -> None: + _run(_job(_database()), "sync") + + def fail_listing(connector: SpiralDBConnector) -> dict[str, str]: + raise TimeoutError("listing timed out") + + monkeypatch.setattr(SpiralDBConnector, "_list_tables_for_scope", 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 From 77ad91a7476606fd06f03881f11dfe2ebefb960b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 02:13:33 -0800 Subject: [PATCH 22/46] docs(spiraldb): document single-writer scopes and optional locks --- changelog.d/ITL-1899.md | 48 +++---- docs/api/databases.md | 4 + docs/api/errors.md | 2 +- docs/concepts/spiraldb-database.md | 135 +++++------------- .../scripts/itl_1844_database_evaluation.py | 66 ++------- 5 files changed, 71 insertions(+), 184 deletions(-) diff --git a/changelog.d/ITL-1899.md b/changelog.d/ITL-1899.md index c67088d52..5e3fb319b 100644 --- a/changelog.d/ITL-1899.md +++ b/changelog.d/ITL-1899.md @@ -1,31 +1,21 @@ ### Changed -- A run on a writable SpiralDB database takes the dataset's writer lease at its first - write to the dataset, not when it starts (ITL-1900). When it starts, the run looks - at the dataset's newest lease (one listing of the dataset, an open of the newest - lease table and a look for the next, about half a second or more on the service). A run that writes nothing (a rerun with nothing new, a `REPLAY` run, a - load-only run) takes no lease. A side-effect node (a `SideEffectPod` node, or a - function node whose pod takes the invocation context) reads its invocation log - without the lease and takes it just before its first delivery or function call; - with nothing to deliver it takes none. -- A second writer is refused at its first write, with nothing written by that write - and nothing delivered: with `LeaseBusyError` when another run holds the lease, and - with the new `LeaseChangedError` (a `LeaseBusyError`) when another writer took the - lease after the run started, so what the run read may be out of date; run again. - The check is per dataset: rows the run wrote to another dataset before the refusal - stay stored. A refusal - reached through a node's commit is raised as the lease error itself, with a note - naming the commit error. -- A writer lease verified when it was taken is not verified again before the run's - first write unless 60 seconds or more passed since (interim, ITL-1901). -- A job saved after a run refused its lease no longer records the advisory stored - row counts (`expected_rows`): the refusal now stops a run that has started, as any - failed run does. -- Writable SpiralDB runs make fewer service calls (ITL-1899). A run lists its - dataset once, when it starts: that listing finds the newest writer lease generation - and is the run's view of the dataset's tables, and the lease is claimed from that - generation without listing again. A run opens no table that its listing shows - absent, and reads back no table it created. A run reads each - table whole once per batch of writes and keeps what it read under its lease (at most - 256 MiB; beyond that the oldest is dropped and read again when needed), instead of - twice per computed row, and identifies each existing table once. +- 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. 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..99c1a7cf0 100644 --- a/docs/api/databases.md +++ b/docs/api/databases.md @@ -29,3 +29,7 @@ the underlying database classes (ITL-1539), so its public form may change. ::: orcapod.databases.PostgreSQLConnector ::: orcapod.databases.SpiralDBConnector + +::: orcapod.databases.WriteLock + +::: orcapod.databases.NoWriteLock diff --git a/docs/api/errors.md b/docs/api/errors.md index 14b42268c..f79928bfd 100644 --- a/docs/api/errors.md +++ b/docs/api/errors.md @@ -134,7 +134,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 3307cf4be..45e7a8a30 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,67 +40,35 @@ 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()`) that writes the dataset holds its **writer -lease** while it writes, and releases it when the run ends, also when it fails. A run -whose database and result database are on one dataset takes one lease. - -The lease is taken at the run's first write, not when the run starts: - -- **When the run starts**, it looks at the dataset's newest lease: one listing of the - dataset (several requests for a dataset of many tables), an open of the newest - listed lease table and a look for the next one, about half a second or more on the - service; nothing is read from the lease. The same listing is the run's view of the - dataset's tables. The run reads the stored tables as it needs them, with no lease. -- **At its first write** to the dataset (a table created or rows appended), the run takes - the lease. A run that writes nothing (a rerun with nothing new, a `REPLAY` run, a - load-only run) takes no lease: only the look at the start. -- **A side-effect node** (a `SideEffectPod` node, or a function node whose pod takes the - invocation context) reads its invocation log without the lease and takes it just - before its first delivery, or its function's first call. With nothing to deliver it - takes no lease. - -The lease is refused, with nothing written by that write, nothing delivered and no -function called, in two cases. Another run holds it: `LeaseBusyError`, naming the -lease's table id and who holds it. Or another writer took the lease after this run -started (and may have written since): `LeaseChangedError`, a `LeaseBusyError`, because -what the run read of that dataset may be out of date; run again. So what a run read of -a dataset is what that dataset held when the run first wrote it. The check is per -dataset: a refused write to one dataset does not undo the run's earlier writes to -another, which stay stored under that dataset's lease. 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 when a cached -source it reads stores new rows. A run takes one lease per dataset of one service, also -when several of its writes start at once on several threads: 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. + +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. + +The scope lists the dataset once and shares the resulting table catalog, stored +key index and recent whole-table reads across its connectors. 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. +`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 job node's `run()` commits a function node's writes in batches (every 100 rows and at the node's end, as `job.run()` does) when every database the node commits to (its @@ -124,41 +92,6 @@ result. No pipeline record ever points to a result that is not stored. A connection resolves a table by name and checks its recorded path when it finds the table. Later operations use the resolved table ID for that connection. -### 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 lease when it takes it, and once more before its first write -when 60 seconds or more passed since (a lease taken at the first write is verified -once). This skip is interim, until ITL-1901 settles how a lease is verified. -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, @@ -182,12 +115,8 @@ read different tables. ## Limits -- Each check of which rows a table holds reads the table's whole key column, and each - read of stored rows reads the whole table, so the cost of a run grows 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). +- The first lookup of stored keys reads the whole key column. A run reuses that + index across flushes and keeps recent whole-table reads within 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..3c8ed7c0e 100644 --- a/docs/dev/scripts/itl_1844_database_evaluation.py +++ b/docs/dev/scripts/itl_1844_database_evaluation.py @@ -8,7 +8,7 @@ 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 scope refused while a scope is open. 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,7 +16,7 @@ ``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 +``itl1844_eval_``. spiral-sdk cannot drop a keyed table, so they stay; the report lists every one. Prints a JSON report. """ @@ -48,11 +48,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 +263,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 +292,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 +344,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 +383,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 +419,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 +431,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 From 9d8430c85ba4d0f46f593a2d8059d1c883ed1606 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 02:32:00 -0800 Subject: [PATCH 23/46] fix(spiraldb): preserve commit dependencies during node writes --- changelog.d/ITL-1502.md | 5 +- docs/concepts/spiraldb-database.md | 10 +-- src/orcapod/databases/_pending_commits.py | 15 +++- .../databases/connector_arrow_database.py | 10 ++- src/orcapod/pipeline/node_run.py | 18 ++--- .../test_spiraldb_writable_mode.py | 69 ++++++++++++++++++- .../test_spiraldb_writable_runs.py | 45 +++++++++++- 7 files changed, 149 insertions(+), 23 deletions(-) diff --git a/changelog.d/ITL-1502.md b/changelog.d/ITL-1502.md index e09abfa91..e3e4d1228 100644 --- a/changelog.d/ITL-1502.md +++ b/changelog.d/ITL-1502.md @@ -4,8 +4,9 @@ lookups, and stale-table discovery across a run, shared by every connector and thread of the run. Connections reuse resolved table IDs. - A job node's `run()` commits a function node's writes every 100 rows and at its - end when every database the node commits to is a writable SpiralDB database or an - `InMemoryArrowDatabase`, at least one of them SpiralDB; any other store keeps the + end for pods without an invocation context when every database the node commits + to is a writable SpiralDB database or an `InMemoryArrowDatabase`, at least one + of them SpiralDB; any other store keeps the per-row commits. A failed batched result append is retried one row at a time, in order, so the results before the failing row stay stored. For a definite failure, the stored rows are those of per-row commits. After an ambiguous reply, diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index fde9b26e6..be98766bb 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -86,12 +86,14 @@ Every writer must respect the dataset's lease. Writes from outside the lease can invalidate the index and are unsupported. A job node's `run()` commits a function node's writes in batches (every 100 rows and -at the node's end, as `job.run()` does) when every database the node commits to (its -pipeline database, its result database, and its ephemeral result database when its -results are ephemeral) is a writable SpiralDB database or an `InMemoryArrowDatabase`, +at the node's end, as `job.run()` does) for pods without an invocation context when +every database the node commits to (its pipeline database, its result database, and +its ephemeral result database when its results are ephemeral) is a writable SpiralDB +database or an `InMemoryArrowDatabase`, and at least one is a writable SpiralDB database. Any other store among them (Delta, SQL, PostgreSQL) keeps the node committing after every row, so another reader of that -store sees each result as soon as it is stored. If a batched result append fails, its +store sees each result as soon as it is stored. A context-taking function node commits +each result before starting the next call. If a batched result append fails, its rows are appended one at a time, in order, up to the first that fails: the results before that row and their pipeline records stay stored, as a node committing after every row keeps them, and the run stops with that row's error. For a definite diff --git a/src/orcapod/databases/_pending_commits.py b/src/orcapod/databases/_pending_commits.py index 29e1ad05d..81a6a5b4d 100644 --- a/src/orcapod/databases/_pending_commits.py +++ b/src/orcapod/databases/_pending_commits.py @@ -221,8 +221,17 @@ def restore(self, key: str, batch: pa.Table, ids: set[bytes]) -> None: self._batches[key] = batch if held is None else pa.concat_tables([batch, held]) self._ids.setdefault(key, set()).update(ids) - def forget(self, key: str, ids: set[bytes]) -> None: - """Forget dependencies for records that are leaving the queue.""" + def forget( + self, key: str, ids: set[bytes], *, keep_schema_check: bool = False + ) -> None: + """Forget dependencies for records leaving the queue. + + Args: + key: The table's record key. + ids: The rows leaving the queue. + keep_schema_check: Keep the check while more rows from a taken batch + are still being retried. + """ with self._receipt_lock: receipts = self._receipts.get(key) if receipts is not None: @@ -235,7 +244,7 @@ def forget(self, key: str, ids: set[bytes]) -> None: _ = evidence.pop(record_id, None) if not evidence: del self._peer_receipts[key] - if key not in self._batches: + if not keep_schema_check and key not in self._batches: self._schema_checks.pop(key, None) guards = self._guards.get(key) if guards is not None: diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 42d6a02f4..4704b2c09 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1311,7 +1311,11 @@ def _flush_by_key(self, record_key: str, *, in_order: bool = False) -> None: def _committed(self, record_key: str, ids: set[bytes]) -> None: """Release committed rows' dependents and tell the receipt peers.""" self._pending_commits.forget(record_key, ids) - self._pending_commits.finish(record_key, committed=True) + self._pending_commits.finish( + record_key, + committed=True, + ids=ids if record_key in self._pending_batches else None, + ) if self._receipt_peers is not None: with _receipt_queue_lock: peers = tuple(self._receipt_peers.items()) @@ -1394,7 +1398,9 @@ def _write_rows_in_order( ids.difference(row_ids[:position]), ) raise - self._pending_commits.forget(record_key, {record_id}) + self._pending_commits.forget( + record_key, {record_id}, keep_schema_check=True + ) self._pending_commits.finish(record_key, committed=True, ids={record_id}) def _write_ready_batch( diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 74843a68a..3828f5ba2 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -636,14 +636,14 @@ def batches_node_commits(node: Any) -> bool: """Whether a node run (a job node's ``run()``, outside ``job.run()``) commits this node's writes in batches; the one place this is decided. - A function job node batches when every database its commits write (its pipeline - database, its result database, and its ephemeral result database when its results - are ephemeral) is either a writable SpiralDB database or an - ``InMemoryArrowDatabase``, and at least one is a writable SpiralDB database. Each - SpiralDB append is a service request, and an in-memory store has no reader outside - the process. Every other node keeps committing after every row: a Delta, SQL, - PostgreSQL or read-only store anywhere among its databases keeps its rows visible - to another reader as each is stored. + A function job node without an invocation context batches when every database + its commits write (its pipeline database, its result database, and its ephemeral + result database when its results are ephemeral) is either a writable SpiralDB + database or an ``InMemoryArrowDatabase``, and at least one is a writable SpiralDB + database. Each SpiralDB append is a service request, and an in-memory store has + no reader outside the process. Every other node keeps committing after every row. + A Delta, SQL, PostgreSQL or read-only store anywhere among its databases keeps + its rows visible to another reader as each is stored. Args: node: A node the run executes. @@ -659,6 +659,8 @@ def batches_node_commits(node: Any) -> bool: if not isinstance(node, FunctionJobNode) or not any_writable_connector(): return False + if node._delivers_side_effects: # pyright: ignore[reportPrivateUsage] # the run sets the commit cadence + return False databases = node._committed_databases() # pyright: ignore[reportPrivateUsage] # the run sets the commit cadence spiral = [bool(writable_connectors([database])) for database in databases] return any(spiral) and all( diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index 994ba0682..ba8964d36 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -2415,6 +2415,73 @@ def with_metadata(table: pa.Table) -> pa.Table: assert seen[0].equals(recorded, check_metadata=True) +@pytest.mark.usefixtures("root") +def test_a_partial_flush_releases_only_the_written_rows() -> None: + """A blocked result and the whole table remain pending after a partial flush.""" + from orcapod.databases._pending_commits import PendingCommit + + db = ConnectorArrowDatabase(writable_connector()) + fresh = ConnectorArrowDatabase(writable_connector()) + prerequisite = PendingCommit() + with db.guard_record(RESULT, b"blocked", prerequisite): + _add(db, rows(["ready", "blocked"])) + ready = db.pending_result(RESULT, b"ready") + blocked = db.pending_result(RESULT, b"blocked") + assert ready is not None and blocked is not None + # The whole-table attempt has no public factory on this backend. + key = db._get_record_key(RESULT) # pyright: ignore[reportPrivateUsage] + whole = db._pending_commits.attempt(key) # pyright: ignore[reportPrivateUsage] + + db.flush_batch(RESULT) + assert ready.committed + assert not blocked.committed + assert not whole.committed + assert (stored := _get(fresh)) is not None + assert stored["__record_id"].to_pylist() == [b"ready"] + + prerequisite.finish(committed=True) + db.flush_batch(RESULT) + assert blocked.committed + assert whole.committed + assert (stored := _get(fresh)) is not None + assert by_id(stored)["__record_id"].to_pylist() == [b"blocked", b"ready"] + + +@pytest.mark.usefixtures("root") +def test_the_schema_guard_checks_each_ordered_retry( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A schema guard can reject the next retry after the first row commits.""" + db = ConnectorArrowDatabase(writable_connector()) + _add(db, rows(["first", "second", "third"])) + first = db.pending_result(RESULT, b"first") + second = db.pending_result(RESULT, b"second") + assert first is not None and second is not None + append = fake.FakeKeyedTable.append + + def refuse_batch(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: + if batch.num_rows > 1: + raise fake.SpiralError("retry each row") + return append(table, batch) + + monkeypatch.setattr(fake.FakeKeyedTable, "append", refuse_batch) + + def check(schema: pa.Schema) -> None: + if first.committed: + raise ValueError("schema guard refused the second retry") + + with ( + db.guard_table_schema(RESULT, check), + pytest.raises(ValueError, match="schema guard refused the second retry"), + ): + db.flush_result_batch_in_order(RESULT, publish_records=True) + assert first.committed + assert not second.committed + fresh = ConnectorArrowDatabase(writable_connector()) + assert (stored := _get(fresh)) is not None + assert stored["__record_id"].to_pylist() == [b"first"] + + # ------------------------------------- review round 7 (PR 692): CodeRabbit, final head @@ -2685,9 +2752,9 @@ async def exercise() -> None: lost.setattr(fake.FakeKeyedTable, "append", lost_reply) with pytest.raises(Exception, match="reply was lost"): await asyncio.to_thread(write, second, paths[0]) + assert stale() == [paths[0]] assert (got := first.get_all_records(paths[0])) is not None assert got.num_rows == 1 - assert stale() == [paths[0]] await asyncio.create_task(asyncio.to_thread(write, third, paths[1])) assert stale() == sorted(paths) diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 9051bfaf4..673273595 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -46,7 +46,7 @@ from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.pipeline import node_run from orcapod.semantic_types.universal_converter import UniversalTypeConverter -from orcapod.side_effects import SideEffectPod, sink_pod +from orcapod.side_effects import InvocationContext, SideEffectPod, sink_pod from orcapod.sources import ArrowTableSource from orcapod.protocols.core_protocols import StreamProtocol from orcapod.types import CacheMode, ColumnConfig @@ -364,6 +364,44 @@ def counted(client: Any, project: str, dataset: str) -> dict[str, str]: assert listings == [("p", "d")] * LEASES[entry] +@pytest.mark.usefixtures("root") +def test_a_context_taking_node_stops_calling_after_a_failed_result_write( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A failed result write stops the run before another external call starts.""" + from orcapod.errors import OrcapodDatabaseWriteError + + invoked: list[int] = [] + + @function_pod(output_keys="sent", ctx_arg="ctx") + def send(x: int, ctx: InvocationContext) -> int: + invoked.append(x) + return x + + append = fake.FakeKeyedTable.append + + def refuse_second_result(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: + record = spiral_database_identity.read_table_identity_metadata( + table.get_metadata() + ) + if record is not None and record.path[-1] == "rdb_v1" and len(invoked) >= 2: + sent_column = next( + column for column in batch.column_names if column.endswith("sent") + ) + if invoked[1] in batch[sent_column].to_pylist(): + raise fake.SpiralError("second result was refused") + return append(table, batch) + + database = _database() + job = PipelineJob(name=JOB, database=database) + with job: + send.pod(_cached(database, _rows()), label="send") + monkeypatch.setattr(fake.FakeKeyedTable, "append", refuse_second_result) + with pytest.raises(OrcapodDatabaseWriteError, match="second result was refused"): + _ = job.nodes["send"].run() + assert len(invoked) == 2 + + @pytest.mark.usefixtures("root") @pytest.mark.parametrize("order", ORDERS) @pytest.mark.parametrize("target", ["combine", "select"]) @@ -1920,8 +1958,9 @@ def refuse_total_8(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: # One batch of three, then one row at a time up to the failing row. batch, *single = attempted assert sorted(batch) == [6, 8, 10] - assert [len(s) for s in single] == [1] * len(single) and single[-1] == [8] - kept = sorted(s[0] for s in single[:-1]) + failure = batch.index(8) + assert single == [[total] for total in batch[: failure + 1]] + kept = sorted(batch[:failure]) fresh = _database() stored = { path[-1]: table From 1ed6dd0b33cdcf2bf39cc39a3804747470662202 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 02:41:19 -0800 Subject: [PATCH 24/46] fix(spiraldb): guard side effects at the write boundary --- scripts/migrate_spiral_schemas.py | 22 ++- src/orcapod/core/cached_function_pod.py | 136 ++++++++++------- src/orcapod/core/data_function.py | 81 ++++++---- src/orcapod/core/nodes/function_node.py | 123 +++++++-------- .../databases/connector_arrow_database.py | 5 + .../databases/extension_aware_database.py | 8 + src/orcapod/databases/spiraldb_tables.py | 9 +- src/orcapod/databases/spiraldb_write_scope.py | 35 +++-- .../protocols/core_protocols/function_pod.py | 21 ++- src/orcapod/protocols/spiraldb_run.py | 42 +++++- src/orcapod/side_effects.py | 127 ++++++++-------- .../test_migrate_spiral_schemas.py | 8 + .../test_spiraldb_writable_mode.py | 5 +- .../test_spiraldb_write_lock.py | 141 +++++++++++++++++- 14 files changed, 512 insertions(+), 251 deletions(-) diff --git a/scripts/migrate_spiral_schemas.py b/scripts/migrate_spiral_schemas.py index e32f4f70c..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(): @@ -425,11 +425,19 @@ def require_unchanged( # Not the connector's listing: it refuses a dataset whose migration was interrupted. listed = _list_dataset(client, project, dataset) - names = sorted( - name - for name in listed.values() - if name != SCHEMA_TABLE and LEASE_TABLE_PATTERN.fullmatch(name) is None - ) + 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 74f9ac24a..a87fde38c 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 @@ -33,6 +34,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, @@ -245,36 +247,47 @@ 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, - ) - # 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 + with ( + invocation_write_database(self.result_database) + if self.ctx_arg_name is not None + else nullcontext() + ): + tag, output = self._function_pod.process_data( + tag, data, logger=logger, run_id=run_id ) - if stored is not None: - module_logger.info( - "A result for this input was stored meanwhile; using it" + 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( @@ -316,36 +329,47 @@ 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, - ) - # 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 + with ( + invocation_write_database(self.result_database) + if self.ctx_arg_name is not None + else nullcontext() + ): + tag, output = await self._function_pod.async_process_data( + tag, data, logger=logger, run_id=run_id ) - if stored is not None: - module_logger.info( - "A result for this input was stored meanwhile; using it" + 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( diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 28600be21..ff71927ea 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 @@ -41,6 +41,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 +1292,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( @@ -1320,6 +1325,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( @@ -1356,6 +1362,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: @@ -1381,6 +1388,7 @@ async def direct_async_call( 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) @@ -1635,6 +1643,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 +1728,26 @@ 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() + ): + 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, + ) + 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,28 @@ 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, - ) - output_data = output_data.with_meta_columns( - **{self.RESULT_COMPUTED_FLAG: True} + with ( + invocation_write_database(self.result_database) + if self._takes_context and not skip_cache_insert + else nullcontext() + ): + 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, + ) + 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/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 3a8adaad9..e8aa42a8c 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -122,10 +122,9 @@ ) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.hashing_protocols import IdentityWalkProtocol -from orcapod.core.pod_result_databases import pod_result_databases from orcapod.protocols.spiraldb_run import ( InOrderResultFlushProtocol, - SpiralDBRunLookupProtocol, + invocation_write_database, ) from orcapod.protocols.observability_protocols import ( DataExecutionLoggerProtocol, @@ -1626,21 +1625,11 @@ def _begin_run(self) -> None: self._current_tables_checked = False self._account_for_stale_tables() - def _acquire_write_locks(self) -> None: - """Acquire the run's write locks before calling a context-taking function - for an uncached row.""" - databases = [self._pipeline_database] - databases.extend( - pod.result_database - for pod in (self._cached_function_pod, self._ephemeral_cached_pod) - if pod is not None - ) - # The result stores of the pods and data functions it wraps too: they are - # written after the function returns (``pod_result_databases``). - databases.extend(pod_result_databases(self)) - for database in databases: - if isinstance(database, SpiralDBRunLookupProtocol): - database.spiral_acquire_write_lock() + 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). @@ -3048,9 +3037,6 @@ def _process_data_internal( if isinstance(data, EmptyData): return self._empty_data_cache_hit(tag, data, instance_id) - if self._delivers_side_effects: - # Acquire the write lock before the function can be called. - self._acquire_write_locks() self._preflight_pipeline_write_schema() ephemeral_result = bool(self._node_config.is_result_ephemeral) @@ -3067,12 +3053,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( + 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( @@ -3091,12 +3078,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( + 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( @@ -3113,9 +3101,10 @@ 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(): + tag_out, output_data = self._function_pod.process_data( + 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 @@ -3196,9 +3185,6 @@ async def _async_process_data_internal( if isinstance(data, EmptyData): return self._empty_data_cache_hit(tag, data, instance_id) - if self._delivers_side_effects: - # Acquire the write lock before the function can be called. - self._acquire_write_locks() self._preflight_pipeline_write_schema() ephemeral_result = bool(self._node_config.is_result_ephemeral) @@ -3215,12 +3201,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( + tag, function_input(self._function_pod, data), logger=logger + ) if output_data is not None: result_computed = bool( output_data.get_meta_value( @@ -3238,9 +3225,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( + tag, function_input(self._function_pod, data), logger=logger + ) if output_data is not None: result_computed = bool( output_data.get_meta_value( @@ -3256,9 +3247,10 @@ 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(): + tag_out, output_data = await self._function_pod.async_process_data( + tag, data, logger=logger + ) 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 @@ -4949,10 +4941,6 @@ async def route_inputs() -> None: (stamped_tag, found) ) continue - if self._delivers_side_effects: - # Before the function can be called for the - # row, as on the sync path. - self._acquire_write_locks() # The function takes the row without its # fall-through columns (ITL-1023). await compute_channel.writer.send( @@ -5114,18 +5102,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( + [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: diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 2f9344a00..b6b727197 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1552,6 +1552,11 @@ def spiral_records_match_context( pending is None or tables.data_context(pending) == current ) + 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() 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: diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index 9df1c80b5..c205f40f6 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,12 @@ def spiral_completion_lookup( return self._db.spiral_completion_lookup(record_path) return None + 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): diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index 780e1bc47..4ffd6bdee 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -1177,11 +1177,10 @@ def attach_run(self, state: RunState) -> None: self._attached_run = state def acquire_write_lock(self) -> None: - """Acquire the scope's write lock now, as a first write would; nothing outside - a scope or once acquired. - - """ - if (state := self._run_state) is not None: + """Acquire the scope's write lock before an invocation.""" + with self.write_scope(): + state = self._run_state + assert state is not None state.acquire_lock() def detach_run(self, state: RunState) -> None: diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index 69ce9e34b..14043812e 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -32,6 +32,7 @@ import contextlib import threading +from asyncio import CancelledError from collections.abc import Iterable, Iterator from typing import TYPE_CHECKING @@ -153,20 +154,24 @@ def _connector_scopes(writable: list[SpiralDBConnector]) -> Iterator[None]: def _refusal_behind( error: BaseException, scopes: list[_DatasetScope] -) -> Exception | None: - """The error a write lock of ``scopes`` raised that ``error`` is or was raised - from, if any; never for an interruption.""" - if not isinstance(error, Exception): - return None +) -> BaseException | None: + """Recover a provider error behind a wrapper or a task group's exception.""" refusals = [scope.refused for scope in scopes if scope.refused is not None] - seen: list[BaseException] = [] - current: BaseException | None = error - while current is not None and not any(current is s for s in seen): - for refusal in refusals: - if current is refusal: - return refusal - seen.append(current) - current = current.__cause__ or current.__context__ + if not refusals or not isinstance(error, Exception): + return None + seen: set[int] = set() + pending: list[BaseException] = [error] + while pending: + current = pending.pop() + if id(current) in seen: + continue + seen.add(id(current)) + if any(current is refusal for refusal in refusals): + return current + if isinstance(current, BaseExceptionGroup): + pending.extend(reversed(current.exceptions)) + if (cause := current.__cause__ or current.__context__) is not None: + pending.append(cause) return None @@ -192,7 +197,7 @@ def __init__( self._handle: WriteLockHandle | None = None self._holding: list[SpiralDBTables] = [] self._registered = False - self.refused: Exception | None = None + self.refused: BaseException | None = None self.state = RunState(self._acquire) def open(self, connectors: list[SpiralDBConnector]) -> None: @@ -232,7 +237,7 @@ def _acquire(self) -> None: return try: self._handle = self._lock.acquire(self._project_id, self._dataset) - except Exception as refusal: + 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. 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 4584a9ccc..b12d7f475 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 @@ -20,12 +22,48 @@ 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. Do nothing outside a write scope.""" + context-taking function.""" ... +_invocation_databases: ContextVar[tuple[SpiralDBRunLookupProtocol, ...]] = ContextVar( + "spiraldb_invocation_databases", default=() +) + + +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): + 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() + + @runtime_checkable class InOrderResultFlushProtocol(Protocol): """A store that can commit a failed result batch's rows one at a time.""" diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 742bd3a93..458bdb344 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -64,7 +64,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 @@ -1299,29 +1302,30 @@ 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, - before_delivery=self._acquire_write_lock, - ) - 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 @@ -1578,43 +1582,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, - 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) + 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_databases/test_migrate_spiral_schemas.py b/tests/test_databases/test_migrate_spiral_schemas.py index 50988fecc..aae3c2926 100644 --- a/tests/test_databases/test_migrate_spiral_schemas.py +++ b/tests/test_databases/test_migrate_spiral_schemas.py @@ -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_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index 1d85b32c9..f03525f2a 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -2489,6 +2489,7 @@ def test_an_ambiguous_append_never_lets_another_connector_overwrite_its_key( """ import threading from concurrent.futures import ThreadPoolExecutor + from contextvars import copy_context first = ConnectorArrowDatabase(writable_connector()) second = ConnectorArrowDatabase(writable_connector()) @@ -2521,7 +2522,7 @@ def peer() -> str: _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: @@ -2530,7 +2531,7 @@ def peer() -> str: first.flush() finally: appended.set() - _ = future.result() + assert future.result() == "refused" second.flush() got = _get(ConnectorArrowDatabase(writable_connector())) assert got is not None diff --git a/tests/test_databases/test_spiraldb_write_lock.py b/tests/test_databases/test_spiraldb_write_lock.py index b2305269e..41e79ea9e 100644 --- a/tests/test_databases/test_spiraldb_write_lock.py +++ b/tests/test_databases/test_spiraldb_write_lock.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio from concurrent.futures import ThreadPoolExecutor from contextvars import copy_context from collections.abc import Callable @@ -21,7 +22,7 @@ from orcapod.databases.spiraldb_write_scope import database_writes from orcapod.errors import SpiralDBScopeOpenError from orcapod.invocation import InvocationContext -from orcapod.side_effects import SideEffectPod, sink_pod +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 @@ -51,7 +52,7 @@ class RecordingLock: def __init__( self, events: list[str], - refusal: Exception | None = None, + refusal: BaseException | None = None, release_error: BaseException | None = None, ) -> None: self.events = events @@ -294,12 +295,20 @@ def read(table: fake.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any: @pytest.mark.parametrize("entry", ENTRIES) -def test_lock_wraps_creates_and_appends(entry: str, sdk_events: list[str]) -> None: +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() - _run_side_effect(_context_job(_database(lock=lock), n), entry) + 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" @@ -507,3 +516,127 @@ def test_first_writes_in_one_scope_share_one_handle() -> None: 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") + ) From b0eada7bedbf472b63ad44ce85fbdf5cac031014 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 02:59:43 -0800 Subject: [PATCH 25/46] fix(spiraldb): share scopes across cached invocations --- changelog.d/ITL-1502.md | 2 +- docs/concepts/spiraldb-database.md | 3 +- src/orcapod/core/function_pod.py | 27 +++--- src/orcapod/core/pod_result_databases.py | 14 +-- .../databases/connector_arrow_database.py | 4 +- src/orcapod/databases/spiraldb_connector.py | 2 +- src/orcapod/databases/spiraldb_tables.py | 14 +-- src/orcapod/databases/spiraldb_write_scope.py | 80 ++++++++++++++--- .../test_spiraldb_write_lock.py | 88 +++++++++++++++++++ 9 files changed, 196 insertions(+), 38 deletions(-) diff --git a/changelog.d/ITL-1502.md b/changelog.d/ITL-1502.md index e3e4d1228..5d53a88f4 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. - A job node's `run()` commits a function node's writes every 100 rows and at its diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index 31c1bea30..79ac52f11 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -50,7 +50,8 @@ 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. +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 and shares the resulting table catalog, stored key index and recent whole-table reads across its connectors. A commit updates diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 1c4dd7087..30444bbbc 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -37,6 +37,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, @@ -746,6 +747,7 @@ 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. """ + from orcapod.databases.spiraldb_write_scope import invocation_writes from orcapod.pipeline.observer import NoOpObserver try: @@ -796,18 +798,19 @@ 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 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() diff --git a/src/orcapod/core/pod_result_databases.py b/src/orcapod/core/pod_result_databases.py index 1afec9ca8..c4fdbd267 100644 --- a/src/orcapod/core/pod_result_databases.py +++ b/src/orcapod/core/pod_result_databases.py @@ -1,7 +1,6 @@ """The result databases a function node's own pods write on a cache miss. -A leaf module, read by the run's write scope (``pipeline.node_run``) and by a function -node that acquires its write locks before its function is called. +Used for both a job's run scope and a standalone pod execution. """ from __future__ import annotations @@ -18,11 +17,16 @@ def pod_result_databases(node: Any) -> list[Any]: # pyright: ignore[reportExpli (``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. """ - found: list[Any] = [] - pods: list[Any] = [ + 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.""" + found: list[object] = [] + pods = list(roots) visited: set[int] = set() while pods: pod = pods.pop(0) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index d28c477f4..853abd4b1 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1561,7 +1561,9 @@ def spiral_records_match_context( 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() if tables is not None else nullcontext() + 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.""" diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 8db8ae6d6..d176c42fd 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -1134,7 +1134,7 @@ def _new_tables(self) -> SpiralDBTables: ), lambda: _list_dataset(client, project_id, dataset), lambda doing: _service_call(f"{doing} of {project_id}/{dataset}", health), - lambda: one_call_scope(connector), + lambda invocation: one_call_scope(connector, invocation=invocation), ) @property diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index 4ffd6bdee..239e7d170 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -359,8 +359,8 @@ class SpiralDBTables: 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 of these tables alone, for a write outside a - run (``spiraldb_write_scope``). + 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__( @@ -373,7 +373,7 @@ def __init__( create_table: Callable[[str, pa.Schema], _KeyedTable], list_tables: Callable[[], dict[str, str]], service_call: Callable[[str], AbstractContextManager[None]], - one_call_scope: Callable[[], AbstractContextManager[None]], + one_call_scope: Callable[[bool], AbstractContextManager[None]], ) -> None: self._sdk: Any = sdk # pyright: ignore[reportExplicitAny] self._project_id: str = project_id @@ -384,7 +384,7 @@ def __init__( 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[[], AbstractContextManager[None]] = ( + self._one_call_scope: Callable[[bool], AbstractContextManager[None]] = ( one_call_scope ) self._paths: dict[str, tuple[str, ...]] = {} @@ -1155,12 +1155,12 @@ def _run_state(self) -> RunState | None: return state if state in active_run_states.get() else None @contextmanager - def write_scope(self) -> Iterator[None]: + 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(): + with self._one_call_scope(invocation): yield def attach_run(self, state: RunState) -> None: @@ -1178,7 +1178,7 @@ def attach_run(self, state: RunState) -> None: def acquire_write_lock(self) -> None: """Acquire the scope's write lock before an invocation.""" - with self.write_scope(): + with self.write_scope(invocation=True): state = self._run_state assert state is not None state.acquire_lock() diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index 14043812e..765fa1e2f 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -14,10 +14,10 @@ the catalog (one listing of the dataset when the scope opens) 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: two would each hold their own key -index, and could store one key twice with no other writer involved. A second scope of a -dataset that is open raises ``SpiralDBScopeOpenError`` before it can read or write -that dataset. +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 @@ -34,6 +34,7 @@ import threading from asyncio import CancelledError from collections.abc import Iterable, Iterator +from contextvars import ContextVar from typing import TYPE_CHECKING from orcapod.databases.spiraldb_tables import RunState, active_run_states @@ -50,6 +51,12 @@ _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.""" + + def writable_connectors(databases: Iterable[object]) -> list[SpiralDBConnector]: """The distinct writable SpiralDB connectors under ``databases``, in the order met. @@ -106,37 +113,57 @@ def database_writes(databases: Iterable[object]) -> Iterator[None]: @contextlib.contextmanager -def one_call_scope(connector: SpiralDBConnector) -> Iterator[None]: - """A write scope of one connector's dataset for one call outside a run: attached - to that connector only, its lock acquired at the call's first write and released - after, and nothing it read kept past the call. +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. + invocation: Whether the call may join its execution's scope. Raises: SpiralDBScopeOpenError: If a scope of the dataset is open in this process. Exception: Whatever its ``WriteLock`` raises, unchanged. """ - with _connector_scopes([connector]): + with _connector_scopes([connector], join=invocation): yield +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) + + @contextlib.contextmanager -def _connector_scopes(writable: list[SpiralDBConnector]) -> Iterator[None]: +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) token = active_run_states.set(active_run_states.get() | {s.state for s in scopes}) try: try: @@ -150,6 +177,7 @@ def _connector_scopes(writable: list[SpiralDBConnector]) -> Iterator[None]: _close_all(scopes, None) finally: active_run_states.reset(token) + _invocation_scopes.reset(invocation_token) def _refusal_behind( @@ -197,6 +225,7 @@ def __init__( 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) @@ -219,6 +248,35 @@ def open(self, connectors: list[SpiralDBConnector]) -> None: self.state.start_catalog(listing) 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).""" @@ -251,6 +309,8 @@ def close(self) -> list[BaseException]: The failures, in order. """ failures: list[BaseException] = [] + with self.state.lock: + self._accepting_joins = False for tables in self._holding: try: tables.detach_run(self.state) diff --git a/tests/test_databases/test_spiraldb_write_lock.py b/tests/test_databases/test_spiraldb_write_lock.py index 41e79ea9e..032745476 100644 --- a/tests/test_databases/test_spiraldb_write_lock.py +++ b/tests/test_databases/test_spiraldb_write_lock.py @@ -12,6 +12,7 @@ import pytest from orcapod import PipelineJob, function_pod +from orcapod.channels import Channel from orcapod.contexts import get_default_context from orcapod.core.operators import SelectDataColumns from orcapod.databases import ( @@ -22,6 +23,7 @@ from orcapod.databases.spiraldb_write_scope import database_writes from orcapod.errors import SpiralDBScopeOpenError from orcapod.invocation import InvocationContext +from orcapod.protocols.core_protocols import DataProtocol, TagProtocol from orcapod.side_effects import SideEffectJobNode, SideEffectPod, sink_pod from orcapod.sources import ArrowTableSource from orcapod.types import CacheMode, NodeConfig @@ -640,3 +642,89 @@ def act(x: int, ctx: InvocationContext) -> int: < 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("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"] From b2449867aa76a018ece37b10ae957bbedf79a07d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 03:07:58 -0800 Subject: [PATCH 26/46] perf: build SpiralDB key sets on demand --- src/orcapod/databases/spiraldb_tables.py | 83 +++++++------ tests/test_databases/test_fake_spiral_sdk.py | 1 + .../test_spiraldb_round_trips.py | 110 +++++++++++++----- .../test_spiraldb_writable_mode.py | 6 + .../test_spiraldb_write_lock.py | 1 + 5 files changed, 141 insertions(+), 60 deletions(-) diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index 239e7d170..213530347 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -136,8 +136,9 @@ class RunState: Attributes: 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. @@ -160,7 +161,9 @@ class RunState: 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 commits: int = 0 @@ -285,13 +288,16 @@ def _table(self) -> _KeyedTable: @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._table().key_columns def schema(self) -> pa.Schema: + """Return the schema, opening the snapshot on first use.""" return self._table().schema() def get_metadata(self) -> dict[str, bytes]: @@ -849,6 +855,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() @@ -1005,7 +1012,7 @@ def scan(self, table_name: str) -> Iterator[pa.RecordBatch]: 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, and its keys, for the run, + """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: @@ -1028,8 +1035,6 @@ def _keep_read(self, table_name: str, table_id: str, stored: pa.Table) -> None: break total -= kept.pop(oldest).nbytes kept[table_id] = stored - if table_id not in run.keys_by_table: - run.keys_by_table[table_id] = _keys_of(stored) def existing_record_ids( self, table_name: str, ids: Collection[bytes] @@ -1099,13 +1104,7 @@ def holds_record_id(self, table_name: str, record_id: bytes) -> bool | None: table_id = run.table_ids[table_name] if table_id is None: return False - held = run.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)) - run.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 @@ -1114,8 +1113,9 @@ def _held_ids( 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 a snapshot taken under the scope's lock: ``table`` itself when the - caller opened it under that lock (``fresh``), a newly opened one otherwise. + 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. @@ -1131,21 +1131,36 @@ def _held_ids( return self._scan_keys(table).intersection(ids) table_id = str(table.resource_id) with run.lock: - held = run.keys_by_table.get(table_id) - if held is None: - # The run-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) - run.keys_by_table[table_id] = held - return held.intersection(ids) + 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 _keys_of(stored) + return _keys_of(stored.column(codec.KEY_COLUMN)) # ── writing ────────────────────────────────────────────────────────────── @@ -1504,7 +1519,12 @@ def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: raise finally: run.commits += 1 - run.keys_by_table.setdefault(found.table_id, set()).update(_ids(encoded)) + 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: @@ -1596,14 +1616,9 @@ def _holds_rows( return keys.num_rows > 0 -def _keys_of(stored: pa.Table) -> set[bytes]: - """Every key of rows read from a database table.""" - return set( - cast( - "list[bytes]", - stored.column(codec.KEY_COLUMN).cast(pa.large_binary()).to_pylist(), - ) - ) +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]: 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_spiraldb_round_trips.py b/tests/test_databases/test_spiraldb_round_trips.py index d1a2edc2a..32bfac51f 100644 --- a/tests/test_databases/test_spiraldb_round_trips.py +++ b/tests/test_databases/test_spiraldb_round_trips.py @@ -55,6 +55,7 @@ class Call: def _name(table: fake.FakeKeyedTable) -> str: + """Return the name of a fake table from its listing record.""" return table._table["name"] # pyright: ignore[reportPrivateUsage] @@ -64,9 +65,11 @@ def sdk_calls(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[Call]]: 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: @@ -102,6 +105,7 @@ def scanned( *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" @@ -118,6 +122,7 @@ def scanned( listing = spiraldb_connector._list_dataset # pyright: ignore[reportPrivateUsage] def listed(client: Any, project: str, dataset: str) -> dict[str, str]: # pyright: ignore[reportExplicitAny] + """Record a dataset listing before calling the service.""" calls.append(Call("listing", "")) return listing(client, project, dataset) @@ -126,10 +131,12 @@ def listed(client: Any, project: str, dataset: str) -> dict[str, str]: # pyrigh 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() @@ -197,6 +204,17 @@ def test_new_rows_read_each_table_whole_once_per_batch_of_writes( 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 @@ -204,16 +222,8 @@ def test_kept_rows_are_what_a_fresh_read_gives() -> None: db, other = _database(), _database() path = ("fn", "rdb_v1") - def rows(*ids: str) -> pa.Table: - 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), - } - ) - 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") @@ -221,16 +231,19 @@ def fresh() -> list[bytes]: 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, rows("a"), record_id_column="__record_id", flush=True) + 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, rows("b"), record_id_column="__record_id", flush=True) + 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, rows("c"), record_id_column="__record_id", flush=True) + 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"] @@ -240,28 +253,73 @@ def test_rows_read_from_a_snapshot_older_than_an_append_are_not_kept( ) -> 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("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") - first = pa.table( - { - "__record_id": pa.array([b"a"], pa.large_binary()), - "x": pa.array([1], pa.int64()), - "__data_context": ["std:v1:default"], - } - ) + if not new_table: + db.add_records(path, _key_rows("a"), record_id_column="__record_id", flush=True) with database_writes([db]): - db.add_records(path, first, record_id_column="__record_id", flush=True) tables = db._spiral # pyright: ignore[reportPrivateUsage] assert isinstance(tables, SpiralDBTables) state = tables._run_state # pyright: ignore[reportPrivateUsage] assert isinstance(state, RunState) - state.rows_by_table.clear() + 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) - with tables.operation(): - _ = tables.has_table(name) - state.commits += 2 # an append of the run committed meanwhile - assert len(list(tables.scan(name))) == 1 - assert state.rows_by_table == {} + 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 ─────────────────────────────────────── diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index c09a1aab5..916219fda 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -717,6 +717,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( @@ -1392,6 +1393,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") @@ -2324,6 +2326,7 @@ def test_a_table_left_empty_by_a_failed_first_write_is_not_listed( def failing( self: SpiralDBTables, table: Any, found: Any, encoded: pa.Table ) -> None: + """Fail before calling the service to append any rows.""" raise RuntimeError("the append failed") with monkeypatch.context() as patched: @@ -2426,6 +2429,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) @@ -2565,6 +2569,7 @@ def test_an_ambiguous_append_never_lets_another_connector_overwrite_its_key( check = SpiralDBTables.existing_record_ids def lost_reply(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: + """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") @@ -2697,6 +2702,7 @@ def test_an_ambiguous_first_append_is_reported_stale_at_once( append = fake.FakeKeyedTable.append def lost_reply(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: + """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") diff --git a/tests/test_databases/test_spiraldb_write_lock.py b/tests/test_databases/test_spiraldb_write_lock.py index 032745476..cb811d0b4 100644 --- a/tests/test_databases/test_spiraldb_write_lock.py +++ b/tests/test_databases/test_spiraldb_write_lock.py @@ -396,6 +396,7 @@ def act(x: int, ctx: InvocationContext) -> int: 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( From 22d9d02d7863e64f2ed890c26acb09b445de3ed8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 03:16:14 -0800 Subject: [PATCH 27/46] fix: isolate standalone SpiralDB executions --- docs/concepts/spiraldb-database.md | 4 +- src/orcapod/core/cached_function_pod.py | 29 ++-- src/orcapod/core/function_pod.py | 134 ++++++++++++++---- src/orcapod/core/nodes/function_node.py | 38 +++-- src/orcapod/databases/spiraldb_connector.py | 12 -- src/orcapod/databases/spiraldb_tables.py | 32 +++-- src/orcapod/databases/spiraldb_write_scope.py | 46 ++++-- src/orcapod/pipeline/node_run.py | 27 +++- src/orcapod/protocols/spiraldb_run.py | 10 ++ .../test_spiraldb_round_trips.py | 2 +- .../test_spiraldb_writable_mode.py | 4 +- .../test_spiraldb_writable_runs.py | 2 +- .../test_spiraldb_write_lock.py | 101 ++++++++++++- 13 files changed, 348 insertions(+), 93 deletions(-) diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index 79ac52f11..d2e778955 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -53,8 +53,8 @@ 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 and shares the resulting table catalog, stored -key index and recent whole-table reads across its connectors. A commit updates +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. diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py index a87fde38c..a18ee00d6 100644 --- a/src/orcapod/core/cached_function_pod.py +++ b/src/orcapod/core/cached_function_pod.py @@ -15,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, @@ -215,7 +216,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, @@ -252,9 +253,13 @@ def process_data( if self.ctx_arg_name is not None else nullcontext() ): - tag, output = self._function_pod.process_data( - tag, data, logger=logger, run_id=run_id + 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, output = process(tag, data, logger=logger, run_id=run_id) if output is not None: pf = self._function_pod.data_function var_dg = Datagram( @@ -290,7 +295,7 @@ def process_data( ) return tag, output - async def async_process_data( + async def _async_process_data( self, tag: TagProtocol, data: DataProtocol, @@ -334,9 +339,13 @@ async def _async_compute_and_store( if self.ctx_arg_name is not None else nullcontext() ): - tag, output = await self._function_pod.async_process_data( - tag, data, logger=logger, run_id=run_id + 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, 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( @@ -384,7 +393,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. @@ -400,14 +409,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: @@ -527,7 +536,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/function_pod.py b/src/orcapod/core/function_pod.py index 30444bbbc..861990d3e 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -13,6 +13,7 @@ Iterator, Sequence, ) +from contextlib import AbstractContextManager from functools import update_wrapper, wraps from typing import TYPE_CHECKING, Any, Literal, Protocol, cast @@ -389,6 +390,18 @@ def process_data( *, logger: DataExecutionLoggerProtocol | None = None, run_id: str | None = None, + ) -> tuple[TagProtocol, DataProtocol | None]: + """Process one row as an independent execution.""" + with self._standalone_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. @@ -426,6 +439,42 @@ async def async_process_data( *, logger: DataExecutionLoggerProtocol | None = None, run_id: str | None = None, + ) -> tuple[TagProtocol, DataProtocol | None]: + """Process one async row as an independent execution.""" + with self._standalone_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)) + + @property + def _row_processor( + self, + ) -> Callable[..., tuple[TagProtocol, DataProtocol | None]]: + """Use a custom row processor when the pod overrides the public method.""" + if type(self).process_data is not _FunctionPodBase.process_data: + return self.process_data + return self._process_data + + @property + def _async_row_processor(self) -> AsyncRowInvoker: + """Use a custom async row processor when the pod overrides the public method.""" + if type(self).async_process_data is not _FunctionPodBase.async_process_data: + return self.async_process_data + return self._async_process_data + + 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``. @@ -583,14 +632,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: @@ -649,7 +698,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 ) @@ -658,7 +707,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: @@ -747,6 +796,28 @@ 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 @@ -798,7 +869,11 @@ async def process_one(tag: TagProtocol, data: DataProtocol) -> None: if sem is not None: sem.release() - with invocation_writes(result_databases_of_pods(self)): + 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]: @@ -1508,6 +1583,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]]: @@ -1551,7 +1632,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. @@ -1600,12 +1683,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[ @@ -1614,23 +1699,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)) @@ -2370,7 +2456,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, @@ -2378,12 +2464,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, @@ -2391,7 +2477,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 e8aa42a8c..a9cd38a72 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -41,6 +41,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, @@ -3054,7 +3055,7 @@ def _process_data_internal( tag_out = tag else: with self._invocation_write_database(): - tag_out, output_data = self._ephemeral_cached_pod.process_data( + 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, @@ -3079,7 +3080,7 @@ def _process_data_internal( ) elif self._cached_function_pod is not None: with self._invocation_write_database(): - tag_out, output_data = self._cached_function_pod.process_data( + 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, @@ -3102,9 +3103,13 @@ def _process_data_internal( ) else: with self._invocation_write_database(): - tag_out, output_data = self._function_pod.process_data( - tag, data, logger=logger, run_id=run_id + 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 @@ -3205,7 +3210,7 @@ async def _async_process_data_internal( ( tag_out, output_data, - ) = await self._ephemeral_cached_pod.async_process_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: @@ -3229,7 +3234,7 @@ async def _async_process_data_internal( ( tag_out, output_data, - ) = await self._cached_function_pod.async_process_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: @@ -3248,8 +3253,14 @@ async def _async_process_data_internal( ) else: with self._invocation_write_database(): - tag_out, output_data = await self._function_pod.async_process_data( - tag, data, logger=logger + 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: @@ -5106,7 +5117,7 @@ def create_data_logger(self, tag: Any, data: Any) -> Any: async with asyncio.TaskGroup() as tg: tg.create_task(route_inputs()) tg.create_task( - execution_pod.async_execute( + 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. @@ -5128,7 +5139,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/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index d176c42fd..ad6031c7c 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -1176,18 +1176,6 @@ def _write_scope_key(self) -> tuple[str, str, str]: self._require_open() return (_service_address(self._client), self._project_id, self._dataset) - def _list_tables_for_scope(self) -> dict[str, str]: - """List the dataset's tables (names by table id) once, for a write scope's - catalog (``spiraldb_write_scope``). - - Raises: - RuntimeError: If this connector has been closed. - """ - self._require_open() - project_id, dataset = self._project_id, self._dataset - with _service_call(f"list the tables of {project_id}/{dataset}", self._health): - return _list_dataset(self._client, project_id, dataset) - def _refuse_if_writable(self) -> None: """Refuse an operation on raw tables of a writable connector.""" if self._writable: diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index 213530347..78e1b32c5 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -142,9 +142,10 @@ class RunState: 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 when the scope opened (or at its first - listing), 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 scope's connectors made. @@ -166,16 +167,25 @@ class RunState: ) table_ids: dict[str, str | None] = field(default_factory=dict) catalog: _Catalog | None = None + catalog_attempted: bool = False commits: int = 0 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 start_catalog(self, names: dict[str, str]) -> None: - """Take a listing of the dataset's tables (names by table id), made when the - scope opened, as its catalog (ITL-1899).""" + 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: - self.catalog = _Catalog(dict(names)) + 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, @@ -184,6 +194,7 @@ def forget_reads(self) -> None: 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() @@ -649,6 +660,8 @@ def _judgment(self, table_name: str) -> _Judgment: if judged is not None and table_name in judged: return judged[table_name] 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 run is None else run.commits with self._about(table_name): @@ -816,9 +829,8 @@ def table_paths( else: # 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 run.catalog is None: - run.catalog = _Catalog(self._list_dataset()) - catalog = run.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) diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index 765fa1e2f..75e376d49 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -11,7 +11,7 @@ ``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 when the scope opens) and the kept reads. It is +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 @@ -40,6 +40,7 @@ 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 @@ -56,6 +57,11 @@ ) """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]: """The distinct writable SpiralDB connectors under ``databases``, in the order met. @@ -82,11 +88,13 @@ def writable_connectors(databases: Iterable[object]) -> list[SpiralDBConnector]: @contextlib.contextmanager -def database_writes(databases: Iterable[object]) -> Iterator[None]: +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 when its scope opens (the scope's catalog; a listing + 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 @@ -101,6 +109,7 @@ def database_writes(databases: Iterable[object]) -> Iterator[None]: Args: databases: The databases the run may write. Nothing happens when none is a writable SpiralDB database. + source_streams: Live pod streams the job delegates to for its source rows. Raises: SpiralDBScopeOpenError: If a scope of one of the datasets is open in this @@ -108,8 +117,21 @@ def database_writes(databases: Iterable[object]) -> Iterator[None]: Exception: Whatever a ``WriteLock`` raises, unchanged; nothing was written to that dataset after it. """ - with _connector_scopes(writable_connectors(databases)): - yield + token = _source_streams.set(frozenset(map(id, source_streams))) + try: + 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) @contextlib.contextmanager @@ -164,7 +186,10 @@ def _connector_scopes( yield return invocation_token = _invocation_scopes.set(inherited | owned) - token = active_run_states.set(active_run_states.get() | {s.state for s in scopes}) + states = frozenset(s.state for s in scopes) + if join: + states |= active_run_states.get() + token = active_run_states.set(states) try: try: yield @@ -230,7 +255,7 @@ def __init__( self.state = RunState(self._acquire) def open(self, connectors: list[SpiralDBConnector]) -> None: - """Reserve the dataset, seed the catalog and attach each tables object.""" + """Reserve the dataset and attach each tables object.""" with _open_scopes_lock: if self._reservation in _open_scopes: raise SpiralDBScopeOpenError( @@ -239,13 +264,6 @@ def open(self, connectors: list[SpiralDBConnector]) -> None: ) _open_scopes.add(self._reservation) self._registered = True - try: - # The scope's view of the dataset's tables: one listing (ITL-1899). - listing = connectors[0]._list_tables_for_scope() # pyright: ignore[reportPrivateUsage] # scopes are opened by this module only - except Exception: # noqa: BLE001 # without a catalog, tables are found by name - listing = None - if listing is not None: - self.state.start_catalog(listing) for connector in connectors: self._attach(_tables(connector)) self._accepting_joins = True diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index b6183c093..56e49fc97 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -264,7 +264,9 @@ def run_sources(streams: Iterable[Any]) -> list[Any]: 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 = None +) -> list[Any]: """The databases written by what feeds ``streams`` from outside the job's nodes, through bound sources, wrapped sources and streams. @@ -279,6 +281,7 @@ def _source_side_databases(streams: Iterable[Any], *, load_only: bool) -> list[A those databases. The walk visits each stream at most twice, depending on whether it is behind a held table. """ + from orcapod.core.function_pod import FunctionPodStream from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.sources.cached_source import CachedSource from orcapod.core.streams.arrow_table_stream import ArrowTableStream @@ -300,6 +303,8 @@ def _source_side_databases(streams: Iterable[Any], *, load_only: bool) -> list[A if not load_only and not behind_table and not _is_job_node(stream): # A job node's pods: ``write_scope_databases``. 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) behind = behind_table or isinstance(stream, ArrowTableStream) inputs = getattr(stream, "live_source_inputs", None) pending.extend((each, behind) for each in inputs or ()) @@ -328,7 +333,11 @@ 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 write scopes (``database_write_scope``). @@ -345,6 +354,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``). @@ -358,7 +368,11 @@ def write_scope_databases( written.extend( 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 @@ -398,8 +412,11 @@ def database_write_scope( return contextlib.nullcontext() from orcapod.databases.spiraldb_write_scope import database_writes - written = write_scope_databases(streams, load_only=load_only, databases=databases) - return database_writes(written) + 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/spiraldb_run.py b/src/orcapod/protocols/spiraldb_run.py index b12d7f475..853e943db 100644 --- a/src/orcapod/protocols/spiraldb_run.py +++ b/src/orcapod/protocols/spiraldb_run.py @@ -37,6 +37,16 @@ def spiral_acquire_write_lock(self) -> None: ) +@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): diff --git a/tests/test_databases/test_spiraldb_round_trips.py b/tests/test_databases/test_spiraldb_round_trips.py index 32bfac51f..2accdc6e0 100644 --- a/tests/test_databases/test_spiraldb_round_trips.py +++ b/tests/test_databases/test_spiraldb_round_trips.py @@ -149,7 +149,7 @@ def _first_run(entry: str, calls: list[Call], rows: int = 3) -> None: 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, when it starts, + """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.""" diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index 916219fda..c188c91a6 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -993,7 +993,7 @@ 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, at scope entry. + # 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) @@ -2618,7 +2618,7 @@ 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 at scope entry, so a table that + """Review B3: the run keeps one dataset listing, so a table that another connector of the run writes from a plain thread is in the next stale report, as main reports it.""" from concurrent.futures import ThreadPoolExecutor diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 3fc4e8349..8652e4e20 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -331,7 +331,7 @@ 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 when it starts + """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_dataset # pyright: ignore[reportPrivateUsage] diff --git a/tests/test_databases/test_spiraldb_write_lock.py b/tests/test_databases/test_spiraldb_write_lock.py index cb811d0b4..677657c4b 100644 --- a/tests/test_databases/test_spiraldb_write_lock.py +++ b/tests/test_databases/test_spiraldb_write_lock.py @@ -19,6 +19,7 @@ ConnectorArrowDatabase, SpiralDBConnector, spiral_database_identity, + spiraldb_connector, ) from orcapod.databases.spiraldb_write_scope import database_writes from orcapod.errors import SpiralDBScopeOpenError @@ -481,10 +482,13 @@ def test_listing_failure_falls_back_to_resolving_names( ) -> None: _run(_job(_database()), "sync") - def fail_listing(connector: SpiralDBConnector) -> dict[str, str]: + 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") - monkeypatch.setattr(SpiralDBConnector, "_list_tables_for_scope", fail_listing) + 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) @@ -729,3 +733,96 @@ async def run() -> list[int]: 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 + + +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 == [] From 8e56c860b382e29328f934e56f406d3c5c4a7423 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 03:33:02 -0800 Subject: [PATCH 28/46] docs(spiraldb): clarify write scope limitations --- docs/concepts/spiraldb-database.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index d2e778955..c68fbf845 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -45,6 +45,11 @@ 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 From 183b7e099c837934808683d7c93e3044d03170e1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 04:31:54 -0800 Subject: [PATCH 29/46] fix: restore async pod overrides and align database checks --- changelog.d/ITL-1899.md | 3 ++- docs/api/databases.md | 6 ++++-- docs/concepts/spiraldb-database.md | 3 ++- .../dev/scripts/itl_1844_database_evaluation.py | 7 ++++--- src/orcapod/core/function_pod.py | 7 ++++--- src/orcapod/databases/__init__.py | 3 --- tests/test_channels/test_node_async_execute.py | 3 ++- .../test_itl_1844_database_evaluation.py | 17 +++++++---------- 8 files changed, 25 insertions(+), 24 deletions(-) diff --git a/changelog.d/ITL-1899.md b/changelog.d/ITL-1899.md index 5e3fb319b..1c45fddfb 100644 --- a/changelog.d/ITL-1899.md +++ b/changelog.d/ITL-1899.md @@ -15,7 +15,8 @@ ### Added -- Writable `SpiralDBConnector` accepts a `WriteLock` provider. The default +- 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 99c1a7cf0..045e29661 100644 --- a/docs/api/databases.md +++ b/docs/api/databases.md @@ -30,6 +30,8 @@ the underlying database classes (ITL-1539), so its public form may change. ::: orcapod.databases.SpiralDBConnector -::: orcapod.databases.WriteLock +::: orcapod.databases.write_lock.WriteLock -::: orcapod.databases.NoWriteLock +::: orcapod.databases.write_lock.WriteLockHandle + +::: orcapod.databases.write_lock.NoWriteLock diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index c68fbf845..73a975489 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -66,7 +66,8 @@ index from the service. ### Optional write lock -`SpiralDBConnector(..., write_lock=provider)` accepts a `WriteLock` provider. +`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 diff --git a/docs/dev/scripts/itl_1844_database_evaluation.py b/docs/dev/scripts/itl_1844_database_evaluation.py index 3c8ed7c0e..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 scope refused while a scope is open. +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_``. 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 diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 861990d3e..616d6f742 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -464,9 +464,10 @@ def _row_processor( @property def _async_row_processor(self) -> AsyncRowInvoker: """Use a custom async row processor when the pod overrides the public method.""" - if type(self).async_process_data is not _FunctionPodBase.async_process_data: - return self.async_process_data - return self._async_process_data + process = self.async_process_data + if getattr(process, "__func__", None) is _FunctionPodBase.async_process_data: + return self._async_process_data + return process async def _async_process_data( self, diff --git a/src/orcapod/databases/__init__.py b/src/orcapod/databases/__init__.py index 927505060..ce7cfbdb2 100644 --- a/src/orcapod/databases/__init__.py +++ b/src/orcapod/databases/__init__.py @@ -6,7 +6,6 @@ from .postgresql_connector import PostgreSQLConnector from .spiraldb_connector import SpiralDBConnector from .sqlite_connector import SQLiteConnector -from .write_lock import NoWriteLock, WriteLock __all__ = [ "ConnectorArrowDatabase", @@ -15,8 +14,6 @@ "InMemoryArrowDatabase", "NoOpArrowDatabase", "SpiralDBConnector", - "NoWriteLock", - "WriteLock", "SQLiteConnector", "PostgreSQLConnector", ] 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_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", } From d9ce39bbc8e9863a143e2aaeb7ecfd846ade55d4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 04:33:37 -0800 Subject: [PATCH 30/46] test(spiraldb): compare batch retries with per-row commits --- docs/concepts/spiraldb-database.md | 8 ++- .../test_spiraldb_writable_runs.py | 57 ++++++++++++++----- tests/test_docs/test_doc_samples.py | 13 +++++ 3 files changed, 61 insertions(+), 17 deletions(-) diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index be98766bb..c231b3804 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -165,9 +165,11 @@ read different tables. ## Limits -- Each check of which rows a table holds reads the table's whole key column, and each - read of stored rows reads the whole table, so the cost of a run grows with the - table's history. +- 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). diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 673273595..6d6500996 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -1934,22 +1934,44 @@ def test_a_permanent_result_failure_keeps_the_rows_before_it( append = fake.FakeKeyedTable.append attempted: list[list[int]] = [] - def refuse_total_8(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: + def trace_results(table: fake.FakeKeyedTable, batch: pa.Table) -> list[int]: record = spiral_database_identity.read_table_identity_metadata( table.get_metadata() ) - if record is not None and record.path[-1] == "rdb_v1": - totals = [ - value - for column in batch.columns - for value in column.to_pylist() - if value in (6, 8, 10) - ] + if record is None or record.path[-1] != "rdb_v1": + return [] + return [ + value + for column in batch.columns + for value in column.to_pylist() + if value in (6, 8, 10) + ] + + def record_per_row_append( + table: fake.FakeKeyedTable, batch: pa.Table + ) -> fake.FakeKeyedTable: + 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: + totals = trace_results(table, batch) + if totals: attempted.append(totals) if 8 in totals: raise fake.SpiralError("permanent failure writing total=8") return append(table, batch) + reference_job = _job(_database("per-row"), order=order) + with monkeypatch.context() as patch: + patch.setattr(node_run, "batches_node_commits", lambda _node: False) + patch.setattr(fake.FakeKeyedTable, "append", record_per_row_append) + _ = reference_job.nodes[target].run() + reference = [total for (total,) in attempted] + assert sorted(reference) == [6, 8, 10] + attempted.clear() + job = _job(_database(), order=order) with monkeypatch.context() as patch: patch.setattr(fake.FakeKeyedTable, "append", refuse_total_8) @@ -1957,21 +1979,28 @@ def refuse_total_8(table: fake.FakeKeyedTable, batch: pa.Table) -> Any: _ = job.nodes[target].run() # One batch of three, then one row at a time up to the failing row. batch, *single = attempted - assert sorted(batch) == [6, 8, 10] - failure = batch.index(8) - assert single == [[total] for total in batch[: failure + 1]] - kept = sorted(batch[:failure]) + assert batch == reference + failure = reference.index(8) + assert single == [[total] for total in reference[: failure + 1]] + kept = sorted(reference[:failure]) fresh = _database() stored = { path[-1]: table for path in fresh.list_table_paths() - if (table := fresh.get_all_records(path)) is not None + if (table := fresh.get_all_records(path, record_id_column="result_id")) + is not None } results = stored.get("rdb_v1") totals = [] if results is None else cast("list[int]", results["total"].to_pylist()) assert sorted(totals) == kept records = stored.get("pdb_v2") - assert (0 if records is None else records.num_rows) == len(kept) + result_ids = ( + [] if results is None else cast("list[bytes]", results["result_id"].to_pylist()) + ) + referenced_ids = ( + [] if records is None else cast("list[bytes]", records["__data_id"].to_pylist()) + ) + assert sorted(referenced_ids) == sorted(result_ids) assert stored["sdb_v2"].num_rows == 3 with database_writes([fresh], owner="recovery"): pass diff --git a/tests/test_docs/test_doc_samples.py b/tests/test_docs/test_doc_samples.py index e9925bdf0..5de4a94b7 100644 --- a/tests/test_docs/test_doc_samples.py +++ b/tests/test_docs/test_doc_samples.py @@ -277,6 +277,19 @@ def test_doc_pages_are_discovered(): assert expected in DOC_PAGES +def test_spiraldb_limits_describe_when_key_scans_are_needed(): + """The key index and full-row reads have different scan costs.""" + page = (REPO_ROOT / "docs/concepts/spiraldb-database.md").read_text( + encoding="utf-8" + ) + 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 + + @pytest.mark.parametrize("page", DOC_PAGES) def test_doc_page_samples_run(page: str, tmp_path: Path): """Every python sample on the page runs and prints what the page shows. From 7b5c0efc7a1105a162e3bd907b06debb5fa375c3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 05:11:34 -0800 Subject: [PATCH 31/46] fix(spiraldb): preserve write scopes through review edge cases --- docs/concepts/spiraldb-database.md | 14 +- src/orcapod/core/data_function.py | 13 +- src/orcapod/core/function_pod.py | 70 ++++- src/orcapod/databases/spiraldb_tables.py | 9 + src/orcapod/databases/spiraldb_write_scope.py | 43 ++- .../test_spiraldb_round_trips.py | 90 +++++- .../test_spiraldb_writable_mode.py | 26 +- .../test_spiraldb_writable_runs.py | 1 + .../test_spiraldb_write_lock.py | 262 +++++++++++++++++- tests/test_docs/test_doc_samples.py | 9 +- 10 files changed, 477 insertions(+), 60 deletions(-) diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index 1d6fa70ae..94075044b 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -124,13 +124,13 @@ read different tables. ## Limits -- In a write scope, a key check for an existing table reads the whole key - column when the scope has neither an index nor keys from an earlier read. - This can happen on the first check or after a failed write invalidates the - scope's cached reads. Successful appends update the index, and later checks - reuse it across flushes. Outside a write scope, each nonempty key check on an - existing table 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. +- 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/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index ff71927ea..a82a5226a 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -1733,7 +1733,11 @@ def call( if self._takes_context and not skip_cache_insert else nullcontext() ): - output_data = self._data_function.call(data, logger=logger, **kwargs) + 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: @@ -1785,9 +1789,10 @@ async def async_call( if self._takes_context and not skip_cache_insert else nullcontext() ): - output_data = await self._data_function.async_call( - data, logger=logger, **kwargs - ) + 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: diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 616d6f742..c9557da57 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -13,7 +13,8 @@ Iterator, Sequence, ) -from contextlib import AbstractContextManager +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 @@ -126,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.""" @@ -391,8 +397,8 @@ def process_data( logger: DataExecutionLoggerProtocol | None = None, run_id: str | None = None, ) -> tuple[TagProtocol, DataProtocol | None]: - """Process one row as an independent execution.""" - with self._standalone_writes(): + """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( @@ -440,8 +446,8 @@ async def async_process_data( logger: DataExecutionLoggerProtocol | None = None, run_id: str | None = None, ) -> tuple[TagProtocol, DataProtocol | None]: - """Process one async row as an independent execution.""" - with self._standalone_writes(): + """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 ) @@ -452,14 +458,46 @@ def _standalone_writes(self) -> AbstractContextManager[None]: 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.""" - if type(self).process_data is not _FunctionPodBase.process_data: - return self.process_data - return self._process_data + 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: @@ -467,7 +505,21 @@ def _async_row_processor(self) -> AsyncRowInvoker: process = self.async_process_data if getattr(process, "__func__", None) is _FunctionPodBase.async_process_data: return self._async_process_data - return process + + 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, diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index 78e1b32c5..cf9cad349 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -1077,6 +1077,15 @@ def existing_record_ids( 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. + with self.outside_operation(): + opened = self._judge(table_name) + reused = False if opened is None: return set() # A snapshot this operation opened earlier can predate another diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index 75e376d49..673913040 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -208,24 +208,30 @@ def _connector_scopes( def _refusal_behind( error: BaseException, scopes: list[_DatasetScope] ) -> BaseException | None: - """Recover a provider error behind a wrapper or a task group's exception.""" + """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] - if not refusals or not isinstance(error, Exception): - return None - seen: set[int] = set() - pending: list[BaseException] = [error] - while pending: - current = pending.pop() + + 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: - continue - seen.add(id(current)) + return None if any(current is refusal for refusal in refusals): return current + seen = seen | {id(current)} if isinstance(current, BaseExceptionGroup): - pending.extend(reversed(current.exceptions)) - if (cause := current.__cause__ or current.__context__) is not None: - pending.append(cause) - return None + 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__ or current.__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: @@ -327,7 +333,11 @@ def close(self) -> list[BaseException]: The failures, in order. """ failures: list[BaseException] = [] - with self.state.lock: + 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: @@ -374,7 +384,10 @@ def _close_all(scopes: list[_DatasetScope], error: BaseException | None) -> None """ failures: list[BaseException] = [] for scope in reversed(scopes): - failures.extend(scope.close()) + try: + failures.extend(scope.close()) + except BaseException as exc: # noqa: BLE001 # close the remaining scopes + failures.append(exc) if not failures: return interruptions = [f for f in failures if not isinstance(f, Exception)] diff --git a/tests/test_databases/test_spiraldb_round_trips.py b/tests/test_databases/test_spiraldb_round_trips.py index 2accdc6e0..8d7d637b9 100644 --- a/tests/test_databases/test_spiraldb_round_trips.py +++ b/tests/test_databases/test_spiraldb_round_trips.py @@ -15,8 +15,12 @@ import pyarrow as pa import pytest -from orcapod.databases import ConnectorArrowDatabase, spiraldb_connector -from orcapod.databases.spiraldb_tables import SpiralDBTables, RunState +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 @@ -114,17 +118,27 @@ def scanned( 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 scan(table, *args, **kwargs) + 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 a dataset listing before calling the service.""" + """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 listing(client, project, dataset) + return result monkeypatch.setattr(spiraldb_connector, "_list_dataset", listed) yield calls @@ -141,6 +155,38 @@ def _first_run(entry: str, calls: list[Call], rows: int = 3) -> None: 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 ───────────────────────────── @@ -155,6 +201,8 @@ def test_a_first_run_opens_no_name_its_listing_shows_absent( 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 @@ -287,6 +335,38 @@ def scan_then_append( ] +@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") @pytest.mark.parametrize("new_table", [False, True]) def test_the_first_key_lookup_indexes_keys_without_a_second_read( diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index c188c91a6..2b4cb9aee 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -2618,14 +2618,14 @@ def peer() -> str: def test_a_table_written_from_another_thread_is_reported_stale_at_once( revisions: tuple[str, ...], ) -> None: - """Review B3: the run keeps one dataset listing, 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()) - second = ConnectorArrowDatabase(writable_connector()) + connector = writable_connector() + second = ConnectorArrowDatabase(connector) paths = [(*RESULT[:-2], revision, "rdb_v1") for revision in revisions] def stale() -> list[tuple[str, ...]]: @@ -2633,17 +2633,19 @@ def stale() -> list[tuple[str, ...]]: return sorted(entry.record_path for entry in found.tables) 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: + 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( - copy_context().run, - 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) diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 23316d539..4ad731218 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -952,6 +952,7 @@ def test_a_job_on_a_shared_writable_connector_takes_the_scope_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 diff --git a/tests/test_databases/test_spiraldb_write_lock.py b/tests/test_databases/test_spiraldb_write_lock.py index 677657c4b..b0509bfdc 100644 --- a/tests/test_databases/test_spiraldb_write_lock.py +++ b/tests/test_databases/test_spiraldb_write_lock.py @@ -3,28 +3,39 @@ from __future__ import annotations import asyncio +from collections.abc import Callable from concurrent.futures import ThreadPoolExecutor from contextvars import copy_context -from collections.abc import Callable -from typing import Any +from typing import Any, 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.function_pod import FunctionPod 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 SpiralDBScopeOpenError +from orcapod.errors import OrcapodDatabaseWriteError, SpiralDBScopeOpenError from orcapod.invocation import InvocationContext -from orcapod.protocols.core_protocols import DataProtocol, TagProtocol +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 @@ -477,6 +488,102 @@ def test_all_handles_release_even_if_a_release_fails() -> None: pass +@pytest.mark.parametrize("interrupt_at", ["lock entry", "scope close"]) +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 == "lock entry": + 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 + + 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(state, "lock", 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("independent_error", [False, True]) +def test_provider_refusal_unwrap_preserves_other_task_failures( + independent_error: bool, +) -> None: + refusal = OSError("provider refused") + independent = ValueError("another task failed") + database = _database(lock=RecordingLock([], refusal)) + errors: list[Exception] = [] + + async def fail(*, independent_task: bool) -> None: + if independent_task: + raise independent + database.spiral_acquire_write_lock() + + async def run() -> None: + with database_writes([database]): + try: + async with asyncio.TaskGroup() as tasks: + _ = tasks.create_task(fail(independent_task=False)) + _ = tasks.create_task(fail(independent_task=independent_error)) + except ExceptionGroup as group: + errors.append(group) + raise + + if independent_error: + 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 + + def test_listing_failure_falls_back_to_resolving_names( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -681,6 +788,153 @@ def act(x: int, ctx: InvocationContext) -> int: assert "acquire" not in sdk_events +@pytest.mark.parametrize("async_call", [False, True]) +def test_custom_cached_function_acquires_the_lock_before_invocation( + async_call: bool, +) -> None: + refusal = OSError("cache lock refused") + lock = RecordingLock([], refusal) + + def shape(x: int) -> int: + return x + + class CustomFunction(PythonDataFunction): + """Supply the invocation directly through the data function protocol.""" + + @override + def call( + self, + data: DataProtocol, + *, + logger: DataExecutionLoggerProtocol | None = None, + **kwargs: object, + ) -> DataProtocol: + lock.events.append("call") + return Data({"total": data.as_dict()["x"]}) + + @override + async def async_call( + self, + data: DataProtocol, + *, + logger: DataExecutionLoggerProtocol | None = None, + **kwargs: object, + ) -> DataProtocol: + return self.call(data, logger=logger, **kwargs) + + function = cast(object, CustomFunction(shape, output_keys="total")) + 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]) diff --git a/tests/test_docs/test_doc_samples.py b/tests/test_docs/test_doc_samples.py index e8a73f67f..ccf38dfb6 100644 --- a/tests/test_docs/test_doc_samples.py +++ b/tests/test_docs/test_doc_samples.py @@ -284,13 +284,14 @@ def test_spiraldb_limits_describe_when_key_scans_are_needed(): ) limits = " ".join(page.split("## Limits\n", 1)[1].split("\n## ", 1)[0].split()) + 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 ( - "reads the whole key column when the scope has neither an index nor keys from an earlier read" + "Outside a write scope, every check for one or more keys in a table with rows scans the key column" in limits ) - assert "after a failed write invalidates the scope's cached reads" in limits - assert "Successful appends update the index" in limits - assert "each nonempty key check on an existing table scans the key column" in limits assert "Reads of stored rows load the whole table" in limits assert "lease" not in limits From bc14f508f9bbb4dbe5d477165e37b4a7351a30d7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 06:27:54 -0800 Subject: [PATCH 32/46] fix(spiraldb): preserve write scope guarantees Acquire before native invocation overrides and isolate key refreshes from operation snapshots. Preserve suppressed exceptions and finish releasing the reservation when registry lock entry is interrupted. --- src/orcapod/core/data_function.py | 13 +++- src/orcapod/databases/spiraldb_tables.py | 9 +-- src/orcapod/databases/spiraldb_write_scope.py | 23 +++++-- .../test_spiraldb_round_trips.py | 34 ++++++++++ .../test_spiraldb_write_lock.py | 68 +++++++++++++------ 5 files changed, 114 insertions(+), 33 deletions(-) diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index a82a5226a..91102ec7d 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -1312,7 +1312,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, @@ -1345,7 +1348,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). diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index cf9cad349..e1a64cc5c 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -639,7 +639,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``). @@ -648,6 +648,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. @@ -656,7 +657,7 @@ 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] run = self._run_state @@ -1083,8 +1084,8 @@ def existing_record_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. - with self.outside_operation(): - opened = self._judge(table_name) + judgment = self._judgment(table_name, refresh=True) + opened = judgment if isinstance(judgment, _Opened) else None reused = False if opened is None: return set() diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index 673913040..7d5f4b4e1 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -46,8 +46,8 @@ from orcapod.databases.spiraldb_connector import SpiralDBConnector from orcapod.databases.spiraldb_tables import SpiralDBTables -_open_scopes: set[tuple[str, str]] = set() -"""The (project, dataset) pairs reserved by open scopes in this process.""" +_open_scopes: dict[tuple[str, str], _DatasetScope] = {} +"""Open scopes by (project, dataset) in this process.""" _open_scopes_lock = threading.Lock() @@ -226,7 +226,9 @@ def find(current: BaseException, seen: set[int]) -> BaseException | None: ): return refusal return None - cause = current.__cause__ or current.__context__ + cause = current.__cause__ + if cause is None and not current.__suppress_context__: + cause = current.__context__ return None if cause is None else find(cause, seen) if not refusals or not isinstance(error, Exception): @@ -268,8 +270,8 @@ def open(self, connectors: list[SpiralDBConnector]) -> None: f"A write scope for SpiralDB dataset " f"{self._project_id}/{self._dataset} is already open in this process" ) - _open_scopes.add(self._reservation) self._registered = True + _open_scopes[self._reservation] = self for connector in connectors: self._attach(_tables(connector)) self._accepting_joins = True @@ -355,9 +357,16 @@ def close(self) -> list[BaseException]: handle.release() except BaseException as exc: # noqa: BLE001 # reported with the others failures.append(exc) - if self._registered: - with _open_scopes_lock: - _open_scopes.remove(self._reservation) + 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 diff --git a/tests/test_databases/test_spiraldb_round_trips.py b/tests/test_databases/test_spiraldb_round_trips.py index 8d7d637b9..71bd018aa 100644 --- a/tests/test_databases/test_spiraldb_round_trips.py +++ b/tests/test_databases/test_spiraldb_round_trips.py @@ -367,6 +367,40 @@ def test_key_checks_see_peer_appends_after_a_negative_judgment( 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( diff --git a/tests/test_databases/test_spiraldb_write_lock.py b/tests/test_databases/test_spiraldb_write_lock.py index b0509bfdc..835c9c2cd 100644 --- a/tests/test_databases/test_spiraldb_write_lock.py +++ b/tests/test_databases/test_spiraldb_write_lock.py @@ -488,7 +488,7 @@ def test_all_handles_release_even_if_a_release_fails() -> None: pass -@pytest.mark.parametrize("interrupt_at", ["lock entry", "scope close"]) +@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: @@ -501,12 +501,17 @@ def test_scope_cleanup_continues_after_an_interruption( with database_writes([first_db, second_db]): first_db.spiral_acquire_write_lock() second_db.spiral_acquire_write_lock() - if interrupt_at == "lock entry": - 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 + 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.""" @@ -522,7 +527,7 @@ def __enter__(self) -> None: def __exit__(self, *_exc: object) -> None: real_lock.release() - patch.setattr(state, "lock", InterruptOnce()) + patch.setattr(owner, attribute, InterruptOnce()) else: scope_class = spiraldb_write_scope._DatasetScope # pyright: ignore[reportPrivateUsage] close = scope_class.close @@ -545,31 +550,36 @@ def close_then_interrupt( pass -@pytest.mark.parametrize("independent_error", [False, True]) +@pytest.mark.parametrize("second_error", ["refusal", "independent", "suppressed"]) def test_provider_refusal_unwrap_preserves_other_task_failures( - independent_error: bool, + second_error: str, ) -> None: refusal = OSError("provider refused") independent = ValueError("another task failed") database = _database(lock=RecordingLock([], refusal)) errors: list[Exception] = [] - async def fail(*, independent_task: bool) -> None: - if independent_task: + async def fail(kind: str) -> None: + if kind == "independent": raise independent - database.spiral_acquire_write_lock() + try: + database.spiral_acquire_write_lock() + except OrcapodDatabaseWriteError: + 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(independent_task=False)) - _ = tasks.create_task(fail(independent_task=independent_error)) + _ = tasks.create_task(fail("refusal")) + _ = tasks.create_task(fail(second_error)) except ExceptionGroup as group: errors.append(group) raise - if independent_error: + if second_error != "refusal": with pytest.raises(ExceptionGroup) as raised: asyncio.run(run()) assert raised.value is errors[0] @@ -789,8 +799,10 @@ def act(x: int, ctx: InvocationContext) -> int: @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) @@ -798,7 +810,21 @@ def test_custom_cached_function_acquires_the_lock_before_invocation( def shape(x: int) -> int: return x - class CustomFunction(PythonDataFunction): + 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 @@ -809,8 +835,7 @@ def call( logger: DataExecutionLoggerProtocol | None = None, **kwargs: object, ) -> DataProtocol: - lock.events.append("call") - return Data({"total": data.as_dict()["x"]}) + return self.direct_call(data, **kwargs) @override async def async_call( @@ -822,7 +847,10 @@ async def async_call( ) -> DataProtocol: return self.call(data, logger=logger, **kwargs) - function = cast(object, CustomFunction(shape, output_keys="total")) + 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") From d6fe77a312eac5a709dd9e7fa66c8c4b6e4b3794 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 10:56:00 -0800 Subject: [PATCH 33/46] feat(databases): add SpiralDatabase factory --- changelog.d/ITL-1933.md | 4 + docs/api/databases.md | 10 ++- docs/concepts/pipeline-job.md | 6 +- docs/concepts/sources.md | 4 +- docs/concepts/spiraldb-keyed-database.md | 42 +++++++---- src/orcapod/databases/__init__.py | 2 + src/orcapod/databases/spiral_database.py | 26 +++++++ .../test_spiraldb_writable_runs.py | 73 ++++++++++++++++++- 8 files changed, 141 insertions(+), 26 deletions(-) create mode 100644 changelog.d/ITL-1933.md create mode 100644 src/orcapod/databases/spiral_database.py diff --git a/changelog.d/ITL-1933.md b/changelog.d/ITL-1933.md new file mode 100644 index 000000000..a131f2a35 --- /dev/null +++ b/changelog.d/ITL-1933.md @@ -0,0 +1,4 @@ +### Added + +- `orcapod.databases.SpiralDatabase(project_id, dataset, ...)` opens a writable SpiralDB + database for a job. Saved jobs record the concrete backend and its configuration. diff --git a/docs/api/databases.md b/docs/api/databases.md index 008eba163..8b8befbea 100644 --- a/docs/api/databases.md +++ b/docs/api/databases.md @@ -6,10 +6,10 @@ introduction. Every signature and docstring on the published page comes from the code. See site/README.md. --> -Database backends store pipeline results. The SQLite and PostgreSQL connectors support -reads and writes through `ConnectorArrowDatabase`. `SpiralDBKeyedConnector` reads, and writes -only when opened writable (`writable=True`, provisional; see -[Keyed SpiralDB as a Job's Database](../concepts/spiraldb-keyed-database.md)). +Database backends store pipeline results. `SpiralDatabase` opens a writable database on +Orcapod's default SpiralDB backend. See +[Keyed SpiralDB as a Job's Database](../concepts/spiraldb-keyed-database.md). +The SQLite and PostgreSQL connectors support reads and writes through `ConnectorArrowDatabase`. **Provisional.** `ExtensionAwareDatabase` is expected to be integrated more closely with the underlying database classes (ITL-1539), so its public form may change. @@ -20,6 +20,8 @@ the underlying database classes (ITL-1539), so its public form may change. ::: orcapod.databases.NoOpArrowDatabase +::: orcapod.databases.SpiralDatabase + ::: orcapod.databases.ConnectorArrowDatabase ::: orcapod.databases.ExtensionAwareDatabase diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 5475e8ce2..1ca4d5ff1 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -276,10 +276,8 @@ structs, dates or timestamps on SQLite, narrower integers and floats, logical ty refused. PostgreSQL also refuses column names and explicit table identifiers longer than 63 bytes, which it would truncate (`UnstorableTableNameError` for a table). SQLite and PostgreSQL stores generate table names within 63 bytes from the node's -path, using a readable hint and a digest of the full path. A database on -`SpiralDBKeyedConnector` refuses every write (`SpiralDBWriteNotSupportedError`) unless it is opened -writable, `SpiralDBKeyedConnector(..., writable=True)`: see -[Keyed SpiralDB as a Job's Database](spiraldb-keyed-database.md). The full list, +path, using a readable hint and a digest of the full path. Use `SpiralDatabase` to +store job tables in SpiralDB. See [Keyed SpiralDB as a Job's Database](spiraldb-keyed-database.md). The full list, type by type, is [Data types per database](../reference/database-types.md). Orcapod's own stored tables hold such columns. A function node's result table holds diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 77a64b4be..f8d4cfe8b 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -568,8 +568,8 @@ whose calls failed, gives the next new source a new client. Closing a source aff the client goes with the last source that uses it, and a forked process starts with none. A plain `SpiralDBKeyedConnector` only reads: a write through it (or a job whose database is on -one) raises `SpiralDBWriteNotSupportedError`. A job can keep its tables in SpiralDB through -a writable SpiralDB database, `SpiralDBKeyedConnector(..., writable=True)`: see +one) raises `SpiralDBWriteNotSupportedError`. Use `SpiralDatabase` to store job tables +in SpiralDB. See [Keyed SpiralDB as a Job's Database](spiraldb-keyed-database.md). Replace the example project, dataset and table names with identifiers you can access. diff --git a/docs/concepts/spiraldb-keyed-database.md b/docs/concepts/spiraldb-keyed-database.md index 509af7bf1..c2cb78f49 100644 --- a/docs/concepts/spiraldb-keyed-database.md +++ b/docs/concepts/spiraldb-keyed-database.md @@ -13,24 +13,32 @@ records, operator caches, cached sources and side-effect logs. Open the dataset ## Opening the SpiralDB database -`SpiralDBKeyedConnector(project_id, dataset, writable=True)` opens one dataset as a writable -SpiralDB database. Wrap it in `ConnectorArrowDatabase` and use it as the job's database, its separate result -database, or a cached source's database: +Use `SpiralDatabase(project_id, dataset)` to open a writable database for a job, its +separate result database, or a cached source. Install `orcapod[spiraldb]` and sign in +through spiral-sdk before opening the database. - ```python from orcapod import PipelineJob -from orcapod.databases import ConnectorArrowDatabase, SpiralDBKeyedConnector +from orcapod.databases import SpiralDatabase -database = ConnectorArrowDatabase( - SpiralDBKeyedConnector("my-project-123456", "pipeline_results", writable=True) -) -job = PipelineJob(name="experiment", database=database) + +def make_job(project_id: str, dataset: str) -> PipelineJob: + return PipelineJob(name="experiment", database=SpiralDatabase(project_id, dataset)) ``` -Signing in is spiral-sdk's: the `SPIRAL_*` environment variables, or a saved -`spiral login`. Without `writable=True`, a `SpiralDBKeyedConnector` reads existing keyed tables -(a `SpiralDBTableSource`) and writes nothing. +Call `make_job` with a project identifier and dataset you can write to. + + +```python +job = make_job("my-project-123456", "pipeline_results") +``` + +Spiral-sdk signs in using the `SPIRAL_*` environment variables or a saved `spiral login`. +`SpiralDatabase` currently returns a `ConnectorArrowDatabase` backed by +`SpiralDBKeyedConnector(..., writable=True)` and passes other keyword options, such as +`overrides`, to the connector. The default backend may change in a later release. +Orcapod will announce any change one release ahead. Build the database with the explicit +connector to choose the keyed backend directly. Each stored table is one keyed table of the dataset, named from its path (a readable part of the path and a digest of all of it). Its metadata records the full path, the @@ -111,12 +119,16 @@ one, also released ones: removing one by hand can let two writers in. ## Saving and loading a job -A job saved on the keyed SpiralDB database records `connector_type: spiraldb_keyed` -along with the project, dataset, service address and `writable: true`. It saves no -credentials. Pass the connector again when loading the job: +A job saved using `SpiralDatabase` records its concrete backend. A job on the keyed +backend records `connector_type: spiraldb_keyed` along with the project, dataset, +connection overrides and `writable: true`. It saves no credentials. A change to the +default backend leaves that saved configuration intact. Supply the recorded backend +when loading the job, using the explicit classes to select it directly. ```python +from orcapod.databases import ConnectorArrowDatabase, SpiralDBKeyedConnector + loaded = PipelineJob.load( "experiment.json", database=ConnectorArrowDatabase( diff --git a/src/orcapod/databases/__init__.py b/src/orcapod/databases/__init__.py index f3ed6b908..c2783fd39 100644 --- a/src/orcapod/databases/__init__.py +++ b/src/orcapod/databases/__init__.py @@ -4,6 +4,7 @@ from .in_memory_databases import InMemoryArrowDatabase from .noop_database import NoOpArrowDatabase from .postgresql_connector import PostgreSQLConnector +from .spiral_database import SpiralDatabase from .spiraldb_keyed.connector import SpiralDBKeyedConnector from .sqlite_connector import SQLiteConnector @@ -13,6 +14,7 @@ "ExtensionAwareDatabase", "InMemoryArrowDatabase", "NoOpArrowDatabase", + "SpiralDatabase", "SpiralDBKeyedConnector", "SQLiteConnector", "PostgreSQLConnector", diff --git a/src/orcapod/databases/spiral_database.py b/src/orcapod/databases/spiral_database.py new file mode 100644 index 000000000..1b7cd3fc4 --- /dev/null +++ b/src/orcapod/databases/spiral_database.py @@ -0,0 +1,26 @@ +from typing import Any + +from .connector_arrow_database import ConnectorArrowDatabase +from .spiraldb_keyed.connector import SpiralDBKeyedConnector + + +def SpiralDatabase( + project_id: str, dataset: str, **connector_options: Any +) -> ConnectorArrowDatabase: + """Open a writable SpiralDB database using Orcapod's default backend. + + The factory sets ``writable=True`` and forwards other keyword arguments, + such as ``overrides``, to the keyed connector. + Saved jobs record the concrete backend and its configuration. The default + backend may change in a later release, with one release of advance notice. + + Args: + project_id: SpiralDB project identifier. + dataset: Dataset within the project. + + Returns: + A database backed by a writable ``SpiralDBKeyedConnector``. + """ + return ConnectorArrowDatabase( + SpiralDBKeyedConnector(project_id, dataset, writable=True, **connector_options) + ) diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 3ccca2b7a..de75eea0a 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -29,6 +29,7 @@ ConnectorArrowDatabase, DeltaTableDatabase, InMemoryArrowDatabase, + SpiralDatabase, SpiralDBKeyedConnector, spiraldb_lease, ) @@ -110,12 +111,14 @@ def _rows(n: int = 3) -> pa.Table: def _cached(cache: Any, table: pa.Table, *, order: str = "as given") -> CachedSource: + tags = ["unit", "trial"] if order == "reversed": table = table.select(list(reversed(table.column_names))) + tags.reverse() return CachedSource( ArrowTableSource( table, - tag_columns=["unit", "trial"], + tag_columns=tags, tag_only_columns=True, source_id="trials", record_id_columns=["unit", "trial"], @@ -227,6 +230,26 @@ def _run(job: PipelineJob, entry: str, **kwargs: Any) -> Any: # ------------------------------------------------------------ every table kind +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "run_async"]) +@pytest.mark.parametrize("order", ["as given", "reversed"]) +def test_spiral_database_stores_every_role_like_the_explicit_backend( + entry: str, order: str +) -> None: + database = SpiralDatabase("p", "factory") + explicit = _database("explicit") + for backend in (database, explicit): + calls.clear() + delivered.clear() + _ = _run(_job(backend, order=order), entry) + assert sorted(calls) == [(1, 5), (2, 6), (3, 7)] + assert sorted(delivered) == [6, 8, 10] + + assert sorted(path[-1] for path in database.list_table_paths()) == sorted(LAYOUTS) + _same_tables(database, explicit) + assert _database_tables("factory") == _database_tables("explicit") + + @pytest.mark.usefixtures("root") @pytest.mark.parametrize("entry", ENTRIES) @pytest.mark.parametrize("order", ["as given", "reversed"]) @@ -308,6 +331,54 @@ def test_a_new_input_and_a_replay_are_stored_as_on_delta( # ------------------------------------------------------------------ load only +def test_spiral_database_job_round_trip_records_the_concrete_backend( + root: Path, +) -> None: + overrides = {"server.url": "https://example.invalid"} + database = SpiralDatabase(project_id="p", dataset="d", overrides=overrides) + results = SpiralDatabase(overrides=overrides, dataset="r", project_id="p") + job = _job(database, result_database=results) + _ = job.run() + saved = root / "job.json" + job.save(saved) + bindings = json.loads(saved.read_text())["bindings"] + + explicit = ConnectorArrowDatabase( + SpiralDBKeyedConnector("p", "d", overrides=overrides, writable=True) + ) + explicit_results = ConnectorArrowDatabase( + SpiralDBKeyedConnector("p", "r", overrides=overrides, writable=True) + ) + for slot, dataset, backend in ( + ("database", "d", explicit), + ("result_database", "r", explicit_results), + ): + assert bindings[slot] == backend.to_config() + assert bindings[slot]["type"] == "connector_arrow_database" + assert bindings[slot]["connector"] == { + "connector_type": "spiraldb_keyed", + "project_id": "p", + "dataset": dataset, + "overrides": overrides, + "writable": True, + } + + loaded = PipelineJob.load( + saved, database=explicit, result_database=explicit_results + ) + _ = loaded.run(load_only=True) + for label in ("combine", "select"): + original = job.nodes[label].as_source().as_table() + restored = loaded.nodes[label].as_source().as_table() + assert restored.num_rows == 3 + assert _comparable(restored) == _comparable(original) + saved_again = root / "loaded.json" + loaded.save(saved_again) + recorded = json.loads(saved_again.read_text())["bindings"] + for slot in ("database", "result_database"): + assert recorded[slot] == bindings[slot] + + @pytest.mark.usefixtures("root") def test_a_loaded_job_reads_and_load_only_runs_take_no_lease(root: Path) -> None: spiral_db = _database() From fc931c4e174181ba48db30d61c048fbc3b186445 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 11:04:33 -0800 Subject: [PATCH 34/46] feat(databases): add SpiralDatabase factory (#703) --- changelog.d/ITL-1933.md | 4 + docs/api/databases.md | 10 ++- docs/concepts/pipeline-job.md | 6 +- docs/concepts/sources.md | 4 +- docs/concepts/spiraldb-keyed-database.md | 42 +++++++---- src/orcapod/databases/__init__.py | 2 + src/orcapod/databases/spiral_database.py | 26 +++++++ .../test_spiraldb_writable_runs.py | 73 ++++++++++++++++++- 8 files changed, 141 insertions(+), 26 deletions(-) create mode 100644 changelog.d/ITL-1933.md create mode 100644 src/orcapod/databases/spiral_database.py diff --git a/changelog.d/ITL-1933.md b/changelog.d/ITL-1933.md new file mode 100644 index 000000000..a131f2a35 --- /dev/null +++ b/changelog.d/ITL-1933.md @@ -0,0 +1,4 @@ +### Added + +- `orcapod.databases.SpiralDatabase(project_id, dataset, ...)` opens a writable SpiralDB + database for a job. Saved jobs record the concrete backend and its configuration. diff --git a/docs/api/databases.md b/docs/api/databases.md index 008eba163..8b8befbea 100644 --- a/docs/api/databases.md +++ b/docs/api/databases.md @@ -6,10 +6,10 @@ introduction. Every signature and docstring on the published page comes from the code. See site/README.md. --> -Database backends store pipeline results. The SQLite and PostgreSQL connectors support -reads and writes through `ConnectorArrowDatabase`. `SpiralDBKeyedConnector` reads, and writes -only when opened writable (`writable=True`, provisional; see -[Keyed SpiralDB as a Job's Database](../concepts/spiraldb-keyed-database.md)). +Database backends store pipeline results. `SpiralDatabase` opens a writable database on +Orcapod's default SpiralDB backend. See +[Keyed SpiralDB as a Job's Database](../concepts/spiraldb-keyed-database.md). +The SQLite and PostgreSQL connectors support reads and writes through `ConnectorArrowDatabase`. **Provisional.** `ExtensionAwareDatabase` is expected to be integrated more closely with the underlying database classes (ITL-1539), so its public form may change. @@ -20,6 +20,8 @@ the underlying database classes (ITL-1539), so its public form may change. ::: orcapod.databases.NoOpArrowDatabase +::: orcapod.databases.SpiralDatabase + ::: orcapod.databases.ConnectorArrowDatabase ::: orcapod.databases.ExtensionAwareDatabase diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 5475e8ce2..1ca4d5ff1 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -276,10 +276,8 @@ structs, dates or timestamps on SQLite, narrower integers and floats, logical ty refused. PostgreSQL also refuses column names and explicit table identifiers longer than 63 bytes, which it would truncate (`UnstorableTableNameError` for a table). SQLite and PostgreSQL stores generate table names within 63 bytes from the node's -path, using a readable hint and a digest of the full path. A database on -`SpiralDBKeyedConnector` refuses every write (`SpiralDBWriteNotSupportedError`) unless it is opened -writable, `SpiralDBKeyedConnector(..., writable=True)`: see -[Keyed SpiralDB as a Job's Database](spiraldb-keyed-database.md). The full list, +path, using a readable hint and a digest of the full path. Use `SpiralDatabase` to +store job tables in SpiralDB. See [Keyed SpiralDB as a Job's Database](spiraldb-keyed-database.md). The full list, type by type, is [Data types per database](../reference/database-types.md). Orcapod's own stored tables hold such columns. A function node's result table holds diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 77a64b4be..f8d4cfe8b 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -568,8 +568,8 @@ whose calls failed, gives the next new source a new client. Closing a source aff the client goes with the last source that uses it, and a forked process starts with none. A plain `SpiralDBKeyedConnector` only reads: a write through it (or a job whose database is on -one) raises `SpiralDBWriteNotSupportedError`. A job can keep its tables in SpiralDB through -a writable SpiralDB database, `SpiralDBKeyedConnector(..., writable=True)`: see +one) raises `SpiralDBWriteNotSupportedError`. Use `SpiralDatabase` to store job tables +in SpiralDB. See [Keyed SpiralDB as a Job's Database](spiraldb-keyed-database.md). Replace the example project, dataset and table names with identifiers you can access. diff --git a/docs/concepts/spiraldb-keyed-database.md b/docs/concepts/spiraldb-keyed-database.md index 509af7bf1..c2cb78f49 100644 --- a/docs/concepts/spiraldb-keyed-database.md +++ b/docs/concepts/spiraldb-keyed-database.md @@ -13,24 +13,32 @@ records, operator caches, cached sources and side-effect logs. Open the dataset ## Opening the SpiralDB database -`SpiralDBKeyedConnector(project_id, dataset, writable=True)` opens one dataset as a writable -SpiralDB database. Wrap it in `ConnectorArrowDatabase` and use it as the job's database, its separate result -database, or a cached source's database: +Use `SpiralDatabase(project_id, dataset)` to open a writable database for a job, its +separate result database, or a cached source. Install `orcapod[spiraldb]` and sign in +through spiral-sdk before opening the database. - ```python from orcapod import PipelineJob -from orcapod.databases import ConnectorArrowDatabase, SpiralDBKeyedConnector +from orcapod.databases import SpiralDatabase -database = ConnectorArrowDatabase( - SpiralDBKeyedConnector("my-project-123456", "pipeline_results", writable=True) -) -job = PipelineJob(name="experiment", database=database) + +def make_job(project_id: str, dataset: str) -> PipelineJob: + return PipelineJob(name="experiment", database=SpiralDatabase(project_id, dataset)) ``` -Signing in is spiral-sdk's: the `SPIRAL_*` environment variables, or a saved -`spiral login`. Without `writable=True`, a `SpiralDBKeyedConnector` reads existing keyed tables -(a `SpiralDBTableSource`) and writes nothing. +Call `make_job` with a project identifier and dataset you can write to. + + +```python +job = make_job("my-project-123456", "pipeline_results") +``` + +Spiral-sdk signs in using the `SPIRAL_*` environment variables or a saved `spiral login`. +`SpiralDatabase` currently returns a `ConnectorArrowDatabase` backed by +`SpiralDBKeyedConnector(..., writable=True)` and passes other keyword options, such as +`overrides`, to the connector. The default backend may change in a later release. +Orcapod will announce any change one release ahead. Build the database with the explicit +connector to choose the keyed backend directly. Each stored table is one keyed table of the dataset, named from its path (a readable part of the path and a digest of all of it). Its metadata records the full path, the @@ -111,12 +119,16 @@ one, also released ones: removing one by hand can let two writers in. ## Saving and loading a job -A job saved on the keyed SpiralDB database records `connector_type: spiraldb_keyed` -along with the project, dataset, service address and `writable: true`. It saves no -credentials. Pass the connector again when loading the job: +A job saved using `SpiralDatabase` records its concrete backend. A job on the keyed +backend records `connector_type: spiraldb_keyed` along with the project, dataset, +connection overrides and `writable: true`. It saves no credentials. A change to the +default backend leaves that saved configuration intact. Supply the recorded backend +when loading the job, using the explicit classes to select it directly. ```python +from orcapod.databases import ConnectorArrowDatabase, SpiralDBKeyedConnector + loaded = PipelineJob.load( "experiment.json", database=ConnectorArrowDatabase( diff --git a/src/orcapod/databases/__init__.py b/src/orcapod/databases/__init__.py index f3ed6b908..c2783fd39 100644 --- a/src/orcapod/databases/__init__.py +++ b/src/orcapod/databases/__init__.py @@ -4,6 +4,7 @@ from .in_memory_databases import InMemoryArrowDatabase from .noop_database import NoOpArrowDatabase from .postgresql_connector import PostgreSQLConnector +from .spiral_database import SpiralDatabase from .spiraldb_keyed.connector import SpiralDBKeyedConnector from .sqlite_connector import SQLiteConnector @@ -13,6 +14,7 @@ "ExtensionAwareDatabase", "InMemoryArrowDatabase", "NoOpArrowDatabase", + "SpiralDatabase", "SpiralDBKeyedConnector", "SQLiteConnector", "PostgreSQLConnector", diff --git a/src/orcapod/databases/spiral_database.py b/src/orcapod/databases/spiral_database.py new file mode 100644 index 000000000..1b7cd3fc4 --- /dev/null +++ b/src/orcapod/databases/spiral_database.py @@ -0,0 +1,26 @@ +from typing import Any + +from .connector_arrow_database import ConnectorArrowDatabase +from .spiraldb_keyed.connector import SpiralDBKeyedConnector + + +def SpiralDatabase( + project_id: str, dataset: str, **connector_options: Any +) -> ConnectorArrowDatabase: + """Open a writable SpiralDB database using Orcapod's default backend. + + The factory sets ``writable=True`` and forwards other keyword arguments, + such as ``overrides``, to the keyed connector. + Saved jobs record the concrete backend and its configuration. The default + backend may change in a later release, with one release of advance notice. + + Args: + project_id: SpiralDB project identifier. + dataset: Dataset within the project. + + Returns: + A database backed by a writable ``SpiralDBKeyedConnector``. + """ + return ConnectorArrowDatabase( + SpiralDBKeyedConnector(project_id, dataset, writable=True, **connector_options) + ) diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 3ccca2b7a..de75eea0a 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -29,6 +29,7 @@ ConnectorArrowDatabase, DeltaTableDatabase, InMemoryArrowDatabase, + SpiralDatabase, SpiralDBKeyedConnector, spiraldb_lease, ) @@ -110,12 +111,14 @@ def _rows(n: int = 3) -> pa.Table: def _cached(cache: Any, table: pa.Table, *, order: str = "as given") -> CachedSource: + tags = ["unit", "trial"] if order == "reversed": table = table.select(list(reversed(table.column_names))) + tags.reverse() return CachedSource( ArrowTableSource( table, - tag_columns=["unit", "trial"], + tag_columns=tags, tag_only_columns=True, source_id="trials", record_id_columns=["unit", "trial"], @@ -227,6 +230,26 @@ def _run(job: PipelineJob, entry: str, **kwargs: Any) -> Any: # ------------------------------------------------------------ every table kind +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "run_async"]) +@pytest.mark.parametrize("order", ["as given", "reversed"]) +def test_spiral_database_stores_every_role_like_the_explicit_backend( + entry: str, order: str +) -> None: + database = SpiralDatabase("p", "factory") + explicit = _database("explicit") + for backend in (database, explicit): + calls.clear() + delivered.clear() + _ = _run(_job(backend, order=order), entry) + assert sorted(calls) == [(1, 5), (2, 6), (3, 7)] + assert sorted(delivered) == [6, 8, 10] + + assert sorted(path[-1] for path in database.list_table_paths()) == sorted(LAYOUTS) + _same_tables(database, explicit) + assert _database_tables("factory") == _database_tables("explicit") + + @pytest.mark.usefixtures("root") @pytest.mark.parametrize("entry", ENTRIES) @pytest.mark.parametrize("order", ["as given", "reversed"]) @@ -308,6 +331,54 @@ def test_a_new_input_and_a_replay_are_stored_as_on_delta( # ------------------------------------------------------------------ load only +def test_spiral_database_job_round_trip_records_the_concrete_backend( + root: Path, +) -> None: + overrides = {"server.url": "https://example.invalid"} + database = SpiralDatabase(project_id="p", dataset="d", overrides=overrides) + results = SpiralDatabase(overrides=overrides, dataset="r", project_id="p") + job = _job(database, result_database=results) + _ = job.run() + saved = root / "job.json" + job.save(saved) + bindings = json.loads(saved.read_text())["bindings"] + + explicit = ConnectorArrowDatabase( + SpiralDBKeyedConnector("p", "d", overrides=overrides, writable=True) + ) + explicit_results = ConnectorArrowDatabase( + SpiralDBKeyedConnector("p", "r", overrides=overrides, writable=True) + ) + for slot, dataset, backend in ( + ("database", "d", explicit), + ("result_database", "r", explicit_results), + ): + assert bindings[slot] == backend.to_config() + assert bindings[slot]["type"] == "connector_arrow_database" + assert bindings[slot]["connector"] == { + "connector_type": "spiraldb_keyed", + "project_id": "p", + "dataset": dataset, + "overrides": overrides, + "writable": True, + } + + loaded = PipelineJob.load( + saved, database=explicit, result_database=explicit_results + ) + _ = loaded.run(load_only=True) + for label in ("combine", "select"): + original = job.nodes[label].as_source().as_table() + restored = loaded.nodes[label].as_source().as_table() + assert restored.num_rows == 3 + assert _comparable(restored) == _comparable(original) + saved_again = root / "loaded.json" + loaded.save(saved_again) + recorded = json.loads(saved_again.read_text())["bindings"] + for slot in ("database", "result_database"): + assert recorded[slot] == bindings[slot] + + @pytest.mark.usefixtures("root") def test_a_loaded_job_reads_and_load_only_runs_take_no_lease(root: Path) -> None: spiral_db = _database() From cba5d7429e12190e00f5c6a088de75b740eabe35 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 11:10:16 -0800 Subject: [PATCH 35/46] fix(databases): honor SpiralDatabase write mode --- changelog.d/ITL-1903.md | 5 ++ changelog.d/ITL-1933.md | 4 - docs/concepts/spiraldb-keyed-database.md | 27 +++++- src/orcapod/databases/spiral_database.py | 18 ++-- .../test_spiraldb_writable_runs.py | 85 +++++++++++++++++-- 5 files changed, 118 insertions(+), 21 deletions(-) delete mode 100644 changelog.d/ITL-1933.md diff --git a/changelog.d/ITL-1903.md b/changelog.d/ITL-1903.md index eaaf60d22..6cc67e820 100644 --- a/changelog.d/ITL-1903.md +++ b/changelog.d/ITL-1903.md @@ -1,3 +1,8 @@ +### Added + +- `orcapod.databases.SpiralDatabase(project_id, dataset, ...)` opens a writable SpiralDB + database for a job. Saved jobs record the concrete backend and its configuration. + ### Changed - Renamed `SpiralDBConnector` to `SpiralDBKeyedConnector`. Saved jobs now use the diff --git a/changelog.d/ITL-1933.md b/changelog.d/ITL-1933.md deleted file mode 100644 index a131f2a35..000000000 --- a/changelog.d/ITL-1933.md +++ /dev/null @@ -1,4 +0,0 @@ -### Added - -- `orcapod.databases.SpiralDatabase(project_id, dataset, ...)` opens a writable SpiralDB - database for a job. Saved jobs record the concrete backend and its configuration. diff --git a/docs/concepts/spiraldb-keyed-database.md b/docs/concepts/spiraldb-keyed-database.md index c2cb78f49..c1250df14 100644 --- a/docs/concepts/spiraldb-keyed-database.md +++ b/docs/concepts/spiraldb-keyed-database.md @@ -26,17 +26,36 @@ def make_job(project_id: str, dataset: str) -> PipelineJob: return PipelineJob(name="experiment", database=SpiralDatabase(project_id, dataset)) ``` -Call `make_job` with a project identifier and dataset you can write to. +Call `make_job` with a project identifier and dataset you can write to, then bind +the steps the job will run. ```python +from orcapod import function_pod +from orcapod.sources import DictSource + + +@function_pod(output_keys="double") +def double_reading(reading: int) -> int: + return reading * 2 + + +readings = DictSource( + data=[{"sample_id": "s1", "reading": 3}], + tag_columns=["sample_id"], + tag_only_columns=True, + source_id="readings", +) job = make_job("my-project-123456", "pipeline_results") +with job: + double_reading.pod(readings, label="double") ``` Spiral-sdk signs in using the `SPIRAL_*` environment variables or a saved `spiral login`. `SpiralDatabase` currently returns a `ConnectorArrowDatabase` backed by -`SpiralDBKeyedConnector(..., writable=True)` and passes other keyword options, such as -`overrides`, to the connector. The default backend may change in a later release. +`SpiralDBKeyedConnector`. It defaults to `writable=True` and passes options such as +`overrides` to the connector. Use `writable=False` to open the plain keyed layout. +The default backend may change in a later release. Orcapod will announce any change one release ahead. Build the database with the explicit connector to choose the keyed backend directly. @@ -62,6 +81,8 @@ before the refusal may hold a new lease table, released.) The error names the le 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. +Run the job with the step bound above and handle a lease refusal at the call site. + ```python from orcapod.databases.spiraldb_lease import LeaseBusyError diff --git a/src/orcapod/databases/spiral_database.py b/src/orcapod/databases/spiral_database.py index 1b7cd3fc4..1ff8c8562 100644 --- a/src/orcapod/databases/spiral_database.py +++ b/src/orcapod/databases/spiral_database.py @@ -5,11 +5,15 @@ def SpiralDatabase( - project_id: str, dataset: str, **connector_options: Any + project_id: str, + dataset: str, + *, + writable: bool = True, + **connector_options: Any, ) -> ConnectorArrowDatabase: - """Open a writable SpiralDB database using Orcapod's default backend. + """Open a SpiralDB database using Orcapod's default backend. - The factory sets ``writable=True`` and forwards other keyword arguments, + The factory forwards the write mode and other keyword arguments, such as ``overrides``, to the keyed connector. Saved jobs record the concrete backend and its configuration. The default backend may change in a later release, with one release of advance notice. @@ -17,10 +21,14 @@ def SpiralDatabase( Args: project_id: SpiralDB project identifier. dataset: Dataset within the project. + writable: Use the writable database layout. Pass ``False`` for the plain + keyed connector's layout. Returns: - A database backed by a writable ``SpiralDBKeyedConnector``. + A database backed by a ``SpiralDBKeyedConnector``. """ return ConnectorArrowDatabase( - SpiralDBKeyedConnector(project_id, dataset, writable=True, **connector_options) + SpiralDBKeyedConnector( + project_id, dataset, writable=writable, **connector_options + ) ) diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index de75eea0a..68e117860 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -14,8 +14,10 @@ import warnings import weakref from collections.abc import Callable, Iterator +from dataclasses import replace from pathlib import Path from typing import Any +from unittest.mock import patch import pyarrow as pa import pytest @@ -57,6 +59,7 @@ from orcapod.sources import ArrowTableSource from orcapod.types import CacheMode, ColumnConfig from tests.test_databases import fake_spiral_sdk as fake +from tests.test_docs._doc_samples import extract_blocks, run_blocks pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") @@ -196,17 +199,18 @@ def _types(table: pa.Table) -> dict[str, pa.DataType]: return {f.name: f.type for f in table.schema if f.name not in VOLATILE} -def _same_tables(spiral_db: Any, delta: Any) -> None: +def _same_tables(left: Any, right: Any, *, same_column_order: bool = True) -> None: """Same paths, and in each the same rows, apart from the volatile columns.""" - paths = sorted(spiral_db.list_table_paths()) - assert paths == sorted(delta.list_table_paths()) + paths = sorted(left.list_table_paths()) + assert paths == sorted(right.list_table_paths()) for path in paths: - on_spiral = spiral_db.get_all_records(path) - on_delta = delta.get_all_records(path) - assert on_spiral is not None and on_delta is not None, path - assert on_spiral.schema.names == on_delta.schema.names, path - assert _types(on_spiral) == _types(on_delta), path - assert _comparable(on_spiral) == _comparable(on_delta), path + left_table = left.get_all_records(path) + right_table = right.get_all_records(path) + assert left_table is not None and right_table is not None, path + if same_column_order: + assert left_table.schema.names == right_table.schema.names, path + assert _types(left_table) == _types(right_table), path + assert _comparable(left_table) == _comparable(right_table), path def _run(job: PipelineJob, entry: str, **kwargs: Any) -> Any: @@ -230,6 +234,28 @@ def _run(job: PipelineJob, entry: str, **kwargs: Any) -> Any: # ------------------------------------------------------------ every table kind +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("writable", [True, False]) +def test_spiral_database_forwards_explicit_write_mode(writable: bool) -> None: + overrides = {"server.url": "https://example.invalid"} + default = SpiralDatabase("p", "d", overrides=overrides) + default_backend = ConnectorArrowDatabase( + SpiralDBKeyedConnector("p", "d", overrides=overrides, writable=True) + ) + assert default.to_config() == default_backend.to_config() + + overrides_first = SpiralDatabase("p", "d", overrides=overrides, writable=writable) + writable_first = SpiralDatabase("p", "d", writable=writable, overrides=overrides) + explicit = ConnectorArrowDatabase( + SpiralDBKeyedConnector("p", "d", overrides=overrides, writable=writable) + ) + assert ( + overrides_first.to_config() + == writable_first.to_config() + == explicit.to_config() + ) + + @pytest.mark.usefixtures("root") @pytest.mark.parametrize("entry", ["sync", "run_async"]) @pytest.mark.parametrize("order", ["as given", "reversed"]) @@ -250,6 +276,19 @@ def test_spiral_database_stores_every_role_like_the_explicit_backend( assert _database_tables("factory") == _database_tables("explicit") +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "run_async"]) +def test_spiral_database_storage_is_stable_across_arrangements(entry: str) -> None: + original = SpiralDatabase("p", "original") + reordered = SpiralDatabase("p", "reordered") + _ = _run(_job(original, order="as given"), entry) + _ = _run(_job(reordered, order="reversed"), entry) + + assert sorted(path[-1] for path in original.list_table_paths()) == sorted(LAYOUTS) + assert _database_tables("original") == _database_tables("reordered") + _same_tables(original, reordered, same_column_order=False) + + @pytest.mark.usefixtures("root") @pytest.mark.parametrize("entry", ENTRIES) @pytest.mark.parametrize("order", ["as given", "reversed"]) @@ -362,6 +401,12 @@ def test_spiral_database_job_round_trip_records_the_concrete_backend( "overrides": overrides, "writable": True, } + (cache_slot,) = ( + name + for name, config in bindings["sources"].items() + if config["source_type"] == "cached" + ) + assert bindings["sources"][cache_slot]["cache_database"] == explicit.to_config() loaded = PipelineJob.load( saved, database=explicit, result_database=explicit_results @@ -377,6 +422,7 @@ def test_spiral_database_job_round_trip_records_the_concrete_backend( recorded = json.loads(saved_again.read_text())["bindings"] for slot in ("database", "result_database"): assert recorded[slot] == bindings[slot] + assert recorded["sources"][cache_slot]["cache_database"] == explicit.to_config() @pytest.mark.usefixtures("root") @@ -556,6 +602,27 @@ def _held_by_another_writer(dataset: str = "d") -> Callable[[], None]: return release +@pytest.mark.usefixtures("root") +def test_spiral_database_lease_example_runs_with_a_held_lease() -> None: + page = ( + Path(__file__).resolve().parents[2] / "docs/concepts/spiraldb-keyed-database.md" + ) + setup_and_lease = page.read_text().split("### A lease left behind", 1)[0] + blocks = [replace(block, skip=False) for block in extract_blocks(setup_and_lease)] + _, release = take_lease( + SpiralDBKeyedConnector("my-project-123456", "pipeline_results", writable=True), + "another writer", + ) + try: + with patch("builtins.print", wraps=print) as printed: + results = run_blocks(blocks, str(page)) + assert all(result["status"] == "passed" for result in results), results + printed.assert_called_once() + assert isinstance(printed.call_args.args[0], spiraldb_lease.LeaseBusyError) + finally: + release() + + @pytest.mark.usefixtures("root") @pytest.mark.parametrize("entry", ENTRIES) @pytest.mark.parametrize("load_only", [False, True]) From f4b893efaca797f470be66f49f0c002d8434b4a0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 11:40:05 -0800 Subject: [PATCH 36/46] fix(spiraldb): guard node batching and scope append retries --- changelog.d/ITL-1502.md | 20 ++--- docs/concepts/spiraldb-database.md | 30 +++---- .../databases/connector_arrow_database.py | 35 ++++++-- src/orcapod/databases/spiraldb_tables.py | 39 ++++++-- src/orcapod/pipeline/node_run.py | 9 +- .../test_spiraldb_writable_mode.py | 39 +++++++- .../test_spiraldb_writable_runs.py | 89 ++++++++++++++++--- 7 files changed, 201 insertions(+), 60 deletions(-) diff --git a/changelog.d/ITL-1502.md b/changelog.d/ITL-1502.md index e3e4d1228..bdfb4db17 100644 --- a/changelog.d/ITL-1502.md +++ b/changelog.d/ITL-1502.md @@ -4,16 +4,16 @@ lookups, and stale-table discovery across a run, shared by every connector and thread of the run. Connections reuse resolved table IDs. - A job node's `run()` commits a function node's writes every 100 rows and at its - end for pods without an invocation context when every database the node commits - to is a writable SpiralDB database or an `InMemoryArrowDatabase`, at least one - of them SpiralDB; any other store keeps the - per-row commits. A failed batched result append is retried one row at a time, in - order, so the results before the failing row stay stored. For a definite - failure, the stored rows are those of per-row commits. After an ambiguous reply, - every row before the first failing row gets its pipeline record, including a row - the service had already accepted (it is not appended again); only a row the - service accepted beyond that prefix can stay stored without a pipeline record, - and a later run reuses it as a cached result. No pipeline record dangles. + end when it has a pipeline database, the pod takes no invocation context, and + every database the node commits to is a writable SpiralDB database or an + `InMemoryArrowDatabase`, including at least one writable SpiralDB database. + Other node runs keep per-row commits. A failed batched result append is retried + one row at a time in order. Read and validation errors before the append stop the + run immediately. After a definite append failure, the results and pipeline records + before the failing row stay stored, as with per-row commits. After an ambiguous + reply, each row before the first failing row gets its pipeline record, including + rows the service already accepted. A result the service accepted beyond that prefix + can stay stored without a pipeline record and be reused by a later run. ### Fixed diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index c231b3804..b76fa66eb 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -85,21 +85,21 @@ 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. -A job node's `run()` commits a function node's writes in batches (every 100 rows and -at the node's end, as `job.run()` does) for pods without an invocation context when -every database the node commits to (its pipeline database, its result database, and -its ephemeral result database when its results are ephemeral) is a writable SpiralDB -database or an `InMemoryArrowDatabase`, -and at least one is a writable SpiralDB database. Any other store among them (Delta, -SQL, PostgreSQL) keeps the node committing after every row, so another reader of that -store sees each result as soon as it is stored. A context-taking function node commits -each result before starting the next call. If a batched result append fails, its -rows are appended one at a time, in order, up to the first that fails: the results -before that row and their pipeline records stay stored, as a node committing after -every row keeps them, and the run stops with that row's error. For a definite -failure, the rows that stay stored are those a node committing after every row -keeps. After an ambiguous reply (the service may have accepted some of the batch's -rows before the reply was lost), the ordered retry still publishes a pipeline record +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 +context. The node must commit only to writable SpiralDB databases or +`InMemoryArrowDatabase` instances, including at least one writable SpiralDB database. +Other node runs commit after each row. This includes a standalone function node +with only an ephemeral result database and a node writing to a store such as Delta +or PostgreSQL, where another reader can see each result as it is stored. A +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 diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 0fec536a4..58a06c3a9 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1241,8 +1241,8 @@ def flush_batch(self, record_path: tuple[str, ...]) -> None: def flush_result_batch_in_order( self, record_path: tuple[str, ...], *, publish_records: bool ) -> None: - """Commit a result table's ready records; if the batch fails, commit its rows - one at a time, in order, up to the first that fails. + """Commit a result table's ready records, retrying a failed SpiralDB append + one row at a time, in order, up to the first row that fails. A node run that batches its commits (``node_run.batch_node_commits``) uses this for its result tables, so a permanent failure keeps the results before @@ -1267,7 +1267,7 @@ def flush_result_batch_in_order( Raises: Exception: The first failing row's error, with the batch's error as a - note; nothing when every row commits on its own. + note, or the original error if the batch failed before an append. """ self._flush_by_key(self._get_record_key(record_path), in_order=True) @@ -1276,7 +1276,7 @@ def _flush_by_key(self, record_key: str, *, in_order: bool = False) -> None: Args: record_key: The table's record key. - in_order: After a failed write of several rows, write them one at a time + in_order: After a failed SpiralDB append, write the rows one at a time (``flush_result_batch_in_order``). """ queued_schema = self._schema_from_record_key(record_key) @@ -1292,10 +1292,21 @@ def _flush_by_key(self, record_key: str, *, in_order: bool = False) -> None: if ready is None: return pending, ids = ready + append_failed = False + + def note_append_failure() -> None: + nonlocal append_failed + append_failed = True + try: - self._write_pending(record_key, pending, queued_schema) + self._write_pending( + record_key, + pending, + queued_schema, + on_append_error=note_append_failure if in_order else None, + ) except Exception as batch_error: - if not in_order or pending.num_rows < 2: + if not append_failed or pending.num_rows < 2: self._pending_commits.fail_batch(record_key, pending, ids) raise # Raises, having failed the rows from the first failing one on. @@ -1332,7 +1343,12 @@ def _committed(self, record_key: str, ids: set[bytes]) -> None: ) def _write_pending( - self, record_key: str, pending: pa.Table, queued_schema: str | None + self, + record_key: str, + pending: pa.Table, + queued_schema: str | None, + *, + on_append_error: Callable[[], None] | None = None, ) -> None: """Write rows taken from a table's queue, in the table's transaction.""" skip_duplicates = self._pending_skip_existing.get(record_key, False) @@ -1360,6 +1376,7 @@ def _write_pending( skip_duplicates, table_exists, schema, + on_append_error=on_append_error, ) def _write_rows_in_order( @@ -1415,6 +1432,8 @@ def _write_ready_batch( skip_duplicates: bool, table_exists: bool, schema: str | None, + *, + on_append_error: Callable[[], None] | None, ) -> None: """Check the current schema and write the ready rows.""" tables = self._spiral @@ -1486,7 +1505,7 @@ def _fmt(cols: Mapping[str, pa.DataType]) -> str: # 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. - tables.write(table_name, pending) + tables.write(table_name, pending, on_append_error=on_append_error) elif self._sql_store is None: self._connector.create_table_if_not_exists( table_name, columns, pk_column=self.RECORD_ID_COLUMN diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index 923aea908..7dd712766 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -1061,7 +1061,13 @@ def _require_same_manifest( ) return _Found(str(table.resource_id), record, current) - def write(self, table_name: str, records: pa.Table) -> None: + def write( + self, + table_name: str, + records: pa.Table, + *, + 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 keys already stored and the keys appended during the run. Concurrent writes @@ -1074,6 +1080,7 @@ def write(self, table_name: str, records: pa.Table) -> None: Args: table_name: A name ``table_name`` returned. records: The rows, record id column included. + on_append_error: Called if the SDK append of the rows raises. Raises: ValueError: If the rows hold no ``__data_context`` column, or several data @@ -1093,7 +1100,7 @@ def write(self, table_name: str, records: pa.Table) -> None: # 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) + self._write(table_name, path, context, records, on_append_error) def _write( self, @@ -1101,6 +1108,7 @@ def _write( path: tuple[str, ...], context: str, records: pa.Table, + on_append_error: Callable[[], None] | None, ) -> None: """Write records while holding the lease's lock.""" # A caller's schema check may have written rows since the earlier snapshot @@ -1115,7 +1123,15 @@ def _write( seen, seen_record = opened.seen, opened.record else: seen, seen_record = ("none", None), None - self._write_first(table_name, path, context, records, seen, seen_record) + self._write_first( + table_name, + path, + context, + records, + seen, + seen_record, + on_append_error, + ) return found = opened.found _require_data_context(found, context) @@ -1139,7 +1155,7 @@ def _write( if encoded.num_rows == 0: return # a write of no rows is never sent self._forget_opened(table_name) - self._append(opened.table, found, encoded) + self._append(opened.table, found, encoded, on_append_error) def _write_first( self, @@ -1149,6 +1165,7 @@ def _write_first( records: pa.Table, seen: _Seen, seen_record: identity.TableRecord | None, + on_append_error: Callable[[], None] | None, ) -> None: """The first write of a table judged absent or new (``write``). @@ -1161,6 +1178,7 @@ def _write_first( (``_seen_manifest``; ``("none", None)`` when it was absent). seen_record: The identity record it held then (``None`` when absent or unrecorded): a changed record is never recorded over. + on_append_error: Called if the SDK append of the rows raises. """ manifest = codec.new_manifest(path, path[-1], records.schema) metadata = { @@ -1190,7 +1208,7 @@ def _write_first( encoded = _encoded(_without_ids(records, held)) self._ids_by_name[table_name] = recorded.table_id if encoded.num_rows > 0: - self._append(table, recorded, encoded) + self._append(table, recorded, encoded, on_append_error) if first_append: try: with self._service_call("mark a database table as holding rows"): @@ -1200,13 +1218,20 @@ def _write_first( "Could not mark SpiralDB table as holding rows", exc_info=True ) - def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: + def _append( + self, + table: _KeyedTable, + found: _Found, + encoded: pa.Table, + on_append_error: Callable[[], None] | None, + ) -> None: """Append encoded rows; keep what the table records only once that succeeded. Args: table: The table, opened under its name. found: What it records. 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 @@ -1230,6 +1255,8 @@ def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: _ = catalog.names.setdefault( 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 diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 05246aa95..0bd555795 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -729,10 +729,9 @@ def batches_node_commits(node: Any) -> bool: """Whether a node run (a job node's ``run()``, outside ``job.run()``) commits this node's writes in batches; the one place this is decided. - A function job node without an invocation context batches when every database - its commits write (its pipeline database, its result database, and its ephemeral - result database when its results are ephemeral) is either a writable SpiralDB - database or an ``InMemoryArrowDatabase``, and at least one is a writable SpiralDB + A function job node with a pipeline database and without an invocation context + batches when every store it commits to is a writable SpiralDB database or an + ``InMemoryArrowDatabase``, and at least one is a writable SpiralDB database. Each SpiralDB append is a service request, and an in-memory store has no reader outside the process. Every other node keeps committing after every row. A Delta, SQL, PostgreSQL or read-only store anywhere among its databases keeps @@ -752,6 +751,8 @@ def batches_node_commits(node: Any) -> bool: if not isinstance(node, FunctionJobNode) or not any_writable_connector(): return False + if node._pipeline_database is None: # pyright: ignore[reportPrivateUsage] # batched commits publish pipeline records + return False if node._delivers_side_effects: # pyright: ignore[reportPrivateUsage] # the run sets the commit cadence return False databases = node._committed_databases() # pyright: ignore[reportPrivateUsage] # the run sets the commit cadence diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index 8ca11d9ea..fd8b903e8 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -2407,13 +2407,11 @@ def test_a_table_left_empty_by_a_failed_first_write_is_not_listed( """Recorded, then its first append failed: no rows, so nothing stored there.""" db = ConnectorArrowDatabase(writable_connector()) - def failing( - self: SpiralDBTables, table: Any, found: Any, encoded: pa.Table - ) -> None: + def failing(table: fake.FakeKeyedTable, batch: pa.Table) -> fake.FakeKeyedTable: raise RuntimeError("the append failed") with monkeypatch.context() as patched: - patched.setattr(SpiralDBTables, "_append", failing) + patched.setattr(fake.FakeKeyedTable, "append", failing) with pytest.raises(Exception, match="the append failed"): db.add_records( RESULT, rows(["r0"]), record_id_column="__record_id", flush=True @@ -2534,6 +2532,37 @@ def check(schema: pa.Schema) -> None: assert stored["__record_id"].to_pylist() == [b"first"] +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("ids", [["first", "second"], ["second", "first"]]) +def test_an_ordered_flush_propagates_a_schema_guard_read_failure( + ids: list[str], +) -> None: + """A transient pre-write read error still aborts the flush without appending.""" + db = ConnectorArrowDatabase(writable_connector()) + _add(db, rows(ids)) + read_error = OrcapodDatabaseReadError("result", RESULT) + attempted: list[pa.Schema] = [] + + def check(schema: pa.Schema) -> None: + attempted.append(schema) + if len(attempted) == 1: + raise read_error + + with ( + db.guard_table_schema(RESULT, check), + pytest.raises(OrcapodDatabaseReadError) as raised, + ): + db.flush_result_batch_in_order(RESULT, publish_records=True) + + assert raised.value is read_error + assert len(attempted) == 1 + assert _get(ConnectorArrowDatabase(writable_connector())) is None + _add(db, rows(ids)) + db.flush_result_batch_in_order(RESULT, publish_records=True) + assert (stored := _get(ConnectorArrowDatabase(writable_connector()))) is not None + assert sorted(_record_ids(stored)) == sorted(item.encode() for item in ids) + + # ------------------------------------- review round 7 (PR 692): CodeRabbit, final head @@ -2650,6 +2679,7 @@ def test_an_ambiguous_append_never_lets_another_connector_overwrite_its_key( 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.""" result = append(table, batch) if b"r1" in batch.column("__record_id").to_pylist(): raise fake.SpiralError("the reply was lost") @@ -2780,6 +2810,7 @@ def test_an_ambiguous_first_append_is_reported_stale_at_once( 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.""" result = append(table, batch) if "__record_id" in batch.column_names: raise fake.SpiralError("the reply was lost") diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 8e545cbf8..b872ab201 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -23,6 +23,7 @@ import pytest from orcapod import PipelineJob, function_pod +from orcapod.core.function_pod import FallThroughPod, FunctionPod from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.core.nodes.source_node import SourceJobNode, SourceNode @@ -57,10 +58,15 @@ from orcapod.pipeline import node_run from orcapod.pipeline.execution_context import ExecutionContext from orcapod.semantic_types.universal_converter import UniversalTypeConverter -from orcapod.side_effects import InvocationContext, SideEffectPod, sink_pod +from orcapod.side_effects import ( + InvocationContext, + SideEffectJobNode, + SideEffectPod, + sink_pod, +) from orcapod.sources import ArrowTableSource from orcapod.protocols.core_protocols import StreamProtocol -from orcapod.types import CacheMode, ColumnConfig, ContentHash +from orcapod.types import CacheMode, ColumnConfig, ContentHash, NodeConfig from tests.test_databases import fake_spiral_sdk as fake pytestmark = [ @@ -1085,9 +1091,17 @@ def counted(table: fake.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any: ) assert len(reads) == 1 + checks: list[str] = [] + check = spiraldb_lease.check + + 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"): - reads.clear() - assert reads == [] + pass + assert len(checks) == 1 # acquisition only @pytest.mark.usefixtures("root") @@ -1798,8 +1812,8 @@ def test_a_cached_source_behind_a_held_table_is_still_leased() -> None: # ----------------------------------------------- independent review of 48aa8c871 -def _receipt_job(database: Any, table: pa.Table, observe: Any, *labels: str) -> Any: - """A tracked sink per label over one source of two tags and two data columns.""" +def _receipt_job(database: Any, table: pa.Table, observe: Any, label: str) -> Any: + """A job with one tracked sink over a source of two tags and two data columns.""" source = ArrowTableSource( table, tag_columns=["group", "item"], @@ -1811,12 +1825,12 @@ def _receipt_job(database: Any, table: pa.Table, observe: Any, *labels: str) -> with job: pod = sink_pod(observe) assert isinstance(pod, SideEffectPod) - for label in labels: - pod.process(source, label=label) + pod.process(source, label=label) return job def _receipt_rows(items: list[int]) -> pa.Table: + """Keep item order and give each item the observable value ``x = 11 * item``.""" schema = pa.schema( [ pa.field("group", pa.large_string(), nullable=False), @@ -1886,11 +1900,28 @@ def observe(x: int, y: int, ctx: Any) -> None: @pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) @pytest.mark.parametrize("labels", [("first", "second"), ("second", "first")]) def test_two_sinks_sharing_a_tracking_table_deliver_each_row_once( - root: Path, entry: str, labels: tuple[str, str] + root: Path, monkeypatch: pytest.MonkeyPatch, entry: str, labels: tuple[str, str] ) -> None: """Two tracked sinks of one pod over one source share one invocation log; every row is delivered once, as on Delta.""" observed: dict[str, list[int]] = {} + checked: dict[str, list[tuple[tuple[str, ...], bytes]]] = {} + completion_lookup = SideEffectJobNode._completion_lookup # pyright: ignore[reportPrivateUsage] + + def trace_lookup(node: SideEffectJobNode) -> Callable[[bytes], bool] | None: + lookup = completion_lookup(node) + if lookup is None: + return None + path = node._table_path # pyright: ignore[reportPrivateUsage] + assert path is not None + + def trace(record_id: bytes) -> bool: + checked.setdefault(node.label, []).append((path, record_id)) + return lookup(record_id) + + return trace + + monkeypatch.setattr(SideEffectJobNode, "_completion_lookup", trace_lookup) for name, database in ( ("spiral", _database()), ("delta", DeltaTableDatabase(root / "delta")), @@ -1900,9 +1931,15 @@ def test_two_sinks_sharing_a_tracking_table_deliver_each_row_once( def observe(x: int, y: int, ctx: Any, found: list[int] = found) -> None: found.append(x) - job = _receipt_job(database, _receipt_rows([1, 2, 3]), observe, *labels) - _ = _run(job, entry) + # The same invocation captured twice in one graph is compiled to one node. + for label in labels: + job = _receipt_job(database, _receipt_rows([1, 2, 3]), observe, label) + _ = _run(job, entry) observed[name] = sorted(found) + assert set(checked) == set(labels) + assert len(checked[labels[0]]) == 3 + assert sorted(checked[labels[0]]) == sorted(checked[labels[1]]) + assert len({path for path, _ in checked[labels[0]]}) == 1 assert observed["spiral"] == observed["delta"] == [11, 22, 33] @@ -1966,8 +2003,6 @@ def test_a_node_run_over_an_ephemeral_spiral_result_store_appends_once( """Review S2: an in-memory job with a writable SpiralDB ephemeral result store batches its node run: the three results are one append, and the node shows the rows and counts an in-memory ephemeral store gives.""" - from orcapod.types import NodeConfig - outcomes: list[Any] = [] for ephemeral in (_database(), InMemoryArrowDatabase()): job = PipelineJob(name=JOB, database=InMemoryArrowDatabase()) @@ -1993,6 +2028,34 @@ def test_a_node_run_over_an_ephemeral_spiral_result_store_appends_once( assert outcomes[0] == outcomes[1] +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("order", ORDERS) +def test_a_standalone_ephemeral_node_commits_results_one_at_a_time( + monkeypatch: pytest.MonkeyPatch, order: str +) -> None: + """A node with only an ephemeral store can run and commit each result.""" + database = _database() + source = _cached(InMemoryArrowDatabase(), _rows(), order=order) + plain_pod = combine.pod + assert isinstance(plain_pod, FunctionPod) + pod = ( + FallThroughPod(plain_pod, ("unit", "trial")) + if order == "data-tags" + else plain_pod + ) + node = FunctionJobNode(pod, source, ephemeral_database=database) + node.node_config = NodeConfig(is_result_ephemeral=True) + appended = _result_appends(monkeypatch) + + _ = node.run() + + assert node.as_table().num_rows == 3 + assert appended == [1, 1, 1] + [path] = database.list_table_paths() + stored = database.get_all_records(path) + assert stored is not None and stored.num_rows == 3 + + @pytest.mark.usefixtures("root") @pytest.mark.parametrize("order", ORDERS) @pytest.mark.parametrize("target", ["combine", "select"]) From 9aa1062abfd3311fe0ea1db6fd2d36c080513e04 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 12:10:34 -0800 Subject: [PATCH 37/46] fix(spiraldb): settle ordered retries before annotating errors --- .../databases/connector_arrow_database.py | 12 +-- .../test_spiraldb_writable_mode.py | 73 +++++++++++++++++++ .../test_spiraldb_writable_runs.py | 47 +++++++++++- 3 files changed, 124 insertions(+), 8 deletions(-) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 705009828..70e9c0f5b 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1416,7 +1416,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()) @@ -1426,16 +1426,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 diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index 82eca51ed..c203d0e9c 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -2092,6 +2092,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) @@ -2108,6 +2109,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)) @@ -2506,6 +2528,57 @@ def check(schema: pa.Schema) -> None: 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") @pytest.mark.parametrize("ids", [["first", "second"], ["second", "first"]]) def test_an_ordered_flush_propagates_a_schema_guard_read_failure( diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index bf778c447..0325ce699 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -185,6 +185,7 @@ def root(tmp_path: Path) -> Iterator[Path]: 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) ) @@ -708,6 +709,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() @@ -778,10 +780,12 @@ class SnapshotSource(ArrowTableSource): @override def pinned_snapshot(self) -> SnapshotSource: + """Keep this instrumented snapshot for the reader.""" return self @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 @@ -853,6 +857,7 @@ def test_a_retried_attachment_flush_runs_under_its_dataset_scope() -> 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") @@ -865,7 +870,14 @@ 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() + 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"] @@ -1640,6 +1652,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 @@ -1647,6 +1660,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) @@ -1790,8 +1804,9 @@ 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 @@ -1803,6 +1818,7 @@ def test_a_permanent_result_failure_keeps_the_rows_before_it( 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() ) @@ -1818,12 +1834,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) @@ -1840,7 +1858,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"): @@ -1859,6 +1881,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") @@ -2081,6 +2113,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( @@ -2144,6 +2177,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) @@ -2329,6 +2363,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 @@ -2435,6 +2470,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 @@ -2483,6 +2519,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() @@ -2538,6 +2575,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 @@ -2562,6 +2600,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) @@ -2631,6 +2670,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 @@ -2743,10 +2783,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 ) @@ -2842,6 +2884,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": From c43a983a9242aaae9db66982770b87295977c812 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 12:41:19 -0800 Subject: [PATCH 38/46] fix(spiraldb): separate snapshot opens from append failures --- src/orcapod/databases/spiraldb_tables.py | 19 +++++++---- .../test_spiraldb_writable_mode.py | 34 +++++++++++++++++++ 2 files changed, 46 insertions(+), 7 deletions(-) diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index 9fc451595..8ff778619 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -292,7 +292,8 @@ def __init__(self, table_id: str, open_by_id: Callable[[str], _KeyedTable]) -> N self._open_by_id: Callable[[str], _KeyedTable] = open_by_id self._opened: _KeyedTable | None = None - def _table(self) -> _KeyedTable: + 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 @@ -305,19 +306,19 @@ def resource_id(self) -> str: @property def key_columns(self) -> tuple[str, ...]: """Return the key columns, opening the snapshot on first use.""" - return self._table().key_columns + return self.open().key_columns def schema(self) -> pa.Schema: """Return the schema, opening the snapshot on first use.""" - return self._table().schema() + return self.open().schema() def get_metadata(self) -> dict[str, bytes]: """The table's metadata entries, as stored.""" - return self._table().get_metadata() + return self.open().get_metadata() def set_metadata(self, metadata: dict[str, bytes]) -> None: """Record metadata entries (an upsert of the given keys).""" - self._table().set_metadata(metadata) + self.open().set_metadata(metadata) def scan( self, @@ -327,11 +328,11 @@ def scan( limit: int | None = None, ) -> _Scan: """A read of the snapshot (``_KeyedTable.scan``).""" - return self._table().scan(columns, filter=filter, limit=limit) + return self.open().scan(columns, filter=filter, limit=limit) def append(self, data: pa.Table) -> _KeyedTable: """Write rows (``_KeyedTable.append``).""" - return self._table().append(data) + return self.open().append(data) _Seen = tuple[str, object] @@ -1545,6 +1546,10 @@ def _append( # 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())) + # 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 diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index c203d0e9c..904a6734e 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -2610,6 +2610,40 @@ 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, From bd084a7f98e8fbca4da064661e54635d7281193b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 14:14:32 -0800 Subject: [PATCH 39/46] fix(spiraldb): keep write scopes open during cancelled calls --- src/orcapod/core/data_function.py | 17 +---- src/orcapod/core/executors/local.py | 66 ++++++++++++++--- .../databases/connector_arrow_database.py | 5 ++ .../databases/extension_aware_database.py | 7 ++ src/orcapod/protocols/spiraldb_run.py | 15 +++- .../test_spiraldb_writable_runs.py | 24 +++++-- .../test_spiraldb_write_lock.py | 71 +++++++++++++++++++ .../test_observer_main_compatibility.py | 10 ++- 8 files changed, 182 insertions(+), 33 deletions(-) diff --git a/src/orcapod/core/data_function.py b/src/orcapod/core/data_function.py index 91102ec7d..3953a8e41 100644 --- a/src/orcapod/core/data_function.py +++ b/src/orcapod/core/data_function.py @@ -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 ( @@ -1392,8 +1393,6 @@ 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 @@ -1402,19 +1401,7 @@ async def direct_async_call( 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]: 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/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 70e9c0f5b..8ae194f9b 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1581,6 +1581,11 @@ 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 diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index 8c8cc8f80..297aac72f 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -107,6 +107,13 @@ 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): diff --git a/src/orcapod/protocols/spiraldb_run.py b/src/orcapod/protocols/spiraldb_run.py index 853e943db..b2ec55398 100644 --- a/src/orcapod/protocols/spiraldb_run.py +++ b/src/orcapod/protocols/spiraldb_run.py @@ -10,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: @@ -57,7 +62,10 @@ def invocation_write_scope(database: object) -> AbstractContextManager[None]: @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): + if ( + not isinstance(database, SpiralDBRunLookupProtocol) + or not database.spiral_writable + ): yield return with database.spiral_write_scope(): @@ -74,6 +82,11 @@ def acquire_invocation_write_locks() -> None: 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 InOrderResultFlushProtocol(Protocol): """A store that can commit a failed result batch's rows one at a time.""" diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 0325ce699..a511de93c 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -1966,20 +1966,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( @@ -2003,6 +2006,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) @@ -2036,8 +2041,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]] @@ -2045,7 +2055,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]] = [] @@ -2055,10 +2065,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, diff --git a/tests/test_databases/test_spiraldb_write_lock.py b/tests/test_databases/test_spiraldb_write_lock.py index 835c9c2cd..4fb2d7fa3 100644 --- a/tests/test_databases/test_spiraldb_write_lock.py +++ b/tests/test_databases/test_spiraldb_write_lock.py @@ -6,6 +6,7 @@ from collections.abc import Callable from concurrent.futures import ThreadPoolExecutor from contextvars import copy_context +from threading import Event from typing import Any, cast import pyarrow as pa @@ -17,6 +18,7 @@ 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.operators import SelectDataColumns from orcapod.databases import ( @@ -1075,6 +1077,75 @@ async def outer(x: int, ctx: InvocationContext) -> int: 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( + 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() + + 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" + ) + loop.set_default_executor(ThreadPoolExecutor(max_workers=1)) + blocker = loop.run_in_executor(None, finish.wait) if queued else None + task = asyncio.create_task(cached.async_call(Data({"x": 1}), ctx=None)) + successor = _database(lock=lock) + try: + if queued: + await asyncio.sleep(0) + 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: 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] ) From 98c96ae7e00b727a304dc65a9abba88911f52fb3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 14:16:11 -0800 Subject: [PATCH 40/46] fix(spiraldb): retry node batches and refresh table bindings --- changelog.d/ITL-1502.md | 4 +- docs/concepts/spiraldb-database.md | 9 +- src/orcapod/core/database_writes.py | 15 ++- src/orcapod/core/nodes/function_node.py | 13 +- src/orcapod/databases/_pending_commits.py | 13 ++ .../databases/connector_arrow_database.py | 5 + .../databases/extension_aware_database.py | 11 +- src/orcapod/databases/spiraldb_tables.py | 2 + src/orcapod/pipeline/job.py | 17 +-- src/orcapod/pipeline/node_run.py | 44 +++++-- src/orcapod/protocols/spiraldb_run.py | 8 +- .../test_spiraldb_writable_mode.py | 23 ++++ .../test_spiraldb_writable_runs.py | 113 ++++++++++++++++++ .../test_job_attached_database_commit.py | 5 +- 14 files changed, 244 insertions(+), 38 deletions(-) diff --git a/changelog.d/ITL-1502.md b/changelog.d/ITL-1502.md index bdfb4db17..e1e25eb69 100644 --- a/changelog.d/ITL-1502.md +++ b/changelog.d/ITL-1502.md @@ -2,7 +2,7 @@ - Writable SpiralDB jobs reuse lease verification, 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. + 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 end when it has a pipeline database, the pod takes no invocation context, and every database the node commits to is a writable SpiralDB database or an @@ -14,6 +14,8 @@ reply, each row before the first failing row gets its pipeline record, including rows the service already accepted. A result the service accepted beyond that prefix can stay stored without a pipeline record and be reused by a later run. + Failed pipeline-record appends also retry one row at a time. An interrupted node + run withdraws its pending results and pipeline records. ### Fixed diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index b76fa66eb..a0de9b152 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -106,8 +106,15 @@ service accepted beyond that prefix, from the failing row on, can stay stored wi 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. +A failed batched pipeline-record append also retries the records in order. The +records before the first permanent failure stay published. The results were +committed first, so later runs can reuse them even if publishing their records +failed. An interrupted node run withdraws its still-pending results and pipeline +records. Results and records already committed stay stored. + A connection resolves a table by name and checks its recorded path when it finds -the table. Later operations use the resolved table ID for that connection. +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 diff --git a/src/orcapod/core/database_writes.py b/src/orcapod/core/database_writes.py index b5e38b787..97a3a001c 100644 --- a/src/orcapod/core/database_writes.py +++ b/src/orcapod/core/database_writes.py @@ -7,7 +7,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Protocol -from orcapod.databases._pending_commits import observe_records +from orcapod.databases._pending_commits import observe_queue, observe_records if TYPE_CHECKING: from collections.abc import Callable, Collection, Iterator, Set @@ -31,6 +31,13 @@ def stores_records(self) -> bool: ... +def shared_database_queue(database: WriteDatabase) -> PendingCommits | None: + """Identify a view's native pending queue through its forwarded path.""" + with observe_queue() as queues: + _ = database.base_path + return queues[0] if len(queues) == 1 else None + + @dataclass class _Write: """One write site that still needs its database's final whole flush.""" @@ -92,6 +99,12 @@ def function_databases(self) -> dict[int, WriteDatabase]: if write.function } + def withdraw_pending_function_writes(self) -> None: + """Withdraw function results and pipeline records still pending from this run.""" + for (_, (key, _)), write in self._writes.items(): + if write.function: + write.pending.withdraw_pending(key, write.ids) + def logs_to_replay(self, queue: int) -> dict[LogTable, set[bytes]] | None: """Keep the IDs from pending logs without querying the store after failure.""" logs: dict[LogTable, set[bytes]] = {} diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index c35c0b70f..d46becd81 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -126,7 +126,7 @@ ) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.hashing_protocols import IdentityWalkProtocol -from orcapod.protocols.spiraldb_run import InOrderResultFlushProtocol +from orcapod.protocols.spiraldb_run import InOrderFlushProtocol from orcapod.protocols.observability_protocols import ( DataExecutionLoggerProtocol, ExecutionObserverProtocol, @@ -2485,10 +2485,9 @@ def _batched_commits( Args: rows_per_commit: How many processed rows' writes one commit holds. - results_in_order: Commit a failed result batch's rows one at a time, in - order, up to the first that fails, where the result store can - (``InOrderResultFlushProtocol``): the results before the failing - row, and their records, stay as a node committing every row keeps. + results_in_order: Retry failed result and pipeline-record appends one + row at a time up to the first failure, where the store supports + ordered retry (``InOrderFlushProtocol``). Yields: Nothing; the node commits in batches while the block runs. @@ -2525,13 +2524,15 @@ def _flush_node_table( if ( result and self._results_in_order - and isinstance(database, InOrderResultFlushProtocol) + and isinstance(database, InOrderFlushProtocol) ): database.flush_result_batch_in_order( path, publish_records=publish_records ) elif result: database.flush_result_batch(path, publish_records=publish_records) + elif self._results_in_order and isinstance(database, InOrderFlushProtocol): + database.flush_batch_in_order(path) else: database.flush_batch(path) except BaseException as exc: diff --git a/src/orcapod/databases/_pending_commits.py b/src/orcapod/databases/_pending_commits.py index 81a6a5b4d..c6c167f21 100644 --- a/src/orcapod/databases/_pending_commits.py +++ b/src/orcapod/databases/_pending_commits.py @@ -183,6 +183,19 @@ def discard(self, key: str, ids: set[bytes], attempt: PendingCommit) -> None: guards = self._guards.get(key, {}) ids = {record_id for record_id in ids if guards.get(record_id) is attempt} self.forget(key, ids) + self._remove_pending(key, ids) + + def withdraw_pending(self, key: str, ids: set[bytes]) -> None: + """Withdraw still-pending rows enqueued by an interrupted caller.""" + pending = ids.intersection(self._ids.get(key, ())) + if not pending: + return + self.forget(key, pending) + self._remove_pending(key, pending) + self.finish(key, committed=False, ids=pending if key in self._batches else None) + + def _remove_pending(self, key: str, ids: set[bytes]) -> None: + """Remove queued rows and clear table-level state if the queue is empty.""" held_ids = self._ids.get(key) if held_ids is None or not held_ids.intersection(ids): return diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 58a06c3a9..b3f61949a 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1237,6 +1237,11 @@ 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 + 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 def flush_result_batch_in_order( self, record_path: tuple[str, ...], *, publish_records: bool diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index a17ace89b..e28eeb65a 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -29,7 +29,7 @@ from orcapod.logical_types.database_hooks import register_discovered_logical_types from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.spiraldb_run import ( - InOrderResultFlushProtocol, + InOrderFlushProtocol, SpiralDBRunLookupProtocol, ) @@ -241,6 +241,13 @@ def flush_batch(self, record_path: tuple[str, ...]) -> None: """Flush the wrapped pipeline batch.""" self._db.flush_batch(record_path) + def flush_batch_in_order(self, record_path: tuple[str, ...]) -> None: + """Flush the wrapped pipeline batch in order when the wrapped store can.""" + if isinstance(self._db, InOrderFlushProtocol): + self._db.flush_batch_in_order(record_path) + else: + self._db.flush_batch(record_path) + def flush_result_batch( self, record_path: tuple[str, ...], *, publish_records: bool ) -> None: @@ -251,7 +258,7 @@ def flush_result_batch_in_order( self, record_path: tuple[str, ...], *, publish_records: bool ) -> None: """Flush the wrapped result batch in order when the wrapped store can.""" - if isinstance(self._db, InOrderResultFlushProtocol): + if isinstance(self._db, InOrderFlushProtocol): self._db.flush_result_batch_in_order( record_path, publish_records=publish_records ) diff --git a/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index 7dd712766..300c11e37 100644 --- a/src/orcapod/databases/spiraldb_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -922,6 +922,8 @@ def hold_lease(self, check: WriterLease) -> None: raise RuntimeError( "these database tables are already written under a lease" ) + # A table may have been replaced since this connector last used its name. + self._ids_by_name.clear() self._lease_check = check def let_go_of_lease(self, check: WriterLease) -> None: diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index d6bdd6aa9..6637025dc 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -14,7 +14,11 @@ from typing import TYPE_CHECKING, Any, cast import orcapod -from orcapod.core.database_writes import DatabaseWrites, collect_database_writes +from orcapod.core.database_writes import ( + DatabaseWrites, + collect_database_writes, + shared_database_queue, +) from orcapod.core.identity_chains import graph_hash from orcapod.core.nodes import JobNode from orcapod.core.nodes.function_node import FunctionJobNode @@ -25,7 +29,6 @@ from orcapod.core.sources.derived_source import DerivedSource from orcapod.core.streams.base import StreamBase from orcapod.core.tracker import AutoRegisteringContextBasedTracker -from orcapod.databases._pending_commits import observe_queue from orcapod.databases.utils import as_table_committing from orcapod.errors import ( InconsistentSourceError, @@ -92,7 +95,6 @@ from orcapod.core.nodes.source_node import ( _DeclaredForm, # pyright: ignore[reportPrivateUsage] # shared binding transaction ) - from orcapod.databases._pending_commits import PendingCommits from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.execution_context import ExecutionContext from orcapod.pipeline.graph import Pipeline @@ -145,13 +147,6 @@ def _supports_attachment_enrollment(database: WriteDatabase) -> bool: ) -def _shared_queue(database: WriteDatabase) -> PendingCommits | None: - """Identify an owned view's queue through its forwarded path property.""" - with observe_queue() as queues: - _ = database.base_path - return queues[0] if len(queues) == 1 else None - - class _Unchanged(enum.Enum): """The default of ``PipelineJob.bind(result_database=...)``: keep the binding. @@ -1848,7 +1843,7 @@ def _prepare_run( (pipeline_db, result_db, *self._node_database_views, self._database) if plan.to_run and not load_only else (), - shared_queue=_shared_queue, + shared_queue=shared_database_queue, supports_enrollment=_supports_attachment_enrollment, retry_log_queues={ queue diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 0bd555795..75d5409a1 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -21,6 +21,11 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any +from orcapod.core.database_writes import ( + DatabaseWrites, + collect_database_writes, + shared_database_queue, +) from orcapod.errors import ( CachedSourceChangedRowError, OrcapodDatabaseError, @@ -767,25 +772,40 @@ def batches_node_commits(node: Any) -> bool: def batch_node_commits(nodes: Sequence[Any], *, load_only: bool) -> Iterator[None]: """Commit in batches the writes of the nodes ``batches_node_commits`` names. - A failed result batch is committed one row at a time, in order, up to the - first failing row, so a permanent failure keeps the results and records a node - committing every row keeps (``FunctionJobNode._batched_commits``). + Failed appends can retry in order. On interruption, withdraw still-pending + function writes from this run before relinquishing the write scope. Args: nodes: The nodes the run executes. load_only: Whether the run is load-only: it writes nothing, so nothing is batched. """ - with contextlib.ExitStack() as stack: - if not load_only: - for node in nodes: - if batches_node_commits(node): - stack.enter_context( - node._batched_commits( # pyright: ignore[reportPrivateUsage] # the run sets the commit cadence - DEFAULT_COMMIT_EVERY_ROWS, results_in_order=True - ) - ) + batched = ( + [] if load_only else [node for node in nodes if batches_node_commits(node)] + ) + if not batched: yield + return + writes = DatabaseWrites( + (), + shared_queue=shared_database_queue, + supports_enrollment=lambda _: True, + retry_log_queues=(), + ) + with contextlib.ExitStack() as stack: + for node in batched: + stack.enter_context( + node._batched_commits( # pyright: ignore[reportPrivateUsage] # the run sets the commit cadence + DEFAULT_COMMIT_EVERY_ROWS, results_in_order=True + ) + ) + stack.enter_context(collect_database_writes(writes)) + try: + yield + except BaseException as error: + if not isinstance(error, Exception): + writes.withdraw_pending_function_writes() + raise def run_with_dependencies( diff --git a/src/orcapod/protocols/spiraldb_run.py b/src/orcapod/protocols/spiraldb_run.py index a69ff0e78..c55a1f8ce 100644 --- a/src/orcapod/protocols/spiraldb_run.py +++ b/src/orcapod/protocols/spiraldb_run.py @@ -22,8 +22,12 @@ def spiral_completion_lookup( @runtime_checkable -class InOrderResultFlushProtocol(Protocol): - """A store that can commit a failed result batch's rows one at a time.""" +class InOrderFlushProtocol(Protocol): + """A store that can commit a failed batch's rows one at a time.""" + + def flush_batch_in_order(self, record_path: tuple[str, ...]) -> None: + """Commit ready pipeline records, retrying a failed append in row order.""" + ... def flush_result_batch_in_order( self, record_path: tuple[str, ...], *, publish_records: bool diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index fd8b903e8..489fcbadb 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -2844,3 +2844,26 @@ async def exercise() -> None: with database_writes([first, second, third], owner="test"): asyncio.run(exercise()) assert stale() == sorted(paths) + + +@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"): + _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"): + _add(replacement, rows(["replacement"]), flush=True) + with database_writes([database], owner="write to replacement"): + _add(database, rows(["new"]), flush=True) + + retired = client.keyed_table_by_id(retired_id).scan().to_table() + current = client.keyed_table("p", "d", name).scan().to_table() + assert _record_ids(retired) == [b"old"] + assert sorted(_record_ids(current)) == [b"new", b"replacement"] diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index b872ab201..93c55b0c2 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -66,6 +66,7 @@ ) from orcapod.sources import ArrowTableSource from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.types import CacheMode, ColumnConfig, ContentHash, NodeConfig from tests.test_databases import fake_spiral_sdk as fake @@ -3156,3 +3157,115 @@ def build() -> tuple[CachedSource, Any, PipelineJob]: assert cache.list_table_paths() == [] if unstorable == "SpiralDB column": assert _database_tables("cache") == [] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("reject_single_row", [False, True]) +def test_node_run_retries_rejected_pipeline_records_in_order( + monkeypatch: pytest.MonkeyPatch, reject_single_row: bool +) -> None: + """A failed pipeline append retries its ready rows through the first rejection.""" + from orcapod.errors import OrcapodDatabaseWriteError + + append = fake.FakeKeyedTable.append + attempts: list[list[bytes]] = [] + + def reject(table: fake.FakeKeyedTable, batch: pa.Table) -> fake.FakeKeyedTable: + record = spiral_database_identity.read_table_identity_metadata( + table.get_metadata() + ) + if record is not None and record.path[-1] == "pdb_v2": + keys = cast("list[bytes]", batch["__record_id"].to_pylist()) + attempts.append(keys) + if len(keys) > 1: + raise fake.SpiralError("rejected batch") + if reject_single_row and keys == attempts[0][1:2]: + raise fake.SpiralError("rejected second row") + return append(table, batch) + + monkeypatch.setattr(fake.FakeKeyedTable, "append", reject) + node = cast("FunctionJobNode", _job(_database()).nodes["combine"]) + if reject_single_row: + with pytest.raises(OrcapodDatabaseWriteError, match="rejected second row"): + _ = node.run() + else: + _ = node.run() + + batch, *single_rows = attempts + assert len(batch) == 3 + assert single_rows == [[key] for key in batch[: 2 if reject_single_row else 3]] + fresh = _database() + paths = {path[-1]: path for path in fresh.list_table_paths()} + results = fresh.get_all_records(paths["rdb_v1"], record_id_column="__record_id") + records = fresh.get_all_records(paths["pdb_v2"], record_id_column="__record_id") + assert results is not None and results.num_rows == 3 + assert records is not None + assert set(records["__record_id"].to_pylist()) == set( + batch[: 1 if reject_single_row else 3] + ) + assert set(records["__data_id"].to_pylist()) <= set( + results["__record_id"].to_pylist() + ) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("before", ["rdb_v1", "pdb_v2"]) +@pytest.mark.parametrize("in_memory_results", [False, True]) +def test_interrupted_batched_node_run_withdraws_its_pending_writes( + monkeypatch: pytest.MonkeyPatch, before: str, in_memory_results: bool +) -> None: + """An interruption may retain durable results but never leaves run-owned batches.""" + database = _database() + result_store = InMemoryArrowDatabase() if in_memory_results else database + job = _job(database, result_database=result_store) + node = cast("FunctionJobNode", job.nodes["combine"]) + unrelated = ("unrelated", "rdb_v1") + flush = FunctionJobNode._flush_node_table # pyright: ignore[reportPrivateUsage] + + def interrupt( + self: FunctionJobNode, + store: ArrowDatabaseProtocol, + path: tuple[str, ...], + *, + result: bool = False, + publish_records: bool = True, + ) -> None: + if self is node and path[-1] == before: + database.add_records( + unrelated, + pa.table( + { + "__record_id": pa.array([b"keep"], pa.large_binary()), + "__data_context": [get_default_context().context_key], + } + ), + record_id_column="__record_id", + ) + raise KeyboardInterrupt("interrupted between flushes") + flush(self, store, path, result=result, publish_records=publish_records) + + with monkeypatch.context() as patch: + patch.setattr(FunctionJobNode, "_flush_node_table", interrupt) + with pytest.raises(KeyboardInterrupt, match="interrupted between flushes"): + _ = node.run() + + fresh = _database() + assert unrelated in database.list_table_paths() + assert unrelated not in fresh.list_table_paths() + assert all(path[-1] != "pdb_v2" for path in database.list_table_paths()) + + def result_paths(store: ArrowDatabaseProtocol) -> set[tuple[str, ...]]: + return { + path + for path in store.list_table_paths() + if path[-1] == "rdb_v1" and path != unrelated + } + + assert bool(result_paths(result_store)) == (before == "pdb_v2") + with database_writes([database], owner="subsequent caller"): + result_store.flush() + if result_store is not database: + database.flush() + assert unrelated in fresh.list_table_paths() + assert all(path[-1] != "pdb_v2" for path in fresh.list_table_paths()) + assert bool(result_paths(result_store)) == (before == "pdb_v2") diff --git a/tests/test_pipeline/test_job_attached_database_commit.py b/tests/test_pipeline/test_job_attached_database_commit.py index 7f9dc812a..6be24d8ba 100644 --- a/tests/test_pipeline/test_job_attached_database_commit.py +++ b/tests/test_pipeline/test_job_attached_database_commit.py @@ -14,6 +14,7 @@ import orcapod.pipeline.job as job_module from orcapod import PipelineJob, function_pod +from orcapod.core.database_writes import shared_database_queue from orcapod.core.function_pod import FunctionPod from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode @@ -1077,8 +1078,8 @@ async def test_load_only_skips_opaque_queue_probe( with job: total.pod(source, label="sum") - probe = Mock(wraps=job_module._shared_queue) # pyright: ignore[reportPrivateUsage] # observe the job's queue probe - monkeypatch.setattr(job_module, "_shared_queue", probe) + probe = Mock(wraps=shared_database_queue) + monkeypatch.setattr(job_module, "shared_database_queue", probe) await _run(job, runner, load_only=True) probe.assert_not_called() From c761db31c39bb51f9cb2becdd533746931e76966 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 15:29:11 -0800 Subject: [PATCH 41/46] fix(database): propagate write lock refusals from node execution --- docs/concepts/spiraldb-database.md | 21 +++-- src/orcapod/core/nodes/function_node.py | 94 +++++++++++-------- .../test_spiraldb_write_lock.py | 58 +++++++++++- 3 files changed, 119 insertions(+), 54 deletions(-) diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index d8a34f3ee..332c7d138 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -88,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 diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index d6fe1c247..66ebf85c2 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -87,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, @@ -2776,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: @@ -2831,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) @@ -2845,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) diff --git a/tests/test_databases/test_spiraldb_write_lock.py b/tests/test_databases/test_spiraldb_write_lock.py index 4fb2d7fa3..4038856b6 100644 --- a/tests/test_databases/test_spiraldb_write_lock.py +++ b/tests/test_databases/test_spiraldb_write_lock.py @@ -4,10 +4,10 @@ import asyncio from collections.abc import Callable -from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import Future, ThreadPoolExecutor from contextvars import copy_context from threading import Event -from typing import Any, cast +from typing import Any, Literal, cast import pyarrow as pa import pytest @@ -20,6 +20,7 @@ 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, @@ -409,6 +410,41 @@ def act(x: int, ctx: InvocationContext) -> int: 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( @@ -1080,7 +1116,7 @@ async def outer(x: int, ctx: InvocationContext) -> int: @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( - use_executor: bool, queued: bool + monkeypatch: pytest.MonkeyPatch, use_executor: bool, queued: bool ) -> None: events: list[str] = [] lock = RecordingLock(events) @@ -1089,6 +1125,7 @@ def test_cancelled_context_call_keeps_its_scope_until_running_work_ends( 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) @@ -1107,13 +1144,24 @@ def effect(x: int, ctx: InvocationContext) -> int: cached = CachedDataFunction( function, _database(lock=lock), context_parameter="ctx" ) - loop.set_default_executor(ThreadPoolExecutor(max_workers=1)) + 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.sleep(0) + await asyncio.wait_for(submitted.wait(), timeout=5) else: await asyncio.wait_for(entered.wait(), timeout=5) assert events == ["acquire"] From b1bf4d469774ceb039424d5de5306c884b66281b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 19:54:48 -0800 Subject: [PATCH 42/46] fix(database): preserve primary write scope errors --- src/orcapod/databases/spiraldb_write_scope.py | 24 ++++++- .../test_spiraldb_writable_mode.py | 25 +++++-- .../test_spiraldb_write_lock.py | 71 ++++++++++++++++++- 3 files changed, 109 insertions(+), 11 deletions(-) diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index 7d5f4b4e1..ce9d53a66 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -228,7 +228,11 @@ def find(current: BaseException, seen: set[int]) -> BaseException | None: return None cause = current.__cause__ if cause is None and not current.__suppress_context__: - cause = current.__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): @@ -377,6 +381,14 @@ def _tables(connector: SpiralDBConnector) -> SpiralDBTables: return tables +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. @@ -403,13 +415,19 @@ def _close_all(scopes: list[_DatasetScope], error: BaseException | None) -> None if error is not None and not interruptions: # The body's error is raised by the caller; every failure is a note on it. for failure in failures: - error.add_note(f"Closing a SpiralDB write scope also failed: {failure}") + error.add_note( + "Closing a SpiralDB write scope also failed: " + + _cleanup_failure_message(failure) + ) return # An interruption outranks an ordinary failure: it stops the program. primary = interruptions[0] if interruptions else failures[0] for failure in failures: if failure is not primary: - primary.add_note(f"Closing another SpiralDB write scope failed: {failure}") + primary.add_note( + "Closing another SpiralDB write scope failed: " + + _cleanup_failure_message(failure) + ) if error is not None: raise primary from error raise primary diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index bb3506699..93c8cb106 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -12,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 @@ -1952,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 key 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()} == { @@ -2859,6 +2865,11 @@ def stale() -> list[tuple[str, ...]]: 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 diff --git a/tests/test_databases/test_spiraldb_write_lock.py b/tests/test_databases/test_spiraldb_write_lock.py index 4038856b6..942734ada 100644 --- a/tests/test_databases/test_spiraldb_write_lock.py +++ b/tests/test_databases/test_spiraldb_write_lock.py @@ -526,6 +526,42 @@ def test_all_handles_release_even_if_a_release_fails() -> None: 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 @@ -588,7 +624,9 @@ def close_then_interrupt( pass -@pytest.mark.parametrize("second_error", ["refusal", "independent", "suppressed"]) +@pytest.mark.parametrize( + "second_error", ["refusal", "independent", "implicit", "suppressed"] +) def test_provider_refusal_unwrap_preserves_other_task_failures( second_error: str, ) -> None: @@ -603,6 +641,8 @@ async def fail(kind: str) -> None: try: database.spiral_acquire_write_lock() except OrcapodDatabaseWriteError: + if kind == "implicit": + raise independent if kind == "suppressed": raise independent from None raise @@ -632,6 +672,35 @@ async def run() -> None: 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: From 6f527df565854a6d90843aac4cdf498bbe8395f4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 20:06:21 -0800 Subject: [PATCH 43/46] style: organize keyed SpiralDB imports --- .../scripts/itl_1844_database_evaluation.py | 2 +- .../databases/spiraldb_keyed/connector.py | 2 +- .../test_migrate_spiral_schemas.py | 3 +-- .../test_spiraldb_round_trips.py | 4 +++- .../test_spiraldb_writable_runs.py | 19 ++++++++++++------- .../test_spiraldb_write_lock.py | 6 +++++- 6 files changed, 23 insertions(+), 13 deletions(-) diff --git a/docs/dev/scripts/itl_1844_database_evaluation.py b/docs/dev/scripts/itl_1844_database_evaluation.py index 4139a42f5..555fed732 100644 --- a/docs/dev/scripts/itl_1844_database_evaluation.py +++ b/docs/dev/scripts/itl_1844_database_evaluation.py @@ -50,8 +50,8 @@ SpiralDBKeyedConnector, ) from orcapod.databases.spiraldb_keyed.identity import spiral_table_name # noqa: E402 -from orcapod.errors import SpiralDBScopeOpenError # noqa: E402 from orcapod.databases.spiraldb_keyed.write_scope import database_writes # noqa: E402 +from orcapod.errors import SpiralDBScopeOpenError # 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 diff --git a/src/orcapod/databases/spiraldb_keyed/connector.py b/src/orcapod/databases/spiraldb_keyed/connector.py index 06f2c398f..9718e0c05 100644 --- a/src/orcapod/databases/spiraldb_keyed/connector.py +++ b/src/orcapod/databases/spiraldb_keyed/connector.py @@ -49,10 +49,10 @@ describe_difference, ) from orcapod.databases.spiraldb_keyed.sign_in import require_sign_in, saved_login_path +from orcapod.databases.spiraldb_keyed.tables import SpiralDBTables from orcapod.databases.spiraldb_keyed.writable_registry import ( register_writable_connector, ) -from orcapod.databases.spiraldb_keyed.tables import SpiralDBTables from orcapod.databases.write_lock import NoWriteLock, WriteLock from orcapod.errors import ( NullInNonNullableColumnError, diff --git a/tests/test_databases/test_migrate_spiral_schemas.py b/tests/test_databases/test_migrate_spiral_schemas.py index 6a4bcacf5..c1b973de9 100644 --- a/tests/test_databases/test_migrate_spiral_schemas.py +++ b/tests/test_databases/test_migrate_spiral_schemas.py @@ -14,10 +14,9 @@ import pyarrow as pa import pytest -from orcapod.databases.store_table_names import store_table_name from orcapod.databases import SpiralDBKeyedConnector from orcapod.databases.spiraldb_keyed import schema_table as st - +from orcapod.databases.store_table_names import store_table_name from orcapod.errors import TableSchemaError from orcapod.sources import SpiralDBTableSource from tests.test_databases import fake_spiral_sdk as fake diff --git a/tests/test_databases/test_spiraldb_round_trips.py b/tests/test_databases/test_spiraldb_round_trips.py index b1a5db814..9b66aead8 100644 --- a/tests/test_databases/test_spiraldb_round_trips.py +++ b/tests/test_databases/test_spiraldb_round_trips.py @@ -19,9 +19,11 @@ ConnectorArrowDatabase, ) from orcapod.databases.spiraldb_keyed import ( - identity as spiral_database_identity, connector as spiraldb_connector, ) +from orcapod.databases.spiraldb_keyed import ( + identity as spiral_database_identity, +) from orcapod.databases.spiraldb_keyed.tables import RunState, SpiralDBTables from orcapod.databases.spiraldb_keyed.write_scope import database_writes from orcapod.types import CacheMode diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index f87086bb1..6ba2b5816 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -28,7 +28,7 @@ from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.core.nodes.source_node import SourceJobNode, SourceNode from orcapod.core.operators import SelectDataColumns -from orcapod.core.sources.cached_source import CachedSource, SOURCE_RECORDED_AT_COL +from orcapod.core.sources.cached_source import SOURCE_RECORDED_AT_COL, CachedSource from orcapod.core.streams.base import typed_zero_row_table from orcapod.databases import ( ConnectorArrowDatabase, @@ -38,13 +38,19 @@ SpiralDBKeyedConnector, SQLiteConnector, ) +from orcapod.databases.extension_aware_database import ExtensionAwareDatabase from orcapod.databases.spiraldb_keyed import ( - identity as spiral_database_identity, connector as spiraldb_connector, +) +from orcapod.databases.spiraldb_keyed import ( + identity as spiral_database_identity, +) +from orcapod.databases.spiraldb_keyed import ( writable_registry as spiraldb_writable_registry, +) +from orcapod.databases.spiraldb_keyed import ( write_scope as spiraldb_write_scope, ) -from orcapod.databases.extension_aware_database import ExtensionAwareDatabase from orcapod.databases.spiraldb_keyed.write_scope import database_writes from orcapod.databases.write_lock import NoWriteLock, WriteLock, WriteLockHandle from orcapod.errors import ( @@ -53,9 +59,10 @@ UnboundSourceError, UnstorableColumnError, ) -from orcapod.pipeline import AsyncPipelineOrchestrator -from orcapod.pipeline import node_run +from orcapod.pipeline import AsyncPipelineOrchestrator, node_run from orcapod.pipeline.execution_context import ExecutionContext +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.side_effects import ( InvocationContext, @@ -64,8 +71,6 @@ sink_pod, ) from orcapod.sources import ArrowTableSource -from orcapod.protocols.core_protocols import StreamProtocol -from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.types import CacheMode, ColumnConfig, ContentHash, NodeConfig from tests.test_databases import fake_spiral_sdk as fake diff --git a/tests/test_databases/test_spiraldb_write_lock.py b/tests/test_databases/test_spiraldb_write_lock.py index 52ce6d05d..9f356f094 100644 --- a/tests/test_databases/test_spiraldb_write_lock.py +++ b/tests/test_databases/test_spiraldb_write_lock.py @@ -27,8 +27,12 @@ SpiralDBKeyedConnector, ) from orcapod.databases.spiraldb_keyed import ( - identity as spiral_database_identity, connector as spiraldb_connector, +) +from orcapod.databases.spiraldb_keyed import ( + identity as spiral_database_identity, +) +from orcapod.databases.spiraldb_keyed import ( write_scope as spiraldb_write_scope, ) from orcapod.databases.spiraldb_keyed.tables import SpiralDBTables From 41221d094b1443d1cf5b25963748ec6a21d71d1b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 20:23:19 -0800 Subject: [PATCH 44/46] test: classify the SpiralDatabase factory for observers --- .../test_pipeline/test_observer_databases.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/tests/test_pipeline/test_observer_databases.py b/tests/test_pipeline/test_observer_databases.py index acd055784..b81fd2688 100644 --- a/tests/test_pipeline/test_observer_databases.py +++ b/tests/test_pipeline/test_observer_databases.py @@ -17,6 +17,7 @@ ExtensionAwareDatabase, InMemoryArrowDatabase, NoOpArrowDatabase, + SpiralDatabase, SpiralDBKeyedConnector, SQLiteConnector, ) @@ -367,7 +368,21 @@ def test_other_databases_are_accepted( assert capture_install.call_count == int(observer_class is LoggingObserver) -def test_every_database_class_exported_from_orcapod_databases_is_classified() -> None: +@pytest.mark.parametrize("observer_class", _OBSERVERS) +def test_spiral_database_factory_is_refused_at_observer_setup( + observer_class: type[StatusObserver] | type[LoggingObserver], + tmp_path: Path, + capture_install: Mock, +) -> None: + with fake_spiral_sdk.install(tmp_path / "spiral"): + database = SpiralDatabase("p", "d") + with pytest.raises(SpiralDBObserverNotSupportedError, match=_REFUSAL): + _ = observer_class(database) + + capture_install.assert_not_called() + + +def test_every_database_export_from_orcapod_databases_is_classified() -> None: """Require an explicit classification for names exported through ``__all__``.""" assert set(databases.__all__) == { # Roots kept as-is by the observer check. @@ -377,6 +392,8 @@ def test_every_database_class_exported_from_orcapod_databases_is_classified() -> # The wrapper is unwrapped, then the connector decides the result. "ExtensionAwareDatabase", "ConnectorArrowDatabase", + # The factory returns a keyed connector database, refused at setup. + "SpiralDatabase", # Connectors: SpiralDB is refused; SQLite and PostgreSQL pass. "SpiralDBKeyedConnector", "SQLiteConnector", From c12395eb09f8d5da711890f943e0522d8f516402 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 21:59:09 -0800 Subject: [PATCH 45/46] fix(spiraldb): validate retired connectors in saved caches --- changelog.d/ITL-1844.md | 24 ++++--------- .../2026-06-23-pyspiral-upgrade-plt-1773.md | 2 +- docs/dev/scripts/itl_1903/rename.py | 4 +++ src/orcapod/core/sources/cached_source.py | 17 ++++++++++ .../databases/connector_arrow_database.py | 5 ++- src/orcapod/databases/spiral_database.py | 4 +-- .../databases/spiraldb_keyed/connector.py | 3 +- tests/test_changelog_fragments.py | 11 ++++++ .../test_spiraldb_writable_runs.py | 34 +++++++++++++++++++ .../test_dev_scripts/test_itl_1903_rename.py | 22 ++++++++++++ tests/test_docs/test_api_reference.py | 24 +++++++++++++ 11 files changed, 125 insertions(+), 25 deletions(-) diff --git a/changelog.d/ITL-1844.md b/changelog.d/ITL-1844.md index 26d599966..a7c7174a4 100644 --- a/changelog.d/ITL-1844.md +++ b/changelog.d/ITL-1844.md @@ -3,28 +3,18 @@ - A SpiralDB dataset can be a job's database: a writable SpiralDB database, `SpiralDBKeyedConnector(project_id, dataset, writable=True)` under `ConnectorArrowDatabase`, stores every table a job writes (function results and pipeline records, operator caches, cached sources, side-effect logs), also as a separate - result database. Provisional in 0.4.0: the database's table format and its writer lease may - change in a later version, which may not read tables written now. Nothing of the - database enters a hash. See "SpiralDB as a Job's Database" in the concepts. -- One writer per writable SpiralDB database: `job.run()`, `job.run_async()` and a job node's `run()` - take the dataset's writer lease before checking a source or writing anything, and release - it when they end, also when they fail. A second writer is refused then with - `LeaseBusyError`, before anything of its run happens. A stale lease is cleared by its - project, dataset and table id with - `spiraldb_lease.clear(client, project_id, dataset, table_id, confirm_writer_stopped=True)`. + result database. The table format is provisional in 0.4.0 and later versions may + be unable to read tables written now. Nothing of the database enters a hash. + See [Keyed SpiralDB as a Job's Database](docs/concepts/spiraldb-keyed-database.md). - A job saved on a writable SpiralDB database records `writable: true` and no credential; `PipelineJob.load` takes the connector again and refuses a SpiralDB connector of the other kind. ### Known limitations -- Only a job run writes a writable SpiralDB database, through the writable connectors it - holds the lease with: a write through any other writable connector (a cached source read outside a run, a - `ConnectorArrowDatabase` over a connector of its own flushed directly) raises - `SpiralDBLeaseRequiredError`, also while a run holds the lease. A write through a - running job's own databases from outside the run is not told apart from the run's own. - A way to hold the lease outside a run is later work (ITL-1849). -- The writer lease is refuse-only: no waiting, no takeover, no expiry. Each run leaves one - small lease table in the dataset, which is kept. +- Writable SpiralDB databases assume one writer process per keyed dataset at a time. + The caller manages cross-process exclusion. The default `NoWriteLock` performs + no cross-process coordination. A direct write outside a run opens a write scope + for that call. - A writable SpiralDB database reads a table's whole key column to tell which rows it holds, and whole tables to read stored rows, so a run's cost grows with the tables' history. - The database does not take over tables it did not write, and status and logging observers diff --git a/docs/dev/plans/2026-06-23-pyspiral-upgrade-plt-1773.md b/docs/dev/plans/2026-06-23-pyspiral-upgrade-plt-1773.md index e4fb83ee7..230c3f652 100644 --- a/docs/dev/plans/2026-06-23-pyspiral-upgrade-plt-1773.md +++ b/docs/dev/plans/2026-06-23-pyspiral-upgrade-plt-1773.md @@ -155,7 +155,7 @@ using ``httpx``) resolved the issue. If these tests start failing with a similar - [ ] **Step 2: Verify the file still imports cleanly** ```bash -uv run python -c "import tests.test_databases.test_spiraldb_connector_integration" 2>&1 || \ +uv run python -c "import tests.test_databases.test_spiraldb_keyed_connector_integration" 2>&1 || \ uv run python -c " import importlib.util, sys spec = importlib.util.spec_from_file_location( diff --git a/docs/dev/scripts/itl_1903/rename.py b/docs/dev/scripts/itl_1903/rename.py index 3995ded3b..bdeb88b7d 100644 --- a/docs/dev/scripts/itl_1903/rename.py +++ b/docs/dev/scripts/itl_1903/rename.py @@ -77,6 +77,10 @@ "test_spiraldb_connector_integration.py", "test_spiraldb_keyed_connector_integration.py", ), + ( + "tests.test_databases.test_spiraldb_connector_integration", + "tests.test_databases.test_spiraldb_keyed_connector_integration", + ), ("from .spiraldb_connector import ", "from .spiraldb_keyed.connector import "), ( "from orcapod.databases import SpiralDBKeyedConnector, spiraldb_connector", diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index c6c24ad9b..13b7c6033 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -304,6 +304,23 @@ def config_for_resave(cls, config: dict[str, Any]) -> dict[str, Any]: ) return saved + @classmethod + def check_saved_config(cls, config: dict[str, Any]) -> None: + """Refuse unsupported inline cache database configurations on job load. + + Args: + config: The saved cached source configuration. + + Raises: + ValueError: If the cache database has an unsupported SpiralDB config. + """ + from orcapod.pipeline.serialization import spiraldb_saved_config_refusal + + if ( + reason := spiraldb_saved_config_refusal(config.get("cache_database")) + ) is not None: + raise ValueError(f"cache_database: {reason}") + @classmethod def from_config( cls, diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 4ca93ed54..498771654 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -8,9 +8,8 @@ Connector implementations (SQLiteConnector, PostgreSQLConnector, SpiralDBKeyedConnector) need only satisfy DBConnectorProtocol; they do not implement ArrowDatabaseProtocol. -Example:: - - connector = SQLiteConnector(":memory:") # PLT-1076 +Examples: + connector = SQLiteConnector(":memory:") db = ConnectorArrowDatabase(connector) db.add_record(("results", "my_fn"), record_id=b"sha256:abc", record=table) db.flush() diff --git a/src/orcapod/databases/spiral_database.py b/src/orcapod/databases/spiral_database.py index 1ff8c8562..b355ad588 100644 --- a/src/orcapod/databases/spiral_database.py +++ b/src/orcapod/databases/spiral_database.py @@ -13,8 +13,6 @@ def SpiralDatabase( ) -> ConnectorArrowDatabase: """Open a SpiralDB database using Orcapod's default backend. - The factory forwards the write mode and other keyword arguments, - such as ``overrides``, to the keyed connector. Saved jobs record the concrete backend and its configuration. The default backend may change in a later release, with one release of advance notice. @@ -23,6 +21,8 @@ def SpiralDatabase( dataset: Dataset within the project. writable: Use the writable database layout. Pass ``False`` for the plain keyed connector's layout. + **connector_options: Additional keyword arguments forwarded to + ``SpiralDBKeyedConnector``, such as ``overrides`` or ``write_lock``. Returns: A database backed by a ``SpiralDBKeyedConnector``. diff --git a/src/orcapod/databases/spiraldb_keyed/connector.py b/src/orcapod/databases/spiraldb_keyed/connector.py index 9718e0c05..8c72ea78a 100644 --- a/src/orcapod/databases/spiraldb_keyed/connector.py +++ b/src/orcapod/databases/spiraldb_keyed/connector.py @@ -8,8 +8,7 @@ a single ``(project_id, dataset)`` pair. They are SpiralDB's keyed tables. The schema each is read with is in the dataset's schema table (``spiraldb_keyed.schema_table``). -Example:: - +Examples: connector = SpiralDBKeyedConnector(project_id="my-project-123456", dataset="default") rows = pa.Table.from_batches(connector.scan_batches("units")) """ diff --git a/tests/test_changelog_fragments.py b/tests/test_changelog_fragments.py index 4a03c5755..6e8bdf665 100644 --- a/tests/test_changelog_fragments.py +++ b/tests/test_changelog_fragments.py @@ -97,6 +97,17 @@ def test_repository_fragments_directory_has_a_readme() -> None: assert (REPO_ROOT / "changelog.d" / "README.md").is_file() +def test_unreleased_fragments_do_not_advertise_removed_spiraldb_lease_apis() -> None: + for fragment in (REPO_ROOT / "changelog.d").glob("*.md"): + text = fragment.read_text(encoding="utf-8") + for retired_api in ( + "spiraldb_lease.clear", + "LeaseBusyError", + "SpiralDBLeaseRequiredError", + ): + assert retired_api not in text, fragment.name + + # --- --check ------------------------------------------------------------------------ diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 6ba2b5816..6499d41c1 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -628,6 +628,40 @@ def partial_results(x: int, y: int) -> tuple[int, float]: # ------------------------------------------------------------------ load only +@pytest.mark.parametrize("nested", [False, True], ids=["direct", "nested"]) +def test_load_refuses_the_retired_connector_type_in_a_cache( + root: Path, nested: bool +) -> None: + database = SpiralDatabase("p", "d") + job = _job(database) + if nested: + (source_node,) = ( + node for node in job.nodes.values() if isinstance(node, SourceJobNode) + ) + assert isinstance(source_node.bound_source, CachedSource) + job.bind( + sources={ + source_node.name: CachedSource( + source_node.bound_source, cache_database=database + ) + } + ) + saved = root / "job.json" + job.save(saved) + contents = json.loads(saved.read_text()) + (source,) = ( + source + for source in contents["bindings"]["sources"].values() + if source["source_type"] == "cached" + ) + cache_owner = source["inner_source"] if nested else source + cache_owner["cache_database"]["connector"]["connector_type"] = "spiraldb" + saved.write_text(json.dumps(contents)) + + with pytest.raises(ValueError, match=r"cache_database.*spiraldb_keyed"): + PipelineJob.load(saved, database=database) + + def test_spiral_database_job_round_trip_records_the_concrete_backend( root: Path, ) -> None: diff --git a/tests/test_dev_scripts/test_itl_1903_rename.py b/tests/test_dev_scripts/test_itl_1903_rename.py index 8383c0c5c..ce543a0b2 100644 --- a/tests/test_dev_scripts/test_itl_1903_rename.py +++ b/tests/test_dev_scripts/test_itl_1903_rename.py @@ -4,6 +4,7 @@ import runpy from collections.abc import Callable +from importlib.util import find_spec from pathlib import Path from typing import cast @@ -30,3 +31,24 @@ def test_rename_updates_release_guide_references() -> None: assert Path("RELEASING.md") in extra_text guide = (ROOT / "RELEASING.md").read_text(encoding="utf-8") assert all(reference in guide for reference in expected.splitlines()) + + +def test_rename_updates_dotted_test_module_references() -> None: + script = runpy.run_path(str(ROOT / "docs/dev/scripts/itl_1903/rename.py")) + replace_text = cast("Callable[[str], str]", script["replace_text"]) + old_module = "test_spiraldb_connector_integration" + previous = f"import tests.test_databases.{old_module}" + expected = "import tests.test_databases.test_spiraldb_keyed_connector_integration" + + assert replace_text(previous) == expected + assert replace_text(expected) == expected + + +def test_developer_import_recipe_uses_an_existing_module() -> None: + plan = ROOT / "docs/dev/plans/2026-06-23-pyspiral-upgrade-plt-1773.md" + step = plan.read_text(encoding="utf-8").split( + "Verify the file still imports cleanly", 1 + )[1] + module = step.split('uv run python -c "import ', 1)[1].split('"', 1)[0] + + assert find_spec(module) is not None diff --git a/tests/test_docs/test_api_reference.py b/tests/test_docs/test_api_reference.py index fbb340f9f..7fac05af0 100644 --- a/tests/test_docs/test_api_reference.py +++ b/tests/test_docs/test_api_reference.py @@ -5,12 +5,16 @@ import re from collections.abc import Sequence from importlib import import_module +from inspect import getdoc from pathlib import Path from typing import cast import griffe +import pytest from griffe import Alias, Module, Object +from orcapod.databases import SpiralDatabase + REPO_ROOT = Path(__file__).resolve().parents[2] PUBLIC_MODULES = ( "orcapod", @@ -140,3 +144,23 @@ def reference_key(path: str) -> tuple[str, str]: assert not missing, ( "Add API reference entries or reasoned exclusions for:\n" + "\n".join(missing) ) + + +@pytest.mark.parametrize( + "module_name", + [ + "orcapod.databases.spiraldb_keyed.connector", + "orcapod.databases.connector_arrow_database", + ], +) +def test_database_module_examples_use_google_style(module_name: str) -> None: + docstring = getdoc(import_module(module_name)) + assert docstring is not None + assert "Examples:" in docstring.splitlines() + assert "Example::" not in docstring + + +def test_spiral_database_documents_connector_options() -> None: + docstring = getdoc(SpiralDatabase) + assert docstring is not None + assert " **connector_options:" in docstring From e1ceeace30ae6dd74e8964b5674625ec62b4a794 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 22:23:14 -0800 Subject: [PATCH 46/46] fix(spiraldb): preserve migration and guide compatibility --- docs/dev/scripts/itl_1903/rename.py | 27 ++++++++++++- scripts/migrate_spiral_schemas.py | 14 ++++++- site/astro.config.mjs | 3 ++ .../test_migrate_spiral_schemas.py | 38 +++++++++++++++++++ .../test_dev_scripts/test_itl_1903_rename.py | 15 ++++++++ tests/test_docs/test_site_content.py | 10 +++++ 6 files changed, 104 insertions(+), 3 deletions(-) diff --git a/docs/dev/scripts/itl_1903/rename.py b/docs/dev/scripts/itl_1903/rename.py index bdeb88b7d..f88d980e4 100644 --- a/docs/dev/scripts/itl_1903/rename.py +++ b/docs/dev/scripts/itl_1903/rename.py @@ -47,6 +47,20 @@ Path("RELEASING.md"), Path(".zed/rules"), } +LEGACY_CONNECTOR_REFERENCES = ( + "orcapod.databases.spiraldb_connector", + "SpiralDBConnector", +) +LEGACY_GUIDE_REFERENCES = ("'/concepts/spiraldb-database':",) +# The cross-version dry run and the old guide redirect still use these names. +PRESERVED_REFERENCES = { + Path("scripts/migrate_spiral_schemas.py"): LEGACY_CONNECTOR_REFERENCES, + Path("tests/test_databases/test_migrate_spiral_schemas.py"): ( + LEGACY_CONNECTOR_REFERENCES + ), + Path("site/astro.config.mjs"): LEGACY_GUIDE_REFERENCES, + Path("tests/test_docs/test_site_content.py"): LEGACY_GUIDE_REFERENCES, +} BASELINE = Path(".basedpyright/baseline.json") SCRIPT_DIR = Path("docs/dev/scripts/itl_1903") RENAME_FRAGMENT = Path("changelog.d/ITL-1903.md") @@ -167,6 +181,17 @@ def replace_text(text: str) -> str: return text +def replace_file_text(path: Path, text: str) -> str: + """Rename references in a file while keeping its intentional legacy literals.""" + if path not in PRESERVED_REFERENCES: + return replace_text(text) + literals = "|".join(map(re.escape, PRESERVED_REFERENCES[path])) + parts = re.split(f"({literals})", text) + # The captures are preserved verbatim and the intervening text is renamed. + parts[::2] = map(replace_text, parts[::2]) + return "".join(parts) + + def replace_grouped_imports(match: re.Match[str]) -> str: imports = match["imports"].splitlines() direct: list[str] = [] @@ -216,7 +241,7 @@ def main() -> None: and (path not in generic_paths or path.exists()) ): original = path.read_text(encoding="utf-8") - updated = replace_text(original) + updated = replace_file_text(path, original) else: continue if original != updated: diff --git a/scripts/migrate_spiral_schemas.py b/scripts/migrate_spiral_schemas.py index f57bceced..c65d5e9a8 100644 --- a/scripts/migrate_spiral_schemas.py +++ b/scripts/migrate_spiral_schemas.py @@ -252,7 +252,17 @@ def describe_table( def dry_run(args: argparse.Namespace) -> None: """Write the plan and print what each dataset's schema table would hold.""" - from orcapod.databases.spiraldb_keyed.connector import SpiralDBKeyedConnector + keyed_package = "orcapod.databases.spiraldb_keyed" + keyed_module = f"{keyed_package}.connector" + try: + connector_type = importlib.import_module(keyed_module).SpiralDBKeyedConnector + except ModuleNotFoundError as exc: + if exc.name not in (keyed_package, keyed_module): + raise + # The pinned pyspiral release recipe uses Orcapod from before the rename. + connector_type = importlib.import_module( + "orcapod.databases.spiraldb_connector" + ).SpiralDBConnector sp = spiral_module() @@ -280,7 +290,7 @@ def dry_run(args: argparse.Namespace) -> None: # Every selected dataset that lists a table, a reserved name included: a dataset # whose only table is a reserved name reaches the reserved-name check below. connectors = { - dataset: SpiralDBKeyedConnector(args.project, dataset) + dataset: connector_type(args.project, dataset) for dataset in sorted(set(args.dataset)) if dataset in tables or dataset in reserved } diff --git a/site/astro.config.mjs b/site/astro.config.mjs index e31ad54ea..af9060a75 100644 --- a/site/astro.config.mjs +++ b/site/astro.config.mjs @@ -98,6 +98,9 @@ const page = (label, slug) => ({ label, slug }); export default defineConfig({ site, base, + redirects: { + '/concepts/spiraldb-database': `${base}concepts/spiraldb-keyed-database/`, + }, // mkdocs rendered '--' and quotes as written; so does the site. markdown: { smartypants: false }, // sharp is not installed (pnpm-workspace.yaml): images are served as they are. diff --git a/tests/test_databases/test_migrate_spiral_schemas.py b/tests/test_databases/test_migrate_spiral_schemas.py index c1b973de9..5a1ae2886 100644 --- a/tests/test_databases/test_migrate_spiral_schemas.py +++ b/tests/test_databases/test_migrate_spiral_schemas.py @@ -280,6 +280,44 @@ def _lease_key(n: int, arrow_type: pa.DataType | None = None) -> list[pa.Field[A return _key(f"{SPIRAL_LEASE_KEY_PREFIX}{n:032x}", arrow_type) +@pytest.mark.parametrize("keyed_available", [True, False], ids=["keyed", "pre-rename"]) +def test_dry_run_loads_the_connector_for_the_installed_version( + tool: ModuleType, + args: argparse.Namespace, + monkeypatch: pytest.MonkeyPatch, + keyed_available: bool, +) -> None: + """Both connector module layouts support the same synthetic dry run.""" + dataset = args.dataset[0] + lease = spiral_lease_table_name(1) + plan, opened = _legacy_listing( + tool, args, monkeypatch, [(dataset, lease, _lease_key(1))] + ) + keyed = "orcapod.databases.spiraldb_keyed.connector" + previous = "orcapod.databases.spiraldb_connector" + load = importlib.import_module + constructor = load(keyed).SpiralDBKeyedConnector + imported: list[str] = [] + + def load_connector(name: str) -> Any: + imported.append(name) + if not keyed_available: + if name == keyed: + raise ModuleNotFoundError(name="orcapod.databases.spiraldb_keyed") + if name == previous: + return SimpleNamespace(SpiralDBConnector=constructor) + return load(name) + + monkeypatch.setattr( + tool, "importlib", SimpleNamespace(import_module=load_connector) + ) + tool.dry_run(args) + + assert imported == ([keyed] if keyed_available else [keyed, previous]) + assert opened == [(dataset, lease)] + assert tool.read_plan(args.plan) == plan + + def test_dry_run_and_write_skip_lease_generations( tool: ModuleType, args: argparse.Namespace, diff --git a/tests/test_dev_scripts/test_itl_1903_rename.py b/tests/test_dev_scripts/test_itl_1903_rename.py index ce543a0b2..24677c382 100644 --- a/tests/test_dev_scripts/test_itl_1903_rename.py +++ b/tests/test_dev_scripts/test_itl_1903_rename.py @@ -44,6 +44,21 @@ def test_rename_updates_dotted_test_module_references() -> None: assert replace_text(expected) == expected +def test_rename_preserves_the_migration_fallback_and_guide_redirect() -> None: + """Rerunning the rename keeps the old import and the old route where needed.""" + script = runpy.run_path(str(ROOT / "docs/dev/scripts/itl_1903/rename.py")) + replace_file_text = cast("Callable[[Path, str], str]", script["replace_file_text"]) + for name in ( + "scripts/migrate_spiral_schemas.py", + "tests/test_databases/test_migrate_spiral_schemas.py", + "site/astro.config.mjs", + "tests/test_docs/test_site_content.py", + ): + path = Path(name) + original = (ROOT / path).read_text(encoding="utf-8") + assert replace_file_text(path, original) == original + + def test_developer_import_recipe_uses_an_existing_module() -> None: plan = ROOT / "docs/dev/plans/2026-06-23-pyspiral-upgrade-plt-1773.md" step = plan.read_text(encoding="utf-8").split( diff --git a/tests/test_docs/test_site_content.py b/tests/test_docs/test_site_content.py index 9219f9fee..89105b619 100644 --- a/tests/test_docs/test_site_content.py +++ b/tests/test_docs/test_site_content.py @@ -589,6 +589,16 @@ def test_an_invalid_address_is_refused(env: dict[str, str]): assert variable in proc.stderr +def test_the_site_redirects_the_old_spiraldb_guide(): + """External links to the previous guide route follow the renamed guide.""" + config = (REPO_ROOT / "site" / "astro.config.mjs").read_text(encoding="utf-8") + assert ( + "redirects: {\n" + "\t\t'/concepts/spiraldb-database': `${base}concepts/spiraldb-keyed-database/`,\n" + "\t}," in config + ) + + def test_the_site_shows_code_comments_as_written(): """A printed value that looks like a file name (`# 1.58`) stays in its code block.