diff --git a/changelog.d/ITL-1383.md b/changelog.d/ITL-1383.md new file mode 100644 index 000000000..a5981f9ba --- /dev/null +++ b/changelog.d/ITL-1383.md @@ -0,0 +1,7 @@ +### Fixed + +- Job runs flush additional databases that their nodes write to after the job's own databases, including on the best-effort commit path after an execution error. Each additional database object is flushed once, together with anything else pending in that object. A failed transaction keeps tracked side-effect receipts queued so a later run can publish them without repeating delivery. The job retries a failed attachment flush even after rebinding its sources or node attachments. Duplicate-only replays leave unrelated rows queued when durability is confirmed. When a separate PostgreSQL connection reports a pending receipt as committed, the retry verifies that record ID on the writer's connection before skipping its flush. + +### Known limitations + +- Automatic end-of-run flushing for independently attached databases requires a supported backend that can distinguish buffered rows from durable rows. Opaque third-party protocol wrappers keep their existing commit behavior. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 3401e528e..58b9037d1 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -368,6 +368,17 @@ it with `job.bind(sources=...)`. See [Running again: what a run runs](function-pods.md#running-again-what-a-run-runs) and [What a source does at a run](sources.md#what-a-source-does-at-a-run). +After committing its own databases, the job flushes each supported attachment that +received a new row from a node during the run. A successful side-effect delivery can +enroll its receipt attachment even when completion tracking is disabled and the same +receipt already exists. The flush publishes anything else pending in that database +object. Scoped views sharing pending writes share one flush. A transaction +failure leaves a tracked delivery receipt in the queue, so the next run can +retry its commit without performing the delivery again. +Automatic attachment flushing covers the built-in Delta, connector, and in-memory +databases and their library-provided views. With a separate opaque third-party +attachment, flush any remaining buffered writes explicitly. + ## `Pipeline`: a blueprint without data A `Pipeline` records steps the same way, but has no database and never runs. It is a diff --git a/docs/dev/design_issues/ITL-1383-BL3.md b/docs/dev/design_issues/ITL-1383-BL3.md new file mode 100644 index 000000000..27282c2d2 --- /dev/null +++ b/docs/dev/design_issues/ITL-1383-BL3.md @@ -0,0 +1,46 @@ +## `src/orcapod/pipeline/job.py`, orchestrators, node write paths — database write failures + +### BL3 — A job omitted independently attached database objects from its final commit +**Status:** resolved +**Severity:** high +**Issue:** ITL-1383 + +A caching operator attached to a separate database object returned its new rows +from memory while its log was still buffered. The whole-job final commit flushed +only the job's database views. Independently constructed objects could have separate +pending writes even when they used the same storage location. + +**Fix:** After the job's usual commit, the run flushes each additional database +object that accepted node writes once, including anything else pending in the +object. Scoped views share a flush, including sibling views behind a forwarding +wrapper. The job also attempts the flush when execution fails, keeping the +original error. Load-only runs skip the commit. A failed flush +clears the current rows of the nodes that ran and leaves previously held rows +available. A retry can flush the same log rows and side-effect receipts when +they are still pending. Durable cache hits and completion hits leave the attachment +alone. Successful deliveries enroll their receipt attachments without rereading history. An +attached database that accepted function writes also gets a whole flush after +the function's table commits, even if the pipeline store discards its records. +A failed whole flush stays with the job across source and attachment rebindings. +If an attachment becomes a job-owned store, a successful pre-run or final flush +retires the retry. An interrupted attachment flush remains eligible for retry. +If an attachment interrupts the best-effort commit, the job clears the failed +run and also keeps the unattempted attachments eligible for retry. +Cancellation and an interruption in the owned best-effort commit also retain +attachment writes for the next committing run. +If an existing lookup or a successful local PostgreSQL peer commit confirms +that every replayed row is durable in the same store schema, a duplicate-only +replay leaves the attachment's unrelated writes buffered. When a peer uses a +different connection, the writer checks the record ID on its own session before +treating that commit as durable. A failed transaction +keeps queued completion receipts so a retry can publish them without repeating +delivery. The collector observes +which rows the existing write queued, including when a threshold flush fails. +It uses the table key and schema already resolved by the database operation. +It checks pending receipts against the in-memory queue and identifies a +forwarding view's queue through its path metadata. Connectors otherwise +deduplicate buffered writes during their ordinary upsert. + +Opaque protocol attachments use the existing commit sequence. Automatic +attachment enrollment requires the ability to distinguish durable from pending +records, which the forwarding protocol does not expose. diff --git a/src/orcapod/core/database_writes.py b/src/orcapod/core/database_writes.py new file mode 100644 index 000000000..b5e38b787 --- /dev/null +++ b/src/orcapod/core/database_writes.py @@ -0,0 +1,222 @@ +"""Collect additional database flushes at the node write sites.""" + +from __future__ import annotations + +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass +from typing import TYPE_CHECKING, Protocol + +from orcapod.databases._pending_commits import observe_records + +if TYPE_CHECKING: + from collections.abc import Callable, Collection, Iterator, Set + + from orcapod.databases._pending_commits import PendingCommits + +LogTable = tuple[str, tuple[str, ...]] + + +class WriteDatabase(Protocol): + """The database operations needed at the node write sites.""" + + @property + def base_path(self) -> tuple[str, ...]: + """Return the scope of this database view.""" + ... + + @property + def stores_records(self) -> bool: + """Return whether this database keeps the records it receives.""" + ... + + +@dataclass +class _Write: + """One write site that still needs its database's final whole flush.""" + + database: WriteDatabase + pending: PendingCommits + ids: set[bytes] + function: bool + + +class DatabaseWrites: + """A run's writes to objects outside the job's original flush sequence.""" + + def __init__( + self, + owned: tuple[WriteDatabase, ...], + *, + shared_queue: Callable[[WriteDatabase], PendingCommits | None], + supports_enrollment: Callable[[WriteDatabase], bool], + retry_log_queues: Collection[int], + ) -> None: + """Create a collector for one run.""" + self._shared_queue = shared_queue + self._queues: dict[int, tuple[WriteDatabase, PendingCommits | None]] = {} + self._supports_enrollment = supports_enrollment + self._retry_log_queues = retry_log_queues + self._covered = {self.queue_id(database) for database in owned} + self._writes: dict[tuple[int, LogTable], _Write] = {} + self._durable_logs: dict[tuple[int, LogTable], set[bytes]] = {} + + def _queue(self, database: WriteDatabase) -> PendingCommits | None: + """Resolve each view once and keep it alive while its identity is in use.""" + identity = id(database) + if identity not in self._queues: + self._queues[identity] = (database, self._shared_queue(database)) + return self._queues[identity][1] + + def queue_id(self, database: WriteDatabase) -> int: + """Identify the store by its shared queue when it exposes one.""" + queue = self._queue(database) + return id(database if queue is None else queue) + + def covers(self, queue: int) -> bool: + """Return whether the job's existing flush sequence covers this queue.""" + return queue in self._covered + + def databases(self) -> dict[int, WriteDatabase]: + """Return one view per enrolled store in write order.""" + result: dict[int, WriteDatabase] = {} + for (queue, _), write in self._writes.items(): + _ = result.setdefault(queue, write.database) + return result + + def function_databases(self) -> dict[int, WriteDatabase]: + """Return attachments whose function writes may be durable before job commit.""" + return { + queue: write.database + for (queue, _), write in self._writes.items() + if write.function + } + + def logs_to_replay(self, queue: int) -> dict[LogTable, set[bytes]] | None: + """Keep the IDs from pending logs without querying the store after failure.""" + logs: dict[LogTable, set[bytes]] = {} + for (identity, table), write in self._writes.items(): + if identity != queue or write.function: + continue + key, _ = table + if not write.pending.has_pending(key, write.ids): + # Even though its rows committed, the whole flush remains owed. + return {} + logs[table] = write.ids + return logs or None + + def replayed_durable_logs( + self, + queue: int, + logs: dict[LogTable, set[bytes]], + ) -> bool: + """A duplicate-only replay can find the failed logs now durable elsewhere.""" + return bool(logs) and all( + ids <= self._durable_logs.get((queue, table), set()) + for table, ids in logs.items() + ) + + @contextmanager + def track( + self, + database: WriteDatabase, + path: tuple[str, ...], + *, + function: bool = False, + completion: bool = False, + ) -> Iterator[None]: + """Track the outcome of the existing native store operation.""" + if not self._supports_enrollment(database): + yield + return + pending = self._queue(database) + queue = id(pending) + if pending is None or self.covers(queue): + yield + return + retry = queue in self._retry_log_queues + if completion and not retry: + yield + return + + def record( + key: str, + added: set[bytes], + durable: Set[bytes], + ) -> None: + table = key, database.base_path + path + if added: + write = self._writes.setdefault( + (queue, table), _Write(database, pending, set(), function) + ) + write.ids.update(added) + if retry and not function and durable: + self._durable_logs.setdefault((queue, table), set()).update(durable) + + with observe_records(record): + yield + + def exclude_unpublished_result( + self, database: WriteDatabase, path: tuple[str, ...] + ) -> None: + """Keep an unpublished result from enrolling a queue on its own.""" + queue = self.queue_id(database) + full_path = database.base_path + path + for identity, table in tuple(self._writes): + key, tracked_path = table + write = self._writes[identity, table] + if ( + identity == queue + and tracked_path == full_path + and write.pending.has_pending(key, write.ids) + ): + del self._writes[identity, table] + + +_run_writes: ContextVar[DatabaseWrites | None] = ContextVar("_run_writes", default=None) + + +@contextmanager +def collect_database_writes(writes: DatabaseWrites) -> Iterator[None]: + """Share the run's write collection with its synchronous and async nodes.""" + token = _run_writes.set(writes) + try: + yield + finally: + _run_writes.reset(token) + + +@contextmanager +def track_database_write( + database: WriteDatabase, + path: tuple[str, ...], + *, + function: bool = False, +) -> Iterator[None]: + """Track a write when the node is running as part of a job.""" + run = _run_writes.get() + if run is None or not database.stores_records: + yield + return + with run.track(database, path, function=function): + yield + + +@contextmanager +def track_completion_lookup( + database: WriteDatabase, path: tuple[str, ...] +) -> Iterator[None]: + """Share the completion lookup's table key with the enclosing job run.""" + run = _run_writes.get() + if run is None: + yield + return + with run.track(database, path, completion=True): + yield + + +def exclude_unpublished_result(database: WriteDatabase, path: tuple[str, ...]) -> None: + """Keep a dry-run result from independently triggering a whole flush.""" + run = _run_writes.get() + if run is not None: + run.exclude_unpublished_result(database, path) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index f27c84b7e..9b2e07f09 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -76,6 +76,10 @@ from orcapod.core.data_function import output_source_info from orcapod.core.datagrams.tag_data import Data, EmptyData, Tag from orcapod.core.row_ids import INSTANCE_ID_COL, RECORD_ID_COL +from orcapod.core.database_writes import ( + exclude_unpublished_result, + track_database_write, +) from orcapod.core.provisional_pods import CONTEXT_FUNCTION_POD, warn_provisional_pod from orcapod.errors import ( EphemeralResultMissingError, @@ -2450,6 +2454,8 @@ def _flush_node_table( flush=True, table_flush=True, ) from exc + if result and not publish_records: + exclude_unpublished_result(database, path) def _commit_pending_writes(self) -> None: """Commit results before publishing any records that depend on them.""" @@ -2514,7 +2520,11 @@ def _write_pipeline_record( if dependency is None else database.guard_record(path, row_key, dependency) ) - with database.guard_table_schema(path, check), result_guard: + with ( + database.guard_table_schema(path, check), + result_guard, + track_database_write(database, path, function=True), + ): database.add_record(path, row_key, record, skip_duplicates=True) def _row_processed(self) -> None: diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index cb3bc9db6..e440636af 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -69,6 +69,7 @@ ) from orcapod.core.tracker import DEFAULT_TRACKER_MANAGER from orcapod.core.nodes.staleness import RunHoldingNode +from orcapod.core.database_writes import track_database_write from orcapod.errors import ( InputValidationError, PipelineJobRequiredError, @@ -1571,23 +1572,23 @@ def _store_output_stream(self, stream: StreamProtocol) -> None: # deduplicates exact re-runs of the same node within a single run. # The data context column is appended after the record hashes are computed: # it names the generation of hashing that produced them and is not hashed. + path = self._stored_table_path try: - pipeline_database.add_records( - self._stored_table_path, - with_data_context( - mark_data_tags(stored_table, stream_data_tags(self)), - self.data_context_key, - ), - record_id_column=self.HASH_COLUMN_NAME, - skip_duplicates=True, - ) + with track_database_write(pipeline_database, path): + pipeline_database.add_records( + path, + with_data_context( + mark_data_tags(stored_table, stream_data_tags(self)), + self.data_context_key, + ), + record_id_column=self.HASH_COLUMN_NAME, + skip_duplicates=True, + ) except OrcapodDatabaseReadError: # The stored table could not be read: report the read failure itself. raise except Exception as exc: - raise OrcapodDatabaseWriteError( - self._stored_table_path, node_label=self.label - ) from exc + raise OrcapodDatabaseWriteError(path, node_label=self.label) from exc self._cached_output_table = output_table.drop( [self.HASH_COLUMN_NAME, constants.NODE_CONTENT_HASH_COL] diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index 5500685ff..b4bfe48d4 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -15,6 +15,7 @@ import pyarrow as pa from orcapod.core.data_function_types import StoredColumn +from orcapod.core.database_writes import track_database_write from orcapod.errors import ( InputValidationError, OrcapodDatabaseReadError, @@ -537,18 +538,25 @@ def store( ) data_table = with_data_context(data_table, data_context_key) + path = self._versioned_record_path + result_id = output_data.datagram_uuid.bytes try: - self._result_database.add_record( - self._versioned_record_path, - output_data.datagram_uuid.bytes, - data_table, - skip_duplicates=skip_duplicates, - ) + with track_database_write( + self._result_database, + path, + function=True, + ): + self._result_database.add_record( + path, + result_id, + data_table, + skip_duplicates=skip_duplicates, + ) except OrcapodDatabaseReadError: # The stored table could not be read: report the read failure itself. raise except Exception as exc: - raise OrcapodDatabaseWriteError(self._versioned_record_path) from exc + raise OrcapodDatabaseWriteError(path) from exc if self._auto_flush: try: self._result_database.flush() diff --git a/src/orcapod/databases/_pending_commits.py b/src/orcapod/databases/_pending_commits.py index a3891705f..0e82b8a8e 100644 --- a/src/orcapod/databases/_pending_commits.py +++ b/src/orcapod/databases/_pending_commits.py @@ -2,8 +2,10 @@ from __future__ import annotations -from collections.abc import Callable, Iterator +from collections.abc import Callable, Iterator, Set from contextlib import contextmanager +from contextvars import ContextVar +from threading import Lock import pyarrow as pa @@ -46,6 +48,51 @@ def __init__( self._attempts: dict[str, PendingCommit] = {} self._guards: dict[str, dict[bytes, PendingCommit]] = {} self._schema_checks: dict[str, Callable[[pa.Schema], None]] = {} + self._receipts: dict[str, set[bytes]] = {} + self._peer_receipts: dict[str, dict[bytes, bool]] = {} + self._receipt_lock = Lock() + + def record_receipts(self, key: str, ids: set[bytes]) -> None: + """Keep completed deliveries queued until their records commit.""" + if _recording_receipt.get(): + with self._receipt_lock: + self._receipts.setdefault(key, set()).update(ids) + + def note_peer_receipts( + self, key: str, ids: set[bytes], *, same_connection: bool + ) -> None: + """Remember peer commits for queued receipts, preferring the same connection.""" + with self._receipt_lock: + matching = ids & self._receipts.get(key, set()) + if matching: + evidence = self._peer_receipts.setdefault(key, {}) + for record_id in matching: + evidence[record_id] = same_connection or evidence.get( + record_id, False + ) + + def receipt_peer_evidence(self, key: str, record_id: bytes) -> bool | None: + """Return whether the peer used our connection, or None without evidence.""" + with self._receipt_lock: + return self._peer_receipts.get(key, {}).get(record_id) + + def has_receipts(self, key: str, ids: set[bytes]) -> bool: + """Return whether this batch contains completed deliveries.""" + with self._receipt_lock: + return not ids.isdisjoint(self._receipts.get(key, ())) + + def fail_batch(self, key: str, batch: pa.Table, ids: set[bytes]) -> None: + """Keep failed receipts and withdraw records depending on this commit.""" + with self._receipt_lock: + receipts = ids & self._receipts.get(key, set()) + if receipts: + self.restore( + key, + batch if receipts == ids else self._select(batch, receipts, keep=True), + receipts, + ) + self.forget(key, ids - receipts) + self.finish(key, committed=False) @contextmanager def guard_schema( @@ -63,6 +110,10 @@ def schema_check(self, key: str) -> Callable[[pa.Schema], None] | None: """Get the check for a batch being committed.""" return self._schema_checks.get(key) + def has_pending(self, key: str, ids: set[bytes]) -> bool: + """Return whether any of the given IDs are still queued.""" + return not ids.isdisjoint(self._ids.get(key, ())) + def attempt(self, key: str) -> PendingCommit: """Get the attempt shared by all rows currently pending for a table.""" attempt = self._attempts.get(key) @@ -137,6 +188,18 @@ def restore(self, key: str, batch: pa.Table, ids: set[bytes]) -> None: def forget(self, key: str, ids: set[bytes]) -> None: """Forget dependencies for records that are leaving the queue.""" + with self._receipt_lock: + receipts = self._receipts.get(key) + if receipts is not None: + receipts.difference_update(ids) + if not receipts: + del self._receipts[key] + evidence = self._peer_receipts.get(key) + if evidence is not None: + for record_id in ids: + _ = evidence.pop(record_id, None) + if not evidence: + del self._peer_receipts[key] if key not in self._batches: self._schema_checks.pop(key, None) guards = self._guards.get(key) @@ -153,3 +216,71 @@ def _select(self, batch: pa.Table, ids: set[bytes], *, keep: bool) -> pa.Table: for record_id in batch[self._record_id_column].to_pylist() ] return batch.filter(pa.array(mask, type=pa.bool_())) + + +_queue_lookup: ContextVar[list[PendingCommits] | None] = ContextVar( + "_queue_lookup", default=None +) +RecordObserver = Callable[[str, set[bytes], Set[bytes]], None] +_recording_receipt: ContextVar[bool] = ContextVar("recording_receipt", default=False) + +_record_observer: ContextVar[RecordObserver | None] = ContextVar( + "_record_observer", default=None +) + + +def observing_records() -> bool: + """Return whether the caller needs record acceptance or durability evidence.""" + return _record_observer.get() is not None + + +@contextmanager +def record_completion_receipt(tracked: bool) -> Iterator[None]: + """Keep a delivery receipt in its store queue if its flush fails.""" + token = _recording_receipt.set(tracked) + try: + yield + finally: + _recording_receipt.reset(token) + + +@contextmanager +def observe_queue() -> Iterator[list[PendingCommits]]: + """Identify a forwarding view's native queue during a path lookup.""" + queues: list[PendingCommits] = [] + token = _queue_lookup.set(queues) + try: + yield queues + finally: + _queue_lookup.reset(token) + + +def report_queue(queue: PendingCommits) -> None: + """Report the native queue to a caller observing a view's path.""" + queues = _queue_lookup.get() + if queues is not None: + queues.append(queue) + + +@contextmanager +def observe_records( + observer: RecordObserver, +) -> Iterator[None]: + """Observe the IDs resolved by an existing write or completion lookup.""" + token = _record_observer.set(observer) + try: + yield + finally: + _record_observer.reset(token) + + +def report_records( + key: str, + *, + added: set[bytes], + durable: Set[bytes] = frozenset(), +) -> None: + """Report accepted and already durable IDs using the resolved table key.""" + observer = _record_observer.get() + if observer is not None: + observer(key, added, durable) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 267caf622..71ed8c774 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -22,17 +22,26 @@ from collections import defaultdict from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager, nullcontext +from threading import Lock from typing import Any, cast +from weakref import WeakKeyDictionary, WeakValueDictionary import pyarrow as pa import pyarrow.compute as pc -from orcapod.databases._pending_commits import PendingCommit, PendingCommits +from orcapod.databases._pending_commits import ( + PendingCommit, + PendingCommits, + observing_records, + report_queue, + report_records, +) from orcapod.databases._sql_store import ( SQLStoreConnector, require_store_table_owner, stored_path, ) +from orcapod.databases.postgresql_connector import PostgreSQLConnector from orcapod.databases.store_table_names import ( STORE_TABLE_NAME_PREFIX, store_table_name, @@ -68,6 +77,27 @@ _SQL_HINT_LENGTH = 27 _SQL_DIGEST_LENGTH = 32 +# A shared endpoint identifies candidates for peer evidence. The queued table +# key also carries the schema. Nothing records receipt history. +_ReceiptPeers = WeakKeyDictionary[PendingCommits, PostgreSQLConnector] +_receipt_queues: WeakValueDictionary[tuple[str, int, str], _ReceiptPeers] = ( + WeakValueDictionary() +) +_receipt_queue_lock = Lock() + + +def _connect_receipt_queue( + connector: PostgreSQLConnector, pending: PendingCommits +) -> _ReceiptPeers: + """Register a pending queue for commits by another local PostgreSQL handle.""" + identity = connector._receipt_store_identity() # pyright: ignore[reportPrivateUsage] # private store tracking + with _receipt_queue_lock: + queues = _receipt_queues.get(identity) + if queues is None: + queues = _receipt_queues[identity] = WeakKeyDictionary() + queues[pending] = connector + return queues + def _arrow_schema_to_column_infos(schema: pa.Schema) -> list[ColumnInfo]: """Convert a PyArrow schema to a list of ColumnInfo.""" @@ -188,6 +218,13 @@ def __init__( on_empty=self._discard_pending_duplicate_policy, ) ) + self._receipt_peers: _ReceiptPeers | None = None + if _root is not None: + self._receipt_peers = _root._receipt_peers + elif isinstance(connector, PostgreSQLConnector): + self._receipt_peers = _connect_receipt_queue( + connector, self._pending_commits + ) def _discard_pending_duplicate_policy(self, key: str) -> None: """Forget indexes when an entire queued batch is discarded.""" @@ -671,9 +708,10 @@ def add_records( self._pending_batches[record_key] = pa.concat_tables( [existing_pending, records] ) - self._pending_record_ids[record_key].update( - cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist()) - ) + added = set(cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist())) + self._pending_record_ids[record_key].update(added) + self._pending_commits.record_receipts(record_key, added) + report_records(record_key, added=added) if flush: self.flush() @@ -806,6 +844,7 @@ def _read_stored_schema( @property def base_path(self) -> tuple[str, ...]: """The current relative root of this database view (always () for root instances).""" + report_queue(self._pending_commits) return self._path_prefix def at(self, *path_components: str) -> "ConnectorArrowDatabase": @@ -907,12 +946,9 @@ def _flush_by_key(self, record_key: str) -> None: return pending, ids = ready skip_existing = self._pending_skip_existing.get(record_key, False) - if record_key not in self._pending_batches: - self._discard_pending_duplicate_policy(record_key) - record_path = self._record_path_from_key(record_key) - table_name = self._path_to_table_name(record_path) - try: + record_path = self._record_path_from_key(record_key) + table_name = self._path_to_table_name(record_path) self._require_table_name(table_name) if self._sql_store is None: transaction = nullcontext( @@ -930,12 +966,24 @@ def _flush_by_key(self, record_key: str) -> None: record_key, table_name, pending, skip_existing, table_exists, schema ) except BaseException: - self._pending_commits.finish(record_key, committed=False) + self._pending_commits.fail_batch(record_key, pending, ids) raise else: + self._pending_commits.forget(record_key, ids) self._pending_commits.finish(record_key, committed=True) + if self._receipt_peers is not None: + with _receipt_queue_lock: + peers = tuple(self._receipt_peers.items()) + for peer, connector in peers: + if peer is not self._pending_commits: + peer.note_peer_receipts( + record_key, + ids, + same_connection=connector is self._connector, + ) finally: - self._pending_commits.forget(record_key, ids) + if record_key not in self._pending_batches: + self._discard_pending_duplicate_policy(record_key) def _write_ready_batch( self, @@ -1020,11 +1068,24 @@ def get_record_by_id( pending = self._pending_batches[record_key] filtered = pending.filter(pc.field(self.RECORD_ID_COLUMN) == record_id) if filtered.num_rows > 0: + table = None if self._sql_store is not None: full_path = self._path_prefix + record_path - _ = self._find_committed_table( + table = self._find_committed_table( self._path_to_table_name(full_path), full_path, schema=schema ) + if table is not None and observing_records(): + evidence = self._pending_commits.receipt_peer_evidence( + record_key, record_id + ) + if evidence is True or ( + evidence is False + and isinstance(self._connector, PostgreSQLConnector) + and self._connector._has_committed_record( # pyright: ignore[reportPrivateUsage] # confirm peer evidence on the writer session + table, self.RECORD_ID_COLUMN, record_id + ) + ): + report_records(record_key, added=set(), durable={record_id}) return self._handle_record_id_column(filtered, record_id_column) # Check committed @@ -1034,6 +1095,8 @@ def get_record_by_id( filtered = committed.filter(pc.field(self.RECORD_ID_COLUMN) == record_id) if filtered.num_rows == 0: return None + # This lookup already read the row from committed storage. + report_records(record_key, added=set(), durable={record_id}) return self._handle_record_id_column(filtered, record_id_column) def get_all_records( diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index e9373b91e..4e2fa16cc 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -18,7 +18,12 @@ import pyarrow as pa import pyarrow.compute as pc -from orcapod.databases._pending_commits import PendingCommit, PendingCommits +from orcapod.databases._pending_commits import ( + PendingCommit, + PendingCommits, + report_queue, + report_records, +) from orcapod.databases._row_index import ( KeyIndex, compact_tail, @@ -2975,14 +2980,20 @@ def add_records( # Step 2: Deduplicate within input table (keep last occurrence) deduplicated_table = self._deduplicate_within_table(records) + durable: set[bytes] = set() # Step 3: Handle conflicts based on skip_duplicates setting if skip_duplicates: # A read failure here propagates as it is: it fails the run whatever # the error policy. - filtered_table = self._filter_existing_records( + filtered_table, durable = self._filter_existing_records( record_path, deduplicated_table ) if filtered_table.num_rows == 0: + report_records( + self._get_record_key(record_path), + added=set(), + durable=durable, + ) logger.debug("All records were duplicates, nothing to insert") return None else: @@ -3041,7 +3052,14 @@ def add_records( self._pending_batches[self._get_record_key(record_path)] = staged_pending # Step 7: Add to pending batch (no overwrite logic needed) - self._add_to_pending_batch(record_path, schema_compatible_table) + added = self._add_to_pending_batch(record_path, schema_compatible_table) + record_key = self._get_record_key(record_path) + self._pending_commits.record_receipts(record_key, added) + report_records( + record_key, + added=added, + durable=durable, + ) # Step 8: Flush if asked to; otherwise commit this table alone once its # pending batch reaches batch_size. Only the full table: committing every @@ -3081,9 +3099,9 @@ def _deduplicate_within_table(self, table: pa.Table) -> pa.Table: def _filter_existing_records( self, record_path: tuple[str, ...], table: pa.Table - ) -> pa.Table: + ) -> tuple[pa.Table, set[bytes]]: """Filter out records that already exist (for skip_duplicates=True).""" - input_ids = set(table[self.RECORD_ID_COLUMN].to_pylist()) + input_ids = set(cast(list[bytes], table[self.RECORD_ID_COLUMN].to_pylist())) record_key = self._get_record_key(record_path) # Get IDs that already exist in pending batch or Delta table @@ -3103,7 +3121,7 @@ def _filter_existing_records( all_existing = existing_in_pending.union(existing_in_delta) if not all_existing: - return table # No duplicates found + return table, existing_in_delta # No duplicates found # Filter out existing records mask = pc.invert( @@ -3112,7 +3130,7 @@ def _filter_existing_records( filtered = table.filter(mask) logger.debug(f"Skipped {len(all_existing)} duplicate records") - return filtered + return filtered, existing_in_delta def _check_all_conflicts( self, record_path: tuple[str, ...], table: pa.Table @@ -3224,7 +3242,9 @@ def _handle_delta_schema_compatibility( else: raise ValueError(f"Unknown schema handling: {schema_handling}") - def _add_to_pending_batch(self, record_path: tuple[str, ...], table: pa.Table): + def _add_to_pending_batch( + self, record_path: tuple[str, ...], table: pa.Table + ) -> set[bytes]: """Add table to pending batch.""" # Add row index column for internal tracking record_key = self._get_record_key(record_path) @@ -3240,8 +3260,9 @@ def _add_to_pending_batch(self, record_path: tuple[str, ...], table: pa.Table): if index is not None and index.table is pending_batch: index.append(table, grown) - pending_ids = cast(list[bytes], table[self.RECORD_ID_COLUMN].to_pylist()) + pending_ids = set(cast(list[bytes], table[self.RECORD_ID_COLUMN].to_pylist())) self._pending_record_ids[record_key].update(pending_ids) + return pending_ids def _should_auto_flush(self, record_path: tuple[str, ...]) -> bool: """Check if auto-flush should be triggered.""" @@ -3526,6 +3547,7 @@ def get_record_by_id( return None # Handle (remove/rename) the record id column before returning + report_records(record_key, added=set(), durable={record_id}) return self._handle_record_id_column(result, record_id_column) def get_records_by_ids( @@ -3843,6 +3865,12 @@ def _flush_by_key(self, record_key: str) -> None: attempt += 1 except (InputValidationError, StoredTableSchemaError) as e: + if self._pending_commits.has_receipts(record_key, pending_ids): + # The callback already ran. Keep its receipt until storage is repaired. + self._delta_table_cache.pop(record_key, None) + self._snapshots.pop(record_key, None) + self._pending_commits.fail_batch(record_key, pending_batch, pending_ids) + raise # The stored table refuses these rows (``_append_refusal``, # ``_conformed_to_stored``): they would be refused by every later flush # too, so they leave the queue, as rows refused when added never enter @@ -3872,7 +3900,10 @@ def _flush_by_key(self, record_key: str) -> None: except BaseException as e: permanent = isinstance(e, Exception) and _permanent_commit_failure(e) reported = _write_refused_for_duplicate_name(e) - if permanent and reported is None: + retain_receipts = self._pending_commits.has_receipts( + record_key, pending_ids + ) + if permanent and reported is None and not retain_receipts: # Refused by Delta for the rows themselves: every later flush would be # refused the same way, so the batch leaves the queue, and nothing of # it was written (ITL-1403). The flush is the point of truth. Records @@ -3890,7 +3921,7 @@ def _flush_by_key(self, record_key: str) -> None: self._pending_commits.finish(record_key, committed=False) logger.error(f"Refused batch for {record_key}: {refused}") raise refused from e - if reported is not None: + if reported is not None and not retain_receipts: # The batch's own name, not the message's: a name may hold a quote. duplicate, arrow_type = _reported_field(e, pending_batch.schema) # delta-rs folds case with Rust's ``to_lowercase``, which agrees with @@ -4424,6 +4455,7 @@ def storage_location(self) -> str: @property def base_path(self) -> tuple[str, ...]: """The current relative root of this database view (always () for root instances).""" + report_queue(self._pending_commits) return self._path_prefix def at(self, *path_components: str) -> "DeltaTableDatabase": diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 2ccb4d696..3a94109e5 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -9,7 +9,12 @@ import pyarrow as pa import pyarrow.compute as pc -from orcapod.databases._pending_commits import PendingCommit, PendingCommits +from orcapod.databases._pending_commits import ( + PendingCommit, + PendingCommits, + report_queue, + report_records, +) from orcapod.databases._row_index import KeyIndex, compact_tail, matching_rows from orcapod.databases.utils import ( coerce_record_id, @@ -194,23 +199,23 @@ def _committed_id_index(self, record_key: str) -> dict[Any, list[int]]: def _filter_existing_records( self, record_key: str, table: "pa.Table" - ) -> "pa.Table": + ) -> tuple[pa.Table, set[bytes]]: """Filter out records whose IDs are already in pending or committed database.""" - input_ids = set(table[self.RECORD_ID_COLUMN].to_pylist()) + input_ids = set(cast(list[bytes], table[self.RECORD_ID_COLUMN].to_pylist())) pending_ids = self._pending_record_ids[record_key] committed_ids = self._committed_id_index(record_key) - all_existing = { + durable = { record_id for record_id in input_ids - if record_id in pending_ids - or (record_id is not None and record_id in committed_ids) + if record_id is not None and record_id in committed_ids } + all_existing = (input_ids & pending_ids) | durable if not all_existing: - return table + return table, durable mask = pc.invert( pc.is_in(table[self.RECORD_ID_COLUMN], pa.array(list(all_existing))) ) - return table.filter(mask) + return table.filter(mask), durable # ------------------------------------------------------------------ # Write methods @@ -312,13 +317,17 @@ def add_records( # Deduplicate within the incoming batch (keep last) records = self._deduplicate_within_table(records) + durable: set[bytes] = set() if skip_duplicates: - records = self._filter_existing_records(record_key, records) + records, durable = self._filter_existing_records(record_key, records) if records.num_rows == 0: + report_records(record_key, added=set(), durable=durable) return else: # Check for conflicts in the pending batch only - input_ids = set(records[self.RECORD_ID_COLUMN].to_pylist()) + input_ids = set( + cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist()) + ) pending_conflicts = input_ids & self._pending_record_ids[record_key] if pending_conflicts: raise ValueError( @@ -335,7 +344,10 @@ def add_records( [existing_pending, records] ) pending_ids = cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist()) - self._pending_record_ids[record_key].update(pending_ids) + added = set(pending_ids) + self._pending_record_ids[record_key].update(added) + self._pending_commits.record_receipts(record_key, added) + report_records(record_key, added=added, durable=durable) if flush: self.flush() @@ -424,13 +436,11 @@ 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.fail_batch(record_key, pending, ids) raise else: - self._pending_commits.finish(record_key, committed=True) - finally: 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.""" @@ -471,6 +481,7 @@ def _promote(self, record_key: str, pending: "pa.Table") -> None: @property def base_path(self) -> tuple[str, ...]: """The current relative root of this database view (always () for root instances).""" + report_queue(self._pending_commits) return self._path_prefix def at(self, *path_components: str) -> "InMemoryArrowDatabase": @@ -618,6 +629,7 @@ def get_record_by_id( filtered = committed.filter(pc.field(self.RECORD_ID_COLUMN) == record_id) if filtered.num_rows == 0: return None + report_records(record_key, added=set(), durable={record_id}) return self._handle_record_id_column(filtered, record_id_column) def get_all_records( diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index b767a955d..32620eb99 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -439,6 +439,35 @@ def _require_open(self) -> Any: raise RuntimeError("PostgreSQLConnector is closed") return self._conn + def _receipt_store_identity(self) -> tuple[str, int, str]: + """Group connections that report the same endpoint and database name.""" + with self._lock: + conn = cast("psycopg.Connection[tuple[object, ...]]", self._require_open()) + info = conn.info + return info.hostaddr or info.host, info.port, info.dbname + + def _has_committed_record( + self, table: tuple[str | None, str], id_column: str, record_id: bytes + ) -> bool: + """Confirm a peer's commit on this writer's session using the record ID.""" + from psycopg import sql as pg_sql + + schema, name = table + assert schema is not None + query = pg_sql.SQL("SELECT 1 FROM {} WHERE {} = %s LIMIT 1").format( + pg_sql.Identifier(schema.replace("%", "%%"), name.replace("%", "%%")), + pg_sql.Identifier(id_column.replace("%", "%%")), + ) + with self._lock: + conn = cast("psycopg.Connection[tuple[object, ...]]", self._require_open()) + try: + with conn.transaction(force_rollback=True), conn.cursor() as cur: + _ = cur.execute(query, (record_id,)) + return cur.fetchone() is not None + except psycopg.Error: + # Without confirmation the job can still retry its ordinary flush. + return False + @staticmethod def _validate_table_name(table_name: str) -> None: """Raise ValueError if table_name contains a double-quote character.""" diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index cd745867a..e9d494c6e 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -6,13 +6,16 @@ import enum import logging import sys +import uuid from collections.abc import Iterable, Iterator, Sequence from copy import deepcopy from dataclasses import dataclass from itertools import chain from typing import TYPE_CHECKING, Any, cast + import orcapod +from orcapod.core.database_writes import DatabaseWrites, collect_database_writes from orcapod.core.nodes import JobNode from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode @@ -21,8 +24,9 @@ from orcapod.core.sources.base import RootSource from orcapod.core.sources.derived_source import DerivedSource from orcapod.core.streams.base import StreamBase -from orcapod.side_effects import SideEffectJobNode, SideEffectNode from orcapod.core.tracker import AutoRegisteringContextBasedTracker +from orcapod.databases._pending_commits import observe_queue +from orcapod.databases.utils import as_table_committing from orcapod.errors import ( InconsistentSourceError, OrcapodDatabaseError, @@ -60,17 +64,23 @@ require_live_source_bindings, ) from orcapod.protocols import core_protocols as cp -from orcapod.databases.utils import as_table_committing +from orcapod.side_effects import SideEffectJobNode, SideEffectNode from orcapod.types import NodeConfig -from orcapod.utils.database_errors import database_write_path, flush_best_effort +from orcapod.utils.database_errors import ( + commit_best_effort, + database_write_path, +) if TYPE_CHECKING: from collections.abc import Mapping from pathlib import Path from types import FrameType - from orcapod.core.nodes.source_node import _DeclaredForm # pyright: ignore[reportPrivateUsage] # shared binding transaction - + from orcapod.core.database_writes import LogTable, WriteDatabase + from orcapod.core.nodes.source_node import ( + _DeclaredForm, # pyright: ignore[reportPrivateUsage] # shared binding transaction + ) + from orcapod.databases._pending_commits import PendingCommits from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.execution_context import ExecutionContext from orcapod.pipeline.graph import Pipeline @@ -85,6 +95,32 @@ logger = logging.getLogger(__name__) +def _backend(database: WriteDatabase) -> WriteDatabase: + """Unwrap library views that forward operations to a backend.""" + while isinstance(database, orcapod.databases.ExtensionAwareDatabase): + database = database._db # pyright: ignore[reportPrivateUsage] + return database + + +def _supports_attachment_enrollment(database: WriteDatabase) -> bool: + """Recognize stores whose durable rows we can distinguish from pending ones.""" + return isinstance( + _backend(database), + ( + orcapod.databases.DeltaTableDatabase, + orcapod.databases.InMemoryArrowDatabase, + orcapod.databases.ConnectorArrowDatabase, + ), + ) + + +def _shared_queue(database: WriteDatabase) -> PendingCommits | None: + """Identify an owned view's queue through its forwarded path property.""" + with observe_queue() as queues: + _ = database.base_path + return queues[0] if len(queues) == 1 else None + + class _Unchanged(enum.Enum): """The default of ``PipelineJob.bind(result_database=...)``: keep the binding. @@ -112,6 +148,7 @@ class _PreparedRun: pipeline_uri: ``@``, passed to the observer. pipeline_db: The job's view of the database. result_db: The job's function-result view of the database. + writes: The additional databases written by the job's nodes. plan: What the run runs and holds (``plan_run``, ITL-1095). unchecked_sources: The sources the start-of-run check could not check (``check_sources``, ITL-1102). @@ -124,6 +161,15 @@ class _PreparedRun: result_db: "ArrowDatabaseProtocol" plan: "RunPlan" unchecked_sources: tuple[str, ...] + writes: DatabaseWrites + + +@dataclass(frozen=True) +class _AttachmentRetry: + """A failed whole flush, with any pending logs that could make it redundant.""" + + database: ArrowDatabaseProtocol + logs: dict[LogTable, set[bytes]] def _with_counter( @@ -234,6 +280,8 @@ def __init__( super().__init__(name=name, tracker_manager=tracker_manager) self._database = database self._result_database: "ArrowDatabaseProtocol | None" = result_database + self._node_database_views: "tuple[ArrowDatabaseProtocol, ...]" = () + self._retry_attachment_flushes: dict[int, _AttachmentRetry] = {} # For a loaded job whose file names a separate result database that is not # available (it could not be rebuilt, or it was in memory) and none was given: # that saved configuration. Its function nodes get no database rather than the @@ -859,6 +907,7 @@ def _distribute_databases(self) -> None: node.attach_databases( pipeline_database=pipeline_db, ) + self._node_database_views = (pipeline_db, result_db) # ------------------------------------------------------------------ # _iter_function_job_nodes() / apply_node_config() @@ -931,6 +980,7 @@ def as_pipeline(self) -> "Pipeline": RuntimeError: If this job has not been compiled. """ import networkx as _nx + from orcapod.core.nodes.function_node import FunctionNode from orcapod.core.nodes.operator_node import OperatorNode from orcapod.pipeline.graph import Pipeline @@ -1416,7 +1466,6 @@ def _prepare_run( OrcapodDatabaseError: If writes still pending from before the run cannot be committed. """ import hashlib - import uuid if ( isinstance(commit_every_rows, bool) @@ -1609,6 +1658,18 @@ def _prepare_run( warn_restricted_aggregation(exec_dag) # The state rule (ITL-1095): a node that holds a current run is not run again. plan = plan_run(exec_dag, load_only=load_only) + writes = DatabaseWrites( + (pipeline_db, result_db, *self._node_database_views, self._database) + if plan.to_run and not load_only + else (), + shared_queue=_shared_queue, + supports_enrollment=_supports_attachment_enrollment, + retry_log_queues={ + queue + for queue, retry in self._retry_attachment_flushes.items() + if retry.logs + }, + ) # A database that commits a table by itself at batch_size: commit what it already # holds pending (writes made without a flush, or a failed run's batches) before # this run writes. Those rows would otherwise count towards a table's @@ -1625,7 +1686,7 @@ def _prepare_run( ) for pending_db in pending_dbs: try: - pending_db.flush() + self._flush_owned(pending_db, writes) except OrcapodDatabaseError as exc: exc.add_note(_PENDING_BEFORE_RUN_NOTE) raise @@ -1644,6 +1705,7 @@ def _prepare_run( result_db=result_db, plan=plan, unchecked_sources=unchecked, + writes=writes, ) @contextlib.contextmanager @@ -1668,7 +1730,10 @@ def _executing( load_only: As for ``run``. """ try: - with contextlib.ExitStack() as batched: + with ( + collect_database_writes(prepared.writes), + contextlib.ExitStack() as batched, + ): # Function nodes commit every commit_every_rows rows (ITL-919). for node in plan.to_run: if isinstance(node, FunctionJobNode): @@ -1680,9 +1745,9 @@ def _executing( # 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, + best_effort = isinstance(run_error, Exception) and not load_only + if best_effort: + owned = ( prepared.pipeline_db, prepared.result_db, # Records a separate result database's flush released (ITL-1408). @@ -1692,9 +1757,108 @@ def _executing( else () ), ) - clear_run_rows(plan.to_run) + try: + for database in owned: + commit_best_effort( + run_error, + lambda: self._flush_owned(database, prepared.writes), + ) + except BaseException: + self._retain_run_attachments(prepared.writes) + raise + elif not load_only: + self._retain_run_attachments(prepared.writes) + # Once the owned sequence returns, clear the failed run even if an + # attachment interrupts cleanup. Keep the attachments it prevented + # us from attempting, in addition to the one that interrupted us. + additional: dict[int, ArrowDatabaseProtocol] = {} + try: + if best_effort: + additional = self._additional_flushes(prepared) + for queue in tuple(additional): + database = additional.pop(queue) + commit_best_effort( + run_error, + lambda: self._flush_attachment( + queue, database, prepared.writes + ), + ) + finally: + clear_run_rows(plan.to_run) + for queue, attachment in additional.items(): + self._retain_attachment_flush(queue, attachment, prepared.writes) raise + def _retain_run_attachments(self, writes: DatabaseWrites) -> None: + """Retain new attachment writes when cleanup cannot attempt their flush.""" + for queue, database in writes.databases().items(): + self._retain_attachment_flush( + queue, cast("ArrowDatabaseProtocol", database), writes + ) + + def _additional_flushes( + self, prepared: _PreparedRun + ) -> "dict[int, ArrowDatabaseProtocol]": + """Include unfinished attachment flushes outside the current owned sequence.""" + # Job nodes supply the full database protocol at all the tracked write sites. + current = cast("dict[int, ArrowDatabaseProtocol]", prepared.writes.databases()) + function = cast( + "dict[int, ArrowDatabaseProtocol]", prepared.writes.function_databases() + ) + retries: dict[int, ArrowDatabaseProtocol] = {} + for queue, retry in list(self._retry_attachment_flushes.items()): + if queue not in current and prepared.writes.replayed_durable_logs( + queue, retry.logs + ): + # A second handle already published the logs. A duplicate-only + # replay leaves this attachment's other pending writes alone. + del self._retry_attachment_flushes[queue] + else: + retries[queue] = retry.database + for queue, database in function.items(): + self._retry_attachment_flushes[queue] = _AttachmentRetry(database, {}) + return { + queue: database + for queue, database in (retries | current).items() + if not prepared.writes.covers(queue) + } + + def _flush_owned( + self, database: "ArrowDatabaseProtocol", writes: DatabaseWrites + ) -> None: + """Use the existing owned flush and retire any retry it now covers.""" + database.flush() + _ = self._retry_attachment_flushes.pop(writes.queue_id(database), None) + + def _flush_attachment( + self, queue: int, database: "ArrowDatabaseProtocol", writes: DatabaseWrites + ) -> None: + """Keep a failed whole flush eligible across source or database bindings.""" + try: + database.flush() + except BaseException: + self._retain_attachment_flush(queue, database, writes) + raise + _ = self._retry_attachment_flushes.pop(queue, None) + + def _retain_attachment_flush( + self, queue: int, database: "ArrowDatabaseProtocol", writes: DatabaseWrites + ) -> None: + """Remember an attachment that the run could not finish flushing.""" + previous = self._retry_attachment_flushes.get(queue) + if previous is not None and not previous.logs: + return + logs = writes.logs_to_replay(queue) + if previous is None: + self._retry_attachment_flushes[queue] = _AttachmentRetry( + database, logs or {} + ) + elif logs is not None: + if logs: + for path, ids in previous.logs.items(): + logs.setdefault(path, set()).update(ids) + self._retry_attachment_flushes[queue] = _AttachmentRetry(database, logs) + def _finish_run( self, prepared: "_PreparedRun", @@ -1738,6 +1902,7 @@ def _finish_run( + "have been stored." ) database = pipeline_db + additional: dict[int, ArrowDatabaseProtocol] = {} try: if not load_only and plan.to_run: # A load-only run writes nothing and commits nothing, and a run that @@ -1745,32 +1910,35 @@ def _finish_run( # Pending results gate the pipeline records that name them (ITL-1412), # across databases too, so no order of these flushes publishes a record # before its result. - database.flush() + additional = self._additional_flushes(prepared) + self._flush_owned(database, prepared.writes) database = result_db - database.flush() + self._flush_owned(database, prepared.writes) if self._result_database is not None: # A separate result database (ITL-1408): records the result flush # just released are still queued in the pipeline database. database = pipeline_db - database.flush() - except OrcapodDatabaseReadError as exc: - # A stored table could not be read: report the read failure itself. - exc.add_note(pending_note) - # A run whose commit failed did not complete: no node holds its rows. + self._flush_owned(database, prepared.writes) + # Node writes can target their own database objects (ITL-1383). + for queue in tuple(additional): + database = additional.pop(queue) + self._flush_attachment(queue, database, prepared.writes) + except BaseException as exc: + for queue, attachment in additional.items(): + self._retain_attachment_flush(queue, attachment, prepared.writes) clear_run_rows(plan.to_run) - raise - except Exception as exc: + if not isinstance(exc, Exception): + # Propagate an interruption with the unfinished flushes retained. + raise + if isinstance(exc, OrcapodDatabaseReadError): + # A stored table could not be read: report the read failure itself. + exc.add_note(pending_note) + raise 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 - except BaseException: - # An interruption (KeyboardInterrupt, cancellation) leaves the commit's - # outcome unknown: no node holds the run's rows. Re-raised unchanged. - clear_run_rows(plan.to_run) - raise # Mutate self in place. self._has_run = True diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index ea9df70b3..863241df2 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -39,6 +39,8 @@ ) from orcapod.core.provisional_pods import warn_provisional_pod from orcapod.core.tracker import DEFAULT_TRACKER_MANAGER +from orcapod.core.database_writes import track_completion_lookup, track_database_write +from orcapod.databases._pending_commits import record_completion_receipt from orcapod.errors import ( OrcapodDatabaseError, OrcapodDatabaseReadError, @@ -461,7 +463,8 @@ def _execute_side_effect_row( and table_path is not None ): try: - prior = pipeline_database.get_record_by_id(table_path, entry_id) + with track_completion_lookup(pipeline_database, table_path): + prior = pipeline_database.get_record_by_id(table_path, entry_id) except OrcapodDatabaseError as exc: # A failed lookup fails the run like a failed write: name pod and row. exc.add_context(node_label=pod_name, tag=tag.as_dict()) @@ -489,13 +492,14 @@ def _execute_side_effect_row( try: fn(**{ctx_arg_name: ctx, **data_dict}) if pipeline_database is not None and table_path is not None: - _write_invocation_row( - pipeline_database=pipeline_database, - table_path=table_path, - entry_id=entry_id, - run_id=run_id, - data_context_key=data_context_key, - ) + with record_completion_receipt(pod_config.track_completion): + _write_invocation_row( + pipeline_database=pipeline_database, + table_path=table_path, + entry_id=entry_id, + run_id=run_id, + data_context_key=data_context_key, + ) return (tag, data) except OrcapodDatabaseError as exc: # A failed database read or write fails the run, even under on_error="log". @@ -564,12 +568,13 @@ def _write_invocation_row( schema=_invocation_log_schema(), ) try: - pipeline_database.add_record( - table_path, - entry_id, - with_data_context(record, data_context_key), - skip_duplicates=True, - ) + with track_database_write(pipeline_database, table_path): + pipeline_database.add_record( + table_path, + entry_id, + with_data_context(record, data_context_key), + skip_duplicates=True, + ) except OrcapodDatabaseReadError: # The stored table could not be read: report the read failure itself. raise diff --git a/tests/test_databases/test_postgresql_connector_integration.py b/tests/test_databases/test_postgresql_connector_integration.py index 78132b437..92e7a1388 100644 --- a/tests/test_databases/test_postgresql_connector_integration.py +++ b/tests/test_databases/test_postgresql_connector_integration.py @@ -25,7 +25,7 @@ import os import uuid from collections.abc import Iterator -from typing import cast +from typing import Any, cast from unittest.mock import DEFAULT, patch import psycopg @@ -33,9 +33,17 @@ import pytest from psycopg import sql -from orcapod.databases import ConnectorArrowDatabase, PostgreSQLConnector +from orcapod import PipelineJob +from orcapod.databases import ( + ConnectorArrowDatabase, + InMemoryArrowDatabase, + PostgreSQLConnector, +) from orcapod.databases._sql_store import STORE_PATH_CATALOG -from orcapod.errors import OrcapodDatabaseError +from orcapod.errors import OrcapodDatabaseError, OrcapodDatabaseWriteError +from orcapod.invocation import InvocationContext +from orcapod.side_effects import SideEffectPod, SideEffectPodConfig +from orcapod.sources import DictSource from orcapod.types import ColumnInfo from tests.test_databases.test_sqlite_connector_integration import ( _check_catalog_operation, @@ -47,6 +55,7 @@ TIE_ORDERS, check_result_lookup_timestamp_tie, ) +from tests.test_pipeline.test_job_attached_database_commit import JOB_RUNNERS, _run # --------------------------------------------------------------------------- @@ -525,6 +534,382 @@ def test_schema_mismatch_raises(self, db: ConnectorArrowDatabase) -> None: # --------------------------------------------------------------------------- +def _attachment_job(attached: ConnectorArrowDatabase) -> PipelineJob: + """Log each delivery, including repeats, using the connector attachment.""" + + def deliver(ctx: InvocationContext, value: int) -> None: + pass + + source = DictSource( + data=[{"tag": 1, "value": 2}], + tag_columns=["tag"], + tag_only_columns=True, + source_id="input", + ) + job = PipelineJob(name="job", database=InMemoryArrowDatabase()) + with job: + _ = SideEffectPod(deliver, config=SideEffectPodConfig(track_completion=False))( + source, label="sink" + ) + job.nodes["sink"].attach_databases(pipeline_database=attached) + return job + + +@pytest.mark.postgres +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_delivery_appends_receipt_without_reading_history( + connector: PostgreSQLConnector, monkeypatch: pytest.MonkeyPatch, runner: str +) -> None: + """A warm untracked delivery needs only insert and record-ID privileges.""" + attached = ConnectorArrowDatabase(connector) + job = _attachment_job(attached) + await _run(job, runner) + attached.flush() + (path,) = attached.list_table_paths() + _, _, _, schema = connector.current_location() + role_name = f"writer_{uuid.uuid4().hex[:12]}" + role = sql.Identifier(role_name) + reads: list[str] = [] + fetched_rows = 0 + with psycopg.connect(_base_dsn(), autocommit=True) as admin: + (name,) = admin.execute( + "SELECT tablename FROM pg_tables WHERE schemaname = %s AND tablename <> %s", + (schema, STORE_PATH_CATALOG), + ).fetchone() or ("",) + assert name + table = sql.Identifier(schema, name) + catalog = sql.Identifier(schema, STORE_PATH_CATALOG) + + _ = admin.execute(sql.SQL("CREATE ROLE {}").format(role)) + try: + _ = admin.execute( + sql.SQL("GRANT USAGE, CREATE ON SCHEMA {} TO {}").format( + sql.Identifier(schema), role + ) + ) + _ = admin.execute( + sql.SQL("GRANT SELECT, INSERT ON {}, {} TO {}").format( + catalog, table, role + ) + ) + dsn = f"{_base_dsn()} options='-csearch_path={schema} -crole={role_name}'" + with PostgreSQLConnector(dsn) as writer: + store = ConnectorArrowDatabase(writer) + warmed = _attachment_job(store) + await _run(warmed, runner) + store.flush() + warmed.nodes["sink"].clear_cache() + warmed.bind( + sources={ + next(iter(warmed.sources)): DictSource( + data=[{"tag": 2, "value": 3}], + tag_columns=["tag"], + tag_only_columns=True, + source_id="input", + ) + } + ) + _ = admin.execute( + sql.SQL("REVOKE SELECT ON {} FROM {}").format(table, role) + ) + _ = admin.execute( + sql.SQL('GRANT SELECT ("__record_id") ON {} TO {}').format( + table, role + ) + ) + read = writer.iter_batches + + def observe_read( + query: str, params: Any = None, batch_size: int = 1000 + ) -> Iterator[pa.RecordBatch]: + nonlocal fetched_rows + if name in query: + reads.append(query) + for batch in read(query, params, batch_size): + if name in query: + fetched_rows += batch.num_rows + yield batch + + with monkeypatch.context() as patch: + patch.setattr(writer, "iter_batches", observe_read) + await _run(warmed, runner) + assert reads == [] + assert fetched_rows == 0 + (count,) = admin.execute( + sql.SQL("SELECT count(*) FROM {}").format(table) + ).fetchone() or (0,) + assert count == 2 + finally: + _ = admin.execute(sql.SQL("DROP OWNED BY {}").format(role)) + _ = admin.execute(sql.SQL("DROP ROLE {}").format(role)) + assert attached.get_all_records(path) is not None + + +@pytest.mark.postgres +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +@pytest.mark.parametrize("failure", ["missing_create", "one_connection"]) +async def test_postgresql_attachment_receipt_retry( + connector: PostgreSQLConnector, + monkeypatch: pytest.MonkeyPatch, + runner: str, + failure: str, +) -> None: + """A rolled-back flush keeps the receipt, and a durable replay needs no probe.""" + delivered: list[int] = [] + + def deliver(ctx: InvocationContext, value: int) -> None: + delivered.append(value) + + def job_for(store: ConnectorArrowDatabase, *values: int) -> PipelineJob: + source = DictSource( + data=[{"tag": value, "value": value} for value in values], + tag_columns=["tag"], + tag_only_columns=True, + source_id="input", + ) + job = PipelineJob(name="job", database=InMemoryArrowDatabase()) + with job: + _ = SideEffectPod(deliver)(source, label="sink") + job.nodes["sink"].attach_databases(pipeline_database=store) + return job + + def fail_flush() -> None: + raise OSError("temporary flush failure") + + _, _, _, schema = connector.current_location() + schema_name = sql.Identifier(schema) + role = f"writer_{uuid.uuid4().hex[:12]}" + role_name = sql.Identifier(role) + peer = ConnectorArrowDatabase(connector) + base_dsn = _base_dsn() + one_connection = failure == "one_connection" + with psycopg.connect(base_dsn, autocommit=True) as admin: + _ = admin.execute( + sql.SQL( + "CREATE ROLE {} LOGIN PASSWORD 'test_writer' CONNECTION LIMIT {}" + ).format(role_name, sql.Literal(1 if one_connection else -1)) + ) + try: + if not one_connection: + await _run(job_for(peer, 0), runner) + delivered.clear() + _ = admin.execute( + sql.SQL("GRANT USAGE ON SCHEMA {} TO {}").format(schema_name, role_name) + ) + _ = admin.execute( + sql.SQL("GRANT SELECT, INSERT ON ALL TABLES IN SCHEMA {} TO {}").format( + schema_name, role_name + ) + ) + if one_connection: + _ = admin.execute( + sql.SQL("GRANT CREATE ON SCHEMA {} TO {}").format( + schema_name, role_name + ) + ) + + dsn = f"{base_dsn} user={role} password=test_writer options=-csearch_path={schema}" + with PostgreSQLConnector(dsn) as writer: + attached = ConnectorArrowDatabase(writer) + job = job_for(attached, 1, 2) + with monkeypatch.context() as scoped: + if one_connection: + scoped.setattr(attached, "flush", fail_flush) + with pytest.raises(OrcapodDatabaseWriteError) as error: + await _run(job, runner) + expected_error = ( + OSError if one_connection else psycopg.errors.InsufficientPrivilege + ) + assert isinstance(error.value.__cause__, expected_error) + assert delivered == [1, 2] + (path,) = attached.list_table_paths() + receipts = attached.get_all_records(path, record_id_column="receipt_id") + expected_count = 2 if one_connection else 3 + assert receipts is not None and receipts.num_rows == expected_count + + if one_connection: + peer.add_records( + path, + receipts, + record_id_column="receipt_id", + skip_duplicates=True, + flush=True, + ) + _ = admin.execute( + sql.SQL( + "GRANT SELECT, INSERT ON ALL TABLES IN SCHEMA {} TO {}" + ).format(schema_name, role_name) + ) + attached.add_record( + ("unrelated",), b"extra", pa.table({"value": [10]}) + ) + else: + committed = peer.get_all_records(path) + assert committed is not None and committed.num_rows == 1 + _ = admin.execute( + sql.SQL("GRANT CREATE ON SCHEMA {} TO {}").format( + schema_name, role_name + ) + ) + + job.nodes["sink"].clear_cache() + await _run(job, runner) + assert delivered == [1, 2] + committed = peer.get_all_records(path) + assert committed is not None and committed.num_rows == expected_count + if one_connection: + assert not peer.table_exists(("unrelated",)) + attached.flush() + assert peer.table_exists(("unrelated",)) + finally: + _ = admin.execute(sql.SQL("DROP OWNED BY {}").format(role_name)) + _ = admin.execute(sql.SQL("DROP ROLE {}").format(role_name)) + + +@pytest.mark.postgres +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_attachment_receipt_replay_checks_the_writer_backend( + connector: PostgreSQLConnector, + monkeypatch: pytest.MonkeyPatch, + runner: str, +) -> None: + """A proxy endpoint can route two open connections to different backends.""" + delivered: list[int] = [] + + def deliver(ctx: InvocationContext, value: int) -> None: + delivered.append(value) + + def job_for(value: int) -> PipelineJob: + source = DictSource( + data=[{"tag": value, "value": value}], + tag_columns=["tag"], + tag_only_columns=True, + source_id="input", + ) + job = PipelineJob(name="job", database=InMemoryArrowDatabase()) + with job: + _ = SideEffectPod(deliver)(source, label="sink") + job.nodes["sink"].attach_databases(pipeline_database=attached) + return job + + # Model the libpq endpoint reported by a routing proxy. The actual + # connectors still have independent tables and transactions. + monkeypatch.setattr( + PostgreSQLConnector, "_receipt_store_identity", lambda _: ("proxy", 5432, "db") + ) + attached = ConnectorArrowDatabase(connector) + await _run(job_for(0), runner) + (path,) = attached.list_table_paths() + job = job_for(1) + with patch.object( + attached, "flush", side_effect=OSError("temporary flush failure") + ): + with pytest.raises(OrcapodDatabaseWriteError): + await _run(job, runner) + receipts = attached.get_all_records(path, record_id_column="receipt_id") + assert receipts is not None and receipts.num_rows == 2 + + _, _, _, schema = connector.current_location() + other_name = f"test_{uuid.uuid4().hex[:12]}" + other_database = sql.Identifier(other_name) + base_dsn = _base_dsn() + other_dsn = f"{base_dsn} dbname={other_name} options=-csearch_path={schema}" + with psycopg.connect(base_dsn, autocommit=True) as admin: + _ = admin.execute(sql.SQL("CREATE DATABASE {}").format(other_database)) + try: + with psycopg.connect(other_dsn, autocommit=True) as other_admin: + _ = other_admin.execute( + sql.SQL("CREATE SCHEMA {}").format(sql.Identifier(schema)) + ) + with PostgreSQLConnector(other_dsn) as other_connector: + peer = ConnectorArrowDatabase(other_connector) + peer.add_records( + path, receipts, record_id_column="receipt_id", flush=True + ) + + # Use a fresh queue to verify what is actually durable on the writer. + committed = ConnectorArrowDatabase(connector) + rows = committed.get_all_records(path) + assert rows is not None and rows.num_rows == 1 + job.nodes["sink"].clear_cache() + await _run(job, runner) + rows = committed.get_all_records(path) + assert rows is not None and rows.num_rows == 2 + assert delivered == [0, 1] + finally: + _ = admin.execute(sql.SQL("DROP DATABASE {}").format(other_database)) + + +@pytest.mark.postgres +def test_attachment_retry_survives_replay_in_a_different_schema( + connector: PostgreSQLConnector, monkeypatch: pytest.MonkeyPatch +) -> None: + """Durable IDs in the new schema do not publish the same IDs in the old one.""" + _, _, _, original = connector.current_location() + alternate = f"test_{uuid.uuid4().hex[:12]}" + base_dsn = _base_dsn() + attached = ConnectorArrowDatabase(connector) + job = _attachment_job(attached) + sink = job.nodes["sink"] + + def fail_flush() -> None: + raise OSError("temporary attachment flush failure") + + with monkeypatch.context() as patch: + patch.setattr(attached, "flush", fail_flush) + with pytest.raises(OrcapodDatabaseWriteError) as first_error: + _ = job.run() + assert isinstance(first_error.value.__cause__, OSError), repr( + first_error.value.__cause__ + ) + (path,) = attached.list_table_paths() + + with psycopg.connect(base_dsn, autocommit=True) as admin: + _ = admin.execute(sql.SQL("CREATE SCHEMA {}").format(sql.Identifier(alternate))) + try: + with PostgreSQLConnector( + f"{base_dsn} options=-csearch_path={alternate}" + ) as other: + sink.attach_databases( + pipeline_database=ConnectorArrowDatabase(other), + ) + sink.run() + connection = connector._require_open() + _ = connection.execute( + sql.SQL("SET search_path TO {}").format(sql.Identifier(alternate)) + ) + connection.commit() + sink.attach_databases(pipeline_database=attached) + sink.clear_cache() + with pytest.raises(OrcapodDatabaseWriteError, match="switch back"): + _ = job.run() + _ = connection.execute( + sql.SQL("SET search_path TO {}").format(sql.Identifier(original)) + ) + connection.commit() + # The original batch commits first. The connector may also be + # holding a duplicate upsert under the alternate schema. + with pytest.raises(OrcapodDatabaseWriteError, match="switch back"): + _ = job.run() + with PostgreSQLConnector( + f"{base_dsn} options=-csearch_path={original}" + ) as reopened: + committed = ConnectorArrowDatabase(reopened).get_all_records(path) + assert committed is not None and committed.num_rows == 1 + finally: + connection = connector._require_open() + _ = connection.execute( + sql.SQL("SET search_path TO {}").format(sql.Identifier(original)) + ) + connection.commit() + _ = admin.execute( + sql.SQL("DROP SCHEMA {} CASCADE").format(sql.Identifier(alternate)) + ) + + @pytest.mark.postgres @pytest.mark.parametrize( "arrow_type, values", diff --git a/tests/test_pipeline/fixtures/attachment_store_io.json b/tests/test_pipeline/fixtures/attachment_store_io.json new file mode 100644 index 000000000..5acf594e2 --- /dev/null +++ b/tests/test_pipeline/fixtures/attachment_store_io.json @@ -0,0 +1,796 @@ +{ + "cases": { + "memory": { + "delivery": [ + { + "rows": {}, + "statements": {} + }, + { + "rows": {}, + "statements": {} + } + ], + "duplicate_operator": [ + { + "rows": {}, + "statements": {} + }, + { + "rows": {}, + "statements": {} + } + ], + "failed_flush": [ + { + "rows": {}, + "statements": {} + }, + { + "rows": {}, + "statements": {} + } + ], + "failed_flush_then_fresh_receipt": [ + { + "rows": {}, + "statements": {} + }, + { + "rows": {}, + "statements": {} + } + ], + "forwarding_attachment": [ + { + "rows": {}, + "statements": { + "get_all_records": 1 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "forwarding_load_only": [ + { + "rows": {}, + "statements": {} + }, + { + "rows": {}, + "statements": {} + } + ], + "forwarding_store": [ + { + "rows": {}, + "statements": { + "get_all_records": 1 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "function": [ + { + "rows": {}, + "statements": { + "get_all_records": 1, + "get_records_with_column_value": 4, + "get_table_schema": 1 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "load_only": [ + { + "rows": {}, + "statements": {} + }, + { + "rows": {}, + "statements": {} + } + ], + "pending_replay": [ + { + "rows": { + "get_record_by_id": 2 + }, + "statements": { + "get_record_by_id": 2 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "rebind": [ + { + "rows": {}, + "statements": {} + }, + { + "rows": {}, + "statements": {} + } + ], + "replay": [ + { + "rows": { + "get_record_by_id": 2 + }, + "statements": { + "get_record_by_id": 2 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "wrappers": [ + { + "rows": {}, + "statements": { + "get_all_records": 1 + } + }, + { + "rows": {}, + "statements": {} + } + ] + }, + "postgres": { + "delivery": [ + { + "rows": { + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 3, + "SELECT ns.nspname, ns.oid, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' WHERE ns.nspname = COALESCE(%s, current_schema())": 2, + "SELECT paths.table_name, paths.entry_value, paths.layout_version, physical.oid IS NOT NULL FROM \"schema\".\"orcapod.store_paths.v1\" AS paths LEFT JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name AND physical.relnamespace = %s AND physical.relkind IN ('r', 'p') WHERE paths.table_name = %s AND paths.entry_kind = %s AND paths.entry_name = ''": 1, + "SELECT paths.table_name, paths.entry_value, paths.layout_version, physical.oid IS NOT NULL FROM \"schema\".\"orcapod.store_paths.v1\" AS paths LEFT JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name AND physical.relnamespace = %s AND physical.relkind IN ('r', 'p') WHERE paths.table_name LIKE %s ESCAPE '!' AND paths.entry_kind = %s AND paths.entry_name = ''": 1 + }, + "statements": { + "BEGIN": 5, + "DEALLOCATE ALL": 1, + "ROLLBACK": 5, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 3, + "SELECT ns.nspname, ns.oid, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' WHERE ns.nspname = COALESCE(%s, current_schema())": 2, + "SELECT paths.table_name, paths.entry_value, paths.layout_version, physical.oid IS NOT NULL FROM \"schema\".\"orcapod.store_paths.v1\" AS paths LEFT JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name AND physical.relnamespace = %s AND physical.relkind IN ('r', 'p') WHERE paths.table_name = %s AND paths.entry_kind = %s AND paths.entry_name = ''": 1, + "SELECT paths.table_name, paths.entry_value, paths.layout_version, physical.oid IS NOT NULL FROM \"schema\".\"orcapod.store_paths.v1\" AS paths LEFT JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name AND physical.relnamespace = %s AND physical.relkind IN ('r', 'p') WHERE paths.table_name LIKE %s ESCAPE '!' AND paths.entry_kind = %s AND paths.entry_name = ''": 1 + } + }, + { + "rows": { + "SELECT column_name, data_type, udt_name, is_nullable FROM information_schema.columns WHERE table_schema = COALESCE(%s, current_schema()) AND table_name = %s ORDER BY ordinal_position": 5, + "SELECT entry_value, layout_version FROM \"schema\".\"orcapod.store_paths.v1\" WHERE table_name = %s AND entry_kind = %s AND entry_name = ''": 1, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 1, + "SELECT oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), pg_advisory_xact_lock(%s, oid::integer) FROM pg_catalog.pg_namespace WHERE nspname = %s": 1, + "SELECT rel.relkind FROM pg_catalog.pg_class AS rel JOIN pg_catalog.pg_namespace AS ns ON ns.oid = rel.relnamespace WHERE ns.nspname = %s AND rel.relname = %s": 1 + }, + "statements": { + "BEGIN": 2, + "COMMIT": 1, + "CREATE TABLE IF NOT EXISTS \"schema\".\"o1_attached_side_effects__deli_e5841eedf17116508df160ee00b88b05\" ( \"__record_id\" BYTEA PRIMARY KEY, \"entry_id\" BYTEA, \"pipeline_run_id\" TEXT, \"executed_at\" TIMESTAMPTZ, \"__data_context\" TEXT NOT NULL )": 1, + "CREATE TABLE IF NOT EXISTS \"schema\".\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 1, + "INSERT INTO \"schema\".\"o1_attached_side_effects__deli_e5841eedf17116508df160ee00b88b05\" (\"__record_id\", \"entry_id\", \"pipeline_run_id\", \"executed_at\", \"__data_context\") VALUES (%s, %s, %s, %s, %s) ON CONFLICT (\"__record_id\") DO NOTHING": 1, + "RELEASE \"_pg3_1\"": 1, + "ROLLBACK": 1, + "ROLLBACK TO \"_pg3_1\"": 1, + "SAVEPOINT \"_pg3_1\"": 1, + "SELECT column_name, data_type, udt_name, is_nullable FROM information_schema.columns WHERE table_schema = COALESCE(%s, current_schema()) AND table_name = %s ORDER BY ordinal_position": 1, + "SELECT entry_value, layout_version FROM \"schema\".\"orcapod.store_paths.v1\" WHERE table_name = %s AND entry_kind = %s AND entry_name = ''": 1, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 1, + "SELECT oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), pg_advisory_xact_lock(%s, oid::integer) FROM pg_catalog.pg_namespace WHERE nspname = %s": 1, + "SELECT rel.relkind FROM pg_catalog.pg_class AS rel JOIN pg_catalog.pg_namespace AS ns ON ns.oid = rel.relnamespace WHERE ns.nspname = %s AND rel.relname = %s": 1 + } + } + ], + "duplicate_operator": [ + { + "rows": { + "SELECT entry_value, layout_version FROM \"schema\".\"orcapod.store_paths.v1\" WHERE table_name = %s AND entry_kind = %s AND entry_name = ''": 0, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 1, + "SELECT oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), pg_advisory_xact_lock(%s, oid::integer) FROM pg_catalog.pg_namespace WHERE nspname = %s": 1, + "SELECT rel.relkind FROM pg_catalog.pg_class AS rel JOIN pg_catalog.pg_namespace AS ns ON ns.oid = rel.relnamespace WHERE ns.nspname = %s AND rel.relname = %s": 0 + }, + "statements": { + "BEGIN": 2, + "COMMIT": 1, + "CREATE TABLE IF NOT EXISTS \"schema\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" ( \"__record_id\" BYTEA PRIMARY KEY, \"value\" BIGINT )": 1, + "CREATE TABLE IF NOT EXISTS \"schema\".\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 1, + "INSERT INTO \"schema\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" (\"__record_id\", \"value\") VALUES (%s, %s) ON CONFLICT (\"__record_id\") DO UPDATE SET \"value\" = EXCLUDED.\"value\"": 1, + "INSERT INTO \"schema\".\"orcapod.store_paths.v1\" (table_name, entry_kind, entry_name, entry_value, layout_version) VALUES (%s, %s, '', %s, %s)": 1, + "ROLLBACK": 1, + "SELECT entry_value, layout_version FROM \"schema\".\"orcapod.store_paths.v1\" WHERE table_name = %s AND entry_kind = %s AND entry_name = ''": 1, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 1, + "SELECT oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), pg_advisory_xact_lock(%s, oid::integer) FROM pg_catalog.pg_namespace WHERE nspname = %s": 1, + "SELECT rel.relkind FROM pg_catalog.pg_class AS rel JOIN pg_catalog.pg_namespace AS ns ON ns.oid = rel.relnamespace WHERE ns.nspname = %s AND rel.relname = %s": 1 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "failed_flush": [ + { + "rows": { + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 3, + "SELECT ns.nspname, ns.oid, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' WHERE ns.nspname = COALESCE(%s, current_schema())": 2, + "SELECT paths.table_name, paths.entry_value, paths.layout_version, physical.oid IS NOT NULL FROM \"schema\".\"orcapod.store_paths.v1\" AS paths LEFT JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name AND physical.relnamespace = %s AND physical.relkind IN ('r', 'p') WHERE paths.table_name = %s AND paths.entry_kind = %s AND paths.entry_name = ''": 1, + "SELECT paths.table_name, paths.entry_value, paths.layout_version, physical.oid IS NOT NULL FROM \"schema\".\"orcapod.store_paths.v1\" AS paths LEFT JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name AND physical.relnamespace = %s AND physical.relkind IN ('r', 'p') WHERE paths.table_name LIKE %s ESCAPE '!' AND paths.entry_kind = %s AND paths.entry_name = ''": 1 + }, + "statements": { + "BEGIN": 5, + "DEALLOCATE ALL": 1, + "ROLLBACK": 5, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 3, + "SELECT ns.nspname, ns.oid, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' WHERE ns.nspname = COALESCE(%s, current_schema())": 2, + "SELECT paths.table_name, paths.entry_value, paths.layout_version, physical.oid IS NOT NULL FROM \"schema\".\"orcapod.store_paths.v1\" AS paths LEFT JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name AND physical.relnamespace = %s AND physical.relkind IN ('r', 'p') WHERE paths.table_name = %s AND paths.entry_kind = %s AND paths.entry_name = ''": 1, + "SELECT paths.table_name, paths.entry_value, paths.layout_version, physical.oid IS NOT NULL FROM \"schema\".\"orcapod.store_paths.v1\" AS paths LEFT JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name AND physical.relnamespace = %s AND physical.relkind IN ('r', 'p') WHERE paths.table_name LIKE %s ESCAPE '!' AND paths.entry_kind = %s AND paths.entry_name = ''": 1 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "failed_flush_then_fresh_receipt": [ + { + "rows": { + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 3, + "SELECT ns.nspname, ns.oid, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' WHERE ns.nspname = COALESCE(%s, current_schema())": 2, + "SELECT paths.table_name, paths.entry_value, paths.layout_version, physical.oid IS NOT NULL FROM \"schema\".\"orcapod.store_paths.v1\" AS paths LEFT JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name AND physical.relnamespace = %s AND physical.relkind IN ('r', 'p') WHERE paths.table_name = %s AND paths.entry_kind = %s AND paths.entry_name = ''": 1, + "SELECT paths.table_name, paths.entry_value, paths.layout_version, physical.oid IS NOT NULL FROM \"schema\".\"orcapod.store_paths.v1\" AS paths LEFT JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name AND physical.relnamespace = %s AND physical.relkind IN ('r', 'p') WHERE paths.table_name LIKE %s ESCAPE '!' AND paths.entry_kind = %s AND paths.entry_name = ''": 1 + }, + "statements": { + "BEGIN": 5, + "ROLLBACK": 5, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 3, + "SELECT ns.nspname, ns.oid, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' WHERE ns.nspname = COALESCE(%s, current_schema())": 2, + "SELECT paths.table_name, paths.entry_value, paths.layout_version, physical.oid IS NOT NULL FROM \"schema\".\"orcapod.store_paths.v1\" AS paths LEFT JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name AND physical.relnamespace = %s AND physical.relkind IN ('r', 'p') WHERE paths.table_name = %s AND paths.entry_kind = %s AND paths.entry_name = ''": 1, + "SELECT paths.table_name, paths.entry_value, paths.layout_version, physical.oid IS NOT NULL FROM \"schema\".\"orcapod.store_paths.v1\" AS paths LEFT JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name AND physical.relnamespace = %s AND physical.relkind IN ('r', 'p') WHERE paths.table_name LIKE %s ESCAPE '!' AND paths.entry_kind = %s AND paths.entry_name = ''": 1 + } + }, + { + "rows": { + "SELECT column_name, data_type, udt_name, is_nullable FROM information_schema.columns WHERE table_schema = COALESCE(%s, current_schema()) AND table_name = %s ORDER BY ordinal_position": 5, + "SELECT entry_value, layout_version FROM \"schema\".\"orcapod.store_paths.v1\" WHERE table_name = %s AND entry_kind = %s AND entry_name = ''": 1, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 1, + "SELECT oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), pg_advisory_xact_lock(%s, oid::integer) FROM pg_catalog.pg_namespace WHERE nspname = %s": 1, + "SELECT rel.relkind FROM pg_catalog.pg_class AS rel JOIN pg_catalog.pg_namespace AS ns ON ns.oid = rel.relnamespace WHERE ns.nspname = %s AND rel.relname = %s": 1 + }, + "statements": { + "BEGIN": 2, + "COMMIT": 1, + "CREATE TABLE IF NOT EXISTS \"schema\".\"o1_attached_side_effects__deli_e5841eedf17116508df160ee00b88b05\" ( \"__record_id\" BYTEA PRIMARY KEY, \"entry_id\" BYTEA, \"pipeline_run_id\" TEXT, \"executed_at\" TIMESTAMPTZ, \"__data_context\" TEXT NOT NULL )": 1, + "CREATE TABLE IF NOT EXISTS \"schema\".\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 1, + "INSERT INTO \"schema\".\"o1_attached_side_effects__deli_e5841eedf17116508df160ee00b88b05\" (\"__record_id\", \"entry_id\", \"pipeline_run_id\", \"executed_at\", \"__data_context\") VALUES (%s, %s, %s, %s, %s) ON CONFLICT (\"__record_id\") DO NOTHING": 2, + "RELEASE \"_pg3_1\"": 1, + "ROLLBACK": 1, + "ROLLBACK TO \"_pg3_1\"": 1, + "SAVEPOINT \"_pg3_1\"": 1, + "SELECT column_name, data_type, udt_name, is_nullable FROM information_schema.columns WHERE table_schema = COALESCE(%s, current_schema()) AND table_name = %s ORDER BY ordinal_position": 1, + "SELECT entry_value, layout_version FROM \"schema\".\"orcapod.store_paths.v1\" WHERE table_name = %s AND entry_kind = %s AND entry_name = ''": 1, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 1, + "SELECT oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), pg_advisory_xact_lock(%s, oid::integer) FROM pg_catalog.pg_namespace WHERE nspname = %s": 1, + "SELECT rel.relkind FROM pg_catalog.pg_class AS rel JOIN pg_catalog.pg_namespace AS ns ON ns.oid = rel.relnamespace WHERE ns.nspname = %s AND rel.relname = %s": 1 + } + } + ], + "forwarding_attachment": [ + { + "rows": { + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 6, + "SELECT ns.nspname, ns.oid, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' WHERE ns.nspname = COALESCE(%s, current_schema())": 4 + }, + "statements": { + "BEGIN": 10, + "ROLLBACK": 10, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 6, + "SELECT ns.nspname, ns.oid, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' WHERE ns.nspname = COALESCE(%s, current_schema())": 4 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "forwarding_load_only": [ + { + "rows": {}, + "statements": {} + }, + { + "rows": {}, + "statements": {} + } + ], + "forwarding_store": [ + { + "rows": { + "SELECT entry_value, layout_version FROM \"schema\".\"orcapod.store_paths.v1\" WHERE table_name = %s AND entry_kind = %s AND entry_name = ''": 0, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 7, + "SELECT ns.nspname, ns.oid, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' WHERE ns.nspname = COALESCE(%s, current_schema())": 4, + "SELECT oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), pg_advisory_xact_lock(%s, oid::integer) FROM pg_catalog.pg_namespace WHERE nspname = %s": 1, + "SELECT rel.relkind FROM pg_catalog.pg_class AS rel JOIN pg_catalog.pg_namespace AS ns ON ns.oid = rel.relnamespace WHERE ns.nspname = %s AND rel.relname = %s": 0 + }, + "statements": { + "BEGIN": 12, + "COMMIT": 1, + "CREATE TABLE IF NOT EXISTS \"schema\".\"o1_sibling_side_effects__deliv_502547eb12adf57616baa1aa066d9ee3\" ( \"__record_id\" BYTEA PRIMARY KEY, \"entry_id\" BYTEA, \"pipeline_run_id\" TEXT, \"executed_at\" TIMESTAMPTZ, \"__data_context\" TEXT NOT NULL )": 1, + "CREATE TABLE IF NOT EXISTS \"schema\".\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 1, + "INSERT INTO \"schema\".\"o1_sibling_side_effects__deliv_502547eb12adf57616baa1aa066d9ee3\" (\"__record_id\", \"entry_id\", \"pipeline_run_id\", \"executed_at\", \"__data_context\") VALUES (%s, %s, %s, %s, %s) ON CONFLICT (\"__record_id\") DO NOTHING": 2, + "INSERT INTO \"schema\".\"orcapod.store_paths.v1\" (table_name, entry_kind, entry_name, entry_value, layout_version) VALUES (%s, %s, '', %s, %s)": 1, + "ROLLBACK": 11, + "SELECT entry_value, layout_version FROM \"schema\".\"orcapod.store_paths.v1\" WHERE table_name = %s AND entry_kind = %s AND entry_name = ''": 1, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 7, + "SELECT ns.nspname, ns.oid, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' WHERE ns.nspname = COALESCE(%s, current_schema())": 4, + "SELECT oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), pg_advisory_xact_lock(%s, oid::integer) FROM pg_catalog.pg_namespace WHERE nspname = %s": 1, + "SELECT rel.relkind FROM pg_catalog.pg_class AS rel JOIN pg_catalog.pg_namespace AS ns ON ns.oid = rel.relnamespace WHERE ns.nspname = %s AND rel.relname = %s": 1 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "function": [ + { + "rows": { + "SELECT entry_value, layout_version FROM \"schema\".\"orcapod.store_paths.v1\" WHERE table_name = %s AND entry_kind = %s AND entry_name = ''": 0, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 1, + "SELECT oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), pg_advisory_xact_lock(%s, oid::integer) FROM pg_catalog.pg_namespace WHERE nspname = %s": 1, + "SELECT rel.relkind FROM pg_catalog.pg_class AS rel JOIN pg_catalog.pg_namespace AS ns ON ns.oid = rel.relnamespace WHERE ns.nspname = %s AND rel.relname = %s": 0 + }, + "statements": { + "BEGIN": 2, + "COMMIT": 1, + "CREATE TABLE IF NOT EXISTS \"schema\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" ( \"__record_id\" BYTEA PRIMARY KEY, \"value\" BIGINT )": 1, + "CREATE TABLE IF NOT EXISTS \"schema\".\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 1, + "INSERT INTO \"schema\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" (\"__record_id\", \"value\") VALUES (%s, %s) ON CONFLICT (\"__record_id\") DO UPDATE SET \"value\" = EXCLUDED.\"value\"": 1, + "INSERT INTO \"schema\".\"orcapod.store_paths.v1\" (table_name, entry_kind, entry_name, entry_value, layout_version) VALUES (%s, %s, '', %s, %s)": 1, + "ROLLBACK": 1, + "SELECT entry_value, layout_version FROM \"schema\".\"orcapod.store_paths.v1\" WHERE table_name = %s AND entry_kind = %s AND entry_name = ''": 1, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 1, + "SELECT oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), pg_advisory_xact_lock(%s, oid::integer) FROM pg_catalog.pg_namespace WHERE nspname = %s": 1, + "SELECT rel.relkind FROM pg_catalog.pg_class AS rel JOIN pg_catalog.pg_namespace AS ns ON ns.oid = rel.relnamespace WHERE ns.nspname = %s AND rel.relname = %s": 1, + "get_all_records": 1, + "get_records_with_column_value": 4, + "get_table_schema": 1 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "load_only": [ + { + "rows": {}, + "statements": {} + }, + { + "rows": {}, + "statements": {} + } + ], + "pending_replay": [ + { + "rows": { + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 3, + "SELECT ns.nspname, ns.oid, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' WHERE ns.nspname = COALESCE(%s, current_schema())": 3 + }, + "statements": { + "BEGIN": 6, + "ROLLBACK": 6, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 3, + "SELECT ns.nspname, ns.oid, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' WHERE ns.nspname = COALESCE(%s, current_schema())": 3 + } + }, + { + "rows": { + "SELECT entry_value, layout_version FROM \"schema\".\"orcapod.store_paths.v1\" WHERE table_name = %s AND entry_kind = %s AND entry_name = ''": 0, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 1, + "SELECT oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), pg_advisory_xact_lock(%s, oid::integer) FROM pg_catalog.pg_namespace WHERE nspname = %s": 1, + "SELECT rel.relkind FROM pg_catalog.pg_class AS rel JOIN pg_catalog.pg_namespace AS ns ON ns.oid = rel.relnamespace WHERE ns.nspname = %s AND rel.relname = %s": 0 + }, + "statements": { + "BEGIN": 2, + "COMMIT": 1, + "CREATE TABLE IF NOT EXISTS \"schema\".\"o1_attached_side_effects__deli_afb3b24a6538f4bb14f2a151291c9f57\" ( \"__record_id\" BYTEA PRIMARY KEY, \"entry_id\" BYTEA, \"pipeline_run_id\" TEXT, \"executed_at\" TIMESTAMPTZ, \"__data_context\" TEXT NOT NULL )": 1, + "CREATE TABLE IF NOT EXISTS \"schema\".\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 1, + "INSERT INTO \"schema\".\"o1_attached_side_effects__deli_afb3b24a6538f4bb14f2a151291c9f57\" (\"__record_id\", \"entry_id\", \"pipeline_run_id\", \"executed_at\", \"__data_context\") VALUES (%s, %s, %s, %s, %s) ON CONFLICT (\"__record_id\") DO NOTHING": 2, + "INSERT INTO \"schema\".\"orcapod.store_paths.v1\" (table_name, entry_kind, entry_name, entry_value, layout_version) VALUES (%s, %s, '', %s, %s)": 1, + "ROLLBACK": 1, + "SELECT entry_value, layout_version FROM \"schema\".\"orcapod.store_paths.v1\" WHERE table_name = %s AND entry_kind = %s AND entry_name = ''": 1, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 1, + "SELECT oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), pg_advisory_xact_lock(%s, oid::integer) FROM pg_catalog.pg_namespace WHERE nspname = %s": 1, + "SELECT rel.relkind FROM pg_catalog.pg_class AS rel JOIN pg_catalog.pg_namespace AS ns ON ns.oid = rel.relnamespace WHERE ns.nspname = %s AND rel.relname = %s": 1 + } + } + ], + "rebind": [ + { + "rows": { + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 6, + "SELECT ns.nspname, ns.oid, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' WHERE ns.nspname = COALESCE(%s, current_schema())": 4 + }, + "statements": { + "BEGIN": 10, + "ROLLBACK": 10, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 6, + "SELECT ns.nspname, ns.oid, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' WHERE ns.nspname = COALESCE(%s, current_schema())": 4 + } + }, + { + "rows": { + "SELECT entry_value, layout_version FROM \"schema\".\"orcapod.store_paths.v1\" WHERE table_name = %s AND entry_kind = %s AND entry_name = ''": 0, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 2, + "SELECT oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), pg_advisory_xact_lock(%s, oid::integer) FROM pg_catalog.pg_namespace WHERE nspname = %s": 2, + "SELECT rel.relkind FROM pg_catalog.pg_class AS rel JOIN pg_catalog.pg_namespace AS ns ON ns.oid = rel.relnamespace WHERE ns.nspname = %s AND rel.relname = %s": 0 + }, + "statements": { + "BEGIN": 4, + "COMMIT": 2, + "CREATE TABLE IF NOT EXISTS \"schema\".\"o1_attached_side_effects__deli_e5841eedf17116508df160ee00b88b05\" ( \"__record_id\" BYTEA PRIMARY KEY, \"entry_id\" BYTEA, \"pipeline_run_id\" TEXT, \"executed_at\" TIMESTAMPTZ, \"__data_context\" TEXT NOT NULL )": 1, + "CREATE TABLE IF NOT EXISTS \"schema\".\"o1_other_side_effects__deliver_8e9915a6d0a8973841e683da10828610\" ( \"__record_id\" BYTEA PRIMARY KEY, \"entry_id\" BYTEA, \"pipeline_run_id\" TEXT, \"executed_at\" TIMESTAMPTZ, \"__data_context\" TEXT NOT NULL )": 1, + "CREATE TABLE IF NOT EXISTS \"schema\".\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 2, + "DEALLOCATE ALL": 1, + "INSERT INTO \"schema\".\"o1_attached_side_effects__deli_e5841eedf17116508df160ee00b88b05\" (\"__record_id\", \"entry_id\", \"pipeline_run_id\", \"executed_at\", \"__data_context\") VALUES (%s, %s, %s, %s, %s) ON CONFLICT (\"__record_id\") DO NOTHING": 2, + "INSERT INTO \"schema\".\"o1_other_side_effects__deliver_8e9915a6d0a8973841e683da10828610\" (\"__record_id\", \"entry_id\", \"pipeline_run_id\", \"executed_at\", \"__data_context\") VALUES (%s, %s, %s, %s, %s) ON CONFLICT (\"__record_id\") DO NOTHING": 2, + "INSERT INTO \"schema\".\"orcapod.store_paths.v1\" (table_name, entry_kind, entry_name, entry_value, layout_version) VALUES (%s, %s, '', %s, %s)": 2, + "ROLLBACK": 2, + "SELECT entry_value, layout_version FROM \"schema\".\"orcapod.store_paths.v1\" WHERE table_name = %s AND entry_kind = %s AND entry_name = ''": 2, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 2, + "SELECT oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), pg_advisory_xact_lock(%s, oid::integer) FROM pg_catalog.pg_namespace WHERE nspname = %s": 2, + "SELECT rel.relkind FROM pg_catalog.pg_class AS rel JOIN pg_catalog.pg_namespace AS ns ON ns.oid = rel.relnamespace WHERE ns.nspname = %s AND rel.relname = %s": 2 + } + } + ], + "replay": [ + { + "rows": { + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 3, + "SELECT ns.nspname, ns.oid, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' WHERE ns.nspname = COALESCE(%s, current_schema())": 3, + "SELECT paths.table_name, paths.entry_value, paths.layout_version, physical.oid IS NOT NULL FROM \"schema\".\"orcapod.store_paths.v1\" AS paths LEFT JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name AND physical.relnamespace = %s AND physical.relkind IN ('r', 'p') WHERE paths.table_name = %s AND paths.entry_kind = %s AND paths.entry_name = ''": 2, + "SELECT paths.table_name, paths.entry_value, paths.layout_version, physical.oid IS NOT NULL FROM \"schema\".\"orcapod.store_paths.v1\" AS paths LEFT JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name AND physical.relnamespace = %s AND physical.relkind IN ('r', 'p') WHERE paths.table_name LIKE %s ESCAPE '!' AND paths.entry_kind = %s AND paths.entry_name = ''": 1 + }, + "statements": { + "BEGIN": 6, + "ROLLBACK": 6, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 3, + "SELECT ns.nspname, ns.oid, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' WHERE ns.nspname = COALESCE(%s, current_schema())": 3, + "SELECT paths.table_name, paths.entry_value, paths.layout_version, physical.oid IS NOT NULL FROM \"schema\".\"orcapod.store_paths.v1\" AS paths LEFT JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name AND physical.relnamespace = %s AND physical.relkind IN ('r', 'p') WHERE paths.table_name = %s AND paths.entry_kind = %s AND paths.entry_name = ''": 2, + "SELECT paths.table_name, paths.entry_value, paths.layout_version, physical.oid IS NOT NULL FROM \"schema\".\"orcapod.store_paths.v1\" AS paths LEFT JOIN pg_catalog.pg_class AS physical ON physical.relname = paths.table_name AND physical.relnamespace = %s AND physical.relkind IN ('r', 'p') WHERE paths.table_name LIKE %s ESCAPE '!' AND paths.entry_kind = %s AND paths.entry_name = ''": 1 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "wrappers": [ + { + "rows": { + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 6, + "SELECT ns.nspname, ns.oid, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' WHERE ns.nspname = COALESCE(%s, current_schema())": 4 + }, + "statements": { + "BEGIN": 10, + "ROLLBACK": 10, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 6, + "SELECT ns.nspname, ns.oid, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid), rel.oid IS NOT NULL FROM pg_catalog.pg_namespace AS ns LEFT JOIN pg_catalog.pg_class AS rel ON rel.relnamespace = ns.oid AND rel.relname = %s AND rel.relkind = 'r' WHERE ns.nspname = COALESCE(%s, current_schema())": 4 + } + }, + { + "rows": { + "SELECT entry_value, layout_version FROM \"schema\".\"orcapod.store_paths.v1\" WHERE table_name = %s AND entry_kind = %s AND entry_name = ''": 0, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 1, + "SELECT oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), pg_advisory_xact_lock(%s, oid::integer) FROM pg_catalog.pg_namespace WHERE nspname = %s": 1, + "SELECT rel.relkind FROM pg_catalog.pg_class AS rel JOIN pg_catalog.pg_namespace AS ns ON ns.oid = rel.relnamespace WHERE ns.nspname = %s AND rel.relname = %s": 0 + }, + "statements": { + "BEGIN": 2, + "COMMIT": 1, + "CREATE TABLE IF NOT EXISTS \"schema\".\"o1_attached_side_effects__deli_e5841eedf17116508df160ee00b88b05\" ( \"__record_id\" BYTEA PRIMARY KEY, \"entry_id\" BYTEA, \"pipeline_run_id\" TEXT, \"executed_at\" TIMESTAMPTZ, \"__data_context\" TEXT NOT NULL )": 1, + "CREATE TABLE IF NOT EXISTS \"schema\".\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 1, + "INSERT INTO \"schema\".\"o1_attached_side_effects__deli_e5841eedf17116508df160ee00b88b05\" (\"__record_id\", \"entry_id\", \"pipeline_run_id\", \"executed_at\", \"__data_context\") VALUES (%s, %s, %s, %s, %s) ON CONFLICT (\"__record_id\") DO NOTHING": 2, + "INSERT INTO \"schema\".\"orcapod.store_paths.v1\" (table_name, entry_kind, entry_name, entry_value, layout_version) VALUES (%s, %s, '', %s, %s)": 1, + "ROLLBACK": 1, + "SELECT entry_value, layout_version FROM \"schema\".\"orcapod.store_paths.v1\" WHERE table_name = %s AND entry_kind = %s AND entry_name = ''": 1, + "SELECT ns.nspname, ns.oid = pg_my_temp_schema() OR pg_is_other_temp_schema(ns.oid) FROM pg_catalog.pg_namespace AS ns WHERE ns.nspname = current_schema()": 1, + "SELECT oid = pg_my_temp_schema() OR pg_is_other_temp_schema(oid), pg_advisory_xact_lock(%s, oid::integer) FROM pg_catalog.pg_namespace WHERE nspname = %s": 1, + "SELECT rel.relkind FROM pg_catalog.pg_class AS rel JOIN pg_catalog.pg_namespace AS ns ON ns.oid = rel.relnamespace WHERE ns.nspname = %s AND rel.relname = %s": 1 + } + } + ] + }, + "sqlite": { + "delivery": [ + { + "rows": { + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 0, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 0 + }, + "statements": { + "BEGIN IMMEDIATE": 1, + "COMMIT": 1, + "CREATE TABLE IF NOT EXISTS \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" ( \"__record_id\" BLOB PRIMARY KEY, \"value\" INTEGER )": 1, + "CREATE TABLE IF NOT EXISTS main.\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 1, + "INSERT INTO main.\"orcapod.store_paths.v1\" (table_name, entry_kind, entry_name, entry_value, layout_version) VALUES (?, ?, '', ?, ?)": 1, + "INSERT OR REPLACE INTO \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" (\"__record_id\", \"value\") VALUES (?, ?)": 1, + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 1, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 1 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "duplicate_operator": [ + { + "rows": { + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 0, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 0 + }, + "statements": { + "BEGIN IMMEDIATE": 1, + "COMMIT": 1, + "CREATE TABLE IF NOT EXISTS \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" ( \"__record_id\" BLOB PRIMARY KEY, \"value\" INTEGER )": 1, + "CREATE TABLE IF NOT EXISTS main.\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 1, + "INSERT INTO main.\"orcapod.store_paths.v1\" (table_name, entry_kind, entry_name, entry_value, layout_version) VALUES (?, ?, '', ?, ?)": 1, + "INSERT OR REPLACE INTO \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" (\"__record_id\", \"value\") VALUES (?, ?)": 1, + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 1, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 1 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "failed_flush": [ + { + "rows": { + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 0, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 0 + }, + "statements": { + "BEGIN IMMEDIATE": 1, + "COMMIT": 1, + "CREATE TABLE IF NOT EXISTS \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" ( \"__record_id\" BLOB PRIMARY KEY, \"value\" INTEGER )": 1, + "CREATE TABLE IF NOT EXISTS main.\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 1, + "INSERT INTO main.\"orcapod.store_paths.v1\" (table_name, entry_kind, entry_name, entry_value, layout_version) VALUES (?, ?, '', ?, ?)": 1, + "INSERT OR REPLACE INTO \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" (\"__record_id\", \"value\") VALUES (?, ?)": 1, + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 1, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 1 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "failed_flush_then_fresh_receipt": [ + { + "rows": { + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 0, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 0 + }, + "statements": { + "BEGIN IMMEDIATE": 1, + "COMMIT": 1, + "CREATE TABLE IF NOT EXISTS \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" ( \"__record_id\" BLOB PRIMARY KEY, \"value\" INTEGER )": 1, + "CREATE TABLE IF NOT EXISTS main.\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 1, + "INSERT INTO main.\"orcapod.store_paths.v1\" (table_name, entry_kind, entry_name, entry_value, layout_version) VALUES (?, ?, '', ?, ?)": 1, + "INSERT OR REPLACE INTO \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" (\"__record_id\", \"value\") VALUES (?, ?)": 1, + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 1, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 1 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "forwarding_attachment": [ + { + "rows": { + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 0, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 0 + }, + "statements": { + "BEGIN IMMEDIATE": 1, + "COMMIT": 1, + "CREATE TABLE IF NOT EXISTS \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" ( \"__record_id\" BLOB PRIMARY KEY, \"value\" INTEGER )": 1, + "CREATE TABLE IF NOT EXISTS main.\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 1, + "INSERT INTO main.\"orcapod.store_paths.v1\" (table_name, entry_kind, entry_name, entry_value, layout_version) VALUES (?, ?, '', ?, ?)": 1, + "INSERT OR REPLACE INTO \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" (\"__record_id\", \"value\") VALUES (?, ?)": 1, + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 1, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 1, + "get_all_records": 1 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "forwarding_load_only": [ + { + "rows": {}, + "statements": {} + }, + { + "rows": {}, + "statements": {} + } + ], + "forwarding_store": [ + { + "rows": { + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 0, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 0 + }, + "statements": { + "BEGIN IMMEDIATE": 1, + "COMMIT": 1, + "CREATE TABLE IF NOT EXISTS \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" ( \"__record_id\" BLOB PRIMARY KEY, \"value\" INTEGER )": 1, + "CREATE TABLE IF NOT EXISTS main.\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 1, + "INSERT INTO main.\"orcapod.store_paths.v1\" (table_name, entry_kind, entry_name, entry_value, layout_version) VALUES (?, ?, '', ?, ?)": 1, + "INSERT OR REPLACE INTO \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" (\"__record_id\", \"value\") VALUES (?, ?)": 1, + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 1, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 1, + "get_all_records": 1 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "function": [ + { + "rows": { + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 0, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 0 + }, + "statements": { + "BEGIN IMMEDIATE": 1, + "COMMIT": 1, + "CREATE TABLE IF NOT EXISTS \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" ( \"__record_id\" BLOB PRIMARY KEY, \"value\" INTEGER )": 1, + "CREATE TABLE IF NOT EXISTS main.\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 1, + "INSERT INTO main.\"orcapod.store_paths.v1\" (table_name, entry_kind, entry_name, entry_value, layout_version) VALUES (?, ?, '', ?, ?)": 1, + "INSERT OR REPLACE INTO \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" (\"__record_id\", \"value\") VALUES (?, ?)": 1, + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 1, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 1, + "get_all_records": 1, + "get_records_with_column_value": 4, + "get_table_schema": 1 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "load_only": [ + { + "rows": {}, + "statements": {} + }, + { + "rows": {}, + "statements": {} + } + ], + "pending_replay": [ + { + "rows": { + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 0, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 0, + "get_record_by_id": 2 + }, + "statements": { + "BEGIN IMMEDIATE": 1, + "COMMIT": 1, + "CREATE TABLE IF NOT EXISTS \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" ( \"__record_id\" BLOB PRIMARY KEY, \"value\" INTEGER )": 1, + "CREATE TABLE IF NOT EXISTS main.\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 1, + "INSERT INTO main.\"orcapod.store_paths.v1\" (table_name, entry_kind, entry_name, entry_value, layout_version) VALUES (?, ?, '', ?, ?)": 1, + "INSERT OR REPLACE INTO \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" (\"__record_id\", \"value\") VALUES (?, ?)": 1, + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 1, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 1, + "get_record_by_id": 2 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "rebind": [ + { + "rows": { + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 0, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 0 + }, + "statements": { + "BEGIN IMMEDIATE": 1, + "COMMIT": 1, + "CREATE TABLE IF NOT EXISTS \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" ( \"__record_id\" BLOB PRIMARY KEY, \"value\" INTEGER )": 1, + "CREATE TABLE IF NOT EXISTS main.\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 1, + "INSERT INTO main.\"orcapod.store_paths.v1\" (table_name, entry_kind, entry_name, entry_value, layout_version) VALUES (?, ?, '', ?, ?)": 1, + "INSERT OR REPLACE INTO \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" (\"__record_id\", \"value\") VALUES (?, ?)": 1, + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 1, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 1, + "get_all_records": 1 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "replay": [ + { + "rows": { + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 0, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 0, + "get_record_by_id": 2 + }, + "statements": { + "BEGIN IMMEDIATE": 1, + "COMMIT": 1, + "CREATE TABLE IF NOT EXISTS \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" ( \"__record_id\" BLOB PRIMARY KEY, \"value\" INTEGER )": 1, + "CREATE TABLE IF NOT EXISTS main.\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 1, + "INSERT INTO main.\"orcapod.store_paths.v1\" (table_name, entry_kind, entry_name, entry_value, layout_version) VALUES (?, ?, '', ?, ?)": 1, + "INSERT OR REPLACE INTO \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" (\"__record_id\", \"value\") VALUES (?, ?)": 1, + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 1, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 1, + "get_record_by_id": 2 + } + }, + { + "rows": {}, + "statements": {} + } + ], + "wrappers": [ + { + "rows": { + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 0, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 0 + }, + "statements": { + "BEGIN IMMEDIATE": 1, + "COMMIT": 1, + "CREATE TABLE IF NOT EXISTS \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" ( \"__record_id\" BLOB PRIMARY KEY, \"value\" INTEGER )": 1, + "CREATE TABLE IF NOT EXISTS main.\"orcapod.store_paths.v1\" ( table_name TEXT NOT NULL, entry_kind TEXT NOT NULL, entry_name TEXT NOT NULL, entry_value TEXT NOT NULL, layout_version INTEGER NOT NULL CHECK (layout_version = 1), PRIMARY KEY (table_name, entry_kind, entry_name) )": 1, + "INSERT INTO main.\"orcapod.store_paths.v1\" (table_name, entry_kind, entry_name, entry_value, layout_version) VALUES (?, ?, '', ?, ?)": 1, + "INSERT OR REPLACE INTO \"main\".\"o1_owned_queued_501c21093366b2dbfa897ed5de06379e\" (\"__record_id\", \"value\") VALUES (?, ?)": 1, + "SELECT entry_value, layout_version FROM main.\"orcapod.store_paths.v1\" WHERE table_name = ? AND entry_kind = ? AND entry_name = ''": 1, + "SELECT name, type FROM main.sqlite_schema WHERE name = ? COLLATE NOCASE": 1, + "get_all_records": 1 + } + }, + { + "rows": {}, + "statements": {} + } + ] + } + }, + "main": "4faef270ede72083f5ff37b541af038d98fd3693" +} diff --git a/tests/test_pipeline/test_attachment_store_io.py b/tests/test_pipeline/test_attachment_store_io.py new file mode 100644 index 000000000..a640498bf --- /dev/null +++ b/tests/test_pipeline/test_attachment_store_io.py @@ -0,0 +1,493 @@ +"""Bound the I/O of attachment tracking by the same public runs on origin/main.""" + +from __future__ import annotations + +import json +import re +import sqlite3 +import uuid +from collections import Counter +from collections.abc import Iterable, Iterator +from contextlib import contextmanager +from pathlib import Path +from typing import Any, cast +from unittest.mock import patch + +import psycopg +import pyarrow as pa +import pytest +from psycopg import sql + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators import SelectDataColumns +from orcapod.databases import ( + ConnectorArrowDatabase, + ExtensionAwareDatabase, + InMemoryArrowDatabase, + PostgreSQLConnector, + SQLiteConnector, +) +from orcapod.errors import OrcapodDatabaseWriteError +from orcapod.invocation import InvocationContext +from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.semantic_types.universal_converter import UniversalTypeConverter +from orcapod.side_effects import SideEffectPod, SideEffectPodConfig +from orcapod.sources import DictSource +from orcapod.types import CacheMode +from tests.test_databases.test_postgresql_connector_integration import _base_dsn + +from .test_mixed_function_commits import ProtocolDatabase + +JOB_RUNNERS = ("sync", "async", "run_async") + + +async def _run(job: PipelineJob, runner: str, *, load_only: bool = False) -> None: + """Use each public job runner against the same scenario.""" + if runner == "run_async": + _ = await job.run_async(load_only=load_only) + else: + orchestrator = AsyncPipelineOrchestrator() if runner == "async" else None + _ = job.run(orchestrator=orchestrator, load_only=load_only) + + +BASELINE = Path(__file__).with_name("fixtures") / "attachment_store_io.json" +SCENARIOS = ( + "delivery", + "failed_flush", + "failed_flush_then_fresh_receipt", + "replay", + "pending_replay", + "rebind", + "load_only", + "forwarding_store", + "forwarding_load_only", + "wrappers", + "forwarding_attachment", + "duplicate_operator", + "function", +) +# These entries allow the statements and returned metadata rows that main uses +# for an explicit flush of the same additional attachment after the run. +ATTACHMENT_FLUSHES = { + "delivery": "Publish the newly delivered receipt before returning.", + "failed_flush_then_fresh_receipt": "Publish the failed receipt and the fresh receipt.", + "pending_replay": "Publish the buffered completion receipts without delivering them again.", + "rebind": "Publish the old attachment's pending log and the new attachment's log.", + "wrappers": "Publish the receipt queued through the library's extension wrapper.", + "function": "Flush the other buffered writes in the function's attachment.", +} + +Counts = dict[str, dict[str, int]] + + +class StoreIO: + """Count explicit SQL executions and data returned by each read.""" + + def __init__(self) -> None: + self.statements: Counter[str] = Counter() + self.rows: Counter[str] = Counter() + + def reset(self) -> None: + """Start measuring a new phase.""" + self.statements.clear() + self.rows.clear() + + def snapshot(self) -> Counts: + """Freeze the statement counts and counts of rows fetched from the driver.""" + return {"statements": dict(self.statements), "rows": dict(self.rows)} + + def statement(self, query: str | sql.Composable, count: int = 1) -> str: + """Normalize formatting and the disposable PostgreSQL schema name.""" + query = query.as_string() if isinstance(query, sql.Composable) else query + key = re.sub(r'"io_[0-9a-f]+"', '"schema"', " ".join(query.split())) + self.statements[key] += count + return key + + +class CountingCursor: + """Forward each store statement and charge fetched rows to that statement.""" + + def __init__(self, cursor: Any, log: StoreIO) -> None: + self.cursor = cursor + self.log = log + self.query = "" + + def __getattr__(self, name: str) -> Any: + return getattr(self.cursor, name) + + def __enter__(self) -> CountingCursor: + _ = self.cursor.__enter__() + return self + + def __exit__(self, *exc: Any) -> None: + self.cursor.__exit__(*exc) + + def __iter__(self) -> Iterator[Any]: + for row in self.cursor: + self.log.rows[self.query] += 1 + yield row + + def execute( + self, query: str | sql.Composable, *args: Any, **kwargs: Any + ) -> CountingCursor: + """Capture attempts even when the driver rejects the statement.""" + self.query = self.log.statement(query) + self.cursor.execute(query, *args, **kwargs) + return self + + def executemany( + self, query: str | sql.Composable, params: Iterable[Any], **kwargs: Any + ) -> CountingCursor: + """Count the number of parameter sets executed for a batched upsert.""" + values = list(params) + self.query = self.log.statement(query, len(values)) + self.cursor.executemany(query, values, **kwargs) + return self + + def fetchone(self) -> Any: + """Count a successful single-row fetch.""" + row = self.cursor.fetchone() + self.log.rows[self.query] += int(row is not None) + return row + + def fetchall(self) -> list[Any]: + """Count rows fetched in full.""" + rows = cast("list[Any]", self.cursor.fetchall()) + self.log.rows[self.query] += len(rows) + return rows + + def fetchmany(self, *args: Any) -> list[Any]: + """Count rows fetched in a batch.""" + rows = cast("list[Any]", self.cursor.fetchmany(*args)) + self.log.rows[self.query] += len(rows) + return rows + + +class CountingConnection: + """Instrument both direct executions and regular or server-side cursors.""" + + def __init__(self, connection: Any, log: StoreIO) -> None: + self.connection = connection + self.log = log + + def __getattr__(self, name: str) -> Any: + return getattr(self.connection, name) + + def __enter__(self) -> CountingConnection: + _ = self.connection.__enter__() + return self + + def __exit__(self, *exc: Any) -> None: + self.connection.__exit__(*exc) + + @property + def row_factory(self) -> Any: + """Forward the SQLite connector's row factory.""" + return self.connection.row_factory + + @row_factory.setter + def row_factory(self, value: Any) -> None: + self.connection.row_factory = value + + def cursor(self, *args: Any, **kwargs: Any) -> CountingCursor: + """Count SQL and reads from the connection's cursor.""" + return CountingCursor(self.connection.cursor(*args, **kwargs), self.log) + + def execute(self, query: str, *args: Any, **kwargs: Any) -> CountingCursor: + """Count connection-level SQLite statements.""" + return self.cursor().execute(query, *args, **kwargs) + + def executemany(self, query: str, params: Iterable[Any]) -> CountingCursor: + """Count connection-level SQLite upserts.""" + return self.cursor().executemany(query, params) + + def commit(self) -> None: + """Count explicitly requested transaction commits.""" + if isinstance(self.connection, sqlite3.Connection): + _ = self.log.statement("COMMIT") + self.connection.commit() + + def rollback(self) -> None: + """Count explicitly requested transaction rollbacks.""" + if isinstance(self.connection, sqlite3.Connection): + _ = self.log.statement("ROLLBACK") + self.connection.rollback() + + +@contextmanager +def _measured_store( + backend: str, log: StoreIO, monkeypatch: pytest.MonkeyPatch +) -> Iterator[ArrowDatabaseProtocol]: + """Use real SQL drivers and count public in-memory lookups.""" + for method in ( + "get_all_records", + "get_record_by_id", + "get_records_by_ids", + "get_records_with_column_value", + "get_table_schema", + "table_exists", + ): + original = getattr(InMemoryArrowDatabase, method) + + def observe( + store: InMemoryArrowDatabase, + *args: Any, + method: str = method, + original: Any = original, + **kwargs: Any, + ) -> Any: + log.statements[method] += 1 + result = original(store, *args, **kwargs) + if isinstance(result, pa.Table): + log.rows[method] += result.num_rows + return result + + monkeypatch.setattr(InMemoryArrowDatabase, method, observe) + if backend == "memory": + yield InMemoryArrowDatabase() + elif backend == "sqlite": + connect = sqlite3.connect + + def sqlite_connect(*args: Any, **kwargs: Any) -> CountingConnection: + return CountingConnection(connect(*args, **kwargs), log) + + monkeypatch.setattr(sqlite3, "connect", sqlite_connect) + with SQLiteConnector() as connector: + yield ConnectorArrowDatabase(connector) + else: + schema = f"io_{uuid.uuid4().hex[:12]}" + dsn = _base_dsn() + connect = psycopg.connect + + class CountingPGConnection(psycopg.Connection[Any]): + """Include transaction control and commands for server-side cursors.""" + + def _exec_command(self, command: Any, *args: Any, **kwargs: Any) -> Any: + if isinstance(command, bytes): + command = command.decode("ascii") + _ = log.statement(command) + return super()._exec_command(command, *args, **kwargs) + + def postgres_connect(*args: Any, **kwargs: Any) -> CountingConnection: + return CountingConnection( + CountingPGConnection.connect(*args, **kwargs), log + ) + + with connect(dsn, autocommit=True) as admin: + identifier = sql.Identifier(schema) + _ = admin.execute(sql.SQL("CREATE SCHEMA {}").format(identifier)) + try: + with monkeypatch.context() as scoped: + scoped.setattr(psycopg, "connect", postgres_connect) + with PostgreSQLConnector( + f"{dsn} options=-csearch_path={schema}" + ) as connector: + yield ConnectorArrowDatabase(connector) + finally: + _ = admin.execute(sql.SQL("DROP SCHEMA {} CASCADE").format(identifier)) + + +def _source(*values: int, reverse: bool = False) -> DictSource: + """Return schema-compatible input with stable identities across rebinding.""" + tags = ["group", "tag"] + rows = [{"group": 0, "tag": i, "value": i + 1, "other": i + 2} for i in values] + if reverse: + tags.reverse() + rows = [dict(reversed(tuple(row.items()))) for row in rows] + return DictSource( + data=rows, + tag_columns=tags, + tag_only_columns=True, + source_id="input", + ) + + +def _deliver(ctx: InvocationContext, value: int, other: int) -> None: + """Complete delivery without introducing another store.""" + + +@function_pod(output_keys="total") +def _total(value: int, other: int) -> int: + """Exercise both function storage tables.""" + return value + other + + +async def _capture_scenario( + backend: str, + runner: str, + scenario: str, + monkeypatch: pytest.MonkeyPatch, + *, + record_main: bool = False, +) -> tuple[Counts, Counts]: + """Capture the job and, on main, the equivalent explicit attachment flush.""" + log = StoreIO() + second: ConnectorArrowDatabase | None = None + with _measured_store(backend, log, monkeypatch) as root: + owned = root.at("owned") + attached = root.at("attached") + other = root.at("other") + # Use distinct queues for independent attachments. The SQL stores share + # the physical connector and its statement log. + if isinstance(root, ConnectorArrowDatabase): + connector = root._connector # pyright: ignore[reportPrivateUsage] # share the measured SQL connection + attached = ConnectorArrowDatabase(connector).at("attached") + other = ConnectorArrowDatabase(connector).at("other") + else: + attached = InMemoryArrowDatabase().at("attached") + other = InMemoryArrowDatabase().at("other") + + forwarding = scenario in ("forwarding_store", "forwarding_load_only") + load_only = scenario.endswith("load_only") + operator = scenario == "duplicate_operator" or ( + scenario == "rebind" and backend == "memory" + ) + # SQLite rejects the timezone-aware receipt and operator log schemas. + # Both SQL backends reject function tables. Keep the node attachments + # in memory on those paths and still measure the real SQL job store. + use_memory_attachment = backend == "sqlite" or scenario in ( + "duplicate_operator", + "function", + ) + if use_memory_attachment and backend != "memory": + attached = InMemoryArrowDatabase().at("attached") + other = InMemoryArrowDatabase().at("other") + tracked = scenario in ("replay", "pending_replay") + job = PipelineJob( + name="io_job", + database=ProtocolDatabase(owned) + if forwarding or use_memory_attachment + else owned, + ) + source = ( + _source(*range(8)) + if scenario + in ("delivery", "failed_flush", "failed_flush_then_fresh_receipt") + else _source(0, 1) + ) + with job: + if operator: + _ = SelectDataColumns(["value", "other"])(source, label="sink") + elif scenario == "function": + _ = _total.pod(source, label="sink") + else: + _ = SideEffectPod( + _deliver, config=SideEffectPodConfig(track_completion=tracked) + )(source, label="sink") + sink = job.nodes["sink"] + if scenario == "function": + sink.attach_databases(pipeline_database=attached, result_database=attached) + attached.add_record(("extra",), b"extra", pa.table({"value": [10]})) + elif (forwarding or load_only) and backend != "sqlite": + # A sibling view behind the forwarding job database shares its queue. + sink.attach_databases(pipeline_database=root.at("sibling")) + elif operator: + sink.attach_databases(pipeline_database=attached, cache_mode=CacheMode.LOG) + elif scenario == "forwarding_attachment": + sink.attach_databases(pipeline_database=ProtocolDatabase(attached)) + else: + store = ( + ExtensionAwareDatabase(attached, UniversalTypeConverter()) + if scenario == "wrappers" + else attached + ) + sink.attach_databases(pipeline_database=store) + + def bind_input(*values: int) -> None: + job.bind(sources={next(iter(job.sources)): _source(*values, reverse=True)}) + + if scenario in ( + "delivery", + "failed_flush", + "failed_flush_then_fresh_receipt", + "duplicate_operator", + ): + await _run(job, runner) + attached.flush() + sink.clear_cache() + if scenario in ("delivery", "failed_flush"): + bind_input(8) + + async def run_with_failed_flush() -> None: + def fail() -> None: + raise OSError("temporary first attachment flush failure") + + with patch.object(attached, "flush", side_effect=fail): + try: + await _run(job, runner) + except OrcapodDatabaseWriteError as error: + assert isinstance(error.__cause__, OSError) + else: + assert record_main, "the attachment should have reached its flush" + + if scenario in ( + "failed_flush_then_fresh_receipt", + "replay", + "pending_replay", + "rebind", + ): + if scenario == "failed_flush_then_fresh_receipt": + bind_input(8) + + await run_with_failed_flush() + sink.clear_cache() + if scenario == "failed_flush_then_fresh_receipt": + bind_input(9) + elif scenario == "rebind": + sink.attach_databases( + pipeline_database=other, + **({"cache_mode": CacheMode.LOG} if operator else {}), + ) + elif scenario == "replay": + # A second handle has made the receipts durable. Replay leaves this + # handle's unrelated row queued with the same reads as main. + if isinstance(attached, ConnectorArrowDatabase): + second = ConnectorArrowDatabase(attached._connector).at("attached") # pyright: ignore[reportPrivateUsage] # preserve the same physical store + (path,) = attached.list_table_paths() + rows = attached.get_all_records(path, "__record_id") + assert rows is not None + second.add_records( + path, rows, record_id_column="__record_id", flush=True + ) + else: + attached.flush() + attached.add_record(("extra",), b"extra", pa.table({"value": [10]})) + + if use_memory_attachment and backend != "memory": + owned.add_record(("queued",), b"queued", pa.table({"value": [10]})) + log.reset() + if scenario == "failed_flush": + await run_with_failed_flush() + else: + await _run(job, runner, load_only=load_only) + actual = log.snapshot() + if second is not None: + assert not second.table_exists(("extra",)) + log.reset() + if record_main and scenario in ATTACHMENT_FLUSHES: + attached.flush() + if scenario == "rebind": + other.flush() + return actual, log.snapshot() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("scenario", SCENARIOS) +@pytest.mark.parametrize("runner", JOB_RUNNERS) +@pytest.mark.parametrize( + "backend", + ("memory", "sqlite", pytest.param("postgres", marks=pytest.mark.postgres)), +) +async def test_attachment_runs_stay_within_main_store_io( + backend: str, runner: str, scenario: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """Permit only main's operations and its explicit attachment flush I/O.""" + actual, _ = await _capture_scenario(backend, runner, scenario, monkeypatch) + baseline = json.loads(BASELINE.read_text()) + expected, flush = baseline["cases"][backend][scenario] + for kind in ("statements", "rows"): + budget = Counter(expected[kind]) + if scenario in ATTACHMENT_FLUSHES: + budget.update(flush[kind]) + assert not (extra := Counter(actual[kind]) - budget), (kind, dict(extra)) diff --git a/tests/test_pipeline/test_job_attached_database_commit.py b/tests/test_pipeline/test_job_attached_database_commit.py new file mode 100644 index 000000000..7f9dc812a --- /dev/null +++ b/tests/test_pipeline/test_job_attached_database_commit.py @@ -0,0 +1,1200 @@ +"""A run commits the database objects its nodes actually write to (ITL-1383).""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from unittest.mock import Mock + +import deltalake +import psycopg +import pyarrow as pa +import pytest +from typing_extensions import override + +import orcapod.pipeline.job as job_module +from orcapod import PipelineJob, function_pod +from orcapod.core.function_pod import FunctionPod +from orcapod.core.nodes.function_node import FunctionJobNode +from orcapod.core.nodes.operator_node import OperatorJobNode +from orcapod.core.operators import GroupBy, SelectDataColumns +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + ExtensionAwareDatabase, + InMemoryArrowDatabase, + NoOpArrowDatabase, +) +from orcapod.errors import OrcapodDatabaseWriteError +from orcapod.invocation import InvocationContext +from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.pipeline.observer import NoOpObserver +from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.protocols.observability_protocols import ExecutionObserverProtocol +from orcapod.semantic_types.universal_converter import UniversalTypeConverter +from orcapod.side_effects import SideEffectPod, SideEffectPodConfig +from orcapod.sources import ArrowTableSource +from orcapod.types import CacheMode, NodeConfig + +from .test_mixed_function_commits import CommitConnector, ProtocolDatabase + +JOB_RUNNERS = ("sync", "async", "run_async") +RUNNERS = (*JOB_RUNNERS, "node") + + +@pytest.fixture(params=["tags_first", "data_first"]) +def source(request: pytest.FixtureRequest) -> ArrowTableSource: + """Give the same input in two physical layouts and tag orders.""" + schema = pa.schema( + [ + pa.field("group", pa.int64(), nullable=False), + pa.field("site", pa.string(), nullable=False), + pa.field("x", pa.int64(), nullable=False), + pa.field("y", pa.int64(), nullable=False), + ] + ) + table = pa.table( + {"group": [0, 1], "site": ["a", "b"], "x": [1, 2], "y": [3, 4]}, schema=schema + ) + tags = ["group", "site"] + if request.param == "data_first": + table = table.select(["y", "x", "site", "group"]) + tags.reverse() + return ArrowTableSource( + table, tag_columns=tags, tag_only_columns=True, source_id="source" + ) + + +@function_pod(output_keys="total") +def total(x: int, y: int) -> int: + """Add the two inputs.""" + return x + y + + +async def _run( + job: PipelineJob, + runner: str, + *, + load_only: bool = False, + observer: ExecutionObserverProtocol | None = None, +) -> None: + """Run the job or its operator node via the selected entry point.""" + if runner == "node": + job.nodes["grouped"].run(load_only=load_only) + elif runner == "run_async": + await job.run_async(load_only=load_only, observer=observer) + else: + orchestrator = AsyncPipelineOrchestrator() if runner == "async" else None + job.run(orchestrator=orchestrator, load_only=load_only, observer=observer) + + +def _make_job( + store: ArrowDatabaseProtocol, + attached: ArrowDatabaseProtocol, + source: ArrowTableSource, +) -> PipelineJob: + """Route an operator's log to an independently constructed database.""" + job = PipelineJob(name="job", database=store) + with job: + selected = SelectDataColumns(list(source.output_schema()[1].keys()))( + source, label="other" + ) + GroupBy(by=list(source.output_schema()[0].keys()))(selected, label="grouped") + job.nodes["other"].attach_databases( + pipeline_database=store.at("job"), cache_mode=CacheMode.LOG + ) + job.nodes["grouped"].attach_databases( + pipeline_database=attached, cache_mode=CacheMode.LOG + ) + return job + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", RUNNERS) +async def test_a_run_commits_a_manually_attached_operator_log( + tmp_path: Path, runner: str, source: ArrowTableSource +) -> None: + """Read the two logged operator rows from disk as soon as the run returns.""" + job = _make_job( + DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path).at("mine"), source + ) + await _run(job, runner) + node = job.nodes["grouped"] + assert node.as_table().num_rows == node.as_source().as_table().num_rows == 2 + for prefix in ("job", "mine"): + logs = list((tmp_path / prefix).rglob("_delta_log")) + assert len(logs) == 1 + (log,) = logs + assert deltalake.DeltaTable(str(log.parent)).to_pyarrow_table().num_rows == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_a_manually_attached_function_store_is_committed( + tmp_path: Path, runner: str, source: ArrowTableSource +) -> None: + """The job flushes the attachment even after its function tables committed.""" + job = PipelineJob(name="job", database=DeltaTableDatabase(tmp_path)) + with job: + total.pod(source, label="sum") + attachment = DeltaTableDatabase(tmp_path).at("mine") + job.nodes["sum"].attach_databases(pipeline_database=attachment) + attachment.add_record(("pending",), b"pending", pa.table({"value": [3]})) + + await _run(job, runner) + assert (tmp_path / "mine" / "pending" / "_delta_log").is_dir() + logs = list((tmp_path / "mine").rglob("_delta_log")) + assert {log.parent.name for log in logs} == {"pdb_v2", "rdb_v1", "pending"} + assert all( + deltalake.DeltaTable(str(log.parent)).to_pyarrow_table().num_rows == 2 + for log in logs + if log.parent.name != "pending" + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", RUNNERS) +async def test_load_only_does_not_commit_a_manually_attached_store( + tmp_path: Path, runner: str, source: ArrowTableSource +) -> None: + """A buffered write from outside the job stays pending during load-only runs.""" + attached = DeltaTableDatabase(tmp_path).at("mine") + job = _make_job(DeltaTableDatabase(tmp_path), attached, source) + attached.add_record(("pending",), b"pending", pa.table({"x": [1]})) + await _run(job, runner, load_only=True) + assert job.nodes["grouped"].as_table().num_rows == 2 + assert not list(tmp_path.rglob("_delta_log")) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", RUNNERS) +async def test_a_failed_attached_flush_clears_only_the_nodes_that_ran( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The new run loses its rows and an already current node keeps its rows.""" + attached = DeltaTableDatabase(tmp_path).at("mine") + job = _make_job(DeltaTableDatabase(tmp_path), attached, source) + held = job.nodes["other"] + held.run() + + def fail() -> None: + raise OSError("disk full") + + monkeypatch.setattr(attached, "flush", fail) + with pytest.raises(OrcapodDatabaseWriteError, match="mine") as exc_info: + await _run(job, runner) + assert exc_info.value.flush + assert isinstance(exc_info.value.__cause__, OSError) + assert job.nodes["grouped"].as_table().num_rows == 0 + assert held.as_table().num_rows == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_reattaching_an_operator_flushes_the_store_that_received_its_rows( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A run-end observer can change the node's attachment after it writes.""" + store = DeltaTableDatabase(tmp_path / "owned") + attached = DeltaTableDatabase(tmp_path / "attached") + job = _make_job(store, attached, source) + replacement = DeltaTableDatabase(tmp_path / "unused") + owned_view = store.at("job") + job.nodes["other"].attach_databases( + pipeline_database=owned_view, cache_mode=CacheMode.LOG + ) + + def flush_unused_store() -> None: + pytest.fail("The replacement store received no write") + + def flush_owned_view() -> None: + pytest.fail("The scheduled flush already covers this view") + + monkeypatch.setattr(replacement, "flush", flush_unused_store) + monkeypatch.setattr(owned_view, "flush", flush_owned_view) + + class Reattach(NoOpObserver): + def on_run_end(self, run_id: str) -> None: + job.nodes["grouped"].attach_databases( + pipeline_database=replacement, cache_mode=CacheMode.LOG + ) + job.nodes["other"].attach_databases( + pipeline_database=replacement, cache_mode=CacheMode.LOG + ) + + await _run(job, runner, observer=Reattach()) + for store_path in (tmp_path / "owned", tmp_path / "attached"): + (log,) = store_path.rglob("_delta_log") + assert deltalake.DeltaTable(str(log.parent)).to_pyarrow_table().num_rows == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_execution_error_still_flushes_a_manually_attached_store( + tmp_path: Path, runner: str, source: ArrowTableSource +) -> None: + """An observer exception propagates after the completed operator log commits.""" + attached = DeltaTableDatabase(tmp_path / "attached") + job = _make_job(DeltaTableDatabase(tmp_path / "owned"), attached, source) + + class FailRun(NoOpObserver): + def on_run_end(self, run_id: str) -> None: + raise RuntimeError("observer failed") + + with pytest.raises(RuntimeError, match="observer failed"): + await _run(job, runner, observer=FailRun()) + (log,) = (tmp_path / "attached").rglob("_delta_log") + assert deltalake.DeltaTable(str(log.parent)).to_pyarrow_table().num_rows == 2 + assert job.nodes["grouped"].as_table().num_rows == 0 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_interrupted_best_effort_flush_clears_run_and_retries_both_attachments( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A failed run clears both nodes as on main and retries both unfinished logs.""" + first = DeltaTableDatabase(tmp_path / "first") + second = DeltaTableDatabase(tmp_path / "second") + job = _make_job(InMemoryArrowDatabase(), second, source) + job.nodes["other"].attach_databases( + pipeline_database=first, cache_mode=CacheMode.LOG + ) + + class FailRun(NoOpObserver): + def on_run_end(self, run_id: str) -> None: + raise RuntimeError("observer failed") + + def interrupt() -> None: + raise KeyboardInterrupt + + with monkeypatch.context() as patch: + patch.setattr(first, "flush", interrupt) + with pytest.raises(KeyboardInterrupt): + await _run(job, runner, observer=FailRun()) + assert job.nodes["other"].as_table().num_rows == 0 + assert job.nodes["grouped"].as_table().num_rows == 0 + assert not list(tmp_path.rglob("_delta_log")) + + # Rebind so the retry can commit the original logs only through enrollment. + replacement = InMemoryArrowDatabase() + for label in ("other", "grouped"): + job.nodes[label].attach_databases( + pipeline_database=replacement, cache_mode=CacheMode.LOG + ) + await _run(job, runner) + for name in ("first", "second"): + (log,) = (tmp_path / name).rglob("_delta_log") + assert deltalake.DeltaTable(str(log.parent)).to_pyarrow_table().num_rows == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_owned_best_effort_interrupt_retains_attachment( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The interrupt propagates, and a later committing run can flush the attachment.""" + attached = DeltaTableDatabase(tmp_path) + job = _make_job(InMemoryArrowDatabase(), attached, source) + + class FailRun(NoOpObserver): + def on_run_end(self, run_id: str) -> None: + raise RuntimeError("observer failed") + + def interrupt(_database: InMemoryArrowDatabase) -> None: + raise KeyboardInterrupt + + with monkeypatch.context() as patch: + patch.setattr(InMemoryArrowDatabase, "flush", interrupt) + with pytest.raises(KeyboardInterrupt): + await _run(job, runner, observer=FailRun()) + assert not list(tmp_path.rglob("_delta_log")) + assert job.nodes["grouped"].as_table().num_rows == 2 + + job.nodes["grouped"].attach_databases( + pipeline_database=InMemoryArrowDatabase(), cache_mode=CacheMode.LOG + ) + job.nodes["grouped"].clear_cache() + await _run(job, runner) + (log,) = tmp_path.rglob("_delta_log") + assert deltalake.DeltaTable(str(log.parent)).to_pyarrow_table().num_rows == 2 + + +@pytest.mark.asyncio +async def test_cancelled_run_retains_pending_attachment( + tmp_path: Path, source: ArrowTableSource +) -> None: + """Cancelling a task with a completed log leaves it buffered until the retry.""" + attached = DeltaTableDatabase(tmp_path) + job = PipelineJob(name="job", database=InMemoryArrowDatabase()) + log_written = asyncio.Event() + unblock = asyncio.Event() + + async def wait_for_cancel(x: int) -> int: + await unblock.wait() + return x + + class ObserveLog(NoOpObserver): + def on_node_end(self, node_label: str, node_hash: str) -> None: + if node_label == "selected": + log_written.set() + + with job: + selected = SelectDataColumns(["x"])(source, label="selected") + FunctionPod.from_fn(wait_for_cancel, output_keys="waited")( + selected, label="slow" + ) + job.nodes["selected"].attach_databases( + pipeline_database=attached, cache_mode=CacheMode.LOG + ) + task = asyncio.create_task(job.run_async(observer=ObserveLog())) + async with asyncio.timeout(10): + await log_written.wait() + _ = task.cancel() + with pytest.raises(asyncio.CancelledError): + _ = await task + assert not list(tmp_path.rglob("_delta_log")) + + unblock.set() + _ = await job.run_async() + (log,) = tmp_path.rglob("_delta_log") + assert deltalake.DeltaTable(str(log.parent)).to_pyarrow_table().num_rows == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_persistent_cache_hits_leave_the_unused_ephemeral_store_alone( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A persistent hit leaves even another pending table in the ephemeral store alone.""" + job = PipelineJob(name="job", database=InMemoryArrowDatabase()) + with job: + total.pod(source, label="sum") + await _run(job, runner) + node = job.nodes["sum"] + node.clear_cache() + + ephemeral = DeltaTableDatabase(tmp_path) + ephemeral.add_record(("pending",), b"pending", pa.table({"value": [3]})) + job.set_ephemeral_database(ephemeral) + job.apply_node_config(NodeConfig(is_result_ephemeral=True)) + + def fail() -> None: + raise OSError("the unused store cannot commit") + + monkeypatch.setattr(ephemeral, "flush", fail) + await _run(job, runner) + assert node.as_table().num_rows == 2 + assert not (tmp_path / "pending" / "_delta_log").exists() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_owned_pipeline_flush_precedes_a_failing_split_result_flush( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The ready pipeline write survives a failed commit of the split result store.""" + pipeline = DeltaTableDatabase(tmp_path / "pipeline") + result = DeltaTableDatabase(tmp_path / "result") + job = PipelineJob(name="job", database=pipeline, result_database=result) + with job: + total.pod(source, label="sum") + + def fail() -> None: + raise OSError("result commit failed") + + class QueueReadyWrite(NoOpObserver): + def on_run_end(self, run_id: str) -> None: + pipeline.at("job").add_record( + ("ready",), b"ready", pa.table({"value": [3]}) + ) + monkeypatch.setattr(result, "flush", fail) + + with pytest.raises(OrcapodDatabaseWriteError) as error: + await _run(job, runner, observer=QueueReadyWrite()) + assert isinstance(error.value.__cause__, OSError) + assert (tmp_path / "pipeline" / "job" / "ready" / "_delta_log").is_dir() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +@pytest.mark.parametrize("scoped", [False, True], ids=["same_view", "scoped_views"]) +async def test_logging_nodes_sharing_one_database_flush_it_once( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, + *, + scoped: bool, +) -> None: + """Both logs are durable after one shared flush following the owned flush.""" + store = DeltaTableDatabase(tmp_path / "owned") + attached = DeltaTableDatabase(tmp_path / "attached") + first = attached.at("first") if scoped else attached + second = attached.at("second") if scoped else attached + job = _make_job(store, second, source) + job.nodes["other"].attach_databases( + pipeline_database=first, cache_mode=CacheMode.LOG + ) + flush = attached.flush + calls = 0 + + def count_flush() -> None: + nonlocal calls + assert (tmp_path / "owned" / "job" / "ready" / "_delta_log").is_dir() + calls += 1 + flush() + + class QueueReadyWrite(NoOpObserver): + def on_run_end(self, run_id: str) -> None: + store.at("job").add_record(("ready",), b"ready", pa.table({"value": [3]})) + + monkeypatch.setattr(first, "flush", count_flush) + monkeypatch.setattr(second, "flush", count_flush) + await _run(job, runner, observer=QueueReadyWrite()) + assert calls == 1 + logs = list((tmp_path / "attached").rglob("_delta_log")) + assert len(logs) == 2 + assert all( + deltalake.DeltaTable(str(log.parent)).to_pyarrow_table().num_rows == 2 + for log in logs + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +@pytest.mark.parametrize("wrapped", [False, True], ids=["native", "protocol"]) +async def test_duplicate_operator_logs_do_not_flush_an_attached_store( + tmp_path: Path, runner: str, source: ArrowTableSource, *, wrapped: bool +) -> None: + """An all-duplicate insert leaves unrelated pending writes alone on a rerun.""" + store = DeltaTableDatabase(tmp_path / "attached") + attached = ProtocolDatabase(store) if wrapped else store + job = _make_job(DeltaTableDatabase(tmp_path / "owned"), attached, source) + job.nodes["grouped"].run() + assert len(list((tmp_path / "attached").rglob("_delta_log"))) == 1 + for label in ("other", "grouped"): + job.nodes[label].clear_cache() + + attached.add_record(("pending",), b"pending", pa.table({"value": [3]})) + await _run(job, runner) + assert job.nodes["grouped"].as_table().num_rows == 2 + assert not (tmp_path / "attached" / "pending" / "_delta_log").exists() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_durable_delta_duplicates_after_failed_flush_leave_other_rows_pending( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A second handle's durable rows take precedence over the first handle's queue.""" + root = tmp_path / "attached" + attached = DeltaTableDatabase(root) + second = DeltaTableDatabase(root) + job = _make_job(DeltaTableDatabase(tmp_path / "owned"), attached, source) + other = _make_job(DeltaTableDatabase(tmp_path / "other"), second, source) + + def fail() -> None: + raise OSError("temporary attachment flush failure") + + with monkeypatch.context() as patch: + patch.setattr(attached, "flush", fail) + with pytest.raises(OrcapodDatabaseWriteError): + await _run(job, runner) + + other.nodes["grouped"].run() + (log,) = root.rglob("_delta_log") + attached.refresh_table(log.parent.relative_to(root).parts) + assert deltalake.DeltaTable(str(log.parent)).to_pyarrow_table().num_rows == 2 + attached.add_record(("pending",), b"pending", pa.table({"value": [3]})) + + await _run(job, runner) + assert job.nodes["grouped"].as_table().num_rows == 2 + assert not (root / "pending" / "_delta_log").exists() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_noop_pipeline_still_flushes_durable_function_result_attachment( + tmp_path: Path, runner: str, source: ArrowTableSource +) -> None: + """A durable result write enrolls its store even when pipeline records are discarded.""" + job = PipelineJob(name="job", database=InMemoryArrowDatabase()) + with job: + total.pod(source, label="sum") + attached = DeltaTableDatabase(tmp_path) + job.nodes["sum"].attach_databases( + pipeline_database=NoOpArrowDatabase(), result_database=attached + ) + attached.add_record(("pending",), b"pending", pa.table({"value": [3]})) + + await _run(job, runner) + (results,) = tmp_path.rglob("rdb_v1/_delta_log") + assert deltalake.DeltaTable(str(results.parent)).to_pyarrow_table().num_rows == 2 + assert (tmp_path / "pending" / "_delta_log").is_dir() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_retry_flushes_function_attachment_after_its_tables_are_durable( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A failed whole flush is retried even when function writes hit the cache.""" + job = PipelineJob(name="job", database=InMemoryArrowDatabase()) + with job: + total.pod(source, label="sum") + attached = DeltaTableDatabase(tmp_path) + job.nodes["sum"].attach_databases( + pipeline_database=attached, result_database=attached + ) + attached.add_record(("pending",), b"pending", pa.table({"value": [3]})) + + def fail() -> None: + raise OSError("temporary attachment flush failure") + + with monkeypatch.context() as patch: + patch.setattr(attached, "flush", fail) + with pytest.raises(OrcapodDatabaseWriteError): + await _run(job, runner) + assert len(list(tmp_path.rglob("_delta_log"))) == 2 + assert not (tmp_path / "pending" / "_delta_log").exists() + + await _run(job, runner) + assert job.nodes["sum"].as_table().num_rows == 2 + assert (tmp_path / "pending" / "_delta_log").is_dir() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +@pytest.mark.parametrize("wrapped", [False, True], ids=["native", "protocol"]) +async def test_connector_log_duplicates_use_the_native_upsert( + tmp_path: Path, runner: str, source: ArrowTableSource, *, wrapped: bool +) -> None: + """Native queues use ordinary whole flushes and the connector deduplicates.""" + connector = CommitConnector() + store = ConnectorArrowDatabase(connector) + attachment = ProtocolDatabase(store) if wrapped else store + job = _make_job(DeltaTableDatabase(tmp_path), attachment, source) + job.nodes["grouped"].run() + reopened = ConnectorArrowDatabase(connector) + existing_paths = reopened.list_table_paths() + assert len(existing_paths) == 1 + attachment.add_record(("pending",), b"pending", pa.table({"value": [3]})) + + for _ in range(2): + for label in ("other", "grouped"): + job.nodes[label].clear_cache() + await _run(job, runner) + assert job.nodes["grouped"].as_table().num_rows == 2 + assert (("pending",) in reopened.list_table_paths()) is not wrapped + committed = reopened.get_all_records(existing_paths[0]) + assert committed is not None and committed.num_rows == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +@pytest.mark.parametrize("scopes", ["descendant", "sibling", "sibling_auto_commit"]) +@pytest.mark.parametrize("fail_run", [False, True]) +async def test_an_alias_of_a_wrapped_job_store_keeps_main_flush_order( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, + scopes: str, + *, + fail_run: bool, +) -> None: + """The existing whole flushes cover an alias behind a protocol wrapper.""" + database = DeltaTableDatabase( + tmp_path, batch_size=2 if scopes == "sibling_auto_commit" else 1000 + ) + owner = () if scopes == "descendant" else ("owned",) + store = ProtocolDatabase(database.at(*owner)) + alias = store.at("alias") if scopes == "descendant" else database.at("alias") + job = _make_job(store, alias, source) + original_flush = DeltaTableDatabase.flush + paths: list[tuple[str, ...]] = [] + + def record_flush(database: DeltaTableDatabase) -> None: + paths.append(database.base_path) + original_flush(database) + + class FailRun(NoOpObserver): + def on_run_end(self, run_id: str) -> None: + raise RuntimeError("observer failed") + + monkeypatch.setattr(DeltaTableDatabase, "flush", record_flush) + if fail_run: + with pytest.raises(RuntimeError, match="observer failed"): + await _run(job, runner, observer=FailRun()) + else: + await _run(job, runner) + assert paths == [(*owner, "job"), (*owner, "job", "_result")] + (log,) = (tmp_path / "alias").rglob("_delta_log") + assert deltalake.DeltaTable(str(log.parent)).to_pyarrow_table().num_rows == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +@pytest.mark.parametrize("wrapped", [False, True], ids=["native", "extension_aware"]) +async def test_retry_commits_operator_logs_left_pending_by_a_failed_flush( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, + *, + wrapped: bool, +) -> None: + """A retry commits the same record IDs even though the queue deduplicates them.""" + store = DeltaTableDatabase(tmp_path / "attached") + attached = ( + ExtensionAwareDatabase(store, UniversalTypeConverter()) if wrapped else store + ) + job = _make_job(DeltaTableDatabase(tmp_path / "owned"), attached, source) + + def fail() -> None: + raise OSError("temporary attachment flush failure") + + with monkeypatch.context() as patch: + patch.setattr(attached, "flush", fail) + with pytest.raises(OrcapodDatabaseWriteError) as error: + await _run(job, runner) + assert error.value.flush + assert isinstance(error.value.__cause__, OSError) + assert job.nodes["grouped"].as_table().num_rows == 0 + assert not list((tmp_path / "attached").rglob("_delta_log")) + + await _run(job, runner) + (log,) = (tmp_path / "attached").rglob("_delta_log") + assert deltalake.DeltaTable(str(log.parent)).to_pyarrow_table().num_rows == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +@pytest.mark.parametrize("rebind", ["empty_source", "new_attachment"]) +async def test_retry_commits_pending_operator_logs_after_rebinding( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, + rebind: str, +) -> None: + """A failed attachment remains pending even when the node writes elsewhere.""" + old_root = tmp_path / "old" + attached = DeltaTableDatabase(old_root) + job = PipelineJob(name="job", database=InMemoryArrowDatabase()) + tags, data = source.output_schema() + with job: + _ = SelectDataColumns(list(data))(source, label="sink") + sink = job.nodes["sink"] + assert isinstance(sink, OperatorJobNode) + sink.attach_databases(pipeline_database=attached, cache_mode=CacheMode.LOG) + + def fail() -> None: + raise OSError("temporary attachment flush failure") + + with monkeypatch.context() as patch: + patch.setattr(attached, "flush", fail) + with pytest.raises(OrcapodDatabaseWriteError): + await _run(job, runner) + assert not list(old_root.rglob("_delta_log")) + + new_root = tmp_path / "new" + if rebind == "empty_source": + empty = ArrowTableSource( + source.table.select([*tags, *data]).slice(0, 0), + tag_columns=list(tags), + tag_only_columns=True, + source_id="empty", + ) + job.bind(sources={next(iter(job.sources)): empty}) + else: + sink.attach_databases( + pipeline_database=DeltaTableDatabase(new_root), cache_mode=CacheMode.LOG + ) + + await _run(job, runner) + (log,) = old_root.rglob("_delta_log") + assert deltalake.DeltaTable(str(log.parent)).to_pyarrow_table().num_rows == 2 + if rebind == "empty_source": + assert sink.as_table().num_rows == 0 + else: + (new_log,) = new_root.rglob("_delta_log") + assert ( + deltalake.DeltaTable(str(new_log.parent)).to_pyarrow_table().num_rows == 2 + ) + + attached.add_record(("pending",), b"pending", pa.table({"value": [3]})) + sink.clear_cache() + await _run(job, runner) + assert not (old_root / "pending" / "_delta_log").exists() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_an_attached_database_flush_includes_other_writes_after_auto_commit( + tmp_path: Path, runner: str, source: ArrowTableSource +) -> None: + """An automatic table commit still leaves the object eligible for a whole flush.""" + attached = DeltaTableDatabase(tmp_path / "attached", batch_size=2) + job = _make_job(DeltaTableDatabase(tmp_path / "owned"), attached, source) + attached.add_record(("pending",), b"pending", pa.table({"value": [3]})) + + await _run(job, runner) + assert (tmp_path / "attached" / "pending" / "_delta_log").is_dir() + assert len(list((tmp_path / "attached").rglob("_delta_log"))) == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +@pytest.mark.parametrize("fail_run", [False, True]) +async def test_retry_flushes_operator_attachment_after_auto_commit( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, + *, + fail_run: bool, +) -> None: + """Retry the whole flush even when the log table committed during the write.""" + root = tmp_path / "attached" + attached = DeltaTableDatabase(root, batch_size=2) + job = _make_job(DeltaTableDatabase(tmp_path / "owned"), attached, source) + attached.add_record(("pending",), b"pending", pa.table({"value": [3]})) + original_flush = attached.flush + calls = 0 + + def flush() -> None: + nonlocal calls + calls += 1 + if calls == 1: + raise OSError("temporary attachment flush failure") + original_flush() + + class FailRun(NoOpObserver): + @override + def on_run_end(self, run_id: str) -> None: + raise RuntimeError("observer failed") + + monkeypatch.setattr(attached, "flush", flush) + if fail_run: + with pytest.raises(RuntimeError, match="observer failed"): + await _run(job, runner, observer=FailRun()) + else: + with pytest.raises(OrcapodDatabaseWriteError) as error: + await _run(job, runner) + assert isinstance(error.value.__cause__, OSError) + assert calls == 1 + (log,) = root.rglob("_delta_log") + assert deltalake.DeltaTable(str(log.parent)).to_pyarrow_table().num_rows == 2 + assert not (root / "pending" / "_delta_log").exists() + + await _run(job, runner) + assert calls == 2 + assert (root / "pending" / "_delta_log").is_dir() + node = job.nodes["grouped"] + assert isinstance(node, OperatorJobNode) + node.clear_cache() + await _run(job, runner) + assert calls == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +@pytest.mark.parametrize("binding", ["same_view", "sibling", "wrapped_sibling"]) +async def test_retry_does_not_flush_an_attachment_again_after_binding_it_to_the_job( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, + binding: str, +) -> None: + """The regular job commit now covers the failed attachment's underlying store.""" + root = DeltaTableDatabase(tmp_path) + attached = root.at("attached") + job = PipelineJob(name="job", database=InMemoryArrowDatabase()) + with job: + _ = total.pod(source, label="sum") + node = job.nodes["sum"] + assert isinstance(node, FunctionJobNode) + node.attach_databases( + pipeline_database=InMemoryArrowDatabase(), result_database=attached + ) + attached.add_record(("pending",), b"pending", pa.table({"value": [3]})) + original_flush = DeltaTableDatabase.flush + paths: list[tuple[str, ...]] = [] + fail_next = True + + def flush(database: DeltaTableDatabase) -> None: + nonlocal fail_next + paths.append(database.base_path) + if fail_next: + fail_next = False + raise OSError("temporary attachment flush failure") + original_flush(database) + + monkeypatch.setattr(DeltaTableDatabase, "flush", flush) + with pytest.raises(OrcapodDatabaseWriteError) as error: + await _run(job, runner) + assert isinstance(error.value.__cause__, OSError) + assert paths == [("attached",)] + + result = attached if binding == "same_view" else root.at("result") + job.bind( + result_database=ProtocolDatabase(result) + if binding == "wrapped_sibling" + else result + ) + node.clear_cache() + paths.clear() + await _run(job, runner) + expected_count = 1 if binding == "wrapped_sibling" else 2 + assert paths == [result.base_path] * expected_count + assert (tmp_path / "attached" / "pending" / "_delta_log").is_dir() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_a_side_effect_log_is_committed_to_its_attachment( + tmp_path: Path, runner: str, source: ArrowTableSource +) -> None: + """A node that records delivery completion also enrolls its attached store.""" + job = PipelineJob(name="job", database=InMemoryArrowDatabase()) + + def deliver(ctx: InvocationContext, x: int, y: int) -> None: + """Successfully deliver the row.""" + + with job: + _ = SideEffectPod(deliver)(source, label="delivery") + job.nodes["delivery"].attach_databases(DeltaTableDatabase(tmp_path)) + + await _run(job, runner) + (log,) = tmp_path.rglob("_delta_log") + assert deltalake.DeltaTable(str(log.parent)).to_pyarrow_table().num_rows == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_failed_receipt_promotion_keeps_delivery_queued( + runner: str, source: ArrowTableSource, monkeypatch: pytest.MonkeyPatch +) -> None: + """A failure inside the flush keeps completed deliveries available for retry.""" + attached = InMemoryArrowDatabase() + job = PipelineJob(name="job", database=InMemoryArrowDatabase()) + delivered: list[tuple[int, int]] = [] + + def deliver(ctx: InvocationContext, x: int, y: int) -> None: + delivered.append((x, y)) + + with job: + _ = SideEffectPod(deliver)(source, label="delivery") + sink = job.nodes["delivery"] + sink.attach_databases(pipeline_database=attached) + + with monkeypatch.context() as patch: + patch.setattr( + attached, "_promote", Mock(side_effect=OSError("promotion failed")) + ) + with pytest.raises(OrcapodDatabaseWriteError, match="flush"): + await _run(job, runner) + (path,) = attached.list_table_paths() + buffered = attached.get_all_records(path) + assert buffered is not None and buffered.num_rows == 2 + + sink.clear_cache() + await _run(job, runner) + assert sorted(delivered) == [(1, 3), (2, 4)] + promote = Mock(wraps=attached._promote) # pyright: ignore[reportPrivateUsage] + monkeypatch.setattr(attached, "_promote", promote) + attached.flush() + promote.assert_not_called() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +@pytest.mark.parametrize("wrapped", [False, True], ids=["native", "extension_aware"]) +async def test_retry_commits_a_pending_side_effect_receipt_without_redelivery( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, + *, + wrapped: bool, +) -> None: + """A remembered delivery remains eligible for commit until it is durable.""" + job = PipelineJob(name="job", database=InMemoryArrowDatabase()) + delivered: list[tuple[int, int]] = [] + + def deliver(ctx: InvocationContext, x: int, y: int) -> None: + """Record each delivery to detect a repeated call.""" + delivered.append((x, y)) + + with job: + _ = SideEffectPod(deliver)(source, label="delivery") + store = DeltaTableDatabase(tmp_path) + attachment = ( + ExtensionAwareDatabase(store, UniversalTypeConverter()) if wrapped else store + ) + job.nodes["delivery"].attach_databases(attachment) + + def fail() -> None: + raise OSError("temporary attachment flush failure") + + with monkeypatch.context() as patch: + patch.setattr(attachment, "flush", fail) + with pytest.raises(OrcapodDatabaseWriteError): + await _run(job, runner) + assert not list(tmp_path.rglob("_delta_log")) + + await _run(job, runner) + assert sorted(delivered) == [(1, 3), (2, 4)] + (log,) = tmp_path.rglob("_delta_log") + assert deltalake.DeltaTable(str(log.parent)).to_pyarrow_table().num_rows == 2 + attachment.add_record(("pending",), b"pending", pa.table({"value": [3]})) + job.nodes["delivery"].clear_cache() + await _run(job, runner) + assert sorted(delivered) == [(1, 3), (2, 4)] + assert not (tmp_path / "pending" / "_delta_log").exists() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +@pytest.mark.parametrize("scenario", ["partial_threshold_failure", "durable_receipts"]) +async def test_attachment_retry_checks_all_receipts( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, + scenario: str, +) -> None: + """Retire a receipt retry only when all its IDs are durable.""" + partial = scenario == "partial_threshold_failure" + job = PipelineJob(name="job", database=InMemoryArrowDatabase()) + attached = DeltaTableDatabase(tmp_path, batch_size=2 if partial else 100) + second = DeltaTableDatabase(tmp_path) + delivered: list[tuple[int, int]] = [] + + def deliver(ctx: InvocationContext, x: int, y: int) -> None: + delivered.append((x, y)) + + with job: + _ = SideEffectPod( + deliver, config=SideEffectPodConfig(track_completion=not partial) + )(source, label="delivery") + job.nodes["delivery"].attach_databases(pipeline_database=attached) + + def fail_flush() -> None: + raise OSError("temporary whole-flush failure") + + def fail_threshold(path: tuple[str, ...]) -> None: + raise OSError("temporary threshold failure") + + with monkeypatch.context() as patch: + add_record = Mock(wraps=attached.add_record) + patch.setattr(attached, "add_record", add_record) + patch.setattr(attached, "flush", fail_flush) + if partial: + patch.setattr(attached, "flush_batch", fail_threshold) + with pytest.raises(OrcapodDatabaseWriteError): + await _run(job, runner) + path = add_record.call_args.args[0] + receipts = attached.get_all_records(path, "__record_id") + assert receipts is not None and receipts.num_rows == 2 + second.add_records(path, receipts.slice(0, 1) if partial else receipts, flush=True) + attached.refresh_table(path) + attached.add_record(("pending",), b"unrelated", pa.table({"value": [3]})) + await _run(job, runner) + + committed = DeltaTableDatabase(tmp_path).get_all_records(path) + assert committed is not None and committed.num_rows == 2 + assert (tmp_path / "pending" / "_delta_log").exists() == partial + if not partial: + assert sorted(delivered) == [(1, 3), (2, 4)] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_failed_attachment_write_preserves_original_error( + runner: str, source: ArrowTableSource, monkeypatch: pytest.MonkeyPatch +) -> None: + """A driver failure during the pending-row lookup cannot replace a write error.""" + connector = CommitConnector() + attached = ConnectorArrowDatabase(connector) + job = _make_job(InMemoryArrowDatabase(), attached, source) + write_error = OSError("original write failure") + write_failed = False + get_tables = connector.get_table_names + + def fail_write(records: pa.Table) -> None: + nonlocal write_failed + write_failed = True + raise write_error + + def get_table_names() -> list[str]: + if write_failed: + raise psycopg.OperationalError("pending-row lookup failed") + return get_tables() + + monkeypatch.setattr(connector, "validate_records", fail_write) + monkeypatch.setattr(connector, "get_table_names", get_table_names) + with pytest.raises(OrcapodDatabaseWriteError) as error: + await _run(job, runner) + assert error.value.__cause__ is write_error + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_load_only_skips_opaque_queue_probe( + runner: str, source: ArrowTableSource, monkeypatch: pytest.MonkeyPatch +) -> None: + """A forwarding wrapper needs no queue identity for a load-only run.""" + database = ConnectorArrowDatabase(CommitConnector()) + job = PipelineJob(name="job", database=ProtocolDatabase(database)) + with job: + total.pod(source, label="sum") + + probe = Mock(wraps=job_module._shared_queue) # pyright: ignore[reportPrivateUsage] # observe the job's queue probe + monkeypatch.setattr(job_module, "_shared_queue", probe) + await _run(job, runner, load_only=True) + probe.assert_not_called() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +@pytest.mark.parametrize("backend", ["delta", "connector"]) +async def test_wrapped_duplicate_replay_leaves_other_rows_pending( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, + backend: str, +) -> None: + """A forwarding attachment keeps main's whole-flush behavior on replay.""" + if backend == "delta": + root = tmp_path / "attached" + first, second = DeltaTableDatabase(root), DeltaTableDatabase(root) + else: + connector = CommitConnector() + first, second = ( + ConnectorArrowDatabase(connector), + ConnectorArrowDatabase(connector), + ) + attachment = ProtocolDatabase(first) + job = _make_job(InMemoryArrowDatabase(), attachment, source) + other = _make_job(InMemoryArrowDatabase(), second, source) + flushes: list[bool] = [] + original = attachment.flush + + def flush() -> None: + flushes.append(True) + if len(flushes) == 1: + raise OSError("temporary attachment flush failure") + original() + + monkeypatch.setattr(attachment, "flush", flush) + await _run(job, runner) + other.nodes["grouped"].run() + (log_path,) = second.list_table_paths() + attachment.refresh_table(log_path) + attachment.add_record(("pending",), b"pending", pa.table({"value": [3]})) + job.nodes["grouped"].clear_cache() + + await _run(job, runner) + assert second.list_table_paths() == [log_path] + assert not flushes + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_successful_owned_preflush_retires_attachment_retry( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A later owned commit error does not undo the successful pre-run flush.""" + attached = DeltaTableDatabase(tmp_path) + job = _make_job(InMemoryArrowDatabase(), attached, source) + + def fail() -> None: + raise OSError("temporary attachment flush failure") + + with monkeypatch.context() as patch: + patch.setattr(attached, "flush", fail) + with pytest.raises(OrcapodDatabaseWriteError): + await _run(job, runner) + + job.bind(database=attached) + job.nodes["grouped"].clear_cache() + original = DeltaTableDatabase.flush + phases: list[tuple[str, ...]] = [] + + def fail_final(database: DeltaTableDatabase) -> None: + phases.append(database.base_path) + if len(phases) == 2: + raise OSError("owned final flush failed after pre-run flush") + original(database) + + with monkeypatch.context() as patch: + patch.setattr(DeltaTableDatabase, "flush", fail_final) + with pytest.raises(OrcapodDatabaseWriteError): + await _run(job, runner) + assert phases == [("job",), ("job",)] + assert list(tmp_path.rglob("_delta_log")) + + job.bind(database=InMemoryArrowDatabase()) + job.nodes["grouped"].clear_cache() + attached.add_record(("pending",), b"pending", pa.table({"value": [3]})) + await _run(job, runner) + assert not (tmp_path / "pending" / "_delta_log").exists() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_retry_commits_operator_log_after_interrupted_attachment_flush( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An interruption propagates and the pending log remains eligible for retry.""" + attached = DeltaTableDatabase(tmp_path) + job = _make_job(InMemoryArrowDatabase(), attached, source) + + def interrupt() -> None: + raise KeyboardInterrupt + + with monkeypatch.context() as patch: + patch.setattr(attached, "flush", interrupt) + with pytest.raises(KeyboardInterrupt): + await _run(job, runner) + assert job.nodes["grouped"].as_table().num_rows == 0 + assert not list(tmp_path.rglob("_delta_log")) + + await _run(job, runner) + (log,) = tmp_path.rglob("_delta_log") + assert deltalake.DeltaTable(str(log.parent)).to_pyarrow_table().num_rows == 2 diff --git a/tests/test_pipeline/test_mixed_function_commits.py b/tests/test_pipeline/test_mixed_function_commits.py index d5c6b9b64..dfa36e3f6 100644 --- a/tests/test_pipeline/test_mixed_function_commits.py +++ b/tests/test_pipeline/test_mixed_function_commits.py @@ -171,6 +171,7 @@ def test_mixed_database_batches_keep_main_cadence( ) whole_flushes: dict[type, int] = defaultdict(int) promotions: dict[str, list[int]] = defaultdict(list) + attached_result_flushes = 0 flush_memory = InMemoryArrowDatabase.flush flush_noop = NoOpArrowDatabase.flush promote = getattr(InMemoryArrowDatabase, "flush_pending_table", None) @@ -186,7 +187,11 @@ def record_promotions(db: InMemoryArrowDatabase, before: dict[str, int]) -> None promotions[key.split("/")[-1]].append(inserted) def observe_memory(db: InMemoryArrowDatabase) -> None: - whole_flushes[InMemoryArrowDatabase] += 1 + nonlocal attached_result_flushes + if db is results: + attached_result_flushes += 1 + else: + whole_flushes[InMemoryArrowDatabase] += 1 before = heap_rows(db) flush_memory(db) record_promotions(db, before) @@ -214,6 +219,9 @@ def observe_promotion(db: InMemoryArrowDatabase, path: tuple[str, ...]) -> None: # 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) + assert attached_result_flushes == int( + result_kind == "memory" and pipeline_kind != "noop" + ) if pipeline_kind == "memory": assert whole_flushes[InMemoryArrowDatabase] == expected_whole assert promotions[PIPELINE] == pipeline_batches @@ -469,7 +477,7 @@ def fail_result(*args: object, **kwargs: object) -> None: class DatabaseWithoutCommitGuards: """Stand-in for the database interface without the required commit methods.""" - def __init__(self, inner: InMemoryArrowDatabase) -> None: + def __init__(self, inner: ArrowDatabaseProtocol) -> None: self._inner = inner def add_record(self, *args: Any, **kwargs: Any) -> None: @@ -614,4 +622,10 @@ def observe_flush(database: InMemoryArrowDatabase) -> None: 19, 22, ] - assert calls == [("pipeline", "mixed")] * 4 + [("pipeline", "mixed", "_result")] + expected: list[tuple[str, ...]] = [("pipeline", "mixed")] * 4 + expected.append(("pipeline", "mixed", "_result")) + # Only this placement gives the node an independently attached native result + # store. Opaque result wrappers keep the same whole flushes as main. + if placement == "pipeline": + expected.append(("result",)) + assert calls == expected