From 5db7affd1e2abbe8b8ec692af8f4bd2b99f3b19b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 10:01:46 -0800 Subject: [PATCH 01/10] fix(pipeline): report publication races before add (ITL-1983) --- changelog.d/ITL-1983.md | 3 ++ src/orcapod/pipeline/repository.py | 24 +++++---- .../test_pipeline/test_pipeline_repository.py | 49 ++++++++++++++----- 3 files changed, 56 insertions(+), 20 deletions(-) create mode 100644 changelog.d/ITL-1983.md diff --git a/changelog.d/ITL-1983.md b/changelog.d/ITL-1983.md new file mode 100644 index 000000000..0d8c0c53b --- /dev/null +++ b/changelog.d/ITL-1983.md @@ -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. diff --git a/src/orcapod/pipeline/repository.py b/src/orcapod/pipeline/repository.py index 2184b479a..0aac15179 100644 --- a/src/orcapod/pipeline/repository.py +++ b/src/orcapod/pipeline/repository.py @@ -273,7 +273,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( @@ -296,9 +296,11 @@ 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: @@ -311,17 +313,21 @@ def record_acceptance( self._database.refresh_table(_TABLE_PATH) rows = self._publication_rows(publication.name, publication.version) except Exception as read_error: - if flush_error is not None: - raise flush_error from read_error + if write_error is not None: + raise write_error from read_error raise 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 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: + matches = ( + row[_JOB_HASH] == publication.job_hash and row[_SAVED_JOB] == saved_text + ) + if accepted or matches: + _ = self._retries.pop(retry_key, None) + if not matches: raise PipelinePublicationConflictError( f"{location} was written by another publisher. Publish again to retry." ) diff --git a/tests/test_pipeline/test_pipeline_repository.py b/tests/test_pipeline/test_pipeline_repository.py index 758560751..a727ef401 100644 --- a/tests/test_pipeline/test_pipeline_repository.py +++ b/tests/test_pipeline/test_pipeline_repository.py @@ -476,12 +476,14 @@ def test_publication_names_and_prefixes_preserve_component_order(reverse: bool) @pytest.mark.parametrize("overlap_at_flush", [False, True], ids=["add", "flush"]) +@pytest.mark.parametrize("same_job", [False, True], ids=["different-job", "same-job"]) def test_overlapping_publications_of_one_name( open_repository_database: Callable[[], ArrowDatabaseProtocol], overlap_at_flush: bool, + same_job: bool, ) -> None: _check_overlapping_publications( - open_repository_database, overlap_at_flush=overlap_at_flush + open_repository_database, overlap_at_flush=overlap_at_flush, same_job=same_job ) @@ -489,6 +491,7 @@ def _check_overlapping_publications( open_repository_database: Callable[[], ArrowDatabaseProtocol], *, overlap_at_flush: bool, + same_job: bool = False, ) -> None: results = InMemoryArrowDatabase() first = PipelineRepository(open_repository_database()) @@ -497,7 +500,7 @@ def _check_overlapping_publications( original = first.publish(_run_job("daily", results, 10)) unrelated = first.publish(_run_job("weekly", results, 20)) first_update = _run_job("daily", results, 30) - second_update = _run_job("daily", results, 40) + second_update = first_update if same_job else _run_job("daily", results, 40) read_latest = second._latest flush_batch = second_database.flush_batch shared_queue = isinstance(second_database, InMemoryArrowDatabase) @@ -508,7 +511,7 @@ def read_before_first_write(name: tuple[str, ...]) -> PipelinePublication | None latest = read_latest(name) assert latest == original if not overlap_at_flush: - winner = first.publish(first_update) + winner = first.publish(first_update, author="first") return latest def flush_after_first_write(path: tuple[str, ...]) -> None: @@ -521,34 +524,38 @@ def flush_after_first_write(path: tuple[str, ...]) -> None: ): _ = first.publish(first_update) else: - winner = first.publish(first_update) + winner = first.publish(first_update, author="first") flush_batch(path) with ( + patch.object( + first_update, "_saved_text", return_value=first_update._saved_text() + ), patch.object(second, "_latest", side_effect=read_before_first_write), patch.object( second_database, "flush_batch", side_effect=flush_after_first_write ), ): - if not overlap_at_flush: - with pytest.raises(ValueError, match="already exist in the stored"): - _ = second.publish(second_update) - elif shared_queue: - winner = second.publish(second_update) + if overlap_at_flush and shared_queue: + winner = second.publish(second_update, author="second") + elif same_job: + published = second.publish(second_update, author="second") + assert published == winner else: with pytest.raises( PipelinePublicationConflictError, match=r"daily.*version 2.*another publisher", ): - _ = second.publish(second_update) + _ = second.publish(second_update, author="second") assert winner is not None and winner.version == 2 + assert winner.author == ("second" if overlap_at_flush and shared_queue else "first") reader = PipelineRepository(open_repository_database()) assert reader.list_versions("daily") == [original, winner] assert reader.list_versions("weekly") == [unrelated] assert _totals(reader.load("daily", 1, database=results)) == [11, 12] assert _totals(reader.load("daily", database=results)) == ( - [41, 42] if overlap_at_flush and shared_queue else [31, 32] + [41, 42] if overlap_at_flush and shared_queue and not same_job else [31, 32] ) assert _totals(reader.load("weekly", database=results)) == [21, 22] @@ -594,6 +601,26 @@ def flush_after_first_write(path: tuple[str, ...]) -> None: assert first.list_versions("daily") == [original, *committed] +def test_publication_preserves_add_error_without_committed_record() -> None: + store = InMemoryArrowDatabase() + repository = PipelineRepository(store) + results = InMemoryArrowDatabase() + original = repository.publish(_run_job("daily", results, 10)) + candidate = _run_job("daily", results, 20) + refusal = ValueError("invalid publication batch") + + with ( + patch.object(store, "add_records", side_effect=refusal), + pytest.raises(ValueError) as caught, + ): + _ = repository.publish(candidate, author="first attempt") + + assert caught.value is refusal + published = repository.publish(candidate, author="second attempt") + assert published.author == "second attempt" + assert repository.list_versions("daily") == [original, published] + + @pytest.mark.parametrize("has_version", [False, True], ids=["first", "update"]) def test_failed_flush_does_not_publish_pending_row( open_repository_database: Callable[[], ArrowDatabaseProtocol], has_version: bool From ebb64b4e223cbbaa082aeab1bf8b3a0aaf0f5883 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 10:54:29 -0800 Subject: [PATCH 02/10] fix(pipeline): match concurrent publications by job hash --- src/orcapod/pipeline/repository.py | 4 +- .../test_pipeline/test_pipeline_repository.py | 52 +++++++++++-------- 2 files changed, 32 insertions(+), 24 deletions(-) diff --git a/src/orcapod/pipeline/repository.py b/src/orcapod/pipeline/repository.py index 0aac15179..049f972ba 100644 --- a/src/orcapod/pipeline/repository.py +++ b/src/orcapod/pipeline/repository.py @@ -322,9 +322,7 @@ def record_acceptance( raise write_error raise RuntimeError(f"{location} is missing after publication.") row = rows.to_pylist()[0] - matches = ( - row[_JOB_HASH] == publication.job_hash and row[_SAVED_JOB] == saved_text - ) + matches = row[_JOB_HASH] == publication.job_hash if accepted or matches: _ = self._retries.pop(retry_key, None) if not matches: diff --git a/tests/test_pipeline/test_pipeline_repository.py b/tests/test_pipeline/test_pipeline_repository.py index a727ef401..923a60578 100644 --- a/tests/test_pipeline/test_pipeline_repository.py +++ b/tests/test_pipeline/test_pipeline_repository.py @@ -560,9 +560,9 @@ def flush_after_first_write(path: tuple[str, ...]) -> None: assert _totals(reader.load("weekly", database=results)) == [21, 22] -@pytest.mark.parametrize("same_text", [True, False], ids=["same-text", "changed-text"]) -def test_overlapping_publications_with_matching_job_hash( - tmp_path: Path, same_text: bool +@pytest.mark.parametrize("overlap_at_flush", [False, True], ids=["add", "flush"]) +def test_overlapping_publications_ignore_run_identity( + tmp_path: Path, overlap_at_flush: bool ) -> None: path = str(tmp_path / "pipelines.sqlite") with ( @@ -573,32 +573,42 @@ def test_overlapping_publications_with_matching_job_hash( first = PipelineRepository(ConnectorArrowDatabase(first_connector)) second_database = ConnectorArrowDatabase(second_connector) second = PipelineRepository(second_database) - job = _run_job("daily", results, 10) - original = first.publish(job) - update = _run_job("daily", results, 20) + original = first.publish(_run_job("daily", results, 10)) + completed = _run_job("daily", results, 20) + pending = _run_job("daily", results, 20, run=False) + assert completed._run_record()["run_id"] is not None + assert pending._run_record()["run_id"] is None + read_latest = second._latest flush_batch = second_database.flush_batch committed: list[PipelinePublication] = [] + def read_before_first_write( + name: tuple[str, ...], + ) -> PipelinePublication | None: + latest = read_latest(name) + assert latest == original + committed.append(first.publish(completed, author="first")) + return latest + def flush_after_first_write(path: tuple[str, ...]) -> None: - committed.append(first.publish(update, author="first")) + committed.append(first.publish(completed, author="first")) flush_batch(path) - saved = update._saved_text() - # JSON whitespace changes the saved bytes without affecting the canonical hash. - candidate = saved if same_text else saved + "\n" - with ( + hook = ( patch.object( second_database, "flush_batch", side_effect=flush_after_first_write - ), - patch.object(update, "_saved_text", side_effect=[candidate, saved]), - ): - if same_text: - assert second.publish(update, author="second") == committed[0] - else: - with pytest.raises(PipelinePublicationConflictError, match="version 2"): - _ = second.publish(update, author="second") - assert committed[0].author == "first" - assert first.list_versions("daily") == [original, *committed] + ) + if overlap_at_flush + else patch.object(second, "_latest", side_effect=read_before_first_write) + ) + with hook: + publication = second.publish(pending, author="second") + + assert committed == [publication] + assert publication.version == 2 + assert publication.author == "first" + assert second.publish(pending) == publication + assert first.list_versions("daily") == [original, publication] def test_publication_preserves_add_error_without_committed_record() -> None: From 257b03924e78ebb4a7fad80a3be669bee07827e5 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 11:39:49 -0800 Subject: [PATCH 03/10] fix(pipeline): match publication retries by job hash --- docs/concepts/pipeline-job.md | 16 +++--- .../dev/specs/itl-1965-pipeline-repository.md | 18 +++--- src/orcapod/pipeline/repository.py | 2 +- .../test_pipeline/test_pipeline_repository.py | 55 ++++++++++++++++++- 4 files changed, 75 insertions(+), 16 deletions(-) diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 4524bdf41..079358122 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -773,15 +773,17 @@ 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. List and load use read-only operations on committed entries in the repository's own storage. For SpiralDB, a viewer opens the repository with diff --git a/docs/dev/specs/itl-1965-pipeline-repository.md b/docs/dev/specs/itl-1965-pipeline-repository.md index c2a66a7a8..a31a1f47f 100644 --- a/docs/dev/specs/itl-1965-pipeline-repository.md +++ b/docs/dev/specs/itl-1965-pipeline-repository.md @@ -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 @@ -137,10 +137,14 @@ 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. ## Shared saved-job format diff --git a/src/orcapod/pipeline/repository.py b/src/orcapod/pipeline/repository.py index 049f972ba..48032169d 100644 --- a/src/orcapod/pipeline/repository.py +++ b/src/orcapod/pipeline/repository.py @@ -217,7 +217,7 @@ def publish( rows = self._publication_rows(name, original.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: + if row[_JOB_HASH] == job_hash: _ = self._retries.pop(retry_key, None) return _publication_from_row(row) return self._write_publication( diff --git a/tests/test_pipeline/test_pipeline_repository.py b/tests/test_pipeline/test_pipeline_repository.py index 923a60578..165a8500f 100644 --- a/tests/test_pipeline/test_pipeline_repository.py +++ b/tests/test_pipeline/test_pipeline_repository.py @@ -31,7 +31,7 @@ SpiralDBKeyedConnector, SQLiteConnector, ) -from orcapod.pipeline.repository import PIPELINE_JSON_HASH_LABEL +from orcapod.pipeline.repository import PIPELINE_JSON_HASH_LABEL, _publication_hash from orcapod.pipeline.serialization import LoadStatus from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.sources import DictSource @@ -777,6 +777,59 @@ def commit_then_fail_readback(path: tuple[str, ...]) -> None: assert _totals(reader.load(job.name, database=results)) == [11, 12] +def test_retry_recognizes_identical_race_winner_with_different_saved_run( + tmp_path: Path, +) -> None: + path = str(tmp_path / "pipelines.sqlite") + with SQLiteConnector(path) as first, SQLiteConnector(path) as second: + winner = PipelineRepository(ConnectorArrowDatabase(first)) + store = ConnectorArrowDatabase(second) + loser = PipelineRepository(store) + results = InMemoryArrowDatabase() + initial = winner.publish(_run_job("daily", results, 10)) + completed = _run_job("daily", results, 20) + pending = _run_job("daily", results, 20, run=False) + flush = store.flush_batch + saved: list[PipelinePublication] = [] + + with ExitStack() as patches: + + def win_during_flush(key: tuple[str, ...]) -> None: + saved.append(winner.publish(completed, author="winner")) + flush(key) + _ = patches.enter_context( + patch.object( + store, + "get_record_by_id", + side_effect=OSError("readback failed"), + ) + ) + + _ = patches.enter_context( + patch.object(store, "flush_batch", side_effect=win_during_flush) + ) + with pytest.raises(OSError, match="readback failed"): + _ = loser.publish(pending, author="loser") + + committed = saved[0] + assert len(loser._retries) == 1 + pending_text = pending._saved_text() + assert pending_text != completed._saved_text() + assert ( + _publication_hash(json.loads(pending_text)).to_string() + == committed.job_hash + ) + newer = winner.publish(_run_job("daily", results, 30)) + + assert loser.publish(pending) == committed + assert loser._retries == {} + assert winner.list_versions("daily") == [initial, committed, newer] + + republished = loser.publish(pending, author="new publisher") + assert (republished.version, republished.author) == (4, "new publisher") + assert winner.list_versions("daily") == [initial, committed, newer, republished] + + @pytest.mark.parametrize("committed", [False, True], ids=["failed", "committed"]) def test_delta_auto_flush_error_preserves_publication_candidate( tmp_path: Path, committed: bool From f9faffc92ef71afe7100e5a8715548f57d4b3b5e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 11:54:12 -0800 Subject: [PATCH 04/10] fix(pipeline): retain retries after inconclusive add refusal --- src/orcapod/pipeline/repository.py | 24 +++++++----- .../test_pipeline/test_pipeline_repository.py | 39 +++++++++++++++++++ 2 files changed, 54 insertions(+), 9 deletions(-) diff --git a/src/orcapod/pipeline/repository.py b/src/orcapod/pipeline/repository.py index 48032169d..2c686ecd9 100644 --- a/src/orcapod/pipeline/repository.py +++ b/src/orcapod/pipeline/repository.py @@ -282,8 +282,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. @@ -302,11 +309,8 @@ def record_acceptance( raise 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 + if not accepted and write_error is None: + restore_previous_retry() attempt.finish(committed=False) try: @@ -316,13 +320,15 @@ def record_acceptance( if write_error is not None: 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 + if not accepted and not matches: + restore_previous_retry() location = f"Pipeline {publication.name!r} at version {publication.version}" - if rows is None or not rows.num_rows: + if row is None: if write_error is not None: raise write_error raise RuntimeError(f"{location} is missing after publication.") - row = rows.to_pylist()[0] - matches = row[_JOB_HASH] == publication.job_hash if accepted or matches: _ = self._retries.pop(retry_key, None) if not matches: diff --git a/tests/test_pipeline/test_pipeline_repository.py b/tests/test_pipeline/test_pipeline_repository.py index 165a8500f..e21678116 100644 --- a/tests/test_pipeline/test_pipeline_repository.py +++ b/tests/test_pipeline/test_pipeline_repository.py @@ -830,6 +830,45 @@ def win_during_flush(key: tuple[str, ...]) -> None: assert winner.list_versions("daily") == [initial, committed, newer, republished] +def test_retry_recovers_winner_after_add_refusal_and_failed_readback( + tmp_path: Path, +) -> None: + path = str(tmp_path / "pipelines.sqlite") + with SQLiteConnector(path) as first, SQLiteConnector(path) as second: + winner = PipelineRepository(ConnectorArrowDatabase(first)) + store = ConnectorArrowDatabase(second) + loser = PipelineRepository(store) + results = InMemoryArrowDatabase() + initial = winner.publish(_run_job("daily", results, 10)) + completed = _run_job("daily", results, 20) + pending = _run_job("daily", results, 20, run=False) + read_latest = loser._latest + saved: list[PipelinePublication] = [] + + def read_before_winner_commits( + name: tuple[str, ...], + ) -> PipelinePublication | None: + latest = read_latest(name) + assert latest == initial + saved.append(winner.publish(completed, author="winner")) + return latest + + read_error = OSError("readback failed") + with ( + patch.object(loser, "_latest", side_effect=read_before_winner_commits), + patch.object(store, "get_record_by_id", side_effect=read_error), + pytest.raises(ValueError) as refusal, + ): + _ = loser.publish(pending, author="loser") + + assert refusal.value.__cause__ is read_error + committed = saved[0] + newer = winner.publish(_run_job("daily", results, 30)) + assert loser.publish(pending) == committed + assert not loser._retries + assert winner.list_versions("daily") == [initial, committed, newer] + + @pytest.mark.parametrize("committed", [False, True], ids=["failed", "committed"]) def test_delta_auto_flush_error_preserves_publication_candidate( tmp_path: Path, committed: bool From 319fccd031ff7b17e9f525fbf8190b1f00c37889 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 12:20:36 -0800 Subject: [PATCH 05/10] fix(pipeline): verify refused publications without restaging --- src/orcapod/pipeline/repository.py | 22 ++++++--- .../test_pipeline/test_pipeline_repository.py | 49 +++++++++++++++++++ 2 files changed, 63 insertions(+), 8 deletions(-) diff --git a/src/orcapod/pipeline/repository.py b/src/orcapod/pipeline/repository.py index 2c686ecd9..162357c5e 100644 --- a/src/orcapod/pipeline/repository.py +++ b/src/orcapod/pipeline/repository.py @@ -146,8 +146,9 @@ def __init__(self, database: ArrowDatabaseProtocol) -> None: """Open a repository relative to the supplied database view.""" self._database: ArrowDatabaseProtocol = database self._context_key: str = get_default_context_key() + # A version alone can be verified but has no candidate to restage. self._retries: dict[ - tuple[tuple[str, ...], str], tuple[PipelinePublication, str] + tuple[tuple[str, ...], str], int | tuple[PipelinePublication, str] ] = {} def _record_id(self, name: tuple[str, ...], version: int) -> bytes: @@ -213,16 +214,19 @@ def publish( 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) + attempted_version = retry if isinstance(retry, int) else retry[0].version + 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: _ = self._retries.pop(retry_key, None) return _publication_from_row(row) - return self._write_publication( - replace(original, version=version), original_text - ) + if not isinstance(retry, int): + original, original_text = retry + return self._write_publication( + replace(original, version=version), original_text + ) + _ = self._retries.pop(retry_key, None) function_nodes = tuple( sorted( @@ -305,8 +309,10 @@ def restore_previous_retry() -> None: except Exception as exc: # 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 + if not accepted: + if not isinstance(exc, ValueError): + raise + self._retries[retry_key] = publication.version write_error = exc finally: if not accepted and write_error is None: diff --git a/tests/test_pipeline/test_pipeline_repository.py b/tests/test_pipeline/test_pipeline_repository.py index e21678116..056ee6531 100644 --- a/tests/test_pipeline/test_pipeline_repository.py +++ b/tests/test_pipeline/test_pipeline_repository.py @@ -869,6 +869,55 @@ def read_before_winner_commits( assert winner.list_versions("daily") == [initial, committed, newer] +@pytest.mark.parametrize("other_commits", [False, True], ids=["missing", "different"]) +def test_retry_uses_fresh_inputs_after_refused_add(other_commits: bool) -> None: + store = InMemoryArrowDatabase() + repository = PipelineRepository(store) + results = InMemoryArrowDatabase() + job = _run_job("daily", results, 20, run=False) + refused_time = datetime(2026, 1, 1, tzinfo=timezone.utc) + published_time = refused_time + timedelta(days=1) + read_error = OSError("readback failed") + with ( + patch("orcapod.pipeline.repository.datetime", wraps=datetime) as clock, + patch.object(store, "add_records", side_effect=ValueError("add refused")), + patch.object(store, "get_record_by_id", side_effect=read_error), + pytest.raises(ValueError, match="add refused") as refusal, + ): + clock.now.return_value = refused_time + _ = repository.publish( + job, author="Refused author", description="Refused description" + ) + assert refusal.value.__cause__ is read_error + + if other_commits: + other = PipelineRepository(store.at()) + _ = other.publish(_run_job("daily", results, 30)) + job.run() + with ( + patch("orcapod.pipeline.repository.datetime", wraps=datetime) as clock, + patch.object( + store, + "get_publisher_identity", + create=True, + return_value="Current identity", + ) as identity, + ): + clock.now.return_value = published_time + publication = repository.publish(job, description="Current description") + + identity.assert_called_once_with() + assert publication.version == (2 if other_commits else 1) + assert publication.author == "Current identity" + assert publication.description == "Current description" + assert publication.published_at == published_time + rows = repository._publication_rows(job.name, publication.version) + assert rows is not None + saved_run = json.loads(rows["saved_job"][0].as_py())["run"] + assert saved_run["run_id"] == job._run_record()["run_id"] + assert saved_run["status"] == "complete" + + @pytest.mark.parametrize("committed", [False, True], ids=["failed", "committed"]) def test_delta_auto_flush_error_preserves_publication_candidate( tmp_path: Path, committed: bool From 556ab8703a3b8bacffdd84169bd76f6165e0dfb9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 12:27:21 -0800 Subject: [PATCH 06/10] fix(pipeline): retire obsolete publication verification entries --- docs/concepts/pipeline-job.md | 5 ++- .../dev/specs/itl-1965-pipeline-repository.md | 5 ++- src/orcapod/pipeline/repository.py | 22 ++++++++++++- .../test_pipeline/test_pipeline_repository.py | 33 ++++++++++++++++++- 4 files changed, 61 insertions(+), 4 deletions(-) diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 079358122..ad03fb42f 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -783,7 +783,10 @@ 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 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. +matches. When the add is refused and readback fails, the repository keeps +only the attempted version for verification. If the retry finds no matching +publication, 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 diff --git a/docs/dev/specs/itl-1965-pipeline-repository.md b/docs/dev/specs/itl-1965-pipeline-repository.md index a31a1f47f..9c82733f5 100644 --- a/docs/dev/specs/itl-1965-pipeline-repository.md +++ b/docs/dev/specs/itl-1965-pipeline-repository.md @@ -144,7 +144,10 @@ 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. +matching job hash if the latest publication's hash differs. If the add was +refused and readback failed, the repository keeps only the attempted version +for verification. A retry that finds no matching committed row publishes +using the new call's saved state, author, description, and timestamp. ## Shared saved-job format diff --git a/src/orcapod/pipeline/repository.py b/src/orcapod/pipeline/repository.py index 162357c5e..f386faf5e 100644 --- a/src/orcapod/pipeline/repository.py +++ b/src/orcapod/pipeline/repository.py @@ -218,7 +218,9 @@ def publish( 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: + 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) return _publication_from_row(row) if not isinstance(retry, int): @@ -335,6 +337,9 @@ def restore_previous_retry() -> None: if write_error is not None: raise write_error raise RuntimeError(f"{location} is missing after publication.") + self._retire_refused_retries( + publication.name, publication.version, cast(str, row[_JOB_HASH]) + ) if accepted or matches: _ = self._retries.pop(retry_key, None) if not matches: @@ -343,6 +348,21 @@ def restore_previous_retry() -> None: ) return _publication_from_row(row) + def _retire_refused_retries( + self, name: tuple[str, ...], version: int, committed_hash: str + ) -> None: + """Discard verification entries that the committed row rules out.""" + obsolete = [ + (retry_name, retry_hash) + for (retry_name, retry_hash), retry in self._retries.items() + if isinstance(retry, int) + and retry == version + and retry_name == name + and retry_hash != committed_hash + ] + for key in obsolete: + del self._retries[key] + 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 diff --git a/tests/test_pipeline/test_pipeline_repository.py b/tests/test_pipeline/test_pipeline_repository.py index 056ee6531..220aaba93 100644 --- a/tests/test_pipeline/test_pipeline_repository.py +++ b/tests/test_pipeline/test_pipeline_repository.py @@ -863,7 +863,7 @@ def read_before_winner_commits( assert refusal.value.__cause__ is read_error committed = saved[0] - newer = winner.publish(_run_job("daily", results, 30)) + newer = loser.publish(_run_job("daily", results, 30)) assert loser.publish(pending) == committed assert not loser._retries assert winner.list_versions("daily") == [initial, committed, newer] @@ -918,6 +918,37 @@ def test_retry_uses_fresh_inputs_after_refused_add(other_commits: bool) -> None: assert saved_run["status"] == "complete" +def test_other_job_clears_refused_retry_at_resolved_version( + open_repository_database: Callable[[], ArrowDatabaseProtocol], +) -> None: + store = open_repository_database() + repository = PipelineRepository(store) + results = InMemoryArrowDatabase() + refused = _run_job("daily", results, 20) + other = _run_job("daily", results, 30) + + with ( + patch.object(store, "add_records", side_effect=ValueError("refused")), + patch.object(store, "get_record_by_id", side_effect=OSError("readback failed")), + pytest.raises(ValueError, match="refused"), + ): + _ = repository.publish( + refused, author="refused", description="refused description" + ) + + assert len(repository._retries) == 1 + saved = repository.publish( + other, author="different", description="different description" + ) + assert (saved.version, saved.author, saved.description) == ( + 1, + "different", + "different description", + ) + assert repository.list_versions("daily") == [saved] + assert not repository._retries + + @pytest.mark.parametrize("committed", [False, True], ids=["failed", "committed"]) def test_delta_auto_flush_error_preserves_publication_candidate( tmp_path: Path, committed: bool From c2dda1db8f257e2e4bf12783df25f86207d36d0c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 12:33:26 -0800 Subject: [PATCH 07/10] fix(pipeline): retire obsolete retries from latest publication --- src/orcapod/pipeline/repository.py | 8 +++-- .../test_pipeline/test_pipeline_repository.py | 30 +++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/orcapod/pipeline/repository.py b/src/orcapod/pipeline/repository.py index f386faf5e..8e4cc3bf6 100644 --- a/src/orcapod/pipeline/repository.py +++ b/src/orcapod/pipeline/repository.py @@ -208,9 +208,11 @@ def publish( job_hash = _publication_hash(document).to_string() latest = self._latest(name) retry_key = (name, job_hash) - if latest is not None and latest.job_hash == job_hash: - _ = self._retries.pop(retry_key, None) - return latest + if latest is not None: + self._retire_refused_retries(name, latest.version, latest.job_hash) + if latest.job_hash == job_hash: + _ = self._retries.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: diff --git a/tests/test_pipeline/test_pipeline_repository.py b/tests/test_pipeline/test_pipeline_repository.py index 220aaba93..9a2d02e6a 100644 --- a/tests/test_pipeline/test_pipeline_repository.py +++ b/tests/test_pipeline/test_pipeline_repository.py @@ -949,6 +949,36 @@ def test_other_job_clears_refused_retry_at_resolved_version( assert not repository._retries +@pytest.mark.parametrize("append", [False, True], ids=["no-op", "append"]) +def test_latest_read_retires_obsolete_verification( + open_repository_database: Callable[[], ArrowDatabaseProtocol], append: bool +) -> None: + store = open_repository_database() + repository = PipelineRepository(store) + other = PipelineRepository(open_repository_database()) + results = InMemoryArrowDatabase() + refused = _run_job("daily", results, 20) + different = _run_job("daily", results, 30) + + with ( + patch.object(store, "add_records", side_effect=ValueError("refused")), + patch.object(store, "get_record_by_id", side_effect=OSError("readback failed")), + pytest.raises(ValueError, match="refused"), + ): + _ = repository.publish(refused) + assert len(repository._retries) == 1 + + committed = other.publish(different, author="winner") + assert committed.version == 1 + if append: + after = repository.publish(_run_job("daily", results, 40), author="later") + assert (after.version, after.author) == (2, "later") + assert repository.list_versions("daily") == [committed, after] + else: + assert repository.publish(different) == committed + assert not repository._retries + + @pytest.mark.parametrize("committed", [False, True], ids=["failed", "committed"]) def test_delta_auto_flush_error_preserves_publication_candidate( tmp_path: Path, committed: bool From 04fe74fa710c41a6869b16b5c4d62990890d38fc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 12:39:35 -0800 Subject: [PATCH 08/10] fix(pipeline): reconcile refused retries against publication history --- src/orcapod/pipeline/repository.py | 41 ++++++++-------- .../test_pipeline/test_pipeline_repository.py | 47 ++++++++++++++++--- 2 files changed, 62 insertions(+), 26 deletions(-) diff --git a/src/orcapod/pipeline/repository.py b/src/orcapod/pipeline/repository.py index 8e4cc3bf6..7e5397fcf 100644 --- a/src/orcapod/pipeline/repository.py +++ b/src/orcapod/pipeline/repository.py @@ -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 @@ -206,13 +206,11 @@ 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: - self._retire_refused_retries(name, latest.version, latest.job_hash) - if latest.job_hash == job_hash: - _ = self._retries.pop(retry_key, None) - return latest + if latest is not None and latest.job_hash == job_hash: + _ = self._retries.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: @@ -221,7 +219,7 @@ def publish( if rows is not None and rows.num_rows: row = rows.to_pylist()[0] committed_hash = cast(str, row[_JOB_HASH]) - self._retire_refused_retries(name, attempted_version, committed_hash) + self._retire_refused_retries(name, {attempted_version: committed_hash}) if committed_hash == job_hash: _ = self._retries.pop(retry_key, None) return _publication_from_row(row) @@ -340,7 +338,7 @@ def restore_previous_retry() -> None: raise write_error raise RuntimeError(f"{location} is missing after publication.") self._retire_refused_retries( - publication.name, publication.version, cast(str, row[_JOB_HASH]) + publication.name, {publication.version: cast(str, row[_JOB_HASH])} ) if accepted or matches: _ = self._retries.pop(retry_key, None) @@ -351,16 +349,16 @@ def restore_previous_retry() -> None: return _publication_from_row(row) def _retire_refused_retries( - self, name: tuple[str, ...], version: int, committed_hash: str + self, name: tuple[str, ...], committed_hashes: Mapping[int, str] ) -> None: - """Discard verification entries that the committed row rules out.""" + """Discard verification entries disproved by committed version hashes.""" obsolete = [ (retry_name, retry_hash) for (retry_name, retry_hash), retry in self._retries.items() if isinstance(retry, int) - and retry == version and retry_name == name - and retry_hash != committed_hash + and retry in committed_hashes + and retry_hash != committed_hashes[retry] ] for key in obsolete: del self._retries[key] @@ -393,13 +391,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._retries: + 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( diff --git a/tests/test_pipeline/test_pipeline_repository.py b/tests/test_pipeline/test_pipeline_repository.py index 9a2d02e6a..6179dff43 100644 --- a/tests/test_pipeline/test_pipeline_repository.py +++ b/tests/test_pipeline/test_pipeline_repository.py @@ -506,9 +506,11 @@ def _check_overlapping_publications( shared_queue = isinstance(second_database, InMemoryArrowDatabase) winner: PipelinePublication | None = None - def read_before_first_write(name: tuple[str, ...]) -> PipelinePublication | None: + def read_before_first_write( + name: tuple[str, ...], *, for_publish: bool + ) -> PipelinePublication | None: nonlocal winner - latest = read_latest(name) + latest = read_latest(name, for_publish=for_publish) assert latest == original if not overlap_at_flush: winner = first.publish(first_update, author="first") @@ -583,9 +585,9 @@ def test_overlapping_publications_ignore_run_identity( committed: list[PipelinePublication] = [] def read_before_first_write( - name: tuple[str, ...], + name: tuple[str, ...], *, for_publish: bool ) -> PipelinePublication | None: - latest = read_latest(name) + latest = read_latest(name, for_publish=for_publish) assert latest == original committed.append(first.publish(completed, author="first")) return latest @@ -846,9 +848,9 @@ def test_retry_recovers_winner_after_add_refusal_and_failed_readback( saved: list[PipelinePublication] = [] def read_before_winner_commits( - name: tuple[str, ...], + name: tuple[str, ...], *, for_publish: bool ) -> PipelinePublication | None: - latest = read_latest(name) + latest = read_latest(name, for_publish=for_publish) assert latest == initial saved.append(winner.publish(completed, author="winner")) return latest @@ -979,6 +981,39 @@ def test_latest_read_retires_obsolete_verification( assert not repository._retries +def test_publish_history_retires_obsolete_verification( + open_repository_database: Callable[[], ArrowDatabaseProtocol], +) -> None: + store = open_repository_database() + repository = PipelineRepository(store) + other = PipelineRepository(open_repository_database()) + results = InMemoryArrowDatabase() + refused = _run_job("daily", results, 20) + + with ( + patch.object(store, "add_records", side_effect=ValueError("refused")), + patch.object(store, "get_record_by_id", side_effect=OSError("readback failed")), + pytest.raises(ValueError, match="refused"), + ): + _ = repository.publish(refused) + assert len(repository._retries) == 1 + + first = other.publish(_run_job("daily", results, 30)) + job = _run_job("daily", results, 40) + latest = other.publish(job) + assert (first.version, latest.version) == (1, 2) + assert repository.list_versions("daily") == [first, latest] + assert _totals(repository.load("daily", database=results)) == [41, 42] + assert len(repository._retries) == 1 + + with patch.object( + repository, "_publications", wraps=repository._publications + ) as reads: + assert repository.publish(job) == latest + reads.assert_called_once_with(("daily",)) + assert not repository._retries + + @pytest.mark.parametrize("committed", [False, True], ids=["failed", "committed"]) def test_delta_auto_flush_error_preserves_publication_candidate( tmp_path: Path, committed: bool From ca9cdf47f660091db93408c0e2635ee629cc79aa Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 13:21:04 -0800 Subject: [PATCH 09/10] fix(pipeline): snapshot retries during publication reconciliation --- src/orcapod/pipeline/repository.py | 4 +-- .../test_pipeline/test_pipeline_repository.py | 33 ++++++++++++++++++- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/src/orcapod/pipeline/repository.py b/src/orcapod/pipeline/repository.py index 7e5397fcf..e84794f42 100644 --- a/src/orcapod/pipeline/repository.py +++ b/src/orcapod/pipeline/repository.py @@ -354,14 +354,14 @@ def _retire_refused_retries( """Discard verification entries disproved by committed version hashes.""" obsolete = [ (retry_name, retry_hash) - for (retry_name, retry_hash), retry in self._retries.items() + for (retry_name, retry_hash), retry in list(self._retries.items()) if isinstance(retry, int) and retry_name == name and retry in committed_hashes and retry_hash != committed_hashes[retry] ] for key in obsolete: - del self._retries[key] + _ = self._retries.pop(key, None) def _publication_rows(self, name: tuple[str, ...], version: int) -> pa.Table | None: rows = self._database.get_record_by_id( diff --git a/tests/test_pipeline/test_pipeline_repository.py b/tests/test_pipeline/test_pipeline_repository.py index 6179dff43..3663e9281 100644 --- a/tests/test_pipeline/test_pipeline_repository.py +++ b/tests/test_pipeline/test_pipeline_repository.py @@ -12,7 +12,7 @@ from pathlib import Path from types import SimpleNamespace from typing import cast -from unittest.mock import patch +from unittest.mock import MagicMock, patch import pytest @@ -873,6 +873,7 @@ def read_before_winner_commits( @pytest.mark.parametrize("other_commits", [False, True], ids=["missing", "different"]) def test_retry_uses_fresh_inputs_after_refused_add(other_commits: bool) -> None: + """Use fresh inputs when a refused version has no matching committed job.""" store = InMemoryArrowDatabase() repository = PipelineRepository(store) results = InMemoryArrowDatabase() @@ -923,6 +924,7 @@ def test_retry_uses_fresh_inputs_after_refused_add(other_commits: bool) -> None: def test_other_job_clears_refused_retry_at_resolved_version( open_repository_database: Callable[[], ArrowDatabaseProtocol], ) -> None: + """Retire verification when a different job commits at the attempted version.""" store = open_repository_database() repository = PipelineRepository(store) results = InMemoryArrowDatabase() @@ -955,6 +957,7 @@ def test_other_job_clears_refused_retry_at_resolved_version( def test_latest_read_retires_obsolete_verification( open_repository_database: Callable[[], ArrowDatabaseProtocol], append: bool ) -> None: + """Retire verification when publish reads a different job as latest.""" store = open_repository_database() repository = PipelineRepository(store) other = PipelineRepository(open_repository_database()) @@ -984,6 +987,7 @@ def test_latest_read_retires_obsolete_verification( def test_publish_history_retires_obsolete_verification( open_repository_database: Callable[[], ArrowDatabaseProtocol], ) -> None: + """Retire obsolete verification for an older version only during publish.""" store = open_repository_database() repository = PipelineRepository(store) other = PipelineRepository(open_repository_database()) @@ -1014,6 +1018,33 @@ def test_publish_history_retires_obsolete_verification( assert not repository._retries +@pytest.mark.parametrize("remove_obsolete", [False, True], ids=["insert", "remove"]) +def test_retry_retirement_tolerates_map_changes_during_sweep( + remove_obsolete: bool, +) -> None: + """Mutate retry state after the sweep starts comparing committed hashes.""" + repository = PipelineRepository(InMemoryArrowDatabase()) + name = ("daily",) + obsolete = (name, "refused") + unrelated = (("weekly",), "other") + repository._retries[obsolete] = 1 + + def read_committed_hash(version: int) -> str: + assert version == 1 + if remove_obsolete: + del repository._retries[obsolete] + else: + repository._retries[unrelated] = 1 + return "winner" + + committed_hashes = MagicMock(spec=dict) + committed_hashes.__contains__.return_value = True + committed_hashes.__getitem__.side_effect = read_committed_hash + repository._retire_refused_retries(name, committed_hashes) + + assert repository._retries == ({} if remove_obsolete else {unrelated: 1}) + + @pytest.mark.parametrize("committed", [False, True], ids=["failed", "committed"]) def test_delta_auto_flush_error_preserves_publication_candidate( tmp_path: Path, committed: bool From e301dcd2fa312ee4963a0155b0e8ef187d29242d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 13:30:50 -0800 Subject: [PATCH 10/10] fix(pipeline): preserve accepted candidates across refused restages --- docs/concepts/pipeline-job.md | 7 +- .../dev/specs/itl-1965-pipeline-repository.md | 7 +- src/orcapod/pipeline/repository.py | 55 +++++----- .../test_pipeline/test_pipeline_repository.py | 101 +++++++++++++++--- 4 files changed, 128 insertions(+), 42 deletions(-) diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 0fb43ebfc..456382c46 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -784,9 +784,10 @@ repository instance to reuse its original saved text and publication metadata. 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 -only the attempted version for verification. If the retry finds no matching -publication, it publishes using the new call's saved state, author, -description, and timestamp. +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 diff --git a/docs/dev/specs/itl-1965-pipeline-repository.md b/docs/dev/specs/itl-1965-pipeline-repository.md index 9c82733f5..48dd2e279 100644 --- a/docs/dev/specs/itl-1965-pipeline-repository.md +++ b/docs/dev/specs/itl-1965-pipeline-repository.md @@ -145,9 +145,10 @@ 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 only the attempted version -for verification. A retry that finds no matching committed row publishes -using the new call's saved state, author, description, and timestamp. +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 diff --git a/src/orcapod/pipeline/repository.py b/src/orcapod/pipeline/repository.py index e5a07288b..1ff9df6e0 100644 --- a/src/orcapod/pipeline/repository.py +++ b/src/orcapod/pipeline/repository.py @@ -146,10 +146,12 @@ def __init__(self, database: ArrowDatabaseProtocol) -> None: """Open a repository relative to the supplied database view.""" self._database: ArrowDatabaseProtocol = database self._context_key: str = get_default_context_key() - # A version alone can be verified but has no candidate to restage. self._retries: dict[ - tuple[tuple[str, ...], str], int | tuple[PipelinePublication, str] + 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.""" @@ -210,11 +212,15 @@ def publish( 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: - attempted_version = retry if isinstance(retry, int) else retry[0].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] @@ -222,13 +228,14 @@ def publish( 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) - if not isinstance(retry, int): - original, original_text = retry - return self._write_publication( - replace(original, version=version), original_text - ) - _ = self._retries.pop(retry_key, None) + _ = 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 + ) function_nodes = tuple( sorted( @@ -311,13 +318,11 @@ def restore_previous_retry() -> None: except Exception as exc: # A backend can refuse an already committed ID before staging it. # Check the committed row before classifying that ValueError. - if not accepted: - if not isinstance(exc, ValueError): - raise - self._retries[retry_key] = publication.version + if not accepted and not isinstance(exc, ValueError): + raise write_error = exc finally: - if not accepted and write_error is None: + if not accepted: restore_previous_retry() attempt.finish(committed=False) @@ -326,12 +331,12 @@ def restore_previous_retry() -> None: rows = self._publication_rows(publication.name, publication.version) except Exception as read_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 - if not accepted and not matches: - restore_previous_retry() location = f"Pipeline {publication.name!r} at version {publication.version}" if row is None: if write_error is not None: @@ -342,6 +347,7 @@ def restore_previous_retry() -> None: ) 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." @@ -354,14 +360,15 @@ def _retire_refused_retries( """Discard verification entries disproved by committed version hashes.""" obsolete = [ (retry_name, retry_hash) - for (retry_name, retry_hash), retry in list(self._retries.items()) - if isinstance(retry, int) - and retry_name == name - and retry in committed_hashes - and retry_hash != committed_hashes[retry] + 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._retries.pop(key, None) + _ = 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( @@ -396,7 +403,7 @@ def _latest( ) -> PipelinePublication | None: """Read the highest version and reconcile verification entries on publish.""" publications = self._publications(name) - if for_publish and self._retries: + if for_publish and self._refused_versions: self._retire_refused_retries( name, {row.version: row.job_hash for row in publications} ) diff --git a/tests/test_pipeline/test_pipeline_repository.py b/tests/test_pipeline/test_pipeline_repository.py index 93e5430a5..77cad2dec 100644 --- a/tests/test_pipeline/test_pipeline_repository.py +++ b/tests/test_pipeline/test_pipeline_repository.py @@ -988,7 +988,7 @@ def read_before_winner_commits( committed = saved[0] newer = loser.publish(_run_job("daily", results, 30)) assert loser.publish(pending) == committed - assert not loser._retries + assert not loser._refused_versions assert winner.list_versions("daily") == [initial, committed, newer] @@ -1061,7 +1061,7 @@ def test_other_job_clears_refused_retry_at_resolved_version( refused, author="refused", description="refused description" ) - assert len(repository._retries) == 1 + assert len(repository._refused_versions) == 1 saved = repository.publish( other, author="different", description="different description" ) @@ -1071,7 +1071,7 @@ def test_other_job_clears_refused_retry_at_resolved_version( "different description", ) assert repository.list_versions("daily") == [saved] - assert not repository._retries + assert not repository._refused_versions @pytest.mark.parametrize("append", [False, True], ids=["no-op", "append"]) @@ -1092,7 +1092,7 @@ def test_latest_read_retires_obsolete_verification( pytest.raises(ValueError, match="refused"), ): _ = repository.publish(refused) - assert len(repository._retries) == 1 + assert len(repository._refused_versions) == 1 committed = other.publish(different, author="winner") assert committed.version == 1 @@ -1102,7 +1102,7 @@ def test_latest_read_retires_obsolete_verification( assert repository.list_versions("daily") == [committed, after] else: assert repository.publish(different) == committed - assert not repository._retries + assert not repository._refused_versions def test_publish_history_retires_obsolete_verification( @@ -1121,7 +1121,7 @@ def test_publish_history_retires_obsolete_verification( pytest.raises(ValueError, match="refused"), ): _ = repository.publish(refused) - assert len(repository._retries) == 1 + assert len(repository._refused_versions) == 1 first = other.publish(_run_job("daily", results, 30)) job = _run_job("daily", results, 40) @@ -1129,14 +1129,14 @@ def test_publish_history_retires_obsolete_verification( assert (first.version, latest.version) == (1, 2) assert repository.list_versions("daily") == [first, latest] assert _totals(repository.load("daily", database=results)) == [41, 42] - assert len(repository._retries) == 1 + assert len(repository._refused_versions) == 1 with patch.object( repository, "_publications", wraps=repository._publications ) as reads: assert repository.publish(job) == latest reads.assert_called_once_with(("daily",)) - assert not repository._retries + assert not repository._refused_versions @pytest.mark.parametrize("remove_obsolete", [False, True], ids=["insert", "remove"]) @@ -1148,14 +1148,14 @@ def test_retry_retirement_tolerates_map_changes_during_sweep( name = ("daily",) obsolete = (name, "refused") unrelated = (("weekly",), "other") - repository._retries[obsolete] = 1 + repository._refused_versions[obsolete] = 1 def read_committed_hash(version: int) -> str: assert version == 1 if remove_obsolete: - del repository._retries[obsolete] + del repository._refused_versions[obsolete] else: - repository._retries[unrelated] = 1 + repository._refused_versions[unrelated] = 1 return "winner" committed_hashes = MagicMock(spec=dict) @@ -1163,7 +1163,84 @@ def read_committed_hash(version: int) -> str: committed_hashes.__getitem__.side_effect = read_committed_hash repository._retire_refused_retries(name, committed_hashes) - assert repository._retries == ({} if remove_obsolete else {unrelated: 1}) + assert repository._refused_versions == ({} if remove_obsolete else {unrelated: 1}) + + +@pytest.mark.parametrize( + "scenario", ["same-version", "next-version", "matched-restage"] +) +def test_accepted_retry_survives_refused_restage_with_failed_readback( + open_repository_database: Callable[[], ArrowDatabaseProtocol], + scenario: str, +) -> None: + """Keep accepted metadata while checking a refused restage for a winner.""" + store = open_repository_database() + repository = PipelineRepository(store) + results = InMemoryArrowDatabase() + candidate = _run_job("daily", results, 20, run=False) + original_text = candidate._saved_text() + original_time = datetime(2026, 1, 1, tzinfo=timezone.utc) + with ( + patch.object(store, "flush_batch", side_effect=OSError("initial flush failed")), + patch("orcapod.pipeline.repository.datetime", wraps=datetime) as clock, + patch.object(candidate, "_saved_text", return_value=original_text), + pytest.raises(OSError, match="initial flush failed"), + ): + clock.now.return_value = original_time + _ = repository.publish( + candidate, author="original", description="first description" + ) + assert repository.list_versions("daily") == [] + + other = PipelineRepository(open_repository_database()) + history: list[PipelinePublication] = [] + restage_version = 1 + if scenario != "same-version": + history.append(other.publish(_run_job("daily", results, 30))) + restage_version = 2 + + committed_original = repository._publication_rows(candidate.name, 1) + read_error = OSError("restage readback failed") + with ( + patch.object(store, "add_records", side_effect=ValueError("restage refused")), + patch.object( + repository, + "_publication_rows", + side_effect=[committed_original, read_error], + ), + pytest.raises(ValueError, match="restage refused") as refusal, + ): + _ = repository.publish( + candidate, author="second", description="second description" + ) + assert refusal.value.__cause__ is read_error + assert repository.list_versions("daily") == history + + candidate.run() + if scenario == "matched-restage": + winner = other.publish(candidate, author="winner") + newer = other.publish(_run_job("daily", results, 40)) + assert winner.version == restage_version + assert repository.publish(candidate, author="third") == winner + assert repository.list_versions("daily") == [*history, winner, newer] + else: + with patch("orcapod.pipeline.repository.datetime", wraps=datetime) as clock: + clock.now.return_value = original_time + timedelta(days=1) + saved = repository.publish( + candidate, author="third", description="third description" + ) + assert saved.version == restage_version + assert (saved.author, saved.description, saved.published_at) == ( + "original", + "first description", + original_time, + ) + found = repository._publication_rows(candidate.name, restage_version) + assert found is not None + assert found["saved_job"][0].as_py() == original_text + assert repository.list_versions("daily") == [*history, saved] + assert not repository._retries + assert not repository._refused_versions @pytest.mark.parametrize("committed", [False, True], ids=["failed", "committed"])