From 014150e131e8d109867e131d1f1252a03aef2c49 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:34:48 -0800 Subject: [PATCH 01/16] fix(pipeline): flush databases attached to nodes at the end of job runs --- changelog.d/ITL-1383.md | 3 + docs/dev/design_issues/ITL-1383-BL3.md | 16 ++ src/orcapod/pipeline/job.py | 58 +++----- src/orcapod/pipeline/node_run.py | 34 +++-- .../test_job_attached_database_commit.py | 140 ++++++++++++++++++ 5 files changed, 203 insertions(+), 48 deletions(-) create mode 100644 changelog.d/ITL-1383.md create mode 100644 docs/dev/design_issues/ITL-1383-BL3.md create mode 100644 tests/test_pipeline/test_job_attached_database_commit.py diff --git a/changelog.d/ITL-1383.md b/changelog.d/ITL-1383.md new file mode 100644 index 000000000..a1e4e2877 --- /dev/null +++ b/changelog.d/ITL-1383.md @@ -0,0 +1,3 @@ +### Fixed + +- Job runs now flush database objects attached directly to their nodes, so buffered operator logs are stored when the run returns. 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..053538eb8 --- /dev/null +++ b/docs/dev/design_issues/ITL-1383-BL3.md @@ -0,0 +1,16 @@ +## `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:** The final commit uses the database objects attached to the nodes that +ran. It flushes each object once, with result databases first. Load-only runs +skip the commit. A failed flush clears the current rows of the nodes that ran +and leaves previously held rows available. diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 82f59257c..80a22f20a 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -31,6 +31,7 @@ check_sources, clear_run_rows, plan_run, + run_databases, ) from orcapod.pipeline.restrictions import ( refuse_restricted_operator_caches, @@ -1511,49 +1512,32 @@ def _finish_run( OrcapodDatabaseReadError: As for ``run``. OrcapodDatabaseWriteError: As for ``run``. """ - pipeline_db = prepared.pipeline_db - result_db = prepared.result_db - # Flush databases. Every view of the database shares one set of pending - # batches, so a failed batch can leave the ones after it unwritten. pending_note = ( "Writes that were still pending when the flush failed, such as a " + "cache_mode=LOG operator's output or a node's last records, may not " + "have been stored." ) - database = pipeline_db - try: - if not load_only and plan.to_run: - # A load-only run writes nothing and commits nothing, and a run that - # ran no node touches no database (ITL-1095). - # 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() - database = result_db + # A load-only run writes nothing. Held nodes belong to earlier runs (ITL-1095). + databases = [] if load_only else run_databases(plan.to_run) + for database in databases: + try: database.flush() - 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. - clear_run_rows(plan.to_run) - raise - except Exception as exc: - 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 + except OrcapodDatabaseReadError as exc: + # A stored table could not be read: report the read failure itself. + exc.add_note(pending_note) + clear_run_rows(plan.to_run) + raise + except Exception as exc: + 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 leaves the commit's outcome unknown. + clear_run_rows(plan.to_run) + raise # Mutate self in place. self._has_run = True diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index b1799c170..041309c31 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -26,6 +26,7 @@ ) from orcapod.pipeline.restrictions import restrictions_in_force, source_name from orcapod.pipeline.result import StreamsOnRead +from orcapod.types import CacheMode from orcapod.utils.database_errors import flush_best_effort if TYPE_CHECKING: @@ -128,22 +129,33 @@ def refuse_unloadable_inputs(node: Any) -> None: ) -def _databases(nodes: list[Any]) -> list[ArrowDatabaseProtocol]: - """The distinct databases the given nodes write to, each node's results first. +def run_databases(nodes: Sequence[Any]) -> list[ArrowDatabaseProtocol]: + """Collect distinct database objects the given nodes can write to. - A function node's result database comes before its pipeline database, so the - end-of-run commit stores results before the records that point at them (ITL-919), - also when the results are in a separate database (ITL-1408). + Results come first to release any pending records that depend on them + (ITL-1412). Separate objects at the same storage location can hold different + pending writes. """ - found: list[ArrowDatabaseProtocol] = [] + from orcapod.core.nodes.function_node import FunctionJobNode + from orcapod.core.nodes.operator_node import OperatorJobNode + + results: list[ArrowDatabaseProtocol] = [] + pipelines: list[ArrowDatabaseProtocol] = [] for node in nodes: + if isinstance(node, OperatorJobNode) and node.cache_mode != CacheMode.LOG: + continue pipeline_database = getattr(node, "_pipeline_database", None) + if pipeline_database is not None: + pipelines.append(pipeline_database) cached_pod = getattr(node, "_cached_function_pod", None) result_database = getattr(cached_pod, "result_database", None) - for database in (result_database, pipeline_database): - if database is not None and not any(database is d for d in found): - found.append(database) - return found + if result_database is not None: + results.append(result_database) + if isinstance(node, FunctionJobNode) and node.node_config.is_result_ephemeral: + ephemeral = node.ephemeral_result_database + if ephemeral is not None: + results.append(ephemeral) + return list({id(database): database for database in results + pipelines}.values()) def _job_name(node: Any) -> str: @@ -445,7 +457,7 @@ def visit(node: Any) -> None: visit(target) plan = plan_run(graph, load_only=load_only, outside=outside) - databases = _databases(plan.to_run) + databases = [] if load_only else run_databases(plan.to_run) counter = RunCountingObserver() try: _ = SyncPipelineOrchestrator().run( 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..159a28b04 --- /dev/null +++ b/tests/test_pipeline/test_job_attached_database_commit.py @@ -0,0 +1,140 @@ +"""A run commits the database objects its nodes actually write to (ITL-1383).""" + +from __future__ import annotations + +from pathlib import Path + +import deltalake +import pytest +import pyarrow as pa + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators import GroupBy, SelectDataColumns +from orcapod.databases import DeltaTableDatabase +from orcapod.errors import OrcapodDatabaseWriteError +from orcapod.pipeline import AsyncPipelineOrchestrator +from orcapod.sources import DictSource +from orcapod.types import CacheMode + +RUNNERS = ("sync", "async", "run_async", "node") + + +@function_pod(output_keys="y") +def increment(x: int) -> int: + """Return the next integer.""" + return x + 1 + + +async def _run(job: PipelineJob, runner: str, *, load_only: bool = False) -> 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) + else: + orchestrator = AsyncPipelineOrchestrator() if runner == "async" else None + job.run(orchestrator=orchestrator, load_only=load_only) + + +def _make_job(store: DeltaTableDatabase, attached: DeltaTableDatabase) -> PipelineJob: + """Route an operator's log to an independently constructed database.""" + source = DictSource( + [{"group": 0, "x": 1}, {"group": 1, "x": 2}], + tag_columns=["group"], + tag_only_columns=True, + source_id="source", + ) + job = PipelineJob(name="job", database=store) + with job: + selected = SelectDataColumns(["x"])(source, label="other") + GroupBy(by=["group"])(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 +) -> 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") + ) + 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.parametrize("asynchronous", [False, True]) +def test_a_manually_attached_function_store_is_committed( + tmp_path: Path, *, asynchronous: bool +) -> None: + """Function nodes already commit both their result and pipeline tables.""" + source = DictSource( + [{"k": 0, "x": 1}, {"k": 1, "x": 2}], + tag_columns=["k"], + tag_only_columns=True, + source_id="source", + ) + job = PipelineJob(name="job", database=DeltaTableDatabase(tmp_path)) + with job: + increment.pod(source, label="inc") + job.nodes["inc"].attach_databases( + pipeline_database=DeltaTableDatabase(tmp_path).at("mine") + ) + orchestrator = AsyncPipelineOrchestrator() if asynchronous else None + job.run(orchestrator=orchestrator) + logs = list((tmp_path / "mine").rglob("_delta_log")) + assert {log.parent.name for log in logs} == {"pdb_v2", "rdb_v1"} + assert all( + deltalake.DeltaTable(str(log.parent)).to_pyarrow_table().num_rows == 2 + for log in logs + ) + + +@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 +) -> 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) + 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, 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) + 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 From 99d729db4c1bec65ec4a0a68a9585ca490ac0816 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 05:14:06 -0800 Subject: [PATCH 02/16] fix(pipeline): preserve job commit order for attached stores --- changelog.d/ITL-1383.md | 2 +- docs/dev/design_issues/ITL-1383-BL3.md | 9 +- src/orcapod/core/nodes/function_node.py | 11 +- src/orcapod/core/nodes/operator_node.py | 25 +- src/orcapod/core/result_cache.py | 17 +- src/orcapod/databases/_write_tracking.py | 92 ++++++ .../databases/connector_arrow_database.py | 2 + src/orcapod/databases/delta_lake_databases.py | 2 + .../databases/extension_aware_database.py | 5 + src/orcapod/databases/in_memory_databases.py | 2 + src/orcapod/pipeline/job.py | 93 ++++-- src/orcapod/pipeline/node_run.py | 34 +- src/orcapod/side_effects.py | 14 +- .../test_job_attached_database_commit.py | 301 +++++++++++++++--- 14 files changed, 496 insertions(+), 113 deletions(-) create mode 100644 src/orcapod/databases/_write_tracking.py diff --git a/changelog.d/ITL-1383.md b/changelog.d/ITL-1383.md index a1e4e2877..8c11623f2 100644 --- a/changelog.d/ITL-1383.md +++ b/changelog.d/ITL-1383.md @@ -1,3 +1,3 @@ ### Fixed -- Job runs now flush database objects attached directly to their nodes, so buffered operator logs are stored when the run returns. +- Job runs flush additional databases with pending node writes after the job's own databases, including on the best-effort commit path after an execution error. diff --git a/docs/dev/design_issues/ITL-1383-BL3.md b/docs/dev/design_issues/ITL-1383-BL3.md index 053538eb8..fef3bf68b 100644 --- a/docs/dev/design_issues/ITL-1383-BL3.md +++ b/docs/dev/design_issues/ITL-1383-BL3.md @@ -10,7 +10,8 @@ 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:** The final commit uses the database objects attached to the nodes that -ran. It flushes each object once, with result databases first. Load-only runs -skip the commit. A failed flush clears the current rows of the nodes that ran -and leaves previously held rows available. +**Fix:** After the job's usual commit, the run flushes each additional database +object with node writes left to commit, once. It also makes this attempt 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. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 9809760af..ecf73f529 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -72,6 +72,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.databases._write_tracking import ( + finish_database_table_write, + track_database_write, +) from orcapod.errors import ( EphemeralResultMissingError, InputValidationError, @@ -2438,6 +2442,7 @@ def _flush_node_table( flush=True, table_flush=True, ) from exc + finish_database_table_write(database, path) def _commit_pending_writes(self) -> None: """Commit results before publishing any records that depend on them.""" @@ -2502,7 +2507,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), + ): 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 4f4632f3d..0a2e54d8e 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -66,6 +66,7 @@ ) from orcapod.core.tracker import DEFAULT_TRACKER_MANAGER from orcapod.core.nodes.staleness import RunHoldingNode +from orcapod.databases._write_tracking import track_database_write from orcapod.errors import ( InputValidationError, PipelineJobRequiredError, @@ -1504,23 +1505,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, has_rows=n_rows > 0): + 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 e341983bf..da02320a2 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.databases._write_tracking import track_database_write from orcapod.errors import ( InputValidationError, OrcapodDatabaseReadError, @@ -477,18 +478,20 @@ def store( ) data_table = with_data_context(data_table, data_context_key) + path = self._versioned_record_path 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): + self._result_database.add_record( + path, + output_data.datagram_uuid.bytes, + 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/_write_tracking.py b/src/orcapod/databases/_write_tracking.py new file mode 100644 index 000000000..d04c15324 --- /dev/null +++ b/src/orcapod/databases/_write_tracking.py @@ -0,0 +1,92 @@ +"""Track the database objects that accept a job's node writes.""" + +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar +from typing import TYPE_CHECKING, Protocol + +if TYPE_CHECKING: + from orcapod.databases._pending_commits import PendingCommits + + +class WriteDatabase(Protocol): + """The part of the database interface used to track a node's writes.""" + + @property + def stores_records(self) -> bool: + """Whether the database stores rows when asked to insert them.""" + ... + + +WriteKey = tuple[int, tuple[str, ...]] +DatabaseWrites = dict[WriteKey, WriteDatabase] + +_run_writes: ContextVar[DatabaseWrites | None] = ContextVar("_run_writes", default=None) +_current_write: ContextVar[tuple[object, WriteKey, WriteDatabase] | None] = ContextVar( + "_current_write", default=None +) + + +def database_queue(database: WriteDatabase) -> object: + """Identify the pending queue that a whole flush covers, shared by scoped views.""" + queue = getattr(database, "_pending_commits", None) + return database if queue is None else queue + + +@contextmanager +def collect_database_writes( + writes: DatabaseWrites, +) -> Iterator[None]: + """Collect node writes for one job execution, including its async tasks.""" + run_token = _run_writes.set(writes) + write_token = _current_write.set(None) + try: + yield + finally: + _current_write.reset(write_token) + _run_writes.reset(run_token) + + +@contextmanager +def track_database_write( + database: WriteDatabase, path: tuple[str, ...], *, has_rows: bool = True +) -> Iterator[None]: + """Track an insert only if it queued rows, before any automatic flush.""" + writes = _run_writes.get() + key = (id(database), path) + if writes is None or key in writes or not has_rows or not database.stores_records: + yield + return + + queue = database_queue(database) + if queue is database: + # The protocol's add methods give no receipt. For a custom database + # without a queue, treat a successfully completed add as a write. + yield + writes[key] = database + return + + token = _current_write.set((queue, key, database)) + try: + yield + finally: + _current_write.reset(token) + + +def note_queued_write(queue: PendingCommits) -> None: + """Record a node write after deduplication and before automatic publication.""" + active = _current_write.get() + if active is not None and active[0] is queue: + writes = _run_writes.get() + if writes is not None: + _, key, database = active + writes[key] = database + + +def finish_database_table_write(database: WriteDatabase, path: tuple[str, ...]) -> None: + """Retire a table handled by the node's own commit, including dry-run results.""" + writes = _run_writes.get() + if writes is not None: + _ = writes.pop((id(database), path), None) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 267caf622..144aaf8b4 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -33,6 +33,7 @@ require_store_table_owner, stored_path, ) +from orcapod.databases._write_tracking import note_queued_write from orcapod.databases.store_table_names import ( STORE_TABLE_NAME_PREFIX, store_table_name, @@ -674,6 +675,7 @@ def add_records( self._pending_record_ids[record_key].update( cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist()) ) + note_queued_write(self._pending_commits) if flush: self.flush() diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index c88b322d8..6051d8638 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -26,6 +26,7 @@ matching_rows, rows_at, ) +from orcapod.databases._write_tracking import note_queued_write from orcapod.databases.delta_arrow_types import ( ARROW_TYPE_KEY, first_column_out_of_stored_range, @@ -2852,6 +2853,7 @@ def add_records( # Step 7: Add to pending batch (no overwrite logic needed) self._add_to_pending_batch(record_path, schema_compatible_table) + note_queued_write(self._pending_commits) # Step 8: Flush if asked to; otherwise commit this table alone once its # pending batch reaches batch_size. Only the full table: committing every diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index bbb891f2e..ab4568919 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -198,6 +198,11 @@ def validate_records(self, records: pa.Table) -> None: if isinstance(self._db, RecordValidatingDatabaseProtocol): self._db.validate_records(records) + @property + def _pending_commits(self) -> object | None: + """Forward the identity of the shared pending queue for write tracking.""" + return getattr(self._db, "_pending_commits", None) + def flush(self) -> None: self._db.flush() diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 2ccb4d696..460b50b9f 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -11,6 +11,7 @@ from orcapod.databases._pending_commits import PendingCommit, PendingCommits from orcapod.databases._row_index import KeyIndex, compact_tail, matching_rows +from orcapod.databases._write_tracking import note_queued_write from orcapod.databases.utils import ( coerce_record_id, first_changed_column, @@ -336,6 +337,7 @@ def add_records( ) pending_ids = cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist()) self._pending_record_ids[record_key].update(pending_ids) + note_queued_write(self._pending_commits) if flush: self.flush() diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 80a22f20a..4d3b54f7a 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -7,7 +7,7 @@ import logging import sys from collections.abc import Iterator -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, cast import orcapod @@ -19,6 +19,7 @@ from orcapod.core.streams.base import StreamBase from orcapod.side_effects import SideEffectJobNode, SideEffectNode from orcapod.core.tracker import AutoRegisteringContextBasedTracker +from orcapod.databases._write_tracking import collect_database_writes, database_queue from orcapod.errors import ( OrcapodDatabaseError, OrcapodDatabaseReadError, @@ -31,7 +32,6 @@ check_sources, clear_run_rows, plan_run, - run_databases, ) from orcapod.pipeline.restrictions import ( refuse_restricted_operator_caches, @@ -53,6 +53,7 @@ if TYPE_CHECKING: from pathlib import Path + from orcapod.databases._write_tracking import DatabaseWrites from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.execution_context import ExecutionContext from orcapod.pipeline.graph import Pipeline @@ -90,6 +91,8 @@ 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. + owned_queues: The pending queues already covered by the job's commit. + pending_node_writes: The node writes left for the job to commit. 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). @@ -102,6 +105,20 @@ class _PreparedRun: result_db: "ArrowDatabaseProtocol" plan: "RunPlan" unchecked_sources: tuple[str, ...] + owned_queues: tuple[object, ...] + pending_node_writes: "DatabaseWrites" = field(default_factory=dict) + + def additional_databases(self) -> "Iterator[ArrowDatabaseProtocol]": + """Yield additional database objects with writes left for the job to commit.""" + databases = { + identity: database + for (identity, _), database in self.pending_node_writes.items() + } + for database in databases.values(): + queue = database_queue(database) + if all(queue is not owned for owned in self.owned_queues): + # Every node's write path supplies an ArrowDatabaseProtocol. + yield cast("ArrowDatabaseProtocol", database) def _with_counter( @@ -178,6 +195,7 @@ 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, ...]" = () # 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 @@ -668,6 +686,7 @@ def _distribute_databases(self) -> None: ) elif isinstance(node, SideEffectJobNode): node.attach_databases(pipeline_database=pipeline_db) + self._node_database_views = (pipeline_db, result_db) # ------------------------------------------------------------------ # _iter_function_job_nodes() / apply_node_config() @@ -1431,6 +1450,10 @@ def _prepare_run( result_db=result_db, plan=plan, unchecked_sources=unchecked, + owned_queues=tuple( + database_queue(database) + for database in (pipeline_db, result_db, *self._node_database_views) + ), ) @contextlib.contextmanager @@ -1455,7 +1478,10 @@ def _executing( load_only: As for ``run``. """ try: - with contextlib.ExitStack() as batched: + with ( + collect_database_writes(prepared.pending_node_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): @@ -1478,6 +1504,7 @@ def _executing( if self._result_database is not None else () ), + *prepared.additional_databases(), ) clear_run_rows(plan.to_run) raise @@ -1512,32 +1539,52 @@ def _finish_run( OrcapodDatabaseReadError: As for ``run``. OrcapodDatabaseWriteError: As for ``run``. """ + pipeline_db = prepared.pipeline_db + result_db = prepared.result_db + # Flush databases. Every view of the database shares one set of pending + # batches, so a failed batch can leave the ones after it unwritten. pending_note = ( "Writes that were still pending when the flush failed, such as a " + "cache_mode=LOG operator's output or a node's last records, may not " + "have been stored." ) - # A load-only run writes nothing. Held nodes belong to earlier runs (ITL-1095). - databases = [] if load_only else run_databases(plan.to_run) - for database in databases: - try: + database = pipeline_db + try: + if not load_only and plan.to_run: + # A load-only run writes nothing and commits nothing, and a run that + # ran no node touches no database (ITL-1095). + # 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() - except OrcapodDatabaseReadError as exc: - # A stored table could not be read: report the read failure itself. - exc.add_note(pending_note) - clear_run_rows(plan.to_run) - raise - except Exception as exc: - 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 leaves the commit's outcome unknown. - clear_run_rows(plan.to_run) - raise + database = result_db + database.flush() + 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() + # Node writes can target their own database objects (ITL-1383). + for database in prepared.additional_databases(): + 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. + clear_run_rows(plan.to_run) + raise + except Exception as exc: + 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/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 041309c31..b1799c170 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -26,7 +26,6 @@ ) from orcapod.pipeline.restrictions import restrictions_in_force, source_name from orcapod.pipeline.result import StreamsOnRead -from orcapod.types import CacheMode from orcapod.utils.database_errors import flush_best_effort if TYPE_CHECKING: @@ -129,33 +128,22 @@ def refuse_unloadable_inputs(node: Any) -> None: ) -def run_databases(nodes: Sequence[Any]) -> list[ArrowDatabaseProtocol]: - """Collect distinct database objects the given nodes can write to. +def _databases(nodes: list[Any]) -> list[ArrowDatabaseProtocol]: + """The distinct databases the given nodes write to, each node's results first. - Results come first to release any pending records that depend on them - (ITL-1412). Separate objects at the same storage location can hold different - pending writes. + A function node's result database comes before its pipeline database, so the + end-of-run commit stores results before the records that point at them (ITL-919), + also when the results are in a separate database (ITL-1408). """ - from orcapod.core.nodes.function_node import FunctionJobNode - from orcapod.core.nodes.operator_node import OperatorJobNode - - results: list[ArrowDatabaseProtocol] = [] - pipelines: list[ArrowDatabaseProtocol] = [] + found: list[ArrowDatabaseProtocol] = [] for node in nodes: - if isinstance(node, OperatorJobNode) and node.cache_mode != CacheMode.LOG: - continue pipeline_database = getattr(node, "_pipeline_database", None) - if pipeline_database is not None: - pipelines.append(pipeline_database) cached_pod = getattr(node, "_cached_function_pod", None) result_database = getattr(cached_pod, "result_database", None) - if result_database is not None: - results.append(result_database) - if isinstance(node, FunctionJobNode) and node.node_config.is_result_ephemeral: - ephemeral = node.ephemeral_result_database - if ephemeral is not None: - results.append(ephemeral) - return list({id(database): database for database in results + pipelines}.values()) + for database in (result_database, pipeline_database): + if database is not None and not any(database is d for d in found): + found.append(database) + return found def _job_name(node: Any) -> str: @@ -457,7 +445,7 @@ def visit(node: Any) -> None: visit(target) plan = plan_run(graph, load_only=load_only, outside=outside) - databases = [] if load_only else run_databases(plan.to_run) + databases = _databases(plan.to_run) counter = RunCountingObserver() try: _ = SyncPipelineOrchestrator().run( diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index dd691c62d..1cc890071 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -38,6 +38,7 @@ StreamView, ) from orcapod.core.tracker import DEFAULT_TRACKER_MANAGER +from orcapod.databases._write_tracking import track_database_write from orcapod.errors import ( OrcapodDatabaseError, OrcapodDatabaseReadError, @@ -560,12 +561,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_pipeline/test_job_attached_database_commit.py b/tests/test_pipeline/test_job_attached_database_commit.py index 159a28b04..bfd750372 100644 --- a/tests/test_pipeline/test_job_attached_database_commit.py +++ b/tests/test_pipeline/test_job_attached_database_commit.py @@ -5,49 +5,81 @@ from pathlib import Path import deltalake -import pytest import pyarrow as pa +import pytest from orcapod import PipelineJob, function_pod from orcapod.core.operators import GroupBy, SelectDataColumns -from orcapod.databases import DeltaTableDatabase +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.errors import OrcapodDatabaseWriteError +from orcapod.invocation import InvocationContext from orcapod.pipeline import AsyncPipelineOrchestrator -from orcapod.sources import DictSource -from orcapod.types import CacheMode +from orcapod.pipeline.observer import NoOpObserver +from orcapod.protocols.observability_protocols import ExecutionObserverProtocol +from orcapod.side_effects import SideEffectPod +from orcapod.sources import ArrowTableSource +from orcapod.types import CacheMode, NodeConfig + +JOB_RUNNERS = ("sync", "async", "run_async") +RUNNERS = (*JOB_RUNNERS, "node") -RUNNERS = ("sync", "async", "run_async", "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="y") -def increment(x: int) -> int: - """Return the next integer.""" - return x + 1 +@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) -> None: +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) + 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) + job.run(orchestrator=orchestrator, load_only=load_only, observer=observer) -def _make_job(store: DeltaTableDatabase, attached: DeltaTableDatabase) -> PipelineJob: +def _make_job( + store: DeltaTableDatabase, attached: DeltaTableDatabase, source: ArrowTableSource +) -> PipelineJob: """Route an operator's log to an independently constructed database.""" - source = DictSource( - [{"group": 0, "x": 1}, {"group": 1, "x": 2}], - tag_columns=["group"], - tag_only_columns=True, - source_id="source", - ) job = PipelineJob(name="job", database=store) with job: - selected = SelectDataColumns(["x"])(source, label="other") - GroupBy(by=["group"])(selected, label="grouped") + 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 ) @@ -60,11 +92,11 @@ def _make_job(store: DeltaTableDatabase, attached: DeltaTableDatabase) -> Pipeli @pytest.mark.asyncio @pytest.mark.parametrize("runner", RUNNERS) async def test_a_run_commits_a_manually_attached_operator_log( - tmp_path: Path, runner: str + 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") + DeltaTableDatabase(tmp_path), DeltaTableDatabase(tmp_path).at("mine"), source ) await _run(job, runner) node = job.nodes["grouped"] @@ -78,19 +110,13 @@ async def test_a_run_commits_a_manually_attached_operator_log( @pytest.mark.parametrize("asynchronous", [False, True]) def test_a_manually_attached_function_store_is_committed( - tmp_path: Path, *, asynchronous: bool + tmp_path: Path, source: ArrowTableSource, *, asynchronous: bool ) -> None: """Function nodes already commit both their result and pipeline tables.""" - source = DictSource( - [{"k": 0, "x": 1}, {"k": 1, "x": 2}], - tag_columns=["k"], - tag_only_columns=True, - source_id="source", - ) job = PipelineJob(name="job", database=DeltaTableDatabase(tmp_path)) with job: - increment.pod(source, label="inc") - job.nodes["inc"].attach_databases( + total.pod(source, label="sum") + job.nodes["sum"].attach_databases( pipeline_database=DeltaTableDatabase(tmp_path).at("mine") ) orchestrator = AsyncPipelineOrchestrator() if asynchronous else None @@ -106,11 +132,11 @@ def test_a_manually_attached_function_store_is_committed( @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 + 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) + 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 @@ -120,11 +146,14 @@ async def test_load_only_does_not_commit_a_manually_attached_store( @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, monkeypatch: pytest.MonkeyPatch + 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) + job = _make_job(DeltaTableDatabase(tmp_path), attached, source) held = job.nodes["other"] held.run() @@ -138,3 +167,203 @@ def fail() -> None: 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_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) +async def test_logging_nodes_sharing_one_database_flush_it_once( + tmp_path: Path, + runner: str, + source: ArrowTableSource, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Both logs are durable after one shared flush following the owned flush.""" + store = DeltaTableDatabase(tmp_path / "owned") + attached = DeltaTableDatabase(tmp_path / "attached") + job = _make_job(store, attached, source) + job.nodes["other"].attach_databases( + pipeline_database=attached, 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(attached, "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) +async def test_duplicate_operator_logs_do_not_flush_an_attached_store( + tmp_path: Path, runner: str, source: ArrowTableSource +) -> None: + """An all-duplicate insert leaves unrelated pending writes alone on a rerun.""" + attached = DeltaTableDatabase(tmp_path / "attached") + job = _make_job(DeltaTableDatabase(tmp_path / "owned"), attached, source) + await _run(job, runner) + 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_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 From 8d807c48dbf7f9215c9ff811fd157067fc7e7f64 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 06:31:43 -0800 Subject: [PATCH 03/16] fix(pipeline): retry and deduplicate attached database commits --- changelog.d/ITL-1383.md | 2 +- docs/concepts/pipeline-job.md | 4 ++ docs/dev/design_issues/ITL-1383-BL3.md | 9 +-- src/orcapod/core/nodes/function_node.py | 2 +- src/orcapod/core/nodes/operator_node.py | 2 +- src/orcapod/core/result_cache.py | 5 +- src/orcapod/databases/_write_tracking.py | 52 +++++++++----- .../databases/connector_arrow_database.py | 1 + src/orcapod/databases/delta_lake_databases.py | 3 + src/orcapod/databases/in_memory_databases.py | 5 +- src/orcapod/pipeline/job.py | 18 +++-- src/orcapod/side_effects.py | 2 +- .../test_job_attached_database_commit.py | 72 +++++++++++++++++-- .../test_mixed_function_commits.py | 2 +- 14 files changed, 132 insertions(+), 47 deletions(-) diff --git a/changelog.d/ITL-1383.md b/changelog.d/ITL-1383.md index 8c11623f2..45de1ae15 100644 --- a/changelog.d/ITL-1383.md +++ b/changelog.d/ITL-1383.md @@ -1,3 +1,3 @@ ### Fixed -- Job runs flush additional databases with pending node writes after the job's own databases, including on the best-effort commit path after an execution error. +- 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 retry can commit log rows left pending by a failed flush. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 0515f10ac..fdb9e19ac 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -338,6 +338,10 @@ 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 the job's own databases are committed, a database a job node writes to through +a separate attachment is flushed once, together with anything else pending in that +database object. Scoped views sharing its pending writes share that flush. + ## `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 index fef3bf68b..e1739bbcf 100644 --- a/docs/dev/design_issues/ITL-1383-BL3.md +++ b/docs/dev/design_issues/ITL-1383-BL3.md @@ -11,7 +11,8 @@ only the job's database views. Independently constructed objects could have sepa pending writes even when they used the same storage location. **Fix:** After the job's usual commit, the run flushes each additional database -object with node writes left to commit, once. It also makes this attempt 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. +object that accepted node writes once, including anything else pending in the +object. Scoped views share a flush. 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 if they are still pending. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index ecf73f529..1bbdd5d69 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -2510,7 +2510,7 @@ def _write_pipeline_record( with ( database.guard_table_schema(path, check), result_guard, - track_database_write(database, path), + track_database_write(database, path, (row_key,)), ): database.add_record(path, row_key, record, skip_duplicates=True) diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 0a2e54d8e..3fa407c0a 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1507,7 +1507,7 @@ def _store_output_stream(self, stream: StreamProtocol) -> None: # it names the generation of hashing that produced them and is not hashed. path = self._stored_table_path try: - with track_database_write(pipeline_database, path, has_rows=n_rows > 0): + with track_database_write(pipeline_database, path, record_hashes): pipeline_database.add_records( path, with_data_context( diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index da02320a2..aebc16fda 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -479,11 +479,12 @@ 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: - with track_database_write(self._result_database, path): + with track_database_write(self._result_database, path, (result_id,)): self._result_database.add_record( path, - output_data.datagram_uuid.bytes, + result_id, data_table, skip_duplicates=skip_duplicates, ) diff --git a/src/orcapod/databases/_write_tracking.py b/src/orcapod/databases/_write_tracking.py index d04c15324..581ad22ea 100644 --- a/src/orcapod/databases/_write_tracking.py +++ b/src/orcapod/databases/_write_tracking.py @@ -2,13 +2,13 @@ from __future__ import annotations -from collections.abc import Iterator +from collections.abc import Iterator, Sequence from contextlib import contextmanager from contextvars import ContextVar from typing import TYPE_CHECKING, Protocol if TYPE_CHECKING: - from orcapod.databases._pending_commits import PendingCommits + from orcapod.databases._pending_commits import PendingCommit, PendingCommits class WriteDatabase(Protocol): @@ -19,9 +19,15 @@ def stores_records(self) -> bool: """Whether the database stores rows when asked to insert them.""" ... + def pending_result( + self, record_path: tuple[str, ...], record_id: bytes + ) -> PendingCommit | None: + """Return a token for a buffered record.""" + ... + WriteKey = tuple[int, tuple[str, ...]] -DatabaseWrites = dict[WriteKey, WriteDatabase] +DatabaseWrites = dict[WriteKey, tuple[object, WriteDatabase]] _run_writes: ContextVar[DatabaseWrites | None] = ContextVar("_run_writes", default=None) _current_write: ContextVar[tuple[object, WriteKey, WriteDatabase] | None] = ContextVar( @@ -51,38 +57,46 @@ def collect_database_writes( @contextmanager def track_database_write( - database: WriteDatabase, path: tuple[str, ...], *, has_rows: bool = True + database: WriteDatabase, path: tuple[str, ...], record_ids: Sequence[bytes] ) -> Iterator[None]: - """Track an insert only if it queued rows, before any automatic flush.""" + """Track an insert that queues rows or retries the same still-pending IDs.""" writes = _run_writes.get() key = (id(database), path) - if writes is None or key in writes or not has_rows or not database.stores_records: + if writes is None or key in writes or not record_ids or not database.stores_records: yield return queue = database_queue(database) - if queue is database: - # The protocol's add methods give no receipt. For a custom database - # without a queue, treat a successfully completed add as a write. - yield - writes[key] = database - return - token = _current_write.set((queue, key, database)) try: yield finally: _current_write.reset(token) + # A protocol implementation can buffer rows without using a library queue. + # Its insert methods give no receipt, but the commit protocol identifies + # buffered IDs, including a retry of a pending row and excluding durable hits. + if ( + queue is database + and key not in writes + and any( + database.pending_result(path, record_id) is not None + for record_id in record_ids + ) + ): + writes[key] = (queue, database) + def note_queued_write(queue: PendingCommits) -> None: - """Record a node write after deduplication and before automatic publication.""" + """Record new or retried pending rows before automatic publication.""" active = _current_write.get() - if active is not None and active[0] is queue: - writes = _run_writes.get() - if writes is not None: - _, key, database = active - writes[key] = database + if active is None: + return + expected, key, database = active + writes = _run_writes.get() + # A protocol wrapper can forward inserts without exposing the queue. + if writes is not None and (expected is queue or expected is database): + writes[key] = (queue, database) def finish_database_table_write(database: WriteDatabase, path: tuple[str, ...]) -> None: diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 144aaf8b4..412d66417 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -647,6 +647,7 @@ def add_records( ) records = records.filter(mask) if records.num_rows == 0: + note_queued_write(self._pending_commits) return # Mark this pending slot so flush() uses skip_existing=True. self._pending_skip_existing[record_key] = True diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 6051d8638..8addfd5f7 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -2922,6 +2922,9 @@ def _filter_existing_records( pc.is_in(table[self.RECORD_ID_COLUMN], pa.array(list(all_existing))) ) filtered = table.filter(mask) + if filtered.num_rows == 0 and existing_in_pending: + # A rerun can reach the same rows after its end-of-run flush failed. + note_queued_write(self._pending_commits) logger.debug(f"Skipped {len(all_existing)} duplicate records") return filtered diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 460b50b9f..3cf6c4fe1 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -211,7 +211,10 @@ def _filter_existing_records( mask = pc.invert( pc.is_in(table[self.RECORD_ID_COLUMN], pa.array(list(all_existing))) ) - return table.filter(mask) + filtered = table.filter(mask) + if filtered.num_rows == 0 and not input_ids.isdisjoint(pending_ids): + note_queued_write(self._pending_commits) + return filtered # ------------------------------------------------------------------ # Write methods diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 4d3b54f7a..72b7c8501 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -109,16 +109,14 @@ class _PreparedRun: pending_node_writes: "DatabaseWrites" = field(default_factory=dict) def additional_databases(self) -> "Iterator[ArrowDatabaseProtocol]": - """Yield additional database objects with writes left for the job to commit.""" - databases = { - identity: database - for (identity, _), database in self.pending_node_writes.items() - } - for database in databases.values(): - queue = database_queue(database) - if all(queue is not owned for owned in self.owned_queues): - # Every node's write path supplies an ArrowDatabaseProtocol. - yield cast("ArrowDatabaseProtocol", database) + """Yield one view per additional database queue the job wrote to.""" + covered = {id(queue) for queue in self.owned_queues} + for queue, database in self.pending_node_writes.values(): + if id(queue) in covered or id(database) in covered: + continue + covered.update((id(queue), id(database))) + # Every node's write path supplies an ArrowDatabaseProtocol. + yield cast("ArrowDatabaseProtocol", database) def _with_counter( diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 1cc890071..71d67c6f3 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -561,7 +561,7 @@ def _write_invocation_row( schema=_invocation_log_schema(), ) try: - with track_database_write(pipeline_database, table_path): + with track_database_write(pipeline_database, table_path, (entry_id,)): pipeline_database.add_record( table_path, entry_id, diff --git a/tests/test_pipeline/test_job_attached_database_commit.py b/tests/test_pipeline/test_job_attached_database_commit.py index bfd750372..751442e25 100644 --- a/tests/test_pipeline/test_job_attached_database_commit.py +++ b/tests/test_pipeline/test_job_attached_database_commit.py @@ -15,11 +15,14 @@ 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.side_effects import SideEffectPod from orcapod.sources import ArrowTableSource from orcapod.types import CacheMode, NodeConfig +from .test_mixed_function_commits import ProtocolDatabase + JOB_RUNNERS = ("sync", "async", "run_async") RUNNERS = (*JOB_RUNNERS, "node") @@ -71,7 +74,7 @@ async def _run( def _make_job( - store: DeltaTableDatabase, attached: DeltaTableDatabase, source: ArrowTableSource + store: DeltaTableDatabase, attached: ArrowDatabaseProtocol, source: ArrowTableSource ) -> PipelineJob: """Route an operator's log to an independently constructed database.""" job = PipelineJob(name="job", database=store) @@ -294,18 +297,23 @@ def on_run_end(self, run_id: str) -> None: @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") - job = _make_job(store, attached, source) + 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=attached, cache_mode=CacheMode.LOG + pipeline_database=first, cache_mode=CacheMode.LOG ) flush = attached.flush calls = 0 @@ -320,7 +328,8 @@ 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(attached, "flush", count_flush) + 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")) @@ -333,13 +342,16 @@ def on_run_end(self, run_id: str) -> None: @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 + tmp_path: Path, runner: str, source: ArrowTableSource, *, wrapped: bool ) -> None: """An all-duplicate insert leaves unrelated pending writes alone on a rerun.""" - attached = DeltaTableDatabase(tmp_path / "attached") + store = DeltaTableDatabase(tmp_path / "attached") + attached = ProtocolDatabase(store) if wrapped else store job = _make_job(DeltaTableDatabase(tmp_path / "owned"), attached, source) await _run(job, runner) + assert len(list((tmp_path / "attached").rglob("_delta_log"))) == 1 for label in ("other", "grouped"): job.nodes[label].clear_cache() @@ -349,6 +361,54 @@ async def test_duplicate_operator_logs_do_not_flush_an_attached_store( assert not (tmp_path / "attached" / "pending" / "_delta_log").exists() +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +@pytest.mark.parametrize("wrapped", [False, True], ids=["native", "protocol"]) +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 = ProtocolDatabase(store) 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) +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) async def test_a_side_effect_log_is_committed_to_its_attachment( diff --git a/tests/test_pipeline/test_mixed_function_commits.py b/tests/test_pipeline/test_mixed_function_commits.py index d5c6b9b64..6c2f8f68c 100644 --- a/tests/test_pipeline/test_mixed_function_commits.py +++ b/tests/test_pipeline/test_mixed_function_commits.py @@ -469,7 +469,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: From 95b935c1721bd8ba3cce372bc3b115e5c4080de5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 07:41:27 -0800 Subject: [PATCH 04/16] fix(pipeline): preserve owned commits and flush pending attachments --- docs/dev/design_issues/ITL-1383-BL3.md | 4 +- src/orcapod/core/nodes/function_node.py | 5 +- src/orcapod/databases/_write_tracking.py | 129 +++++++++++----- .../databases/connector_arrow_database.py | 32 +++- src/orcapod/databases/delta_lake_databases.py | 9 +- src/orcapod/databases/in_memory_databases.py | 9 +- src/orcapod/pipeline/job.py | 56 ++++--- src/orcapod/side_effects.py | 8 +- .../test_job_attached_database_commit.py | 141 ++++++++++++++++-- .../test_mixed_function_commits.py | 16 +- 10 files changed, 325 insertions(+), 84 deletions(-) diff --git a/docs/dev/design_issues/ITL-1383-BL3.md b/docs/dev/design_issues/ITL-1383-BL3.md index e1739bbcf..b52d16dde 100644 --- a/docs/dev/design_issues/ITL-1383-BL3.md +++ b/docs/dev/design_issues/ITL-1383-BL3.md @@ -15,4 +15,6 @@ object that accepted node writes once, including anything else pending in the object. Scoped views share a flush. 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 if they are still pending. +available. A retry can flush the same log rows and side-effect receipts when +they are still pending. An attached database that accepted function writes also +gets a whole flush after the function's table commits. diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 1bbdd5d69..d64ff9ea4 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -73,7 +73,7 @@ from orcapod.core.datagrams.tag_data import Data, EmptyData, Tag from orcapod.core.row_ids import INSTANCE_ID_COL, RECORD_ID_COL from orcapod.databases._write_tracking import ( - finish_database_table_write, + discard_dry_run_write, track_database_write, ) from orcapod.errors import ( @@ -2442,7 +2442,8 @@ def _flush_node_table( flush=True, table_flush=True, ) from exc - finish_database_table_write(database, path) + if result and not publish_records: + discard_dry_run_write(database, path) def _commit_pending_writes(self) -> None: """Commit results before publishing any records that depend on them.""" diff --git a/src/orcapod/databases/_write_tracking.py b/src/orcapod/databases/_write_tracking.py index 581ad22ea..0ed112c1f 100644 --- a/src/orcapod/databases/_write_tracking.py +++ b/src/orcapod/databases/_write_tracking.py @@ -2,9 +2,10 @@ from __future__ import annotations -from collections.abc import Iterator, Sequence +from collections.abc import Callable, Iterator, Sequence from contextlib import contextmanager from contextvars import ContextVar +from dataclasses import dataclass from typing import TYPE_CHECKING, Protocol if TYPE_CHECKING: @@ -29,9 +30,23 @@ def pending_result( WriteKey = tuple[int, tuple[str, ...]] DatabaseWrites = dict[WriteKey, tuple[object, WriteDatabase]] -_run_writes: ContextVar[DatabaseWrites | None] = ContextVar("_run_writes", default=None) -_current_write: ContextVar[tuple[object, WriteKey, WriteDatabase] | None] = ContextVar( - "_current_write", default=None + +@dataclass +class _Write: + """An insert whose database may forward to a built-in store.""" + + queue: object + key: WriteKey + database: WriteDatabase + observed: bool = False + + +_run_writes: ContextVar[tuple[DatabaseWrites, set[int]] | None] = ContextVar( + "_run_writes", default=None +) +_current_write: ContextVar[_Write | None] = ContextVar("_current_write", default=None) +_owned_flush_queues: ContextVar[set[int] | None] = ContextVar( + "_owned_flush_queues", default=None ) @@ -43,10 +58,10 @@ def database_queue(database: WriteDatabase) -> object: @contextmanager def collect_database_writes( - writes: DatabaseWrites, + writes: DatabaseWrites, covered: set[int] ) -> Iterator[None]: """Collect node writes for one job execution, including its async tasks.""" - run_token = _run_writes.set(writes) + run_token = _run_writes.set((writes, covered)) write_token = _current_write.set(None) try: yield @@ -57,50 +72,90 @@ def collect_database_writes( @contextmanager def track_database_write( - database: WriteDatabase, path: tuple[str, ...], record_ids: Sequence[bytes] + database: WriteDatabase, + path: tuple[str, ...], + record_ids: Sequence[bytes], + *, + retry: bool = False, ) -> Iterator[None]: - """Track an insert that queues rows or retries the same still-pending IDs.""" - writes = _run_writes.get() - key = (id(database), path) - if writes is None or key in writes or not record_ids or not database.stores_records: + """Track an insert or check for a receipt that is still pending on retry.""" + run = _run_writes.get() + if run is None or not record_ids or not database.stores_records: yield return + writes, covered = run queue = database_queue(database) - token = _current_write.set((queue, key, database)) + key = (id(database), path) + if key in writes or id(queue) in covered: + yield + return + + active = _Write(queue, key, database) + token = _current_write.set(active) try: yield + # A protocol implementation can buffer rows without using a library queue. + # Its insert methods give no receipt, but the commit protocol identifies + # buffered IDs. For a retry, the existing receipt may still be buffered. + if ( + (retry or queue is database) + and not active.observed + and any( + database.pending_result(path, row) is not None for row in record_ids + ) + and not active.observed + ): + writes[key] = (queue, database) finally: _current_write.reset(token) - # A protocol implementation can buffer rows without using a library queue. - # Its insert methods give no receipt, but the commit protocol identifies - # buffered IDs, including a retry of a pending row and excluding durable hits. - if ( - queue is database - and key not in writes - and any( - database.pending_result(path, record_id) is not None - for record_id in record_ids - ) - ): - writes[key] = (queue, database) - - -def note_queued_write(queue: PendingCommits) -> None: + +def note_queued_write( + queue: PendingCommits, *, needs_commit: Callable[[], bool] | None = None +) -> None: """Record new or retried pending rows before automatic publication.""" active = _current_write.get() - if active is None: + run = _run_writes.get() + if active is None or run is None: return - expected, key, database = active - writes = _run_writes.get() + writes, covered = run # A protocol wrapper can forward inserts without exposing the queue. - if writes is not None and (expected is queue or expected is database): - writes[key] = (queue, database) + if active.queue is queue or active.queue is active.database: + active.observed = True + if id(queue) not in covered and (needs_commit is None or needs_commit()): + writes[active.key] = (queue, active.database) + + +def discard_dry_run_write(database: WriteDatabase, path: tuple[str, ...]) -> None: + """Keep a dry-run result from introducing a whole-database commit.""" + run = _run_writes.get() + if run is not None: + _ = run[0].pop((id(database), path), None) + + +@contextmanager +def collect_owned_flush_queues(covered: set[int]) -> Iterator[None]: + """Observe the queues reached by the job's original end-of-run flushes.""" + token = _owned_flush_queues.set(covered) + try: + yield + finally: + _owned_flush_queues.reset(token) + + +def note_whole_flush(queue: PendingCommits) -> None: + """Identify the queue reached by a whole flush, even through an opaque view.""" + covered = _owned_flush_queues.get() + if covered is not None: + covered.add(id(queue)) -def finish_database_table_write(database: WriteDatabase, path: tuple[str, ...]) -> None: - """Retire a table handled by the node's own commit, including dry-run results.""" - writes = _run_writes.get() - if writes is not None: - _ = writes.pop((id(database), path), None) +def finish_whole_flush(queue: PendingCommits) -> None: + """Retire additional writes already handled by a whole flush during execution.""" + run = _run_writes.get() + if run is not None: + writes, _ = run + for key, (written_queue, _) in list(writes.items()): + if written_queue is queue: + del writes[key] diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 412d66417..d8320703f 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -33,7 +33,11 @@ require_store_table_owner, stored_path, ) -from orcapod.databases._write_tracking import note_queued_write +from orcapod.databases._write_tracking import ( + finish_whole_flush, + note_queued_write, + note_whole_flush, +) from orcapod.databases.store_table_names import ( STORE_TABLE_NAME_PREFIX, store_table_name, @@ -632,6 +636,25 @@ def add_records( records = self._deduplicate_within_table(records) input_ids = set(cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist())) + def has_new_rows() -> bool: + # The upsert still handles deduplication. For job attachments, decide + # if an insert-or-ignore is reason to flush the whole database. + committed = self._find_committed_table( + table_name, full_path, schema=self._schema_from_record_key(record_key) + ) + if committed is None: + return True + schema, name = committed + missing = set(input_ids) + for batch in self._connector.iter_batches( + f'SELECT "{self.RECORD_ID_COLUMN}" FROM {sql_table_identifier(name, schema)}' + ): + missing.difference_update(batch[self.RECORD_ID_COLUMN].to_pylist()) + if not missing: + return False + return True + + needs_commit = has_new_rows if skip_duplicates else None if skip_duplicates: # Only filter records that conflict with the in-flight pending batch. # Committed duplicates are handled at flush time via @@ -647,7 +670,7 @@ def add_records( ) records = records.filter(mask) if records.num_rows == 0: - note_queued_write(self._pending_commits) + note_queued_write(self._pending_commits, needs_commit=needs_commit) return # Mark this pending slot so flush() uses skip_existing=True. self._pending_skip_existing[record_key] = True @@ -676,7 +699,7 @@ def add_records( self._pending_record_ids[record_key].update( cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist()) ) - note_queued_write(self._pending_commits) + note_queued_write(self._pending_commits, needs_commit=needs_commit) if flush: self.flush() @@ -848,6 +871,7 @@ def pending_result( """Return a commit dependency for a buffered result, or verify it is stored.""" key = self._get_record_key(record_path) if record_id in self._pending_record_ids.get(key, ()): + note_queued_write(self._pending_commits) return self._pending_commits.attempt(key) if self.get_record_by_id(record_path, record_id) is None: raise ValueError("The referenced result is neither stored nor pending.") @@ -878,8 +902,10 @@ def guard_table_schema( def flush(self) -> None: """Commit all pending batches to the connector via upsert.""" + note_whole_flush(self._pending_commits) for record_key in list(self._pending_batches): self._flush_by_key(record_key) + finish_whole_flush(self._pending_commits) def refresh_table(self, record_path: tuple[str, ...]) -> None: """Nothing to refresh: every read queries the connector's backend (ITL-1408).""" diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 8addfd5f7..371f7a0a5 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -26,7 +26,11 @@ matching_rows, rows_at, ) -from orcapod.databases._write_tracking import note_queued_write +from orcapod.databases._write_tracking import ( + finish_whole_flush, + note_queued_write, + note_whole_flush, +) from orcapod.databases.delta_arrow_types import ( ARROW_TYPE_KEY, first_column_out_of_stored_range, @@ -3485,6 +3489,7 @@ def flush(self) -> None: RuntimeError: If batches failed with other errors only, naming the failed batches, with the first failure as its ``__cause__``. """ + note_whole_flush(self._pending_commits) # A flush is where this database looks at the store again (ITL-1173). self._absent_tables.clear() errors: list[tuple[str, Exception]] = [] @@ -3512,6 +3517,7 @@ def flush(self) -> None: raise RuntimeError( f"Failed to flush {len(errors)} batch(es): {failed_keys}" ) from errors[0][1] + finish_whole_flush(self._pending_commits) def pending_result( self, record_path: tuple[str, ...], record_id: bytes @@ -3519,6 +3525,7 @@ def pending_result( """Return a commit dependency for a buffered result, or verify it is stored.""" key = self._get_record_key(record_path) if record_id in self._pending_record_ids.get(key, ()): + note_queued_write(self._pending_commits) return self._pending_commits.attempt(key) if record_id not in self._stored_ids(record_path): raise ValueError("The referenced result is neither stored nor pending.") diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index 3cf6c4fe1..bdab952dd 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -11,7 +11,11 @@ from orcapod.databases._pending_commits import PendingCommit, PendingCommits from orcapod.databases._row_index import KeyIndex, compact_tail, matching_rows -from orcapod.databases._write_tracking import note_queued_write +from orcapod.databases._write_tracking import ( + finish_whole_flush, + note_queued_write, + note_whole_flush, +) from orcapod.databases.utils import ( coerce_record_id, first_changed_column, @@ -360,6 +364,7 @@ def pending_result( """Return a commit dependency for a buffered result, or verify it is stored.""" key = self._get_record_key(record_path) if record_id in self._pending_record_ids.get(key, ()): + note_queued_write(self._pending_commits) return self._pending_commits.attempt(key) if record_id not in self._committed_id_index(key): raise ValueError("The referenced result is neither stored nor pending.") @@ -390,8 +395,10 @@ def guard_table_schema( def flush(self) -> None: """Promote the ready batches in the shared queue.""" + note_whole_flush(self._pending_commits) for record_key in list(self._pending_batches): self._flush_by_key(record_key) + finish_whole_flush(self._pending_commits) def refresh_table(self, record_path: tuple[str, ...]) -> None: """Nothing to refresh: every view reads the one shared store (ITL-1408). diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 72b7c8501..af97df4f9 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -19,7 +19,11 @@ from orcapod.core.streams.base import StreamBase from orcapod.side_effects import SideEffectJobNode, SideEffectNode from orcapod.core.tracker import AutoRegisteringContextBasedTracker -from orcapod.databases._write_tracking import collect_database_writes, database_queue +from orcapod.databases._write_tracking import ( + collect_database_writes, + collect_owned_flush_queues, + database_queue, +) from orcapod.errors import ( OrcapodDatabaseError, OrcapodDatabaseReadError, @@ -108,9 +112,11 @@ class _PreparedRun: owned_queues: tuple[object, ...] pending_node_writes: "DatabaseWrites" = field(default_factory=dict) - def additional_databases(self) -> "Iterator[ArrowDatabaseProtocol]": + def additional_databases( + self, covered_queues: set[int] + ) -> "Iterator[ArrowDatabaseProtocol]": """Yield one view per additional database queue the job wrote to.""" - covered = {id(queue) for queue in self.owned_queues} + covered = set(covered_queues) for queue, database in self.pending_node_writes.values(): if id(queue) in covered or id(database) in covered: continue @@ -1475,9 +1481,10 @@ def _executing( commit_every_rows: As for ``run``. load_only: As for ``run``. """ + covered_queues = {id(queue) for queue in prepared.owned_queues} try: with ( - collect_database_writes(prepared.pending_node_writes), + collect_database_writes(prepared.pending_node_writes, covered_queues), contextlib.ExitStack() as batched, ): # Function nodes commit every commit_every_rows rows (ITL-919). @@ -1492,17 +1499,20 @@ def _executing( # 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: + with collect_owned_flush_queues(covered_queues): + flush_best_effort( + run_error, + prepared.pipeline_db, + prepared.result_db, + # Records a separate result database's flush released (ITL-1408). + *( + (prepared.pipeline_db,) + if self._result_database is not None + else () + ), + ) flush_best_effort( - run_error, - prepared.pipeline_db, - prepared.result_db, - # Records a separate result database's flush released (ITL-1408). - *( - (prepared.pipeline_db,) - if self._result_database is not None - else () - ), - *prepared.additional_databases(), + run_error, *prepared.additional_databases(covered_queues) ) clear_run_rows(plan.to_run) raise @@ -1554,16 +1564,18 @@ 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() - database = result_db - database.flush() - 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 + covered_queues = {id(queue) for queue in prepared.owned_queues} + with collect_owned_flush_queues(covered_queues): + database.flush() + database = result_db database.flush() + 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() # Node writes can target their own database objects (ITL-1383). - for database in prepared.additional_databases(): + for database in prepared.additional_databases(covered_queues): database.flush() except OrcapodDatabaseReadError as exc: # A stored table could not be read: report the read failure itself. diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 71d67c6f3..72be05b2c 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -459,12 +459,16 @@ def _execute_side_effect_row( ): try: prior = pipeline_database.get_record_by_id(table_path, entry_id) + if prior is not None: + with track_database_write( + pipeline_database, table_path, (entry_id,), retry=True + ): + # A buffered receipt suppresses delivery but still needs a commit. + return (tag, data) except OrcapodDatabaseError as exc: # A failed lookup fails the run like a failed write: name pod and row. exc.add_context(node_label=pod_name, tag=tag.as_dict()) raise - if prior is not None: - return (tag, data) # already completed — re-emit without re-delivery # 3. Build InvocationContext (invocation_hash derived lazily via format_id()). ctx = InvocationContext( diff --git a/tests/test_pipeline/test_job_attached_database_commit.py b/tests/test_pipeline/test_job_attached_database_commit.py index 751442e25..5c0576165 100644 --- a/tests/test_pipeline/test_job_attached_database_commit.py +++ b/tests/test_pipeline/test_job_attached_database_commit.py @@ -10,7 +10,11 @@ from orcapod import PipelineJob, function_pod from orcapod.core.operators import GroupBy, SelectDataColumns -from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + InMemoryArrowDatabase, +) from orcapod.errors import OrcapodDatabaseWriteError from orcapod.invocation import InvocationContext from orcapod.pipeline import AsyncPipelineOrchestrator @@ -21,7 +25,7 @@ from orcapod.sources import ArrowTableSource from orcapod.types import CacheMode, NodeConfig -from .test_mixed_function_commits import ProtocolDatabase +from .test_mixed_function_commits import CommitConnector, ProtocolDatabase JOB_RUNNERS = ("sync", "async", "run_async") RUNNERS = (*JOB_RUNNERS, "node") @@ -74,7 +78,9 @@ async def _run( def _make_job( - store: DeltaTableDatabase, attached: ArrowDatabaseProtocol, source: ArrowTableSource + store: ArrowDatabaseProtocol, + attached: ArrowDatabaseProtocol, + source: ArrowTableSource, ) -> PipelineJob: """Route an operator's log to an independently constructed database.""" job = PipelineJob(name="job", database=store) @@ -111,24 +117,27 @@ async def test_a_run_commits_a_manually_attached_operator_log( assert deltalake.DeltaTable(str(log.parent)).to_pyarrow_table().num_rows == 2 -@pytest.mark.parametrize("asynchronous", [False, True]) -def test_a_manually_attached_function_store_is_committed( - tmp_path: Path, source: ArrowTableSource, *, asynchronous: bool +@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: - """Function nodes already commit both their result and pipeline tables.""" + """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") - job.nodes["sum"].attach_databases( - pipeline_database=DeltaTableDatabase(tmp_path).at("mine") - ) - orchestrator = AsyncPipelineOrchestrator() if asynchronous else None - job.run(orchestrator=orchestrator) + 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"} + 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" ) @@ -361,6 +370,67 @@ async def test_duplicate_operator_logs_do_not_flush_an_attached_store( assert not (tmp_path / "attached" / "pending" / "_delta_log").exists() +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +async def test_durable_connector_duplicates_leave_the_attachment_unflushed( + tmp_path: Path, runner: str, source: ArrowTableSource +) -> None: + """A connector defers durable duplicate checking to the upsert.""" + connector = CommitConnector() + attachment = ConnectorArrowDatabase(connector) + job = _make_job(DeltaTableDatabase(tmp_path), attachment, source) + await _run(job, runner) + attachment.flush() + reopened = ConnectorArrowDatabase(connector) + existing_paths = reopened.list_table_paths() + assert len(existing_paths) == 1 + for label in ("other", "grouped"): + job.nodes[label].clear_cache() + attachment.add_record(("pending",), b"pending", pa.table({"value": [3]})) + + for _ in range(2): + await _run(job, runner) + assert job.nodes["grouped"].as_table().num_rows == 2 + assert reopened.list_table_paths() == existing_paths + job.nodes["grouped"].clear_cache() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", JOB_RUNNERS) +@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, + *, + fail_run: bool, +) -> None: + """The existing whole flushes cover an alias behind a protocol wrapper.""" + store = ProtocolDatabase(DeltaTableDatabase(tmp_path)) + job = _make_job(store, store.at("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 == [("job",), ("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", "protocol"]) @@ -427,3 +497,48 @@ def deliver(ctx: InvocationContext, x: int, y: int) -> None: 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) +@pytest.mark.parametrize("wrapped", [False, True], ids=["native", "protocol"]) +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 = ProtocolDatabase(store) 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() diff --git a/tests/test_pipeline/test_mixed_function_commits.py b/tests/test_pipeline/test_mixed_function_commits.py index 6c2f8f68c..85cb84271 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 @@ -614,4 +622,8 @@ 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")) + if placement != "shared": + expected.append(("result",)) + assert calls == expected From 78da630c3b560d8909633433a3c46e6286ce7eef Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 08:58:46 -0800 Subject: [PATCH 05/16] fix(pipeline): enroll attachment commits at node write sites --- changelog.d/ITL-1383.md | 2 +- docs/dev/design_issues/ITL-1383-BL3.md | 7 +- src/orcapod/core/database_writes.py | 231 ++++++++++++++++++ src/orcapod/core/nodes/function_node.py | 8 +- src/orcapod/core/nodes/operator_node.py | 2 +- src/orcapod/core/result_cache.py | 10 +- src/orcapod/databases/_write_tracking.py | 161 ------------ .../databases/connector_arrow_database.py | 29 --- src/orcapod/databases/delta_lake_databases.py | 12 - .../databases/extension_aware_database.py | 5 - src/orcapod/databases/in_memory_databases.py | 14 +- src/orcapod/pipeline/job.py | 102 ++++---- src/orcapod/side_effects.py | 6 +- .../test_job_attached_database_commit.py | 89 +++++++ 14 files changed, 391 insertions(+), 287 deletions(-) create mode 100644 src/orcapod/core/database_writes.py delete mode 100644 src/orcapod/databases/_write_tracking.py diff --git a/changelog.d/ITL-1383.md b/changelog.d/ITL-1383.md index 45de1ae15..a9b72d923 100644 --- a/changelog.d/ITL-1383.md +++ b/changelog.d/ITL-1383.md @@ -1,3 +1,3 @@ ### 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 retry can commit log rows left pending by a failed flush. +- 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 retry can commit pending log rows and retry a failed whole flush after function tables have committed. diff --git a/docs/dev/design_issues/ITL-1383-BL3.md b/docs/dev/design_issues/ITL-1383-BL3.md index b52d16dde..7eca1a803 100644 --- a/docs/dev/design_issues/ITL-1383-BL3.md +++ b/docs/dev/design_issues/ITL-1383-BL3.md @@ -16,5 +16,8 @@ object. Scoped views share a flush. The job also attempts the flush when executi 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. An attached database that accepted function writes also -gets a whole flush after the function's table commits. +they are still pending. Durable duplicates leave the attachment alone. 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 of that attachment is retried when the function's tables +are already durable. diff --git a/src/orcapod/core/database_writes.py b/src/orcapod/core/database_writes.py new file mode 100644 index 000000000..af9eea7e2 --- /dev/null +++ b/src/orcapod/core/database_writes.py @@ -0,0 +1,231 @@ +"""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, cast + +from orcapod.errors import OrcapodDatabaseError + +if TYPE_CHECKING: + from collections.abc import Iterator, Sequence + + from orcapod.protocols.database_protocols import ArrowDatabaseProtocol + + +def _backend(database: ArrowDatabaseProtocol) -> ArrowDatabaseProtocol: + """Unwrap library views that forward operations to a backend.""" + from orcapod.databases.extension_aware_database import ExtensionAwareDatabase + + while isinstance(database, ExtensionAwareDatabase): + database = database._db # pyright: ignore[reportPrivateUsage] + return database + + +def _queue(database: ArrowDatabaseProtocol) -> object: + """Use the shared queue as the identity of a built-in store and its views.""" + backend = _backend(database) + return getattr(backend, "_pending_commits", backend) + + +def _all_durable( + database: ArrowDatabaseProtocol, path: tuple[str, ...], ids: Sequence[bytes] +) -> bool: + """Check committed IDs separately from buffered retries and duplicate upserts.""" + # The database modules can reach the node write sites via core protocols. + from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase + from orcapod.databases.delta_lake_databases import DeltaTableDatabase + from orcapod.databases.in_memory_databases import InMemoryArrowDatabase + from orcapod.databases.utils import sql_table_identifier + + backend = _backend(database) + unique_ids = set(ids) + if isinstance(backend, DeltaTableDatabase): + return unique_ids.issubset(backend._stored_ids(path)) # pyright: ignore[reportPrivateUsage] + if isinstance(backend, InMemoryArrowDatabase): + key = backend._get_record_key(path) # pyright: ignore[reportPrivateUsage] + return unique_ids.issubset(backend._committed_id_index(key)) # pyright: ignore[reportPrivateUsage] + if isinstance(backend, ConnectorArrowDatabase): + key = backend._get_record_key(path) # pyright: ignore[reportPrivateUsage] + schema = backend._schema_from_record_key(key) # pyright: ignore[reportPrivateUsage] + full_path = backend.base_path + path + name = backend._path_to_table_name(full_path) # pyright: ignore[reportPrivateUsage] + table = backend._find_committed_table( # pyright: ignore[reportPrivateUsage] + name, full_path, schema=schema + ) + if table is None: + return False + schema, name = table + column = backend.RECORD_ID_COLUMN + batches = backend._connector.iter_batches( # pyright: ignore[reportPrivateUsage] + f'SELECT "{column}" FROM {sql_table_identifier(name, schema)}' + ) + for batch in batches: + unique_ids.difference_update(cast("list[bytes]", batch[column].to_pylist())) + if not unique_ids: + return True + return False + rows = database.get_records_by_ids(path, unique_ids) + return ( + rows is not None + and rows.num_rows >= len(unique_ids) + and all(database.pending_result(path, row) is None for row in unique_ids) + ) + + +@dataclass +class _Write: + """One write site that still needs its database's final whole flush.""" + + database: ArrowDatabaseProtocol + sample_id: bytes + function: bool + + +class DatabaseWrites: + """A run's writes to objects outside the job's original flush sequence.""" + + def __init__(self, owned: tuple[ArrowDatabaseProtocol, ...]) -> None: + self._owned: tuple[ArrowDatabaseProtocol, ...] = owned + self._covered: set[int] = {id(_queue(database)) for database in owned} + self._writes: dict[tuple[int, tuple[str, ...]], _Write] = {} + + def _covered_by_owned_wrapper( + self, + database: ArrowDatabaseProtocol, + path: tuple[str, ...], + rows: Sequence[bytes], + ) -> bool: + """Recognize aliases of an opaque job store by their shared commit token.""" + full_path = database.base_path + path + opaque = _queue(database) is _backend(database) + candidates = [ + owned + for owned in self._owned + if (opaque or _queue(owned) is _backend(owned)) + and full_path[: len(owned.base_path)] == owned.base_path + ] + if not candidates: + return False + for row in rows: + token = database.pending_result(path, row) + if token is None: + continue + for owned in candidates: + relative = full_path[len(owned.base_path) :] + try: + if owned.pending_result(relative, row) is token: + return True + except (ValueError, OrcapodDatabaseError): + # An independent store has no such pending record. + continue + break # A pending row is enough to check where the table is queued. + return False + + def databases(self) -> dict[int, ArrowDatabaseProtocol]: + """Return one view per enrolled store in write order.""" + result: dict[int, ArrowDatabaseProtocol] = {} + for (queue, _), write in self._writes.items(): + _ = result.setdefault(queue, write.database) + return result + + def function_databases(self) -> dict[int, ArrowDatabaseProtocol]: + """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 + } + + @contextmanager + def track( + self, + database: ArrowDatabaseProtocol, + path: tuple[str, ...], + record_ids: Sequence[bytes], + *, + skip_duplicates: bool, + function: bool, + ) -> Iterator[None]: + """Enroll a write unless every ID is already committed.""" + key = (id(_queue(database)), database.base_path + path) + if ( + key[0] in self._covered + or key in self._writes + or (skip_duplicates and _all_durable(database, path, record_ids)) + ): + yield + return + + try: + yield + except Exception: + # A write can queue records and then fail an automatic table commit. + # Keep any such attachment eligible for the job's best-effort flush. + for row in record_ids: + try: + if database.pending_result(path, row) is not None: + if not self._covered_by_owned_wrapper(database, path, (row,)): + self._writes[key] = _Write(database, row, function) + break + except (ValueError, OrcapodDatabaseError): + continue + raise + if not self._covered_by_owned_wrapper(database, path, record_ids): + self._writes[key] = _Write(database, record_ids[0], function) + + def exclude_unpublished_result( + self, database: ArrowDatabaseProtocol, path: tuple[str, ...] + ) -> None: + """Leave dry-run results queued when the table commit kept them there.""" + key = (id(_queue(database)), database.base_path + path) + write = self._writes.get(key) + if ( + write is not None + and database.pending_result(path, write.sample_id) is not None + ): + del self._writes[key] + + +_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: ArrowDatabaseProtocol, + path: tuple[str, ...], + record_ids: Sequence[bytes], + *, + skip_duplicates: bool = True, + 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 record_ids or not database.stores_records: + yield + return + with run.track( + database, path, record_ids, skip_duplicates=skip_duplicates, function=function + ): + yield + + +def exclude_unpublished_result( + database: ArrowDatabaseProtocol, path: tuple[str, ...] +) -> None: + """Keep a dry-run result queued when the job's store did not publish it.""" + 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 d64ff9ea4..b5cb99e08 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -72,8 +72,8 @@ 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.databases._write_tracking import ( - discard_dry_run_write, +from orcapod.core.database_writes import ( + exclude_unpublished_result, track_database_write, ) from orcapod.errors import ( @@ -2443,7 +2443,7 @@ def _flush_node_table( table_flush=True, ) from exc if result and not publish_records: - discard_dry_run_write(database, path) + exclude_unpublished_result(database, path) def _commit_pending_writes(self) -> None: """Commit results before publishing any records that depend on them.""" @@ -2511,7 +2511,7 @@ def _write_pipeline_record( with ( database.guard_table_schema(path, check), result_guard, - track_database_write(database, path, (row_key,)), + track_database_write(database, path, (row_key,), function=True), ): database.add_record(path, row_key, record, skip_duplicates=True) diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 3fa407c0a..a6ace7a4d 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -66,7 +66,7 @@ ) from orcapod.core.tracker import DEFAULT_TRACKER_MANAGER from orcapod.core.nodes.staleness import RunHoldingNode -from orcapod.databases._write_tracking import track_database_write +from orcapod.core.database_writes import track_database_write from orcapod.errors import ( InputValidationError, PipelineJobRequiredError, diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index aebc16fda..d363ca4c9 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -15,7 +15,7 @@ import pyarrow as pa from orcapod.core.data_function_types import StoredColumn -from orcapod.databases._write_tracking import track_database_write +from orcapod.core.database_writes import track_database_write from orcapod.errors import ( InputValidationError, OrcapodDatabaseReadError, @@ -481,7 +481,13 @@ def store( path = self._versioned_record_path result_id = output_data.datagram_uuid.bytes try: - with track_database_write(self._result_database, path, (result_id,)): + with track_database_write( + self._result_database, + path, + (result_id,), + skip_duplicates=skip_duplicates, + function=True, + ): self._result_database.add_record( path, result_id, diff --git a/src/orcapod/databases/_write_tracking.py b/src/orcapod/databases/_write_tracking.py deleted file mode 100644 index 0ed112c1f..000000000 --- a/src/orcapod/databases/_write_tracking.py +++ /dev/null @@ -1,161 +0,0 @@ -"""Track the database objects that accept a job's node writes.""" - -from __future__ import annotations - -from collections.abc import Callable, Iterator, Sequence -from contextlib import contextmanager -from contextvars import ContextVar -from dataclasses import dataclass -from typing import TYPE_CHECKING, Protocol - -if TYPE_CHECKING: - from orcapod.databases._pending_commits import PendingCommit, PendingCommits - - -class WriteDatabase(Protocol): - """The part of the database interface used to track a node's writes.""" - - @property - def stores_records(self) -> bool: - """Whether the database stores rows when asked to insert them.""" - ... - - def pending_result( - self, record_path: tuple[str, ...], record_id: bytes - ) -> PendingCommit | None: - """Return a token for a buffered record.""" - ... - - -WriteKey = tuple[int, tuple[str, ...]] -DatabaseWrites = dict[WriteKey, tuple[object, WriteDatabase]] - - -@dataclass -class _Write: - """An insert whose database may forward to a built-in store.""" - - queue: object - key: WriteKey - database: WriteDatabase - observed: bool = False - - -_run_writes: ContextVar[tuple[DatabaseWrites, set[int]] | None] = ContextVar( - "_run_writes", default=None -) -_current_write: ContextVar[_Write | None] = ContextVar("_current_write", default=None) -_owned_flush_queues: ContextVar[set[int] | None] = ContextVar( - "_owned_flush_queues", default=None -) - - -def database_queue(database: WriteDatabase) -> object: - """Identify the pending queue that a whole flush covers, shared by scoped views.""" - queue = getattr(database, "_pending_commits", None) - return database if queue is None else queue - - -@contextmanager -def collect_database_writes( - writes: DatabaseWrites, covered: set[int] -) -> Iterator[None]: - """Collect node writes for one job execution, including its async tasks.""" - run_token = _run_writes.set((writes, covered)) - write_token = _current_write.set(None) - try: - yield - finally: - _current_write.reset(write_token) - _run_writes.reset(run_token) - - -@contextmanager -def track_database_write( - database: WriteDatabase, - path: tuple[str, ...], - record_ids: Sequence[bytes], - *, - retry: bool = False, -) -> Iterator[None]: - """Track an insert or check for a receipt that is still pending on retry.""" - run = _run_writes.get() - if run is None or not record_ids or not database.stores_records: - yield - return - - writes, covered = run - queue = database_queue(database) - key = (id(database), path) - if key in writes or id(queue) in covered: - yield - return - - active = _Write(queue, key, database) - token = _current_write.set(active) - try: - yield - # A protocol implementation can buffer rows without using a library queue. - # Its insert methods give no receipt, but the commit protocol identifies - # buffered IDs. For a retry, the existing receipt may still be buffered. - if ( - (retry or queue is database) - and not active.observed - and any( - database.pending_result(path, row) is not None for row in record_ids - ) - and not active.observed - ): - writes[key] = (queue, database) - finally: - _current_write.reset(token) - - -def note_queued_write( - queue: PendingCommits, *, needs_commit: Callable[[], bool] | None = None -) -> None: - """Record new or retried pending rows before automatic publication.""" - active = _current_write.get() - run = _run_writes.get() - if active is None or run is None: - return - writes, covered = run - # A protocol wrapper can forward inserts without exposing the queue. - if active.queue is queue or active.queue is active.database: - active.observed = True - if id(queue) not in covered and (needs_commit is None or needs_commit()): - writes[active.key] = (queue, active.database) - - -def discard_dry_run_write(database: WriteDatabase, path: tuple[str, ...]) -> None: - """Keep a dry-run result from introducing a whole-database commit.""" - run = _run_writes.get() - if run is not None: - _ = run[0].pop((id(database), path), None) - - -@contextmanager -def collect_owned_flush_queues(covered: set[int]) -> Iterator[None]: - """Observe the queues reached by the job's original end-of-run flushes.""" - token = _owned_flush_queues.set(covered) - try: - yield - finally: - _owned_flush_queues.reset(token) - - -def note_whole_flush(queue: PendingCommits) -> None: - """Identify the queue reached by a whole flush, even through an opaque view.""" - covered = _owned_flush_queues.get() - if covered is not None: - covered.add(id(queue)) - - -def finish_whole_flush(queue: PendingCommits) -> None: - """Retire additional writes already handled by a whole flush during execution.""" - run = _run_writes.get() - if run is not None: - writes, _ = run - for key, (written_queue, _) in list(writes.items()): - if written_queue is queue: - del writes[key] diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index d8320703f..267caf622 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -33,11 +33,6 @@ require_store_table_owner, stored_path, ) -from orcapod.databases._write_tracking import ( - finish_whole_flush, - note_queued_write, - note_whole_flush, -) from orcapod.databases.store_table_names import ( STORE_TABLE_NAME_PREFIX, store_table_name, @@ -636,25 +631,6 @@ def add_records( records = self._deduplicate_within_table(records) input_ids = set(cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist())) - def has_new_rows() -> bool: - # The upsert still handles deduplication. For job attachments, decide - # if an insert-or-ignore is reason to flush the whole database. - committed = self._find_committed_table( - table_name, full_path, schema=self._schema_from_record_key(record_key) - ) - if committed is None: - return True - schema, name = committed - missing = set(input_ids) - for batch in self._connector.iter_batches( - f'SELECT "{self.RECORD_ID_COLUMN}" FROM {sql_table_identifier(name, schema)}' - ): - missing.difference_update(batch[self.RECORD_ID_COLUMN].to_pylist()) - if not missing: - return False - return True - - needs_commit = has_new_rows if skip_duplicates else None if skip_duplicates: # Only filter records that conflict with the in-flight pending batch. # Committed duplicates are handled at flush time via @@ -670,7 +646,6 @@ def has_new_rows() -> bool: ) records = records.filter(mask) if records.num_rows == 0: - note_queued_write(self._pending_commits, needs_commit=needs_commit) return # Mark this pending slot so flush() uses skip_existing=True. self._pending_skip_existing[record_key] = True @@ -699,7 +674,6 @@ def has_new_rows() -> bool: self._pending_record_ids[record_key].update( cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist()) ) - note_queued_write(self._pending_commits, needs_commit=needs_commit) if flush: self.flush() @@ -871,7 +845,6 @@ def pending_result( """Return a commit dependency for a buffered result, or verify it is stored.""" key = self._get_record_key(record_path) if record_id in self._pending_record_ids.get(key, ()): - note_queued_write(self._pending_commits) return self._pending_commits.attempt(key) if self.get_record_by_id(record_path, record_id) is None: raise ValueError("The referenced result is neither stored nor pending.") @@ -902,10 +875,8 @@ def guard_table_schema( def flush(self) -> None: """Commit all pending batches to the connector via upsert.""" - note_whole_flush(self._pending_commits) for record_key in list(self._pending_batches): self._flush_by_key(record_key) - finish_whole_flush(self._pending_commits) def refresh_table(self, record_path: tuple[str, ...]) -> None: """Nothing to refresh: every read queries the connector's backend (ITL-1408).""" diff --git a/src/orcapod/databases/delta_lake_databases.py b/src/orcapod/databases/delta_lake_databases.py index 371f7a0a5..c88b322d8 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -26,11 +26,6 @@ matching_rows, rows_at, ) -from orcapod.databases._write_tracking import ( - finish_whole_flush, - note_queued_write, - note_whole_flush, -) from orcapod.databases.delta_arrow_types import ( ARROW_TYPE_KEY, first_column_out_of_stored_range, @@ -2857,7 +2852,6 @@ def add_records( # Step 7: Add to pending batch (no overwrite logic needed) self._add_to_pending_batch(record_path, schema_compatible_table) - note_queued_write(self._pending_commits) # Step 8: Flush if asked to; otherwise commit this table alone once its # pending batch reaches batch_size. Only the full table: committing every @@ -2926,9 +2920,6 @@ def _filter_existing_records( pc.is_in(table[self.RECORD_ID_COLUMN], pa.array(list(all_existing))) ) filtered = table.filter(mask) - if filtered.num_rows == 0 and existing_in_pending: - # A rerun can reach the same rows after its end-of-run flush failed. - note_queued_write(self._pending_commits) logger.debug(f"Skipped {len(all_existing)} duplicate records") return filtered @@ -3489,7 +3480,6 @@ def flush(self) -> None: RuntimeError: If batches failed with other errors only, naming the failed batches, with the first failure as its ``__cause__``. """ - note_whole_flush(self._pending_commits) # A flush is where this database looks at the store again (ITL-1173). self._absent_tables.clear() errors: list[tuple[str, Exception]] = [] @@ -3517,7 +3507,6 @@ def flush(self) -> None: raise RuntimeError( f"Failed to flush {len(errors)} batch(es): {failed_keys}" ) from errors[0][1] - finish_whole_flush(self._pending_commits) def pending_result( self, record_path: tuple[str, ...], record_id: bytes @@ -3525,7 +3514,6 @@ def pending_result( """Return a commit dependency for a buffered result, or verify it is stored.""" key = self._get_record_key(record_path) if record_id in self._pending_record_ids.get(key, ()): - note_queued_write(self._pending_commits) return self._pending_commits.attempt(key) if record_id not in self._stored_ids(record_path): raise ValueError("The referenced result is neither stored nor pending.") diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index ab4568919..bbb891f2e 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -198,11 +198,6 @@ def validate_records(self, records: pa.Table) -> None: if isinstance(self._db, RecordValidatingDatabaseProtocol): self._db.validate_records(records) - @property - def _pending_commits(self) -> object | None: - """Forward the identity of the shared pending queue for write tracking.""" - return getattr(self._db, "_pending_commits", None) - def flush(self) -> None: self._db.flush() diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index bdab952dd..2ccb4d696 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -11,11 +11,6 @@ from orcapod.databases._pending_commits import PendingCommit, PendingCommits from orcapod.databases._row_index import KeyIndex, compact_tail, matching_rows -from orcapod.databases._write_tracking import ( - finish_whole_flush, - note_queued_write, - note_whole_flush, -) from orcapod.databases.utils import ( coerce_record_id, first_changed_column, @@ -215,10 +210,7 @@ def _filter_existing_records( mask = pc.invert( pc.is_in(table[self.RECORD_ID_COLUMN], pa.array(list(all_existing))) ) - filtered = table.filter(mask) - if filtered.num_rows == 0 and not input_ids.isdisjoint(pending_ids): - note_queued_write(self._pending_commits) - return filtered + return table.filter(mask) # ------------------------------------------------------------------ # Write methods @@ -344,7 +336,6 @@ def add_records( ) pending_ids = cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist()) self._pending_record_ids[record_key].update(pending_ids) - note_queued_write(self._pending_commits) if flush: self.flush() @@ -364,7 +355,6 @@ def pending_result( """Return a commit dependency for a buffered result, or verify it is stored.""" key = self._get_record_key(record_path) if record_id in self._pending_record_ids.get(key, ()): - note_queued_write(self._pending_commits) return self._pending_commits.attempt(key) if record_id not in self._committed_id_index(key): raise ValueError("The referenced result is neither stored nor pending.") @@ -395,10 +385,8 @@ def guard_table_schema( def flush(self) -> None: """Promote the ready batches in the shared queue.""" - note_whole_flush(self._pending_commits) for record_key in list(self._pending_batches): self._flush_by_key(record_key) - finish_whole_flush(self._pending_commits) def refresh_table(self, record_path: tuple[str, ...]) -> None: """Nothing to refresh: every view reads the one shared store (ITL-1408). diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index af97df4f9..c4d56ad27 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -7,10 +7,11 @@ import logging import sys from collections.abc import Iterator -from dataclasses import dataclass, field +from dataclasses import dataclass 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 @@ -19,11 +20,6 @@ from orcapod.core.streams.base import StreamBase from orcapod.side_effects import SideEffectJobNode, SideEffectNode from orcapod.core.tracker import AutoRegisteringContextBasedTracker -from orcapod.databases._write_tracking import ( - collect_database_writes, - collect_owned_flush_queues, - database_queue, -) from orcapod.errors import ( OrcapodDatabaseError, OrcapodDatabaseReadError, @@ -52,12 +48,15 @@ from orcapod.protocols import core_protocols as cp from orcapod.databases.utils import as_table_committing from orcapod.types import NodeConfig -from orcapod.utils.database_errors import database_write_path, flush_best_effort +from orcapod.utils.database_errors import ( + commit_best_effort, + database_write_path, + flush_best_effort, +) if TYPE_CHECKING: from pathlib import Path - from orcapod.databases._write_tracking import DatabaseWrites from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.execution_context import ExecutionContext from orcapod.pipeline.graph import Pipeline @@ -95,8 +94,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. - owned_queues: The pending queues already covered by the job's commit. - pending_node_writes: The node writes left for the job to commit. + 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). @@ -109,20 +107,7 @@ class _PreparedRun: result_db: "ArrowDatabaseProtocol" plan: "RunPlan" unchecked_sources: tuple[str, ...] - owned_queues: tuple[object, ...] - pending_node_writes: "DatabaseWrites" = field(default_factory=dict) - - def additional_databases( - self, covered_queues: set[int] - ) -> "Iterator[ArrowDatabaseProtocol]": - """Yield one view per additional database queue the job wrote to.""" - covered = set(covered_queues) - for queue, database in self.pending_node_writes.values(): - if id(queue) in covered or id(database) in covered: - continue - covered.update((id(queue), id(database))) - # Every node's write path supplies an ArrowDatabaseProtocol. - yield cast("ArrowDatabaseProtocol", database) + writes: DatabaseWrites def _with_counter( @@ -200,6 +185,7 @@ def __init__( self._database = database self._result_database: "ArrowDatabaseProtocol | None" = result_database self._node_database_views: "tuple[ArrowDatabaseProtocol, ...]" = () + self._retry_function_flushes: "dict[int, ArrowDatabaseProtocol]" = {} # 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 @@ -1454,9 +1440,8 @@ def _prepare_run( result_db=result_db, plan=plan, unchecked_sources=unchecked, - owned_queues=tuple( - database_queue(database) - for database in (pipeline_db, result_db, *self._node_database_views) + writes=DatabaseWrites( + (pipeline_db, result_db, *self._node_database_views, self._database) ), ) @@ -1481,10 +1466,9 @@ def _executing( commit_every_rows: As for ``run``. load_only: As for ``run``. """ - covered_queues = {id(queue) for queue in prepared.owned_queues} try: with ( - collect_database_writes(prepared.pending_node_writes, covered_queues), + collect_database_writes(prepared.writes), contextlib.ExitStack() as batched, ): # Function nodes commit every commit_every_rows rows (ITL-919). @@ -1499,24 +1483,37 @@ def _executing( # 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: - with collect_owned_flush_queues(covered_queues): - flush_best_effort( - run_error, - prepared.pipeline_db, - prepared.result_db, - # Records a separate result database's flush released (ITL-1408). - *( - (prepared.pipeline_db,) - if self._result_database is not None - else () - ), - ) flush_best_effort( - run_error, *prepared.additional_databases(covered_queues) + run_error, + prepared.pipeline_db, + prepared.result_db, + # Records a separate result database's flush released (ITL-1408). + *( + (prepared.pipeline_db,) + if self._result_database is not None + else () + ), ) + for queue, database in self._additional_flushes(prepared).items(): + commit_best_effort( + run_error, lambda: self._flush_attachment(queue, database) + ) clear_run_rows(plan.to_run) raise + def _additional_flushes( + self, prepared: _PreparedRun + ) -> "dict[int, ArrowDatabaseProtocol]": + """Include unfinished whole flushes of attachments with function table writes.""" + additional = self._retry_function_flushes | prepared.writes.databases() + self._retry_function_flushes.update(prepared.writes.function_databases()) + return additional + + def _flush_attachment(self, queue: int, database: "ArrowDatabaseProtocol") -> None: + """Flush the attachment, retiring any retry once the flush succeeds.""" + database.flush() + self._retry_function_flushes.pop(queue, None) + def _finish_run( self, prepared: "_PreparedRun", @@ -1564,19 +1561,18 @@ 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. - covered_queues = {id(queue) for queue in prepared.owned_queues} - with collect_owned_flush_queues(covered_queues): + additional = self._additional_flushes(prepared) + database.flush() + database = result_db + database.flush() + 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() - database = result_db - database.flush() - 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() # Node writes can target their own database objects (ITL-1383). - for database in prepared.additional_databases(covered_queues): - database.flush() + for queue, database in additional.items(): + self._flush_attachment(queue, database) except OrcapodDatabaseReadError as exc: # A stored table could not be read: report the read failure itself. exc.add_note(pending_note) diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 72be05b2c..9af51dc53 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -38,7 +38,7 @@ StreamView, ) from orcapod.core.tracker import DEFAULT_TRACKER_MANAGER -from orcapod.databases._write_tracking import track_database_write +from orcapod.core.database_writes import track_database_write from orcapod.errors import ( OrcapodDatabaseError, OrcapodDatabaseReadError, @@ -460,9 +460,7 @@ def _execute_side_effect_row( try: prior = pipeline_database.get_record_by_id(table_path, entry_id) if prior is not None: - with track_database_write( - pipeline_database, table_path, (entry_id,), retry=True - ): + with track_database_write(pipeline_database, table_path, (entry_id,)): # A buffered receipt suppresses delivery but still needs a commit. return (tag, data) except OrcapodDatabaseError as exc: diff --git a/tests/test_pipeline/test_job_attached_database_commit.py b/tests/test_pipeline/test_job_attached_database_commit.py index 5c0576165..2b69fda41 100644 --- a/tests/test_pipeline/test_job_attached_database_commit.py +++ b/tests/test_pipeline/test_job_attached_database_commit.py @@ -14,6 +14,7 @@ ConnectorArrowDatabase, DeltaTableDatabase, InMemoryArrowDatabase, + NoOpArrowDatabase, ) from orcapod.errors import OrcapodDatabaseWriteError from orcapod.invocation import InvocationContext @@ -370,6 +371,94 @@ async def test_duplicate_operator_logs_do_not_flush_an_attached_store( 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) async def test_durable_connector_duplicates_leave_the_attachment_unflushed( From 59452ea32c17899dce7c85e7714dc160e3771e57 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 09:01:02 -0800 Subject: [PATCH 06/16] fix(pipeline): avoid a type import cycle in write enrollment --- src/orcapod/core/database_writes.py | 146 ++++++++++++---------------- src/orcapod/pipeline/job.py | 72 ++++++++++++-- 2 files changed, 129 insertions(+), 89 deletions(-) diff --git a/src/orcapod/core/database_writes.py b/src/orcapod/core/database_writes.py index af9eea7e2..6ff2040e2 100644 --- a/src/orcapod/core/database_writes.py +++ b/src/orcapod/core/database_writes.py @@ -5,81 +5,48 @@ from contextlib import contextmanager from contextvars import ContextVar from dataclasses import dataclass -from typing import TYPE_CHECKING, cast +from typing import TYPE_CHECKING, Protocol from orcapod.errors import OrcapodDatabaseError if TYPE_CHECKING: - from collections.abc import Iterator, Sequence - - from orcapod.protocols.database_protocols import ArrowDatabaseProtocol - - -def _backend(database: ArrowDatabaseProtocol) -> ArrowDatabaseProtocol: - """Unwrap library views that forward operations to a backend.""" - from orcapod.databases.extension_aware_database import ExtensionAwareDatabase - - while isinstance(database, ExtensionAwareDatabase): - database = database._db # pyright: ignore[reportPrivateUsage] - return database - - -def _queue(database: ArrowDatabaseProtocol) -> object: - """Use the shared queue as the identity of a built-in store and its views.""" - backend = _backend(database) - return getattr(backend, "_pending_commits", backend) - - -def _all_durable( - database: ArrowDatabaseProtocol, path: tuple[str, ...], ids: Sequence[bytes] -) -> bool: - """Check committed IDs separately from buffered retries and duplicate upserts.""" - # The database modules can reach the node write sites via core protocols. - from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase - from orcapod.databases.delta_lake_databases import DeltaTableDatabase - from orcapod.databases.in_memory_databases import InMemoryArrowDatabase - from orcapod.databases.utils import sql_table_identifier - - backend = _backend(database) - unique_ids = set(ids) - if isinstance(backend, DeltaTableDatabase): - return unique_ids.issubset(backend._stored_ids(path)) # pyright: ignore[reportPrivateUsage] - if isinstance(backend, InMemoryArrowDatabase): - key = backend._get_record_key(path) # pyright: ignore[reportPrivateUsage] - return unique_ids.issubset(backend._committed_id_index(key)) # pyright: ignore[reportPrivateUsage] - if isinstance(backend, ConnectorArrowDatabase): - key = backend._get_record_key(path) # pyright: ignore[reportPrivateUsage] - schema = backend._schema_from_record_key(key) # pyright: ignore[reportPrivateUsage] - full_path = backend.base_path + path - name = backend._path_to_table_name(full_path) # pyright: ignore[reportPrivateUsage] - table = backend._find_committed_table( # pyright: ignore[reportPrivateUsage] - name, full_path, schema=schema - ) - if table is None: - return False - schema, name = table - column = backend.RECORD_ID_COLUMN - batches = backend._connector.iter_batches( # pyright: ignore[reportPrivateUsage] - f'SELECT "{column}" FROM {sql_table_identifier(name, schema)}' - ) - for batch in batches: - unique_ids.difference_update(cast("list[bytes]", batch[column].to_pylist())) - if not unique_ids: - return True - return False - rows = database.get_records_by_ids(path, unique_ids) - return ( - rows is not None - and rows.num_rows >= len(unique_ids) - and all(database.pending_result(path, row) is None for row in unique_ids) - ) + from collections.abc import Callable, Collection, Iterator, Sequence + + import pyarrow as pa + from orcapod.databases._pending_commits import PendingCommit + + +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.""" + ... + + def get_records_by_ids( + self, record_path: tuple[str, ...], record_ids: Collection[bytes] + ) -> pa.Table | None: + """Look up the given rows, including buffered rows.""" + ... + + def pending_result( + self, record_path: tuple[str, ...], record_id: bytes + ) -> PendingCommit | None: + """Return a commit token for a buffered row, or None for a durable row.""" + ... @dataclass class _Write: """One write site that still needs its database's final whole flush.""" - database: ArrowDatabaseProtocol + database: WriteDatabase sample_id: bytes function: bool @@ -87,24 +54,39 @@ class _Write: class DatabaseWrites: """A run's writes to objects outside the job's original flush sequence.""" - def __init__(self, owned: tuple[ArrowDatabaseProtocol, ...]) -> None: - self._owned: tuple[ArrowDatabaseProtocol, ...] = owned - self._covered: set[int] = {id(_queue(database)) for database in owned} + def __init__( + self, + owned: tuple[WriteDatabase, ...], + *, + shared_queue: Callable[[WriteDatabase], object | None], + all_durable: Callable[[WriteDatabase, tuple[str, ...], Sequence[bytes]], bool], + ) -> None: + self._owned: tuple[WriteDatabase, ...] = owned + self._shared_queue: Callable[[WriteDatabase], object | None] = shared_queue + self._all_durable: Callable[ + [WriteDatabase, tuple[str, ...], Sequence[bytes]], bool + ] = all_durable + self._covered: set[int] = {self._queue_id(database) for database in owned} self._writes: dict[tuple[int, tuple[str, ...]], _Write] = {} + def _queue_id(self, database: WriteDatabase) -> int: + """Identify the store by its shared queue when it exposes one.""" + queue = self._shared_queue(database) + return id(database if queue is None else queue) + def _covered_by_owned_wrapper( self, - database: ArrowDatabaseProtocol, + database: WriteDatabase, path: tuple[str, ...], rows: Sequence[bytes], ) -> bool: """Recognize aliases of an opaque job store by their shared commit token.""" full_path = database.base_path + path - opaque = _queue(database) is _backend(database) + opaque = self._shared_queue(database) is None candidates = [ owned for owned in self._owned - if (opaque or _queue(owned) is _backend(owned)) + if (opaque or self._shared_queue(owned) is None) and full_path[: len(owned.base_path)] == owned.base_path ] if not candidates: @@ -124,14 +106,14 @@ def _covered_by_owned_wrapper( break # A pending row is enough to check where the table is queued. return False - def databases(self) -> dict[int, ArrowDatabaseProtocol]: + def databases(self) -> dict[int, WriteDatabase]: """Return one view per enrolled store in write order.""" - result: dict[int, ArrowDatabaseProtocol] = {} + result: dict[int, WriteDatabase] = {} for (queue, _), write in self._writes.items(): _ = result.setdefault(queue, write.database) return result - def function_databases(self) -> dict[int, ArrowDatabaseProtocol]: + def function_databases(self) -> dict[int, WriteDatabase]: """Return attachments whose function writes may be durable before job commit.""" return { queue: write.database @@ -142,7 +124,7 @@ def function_databases(self) -> dict[int, ArrowDatabaseProtocol]: @contextmanager def track( self, - database: ArrowDatabaseProtocol, + database: WriteDatabase, path: tuple[str, ...], record_ids: Sequence[bytes], *, @@ -150,11 +132,11 @@ def track( function: bool, ) -> Iterator[None]: """Enroll a write unless every ID is already committed.""" - key = (id(_queue(database)), database.base_path + path) + key = (self._queue_id(database), database.base_path + path) if ( key[0] in self._covered or key in self._writes - or (skip_duplicates and _all_durable(database, path, record_ids)) + or (skip_duplicates and self._all_durable(database, path, record_ids)) ): yield return @@ -177,10 +159,10 @@ def track( self._writes[key] = _Write(database, record_ids[0], function) def exclude_unpublished_result( - self, database: ArrowDatabaseProtocol, path: tuple[str, ...] + self, database: WriteDatabase, path: tuple[str, ...] ) -> None: """Leave dry-run results queued when the table commit kept them there.""" - key = (id(_queue(database)), database.base_path + path) + key = (self._queue_id(database), database.base_path + path) write = self._writes.get(key) if ( write is not None @@ -204,7 +186,7 @@ def collect_database_writes(writes: DatabaseWrites) -> Iterator[None]: @contextmanager def track_database_write( - database: ArrowDatabaseProtocol, + database: WriteDatabase, path: tuple[str, ...], record_ids: Sequence[bytes], *, @@ -222,9 +204,7 @@ def track_database_write( yield -def exclude_unpublished_result( - database: ArrowDatabaseProtocol, path: tuple[str, ...] -) -> None: +def exclude_unpublished_result(database: WriteDatabase, path: tuple[str, ...]) -> None: """Keep a dry-run result queued when the job's store did not publish it.""" run = _run_writes.get() if run is not None: diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index c4d56ad27..8abd6469e 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -6,7 +6,7 @@ import enum import logging import sys -from collections.abc import Iterator +from collections.abc import Iterator, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast @@ -46,7 +46,7 @@ warn_row_failures, ) from orcapod.protocols import core_protocols as cp -from orcapod.databases.utils import as_table_committing +from orcapod.databases.utils import as_table_committing, sql_table_identifier from orcapod.types import NodeConfig from orcapod.utils.database_errors import ( commit_best_effort, @@ -57,6 +57,7 @@ if TYPE_CHECKING: from pathlib import Path + from orcapod.core.database_writes import WriteDatabase from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.execution_context import ExecutionContext from orcapod.pipeline.graph import Pipeline @@ -67,6 +68,58 @@ 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 _shared_queue(database: WriteDatabase) -> object | None: + """Use the shared queue as the identity of a built-in store and its views.""" + backend = _backend(database) + return getattr(backend, "_pending_commits", None) + + +def _all_records_durable( + database: WriteDatabase, path: tuple[str, ...], ids: Sequence[bytes] +) -> bool: + """Check committed IDs separately from buffered retries and duplicate upserts.""" + backend = _backend(database) + unique_ids = set(ids) + if isinstance(backend, orcapod.databases.DeltaTableDatabase): + return unique_ids.issubset(backend._stored_ids(path)) # pyright: ignore[reportPrivateUsage] + if isinstance(backend, orcapod.databases.InMemoryArrowDatabase): + key = backend._get_record_key(path) # pyright: ignore[reportPrivateUsage] + return unique_ids.issubset(backend._committed_id_index(key)) # pyright: ignore[reportPrivateUsage] + if isinstance(backend, orcapod.databases.ConnectorArrowDatabase): + key = backend._get_record_key(path) # pyright: ignore[reportPrivateUsage] + schema = backend._schema_from_record_key(key) # pyright: ignore[reportPrivateUsage] + full_path = backend.base_path + path + name = backend._path_to_table_name(full_path) # pyright: ignore[reportPrivateUsage] + table = backend._find_committed_table( # pyright: ignore[reportPrivateUsage] + name, full_path, schema=schema + ) + if table is None: + return False + schema, name = table + column = backend.RECORD_ID_COLUMN + batches = backend._connector.iter_batches( # pyright: ignore[reportPrivateUsage] + f'SELECT "{column}" FROM {sql_table_identifier(name, schema)}' + ) + for batch in batches: + unique_ids.difference_update(cast("list[bytes]", batch[column].to_pylist())) + if not unique_ids: + return True + return False + rows = database.get_records_by_ids(path, unique_ids) + return ( + rows is not None + and rows.num_rows >= len(unique_ids) + and all(database.pending_result(path, row) is None for row in unique_ids) + ) + + class _Unchanged(enum.Enum): """The default of ``PipelineJob.bind(result_database=...)``: keep the binding. @@ -1441,7 +1494,9 @@ def _prepare_run( plan=plan, unchecked_sources=unchecked, writes=DatabaseWrites( - (pipeline_db, result_db, *self._node_database_views, self._database) + (pipeline_db, result_db, *self._node_database_views, self._database), + shared_queue=_shared_queue, + all_durable=_all_records_durable, ), ) @@ -1505,14 +1560,19 @@ def _additional_flushes( self, prepared: _PreparedRun ) -> "dict[int, ArrowDatabaseProtocol]": """Include unfinished whole flushes of attachments with function table writes.""" - additional = self._retry_function_flushes | prepared.writes.databases() - self._retry_function_flushes.update(prepared.writes.function_databases()) + # 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() + ) + additional = self._retry_function_flushes | current + self._retry_function_flushes.update(function) return additional def _flush_attachment(self, queue: int, database: "ArrowDatabaseProtocol") -> None: """Flush the attachment, retiring any retry once the flush succeeds.""" database.flush() - self._retry_function_flushes.pop(queue, None) + _ = self._retry_function_flushes.pop(queue, None) def _finish_run( self, From 64d62a3fbeb477e14e325d9f2b7678625a8bc861 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 09:51:02 -0800 Subject: [PATCH 07/16] fix(pipeline): retry durable logs and preserve owned flush counts --- changelog.d/ITL-1383.md | 2 +- docs/dev/design_issues/ITL-1383-BL3.md | 10 +- src/orcapod/core/database_writes.py | 87 +++++++++--- src/orcapod/pipeline/job.py | 97 +++++++++++--- .../test_job_attached_database_commit.py | 124 +++++++++++++++++- 5 files changed, 274 insertions(+), 46 deletions(-) diff --git a/changelog.d/ITL-1383.md b/changelog.d/ITL-1383.md index a9b72d923..caa19572f 100644 --- a/changelog.d/ITL-1383.md +++ b/changelog.d/ITL-1383.md @@ -1,3 +1,3 @@ ### 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 retry can commit pending log rows and retry a failed whole flush after function tables have committed. +- 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 retry can commit pending log rows or finish a failed whole flush after a function or LOG table has already committed. diff --git a/docs/dev/design_issues/ITL-1383-BL3.md b/docs/dev/design_issues/ITL-1383-BL3.md index 7eca1a803..8405930c5 100644 --- a/docs/dev/design_issues/ITL-1383-BL3.md +++ b/docs/dev/design_issues/ITL-1383-BL3.md @@ -12,12 +12,14 @@ 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. The job also attempts the flush when execution -fails, keeping the original error. Load-only runs skip the commit. A failed flush +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 duplicates leave the attachment alone. 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 of that attachment is retried when the function's tables -are already durable. +A failed whole flush of an attachment is retried when its function tables or +operator logs are already durable at the time of failure. If the job is rebound +to the same underlying store, its regular commit covers the retry. diff --git a/src/orcapod/core/database_writes.py b/src/orcapod/core/database_writes.py index 6ff2040e2..a5da08f55 100644 --- a/src/orcapod/core/database_writes.py +++ b/src/orcapod/core/database_writes.py @@ -2,6 +2,7 @@ from __future__ import annotations +import logging from contextlib import contextmanager from contextvars import ContextVar from dataclasses import dataclass @@ -10,11 +11,19 @@ from orcapod.errors import OrcapodDatabaseError if TYPE_CHECKING: - from collections.abc import Callable, Collection, Iterator, Sequence + from collections.abc import ( + Callable, + Collection, + Iterator, + Sequence, + ) + from contextlib import AbstractContextManager import pyarrow as pa from orcapod.databases._pending_commits import PendingCommit +logger = logging.getLogger(__name__) + class WriteDatabase(Protocol): """The database operations needed at the node write sites.""" @@ -41,6 +50,12 @@ def pending_result( """Return a commit token for a buffered row, or None for a durable row.""" ... + def guard_record( + self, record_path: tuple[str, ...], record_id: bytes, dependency: PendingCommit + ) -> AbstractContextManager[None]: + """Register a record's dependency on a pending commit.""" + ... + @dataclass class _Write: @@ -49,6 +64,7 @@ class _Write: database: WriteDatabase sample_id: bytes function: bool + log_ids: set[bytes] class DatabaseWrites: @@ -59,21 +75,35 @@ def __init__( owned: tuple[WriteDatabase, ...], *, shared_queue: Callable[[WriteDatabase], object | None], - all_durable: Callable[[WriteDatabase, tuple[str, ...], Sequence[bytes]], bool], + all_durable: Callable[ + [WriteDatabase, tuple[str, ...], Collection[bytes]], bool + ], ) -> None: self._owned: tuple[WriteDatabase, ...] = owned self._shared_queue: Callable[[WriteDatabase], object | None] = shared_queue + self._queues: dict[int, tuple[WriteDatabase, object | None]] = {} self._all_durable: Callable[ - [WriteDatabase, tuple[str, ...], Sequence[bytes]], bool + [WriteDatabase, tuple[str, ...], Collection[bytes]], bool ] = all_durable - self._covered: set[int] = {self._queue_id(database) for database in owned} + self._covered: set[int] = {self.queue_id(database) for database in owned} self._writes: dict[tuple[int, tuple[str, ...]], _Write] = {} - def _queue_id(self, database: WriteDatabase) -> int: + def _queue(self, database: WriteDatabase) -> object | 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._shared_queue(database) + 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 _covered_by_owned_wrapper( self, database: WriteDatabase, @@ -82,11 +112,11 @@ def _covered_by_owned_wrapper( ) -> bool: """Recognize aliases of an opaque job store by their shared commit token.""" full_path = database.base_path + path - opaque = self._shared_queue(database) is None + opaque = self._queue(database) is None candidates = [ owned for owned in self._owned - if (opaque or self._shared_queue(owned) is None) + if (opaque or self._queue(owned) is None) and full_path[: len(owned.base_path)] == owned.base_path ] if not candidates: @@ -121,6 +151,23 @@ def function_databases(self) -> dict[int, WriteDatabase]: if write.function } + def has_durable_logs(self, queue: int) -> bool: + """Check if a failed whole flush leaves a log whose replay needs no insert.""" + for (identity, full_path), write in self._writes.items(): + if identity != queue or not write.log_ids: + continue + try: + path = full_path[len(write.database.base_path) :] + if self._all_durable(write.database, path, write.log_ids): + return True + except Exception: + # Preserve the original flush failure if the table cannot be read. + logger.debug( + "Could not check log durability after a flush failure", + exc_info=True, + ) + return False + @contextmanager def track( self, @@ -132,15 +179,21 @@ def track( function: bool, ) -> Iterator[None]: """Enroll a write unless every ID is already committed.""" - key = (self._queue_id(database), database.base_path + path) - if ( - key[0] in self._covered - or key in self._writes - or (skip_duplicates and self._all_durable(database, path, record_ids)) - ): + key = (self.queue_id(database), database.base_path + path) + if self.covers(key[0]): + yield + return + previous = self._writes.get(key) + if previous is not None: + yield + if not function: + previous.log_ids.update(record_ids) + return + if skip_duplicates and self._all_durable(database, path, record_ids): yield return + log_ids: set[bytes] = set() if function else set(record_ids) try: yield except Exception: @@ -150,19 +203,19 @@ def track( try: if database.pending_result(path, row) is not None: if not self._covered_by_owned_wrapper(database, path, (row,)): - self._writes[key] = _Write(database, row, function) + self._writes[key] = _Write(database, row, function, log_ids) break except (ValueError, OrcapodDatabaseError): continue raise if not self._covered_by_owned_wrapper(database, path, record_ids): - self._writes[key] = _Write(database, record_ids[0], function) + self._writes[key] = _Write(database, record_ids[0], function, log_ids) def exclude_unpublished_result( self, database: WriteDatabase, path: tuple[str, ...] ) -> None: """Leave dry-run results queued when the table commit kept them there.""" - key = (self._queue_id(database), database.base_path + path) + key = (self.queue_id(database), database.base_path + path) write = self._writes.get(key) if ( write is not None diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 8abd6469e..bf232d3ce 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -6,10 +6,13 @@ import enum import logging import sys -from collections.abc import Iterator, Sequence +import uuid +from collections.abc import Collection, Iterator from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast +from typing_extensions import override + import orcapod from orcapod.core.database_writes import DatabaseWrites, collect_database_writes from orcapod.core.nodes import JobNode @@ -20,6 +23,7 @@ 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 PendingCommit from orcapod.errors import ( OrcapodDatabaseError, OrcapodDatabaseReadError, @@ -51,13 +55,13 @@ from orcapod.utils.database_errors import ( commit_best_effort, database_write_path, - flush_best_effort, ) if TYPE_CHECKING: from pathlib import Path from orcapod.core.database_writes import WriteDatabase + 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 @@ -75,14 +79,37 @@ def _backend(database: WriteDatabase) -> WriteDatabase: return database +class _QueueProbe(PendingCommit): + """Capture the queue that registers a dependency through a forwarding view.""" + + queue: PendingCommits | None = None + + @override + def add_dependent(self, queue: PendingCommits, key: str, record_id: bytes) -> None: + """Identify the queue without retaining any dependent records.""" + self.queue = queue + + def _shared_queue(database: WriteDatabase) -> object | None: - """Use the shared queue as the identity of a built-in store and its views.""" + """Identify scoped views by their actual pending queue.""" backend = _backend(database) - return getattr(backend, "_pending_commits", None) + queue = getattr(backend, "_pending_commits", None) + if queue is not None or not database.stores_records: + return queue + + # A protocol wrapper can forward guards without exposing its backend. Use a + # fresh table and id with no insert, so exiting the guard removes it. + probe = _QueueProbe() + nonce = uuid.uuid4() + try: + with database.guard_record((f"queue_probe_{nonce.hex}",), nonce.bytes, probe): + return probe.queue + except (ValueError, OrcapodDatabaseError, NotImplementedError): + return None def _all_records_durable( - database: WriteDatabase, path: tuple[str, ...], ids: Sequence[bytes] + database: WriteDatabase, path: tuple[str, ...], ids: Collection[bytes] ) -> bool: """Check committed IDs separately from buffered retries and duplicate upserts.""" backend = _backend(database) @@ -238,7 +265,7 @@ def __init__( self._database = database self._result_database: "ArrowDatabaseProtocol | None" = result_database self._node_database_views: "tuple[ArrowDatabaseProtocol, ...]" = () - self._retry_function_flushes: "dict[int, ArrowDatabaseProtocol]" = {} + self._retry_attachment_flushes: "dict[int, ArrowDatabaseProtocol]" = {} # 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 @@ -1273,7 +1300,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) @@ -1538,8 +1564,7 @@ def _executing( # 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, + owned = ( prepared.pipeline_db, prepared.result_db, # Records a separate result database's flush released (ITL-1408). @@ -1549,9 +1574,16 @@ def _executing( else () ), ) + for database in owned: + commit_best_effort( + run_error, lambda: self._flush_owned(database, prepared.writes) + ) for queue, database in self._additional_flushes(prepared).items(): commit_best_effort( - run_error, lambda: self._flush_attachment(queue, database) + run_error, + lambda: self._flush_attachment( + queue, database, prepared.writes + ), ) clear_run_rows(plan.to_run) raise @@ -1559,20 +1591,43 @@ def _executing( def _additional_flushes( self, prepared: _PreparedRun ) -> "dict[int, ArrowDatabaseProtocol]": - """Include unfinished whole flushes of attachments with function table writes.""" + """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() ) - additional = self._retry_function_flushes | current - self._retry_function_flushes.update(function) - return additional + additional = self._retry_attachment_flushes | current + self._retry_attachment_flushes.update(function) + return { + queue: database + for queue, database in additional.items() + if not prepared.writes.covers(queue) + } - def _flush_attachment(self, queue: int, database: "ArrowDatabaseProtocol") -> None: - """Flush the attachment, retiring any retry once the flush succeeds.""" + 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_function_flushes.pop(queue, None) + _ = 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 even if its logs are already durable.""" + try: + database.flush() + except Exception: + # Logs still pending are enrolled by replay, unless another handle + # makes them durable first. Remember logs already durable here, + # because replay alone cannot recover the failed whole flush. + if queue not in self._retry_attachment_flushes and writes.has_durable_logs( + queue + ): + self._retry_attachment_flushes[queue] = database + raise + _ = self._retry_attachment_flushes.pop(queue, None) def _finish_run( self, @@ -1622,17 +1677,17 @@ def _finish_run( # across databases too, so no order of these flushes publishes a record # before its result. additional = self._additional_flushes(prepared) - database.flush() + 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() + self._flush_owned(database, prepared.writes) # Node writes can target their own database objects (ITL-1383). for queue, database in additional.items(): - self._flush_attachment(queue, database) + self._flush_attachment(queue, database, prepared.writes) except OrcapodDatabaseReadError as exc: # A stored table could not be read: report the read failure itself. exc.add_note(pending_note) diff --git a/tests/test_pipeline/test_job_attached_database_commit.py b/tests/test_pipeline/test_job_attached_database_commit.py index 2b69fda41..55b8c5d4e 100644 --- a/tests/test_pipeline/test_job_attached_database_commit.py +++ b/tests/test_pipeline/test_job_attached_database_commit.py @@ -7,8 +7,11 @@ import deltalake import pyarrow as pa import pytest +from typing_extensions import override from orcapod import PipelineJob, function_pod +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, @@ -486,18 +489,25 @@ async def test_durable_connector_duplicates_leave_the_attachment_unflushed( @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.""" - store = ProtocolDatabase(DeltaTableDatabase(tmp_path)) - job = _make_job(store, store.at("alias"), source) + 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, ...]] = [] @@ -515,7 +525,7 @@ def on_run_end(self, run_id: str) -> None: await _run(job, runner, observer=FailRun()) else: await _run(job, runner) - assert paths == [("job",), ("job", "_result")] + 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 @@ -568,6 +578,114 @@ async def test_an_attached_database_flush_includes_other_writes_after_auto_commi 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( From b9e3200b4bae74462bc0649be79cf8d10fc06738 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 10:45:04 -0800 Subject: [PATCH 08/16] fix(pipeline): retain failed attachment flushes across rebindings --- changelog.d/ITL-1383.md | 2 +- docs/dev/design_issues/ITL-1383-BL3.md | 7 +- src/orcapod/core/database_writes.py | 72 ++++++++++++++---- src/orcapod/pipeline/job.py | 72 +++++++++++++----- src/orcapod/side_effects.py | 6 +- .../test_job_attached_database_commit.py | 75 +++++++++++++++++-- 6 files changed, 186 insertions(+), 48 deletions(-) diff --git a/changelog.d/ITL-1383.md b/changelog.d/ITL-1383.md index caa19572f..0491f9a42 100644 --- a/changelog.d/ITL-1383.md +++ b/changelog.d/ITL-1383.md @@ -1,3 +1,3 @@ ### 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 retry can commit pending log rows or finish a failed whole flush after a function or LOG table has already committed. +- 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. The job retries a failed attachment flush even after rebinding its sources or node attachments. Duplicate-only replays leave unrelated pending rows alone when the replayed rows are already durable. diff --git a/docs/dev/design_issues/ITL-1383-BL3.md b/docs/dev/design_issues/ITL-1383-BL3.md index 8405930c5..de296b7b5 100644 --- a/docs/dev/design_issues/ITL-1383-BL3.md +++ b/docs/dev/design_issues/ITL-1383-BL3.md @@ -20,6 +20,7 @@ available. A retry can flush the same log rows and side-effect receipts when they are still pending. Durable duplicates leave the attachment alone. 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 of an attachment is retried when its function tables or -operator logs are already durable at the time of failure. If the job is rebound -to the same underlying store, its regular commit covers the retry. +A failed whole flush stays with the job across source and attachment rebindings. +If an attachment becomes a job-owned store, the regular commit covers the retry. +If a second handle makes previously pending logs durable, a duplicate-only replay +leaves the attachment's unrelated writes buffered. diff --git a/src/orcapod/core/database_writes.py b/src/orcapod/core/database_writes.py index a5da08f55..142b45f41 100644 --- a/src/orcapod/core/database_writes.py +++ b/src/orcapod/core/database_writes.py @@ -6,7 +6,7 @@ from contextlib import contextmanager from contextvars import ContextVar from dataclasses import dataclass -from typing import TYPE_CHECKING, Protocol +from typing import TYPE_CHECKING, Protocol, cast from orcapod.errors import OrcapodDatabaseError @@ -39,7 +39,10 @@ def stores_records(self) -> bool: ... def get_records_by_ids( - self, record_path: tuple[str, ...], record_ids: Collection[bytes] + self, + record_path: tuple[str, ...], + record_ids: Collection[bytes], + record_id_column: str | None = None, ) -> pa.Table | None: """Look up the given rows, including buffered rows.""" ... @@ -87,6 +90,9 @@ def __init__( ] = all_durable self._covered: set[int] = {self.queue_id(database) for database in owned} self._writes: dict[tuple[int, tuple[str, ...]], _Write] = {} + self._duplicate_logs: dict[ + tuple[int, tuple[str, ...]], tuple[WriteDatabase, set[bytes]] + ] = {} def _queue(self, database: WriteDatabase) -> object | None: """Resolve each view once and keep it alive while its identity is in use.""" @@ -151,22 +157,45 @@ def function_databases(self) -> dict[int, WriteDatabase]: if write.function } - def has_durable_logs(self, queue: int) -> bool: - """Check if a failed whole flush leaves a log whose replay needs no insert.""" + def logs_to_replay(self, queue: int) -> dict[tuple[str, ...], set[bytes]] | None: + """Identify pending logs, or return None when the run wrote no logs here.""" + logs: dict[tuple[str, ...], set[bytes]] = {} for (identity, full_path), write in self._writes.items(): if identity != queue or not write.log_ids: continue try: path = full_path[len(write.database.base_path) :] if self._all_durable(write.database, path, write.log_ids): - return True + # The whole flush was owed even with this log already durable. + return {} except Exception: # Preserve the original flush failure if the table cannot be read. logger.debug( "Could not check log durability after a flush failure", exc_info=True, ) - return False + return {} + logs[full_path] = write.log_ids + return logs or None + + def replayed_durable_logs( + self, + queue: int, + logs: dict[tuple[str, ...], set[bytes]], + ) -> bool: + """A duplicate-only replay can find the failed logs now durable elsewhere.""" + try: + for full_path, ids in logs.items(): + replay = self._duplicate_logs.get((queue, full_path)) + if replay is None: + return False + database, duplicates = replay + path = full_path[len(database.base_path) :] + if not ids <= duplicates or not self._all_durable(database, path, ids): + return False + except (ValueError, OrcapodDatabaseError): + return False + return bool(logs) @contextmanager def track( @@ -178,22 +207,39 @@ def track( skip_duplicates: bool, function: bool, ) -> Iterator[None]: - """Enroll a write unless every ID is already committed.""" + """Enroll a write if it has a record the database did not already hold.""" key = (self.queue_id(database), database.base_path + path) if self.covers(key[0]): yield return previous = self._writes.get(key) - if previous is not None: - yield - if not function: - previous.log_ids.update(record_ids) - return - if skip_duplicates and self._all_durable(database, path, record_ids): + if previous is not None and function: yield return + if skip_duplicates: + # Connector reads can return both a durable record and its buffered + # duplicate. Count distinct IDs so those copies cannot mask a new row. + id_column = "__record_id" + rows = database.get_records_by_ids(path, set(record_ids), id_column) + existing: set[bytes] = ( + set() + if rows is None + else set(cast("list[bytes]", rows[id_column].to_pylist())) + ) + record_ids = [row for row in record_ids if row not in existing] + if not record_ids: + yield + if not function: + self._duplicate_logs.setdefault(key, (database, set()))[1].update( + existing + ) + return log_ids: set[bytes] = set() if function else set(record_ids) + if previous is not None: + yield + previous.log_ids.update(log_ids) + return try: yield except Exception: diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index bf232d3ce..0930de480 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -190,6 +190,14 @@ class _PreparedRun: writes: DatabaseWrites +@dataclass(frozen=True) +class _AttachmentRetry: + """A failed whole flush, with any pending logs that could make it redundant.""" + + database: ArrowDatabaseProtocol + logs: dict[tuple[str, ...], set[bytes]] + + def _with_counter( observer: "ExecutionObserverProtocol | None", counter: RunCountingObserver ) -> "ExecutionObserverProtocol": @@ -265,7 +273,7 @@ def __init__( self._database = database self._result_database: "ArrowDatabaseProtocol | None" = result_database self._node_database_views: "tuple[ArrowDatabaseProtocol, ...]" = () - self._retry_attachment_flushes: "dict[int, 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 @@ -1597,11 +1605,21 @@ def _additional_flushes( function = cast( "dict[int, ArrowDatabaseProtocol]", prepared.writes.function_databases() ) - additional = self._retry_attachment_flushes | current - self._retry_attachment_flushes.update(function) + 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 additional.items() + for queue, database in (retries | current).items() if not prepared.writes.covers(queue) } @@ -1615,20 +1633,32 @@ def _flush_owned( def _flush_attachment( self, queue: int, database: "ArrowDatabaseProtocol", writes: DatabaseWrites ) -> None: - """Keep a failed whole flush eligible even if its logs are already durable.""" + """Keep a failed whole flush eligible across source or database bindings.""" try: database.flush() except Exception: - # Logs still pending are enrolled by replay, unless another handle - # makes them durable first. Remember logs already durable here, - # because replay alone cannot recover the failed whole flush. - if queue not in self._retry_attachment_flushes and writes.has_durable_logs( - queue - ): - self._retry_attachment_flushes[queue] = database + 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", @@ -1669,6 +1699,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 @@ -1686,20 +1717,21 @@ def _finish_run( database = pipeline_db self._flush_owned(database, prepared.writes) # Node writes can target their own database objects (ITL-1383). - for queue, database in additional.items(): + for queue in tuple(additional): + database = additional.pop(queue) self._flush_attachment(queue, database, prepared.writes) - 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. - clear_run_rows(plan.to_run) - raise except Exception as exc: + for queue, attachment in additional.items(): + self._retain_attachment_flush(queue, attachment, prepared.writes) + clear_run_rows(plan.to_run) + 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 diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 9af51dc53..504dbfa81 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -459,14 +459,12 @@ def _execute_side_effect_row( ): try: prior = pipeline_database.get_record_by_id(table_path, entry_id) - if prior is not None: - with track_database_write(pipeline_database, table_path, (entry_id,)): - # A buffered receipt suppresses delivery but still needs a commit. - return (tag, data) except OrcapodDatabaseError as exc: # A failed lookup fails the run like a failed write: name pod and row. exc.add_context(node_label=pod_name, tag=tag.as_dict()) raise + if prior is not None: + return (tag, data) # already completed — re-emit without re-delivery # 3. Build InvocationContext (invocation_hash derived lazily via format_id()). ctx = InvocationContext( diff --git a/tests/test_pipeline/test_job_attached_database_commit.py b/tests/test_pipeline/test_job_attached_database_commit.py index 55b8c5d4e..89207ff52 100644 --- a/tests/test_pipeline/test_job_attached_database_commit.py +++ b/tests/test_pipeline/test_job_attached_database_commit.py @@ -464,27 +464,27 @@ def fail() -> None: @pytest.mark.asyncio @pytest.mark.parametrize("runner", JOB_RUNNERS) +@pytest.mark.parametrize("wrapped", [False, True], ids=["native", "protocol"]) async def test_durable_connector_duplicates_leave_the_attachment_unflushed( - tmp_path: Path, runner: str, source: ArrowTableSource + tmp_path: Path, runner: str, source: ArrowTableSource, *, wrapped: bool ) -> None: """A connector defers durable duplicate checking to the upsert.""" connector = CommitConnector() - attachment = ConnectorArrowDatabase(connector) + store = ConnectorArrowDatabase(connector) + attachment = ProtocolDatabase(store) if wrapped else store job = _make_job(DeltaTableDatabase(tmp_path), attachment, source) - await _run(job, runner) - attachment.flush() + job.nodes["grouped"].run() reopened = ConnectorArrowDatabase(connector) existing_paths = reopened.list_table_paths() assert len(existing_paths) == 1 - for label in ("other", "grouped"): - job.nodes[label].clear_cache() 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 reopened.list_table_paths() == existing_paths - job.nodes["grouped"].clear_cache() @pytest.mark.asyncio @@ -563,6 +563,67 @@ def fail() -> None: 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( From f22fa0675b89e8956f1e5026bfb0e13fce3d5f45 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 11:36:35 -0800 Subject: [PATCH 09/16] fix(pipeline): preserve attachment flush retries and owned cadence --- changelog.d/ITL-1383.md | 4 + docs/dev/design_issues/ITL-1383-BL3.md | 7 +- src/orcapod/core/database_writes.py | 49 ++++--- src/orcapod/core/result_cache.py | 1 - src/orcapod/pipeline/job.py | 45 +++--- .../test_job_attached_database_commit.py | 136 +++++++++++++++++- .../test_mixed_function_commits.py | 4 +- 7 files changed, 196 insertions(+), 50 deletions(-) diff --git a/changelog.d/ITL-1383.md b/changelog.d/ITL-1383.md index 0491f9a42..a2797922d 100644 --- a/changelog.d/ITL-1383.md +++ b/changelog.d/ITL-1383.md @@ -1,3 +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. The job retries a failed attachment flush even after rebinding its sources or node attachments. Duplicate-only replays leave unrelated pending rows alone when the replayed rows are already durable. + +### 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/dev/design_issues/ITL-1383-BL3.md b/docs/dev/design_issues/ITL-1383-BL3.md index de296b7b5..525343e39 100644 --- a/docs/dev/design_issues/ITL-1383-BL3.md +++ b/docs/dev/design_issues/ITL-1383-BL3.md @@ -21,6 +21,11 @@ they are still pending. Durable duplicates leave the attachment alone. 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, the regular commit covers the retry. +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 a second handle makes previously pending logs durable, a duplicate-only replay leaves the attachment's unrelated writes buffered. + +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 index 142b45f41..83aca28b2 100644 --- a/src/orcapod/core/database_writes.py +++ b/src/orcapod/core/database_writes.py @@ -81,6 +81,7 @@ def __init__( all_durable: Callable[ [WriteDatabase, tuple[str, ...], Collection[bytes]], bool ], + supports_enrollment: Callable[[WriteDatabase], bool], ) -> None: self._owned: tuple[WriteDatabase, ...] = owned self._shared_queue: Callable[[WriteDatabase], object | None] = shared_queue @@ -88,6 +89,7 @@ def __init__( self._all_durable: Callable[ [WriteDatabase, tuple[str, ...], Collection[bytes]], bool ] = all_durable + self._supports_enrollment = supports_enrollment self._covered: set[int] = {self.queue_id(database) for database in owned} self._writes: dict[tuple[int, tuple[str, ...]], _Write] = {} self._duplicate_logs: dict[ @@ -204,10 +206,14 @@ def track( path: tuple[str, ...], record_ids: Sequence[bytes], *, - skip_duplicates: bool, function: bool, ) -> Iterator[None]: """Enroll a write if it has a record the database did not already hold.""" + # Opaque stores can expose a pending token even for a durable row and + # their writes return no status. Keep their existing commit behavior. + if not self._supports_enrollment(database): + yield + return key = (self.queue_id(database), database.base_path + path) if self.covers(key[0]): yield @@ -216,24 +222,24 @@ def track( if previous is not None and function: yield return - if skip_duplicates: - # Connector reads can return both a durable record and its buffered - # duplicate. Count distinct IDs so those copies cannot mask a new row. - id_column = "__record_id" - rows = database.get_records_by_ids(path, set(record_ids), id_column) - existing: set[bytes] = ( - set() - if rows is None - else set(cast("list[bytes]", rows[id_column].to_pylist())) - ) - record_ids = [row for row in record_ids if row not in existing] - if not record_ids: - yield - if not function: - self._duplicate_logs.setdefault(key, (database, set()))[1].update( - existing - ) - return + # The native add methods accept every previously absent ID on success, + # even if the row reaches the auto-commit threshold during the call. + # A connector can return both durable and buffered copies of an ID. + id_column = "__record_id" + rows = database.get_records_by_ids(path, set(record_ids), id_column) + existing: set[bytes] = ( + set() + if rows is None + else set(cast("list[bytes]", rows[id_column].to_pylist())) + ) + record_ids = [row for row in record_ids if row not in existing] + if not record_ids: + yield + if not function: + self._duplicate_logs.setdefault(key, (database, set()))[1].update( + existing + ) + return log_ids: set[bytes] = set() if function else set(record_ids) if previous is not None: @@ -289,7 +295,6 @@ def track_database_write( path: tuple[str, ...], record_ids: Sequence[bytes], *, - skip_duplicates: bool = True, function: bool = False, ) -> Iterator[None]: """Track a write when the node is running as part of a job.""" @@ -297,9 +302,7 @@ def track_database_write( if run is None or not record_ids or not database.stores_records: yield return - with run.track( - database, path, record_ids, skip_duplicates=skip_duplicates, function=function - ): + with run.track(database, path, record_ids, function=function): yield diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index d363ca4c9..22ee442b1 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -485,7 +485,6 @@ def store( self._result_database, path, (result_id,), - skip_duplicates=skip_duplicates, function=True, ): self._result_database.add_record( diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 0930de480..04c41ccc8 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -79,6 +79,18 @@ def _backend(database: WriteDatabase) -> WriteDatabase: 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, + ), + ) + + class _QueueProbe(PendingCommit): """Capture the queue that registers a dependency through a forwarding view.""" @@ -139,12 +151,7 @@ def _all_records_durable( if not unique_ids: return True return False - rows = database.get_records_by_ids(path, unique_ids) - return ( - rows is not None - and rows.num_rows >= len(unique_ids) - and all(database.pending_result(path, row) is None for row in unique_ids) - ) + return False class _Unchanged(enum.Enum): @@ -1492,6 +1499,12 @@ 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), + shared_queue=_shared_queue, + all_durable=_all_records_durable, + supports_enrollment=_supports_attachment_enrollment, + ) # 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 @@ -1508,7 +1521,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 @@ -1527,11 +1540,7 @@ def _prepare_run( result_db=result_db, plan=plan, unchecked_sources=unchecked, - writes=DatabaseWrites( - (pipeline_db, result_db, *self._node_database_views, self._database), - shared_queue=_shared_queue, - all_durable=_all_records_durable, - ), + writes=writes, ) @contextlib.contextmanager @@ -1636,7 +1645,7 @@ def _flush_attachment( """Keep a failed whole flush eligible across source or database bindings.""" try: database.flush() - except Exception: + except BaseException: self._retain_attachment_flush(queue, database, writes) raise _ = self._retry_attachment_flushes.pop(queue, None) @@ -1720,10 +1729,13 @@ def _finish_run( for queue in tuple(additional): database = additional.pop(queue) self._flush_attachment(queue, database, prepared.writes) - except Exception as exc: + except BaseException as exc: for queue, attachment in additional.items(): self._retain_attachment_flush(queue, attachment, prepared.writes) clear_run_rows(plan.to_run) + 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) @@ -1733,11 +1745,6 @@ def _finish_run( ) flush_error.add_note(pending_note) 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/tests/test_pipeline/test_job_attached_database_commit.py b/tests/test_pipeline/test_job_attached_database_commit.py index 89207ff52..9ff3b8ca6 100644 --- a/tests/test_pipeline/test_job_attached_database_commit.py +++ b/tests/test_pipeline/test_job_attached_database_commit.py @@ -16,6 +16,7 @@ from orcapod.databases import ( ConnectorArrowDatabase, DeltaTableDatabase, + ExtensionAwareDatabase, InMemoryArrowDatabase, NoOpArrowDatabase, ) @@ -25,6 +26,7 @@ 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 from orcapod.sources import ArrowTableSource from orcapod.types import CacheMode, NodeConfig @@ -363,7 +365,7 @@ async def test_duplicate_operator_logs_do_not_flush_an_attached_store( store = DeltaTableDatabase(tmp_path / "attached") attached = ProtocolDatabase(store) if wrapped else store job = _make_job(DeltaTableDatabase(tmp_path / "owned"), attached, source) - await _run(job, runner) + job.nodes["grouped"].run() assert len(list((tmp_path / "attached").rglob("_delta_log"))) == 1 for label in ("other", "grouped"): job.nodes[label].clear_cache() @@ -532,7 +534,7 @@ def on_run_end(self, run_id: str) -> None: @pytest.mark.asyncio @pytest.mark.parametrize("runner", JOB_RUNNERS) -@pytest.mark.parametrize("wrapped", [False, True], ids=["native", "protocol"]) +@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, @@ -543,7 +545,9 @@ async def test_retry_commits_operator_logs_left_pending_by_a_failed_flush( ) -> None: """A retry commits the same record IDs even though the queue deduplicates them.""" store = DeltaTableDatabase(tmp_path / "attached") - attached = ProtocolDatabase(store) if wrapped else store + attached = ( + ExtensionAwareDatabase(store, UniversalTypeConverter()) if wrapped else store + ) job = _make_job(DeltaTableDatabase(tmp_path / "owned"), attached, source) def fail() -> None: @@ -769,7 +773,7 @@ def deliver(ctx: InvocationContext, x: int, y: int) -> None: @pytest.mark.asyncio @pytest.mark.parametrize("runner", JOB_RUNNERS) -@pytest.mark.parametrize("wrapped", [False, True], ids=["native", "protocol"]) +@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, @@ -789,7 +793,9 @@ def deliver(ctx: InvocationContext, x: int, y: int) -> None: with job: _ = SideEffectPod(deliver)(source, label="delivery") store = DeltaTableDatabase(tmp_path) - attachment = ProtocolDatabase(store) if wrapped else store + attachment = ( + ExtensionAwareDatabase(store, UniversalTypeConverter()) if wrapped else store + ) job.nodes["delivery"].attach_databases(attachment) def fail() -> None: @@ -810,3 +816,123 @@ def fail() -> None: 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("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) + try: + await _run(job, runner) + except OrcapodDatabaseWriteError: + pass # The reviewed head enrolled the forwarding wrapper. + 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 85cb84271..dfa36e3f6 100644 --- a/tests/test_pipeline/test_mixed_function_commits.py +++ b/tests/test_pipeline/test_mixed_function_commits.py @@ -624,6 +624,8 @@ def observe_flush(database: InMemoryArrowDatabase) -> None: ] expected: list[tuple[str, ...]] = [("pipeline", "mixed")] * 4 expected.append(("pipeline", "mixed", "_result")) - if placement != "shared": + # 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 From 0203fe0c9f4376df2d1e282dc80174f4269c1c63 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 12:09:52 -0800 Subject: [PATCH 10/16] fix(pipeline): retain attachments after an interrupted best-effort flush --- docs/dev/design_issues/ITL-1383-BL3.md | 2 + src/orcapod/pipeline/job.py | 30 +++++++++---- .../test_job_attached_database_commit.py | 43 +++++++++++++++++++ 3 files changed, 66 insertions(+), 9 deletions(-) diff --git a/docs/dev/design_issues/ITL-1383-BL3.md b/docs/dev/design_issues/ITL-1383-BL3.md index 525343e39..210673e3b 100644 --- a/docs/dev/design_issues/ITL-1383-BL3.md +++ b/docs/dev/design_issues/ITL-1383-BL3.md @@ -23,6 +23,8 @@ 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. If a second handle makes previously pending logs durable, a duplicate-only replay leaves the attachment's unrelated writes buffered. diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 04c41ccc8..51db62db2 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -1580,7 +1580,8 @@ 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: + best_effort = isinstance(run_error, Exception) and not load_only + if best_effort: owned = ( prepared.pipeline_db, prepared.result_db, @@ -1595,14 +1596,25 @@ def _executing( commit_best_effort( run_error, lambda: self._flush_owned(database, prepared.writes) ) - for queue, database in self._additional_flushes(prepared).items(): - commit_best_effort( - run_error, - lambda: self._flush_attachment( - queue, database, prepared.writes - ), - ) - clear_run_rows(plan.to_run) + # 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 _additional_flushes( diff --git a/tests/test_pipeline/test_job_attached_database_commit.py b/tests/test_pipeline/test_job_attached_database_commit.py index 9ff3b8ca6..1512f7fec 100644 --- a/tests/test_pipeline/test_job_attached_database_commit.py +++ b/tests/test_pipeline/test_job_attached_database_commit.py @@ -249,6 +249,49 @@ def on_run_end(self, run_id: str) -> None: 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_persistent_cache_hits_leave_the_unused_ephemeral_store_alone( From 0df136ea71472d7744c727843e767288d14929a3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 13:14:34 -0800 Subject: [PATCH 11/16] fix(pipeline): preserve attachment retries through interrupted runs --- docs/concepts/pipeline-job.md | 9 +- docs/dev/design_issues/ITL-1383-BL3.md | 4 +- src/orcapod/core/database_writes.py | 47 +++-- src/orcapod/pipeline/job.py | 55 ++++-- .../test_postgresql_connector_integration.py | 166 +++++++++++++++++- .../test_job_attached_database_commit.py | 78 ++++++++ 6 files changed, 323 insertions(+), 36 deletions(-) diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 4d966d5a0..e2493600a 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -349,9 +349,12 @@ 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 the job's own databases are committed, a database a job node writes to through -a separate attachment is flushed once, together with anything else pending in that -database object. Scoped views sharing its pending writes share that flush. +After committing its own databases, the job flushes each supported attachment that +accepted a new row from a node during the run. The flush publishes anything else +pending in that database object. Scoped views sharing pending writes share one flush. +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 diff --git a/docs/dev/design_issues/ITL-1383-BL3.md b/docs/dev/design_issues/ITL-1383-BL3.md index 210673e3b..6c7918ced 100644 --- a/docs/dev/design_issues/ITL-1383-BL3.md +++ b/docs/dev/design_issues/ITL-1383-BL3.md @@ -25,8 +25,10 @@ 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 a second handle makes previously pending logs durable, a duplicate-only replay -leaves the attachment's unrelated writes buffered. +in the same store schema leaves the attachment's unrelated writes buffered. Opaque protocol attachments use the existing commit sequence. Automatic attachment enrollment requires the ability to distinguish durable from pending diff --git a/src/orcapod/core/database_writes.py b/src/orcapod/core/database_writes.py index 83aca28b2..aa4993c5f 100644 --- a/src/orcapod/core/database_writes.py +++ b/src/orcapod/core/database_writes.py @@ -24,6 +24,8 @@ logger = logging.getLogger(__name__) +LogTable = tuple[str | None, tuple[str, ...]] + class WriteDatabase(Protocol): """The database operations needed at the node write sites.""" @@ -79,21 +81,23 @@ def __init__( *, shared_queue: Callable[[WriteDatabase], object | None], all_durable: Callable[ - [WriteDatabase, tuple[str, ...], Collection[bytes]], bool + [WriteDatabase, tuple[str, ...], Collection[bytes], str | None], bool ], + store_schema: Callable[[WriteDatabase, tuple[str, ...]], str | None], supports_enrollment: Callable[[WriteDatabase], bool], ) -> None: self._owned: tuple[WriteDatabase, ...] = owned self._shared_queue: Callable[[WriteDatabase], object | None] = shared_queue self._queues: dict[int, tuple[WriteDatabase, object | None]] = {} self._all_durable: Callable[ - [WriteDatabase, tuple[str, ...], Collection[bytes]], bool + [WriteDatabase, tuple[str, ...], Collection[bytes], str | None], bool ] = all_durable + self._store_schema = store_schema self._supports_enrollment = supports_enrollment self._covered: set[int] = {self.queue_id(database) for database in owned} - self._writes: dict[tuple[int, tuple[str, ...]], _Write] = {} + self._writes: dict[tuple[int, LogTable], _Write] = {} self._duplicate_logs: dict[ - tuple[int, tuple[str, ...]], tuple[WriteDatabase, set[bytes]] + tuple[int, LogTable], tuple[WriteDatabase, set[bytes]] ] = {} def _queue(self, database: WriteDatabase) -> object | None: @@ -159,15 +163,16 @@ def function_databases(self) -> dict[int, WriteDatabase]: if write.function } - def logs_to_replay(self, queue: int) -> dict[tuple[str, ...], set[bytes]] | None: + def logs_to_replay(self, queue: int) -> dict[LogTable, set[bytes]] | None: """Identify pending logs, or return None when the run wrote no logs here.""" - logs: dict[tuple[str, ...], set[bytes]] = {} - for (identity, full_path), write in self._writes.items(): + logs: dict[LogTable, set[bytes]] = {} + for (identity, table), write in self._writes.items(): if identity != queue or not write.log_ids: continue try: + schema, full_path = table path = full_path[len(write.database.base_path) :] - if self._all_durable(write.database, path, write.log_ids): + if self._all_durable(write.database, path, write.log_ids, schema): # The whole flush was owed even with this log already durable. return {} except Exception: @@ -177,25 +182,29 @@ def logs_to_replay(self, queue: int) -> dict[tuple[str, ...], set[bytes]] | None exc_info=True, ) return {} - logs[full_path] = write.log_ids + logs[table] = write.log_ids return logs or None def replayed_durable_logs( self, queue: int, - logs: dict[tuple[str, ...], set[bytes]], + logs: dict[LogTable, set[bytes]], ) -> bool: """A duplicate-only replay can find the failed logs now durable elsewhere.""" try: - for full_path, ids in logs.items(): - replay = self._duplicate_logs.get((queue, full_path)) + for table, ids in logs.items(): + replay = self._duplicate_logs.get((queue, table)) if replay is None: return False database, duplicates = replay + schema, full_path = table path = full_path[len(database.base_path) :] - if not ids <= duplicates or not self._all_durable(database, path, ids): + if not ids <= duplicates or not self._all_durable( + database, path, ids, schema + ): return False - except (ValueError, OrcapodDatabaseError): + except Exception: + logger.debug("Could not verify replayed log durability", exc_info=True) return False return bool(logs) @@ -214,10 +223,11 @@ def track( if not self._supports_enrollment(database): yield return - key = (self.queue_id(database), database.base_path + path) - if self.covers(key[0]): + queue = self.queue_id(database) + if self.covers(queue): yield return + key = (queue, (self._store_schema(database, path), database.base_path + path)) previous = self._writes.get(key) if previous is not None and function: yield @@ -267,7 +277,10 @@ def exclude_unpublished_result( self, database: WriteDatabase, path: tuple[str, ...] ) -> None: """Leave dry-run results queued when the table commit kept them there.""" - key = (self.queue_id(database), database.base_path + path) + queue = self.queue_id(database) + if self.covers(queue) or not self._supports_enrollment(database): + return + key = (queue, (self._store_schema(database, path), database.base_path + path)) write = self._writes.get(key) if ( write is not None diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 1f321548e..596532500 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -72,7 +72,7 @@ if TYPE_CHECKING: from pathlib import Path - from orcapod.core.database_writes import WriteDatabase + 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 @@ -136,8 +136,20 @@ def _shared_queue(database: WriteDatabase) -> object | None: return None +def _record_store_schema(database: WriteDatabase, path: tuple[str, ...]) -> str | None: + """Capture the schema used by a connector's pending record key.""" + backend = _backend(database) + if isinstance(backend, orcapod.databases.ConnectorArrowDatabase): + key = backend._get_record_key(path) # pyright: ignore[reportPrivateUsage] + return backend._schema_from_record_key(key) # pyright: ignore[reportPrivateUsage] + return None + + def _all_records_durable( - database: WriteDatabase, path: tuple[str, ...], ids: Collection[bytes] + database: WriteDatabase, + path: tuple[str, ...], + ids: Collection[bytes], + schema: str | None, ) -> bool: """Check committed IDs separately from buffered retries and duplicate upserts.""" backend = _backend(database) @@ -148,8 +160,6 @@ def _all_records_durable( key = backend._get_record_key(path) # pyright: ignore[reportPrivateUsage] return unique_ids.issubset(backend._committed_id_index(key)) # pyright: ignore[reportPrivateUsage] if isinstance(backend, orcapod.databases.ConnectorArrowDatabase): - key = backend._get_record_key(path) # pyright: ignore[reportPrivateUsage] - schema = backend._schema_from_record_key(key) # pyright: ignore[reportPrivateUsage] full_path = backend.base_path + path name = backend._path_to_table_name(full_path) # pyright: ignore[reportPrivateUsage] table = backend._find_committed_table( # pyright: ignore[reportPrivateUsage] @@ -159,9 +169,15 @@ def _all_records_durable( return False schema, name = table column = backend.RECORD_ID_COLUMN - batches = backend._connector.iter_batches( # pyright: ignore[reportPrivateUsage] - f'SELECT "{column}" FROM {sql_table_identifier(name, schema)}' - ) + connector = backend._connector # pyright: ignore[reportPrivateUsage] + query = f'SELECT "{column}" FROM {sql_table_identifier(name, schema)}' + if isinstance(connector, orcapod.databases.PostgreSQLConnector): + batches = connector.iter_batches( + f'{query} WHERE "{column}" = ANY(%s)', (list(unique_ids),) + ) + else: + # The generic connector protocol does not require SQL predicates. + batches = connector.iter_batches(query) for batch in batches: unique_ids.difference_update(cast("list[bytes]", batch[column].to_pylist())) if not unique_ids: @@ -218,7 +234,7 @@ class _AttachmentRetry: """A failed whole flush, with any pending logs that could make it redundant.""" database: ArrowDatabaseProtocol - logs: dict[tuple[str, ...], set[bytes]] + logs: dict[LogTable, set[bytes]] def _with_counter( @@ -1655,6 +1671,7 @@ def _prepare_run( (pipeline_db, result_db, *self._node_database_views, self._database), shared_queue=_shared_queue, all_durable=_all_records_durable, + store_schema=_record_store_schema, supports_enrollment=_supports_attachment_enrollment, ) # A database that commits a table by itself at batch_size: commit what it already @@ -1744,10 +1761,17 @@ def _executing( else () ), ) - for database in owned: - commit_best_effort( - run_error, lambda: self._flush_owned(database, prepared.writes) - ) + 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. @@ -1769,6 +1793,13 @@ def _executing( 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]": diff --git a/tests/test_databases/test_postgresql_connector_integration.py b/tests/test_databases/test_postgresql_connector_integration.py index 9e8006978..c427875c6 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,18 @@ 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.pipeline.observer import NoOpObserver +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, @@ -525,6 +534,157 @@ 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.parametrize("scenario", ["filtered", "read_error", "durable"]) +def test_postgresql_attachment_durability_probe( + connector: PostgreSQLConnector, + monkeypatch: pytest.MonkeyPatch, + scenario: str, +) -> None: + """Check only requested durable IDs, and tolerate a transient probe failure.""" + attached = ConnectorArrowDatabase(connector) + job = _attachment_job(attached) + queries: list[str] = [] + returned_ids: list[bytes] = [] + read = connector.iter_batches + + def observe_read( + query: str, params: Any = None, batch_size: int = 1000 + ) -> Iterator[pa.RecordBatch]: + if not query.startswith('SELECT "__record_id"'): + yield from read(query, params, batch_size) + return + queries.append(query) + if scenario == "read_error" and retries: + raise psycopg.OperationalError("temporary connector read failure") + for batch in read(query, params, batch_size): + returned_ids.extend(cast("list[bytes]", batch[0].to_pylist())) + yield batch + + def fail_flush() -> None: + raise OSError("temporary attachment flush failure") + + class FailRun(NoOpObserver): + def on_run_end(self, run_id: str) -> None: + raise RuntimeError("observer failed") + + retries = False + monkeypatch.setattr(connector, "iter_batches", observe_read) + 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() + records = attached.get_all_records(path, record_id_column="record_id") + assert records is not None + rows = records.drop(["record_id"]) + receipt_id = cast(bytes, records["record_id"][0].as_py()) + other = ConnectorArrowDatabase(connector) + other.add_record(path, b"historical", rows.slice(0, 1), flush=True) + if scenario == "durable": + other.add_record(path, receipt_id, rows, flush=True) + attached.add_record(("pending",), b"unrelated", pa.table({"value": [1]})) + retries = True + with pytest.raises(RuntimeError, match="observer failed"): + _ = job.run(observer=FailRun()) + assert queries and all(" WHERE " in query for query in queries) + assert returned_ids == ([receipt_id] if scenario == "durable" else []) + assert not other.table_exists(("pending",)) + committed = other.get_all_records(path) + assert committed is not None and committed.num_rows == 2 + + +@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/test_job_attached_database_commit.py b/tests/test_pipeline/test_job_attached_database_commit.py index 1512f7fec..4a822d9ca 100644 --- a/tests/test_pipeline/test_job_attached_database_commit.py +++ b/tests/test_pipeline/test_job_attached_database_commit.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio from pathlib import Path import deltalake @@ -10,6 +11,7 @@ from typing_extensions import override 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 @@ -292,6 +294,82 @@ def interrupt() -> None: 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( From b4f3b5e18cf55a0ea1bd16330481b36c799bc38c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 18:00:47 -0800 Subject: [PATCH 12/16] fix(pipeline): preserve attachment retry evidence and write errors --- docs/dev/design_issues/ITL-1383-BL3.md | 4 + src/orcapod/core/database_writes.py | 85 +++++++++++-- src/orcapod/pipeline/job.py | 19 ++- src/orcapod/side_effects.py | 3 +- .../test_job_attached_database_commit.py | 112 +++++++++++++++++- 5 files changed, 202 insertions(+), 21 deletions(-) diff --git a/docs/dev/design_issues/ITL-1383-BL3.md b/docs/dev/design_issues/ITL-1383-BL3.md index 6c7918ced..3bb715721 100644 --- a/docs/dev/design_issues/ITL-1383-BL3.md +++ b/docs/dev/design_issues/ITL-1383-BL3.md @@ -29,6 +29,10 @@ Cancellation and an interruption in the owned best-effort commit also retain attachment writes for the next committing run. If a second handle makes previously pending logs durable, a duplicate-only replay in the same store schema leaves the attachment's unrelated writes buffered. +This includes completion-tracked side-effect receipts. When a write fails after +queueing more rows for a table already tracked by the run, those pending IDs +also count toward the durability check. A failed pending-row lookup preserves +the original write error. Opaque protocol attachments use the existing commit sequence. Automatic attachment enrollment requires the ability to distinguish durable from pending diff --git a/src/orcapod/core/database_writes.py b/src/orcapod/core/database_writes.py index aa4993c5f..073e50824 100644 --- a/src/orcapod/core/database_writes.py +++ b/src/orcapod/core/database_writes.py @@ -85,7 +85,22 @@ def __init__( ], store_schema: Callable[[WriteDatabase, tuple[str, ...]], str | None], supports_enrollment: Callable[[WriteDatabase], bool], + retry_log_queues: Collection[int], ) -> None: + """Create a collector for one run. + + Args: + owned: Database views covered by the job's existing flush sequence. + shared_queue: Returns a view's queue, or None if it is unknown. + all_durable: Checks whether every ID is committed at a path and + schema. Buffered rows alone do not count. + store_schema: Returns the schema for a path, or None if the store + has no separate schema identity. + supports_enrollment: Checks whether the store can distinguish new + writes from retained or durable rows. + retry_log_queues: Queues with unfinished flushes that a replay can + retire once every remembered log ID is durable. + """ self._owned: tuple[WriteDatabase, ...] = owned self._shared_queue: Callable[[WriteDatabase], object | None] = shared_queue self._queues: dict[int, tuple[WriteDatabase, object | None]] = {} @@ -94,6 +109,7 @@ def __init__( ] = all_durable self._store_schema = store_schema self._supports_enrollment = supports_enrollment + self._retry_log_queues = retry_log_queues self._covered: set[int] = {self.queue_id(database) for database in owned} self._writes: dict[tuple[int, LogTable], _Write] = {} self._duplicate_logs: dict[ @@ -208,6 +224,26 @@ def replayed_durable_logs( return False return bool(logs) + def note_completion_hit( + self, database: WriteDatabase, path: tuple[str, ...], record_id: bytes + ) -> None: + """Remember a delivery replay for committed-only verification at flush time.""" + if not self._retry_log_queues or not self._supports_enrollment(database): + return + queue = self.queue_id(database) + if queue not in self._retry_log_queues: + return + try: + key = ( + queue, + (self._store_schema(database, path), database.base_path + path), + ) + except Exception: + # Without the schema, this hit cannot retire the outstanding retry. + logger.debug("Could not identify the replayed receipt table", exc_info=True) + return + self._duplicate_logs.setdefault(key, (database, set()))[1].add(record_id) + @contextmanager def track( self, @@ -251,32 +287,48 @@ def track( ) return - log_ids: set[bytes] = set() if function else set(record_ids) - if previous is not None: - yield - previous.log_ids.update(log_ids) - return try: yield except Exception: # A write can queue records and then fail an automatic table commit. - # Keep any such attachment eligible for the job's best-effort flush. + # Keep only confirmed pending IDs and preserve the original failure. + pending: list[bytes] = [] for row in record_ids: try: if database.pending_result(path, row) is not None: - if not self._covered_by_owned_wrapper(database, path, (row,)): - self._writes[key] = _Write(database, row, function, log_ids) - break + pending.append(row) except (ValueError, OrcapodDatabaseError): continue + except Exception: + logger.debug("Could not check for a pending write", exc_info=True) + if previous is not None: + previous.log_ids.update(pending) + elif pending: + try: + covered = self._covered_by_owned_wrapper(database, path, pending) + except Exception: + logger.debug( + "Could not check the pending write's queue", exc_info=True + ) + covered = False + if not covered: + self._writes[key] = _Write( + database, + pending[0], + function, + set() if function else set(pending), + ) raise - if not self._covered_by_owned_wrapper(database, path, record_ids): + log_ids: set[bytes] = set() if function else set(record_ids) + if previous is not None: + previous.log_ids.update(log_ids) + elif not self._covered_by_owned_wrapper(database, path, record_ids): self._writes[key] = _Write(database, record_ids[0], function, log_ids) def exclude_unpublished_result( self, database: WriteDatabase, path: tuple[str, ...] ) -> None: - """Leave dry-run results queued when the table commit kept them there.""" + """Keep an unpublished result from enrolling a queue on its own.""" queue = self.queue_id(database) if self.covers(queue) or not self._supports_enrollment(database): return @@ -319,8 +371,17 @@ def track_database_write( yield +def note_completion_hit( + database: WriteDatabase, path: tuple[str, ...], record_id: bytes +) -> None: + """Report a side-effect completion hit to the enclosing job run.""" + run = _run_writes.get() + if run is not None: + run.note_completion_hit(database, path, record_id) + + def exclude_unpublished_result(database: WriteDatabase, path: tuple[str, ...]) -> None: - """Keep a dry-run result queued when the job's store did not publish it.""" + """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/pipeline/job.py b/src/orcapod/pipeline/job.py index 8d119b53a..1a358c1ec 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -25,9 +25,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 PendingCommit +from orcapod.databases.utils import as_table_committing, sql_table_identifier from orcapod.errors import ( InconsistentSourceError, OrcapodDatabaseError, @@ -63,7 +63,7 @@ require_live_source_bindings, ) from orcapod.protocols import core_protocols as cp -from orcapod.databases.utils import as_table_committing, sql_table_identifier +from orcapod.side_effects import SideEffectJobNode, SideEffectNode from orcapod.types import NodeConfig from orcapod.utils.database_errors import ( commit_best_effort, @@ -74,7 +74,9 @@ from pathlib import Path from orcapod.core.database_writes import LogTable, WriteDatabase - from orcapod.core.nodes.source_node import _DeclaredForm # pyright: ignore[reportPrivateUsage] # shared binding transaction + 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 @@ -135,6 +137,11 @@ def _shared_queue(database: WriteDatabase) -> object | None: return probe.queue except (ValueError, OrcapodDatabaseError, NotImplementedError): return None + except Exception: + # Queue identity is optional. A forwarding connector can raise a driver + # error while resolving the schema, even when this job needs no writes. + logger.debug("Could not identify the database's pending queue", exc_info=True) + return None def _record_store_schema(database: WriteDatabase, path: tuple[str, ...]) -> str | None: @@ -1010,6 +1017,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 @@ -1682,6 +1690,11 @@ def _prepare_run( all_durable=_all_records_durable, store_schema=_record_store_schema, 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 diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 222d73d07..92ed7aa5d 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -38,7 +38,7 @@ StreamView, ) from orcapod.core.tracker import DEFAULT_TRACKER_MANAGER -from orcapod.core.database_writes import track_database_write +from orcapod.core.database_writes import note_completion_hit, track_database_write from orcapod.errors import ( OrcapodDatabaseError, OrcapodDatabaseReadError, @@ -464,6 +464,7 @@ def _execute_side_effect_row( exc.add_context(node_label=pod_name, tag=tag.as_dict()) raise if prior is not None: + note_completion_hit(pipeline_database, table_path, entry_id) return (tag, data) # already completed — re-emit without re-delivery # 3. Build InvocationContext (invocation_hash derived lazily via format_id()). diff --git a/tests/test_pipeline/test_job_attached_database_commit.py b/tests/test_pipeline/test_job_attached_database_commit.py index 4a822d9ca..a2e0dde4f 100644 --- a/tests/test_pipeline/test_job_attached_database_commit.py +++ b/tests/test_pipeline/test_job_attached_database_commit.py @@ -4,8 +4,10 @@ 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 @@ -29,7 +31,7 @@ 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 +from orcapod.side_effects import SideEffectPod, SideEffectPodConfig from orcapod.sources import ArrowTableSource from orcapod.types import CacheMode, NodeConfig @@ -939,6 +941,109 @@ def fail() -> None: 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_ignores_transient_opaque_queue_probe_failure( + 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") + + def fail_guard(*args: object) -> None: + raise psycopg.OperationalError("could not read the current schema") + + monkeypatch.setattr(ConnectorArrowDatabase, "guard_record", fail_guard) + await _run(job, runner, load_only=True) + + @pytest.mark.asyncio @pytest.mark.parametrize("runner", JOB_RUNNERS) @pytest.mark.parametrize("backend", ["delta", "connector"]) @@ -972,10 +1077,7 @@ def flush() -> None: original() monkeypatch.setattr(attachment, "flush", flush) - try: - await _run(job, runner) - except OrcapodDatabaseWriteError: - pass # The reviewed head enrolled the forwarding wrapper. + await _run(job, runner) other.nodes["grouped"].run() (log_path,) = second.list_table_paths() attachment.refresh_table(log_path) From 2a5e9e42dda7642908014c4695d4aa5491428fe0 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 19:18:04 -0800 Subject: [PATCH 13/16] fix(pipeline): remove receipt history reads from delivery Revert the receipt enrollment lookup introduced by 78da630c and expanded by b9e3200b. Keep the ID-only checks for outstanding attachment recovery. --- changelog.d/ITL-1383.md | 2 +- docs/concepts/pipeline-job.md | 6 +- docs/dev/design_issues/ITL-1383-BL3.md | 3 +- src/orcapod/core/database_writes.py | 38 +++++--- src/orcapod/side_effects.py | 4 +- .../test_postgresql_connector_integration.py | 92 +++++++++++++++++++ 6 files changed, 129 insertions(+), 16 deletions(-) diff --git a/changelog.d/ITL-1383.md b/changelog.d/ITL-1383.md index a2797922d..dab30076f 100644 --- a/changelog.d/ITL-1383.md +++ b/changelog.d/ITL-1383.md @@ -1,6 +1,6 @@ ### 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. The job retries a failed attachment flush even after rebinding its sources or node attachments. Duplicate-only replays leave unrelated pending rows alone when the replayed rows are already durable. +- 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. The job retries a failed attachment flush even after rebinding its sources or node attachments. Duplicate-only replays of cached rows or completed deliveries leave unrelated pending rows alone when the replayed rows are already durable. ### Known limitations diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index f6b471d46..be0509578 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -369,8 +369,10 @@ it with `job.bind(sources=...)`. See [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 -accepted a new row from a node during the run. The flush publishes anything else -pending in that database object. Scoped views sharing pending writes share one flush. +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. 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. diff --git a/docs/dev/design_issues/ITL-1383-BL3.md b/docs/dev/design_issues/ITL-1383-BL3.md index 3bb715721..db7413023 100644 --- a/docs/dev/design_issues/ITL-1383-BL3.md +++ b/docs/dev/design_issues/ITL-1383-BL3.md @@ -17,7 +17,8 @@ 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 duplicates leave the attachment alone. An +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. diff --git a/src/orcapod/core/database_writes.py b/src/orcapod/core/database_writes.py index 073e50824..3f3b1da1b 100644 --- a/src/orcapod/core/database_writes.py +++ b/src/orcapod/core/database_writes.py @@ -252,6 +252,7 @@ def track( record_ids: Sequence[bytes], *, function: bool, + receipt: bool, ) -> Iterator[None]: """Enroll a write if it has a record the database did not already hold.""" # Opaque stores can expose a pending token even for a durable row and @@ -268,16 +269,30 @@ def track( if previous is not None and function: yield return - # The native add methods accept every previously absent ID on success, - # even if the row reaches the auto-commit threshold during the call. - # A connector can return both durable and buffered copies of an ID. - id_column = "__record_id" - rows = database.get_records_by_ids(path, set(record_ids), id_column) - existing: set[bytes] = ( - set() - if rows is None - else set(cast("list[bytes]", rows[id_column].to_pylist())) - ) + if receipt: + # Delivery already ran. Keep its existing insert path free of + # history reads. A buffered retry can still supply replay evidence. + existing: set[bytes] = set() + if queue in self._retry_log_queues: + try: + existing = { + row + for row in record_ids + if database.pending_result(path, row) is not None + } + except Exception: + logger.debug( + "Could not check for a buffered receipt", exc_info=True + ) + else: + # A connector can return both durable and buffered copies of an ID. + id_column = "__record_id" + rows = database.get_records_by_ids(path, set(record_ids), id_column) + existing = ( + set() + if rows is None + else set(cast("list[bytes]", rows[id_column].to_pylist())) + ) record_ids = [row for row in record_ids if row not in existing] if not record_ids: yield @@ -361,13 +376,14 @@ def track_database_write( record_ids: Sequence[bytes], *, function: bool = False, + receipt: 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 record_ids or not database.stores_records: yield return - with run.track(database, path, record_ids, function=function): + with run.track(database, path, record_ids, function=function, receipt=receipt): yield diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index 586657c33..dba702135 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -566,7 +566,9 @@ def _write_invocation_row( schema=_invocation_log_schema(), ) try: - with track_database_write(pipeline_database, table_path, (entry_id,)): + with track_database_write( + pipeline_database, table_path, (entry_id,), receipt=True + ): pipeline_database.add_record( table_path, entry_id, diff --git a/tests/test_databases/test_postgresql_connector_integration.py b/tests/test_databases/test_postgresql_connector_integration.py index 2a13c9446..4894c4e64 100644 --- a/tests/test_databases/test_postgresql_connector_integration.py +++ b/tests/test_databases/test_postgresql_connector_integration.py @@ -56,6 +56,7 @@ TIE_ORDERS, check_result_lookup_timestamp_tie, ) +from tests.test_pipeline.test_job_attached_database_commit import JOB_RUNNERS, _run # --------------------------------------------------------------------------- @@ -555,6 +556,97 @@ def deliver(ctx: InvocationContext, value: int) -> None: 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.parametrize("scenario", ["filtered", "read_error", "durable"]) def test_postgresql_attachment_durability_probe( From 9cbb79ea5380a4cb28b70e0652289d717e6621b8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 20:14:15 -0800 Subject: [PATCH 14/16] fix(pipeline): preserve store reads during attachment tracking --- changelog.d/ITL-1383.md | 2 +- docs/dev/design_issues/ITL-1383-BL3.md | 10 +- src/orcapod/core/database_writes.py | 334 +++----- src/orcapod/core/nodes/function_node.py | 2 +- src/orcapod/core/nodes/operator_node.py | 2 +- src/orcapod/core/result_cache.py | 1 - src/orcapod/databases/_pending_commits.py | 64 +- .../databases/connector_arrow_database.py | 69 +- src/orcapod/databases/delta_lake_databases.py | 41 +- src/orcapod/databases/in_memory_databases.py | 37 +- src/orcapod/databases/postgresql_connector.py | 16 + src/orcapod/databases/sqlite_connector.py | 19 + src/orcapod/pipeline/job.py | 100 +-- src/orcapod/side_effects.py | 10 +- .../test_postgresql_connector_integration.py | 29 +- .../fixtures/attachment_store_io.json | 796 ++++++++++++++++++ .../test_pipeline/test_attachment_store_io.py | 500 +++++++++++ .../test_mixed_function_commits.py | 10 + 18 files changed, 1660 insertions(+), 382 deletions(-) create mode 100644 tests/test_pipeline/fixtures/attachment_store_io.json create mode 100644 tests/test_pipeline/test_attachment_store_io.py diff --git a/changelog.d/ITL-1383.md b/changelog.d/ITL-1383.md index dab30076f..ceb9dda3c 100644 --- a/changelog.d/ITL-1383.md +++ b/changelog.d/ITL-1383.md @@ -1,6 +1,6 @@ ### 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. The job retries a failed attachment flush even after rebinding its sources or node attachments. Duplicate-only replays of cached rows or completed deliveries leave unrelated pending rows alone when the replayed rows are already durable. +- 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. The job retries a failed attachment flush even after rebinding its sources or node attachments. Duplicate-only replays of cached rows or completed deliveries leave unrelated pending rows alone when the store can verify that the replayed rows are durable. Delivery and forwarding load-only runs keep their existing database reads. ### Known limitations diff --git a/docs/dev/design_issues/ITL-1383-BL3.md b/docs/dev/design_issues/ITL-1383-BL3.md index db7413023..f872ea56e 100644 --- a/docs/dev/design_issues/ITL-1383-BL3.md +++ b/docs/dev/design_issues/ITL-1383-BL3.md @@ -30,10 +30,12 @@ Cancellation and an interruption in the owned best-effort commit also retain attachment writes for the next committing run. If a second handle makes previously pending logs durable, a duplicate-only replay in the same store schema leaves the attachment's unrelated writes buffered. -This includes completion-tracked side-effect receipts. When a write fails after -queueing more rows for a table already tracked by the run, those pending IDs -also count toward the durability check. A failed pending-row lookup preserves -the original write error. +This includes completion-tracked side-effect receipts. 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. A connector can use a bounded +primary-key lookup to decide whether already-durable log rows justify a whole flush. Opaque protocol attachments use the existing commit sequence. Automatic attachment enrollment requires the ability to distinguish durable from pending diff --git a/src/orcapod/core/database_writes.py b/src/orcapod/core/database_writes.py index 3f3b1da1b..49add11d5 100644 --- a/src/orcapod/core/database_writes.py +++ b/src/orcapod/core/database_writes.py @@ -5,26 +5,19 @@ import logging from contextlib import contextmanager from contextvars import ContextVar -from dataclasses import dataclass -from typing import TYPE_CHECKING, Protocol, cast +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Protocol -from orcapod.errors import OrcapodDatabaseError +from orcapod.databases._pending_commits import observe_records if TYPE_CHECKING: - from collections.abc import ( - Callable, - Collection, - Iterator, - Sequence, - ) - from contextlib import AbstractContextManager + from collections.abc import Callable, Collection, Iterator, Set - import pyarrow as pa - from orcapod.databases._pending_commits import PendingCommit + from orcapod.databases._pending_commits import PendingCommits, VerifyIDs logger = logging.getLogger(__name__) -LogTable = tuple[str | None, tuple[str, ...]] +LogTable = tuple[str, tuple[str, ...]] class WriteDatabase(Protocol): @@ -40,36 +33,24 @@ def stores_records(self) -> bool: """Return whether this database keeps the records it receives.""" ... - def get_records_by_ids( - self, - record_path: tuple[str, ...], - record_ids: Collection[bytes], - record_id_column: str | None = None, - ) -> pa.Table | None: - """Look up the given rows, including buffered rows.""" - ... - - def pending_result( - self, record_path: tuple[str, ...], record_id: bytes - ) -> PendingCommit | None: - """Return a commit token for a buffered row, or None for a durable row.""" - ... - - def guard_record( - self, record_path: tuple[str, ...], record_id: bytes, dependency: PendingCommit - ) -> AbstractContextManager[None]: - """Register a record's dependency on a pending commit.""" - ... - @dataclass class _Write: """One write site that still needs its database's final whole flush.""" database: WriteDatabase - sample_id: bytes + pending: PendingCommits + ids: set[bytes] function: bool - log_ids: set[bytes] + + +@dataclass +class _Replay: + """Evidence of duplicate rows observed through the existing run.""" + + durable: set[bytes] = field(default_factory=set) + candidates: set[bytes] = field(default_factory=set) + verify: VerifyIDs | None = None class DatabaseWrites: @@ -79,44 +60,20 @@ def __init__( self, owned: tuple[WriteDatabase, ...], *, - shared_queue: Callable[[WriteDatabase], object | None], - all_durable: Callable[ - [WriteDatabase, tuple[str, ...], Collection[bytes], str | None], bool - ], - store_schema: Callable[[WriteDatabase, tuple[str, ...]], str | None], + shared_queue: Callable[[WriteDatabase], PendingCommits | None], supports_enrollment: Callable[[WriteDatabase], bool], retry_log_queues: Collection[int], ) -> None: - """Create a collector for one run. - - Args: - owned: Database views covered by the job's existing flush sequence. - shared_queue: Returns a view's queue, or None if it is unknown. - all_durable: Checks whether every ID is committed at a path and - schema. Buffered rows alone do not count. - store_schema: Returns the schema for a path, or None if the store - has no separate schema identity. - supports_enrollment: Checks whether the store can distinguish new - writes from retained or durable rows. - retry_log_queues: Queues with unfinished flushes that a replay can - retire once every remembered log ID is durable. - """ - self._owned: tuple[WriteDatabase, ...] = owned - self._shared_queue: Callable[[WriteDatabase], object | None] = shared_queue - self._queues: dict[int, tuple[WriteDatabase, object | None]] = {} - self._all_durable: Callable[ - [WriteDatabase, tuple[str, ...], Collection[bytes], str | None], bool - ] = all_durable - self._store_schema = store_schema + """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: set[int] = {self.queue_id(database) for database in owned} + self._covered = {self.queue_id(database) for database in owned} self._writes: dict[tuple[int, LogTable], _Write] = {} - self._duplicate_logs: dict[ - tuple[int, LogTable], tuple[WriteDatabase, set[bytes]] - ] = {} + self._duplicate_logs: dict[tuple[int, LogTable], _Replay] = {} - def _queue(self, database: WriteDatabase) -> object | None: + 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: @@ -132,38 +89,6 @@ def covers(self, queue: int) -> bool: """Return whether the job's existing flush sequence covers this queue.""" return queue in self._covered - def _covered_by_owned_wrapper( - self, - database: WriteDatabase, - path: tuple[str, ...], - rows: Sequence[bytes], - ) -> bool: - """Recognize aliases of an opaque job store by their shared commit token.""" - full_path = database.base_path + path - opaque = self._queue(database) is None - candidates = [ - owned - for owned in self._owned - if (opaque or self._queue(owned) is None) - and full_path[: len(owned.base_path)] == owned.base_path - ] - if not candidates: - return False - for row in rows: - token = database.pending_result(path, row) - if token is None: - continue - for owned in candidates: - relative = full_path[len(owned.base_path) :] - try: - if owned.pending_result(relative, row) is token: - return True - except (ValueError, OrcapodDatabaseError): - # An independent store has no such pending record. - continue - break # A pending row is enough to check where the table is queued. - return False - def databases(self) -> dict[int, WriteDatabase]: """Return one view per enrolled store in write order.""" result: dict[int, WriteDatabase] = {} @@ -180,25 +105,16 @@ def function_databases(self) -> dict[int, WriteDatabase]: } def logs_to_replay(self, queue: int) -> dict[LogTable, set[bytes]] | None: - """Identify pending logs, or return None when the run wrote no logs here.""" + """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 not write.log_ids: + if identity != queue or write.function: continue - try: - schema, full_path = table - path = full_path[len(write.database.base_path) :] - if self._all_durable(write.database, path, write.log_ids, schema): - # The whole flush was owed even with this log already durable. - return {} - except Exception: - # Preserve the original flush failure if the table cannot be read. - logger.debug( - "Could not check log durability after a flush failure", - exc_info=True, - ) + 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.log_ids + logs[table] = write.ids return logs or None def replayed_durable_logs( @@ -212,11 +128,11 @@ def replayed_durable_logs( replay = self._duplicate_logs.get((queue, table)) if replay is None: return False - database, duplicates = replay - schema, full_path = table - path = full_path[len(database.base_path) :] - if not ids <= duplicates or not self._all_durable( - database, path, ids, schema + remaining = ids - replay.durable + if remaining and ( + not remaining <= replay.candidates + or replay.verify is None + or not replay.verify(remaining) ): return False except Exception: @@ -224,136 +140,79 @@ def replayed_durable_logs( return False return bool(logs) - def note_completion_hit( - self, database: WriteDatabase, path: tuple[str, ...], record_id: bytes - ) -> None: - """Remember a delivery replay for committed-only verification at flush time.""" - if not self._retry_log_queues or not self._supports_enrollment(database): - return - queue = self.queue_id(database) - if queue not in self._retry_log_queues: - return - try: - key = ( - queue, - (self._store_schema(database, path), database.base_path + path), - ) - except Exception: - # Without the schema, this hit cannot retire the outstanding retry. - logger.debug("Could not identify the replayed receipt table", exc_info=True) - return - self._duplicate_logs.setdefault(key, (database, set()))[1].add(record_id) - @contextmanager def track( self, database: WriteDatabase, path: tuple[str, ...], - record_ids: Sequence[bytes], *, - function: bool, - receipt: bool, + function: bool = False, + receipt: bool = False, + completion: bool = False, ) -> Iterator[None]: - """Enroll a write if it has a record the database did not already hold.""" - # Opaque stores can expose a pending token even for a durable row and - # their writes return no status. Keep their existing commit behavior. + """Track the outcome of the existing native store operation.""" if not self._supports_enrollment(database): yield return - queue = self.queue_id(database) - if self.covers(queue): + pending = self._queue(database) + queue = id(pending) + if pending is None or self.covers(queue): yield return - key = (queue, (self._store_schema(database, path), database.base_path + path)) - previous = self._writes.get(key) - if previous is not None and function: + retry = queue in self._retry_log_queues + if completion and not retry: yield return - if receipt: - # Delivery already ran. Keep its existing insert path free of - # history reads. A buffered retry can still supply replay evidence. - existing: set[bytes] = set() - if queue in self._retry_log_queues: - try: - existing = { - row - for row in record_ids - if database.pending_result(path, row) is not None - } - except Exception: - logger.debug( - "Could not check for a buffered receipt", exc_info=True - ) - else: - # A connector can return both durable and buffered copies of an ID. - id_column = "__record_id" - rows = database.get_records_by_ids(path, set(record_ids), id_column) - existing = ( - set() - if rows is None - else set(cast("list[bytes]", rows[id_column].to_pylist())) - ) - record_ids = [row for row in record_ids if row not in existing] - if not record_ids: - yield - if not function: - self._duplicate_logs.setdefault(key, (database, set()))[1].update( - existing - ) - return - try: - yield - except Exception: - # A write can queue records and then fail an automatic table commit. - # Keep only confirmed pending IDs and preserve the original failure. - pending: list[bytes] = [] - for row in record_ids: - try: - if database.pending_result(path, row) is not None: - pending.append(row) - except (ValueError, OrcapodDatabaseError): - continue - except Exception: - logger.debug("Could not check for a pending write", exc_info=True) - if previous is not None: - previous.log_ids.update(pending) - elif pending: - try: - covered = self._covered_by_owned_wrapper(database, path, pending) - except Exception: - logger.debug( - "Could not check the pending write's queue", exc_info=True - ) - covered = False - if not covered: - self._writes[key] = _Write( - database, - pending[0], - function, - set() if function else set(pending), + def record( + key: str, + added: set[bytes], + duplicates: set[bytes], + durable: Set[bytes], + verify: VerifyIDs | None, + ) -> None: + table = key, database.base_path + path + if added: + if verify is not None and not (function or receipt or completion): + # Connectors deduplicate committed IDs in the upsert. Check an + # attached operator batch by ID before letting it flush unrelated + # pending rows. Receipts already followed the delivery path. + try: + if verify(added): + durable = durable | added + added = set() + except Exception: + logger.debug("Could not verify operator log IDs", exc_info=True) + if added: + write = self._writes.setdefault( + (queue, table), _Write(database, pending, set(), function) ) - raise - log_ids: set[bytes] = set() if function else set(record_ids) - if previous is not None: - previous.log_ids.update(log_ids) - elif not self._covered_by_owned_wrapper(database, path, record_ids): - self._writes[key] = _Write(database, record_ids[0], function, log_ids) + write.ids.update(added) + if retry and not function and (durable or (duplicates and verify)): + replay = self._duplicate_logs.setdefault((queue, table), _Replay()) + replay.durable.update(durable) + if verify is not None: + replay.candidates.update(duplicates) + replay.verify = verify + + 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) - if self.covers(queue) or not self._supports_enrollment(database): - return - key = (queue, (self._store_schema(database, path), database.base_path + path)) - write = self._writes.get(key) - if ( - write is not None - and database.pending_result(path, write.sample_id) is not None - ): - del self._writes[key] + 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) @@ -373,27 +232,30 @@ def collect_database_writes(writes: DatabaseWrites) -> Iterator[None]: def track_database_write( database: WriteDatabase, path: tuple[str, ...], - record_ids: Sequence[bytes], *, function: bool = False, receipt: 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 record_ids or not database.stores_records: + if run is None or not database.stores_records: yield return - with run.track(database, path, record_ids, function=function, receipt=receipt): + with run.track(database, path, function=function, receipt=receipt): yield -def note_completion_hit( - database: WriteDatabase, path: tuple[str, ...], record_id: bytes -) -> None: - """Report a side-effect completion hit to the enclosing job run.""" +@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 not None: - run.note_completion_hit(database, path, record_id) + if run is None: + yield + return + with run.track(database, path, completion=True): + yield def exclude_unpublished_result(database: WriteDatabase, path: tuple[str, ...]) -> None: diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index e7ab7f99b..64c476620 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -2523,7 +2523,7 @@ def _write_pipeline_record( with ( database.guard_table_schema(path, check), result_guard, - track_database_write(database, path, (row_key,), function=True), + track_database_write(database, path, function=True), ): database.add_record(path, row_key, record, skip_duplicates=True) diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 8db6bc9ee..98cdc7273 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -1574,7 +1574,7 @@ def _store_output_stream(self, stream: StreamProtocol) -> None: # it names the generation of hashing that produced them and is not hashed. path = self._stored_table_path try: - with track_database_write(pipeline_database, path, record_hashes): + with track_database_write(pipeline_database, path): pipeline_database.add_records( path, with_data_context( diff --git a/src/orcapod/core/result_cache.py b/src/orcapod/core/result_cache.py index f13a12f06..b4bfe48d4 100644 --- a/src/orcapod/core/result_cache.py +++ b/src/orcapod/core/result_cache.py @@ -544,7 +544,6 @@ def store( with track_database_write( self._result_database, path, - (result_id,), function=True, ): self._result_database.add_record( diff --git a/src/orcapod/databases/_pending_commits.py b/src/orcapod/databases/_pending_commits.py index a3891705f..74200d534 100644 --- a/src/orcapod/databases/_pending_commits.py +++ b/src/orcapod/databases/_pending_commits.py @@ -2,8 +2,9 @@ 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 import pyarrow as pa @@ -63,6 +64,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) @@ -153,3 +158,60 @@ 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 +) +VerifyIDs = Callable[[set[bytes]], bool] +RecordObserver = Callable[ + [str, set[bytes], set[bytes], Set[bytes], VerifyIDs | None], None +] + +_record_observer: ContextVar[RecordObserver | None] = ContextVar( + "_record_observer", default=None +) + + +@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], + duplicates: set[bytes], + durable: Set[bytes] = frozenset(), + verify: VerifyIDs | None = None, +) -> None: + """Report accepted and duplicate IDs using the operation's resolved table key.""" + observer = _record_observer.get() + if observer is not None: + observer(key, added, duplicates, durable, verify) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 267caf622..99987fbff 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -21,13 +21,19 @@ import re from collections import defaultdict from collections.abc import Callable, Collection, Mapping +from functools import partial from contextlib import AbstractContextManager, nullcontext from typing import Any, cast 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._sql_store import ( SQLStoreConnector, require_store_table_owner, @@ -607,10 +613,13 @@ def add_records( record_key = self._get_record_key(record_path) pending_owner_key: tuple[str, str] | None = None + committed_table = None if self._sql_store is not None: schema = self._schema_from_record_key(record_key) assert schema is not None - _ = self._find_committed_table(table_name, full_path, schema=schema) + committed_table = self._find_committed_table( + table_name, full_path, schema=schema + ) pending_owner_key = (schema, table_name) queued = self._pending_table_owners.get(pending_owner_key) if queued is not None and queued[0] != record_key: @@ -646,6 +655,9 @@ def add_records( ) records = records.filter(mask) if records.num_rows == 0: + self._report_stored_record_outcome( + record_key, committed_table, added=set(), duplicates=input_ids + ) return # Mark this pending slot so flush() uses skip_existing=True. self._pending_skip_existing[record_key] = True @@ -671,8 +683,13 @@ 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._report_stored_record_outcome( + record_key, + committed_table, + added=added, + duplicates=input_ids - added, ) if flush: @@ -806,6 +823,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": @@ -1000,6 +1018,36 @@ def _fmt(cols: Mapping[str, pa.DataType]) -> str: schema=schema, ) + def _report_stored_record_outcome( + self, + record_key: str, + committed_table: tuple[str | None, str] | None, + *, + added: set[bytes], + duplicates: set[bytes], + ) -> None: + """Use the already verified relation for optional committed-ID checks.""" + lookup = getattr(self._connector, "_read_record_ids", None) + if self._sql_store is None and lookup is not None: + # Connectors without an ID predicate must never scan for enrollment. + full_path = self._record_path_from_key(record_key) + committed_table = (None, self._path_to_table_name(full_path)) + verify = ( + partial(self._all_ids_committed, lookup, committed_table) + if lookup is not None and committed_table is not None + else None + ) + report_records(record_key, added=added, duplicates=duplicates, verify=verify) + + @staticmethod + def _all_ids_committed( + lookup: Callable[[tuple[str | None, str], set[bytes]], set[bytes]], + table: tuple[str | None, str], + ids: set[bytes], + ) -> bool: + """Require every ID while fetching at most one key per requested record.""" + return ids <= lookup(table, ids) + # ── Read methods ────────────────────────────────────────────────────────── def get_record_by_id( @@ -1020,11 +1068,15 @@ 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 ) + self._report_stored_record_outcome( + record_key, table, added=set(), duplicates={record_id} + ) return self._handle_record_id_column(filtered, record_id_column) # Check committed @@ -1034,6 +1086,13 @@ 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(), + duplicates={record_id}, + 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..e07c75eb5 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,21 @@ 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(), + duplicates=set(), + durable=durable, + ) logger.debug("All records were duplicates, nothing to insert") return None else: @@ -3041,7 +3053,13 @@ 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) + report_records( + self._get_record_key(record_path), + added=added, + duplicates=set(), + 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(), duplicates=set(), durable={record_id}) return self._handle_record_id_column(result, record_id_column) def get_records_by_ids( @@ -4424,6 +4446,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..eee333f60 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,19 @@ 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(), duplicates=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 +346,9 @@ 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) + report_records(record_key, added=added, duplicates=set(), durable=durable) if flush: self.flush() @@ -471,6 +484,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 +632,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(), duplicates=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..3f5ca117c 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -762,6 +762,22 @@ def get_column_info( # ── Read ────────────────────────────────────────────────────────────────── + def _read_record_ids( + self, table: tuple[str | None, str], ids: set[bytes] + ) -> set[bytes]: + """Read only the requested primary keys from a verified store table.""" + schema, name = table + target = sql_table_identifier(name, schema).replace("%", "%%") + query = f'SELECT "__record_id" FROM {target} WHERE "__record_id" = ANY(%s)' + with self._lock: + self._require_open() + dsn = self._dsn + # A separate connection sees committed keys even when the caller's + # connection already has an open transaction. + with psycopg.connect(dsn, autocommit=True) as conn, conn.cursor() as cur: + _ = cur.execute(query, (list(ids),)) # pyright: ignore[reportArgumentType] # the identifier is quoted + return {cast(bytes, row[0]) for row in cur.fetchall()} + def iter_batches( self, query: str, diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index 684de8bb7..f5c935545 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -466,6 +466,25 @@ def _get_column_info( # ── Read ────────────────────────────────────────────────────────────────── + def _read_record_ids( + self, table: tuple[str | None, str], ids: set[bytes] + ) -> set[bytes]: + """Read only the requested primary keys from a verified store table.""" + schema, name = table + target = sql_table_identifier(name, schema) + keys = tuple(ids) + found: set[bytes] = set() + with self._lock: + conn = self._require_open() + if conn.in_transaction: + return found # This connection could see an uncommitted row. + for index in range(0, len(keys), 500): + chunk = keys[index : index + 500] + placeholders = ", ".join("?" for _ in chunk) + query = f'SELECT "__record_id" FROM {target} WHERE "__record_id" IN ({placeholders})' + found.update(cast(bytes, row[0]) for row in conn.execute(query, chunk)) + return found + def iter_batches( self, query: str, diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 7569b7bba..bafd40c99 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -7,13 +7,12 @@ import logging import sys import uuid -from collections.abc import Collection, Iterable, Iterator, Sequence +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 -from typing_extensions import override import orcapod from orcapod.core.database_writes import DatabaseWrites, collect_database_writes @@ -26,8 +25,8 @@ from orcapod.core.sources.derived_source import DerivedSource from orcapod.core.streams.base import StreamBase from orcapod.core.tracker import AutoRegisteringContextBasedTracker -from orcapod.databases._pending_commits import PendingCommit -from orcapod.databases.utils import as_table_committing, sql_table_identifier +from orcapod.databases._pending_commits import observe_queue +from orcapod.databases.utils import as_table_committing from orcapod.errors import ( InconsistentSourceError, OrcapodDatabaseError, @@ -115,88 +114,11 @@ def _supports_attachment_enrollment(database: WriteDatabase) -> bool: ) -class _QueueProbe(PendingCommit): - """Capture the queue that registers a dependency through a forwarding view.""" - - queue: PendingCommits | None = None - - @override - def add_dependent(self, queue: PendingCommits, key: str, record_id: bytes) -> None: - """Identify the queue without retaining any dependent records.""" - self.queue = queue - - -def _shared_queue(database: WriteDatabase) -> object | None: - """Identify scoped views by their actual pending queue.""" - backend = _backend(database) - queue = getattr(backend, "_pending_commits", None) - if queue is not None or not database.stores_records: - return queue - - # A protocol wrapper can forward guards without exposing its backend. Use a - # fresh table and id with no insert, so exiting the guard removes it. - probe = _QueueProbe() - nonce = uuid.uuid4() - try: - with database.guard_record((f"queue_probe_{nonce.hex}",), nonce.bytes, probe): - return probe.queue - except (ValueError, OrcapodDatabaseError, NotImplementedError): - return None - except Exception: - # Queue identity is optional. A forwarding connector can raise a driver - # error while resolving the schema, even when this job needs no writes. - logger.debug("Could not identify the database's pending queue", exc_info=True) - return None - - -def _record_store_schema(database: WriteDatabase, path: tuple[str, ...]) -> str | None: - """Capture the schema used by a connector's pending record key.""" - backend = _backend(database) - if isinstance(backend, orcapod.databases.ConnectorArrowDatabase): - key = backend._get_record_key(path) # pyright: ignore[reportPrivateUsage] - return backend._schema_from_record_key(key) # pyright: ignore[reportPrivateUsage] - return None - - -def _all_records_durable( - database: WriteDatabase, - path: tuple[str, ...], - ids: Collection[bytes], - schema: str | None, -) -> bool: - """Check committed IDs separately from buffered retries and duplicate upserts.""" - backend = _backend(database) - unique_ids = set(ids) - if isinstance(backend, orcapod.databases.DeltaTableDatabase): - return unique_ids.issubset(backend._stored_ids(path)) # pyright: ignore[reportPrivateUsage] - if isinstance(backend, orcapod.databases.InMemoryArrowDatabase): - key = backend._get_record_key(path) # pyright: ignore[reportPrivateUsage] - return unique_ids.issubset(backend._committed_id_index(key)) # pyright: ignore[reportPrivateUsage] - if isinstance(backend, orcapod.databases.ConnectorArrowDatabase): - full_path = backend.base_path + path - name = backend._path_to_table_name(full_path) # pyright: ignore[reportPrivateUsage] - table = backend._find_committed_table( # pyright: ignore[reportPrivateUsage] - name, full_path, schema=schema - ) - if table is None: - return False - schema, name = table - column = backend.RECORD_ID_COLUMN - connector = backend._connector # pyright: ignore[reportPrivateUsage] - query = f'SELECT "{column}" FROM {sql_table_identifier(name, schema)}' - if isinstance(connector, orcapod.databases.PostgreSQLConnector): - batches = connector.iter_batches( - f'{query} WHERE "{column}" = ANY(%s)', (list(unique_ids),) - ) - else: - # The generic connector protocol does not require SQL predicates. - batches = connector.iter_batches(query) - for batch in batches: - unique_ids.difference_update(cast("list[bytes]", batch[column].to_pylist())) - if not unique_ids: - return True - return False - return False +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): @@ -1737,10 +1659,10 @@ def _prepare_run( # 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), + (pipeline_db, result_db, *self._node_database_views, self._database) + if plan.to_run and not load_only + else (), shared_queue=_shared_queue, - all_durable=_all_records_durable, - store_schema=_record_store_schema, supports_enrollment=_supports_attachment_enrollment, retry_log_queues={ queue diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index dba702135..be7b2297c 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -39,7 +39,7 @@ ) from orcapod.core.provisional_pods import warn_provisional_pod from orcapod.core.tracker import DEFAULT_TRACKER_MANAGER -from orcapod.core.database_writes import note_completion_hit, track_database_write +from orcapod.core.database_writes import track_completion_lookup, track_database_write from orcapod.errors import ( OrcapodDatabaseError, OrcapodDatabaseReadError, @@ -462,13 +462,13 @@ 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()) raise if prior is not None: - note_completion_hit(pipeline_database, table_path, entry_id) return (tag, data) # already completed — re-emit without re-delivery # 3. Build InvocationContext (invocation_hash derived lazily via format_id()). @@ -566,9 +566,7 @@ def _write_invocation_row( schema=_invocation_log_schema(), ) try: - with track_database_write( - pipeline_database, table_path, (entry_id,), receipt=True - ): + with track_database_write(pipeline_database, table_path, receipt=True): pipeline_database.add_record( table_path, entry_id, diff --git a/tests/test_databases/test_postgresql_connector_integration.py b/tests/test_databases/test_postgresql_connector_integration.py index 4894c4e64..876f53960 100644 --- a/tests/test_databases/test_postgresql_connector_integration.py +++ b/tests/test_databases/test_postgresql_connector_integration.py @@ -657,22 +657,17 @@ def test_postgresql_attachment_durability_probe( """Check only requested durable IDs, and tolerate a transient probe failure.""" attached = ConnectorArrowDatabase(connector) job = _attachment_job(attached) - queries: list[str] = [] - returned_ids: list[bytes] = [] - read = connector.iter_batches - - def observe_read( - query: str, params: Any = None, batch_size: int = 1000 - ) -> Iterator[pa.RecordBatch]: - if not query.startswith('SELECT "__record_id"'): - yield from read(query, params, batch_size) - return - queries.append(query) + requested_ids: list[set[bytes]] = [] + returned_ids: set[bytes] = set() + read = connector._read_record_ids # pyright: ignore[reportPrivateUsage] + + def observe_read(table: tuple[str | None, str], ids: set[bytes]) -> set[bytes]: + requested_ids.append(ids) if scenario == "read_error" and retries: raise psycopg.OperationalError("temporary connector read failure") - for batch in read(query, params, batch_size): - returned_ids.extend(cast("list[bytes]", batch[0].to_pylist())) - yield batch + found = read(table, ids) + returned_ids.update(found) + return found def fail_flush() -> None: raise OSError("temporary attachment flush failure") @@ -682,7 +677,7 @@ def on_run_end(self, run_id: str) -> None: raise RuntimeError("observer failed") retries = False - monkeypatch.setattr(connector, "iter_batches", observe_read) + monkeypatch.setattr(connector, "_read_record_ids", observe_read) with monkeypatch.context() as patch: patch.setattr(attached, "flush", fail_flush) with pytest.raises(OrcapodDatabaseWriteError) as first_error: @@ -703,8 +698,8 @@ def on_run_end(self, run_id: str) -> None: retries = True with pytest.raises(RuntimeError, match="observer failed"): _ = job.run(observer=FailRun()) - assert queries and all(" WHERE " in query for query in queries) - assert returned_ids == ([receipt_id] if scenario == "durable" else []) + assert requested_ids == [{receipt_id}] + assert returned_ids == ({receipt_id} if scenario == "durable" else set()) assert not other.table_exists(("pending",)) committed = other.get_all_records(path) assert committed is not None and committed.num_rows == 2 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..c6895beb3 --- /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": "14def388091efa8830e88721fbac62de68181e89" +} 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..3ee3fb490 --- /dev/null +++ b/tests/test_pipeline/test_attachment_store_io.py @@ -0,0 +1,500 @@ +"""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.", +} + +# Completion already found the buffered rows. Only this ID-only lookup may +# check whether another handle made those two receipts durable in the meantime. +POSTGRES_REPLAY_QUERY = ( + 'SELECT "__record_id" FROM "schema".' + '"o1_attached_side_effects__deli_afb3b24a6538f4bb14f2a151291c9f57" ' + 'WHERE "__record_id" = ANY(%s)' +) + +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() + 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 should check + # exactly those IDs, and leave this handle's unrelated row queued. + 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() + 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 documented attachment flush/replay 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]) + if backend == "postgres" and scenario == "replay": + budget[POSTGRES_REPLAY_QUERY] += 1 if kind == "statements" else 2 + assert not (extra := Counter(actual[kind]) - budget), (kind, dict(extra)) diff --git a/tests/test_pipeline/test_mixed_function_commits.py b/tests/test_pipeline/test_mixed_function_commits.py index dfa36e3f6..2f9841b14 100644 --- a/tests/test_pipeline/test_mixed_function_commits.py +++ b/tests/test_pipeline/test_mixed_function_commits.py @@ -64,6 +64,16 @@ def upsert_records( super().upsert_records(table_name, records, id_column, skip_existing) self.upserts[table_name].append(records.num_rows) + def _read_record_ids( + self, table: tuple[str | None, str], ids: set[bytes] + ) -> set[bytes]: + """Find requested committed IDs in the connector test double.""" + _, name = table + records = self._tables.get(name) + if records is None: + return set() + return ids.intersection(cast("list[bytes]", records["__record_id"].to_pylist())) + def make_job( pipeline: ArrowDatabaseProtocol, From c349c1ade1d8230372b64177c70c41c76197d6f9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 21:30:43 -0800 Subject: [PATCH 15/16] fix(pipeline): retain receipts after attachment rollback --- changelog.d/ITL-1383.md | 2 +- docs/concepts/pipeline-job.md | 4 +- docs/dev/design_issues/ITL-1383-BL3.md | 12 +- src/orcapod/core/database_writes.py | 71 ++------ src/orcapod/databases/_pending_commits.py | 68 +++++++- .../databases/connector_arrow_database.py | 110 ++++++------ src/orcapod/databases/delta_lake_databases.py | 21 ++- src/orcapod/databases/in_memory_databases.py | 15 +- src/orcapod/databases/postgresql_connector.py | 23 +-- src/orcapod/databases/sqlite_connector.py | 19 --- src/orcapod/side_effects.py | 18 +- .../test_postgresql_connector_integration.py | 161 ++++++++++++------ .../fixtures/attachment_store_io.json | 2 +- .../test_pipeline/test_attachment_store_io.py | 19 +-- .../test_job_attached_database_commit.py | 45 ++++- .../test_mixed_function_commits.py | 10 -- 16 files changed, 334 insertions(+), 266 deletions(-) diff --git a/changelog.d/ITL-1383.md b/changelog.d/ITL-1383.md index ceb9dda3c..fe75ce454 100644 --- a/changelog.d/ITL-1383.md +++ b/changelog.d/ITL-1383.md @@ -1,6 +1,6 @@ ### 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. The job retries a failed attachment flush even after rebinding its sources or node attachments. Duplicate-only replays of cached rows or completed deliveries leave unrelated pending rows alone when the store can verify that the replayed rows are durable. Delivery and forwarding load-only runs keep their existing database reads. +- 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 the existing lookup or a local PostgreSQL commit confirms durability. PostgreSQL delivery and replay and forwarding load-only runs keep their existing database reads. ### Known limitations diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index be0509578..58b9037d1 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -372,7 +372,9 @@ After committing its own databases, the job flushes each supported attachment th 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. +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. diff --git a/docs/dev/design_issues/ITL-1383-BL3.md b/docs/dev/design_issues/ITL-1383-BL3.md index f872ea56e..ca81cbaea 100644 --- a/docs/dev/design_issues/ITL-1383-BL3.md +++ b/docs/dev/design_issues/ITL-1383-BL3.md @@ -28,14 +28,16 @@ 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 a second handle makes previously pending logs durable, a duplicate-only replay -in the same store schema leaves the attachment's unrelated writes buffered. -This includes completion-tracked side-effect receipts. The collector observes +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. 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. A connector can use a bounded -primary-key lookup to decide whether already-durable log rows justify a whole flush. +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 diff --git a/src/orcapod/core/database_writes.py b/src/orcapod/core/database_writes.py index 49add11d5..b5e38b787 100644 --- a/src/orcapod/core/database_writes.py +++ b/src/orcapod/core/database_writes.py @@ -2,10 +2,9 @@ from __future__ import annotations -import logging from contextlib import contextmanager from contextvars import ContextVar -from dataclasses import dataclass, field +from dataclasses import dataclass from typing import TYPE_CHECKING, Protocol from orcapod.databases._pending_commits import observe_records @@ -13,9 +12,7 @@ if TYPE_CHECKING: from collections.abc import Callable, Collection, Iterator, Set - from orcapod.databases._pending_commits import PendingCommits, VerifyIDs - -logger = logging.getLogger(__name__) + from orcapod.databases._pending_commits import PendingCommits LogTable = tuple[str, tuple[str, ...]] @@ -44,15 +41,6 @@ class _Write: function: bool -@dataclass -class _Replay: - """Evidence of duplicate rows observed through the existing run.""" - - durable: set[bytes] = field(default_factory=set) - candidates: set[bytes] = field(default_factory=set) - verify: VerifyIDs | None = None - - class DatabaseWrites: """A run's writes to objects outside the job's original flush sequence.""" @@ -71,7 +59,7 @@ def __init__( 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._duplicate_logs: dict[tuple[int, LogTable], _Replay] = {} + 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.""" @@ -123,22 +111,10 @@ def replayed_durable_logs( logs: dict[LogTable, set[bytes]], ) -> bool: """A duplicate-only replay can find the failed logs now durable elsewhere.""" - try: - for table, ids in logs.items(): - replay = self._duplicate_logs.get((queue, table)) - if replay is None: - return False - remaining = ids - replay.durable - if remaining and ( - not remaining <= replay.candidates - or replay.verify is None - or not replay.verify(remaining) - ): - return False - except Exception: - logger.debug("Could not verify replayed log durability", exc_info=True) - return False - return bool(logs) + return bool(logs) and all( + ids <= self._durable_logs.get((queue, table), set()) + for table, ids in logs.items() + ) @contextmanager def track( @@ -147,7 +123,6 @@ def track( path: tuple[str, ...], *, function: bool = False, - receipt: bool = False, completion: bool = False, ) -> Iterator[None]: """Track the outcome of the existing native store operation.""" @@ -167,33 +142,16 @@ def track( def record( key: str, added: set[bytes], - duplicates: set[bytes], durable: Set[bytes], - verify: VerifyIDs | None, ) -> None: table = key, database.base_path + path if added: - if verify is not None and not (function or receipt or completion): - # Connectors deduplicate committed IDs in the upsert. Check an - # attached operator batch by ID before letting it flush unrelated - # pending rows. Receipts already followed the delivery path. - try: - if verify(added): - durable = durable | added - added = set() - except Exception: - logger.debug("Could not verify operator log IDs", exc_info=True) - if added: - write = self._writes.setdefault( - (queue, table), _Write(database, pending, set(), function) - ) - write.ids.update(added) - if retry and not function and (durable or (duplicates and verify)): - replay = self._duplicate_logs.setdefault((queue, table), _Replay()) - replay.durable.update(durable) - if verify is not None: - replay.candidates.update(duplicates) - replay.verify = verify + 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 @@ -234,14 +192,13 @@ def track_database_write( path: tuple[str, ...], *, function: bool = False, - receipt: 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, receipt=receipt): + with run.track(database, path, function=function): yield diff --git a/src/orcapod/databases/_pending_commits.py b/src/orcapod/databases/_pending_commits.py index 74200d534..27d7f15d3 100644 --- a/src/orcapod/databases/_pending_commits.py +++ b/src/orcapod/databases/_pending_commits.py @@ -5,6 +5,7 @@ from collections.abc import Callable, Iterator, Set from contextlib import contextmanager from contextvars import ContextVar +from threading import Lock import pyarrow as pa @@ -47,6 +48,45 @@ 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._durable_receipts: dict[str, set[bytes]] = {} + 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_durable_receipts(self, key: str, ids: set[bytes]) -> None: + """Remember a peer's successful commit only for our queued receipts.""" + with self._receipt_lock: + matching = ids & self._receipts.get(key, set()) + if matching: + self._durable_receipts.setdefault(key, set()).update(matching) + + def has_durable_receipt(self, key: str, record_id: bytes) -> bool: + """Return whether a peer has committed this queued receipt.""" + with self._receipt_lock: + return record_id in self._durable_receipts.get(key, ()) + + 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( @@ -142,6 +182,12 @@ 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: + for receipts in (self._receipts, self._durable_receipts): + if key in receipts: + receipts[key].difference_update(ids) + if not receipts[key]: + del receipts[key] if key not in self._batches: self._schema_checks.pop(key, None) guards = self._guards.get(key) @@ -163,16 +209,24 @@ def _select(self, batch: pa.Table, ids: set[bytes], *, keep: bool) -> pa.Table: _queue_lookup: ContextVar[list[PendingCommits] | None] = ContextVar( "_queue_lookup", default=None ) -VerifyIDs = Callable[[set[bytes]], bool] -RecordObserver = Callable[ - [str, set[bytes], set[bytes], Set[bytes], VerifyIDs | None], 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 ) +@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.""" @@ -207,11 +261,9 @@ def report_records( key: str, *, added: set[bytes], - duplicates: set[bytes], durable: Set[bytes] = frozenset(), - verify: VerifyIDs | None = None, ) -> None: - """Report accepted and duplicate IDs using the operation's resolved table key.""" + """Report accepted and already durable IDs using the resolved table key.""" observer = _record_observer.get() if observer is not None: - observer(key, added, duplicates, durable, verify) + observer(key, added, durable) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 99987fbff..ac1790bdd 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -21,9 +21,10 @@ import re from collections import defaultdict from collections.abc import Callable, Collection, Mapping -from functools import partial from contextlib import AbstractContextManager, nullcontext +from threading import Lock from typing import Any, cast +from weakref import WeakSet, WeakValueDictionary import pyarrow as pa import pyarrow.compute as pc @@ -39,6 +40,7 @@ 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, @@ -74,6 +76,26 @@ _SQL_HINT_LENGTH = 27 _SQL_DIGEST_LENGTH = 32 +# Peers pass commit evidence only to live queues for the same database. The +# queued table key also carries the schema. Nothing records receipt history. +_receipt_queues: WeakValueDictionary[tuple[str, int, str], WeakSet[PendingCommits]] = ( + WeakValueDictionary() +) +_receipt_queue_lock = Lock() + + +def _connect_receipt_queue( + connector: PostgreSQLConnector, pending: PendingCommits +) -> WeakSet[PendingCommits]: + """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] = WeakSet() + queues.add(pending) + return queues + def _arrow_schema_to_column_infos(schema: pa.Schema) -> list[ColumnInfo]: """Convert a PyArrow schema to a list of ColumnInfo.""" @@ -194,6 +216,13 @@ def __init__( on_empty=self._discard_pending_duplicate_policy, ) ) + self._receipt_peers: WeakSet[PendingCommits] | 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.""" @@ -613,13 +642,10 @@ def add_records( record_key = self._get_record_key(record_path) pending_owner_key: tuple[str, str] | None = None - committed_table = None if self._sql_store is not None: schema = self._schema_from_record_key(record_key) assert schema is not None - committed_table = self._find_committed_table( - table_name, full_path, schema=schema - ) + _ = self._find_committed_table(table_name, full_path, schema=schema) pending_owner_key = (schema, table_name) queued = self._pending_table_owners.get(pending_owner_key) if queued is not None and queued[0] != record_key: @@ -655,9 +681,6 @@ def add_records( ) records = records.filter(mask) if records.num_rows == 0: - self._report_stored_record_outcome( - record_key, committed_table, added=set(), duplicates=input_ids - ) return # Mark this pending slot so flush() uses skip_existing=True. self._pending_skip_existing[record_key] = True @@ -685,12 +708,8 @@ def add_records( ) added = set(cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist())) self._pending_record_ids[record_key].update(added) - self._report_stored_record_outcome( - record_key, - committed_table, - added=added, - duplicates=input_ids - added, - ) + self._pending_commits.record_receipts(record_key, added) + report_records(record_key, added=added) if flush: self.flush() @@ -925,12 +944,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( @@ -948,12 +964,20 @@ 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) + for peer in peers: + if peer is not self._pending_commits: + peer.note_durable_receipts(record_key, ids) 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, @@ -1018,36 +1042,6 @@ def _fmt(cols: Mapping[str, pa.DataType]) -> str: schema=schema, ) - def _report_stored_record_outcome( - self, - record_key: str, - committed_table: tuple[str | None, str] | None, - *, - added: set[bytes], - duplicates: set[bytes], - ) -> None: - """Use the already verified relation for optional committed-ID checks.""" - lookup = getattr(self._connector, "_read_record_ids", None) - if self._sql_store is None and lookup is not None: - # Connectors without an ID predicate must never scan for enrollment. - full_path = self._record_path_from_key(record_key) - committed_table = (None, self._path_to_table_name(full_path)) - verify = ( - partial(self._all_ids_committed, lookup, committed_table) - if lookup is not None and committed_table is not None - else None - ) - report_records(record_key, added=added, duplicates=duplicates, verify=verify) - - @staticmethod - def _all_ids_committed( - lookup: Callable[[tuple[str | None, str], set[bytes]], set[bytes]], - table: tuple[str | None, str], - ids: set[bytes], - ) -> bool: - """Require every ID while fetching at most one key per requested record.""" - return ids <= lookup(table, ids) - # ── Read methods ────────────────────────────────────────────────────────── def get_record_by_id( @@ -1074,9 +1068,10 @@ def get_record_by_id( table = self._find_committed_table( self._path_to_table_name(full_path), full_path, schema=schema ) - self._report_stored_record_outcome( - record_key, table, added=set(), duplicates={record_id} - ) + if table is not None and self._pending_commits.has_durable_receipt( + record_key, record_id + ): + report_records(record_key, added=set(), durable={record_id}) return self._handle_record_id_column(filtered, record_id_column) # Check committed @@ -1087,12 +1082,7 @@ def get_record_by_id( if filtered.num_rows == 0: return None # This lookup already read the row from committed storage. - report_records( - record_key, - added=set(), - duplicates={record_id}, - durable={record_id}, - ) + 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 e07c75eb5..4e2fa16cc 100644 --- a/src/orcapod/databases/delta_lake_databases.py +++ b/src/orcapod/databases/delta_lake_databases.py @@ -2992,7 +2992,6 @@ def add_records( report_records( self._get_record_key(record_path), added=set(), - duplicates=set(), durable=durable, ) logger.debug("All records were duplicates, nothing to insert") @@ -3054,10 +3053,11 @@ def add_records( # Step 7: Add to pending batch (no overwrite logic needed) 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( - self._get_record_key(record_path), + record_key, added=added, - duplicates=set(), durable=durable, ) @@ -3547,7 +3547,7 @@ def get_record_by_id( return None # Handle (remove/rename) the record id column before returning - report_records(record_key, added=set(), duplicates=set(), durable={record_id}) + report_records(record_key, added=set(), durable={record_id}) return self._handle_record_id_column(result, record_id_column) def get_records_by_ids( @@ -3865,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 @@ -3894,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 @@ -3912,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 diff --git a/src/orcapod/databases/in_memory_databases.py b/src/orcapod/databases/in_memory_databases.py index eee333f60..3a94109e5 100644 --- a/src/orcapod/databases/in_memory_databases.py +++ b/src/orcapod/databases/in_memory_databases.py @@ -321,9 +321,7 @@ def add_records( if skip_duplicates: records, durable = self._filter_existing_records(record_key, records) if records.num_rows == 0: - report_records( - record_key, added=set(), duplicates=set(), durable=durable - ) + report_records(record_key, added=set(), durable=durable) return else: # Check for conflicts in the pending batch only @@ -348,7 +346,8 @@ def add_records( pending_ids = cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist()) added = set(pending_ids) self._pending_record_ids[record_key].update(added) - report_records(record_key, added=added, duplicates=set(), durable=durable) + self._pending_commits.record_receipts(record_key, added) + report_records(record_key, added=added, durable=durable) if flush: self.flush() @@ -437,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.""" @@ -632,7 +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(), duplicates=set(), durable={record_id}) + 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 3f5ca117c..b6742a531 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -439,6 +439,13 @@ def _require_open(self) -> Any: raise RuntimeError("PostgreSQLConnector is closed") return self._conn + def _receipt_store_identity(self) -> tuple[str, int, str]: + """Identify the connected database without issuing a query.""" + 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 + @staticmethod def _validate_table_name(table_name: str) -> None: """Raise ValueError if table_name contains a double-quote character.""" @@ -762,22 +769,6 @@ def get_column_info( # ── Read ────────────────────────────────────────────────────────────────── - def _read_record_ids( - self, table: tuple[str | None, str], ids: set[bytes] - ) -> set[bytes]: - """Read only the requested primary keys from a verified store table.""" - schema, name = table - target = sql_table_identifier(name, schema).replace("%", "%%") - query = f'SELECT "__record_id" FROM {target} WHERE "__record_id" = ANY(%s)' - with self._lock: - self._require_open() - dsn = self._dsn - # A separate connection sees committed keys even when the caller's - # connection already has an open transaction. - with psycopg.connect(dsn, autocommit=True) as conn, conn.cursor() as cur: - _ = cur.execute(query, (list(ids),)) # pyright: ignore[reportArgumentType] # the identifier is quoted - return {cast(bytes, row[0]) for row in cur.fetchall()} - def iter_batches( self, query: str, diff --git a/src/orcapod/databases/sqlite_connector.py b/src/orcapod/databases/sqlite_connector.py index f5c935545..684de8bb7 100644 --- a/src/orcapod/databases/sqlite_connector.py +++ b/src/orcapod/databases/sqlite_connector.py @@ -466,25 +466,6 @@ def _get_column_info( # ── Read ────────────────────────────────────────────────────────────────── - def _read_record_ids( - self, table: tuple[str | None, str], ids: set[bytes] - ) -> set[bytes]: - """Read only the requested primary keys from a verified store table.""" - schema, name = table - target = sql_table_identifier(name, schema) - keys = tuple(ids) - found: set[bytes] = set() - with self._lock: - conn = self._require_open() - if conn.in_transaction: - return found # This connection could see an uncommitted row. - for index in range(0, len(keys), 500): - chunk = keys[index : index + 500] - placeholders = ", ".join("?" for _ in chunk) - query = f'SELECT "__record_id" FROM {target} WHERE "__record_id" IN ({placeholders})' - found.update(cast(bytes, row[0]) for row in conn.execute(query, chunk)) - return found - def iter_batches( self, query: str, diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py index be7b2297c..863241df2 100644 --- a/src/orcapod/side_effects.py +++ b/src/orcapod/side_effects.py @@ -40,6 +40,7 @@ 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, @@ -491,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". @@ -566,7 +568,7 @@ def _write_invocation_row( schema=_invocation_log_schema(), ) try: - with track_database_write(pipeline_database, table_path, receipt=True): + with track_database_write(pipeline_database, table_path): pipeline_database.add_record( table_path, entry_id, diff --git a/tests/test_databases/test_postgresql_connector_integration.py b/tests/test_databases/test_postgresql_connector_integration.py index 876f53960..3f8a1b864 100644 --- a/tests/test_databases/test_postgresql_connector_integration.py +++ b/tests/test_databases/test_postgresql_connector_integration.py @@ -42,7 +42,6 @@ from orcapod.databases._sql_store import STORE_PATH_CATALOG from orcapod.errors import OrcapodDatabaseError, OrcapodDatabaseWriteError from orcapod.invocation import InvocationContext -from orcapod.pipeline.observer import NoOpObserver from orcapod.side_effects import SideEffectPod, SideEffectPodConfig from orcapod.sources import DictSource from orcapod.types import ColumnInfo @@ -648,61 +647,125 @@ def observe_read( @pytest.mark.postgres -@pytest.mark.parametrize("scenario", ["filtered", "read_error", "durable"]) -def test_postgresql_attachment_durability_probe( +@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, - scenario: str, + runner: str, + failure: str, ) -> None: - """Check only requested durable IDs, and tolerate a transient probe failure.""" - attached = ConnectorArrowDatabase(connector) - job = _attachment_job(attached) - requested_ids: list[set[bytes]] = [] - returned_ids: set[bytes] = set() - read = connector._read_record_ids # pyright: ignore[reportPrivateUsage] - - def observe_read(table: tuple[str | None, str], ids: set[bytes]) -> set[bytes]: - requested_ids.append(ids) - if scenario == "read_error" and retries: - raise psycopg.OperationalError("temporary connector read failure") - found = read(table, ids) - returned_ids.update(found) - return found + """A rolled-back flush keeps the receipt, and a durable replay needs no probe.""" + delivered: list[int] = [] - def fail_flush() -> None: - raise OSError("temporary attachment flush failure") + 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 - class FailRun(NoOpObserver): - def on_run_end(self, run_id: str) -> None: - raise RuntimeError("observer failed") + def fail_flush() -> None: + raise OSError("temporary flush failure") - retries = False - monkeypatch.setattr(connector, "_read_record_ids", observe_read) - 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__ + _, _, _, 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)) ) - (path,) = attached.list_table_paths() - records = attached.get_all_records(path, record_id_column="record_id") - assert records is not None - rows = records.drop(["record_id"]) - receipt_id = cast(bytes, records["record_id"][0].as_py()) - other = ConnectorArrowDatabase(connector) - other.add_record(path, b"historical", rows.slice(0, 1), flush=True) - if scenario == "durable": - other.add_record(path, receipt_id, rows, flush=True) - attached.add_record(("pending",), b"unrelated", pa.table({"value": [1]})) - retries = True - with pytest.raises(RuntimeError, match="observer failed"): - _ = job.run(observer=FailRun()) - assert requested_ids == [{receipt_id}] - assert returned_ids == ({receipt_id} if scenario == "durable" else set()) - assert not other.table_exists(("pending",)) - committed = other.get_all_records(path) - assert committed is not None and committed.num_rows == 2 + 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 diff --git a/tests/test_pipeline/fixtures/attachment_store_io.json b/tests/test_pipeline/fixtures/attachment_store_io.json index c6895beb3..5acf594e2 100644 --- a/tests/test_pipeline/fixtures/attachment_store_io.json +++ b/tests/test_pipeline/fixtures/attachment_store_io.json @@ -792,5 +792,5 @@ ] } }, - "main": "14def388091efa8830e88721fbac62de68181e89" + "main": "4faef270ede72083f5ff37b541af038d98fd3693" } diff --git a/tests/test_pipeline/test_attachment_store_io.py b/tests/test_pipeline/test_attachment_store_io.py index 3ee3fb490..a640498bf 100644 --- a/tests/test_pipeline/test_attachment_store_io.py +++ b/tests/test_pipeline/test_attachment_store_io.py @@ -78,14 +78,6 @@ async def _run(job: PipelineJob, runner: str, *, load_only: bool = False) -> Non "function": "Flush the other buffered writes in the function's attachment.", } -# Completion already found the buffered rows. Only this ID-only lookup may -# check whether another handle made those two receipts durable in the meantime. -POSTGRES_REPLAY_QUERY = ( - 'SELECT "__record_id" FROM "schema".' - '"o1_attached_side_effects__deli_afb3b24a6538f4bb14f2a151291c9f57" ' - 'WHERE "__record_id" = ANY(%s)' -) - Counts = dict[str, dict[str, int]] @@ -331,6 +323,7 @@ async def _capture_scenario( ) -> 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") @@ -447,8 +440,8 @@ def fail() -> None: **({"cache_mode": CacheMode.LOG} if operator else {}), ) elif scenario == "replay": - # A second handle has made the receipts durable. Replay should check - # exactly those IDs, and leave this handle's unrelated row queued. + # 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() @@ -469,6 +462,8 @@ def fail() -> None: 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() @@ -487,7 +482,7 @@ def fail() -> None: 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 documented attachment flush/replay I/O.""" + """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] @@ -495,6 +490,4 @@ async def test_attachment_runs_stay_within_main_store_io( budget = Counter(expected[kind]) if scenario in ATTACHMENT_FLUSHES: budget.update(flush[kind]) - if backend == "postgres" and scenario == "replay": - budget[POSTGRES_REPLAY_QUERY] += 1 if kind == "statements" else 2 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 index a2e0dde4f..58507b65a 100644 --- a/tests/test_pipeline/test_job_attached_database_commit.py +++ b/tests/test_pipeline/test_job_attached_database_commit.py @@ -590,10 +590,10 @@ def fail() -> None: @pytest.mark.asyncio @pytest.mark.parametrize("runner", JOB_RUNNERS) @pytest.mark.parametrize("wrapped", [False, True], ids=["native", "protocol"]) -async def test_durable_connector_duplicates_leave_the_attachment_unflushed( +async def test_connector_log_duplicates_use_the_native_upsert( tmp_path: Path, runner: str, source: ArrowTableSource, *, wrapped: bool ) -> None: - """A connector defers durable duplicate checking to the upsert.""" + """Native queues use ordinary whole flushes and the connector deduplicates.""" connector = CommitConnector() store = ConnectorArrowDatabase(connector) attachment = ProtocolDatabase(store) if wrapped else store @@ -609,7 +609,9 @@ async def test_durable_connector_duplicates_leave_the_attachment_unflushed( job.nodes[label].clear_cache() await _run(job, runner) assert job.nodes["grouped"].as_table().num_rows == 2 - assert reopened.list_table_paths() == existing_paths + 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 @@ -894,6 +896,43 @@ def deliver(ctx: InvocationContext, x: int, y: int) -> None: 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"]) diff --git a/tests/test_pipeline/test_mixed_function_commits.py b/tests/test_pipeline/test_mixed_function_commits.py index 2f9841b14..dfa36e3f6 100644 --- a/tests/test_pipeline/test_mixed_function_commits.py +++ b/tests/test_pipeline/test_mixed_function_commits.py @@ -64,16 +64,6 @@ def upsert_records( super().upsert_records(table_name, records, id_column, skip_existing) self.upserts[table_name].append(records.num_rows) - def _read_record_ids( - self, table: tuple[str | None, str], ids: set[bytes] - ) -> set[bytes]: - """Find requested committed IDs in the connector test double.""" - _, name = table - records = self._tables.get(name) - if records is None: - return set() - return ids.intersection(cast("list[bytes]", records["__record_id"].to_pylist())) - def make_job( pipeline: ArrowDatabaseProtocol, From 8acf7f1ccb430efa999a218ae84236b329d00eaa Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 22:15:19 -0800 Subject: [PATCH 16/16] fix(pipeline): verify receipt evidence on the writer backend --- changelog.d/ITL-1383.md | 2 +- docs/dev/design_issues/ITL-1383-BL3.md | 4 +- src/orcapod/databases/_pending_commits.py | 43 +++++++---- .../databases/connector_arrow_database.py | 44 +++++++---- src/orcapod/databases/postgresql_connector.py | 24 +++++- .../test_postgresql_connector_integration.py | 75 +++++++++++++++++++ .../test_job_attached_database_commit.py | 10 +-- 7 files changed, 166 insertions(+), 36 deletions(-) diff --git a/changelog.d/ITL-1383.md b/changelog.d/ITL-1383.md index fe75ce454..a5981f9ba 100644 --- a/changelog.d/ITL-1383.md +++ b/changelog.d/ITL-1383.md @@ -1,6 +1,6 @@ ### 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 the existing lookup or a local PostgreSQL commit confirms durability. PostgreSQL delivery and replay and forwarding load-only runs keep their existing database reads. +- 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 diff --git a/docs/dev/design_issues/ITL-1383-BL3.md b/docs/dev/design_issues/ITL-1383-BL3.md index ca81cbaea..27282c2d2 100644 --- a/docs/dev/design_issues/ITL-1383-BL3.md +++ b/docs/dev/design_issues/ITL-1383-BL3.md @@ -30,7 +30,9 @@ 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. A failed transaction +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. diff --git a/src/orcapod/databases/_pending_commits.py b/src/orcapod/databases/_pending_commits.py index 27d7f15d3..0e82b8a8e 100644 --- a/src/orcapod/databases/_pending_commits.py +++ b/src/orcapod/databases/_pending_commits.py @@ -49,7 +49,7 @@ def __init__( self._guards: dict[str, dict[bytes, PendingCommit]] = {} self._schema_checks: dict[str, Callable[[pa.Schema], None]] = {} self._receipts: dict[str, set[bytes]] = {} - self._durable_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: @@ -58,17 +58,23 @@ def record_receipts(self, key: str, ids: set[bytes]) -> None: with self._receipt_lock: self._receipts.setdefault(key, set()).update(ids) - def note_durable_receipts(self, key: str, ids: set[bytes]) -> None: - """Remember a peer's successful commit only for our queued receipts.""" + 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: - self._durable_receipts.setdefault(key, set()).update(matching) - - def has_durable_receipt(self, key: str, record_id: bytes) -> bool: - """Return whether a peer has committed this queued receipt.""" + 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 record_id in self._durable_receipts.get(key, ()) + 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.""" @@ -183,11 +189,17 @@ 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: - for receipts in (self._receipts, self._durable_receipts): - if key in receipts: - receipts[key].difference_update(ids) - if not receipts[key]: - del receipts[key] + 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) @@ -217,6 +229,11 @@ def _select(self, batch: pa.Table, ids: set[bytes], *, keep: bool) -> pa.Table: ) +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.""" diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index ac1790bdd..71ed8c774 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -24,7 +24,7 @@ from contextlib import AbstractContextManager, nullcontext from threading import Lock from typing import Any, cast -from weakref import WeakSet, WeakValueDictionary +from weakref import WeakKeyDictionary, WeakValueDictionary import pyarrow as pa import pyarrow.compute as pc @@ -32,6 +32,7 @@ from orcapod.databases._pending_commits import ( PendingCommit, PendingCommits, + observing_records, report_queue, report_records, ) @@ -76,9 +77,10 @@ _SQL_HINT_LENGTH = 27 _SQL_DIGEST_LENGTH = 32 -# Peers pass commit evidence only to live queues for the same database. The -# queued table key also carries the schema. Nothing records receipt history. -_receipt_queues: WeakValueDictionary[tuple[str, int, str], WeakSet[PendingCommits]] = ( +# 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() @@ -86,14 +88,14 @@ def _connect_receipt_queue( connector: PostgreSQLConnector, pending: PendingCommits -) -> WeakSet[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] = WeakSet() - queues.add(pending) + queues = _receipt_queues[identity] = WeakKeyDictionary() + queues[pending] = connector return queues @@ -216,7 +218,7 @@ def __init__( on_empty=self._discard_pending_duplicate_policy, ) ) - self._receipt_peers: WeakSet[PendingCommits] | None = None + self._receipt_peers: _ReceiptPeers | None = None if _root is not None: self._receipt_peers = _root._receipt_peers elif isinstance(connector, PostgreSQLConnector): @@ -971,10 +973,14 @@ def _flush_by_key(self, record_key: str) -> None: self._pending_commits.finish(record_key, committed=True) if self._receipt_peers is not None: with _receipt_queue_lock: - peers = tuple(self._receipt_peers) - for peer in peers: + peers = tuple(self._receipt_peers.items()) + for peer, connector in peers: if peer is not self._pending_commits: - peer.note_durable_receipts(record_key, ids) + peer.note_peer_receipts( + record_key, + ids, + same_connection=connector is self._connector, + ) finally: if record_key not in self._pending_batches: self._discard_pending_duplicate_policy(record_key) @@ -1068,10 +1074,18 @@ def get_record_by_id( table = self._find_committed_table( self._path_to_table_name(full_path), full_path, schema=schema ) - if table is not None and self._pending_commits.has_durable_receipt( - record_key, record_id - ): - report_records(record_key, added=set(), durable={record_id}) + 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 diff --git a/src/orcapod/databases/postgresql_connector.py b/src/orcapod/databases/postgresql_connector.py index b6742a531..32620eb99 100644 --- a/src/orcapod/databases/postgresql_connector.py +++ b/src/orcapod/databases/postgresql_connector.py @@ -440,12 +440,34 @@ def _require_open(self) -> Any: return self._conn def _receipt_store_identity(self) -> tuple[str, int, str]: - """Identify the connected database without issuing a query.""" + """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/tests/test_databases/test_postgresql_connector_integration.py b/tests/test_databases/test_postgresql_connector_integration.py index 3f8a1b864..92e7a1388 100644 --- a/tests/test_databases/test_postgresql_connector_integration.py +++ b/tests/test_databases/test_postgresql_connector_integration.py @@ -768,6 +768,81 @@ def fail_flush() -> None: _ = 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 diff --git a/tests/test_pipeline/test_job_attached_database_commit.py b/tests/test_pipeline/test_job_attached_database_commit.py index 58507b65a..7f9dc812a 100644 --- a/tests/test_pipeline/test_job_attached_database_commit.py +++ b/tests/test_pipeline/test_job_attached_database_commit.py @@ -12,6 +12,7 @@ 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 @@ -1067,7 +1068,7 @@ def get_table_names() -> list[str]: @pytest.mark.asyncio @pytest.mark.parametrize("runner", JOB_RUNNERS) -async def test_load_only_ignores_transient_opaque_queue_probe_failure( +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.""" @@ -1076,11 +1077,10 @@ async def test_load_only_ignores_transient_opaque_queue_probe_failure( with job: total.pod(source, label="sum") - def fail_guard(*args: object) -> None: - raise psycopg.OperationalError("could not read the current schema") - - monkeypatch.setattr(ConnectorArrowDatabase, "guard_record", fail_guard) + 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