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/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 51da440ec..456382c46 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -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 diff --git a/docs/dev/specs/itl-1965-pipeline-repository.md b/docs/dev/specs/itl-1965-pipeline-repository.md index c2a66a7a8..48dd2e279 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,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 diff --git a/src/orcapod/pipeline/repository.py b/src/orcapod/pipeline/repository.py index 93089d357..6aa718d35 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 @@ -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.""" @@ -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 ) @@ -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( @@ -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. @@ -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 @@ -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( diff --git a/tests/test_pipeline/test_pipeline_repository.py b/tests/test_pipeline/test_pipeline_repository.py index 01999d2e7..24b8b469e 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 pyarrow as pa import pytest @@ -33,7 +33,7 @@ SQLiteConnector, ) from orcapod.errors import SpiralDBWritePermissionError -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, reuse_repository_database from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.sources import DictSource @@ -599,12 +599,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 ) @@ -612,6 +614,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()) @@ -620,18 +623,20 @@ 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) 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) + winner = first.publish(first_update, author="first") return latest def flush_after_first_write(path: tuple[str, ...]) -> None: @@ -644,41 +649,45 @@ 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] -@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 ( @@ -689,32 +698,62 @@ 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, ...], *, for_publish: bool + ) -> PipelinePublication | None: + latest = read_latest(name, for_publish=for_publish) + 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: + 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"]) @@ -863,6 +902,349 @@ 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] + + +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, ...], *, for_publish: bool + ) -> PipelinePublication | None: + latest = read_latest(name, for_publish=for_publish) + 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 = loser.publish(_run_job("daily", results, 30)) + assert loser.publish(pending) == committed + assert not loser._refused_versions + 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: + """Use fresh inputs when a refused version has no matching committed job.""" + 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" + + +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() + 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._refused_versions) == 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._refused_versions + + +@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: + """Retire verification when publish reads a different job as latest.""" + 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._refused_versions) == 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._refused_versions + + +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()) + 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._refused_versions) == 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._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._refused_versions + + +@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._refused_versions[obsolete] = 1 + + def read_committed_hash(version: int) -> str: + assert version == 1 + if remove_obsolete: + del repository._refused_versions[obsolete] + else: + repository._refused_versions[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._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"]) def test_delta_auto_flush_error_preserves_publication_candidate( tmp_path: Path, committed: bool