Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
014150e
fix(pipeline): flush databases attached to nodes at the end of job runs
eywalker Nov 28, 2026
99d729d
fix(pipeline): preserve job commit order for attached stores
eywalker Nov 28, 2026
8d807c4
fix(pipeline): retry and deduplicate attached database commits
eywalker Nov 28, 2026
95b935c
fix(pipeline): preserve owned commits and flush pending attachments
eywalker Nov 28, 2026
78da630
fix(pipeline): enroll attachment commits at node write sites
eywalker Nov 28, 2026
59452ea
fix(pipeline): avoid a type import cycle in write enrollment
eywalker Nov 28, 2026
64d62a3
fix(pipeline): retry durable logs and preserve owned flush counts
eywalker Nov 28, 2026
b9e3200
fix(pipeline): retain failed attachment flushes across rebindings
eywalker Nov 28, 2026
f22fa06
fix(pipeline): preserve attachment flush retries and owned cadence
eywalker Nov 28, 2026
0203fe0
fix(pipeline): retain attachments after an interrupted best-effort flush
eywalker Nov 28, 2026
f93b7bc
chore: merge origin/main into ITL-1383
eywalker Nov 28, 2026
0df136e
fix(pipeline): preserve attachment retries through interrupted runs
eywalker Nov 28, 2026
6a12e2f
chore: merge origin/main into ITL-1383
eywalker Nov 28, 2026
367b33b
chore: merge origin/main into ITL-1383
eywalker Nov 28, 2026
bfc8dd2
Merge remote-tracking branch 'origin/main' into eywalker/itl-1383-a-j…
eywalker Nov 29, 2026
b4f3b5e
fix(pipeline): preserve attachment retry evidence and write errors
eywalker Nov 29, 2026
67715b1
chore: merge main into ITL-1383
eywalker Nov 29, 2026
386d64c
Merge remote-tracking branch 'origin/main' into eywalker/itl-1383-a-j…
eywalker Nov 29, 2026
2a5e9e4
fix(pipeline): remove receipt history reads from delivery
eywalker Nov 29, 2026
6abf986
Merge remote-tracking branch 'origin/main' into eywalker/itl-1383-a-j…
eywalker Nov 29, 2026
fc015bc
Merge remote-tracking branch 'origin/main' into eywalker/itl-1383-a-j…
eywalker Nov 29, 2026
9cbb79e
fix(pipeline): preserve store reads during attachment tracking
eywalker Nov 29, 2026
b0accb7
Merge remote-tracking branch 'origin/main' into eywalker/itl-1383-a-j…
eywalker Nov 29, 2026
c349c1a
fix(pipeline): retain receipts after attachment rollback
eywalker Nov 29, 2026
8acf7f1
fix(pipeline): verify receipt evidence on the writer backend
eywalker Nov 29, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changelog.d/ITL-1383.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
### Fixed

- Job runs flush additional databases that their nodes write to after the job's own databases, including on the best-effort commit path after an execution error. Each additional database object is flushed once, together with anything else pending in that object. A failed transaction keeps tracked side-effect receipts queued so a later run can publish them without repeating delivery. The job retries a failed attachment flush even after rebinding its sources or node attachments. Duplicate-only replays leave unrelated rows queued when durability is confirmed. When a separate PostgreSQL connection reports a pending receipt as committed, the retry verifies that record ID on the writer's connection before skipping its flush.

### Known limitations

