diff --git a/changelog.d/ITL-1502.md b/changelog.d/ITL-1502.md new file mode 100644 index 000000000..e1e25eb69 --- /dev/null +++ b/changelog.d/ITL-1502.md @@ -0,0 +1,23 @@ +### Changed + +- 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 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 + `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. + Failed pipeline-record appends also retry one row at a time. An interrupted node + run withdraws its pending results and pipeline records. + +### Fixed + +- Writable SpiralDB appends copy Arrow buffers before writing, including slices + that leave string or binary lists empty. diff --git a/docs/concepts/spiraldb-database.md b/docs/concepts/spiraldb-database.md index d5eefe25e..a0de9b152 100644 --- a/docs/concepts/spiraldb-database.md +++ b/docs/concepts/spiraldb-database.md @@ -77,6 +77,45 @@ 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 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 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 +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. Each new write scope +resolves the names it uses again, so a replacement between runs is picked up. + ### A lease left behind A process that stops in the middle of a run (killed, or a lost connection) leaves its @@ -105,9 +144,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 @@ -132,9 +172,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/src/orcapod/contexts/stored.py b/src/orcapod/contexts/stored.py index cf8cd1531..adf189fd7 100644 --- a/src/orcapod/contexts/stored.py +++ b/src/orcapod/contexts/stored.py @@ -43,6 +43,7 @@ OrcapodDatabaseContentWarning, TableListingNotSupportedError, ) +from orcapod.protocols.spiraldb_run import SpiralDBRunLookupProtocol from orcapod.system_constants import ( OPERATOR_DB_SCHEMA_VERSION, PIPELINE_DB_SCHEMA_VERSION, @@ -466,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 @@ -503,6 +507,12 @@ def find_stale_tables( ) if current is not None: current_path, current_context = current + # SpiralDB records a single data context for the table. Read rows only + # when the report needs to count them under another context. + if isinstance( + 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: found.tables.append( 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 731743bca..d46becd81 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -126,6 +126,7 @@ ) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.hashing_protocols import IdentityWalkProtocol +from orcapod.protocols.spiraldb_run import InOrderFlushProtocol from orcapod.protocols.observability_protocols import ( DataExecutionLoggerProtocol, ExecutionObserverProtocol, @@ -1548,6 +1549,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 @@ -2005,6 +2007,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 @@ -2451,18 +2454,40 @@ 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. 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 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: 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. @@ -2473,6 +2498,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: @@ -2481,6 +2507,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) @@ -2494,8 +2521,18 @@ 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, 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: @@ -4532,7 +4569,7 @@ def _run_alone( """ from dataclasses import replace - from orcapod.pipeline.node_run import 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 @@ -4551,7 +4588,10 @@ def _run_alone( if database is not None ] try: - _ = self.execute(self._input_stream, observer=counter, load_only=load_only) + with batch_node_commits([self], 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/databases/_pending_commits.py b/src/orcapod/databases/_pending_commits.py index 0e82b8a8e..c6c167f21 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( @@ -148,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 @@ -186,8 +234,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: @@ -200,7 +257,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 360447ad0..b3f61949a 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1187,7 +1187,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 @@ -1235,8 +1237,53 @@ 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_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 + ) -> None: + """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 + 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. + + For a definite failure, the durable rows are those a node committing after + 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. + 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, or the original error if the batch failed before an append. + """ + 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 SpiralDB append, write the rows 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() @@ -1250,53 +1297,138 @@ 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) + append_failed = False + + def note_append_failure() -> None: + nonlocal append_failed + append_failed = True + 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, + on_append_error=note_append_failure if in_order else None, + ) + except Exception as batch_error: + 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. + 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, + 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()) + 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, + *, + 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) + 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, + on_append_error=on_append_error, + ) + + 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}, keep_schema_check=True + ) + self._pending_commits.finish(record_key, committed=True, ids={record_id}) + def _write_ready_batch( self, record_key: str, @@ -1305,6 +1437,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 @@ -1335,8 +1469,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: @@ -1375,11 +1509,8 @@ 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). - tables.write(table_name, pending) + # Write only keys that are absent from the lease's key index. + tables.write(table_name, pending, on_append_error=on_append_error) elif self._sql_store is None: self._connector.create_table_if_not_exists( table_name, columns, pk_column=self.RECORD_ID_COLUMN @@ -1415,6 +1546,87 @@ 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: + """Create a completion lookup for one execution of a side-effect node. + + Each lookup consults this database's pending receipts, then the committed + receipts as the run's lease-wide key index has them. Every connector of the + dataset under the run's lease updates that index as it commits, so a receipt + 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. + + 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) + full_path = self._path_prefix + record_path + stored_ids: set[bytes] | None = None + + def committed(record_id: bytes) -> bool: + nonlocal stored_ids + 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(): + table = self._get_committed_table(record_path, schema=None) + stored_ids = ( + set() + if table is None + else set( + cast("list[bytes]", table[self.RECORD_ID_COLUMN].to_pylist()) + ) + ) + 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 + + return completed + @_one_spiral_operation def get_record_by_id( self, diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index 6cc19e0b0..e28eeb65a 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -28,6 +28,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 ( + InOrderFlushProtocol, + SpiralDBRunLookupProtocol, +) if TYPE_CHECKING: from contextlib import AbstractContextManager @@ -85,6 +89,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, ...], @@ -221,12 +241,30 @@ 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: """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, InOrderFlushProtocol): + 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_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/src/orcapod/databases/spiraldb_tables.py b/src/orcapod/databases/spiraldb_tables.py index 8987861d2..300c11e37 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 @@ -29,7 +28,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. @@ -37,10 +36,11 @@ from __future__ import annotations +import logging 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 @@ -64,6 +64,55 @@ 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: + """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) + + +@dataclass +class WriterLease: + """A run's state for one dataset, shared by the dataset's connectors under the + lease: the lease verification, the key index and the catalog. + + 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; 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. + """ + + 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.""" + self.verify() + class _Scan(Protocol): """The part of spiral-sdk's scan the database uses.""" @@ -201,9 +250,9 @@ def __init__( self._list_tables: Callable[[], dict[str, str]] = list_tables self._service_call: Callable[[str], AbstractContextManager[None]] = service_call 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). @@ -216,7 +265,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.""" @@ -349,15 +398,15 @@ 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: self._now.judged = {} + self._now.commits = {} self._now.depth = depth + 1 try: yield @@ -365,23 +414,22 @@ 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]: - """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 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.""" @@ -394,6 +442,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 ────────────────────────────────────────────────────── @@ -415,10 +488,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. @@ -433,10 +504,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: @@ -449,11 +526,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"): @@ -461,19 +540,28 @@ 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) + 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). @@ -518,13 +606,40 @@ 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(): + 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 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 @@ -535,10 +650,16 @@ def table_paths( else: last = identity.other_format_last_component(record, table_format) found.add((*record.path[:-1], last)) - return sorted(found) + + 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. @@ -550,9 +671,11 @@ 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 + 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"): @@ -573,9 +696,14 @@ 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] = read + self._records_by_id[table_id] = run_records[table_id] = read return read # ── reading ────────────────────────────────────────────────────────────── @@ -606,6 +734,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. @@ -674,37 +807,113 @@ 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): - return self._held_ids(opened.table, ids) + lease = self._lease_check + with ( + 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() + # 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. - def _held_ids(self, table: _KeyedTable, ids: Collection[bytes]) -> set[bytes]: - """The ids among ``ids`` a snapshot holds (``existing_record_ids``). + 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], *, 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) + 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) + + 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() - held = cast( - "list[bytes]", - stored.column(codec.KEY_COLUMN).cast(pa.large_binary()).to_pylist(), + return set( + cast( + "list[bytes]", + stored.column(codec.KEY_COLUMN).cast(pa.large_binary()).to_pylist(), + ) ) - return set(ids).intersection(held) # ── 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: - 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. @@ -713,9 +922,11 @@ def hold_lease(self, check: Callable[[], None]) -> 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: 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,8 +935,8 @@ 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: - """Refuse a write unless a run holds the dataset's writer lease, and check it. + 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 through any other connector to the dataset is refused, also while that run @@ -745,6 +956,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. @@ -758,7 +970,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)]) @@ -769,7 +981,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 @@ -814,7 +1026,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( @@ -851,15 +1063,17 @@ 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. 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 @@ -868,6 +1082,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 @@ -885,11 +1100,21 @@ 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() - # 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. + lease = self._require_lease() + with lease.lock: + self._write(table_name, path, context, records, on_append_error) + + def _write( + self, + table_name: str, + 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 + # 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): @@ -900,7 +1125,15 @@ def write(self, table_name: str, records: pa.Table) -> None: 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) @@ -919,15 +1152,12 @@ 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)) + 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 self._forget_opened(table_name) - self._append(opened.table, found, encoded) + self._append(opened.table, found, encoded, on_append_error) def _write_first( self, @@ -937,6 +1167,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``). @@ -949,6 +1180,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 = { @@ -961,7 +1193,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( @@ -973,27 +1206,70 @@ 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: - self._append(table, recorded, encoded) - - def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: + self._append(table, recorded, encoded, on_append_error) + 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, + 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 + # A full slice can still hold a nonzero offset on an empty string or + # binary child of a list. Arrow's take copies the physical columns and + # rebases their children before handing the batch to spiral-sdk 0.16. + batch = encoded.take(pa.array(range(encoded.num_rows), pa.int64())) + lease.commits += 1 # odd while the append is in flight 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) + _ = 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) + ) + if on_append_error is not None: + on_append_error() raise + finally: + lease.commits += 1 + lease.keys_by_table.setdefault(found.table_id, set()).update(_ids(encoded)) + lease.table_ids[identity.spiral_table_name(found.record.path)] = found.table_id self._found_by_id[found.table_id] = found + if (catalog := lease.catalog) is not None: + _ = catalog.names.setdefault( + found.table_id, identity.spiral_table_name(found.record.path) + ) + catalog.records[found.table_id] = (found.record, identity.TABLE_FORMAT) def _stored_names_difference( @@ -1063,6 +1339,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. @@ -1070,7 +1347,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/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index ac03ae498..201a01807 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -17,10 +17,13 @@ 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 +from orcapod.databases.spiraldb_tables import WriterLease if TYPE_CHECKING: from orcapod.databases.spiraldb_connector import SpiralDBConnector @@ -83,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 @@ -92,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: @@ -123,38 +126,47 @@ 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: 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. 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 + 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) - 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 @@ -170,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/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 330e712c5..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, @@ -45,6 +48,7 @@ shared_node_hash_error, ) from orcapod.pipeline.node_run import ( + DEFAULT_COMMIT_EVERY_ROWS, RunPlan, check_sources, clear_run_rows, @@ -91,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 @@ -144,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. @@ -1307,7 +1303,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: @@ -1360,8 +1356,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 @@ -1497,7 +1494,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: @@ -1846,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 79aa21f36..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, @@ -39,6 +44,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).""" @@ -723,6 +730,84 @@ def commit_run(databases: Sequence[ArrowDatabaseProtocol], ran: Sequence[Any]) - raise +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 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 + 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 + 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 + 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. + + 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. + """ + 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( target: Any, *, load_only: bool, unchecked_sources: Sequence[str] = () ) -> RunSummary: @@ -785,9 +870,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_node_commits(plan.to_run, 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/src/orcapod/protocols/spiraldb_run.py b/src/orcapod/protocols/spiraldb_run.py new file mode 100644 index 000000000..c55a1f8ce --- /dev/null +++ b/src/orcapod/protocols/spiraldb_run.py @@ -0,0 +1,37 @@ +"""Run 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.""" + ... + + +@runtime_checkable +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 + ) -> 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/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index d31b8e5fb..6b4e93acb 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -65,6 +65,7 @@ TRACKING_DB_SCHEMA_VERSION, constants, ) +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 @@ -421,6 +422,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. @@ -447,6 +449,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. @@ -465,12 +468,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()). @@ -1297,6 +1305,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( @@ -1312,11 +1321,21 @@ 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 + database = self._pipeline_database + if isinstance(database, SpiralDBRunLookupProtocol): + return database.spiral_completion_lookup(self._table_path) + return None + def _hold( self, rows: list[tuple[TagProtocol, DataProtocol]], *, load_only: bool = False ) -> None: @@ -1557,6 +1576,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: @@ -1573,6 +1593,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/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_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_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index 571284d22..489fcbadb 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -327,7 +327,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() @@ -804,6 +804,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( @@ -812,7 +842,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" @@ -1052,8 +1084,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( @@ -1063,7 +1097,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 @@ -1491,6 +1527,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, @@ -1629,12 +1700,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) @@ -1645,17 +1714,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) @@ -1664,7 +1734,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") @@ -1838,43 +1910,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: - """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) + db = ConnectorArrowDatabase(writable_connector(held=False)) + with database_writes([db], owner="append"): + counts = _counted(monkeypatch) + _add(db, rows(["r2", "r3"], offset=2)) + assert counts == {"names": 1, "ids": 0, "key_reads": 1} + db.flush() + assert counts == {"names": 1, "ids": 3, "key_reads": 1} + _add(db, rows(["r3", "r4"], offset=3), skip_duplicates=True, flush=True) + assert counts == {"names": 1, "ids": 5, "key_reads": 1} got = _get(db) assert got is not None assert sorted(_record_ids(got)) == [ @@ -1886,14 +1963,31 @@ 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, ) -> 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) @@ -1971,10 +2065,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)) @@ -1983,32 +2075,74 @@ 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"] + + +@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 @@ -2273,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 @@ -2333,6 +2465,104 @@ 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"] + + +@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 @@ -2422,3 +2652,218 @@ 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: + """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") + 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)) + + +@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: + """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") + 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 stale() == [paths[0]] + assert (got := first.get_all_records(paths[0])) is not None + assert got.num_rows == 1 + 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) + + +@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 35f77ed60..93c55b0c2 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 @@ -38,6 +39,7 @@ ) from orcapod.contexts import get_default_context from orcapod.databases import ( + spiral_database_identity, spiraldb_connector, spiraldb_lease, spiraldb_writable_registry, @@ -47,6 +49,7 @@ from orcapod.databases.spiraldb_write_scope import database_writes, take_lease from orcapod.databases.store_table_names import is_spiral_lease_table_name from orcapod.errors import ( + RowFailuresWarning, SpiralDBLeaseRequiredError, UnboundSourceError, UnstorableColumnError, @@ -55,13 +58,24 @@ 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 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.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.types import CacheMode, ColumnConfig, ContentHash, NodeConfig 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") @@ -114,13 +128,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"], ), @@ -128,6 +147,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, *, @@ -295,7 +317,7 @@ def test_unsupported_job_column_is_refused_before_writes( @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: @@ -371,6 +393,161 @@ 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", ORDERS) +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[Any] = [] + + def counted(table_handle: fake.FakeKeyedTable, *args: Any, **kwargs: Any) -> Any: + 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) + # 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 + + +@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 ORDERS: + listings.clear() + database = _database() + separate_connector = _database().at(JOB, "results") + _ = _run(_job(database, result_database=separate_connector, order=order), entry) + assert listings == [("p", "d")] * LEASES[entry] + + +@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"]) +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", ORDERS) +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 @@ -738,7 +915,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]) @@ -879,6 +1056,55 @@ 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 + + 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"): + pass + assert len(checks) == 1 # acquisition only + + @pytest.mark.usefixtures("root") @pytest.mark.parametrize("native", ["missing", "no address"]) def test_a_client_without_its_resolved_address_is_refused( @@ -1584,6 +1810,501 @@ def test_a_cached_source_behind_a_held_table_is_still_leased() -> None: assert any(c is connector for c in leased) +# ----------------------------------------------- independent review of 48aa8c871 + + +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"], + 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) + 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), + 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, 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")), + ): + found: list[int] = [] + + def observe(x: int, y: int, ctx: Any, found: list[int] = found) -> None: + found.append(x) + + # 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] + + +@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.""" + 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) +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"]) +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 trace_results(table: fake.FakeKeyedTable, batch: pa.Table) -> list[int]: + record = spiral_database_identity.read_table_identity_metadata( + table.get_metadata() + ) + 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) + 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 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, 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") + 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 + + +@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 + + +@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] + + # ------------------------------------- review of 4715effe3: one preflight (ITL-1871) # An entry and its keyword arguments: every way a run starts, load-only included. @@ -2436,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_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. 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()