From 38e12282dad6d352c9399f4e628ae2c2542e6708 Mon Sep 17 00:00:00 2001 From: Marius Ciepluch <11855163+norandom@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:27:27 +0100 Subject: [PATCH] feat(valid-detection-benchmark): 9.3 publish benchmark-only run, resume, and status commands --- .../specs/valid-detection-benchmark/tasks.md | 2 +- benchmarks/valid/run.py | 778 ++++++++++++++++++ tests/test_valid_benchmark_run.py | 743 +++++++++++++++++ 3 files changed, 1522 insertions(+), 1 deletion(-) create mode 100644 benchmarks/valid/run.py create mode 100644 tests/test_valid_benchmark_run.py diff --git a/.kiro/specs/valid-detection-benchmark/tasks.md b/.kiro/specs/valid-detection-benchmark/tasks.md index f9e13489..ee891403 100644 --- a/.kiro/specs/valid-detection-benchmark/tasks.md +++ b/.kiro/specs/valid-detection-benchmark/tasks.md @@ -294,7 +294,7 @@ - Done when the replacement path has no alternative scorer, V2 fixtures remain byte-identical, and pooled or target-specific output cannot authorize a V3 result. - _Requirements: 6.2, 6.3, 6.4, 6.5, 8.2, 8.6, 9.5, 10.4, 10.5_ - _Boundary: Legacy Scoring Integration, Scoped Admission V3 Consumer_ -- [ ] 9.3 Publish benchmark-only run, resume, and status commands +- [x] 9.3 Publish benchmark-only run, resume, and status commands - Validate settings and store capabilities before accepting source, freeze, run, resume, or status operations. - Persist durable outputs incrementally, keep scratch bounded and rebuildable, and surface workflow status from the validated journal head. - Emit deterministic operator JSON/text while leaving notifier transport, detector rollout, worker health, bucket administration, and retry policy with their owners. diff --git a/benchmarks/valid/run.py b/benchmarks/valid/run.py new file mode 100644 index 00000000..ef299e77 --- /dev/null +++ b/benchmarks/valid/run.py @@ -0,0 +1,778 @@ +"""Task 9.3 benchmark-only operator run, resume, and status commands. + +The entry point validates settings and store capabilities before any run, +resume, or status operation is accepted, drives the committed admission seams +in order while appending durable journal heartbeats between phases, and +renders one deterministic operator projection per command. Notifier transport, +detector rollout, worker health, bucket administration, and retry policy stay +with their owning workflows: no command constructs a client, administers a +bucket, or writes detector or infrastructure state. +""" + +from __future__ import annotations + +import json +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from enum import StrEnum +from typing import TypeVar, cast + +from benchmarks.valid.admission_execution import ( + AdmissionExecutionError, + AdmissionExecutionV1, +) +from benchmarks.valid.admission_orchestrator import ( + AdmissionOrchestrator, + AdmissionOrchestratorError, + AdmissionPreflightV1, + AdmissionRunRequestV1, + IsolatedArmExecutor, +) +from benchmarks.valid.admission_replay import ( + AdmissionReplayError, + ScopedReplayPublicationV1, +) +from benchmarks.valid.admission_spend import AdmissionSpendError, AdmissionSpendReleaseV1 +from benchmarks.valid.arm_contract import RegisteredEvaluationPlanV1 +from benchmarks.valid.artifact_repository import ( + ArtifactActorRole, + ArtifactReadAuthority, + ArtifactRepositoryError, + S3ArtifactRepository, + S3ObjectClient, + artifact_read_authority, +) +from benchmarks.valid.custody_probe_contract import CustodyCapabilityReport +from benchmarks.valid.durable_custody_store import S3DurableCustodyStore +from benchmarks.valid.isolated_execution_bundle import LabelBlindExecutionBundleV1 +from benchmarks.valid.lifecycle import BaselineLifecycleAuthority +from benchmarks.valid.observation_checkpoint import CheckpointSelectorV1, ObservationCheckpointAdapter +from benchmarks.valid.operator_report import ( + ResolvedOperatorReplay, + operator_report_bytes, + operator_report_text, + resolve_operator_replay, +) +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 ( + AcceptedArtifact, + ArtifactAccessClass, + ArtifactKind, + ArtifactReference, + artifact_reference, + canonical_artifact_bytes, + canonical_json_bytes, +) +from benchmarks.valid.sealed_retry import ( + AutomaticRetryError, + AutomaticRetryStatus, + RetryMismatchAuthorityV1, + resume_pre_spend_sealed_retry, +) +from benchmarks.valid.sealed_retry_recovery import resume_spent_sealed_run +from benchmarks.valid.store_configuration import ( + RetentionProfile, + StoreCapabilityEvidence, + StoreConfiguration, + StorePurpose, + StoreStartupError, + StoreStartupReport, + StoreStartupStatus, + assess_store_startup, + load_store_configuration, + require_store_startup, + store_namespace_identity, +) +from benchmarks.valid.workflow_journal import ( + S3WorkflowJournal, + S3WorkflowJournalClient, + WorkflowJournalEntryV1, + WorkflowJournalError, + WorkflowJournalReason, + WorkflowJournalStatus, + successor_head, +) +from benchmarks.valid.workflow_outcome import ( + BenchmarkWorkflowOutcomeV1, + DegradationCode, + WorkflowCounts, + WorkflowPhase, + WorkflowReasonCode, + WorkflowStatus, + decode_workflow_outcome, + workflow_outcome_bytes, +) +from openultrasast.core.canonical import JsonValue, content_digest +from openultrasast.core.custody import PopulationCustodyPolicy, PopulationStatus +from openultrasast.core.evaluation_replay import EvaluationReplayV3 + +OPERATOR_COMMAND_SCHEMA = "openultrasast.valid-detection-benchmark.operator-command.v1" +OPERATOR_READ_POLICY_DIGEST = content_digest("operator-command-read-policy") +OPERATOR_OUTCOME_PROVENANCE = content_digest({"stage": "operator-command-outcome"}) + + +class OperatorCommandKind(StrEnum): + """Closed benchmark-only command surface.""" + + RUN = "run" + RESUME = "resume" + STATUS = "status" + + +class OperatorCommandReason(StrEnum): + """Closed refusal reasons; the error never echoes caller content.""" + + SETTINGS_INVALID = "settings_invalid" + CAPABILITIES_UNSUPPORTED = "capabilities_unsupported" + INVALID_REQUEST = "invalid_request" + WORKFLOW_UNKNOWN = "workflow_unknown" + WORKFLOW_SUPERSEDED = "workflow_superseded" + OUTCOME_PENDING = "outcome_pending" + OUTCOME_UNRESOLVED = "outcome_unresolved" + RESUME_BLOCKED = "resume_blocked" + + +class OperatorCommandError(RuntimeError): + """Refuse one command with a closed reason before or during operation.""" + + def __init__(self, reason: OperatorCommandReason) -> None: + self.reason = reason + super().__init__(f"operator_command_{reason.value}") + + +_SEAM_REFUSALS = ( + AdmissionExecutionError, + AdmissionOrchestratorError, + AdmissionReplayError, + AdmissionSpendError, + AutomaticRetryError, + WorkflowJournalError, +) + + +@dataclass(frozen=True) +class BenchmarkOperatorContextV1: + """Stores bound to one validated configuration; commands never build clients.""" + + configuration: StoreConfiguration + journal: S3WorkflowJournal + repository: S3ArtifactRepository + custody: S3DurableCustodyStore + orchestrator: AdmissionOrchestrator + + +@dataclass(frozen=True) +class OperatorCommandResultV1: + """One deterministic operator projection with its durable outcome reference.""" + + command: OperatorCommandKind + outcome: BenchmarkWorkflowOutcomeV1 + report_bytes: bytes + report_text: str + outcome_reference: ArtifactReference | None + + +@dataclass(frozen=True) +class BenchmarkRunStagesV1: + """The committed execute/spend/replay/publish seams driven in order.""" + + execution: Callable[[AdmissionPreflightV1], AdmissionExecutionV1] + spend: Callable[[AdmissionExecutionV1], AdmissionSpendReleaseV1] + replay: Callable[[AdmissionSpendReleaseV1], EvaluationReplayV3] + publication: Callable[[EvaluationReplayV3], ScopedReplayPublicationV1] + + +@dataclass(frozen=True) +class BenchmarkRunRequestV1: + """Operator authorities for one run plus its progress counts and runtime.""" + + preflight_request: AdmissionRunRequestV1 + stages: BenchmarkRunStagesV1 + counts: WorkflowCounts + runtime_ms: int = 0 + + +@dataclass(frozen=True) +class BenchmarkResumeRequestV1: + """Operator authorities one resume needs after the expired validated head.""" + + workflow_digest: str + admission_identity_digest: str + component_index: int + bundles: tuple[LabelBlindExecutionBundleV1, ...] + checkpoint_selectors: tuple[CheckpointSelectorV1, ...] + plan: RegisteredEvaluationPlanV1 + adapter: ObservationCheckpointAdapter + artifact_authority: ArtifactReadAuthority + manifest: LabelBlindPopulationManifestV3 + public_material_manifest: PublicPopulationMaterialManifestV1 + selection: OrdinarySelectionV1 + lifecycle_authority: BaselineLifecycleAuthority + mismatch_authority: RetryMismatchAuthorityV1 | None = None + access_policy_digest: str = "" + attempt_id: str = "" + lease_owner_id: str = "" + heartbeat_at: str = "" + lease_expires_at: str = "" + now: str = "" + runtime_ms: int = 0 + + +@dataclass(frozen=True) +class BenchmarkStatusRequestV1: + """Head identity, terminal-outcome reference, and replay for validation.""" + + workflow_digest: str + now: str + population_digest: str + freeze_digest: str + plan_digest: str + outcome_reference: ArtifactReference | None + replay: EvaluationReplayV3 | None + + +def validated_operator_configuration( + environ: Mapping[str, str], evidence: Mapping[StorePurpose, StoreCapabilityEvidence] +) -> StoreConfiguration: + """Validate settings and capabilities before any operation is accepted.""" + try: + report = assess_store_startup(environ, evidence) + require_store_startup(report) + return load_store_configuration(environ) + except StoreStartupError as error: + raise OperatorCommandError(_startup_reason(error.report)) from None + + +def _startup_reason(report: StoreStartupReport) -> OperatorCommandReason: + if report.status is StoreStartupStatus.MISSING_CONFIGURATION: + return OperatorCommandReason.SETTINGS_INVALID + return OperatorCommandReason.CAPABILITIES_UNSUPPORTED + + +def bound_operator_context( + configuration: StoreConfiguration, + durable_client: S3ObjectClient, + transient_client: S3WorkflowJournalClient, + lifecycle_authority: BaselineLifecycleAuthority, + custody_policy: PopulationCustodyPolicy, + capability_report: CustodyCapabilityReport, + transient_identity: str, + transient_profile: RetentionProfile, + executor: IsolatedArmExecutor, + custodian_access_policy_digest: str, +) -> BenchmarkOperatorContextV1: + """Bind every store the commands may touch to the validated configuration.""" + _validated_configuration(configuration) + repository = S3ArtifactRepository(configuration.durable, durable_client) + journal = S3WorkflowJournal(configuration.transient, transient_client) + custody = S3DurableCustodyStore( + configuration.durable, durable_client, custody_policy, capability_report, transient_identity, transient_profile + ) + orchestrator = AdmissionOrchestrator( + lifecycle_authority, repository, custody, journal, executor, custodian_access_policy_digest + ) + return BenchmarkOperatorContextV1(configuration, journal, repository, custody, orchestrator) + + +def _validated_configuration(configuration: object) -> None: + if ( + type(configuration) is not StoreConfiguration + or configuration.durable.purpose is not StorePurpose.DURABLE # type: ignore[attr-defined] + or configuration.transient.purpose is not StorePurpose.TRANSIENT # type: ignore[attr-defined] + or store_namespace_identity(configuration.durable) # type: ignore[attr-defined] + == store_namespace_identity(configuration.transient) # type: ignore[attr-defined] + ): + raise OperatorCommandError(OperatorCommandReason.INVALID_REQUEST) + + +def _validated_context(context: object) -> None: + if ( + type(context) is not BenchmarkOperatorContextV1 + or type(context.journal) is not S3WorkflowJournal # type: ignore[attr-defined] + or type(context.repository) is not S3ArtifactRepository # type: ignore[attr-defined] + or type(context.custody) is not S3DurableCustodyStore # type: ignore[attr-defined] + or type(context.orchestrator) is not AdmissionOrchestrator # type: ignore[attr-defined] + ): + raise OperatorCommandError(OperatorCommandReason.INVALID_REQUEST) + _validated_configuration(context.configuration) # type: ignore[attr-defined] + + +class _Interrupted(Exception): + """Internal marker carrying the phase a non-seam crash interrupted.""" + + def __init__(self, phase: WorkflowPhase) -> None: + self.phase = phase + + +def benchmark_run_command( + context: BenchmarkOperatorContextV1, request: BenchmarkRunRequestV1 +) -> OperatorCommandResultV1: + """Preflight, then execute, spend, replay, and publish with durable heartbeats.""" + _validated_context(context) + _validated_run_request(request) + preflight = context.orchestrator.preflight(request.preflight_request) + if preflight.insufficient_outcome is not None: + return _terminal_result(context, OperatorCommandKind.RUN, preflight.insufficient_outcome) + try: + execution = _phase(context, request, WorkflowPhase.ARM_EXECUTION, request.stages.execution, preflight) + if execution.impaired_outcome is not None: + return _terminal_result(context, OperatorCommandKind.RUN, execution.impaired_outcome) + release = _phase(context, request, WorkflowPhase.CUSTODY_SPEND, request.stages.spend, execution) + if release.refusal_reason is not None: + return _terminal_result( + context, OperatorCommandKind.RUN, _spend_refused(request, release) + ) + replay = _phase(context, request, WorkflowPhase.SCORING, request.stages.replay, release) + publication = _phase(context, request, WorkflowPhase.REPORTING, request.stages.publication, replay) + except _Interrupted as interrupted: + return _terminal_result(context, OperatorCommandKind.RUN, _interrupted(context, request, interrupted.phase)) + return _completed_result(context, publication, replay) + + +def _spend_refused( + request: BenchmarkRunRequestV1, release: AdmissionSpendReleaseV1 +) -> BenchmarkWorkflowOutcomeV1: + prior = request.preflight_request + return BenchmarkWorkflowOutcomeV1( + WorkflowStatus.IMPAIRED, + WorkflowPhase.LABEL_RELEASE, + (WorkflowReasonCode.INSTRUMENT_FAILURE,), + prior.population_digest, + prior.freeze_digest, + prior.plan.plan_digest, + prior.workflow_digest, + release.labels_spent, + request.counts, + (), + (), + request.runtime_ms, + "", + "", + None, + "", + ) + + +def _validated_run_request(request: object) -> None: + if ( + type(request) is not BenchmarkRunRequestV1 + or type(request.preflight_request) is not AdmissionRunRequestV1 # type: ignore[attr-defined] + or type(request.stages) is not BenchmarkRunStagesV1 # type: ignore[attr-defined] + or type(request.counts) is not WorkflowCounts # type: ignore[attr-defined] + or type(request.runtime_ms) is not int # type: ignore[attr-defined] + or not 0 <= request.runtime_ms <= 1 << 31 # type: ignore[attr-defined] + or not callable(request.stages.execution) # type: ignore[attr-defined] + or not callable(request.stages.spend) # type: ignore[attr-defined] + or not callable(request.stages.replay) # type: ignore[attr-defined] + or not callable(request.stages.publication) # type: ignore[attr-defined] + ): + raise OperatorCommandError(OperatorCommandReason.INVALID_REQUEST) + + +_T = TypeVar("_T") + + +def _phase( + context: BenchmarkOperatorContextV1, + request: BenchmarkRunRequestV1, + phase: WorkflowPhase, + stage: Callable[..., _T], + prior: object, +) -> _T: + try: + product = stage(prior) + except _SEAM_REFUSALS: + raise + except Exception: + raise _Interrupted(phase) from None + _heartbeat(context, request, phase) + return product + + +def _heartbeat(context: BenchmarkOperatorContextV1, request: BenchmarkRunRequestV1, phase: WorkflowPhase) -> None: + prior = context.journal.current_head(request.preflight_request.workflow_digest) + entry = WorkflowJournalEntryV1( + request.preflight_request.workflow_digest, + prior.sequence + 1, + prior.entry_digest, + request.preflight_request.attempt_id, + request.preflight_request.lease_owner_id, + phase, + request.preflight_request.heartbeat_at, + request.preflight_request.lease_expires_at, + request.counts, + "", + ) + head = successor_head(prior, entry) + if not context.journal.append_and_swap(prior.head_digest, entry, head): + raise OperatorCommandError(OperatorCommandReason.WORKFLOW_SUPERSEDED) + + +def _interrupted( + context: BenchmarkOperatorContextV1, request: BenchmarkRunRequestV1, phase: WorkflowPhase +) -> BenchmarkWorkflowOutcomeV1: + prior = request.preflight_request + spent = context.custody.current_log(prior.population_digest).status is PopulationStatus.SPENT + return BenchmarkWorkflowOutcomeV1( + WorkflowStatus.IMPAIRED, + phase, + (WorkflowReasonCode.INTERRUPTED,), + prior.population_digest, + prior.freeze_digest, + prior.plan.plan_digest, + prior.workflow_digest, + spent, + request.counts, + (), + (), + request.runtime_ms, + "", + "", + None, + "", + ) + + +def _completed_result( + context: BenchmarkOperatorContextV1, + publication: ScopedReplayPublicationV1, + replay: EvaluationReplayV3, +) -> OperatorCommandResultV1: + reference = _persist_terminal_outcome(context, publication.outcome) + resolved = _resolved_replay(context, publication.outcome.evaluation_replay_ref, replay) + return _rendered(OperatorCommandKind.RUN, publication.outcome, resolved, reference) + + +def _terminal_result( + context: BenchmarkOperatorContextV1, command: OperatorCommandKind, outcome: BenchmarkWorkflowOutcomeV1 +) -> OperatorCommandResultV1: + reference = _persist_terminal_outcome(context, outcome) + return _rendered(command, outcome, None, reference) + + +def benchmark_resume_command( + context: BenchmarkOperatorContextV1, request: BenchmarkResumeRequestV1 +) -> OperatorCommandResultV1: + """Resume one interrupted workflow from the durable store via the 8.6 seams.""" + _validated_context(context) + _validated_resume_request(request) + _require_workflow(context, request.workflow_digest, request.now) + counts = WorkflowCounts( + len(request.plan.registrations), 0, len(request.plan.declaration.expected_observation_slots), 0, 0 + ) + head = context.journal.acquire_expired_lease( + request.workflow_digest, + context.journal.current_head(request.workflow_digest).head_digest, + request.attempt_id, + request.lease_owner_id, + phase=WorkflowPhase.ARM_EXECUTION, + counts=counts, + heartbeat_at=request.heartbeat_at, + lease_expires_at=request.lease_expires_at, + ) + if head is None: + raise OperatorCommandError(OperatorCommandReason.WORKFLOW_SUPERSEDED) + outcome = _resume_outcome(context, request) + return _terminal_result(context, OperatorCommandKind.RESUME, outcome) + + +def _validated_resume_request(request: object) -> None: + if ( + type(request) is not BenchmarkResumeRequestV1 + or type(request.bundles) is not tuple # type: ignore[attr-defined] + or not request.bundles # type: ignore[attr-defined] + or type(request.plan) is not RegisteredEvaluationPlanV1 # type: ignore[attr-defined] + or type(request.component_index) is not int # type: ignore[attr-defined] + or not 0 <= request.component_index < len(request.bundles) # type: ignore[attr-defined] + or type(request.artifact_authority) is not ArtifactReadAuthority # type: ignore[attr-defined] + or type(request.manifest) is not LabelBlindPopulationManifestV3 # type: ignore[attr-defined] + or type(request.public_material_manifest) is not PublicPopulationMaterialManifestV1 # type: ignore[attr-defined] + or type(request.selection) is not OrdinarySelectionV1 # type: ignore[attr-defined] + or type(request.lifecycle_authority) is not BaselineLifecycleAuthority # type: ignore[attr-defined] + or type(request.checkpoint_selectors) is not tuple # type: ignore[attr-defined] + or len(request.checkpoint_selectors) != len(request.bundles) # type: ignore[attr-defined] + or type(request.runtime_ms) is not int # type: ignore[attr-defined] + or not callable(getattr(request.adapter, "execute", None)) # type: ignore[attr-defined] + ): + raise OperatorCommandError(OperatorCommandReason.INVALID_REQUEST) + _validated_identity( + request, # type: ignore[arg-type] + ( + "workflow_digest", + "admission_identity_digest", + "access_policy_digest", + "attempt_id", + "lease_owner_id", + "heartbeat_at", + "lease_expires_at", + "now", + ), + ) + + +def _validated_identity(request: BenchmarkResumeRequestV1, names: tuple[str, ...]) -> None: + for name in names: + if type(getattr(request, name)) is not str or not getattr(request, name): + raise OperatorCommandError(OperatorCommandReason.INVALID_REQUEST) + + +def _resume_outcome( + context: BenchmarkOperatorContextV1, request: BenchmarkResumeRequestV1 +) -> BenchmarkWorkflowOutcomeV1: + population = request.bundles[0].population_digest + spent = context.custody.current_log(population).status is PopulationStatus.SPENT + if spent: + resume_spent_sealed_run( + admission_identity_digest=request.admission_identity_digest, + bundles=request.bundles, + checkpoint_selectors=_resume_selectors(request), + plan=request.plan, + journal=context.journal, + workflow_digest=request.workflow_digest, + repository=context.repository, + access_policy_digest=request.access_policy_digest, + custody=context.custody, + ) + return _resume_envelope(request, (WorkflowReasonCode.INTERRUPTED,), WorkflowPhase.CUSTODY_SPEND, True) + result = resume_pre_spend_sealed_retry( + component_index=request.component_index, + admission_identity_digest=request.admission_identity_digest, + bundles=request.bundles, + checkpoint_selectors=_resume_selectors(request), + plan=request.plan, + adapter=request.adapter, + journal=context.journal, + workflow_digest=request.workflow_digest, + repository=context.repository, + artifact_authority=request.artifact_authority, + access_policy_digest=request.access_policy_digest, + manifest=request.manifest, + public_material_manifest=request.public_material_manifest, + selection=request.selection, + lifecycle_authority=request.lifecycle_authority, + custody=context.custody, + mismatch_authority=request.mismatch_authority, + ) + reasons = ( + (WorkflowReasonCode.INTERRUPTED,) + if result.status is AutomaticRetryStatus.RESUMED + else (WorkflowReasonCode.INSTRUMENT_FAILURE,) + ) + if result.status is AutomaticRetryStatus.BLOCKED: + raise OperatorCommandError(OperatorCommandReason.RESUME_BLOCKED) + return _resume_envelope(request, reasons, WorkflowPhase.ARM_EXECUTION, False) + + +def _resume_selectors(request: BenchmarkResumeRequestV1) -> tuple[CheckpointSelectorV1, ...]: + selectors = request.checkpoint_selectors + if any(selector is None or type(selector) is not CheckpointSelectorV1 for selector in selectors): + raise OperatorCommandError(OperatorCommandReason.INVALID_REQUEST) + return selectors # type: ignore[return-value] + + +def _resume_envelope( + request: BenchmarkResumeRequestV1, + reasons: tuple[WorkflowReasonCode, ...], + phase: WorkflowPhase, + spent: bool, +) -> BenchmarkWorkflowOutcomeV1: + bundle = request.bundles[0] + return BenchmarkWorkflowOutcomeV1( + WorkflowStatus.IMPAIRED, + phase, + reasons, + bundle.population_digest, + bundle.freeze_digest, + request.plan.plan_digest, + request.workflow_digest, + spent, + WorkflowCounts( + len(request.plan.registrations), 0, len(request.plan.declaration.expected_observation_slots), 0, 0 + ), + (), + (DegradationCode.AUTOMATIC_RETRY_USED,), + request.runtime_ms, + "", + "", + None, + "", + ) + + +def benchmark_status_command( + context: BenchmarkOperatorContextV1, request: BenchmarkStatusRequestV1 +) -> OperatorCommandResultV1: + """Surface terminal outcomes first, else the validated journal head projection.""" + _validated_context(context) + _validated_status_request(request) + outcome, resolved = _terminal_outcome(context, request) + if outcome is None: + outcome = _head_projection(context, request, _require_workflow(context, request.workflow_digest, request.now)) + return _rendered(OperatorCommandKind.STATUS, outcome, resolved, request.outcome_reference) + + +def _validated_status_request(request: object) -> None: + if ( + type(request) is not BenchmarkStatusRequestV1 + or type(request.outcome_reference) is not ArtifactReference # type: ignore[attr-defined] + and request.outcome_reference is not None # type: ignore[attr-defined] + or type(request.population_digest) is not str # type: ignore[attr-defined] + or not request.population_digest # type: ignore[attr-defined] + or type(request.freeze_digest) is not str # type: ignore[attr-defined] + or not request.freeze_digest # type: ignore[attr-defined] + or type(request.plan_digest) is not str # type: ignore[attr-defined] + or not request.plan_digest # type: ignore[attr-defined] + or type(request.workflow_digest) is not str # type: ignore[attr-defined] + or not request.workflow_digest # type: ignore[attr-defined] + or type(request.now) is not str # type: ignore[attr-defined] + or not request.now # type: ignore[attr-defined] + ): + raise OperatorCommandError(OperatorCommandReason.INVALID_REQUEST) + if request.replay is not None and type(request.replay) is not EvaluationReplayV3: # type: ignore[attr-defined] + raise OperatorCommandError(OperatorCommandReason.INVALID_REQUEST) + + +def _require_workflow( + context: BenchmarkOperatorContextV1, workflow_digest: str, now: str +) -> WorkflowJournalStatus: + try: + return context.journal.rebuild_status(workflow_digest, now) + except WorkflowJournalError as error: + if error.reason is WorkflowJournalReason.NOT_FOUND: + raise OperatorCommandError(OperatorCommandReason.WORKFLOW_UNKNOWN) from None + raise + + +def _terminal_outcome( + context: BenchmarkOperatorContextV1, request: BenchmarkStatusRequestV1 +) -> tuple[BenchmarkWorkflowOutcomeV1 | None, ResolvedOperatorReplay | None]: + if request.outcome_reference is None: + return (None, None) + accepted = _operator_read(context, request.outcome_reference, ArtifactKind.WORKFLOW) + try: + outcome = decode_workflow_outcome(canonical_json_bytes(accepted.artifact.payload)) + except Exception: + raise OperatorCommandError(OperatorCommandReason.OUTCOME_UNRESOLVED) from None + if outcome.workflow_digest != request.workflow_digest: + raise OperatorCommandError(OperatorCommandReason.OUTCOME_UNRESOLVED) + return (outcome, _resolved_replay(context, outcome.evaluation_replay_ref, request.replay)) + + +def _resolved_replay( + context: BenchmarkOperatorContextV1, reference: ArtifactReference | None, replay: EvaluationReplayV3 | None +) -> ResolvedOperatorReplay | None: + if reference is None: + if replay is not None: + raise OperatorCommandError(OperatorCommandReason.OUTCOME_UNRESOLVED) + return None + if replay is None: + raise OperatorCommandError(OperatorCommandReason.OUTCOME_UNRESOLVED) + content = _operator_read(context, reference, ArtifactKind.REPLAY).content + return resolve_operator_replay(reference, content, replay) + + +def _operator_read( + context: BenchmarkOperatorContextV1, reference: ArtifactReference, kind: ArtifactKind +) -> AcceptedArtifact: + authority = artifact_read_authority( + ArtifactActorRole.OPERATOR, + (), + OPERATOR_READ_POLICY_DIGEST, + expected_access_policy_digest=OPERATOR_READ_POLICY_DIGEST, + ) + try: + return context.repository.get( + reference, expected_kind=kind, authority=authority, expected_access_policy_digest=OPERATOR_READ_POLICY_DIGEST + ) + except (ArtifactRepositoryError, RecursionError): + raise OperatorCommandError(OperatorCommandReason.OUTCOME_UNRESOLVED) from None + + +def _head_projection( + context: BenchmarkOperatorContextV1, + request: BenchmarkStatusRequestV1, + journal_status: WorkflowJournalStatus, +) -> BenchmarkWorkflowOutcomeV1: + if not journal_status.lease_expired: + raise OperatorCommandError(OperatorCommandReason.OUTCOME_PENDING) + status, reason = journal_status.projected_status, journal_status.projected_reason + if status is None or reason is None: + raise OperatorCommandError(OperatorCommandReason.OUTCOME_PENDING) + spent = context.custody.current_log(request.population_digest).status is PopulationStatus.SPENT + return BenchmarkWorkflowOutcomeV1( + status, + journal_status.phase, + (reason,), + request.population_digest, + request.freeze_digest, + request.plan_digest, + request.workflow_digest, + spent, + journal_status.counts, + (), + (), + 0, + "", + "", + None, + "", + ) + + +def _persist_terminal_outcome( + context: BenchmarkOperatorContextV1, outcome: BenchmarkWorkflowOutcomeV1 +) -> ArtifactReference: + payload = cast("dict[str, JsonValue]", json.loads(workflow_outcome_bytes(outcome))) + content = canonical_artifact_bytes( + ArtifactKind.WORKFLOW, + payload, + access_class=ArtifactAccessClass.OPERATOR_SAFE, + provenance_digest=content_digest( + {"provenance": OPERATOR_OUTCOME_PROVENANCE, "outcome": outcome.outcome_digest} + ), + ) + reference = artifact_reference(content) + try: + context.repository.put_if_absent(content, reference=reference) + except ArtifactRepositoryError: + raise OperatorCommandError(OperatorCommandReason.OUTCOME_UNRESOLVED) from None + reread = _operator_read(context, reference, ArtifactKind.WORKFLOW) + if reread.content != content: + raise OperatorCommandError(OperatorCommandReason.OUTCOME_UNRESOLVED) + return reference + + +def _rendered( + command: OperatorCommandKind, + outcome: BenchmarkWorkflowOutcomeV1, + resolved: ResolvedOperatorReplay | None, + reference: ArtifactReference | None, +) -> OperatorCommandResultV1: + return OperatorCommandResultV1( + command, + outcome, + operator_report_bytes(outcome, resolved), + operator_report_text(outcome, resolved), + reference, + ) + + +__all__ = [ + "OPERATOR_COMMAND_SCHEMA", + "BenchmarkOperatorContextV1", + "BenchmarkResumeRequestV1", + "BenchmarkRunRequestV1", + "BenchmarkRunStagesV1", + "BenchmarkStatusRequestV1", + "OperatorCommandError", + "OperatorCommandKind", + "OperatorCommandReason", + "OperatorCommandResultV1", + "benchmark_resume_command", + "benchmark_run_command", + "benchmark_status_command", + "bound_operator_context", + "validated_operator_configuration", +] diff --git a/tests/test_valid_benchmark_run.py b/tests/test_valid_benchmark_run.py new file mode 100644 index 00000000..41418eac --- /dev/null +++ b/tests/test_valid_benchmark_run.py @@ -0,0 +1,743 @@ +"""Task 9.3 benchmark-only operator run, resume, and status commands.""" + +from __future__ import annotations + +import json +import sys +from dataclasses import dataclass, replace +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from detection_core_fixtures import stored_artifact # noqa: E402 +from test_valid_benchmark_admission_execution import ( # noqa: E402 + WORKFLOW, + _Adapter, + _admission_review, + _case, + _selectors, +) +from test_valid_benchmark_admission_replay import PLANNED_ARMS, _scoped_replay # noqa: E402 +from test_valid_benchmark_admission_spend import ( # noqa: E402 + _label_bytes, + _LabelSource, + _scope_census, +) +from test_valid_benchmark_orchestrator import ( # noqa: E402 + ACCESS_POLICY, + CUSTODIAN, + _attestation, + _Client, + _digest, + _lifecycle, + _policy, + _settings, + _SpyExecutor, +) +from test_valid_benchmark_orchestrator import WORKFLOW as PREFLIGHT_WORKFLOW # noqa: E402 +from test_valid_benchmark_orchestrator import ( + _case as _preflight_case, +) + +from benchmarks.valid import run # noqa: E402 +from benchmarks.valid.admission_execution import execute_planned_observations # noqa: E402 +from benchmarks.valid.admission_replay import ReplayPublicationRequestV1, publish_scoped_replay # noqa: E402 +from benchmarks.valid.admission_spend import ( # noqa: E402 + AdmissionSpendError, + AdmissionSpendRequestV1, + commit_spend_and_release, + decode_sealed_labels, + join_released_cases, + label_open_request, + release_review_subject, +) +from benchmarks.valid.artifact_repository import ( # noqa: E402 + ArtifactActorRole, + ArtifactReadPermission, + S3ArtifactRepository, + artifact_object_location, + artifact_read_authority, +) +from benchmarks.valid.durable_custody_store import S3DurableCustodyStore # noqa: E402 +from benchmarks.valid.replacement_artifact_contract import canonical_json_bytes # noqa: E402 +from benchmarks.valid.sealed_retry import resolve_head_selected_retry_authority # noqa: E402 +from benchmarks.valid.store_configuration import ( # noqa: E402 + StoreCapabilityEvidence, + StoreConfiguration, + StorePurpose, +) +from benchmarks.valid.workflow_journal import S3WorkflowJournal # noqa: E402 +from benchmarks.valid.workflow_outcome import ( # noqa: E402 + DegradationCode, + WorkflowCounts, + WorkflowPhase, + WorkflowReasonCode, + WorkflowStatus, +) +from openultrasast.core.custody import ( # noqa: E402 + PopulationCustodyPolicy, + PopulationStatus, + derive_population_custody_policy_digest, + empty_population_custody_log, + record_population_use, +) + +LEASE_EXPIRES = "2026-11-21T09:30:00Z" +LATER = "2026-11-21T10:00:00Z" +LATER_LEASE = "2026-11-21T10:30:00Z" +DURABLE_PREFIXES = ( + "reservations/", + "reviews/", + "lifecycles/", + "populations/", + "observations/", + "workflows/", + "reports/", + "replays/", + "custody/", +) + + +def _environ() -> dict[str, str]: + environ: dict[str, str] = {} + for purpose in StorePurpose: + prefix = f"VALID_BENCHMARK_{purpose.value.upper()}" + environ[f"{prefix}_S3_ENDPOINT"] = f"https://{purpose.value}.invalid:9000" + environ[f"{prefix}_S3_BUCKET"] = f"valid-{purpose.value}" + environ[f"{prefix}_AWS_ACCESS_KEY_ID"] = "ACCESS-SECRET" + environ[f"{prefix}_AWS_SECRET_ACCESS_KEY"] = "SECRET-SECRET" + return environ + + +def _evidence() -> dict[StorePurpose, StoreCapabilityEvidence]: + return { + StorePurpose.DURABLE: StoreCapabilityEvidence(StorePurpose.DURABLE, True, True, True, None, 30), + StorePurpose.TRANSIENT: StoreCapabilityEvidence(StorePurpose.TRANSIENT, True, True, True, 14, 1), + } + + +class _RecordingClient(_Client): + def __init__(self) -> None: + super().__init__() + self.operations: list[str] = [] + + def put_object(self, **kwargs: object) -> dict[str, object]: + self.operations.append(f"put:{kwargs['Key']}") + return super().put_object(**kwargs) + + def get_object(self, **kwargs: object) -> dict[str, object]: + self.operations.append(f"get:{kwargs['Key']}") + return super().get_object(**kwargs) + + +class _CrashingLoader: + """Crash exactly between the committed custody CAS and the first label byte.""" + + def __init__(self, payload: bytes) -> None: + self.payload = payload + self.reads = 0 + + def __call__(self) -> bytes: + self.reads += 1 + raise RuntimeError("crash between custody CAS and label load") + + +class _RaceClient(_Client): + """Swap the journal head through a rival lease exactly at the next entry write.""" + + def __init__(self) -> None: + super().__init__() + self._armed = False + self._rival = None + + def arm(self, rival) -> None: + self._armed = True + self._rival = rival + + def put_object(self, **kwargs: object) -> dict[str, object]: + key = str(kwargs["Key"]) + if self._armed and kwargs.get("IfNoneMatch") == "*" and key.startswith(f"workflow/{WORKFLOW}/entries/"): + self._armed = False + assert self._rival is not None + self._rival() + return super().put_object(**kwargs) + + +@dataclass +class _Stores: + durable: _RecordingClient + transient: _RecordingClient + repository: S3ArtifactRepository + custody: S3DurableCustodyStore + journal: S3WorkflowJournal + custody_policy: PopulationCustodyPolicy + + +def _stores(case, durable: _RecordingClient, transient: _RecordingClient) -> _Stores: + repository = S3ArtifactRepository(_settings(StorePurpose.DURABLE), durable) + custody_policy = PopulationCustodyPolicy((CUSTODIAN,), derive_population_custody_policy_digest((CUSTODIAN,))) + custody = S3DurableCustodyStore( + _settings(StorePurpose.DURABLE), durable, custody_policy, case.report, case.transient_identity, case.transient_profile + ) + assert custody.initialize(empty_population_custody_log(case.freeze.population_digest, CUSTODIAN)) + return _Stores( + durable, + transient, + repository, + custody, + S3WorkflowJournal(_settings(StorePurpose.TRANSIENT), transient), + custody_policy, + ) + + +class _CommandEnv: + """Execution-case environment whose stages call the committed seams.""" + + def __init__(self, case=None, *, factory=None, transient_client=None) -> None: + self.case = case if case is not None else _case() + stores = _stores( + self.case, + _RecordingClient(), + transient_client if transient_client is not None else _RecordingClient(), + ) + self.durable, self.transient = stores.durable, stores.transient + self.repository, self.custody, self.journal = stores.repository, stores.custody, stores.journal + self.custody_policy = stores.custody_policy + self.adapter = _Adapter(factory if factory is not None else self.case.default_factory) + self.population = self.case.freeze.population_digest + self.loader = _LabelSource(_label_bytes(self.case.freeze), self.custody, self.population) + self.disclosure, self.resolver = stored_artifact(b'{"conflicts":[]}', artifact_id="run-release-disclosures") + self.last_execution = None + + def lifecycle(self): + return _lifecycle(self.population, self.case.freeze.freeze_digest) + + def context(self): + return run.bound_operator_context( + run.validated_operator_configuration(_environ(), _evidence()), + self.durable, + self.transient, + self.lifecycle(), + self.custody_policy, + self.case.report, + self.case.transient_identity, + self.case.transient_profile, + _SpyExecutor(), + ACCESS_POLICY, + ) + + def counts(self) -> WorkflowCounts: + planned_inputs = len(self.case.manifest.input_digests) + return WorkflowCounts(len(self.case.plan.registrations), 0, planned_inputs, 0, planned_inputs) + + def run_request(self, stages, **preflight_overrides: object): + return run.BenchmarkRunRequestV1(self.case.run_request(**preflight_overrides), stages, self.counts(), 250) + + def release_review(self, execution, loader): + manifest = execution.admission_manifest + assert manifest is not None + try: + cases = join_released_cases( + execution, + self.repository, + ACCESS_POLICY, + decode_sealed_labels(loader.payload), + self.case.freeze.positive_change_digests, + _scope_census(self.case.freeze), + ) + prior = self.custody.current_log(self.population) + request = label_open_request(self.population, manifest.manifest_digest, prior.log_digest) + subject = release_review_subject( + manifest.manifest_digest, + record_population_use(request, prior, CUSTODIAN, self.custody_policy).receipt_digest, + cases, + loader.payload, + ) + except AdmissionSpendError: + subject = _digest("underivable-release-subject") + return _attestation(subject, _digest("release-producer"), self.disclosure) + + def spend_request(self, execution, loader) -> AdmissionSpendRequestV1: + value: dict[str, object] = { + "execution": execution, + "custody": self.custody, + "repository": self.repository, + "custodian_access_policy_digest": ACCESS_POLICY, + "custody_policy": self.custody_policy, + "custodian_identity": CUSTODIAN, + "population_digest": self.population, + "positive_change_digests": self.case.freeze.positive_change_digests, + "scope_census": _scope_census(self.case.freeze), + "load_labels": loader, + "review": self.release_review(execution, loader), + "review_policy": _policy(), + "resolver": self.resolver, + } + return AdmissionSpendRequestV1(**value) + + def publication_request(self, replay_value) -> ReplayPublicationRequestV1: + declaration = replay_value.plan_manifest.declaration + return ReplayPublicationRequestV1( + repository=self.repository, + replay=replay_value, + planned_arm_ids=PLANNED_ARMS, + planned_input_count=len({slot.input_identity_digest for slot in declaration.expected_observation_slots}), + population_digest=declaration.population_digest, + freeze_digest=declaration.freeze_digest, + plan_digest=replay_value.plan_manifest.manifest_digest, + workflow_digest=WORKFLOW, + runtime_ms=321, + ) + + def stages(self, *, replay=None, spend_loader=None, crash_before_spend=False, pending_review=False, after_execution=None): + case = self.case + + def _execution(preflight): + review = None if pending_review else _admission_review(case) + product = execute_planned_observations( + self.lifecycle(), + self.repository, + self.custody, + self.journal, + ACCESS_POLICY, + case.execution_request(preflight, adapter=self.adapter, review=review), + ) + self.last_execution = product + if after_execution is not None: + after_execution() + return product + + def _spend(execution): + if crash_before_spend: + raise RuntimeError("interrupted before custody spend") + return commit_spend_and_release(self.spend_request(execution, self.loader if spend_loader is None else spend_loader)) + + def _replay(release): + return replay + + def _publication(replay_value): + return publish_scoped_replay(self.publication_request(replay_value)) + + return run.BenchmarkRunStagesV1(_execution, _spend, _replay, _publication) + + def resume_request(self, **overrides: object): + authority = resolve_head_selected_retry_authority(self.journal, self.repository, ACCESS_POLICY, WORKFLOW) + value: dict[str, object] = { + "workflow_digest": WORKFLOW, + "admission_identity_digest": authority.admission_identity_digest, + "component_index": 0, + "bundles": self.case.bundles, + "checkpoint_selectors": _selectors(self.last_execution), + "plan": self.case.plan, + "adapter": self.adapter, + "artifact_authority": _custodian(), + "manifest": self.case.manifest, + "public_material_manifest": self.case.material, + "selection": self.case.selection, + "lifecycle_authority": self.lifecycle(), + "mismatch_authority": None, + "access_policy_digest": ACCESS_POLICY, + "attempt_id": "attempt-2", + "lease_owner_id": "owner-b", + "heartbeat_at": LATER, + "lease_expires_at": LATER_LEASE, + "now": LATER, + "runtime_ms": 0, + } + value.update(overrides) + return run.BenchmarkResumeRequestV1(**value) + + def status_request(self, outcome_reference=None, replay=None, *, now=LATER): + return run.BenchmarkStatusRequestV1( + WORKFLOW, + now, + self.population, + self.case.freeze.freeze_digest, + self.case.plan.plan_digest, + outcome_reference, + replay, + ) + + +class _PreflightEnv: + """Orchestrator-case environment for the preflight-insufficient path.""" + + def __init__(self) -> None: + self.case = _preflight_case(small_scope_claimed=True) + stores = _stores(self.case, _RecordingClient(), _RecordingClient()) + self.durable, self.transient = stores.durable, stores.transient + self.repository, self.custody, self.journal = stores.repository, stores.custody, stores.journal + self.custody_policy = stores.custody_policy + + def lifecycle(self): + return _lifecycle(self.case.freeze.population_digest, self.case.freeze.freeze_digest) + + def context(self): + return run.bound_operator_context( + run.validated_operator_configuration(_environ(), _evidence()), + self.durable, + self.transient, + self.lifecycle(), + self.custody_policy, + self.case.report, + self.case.transient_identity, + self.case.transient_profile, + _SpyExecutor(), + ACCESS_POLICY, + ) + + def run_request(self): + planned_inputs = len(self.case.manifest.input_digests) + counts = WorkflowCounts(len(self.case.plan.registrations), 0, planned_inputs, 0, planned_inputs) + return run.BenchmarkRunRequestV1(self.case.request(), run.BenchmarkRunStagesV1(*_never_stages()), counts, 250) + + def status_request(self, outcome_reference=None): + return run.BenchmarkStatusRequestV1( + PREFLIGHT_WORKFLOW, + LATER, + self.case.freeze.population_digest, + self.case.freeze.freeze_digest, + self.case.plan.plan_digest, + outcome_reference, + None, + ) + + +def _custodian(): + return artifact_read_authority( + ArtifactActorRole.CUSTODIAN, + (ArtifactReadPermission.CUSTODIAN_SEALED, ArtifactReadPermission.PRIVATE), + ACCESS_POLICY, + expected_access_policy_digest=ACCESS_POLICY, + ) + + +def _never_stages(): + def _refused(prior): + raise AssertionError("stages must not run after an insufficient preflight") + + return (_refused, _refused, _refused, _refused) + + +def _custody_status(env) -> PopulationStatus: + return env.custody.current_log(env.case.freeze.population_digest).status + + +def test_command_entry_refuses_invalid_settings_and_capabilities_before_any_operation() -> None: + missing = _environ() + missing.pop("VALID_BENCHMARK_TRANSIENT_S3_BUCKET") + with pytest.raises(run.OperatorCommandError) as settings_refusal: + run.validated_operator_configuration(missing, _evidence()) + assert settings_refusal.value.reason is run.OperatorCommandReason.SETTINGS_INVALID + + unsupported = _evidence() + unsupported[StorePurpose.TRANSIENT] = StoreCapabilityEvidence(StorePurpose.TRANSIENT, True, False, True, 14, 1) + with pytest.raises(run.OperatorCommandError) as capability_refusal: + run.validated_operator_configuration(_environ(), unsupported) + assert capability_refusal.value.reason is run.OperatorCommandReason.CAPABILITIES_UNSUPPORTED + + environment = _CommandEnv() + before = (list(environment.durable.operations), list(environment.transient.operations)) + with pytest.raises(run.OperatorCommandError) as collision: + run.validated_operator_configuration( + _environ() | {"VALID_BENCHMARK_TRANSIENT_S3_BUCKET": "valid-durable"}, unsupported + ) + assert collision.value.reason in { + run.OperatorCommandReason.SETTINGS_INVALID, + run.OperatorCommandReason.CAPABILITIES_UNSUPPORTED, + } + assert (environment.durable.operations, environment.transient.operations) == before + + +def test_commands_refuse_a_context_not_bound_to_validated_settings() -> None: + environment = _CommandEnv() + crashed = _CommandEnv() + run.benchmark_run_command(crashed.context(), crashed.run_request(crashed.stages(crash_before_spend=True))) + colliding = StoreConfiguration( + replace( + _settings(StorePurpose.DURABLE), + bucket="valid-transient", + endpoint="https://transient.invalid:9000", + ), + _settings(StorePurpose.TRANSIENT), + ) + bound_orchestrator = environment.context().orchestrator + before = (list(environment.durable.operations), list(environment.transient.operations)) + with pytest.raises(run.OperatorCommandError) as refused: + context = run.bound_operator_context( + colliding, + environment.durable, + environment.transient, + environment.lifecycle(), + environment.custody_policy, + environment.case.report, + environment.case.transient_identity, + environment.case.transient_profile, + _SpyExecutor(), + ACCESS_POLICY, + ) + assert refused.value.reason is run.OperatorCommandReason.INVALID_REQUEST + assert str(refused.value) == "operator_command_invalid_request" + context = run.BenchmarkOperatorContextV1( + colliding, + environment.journal, + environment.repository, + environment.custody, + bound_orchestrator, + ) + for command in ( + lambda: run.benchmark_status_command(context, environment.status_request()), + lambda: run.benchmark_resume_command(context, crashed.resume_request()), + ): + with pytest.raises(run.OperatorCommandError) as direct: + command() + assert direct.value.reason is run.OperatorCommandReason.INVALID_REQUEST + assert (environment.durable.operations, environment.transient.operations) == before + + +def test_run_command_completes_with_incremental_durable_outputs_and_deterministic_reports(monkeypatch) -> None: + _, replay = _scoped_replay(monkeypatch) + environment = _CommandEnv() + result = run.benchmark_run_command(environment.context(), environment.run_request(environment.stages(replay=replay))) + + assert result.command is run.OperatorCommandKind.RUN + assert result.outcome.status is WorkflowStatus.COMPLETED + assert result.outcome.labels_spent is True + assert result.outcome.workflow_digest == WORKFLOW + assert result.outcome.evaluation_replay_ref is not None + assert result.outcome_reference is not None + assert _custody_status(environment) is PopulationStatus.SPENT + journal_status = environment.journal.rebuild_status(WORKFLOW, LATER) + assert journal_status.chain_length >= 4 + assert journal_status.phase is not None + assert any(key.startswith(f"workflow/{WORKFLOW}/entries/") for key in environment.transient.versions) + assert any(operation.startswith("put:workflows/") for operation in environment.durable.operations) + assert any(operation.startswith("put:replays/") for operation in environment.durable.operations) + + canonical_bytes = canonical_json_bytes(json.loads(result.report_bytes)) + assert canonical_bytes == result.report_bytes + assert result.report_text.isascii() + + repeated = _CommandEnv() + repeat = run.benchmark_run_command(repeated.context(), repeated.run_request(repeated.stages(replay=replay))) + assert repeat.report_bytes == result.report_bytes + assert repeat.report_text == result.report_text + assert repeat.outcome.outcome_digest == result.outcome.outcome_digest + + +def test_run_command_surfaces_preflight_insufficiency_without_spend_or_execution() -> None: + environment = _PreflightEnv() + result = run.benchmark_run_command(environment.context(), environment.run_request()) + + assert result.outcome.status is WorkflowStatus.INSUFFICIENT + assert result.outcome.reason_codes == (WorkflowReasonCode.SCOPE_INSUFFICIENT,) + assert result.outcome.labels_spent is False + assert result.outcome_reference is not None + assert _custody_status(environment) is PopulationStatus.AVAILABLE + assert environment.transient.versions == {} + + status = run.benchmark_status_command(environment.context(), environment.status_request(result.outcome_reference)) + assert status.outcome.status is WorkflowStatus.INSUFFICIENT + assert status.report_bytes == result.report_bytes + + with pytest.raises(run.OperatorCommandError) as unknown: + run.benchmark_status_command(environment.context(), environment.status_request()) + assert unknown.value.reason is run.OperatorCommandReason.WORKFLOW_UNKNOWN + + +def test_run_command_surfaces_the_seam_impaired_product_without_spend() -> None: + environment = _CommandEnv() + result = run.benchmark_run_command(environment.context(), environment.run_request(environment.stages(pending_review=True))) + + assert result.outcome.status is WorkflowStatus.IMPAIRED + assert result.outcome.labels_spent is False + assert _custody_status(environment) is PopulationStatus.AVAILABLE + + +def test_interrupted_pre_spend_run_resumes_from_the_durable_store_without_rerun_or_release() -> None: + environment = _CommandEnv() + interrupted = run.benchmark_run_command( + environment.context(), environment.run_request(environment.stages(crash_before_spend=True)) + ) + + assert interrupted.outcome.status is WorkflowStatus.IMPAIRED + assert interrupted.outcome.reason_codes == (WorkflowReasonCode.INTERRUPTED,) + assert interrupted.outcome.labels_spent is False + assert interrupted.outcome_reference is not None + assert _custody_status(environment) is PopulationStatus.AVAILABLE + executions_before = len(environment.adapter.calls) + + resumed = run.benchmark_resume_command(environment.context(), environment.resume_request()) + + assert resumed.command is run.OperatorCommandKind.RESUME + assert resumed.outcome.status is WorkflowStatus.IMPAIRED + assert resumed.outcome.reason_codes == (WorkflowReasonCode.INTERRUPTED,) + assert resumed.outcome.labels_spent is False + assert resumed.outcome.degradation_codes == (DegradationCode.AUTOMATIC_RETRY_USED,) + assert len(environment.adapter.calls) == executions_before + assert environment.loader.reads == 0 + assert _custody_status(environment) is PopulationStatus.AVAILABLE + assert environment.custody.current_log(environment.population).receipt_count == 0 + + +def test_interrupted_post_spend_run_resumes_without_duplicate_release() -> None: + environment = _CommandEnv() + loader = _CrashingLoader(_label_bytes(environment.case.freeze)) + interrupted = run.benchmark_run_command( + environment.context(), environment.run_request(environment.stages(spend_loader=loader)) + ) + + assert interrupted.outcome.status is WorkflowStatus.IMPAIRED + assert interrupted.outcome.reason_codes == (WorkflowReasonCode.INSTRUMENT_FAILURE,) + assert interrupted.outcome.labels_spent is True + assert _custody_status(environment) is PopulationStatus.SPENT + + resumed = run.benchmark_resume_command(environment.context(), environment.resume_request()) + + assert resumed.outcome.status is WorkflowStatus.IMPAIRED + assert resumed.outcome.labels_spent is True + assert resumed.outcome.degradation_codes == (DegradationCode.AUTOMATIC_RETRY_USED,) + log = environment.custody.current_log(environment.population) + assert log.status is PopulationStatus.SPENT + assert log.receipt_count == 1 + assert canonical_json_bytes(json.loads(resumed.report_bytes)) == resumed.report_bytes + assert resumed.report_text.isascii() + + +def test_status_reports_stalled_only_from_the_expired_validated_head() -> None: + environment = _CommandEnv() + run.benchmark_run_command(environment.context(), environment.run_request(environment.stages(crash_before_spend=True))) + + with pytest.raises(run.OperatorCommandError) as pending: + run.benchmark_status_command(environment.context(), environment.status_request(now="2026-11-21T09:10:00Z")) + assert pending.value.reason is run.OperatorCommandReason.OUTCOME_PENDING + + stalled = run.benchmark_status_command(environment.context(), environment.status_request()) + assert stalled.outcome.status is WorkflowStatus.IMPAIRED + assert stalled.outcome.reason_codes == (WorkflowReasonCode.STALLED,) + assert stalled.outcome.labels_spent is False + assert stalled.outcome.phase is not None + + +def test_status_resolves_terminal_outcomes_bound_to_the_requested_workflow(monkeypatch) -> None: + _, replay = _scoped_replay(monkeypatch) + environment = _CommandEnv() + result = run.benchmark_run_command(environment.context(), environment.run_request(environment.stages(replay=replay))) + + status = run.benchmark_status_command( + environment.context(), environment.status_request(result.outcome_reference, replay, now=LATER_LEASE) + ) + assert status.outcome.status is WorkflowStatus.COMPLETED + assert status.report_bytes == result.report_bytes + + with pytest.raises(run.OperatorCommandError) as unresolved: + run.benchmark_status_command(environment.context(), environment.status_request(result.outcome_reference, None)) + assert unresolved.value.reason is run.OperatorCommandReason.OUTCOME_UNRESOLVED + + other = _CommandEnv() + with pytest.raises(run.OperatorCommandError) as foreign: + run.benchmark_status_command(other.context(), other.status_request(result.outcome_reference, replay)) + assert foreign.value.reason is run.OperatorCommandReason.OUTCOME_UNRESOLVED + + +def test_commands_never_mutate_detector_or_infrastructure_state(monkeypatch) -> None: + _, replay = _scoped_replay(monkeypatch) + environment = _CommandEnv() + run.benchmark_run_command(environment.context(), environment.run_request(environment.stages(replay=replay))) + run.benchmark_status_command(environment.context(), environment.status_request()) + crashed = _CommandEnv() + run.benchmark_run_command(crashed.context(), crashed.run_request(crashed.stages(crash_before_spend=True))) + run.benchmark_resume_command(crashed.context(), crashed.resume_request()) + + for env in (environment, crashed): + methods = {operation.split(":", 1)[0] for operation in env.durable.operations + env.transient.operations} + assert methods <= {"put", "get"} + assert all( + operation.split(":", 1)[1].startswith(DURABLE_PREFIXES) for operation in env.durable.operations + ) + assert all( + operation.split(":", 1)[1].startswith(f"workflow/{WORKFLOW}/") for operation in env.transient.operations + ) + assert not any("detector" in operation or "lifecycle-policy" in operation for operation in env.durable.operations) + + +def test_status_refuses_hostile_outcome_bytes_without_a_traceback() -> None: + environment = _CommandEnv() + result = run.benchmark_run_command( + environment.context(), environment.run_request(environment.stages(crash_before_spend=True)) + ) + reference = result.outcome_reference + assert reference is not None + location = artifact_object_location(_settings(StorePurpose.DURABLE), reference) + hostile = b'{"schema_version":' + b"[" * 60000 + environment.durable.put_object(Bucket=location.bucket, Key=location.key, Body=hostile) + + with pytest.raises(run.OperatorCommandError) as refused: + run.benchmark_status_command(environment.context(), environment.status_request(reference)) + + assert refused.value.reason is run.OperatorCommandReason.OUTCOME_UNRESOLVED + assert str(refused.value) == "operator_command_outcome_unresolved" + + +def test_run_command_reports_workflow_superseded_after_a_mid_run_head_race() -> None: + race = _RaceClient() + environment = _CommandEnv(transient_client=race) + + def _rival() -> None: + rival = S3WorkflowJournal(_settings(StorePurpose.TRANSIENT), race) + rival.acquire_expired_lease( + WORKFLOW, + rival.current_head(WORKFLOW).head_digest, + "attempt-rival", + "owner-rival", + phase=WorkflowPhase.ARM_EXECUTION, + counts=environment.counts(), + heartbeat_at=LATER, + lease_expires_at=LATER_LEASE, + ) + + with pytest.raises(run.OperatorCommandError) as superseded: + run.benchmark_run_command( + environment.context(), + environment.run_request(environment.stages(after_execution=lambda: race.arm(_rival))), + ) + + assert superseded.value.reason is run.OperatorCommandReason.WORKFLOW_SUPERSEDED + assert str(superseded.value) == "operator_command_workflow_superseded" + assert _custody_status(environment) is PopulationStatus.AVAILABLE + assert environment.loader.reads == 0 + + +def test_resume_command_reports_blocked_when_the_seam_terminally_blocks() -> None: + environment = _CommandEnv() + run.benchmark_run_command(environment.context(), environment.run_request(environment.stages(crash_before_spend=True))) + ineligible = _lifecycle(environment.population, environment.case.freeze.freeze_digest, active=False) + + with pytest.raises(run.OperatorCommandError) as blocked: + run.benchmark_resume_command( + environment.context(), environment.resume_request(lifecycle_authority=ineligible) + ) + + assert blocked.value.reason is run.OperatorCommandReason.RESUME_BLOCKED + assert str(blocked.value) == "operator_command_resume_blocked" + assert _custody_status(environment) is PopulationStatus.AVAILABLE + assert environment.loader.reads == 0 + + +def test_command_refusals_stay_closed_without_caller_content() -> None: + environment = _CommandEnv() + with pytest.raises(run.OperatorCommandError) as invalid: + run.benchmark_run_command(environment.context(), replace(environment.run_request(environment.stages()), stages=None)) + assert invalid.value.reason is run.OperatorCommandReason.INVALID_REQUEST + assert str(invalid.value) == "operator_command_invalid_request" + + crashed = _CommandEnv() + run.benchmark_run_command(crashed.context(), crashed.run_request(crashed.stages(crash_before_spend=True))) + with pytest.raises(run.OperatorCommandError) as unknown: + run.benchmark_resume_command( + crashed.context(), crashed.resume_request(workflow_digest=_digest("missing-workflow")) + ) + assert unknown.value.reason is run.OperatorCommandReason.WORKFLOW_UNKNOWN + assert str(unknown.value) == "operator_command_workflow_unknown"