diff --git a/changelog.d/ITL-1412.md b/changelog.d/ITL-1412.md new file mode 100644 index 000000000..f7642898a --- /dev/null +++ b/changelog.d/ITL-1412.md @@ -0,0 +1,13 @@ +### Fixed + +- Function pipeline records are published only after their referenced results commit. + A failed or discarded result batch withdraws its pending pipeline records, so + later flushes cannot publish dangling references. Failed table commits identify + the store and table. A configured no-op result database still records the processed + inputs in the pipeline store and explicitly discards its outputs. + +### Changed + +- The internal `ArrowDatabaseProtocol` now requires `pending_result`, + `guard_record`, `fail_pending_result`, `flush_result_batch`, `flush_batch`, + and `stores_records`. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 625400b73..50159ae81 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -129,6 +129,13 @@ run and computes nothing on a second `run()`. A job created without a database can be recorded but not run. Give it one later with `job.bind(database=...)`; `run()` without a database raises `ValueError`. +### Result commit ordering + +A function node publishes its pipeline records after the referenced results +commit. Failed result batches withdraw their pending pipeline records. +`NoOpArrowDatabase` explicitly discards results and still allows pipeline +bookkeeping to be written. + ### Connector databases A `ConnectorArrowDatabase` stores a column only when its connector can store it as written. diff --git a/docs/dev/design_issues/ITL-1412-FC1.md b/docs/dev/design_issues/ITL-1412-FC1.md new file mode 100644 index 000000000..48510c048 --- /dev/null +++ b/docs/dev/design_issues/ITL-1412-FC1.md @@ -0,0 +1,44 @@ +## `src/orcapod/databases/` — function result and pipeline commits + +### FC1 — Function pipeline records could outlive their discarded results +**Status:** resolved +**Severity:** critical +**Issue:** ITL-1412 + +A failed result write left pipeline records pending. A database-wide flush after the +failure could commit those records even when the result still failed or the database +had already dropped it. With separate result and pipeline stores, a successful async +branch could also publish its sibling's pipeline records before the sibling's result +table had committed. + +**Fix:** A pending pipeline record follows the commit attempt for its referenced +result. The database keeps the record in its normal readable queue while the attempt +is pending, makes it eligible for publication after success, and immediately withdraws +it on failure. Where a store supports scoped flushes, a function node flushes the +result and pipeline tables individually. +Nodes that share a physical table can still publish ready rows together. The +dependency state is held in memory and adds no columns or changes to stored identities. + +Each guarded record takes one dependency reference and one entry in the reverse +lookup. A flush checks just its queued dependencies and partitions the Arrow batch +only when some rows must wait. A failed write removes its dependent records by ID +and leaves other pending rows intact. Result retries may still store results that +were buffered, and the next run can reuse those durable results to write new records. + +In-memory tables use the same queue dependencies. A separately attached in-memory +result table is promoted at the node's batch boundary before publishing references +to it. Previously it stayed pending. Reads of the pending and promoted rows +return the same records. A no-op pipeline store leaves a separate in-memory result +table pending because it has no references to publish. + +A no-op result database is an explicit discard. Its function nodes still write their +pipeline records for processed inputs, as before. Those records refer to output +that was never stored. + +The internal `ArrowDatabaseProtocol` requires `pending_result`, `guard_record`, +and `fail_pending_result` for dependency bookkeeping and `flush_result_batch` +and `flush_batch` for committing. Its `stores_records` property distinguishes +retaining stores from explicit discards. Every library database implements these +operations, including `DeltaTableDatabase`, `InMemoryArrowDatabase`, +`ConnectorArrowDatabase`, `NoOpArrowDatabase`, and the forwarding +`ExtensionAwareDatabase` wrapper. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 117eb50b9..5fa042159 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -69,7 +69,6 @@ PipelineJobRequiredError, OrcapodDatabaseError, TypeIdentityError, - OrcapodDatabaseReadError, OrcapodDatabaseWriteError, UnstorableColumnError, ) @@ -86,6 +85,7 @@ ) from orcapod.utils.database_errors import ( commit_best_effort, + database_write_path, keep_database_error, database_error_of, ) @@ -98,7 +98,6 @@ TagProtocol, TrackerManagerProtocol, ) -from orcapod.databases.utils import as_table_committing from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.observability_protocols import ( DataExecutionLoggerProtocol, @@ -2325,66 +2324,86 @@ def _batched_commits(self, rows_per_commit: int) -> Iterator[None]: for pod in pods: pod.set_auto_flush(True) - def _ephemeral_database_in_use(self) -> ArrowDatabaseProtocol | None: - """Return the ephemeral database this node writes results to, if it does.""" - if self._node_config.is_result_ephemeral and self._ephemeral_cached_pod: - return self.ephemeral_result_database - return None - - def _commit_result_table(self) -> None: - """Commit this node's pending result rows, before its pipeline records. - - Every view of a database shares one set of pending writes, and a flush commits - them table by table in no guaranteed order. Committing the result table on - its own first means a crash between the two commits leaves results without - pipeline records (found in the result cache on the rerun, so nothing is - recomputed), never pipeline records pointing at results that were lost. - Only a database that commits table by table - (``TableCommittingDatabaseProtocol``, the Delta database) needs and offers this; - for another database the pipeline flush that follows commits everything. - """ - pod = self._cached_function_pod - if not isinstance(pod, CachedFunctionPod): - return - result_database = as_table_committing(pod.result_database) - if result_database is not None: - result_database.flush_batch(pod.record_path) + def _flush_node_table( + self, + database: ArrowDatabaseProtocol, + path: tuple[str, ...], + *, + result: bool = False, + publish_records: bool = True, + ) -> None: + """Flush one batch and withdraw dependent records if a result write fails.""" + try: + if result: + database.flush_result_batch(path, publish_records=publish_records) + else: + database.flush_batch(path) + except BaseException as exc: + if result: + database.fail_pending_result(path) + if not isinstance(exc, Exception) or isinstance(exc, OrcapodDatabaseError): + raise + raise OrcapodDatabaseWriteError( + database_write_path(database, path), + node_label=self.label, + flush=True, + table_flush=True, + ) from exc def _commit_pending_writes(self) -> None: - """Commit this node's pending writes, results first (see ``_batched_commits``). - - Raises: - OrcapodDatabaseReadError: If a stored table could not be read; it names this node. - OrcapodDatabaseWriteError: If a commit failed, naming this node and the database - (``flush=True``, no row: the batch holds many rows). The failed - writes stay pending, and earlier commits are kept. - """ - pipeline_database = self._require_pipeline_database() - ephemeral = self._ephemeral_database_in_use() + """Commit results before publishing any records that depend on them.""" try: - if ephemeral is not None: - try: - ephemeral.flush() - except OrcapodDatabaseReadError: - raise - except Exception as exc: - raise OrcapodDatabaseWriteError( - ephemeral.base_path, node_label=self.label, flush=True - ) from exc + pipeline_database = self._require_pipeline_database() + ephemeral = self._ephemeral_cached_pod + if self._node_config.is_result_ephemeral and ephemeral is not None: + self._flush_node_table( + ephemeral.result_database, ephemeral.record_path, result=True + ) + pod = self._cached_function_pod + if isinstance(pod, CachedFunctionPod): + self._flush_node_table( + pod.result_database, + pod.record_path, + result=True, + publish_records=pipeline_database.stores_records, + ) + self._flush_node_table(pipeline_database, self._versioned_pipeline_path) + except BaseException as exc: + self._commit_failed = True + if isinstance(exc, OrcapodDatabaseError): + exc.add_context(node_label=self.label) + raise + self._rows_since_commit = 0 + + def _write_pipeline_record( + self, + record_id: bytes, + record: pa.Table, + result_id: bytes, + is_ephemeral: bool, + ) -> None: + """Queue a readable record with a dependency on its result's commit.""" + database = self._require_pipeline_database() + path = self._versioned_pipeline_path + pod = self._ephemeral_cached_pod if is_ephemeral else self._cached_function_pod + if self._commit_every_rows is not None and isinstance(pod, CachedFunctionPod): + result_database = pod.result_database try: - self._commit_result_table() - pipeline_database.flush() - except OrcapodDatabaseReadError: + dependency = result_database.pending_result(pod.record_path, result_id) + except OrcapodDatabaseError: raise except Exception as exc: raise OrcapodDatabaseWriteError( - pipeline_database.base_path, node_label=self.label, flush=True + database_write_path(result_database, pod.record_path), + node_label=self.label, + flush=True, + table_flush=True, ) from exc - except OrcapodDatabaseError as exc: - self._commit_failed = True - exc.add_context(node_label=self.label) - raise - self._rows_since_commit = 0 + if dependency is not None: + with database.guard_record(path, record_id, dependency): + database.add_record(path, record_id, record, skip_duplicates=True) + return + database.add_record(path, record_id, record, skip_duplicates=True) def _row_processed(self) -> None: """Count a processed row; commit once a batch is full (only inside a job run).""" @@ -2402,21 +2421,16 @@ def _commit_at_node_end(self) -> None: def _commit_after_failure(self, run_error: BaseException) -> None: """Commit what succeeded before a failure, never replacing the run's error. - The job flushes its database after a failed run, but not a node's ephemeral - database, a separate database, and not table by table: so the node commits its - ephemeral results and then its result table here, best-effort (a failure - is noted on ``run_error``). Skipped when the failure was this node's own - commit: the job's flush is that commit's one retry. + A node that already tried its commit withdrew records whose results + failed. The job can still retry pending writes through its database. + A failure here is noted on the run's original error. Args: run_error: The error the node is failing with. """ if self._commit_every_rows is None or self._commit_failed: return - ephemeral = self._ephemeral_database_in_use() - if ephemeral is not None: - commit_best_effort(run_error, ephemeral.flush) - commit_best_effort(run_error, self._commit_result_table) + commit_best_effort(run_error, self._commit_pending_writes) @staticmethod def _commit_or_end_node( @@ -3202,13 +3216,10 @@ def _add_pipeline_record( ) try: - pipeline_database.add_record( - self._versioned_pipeline_path, - versioned_entry_id, - combined_record, - skip_duplicates=True, + self._write_pipeline_record( + versioned_entry_id, combined_record, data_record_id.bytes, is_ephemeral ) - except OrcapodDatabaseReadError: + except OrcapodDatabaseError: # The stored table could not be read: report the read failure itself. raise except Exception as exc: diff --git a/src/orcapod/databases/_pending_commits.py b/src/orcapod/databases/_pending_commits.py new file mode 100644 index 000000000..3c36bd4d2 --- /dev/null +++ b/src/orcapod/databases/_pending_commits.py @@ -0,0 +1,141 @@ +"""Dependencies between buffered rows, kept outside their stored Arrow schemas.""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from typing import TYPE_CHECKING + +from orcapod.utils.lazy_module import LazyModule + +if TYPE_CHECKING: + import pyarrow as pa +else: + pa = LazyModule("pyarrow") + + +class PendingCommit: + """The outcome of the current attempt to commit a table's pending rows.""" + + def __init__(self) -> None: + self.committed = False + self._dependents: dict[tuple[PendingCommits, str], set[bytes]] = {} + + def add_dependent(self, queue: PendingCommits, key: str, record_id: bytes) -> None: + """Withdraw this dependent record if the attempt fails.""" + self._dependents.setdefault((queue, key), set()).add(record_id) + + def finish(self, *, committed: bool) -> None: + """Release the guarded rows on success or withdraw them on failure.""" + self.committed = committed + if not committed: + for (queue, key), ids in self._dependents.items(): + queue.discard(key, ids, self) + self._dependents.clear() + + +class PendingCommits: + """Track table commit attempts and dependencies for a database's shared queue.""" + + def __init__( + self, + record_id_column: str, + batches: dict[str, pa.Table], + ids: dict[str, set[bytes]], + *, + on_empty: Callable[[str], None] | None = None, + ) -> None: + self._record_id_column = record_id_column + self._batches = batches + self._ids = ids + self._on_empty = on_empty + self._attempts: dict[str, PendingCommit] = {} + self._guards: dict[str, dict[bytes, PendingCommit]] = {} + + def attempt(self, key: str) -> PendingCommit: + """Get the attempt shared by all rows currently pending for a table.""" + 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.""" + attempt = self._attempts.pop(key, None) + if attempt is not None: + attempt.finish(committed=committed) + + @contextmanager + def guard( + self, key: str, record_id: bytes, attempt: PendingCommit + ) -> Iterator[None]: + """Guard a record before enqueueing it, which can trigger auto-flush.""" + if record_id in self._ids.get(key, ()): + yield # The queued duplicate already has its original dependency. + return + self._guards.setdefault(key, {})[record_id] = attempt + attempt.add_dependent(self, key, record_id) + try: + yield + finally: + if record_id not in self._ids.get(key, ()): + self.forget(key, {record_id}) + + def discard(self, key: str, ids: set[bytes], attempt: PendingCommit) -> None: + """Withdraw the records still guarded by the failed attempt.""" + guards = self._guards.get(key, {}) + ids = {record_id for record_id in ids if guards.get(record_id) is attempt} + self.forget(key, ids) + held_ids = self._ids.get(key) + if held_ids is None or not held_ids.intersection(ids): + return + held_ids.difference_update(ids) + if held_ids: + self._batches[key] = self._select(self._batches[key], ids, keep=False) + else: + self._batches.pop(key) + self._ids.pop(key) + if self._on_empty is not None: + self._on_empty(key) + + def take_ready(self, key: str) -> tuple[pa.Table, set[bytes]] | None: + """Take the records ready to commit, leaving blocked records readable.""" + batch = self._batches.get(key) + if batch is None or not batch.num_rows: + return None + blocked = { + record_id + for record_id, attempt in self._guards.get(key, {}).items() + if not attempt.committed + } + if not blocked: + return self._batches.pop(key), self._ids.pop(key, set()) + ids = self._ids[key] - blocked + if not ids: + return None + self._batches[key] = self._select(batch, blocked, keep=True) + self._ids[key] = blocked + return self._select(batch, blocked, keep=False), ids + + def restore(self, key: str, batch: pa.Table, ids: set[bytes]) -> None: + """Restore a retryable write ahead of rows that were held back.""" + held = self._batches.get(key) + 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.""" + guards = self._guards.get(key) + if guards is not None: + for record_id in ids: + guards.pop(record_id, None) + if not guards: + self._guards.pop(key) + + def _select(self, batch: pa.Table, ids: set[bytes], *, keep: bool) -> pa.Table: + """Keep or remove the given rows, preserving their order and schema.""" + mask = [ + (record_id in ids) == keep + for record_id in batch[self._record_id_column].to_pylist() + ] + return batch.filter(pa.array(mask, type=pa.bool_())) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 761486310..5a3a0f5c7 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -21,8 +21,10 @@ import re from collections import defaultdict from collections.abc import Collection, Mapping +from contextlib import AbstractContextManager from typing import TYPE_CHECKING, Any, cast +from orcapod.databases._pending_commits import PendingCommit, PendingCommits from orcapod.databases.utils import ( coerce_record_id, first_changed_column, @@ -101,6 +103,8 @@ class ConnectorArrowDatabase: Defaults to 10, matching ``InMemoryArrowDatabase``. """ + stores_records = True + RECORD_ID_COLUMN = "__record_id" _ROW_INDEX_COLUMN = "__row_index" @@ -140,6 +144,21 @@ def __init__( else {} ) + self._pending_commits = ( + _root._pending_commits + if _root is not None + else PendingCommits( + self.RECORD_ID_COLUMN, + self._pending_batches, + self._pending_record_ids, + on_empty=self._discard_pending_duplicate_policy, + ) + ) + + def _discard_pending_duplicate_policy(self, key: str) -> None: + """Forget the duplicate policy when an entire queued batch is discarded.""" + self._pending_skip_existing.pop(key, None) + # ── Path helpers ────────────────────────────────────────────────────────── def _get_record_key(self, record_path: tuple[str, ...]) -> str: @@ -614,16 +633,61 @@ def at(self, *path_components: str) -> "ConnectorArrowDatabase": # ── Flush ───────────────────────────────────────────────────────────────── + def pending_result( + self, record_path: tuple[str, ...], record_id: bytes + ) -> PendingCommit | None: + """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) + if self.get_record_by_id(record_path, record_id) is None: + raise ValueError("The referenced result is neither stored nor pending.") + return None + + def fail_pending_result(self, record_path: tuple[str, ...]) -> None: + """Withdraw records depending on this table's current commit attempt.""" + self._pending_commits.finish(self._get_record_key(record_path), committed=False) + + def guard_record( + self, + record_path: tuple[str, ...], + record_id: bytes, + dependency: PendingCommit, + ) -> AbstractContextManager[None]: + """Prevent this record's publication until its result commits.""" + return self._pending_commits.guard( + self._get_record_key(record_path), record_id, dependency + ) + def flush(self) -> None: """Commit all pending batches to the connector via upsert.""" - for record_key in list(self._pending_batches.keys()): - record_path = tuple(record_key.split("/")) - table_name = self._path_to_table_name(record_path) - self._require_table_name(table_name) - pending = self._pending_batches.pop(record_key) - self._pending_record_ids.pop(record_key, None) - skip_existing = self._pending_skip_existing.pop(record_key, False) + for record_key in list(self._pending_batches): + self._flush_by_key(record_key) + + def flush_result_batch( + self, record_path: tuple[str, ...], *, publish_records: bool + ) -> None: + """Commit a durable result table even if no pipeline records are stored.""" + self.flush_batch(record_path) + 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.""" + ready = self._pending_commits.take_ready(record_key) + if ready is None: + return + pending, ids = ready + record_path = tuple(record_key.split("/")) + table_name = self._path_to_table_name(record_path) + skip_existing = self._pending_skip_existing.get(record_key, False) + if record_key not in self._pending_batches: + self._pending_skip_existing.pop(record_key, None) + + try: + self._require_table_name(table_name) columns = _arrow_schema_to_column_infos(pending.schema) # Schema validation: if the table already exists, confirm the column @@ -670,6 +734,13 @@ def _fmt(cols: dict) -> str: id_column=self.RECORD_ID_COLUMN, skip_existing=skip_existing, ) + except BaseException: + self._pending_commits.finish(record_key, committed=False) + raise + else: + self._pending_commits.finish(record_key, committed=True) + finally: + self._pending_commits.forget(record_key, ids) # ── Read methods ────────────────────────────────────────────────────────── diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index cbf6e2831..a6bd0f9e5 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -5,10 +5,12 @@ import sys from collections import defaultdict from collections.abc import Callable, Collection, Mapping +from contextlib import AbstractContextManager from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, cast +from orcapod.databases._pending_commits import PendingCommit, PendingCommits from orcapod.databases._row_index import ( KeyIndex, compact_tail, @@ -1070,6 +1072,8 @@ class DeltaTableDatabase: # Class constants for internal column names ROW_INDEX_COLUMN = "__row_index" + stores_records = True + RECORD_ID_COLUMN = "__record_id" def __init__( @@ -1140,6 +1144,16 @@ def __init__( self._pending_indexes: dict[str, KeyIndex] = ( _shared_pending_indexes if _shared_pending_indexes is not None else {} ) + self._pending_commits = ( + _root._pending_commits + if _root is not None + else PendingCommits( + self.RECORD_ID_COLUMN, + self._pending_batches, + self._pending_record_ids, + on_empty=self._discard_pending_index, + ) + ) # Record keys whose table was found absent (ITL-1173), so lookups do not try # to open it again on every row. Family-wide like the loaded tables, and # forgotten on any flush of the family and on a flush of the key: a table @@ -1149,11 +1163,9 @@ def __init__( _shared_absent_tables if _shared_absent_tables is not None else set() ) - def _clear_pending(self): - """Clear all pending state.""" - self._pending_batches = {} - self._pending_record_ids = defaultdict(set) - # Note: next_row_index continues incrementing + def _discard_pending_index(self, key: str) -> None: + """Release a discarded batch's cached read index.""" + self._pending_indexes.pop(key, None) def _get_record_key(self, record_path: tuple[str, ...]) -> str: """Generate cache key for source storage. @@ -2557,6 +2569,38 @@ def flush(self) -> None: f"Failed to flush {len(errors)} batch(es): {failed_keys}" ) from errors[0][1] + def pending_result( + self, record_path: tuple[str, ...], record_id: bytes + ) -> PendingCommit | None: + """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) + if record_id not in self._stored_ids(record_path): + raise ValueError("The referenced result is neither stored nor pending.") + return None + + def fail_pending_result(self, record_path: tuple[str, ...]) -> None: + """Withdraw records depending on this table's current commit attempt.""" + self._pending_commits.finish(self._get_record_key(record_path), committed=False) + + def guard_record( + self, + record_path: tuple[str, ...], + record_id: bytes, + dependency: PendingCommit, + ) -> AbstractContextManager[None]: + """Prevent this record's publication until its result commits.""" + return self._pending_commits.guard( + self._get_record_key(record_path), record_id, dependency + ) + + def flush_result_batch( + self, record_path: tuple[str, ...], *, publish_records: bool + ) -> None: + """Commit a durable result table even if no pipeline records are stored.""" + self.flush_batch(record_path) + def flush_batch(self, record_path: tuple[str, ...]) -> None: """ Flush pending batch for a specific source path. @@ -2577,15 +2621,10 @@ def _flush_by_key(self, record_key: str) -> None: logger.debug("Flushing triggered!!") self._absent_tables.discard(record_key) - if ( - record_key not in self._pending_batches - or not self._pending_batches[record_key] - ): + ready = self._pending_commits.take_ready(record_key) + if ready is None: return - - # Get all pending records - pending_batch = self._pending_batches.pop(record_key) - pending_ids = self._pending_record_ids.pop(record_key, set()) + pending_batch, pending_ids = ready # Derive the absolute table URI directly from the key (already includes prefix). abs_path_components = tuple(record_key.split("/")) @@ -2721,16 +2760,19 @@ def _flush_by_key(self, record_key: str) -> None: f"{record_key!r} were not written and are no longer queued: correct " "them and add them again." ) + self._pending_commits.forget(record_key, pending_ids) + self._pending_commits.finish(record_key, committed=False) logger.error(f"Refused batch for {record_key}: {refused}") raise refused from e - except Exception as e: - logger.error(f"Error flushing batch for {record_key}: {e}") - # Put the tables back in the pending queue - self._pending_batches[record_key] = pending_batch - self._pending_record_ids[record_key] = pending_ids + except BaseException as exc: + logger.error(f"Error flushing batch for {record_key}: {exc}") + self._pending_commits.finish(record_key, committed=False) + self._pending_commits.restore(record_key, pending_batch, pending_ids) raise # The rows are committed: nothing below may put them back in the queue. + self._pending_commits.forget(record_key, pending_ids) + self._pending_commits.finish(record_key, committed=True) try: committed = ( delta_table @@ -3094,6 +3136,11 @@ def comparable(arrow_type: pa.DataType) -> pa.DataType: return field.name, held, incoming return None + @property + def storage_location(self) -> str: + """The URI of this database's storage root.""" + return self._root_uri + @property def base_path(self) -> tuple[str, ...]: """The current relative root of this database view (always () for root instances).""" diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index 63306b747..74a4aa218 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -23,13 +23,16 @@ from __future__ import annotations from collections.abc import Callable, Collection, Mapping -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, cast from orcapod.logical_types.database_hooks import register_discovered_logical_types from orcapod.protocols.database_protocols import ArrowDatabaseProtocol if TYPE_CHECKING: + from contextlib import AbstractContextManager + import pyarrow as pa + from orcapod.databases._pending_commits import PendingCommit from orcapod.logical_types.protocols import TypeConverterProtocol @@ -202,14 +205,41 @@ def batch_size(self) -> int: """ return getattr(self._db, "batch_size") # noqa: B009 # AttributeError when absent, by design + def flush_batch(self, record_path: tuple[str, ...]) -> None: + """Flush the wrapped pipeline batch.""" + 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 pending_result( + self, record_path: tuple[str, ...], record_id: bytes + ) -> PendingCommit | None: + """Return the wrapped database's pending commit dependency.""" + return self._db.pending_result(record_path, record_id) + + def fail_pending_result(self, record_path: tuple[str, ...]) -> None: + """Withdraw the wrapped result batch's dependent records.""" + self._db.fail_pending_result(record_path) + + def guard_record( + self, record_path: tuple[str, ...], record_id: bytes, dependency: PendingCommit + ) -> AbstractContextManager[None]: + """Guard a queued record in the wrapped database.""" + return self._db.guard_record(record_path, record_id, dependency) + @property - def flush_batch(self) -> Callable[[tuple[str, ...]], None]: - """The wrapped database's ``flush_batch`` (commits one table's writes). + def stores_records(self) -> bool: + """Return whether the wrapped database retains records.""" + return self._db.stores_records - Raises: - AttributeError: If the wrapped database has none (see ``batch_size``). - """ - return getattr(self._db, "flush_batch") # noqa: B009 # AttributeError when absent, by design + @property + def storage_location(self) -> str: + """The wrapped database's storage location, if it names one.""" + return getattr(self._db, "storage_location") # noqa: B009 # optional capability @property def require_storable(self) -> Callable[[pa.Schema], None]: @@ -274,3 +304,15 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: def to_config(self) -> dict[str, Any]: return self._db.to_config() + + @classmethod + def from_config(cls, config: dict[str, Any]) -> ExtensionAwareDatabase: + """Rebuild the underlying store and wrap it with the default converter.""" + from orcapod.contexts import get_default_type_converter + from orcapod.pipeline.serialization import resolve_database_from_config + + database = cast(ArrowDatabaseProtocol, resolve_database_from_config(config)) + converter = cast( + "TypeConverterProtocol", cast(object, get_default_type_converter()) + ) + return cls(database, converter) diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 3c78dd1e0..7c9ec84f6 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -3,15 +3,21 @@ import logging from collections import defaultdict from collections.abc import Collection, Mapping +from contextlib import AbstractContextManager from typing import TYPE_CHECKING, Any, cast +from orcapod.databases._pending_commits import PendingCommit, PendingCommits from orcapod.databases._row_index import KeyIndex, compact_tail, matching_rows from orcapod.databases.utils import ( coerce_record_id, first_changed_column, in_held_column_order, ) -from orcapod.errors import InputValidationError +from orcapod.errors import ( + InputValidationError, + OrcapodDatabaseError, + OrcapodDatabaseWriteError, +) from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: @@ -41,6 +47,8 @@ class InMemoryArrowDatabase: cost of a per-row write, flush or lookup does not grow with the rows already stored. """ + stores_records = True + RECORD_ID_COLUMN = "__record_id" def __init__( @@ -73,6 +81,14 @@ def __init__( _shared_indexes if _shared_indexes is not None else {} ) + self._pending_commits = ( + _root._pending_commits + if _root is not None + else PendingCommits( + self.RECORD_ID_COLUMN, self._pending_batches, self._pending_record_ids + ) + ) + # ------------------------------------------------------------------ # Path helpers # ------------------------------------------------------------------ @@ -325,37 +341,102 @@ def keeps_field_metadata(self) -> bool: """Whether this database keeps Arrow field metadata: it does (ITL-1019).""" return True + def pending_result( + self, record_path: tuple[str, ...], record_id: bytes + ) -> PendingCommit | None: + """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) + if record_id not in self._committed_id_index(key): + raise ValueError("The referenced result is neither stored nor pending.") + return None + + def fail_pending_result(self, record_path: tuple[str, ...]) -> None: + """Withdraw records depending on this table's current commit attempt.""" + self._pending_commits.finish(self._get_record_key(record_path), committed=False) + + def guard_record( + self, + record_path: tuple[str, ...], + record_id: bytes, + dependency: PendingCommit, + ) -> AbstractContextManager[None]: + """Prevent this record's publication until its result commits.""" + return self._pending_commits.guard( + self._get_record_key(record_path), record_id, dependency + ) + def flush(self) -> None: - for record_key in list(self._pending_batches.keys()): - pending = self._pending_batches.pop(record_key) - self._pending_record_ids.pop(record_key, None) - - committed = self._tables.get(record_key) - if committed is None: - self._tables[record_key] = pending.combine_chunks() - continue - - # Insert-if-not-exists: keep committed rows not overwritten by new batch, - # then append the new batch on top. - new_ids = pending[self.RECORD_ID_COLUMN].to_pylist() - committed_ids = self._committed_id_index(record_key) - if any(record_id in committed_ids for record_id in new_ids): - mask = pc.invert( - pc.is_in(committed[self.RECORD_ID_COLUMN], pa.array(list(new_ids))) - ) - kept = committed.filter(mask) - self._tables[record_key] = pa.concat_tables( - [kept, pending] - ).combine_chunks() - # Rows moved: the indexes are rebuilt on the next lookup. - self._indexes.pop(record_key, None) - continue - - appended = compact_tail(pa.concat_tables([committed, pending])) - self._tables[record_key] = appended - key_index = self._indexes.get(record_key) - if key_index is not None and key_index.table is committed: - key_index.append(pending, appended) + """Promote the ready batches in the shared queue.""" + for record_key in list(self._pending_batches): + self._flush_by_key(record_key) + + def flush_result_batch( + self, record_path: tuple[str, ...], *, publish_records: bool + ) -> None: + """Promote the result table when pipeline records will reference it.""" + if publish_records: + self.flush_pending_table(record_path) + + def flush_batch(self, record_path: tuple[str, ...]) -> None: + """Flush the in-memory queue while honoring all pending guards.""" + try: + self.flush() + except OrcapodDatabaseError: + raise + except Exception as exc: + raise OrcapodDatabaseWriteError(self.base_path, flush=True) from exc + + def flush_pending_table(self, record_path: tuple[str, ...]) -> None: + """Promote one in-memory result table before publishing its references.""" + self._flush_by_key(self._get_record_key(record_path)) + + def _flush_by_key(self, record_key: str) -> None: + """Promote the ready records at one key shared by all views.""" + ready = self._pending_commits.take_ready(record_key) + if ready is None: + return + pending, ids = ready + try: + self._promote(record_key, pending) + except BaseException: + # A refused in-memory batch leaves the queue, as it did before guards. + self._pending_commits.finish(record_key, committed=False) + raise + else: + self._pending_commits.finish(record_key, committed=True) + finally: + self._pending_commits.forget(record_key, ids) + + def _promote(self, record_key: str, pending: "pa.Table") -> None: + """Append the ready rows and update the committed indexes.""" + committed = self._tables.get(record_key) + if committed is None: + self._tables[record_key] = pending.combine_chunks() + return + + # Insert-if-not-exists: keep committed rows not overwritten by new batch, + # then append the new batch on top. + new_ids = pending[self.RECORD_ID_COLUMN].to_pylist() + committed_ids = self._committed_id_index(record_key) + if any(record_id in committed_ids for record_id in new_ids): + mask = pc.invert( + pc.is_in(committed[self.RECORD_ID_COLUMN], pa.array(list(new_ids))) + ) + kept = committed.filter(mask) + self._tables[record_key] = pa.concat_tables( + [kept, pending] + ).combine_chunks() + # Rows moved: the indexes are rebuilt on the next lookup. + self._indexes.pop(record_key, None) + return + + appended = compact_tail(pa.concat_tables([committed, pending])) + self._tables[record_key] = appended + key_index = self._indexes.get(record_key) + if key_index is not None and key_index.table is committed: + key_index.append(pending, appended) # ------------------------------------------------------------------ # Path scoping diff --git a/src/orcapod/databases/noop_database.py b/src/orcapod/databases/noop_database.py index 27c1bf9b6..3c60c020b 100644 --- a/src/orcapod/databases/noop_database.py +++ b/src/orcapod/databases/noop_database.py @@ -1,12 +1,14 @@ from __future__ import annotations from collections.abc import Collection, Mapping +from contextlib import AbstractContextManager, nullcontext from typing import TYPE_CHECKING, Any from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: import pyarrow as pa + from orcapod.databases._pending_commits import PendingCommit else: pa = LazyModule("pyarrow") @@ -29,6 +31,8 @@ class NoOpArrowDatabase: node. """ + stores_records = False + def __init__( self, _path_prefix: tuple[str, ...] = (), @@ -101,6 +105,28 @@ def keeps_field_metadata(self) -> bool: def flush(self) -> None: pass + def fail_pending_result(self, record_path: tuple[str, ...]) -> None: + """There are no buffered writes to withdraw.""" + + def flush_result_batch( + self, record_path: tuple[str, ...], *, publish_records: bool + ) -> None: + """A discarded result leaves no batch to commit.""" + + def flush_batch(self, record_path: tuple[str, ...]) -> None: + """Flush the no-op store at the pipeline batch boundary.""" + self.flush() + + def pending_result(self, record_path: tuple[str, ...], record_id: bytes) -> None: + """Treat explicitly discarded outputs as resolved for bookkeeping.""" + return None + + def guard_record( + self, record_path: tuple[str, ...], record_id: bytes, dependency: PendingCommit + ) -> AbstractContextManager[None]: + """Accept the bookkeeping dependency without retaining the pipeline record.""" + return nullcontext() + def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...]]: """Return no path: this no-op implementation never stores a table. diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 7488bb0ba..eded0bcc1 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -988,6 +988,7 @@ def __init__( tag: Mapping[str, Any] | None = None, *, flush: bool = False, + table_flush: bool = False, ) -> None: """Create the error for one failed write. @@ -997,9 +998,11 @@ def __init__( node_label: Label of the node whose write failed, if the write site knows it. tag: Tag values of the row being stored, if the write covered one row. flush: Whether committing pending writes failed. + table_flush: Whether the flush was scoped to the given table. """ self.record_path: tuple[str, ...] = tuple(record_path) self.flush: bool = flush + self._table_flush = table_flush super().__init__( self.record_path, node_label, tag, node_label=node_label, tag=tag ) @@ -1034,6 +1037,11 @@ def __str__(self) -> str: ) if self.flush: node = f" for node {self.node_label!r}" if self.node_label else "" + if self._table_flush: + return ( + f"Could not commit pending writes to the database{node} " + f"(table {'/'.join(self.record_path)!r}){reason}. " + retry + ) return ( f"Could not commit pending writes to the database{node} " f"(database {'/'.join(self.record_path)!r}){reason}. The failing write " diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index ea3f5570f..c7c570326 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -46,7 +46,7 @@ from orcapod.protocols import core_protocols as cp from orcapod.databases.utils import as_table_committing from orcapod.types import NodeConfig -from orcapod.utils.database_errors import flush_best_effort +from orcapod.utils.database_errors import database_write_path, flush_best_effort if TYPE_CHECKING: from pathlib import Path @@ -975,8 +975,9 @@ def run( are flushed first, so rows stored before the failure are kept, and re-running the job does not recompute stored function results. A failed commit of a node's batch names the node but no row - (``flush=True``): the batch's writes stay pending and are retried - once by the flush that follows the failure. + (``flush=True``). When a result batch fails, its pending pipeline + records are withdrawn. The flush after the failure may retry the + result write if the database kept the batch. OrcapodDatabaseReadError: If a stored table exists but could not be read, whatever the orchestrator's ``error_policy``, also when the read was needed to write a node's results. Its rows are not recomputed @@ -1335,9 +1336,9 @@ def _executing( ) yield except BaseException as run_error: - # Commit the writes that did succeed before the failure, so their rows - # do not look dropped, then report the failure itself. A cancelled or - # interrupted run commits nothing more, but clears its nodes too. + # Retry remaining writes. Function records with failed results have + # been withdrawn, and pending results still gate their dependent records. + # A cancelled or interrupted run clears its nodes without flushing here. if isinstance(run_error, Exception) and not load_only: flush_best_effort(run_error, prepared.pipeline_db, prepared.result_db) clear_run_rows(plan.to_run) @@ -1380,12 +1381,14 @@ def _finish_run( + "cache_mode=LOG operator's output or a node's last records, may not " + "have been stored." ) + database = pipeline_db try: if not load_only and plan.to_run: # A load-only run writes nothing and commits nothing, and a run that # ran no node touches no database (ITL-1095). - pipeline_db.flush() - result_db.flush() + database.flush() + database = result_db + database.flush() except OrcapodDatabaseReadError as exc: # A stored table could not be read: report the read failure itself. exc.add_note(pending_note) @@ -1393,7 +1396,9 @@ def _finish_run( clear_run_rows(plan.to_run) raise except Exception as exc: - flush_error = OrcapodDatabaseWriteError(pipeline_db.base_path, flush=True) + flush_error = OrcapodDatabaseWriteError( + database_write_path(database), flush=True + ) flush_error.add_note(pending_note) clear_run_rows(plan.to_run) raise flush_error from exc diff --git a/src/orcapod/protocols/database_protocols.py b/src/orcapod/protocols/database_protocols.py index fa1bbafd5..be9903977 100644 --- a/src/orcapod/protocols/database_protocols.py +++ b/src/orcapod/protocols/database_protocols.py @@ -1,16 +1,65 @@ from __future__ import annotations from collections.abc import Collection, Mapping +from contextlib import AbstractContextManager from typing import Any, Protocol, TYPE_CHECKING, runtime_checkable from orcapod.protocols.db_connector_protocol import ColumnInfo, DBConnectorProtocol if TYPE_CHECKING: import pyarrow as pa + from orcapod.databases._pending_commits import PendingCommit @runtime_checkable class ArrowDatabaseProtocol(Protocol): + """Internal Arrow store interface, including ordered function commits. + + A queued result provides a shared commit token. A guarded pipeline record + stays readable in its queue while its result is pending. Success makes it + eligible for publication. Failure withdraws it, even when result rows stay + queued for retry. Scoped views share their pending queues and commit tokens. + """ + + @property + def stores_records(self) -> bool: + """Return whether this store keeps records. Explicit discards return False.""" + ... + + def pending_result( + self, record_path: tuple[str, ...], record_id: bytes + ) -> PendingCommit | None: + """Return a queued result's token, or None for an already stored or explicitly discarded result.""" + ... + + def guard_record( + self, record_path: tuple[str, ...], record_id: bytes, dependency: PendingCommit + ) -> AbstractContextManager[None]: + """Bind a record to its result's token before enqueue can publish it.""" + ... + + def fail_pending_result(self, record_path: tuple[str, ...]) -> None: + """Withdraw records dependent on a failed result attempt.""" + ... + + def flush_result_batch( + self, record_path: tuple[str, ...], *, publish_records: bool + ) -> None: + """Commit this result batch and resolve its token. + + Durable result stores commit even without pipeline records. In-memory stores + can leave results queued when the pipeline explicitly discards its records. + """ + ... + + def flush_batch(self, record_path: tuple[str, ...]) -> None: + """Flush this pipeline batch, keeping records whose results are pending queued. + + Table-scoped stores commit only this table. In-memory stores may flush the + shared queue while honoring every record's guard. + """ + ... + def add_record( self, record_path: tuple[str, ...], diff --git a/src/orcapod/utils/database_errors.py b/src/orcapod/utils/database_errors.py index 040bb5400..b2b3ebc76 100644 --- a/src/orcapod/utils/database_errors.py +++ b/src/orcapod/utils/database_errors.py @@ -97,6 +97,15 @@ def keep_database_error( note_callback_failure(database_error, during, failure) +def database_write_path( + database: ArrowDatabaseProtocol, record_path: tuple[str, ...] = () +) -> tuple[str, ...]: + """Locate a database write, including the backend's root when it names one.""" + location = getattr(database, "storage_location", None) + root = (location,) if isinstance(location, str) and location else () + return root + database.base_path + record_path + + def commit_best_effort(run_error: BaseException, commit: Callable[[], None]) -> None: """Commit pending writes after a run failed, noting instead of raising a failure. diff --git a/tests/test_databases/test_in_memory_database.py b/tests/test_databases/test_in_memory_database.py index 954f208d9..8e6d35cea 100644 --- a/tests/test_databases/test_in_memory_database.py +++ b/tests/test_databases/test_in_memory_database.py @@ -333,6 +333,51 @@ def test_multiple_flushes_accumulate_records(self, db): assert result.num_rows == 2 +@pytest.mark.parametrize( + "separate", [False, True], ids=["whole-flush", "scoped-result"] +) +def test_refused_result_batch_is_dropped_with_its_dependent_record( + separate: bool, +) -> None: + """A failed promotion clears the bad batch so a corrected write can proceed.""" + results = InMemoryArrowDatabase() + pipeline = InMemoryArrowDatabase() if separate else results.at("pipeline") + result_path = ("results",) + pipeline_path = ("records",) + prior = pa.table({"value": pa.array([1], type=pa.int64())}) + refused = pa.table({"value": pa.array([2], type=pa.int32())}) + corrected = pa.table({"value": pa.array([2], type=pa.int64())}) + + results.add_record(result_path, b"prior", prior, flush=True) + results.add_record(result_path, b"new", refused) + attempt = results.pending_result(result_path, b"new") + assert attempt is not None + with pipeline.guard_record(pipeline_path, b"new", attempt): + pipeline.add_record(pipeline_path, b"new", corrected) + + with pytest.raises(pa.ArrowInvalid): + if separate: + results.flush_result_batch(result_path, publish_records=True) + else: + results.flush() + + results.flush() + pipeline.flush() + assert results.get_all_records(result_path) == prior + assert results.get_record_by_id(result_path, b"new") is None + assert pipeline.get_all_records(pipeline_path) is None + + results.add_record(result_path, b"new", corrected) + retry = results.pending_result(result_path, b"new") + assert retry is not None and retry is not attempt + with pipeline.guard_record(pipeline_path, b"new", retry): + pipeline.add_record(pipeline_path, b"new", corrected) + results.flush() + pipeline.flush() + assert results.get_record_by_id(result_path, b"new") == corrected + assert pipeline.get_record_by_id(pipeline_path, b"new") == corrected + + # --------------------------------------------------------------------------- # 10. at() and base_path # --------------------------------------------------------------------------- diff --git a/tests/test_pipeline/test_function_commit_dependencies.py b/tests/test_pipeline/test_function_commit_dependencies.py new file mode 100644 index 000000000..efc00a547 --- /dev/null +++ b/tests/test_pipeline/test_function_commit_dependencies.py @@ -0,0 +1,364 @@ +"""Function pipeline records follow the durability of the results they reference.""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +import uuid +from collections import Counter +from collections.abc import Callable +from typing import cast + +import deltalake +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.databases import DeltaTableDatabase +from orcapod.errors import InputValidationError, OrcapodDatabaseWriteError +from orcapod.invocation import InvocationContext +from orcapod.sources import DictSource +from orcapod.system_constants import ( + PIPELINE_DB_SCHEMA_VERSION, + RESULT_DB_SCHEMA_VERSION, + constants, +) + +JOB = "ordered" +PIPELINE = PIPELINE_DB_SCHEMA_VERSION +RESULT = RESULT_DB_SCHEMA_VERSION +ENTRY = "__pipeline_entry_id" +BASE_ENTRY = "__pipeline_base_entry_id" +RECOMPUTATION = "__pipeline_recomputation_index" +CALLS: list[int] = [] +DELIVERIES: list[int] = [] + + +@function_pod(output_keys="y") +def double(x: int) -> int: + """Count calls and double the input.""" + CALLS.append(x) + return 2 * x + + +@function_pod(output_keys="z") +def triple(x: int) -> int: + """Triple the input.""" + return 3 * x + + +@function_pod(output_keys="y", ctx_arg="ctx") +def deliver(x: int, ctx: InvocationContext) -> int: + """Record a delivery.""" + DELIVERIES.append(x) + return x + + +def source(start: int, *, reversed_tags: bool = False) -> DictSource: + """Give each branch four rows and its own source identity.""" + rows = [ + {"tag": i, "group": "a", "x": i, "other": i + 10} + for i in range(start, start + 4) + ] + if reversed_tags: + rows = [dict(reversed(tuple(row.items()))) for row in rows] + return DictSource( + data=rows, + tag_columns=["group", "tag"] if reversed_tags else ["tag", "group"], + tag_only_columns=True, + source_id=f"source_{start}", + ) + + +def node_of(job: PipelineJob, name: str) -> FunctionJobNode: + """Get a public function node with its narrowed type.""" + node = job.nodes[name] + assert isinstance(node, FunctionJobNode) + return node + + +def run(job: PipelineJob, asynchronous: bool, every: int) -> None: + """Run via the chosen public entry point.""" + if asynchronous: + asyncio.run(job.run_async(commit_every_rows=every)) + else: + job.run(commit_every_rows=every) + + +def read_tables(root: Path, version: str) -> dict[tuple[str, ...], pa.Table]: + """Read only durable tables through a newly opened handle.""" + reader = DeltaTableDatabase(root) + tables: dict[tuple[str, ...], pa.Table] = {} + for path in reader.list_table_paths(): + if path[-1] == version: + table = reader.get_all_records(path, record_id_column="rid") + assert table is not None + tables[path] = table + return tables + + +def inject_result_failure( + monkeypatch: pytest.MonkeyPatch, failure: type[Exception] +) -> list[Path]: + """Fail only result table writes, leaving pipeline table writes available.""" + original = cast(Callable[..., None], deltalake.write_deltalake) + attempted: list[Path] = [] + + def write( + table_or_uri: str | Path | deltalake.DeltaTable, + data: pa.Table, + **kwargs: object, + ) -> None: + uri = ( + table_or_uri.table_uri + if isinstance(table_or_uri, deltalake.DeltaTable) + else table_or_uri + ) + path = Path(uri) + if path.name == RESULT: + attempted.append(path) + raise failure("injected result table write failure") + original(table_or_uri, data, **kwargs) + + monkeypatch.setattr(deltalake, "write_deltalake", write) + return attempted + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("every", [1, 10]) +@pytest.mark.parametrize( + "separate", [False, True], ids=["shared-store", "split-stores"] +) +@pytest.mark.parametrize( + "failure", [OSError, InputValidationError], ids=["retryable", "dropped"] +) +def test_result_failure_withdraws_records_and_rerun_recovers( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + asynchronous: bool, + every: int, + separate: bool, + failure: type[Exception], +) -> None: + """A failed or dropped result leaves no queued or durable references.""" + CALLS.clear() + pipeline_root = tmp_path / "pipeline" + result_root = tmp_path / "results" if separate else pipeline_root + pipeline_db = DeltaTableDatabase(pipeline_root) + result_db = ( + DeltaTableDatabase(result_root).at("external") + if separate + else pipeline_db.at(JOB, "_result") + ) + job = PipelineJob(name=JOB, database=pipeline_db) + with job: + double.pod(source(0), label="out") + node = node_of(job, "out") + if separate: + node.attach_databases( + pipeline_database=pipeline_db.at(JOB), result_database=result_db + ) + pipeline_path = (JOB, *node.node_identity_path, PIPELINE) + with monkeypatch.context() as fault: + attempts = inject_result_failure(fault, failure) + with pytest.raises(OrcapodDatabaseWriteError) as raised: + run(job, asynchronous, every) + assert attempts and not read_tables(result_root, RESULT) + assert not read_tables(pipeline_root, PIPELINE) + assert pipeline_db.get_all_records(pipeline_path) is None + assert node.as_table().num_rows == 0 + assert str(attempts[0]) in str(raised.value) + assert isinstance(raised.value.__cause__, failure) + + # An unrelated flush after the injection ends cannot publish any of the failed records. + pipeline_db.flush() + assert not read_tables(pipeline_root, PIPELINE) + if failure is InputValidationError: + assert not read_tables(result_root, RESULT) + CALLS.clear() + run(job, asynchronous, every) + assert Counter(node.as_source().as_table()["y"].to_pylist()) == Counter( + [0, 2, 4, 6] + ) + assert Counter(node.as_table()["y"].to_pylist()) == Counter([0, 2, 4, 6]) + if failure is InputValidationError and every > 1: + assert sorted(CALLS) == [0, 1, 2, 3] + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +def test_failed_side_effect_result_leaves_no_completion_record( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, asynchronous: bool +) -> None: + """Delivery can precede a failed write, but its completion cannot persist alone.""" + DELIVERIES.clear() + root = tmp_path / "store" + db = DeltaTableDatabase(root) + job = PipelineJob(name=JOB, database=db) + with job: + deliver.pod(source(0), label="out") + with monkeypatch.context() as fault: + inject_result_failure(fault, InputValidationError) + with pytest.raises(OrcapodDatabaseWriteError): + run(job, asynchronous, 10) + assert sorted(DELIVERIES) == [0, 1, 2, 3] + db.flush() + assert not read_tables(root, PIPELINE) + assert not read_tables(root, RESULT) + assert node_of(job, "out").as_source().as_table().num_rows == 0 + + +@pytest.mark.parametrize( + "separate", [False, True], ids=["shared-store", "split-stores"] +) +@pytest.mark.parametrize( + "shared_table", [False, True], ids=["distinct-tables", "shared-table"] +) +def test_async_flush_exposes_only_records_with_durable_results( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, separate: bool, shared_table: bool +) -> None: + """Read each table from a fresh handle immediately after each effective flush.""" + pipeline_root = tmp_path / "pipeline" + pipeline_db = DeltaTableDatabase(pipeline_root) + result_roots = ( + [tmp_path / "left", tmp_path / "right"] if separate else [pipeline_root] + ) + job = PipelineJob(name=JOB, database=pipeline_db) + with job: + double.pod(source(0), label="left") + second = double if shared_table else triple + second.pod(source(4, reversed_tags=True), label="right") + left, right = (node_of(job, name) for name in ("left", "right")) + assert (left.node_identity_path == right.node_identity_path) == shared_table + if separate: + for node, root in zip((left, right), result_roots, strict=True): + node.attach_databases( + pipeline_database=pipeline_db.at(JOB), + result_database=DeltaTableDatabase(root), + ) + + publication_counts: list[int] = [] + dangling: list[set[bytes]] = [] + original_flush = DeltaTableDatabase.flush + original_batch = DeltaTableDatabase.flush_batch + + def observe() -> None: + committed = { + rid + for root in result_roots + for table in read_tables(root, RESULT).values() + for rid in cast(list[bytes], table["rid"].to_pylist()) + } + referenced = { + rid + for table in read_tables(pipeline_root, PIPELINE).values() + for rid in cast(list[bytes], table[constants.DATA_RECORD_ID].to_pylist()) + } + missing = referenced - committed + if missing: + dangling.append(missing) + if referenced and ( + not publication_counts or len(referenced) != publication_counts[-1] + ): + publication_counts.append(len(referenced)) + + def flush(db: DeltaTableDatabase) -> None: + original_flush(db) + observe() + + def flush_batch(db: DeltaTableDatabase, path: tuple[str, ...]) -> None: + original_batch(db, path) + observe() + + monkeypatch.setattr(DeltaTableDatabase, "flush", flush) + monkeypatch.setattr(DeltaTableDatabase, "flush_batch", flush_batch) + run(job, asynchronous=True, every=10) + assert not dangling + assert publication_counts == ([8] if shared_table and not separate else [4, 8]) + for node in (left, right): + assert node.as_table().num_rows == node.as_source().as_table().num_rows == 4 + if shared_table and not separate: + (log,) = pipeline_root.rglob(f"{PIPELINE}/_delta_log") + assert [ + item["operation"] + for item in deltalake.DeltaTable(str(log.parent)).history() + ] == ["WRITE"] + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize( + "reader", + ["point", "scan", "filtered", "recomputation", "cache", "source", "joined"], +) +def test_pending_records_remain_readable( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, asynchronous: bool, reader: str +) -> None: + """Read queued pipeline records from the live handle before result commit.""" + db = DeltaTableDatabase(tmp_path) + src = source(0) + + def build() -> PipelineJob: + job = PipelineJob(name=JOB, database=db) + with job: + double.pod(src, label="out") + return job + + job, reader_job = build(), build() + writer = node_of(job, "out") + reader_node = node_of(reader_job, "out") + path = (JOB, *writer.node_identity_path, PIPELINE) + original = DeltaTableDatabase.flush_batch + observed = False + + def flush_batch(view: DeltaTableDatabase, record_path: tuple[str, ...]) -> None: + nonlocal observed + if record_path[-1] == RESULT: + assert not read_tables(tmp_path, PIPELINE) + assert not read_tables(tmp_path, RESULT) + queued = db.get_all_records(path, record_id_column=ENTRY) + assert queued is not None and queued.num_rows == 4 + entry_id: bytes = queued[ENTRY][0].as_py() + base_entry: bytes = queued[BASE_ENTRY][0].as_py() + if reader == "point": + pending = db.get_record_by_id(path, entry_id, record_id_column=ENTRY) + assert pending is not None and pending[ENTRY].to_pylist() == [entry_id] + elif reader == "scan": + assert Counter(queued["tag"].to_pylist()) == Counter([0, 1, 2, 3]) + elif reader == "filtered": + pending = db.get_records_with_column_value( + path, {BASE_ENTRY: base_entry}, record_id_column=ENTRY + ) + assert pending is not None and pending[ENTRY].to_pylist() == [entry_id] + elif reader == "cache": + assert base_entry in reader_node.get_cached_results([base_entry]) + elif reader == "source": + assert Counter( + reader_node.as_source().as_table()["y"].to_pylist() + ) == Counter([0, 2, 4, 6]) + elif reader == "joined": + joined = reader_node.get_all_records() + assert joined is not None and joined.num_rows == 4 + else: + (upstream,) = writer.upstreams + tag, data = next( + (tag, data) + for tag, data in upstream.iter_data() + if writer.compute_base_entry_id(tag, data) == base_entry + ) + result_id = uuid.UUID(bytes=queued[constants.DATA_RECORD_ID][0].as_py()) + writer.add_pipeline_record(tag, data, result_id, computed=False) + found = db.get_records_with_column_value( + path, {BASE_ENTRY: base_entry}, record_id_column=ENTRY + ) + assert found is not None + assert Counter(found[RECOMPUTATION].to_pylist()) == Counter([0, 1]) + assert set(found[ENTRY].to_pylist()) == { + entry_id, + writer.compute_pipeline_entry_id(tag, data, 1), + } + observed = True + original(view, record_path) + + monkeypatch.setattr(DeltaTableDatabase, "flush_batch", flush_batch) + run(job, asynchronous, 10) + assert observed diff --git a/tests/test_pipeline/test_job_batched_commits.py b/tests/test_pipeline/test_job_batched_commits.py index 8f9c864cc..a9961e57f 100644 --- a/tests/test_pipeline/test_job_batched_commits.py +++ b/tests/test_pipeline/test_job_batched_commits.py @@ -199,6 +199,12 @@ def flush_batch(self, record_path: tuple[str, ...]) -> None: """Commit one table's pending writes, unless commits fail by now.""" self._commit(lambda: self._inner.flush_batch(record_path)) + def flush_result_batch( + self, record_path: tuple[str, ...], *, publish_records: bool + ) -> None: + """Count the result-table commit through the same faulty write path.""" + self.flush_batch(record_path) + def __getattr__(self, name: str) -> Any: """Delegate everything else.""" return getattr(self._inner, name) diff --git a/tests/test_pipeline/test_job_crash_recovery.py b/tests/test_pipeline/test_job_crash_recovery.py index f1fa10aef..66809d80f 100644 --- a/tests/test_pipeline/test_job_crash_recovery.py +++ b/tests/test_pipeline/test_job_crash_recovery.py @@ -34,9 +34,9 @@ # Runs one job over N_ROWS rows. Arguments: store path, calls file, commit_every_rows, # orchestrator ("sync" or "async"), crash ("none", "fn:" or "flush:"), late row # ("none" or a row number). "fn:" exits while computing row x, once the batches of the -# rows before x are committed; "flush:" exits on the n-th store-wide flush. The run's -# first flush commits what was pending before it; each later one is a node's commit, -# called right after the node committed its result table. +# rows before x are committed; "flush:" exits at the n-th pipeline commit. +# The first commit flushes writes pending before the run. Later commits flush the +# node's pipeline table after the result table. # # The async orchestrator computes rows on a thread pool ahead of the stage that records # them and commits every commit_every_rows rows, so without a wait row x could be @@ -66,6 +66,7 @@ from orcapod.databases import DeltaTableDatabase from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.sources import DictSource + from orcapod.system_constants import PIPELINE_DB_SCHEMA_VERSION database_path, calls_path, every, orchestrator, crash, late = sys.argv[1:7] crash_kind, _, crash_arg = crash.partition(":") @@ -99,14 +100,23 @@ def __init__(self, inner: Any, state: dict[str, int]) -> None: def at(self, *path: str) -> "CrashOnFlush": return CrashOnFlush(self._inner.at(*path), self._state) - def flush(self) -> None: + def _commit(self, flush) -> None: self._state["n"] += 1 if crash_kind == "flush" and self._state["n"] == int(crash_arg): os._exit(3) - self._inner.flush() + flush() if crash_kind == "fn" and self._state["n"] >= flushes_before_crash: earlier_batches_committed.set() + def flush(self) -> None: + self._commit(self._inner.flush) + + def flush_batch(self, path: tuple[str, ...]) -> None: + if path[-1] == PIPELINE_DB_SCHEMA_VERSION: + self._commit(lambda: self._inner.flush_batch(path)) + else: + self._inner.flush_batch(path) + def __getattr__(self, name: str) -> Any: return getattr(self._inner, name) diff --git a/tests/test_pipeline/test_mixed_function_commits.py b/tests/test_pipeline/test_mixed_function_commits.py new file mode 100644 index 000000000..03182fff7 --- /dev/null +++ b/tests/test_pipeline/test_mixed_function_commits.py @@ -0,0 +1,522 @@ +"""Function batches keep their commit cadence across database kinds.""" + +from __future__ import annotations + +import asyncio +from collections import defaultdict +from contextlib import AbstractContextManager +from pathlib import Path +from typing import Any, Literal, Self, TypedDict, cast + +import deltalake +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + ExtensionAwareDatabase, + InMemoryArrowDatabase, + NoOpArrowDatabase, +) +from orcapod.databases._pending_commits import PendingCommit +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.sources import DictSource +from orcapod.system_constants import ( + PIPELINE_DB_SCHEMA_VERSION, + RESULT_DB_SCHEMA_VERSION, +) +from tests.test_databases.test_connector_arrow_database import MockDBConnector + +Layout = Literal["memory", "delta", "noop", "connector"] +PIPELINE = PIPELINE_DB_SCHEMA_VERSION +RESULT = RESULT_DB_SCHEMA_VERSION + + +@function_pod(output_keys="y") +async def double(x: int, offset: int) -> int: + """Return a stable result with two bound input fields.""" + return 2 * x + offset + + +class CommitConnector(MockDBConnector): + """Store function tables as Arrow and count physical connector upserts.""" + + def __init__(self) -> None: + """Start with no tables or writes.""" + super().__init__() + self.upserts: dict[str, list[int]] = defaultdict(list) + + def upsert_records( + self, + table_name: str, + records: pa.Table, + id_column: str, + skip_existing: bool = False, + ) -> None: + """Record each real upsert's table and row count.""" + super().upsert_records(table_name, records, id_column, skip_existing) + self.upserts[table_name].append(records.num_rows) + + +def make_job( + pipeline: ArrowDatabaseProtocol, + results: ArrowDatabaseProtocol | None = None, + *, + reverse_order: bool = False, +) -> PipelineJob: + """Build a batch over five rows, with optionally separate result storage.""" + job = PipelineJob(name="mixed", database=pipeline) + rows = [{"tag": i, "group": "all", "x": i, "offset": i + 10} for i in range(5)] + tags = ["tag", "group"] + if reverse_order: + rows = [dict(reversed(tuple(row.items()))) for row in rows] + tags.reverse() + with job: + _ = double.pod( + DictSource( + data=rows, tag_columns=tags, tag_only_columns=True, source_id="src" + ), + label="out", + ) + if results is not None: + job.nodes["out"].attach_databases( + pipeline_database=pipeline.at("mixed"), result_database=results + ) + return job + + +class RunOptions(TypedDict, total=False): + """The cadence option, omitted when exercising the default.""" + + commit_every_rows: int + + +def run(job: PipelineJob, asynchronous: bool, every: int | None) -> None: + """Exercise either public entry point and omit the option for the default.""" + options: RunOptions = {} if every is None else {"commit_every_rows": every} + if asynchronous: + _ = asyncio.run(job.run_async(**options)) + else: + _ = job.run(**options) + + +def delta_history(root: Path, kind: str) -> list[tuple[str, int]]: + """Read the operation and number of rows added by each Delta commit.""" + (path,) = root.rglob(f"{kind}/_delta_log") + counts = deltalake.DeltaTable(str(path.parent)).history() + return [ + (item["operation"], int(item["operationMetrics"]["num_added_rows"])) + for item in reversed(counts) + ] + + +@pytest.mark.parametrize("pipeline_kind", ["memory", "delta", "noop", "connector"]) +@pytest.mark.parametrize("result_kind", ["memory", "delta"]) +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("every", [1, 3, None], ids=["one", "three", "default"]) +def test_mixed_database_batches_keep_main_cadence( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + pipeline_kind: Layout, + result_kind: Layout, + asynchronous: bool, + every: int | None, +) -> None: + """Keep pipeline writes and whole-store flushes at the measured main cadence.""" + connector = CommitConnector() + pipeline_root = tmp_path / "pipeline" + result_root = tmp_path / "result" + pipeline = { + "connector": ConnectorArrowDatabase(connector), + "delta": DeltaTableDatabase(pipeline_root), + "memory": InMemoryArrowDatabase(), + "noop": NoOpArrowDatabase(), + }[pipeline_kind] + results = ( + DeltaTableDatabase(result_root) + if result_kind == "delta" + else InMemoryArrowDatabase() + ) + whole_flushes: dict[type, int] = defaultdict(int) + promotions: dict[str, list[int]] = defaultdict(list) + flush_memory = InMemoryArrowDatabase.flush + flush_noop = NoOpArrowDatabase.flush + promote = getattr(InMemoryArrowDatabase, "flush_pending_table", None) + + def heap_rows(db: InMemoryArrowDatabase) -> dict[str, int]: + tables = db._tables # pyright: ignore[reportPrivateUsage] # distinguish promoted and pending rows + return {key: table.num_rows for key, table in tables.items()} + + def record_promotions(db: InMemoryArrowDatabase, before: dict[str, int]) -> None: + for key, after in heap_rows(db).items(): + inserted = after - before.get(key, 0) + if inserted: + promotions[key.split("/")[-1]].append(inserted) + + def observe_memory(db: InMemoryArrowDatabase) -> None: + whole_flushes[InMemoryArrowDatabase] += 1 + before = heap_rows(db) + flush_memory(db) + record_promotions(db, before) + + def observe_noop(db: NoOpArrowDatabase) -> None: + whole_flushes[NoOpArrowDatabase] += 1 + flush_noop(db) + + def observe_promotion(db: InMemoryArrowDatabase, path: tuple[str, ...]) -> None: + assert promote is not None + before = heap_rows(db) + promote(db, path) + record_promotions(db, before) + + monkeypatch.setattr(InMemoryArrowDatabase, "flush", observe_memory) + monkeypatch.setattr(NoOpArrowDatabase, "flush", observe_noop) + if promote is not None: + monkeypatch.setattr( + InMemoryArrowDatabase, "flush_pending_table", observe_promotion + ) + job = make_job(pipeline, results, reverse_order=asynchronous) + run(job, asynchronous, every) + pipeline_batches = {1: [1, 1, 1, 1, 1], 3: [3, 2], None: [5]}[every] + result_batches = [5] if asynchronous else pipeline_batches + # Main flushes once per full batch, once at node end and twice at job end + # for in-memory and no-op pipeline stores, even when the last batch is empty. + expected_whole = 3 + (5 // every if every is not None else 0) + if pipeline_kind == "memory": + assert whole_flushes[InMemoryArrowDatabase] == expected_whole + assert promotions[PIPELINE] == pipeline_batches + elif pipeline_kind == "noop": + assert whole_flushes[NoOpArrowDatabase] == expected_whole + assert not pipeline.list_table_paths() + elif pipeline_kind == "connector": + assert list(connector.upserts.values()) == [pipeline_batches] + else: + assert delta_history(pipeline_root, PIPELINE) == [ + ("WRITE", rows) for rows in pipeline_batches + ] + if result_kind == "delta": + assert delta_history(result_root, RESULT) == [ + ("WRITE", rows) for rows in result_batches + ] + elif pipeline_kind == "noop": + assert not promotions[RESULT], ( + "main leaves separate in-memory results pending in a dry run" + ) + else: + # The one promotion exception: main left these rows pending, even after + # publishing their references. The fix promotes them at the batch boundary. + assert promotions[RESULT] == result_batches + assert job.nodes["out"].as_table().num_rows == 5 + if pipeline_kind != "noop": + assert job.nodes["out"].as_source().as_table().num_rows == 5 + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +def test_shared_in_memory_store_keeps_whole_flush_count( + asynchronous: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + """A default all-in-memory job has one whole flush per batch as on main.""" + store = InMemoryArrowDatabase() + original = InMemoryArrowDatabase.flush + count = 0 + + def observe(db: InMemoryArrowDatabase) -> None: + nonlocal count + count += 1 + original(db) + + monkeypatch.setattr(InMemoryArrowDatabase, "flush", observe) + run(make_job(store), asynchronous, 3) + assert count == 4 + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +def test_noop_result_store_keeps_pipeline_records( + tmp_path: Path, asynchronous: bool +) -> None: + """A declared discard keeps main's pipeline bookkeeping and current rows.""" + db = DeltaTableDatabase(tmp_path) + results = NoOpArrowDatabase() + job = make_job(db, results) + run(job, asynchronous, 3) + assert delta_history(tmp_path, PIPELINE) == [("WRITE", 3), ("WRITE", 2)] + assert not results.list_table_paths() + assert job.nodes["out"].as_table().num_rows == 5 + assert job.nodes["out"].as_source().as_table().num_rows == 0 + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +def test_promoting_memory_results_preserves_public_read_views( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, asynchronous: bool +) -> None: + """Pending and promoted result rows are identical through all row readers.""" + memory = InMemoryArrowDatabase() + original = getattr(InMemoryArrowDatabase, "flush_pending_table", None) + observed: list[int] = [] + + def promote(db: InMemoryArrowDatabase, path: tuple[str, ...]) -> None: + def read() -> list[pa.Table | None]: + record_id_name = "rid" + rows = db.get_all_records(path, record_id_column=record_id_name) + assert rows is not None + ids = cast(list[bytes], rows[record_id_name].to_pylist()) + return [ + rows.combine_chunks(), + db.get_record_by_id(path, ids[0], record_id_column=record_id_name), + db.get_records_by_ids(path, ids, record_id_column=record_id_name), + db.get_records_with_column_value( + path, {"y": 10}, record_id_column=record_id_name + ), + ] + + before = read() + assert original is not None + original(db, path) + assert before == read() + full = before[0] + assert full is not None + observed.append(full.num_rows) + + if original is not None: + monkeypatch.setattr(InMemoryArrowDatabase, "flush_pending_table", promote) + job = make_job(DeltaTableDatabase(tmp_path), memory) + run(job, asynchronous, 3) + assert observed == ([5, 5] if asynchronous else [3, 5]) + joined = job.nodes["out"].get_all_records() + assert joined is not None and joined.num_rows == 5 + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +def test_connector_job_keeps_only_ready_records_on_result_failure( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, asynchronous: bool +) -> None: + """A connector can publish independently queued work while a result is pending.""" + from orcapod.errors import OrcapodDatabaseWriteError + + connector = CommitConnector() + pipeline = ConnectorArrowDatabase(connector) + results = DeltaTableDatabase(tmp_path) + job = make_job(pipeline, results) + original_flush = DeltaTableDatabase.flush_batch + original_write = deltalake.write_deltalake + checked = False + + def flush_result(db: DeltaTableDatabase, path: tuple[str, ...]) -> None: + nonlocal checked + if path[-1] == RESULT: + independent = ("independent",) + pipeline.add_record( + independent, b"ok", pa.table({"value": [1]}), skip_duplicates=True + ) + pipeline.flush() + fresh = ConnectorArrowDatabase(connector) + assert fresh.list_table_paths() == [independent] + checked = True + original_flush(db, path) + + def fail_result(table_or_uri, *args, **kwargs): + uri = ( + table_or_uri.table_uri + if isinstance(table_or_uri, deltalake.DeltaTable) + else table_or_uri + ) + if Path(uri).name == RESULT: + raise OSError("result store unavailable") + original_write(table_or_uri, *args, **kwargs) + + monkeypatch.setattr(DeltaTableDatabase, "flush_batch", flush_result) + monkeypatch.setattr(deltalake, "write_deltalake", fail_result) + with pytest.raises(OrcapodDatabaseWriteError) as raised: + run(job, asynchronous, 3) + assert isinstance(raised.value.__cause__, OSError) + assert checked + pipeline.flush() + assert pipeline.list_table_paths() == [("independent",)] + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +def test_result_commit_error_names_the_actual_store_and_table( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, asynchronous: bool +) -> None: + """Check error identity independently of whether pipeline records were written.""" + from orcapod.errors import OrcapodDatabaseWriteError + + pipeline = DeltaTableDatabase(tmp_path / "pipeline") + results = DeltaTableDatabase(tmp_path / "results").at("external") + job = make_job(pipeline, results) + attempted: list[Path] = [] + + def fail_write(table_or_uri, *args, **kwargs): + attempted.append(Path(table_or_uri)) + raise OSError("injected result failure") + + monkeypatch.setattr(deltalake, "write_deltalake", fail_write) + with pytest.raises(OrcapodDatabaseWriteError) as raised: + run(job, asynchronous, 3) + assert attempted and attempted[0].name == RESULT + assert str(attempted[0]) in str(raised.value) + assert isinstance(raised.value.__cause__, OSError) + + +def test_connector_result_failure_withdraws_its_pipeline_records( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A failed connector upsert withdraws the pending Delta references.""" + from orcapod.errors import OrcapodDatabaseWriteError + + pipeline = DeltaTableDatabase(tmp_path) + connector = CommitConnector() + results = ConnectorArrowDatabase(connector) + job = make_job(pipeline, results) + + def fail_result(*args: object, **kwargs: object) -> None: + raise OSError("connector result write failed") + + monkeypatch.setattr(connector, "upsert_records", fail_result) + with pytest.raises(OrcapodDatabaseWriteError) as raised: + run(job, asynchronous=False, every=3) + assert isinstance(raised.value.__cause__, OSError) + assert RESULT in str(raised.value) + pipeline.flush() + assert not pipeline.list_table_paths() + + +class DatabaseWithoutCommitGuards: + """Stand-in for the database interface without the required commit methods.""" + + def __init__(self, inner: InMemoryArrowDatabase) -> None: + self._inner = inner + + def add_record(self, *args: Any, **kwargs: Any) -> None: + self._inner.add_record(*args, **kwargs) + + def add_records(self, *args: Any, **kwargs: Any) -> None: + self._inner.add_records(*args, **kwargs) + + def get_record_by_id(self, *args: Any, **kwargs: Any) -> pa.Table | None: + return self._inner.get_record_by_id(*args, **kwargs) + + def get_all_records(self, *args: Any, **kwargs: Any) -> pa.Table | None: + return self._inner.get_all_records(*args, **kwargs) + + def get_records_by_ids(self, *args: Any, **kwargs: Any) -> pa.Table | None: + return self._inner.get_records_by_ids(*args, **kwargs) + + def get_records_with_column_value( + self, *args: Any, **kwargs: Any + ) -> pa.Table | None: + return self._inner.get_records_with_column_value(*args, **kwargs) + + def flush(self) -> None: + self._inner.flush() + + @property + def base_path(self) -> tuple[str, ...]: + return self._inner.base_path + + def at(self, *path_components: str) -> Self: + return type(self)(self._inner.at(*path_components)) + + def table_exists(self, record_path: tuple[str, ...]) -> bool: + return self._inner.table_exists(record_path) + + def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...]]: + return self._inner.list_table_paths(prefix) + + def to_config(self) -> dict[str, Any]: + return self._inner.to_config() + + @classmethod + def from_config(cls, config: dict[str, Any]) -> Self: + return cls(InMemoryArrowDatabase.from_config(config)) + + +class ProtocolDatabase(DatabaseWithoutCommitGuards): + """Forward the complete protocol without exposing unrelated backend methods.""" + + @property + def stores_records(self) -> bool: + return self._inner.stores_records + + def pending_result( + self, record_path: tuple[str, ...], record_id: bytes + ) -> PendingCommit | None: + return self._inner.pending_result(record_path, record_id) + + def guard_record( + self, record_path: tuple[str, ...], record_id: bytes, dependency: PendingCommit + ) -> AbstractContextManager[None]: + return self._inner.guard_record(record_path, record_id, dependency) + + def fail_pending_result(self, record_path: tuple[str, ...]) -> None: + self._inner.fail_pending_result(record_path) + + def flush_result_batch( + self, record_path: tuple[str, ...], *, publish_records: bool + ) -> None: + self._inner.flush_result_batch(record_path, publish_records=publish_records) + + def flush_batch(self, record_path: tuple[str, ...]) -> None: + self._inner.flush_batch(record_path) + + +def test_library_databases_conform_to_the_commit_protocol(tmp_path: Path) -> None: + """Built-in stores conform, and an incomplete store fails the runtime check.""" + stores: list[ArrowDatabaseProtocol] = [ + InMemoryArrowDatabase(), + DeltaTableDatabase(tmp_path), + ConnectorArrowDatabase(CommitConnector()), + NoOpArrowDatabase(), + ExtensionAwareDatabase.from_config(InMemoryArrowDatabase().to_config()), + ] + assert all(isinstance(store, ArrowDatabaseProtocol) for store in stores) + assert not isinstance( + DatabaseWithoutCommitGuards(InMemoryArrowDatabase()), ArrowDatabaseProtocol + ) + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("placement", ["pipeline", "result", "both", "shared"]) +def test_complete_protocol_database_preserves_main_rows_and_flushes( + monkeypatch: pytest.MonkeyPatch, asynchronous: bool, placement: str +) -> None: + """The complete internal protocol is sufficient to run a job.""" + pipeline = InMemoryArrowDatabase().at("pipeline") + result = InMemoryArrowDatabase().at("result") + pipeline_store = ProtocolDatabase(pipeline) if placement != "result" else pipeline + result_store = ( + ProtocolDatabase(result) if placement in ("result", "both") else result + ) + assert isinstance(pipeline_store, ArrowDatabaseProtocol) + assert isinstance(result_store, ArrowDatabaseProtocol) + calls: list[tuple[str, ...]] = [] + original_flush = InMemoryArrowDatabase.flush + + def observe_flush(database: InMemoryArrowDatabase) -> None: + calls.append(database.base_path) + original_flush(database) + + monkeypatch.setattr(InMemoryArrowDatabase, "flush", observe_flush) + job = make_job( + pipeline_store, + None if placement == "shared" else result_store, + ) + run(job, asynchronous, every=2) + node = job.nodes["out"] + assert sorted(cast(list[int], node.as_table()["y"].to_pylist())) == [ + 10, + 13, + 16, + 19, + 22, + ] + assert sorted(cast(list[int], node.as_source().as_table()["y"].to_pylist())) == [ + 10, + 13, + 16, + 19, + 22, + ] + assert calls == [("pipeline", "mixed")] * 4 + [("pipeline", "mixed", "_result")] diff --git a/tests/test_pipeline/test_store_write_failure.py b/tests/test_pipeline/test_store_write_failure.py index 80dd12c98..28edd6ea8 100644 --- a/tests/test_pipeline/test_store_write_failure.py +++ b/tests/test_pipeline/test_store_write_failure.py @@ -127,6 +127,13 @@ def flush(self) -> None: self._inner.flush() faults.pending_paths.clear() + def flush_batch(self, record_path: tuple[str, ...]) -> None: + """Flush the in-memory batch through the same fault injection.""" + try: + self.flush() + except OSError as exc: + raise OrcapodDatabaseWriteError(self.base_path, flush=True) from exc + def __getattr__(self, name: str) -> Any: """Delegate everything else to the wrapped database.""" return getattr(self._inner, name)