From 4085f236f3442b9de70a612784a051db19ab1d06 Mon Sep 17 00:00:00 2001 From: Marius Ciepluch <11855163+norandom@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:39:10 +0100 Subject: [PATCH] feat(valid-detection-benchmark): 8.6 resume exact pre-spend and post-spend workflows without changing authority --- .../specs/valid-detection-benchmark/tasks.md | 2 +- benchmarks/valid/sealed_retry.py | 779 +++++++++++++++++ benchmarks/valid/sealed_retry_recovery.py | 123 +++ tests/test_valid_benchmark_sealed_retry.py | 823 ++++++++++++++++++ 4 files changed, 1726 insertions(+), 1 deletion(-) create mode 100644 benchmarks/valid/sealed_retry.py create mode 100644 benchmarks/valid/sealed_retry_recovery.py create mode 100644 tests/test_valid_benchmark_sealed_retry.py diff --git a/.kiro/specs/valid-detection-benchmark/tasks.md b/.kiro/specs/valid-detection-benchmark/tasks.md index 112c750e..f9e13489 100644 --- a/.kiro/specs/valid-detection-benchmark/tasks.md +++ b/.kiro/specs/valid-detection-benchmark/tasks.md @@ -268,7 +268,7 @@ - Done when missing one planned arm/report blocks completion, baseline identity is complete, and a valid replay reproduces every scoped decision without legacy scoring helpers. - _Requirements: 6.2, 6.3, 6.4, 6.5, 8.1, 8.2, 8.3, 8.6, 9.1, 9.2, 9.6, 9.7, 10.1_ - _Boundary: Admission Orchestrator, Scoped Admission V3 Consumer_ -- [ ] 8.6 Resume exact pre-spend and post-spend workflows without changing authority +- [x] 8.6 Resume exact pre-spend and post-spend workflows without changing authority - Rebuild the validated workflow chain after scratch loss, resolve only the retry authority selected by its CAS head, and compare the candidate/current identity before checkpoint resolution or an adapter call; never accept an original registered identity from the caller. - Resume pre-spend only from matching sealed checkpoints and unchanged population, freeze, admission, plan, arm, bundle, input, budget, environment, destination, and checkpoint-slot identities; leave custody available after execution impairment. - For an exact independently reviewed identity-bound mismatch disposition, append and reread terminal lifecycle state before returning `IDENTITY_CHANGED`; missing, invalid, malformed, or untrusted mismatch evidence fails closed before execution without claiming retirement or mutating lifecycle. diff --git a/benchmarks/valid/sealed_retry.py b/benchmarks/valid/sealed_retry.py new file mode 100644 index 00000000..45090360 --- /dev/null +++ b/benchmarks/valid/sealed_retry.py @@ -0,0 +1,779 @@ +"""Task 8.6 exact automatic retry over sealed completed component checkpoints.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, replace +from enum import StrEnum + +from benchmarks.valid.admission_execution import ( + AdmissionExecutionError, + AdmissionExecutionReason, + resolve_current_retry_authority, +) +from benchmarks.valid.admission_orchestrator import AdmissionOrchestratorError, AutomaticRetryAuthorityV1 +from benchmarks.valid.arm_contract import ArmRegistryError, RegisteredEvaluationPlanV1 +from benchmarks.valid.artifact_repository import ArtifactReadAuthority, S3ArtifactRepository +from benchmarks.valid.durable_custody_store import S3DurableCustodyStore +from benchmarks.valid.isolated_execution_bundle import LabelBlindExecutionBundleV1 +from benchmarks.valid.lifecycle import ( + BaselineLifecycleAuthority, + LifecycleError, + PopulationLifecycleKind, + PopulationLifecycleState, + decode_lifecycle_event, + reviewed_retirement_event, +) +from benchmarks.valid.observation_checkpoint import ( + ArmCheckpointResultV1, + CheckpointSelectorV1, + CheckpointStatus, + ObservationCheckpointAdapter, + execute_or_resume_component, +) +from benchmarks.valid.ordinary_change_contract import OrdinarySelectionV1 +from benchmarks.valid.population_label_blind_contract import LabelBlindPopulationManifestV3 +from benchmarks.valid.population_material_contract import PublicPopulationMaterialManifestV1 +from benchmarks.valid.replacement_artifact_contract import ArtifactAccessClass, ArtifactKind, ArtifactReference +from benchmarks.valid.sealed_diagnostics import ( + SealedDiagnosticError, + _reference_value, + persist_private_authority_event, +) +from benchmarks.valid.workflow_journal import S3WorkflowJournal +from openultrasast.core import canonical +from openultrasast.core.canonical import JsonValue +from openultrasast.core.custody import PopulationStatus +from openultrasast.core.evaluation_measurement import ArmKindV3 + +AUTOMATIC_RETRY_SCHEMA = "openultrasast.valid-detection-benchmark.automatic-retry.v1" +AUTOMATIC_RETRY_RESULT_SCHEMA = "openultrasast.valid-detection-benchmark.automatic-retry-result.v1" +RETRY_MISMATCH_AUTHORITY_SCHEMA = "openultrasast.valid-detection-benchmark.retry-mismatch-authority.v1" +_DIGEST = re.compile(r"[0-9a-f]{64}") + + +class AutomaticRetryStatus(StrEnum): + RESUMED = "resumed" + IMPAIRED = "impaired" + BLOCKED = "blocked" + + +class AutomaticRetryReason(StrEnum): + NONE = "none" + IDENTITY_CHANGED = "identity_changed" + CHECKPOINT_IMPAIRED = "checkpoint_impaired" + LIFECYCLE_INELIGIBLE = "lifecycle_ineligible" + + +class AutomaticRetryAuthorityReason(StrEnum): + INVALID_REQUEST = "invalid_request" + AUTHORITY_UNRESOLVED = "authority_unresolved" + AUTHORITY_SUBSTITUTED = "authority_substituted" + MISMATCH_AUTHORITY_REQUIRED = "mismatch_authority_required" + AUTHORITY_PERSISTENCE_FAILED = "authority_persistence_failed" + SPEND_ALREADY_COMMITTED = "spend_already_committed" + CUSTODY_NOT_SPENT = "custody_not_spent" + + +class AutomaticRetryError(RuntimeError): + """Closed retry refusal before detector execution.""" + + def __init__(self, reason: AutomaticRetryAuthorityReason) -> None: + self.reason = reason + super().__init__(f"automatic_retry_{reason.value}") + + +def _digest(value: object) -> str: + if type(value) is not str or _DIGEST.fullmatch(value) is None: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + return value + + +@dataclass(frozen=True) +class AutomaticRetryIdentityV1: + population_digest: str + freeze_digest: str + admission_identity_digest: str + plan_digest: str + arm_registration_digests: tuple[str, ...] + bundle_digests: tuple[str, ...] + input_set_digest: str + budget_digests: tuple[str, ...] + environment_digests: tuple[str, ...] + output_destination_digests: tuple[str, ...] + checkpoint_selectors: tuple[CheckpointSelectorV1, ...] + retry_digest: str + + def __post_init__(self) -> None: + if type(self) is not AutomaticRetryIdentityV1: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + for value in ( + self.population_digest, + self.freeze_digest, + self.admission_identity_digest, + self.plan_digest, + self.input_set_digest, + ): + _digest(value) + _validate_retry_rows(self) + expected = canonical.content_digest(_retry_value(self, include_digest=False)) + if not self.retry_digest: + object.__setattr__(self, "retry_digest", expected) + elif _digest(self.retry_digest) != expected: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + + +def _validate_retry_rows(value: AutomaticRetryIdentityV1) -> None: + rows = ( + value.arm_registration_digests, + value.bundle_digests, + value.budget_digests, + value.environment_digests, + value.output_destination_digests, + value.checkpoint_selectors, + ) + size = len(value.arm_registration_digests) + if not size or any(type(row) is not tuple or len(row) != size for row in rows): + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + for row in rows[:-1]: + for item in row: + _digest(item) + if len(set(value.arm_registration_digests)) != size or len(set(value.bundle_digests)) != size: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + if any(type(selector) is not CheckpointSelectorV1 for selector in value.checkpoint_selectors): + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + for selector in value.checkpoint_selectors: + selector.__post_init__() + identities = tuple( + (selector.reference.content_digest, selector.checkpoint_digest) for selector in value.checkpoint_selectors + ) + if len(set(identities)) != size: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + + +def _retry_value(value: AutomaticRetryIdentityV1, *, include_digest: bool) -> dict[str, JsonValue]: + result: dict[str, JsonValue] = { + "schema_version": AUTOMATIC_RETRY_SCHEMA, + "population_digest": value.population_digest, + "freeze_digest": value.freeze_digest, + "admission_identity_digest": value.admission_identity_digest, + "plan_digest": value.plan_digest, + "arm_registration_digests": value.arm_registration_digests, + "bundle_digests": value.bundle_digests, + "input_set_digest": value.input_set_digest, + "budget_digests": value.budget_digests, + "environment_digests": value.environment_digests, + "output_destination_digests": value.output_destination_digests, + "checkpoint_selectors": tuple( + { + "checkpoint_digest": selector.checkpoint_digest, + "reference": _reference_value(selector.reference), + } + for selector in value.checkpoint_selectors + ), + } + if include_digest: + result["retry_digest"] = value.retry_digest + return result + + +def automatic_retry_identity_bytes(value: AutomaticRetryIdentityV1) -> bytes: + value.__post_init__() + return canonical.canonical_bytes(_retry_value(value, include_digest=True)) + + +def build_automatic_retry_identity( + population_digest: str, + freeze_digest: str, + admission_identity_digest: str, + bundles: tuple[LabelBlindExecutionBundleV1, ...], + checkpoint_selectors: tuple[CheckpointSelectorV1, ...], +) -> AutomaticRetryIdentityV1: + if type(bundles) is not tuple or not bundles or any( + type(bundle) is not LabelBlindExecutionBundleV1 for bundle in bundles + ): + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + if type(checkpoint_selectors) is not tuple or len(checkpoint_selectors) != len(bundles): + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + for bundle in bundles: + bundle.__post_init__() + if tuple(bundle.arm.arm_id for bundle in bundles) != tuple(sorted(bundle.arm.arm_id for bundle in bundles)): + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + shared = { + (bundle.population_digest, bundle.freeze_digest, bundle.plan_digest, bundle.input_set_digest) + for bundle in bundles + } + if len(shared) != 1 or shared.pop() != ( + population_digest, + freeze_digest, + bundles[0].plan_digest, + bundles[0].input_set_digest, + ): + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + return AutomaticRetryIdentityV1( + population_digest, + freeze_digest, + admission_identity_digest, + bundles[0].plan_digest, + tuple(bundle.arm.registration_digest for bundle in bundles), + tuple(bundle.bundle_digest for bundle in bundles), + bundles[0].input_set_digest, + tuple(bundle.budget.budget_digest for bundle in bundles), + tuple(bundle.environment.environment_digest for bundle in bundles), + tuple(bundle.output_destination.destination_digest for bundle in bundles), + checkpoint_selectors, + "", + ) + + +def _actual_retry_identity( + candidate: AutomaticRetryIdentityV1, + bundles: tuple[LabelBlindExecutionBundleV1, ...], + checkpoint_selectors: tuple[CheckpointSelectorV1, ...], + plan: RegisteredEvaluationPlanV1, +) -> AutomaticRetryIdentityV1: + try: + if type(plan) is not RegisteredEvaluationPlanV1: + raise ArmRegistryError("retry plan must use exact RegisteredEvaluationPlanV1") + plan.__post_init__() + except (ArmRegistryError, TypeError, ValueError): + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) from None + actual = build_automatic_retry_identity( + bundles[0].population_digest, + bundles[0].freeze_digest, + candidate.admission_identity_digest, + bundles, + checkpoint_selectors, + ) + if actual.plan_digest == plan.plan_digest: + return actual + return replace(actual, plan_digest=plan.plan_digest, retry_digest="") + + +def resolve_head_selected_retry_authority( + journal: S3WorkflowJournal, + repository: S3ArtifactRepository, + access_policy_digest: str, + workflow_digest: str, +) -> AutomaticRetryAuthorityV1: + """Resolve the original retry authority only through the current CAS head.""" + try: + return resolve_current_retry_authority(journal, repository, access_policy_digest, workflow_digest) + except AdmissionExecutionError as error: + if error.reason is AdmissionExecutionReason.AUTHORITY_UNRESOLVED: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.AUTHORITY_UNRESOLVED) from None + raise AutomaticRetryError(AutomaticRetryAuthorityReason.AUTHORITY_SUBSTITUTED) from None + + +def retry_identity_matches_authority( + candidate: AutomaticRetryIdentityV1, + bundles: tuple[LabelBlindExecutionBundleV1, ...], + plan: RegisteredEvaluationPlanV1, + authority: AutomaticRetryAuthorityV1, +) -> bool: + """Compare the candidate identity against every head-selected dimension.""" + if ( + type(candidate) is not AutomaticRetryIdentityV1 + or type(bundles) is not tuple + or not bundles + or type(plan) is not RegisteredEvaluationPlanV1 + or type(authority) is not AutomaticRetryAuthorityV1 + ): + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + try: + plan.__post_init__() + authority.__post_init__() + except (ArmRegistryError, AdmissionOrchestratorError, TypeError, ValueError): + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) from None + return all(left == right for left, right in _identity_rows(candidate, bundles, plan, authority)) + + +def _identity_rows( + candidate: AutomaticRetryIdentityV1, + bundles: tuple[LabelBlindExecutionBundleV1, ...], + plan: RegisteredEvaluationPlanV1, + authority: AutomaticRetryAuthorityV1, +) -> tuple[tuple[object, object], ...]: + components = tuple( + sorted(row.arm_id for row in plan.registrations if row.configuration.kind is ArmKindV3.COMPONENT) + ) + registered = {row.arm_id: row.registration_digest for row in plan.registrations} + return ( + ( + ( + candidate.population_digest, + candidate.freeze_digest, + candidate.admission_identity_digest, + candidate.plan_digest, + plan.plan_digest, + ), + ( + authority.population_digest, + authority.freeze_digest, + authority.admission_identity_digest, + authority.plan_digest, + authority.plan_digest, + ), + ), + (tuple(row.arm_id for row in plan.registrations), authority.ordered_arm_ids), + (tuple(bundle.arm.arm_id for bundle in bundles), components), + (tuple(registered.get(bundle.arm.arm_id, "") for bundle in bundles), candidate.arm_registration_digests), + (candidate.bundle_digests, authority.ordered_bundle_digests), + (candidate.budget_digests, authority.ordered_budget_digests), + (candidate.environment_digests, authority.ordered_environment_digests), + (candidate.output_destination_digests, authority.ordered_destination_digests), + (len(authority.ordered_input_set_digests), len(bundles)), + (tuple(digest for digest in authority.ordered_input_set_digests if digest != candidate.input_set_digest), ()), + ( + tuple(slot.slot_digest for slot in plan.declaration.expected_observation_slots), + authority.ordered_checkpoint_slot_digests, + ), + ) + + +def _mismatch_evidence(registered: str, candidate: str, actual: str, supplied_plan: str) -> str: + return canonical.content_digest( + { + "registered_retry_digest": registered, + "candidate_retry_digest": candidate, + "actual_retry_digest": actual, + "supplied_plan_digest": supplied_plan, + } + ) + + +@dataclass(frozen=True) +class RetryMismatchAuthorityV1: + population_digest: str + freeze_digest: str + predecessor_digest: str + component_index: int + registered_retry_digest: str + candidate_retry_digest: str + actual_retry_digest: str + supplied_plan_digest: str + evidence_digest: str + retirement_event_content: bytes + retirement_event_digest: str + authority_digest: str + + def __post_init__(self) -> None: + if type(self) is not RetryMismatchAuthorityV1 or type(self.component_index) is not int: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + if self.component_index < 0 or type(self.retirement_event_content) is not bytes: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + for value in ( + self.population_digest, + self.freeze_digest, + self.predecessor_digest, + self.registered_retry_digest, + self.candidate_retry_digest, + self.actual_retry_digest, + self.supplied_plan_digest, + self.evidence_digest, + self.retirement_event_digest, + ): + _digest(value) + expected_evidence = _mismatch_evidence( + self.registered_retry_digest, + self.candidate_retry_digest, + self.actual_retry_digest, + self.supplied_plan_digest, + ) + if self.evidence_digest != expected_evidence: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + self._validate_event() + expected = canonical.content_digest(_mismatch_authority_value(self, include_digest=False)) + if not self.authority_digest: + object.__setattr__(self, "authority_digest", expected) + elif _digest(self.authority_digest) != expected: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + + def _validate_event(self) -> None: + try: + event = decode_lifecycle_event(self.retirement_event_content) + valid = ( + event.kind is PopulationLifecycleKind.RETIRED + and event.predecessor_digest == self.predecessor_digest + and event.population_digest == self.population_digest + and event.freeze_digest == self.freeze_digest + and event.evidence_digest == self.evidence_digest + and event.reason_code == "policy_invalidated" + and event.event_digest == self.retirement_event_digest + ) + except (LifecycleError, TypeError, ValueError, RecursionError): + valid = False + if not valid: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + + +def _mismatch_authority_value(value: RetryMismatchAuthorityV1, *, include_digest: bool) -> dict[str, JsonValue]: + result: dict[str, JsonValue] = { + "schema_version": RETRY_MISMATCH_AUTHORITY_SCHEMA, + "population_digest": value.population_digest, + "freeze_digest": value.freeze_digest, + "predecessor_digest": value.predecessor_digest, + "component_index": value.component_index, + "registered_retry_digest": value.registered_retry_digest, + "candidate_retry_digest": value.candidate_retry_digest, + "actual_retry_digest": value.actual_retry_digest, + "supplied_plan_digest": value.supplied_plan_digest, + "evidence_digest": value.evidence_digest, + "retirement_event_digest": value.retirement_event_digest, + } + if include_digest: + result["authority_digest"] = value.authority_digest + return result + + +def review_retry_mismatch_authority( + authority: AutomaticRetryAuthorityV1, + candidate: AutomaticRetryIdentityV1, + *, + bundles: tuple[LabelBlindExecutionBundleV1, ...], + checkpoint_selectors: tuple[CheckpointSelectorV1, ...], + plan: RegisteredEvaluationPlanV1, + lifecycle_authority: BaselineLifecycleAuthority, + producer_identity: str, + reviewer_identity: str, + conflict_disclosed: bool, + policy_digest: str, + component_index: int = 0, +) -> RetryMismatchAuthorityV1: + """Independently review one identity-bound mismatch disposition.""" + if type(candidate) is not AutomaticRetryIdentityV1: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + candidate.__post_init__() + actual = _actual_retry_identity(candidate, bundles, checkpoint_selectors, plan) + if actual.retry_digest == candidate.retry_digest and retry_identity_matches_authority( + candidate, bundles, plan, authority + ): + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + try: + active = lifecycle_authority.require_admission_eligible(authority.population_digest, authority.freeze_digest) + evidence = _mismatch_evidence( + authority.authority_digest, + candidate.retry_digest, + actual.retry_digest, + plan.plan_digest, + ) + content = reviewed_retirement_event( + predecessor_digest=active.head_event_digest, + population_digest=authority.population_digest, + freeze_digest=authority.freeze_digest, + evidence_digest=evidence, + reason_code="policy_invalidated", + producer_identity=producer_identity, + reviewer_identity=reviewer_identity, + conflict_disclosed=conflict_disclosed, + policy_digest=policy_digest, + ) + event = decode_lifecycle_event(content) + except (LifecycleError, TypeError, ValueError, RecursionError): + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) from None + return RetryMismatchAuthorityV1( + authority.population_digest, + authority.freeze_digest, + active.head_event_digest, + component_index, + authority.authority_digest, + candidate.retry_digest, + actual.retry_digest, + plan.plan_digest, + evidence, + content, + event.event_digest, + "", + ) + + +@dataclass(frozen=True) +class AutomaticRetryResultV1: + status: AutomaticRetryStatus + reason: AutomaticRetryReason + retry_digest: str + component_index: int + checkpoint: ArmCheckpointResultV1 | None + lifecycle_reference: ArtifactReference | None + lifecycle_projection_digest: str + result_digest: str + + def __post_init__(self) -> None: + if ( + type(self) is not AutomaticRetryResultV1 + or type(self.status) is not AutomaticRetryStatus + or type(self.reason) is not AutomaticRetryReason + ): + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + _digest(self.retry_digest) + if type(self.component_index) is not int or self.component_index < 0: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + if self.checkpoint is not None: + self.checkpoint.__post_init__() + if self.lifecycle_reference is not None: + self.lifecycle_reference.__post_init__() + if self.lifecycle_projection_digest: + _digest(self.lifecycle_projection_digest) + _validate_result_state(self) + expected = canonical.content_digest(_result_value(self, include_digest=False)) + if not self.result_digest: + object.__setattr__(self, "result_digest", expected) + elif _digest(self.result_digest) != expected: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + + +def _validate_result_state(value: AutomaticRetryResultV1) -> None: + checkpoint = value.checkpoint + lifecycle_reference = value.lifecycle_reference + if value.status is AutomaticRetryStatus.RESUMED: + valid = value.reason is AutomaticRetryReason.NONE and checkpoint is not None + valid = valid and checkpoint is not None and checkpoint.status is CheckpointStatus.COMPLETE + valid = valid and value.lifecycle_reference is None and not value.lifecycle_projection_digest + elif value.status is AutomaticRetryStatus.IMPAIRED: + valid = value.reason is AutomaticRetryReason.CHECKPOINT_IMPAIRED and checkpoint is not None + valid = valid and checkpoint is not None and checkpoint.status is CheckpointStatus.IMPAIRED + valid = valid and value.lifecycle_reference is None and not value.lifecycle_projection_digest + else: + valid = value.reason in {AutomaticRetryReason.IDENTITY_CHANGED, AutomaticRetryReason.LIFECYCLE_INELIGIBLE} + valid = valid and value.checkpoint is None + if value.reason is AutomaticRetryReason.IDENTITY_CHANGED: + valid = valid and lifecycle_reference is not None and bool(value.lifecycle_projection_digest) + if lifecycle_reference is not None: + valid = valid and lifecycle_reference.artifact_kind is ArtifactKind.LIFECYCLE + valid = valid and lifecycle_reference.access_class is ArtifactAccessClass.PRIVATE + else: + valid = valid and lifecycle_reference is None and not value.lifecycle_projection_digest + if not valid: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + + +def _result_value(value: AutomaticRetryResultV1, *, include_digest: bool) -> dict[str, JsonValue]: + result: dict[str, JsonValue] = { + "schema_version": AUTOMATIC_RETRY_RESULT_SCHEMA, + "status": value.status.value, + "reason": value.reason.value, + "retry_digest": value.retry_digest, + "component_index": value.component_index, + "checkpoint_result_digest": None if value.checkpoint is None else value.checkpoint.result_digest, + "lifecycle_reference": ( + None if value.lifecycle_reference is None else _reference_value(value.lifecycle_reference) + ), + "lifecycle_projection_digest": value.lifecycle_projection_digest or None, + } + if include_digest: + result["result_digest"] = value.result_digest + return result + + +def automatic_retry_result_bytes(value: AutomaticRetryResultV1) -> bytes: + value.__post_init__() + return canonical.canonical_bytes(_result_value(value, include_digest=True)) + + +def _result( + status: AutomaticRetryStatus, + reason: AutomaticRetryReason, + retry_digest: str, + component_index: int, + checkpoint: ArmCheckpointResultV1 | None = None, + lifecycle_reference: ArtifactReference | None = None, + lifecycle_projection_digest: str = "", +) -> AutomaticRetryResultV1: + return AutomaticRetryResultV1( + status, + reason, + retry_digest, + component_index, + checkpoint, + lifecycle_reference, + lifecycle_projection_digest, + "", + ) + + +def _block_changed_retry( + authority: AutomaticRetryAuthorityV1, + candidate: AutomaticRetryIdentityV1, + actual: AutomaticRetryIdentityV1, + supplied_plan_digest: str, + component_index: int, + repository: S3ArtifactRepository, + artifact_authority: ArtifactReadAuthority, + access_policy_digest: str, + lifecycle_authority: BaselineLifecycleAuthority, + mismatch_authority: RetryMismatchAuthorityV1 | None, +) -> AutomaticRetryResultV1: + try: + active = lifecycle_authority.require_admission_eligible(authority.population_digest, authority.freeze_digest) + except LifecycleError: + return _result( + AutomaticRetryStatus.BLOCKED, + AutomaticRetryReason.LIFECYCLE_INELIGIBLE, + candidate.retry_digest, + component_index, + ) + expected = ( + authority.population_digest, + authority.freeze_digest, + active.head_event_digest, + component_index, + authority.authority_digest, + candidate.retry_digest, + actual.retry_digest, + supplied_plan_digest, + ) + try: + if mismatch_authority is None: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.MISMATCH_AUTHORITY_REQUIRED) + mismatch_authority.__post_init__() + binding = ( + mismatch_authority.population_digest, + mismatch_authority.freeze_digest, + mismatch_authority.predecessor_digest, + mismatch_authority.component_index, + mismatch_authority.registered_retry_digest, + mismatch_authority.candidate_retry_digest, + mismatch_authority.actual_retry_digest, + mismatch_authority.supplied_plan_digest, + ) + if binding != expected: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.MISMATCH_AUTHORITY_REQUIRED) + reference = persist_private_authority_event( + ArtifactKind.LIFECYCLE, + mismatch_authority.retirement_event_content, + mismatch_authority.retirement_event_digest, + repository, + artifact_authority, + access_policy_digest, + ) + projection = lifecycle_authority.append(mismatch_authority.retirement_event_content) + if projection.state is not PopulationLifecycleState.RETIRED or projection.admission_eligible: + raise LifecycleError("changed retry did not terminally retire baseline") + except AutomaticRetryError: + raise + except SealedDiagnosticError: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.AUTHORITY_PERSISTENCE_FAILED) from None + except (LifecycleError, TypeError, ValueError): + raise AutomaticRetryError(AutomaticRetryAuthorityReason.MISMATCH_AUTHORITY_REQUIRED) from None + return _result( + AutomaticRetryStatus.BLOCKED, + AutomaticRetryReason.IDENTITY_CHANGED, + candidate.retry_digest, + component_index, + lifecycle_reference=reference, + lifecycle_projection_digest=projection.projection_digest, + ) + + +def resume_pre_spend_sealed_retry( + *, + component_index: int, + admission_identity_digest: str, + bundles: tuple[LabelBlindExecutionBundleV1, ...], + checkpoint_selectors: tuple[CheckpointSelectorV1, ...], + plan: RegisteredEvaluationPlanV1, + adapter: ObservationCheckpointAdapter, + journal: S3WorkflowJournal, + workflow_digest: str, + repository: S3ArtifactRepository, + artifact_authority: ArtifactReadAuthority, + access_policy_digest: str, + manifest: LabelBlindPopulationManifestV3, + public_material_manifest: PublicPopulationMaterialManifestV1, + selection: OrdinarySelectionV1, + lifecycle_authority: BaselineLifecycleAuthority, + custody: S3DurableCustodyStore, + mismatch_authority: RetryMismatchAuthorityV1 | None = None, +) -> AutomaticRetryResultV1: + """Resume pre-spend only from the head-selected authority over unchanged identity.""" + _digest(admission_identity_digest) + if ( + type(bundles) is not tuple + or not bundles + or type(component_index) is not int + or not 0 <= component_index < len(bundles) + ): + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + authority = resolve_head_selected_retry_authority(journal, repository, access_policy_digest, workflow_digest) + if custody.current_log(authority.population_digest).status is not PopulationStatus.AVAILABLE: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.SPEND_ALREADY_COMMITTED) + candidate = build_automatic_retry_identity( + bundles[0].population_digest, + bundles[0].freeze_digest, + admission_identity_digest, + bundles, + checkpoint_selectors, + ) + actual = _actual_retry_identity(candidate, bundles, checkpoint_selectors, plan) + if actual.retry_digest != candidate.retry_digest or not retry_identity_matches_authority( + candidate, bundles, plan, authority + ): + return _block_changed_retry( + authority, + candidate, + actual, + plan.plan_digest, + component_index, + repository, + artifact_authority, + access_policy_digest, + lifecycle_authority, + mismatch_authority, + ) + try: + lifecycle_authority.require_admission_eligible(authority.population_digest, authority.freeze_digest) + except LifecycleError: + return _result( + AutomaticRetryStatus.BLOCKED, + AutomaticRetryReason.LIFECYCLE_INELIGIBLE, + candidate.retry_digest, + component_index, + ) + checkpoint = execute_or_resume_component( + plan, + bundles[component_index], + adapter, + repository, + artifact_authority, + access_policy_digest, + manifest, + public_material_manifest, + selection, + checkpoint=checkpoint_selectors[component_index], + ) + if checkpoint.status is CheckpointStatus.COMPLETE: + return _result( + AutomaticRetryStatus.RESUMED, + AutomaticRetryReason.NONE, + candidate.retry_digest, + component_index, + checkpoint, + ) + return _result( + AutomaticRetryStatus.IMPAIRED, + AutomaticRetryReason.CHECKPOINT_IMPAIRED, + candidate.retry_digest, + component_index, + checkpoint, + ) + + +__all__ = [ + "AUTOMATIC_RETRY_RESULT_SCHEMA", + "AUTOMATIC_RETRY_SCHEMA", + "RETRY_MISMATCH_AUTHORITY_SCHEMA", + "AutomaticRetryAuthorityReason", + "AutomaticRetryError", + "AutomaticRetryIdentityV1", + "AutomaticRetryReason", + "AutomaticRetryResultV1", + "AutomaticRetryStatus", + "RetryMismatchAuthorityV1", + "automatic_retry_identity_bytes", + "automatic_retry_result_bytes", + "build_automatic_retry_identity", + "resolve_head_selected_retry_authority", + "resume_pre_spend_sealed_retry", + "retry_identity_matches_authority", + "review_retry_mismatch_authority", +] diff --git a/benchmarks/valid/sealed_retry_recovery.py b/benchmarks/valid/sealed_retry_recovery.py new file mode 100644 index 00000000..353b5bbb --- /dev/null +++ b/benchmarks/valid/sealed_retry_recovery.py @@ -0,0 +1,123 @@ +"""Task 8.6 post-spend recovery of the same immutable sealed run.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from benchmarks.valid.arm_contract import RegisteredEvaluationPlanV1 +from benchmarks.valid.artifact_repository import S3ArtifactRepository +from benchmarks.valid.durable_custody_store import S3DurableCustodyStore +from benchmarks.valid.isolated_execution_bundle import LabelBlindExecutionBundleV1 +from benchmarks.valid.observation_checkpoint import CheckpointSelectorV1 +from benchmarks.valid.sealed_retry import ( + AutomaticRetryAuthorityReason, + AutomaticRetryError, + _actual_retry_identity, + _digest, + build_automatic_retry_identity, + resolve_head_selected_retry_authority, + retry_identity_matches_authority, +) +from benchmarks.valid.workflow_journal import S3WorkflowJournal +from openultrasast.core import canonical +from openultrasast.core.canonical import JsonValue +from openultrasast.core.custody import PopulationStatus + +SPENT_RUN_RESUME_SCHEMA = "openultrasast.valid-detection-benchmark.spent-run-resume.v1" + + +@dataclass(frozen=True) +class SpentRunResumeV1: + """Post-spend resume product: the committed run stays spent and immutable.""" + + authority_digest: str + retry_digest: str + population_digest: str + freeze_digest: str + labels_spent: bool + custody_receipt_digest: str | None + resume_digest: str + + def __post_init__(self) -> None: + if type(self) is not SpentRunResumeV1 or self.labels_spent is not True: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + for value in (self.authority_digest, self.retry_digest, self.population_digest, self.freeze_digest): + _digest(value) + if self.custody_receipt_digest is not None: + _digest(self.custody_receipt_digest) + expected = canonical.content_digest(_resume_value(self, include_digest=False)) + if not self.resume_digest: + object.__setattr__(self, "resume_digest", expected) + elif _digest(self.resume_digest) != expected: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + + +def _resume_value(value: SpentRunResumeV1, *, include_digest: bool) -> dict[str, JsonValue]: + result: dict[str, JsonValue] = { + "schema_version": SPENT_RUN_RESUME_SCHEMA, + "authority_digest": value.authority_digest, + "retry_digest": value.retry_digest, + "population_digest": value.population_digest, + "freeze_digest": value.freeze_digest, + "labels_spent": value.labels_spent, + "custody_receipt_digest": value.custody_receipt_digest, + } + if include_digest: + result["resume_digest"] = value.resume_digest + return result + + +def spent_run_resume_bytes(value: SpentRunResumeV1) -> bytes: + value.__post_init__() + return canonical.canonical_bytes(_resume_value(value, include_digest=True)) + + +def resume_spent_sealed_run( + *, + admission_identity_digest: str, + bundles: tuple[LabelBlindExecutionBundleV1, ...], + checkpoint_selectors: tuple[CheckpointSelectorV1, ...], + plan: RegisteredEvaluationPlanV1, + journal: S3WorkflowJournal, + workflow_digest: str, + repository: S3ArtifactRepository, + access_policy_digest: str, + custody: S3DurableCustodyStore, +) -> SpentRunResumeV1: + """Resume the same immutable run from durable artifacts without restoring untouched status.""" + _digest(admission_identity_digest) + if type(bundles) is not tuple or not bundles: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.INVALID_REQUEST) + authority = resolve_head_selected_retry_authority(journal, repository, access_policy_digest, workflow_digest) + candidate = build_automatic_retry_identity( + bundles[0].population_digest, + bundles[0].freeze_digest, + admission_identity_digest, + bundles, + checkpoint_selectors, + ) + actual = _actual_retry_identity(candidate, bundles, checkpoint_selectors, plan) + if actual.retry_digest != candidate.retry_digest or not retry_identity_matches_authority( + candidate, bundles, plan, authority + ): + raise AutomaticRetryError(AutomaticRetryAuthorityReason.MISMATCH_AUTHORITY_REQUIRED) + log = custody.current_log(authority.population_digest) + if log.status is not PopulationStatus.SPENT or log.receipt_count < 1: + raise AutomaticRetryError(AutomaticRetryAuthorityReason.CUSTODY_NOT_SPENT) + return SpentRunResumeV1( + authority.authority_digest, + candidate.retry_digest, + authority.population_digest, + authority.freeze_digest, + True, + log.head_receipt_digest, + "", + ) + + +__all__ = [ + "SPENT_RUN_RESUME_SCHEMA", + "SpentRunResumeV1", + "resume_spent_sealed_run", + "spent_run_resume_bytes", +] diff --git a/tests/test_valid_benchmark_sealed_retry.py b/tests/test_valid_benchmark_sealed_retry.py new file mode 100644 index 00000000..9ce589c5 --- /dev/null +++ b/tests/test_valid_benchmark_sealed_retry.py @@ -0,0 +1,823 @@ +"""Task 8.6 exact pre-spend and post-spend sealed retry resume.""" + +from __future__ import annotations + +import sys +from dataclasses import replace +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from test_valid_benchmark_admission_execution import ( # noqa: E402 + WORKFLOW, + _Adapter, + _boom, + _selectors, +) +from test_valid_benchmark_admission_execution import ( + _case as _execution_case, +) +from test_valid_benchmark_admission_spend import _SpendEnv # noqa: E402 +from test_valid_benchmark_artifact_repository import _Client # noqa: E402 +from test_valid_benchmark_isolated_executor import _bundles, _plan # noqa: E402 +from test_valid_benchmark_lifecycle import _withdrawal # noqa: E402 +from test_valid_benchmark_observation_checkpoint import _Adapter as _CheckpointAdapter # noqa: E402 +from test_valid_benchmark_observation_checkpoint import _run # noqa: E402 +from test_valid_benchmark_orchestrator import ( # noqa: E402 + ACCESS_POLICY, + _digest, + _settings, +) + +from benchmarks.valid import admission_spend as spend # noqa: E402 +from benchmarks.valid import arm_contract as registry # noqa: E402 +from benchmarks.valid import artifact_repository as repository # noqa: E402 +from benchmarks.valid import lifecycle, observation_checkpoint, sealed_retry # noqa: E402 +from benchmarks.valid.admission_orchestrator import ( # noqa: E402 + RETRY_AUTHORITY_SCHEMA, + AutomaticRetryAuthorityV1, +) +from benchmarks.valid.artifact_repository import S3ArtifactRepository # noqa: E402 +from benchmarks.valid.replacement_artifact_contract import ( # noqa: E402 + ArtifactAccessClass, + ArtifactKind, + canonical_artifact_bytes, +) +from benchmarks.valid.store_configuration import StorePurpose # noqa: E402 +from benchmarks.valid.workflow_journal import ( # noqa: E402 + S3WorkflowJournal, + WorkflowJournalEntryV1, + journal_entry_bytes, + successor_head, + workflow_entry_key, +) +from benchmarks.valid.workflow_outcome import WorkflowCounts, WorkflowPhase # noqa: E402 +from openultrasast.core import canonical # noqa: E402 +from openultrasast.core.custody import PopulationStatus # noqa: E402 +from openultrasast.core.evaluation_measurement import ArmKindV3 # noqa: E402 +from openultrasast.core.evaluation_plan import derive_evaluation_input_set_digest # noqa: E402 + +_FORBIDDEN_BYTES = (b"label", b"finding", b"path", b"exception", b"password", b"repository") + + +def _custodian() -> repository.ArtifactReadAuthority: + return repository.artifact_read_authority( + repository.ArtifactActorRole.CUSTODIAN, + ( + repository.ArtifactReadPermission.CUSTODIAN_SEALED, + repository.ArtifactReadPermission.PRIVATE, + ), + ACCESS_POLICY, + expected_access_policy_digest=ACCESS_POLICY, + ) + + +def _frozen_plan(): + bundles = _bundles() + client = _Client() + results = tuple(_run(bundle, _CheckpointAdapter(), client) for bundle in bundles) + selectors = tuple( + observation_checkpoint.CheckpointSelectorV1(result.reference, result.checkpoint_digest) for result in results + ) + return bundles, client, selectors + + +def _identity(bundles, selectors, admission: str | None = None): + return sealed_retry.build_automatic_retry_identity( + bundles[0].population_digest, + bundles[0].freeze_digest, + _digest("admission-identity") if admission is None else admission, + bundles, + selectors, + ) + + +def _active(population: str, freeze: str) -> lifecycle.BaselineLifecycleAuthority: + root = lifecycle.withdrawn_event(_withdrawal()) + withdrawn = lifecycle.decode_lifecycle_event(root) + replacement = lifecycle.reviewed_replacement_event( + predecessor_digest=withdrawn.event_digest, + historical_withdrawal_digest=withdrawn.historical_withdrawal_digest, + population_digest=population, + freeze_digest=freeze, + producer_identity="lifecycle-producer", + reviewer_identity="lifecycle-reviewer", + conflict_disclosed=True, + policy_digest=_digest("lifecycle-policy"), + ) + authority = lifecycle.BaselineLifecycleAuthority() + authority.append(root) + authority.append(replacement) + return authority + + +def _review() -> dict[str, object]: + return { + "producer_identity": "retry-controller", + "reviewer_identity": "retry-reviewer", + "conflict_disclosed": True, + "policy_digest": _digest("lifecycle-policy"), + } + + +def _matching_authority(bundles, selectors, plan, admission: str) -> AutomaticRetryAuthorityV1: + candidate = _identity(bundles, selectors, admission) + components = tuple( + sorted(row.arm_id for row in plan.registrations if row.configuration.kind is ArmKindV3.COMPONENT) + ) + return AutomaticRetryAuthorityV1( + candidate.population_digest, + candidate.freeze_digest, + admission, + plan.plan_digest, + tuple(row.arm_id for row in plan.registrations), + candidate.bundle_digests, + tuple(slot.slot_digest for slot in plan.declaration.expected_observation_slots), + tuple(candidate.input_set_digest for _ in components), + candidate.budget_digests, + candidate.environment_digests, + candidate.output_destination_digests, + "", + ) + + +class _CrashingLoader: + """Crashes exactly between the committed custody CAS and the first label byte.""" + + def __init__(self) -> None: + self.reads = 0 + + def __call__(self) -> bytes: + self.reads += 1 + raise RuntimeError("crash between custody CAS and label load") + + +class _RetryEnv(_SpendEnv): + def __init__(self, case) -> None: + super().__init__(case) + self.selectors = _selectors(self.product) + assert self.authorized.retry_authority is not None + + def preflight(self, **overrides): + self.authorized = super().preflight(**overrides) + return self.authorized + + def rebuilt_journal(self) -> S3WorkflowJournal: + return S3WorkflowJournal(_settings(StorePurpose.TRANSIENT), self.transient) + + def rebuilt_repository(self) -> S3ArtifactRepository: + return S3ArtifactRepository(_settings(StorePurpose.DURABLE), self.durable) + + +def _review_authority(env, candidate, *, plan=None, bundles=None, selectors=None, lifecycle_authority=None): + return sealed_retry.review_retry_mismatch_authority( + env.authorized.retry_authority, + candidate, + bundles=env.case.bundles if bundles is None else bundles, + checkpoint_selectors=env.selectors if selectors is None else selectors, + plan=env.case.plan if plan is None else plan, + lifecycle_authority=env.lifecycle() if lifecycle_authority is None else lifecycle_authority, + **_review(), + ) + + +def _pre_spend_resume(env, **overrides): + value = { + "component_index": 0, + "admission_identity_digest": env.authorized.retry_authority.admission_identity_digest, + "bundles": env.case.bundles, + "checkpoint_selectors": env.selectors, + "plan": env.case.plan, + "adapter": _Adapter(_boom), + "journal": env.rebuilt_journal(), + "workflow_digest": WORKFLOW, + "repository": env.rebuilt_repository(), + "artifact_authority": _custodian(), + "access_policy_digest": ACCESS_POLICY, + "manifest": env.case.manifest, + "public_material_manifest": env.case.material, + "selection": env.case.selection, + "lifecycle_authority": env.lifecycle(), + "custody": env.custody, + } + value.update(overrides) + return sealed_retry.resume_pre_spend_sealed_retry(**value) + + +def _spent_resume(env, **overrides): + from benchmarks.valid import sealed_retry_recovery + + value = { + "admission_identity_digest": env.authorized.retry_authority.admission_identity_digest, + "bundles": env.case.bundles, + "checkpoint_selectors": env.selectors, + "plan": env.case.plan, + "journal": env.rebuilt_journal(), + "workflow_digest": WORKFLOW, + "repository": env.rebuilt_repository(), + "access_policy_digest": ACCESS_POLICY, + "custody": env.custody, + } + value.update(overrides) + return sealed_retry_recovery.resume_spent_sealed_run(**value) + + +def _crash_after_cas(env) -> object: + loader = _CrashingLoader() + release = spend.commit_spend_and_release(env.spend_request(load_labels=loader)) + assert release.refusal_reason is spend.AdmissionSpendReason.LABELS_UNREADABLE + assert release.labels_spent and release.custody_receipt_digest + log = env.custody.current_log(env.population) + assert log.status is PopulationStatus.SPENT and log.receipt_count == 1 + assert loader.reads == 1 + return release + + +def _advance_phase(env, phase: WorkflowPhase) -> None: + head = env.journal.current_head(WORKFLOW) + entry = WorkflowJournalEntryV1( + WORKFLOW, + head.sequence + 1, + head.entry_digest, + "attempt-1", + "owner-a", + phase, + "2026-11-21T09:10:00Z", + "2026-11-21T09:40:00Z", + WorkflowCounts(3, 2, len(env.case.manifest.input_digests), 0, 0), + "", + ) + assert env.journal.append_and_swap(head.head_digest, entry, successor_head(head, entry)) + + +def _foreign_plan(case, *, changed_inputs: bool = False): + current = case.plan + input_digests = tuple(row.input_identity_digest for row in case.bundles[0].case_inputs) + if changed_inputs: + input_digests = (_digest("foreign-plan-input"), *input_digests[1:]) + return registry.register_evaluation_plan( + registrations=current.registrations, + population_digest=( + current.declaration.population_digest if changed_inputs else _digest("foreign-plan-population") + ), + freeze_digest=current.declaration.freeze_digest, + input_set_digest=derive_evaluation_input_set_digest(input_digests), + input_identity_digests=input_digests, + ) + + +def _no_lifecycle_artifacts(env) -> None: + assert not [key for key in env.durable if "lifecycle" in key] + + +def _rebuilt_retired_authority(env, reference) -> lifecycle.BaselineLifecycleAuthority: + accepted = env.rebuilt_repository().get( + reference, + expected_kind=ArtifactKind.LIFECYCLE, + authority=_custodian(), + expected_access_policy_digest=ACCESS_POLICY, + ) + authority = env.lifecycle() + authority.append(canonical.canonical_bytes(accepted.artifact.payload)) + return authority + + +def test_scratch_loss_pre_spend_resume_resolves_only_head_selected_authority_without_rerun() -> None: + env = _RetryEnv(_execution_case()) + adapter = _Adapter(_boom) + + result = _pre_spend_resume(env, adapter=adapter) + + assert result.status is sealed_retry.AutomaticRetryStatus.RESUMED + assert result.reason is sealed_retry.AutomaticRetryReason.NONE + assert result.checkpoint is not None + assert result.checkpoint.status is observation_checkpoint.CheckpointStatus.COMPLETE + assert result.checkpoint.checkpoint_digest == env.product.component_results[0].checkpoint_digest + assert adapter.calls == [] + assert env.custody.current_log(env.population).status is PopulationStatus.AVAILABLE + env.lifecycle().require_admission_eligible( + env.authorized.retry_authority.population_digest, env.authorized.retry_authority.freeze_digest + ) + content = sealed_retry.automatic_retry_result_bytes(result).lower() + for forbidden in _FORBIDDEN_BYTES: + assert forbidden not in content + + +def test_caller_supplied_original_identity_cannot_authorize_changed_current_bundles() -> None: + case = _execution_case() + env = _RetryEnv(case) + lifecycle_authority = env.lifecycle() + changed_budget = replace( + case.bundles[0].budget, deadline_seconds=case.bundles[0].budget.deadline_seconds + 1, budget_digest="" + ) + bundles = (replace(case.bundles[0], budget=changed_budget, bundle_digest=""), *case.bundles[1:]) + candidate = _identity(bundles, env.selectors, env.authorized.retry_authority.admission_identity_digest) + mismatch = _review_authority(env, candidate, bundles=bundles, lifecycle_authority=lifecycle_authority) + adapter = _Adapter(_boom) + + result = _pre_spend_resume( + env, bundles=bundles, adapter=adapter, mismatch_authority=mismatch, lifecycle_authority=lifecycle_authority + ) + + assert result.status is sealed_retry.AutomaticRetryStatus.BLOCKED + assert result.reason is sealed_retry.AutomaticRetryReason.IDENTITY_CHANGED + assert result.checkpoint is None and result.lifecycle_reference is not None + assert adapter.calls == [] + with pytest.raises(lifecycle.LifecycleError, match="eligible"): + lifecycle_authority.require_admission_eligible( + env.authorized.retry_authority.population_digest, env.authorized.retry_authority.freeze_digest + ) + + +@pytest.mark.parametrize("mutation", ("admission", "plan", "plan-inputs", "bundle-budget")) +def test_changed_identity_dimension_terminally_blocks_admission_without_execution(mutation: str) -> None: + case = _execution_case() + env = _RetryEnv(case) + lifecycle_authority = env.lifecycle() + bundles, plan = case.bundles, case.plan + admission = env.authorized.retry_authority.admission_identity_digest + if mutation == "admission": + admission = _digest("changed-admission") + elif mutation == "plan": + plan = _foreign_plan(case) + elif mutation == "plan-inputs": + plan = _foreign_plan(case, changed_inputs=True) + else: + changed = replace( + case.bundles[0].budget, deadline_seconds=case.bundles[0].budget.deadline_seconds + 1, budget_digest="" + ) + bundles = (replace(case.bundles[0], budget=changed, bundle_digest=""), *case.bundles[1:]) + candidate = _identity(bundles, env.selectors, admission) + mismatch = _review_authority( + env, candidate, plan=plan, bundles=bundles, lifecycle_authority=lifecycle_authority + ) + adapter = _Adapter(_boom) + + result = _pre_spend_resume( + env, + admission_identity_digest=admission, + bundles=bundles, + plan=plan, + adapter=adapter, + mismatch_authority=mismatch, + lifecycle_authority=lifecycle_authority, + ) + + assert result.status is sealed_retry.AutomaticRetryStatus.BLOCKED + assert result.reason is sealed_retry.AutomaticRetryReason.IDENTITY_CHANGED + assert adapter.calls == [] + with pytest.raises(lifecycle.LifecycleError, match="eligible"): + lifecycle_authority.require_admission_eligible( + env.authorized.retry_authority.population_digest, env.authorized.retry_authority.freeze_digest + ) + + +def test_reordered_checkpoint_selectors_never_resume_a_foreign_completed_arm() -> None: + env = _RetryEnv(_execution_case()) + adapter = _Adapter(_boom) + + result = _pre_spend_resume(env, checkpoint_selectors=tuple(reversed(env.selectors)), adapter=adapter) + + assert result.status is sealed_retry.AutomaticRetryStatus.IMPAIRED + assert result.reason is sealed_retry.AutomaticRetryReason.CHECKPOINT_IMPAIRED + assert adapter.calls == [] + assert env.custody.current_log(env.population).status is PopulationStatus.AVAILABLE + + +def test_unreadable_checkpoint_is_impaired_and_leaves_custody_available() -> None: + env = _RetryEnv(_execution_case()) + for selector in env.selectors: + env.durable.put_object( + Bucket="valid-durable", + Key=f"observations/custodian_sealed/{selector.reference.content_digest}.json", + Body=b"corrupted-checkpoint", + ) + adapter = _Adapter(_boom) + + result = _pre_spend_resume(env, adapter=adapter) + + assert result.status is sealed_retry.AutomaticRetryStatus.IMPAIRED + assert result.reason is sealed_retry.AutomaticRetryReason.CHECKPOINT_IMPAIRED + assert adapter.calls == [] + assert env.custody.current_log(env.population).status is PopulationStatus.AVAILABLE + + +def test_missing_mismatch_evidence_fails_closed_without_retirement_or_lifecycle_mutation() -> None: + env = _RetryEnv(_execution_case()) + adapter = _Adapter(_boom) + + with pytest.raises(sealed_retry.AutomaticRetryError) as captured: + _pre_spend_resume(env, admission_identity_digest=_digest("changed-admission"), adapter=adapter) + + assert captured.value.reason is sealed_retry.AutomaticRetryAuthorityReason.MISMATCH_AUTHORITY_REQUIRED + assert adapter.calls == [] + env.lifecycle().require_admission_eligible( + env.authorized.retry_authority.population_digest, env.authorized.retry_authority.freeze_digest + ) + _no_lifecycle_artifacts(env) + + +def test_forged_mismatch_evidence_fails_closed_without_retirement() -> None: + case = _execution_case() + env = _RetryEnv(case) + lifecycle_authority = env.lifecycle() + candidate = _identity(case.bundles, env.selectors, _digest("changed-admission")) + valid = _review_authority(env, candidate, lifecycle_authority=lifecycle_authority) + forged = object.__new__(sealed_retry.RetryMismatchAuthorityV1) + for name, value in vars(valid).items(): + object.__setattr__(forged, name, value) + object.__setattr__(forged, "candidate_retry_digest", _digest("forged-candidate")) + adapter = _Adapter(_boom) + + with pytest.raises(sealed_retry.AutomaticRetryError) as captured: + _pre_spend_resume( + env, + admission_identity_digest=_digest("changed-admission"), + adapter=adapter, + mismatch_authority=forged, + lifecycle_authority=lifecycle_authority, + ) + + assert captured.value.reason is sealed_retry.AutomaticRetryAuthorityReason.INVALID_REQUEST + assert adapter.calls == [] + lifecycle_authority.require_admission_eligible( + env.authorized.retry_authority.population_digest, env.authorized.retry_authority.freeze_digest + ) + _no_lifecycle_artifacts(env) + + +def test_deeply_nested_mismatch_evidence_fails_closed_without_mutation() -> None: + case = _execution_case() + env = _RetryEnv(case) + lifecycle_authority = env.lifecycle() + candidate = _identity(case.bundles, env.selectors, _digest("changed-admission")) + valid = _review_authority(env, candidate, lifecycle_authority=lifecycle_authority) + forged = object.__new__(sealed_retry.RetryMismatchAuthorityV1) + for name, value in vars(valid).items(): + object.__setattr__(forged, name, value) + object.__setattr__( + forged, "retirement_event_content", b'{"a":' * 100_000 + b"1" + b"}" * 100_000 + ) + adapter = _Adapter(_boom) + + with pytest.raises(sealed_retry.AutomaticRetryError) as captured: + _pre_spend_resume( + env, + admission_identity_digest=_digest("changed-admission"), + adapter=adapter, + mismatch_authority=forged, + lifecycle_authority=lifecycle_authority, + ) + + assert captured.value.reason is sealed_retry.AutomaticRetryAuthorityReason.INVALID_REQUEST + assert adapter.calls == [] + lifecycle_authority.require_admission_eligible( + env.authorized.retry_authority.population_digest, env.authorized.retry_authority.freeze_digest + ) + _no_lifecycle_artifacts(env) + + +def test_mismatch_evidence_reviewed_for_another_change_is_refused_closed() -> None: + case = _execution_case() + env = _RetryEnv(case) + lifecycle_authority = env.lifecycle() + first = _identity(case.bundles, env.selectors, _digest("first-change")) + wrong = _review_authority(env, first, lifecycle_authority=lifecycle_authority) + adapter = _Adapter(_boom) + + with pytest.raises(sealed_retry.AutomaticRetryError) as captured: + _pre_spend_resume( + env, + admission_identity_digest=_digest("second-change"), + adapter=adapter, + mismatch_authority=wrong, + lifecycle_authority=lifecycle_authority, + ) + + assert captured.value.reason is sealed_retry.AutomaticRetryAuthorityReason.MISMATCH_AUTHORITY_REQUIRED + assert adapter.calls == [] + lifecycle_authority.require_admission_eligible( + env.authorized.retry_authority.population_digest, env.authorized.retry_authority.freeze_digest + ) + _no_lifecycle_artifacts(env) + + +def test_malformed_supplied_plan_is_refused_before_execution_without_mutation() -> None: + case = _execution_case() + env = _RetryEnv(case) + malformed = object.__new__(registry.RegisteredEvaluationPlanV1) + object.__setattr__(malformed, "registrations", case.plan.registrations) + object.__setattr__(malformed, "declaration", case.plan.declaration) + object.__setattr__(malformed, "baselines", case.plan.baselines) + object.__setattr__(malformed, "plan_digest", _digest("forged-plan-digest")) + adapter = _Adapter(_boom) + + with pytest.raises(sealed_retry.AutomaticRetryError) as captured: + _pre_spend_resume(env, plan=malformed, adapter=adapter) + + assert captured.value.reason is sealed_retry.AutomaticRetryAuthorityReason.INVALID_REQUEST + assert adapter.calls == [] + env.lifecycle().require_admission_eligible( + env.authorized.retry_authority.population_digest, env.authorized.retry_authority.freeze_digest + ) + + +def test_terminal_baseline_cannot_retry_even_with_exact_identity() -> None: + case = _execution_case() + env = _RetryEnv(case) + lifecycle_authority = env.lifecycle() + changed = _identity(case.bundles, env.selectors, _digest("changed-admission")) + mismatch = _review_authority(env, changed, lifecycle_authority=lifecycle_authority) + first = _pre_spend_resume( + env, + admission_identity_digest=_digest("changed-admission"), + mismatch_authority=mismatch, + lifecycle_authority=lifecycle_authority, + ) + assert first.reason is sealed_retry.AutomaticRetryReason.IDENTITY_CHANGED + assert first.lifecycle_reference is not None + adapter = _Adapter(_boom) + + rebuilt = _rebuilt_retired_authority(env, first.lifecycle_reference) + second = _pre_spend_resume(env, adapter=adapter, lifecycle_authority=rebuilt) + + assert second.status is sealed_retry.AutomaticRetryStatus.BLOCKED + assert second.reason is sealed_retry.AutomaticRetryReason.LIFECYCLE_INELIGIBLE + assert adapter.calls == [] + + +def test_pre_spend_resume_over_committed_spend_is_refused_closed() -> None: + env = _RetryEnv(_execution_case()) + _crash_after_cas(env) + spent_log = env.custody.current_log(env.population) + adapter = _Adapter(_boom) + + with pytest.raises(sealed_retry.AutomaticRetryError) as captured: + _pre_spend_resume(env, adapter=adapter) + + assert captured.value.reason is sealed_retry.AutomaticRetryAuthorityReason.SPEND_ALREADY_COMMITTED + assert adapter.calls == [] + assert env.custody.current_log(env.population) == spent_log + env.lifecycle().require_admission_eligible( + env.authorized.retry_authority.population_digest, env.authorized.retry_authority.freeze_digest + ) + + +def test_missing_workflow_head_fails_closed_before_any_execution() -> None: + env = _RetryEnv(_execution_case()) + empty = S3WorkflowJournal(_settings(StorePurpose.TRANSIENT), _Client()) + adapter = _Adapter(_boom) + + with pytest.raises(sealed_retry.AutomaticRetryError) as captured: + _pre_spend_resume(env, journal=empty, adapter=adapter) + + assert captured.value.reason is sealed_retry.AutomaticRetryAuthorityReason.AUTHORITY_UNRESOLVED + assert adapter.calls == [] + + +def test_substituted_authority_bytes_fail_closed_before_execution() -> None: + env = _RetryEnv(_execution_case()) + authority = env.authorized.retry_authority + reference = env.authorized.retry_authority_reference + assert reference is not None + substituted = canonical_artifact_bytes( + ArtifactKind.WORKFLOW, + { + "schema_version": RETRY_AUTHORITY_SCHEMA, + "population_digest": authority.population_digest, + "freeze_digest": authority.freeze_digest, + "admission_identity_digest": _digest("other-admission"), + "plan_digest": authority.plan_digest, + "ordered_arm_ids": authority.ordered_arm_ids, + "ordered_bundle_digests": authority.ordered_bundle_digests, + "ordered_checkpoint_slot_digests": authority.ordered_checkpoint_slot_digests, + "ordered_input_set_digests": authority.ordered_input_set_digests, + "ordered_budget_digests": authority.ordered_budget_digests, + "ordered_environment_digests": authority.ordered_environment_digests, + "ordered_destination_digests": authority.ordered_destination_digests, + "authority_digest": authority.authority_digest, + }, + access_class=ArtifactAccessClass.CUSTODIAN_SEALED, + provenance_digest=_digest("substituted-provenance"), + ) + env.durable.put_object( + Bucket="valid-durable", + Key=f"workflows/custodian_sealed/{reference.content_digest}.json", + Body=substituted, + ) + adapter = _Adapter(_boom) + + with pytest.raises(sealed_retry.AutomaticRetryError) as captured: + _pre_spend_resume(env, adapter=adapter) + + assert captured.value.reason is sealed_retry.AutomaticRetryAuthorityReason.AUTHORITY_SUBSTITUTED + assert adapter.calls == [] + assert env.custody.current_log(env.population).status is PopulationStatus.AVAILABLE + + +def test_orphan_journal_entry_is_never_selected_after_restart() -> None: + env = _RetryEnv(_execution_case()) + head = env.journal.current_head(WORKFLOW) + orphan = WorkflowJournalEntryV1( + WORKFLOW, + head.sequence + 5, + head.entry_digest, + "attempt-9", + "owner-z", + WorkflowPhase.SCORING, + "2026-11-21T09:20:00Z", + "2026-11-21T09:50:00Z", + WorkflowCounts(3, 2, len(env.case.manifest.input_digests), 0, 0), + "", + ) + env.transient.put_object( + Bucket="valid-transient", + Key=workflow_entry_key(WORKFLOW, orphan.entry_digest), + Body=journal_entry_bytes(orphan), + ) + adapter = _Adapter(_boom) + + result = _pre_spend_resume(env, adapter=adapter) + + assert result.status is sealed_retry.AutomaticRetryStatus.RESUMED + assert result.checkpoint is not None + assert result.checkpoint.checkpoint_digest == env.product.component_results[0].checkpoint_digest + assert adapter.calls == [] + + +def test_post_spend_resume_keeps_labels_spent_and_the_same_immutable_run() -> None: + env = _RetryEnv(_execution_case()) + _crash_after_cas(env) + spent_log = env.custody.current_log(env.population) + + resumed = _spent_resume(env) + + assert resumed.labels_spent is True + assert resumed.authority_digest == env.authorized.retry_authority.authority_digest + assert resumed.retry_digest == _identity( + env.case.bundles, env.selectors, env.authorized.retry_authority.admission_identity_digest + ).retry_digest + assert resumed.custody_receipt_digest == spent_log.head_receipt_digest + assert env.custody.current_log(env.population) == spent_log + assert env.custody.current_log(env.population).status is PopulationStatus.SPENT + from benchmarks.valid import sealed_retry_recovery + + content = sealed_retry_recovery.spent_run_resume_bytes(resumed).lower() + for forbidden in (b"finding", b"path", b"exception", b"password", b"repository"): + assert forbidden not in content + assert content.count(b"label") == content.count(b"labels_spent") + + +def test_post_spend_resume_refuses_unspent_custody_and_never_restores_untouched() -> None: + env = _RetryEnv(_execution_case()) + untouched = env.custody.current_log(env.population) + + with pytest.raises(sealed_retry.AutomaticRetryError) as captured: + _spent_resume(env) + + assert captured.value.reason is sealed_retry.AutomaticRetryAuthorityReason.CUSTODY_NOT_SPENT + assert env.custody.current_log(env.population) == untouched + assert env.custody.current_log(env.population).status is PopulationStatus.AVAILABLE + + +def test_post_spend_resume_refuses_changed_identity_without_mutation() -> None: + env = _RetryEnv(_execution_case()) + _crash_after_cas(env) + spent_log = env.custody.current_log(env.population) + + with pytest.raises(sealed_retry.AutomaticRetryError) as captured: + _spent_resume(env, admission_identity_digest=_digest("changed-admission")) + + assert captured.value.reason is sealed_retry.AutomaticRetryAuthorityReason.MISMATCH_AUTHORITY_REQUIRED + assert env.custody.current_log(env.population) == spent_log + env.lifecycle().require_admission_eligible( + env.authorized.retry_authority.population_digest, env.authorized.retry_authority.freeze_digest + ) + _no_lifecycle_artifacts(env) + + +def test_crash_points_converge_to_the_same_terminal_identity() -> None: + case = _execution_case() + identities = set() + + before_cas = _RetryEnv(case) + pre = _pre_spend_resume(before_cas, adapter=_Adapter(_boom)) + assert pre.status is sealed_retry.AutomaticRetryStatus.RESUMED + identities.add((before_cas.authorized.retry_authority.authority_digest, pre.retry_digest)) + + after_cas = _RetryEnv(case) + _crash_after_cas(after_cas) + resumed = _spent_resume(after_cas) + assert resumed.labels_spent is True + identities.add((resumed.authority_digest, resumed.retry_digest)) + + during_scoring = _RetryEnv(case) + _crash_after_cas(during_scoring) + _advance_phase(during_scoring, WorkflowPhase.SCORING) + scoring = _spent_resume(during_scoring) + identities.add((scoring.authority_digest, scoring.retry_digest)) + + before_publication = _RetryEnv(case) + _crash_after_cas(before_publication) + _advance_phase(before_publication, WorkflowPhase.SCORING) + _advance_phase(before_publication, WorkflowPhase.REPORTING) + publication = _spent_resume(before_publication) + identities.add((publication.authority_digest, publication.retry_digest)) + + assert len(identities) == 1 + + +def test_retry_identity_digest_binds_every_dimension() -> None: + bundles, _, selectors = _frozen_plan() + identity = _identity(bundles, selectors) + + with pytest.raises(sealed_retry.AutomaticRetryError) as captured: + replace(identity, input_set_digest=_digest("forged-inputs"), retry_digest=identity.retry_digest) + + assert captured.value.reason is sealed_retry.AutomaticRetryAuthorityReason.INVALID_REQUEST + + +@pytest.mark.parametrize( + "field", + ( + "population_digest", + "freeze_digest", + "admission_identity_digest", + "plan_digest", + "ordered_arm_ids", + "ordered_bundle_digests", + "ordered_checkpoint_slot_digests", + "ordered_input_set_digests", + "ordered_budget_digests", + "ordered_environment_digests", + "ordered_destination_digests", + ), +) +def test_every_head_selected_identity_dimension_must_match(field: str) -> None: + bundles, _, selectors = _frozen_plan() + plan = _plan() + admission = _digest("admission-identity") + authority = _matching_authority(bundles, selectors, plan, admission) + candidate = _identity(bundles, selectors, admission) + assert sealed_retry.retry_identity_matches_authority(candidate, bundles, plan, authority) + + current = getattr(authority, field) + if field == "ordered_arm_ids": + mutated: object = tuple(reversed(current)) + elif field.startswith("ordered_"): + mutated = (_digest(f"other-{field}"), *current[1:]) + else: + mutated = _digest(f"other-{field}") + changed = replace(authority, **{field: mutated}, authority_digest="") + + assert not sealed_retry.retry_identity_matches_authority(candidate, bundles, plan, changed) + + +def test_review_refuses_a_matching_candidate() -> None: + bundles, _, selectors = _frozen_plan() + plan = _plan() + admission = _digest("admission-identity") + authority = _matching_authority(bundles, selectors, plan, admission) + candidate = _identity(bundles, selectors, admission) + + with pytest.raises(sealed_retry.AutomaticRetryError) as captured: + sealed_retry.review_retry_mismatch_authority( + authority, + candidate, + bundles=bundles, + checkpoint_selectors=selectors, + plan=plan, + lifecycle_authority=_active(candidate.population_digest, candidate.freeze_digest), + **_review(), + ) + + assert captured.value.reason is sealed_retry.AutomaticRetryAuthorityReason.INVALID_REQUEST + + +def test_mismatch_authority_requires_its_exact_retirement_event() -> None: + bundles, _, selectors = _frozen_plan() + plan = _plan() + admission = _digest("admission-identity") + authority = _matching_authority(bundles, selectors, plan, admission) + changed = _identity(bundles, selectors, _digest("changed-admission")) + lifecycle_authority = _active(authority.population_digest, authority.freeze_digest) + valid = sealed_retry.review_retry_mismatch_authority( + authority, + changed, + bundles=bundles, + checkpoint_selectors=selectors, + plan=plan, + lifecycle_authority=lifecycle_authority, + **_review(), + ) + forged = object.__new__(sealed_retry.RetryMismatchAuthorityV1) + for name, value in vars(valid).items(): + object.__setattr__(forged, name, value) + object.__setattr__(forged, "predecessor_digest", _digest("forged-predecessor")) + + with pytest.raises(sealed_retry.AutomaticRetryError) as captured: + forged.__post_init__() + + assert captured.value.reason is sealed_retry.AutomaticRetryAuthorityReason.INVALID_REQUEST