Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 3 additions & 0 deletions changelog.d/ITL-1983.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Fixed

- `PipelineRepository.publish` now raises `PipelinePublicationConflictError` when a different job takes the selected version before the database accepts the add. Identical publications return the existing version and metadata.
20 changes: 13 additions & 7 deletions docs/concepts/pipeline-job.md
Original file line number Diff line number Diff line change
Expand Up @@ -773,15 +773,21 @@ default to the PostgreSQL session user or authenticated SpiralDB principal.
When the backend cannot report an identity, the default is `None`.

Publish to each repository name from one writer at a time. If two writers
choose the same version, the store can reject the duplicate while adding it.
If both reach the commit step, `publish` verifies the committed version.
It returns the stored entry for identical saved snapshots and raises
`PipelinePublicationConflictError` if a different snapshot won. The losing
writer can retry to publish against the current version.
choose the same version, `publish` checks the committed row whether the
duplicate is detected during the add or at commit. A matching job hash
returns the stored publication with its original metadata, including when
the saved run IDs differ. A different job hash raises
`PipelinePublicationConflictError`. The losing writer can publish again
against the current version.
If a flush fails before committing, retry the same publication on the same
repository instance to reuse its original saved text and publication metadata.
If the write committed and only readback failed, the retry returns that
publication even if a newer version now exists.
If readback fails and a newer job has a different hash, the retry can
still return the originally attempted version if its committed job hash
matches. When the add is refused and readback fails, the repository keeps
the attempted version for verification. If the retry finds no matching
publication, it uses an earlier accepted candidate if one exists. Otherwise,
it publishes using the new call's saved state, author, description, and
timestamp.

List and load use read-only operations on committed entries in the repository's
own storage. For SpiralDB, a viewer opens the repository with
Expand Down
22 changes: 15 additions & 7 deletions docs/dev/specs/itl-1965-pipeline-repository.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,9 @@ context. Listing and loading read only committed entries, including when the
table has never been created. They perform no flush, table creation, or metadata
write against repository storage. After a flush attempt, the writer withdraws
its candidate from the pending queue if it is still there and checks committed
storage for the outcome. Publishing the same job to the same name on the same
repository instance restages a failed candidate with its original saved text
and metadata. The table is created by the first successful insert.
storage for the outcome. If a retry on the same repository instance restages
a failed candidate, it reuses the original saved text and metadata. The table
is created by the first successful insert.
Reconstructing the job's own bindings follows `PipelineJob.load` and can create
a missing local Delta directory (ITL-1967). Publish reads the
highest version for the name, adds one row through the database protocol, and
Expand All @@ -137,10 +137,18 @@ If two independent queues accept the key before either commits, Delta Lake,
SQLite, and the fake keyed SpiralDB backend keep the first committed row and
skip the other. PostgreSQL uses the same commit-time rule with
`ON CONFLICT DO NOTHING`. In the tested interleavings, the earlier version and
entries under other names are preserved. After flushing, `publish` reads the
committed row. If the saved text and job hash match, it returns the stored
metadata. Otherwise it raises `PipelinePublicationConflictError` so the
caller can publish again against the current version.
entries under other names are preserved. If the add raises `ValueError` or
the write reaches the flush step, `publish` checks the committed row at the
chosen version. A matching job hash returns the stored metadata. A different
job hash raises `PipelinePublicationConflictError` so the caller can publish
again against the current version. If the add was refused and no row is
committed at that version, `publish` raises the original error. After a
failed readback, a retry also checks the original attempted version for a
matching job hash if the latest publication's hash differs. If the add was
refused and readback failed, the repository keeps the attempted version
for verification and preserves any earlier accepted candidate. A retry that
finds no matching committed row restages that candidate if present. Otherwise,
it publishes using the new call's saved state, author, description, and timestamp.

## Shared saved-job format

Expand Down
110 changes: 78 additions & 32 deletions src/orcapod/pipeline/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import hashlib
import json
from collections.abc import Set
from collections.abc import Mapping, Set
from dataclasses import dataclass, replace
from datetime import datetime, timezone
from io import StringIO
Expand Down Expand Up @@ -150,6 +150,9 @@ def __init__(self, database: ArrowDatabaseProtocol) -> None:
self._retries: dict[
tuple[tuple[str, ...], str], tuple[PipelinePublication, str]
] = {}
# A refused restage can need verification while the accepted candidate
# remains eligible for another attempt.
self._refused_versions: dict[tuple[tuple[str, ...], str], int] = {}

