From 479f1819ba9e96d3ea7155e05f9779c7487f9f38 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 19:58:19 -0800 Subject: [PATCH 1/5] fix(pipeline): publish function records after results commit --- changelog.d/ITL-1412.md | 6 + docs/dev/design_issues/ITL-1412-FC1.md | 25 ++ src/orcapod/core/nodes/function_node.py | 176 +++++---- src/orcapod/databases/_pending_commits.py | 140 +++++++ .../databases/connector_arrow_database.py | 77 +++- src/orcapod/databases/delta_lake_databases.py | 75 +++- .../databases/extension_aware_database.py | 34 ++ src/orcapod/databases/noop_database.py | 2 + src/orcapod/errors.py | 8 + src/orcapod/pipeline/job.py | 23 +- src/orcapod/utils/database_errors.py | 9 + .../test_function_commit_dependencies.py | 364 ++++++++++++++++++ .../test_pipeline/test_job_crash_recovery.py | 20 +- 13 files changed, 852 insertions(+), 107 deletions(-) create mode 100644 changelog.d/ITL-1412.md create mode 100644 docs/dev/design_issues/ITL-1412-FC1.md create mode 100644 src/orcapod/databases/_pending_commits.py create mode 100644 tests/test_pipeline/test_function_commit_dependencies.py diff --git a/changelog.d/ITL-1412.md b/changelog.d/ITL-1412.md new file mode 100644 index 000000000..3fb255b8e --- /dev/null +++ b/changelog.d/ITL-1412.md @@ -0,0 +1,6 @@ +### 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. 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..333253e98 --- /dev/null +++ b/docs/dev/design_issues/ITL-1412-FC1.md @@ -0,0 +1,25 @@ +## `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. 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. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 117eb50b9..a881ac04a 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -86,6 +86,7 @@ ) from orcapod.utils.database_errors import ( commit_best_effort, + database_write_path, keep_database_error, database_error_of, ) @@ -98,7 +99,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 +2325,114 @@ 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, + ) -> None: + """Flush one table and withdraw its dependent records if a result write fails.""" + flush_batch = getattr(database, "flush_batch", None) + try: + if flush_batch is None: + database.flush() + else: + flush_batch(path) + except BaseException as exc: + if result: + fail_pending_result = getattr(database, "fail_pending_result", None) + if fail_pending_result is not None: + fail_pending_result(path) + if not isinstance(exc, Exception) or isinstance( + exc, OrcapodDatabaseReadError + ): + raise + raise OrcapodDatabaseWriteError( + database_write_path(database, path if flush_batch is not None else ()), + node_label=self.label, + flush=True, + table_flush=flush_batch is not None, + ) 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: + 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 + ) + self._flush_node_table( + self._require_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 isinstance(pod, CachedFunctionPod): + result_database = pod.result_database + if not getattr(result_database, "stores_records", True): + return # A dry run has no stored results to reference. + if self._commit_every_rows is not None: try: - ephemeral.flush() - except OrcapodDatabaseReadError: + pending_result = getattr(result_database, "pending_result", None) + if pending_result is None: + # A database without dependency tracking must finish the + # result write before the pipeline record enters any queue. + self._flush_node_table( + result_database, pod.record_path, result=True + ) + if ( + result_database.get_record_by_id(pod.record_path, result_id) + is None + ): + raise ValueError( + "The result was missing after its database flushed." + ) + dependency = None + else: + dependency = pending_result(pod.record_path, result_id) + except OrcapodDatabaseError: raise except Exception as exc: raise OrcapodDatabaseWriteError( - ephemeral.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 - try: - self._commit_result_table() - pipeline_database.flush() - except OrcapodDatabaseReadError: - raise - except Exception as exc: - raise OrcapodDatabaseWriteError( - pipeline_database.base_path, node_label=self.label, 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: + guard_record = getattr(database, "guard_record", None) + if guard_record is not None: + with guard_record(path, record_id, dependency): + database.add_record( + path, record_id, record, skip_duplicates=True + ) + return + self._flush_node_table( + result_database, pod.record_path, result=True + ) + 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 +2450,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 +3245,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..a9f98bbee --- /dev/null +++ b/src/orcapod/databases/_pending_commits.py @@ -0,0 +1,140 @@ +"""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: + 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) + 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..bbd6b20b2 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, @@ -140,6 +142,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 +631,55 @@ 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_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 +726,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..f7514f3f0 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, @@ -1140,6 +1142,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 +1161,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 +2567,32 @@ 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_batch(self, record_path: tuple[str, ...]) -> None: """ Flush pending batch for a specific source path. @@ -2577,15 +2613,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 +2752,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 +3128,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..89fb2e955 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -29,7 +29,10 @@ 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 @@ -211,6 +214,37 @@ def flush_batch(self) -> Callable[[tuple[str, ...]], None]: """ return getattr(self._db, "flush_batch") # noqa: B009 # AttributeError when absent, by design + @property + def pending_result( + self, + ) -> Callable[[tuple[str, ...], bytes], PendingCommit | None]: + """The wrapped database's commit dependency lookup, if supported.""" + return getattr(self._db, "pending_result") # noqa: B009 # optional capability + + @property + def fail_pending_result(self) -> Callable[[tuple[str, ...]], None]: + """The wrapped database's failure registration, if supported.""" + return getattr(self._db, "fail_pending_result") # noqa: B009 # optional capability + + @property + def guard_record( + self, + ) -> Callable[ + [tuple[str, ...], bytes, PendingCommit], AbstractContextManager[None] + ]: + """The wrapped database's guarded enqueue operation, if supported.""" + return getattr(self._db, "guard_record") # noqa: B009 # optional capability + + @property + def stores_records(self) -> bool: + """Whether records are retained by the wrapped database.""" + return getattr(self._db, "stores_records", True) + + @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]: """The wrapped database's ``require_storable`` (ITL-1162). diff --git a/src/orcapod/databases/noop_database.py b/src/orcapod/databases/noop_database.py index 27c1bf9b6..ff0136b05 100644 --- a/src/orcapod/databases/noop_database.py +++ b/src/orcapod/databases/noop_database.py @@ -29,6 +29,8 @@ class NoOpArrowDatabase: node. """ + stores_records = False + def __init__( self, _path_prefix: tuple[str, ...] = (), 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/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_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_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) From e95b5a22bb9211d869f48772651e4aea9de78629 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 20:33:48 -0800 Subject: [PATCH 2/5] fix(pipeline): preserve mixed-store batch cadence --- changelog.d/ITL-1412.md | 3 +- docs/dev/design_issues/ITL-1412-FC1.md | 13 +- src/orcapod/core/nodes/function_node.py | 89 ++-- src/orcapod/databases/_pending_commits.py | 5 +- .../databases/extension_aware_database.py | 5 + src/orcapod/databases/in_memory_databases.py | 118 ++++-- .../test_mixed_function_commits.py | 380 ++++++++++++++++++ 7 files changed, 532 insertions(+), 81 deletions(-) create mode 100644 tests/test_pipeline/test_mixed_function_commits.py diff --git a/changelog.d/ITL-1412.md b/changelog.d/ITL-1412.md index 3fb255b8e..840c37153 100644 --- a/changelog.d/ITL-1412.md +++ b/changelog.d/ITL-1412.md @@ -3,4 +3,5 @@ - 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. + the store and table. A configured no-op result database still records the processed + inputs in the pipeline store and explicitly discards its outputs. diff --git a/docs/dev/design_issues/ITL-1412-FC1.md b/docs/dev/design_issues/ITL-1412-FC1.md index 333253e98..b9d5b50de 100644 --- a/docs/dev/design_issues/ITL-1412-FC1.md +++ b/docs/dev/design_issues/ITL-1412-FC1.md @@ -14,7 +14,8 @@ 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. A function node flushes the result and pipeline tables individually. +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. @@ -23,3 +24,13 @@ lookup. A flush checks just its queued dependencies and partitions the Arrow bat 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. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index a881ac04a..bb70cc85c 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -2334,6 +2334,8 @@ def _flush_node_table( ) -> None: """Flush one table and withdraw its dependent records if a result write fails.""" flush_batch = getattr(database, "flush_batch", None) + if result and flush_batch is None: + flush_batch = getattr(database, "flush_pending_table", None) try: if flush_batch is None: database.flush() @@ -2363,14 +2365,18 @@ def _commit_pending_writes(self) -> None: self._flush_node_table( ephemeral.result_database, ephemeral.record_path, result=True ) + pipeline_database = self._require_pipeline_database() pod = self._cached_function_pod if isinstance(pod, CachedFunctionPod): - self._flush_node_table( - pod.result_database, pod.record_path, result=True - ) - self._flush_node_table( - self._require_pipeline_database(), self._versioned_pipeline_path - ) + result_database = pod.result_database + if getattr(result_database, "stores_records", True) and ( + getattr(pipeline_database, "stores_records", True) + or getattr(result_database, "flush_batch", None) is not None + ): + self._flush_node_table( + result_database, pod.record_path, result=True + ) + self._flush_node_table(pipeline_database, self._versioned_pipeline_path) except BaseException as exc: self._commit_failed = True if isinstance(exc, OrcapodDatabaseError): @@ -2389,49 +2395,38 @@ def _write_pipeline_record( database = self._require_pipeline_database() path = self._versioned_pipeline_path pod = self._ephemeral_cached_pod if is_ephemeral else self._cached_function_pod - if isinstance(pod, CachedFunctionPod): + if ( + self._commit_every_rows is not None + and isinstance(pod, CachedFunctionPod) + and getattr(database, "stores_records", True) + and getattr(pod.result_database, "stores_records", True) + ): result_database = pod.result_database - if not getattr(result_database, "stores_records", True): - return # A dry run has no stored results to reference. - if self._commit_every_rows is not None: - try: - pending_result = getattr(result_database, "pending_result", None) - if pending_result is None: - # A database without dependency tracking must finish the - # result write before the pipeline record enters any queue. - self._flush_node_table( - result_database, pod.record_path, result=True - ) - if ( - result_database.get_record_by_id(pod.record_path, result_id) - is None - ): - raise ValueError( - "The result was missing after its database flushed." - ) - dependency = None - else: - dependency = pending_result(pod.record_path, result_id) - except OrcapodDatabaseError: - raise - except Exception as exc: - raise OrcapodDatabaseWriteError( - database_write_path(result_database, pod.record_path), - node_label=self.label, - flush=True, - table_flush=True, - ) from exc - if dependency is not None: - guard_record = getattr(database, "guard_record", None) - if guard_record is not None: - with guard_record(path, record_id, dependency): - database.add_record( - path, record_id, record, skip_duplicates=True - ) - return - self._flush_node_table( - result_database, pod.record_path, result=True + try: + pending_result = getattr(result_database, "pending_result", None) + if pending_result is None: + raise RuntimeError( + "The result store cannot track its pending results." + ) + dependency = pending_result(pod.record_path, result_id) + except OrcapodDatabaseError: + raise + except Exception as exc: + raise OrcapodDatabaseWriteError( + database_write_path(result_database, pod.record_path), + node_label=self.label, + flush=True, + table_flush=True, + ) from exc + if dependency is not None: + guard_record = getattr(database, "guard_record", None) + if guard_record is None: + raise RuntimeError( + "The pipeline store cannot guard a pending result." ) + with 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: diff --git a/src/orcapod/databases/_pending_commits.py b/src/orcapod/databases/_pending_commits.py index a9f98bbee..3c36bd4d2 100644 --- a/src/orcapod/databases/_pending_commits.py +++ b/src/orcapod/databases/_pending_commits.py @@ -43,7 +43,7 @@ def __init__( batches: dict[str, pa.Table], ids: dict[str, set[bytes]], *, - on_empty: Callable[[str], None], + on_empty: Callable[[str], None] | None = None, ) -> None: self._record_id_column = record_id_column self._batches = batches @@ -95,7 +95,8 @@ def discard(self, key: str, ids: set[bytes], attempt: PendingCommit) -> None: else: self._batches.pop(key) self._ids.pop(key) - self._on_empty(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.""" diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index 89fb2e955..6bf0636f6 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -214,6 +214,11 @@ def flush_batch(self) -> Callable[[tuple[str, ...]], None]: """ return getattr(self._db, "flush_batch") # noqa: B009 # AttributeError when absent, by design + @property + def flush_pending_table(self) -> Callable[[tuple[str, ...]], None]: + """The wrapped database's in-memory table promotion, if supported.""" + return getattr(self._db, "flush_pending_table") # noqa: B009 # optional capability + @property def pending_result( self, diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 3c78dd1e0..8fe664848 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -3,8 +3,10 @@ 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, @@ -73,6 +75,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 +335,85 @@ 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_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: + self._pending_commits.finish(record_key, committed=False) + self._pending_commits.restore(record_key, pending, ids) + raise + else: + self._pending_commits.forget(record_key, ids) + self._pending_commits.finish(record_key, committed=True) + + 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/tests/test_pipeline/test_mixed_function_commits.py b/tests/test_pipeline/test_mixed_function_commits.py new file mode 100644 index 000000000..194b5a0f3 --- /dev/null +++ b/tests/test_pipeline/test_mixed_function_commits.py @@ -0,0 +1,380 @@ +"""Function batches keep their commit cadence across database kinds.""" + +from __future__ import annotations + +import asyncio +from collections import defaultdict +from pathlib import Path +from typing import Literal, TypedDict, cast + +import deltalake +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + InMemoryArrowDatabase, + NoOpArrowDatabase, +) +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() From 18ed5f1cc73d16066f27c9725a302478899554fc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 20:44:01 -0800 Subject: [PATCH 3/5] fix(pipeline): keep commit guards optional for custom stores --- changelog.d/ITL-1412.md | 5 +- docs/concepts/pipeline-job.md | 18 +++ docs/dev/design_issues/ITL-1412-FC1.md | 9 ++ src/orcapod/core/nodes/function_node.py | 127 ++++++++++++------ src/orcapod/databases/__init__.py | 2 + src/orcapod/databases/noop_database.py | 12 ++ src/orcapod/databases/utils.py | 16 ++- src/orcapod/protocols/database_protocols.py | 25 ++++ .../test_mixed_function_commits.py | 99 +++++++++++++- 9 files changed, 267 insertions(+), 46 deletions(-) diff --git a/changelog.d/ITL-1412.md b/changelog.d/ITL-1412.md index 840c37153..e43422a26 100644 --- a/changelog.d/ITL-1412.md +++ b/changelog.d/ITL-1412.md @@ -1,7 +1,10 @@ ### Fixed -- Function pipeline records are published only after their referenced results commit. +- With databases that support commit guards, 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. + Databases that implement only the base database protocol keep their existing + write and flush behavior. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 625400b73..db08a1e79 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -129,6 +129,24 @@ 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 + +When both stores support result commit guards, a function node publishes its +pipeline records after the referenced results commit. Failed result batches +withdraw their pending pipeline records. `DeltaTableDatabase`, +`InMemoryArrowDatabase`, and `ConnectorArrowDatabase` support guards. +`ExtensionAwareDatabase` forwards them when its underlying store does. +`NoOpArrowDatabase` explicitly discards results and still allows pipeline +bookkeeping to be written. + +Custom databases can opt in through `ResultCommitGuardingDatabaseProtocol` +in `orcapod.protocols.database_protocols`. Its `pending_result` and +`guard_record` methods connect a queued result's commit to the pipeline +records that reference it. If either store implements only +`ArrowDatabaseProtocol`, the job keeps the original unguarded writes and +flush cadence. This fallback does not guarantee that a failed result write +withdraws its pipeline records. + ### 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 index b9d5b50de..568bfbdd9 100644 --- a/docs/dev/design_issues/ITL-1412-FC1.md +++ b/docs/dev/design_issues/ITL-1412-FC1.md @@ -34,3 +34,12 @@ 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 result-first guarantee applies when both stores offer the optional +`ResultCommitGuardingDatabaseProtocol`. It defines `pending_result`, which returns +the result's commit token, and `guard_record`, which binds a queued pipeline record +to that token. `DeltaTableDatabase`, `InMemoryArrowDatabase` and +`ConnectorArrowDatabase` support it, and `ExtensionAwareDatabase` forwards it +when its underlying database does. `NoOpArrowDatabase` participates as the +explicit discard described above. A database implementing only +`ArrowDatabaseProtocol` still uses the original unguarded writes and flush cadence. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index bb70cc85c..a9df974c1 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -99,6 +99,7 @@ TagProtocol, TrackerManagerProtocol, ) +from orcapod.databases.utils import as_result_commit_guarding, as_table_committing from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.observability_protocols import ( DataExecutionLoggerProtocol, @@ -2331,10 +2332,11 @@ def _flush_node_table( path: tuple[str, ...], *, result: bool = False, + whole: bool = False, ) -> None: """Flush one table and withdraw its dependent records if a result write fails.""" - flush_batch = getattr(database, "flush_batch", None) - if result and flush_batch is None: + flush_batch = None if whole else getattr(database, "flush_batch", None) + if result and not whole and flush_batch is None: flush_batch = getattr(database, "flush_pending_table", None) try: if flush_batch is None: @@ -2357,26 +2359,48 @@ def _flush_node_table( table_flush=flush_batch is not None, ) from exc + def _guarded_commits(self, pipeline_database: ArrowDatabaseProtocol) -> bool: + """Check the optional capability on the pipeline and active result stores.""" + pod = ( + self._ephemeral_cached_pod + if self._node_config.is_result_ephemeral + else self._cached_function_pod + ) + return ( + isinstance(pod, CachedFunctionPod) + and as_result_commit_guarding(pipeline_database) is not None + and as_result_commit_guarding(pod.result_database) is not None + ) + + def _commit_legacy_ephemeral(self) -> None: + """Keep the whole ephemeral-store flush used without commit guards.""" + pod = self._ephemeral_cached_pod + if self._node_config.is_result_ephemeral and pod is not None: + self._flush_node_table( + pod.result_database, pod.record_path, result=True, whole=True + ) + + def _commit_legacy_result(self) -> None: + """Keep the old result-table flush for stores that commit table by table.""" + pod = self._cached_function_pod + if ( + isinstance(pod, CachedFunctionPod) + and as_table_committing(pod.result_database) is not None + ): + self._flush_node_table(pod.result_database, pod.record_path, result=True) + def _commit_pending_writes(self) -> None: """Commit results before publishing any records that depend on them.""" try: - ephemeral = self._ephemeral_cached_pod - if self._node_config.is_result_ephemeral and ephemeral is not None: + pipeline_database = self._require_pipeline_database() + if not self._guarded_commits(pipeline_database): + self._commit_legacy_ephemeral() + self._commit_legacy_result() self._flush_node_table( - ephemeral.result_database, ephemeral.record_path, result=True + pipeline_database, self._versioned_pipeline_path, whole=True ) - pipeline_database = self._require_pipeline_database() - pod = self._cached_function_pod - if isinstance(pod, CachedFunctionPod): - result_database = pod.result_database - if getattr(result_database, "stores_records", True) and ( - getattr(pipeline_database, "stores_records", True) - or getattr(result_database, "flush_batch", None) is not None - ): - self._flush_node_table( - result_database, pod.record_path, result=True - ) - self._flush_node_table(pipeline_database, self._versioned_pipeline_path) + else: + self._commit_guarded_writes(pipeline_database) except BaseException as exc: self._commit_failed = True if isinstance(exc, OrcapodDatabaseError): @@ -2384,6 +2408,23 @@ def _commit_pending_writes(self) -> None: raise self._rows_since_commit = 0 + def _commit_guarded_writes(self, pipeline_database: ArrowDatabaseProtocol) -> None: + """Commit one node's guarded batches.""" + 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): + result_database = pod.result_database + if getattr(result_database, "stores_records", True) and ( + getattr(pipeline_database, "stores_records", True) + or getattr(result_database, "flush_batch", None) is not None + ): + self._flush_node_table(result_database, pod.record_path, result=True) + self._flush_node_table(pipeline_database, self._versioned_pipeline_path) + def _write_pipeline_record( self, record_id: bytes, @@ -2402,31 +2443,26 @@ def _write_pipeline_record( and getattr(pod.result_database, "stores_records", True) ): result_database = pod.result_database - try: - pending_result = getattr(result_database, "pending_result", None) - if pending_result is None: - raise RuntimeError( - "The result store cannot track its pending results." - ) - dependency = pending_result(pod.record_path, result_id) - except OrcapodDatabaseError: - raise - except Exception as exc: - raise OrcapodDatabaseWriteError( - database_write_path(result_database, pod.record_path), - node_label=self.label, - flush=True, - table_flush=True, - ) from exc - if dependency is not None: - guard_record = getattr(database, "guard_record", None) - if guard_record is None: - raise RuntimeError( - "The pipeline store cannot guard a pending result." - ) - with guard_record(path, record_id, dependency): - database.add_record(path, record_id, record, skip_duplicates=True) - return + pipeline_guard = as_result_commit_guarding(database) + result_guard = as_result_commit_guarding(result_database) + if pipeline_guard is not None and result_guard is not None: + try: + dependency = result_guard.pending_result(pod.record_path, result_id) + except OrcapodDatabaseError: + raise + except Exception as exc: + raise OrcapodDatabaseWriteError( + database_write_path(result_database, pod.record_path), + node_label=self.label, + flush=True, + table_flush=True, + ) from exc + if dependency is not None: + with pipeline_guard.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: @@ -2454,7 +2490,12 @@ def _commit_after_failure(self, run_error: BaseException) -> None: """ if self._commit_every_rows is None or self._commit_failed: return - commit_best_effort(run_error, self._commit_pending_writes) + database = self._pipeline_database + if database is not None and self._guarded_commits(database): + commit_best_effort(run_error, self._commit_pending_writes) + else: + commit_best_effort(run_error, self._commit_legacy_ephemeral) + commit_best_effort(run_error, self._commit_legacy_result) @staticmethod def _commit_or_end_node( diff --git a/src/orcapod/databases/__init__.py b/src/orcapod/databases/__init__.py index be4c9dd7b..16eae1fd4 100644 --- a/src/orcapod/databases/__init__.py +++ b/src/orcapod/databases/__init__.py @@ -1,3 +1,4 @@ +from ._pending_commits import PendingCommit from .connector_arrow_database import ConnectorArrowDatabase from .delta_lake_databases import DeltaTableDatabase from .extension_aware_database import ExtensionAwareDatabase @@ -14,6 +15,7 @@ "ExtensionAwareDatabase", "InMemoryArrowDatabase", "NoOpArrowDatabase", + "PendingCommit", "SpiralDBConnector", "SQLiteConnector", "PostgreSQLConnector", diff --git a/src/orcapod/databases/noop_database.py b/src/orcapod/databases/noop_database.py index ff0136b05..1419c9965 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") @@ -103,6 +105,16 @@ def keeps_field_metadata(self) -> bool: def flush(self) -> None: pass + 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/databases/utils.py b/src/orcapod/databases/utils.py index 17018eb43..88ef79958 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -12,7 +12,10 @@ if TYPE_CHECKING: import pyarrow as pa - from orcapod.protocols.database_protocols import TableCommittingDatabaseProtocol + from orcapod.protocols.database_protocols import ( + ResultCommitGuardingDatabaseProtocol, + TableCommittingDatabaseProtocol, + ) else: pa = LazyModule("pyarrow") @@ -64,6 +67,17 @@ def as_table_committing(database: object) -> TableCommittingDatabaseProtocol | N return cast("TableCommittingDatabaseProtocol", database) +def as_result_commit_guarding( + database: object, +) -> ResultCommitGuardingDatabaseProtocol | None: + """Resolve the optional guard methods, including on database wrappers.""" + if callable(getattr(database, "pending_result", None)) and callable( + getattr(database, "guard_record", None) + ): + return cast("ResultCommitGuardingDatabaseProtocol", database) + return None + + _IDENTIFIER = r'(?:"[^"]+"|\w+)' _DIRECT_PROJECTION = re.compile( rf"^\s*SELECT\s+(?:\*|{_IDENTIFIER}(?:\s*,\s*{_IDENTIFIER})*)\s+" diff --git a/src/orcapod/protocols/database_protocols.py b/src/orcapod/protocols/database_protocols.py index fa1bbafd5..138f27bc2 100644 --- a/src/orcapod/protocols/database_protocols.py +++ b/src/orcapod/protocols/database_protocols.py @@ -1,12 +1,14 @@ 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 @@ -206,6 +208,29 @@ class ArrowDatabaseWithMetadataProtocol( pass +@runtime_checkable +class ResultCommitGuardingDatabaseProtocol(Protocol): + """Optional support for publishing pipeline records after their results commit. + + A result store returns a pending commit token for a buffered result and resolves + it when the write succeeds or fails. A pipeline store keeps a guarded record + readable in its queue until the token permits publication, and withdraws it if + the result write fails. The node uses this capability when both stores offer it. + """ + + def pending_result( + self, record_path: tuple[str, ...], record_id: bytes + ) -> PendingCommit | None: + """Return the result's pending commit, or None if it is already available.""" + ... + + def guard_record( + self, record_path: tuple[str, ...], record_id: bytes, dependency: PendingCommit + ) -> AbstractContextManager[None]: + """Guard a record by its result's commit while the caller queues the record.""" + ... + + class TableCommittingDatabaseProtocol(Protocol): """A database that commits table by table (ITL-919). diff --git a/tests/test_pipeline/test_mixed_function_commits.py b/tests/test_pipeline/test_mixed_function_commits.py index 194b5a0f3..e43be6060 100644 --- a/tests/test_pipeline/test_mixed_function_commits.py +++ b/tests/test_pipeline/test_mixed_function_commits.py @@ -5,7 +5,7 @@ import asyncio from collections import defaultdict from pathlib import Path -from typing import Literal, TypedDict, cast +from typing import Any, Literal, TypedDict, cast import deltalake import pyarrow as pa @@ -378,3 +378,100 @@ def fail_result(*args: object, **kwargs: object) -> None: assert RESULT in str(raised.value) pipeline.flush() assert not pipeline.list_table_paths() + + +class ProtocolOnlyDatabase: + """Delegate only the database API, without exposing commit extensions.""" + + 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) -> ProtocolOnlyDatabase: + return ProtocolOnlyDatabase(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]) -> ProtocolOnlyDatabase: + return cls(InMemoryArrowDatabase.from_config(config)) + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("placement", ["pipeline", "result", "both", "shared"]) +def test_protocol_only_database_preserves_main_rows_and_flushes( + monkeypatch: pytest.MonkeyPatch, asynchronous: bool, placement: str +) -> None: + """A user database can run jobs with just the original database methods.""" + pipeline = InMemoryArrowDatabase().at("pipeline") + result = InMemoryArrowDatabase().at("result") + pipeline_store = ( + ProtocolOnlyDatabase(pipeline) if placement != "result" else pipeline + ) + result_store = ( + ProtocolOnlyDatabase(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")] From ba711045240a37862e2021ebe7518bafffa5e608 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 20:56:13 -0800 Subject: [PATCH 4/5] fix(pipeline): require guarded database commits --- changelog.d/ITL-1412.md | 11 +- docs/concepts/pipeline-job.md | 15 +- docs/dev/design_issues/ITL-1412-FC1.md | 15 +- src/orcapod/core/nodes/function_node.py | 141 +++++------------- src/orcapod/databases/__init__.py | 2 - .../databases/connector_arrow_database.py | 8 + src/orcapod/databases/delta_lake_databases.py | 8 + .../databases/extension_aware_database.py | 65 ++++---- src/orcapod/databases/in_memory_databases.py | 24 ++- src/orcapod/databases/noop_database.py | 12 ++ src/orcapod/databases/utils.py | 16 +- src/orcapod/protocols/database_protocols.py | 70 ++++++--- .../test_pipeline/test_job_batched_commits.py | 6 + .../test_mixed_function_commits.py | 69 +++++++-- .../test_pipeline/test_store_write_failure.py | 7 + 15 files changed, 257 insertions(+), 212 deletions(-) diff --git a/changelog.d/ITL-1412.md b/changelog.d/ITL-1412.md index e43422a26..f7642898a 100644 --- a/changelog.d/ITL-1412.md +++ b/changelog.d/ITL-1412.md @@ -1,10 +1,13 @@ ### Fixed -- With databases that support commit guards, function pipeline records are published - only after their referenced results commit. +- 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. - Databases that implement only the base database protocol keep their existing - write and flush behavior. + +### 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 db08a1e79..50159ae81 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -131,22 +131,11 @@ A job created without a database can be recorded but not run. Give it one later ### Result commit ordering -When both stores support result commit guards, a function node publishes its -pipeline records after the referenced results commit. Failed result batches -withdraw their pending pipeline records. `DeltaTableDatabase`, -`InMemoryArrowDatabase`, and `ConnectorArrowDatabase` support guards. -`ExtensionAwareDatabase` forwards them when its underlying store does. +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. -Custom databases can opt in through `ResultCommitGuardingDatabaseProtocol` -in `orcapod.protocols.database_protocols`. Its `pending_result` and -`guard_record` methods connect a queued result's commit to the pipeline -records that reference it. If either store implements only -`ArrowDatabaseProtocol`, the job keeps the original unguarded writes and -flush cadence. This fallback does not guarantee that a failed result write -withdraws its pipeline records. - ### 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 index 568bfbdd9..48510c048 100644 --- a/docs/dev/design_issues/ITL-1412-FC1.md +++ b/docs/dev/design_issues/ITL-1412-FC1.md @@ -35,11 +35,10 @@ A no-op result database is an explicit discard. Its function nodes still write t pipeline records for processed inputs, as before. Those records refer to output that was never stored. -The result-first guarantee applies when both stores offer the optional -`ResultCommitGuardingDatabaseProtocol`. It defines `pending_result`, which returns -the result's commit token, and `guard_record`, which binds a queued pipeline record -to that token. `DeltaTableDatabase`, `InMemoryArrowDatabase` and -`ConnectorArrowDatabase` support it, and `ExtensionAwareDatabase` forwards it -when its underlying database does. `NoOpArrowDatabase` participates as the -explicit discard described above. A database implementing only -`ArrowDatabaseProtocol` still uses the original unguarded writes and flush cadence. +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 a9df974c1..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, ) @@ -99,7 +98,6 @@ TagProtocol, TrackerManagerProtocol, ) -from orcapod.databases.utils import as_result_commit_guarding, as_table_committing from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.protocols.observability_protocols import ( DataExecutionLoggerProtocol, @@ -2332,75 +2330,44 @@ def _flush_node_table( path: tuple[str, ...], *, result: bool = False, - whole: bool = False, + publish_records: bool = True, ) -> None: - """Flush one table and withdraw its dependent records if a result write fails.""" - flush_batch = None if whole else getattr(database, "flush_batch", None) - if result and not whole and flush_batch is None: - flush_batch = getattr(database, "flush_pending_table", None) + """Flush one batch and withdraw dependent records if a result write fails.""" try: - if flush_batch is None: - database.flush() + if result: + database.flush_result_batch(path, publish_records=publish_records) else: - flush_batch(path) + database.flush_batch(path) except BaseException as exc: if result: - fail_pending_result = getattr(database, "fail_pending_result", None) - if fail_pending_result is not None: - fail_pending_result(path) - if not isinstance(exc, Exception) or isinstance( - exc, OrcapodDatabaseReadError - ): + database.fail_pending_result(path) + if not isinstance(exc, Exception) or isinstance(exc, OrcapodDatabaseError): raise raise OrcapodDatabaseWriteError( - database_write_path(database, path if flush_batch is not None else ()), + database_write_path(database, path), node_label=self.label, flush=True, - table_flush=flush_batch is not None, + table_flush=True, ) from exc - def _guarded_commits(self, pipeline_database: ArrowDatabaseProtocol) -> bool: - """Check the optional capability on the pipeline and active result stores.""" - pod = ( - self._ephemeral_cached_pod - if self._node_config.is_result_ephemeral - else self._cached_function_pod - ) - return ( - isinstance(pod, CachedFunctionPod) - and as_result_commit_guarding(pipeline_database) is not None - and as_result_commit_guarding(pod.result_database) is not None - ) - - def _commit_legacy_ephemeral(self) -> None: - """Keep the whole ephemeral-store flush used without commit guards.""" - pod = self._ephemeral_cached_pod - if self._node_config.is_result_ephemeral and pod is not None: - self._flush_node_table( - pod.result_database, pod.record_path, result=True, whole=True - ) - - def _commit_legacy_result(self) -> None: - """Keep the old result-table flush for stores that commit table by table.""" - pod = self._cached_function_pod - if ( - isinstance(pod, CachedFunctionPod) - and as_table_committing(pod.result_database) is not None - ): - self._flush_node_table(pod.result_database, pod.record_path, result=True) - def _commit_pending_writes(self) -> None: """Commit results before publishing any records that depend on them.""" try: pipeline_database = self._require_pipeline_database() - if not self._guarded_commits(pipeline_database): - self._commit_legacy_ephemeral() - self._commit_legacy_result() + ephemeral = self._ephemeral_cached_pod + if self._node_config.is_result_ephemeral and ephemeral is not None: self._flush_node_table( - pipeline_database, self._versioned_pipeline_path, whole=True + ephemeral.result_database, ephemeral.record_path, result=True ) - else: - self._commit_guarded_writes(pipeline_database) + 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): @@ -2408,23 +2375,6 @@ def _commit_pending_writes(self) -> None: raise self._rows_since_commit = 0 - def _commit_guarded_writes(self, pipeline_database: ArrowDatabaseProtocol) -> None: - """Commit one node's guarded batches.""" - 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): - result_database = pod.result_database - if getattr(result_database, "stores_records", True) and ( - getattr(pipeline_database, "stores_records", True) - or getattr(result_database, "flush_batch", None) is not None - ): - self._flush_node_table(result_database, pod.record_path, result=True) - self._flush_node_table(pipeline_database, self._versioned_pipeline_path) - def _write_pipeline_record( self, record_id: bytes, @@ -2436,33 +2386,23 @@ def _write_pipeline_record( 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) - and getattr(database, "stores_records", True) - and getattr(pod.result_database, "stores_records", True) - ): + if self._commit_every_rows is not None and isinstance(pod, CachedFunctionPod): result_database = pod.result_database - pipeline_guard = as_result_commit_guarding(database) - result_guard = as_result_commit_guarding(result_database) - if pipeline_guard is not None and result_guard is not None: - try: - dependency = result_guard.pending_result(pod.record_path, result_id) - except OrcapodDatabaseError: - raise - except Exception as exc: - raise OrcapodDatabaseWriteError( - database_write_path(result_database, pod.record_path), - node_label=self.label, - flush=True, - table_flush=True, - ) from exc - if dependency is not None: - with pipeline_guard.guard_record(path, record_id, dependency): - database.add_record( - path, record_id, record, skip_duplicates=True - ) - return + try: + dependency = result_database.pending_result(pod.record_path, result_id) + except OrcapodDatabaseError: + raise + except Exception as exc: + raise OrcapodDatabaseWriteError( + database_write_path(result_database, pod.record_path), + node_label=self.label, + flush=True, + table_flush=True, + ) from exc + 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: @@ -2490,12 +2430,7 @@ def _commit_after_failure(self, run_error: BaseException) -> None: """ if self._commit_every_rows is None or self._commit_failed: return - database = self._pipeline_database - if database is not None and self._guarded_commits(database): - commit_best_effort(run_error, self._commit_pending_writes) - else: - commit_best_effort(run_error, self._commit_legacy_ephemeral) - commit_best_effort(run_error, self._commit_legacy_result) + commit_best_effort(run_error, self._commit_pending_writes) @staticmethod def _commit_or_end_node( diff --git a/src/orcapod/databases/__init__.py b/src/orcapod/databases/__init__.py index 16eae1fd4..be4c9dd7b 100644 --- a/src/orcapod/databases/__init__.py +++ b/src/orcapod/databases/__init__.py @@ -1,4 +1,3 @@ -from ._pending_commits import PendingCommit from .connector_arrow_database import ConnectorArrowDatabase from .delta_lake_databases import DeltaTableDatabase from .extension_aware_database import ExtensionAwareDatabase @@ -15,7 +14,6 @@ "ExtensionAwareDatabase", "InMemoryArrowDatabase", "NoOpArrowDatabase", - "PendingCommit", "SpiralDBConnector", "SQLiteConnector", "PostgreSQLConnector", diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index bbd6b20b2..5a3a0f5c7 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -103,6 +103,8 @@ class ConnectorArrowDatabase: Defaults to 10, matching ``InMemoryArrowDatabase``. """ + stores_records = True + RECORD_ID_COLUMN = "__record_id" _ROW_INDEX_COLUMN = "__row_index" @@ -662,6 +664,12 @@ def flush(self) -> None: 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)) diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index f7514f3f0..a6bd0f9e5 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -1072,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__( @@ -2593,6 +2595,12 @@ def guard_record( 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. diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index 6bf0636f6..74a4aa218 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -23,7 +23,7 @@ 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 @@ -205,45 +205,36 @@ def batch_size(self) -> int: """ return getattr(self._db, "batch_size") # noqa: B009 # AttributeError when absent, by design - @property - def flush_batch(self) -> Callable[[tuple[str, ...]], None]: - """The wrapped database's ``flush_batch`` (commits one table's writes). - - Raises: - AttributeError: If the wrapped database has none (see ``batch_size``). - """ - return getattr(self._db, "flush_batch") # 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) - @property - def flush_pending_table(self) -> Callable[[tuple[str, ...]], None]: - """The wrapped database's in-memory table promotion, if supported.""" - return getattr(self._db, "flush_pending_table") # noqa: B009 # optional capability + 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) - @property def pending_result( - self, - ) -> Callable[[tuple[str, ...], bytes], PendingCommit | None]: - """The wrapped database's commit dependency lookup, if supported.""" - return getattr(self._db, "pending_result") # noqa: B009 # optional capability + 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) - @property - def fail_pending_result(self) -> Callable[[tuple[str, ...]], None]: - """The wrapped database's failure registration, if supported.""" - return getattr(self._db, "fail_pending_result") # noqa: B009 # optional capability + 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) - @property def guard_record( - self, - ) -> Callable[ - [tuple[str, ...], bytes, PendingCommit], AbstractContextManager[None] - ]: - """The wrapped database's guarded enqueue operation, if supported.""" - return getattr(self._db, "guard_record") # noqa: B009 # optional capability + 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 stores_records(self) -> bool: - """Whether records are retained by the wrapped database.""" - return getattr(self._db, "stores_records", True) + """Return whether the wrapped database retains records.""" + return self._db.stores_records @property def storage_location(self) -> str: @@ -313,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 8fe664848..959035d1c 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -13,7 +13,11 @@ 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: @@ -43,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__( @@ -366,6 +372,22 @@ def flush(self) -> None: 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)) diff --git a/src/orcapod/databases/noop_database.py b/src/orcapod/databases/noop_database.py index 1419c9965..3c60c020b 100644 --- a/src/orcapod/databases/noop_database.py +++ b/src/orcapod/databases/noop_database.py @@ -105,6 +105,18 @@ 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 diff --git a/src/orcapod/databases/utils.py b/src/orcapod/databases/utils.py index 88ef79958..17018eb43 100644 --- a/src/orcapod/databases/utils.py +++ b/src/orcapod/databases/utils.py @@ -12,10 +12,7 @@ if TYPE_CHECKING: import pyarrow as pa - from orcapod.protocols.database_protocols import ( - ResultCommitGuardingDatabaseProtocol, - TableCommittingDatabaseProtocol, - ) + from orcapod.protocols.database_protocols import TableCommittingDatabaseProtocol else: pa = LazyModule("pyarrow") @@ -67,17 +64,6 @@ def as_table_committing(database: object) -> TableCommittingDatabaseProtocol | N return cast("TableCommittingDatabaseProtocol", database) -def as_result_commit_guarding( - database: object, -) -> ResultCommitGuardingDatabaseProtocol | None: - """Resolve the optional guard methods, including on database wrappers.""" - if callable(getattr(database, "pending_result", None)) and callable( - getattr(database, "guard_record", None) - ): - return cast("ResultCommitGuardingDatabaseProtocol", database) - return None - - _IDENTIFIER = r'(?:"[^"]+"|\w+)' _DIRECT_PROJECTION = re.compile( rf"^\s*SELECT\s+(?:\*|{_IDENTIFIER}(?:\s*,\s*{_IDENTIFIER})*)\s+" diff --git a/src/orcapod/protocols/database_protocols.py b/src/orcapod/protocols/database_protocols.py index 138f27bc2..be9903977 100644 --- a/src/orcapod/protocols/database_protocols.py +++ b/src/orcapod/protocols/database_protocols.py @@ -13,6 +13,53 @@ @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, ...], @@ -208,29 +255,6 @@ class ArrowDatabaseWithMetadataProtocol( pass -@runtime_checkable -class ResultCommitGuardingDatabaseProtocol(Protocol): - """Optional support for publishing pipeline records after their results commit. - - A result store returns a pending commit token for a buffered result and resolves - it when the write succeeds or fails. A pipeline store keeps a guarded record - readable in its queue until the token permits publication, and withdraws it if - the result write fails. The node uses this capability when both stores offer it. - """ - - def pending_result( - self, record_path: tuple[str, ...], record_id: bytes - ) -> PendingCommit | None: - """Return the result's pending commit, or None if it is already available.""" - ... - - def guard_record( - self, record_path: tuple[str, ...], record_id: bytes, dependency: PendingCommit - ) -> AbstractContextManager[None]: - """Guard a record by its result's commit while the caller queues the record.""" - ... - - class TableCommittingDatabaseProtocol(Protocol): """A database that commits table by table (ITL-919). 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_mixed_function_commits.py b/tests/test_pipeline/test_mixed_function_commits.py index e43be6060..03182fff7 100644 --- a/tests/test_pipeline/test_mixed_function_commits.py +++ b/tests/test_pipeline/test_mixed_function_commits.py @@ -4,8 +4,9 @@ import asyncio from collections import defaultdict +from contextlib import AbstractContextManager from pathlib import Path -from typing import Any, Literal, TypedDict, cast +from typing import Any, Literal, Self, TypedDict, cast import deltalake import pyarrow as pa @@ -15,9 +16,11 @@ 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 ( @@ -380,8 +383,8 @@ def fail_result(*args: object, **kwargs: object) -> None: assert not pipeline.list_table_paths() -class ProtocolOnlyDatabase: - """Delegate only the database API, without exposing commit extensions.""" +class DatabaseWithoutCommitGuards: + """Stand-in for the database interface without the required commit methods.""" def __init__(self, inner: InMemoryArrowDatabase) -> None: self._inner = inner @@ -413,8 +416,8 @@ def flush(self) -> None: def base_path(self) -> tuple[str, ...]: return self._inner.base_path - def at(self, *path_components: str) -> ProtocolOnlyDatabase: - return ProtocolOnlyDatabase(self._inner.at(*path_components)) + 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) @@ -426,23 +429,65 @@ def to_config(self) -> dict[str, Any]: return self._inner.to_config() @classmethod - def from_config(cls, config: dict[str, Any]) -> ProtocolOnlyDatabase: + 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_protocol_only_database_preserves_main_rows_and_flushes( +def test_complete_protocol_database_preserves_main_rows_and_flushes( monkeypatch: pytest.MonkeyPatch, asynchronous: bool, placement: str ) -> None: - """A user database can run jobs with just the original database methods.""" + """The complete internal protocol is sufficient to run a job.""" pipeline = InMemoryArrowDatabase().at("pipeline") result = InMemoryArrowDatabase().at("result") - pipeline_store = ( - ProtocolOnlyDatabase(pipeline) if placement != "result" else pipeline - ) + pipeline_store = ProtocolDatabase(pipeline) if placement != "result" else pipeline result_store = ( - ProtocolOnlyDatabase(result) if placement in ("result", "both") else result + ProtocolDatabase(result) if placement in ("result", "both") else result ) assert isinstance(pipeline_store, ArrowDatabaseProtocol) assert isinstance(result_store, ArrowDatabaseProtocol) 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) From f3b64bd7e08e557de44e0ce078aca0e6febc537c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 21:26:40 -0800 Subject: [PATCH 5/5] fix(database): discard refused in-memory batches --- src/orcapod/databases/in_memory_databases.py | 5 ++- .../test_databases/test_in_memory_database.py | 45 +++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 959035d1c..7c9ec84f6 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -401,12 +401,13 @@ def _flush_by_key(self, record_key: str) -> None: 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) - self._pending_commits.restore(record_key, pending, ids) raise else: - self._pending_commits.forget(record_key, ids) 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.""" 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 # ---------------------------------------------------------------------------