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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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 9d8430c85ba4d0f46f593a2d8059d1c883ed1606 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 02:32:00 -0800 Subject: [PATCH 14/17] 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 d9ce39bbc8e9863a143e2aaeb7ecfd846ade55d4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 04:33:37 -0800 Subject: [PATCH 15/17] 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 f4b893efaca797f470be66f49f0c002d8434b4a0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 11:40:05 -0800 Subject: [PATCH 16/17] 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 98c96ae7e00b727a304dc65a9abba88911f52fb3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 3 Dec 2026 14:16:11 -0800 Subject: [PATCH 17/17] 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()