diff --git a/.kiro/specs/valid-detection-benchmark/tasks.md b/.kiro/specs/valid-detection-benchmark/tasks.md index b89f1efa..fd72fa46 100644 --- a/.kiro/specs/valid-detection-benchmark/tasks.md +++ b/.kiro/specs/valid-detection-benchmark/tasks.md @@ -384,7 +384,7 @@ - _Requirements: 1.1, 1.2, 1.3, 1.4, 2.6, 3.2, 3.3, 3.4, 5.3, 5.7, 5.8, 5.9, 6.1, 6.2, 6.3, 6.4, 6.5, 6.6, 6.7, 8.1, 8.2, 8.3, 9.1, 9.2, 9.3, 9.4, 9.6, 9.7, 10.1_ - _Boundary: Replacement Benchmark End-to-End Integration_ - _Depends: 8.6, 9.3_ -- [ ] 11.4 Run the spend-ordering, crash, retry, and failure-visibility matrix +- [x] 11.4 Run the spend-ordering, crash, retry, and failure-visibility matrix - Inject insufficient scope, missing arm, zero read, skipped stage, early exit, timeout, budget/resource exhaustion, failed CAS, after-spend interruption, scoring failure, publication failure, expired lease, and stale resume owner. - Assert no pre-spend failure calls the label loader, all post-spend failures preserve spent state, and exact resume never reruns a completed arm. - Require every failure to produce a closed insufficient/impaired reason rather than a clean metric or invented infrastructure diagnosis. @@ -454,3 +454,4 @@ - Task 10.4/10.5 reviews (2026-11-22), advisories forwarded to the next owners: (a) `cohort_selection.py` `_ledger_facts` accepts a non-tuple `pending_entries` iterable from forged in-process ledgers without STATE_MISMATCH (durable paths enforce tuple-of-digests upstream; failure direction is starvation, never acceptance) — one-line isinstance guard; (b) `positive_set_closure.py` `_validate_closure` lacks the `type() is int` strict check on `total_accepted_positives` (forged float 40.0/bool decodes; no gate can flip; integers are equally forgeable, store authority is the integrity boundary) — one-line strict-int guard; (c) `_pending_by_ecosystem` docstring equivalence claim is false in the CONFLICTING_ACCEPTED_REVIEW corner (committed third-round marks the entry answered, fourth-round conservatively keeps it pending; fail-safe direction, committed behavior untouched) — docstring fix only. Real cohorts for rounds 3 and 4 remain PENDING external review records; the 10.5 combined-set closure (48 positives, both ecosystems, 5 families) is fixture-verified only. - Task 11.1 review (2026-11-22), advisory forwarded to the reservation-identity owner (pre-dates 11.1; load-bearing before the 11.6 real run): `reservation_identity.py:70` strips the `.git` suffix case-sensitively (`removesuffix(".git")`), and `reservation_guard.py:178` repeats the case-sensitive strip after an IGNORECASE regex, so a mixed-case `https://GITHUB.com/ACME/Core.GIT` URL normalizes to a distinct identity and escapes the reservation scan (admission still fails closed via the reviewed-registry check in population_freeze). Fix: case-insensitive suffix normalization at both sites + adversarial test. Also: the `license_class` conjunct of the public-material gate (`population_materials.py:92`) has no independent mismatch fixture (non-permissive class + allowlisted expression); one-line addition to the confidentiality suite when next owned. - Task 11.3 review (2026-11-23), items for the 11.6 owner: (a) run.py's `bind_case_adapter_replay_stage`/`AdmissionCaseAdapterRequestV1` re-exports match the `BenchmarkRunStagesV1.replay` seam but have no in-repo consumer yet — 11.6 must adopt the preparation-rooted spend (`derive_case_adapter_preparation`; the CAS receipt must be minted from `preparation.label_release_request`, an 8.3-style `label_open_request` receipt can never satisfy core `_exact_successor_receipt`, proven) or the seam stays declaration-only; (b) the e2e synthetic population uses 20 ordinary pushes TOTAL for 40 positives with relaxed Wilson precision — the literal 3.2 ratio (>=20 per positive) and production precision bind real admission populations (10.6 proved the ratio at draw time); (c) `admission_spend.join_released_cases` now joins positives by `underlying_push_digest` (structurally necessary: core pins `projection.case_input_digest == ref.case_input_digest` at evaluation_observation.py:121 while sealed labels key raw identities) — 11.6 population builders must key both sides consistently; (d) hostile-decode parse hooks in `replacement_artifact_contract._decode_canonical` are defense-in-depth (downstream canonical re-encoding independently rejects non-finite values) — keep, but do not treat hook removal alone as a regression signal. +- Task 11.4 review (2026-11-23), item for the 11.6 owner (11.7 backstop): a run stage returning `None` instead of a product escapes `benchmark_run_command` as a raw `AttributeError` at run.py:445 (`_persist_terminal_outcome` on `None.outcome`; reviewer probe reproduced). Fails loud, never clean, and is a miswired caller contract rather than an operational failure — but 11.6 wires the production stages and owns run.py next: either type-check stage returns (closed INVALID_REQUEST/refusal) or document the seam contract. Optional hardening for the next fixtures owner: `CountingCrashLoader` (tests/valid_benchmark_failure_injection.py) counts reads without asserting custody SPENT itself (committed `_LabelSource` does); ordering violations are still caught via spent-state assertions and the committed pre-CAS refusal. diff --git a/tests/test_valid_benchmark_failure_matrix.py b/tests/test_valid_benchmark_failure_matrix.py new file mode 100644 index 00000000..102ee633 --- /dev/null +++ b/tests/test_valid_benchmark_failure_matrix.py @@ -0,0 +1,448 @@ +"""Task 11.4 spend-ordering, crash, retry, and failure-visibility matrix. + +The failure-matrix sibling of the 11.3 end-to-end suite: every injected +pre-spend, post-spend, and workflow failure over the same synthetic +two-ecosystem population must converge to the exact durable terminal +outcome or replay, never restore untouched custody, never rerun a +completed arm, and never surface as a clean metric or a raw exception. +""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from test_valid_benchmark_admission_execution import _selectors # noqa: E402 +from test_valid_benchmark_end_to_end import _LabelSource, _operator_context # noqa: E402 +from test_valid_benchmark_orchestrator import _settings # noqa: E402 +from valid_benchmark_e2e_fixtures import ( # noqa: E402 + E2E_CUSTODIAN, + PLANNED_ARMS, + WORKFLOW, + E2EEnvironment, + E2EPopulation, +) +from valid_benchmark_failure_injection import ( # noqa: E402 + EXPECTED_FAILURE_SLUGS, + RECORDS, + BoomAdapter, + CountingCrashLoader, + ExecutionDefect, + FailureRun, + OutcomeRefusingClient, + adapter_request, + defect_marker, + population_labels, + racing_environment, + record_failure, + resume_request, +) + +from benchmarks.valid import run # noqa: E402 +from benchmarks.valid.admission_execution import AdmissionExecutionReason # noqa: E402 +from benchmarks.valid.admission_replay import ( # noqa: E402 + AdmissionReplayError, + AdmissionReplayReason, + ReplayPublicationRequestV1, + publish_scoped_replay, +) +from benchmarks.valid.artifact_repository import S3ArtifactRepository # noqa: E402 +from benchmarks.valid.replacement_artifact_contract import canonical_json_bytes # noqa: E402 +from benchmarks.valid.store_configuration import StorePurpose # noqa: E402 +from benchmarks.valid.workflow_journal import ( # noqa: E402 + S3WorkflowJournal, + WorkflowJournalEntryV1, + WorkflowJournalError, + WorkflowJournalReason, + successor_head, +) +from benchmarks.valid.workflow_outcome import ( # noqa: E402 + WorkflowCounts, + WorkflowPhase, + WorkflowReasonCode, + WorkflowStatus, +) +from openultrasast.core.custody import PopulationStatus # noqa: E402 + +NOW_LATER = "2026-11-23T10:30:00Z" + + +def _population_digest(failure: FailureRun) -> str: + return failure.case.freeze.population_digest + + +def _log(failure: FailureRun): + return failure.environment.store.current_log(_population_digest(failure)) + + +def _assert_pre_spend_instrument_failure(failure: FailureRun) -> None: + result = failure.result + assert result.outcome.status is WorkflowStatus.IMPAIRED + assert result.outcome.reason_codes == (WorkflowReasonCode.INSTRUMENT_FAILURE,) + assert result.outcome.labels_spent is False + assert result.outcome.evaluation_replay_ref is None + assert result.outcome.counts.completed_arms < result.outcome.counts.planned_arms + log = _log(failure) + assert log.status is PopulationStatus.AVAILABLE and log.receipt_count == 0 + assert failure.loader.reads == 0 + + +def _assert_spent_state_preserved(failure: FailureRun, *, loader_reads: int) -> None: + log = _log(failure) + assert log.status is PopulationStatus.SPENT + assert log.receipt_count == 1 + assert failure.loader.reads == loader_reads + + +def _status_request(failure: FailureRun, outcome_reference: object) -> run.BenchmarkStatusRequestV1: + return run.BenchmarkStatusRequestV1( + WORKFLOW, + NOW_LATER, + _population_digest(failure), + failure.case.freeze.freeze_digest, + failure.case.plan.plan_digest, + outcome_reference, + None, + ) + + +def test_insufficient_scope_preflight_spends_nothing_and_reads_no_labels() -> None: + population = E2EPopulation(mint_cases=False, minimum_ordinary=15) + assert population.freeze.positive_count == 40 + environment = E2EEnvironment(population) + loader = _LabelSource(population.labels, environment.store, population.freeze.population_digest) + adapter = BoomAdapter("insufficient scope must never execute an arm") + + def _refused(prior: object) -> object: + loader() + adapter.execute(None) + raise AssertionError("insufficient scope must never run a stage") + + stages = run.BenchmarkRunStagesV1(_refused, _refused, _refused, _refused) + counts = WorkflowCounts(len(population.plan.registrations), 0, len(population.manifest.input_digests), 0, 0) + result = run.benchmark_run_command( + _operator_context(environment), + run.BenchmarkRunRequestV1(population.run_request(), stages, counts, 250), + ) + + assert result.outcome.status is WorkflowStatus.INSUFFICIENT + assert result.outcome.reason_codes == (WorkflowReasonCode.SCOPE_INSUFFICIENT,) + assert result.outcome.labels_spent is False + log = environment.store.current_log(population.freeze.population_digest) + assert log.status is PopulationStatus.AVAILABLE and log.receipt_count == 0 + assert loader.reads == 0 + record_failure("insufficient-scope", result.outcome, result.report_text, result.report_bytes, ()) + + +def test_missing_arm_refuses_impaired_before_the_spend() -> None: + failure = FailureRun(ExecutionDefect.MISSING_ARM.value, defect=ExecutionDefect.MISSING_ARM).execute() + _assert_pre_spend_instrument_failure(failure) + product = failure.environment.last_execution + assert product is not None and product.refusal_reason is AdmissionExecutionReason.EXECUTION_IMPAIRED + + +@pytest.mark.parametrize( + "defect", + [ExecutionDefect.INPUT_UNREADABLE, ExecutionDefect.INPUT_EMPTY], +) +def test_zero_or_unreadable_input_closes_as_an_instrument_failure(defect: ExecutionDefect) -> None: + failure = FailureRun(defect.value, defect=defect).execute() + _assert_pre_spend_instrument_failure(failure) + + +@pytest.mark.parametrize( + "defect", + [ExecutionDefect.STAGE_SKIPPED, ExecutionDefect.STAGE_PREMATURE], +) +def test_skipped_stage_or_early_exit_never_reaches_the_spend(defect: ExecutionDefect) -> None: + failure = FailureRun(defect.value, defect=defect).execute() + _assert_pre_spend_instrument_failure(failure) + + +@pytest.mark.parametrize( + "defect", + [ExecutionDefect.DEADLINE_OVERRUN, ExecutionDefect.BUDGET_EXHAUSTED, ExecutionDefect.RESOURCE_LIMIT], +) +def test_timeout_budget_and_resource_exhaustion_close_as_instrument_failures(defect: ExecutionDefect) -> None: + failure = FailureRun(defect.value, defect=defect).execute() + _assert_pre_spend_instrument_failure(failure) + + +def test_adapter_crash_is_a_closed_execution_impairment() -> None: + failure = FailureRun(ExecutionDefect.ADAPTER_CRASH.value, defect=ExecutionDefect.ADAPTER_CRASH).execute() + _assert_pre_spend_instrument_failure(failure) + + +def _rival_custody_spend(failure: FailureRun) -> None: + from benchmarks.valid.admission_case_adapter import derive_case_adapter_preparation + from openultrasast.core.custody import append_population_use, record_population_use + + preparation = derive_case_adapter_preparation( + adapter_request(failure.environment, failure.environment.last_execution) + ) + store = failure.environment.store + prior = store.current_log(_population_digest(failure)) + receipt = record_population_use( + preparation.label_release_request, prior, E2E_CUSTODIAN, failure.environment.custody_policy + ) + successor = append_population_use(prior, receipt, failure.environment.custody_policy) + assert store.compare_and_swap(prior.log_digest, successor) + + +def test_failed_custody_cas_rival_wins_without_any_label_read() -> None: + failure = FailureRun("custody_cas_lost") + failure.before_cas = lambda: _rival_custody_spend(failure) + failure.execute() + + result = failure.result + assert result.outcome.status is WorkflowStatus.IMPAIRED + assert result.outcome.reason_codes == (WorkflowReasonCode.INTERRUPTED,) + assert result.outcome.phase is WorkflowPhase.CUSTODY_SPEND + assert result.outcome.evaluation_replay_ref is None + _assert_spent_state_preserved(failure, loader_reads=0) + + +def test_after_spend_interruption_preserves_spent_state_and_resume_converges() -> None: + marker = defect_marker("after_spend_interruption", "loader") + failure = FailureRun( + "after_spend_interruption", + loader=CountingCrashLoader(population_labels(), marker), + markers=(marker,), + ).execute() + + result = failure.result + assert result.outcome.status is WorkflowStatus.IMPAIRED + assert result.outcome.reason_codes == (WorkflowReasonCode.INTERRUPTED,) + assert result.outcome.labels_spent is True + assert result.outcome.evaluation_replay_ref is None + _assert_spent_state_preserved(failure, loader_reads=1) + + failure.environment.adapter = BoomAdapter("exact resume must never rerun a completed arm") + resumed = run.benchmark_resume_command( + _operator_context(failure.environment), + resume_request(failure.environment, selectors=_selectors(failure.environment.last_execution)), + ) + assert resumed.outcome.status is WorkflowStatus.IMPAIRED + assert resumed.outcome.labels_spent is True + assert resumed.outcome.degradation_codes == (run.DegradationCode.AUTOMATIC_RETRY_USED,) + _assert_spent_state_preserved(failure, loader_reads=1) + + +def test_scoring_failure_is_impaired_never_a_partial_clean_metric() -> None: + failure = FailureRun("scoring_failure", scoring_crash=True).execute() + + result = failure.result + assert result.outcome.status is WorkflowStatus.IMPAIRED + assert result.outcome.reason_codes == (WorkflowReasonCode.INTERRUPTED,) + assert result.outcome.phase is WorkflowPhase.SCORING + assert result.outcome.labels_spent is True + assert result.outcome.evaluation_replay_ref is None + _assert_spent_state_preserved(failure, loader_reads=1) + + status = run.benchmark_status_command(_operator_context(failure.environment), _status_request(failure, result.outcome_reference)) + assert status.outcome.status is WorkflowStatus.IMPAIRED + assert status.report_bytes == result.report_bytes + + +def _publication_request(failure: FailureRun, repository: object) -> ReplayPublicationRequestV1: + replay = failure.replay + assert replay is not None + declaration = replay.plan_manifest.declaration + return ReplayPublicationRequestV1( + repository=repository, + replay=replay, + 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.plan_manifest.manifest_digest, + workflow_digest=WORKFLOW, + runtime_ms=321, + ) + + +def test_publication_failure_keeps_the_validated_replay_and_never_completes() -> None: + failure = FailureRun("publication_failure", publication_crash=True).execute() + + result = failure.result + assert result.outcome.status is WorkflowStatus.IMPAIRED + assert result.outcome.reason_codes == (WorkflowReasonCode.INTERRUPTED,) + assert result.outcome.phase is WorkflowPhase.REPORTING + assert result.outcome.labels_spent is True + assert result.outcome.evaluation_replay_ref is None + _assert_spent_state_preserved(failure, loader_reads=1) + assert failure.replay is not None + + refusing = S3ArtifactRepository( + _settings(StorePurpose.DURABLE), OutcomeRefusingClient(failure.environment.durable) + ) + with pytest.raises(AdmissionReplayError) as seam: + publish_scoped_replay(_publication_request(failure, refusing)) + assert seam.value.reason is AdmissionReplayReason.PERSISTENCE_FAILED + assert str(seam.value) == "admission_replay_persistence_failed" + replay_keys = [key for key in failure.environment.durable.versions if key.startswith("replays/")] + assert replay_keys and all(failure.environment.durable.body(key) for key in replay_keys) + + recovered = publish_scoped_replay(_publication_request(failure, failure.environment.repository)) + assert recovered.outcome.status is WorkflowStatus.COMPLETED + assert recovered.replay_digest == failure.replay.replay_digest + + status = run.benchmark_status_command(_operator_context(failure.environment), _status_request(failure, result.outcome_reference)) + assert status.outcome.status is WorkflowStatus.IMPAIRED + + +def test_expired_lease_projects_stalled_never_instrument_failure() -> None: + environment = E2EEnvironment() + environment.preflight() + case = environment.case + request = run.BenchmarkStatusRequestV1( + WORKFLOW, NOW_LATER, case.freeze.population_digest, case.freeze.freeze_digest, case.plan.plan_digest, None, None + ) + + with pytest.raises(run.OperatorCommandError) as pending: + run.benchmark_status_command(_operator_context(environment), replace_now(request, "2026-11-23T09:10:00Z")) + assert pending.value.reason is run.OperatorCommandReason.OUTCOME_PENDING + + stalled = run.benchmark_status_command(_operator_context(environment), request) + assert stalled.outcome.status is WorkflowStatus.IMPAIRED + assert stalled.outcome.reason_codes == (WorkflowReasonCode.STALLED,) + assert WorkflowReasonCode.INSTRUMENT_FAILURE not in stalled.outcome.reason_codes + assert stalled.outcome.labels_spent is False + log = environment.store.current_log(case.freeze.population_digest) + assert log.status is PopulationStatus.AVAILABLE and log.receipt_count == 0 + record_failure("expired-lease", stalled.outcome, stalled.report_text, stalled.report_bytes, ()) + + +def replace_now(request: run.BenchmarkStatusRequestV1, now: str) -> run.BenchmarkStatusRequestV1: + from dataclasses import replace + + return replace(request, now=now) + + +def test_exact_resume_never_reruns_a_completed_arm_and_stale_owners_are_refused() -> None: + failure = FailureRun("pre_spend_crash_resume", crash_before_spend=True).execute() + assert failure.result.outcome.status is WorkflowStatus.IMPAIRED + assert failure.result.outcome.labels_spent is False + assert _log(failure).status is PopulationStatus.AVAILABLE + + failure.environment.adapter = BoomAdapter("exact resume must never rerun a completed arm") + resumed = run.benchmark_resume_command( + _operator_context(failure.environment), + resume_request(failure.environment, selectors=_selectors(failure.environment.last_execution)), + ) + assert resumed.outcome.status is WorkflowStatus.IMPAIRED + assert resumed.outcome.reason_codes == (WorkflowReasonCode.INTERRUPTED,) + assert resumed.outcome.labels_spent is False + assert _log(failure).receipt_count == 0 + assert failure.loader.reads == 0 + + journal = failure.environment.journal + head = journal.current_head(WORKFLOW) + counts = WorkflowCounts(len(failure.case.plan.registrations), 0, len(failure.case.manifest.input_digests), 0, 0) + stale = WorkflowJournalEntryV1( + WORKFLOW, + head.sequence + 1, + head.entry_digest, + "attempt-1", + "owner-a", + WorkflowPhase.ARM_EXECUTION, + "2026-11-23T10:45:00Z", + "2026-11-23T11:15:00Z", + counts, + "", + ) + with pytest.raises(WorkflowJournalError) as append_refused: + journal.append_and_swap(head.head_digest, stale, successor_head(head, stale)) + assert append_refused.value.reason is WorkflowJournalReason.LEASE_OWNER_MISMATCH + assert str(append_refused.value) == "workflow_journal_lease_owner_mismatch" + + with pytest.raises(WorkflowJournalError) as stale_resume: + run.benchmark_resume_command( + _operator_context(failure.environment), + resume_request( + failure.environment, + selectors=_selectors(failure.environment.last_execution), + attempt_id="attempt-1", + lease_owner_id="owner-a", + heartbeat_at="2026-11-23T10:45:00Z", + lease_expires_at="2026-11-23T11:15:00Z", + now="2026-11-23T10:45:00Z", + ), + ) + assert stale_resume.value.reason is WorkflowJournalReason.LEASE_NOT_EXPIRED + assert str(stale_resume.value) == "workflow_journal_lease_not_expired" + assert _log(failure).status is PopulationStatus.AVAILABLE and _log(failure).receipt_count == 0 + assert failure.loader.reads == 0 + record_failure( + "stale-resume-owner", + None, + str(stale_resume.value), + str(stale_resume.value).encode("ascii"), + (), + closed_text=str(append_refused.value), + ) + + +def test_mid_run_head_race_reports_workflow_superseded_without_spend() -> None: + environment = racing_environment() + race = environment.transient + counts = WorkflowCounts( + len(environment.case.plan.registrations), 0, len(environment.case.manifest.input_digests), 0, 0 + ) + + 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=counts, + heartbeat_at="2026-11-23T10:00:00Z", + lease_expires_at="2026-11-23T10:30:00Z", + ) + + failure = FailureRun("head_race", environment=environment) + failure.after_execution = lambda: race.arm(_rival) + with pytest.raises(run.OperatorCommandError) as superseded: + failure.execute() + assert superseded.value.reason is run.OperatorCommandReason.WORKFLOW_SUPERSEDED + assert str(superseded.value) == "operator_command_workflow_superseded" + log = environment.store.current_log(environment.case.freeze.population_digest) + assert log.status is PopulationStatus.AVAILABLE and log.receipt_count == 0 + assert failure.loader.reads == 0 + record_failure( + "head-race", + None, + str(superseded.value), + str(superseded.value).encode("ascii"), + (), + ) + + +def test_every_injected_failure_surfaces_a_closed_reason_never_a_clean_metric() -> None: + records = {record.slug: record for record in RECORDS} + assert set(records) == EXPECTED_FAILURE_SLUGS + closed_reasons = {code.value for code in WorkflowReasonCode} + for record in RECORDS: + assert record.report_text.isascii() + assert "Traceback (most recent call last)" not in record.report_text + for marker in record.markers: + assert marker not in record.report_text + if record.outcome is not None: + assert record.outcome.status is not WorkflowStatus.COMPLETED + assert record.outcome.evaluation_replay_ref is None + assert all(code.value in closed_reasons for code in record.outcome.reason_codes) + document = json.loads(record.report_bytes) + assert "replay" not in document + assert canonical_json_bytes(document) == record.report_bytes + else: + closed = record.closed_text or record.report_text + assert closed == closed.lower() + assert closed.isascii() and closed.replace("_", "a").isalnum() diff --git a/tests/valid_benchmark_e2e_fixtures.py b/tests/valid_benchmark_e2e_fixtures.py index c9975700..d2ac1cc8 100644 --- a/tests/valid_benchmark_e2e_fixtures.py +++ b/tests/valid_benchmark_e2e_fixtures.py @@ -648,7 +648,15 @@ class _CaseContent: class E2EPopulation: """Full synthetic two-ecosystem admission population with core case content.""" - def __init__(self, *, pairs_python: int = PAIRS_PY, pairs_javascript: int = PAIRS_JS, mint_cases: bool = True) -> None: + def __init__( + self, + *, + pairs_python: int = PAIRS_PY, + pairs_javascript: int = PAIRS_JS, + mint_cases: bool = True, + minimum_ordinary: int = 2, + ) -> None: + self.minimum_ordinary = minimum_ordinary positives = _positive_identities(pairs_python, pairs_javascript) self.freeze = _freeze(positives) self.selection = _selection(self.freeze) @@ -660,23 +668,9 @@ class E2EPopulation: scopes = tuple(sorted(((FAMILY_PY, "python"), (FAMILY_JS, "javascript")))) self.plan = register_evaluation_plan( registrations=( - _registration( - ArmRole.COMBINED, - _relax_precision( - _configuration("arm-combined", scopes, combined=True, minimum_ordinary=2, label="e2e-combined"), - _union_rule(), - ), - ), - _registration( - ArmRole.EXPERIMENTAL, - _relax_precision( - _configuration("arm-experimental", scopes, minimum_ordinary=2, label="e2e-experimental") - ), - ), - _registration( - ArmRole.SHIPPED, - _relax_precision(_configuration("arm-shipped", scopes, minimum_ordinary=2, label="e2e-shipped")), - ), + _registration(ArmRole.COMBINED, self._arm_configuration("arm-combined", scopes, combined=True)), + _registration(ArmRole.EXPERIMENTAL, self._arm_configuration("arm-experimental", scopes)), + _registration(ArmRole.SHIPPED, self._arm_configuration("arm-shipped", scopes)), ), population_digest=self.manifest.population_digest, freeze_digest=self.manifest.freeze_digest, @@ -757,6 +751,13 @@ class E2EPopulation: if mint_cases: self._mint_case_content() + def _arm_configuration(self, arm_id: str, scopes, *, combined: bool = False): + """Task 11.4 seam: minimum_ordinary beyond the census makes every scope insufficient.""" + base = _configuration( + arm_id, scopes, combined=combined, minimum_ordinary=self.minimum_ordinary, label=f"e2e-{arm_id[4:]}" + ) + return _relax_precision(base, _union_rule()) if combined else _relax_precision(base) + def _identities(self) -> tuple[_InputIdentity, ...]: rows = list(self.positive_rows.values()) pushes = {push.push_digest: push for push in self.selection.pushes} diff --git a/tests/valid_benchmark_failure_injection.py b/tests/valid_benchmark_failure_injection.py new file mode 100644 index 00000000..66b86123 --- /dev/null +++ b/tests/valid_benchmark_failure_injection.py @@ -0,0 +1,517 @@ +"""Task 11.4 failure-injection harness over the committed e2e substrate. + +Wraps the committed admission seams (the operator run stages, the execution +adapter factory, the label loader, and the fixture store clients) so one +closed instrument defect at a time can be injected without editing any +committed production module. Every injected raise carries a unique marker +string so the closing visibility sweep can prove no raw failure text ever +reaches the operator surface. +""" + +from __future__ import annotations + +import sys +from dataclasses import dataclass +from enum import StrEnum +from pathlib import Path +from typing import Any + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from test_valid_benchmark_admission_execution import ( # noqa: E402 + _Adapter, + _read_rows, + _stage_rows, +) +from test_valid_benchmark_admission_spend import _scope_census # noqa: E402 +from test_valid_benchmark_end_to_end import _LabelSource, _operator_context # noqa: E402 +from test_valid_benchmark_orchestrator import ACCESS_POLICY, _attestation, _Client, _digest, _settings # noqa: E402 +from valid_benchmark_e2e_fixtures import ( # noqa: E402 + BRIDGE_RETENTION, + E2E_CUSTODIAN, + PLANNED_ARMS, + WORKFLOW, + E2EEnvironment, + _admission_review, + _attempt_review, + _population, +) + +from benchmarks.valid import isolated_execution as execution # noqa: E402 +from benchmarks.valid import observation_checkpoint as checkpoint # noqa: E402 +from benchmarks.valid import run # noqa: E402 +from benchmarks.valid.admission_case_adapter import ( # noqa: E402 + derive_case_adapter_preparation, + derive_case_adapter_replay, +) +from benchmarks.valid.admission_case_graph import AdmissionCaseAdapterRequestV1 # noqa: E402 +from benchmarks.valid.admission_replay import ReplayPublicationRequestV1, publish_scoped_replay # noqa: E402 +from benchmarks.valid.admission_spend import ( # noqa: E402 + AdmissionSpendReleaseV1, + decode_sealed_labels, + join_released_cases, + release_review_subject, +) +from benchmarks.valid.artifact_repository import ( # noqa: E402 + ArtifactActorRole, + ArtifactReadPermission, + artifact_read_authority, +) +from benchmarks.valid.isolated_execution_contract import ProcessOutcomeReason # noqa: E402 +from benchmarks.valid.observation_receipt import InputReadStatus, StageExecutionStatus # noqa: E402 +from benchmarks.valid.replacement_artifact_contract import ( # noqa: E402 + ArtifactAccessClass, + ArtifactKind, + artifact_reference, + canonical_artifact_bytes, +) +from benchmarks.valid.sealed_retry import resolve_head_selected_retry_authority # noqa: E402 +from benchmarks.valid.store_configuration import StorePurpose # noqa: E402 +from benchmarks.valid.workflow_journal import S3WorkflowJournal # noqa: E402 +from benchmarks.valid.workflow_outcome import WorkflowCounts # noqa: E402 +from openultrasast.core import canonical # noqa: E402 +from openultrasast.core.custody import ( # noqa: E402 + PopulationStatus, + append_population_use, + record_population_use, +) + +TARGET_ARM = "arm-shipped" +RESUME_HEARTBEAT = "2026-11-23T10:30:00Z" +RESUME_LEASE_EXPIRES = "2026-11-23T11:00:00Z" + + +class ExecutionDefect(StrEnum): + """Closed instrument defects injectable into one component arm.""" + + INPUT_UNREADABLE = "input_unreadable" + INPUT_EMPTY = "input_empty" + STAGE_SKIPPED = "stage_skipped" + STAGE_PREMATURE = "stage_premature" + DEADLINE_OVERRUN = "deadline_overrun" + BUDGET_EXHAUSTED = "budget_exhausted" + RESOURCE_LIMIT = "resource_limit" + MISSING_ARM = "missing_arm" + ADAPTER_CRASH = "adapter_crash" + + +@dataclass +class FailureRecord: + """One injected failure's operator-visible durable surface.""" + + slug: str + outcome: Any + report_text: str + report_bytes: bytes + markers: tuple[str, ...] = () + closed_text: str = "" + + +RECORDS: list[FailureRecord] = [] +EXPECTED_FAILURE_SLUGS = frozenset( + { + "insufficient-scope", + "missing_arm", + "input_unreadable", + "input_empty", + "stage_skipped", + "stage_premature", + "deadline_overrun", + "budget_exhausted", + "resource_limit", + "adapter_crash", + "custody_cas_lost", + "after_spend_interruption", + "scoring_failure", + "publication_failure", + "pre_spend_crash_resume", + "expired-lease", + "stale-resume-owner", + "head-race", + } +) + + +def record_failure( + slug: str, + outcome: Any, + report_text: str, + report_bytes: bytes, + markers: tuple[str, ...], + closed_text: str = "", +) -> None: + """Register one injected failure for the closing visibility sweep.""" + RECORDS.append(FailureRecord(slug, outcome, report_text, report_bytes, tuple(markers), closed_text)) + + +def defect_marker(*labels: str) -> str: + """Unique marker carried by every injected raise; never operator-visible.""" + return "defect-marker-" + "-".join(labels) + + +def population_labels() -> bytes: + """Sealed label bytes of the shared e2e population.""" + return _population().labels + + +class BoomAdapter: + """Any execution call fails the test: completed arms must never rerun.""" + + def __init__(self, message: str) -> None: + self._message = message + + def execute(self, bundle: object) -> object: + raise AssertionError(self._message) + + +class CountingCrashLoader: + """Crash exactly between the committed custody CAS and the first label byte.""" + + def __init__(self, payload: bytes, marker: str) -> None: + self.payload = payload + self.marker = marker + self.reads = 0 + + def __call__(self) -> bytes: + self.reads += 1 + raise RuntimeError(self.marker) + + +class OutcomeRefusingClient: + """Delegate store operations but refuse durable workflow-outcome writes.""" + + def __init__(self, inner: _Client) -> None: + self._inner = inner + + def put_object(self, **kwargs: object) -> dict[str, object]: + if str(kwargs["Key"]).startswith("workflows/"): + raise RuntimeError(defect_marker("publication", "outcome-refused")) + return self._inner.put_object(**kwargs) + + def get_object(self, **kwargs: object) -> dict[str, object]: + return self._inner.get_object(**kwargs) + + +class RaceWorkflowClient(_Client): + """Swap the journal head through a rival lease exactly at the next entry write.""" + + def __init__(self, workflow: str) -> None: + super().__init__() + self._workflow = workflow + self._armed = False + self._rival = None + + def arm(self, rival: Any) -> 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/{self._workflow}/entries/"): + self._armed = False + assert self._rival is not None + self._rival() + return super().put_object(**kwargs) + + +def racing_environment() -> E2EEnvironment: + """E2E environment whose transient journal store can race the head.""" + environment = E2EEnvironment() + environment.transient = RaceWorkflowClient(WORKFLOW) + environment.journal = S3WorkflowJournal(_settings(StorePurpose.TRANSIENT), environment.transient) + return environment + + +def _last_execution(environment: E2EEnvironment) -> Any: + assert environment.last_execution is not None + return environment.last_execution + + +def adapter_request(environment: E2EEnvironment, product: Any) -> AdmissionCaseAdapterRequestV1: + """The 11.3 case-adapter request bound to one execution product.""" + case = environment.case + return AdmissionCaseAdapterRequestV1( + repository=environment.repository, + custodian_access_policy_digest=ACCESS_POLICY, + execution=product, + plan=case.plan, + selection=case.selection, + population_digest=case.freeze.population_digest, + input_count=len(case.manifest.input_digests), + custody=environment.custody, + resolver=case.evidence_resolver, + context=case.context, + readiness=case.readiness, + case_content=case.content.port, + proof_candidates=case.content.candidate_port, + census_review=case.adapter_census_review, + plan_review=case.adapter_plan_review, + admission_review=lambda subject: _attestation( + subject, _digest("e2e-adapter-admission-producer"), case.disclosure + ), + release_review=lambda subject: _attestation( + subject, _digest("e2e-adapter-release-producer"), case.disclosure + ), + bridged_store_identity="scoped-admission-v3-bridge", + bridged_retention_policy_digest=BRIDGE_RETENTION, + ) + + +def resume_request( + environment: E2EEnvironment, + *, + selectors: tuple, + attempt_id: str = "attempt-2", + lease_owner_id: str = "owner-b", + heartbeat_at: str = RESUME_HEARTBEAT, + lease_expires_at: str = RESUME_LEASE_EXPIRES, + now: str = RESUME_HEARTBEAT, +) -> run.BenchmarkResumeRequestV1: + """The 8.6 resume authorities resolved from the current CAS head.""" + authority = resolve_head_selected_retry_authority( + environment.journal, environment.repository, ACCESS_POLICY, WORKFLOW + ) + return run.BenchmarkResumeRequestV1( + workflow_digest=WORKFLOW, + admission_identity_digest=authority.admission_identity_digest, + component_index=0, + bundles=environment.case.bundles, + checkpoint_selectors=selectors, + plan=environment.case.plan, + adapter=environment.adapter, + artifact_authority=artifact_read_authority( + ArtifactActorRole.CUSTODIAN, + (ArtifactReadPermission.CUSTODIAN_SEALED, ArtifactReadPermission.PRIVATE), + ACCESS_POLICY, + expected_access_policy_digest=ACCESS_POLICY, + ), + manifest=environment.case.manifest, + public_material_manifest=environment.case.material, + selection=environment.case.selection, + lifecycle_authority=environment.lifecycle(), + mismatch_authority=None, + access_policy_digest=ACCESS_POLICY, + attempt_id=attempt_id, + lease_owner_id=lease_owner_id, + heartbeat_at=heartbeat_at, + lease_expires_at=lease_expires_at, + now=now, + runtime_ms=0, + ) + + +def injecting_adapter_factory(environment: E2EEnvironment, defect: ExecutionDefect, target_arm: str) -> Any: + """Wrap the e2e factory so one component arm reports the injected defect.""" + base = environment._factory() + + def factory(bundle: Any) -> Any: + if bundle.arm.arm_id != target_arm: + return base(bundle) + return _defective_capture(bundle, defect, base) + + return factory + + +def _defective_capture(bundle: Any, defect: ExecutionDefect, base: Any) -> Any: + if defect is ExecutionDefect.ADAPTER_CRASH: + raise RuntimeError(defect_marker(defect.value, "adapter")) + capture = base(bundle) + reads, stages = capture.input_reads, capture.stage_executions + outcome, observations = capture.process_outcome, capture.observations + if defect is ExecutionDefect.INPUT_UNREADABLE: + reads = _read_rows(bundle, status=InputReadStatus.UNREADABLE) + elif defect is ExecutionDefect.INPUT_EMPTY: + reads = _read_rows(bundle, status=InputReadStatus.EMPTY) + elif defect is ExecutionDefect.STAGE_SKIPPED: + stages = _stage_rows(status=StageExecutionStatus.SKIPPED) + elif defect is ExecutionDefect.STAGE_PREMATURE: + stages = _stage_rows(status=StageExecutionStatus.PREMATURE) + elif defect is ExecutionDefect.MISSING_ARM: + observations = () + elif defect is ExecutionDefect.DEADLINE_OVERRUN: + outcome = execution.completed_adapter_outcome( + bundle, + checkpoint.component_observation_output_bytes(capture.observations), + runtime_ms=bundle.budget.deadline_seconds * 1000 + 1, + ) + elif defect in (ExecutionDefect.BUDGET_EXHAUSTED, ExecutionDefect.RESOURCE_LIMIT): + reason = ( + ProcessOutcomeReason.BUDGET_EXHAUSTED + if defect is ExecutionDefect.BUDGET_EXHAUSTED + else ProcessOutcomeReason.RESOURCE_LIMIT + ) + outcome = execution.impaired_adapter_outcome(bundle, reason, runtime_ms=9) + return checkpoint.ArmExecutionCaptureV1(outcome, reads, stages, capture.degradations, observations) + + +def _publication_request(environment: E2EEnvironment, replay_value: Any) -> ReplayPublicationRequestV1: + declaration = replay_value.plan_manifest.declaration + return ReplayPublicationRequestV1( + repository=environment.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, + ) + + +class FailureRun: + """One operator run over the e2e population with injectable failures.""" + + def __init__( + self, + slug: str, + *, + environment: E2EEnvironment | None = None, + defect: ExecutionDefect | None = None, + target_arm: str = TARGET_ARM, + loader: Any = None, + markers: tuple[str, ...] = (), + crash_before_spend: bool = False, + scoring_crash: bool = False, + publication_crash: bool = False, + ) -> None: + self.slug = slug + self.environment = environment if environment is not None else E2EEnvironment() + self.case = self.environment.case + self.defect = defect + if defect is not None: + self.environment.adapter = _Adapter(injecting_adapter_factory(self.environment, defect, target_arm)) + self.review = None + else: + self.review = _admission_review(self.case) + self.loader = loader if loader is not None else _LabelSource( + self.case.labels, self.environment.store, self.case.freeze.population_digest + ) + self.extra_markers = markers + self.crash_before_spend = crash_before_spend + self.after_execution = None + self.before_cas = None + self.scoring_crash = scoring_crash + self.publication_crash = publication_crash + self.result = None + self.replay = None + self.publication = None + + def execute(self) -> FailureRun: + counts = WorkflowCounts( + len(self.case.plan.registrations), 0, len(self.case.manifest.input_digests), 0, len(self.case.manifest.input_digests) + ) + self.result = run.benchmark_run_command( + _operator_context(self.environment), + run.BenchmarkRunRequestV1(self.case.run_request(), self._stages(), counts, 250), + ) + record_failure( + self.slug, + self.result.outcome, + self.result.report_text, + self.result.report_bytes, + self._markers(), + ) + return self + + def _markers(self) -> tuple[str, ...]: + markers = list(self.extra_markers) + if self.crash_before_spend: + markers.append(defect_marker(self.slug, "pre-spend")) + if self.before_cas is not None: + markers.append(defect_marker(self.slug, "cas-lost")) + if self.scoring_crash: + markers.append(defect_marker(self.slug, "scoring")) + if self.publication_crash: + markers.append(defect_marker(self.slug, "publication")) + return tuple(markers) + + def _stages(self) -> run.BenchmarkRunStagesV1: + return run.BenchmarkRunStagesV1( + self._execution_stage, + self._spend_stage, + self._replay_stage, + self._publication_stage, + ) + + def _execution_stage(self, preflight: Any) -> Any: + environment, case = self.environment, self.case + product = environment.execute( + preflight, + review=self.review, + attempt_review=_attempt_review(case, preflight), + status_ref=case.status_ref, + ) + if self.after_execution is not None: + self.after_execution() + return product + + def _spend_stage(self, execution_product: Any) -> Any: + if self.crash_before_spend: + raise RuntimeError(defect_marker(self.slug, "pre-spend")) + environment, case = self.environment, self.case + preparation = derive_case_adapter_preparation(adapter_request(environment, _last_execution(environment))) + prior = environment.store.current_log(case.freeze.population_digest) + receipt = record_population_use( + preparation.label_release_request, prior, E2E_CUSTODIAN, environment.custody_policy + ) + successor = append_population_use(prior, receipt, environment.custody_policy) + if self.before_cas is not None: + self.before_cas() + if not environment.store.compare_and_swap(prior.log_digest, successor): + raise RuntimeError(defect_marker(self.slug, "cas-lost")) + return self._release_after_spend(execution_product, receipt) + + def _release_after_spend(self, execution_product: Any, receipt: Any) -> Any: + environment, case = self.environment, self.case + head = environment.store.current_log(receipt.population_digest) + assert head.status is PopulationStatus.SPENT and head.receipts[-1] == receipt + raw = self.loader() + labels = decode_sealed_labels(raw) + released = join_released_cases( + execution_product, + environment.repository, + ACCESS_POLICY, + labels, + case.freeze.positive_change_digests, + _scope_census(case.freeze), + ) + manifest = execution_product.admission_manifest + assert manifest is not None + subject = release_review_subject(manifest.manifest_digest, receipt.receipt_digest, released, raw) + value = { + "admission_manifest_digest": manifest.manifest_digest, + "custody_receipt_digest": receipt.receipt_digest, + "label_bytes_digest": canonical.bytes_digest(raw), + "label_bytes_read": len(raw), + "case_digests": tuple(row.case_digest for row in released), + } + content = canonical_artifact_bytes( + ArtifactKind.WORKFLOW, dict(value), access_class=ArtifactAccessClass.CUSTODIAN_SEALED, provenance_digest=subject + ) + reference = artifact_reference(content) + environment.repository.put_if_absent(content, reference=reference) + return AdmissionSpendReleaseV1( + None, + receipt.receipt_digest, + True, + len(raw), + canonical.bytes_digest(raw), + released, + reference, + canonical.content_digest(value), + ) + + def _replay_stage(self, release: Any) -> Any: + if self.scoring_crash: + raise RuntimeError(defect_marker(self.slug, "scoring")) + self.replay = derive_case_adapter_replay( + adapter_request(self.environment, _last_execution(self.environment)), release + ) + return self.replay + + def _publication_stage(self, replay_value: Any) -> Any: + if self.publication_crash: + raise RuntimeError(defect_marker(self.slug, "publication")) + self.publication = publish_scoped_replay(_publication_request(self.environment, replay_value)) + return self.publication