- Automatic end-of-run flushing for independently attached databases requires a supported backend that can distinguish buffered rows from durable rows. Opaque third-party protocol wrappers keep their existing commit behavior.
11 changes: 11 additions & 0 deletions docs/concepts/pipeline-job.md
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,17 @@ it with `job.bind(sources=...)`. See
[Running again: what a run runs](function-pods.md#running-again-what-a-run-runs) and
[What a source does at a run](sources.md#what-a-source-does-at-a-run).

After committing its own databases, the job flushes each supported attachment that
received a new row from a node during the run. A successful side-effect delivery can
enroll its receipt attachment even when completion tracking is disabled and the same
receipt already exists. The flush publishes anything else pending in that database
object. Scoped views sharing pending writes share one flush. A transaction
failure leaves a tracked delivery receipt in the queue, so the next run can
retry its commit without performing the delivery again.
Automatic attachment flushing covers the built-in Delta, connector, and in-memory
databases and their library-provided views. With a separate opaque third-party
attachment, flush any remaining buffered writes explicitly.

## `Pipeline`: a blueprint without data

A `Pipeline` records steps the same way, but has no database and never runs. It is a
Expand Down
46 changes: 46 additions & 0 deletions docs/dev/design_issues/ITL-1383-BL3.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
## `src/orcapod/pipeline/job.py`, orchestrators, node write paths — database write failures

### BL3 — A job omitted independently attached database objects from its final commit
**Status:** resolved
**Severity:** high
**Issue:** ITL-1383

A caching operator attached to a separate database object returned its new rows
from memory while its log was still buffered. The whole-job final commit flushed
only the job's database views. Independently constructed objects could have separate
pending writes even when they used the same storage location.

**Fix:** After the job's usual commit, the run flushes each additional database
object that accepted node writes once, including anything else pending in the
object. Scoped views share a flush, including sibling views behind a forwarding
wrapper. The job also attempts the flush when execution fails, keeping the
original error. Load-only runs skip the commit. A failed flush
clears the current rows of the nodes that ran and leaves previously held rows
available. A retry can flush the same log rows and side-effect receipts when
they are still pending. Durable cache hits and completion hits leave the attachment
alone. Successful deliveries enroll their receipt attachments without rereading history. An
attached database that accepted function writes also gets a whole flush after
the function's table commits, even if the pipeline store discards its records.
A failed whole flush stays with the job across source and attachment rebindings.
If an attachment becomes a job-owned store, a successful pre-run or final flush
retires the retry. An interrupted attachment flush remains eligible for retry.
If an attachment interrupts the best-effort commit, the job clears the failed
run and also keeps the unattempted attachments eligible for retry.
Cancellation and an interruption in the owned best-effort commit also retain
attachment writes for the next committing run.
If an existing lookup or a successful local PostgreSQL peer commit confirms
that every replayed row is durable in the same store schema, a duplicate-only
replay leaves the attachment's unrelated writes buffered. When a peer uses a
different connection, the writer checks the record ID on its own session before
treating that commit as durable. A failed transaction
keeps queued completion receipts so a retry can publish them without repeating
delivery. The collector observes
which rows the existing write queued, including when a threshold flush fails.
It uses the table key and schema already resolved by the database operation.
It checks pending receipts against the in-memory queue and identifies a
forwarding view's queue through its path metadata. Connectors otherwise
deduplicate buffered writes during their ordinary upsert.

Opaque protocol attachments use the existing commit sequence. Automatic
attachment enrollment requires the ability to distinguish durable from pending
records, which the forwarding protocol does not expose.
222 changes: 222 additions & 0 deletions src/orcapod/core/database_writes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
"""Collect additional database flushes at the node write sites."""

from __future__ import annotations

from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
from typing import TYPE_CHECKING, Protocol

from orcapod.databases._pending_commits import observe_records

if TYPE_CHECKING:
from collections.abc import Callable, Collection, Iterator, Set

from orcapod.databases._pending_commits import PendingCommits

LogTable = tuple[str, tuple[str, ...]]


class WriteDatabase(Protocol):
"""The database operations needed at the node write sites."""

@property
def base_path(self) -> tuple[str, ...]:
"""Return the scope of this database view."""
...

@property
def stores_records(self) -> bool:
"""Return whether this database keeps the records it receives."""
...


@dataclass
class _Write:
"""One write site that still needs its database's final whole flush."""

database: WriteDatabase
pending: PendingCommits
ids: set[bytes]
function: bool


class DatabaseWrites:
"""A run's writes to objects outside the job's original flush sequence."""

def __init__(
self,
owned: tuple[WriteDatabase, ...],
*,
shared_queue: Callable[[WriteDatabase], PendingCommits | None],
supports_enrollment: Callable[[WriteDatabase], bool],
retry_log_queues: Collection[int],
) -> None:
"""Create a collector for one run."""
self._shared_queue = shared_queue
self._queues: dict[int, tuple[WriteDatabase, PendingCommits | None]] = {}
self._supports_enrollment = supports_enrollment
self._retry_log_queues = retry_log_queues
self._covered = {self.queue_id(database) for database in owned}
self._writes: dict[tuple[int, LogTable], _Write] = {}
self._durable_logs: dict[tuple[int, LogTable], set[bytes]] = {}

def _queue(self, database: WriteDatabase) -> PendingCommits | None:
"""Resolve each view once and keep it alive while its identity is in use."""
identity = id(database)
if identity not in self._queues:
self._queues[identity] = (database, self._shared_queue(database))
return self._queues[identity][1]

def queue_id(self, database: WriteDatabase) -> int:
"""Identify the store by its shared queue when it exposes one."""
queue = self._queue(database)
return id(database if queue is None else queue)

def covers(self, queue: int) -> bool:
"""Return whether the job's existing flush sequence covers this queue."""
return queue in self._covered

def databases(self) -> dict[int, WriteDatabase]:
"""Return one view per enrolled store in write order."""
result: dict[int, WriteDatabase] = {}
for (queue, _), write in self._writes.items():
_ = result.setdefault(queue, write.database)
return result

def function_databases(self) -> dict[int, WriteDatabase]:
"""Return attachments whose function writes may be durable before job commit."""
return {
queue: write.database
for (queue, _), write in self._writes.items()
if write.function
}

def logs_to_replay(self, queue: int) -> dict[LogTable, set[bytes]] | None:
"""Keep the IDs from pending logs without querying the store after failure."""
logs: dict[LogTable, set[bytes]] = {}
for (identity, table), write in self._writes.items():
if identity != queue or write.function:
continue
key, _ = table
if not write.pending.has_pending(key, write.ids):
# Even though its rows committed, the whole flush remains owed.
return {}
logs[table] = write.ids
return logs or None

def replayed_durable_logs(
self,
queue: int,
logs: dict[LogTable, set[bytes]],
) -> bool:
"""A duplicate-only replay can find the failed logs now durable elsewhere."""
return bool(logs) and all(
ids <= self._durable_logs.get((queue, table), set())
for table, ids in logs.items()
)

@contextmanager
def track(
self,
database: WriteDatabase,
path: tuple[str, ...],
*,
function: bool = False,
completion: bool = False,
) -> Iterator[None]:
"""Track the outcome of the existing native store operation."""
if not self._supports_enrollment(database):
yield
return
pending = self._queue(database)
queue = id(pending)
if pending is None or self.covers(queue):
yield
return
retry = queue in self._retry_log_queues
if completion and not retry:
yield
return

def record(
key: str,
added: set[bytes],
durable: Set[bytes],
) -> None:
table = key, database.base_path + path
if added:
write = self._writes.setdefault(
(queue, table), _Write(database, pending, set(), function)
)
write.ids.update(added)
if retry and not function and durable:
self._durable_logs.setdefault((queue, table), set()).update(durable)

with observe_records(record):
yield

def exclude_unpublished_result(
self, database: WriteDatabase, path: tuple[str, ...]
) -> None:
"""Keep an unpublished result from enrolling a queue on its own."""
queue = self.queue_id(database)
full_path = database.base_path + path
for identity, table in tuple(self._writes):
key, tracked_path = table
write = self._writes[identity, table]
if (
identity == queue
and tracked_path == full_path
and write.pending.has_pending(key, write.ids)
):
del self._writes[identity, table]


_run_writes: ContextVar[DatabaseWrites | None] = ContextVar("_run_writes", default=None)


@contextmanager
def collect_database_writes(writes: DatabaseWrites) -> Iterator[None]:
"""Share the run's write collection with its synchronous and async nodes."""
token = _run_writes.set(writes)
try:
yield
finally:
_run_writes.reset(token)


@contextmanager
def track_database_write(
database: WriteDatabase,
path: tuple[str, ...],
*,
function: bool = False,
) -> Iterator[None]:
"""Track a write when the node is running as part of a job."""
run = _run_writes.get()
if run is None or not database.stores_records:
yield
return
with run.track(database, path, function=function):
yield


@contextmanager
def track_completion_lookup(
database: WriteDatabase, path: tuple[str, ...]
) -> Iterator[None]:
"""Share the completion lookup's table key with the enclosing job run."""
run = _run_writes.get()
if run is None:
yield
return
with run.track(database, path, completion=True):
yield


def exclude_unpublished_result(database: WriteDatabase, path: tuple[str, ...]) -> None:
"""Keep a dry-run result from independently triggering a whole flush."""
run = _run_writes.get()
if run is not None:
run.exclude_unpublished_result(database, path)
12 changes: 11 additions & 1 deletion src/orcapod/core/nodes/function_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@
from orcapod.core.data_function import output_source_info
from orcapod.core.datagrams.tag_data import Data, EmptyData, Tag
from orcapod.core.row_ids import INSTANCE_ID_COL, RECORD_ID_COL
from orcapod.core.database_writes import (
exclude_unpublished_result,
track_database_write,
)
from orcapod.core.provisional_pods import CONTEXT_FUNCTION_POD, warn_provisional_pod
from orcapod.errors import (
EphemeralResultMissingError,
Expand Down Expand Up @@ -2450,6 +2454,8 @@ def _flush_node_table(
flush=True,
table_flush=True,
) from exc
if result and not publish_records:
exclude_unpublished_result(database, path)

def _commit_pending_writes(self) -> None:
"""Commit results before publishing any records that depend on them."""
Expand Down Expand Up @@ -2514,7 +2520,11 @@ def _write_pipeline_record(
if dependency is None
else database.guard_record(path, row_key, dependency)
)
with database.guard_table_schema(path, check), result_guard:
with (
database.guard_table_schema(path, check),
result_guard,
track_database_write(database, path, function=True),
):
database.add_record(path, row_key, record, skip_duplicates=True)

def _row_processed(self) -> None:
Expand Down
25 changes: 13 additions & 12 deletions src/orcapod/core/nodes/operator_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
)
from orcapod.core.tracker import DEFAULT_TRACKER_MANAGER
from orcapod.core.nodes.staleness import RunHoldingNode
from orcapod.core.database_writes import track_database_write
from orcapod.errors import (
InputValidationError,
PipelineJobRequiredError,
Expand Down Expand Up @@ -1571,23 +1572,23 @@ def _store_output_stream(self, stream: StreamProtocol) -> None:
# deduplicates exact re-runs of the same node within a single run.
# The data context column is appended after the record hashes are computed:
# it names the generation of hashing that produced them and is not hashed.
path = self._stored_table_path
try:
pipeline_database.add_records(
self._stored_table_path,
with_data_context(
mark_data_tags(stored_table, stream_data_tags(self)),
self.data_context_key,
),
record_id_column=self.HASH_COLUMN_NAME,
skip_duplicates=True,
)
with track_database_write(pipeline_database, path):
pipeline_database.add_records(
path,
with_data_context(
mark_data_tags(stored_table, stream_data_tags(self)),
self.data_context_key,
),
record_id_column=self.HASH_COLUMN_NAME,
skip_duplicates=True,
)
except OrcapodDatabaseReadError:
# The stored table could not be read: report the read failure itself.
raise
except Exception as exc:
raise OrcapodDatabaseWriteError(
self._stored_table_path, node_label=self.label
) from exc
raise OrcapodDatabaseWriteError(path, node_label=self.label) from exc

self._cached_output_table = output_table.drop(
[self.HASH_COLUMN_NAME, constants.NODE_CONTENT_HASH_COL]
Expand Down
Loading
Loading