def _record_id(self, name: tuple[str, ...], version: int) -> bytes:
"""Encode a unique key across data contexts, names and versions."""
Expand Down Expand Up @@ -208,21 +211,31 @@ def publish(
saved_text = job._saved_text()
document = json.loads(saved_text)
job_hash = _publication_hash(document).to_string()
latest = self._latest(name)
latest = self._latest(name, for_publish=True)
retry_key = (name, job_hash)
if latest is not None and latest.job_hash == job_hash:
_ = self._retries.pop(retry_key, None)
_ = self._refused_versions.pop(retry_key, None)
return latest
version = 1 if latest is None else latest.version + 1
retry = self._retries.get(retry_key)
if retry is not None:
original, original_text = retry
rows = self._publication_rows(name, original.version)
accepted_version = retry[0].version if retry is not None else None
refused_version = self._refused_versions.get(retry_key)
for attempted_version in dict.fromkeys((accepted_version, refused_version)):
if attempted_version is None:
continue
rows = self._publication_rows(name, attempted_version)
if rows is not None and rows.num_rows:
row = rows.to_pylist()[0]
if row[_JOB_HASH] == job_hash and row[_SAVED_JOB] == original_text:
committed_hash = cast(str, row[_JOB_HASH])
self._retire_refused_retries(name, {attempted_version: committed_hash})
if committed_hash == job_hash:
_ = self._retries.pop(retry_key, None)
_ = self._refused_versions.pop(retry_key, None)
return _publication_from_row(row)
_ = self._refused_versions.pop(retry_key, None)
if retry is not None:
original, original_text = retry
return self._write_publication(
replace(original, version=version), original_text
)
Expand Down Expand Up @@ -276,7 +289,7 @@ def _write_publication(
# The candidate is ready immediately. The guard owns any copy still queued
# when this call exits, so a later flush cannot publish it by accident.
attempt = PendingCommit(committed=True)
flush_error: Exception | None = None
write_error: Exception | None = None
accepted = False

def record_acceptance(
Expand All @@ -285,8 +298,15 @@ def record_acceptance(
nonlocal accepted
accepted = accepted or record_id in added

previous_retry = self._retries.get(retry_key)

def restore_previous_retry() -> None:
if previous_retry is None:
_ = self._retries.pop(retry_key, None)
else:
self._retries[retry_key] = previous_retry

with self._database.guard_record(_TABLE_PATH, record_id, attempt):
previous_retry = self._retries.get(retry_key)
self._retries[retry_key] = (publication, saved_text)
try:
# The database reports acceptance before an add can auto-flush.
Expand All @@ -299,42 +319,65 @@ def record_acceptance(
accepted = True
self._database.flush_batch(_TABLE_PATH)
except Exception as exc:
if not accepted:
# A backend can refuse an already committed ID before staging it.
# Check the committed row before classifying that ValueError.
if not accepted and not isinstance(exc, ValueError):
raise
flush_error = exc
write_error = exc
finally:
if not accepted:
if previous_retry is None:
_ = self._retries.pop(retry_key, None)
else:
self._retries[retry_key] = previous_retry
restore_previous_retry()
attempt.finish(committed=False)

try:
self._database.refresh_table(_TABLE_PATH)
rows = self._publication_rows(publication.name, publication.version)
except Exception as read_error:
if isinstance(flush_error, SpiralDBWritePermissionError):
flush_error.add_note(
if isinstance(write_error, SpiralDBWritePermissionError):
write_error.add_note(
f"Publication readback also failed ({type(read_error).__name__})."
)
raise flush_error
if flush_error is not None:
raise flush_error from read_error
raise write_error
if write_error is not None:
if not accepted:
self._refused_versions[retry_key] = publication.version
raise write_error from read_error
raise
row = rows.to_pylist()[0] if rows is not None and rows.num_rows else None
matches = row is not None and row[_JOB_HASH] == publication.job_hash
location = f"Pipeline {publication.name!r} at version {publication.version}"
if rows is None or not rows.num_rows:
if flush_error is not None:
raise flush_error
if row is None:
if write_error is not None:
raise write_error
raise RuntimeError(f"{location} is missing after publication.")
_ = self._retries.pop(retry_key, None)
row = rows.to_pylist()[0]
if row[_JOB_HASH] != publication.job_hash or row[_SAVED_JOB] != saved_text:
self._retire_refused_retries(
publication.name, {publication.version: cast(str, row[_JOB_HASH])}
)
if accepted or matches:
_ = self._retries.pop(retry_key, None)
_ = self._refused_versions.pop(retry_key, None)
if not matches:
raise PipelinePublicationConflictError(
f"{location} was written by another publisher. Publish again to retry."
)
return _publication_from_row(row)

def _retire_refused_retries(
self, name: tuple[str, ...], committed_hashes: Mapping[int, str]
) -> None:
"""Discard verification entries disproved by committed version hashes."""
obsolete = [
(retry_name, retry_hash)
for (retry_name, retry_hash), version in list(
self._refused_versions.items()
)
if retry_name == name
and version in committed_hashes
and retry_hash != committed_hashes[version]
]
for key in obsolete:
_ = self._refused_versions.pop(key, None)

def _publication_rows(self, name: tuple[str, ...], version: int) -> pa.Table | None:
rows = self._database.get_record_by_id(
_TABLE_PATH, self._record_id(name, version), committed_only=True
Expand Down Expand Up @@ -363,13 +406,16 @@ def list_versions(self, name: str | tuple[str, ...]) -> list[PipelinePublication
self._publications(_name_tuple(name)), key=lambda row: row.version
)

def _latest(self, name: tuple[str, ...]) -> PipelinePublication | None:
"""Return the highest-numbered publication of this name, if any."""
return max(
self._publications(name),
key=lambda row: row.version,
default=None,
)
def _latest(
self, name: tuple[str, ...], *, for_publish: bool = False
) -> PipelinePublication | None:
"""Read the highest version and reconcile verification entries on publish."""
publications = self._publications(name)
if for_publish and self._refused_versions:
self._retire_refused_retries(
name, {row.version: row.job_hash for row in publications}
)
return max(publications, key=lambda row: row.version, default=None)

@overload
def load(
Expand Down
Loading
Loading