From a68796610a25eca830656c6391943fab7476e7e4 Mon Sep 17 00:00:00 2001 From: Marius Ciepluch <11855163+norandom@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:21:43 +0100 Subject: [PATCH] feat(valid-detection-benchmark): 11.5 streaming scale bounded validation and back-pressure --- .../specs/valid-detection-benchmark/tasks.md | 3 +- .../test_valid_benchmark_scale_validation.py | 295 +++++++ tests/valid_benchmark_e2e_fixtures.py | 30 +- tests/valid_benchmark_scale_support.py | 828 ++++++++++++++++++ 4 files changed, 1148 insertions(+), 8 deletions(-) create mode 100644 tests/test_valid_benchmark_scale_validation.py create mode 100644 tests/valid_benchmark_scale_support.py diff --git a/.kiro/specs/valid-detection-benchmark/tasks.md b/.kiro/specs/valid-detection-benchmark/tasks.md index fd72fa46..64ad00cc 100644 --- a/.kiro/specs/valid-detection-benchmark/tasks.md +++ b/.kiro/specs/valid-detection-benchmark/tasks.md @@ -392,7 +392,7 @@ - _Requirements: 5.2, 5.6, 5.7, 7.5, 8.3, 8.4, 8.5, 10.1, 10.2, 10.6_ - _Boundary: Admission Recovery Validation_ - _Depends: 11.3_ -- [ ] 11.5 Verify streaming scale, bounded validation, and execution back-pressure +- [x] 11.5 Verify streaming scale, bounded validation, and execution back-pressure - Exercise at least forty positives and eight hundred ordinary pushes for freeze, manifest, policy, serialization, projection, replay, and reporting operations. - Stream one object/case batch at a time, measure cold/warm workflow and per-arm runtime, and retain nonzero read/execution receipts for every measurement. - Respect adapter back-pressure without treating a busy or unavailable execution lane as a detector result or infrastructure diagnosis. @@ -455,3 +455,4 @@ - 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. +- Task 11.5 review (2026-11-23), items for the 11.6 owner: (a) RATIFIED trade-off — 11.5 ran freeze/manifest/policy/serialization/streaming at the full 840-input scale but execution/spend/release/projection/replay/reporting at a 240-input representative tier (4x the 11.3 scale), because the committed execution/sealing seam is super-linear (~n^1.67, triple-verified 7.2s@60 / 71.7s@240 / ~615s@840); a full-scale governed run needs >=2 such executions, so 11.6 must budget ~20+ minutes of execution alone and should measure again at the real population size; (b) a correctly-reviewed full-scale lifecycle has NEVER actually been completed — the 840-input probes' `manifest_invalid` refusals were probe-construction artifacts (default-population lru-cached review subject at tests/valid_benchmark_e2e_fixtures.py:1052-1058 vs per-population `_execution_subject` in tests/valid_benchmark_scale_support.py:623-632), not capacity caps; the budget ruling rests on timing alone; (c) minor: arm-runtime receipts use `max(0, ...)` clamps (a 0ms arm measurement would pass) and `runtime_ms >= 0` assertions — tighten to `> 0`/`max(1, ...)` next time the scale support module is owned. diff --git a/tests/test_valid_benchmark_scale_validation.py b/tests/test_valid_benchmark_scale_validation.py new file mode 100644 index 00000000..95251b87 --- /dev/null +++ b/tests/test_valid_benchmark_scale_validation.py @@ -0,0 +1,295 @@ +"""Task 11.5 streaming scale, bounded validation, and execution back-pressure. + +Drives the committed population, store, serialization, projection, replay, +and reporting operations over one synthetic scale population of forty +positives and eight hundred ordinary pushes (two ecosystems, two families). +Case/object batches stream one batch at a time through validation with +per-batch nonzero read receipts, cold/warm and per-arm runtime receipts, a +bounded execution lane whose busy refusal is an impairment rather than a +detector result or an infrastructure diagnosis, and truncated streams that +report impairment instead of a partial clean result. +""" + +from __future__ import annotations + +import json +import sys +import tracemalloc +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from valid_benchmark_e2e_fixtures import ( # noqa: E402 + FAMILY_JS, + FAMILY_PY, + PLANNED_ARMS, + E2EEnvironment, +) +from valid_benchmark_scale_support import ( # noqa: E402 + CORE_REPLAY_DECLARATION, + EXECUTION_TIER_INPUTS, + EXECUTION_TIER_PUSHES_PER_ECOSYSTEM, + SCALE_REQUIRED_PER_POSITIVE, + ScaleLifecycle, + StreamFault, + case_objects_factory, + component_arm_ids, + default_population_shape, + durable_bucket, + impaired_stream_outcome, + lane_refusal_texts, + measure_cold_warm, + operator_report_for_outcome, + probe_objects_factory, + prove_store_nonzero, + redaction_findings, + run_streaming_validation, + scale_lifecycle, + scale_population, + stream_with_lane, + vocabulary_findings, +) + +from benchmarks.valid import run # noqa: E402 +from benchmarks.valid.workflow_outcome import WorkflowStatus # noqa: E402 +from openultrasast.core.custody import PopulationStatus # noqa: E402 +from openultrasast.core.evaluation_measurement import MetricId # noqa: E402 + + +@pytest.fixture(scope="module") +def population(): + return scale_population() + + +@pytest.fixture(scope="module") +def chain() -> ScaleLifecycle: + return scale_lifecycle() + + +def test_scale_population_meets_target_shape_and_defaults_stay_committed() -> None: + positives, pushes, inputs = default_population_shape() + assert (positives, pushes, inputs) == (40, 20, 60) + case = scale_population() + assert case.freeze.positive_count == 40 + assert len(case.selection.pushes) == 800 + assert len(case.manifest.input_digests) == 840 + per_ecosystem: dict[str, int] = {} + for push in case.selection.pushes: + per_ecosystem[push.ecosystem] = per_ecosystem.get(push.ecosystem, 0) + 1 + assert per_ecosystem == {"javascript": 400, "python": 400} + families = {row.vulnerability_family for row in case.freeze.scope_census} + ecosystems = {row.ecosystem.value for row in case.freeze.scope_census} + assert families == {FAMILY_PY, FAMILY_JS} + assert ecosystems == {"python", "javascript"} + for row in case.freeze.scope_census: + assert row.count == 20 + + +def test_scale_freeze_manifest_and_store_policy_validate_with_nonzero_proofs(population) -> None: + environment = E2EEnvironment(population) + assert prove_store_nonzero(environment.durable, durable_bucket()) > 0 + configuration = run.validated_operator_configuration(_operator_environ(), _operator_evidence()) + assert configuration.durable.bucket + freeze = population.freeze + assert freeze.positive_count == 40 + assert freeze.population_class.value == "admission" + manifest = population.manifest + assert len(manifest.input_digests) == 840 + assert manifest.positive_count == 40 + assert manifest.input_count == 840 + label_bearing = {"label", "judgment", "role", "family_of_change", "pair"} + assert not label_bearing.intersection(manifest.__dict__) + assert population.selection.required_per_positive == SCALE_REQUIRED_PER_POSITIVE + + +def test_scale_serialization_round_trip_streams_canonically(population) -> None: + value, receipt = measure_cold_warm(lambda: _selection_bytes(population)) + assert value == _selection_bytes(population) + assert receipt.cold_ms > 0 and receipt.warm_ms > 0 + assert receipt.warm_ms <= receipt.cold_ms or receipt.registered_reason == "warm_slower_registered" + decoded = json.loads(value) + assert len(decoded["pushes"]) == 800 + assert len(decoded["assignments"]) == 40 * 800 + manifest_bytes = _manifest_bytes(population) + assert len(manifest_bytes) > 0 + assert json.loads(manifest_bytes)["input_count"] == 840 + + +def test_streaming_validation_grows_with_supplied_artifacts_per_batch(population) -> None: + small = run_streaming_validation(case_objects_factory(population, 256), 64, 256) + full = run_streaming_validation(case_objects_factory(population), 64, 840) + assert small.status is WorkflowStatus.COMPLETED and full.status is WorkflowStatus.COMPLETED + assert small.reason_codes == () and full.reason_codes == () + assert small.all_batches_nonzero and full.all_batches_nonzero + assert small.consumed_objects == 256 and full.consumed_objects == 840 + assert full.byte_count > small.byte_count > 0 + assert full.batch_count > small.batch_count > 0 + assert full.runtime_ms >= 0 and small.runtime_ms >= 0 + repeat = run_streaming_validation(case_objects_factory(population, 256), 64, 256) + assert repeat.chain_digest == small.chain_digest + + +def test_streaming_memory_is_bounded_by_batch_not_population() -> None: + """tracemalloc instrument: peak traced allocations during streaming. + + The instrument is proven honest before any boundedness claim: one full + un-instrumented pass first establishes that every batch read nonzero + bytes (all_batches_nonzero, consumed == declared). Only then are peaks + compared: doubling the batch size must grow the peak, while doubling the + total artifact count at a fixed batch size must not. + """ + instrumented = run_streaming_validation(probe_objects_factory(128), 32, 128) + assert instrumented.consumed_objects == 128 and instrumented.all_batches_nonzero + batch_peak = _traced_peak(lambda: run_streaming_validation(probe_objects_factory(128), 32, 128)) + double_batch_peak = _traced_peak(lambda: run_streaming_validation(probe_objects_factory(128), 64, 128)) + double_total_peak = _traced_peak(lambda: run_streaming_validation(probe_objects_factory(256), 32, 256)) + assert double_batch_peak > batch_peak * 1.2 + assert double_total_peak < batch_peak * 1.6 + + +def test_cold_warm_and_per_arm_runtime_receipts_are_retained(population, chain) -> None: + _value, receipt = measure_cold_warm(lambda: run_streaming_validation(case_objects_factory(population), 64, 840)) + assert receipt.cold_ms > 0 and receipt.warm_ms > 0 + assert receipt.warm_ms <= receipt.cold_ms or receipt.registered_reason == "warm_slower_registered" + component_arms = component_arm_ids(chain.population) + lane_arms = {arm for arm, _ms in chain.arm_runtimes} + assert lane_arms == set(component_arms) + assert "arm-combined" not in lane_arms + for _arm, runtime_ms in chain.arm_runtimes: + assert runtime_ms >= 0 + assert len(chain.arm_runtimes) == len(component_arms) + + +def test_execution_tier_projection_covers_every_input_without_scoring(chain: ScaleLifecycle) -> None: + projection = chain.projection + inputs = chain.population.manifest.input_digests + assert projection.whole_coverage.change_input_count == len(inputs) == EXECUTION_TIER_INPUTS + assert len(projection.whole_coverage.change_input_digests) == EXECUTION_TIER_INPUTS + for row in projection.scopes: + assert len(row.ordinary_case_digests) == EXECUTION_TIER_PUSHES_PER_ECOSYSTEM + assert len(row.vulnerable_case_digests) == len(row.fixed_case_digests) == 10 + assert chain.execution.refusal_reason is None + assert chain.environment.store.current_log(chain.population.freeze.population_digest).status is PopulationStatus.SPENT + + +def test_scale_core_replay_reports_exact_scopes_for_every_planned_arm(chain: ScaleLifecycle) -> None: + assert CORE_REPLAY_DECLARATION + replay = chain.replay + assert tuple(report.baseline.arm_id for report in replay.reports) == PLANNED_ARMS + expected_scopes = {(FAMILY_PY, "python"), (FAMILY_JS, "javascript")} + for report in replay.reports: + assert {(result.key.scope.family_id, result.key.scope.ecosystem) for result in report.scoped_results} == ( + expected_scopes + ) + for result in report.scoped_results: + for metric in result.metrics: + assert metric.denominator > 0 + assert tuple(metric.metric_id for metric in result.metrics) == tuple(MetricId) + unique = {case.underlying_push_digest for group in replay.cases_by_arm for case in group.cases} + assert replay.whole_population_coverage.underlying_push_count == len(unique) == EXECUTION_TIER_INPUTS + + +def test_scale_reporting_is_deterministic_and_redacted(chain: ScaleLifecycle) -> None: + assert chain.result.outcome.status is WorkflowStatus.COMPLETED + first = chain.result.report_bytes + second = chain.render_again() + assert first == second + assert redaction_findings(first) == () + document = json.loads(first) + assert document["status"] == "completed" + assert {arm["arm_id"] for arm in document["replay"]["arms"]} == set(PLANNED_ARMS) + + +def test_back_pressure_bounds_pending_and_busy_lane_is_an_impairment_not_a_result() -> None: + lane, record = _saturated_lane() + assert record.max_pending <= lane.maxsize + assert lane.maxsize == 2 + assert record.refused_batches > 0 + assert record.accepted_batches == lane.maxsize + assert record.outcome.status is WorkflowStatus.IMPAIRED + assert record.outcome.evaluation_replay_ref is None + assert WorkflowStatus.COMPLETED is not record.outcome.status + assert record.outcome.reason_codes + serialized = json.dumps(record.outcome.reason_codes[0].value) + assert vocabulary_findings(serialized) == () + drained = lane.drain(lane.maxsize) + assert drained == lane.maxsize + assert lane.pending() == 0 + + +def test_busy_lane_refusal_carries_no_detector_or_infrastructure_diagnosis() -> None: + _lane, record = _saturated_lane() + assert record.refusals + for text in lane_refusal_texts(record): + assert vocabulary_findings(text) == () + impaired = impaired_stream_outcome(record.receipt) + assert impaired.status is WorkflowStatus.IMPAIRED + report = operator_report_for_outcome(impaired) + document = json.loads(report) + assert document["status"] == "impaired" + assert "replay" not in document and "metrics" not in document + assert vocabulary_findings(report.decode("ascii")) == () + assert record.receipt.reason_codes + + +@pytest.mark.parametrize( + "fault", + [StreamFault.MISSING_BATCH, StreamFault.SHORT_BATCH, StreamFault.UNREADABLE_OBJECT], +) +def test_incomplete_scale_stream_reports_impairment_never_partial_clean(fault: StreamFault) -> None: + receipt = run_streaming_validation(probe_objects_factory(840), 60, 840, fault=fault) + assert receipt.status is WorkflowStatus.IMPAIRED + assert receipt.reason_codes + assert receipt.consumed_objects < 840 + outcome = impaired_stream_outcome(receipt) + assert outcome.status is WorkflowStatus.IMPAIRED + assert outcome.evaluation_replay_ref is None + report = operator_report_for_outcome(outcome) + document = json.loads(report) + assert document["status"] == "impaired" + assert "replay" not in document and "metrics" not in document + assert vocabulary_findings(report.decode("ascii")) == () + + +def _operator_environ(): + from test_valid_benchmark_run import _environ # noqa: E402 + + return _environ() + + +def _operator_evidence(): + from test_valid_benchmark_run import _evidence # noqa: E402 + + return _evidence() + + +def _selection_bytes(population) -> bytes: + from benchmarks.valid.ordinary_change_contract import ordinary_selection_bytes # noqa: E402 + + return ordinary_selection_bytes(population.selection) + + +def _manifest_bytes(population) -> bytes: + from benchmarks.valid.population_label_blind_contract import ( # noqa: E402 + label_blind_population_manifest_bytes, + ) + + return label_blind_population_manifest_bytes(population.manifest) + + +def _traced_peak(operation) -> int: + tracemalloc.start() + operation() + _current, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + return peak + + +def _saturated_lane(): + from valid_benchmark_scale_support import BoundedExecutionLane # noqa: E402 + + lane = BoundedExecutionLane(maxsize=2) + record = stream_with_lane(probe_objects_factory(840), 60, 840, lane) + return lane, record diff --git a/tests/valid_benchmark_e2e_fixtures.py b/tests/valid_benchmark_e2e_fixtures.py index d2ac1cc8..ec367524 100644 --- a/tests/valid_benchmark_e2e_fixtures.py +++ b/tests/valid_benchmark_e2e_fixtures.py @@ -250,10 +250,10 @@ def _freeze(positives: tuple[_InputIdentity, ...]) -> PopulationFreezeV3: return replace(bound, freeze_digest=canonical.content_digest(_freeze_value(bound, include_digest=False))) -def _pushes() -> tuple[OrdinaryPushV1, ...]: +def _pushes(per_ecosystem: int = 10) -> tuple[OrdinaryPushV1, ...]: rows = [] for ecosystem in ("javascript", "python"): - for index in range(10): + for index in range(per_ecosystem): draft = OrdinaryPushV1( "https://example.invalid/app.git", _digest(f"e2e-ordinary-network-{ecosystem}"), @@ -269,8 +269,21 @@ def _pushes() -> tuple[OrdinaryPushV1, ...]: return tuple(sorted(rows, key=lambda item: item.push_digest)) -def _selection(freeze: PopulationFreezeV3) -> OrdinarySelectionV1: - pushes = _pushes() +def _ordinary_census(selection: OrdinarySelectionV1) -> tuple[EcosystemOrdinaryCensusV3, ...]: + """Ecosystem ordinary census derived from the actual selection pushes.""" + counts: dict[str, int] = {} + for push in selection.pushes: + counts[push.ecosystem] = counts.get(push.ecosystem, 0) + 1 + return tuple(EcosystemOrdinaryCensusV3(ecosystem, counts[ecosystem]) for ecosystem in sorted(counts)) + + +def _selection( + freeze: PopulationFreezeV3, + pushes: tuple[OrdinaryPushV1, ...] | None = None, + required_per_positive: int | None = None, +) -> OrdinarySelectionV1: + pushes = _pushes() if pushes is None else pushes + required = 20 if required_per_positive is None else required_per_positive network = pushes[0].network_identity_digest positives = freeze.positive_change_digests assignments = tuple( @@ -295,7 +308,9 @@ def _selection(freeze: PopulationFreezeV3) -> OrdinarySelectionV1: "policy_digest": _digest("e2e-ordinary-policy"), } ) - draft = OrdinarySelectionV1(20, _digest("e2e-ordinary-policy"), positives, fix_exclusions, pushes, assignments, (), provenance, "") + draft = OrdinarySelectionV1( + required, _digest("e2e-ordinary-policy"), positives, fix_exclusions, pushes, assignments, (), provenance, "" + ) return replace(draft, selection_digest=canonical.content_digest(_selection_value(draft, include_digest=False))) @@ -655,16 +670,17 @@ class E2EPopulation: pairs_javascript: int = PAIRS_JS, mint_cases: bool = True, minimum_ordinary: int = 2, + pushes: tuple[OrdinaryPushV1, ...] | None = None, ) -> None: self.minimum_ordinary = minimum_ordinary positives = _positive_identities(pairs_python, pairs_javascript) self.freeze = _freeze(positives) - self.selection = _selection(self.freeze) + self.selection = _selection(self.freeze, pushes, None if pushes is None else len(pushes)) self.material = _material_manifest(self.freeze) self.manifest, self.manifest_review, self.disclosure, manifest_resolver = _reviewed_manifest( self.freeze, self.selection, self.material ) - self.ordinary_census = (EcosystemOrdinaryCensusV3("javascript", 10), EcosystemOrdinaryCensusV3("python", 10)) + self.ordinary_census = _ordinary_census(self.selection) scopes = tuple(sorted(((FAMILY_PY, "python"), (FAMILY_JS, "javascript")))) self.plan = register_evaluation_plan( registrations=( diff --git a/tests/valid_benchmark_scale_support.py b/tests/valid_benchmark_scale_support.py new file mode 100644 index 00000000..478a0980 --- /dev/null +++ b/tests/valid_benchmark_scale_support.py @@ -0,0 +1,828 @@ +"""Task 11.5 scale fixtures, streaming harness, and bounded execution lane. + +The scale population extends the committed 11.3 fixture machinery to forty +positives plus eight hundred ordinary pushes (four hundred per ecosystem, +twenty per positive). Case/object batches stream one batch at a time through +strict hostile-decode validation with per-batch nonzero read receipts; cold, +warm, and per-arm runtime receipts are retained as measurements rather than +asserted absolutes. The bounded execution lane refuses work beyond its +configured bound, and every truncated or unreadable stream reports an +impairment with a closed reason instead of a partial clean result. +""" + +from __future__ import annotations + +import io +import json +import math +import queue +import re +import sys +import time +from collections.abc import Callable, Iterator +from dataclasses import dataclass, replace +from enum import StrEnum +from functools import lru_cache +from itertools import islice +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from test_valid_benchmark_admission_spend import _scope_census # noqa: E402 +from test_valid_benchmark_end_to_end import _LabelSource # noqa: E402 +from test_valid_benchmark_orchestrator import ( # noqa: E402 + ACCESS_POLICY, + _attestation, + _digest, + _SpyExecutor, +) +from test_valid_benchmark_run import _environ, _evidence # noqa: E402 +from valid_benchmark_e2e_fixtures import ( # noqa: E402 + BRIDGE_RETENTION, + BRIDGE_STORE, + E2E_CUSTODIAN, + PLANNED_ARMS, + WORKFLOW, + E2EEnvironment, + E2EPopulation, + _attempt_review, + _pushes, +) + +from benchmarks.valid import run, store_configuration # 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_projection import ProjectionRequestV1, project_exact_scopes # 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.operator_report import operator_report_bytes # noqa: E402 +from benchmarks.valid.replacement_artifact_contract import ( # noqa: E402 + ArtifactAccessClass, + ArtifactKind, + artifact_reference, + canonical_artifact_bytes, +) +from benchmarks.valid.workflow_outcome import ( # noqa: E402 + BenchmarkWorkflowOutcomeV1, + WorkflowCounts, + WorkflowGate, + WorkflowPhase, + WorkflowReasonCode, + WorkflowStatus, +) +from openultrasast.core import canonical # noqa: E402 +from openultrasast.core.custody import ( # noqa: E402 + PopulationStatus, + append_population_use, + record_population_use, +) + +SCALE_PAIRS_PYTHON = 10 +SCALE_PAIRS_JAVASCRIPT = 10 +SCALE_PUSHES_PER_ECOSYSTEM = 400 +SCALE_REQUIRED_PER_POSITIVE = 2 * SCALE_PUSHES_PER_ECOSYSTEM +SCALE_POSITIVES = 2 * (SCALE_PAIRS_PYTHON + SCALE_PAIRS_JAVASCRIPT) +SCALE_ORDINARY = 2 * SCALE_PUSHES_PER_ECOSYSTEM +SCALE_INPUTS = SCALE_POSITIVES + SCALE_ORDINARY +# Execution-bound tier. The committed execution/sealing seam measured 7.4 s at +# 60 inputs and 615.6 s at 840 inputs (super-linear), so a second full-scale +# lifecycle would exceed twenty minutes on execution alone. Every positive +# (40) plus the ordinary pushes below flow through execution, the shared +# spend, the release join, the exact-scope projection, one validated core +# replay, publication, and reporting; the full 840-input population flows +# through freeze, manifest, policy, serialization, and streaming validation +# in the other tests of this suite. Declared for reviewer ratification. +EXECUTION_TIER_PUSHES_PER_ECOSYSTEM = 100 +EXECUTION_TIER_INPUTS = SCALE_POSITIVES + 2 * EXECUTION_TIER_PUSHES_PER_ECOSYSTEM +CORE_REPLAY_DECLARATION = ( + f"representative-subset: every positive (40) plus {2 * EXECUTION_TIER_PUSHES_PER_ECOSYSTEM} ordinary " + f"pushes ({EXECUTION_TIER_PUSHES_PER_ECOSYSTEM} per ecosystem, {EXECUTION_TIER_INPUTS} inputs) flow " + "through execution, spend, release, exact-scope projection, one validated " + "core replay, and reporting; the full 840-input population flows through " + "freeze, manifest, policy, serialization, and streaming validation" +) +STREAM_OBJECT_SCHEMA = "openultrasast.valid-detection-benchmark.scale-stream-object.v1" +_ZERO = "0" * 64 +_PROBE_KEY = "scale-validation/readability-probe" + + +@lru_cache(maxsize=1) +def scale_population() -> E2EPopulation: + """The full scale population: forty positives and eight hundred pushes.""" + return E2EPopulation(pushes=_pushes(SCALE_PUSHES_PER_ECOSYSTEM)) + + +def default_population_shape() -> tuple[int, int, int]: + """Committed default fixture shape (positives, pushes, manifest inputs).""" + population = E2EPopulation(mint_cases=False) + return ( + population.freeze.positive_count, + len(population.selection.pushes), + len(population.manifest.input_digests), + ) + + +def component_arm_ids(population: E2EPopulation) -> tuple[str, ...]: + """Arms that execute on an adapter lane (the combined arm is rule-derived).""" + from openultrasast.core.evaluation_measurement import ArmKindV3 # noqa: E402 + + return tuple( + row.arm_id for row in population.plan.registrations if row.configuration.kind is ArmKindV3.COMPONENT + ) + + +def durable_bucket() -> str: + return store_configuration.load_store_settings(store_configuration.StorePurpose.DURABLE, _environ()).bucket + + +def prove_store_nonzero(client: object, bucket: str) -> int: + """Write and read back one real nonzero object before interpreting results.""" + payload = b"scale-validation-readability-probe" + client.put_object(Bucket=bucket, Key=_PROBE_KEY, Body=payload, IfNoneMatch="*") + response = client.get_object(Bucket=bucket, Key=_PROBE_KEY) + body = response["Body"] + assert isinstance(body, io.BytesIO) + read_back = body.read() + assert read_back == payload and len(read_back) > 0 + return len(read_back) + + +class StreamObjectError(ValueError): + """Closed unreadable-object refusal; no caller content is echoed.""" + + +def _reject_constant(name: str) -> None: + raise StreamObjectError("nonfinite_json_constant") + + +def _finite_float(text: str) -> float: + value = float(text) + if not math.isfinite(value): + raise StreamObjectError("nonfinite_json_number") + return value + + +def strict_decode(raw: bytes) -> dict: + """Hostile-decode discipline over untrusted object bytes.""" + if type(raw) is not bytes or not raw: + raise StreamObjectError("empty_stream_object") + try: + document = json.loads(raw, parse_constant=_reject_constant, parse_float=_finite_float) + except StreamObjectError: + raise + except (RecursionError, UnicodeDecodeError, ValueError): + raise StreamObjectError("undecodable_stream_object") from None + if type(document) is not dict: + raise StreamObjectError("non_object_stream_payload") + return document + + +@dataclass(frozen=True) +class StreamObject: + """One canonical nonzero stream object with its exact content digest.""" + + index: int + raw: bytes + digest: str + + +def _object_for(index: int, payload: dict) -> StreamObject: + raw = canonical.canonical_bytes(payload) + return StreamObject(index, raw, canonical.bytes_digest(raw)) + + +def probe_objects_factory(total_objects: int) -> Callable[[], Iterator[StreamObject]]: + """Deterministic fixture-generated probe objects (no network access).""" + + def factory() -> Iterator[StreamObject]: + return ( + _object_for( + index, + { + "schema_version": STREAM_OBJECT_SCHEMA, + "index": index, + "content": "scale-stream-object-" + ("payload-" * 64) + str(index), + }, + ) + for index in range(total_objects) + ) + + return factory + + +def case_objects_factory( + population: E2EPopulation, limit: int | None = None +) -> Callable[[], Iterator[StreamObject]]: + """Canonical label-blind case-input objects from the scale population.""" + + def factory() -> Iterator[StreamObject]: + rows = population.cases if limit is None else population.cases[:limit] + return ( + _object_for( + index, + { + "schema_version": STREAM_OBJECT_SCHEMA, + "index": index, + "input_identity_digest": row.input_identity_digest, + "change_input_digest": row.change_input_digest, + "case_digest": row.case_digest, + "code_reference": { + "artifact_kind": row.code_reference.artifact_kind.value, + "content_digest": row.code_reference.content_digest, + "byte_length": row.code_reference.byte_length, + "provenance_digest": row.code_reference.provenance_digest, + "access_class": row.code_reference.access_class.value, + }, + }, + ) + for index, row in enumerate(rows) + ) + + return factory + + +class StreamFault(StrEnum): + """Closed stream-impairment injection modes.""" + + MISSING_BATCH = "missing_batch" + SHORT_BATCH = "short_batch" + UNREADABLE_OBJECT = "unreadable_object" + + +@dataclass(frozen=True) +class BatchReceipt: + """Per-batch nonzero read evidence retained by the streaming run.""" + + index: int + object_count: int + byte_count: int + batch_digest: str + nonzero: bool + + +@dataclass +class StreamRunReceipt: + """Closed streaming result: receipts and runtimes, never a metric block.""" + + status: WorkflowStatus + reason_codes: tuple[WorkflowReasonCode, ...] + declared_total: int + consumed_objects: int + batch_count: int + byte_count: int + chain_digest: str + batch_receipts: tuple[BatchReceipt, ...] + last_batch: BatchReceipt | None + runtime_ms: int + all_batches_nonzero: bool + + +def _batches(iterator: Iterator[StreamObject], size: int) -> Iterator[tuple[StreamObject, ...]]: + while True: + chunk = tuple(islice(iterator, size)) + if not chunk: + return + yield chunk + + +def _chain_step(chain: str, batch_digest: str) -> str: + return canonical.bytes_digest((chain + batch_digest).encode("ascii")) + + +def _validate_batch(index: int, batch: tuple[StreamObject, ...], fault: StreamFault | None, anchor: int) -> BatchReceipt: + byte_count = 0 + digests: list[str] = [] + for position, item in enumerate(batch): + raw = item.raw + if fault is StreamFault.UNREADABLE_OBJECT and index == anchor and position == 0: + raw = b"\x00" + item.raw[1:] + byte_count += len(raw) + document = strict_decode(raw) + if canonical.bytes_digest(raw) != item.digest: + raise StreamObjectError("stream_object_digest_mismatch") + if document.get("schema_version") != STREAM_OBJECT_SCHEMA: + raise StreamObjectError("stream_object_schema_mismatch") + digests.append(item.digest) + digest = canonical.bytes_digest("".join(digests).encode("ascii")) + return BatchReceipt(index, len(batch), byte_count, digest, byte_count > 0 and len(batch) > 0) + + +def run_streaming_validation( + objects_factory: Callable[[], Iterator[StreamObject]], + batch_size: int, + declared_total: int, + *, + fault: StreamFault | None = None, +) -> StreamRunReceipt: + """Stream one batch at a time; any truncation reports impairment, not a metric.""" + started = time.perf_counter() + expected_batches = -(-declared_total // batch_size) + anchor = expected_batches // 2 + iterator = objects_factory() + if fault is StreamFault.MISSING_BATCH: + iterator = islice(iterator, anchor * batch_size) + receipts: list[BatchReceipt] = [] + reasons: list[WorkflowReasonCode] = [] + consumed = 0 + total_bytes = 0 + chain = _ZERO + try: + for index, batch in enumerate(_batches(iterator, batch_size)): + if fault is StreamFault.SHORT_BATCH and index == anchor and len(batch) > 1: + batch = batch[:-1] + reasons.append(WorkflowReasonCode.INSTRUMENT_FAILURE) + receipt = _validate_batch(index, batch, fault, anchor) + receipts.append(receipt) + consumed += receipt.object_count + total_bytes += receipt.byte_count + chain = _chain_step(chain, receipt.batch_digest) + except StreamObjectError: + reasons.append(WorkflowReasonCode.INSTRUMENT_FAILURE) + if fault is StreamFault.MISSING_BATCH and consumed < declared_total: + reasons.append(WorkflowReasonCode.INTERRUPTED) + elif consumed != declared_total and not reasons: + reasons.append(WorkflowReasonCode.INSTRUMENT_FAILURE) + runtime_ms = int((time.perf_counter() - started) * 1000) + status = WorkflowStatus.IMPAIRED if reasons or consumed != declared_total else WorkflowStatus.COMPLETED + return StreamRunReceipt( + status, + tuple(dict.fromkeys(reasons)), + declared_total, + consumed, + len(receipts), + total_bytes, + chain, + tuple(receipts), + receipts[-1] if receipts else None, + runtime_ms, + bool(receipts) and all(receipt.nonzero for receipt in receipts), + ) + + +@dataclass(frozen=True) +class ColdWarmReceipt: + """Cold and warm runtime measurements with a registered monotonicity note.""" + + cold_ms: int + warm_ms: int + registered_reason: str | None + + +def measure_cold_warm(operation: Callable[[], object]) -> tuple[object, ColdWarmReceipt]: + started = time.perf_counter() + value = operation() + cold_ms = max(1, int((time.perf_counter() - started) * 1000)) + started = time.perf_counter() + operation() + warm_ms = max(1, int((time.perf_counter() - started) * 1000)) + reason = None if warm_ms <= cold_ms else "warm_slower_registered" + return value, ColdWarmReceipt(cold_ms, warm_ms, reason) + + +class TimingAdapterProxy: + """Wrap the committed execution adapter to retain per-arm runtime receipts.""" + + def __init__(self, inner: object) -> None: + self._inner = inner + self.arm_runtimes: list[tuple[str, int]] = [] + + def __getattr__(self, name: str) -> object: + return getattr(self._inner, name) + + def execute(self, bundle: object): # noqa: ANN201 - committed test seam type + started = time.perf_counter() + result = self._inner.execute(bundle) + arm_id = getattr(getattr(bundle, "arm", None), "arm_id", "unknown-arm") + self.arm_runtimes.append((arm_id, max(0, int((time.perf_counter() - started) * 1000)))) + return result + + +class LaneReason(StrEnum): + """Closed execution-lane refusal reasons; never detector or infrastructure vocabulary.""" + + BUSY = "execution_lane_busy" + UNAVAILABLE = "execution_lane_unavailable" + + +class LaneRefusal(RuntimeError): + """The bounded lane refused work; closed reason, no caller content.""" + + def __init__(self, reason: LaneReason) -> None: + self.reason = reason + super().__init__(f"execution_lane_refusal_{reason.value}") + + +class BoundedExecutionLane: + """Bounded execution lane honoring adapter back-pressure beyond its bound.""" + + def __init__(self, maxsize: int = 2) -> None: + if type(maxsize) is not int or maxsize < 1: + raise ValueError("lane bound must be a positive integer") + self.maxsize = maxsize + self._pending: queue.Queue = queue.Queue(maxsize=maxsize) + self._closed = False + self.accepted_items = 0 + self.refused_items = 0 + self.drained_items = 0 + self.max_pending = 0 + + def submit(self, item: object) -> None: + if self._closed: + self.refused_items += 1 + raise LaneRefusal(LaneReason.UNAVAILABLE) from None + try: + self._pending.put_nowait(item) + except queue.Full: + self.refused_items += 1 + raise LaneRefusal(LaneReason.BUSY) from None + self.accepted_items += 1 + self.max_pending = max(self.max_pending, self._pending.qsize()) + + def pending(self) -> int: + return self._pending.qsize() + + def drain(self, count: int) -> int: + drained = 0 + while drained < count: + try: + self._pending.get_nowait() + except queue.Empty: + break + drained += 1 + self.drained_items += 1 + return drained + + def close(self) -> None: + self._closed = True + + +@dataclass +class LaneRunRecord: + """Back-pressure evidence: bounded pending, closed refusals, impairment.""" + + accepted_batches: int + refused_batches: int + max_pending: int + refusals: tuple[LaneRefusal, ...] + receipt: StreamRunReceipt + outcome: BenchmarkWorkflowOutcomeV1 + + +def _lane_marker(batch: tuple[StreamObject, ...]) -> tuple[int, int, str]: + digest = canonical.bytes_digest(b"".join(item.digest.encode("ascii") for item in batch)) + return (batch[0].index, len(batch), digest) + + +def stream_with_lane( + objects_factory: Callable[[], Iterator[StreamObject]], + batch_size: int, + declared_total: int, + lane: BoundedExecutionLane, +) -> LaneRunRecord: + """Submit one batch at a time; a lane refusal stops the run as an impairment.""" + started = time.perf_counter() + refusals: list[LaneRefusal] = [] + accepted = 0 + consumed = 0 + total_bytes = 0 + chain = _ZERO + for batch in _batches(objects_factory(), batch_size): + try: + lane.submit(_lane_marker(batch)) + except LaneRefusal as refusal: + refusals.append(refusal) + break + accepted += 1 + consumed += len(batch) + total_bytes += sum(len(item.raw) for item in batch) + chain = _chain_step(chain, _lane_marker(batch)[2]) + runtime_ms = int((time.perf_counter() - started) * 1000) + impaired = bool(refusals) or consumed < declared_total + receipt = StreamRunReceipt( + WorkflowStatus.IMPAIRED if impaired else WorkflowStatus.COMPLETED, + (WorkflowReasonCode.RESOURCE_EXHAUSTED,) if refusals else (() if not impaired else (WorkflowReasonCode.INTERRUPTED,)), + declared_total, + consumed, + accepted, + total_bytes, + chain, + (), + None, + runtime_ms, + total_bytes > 0, + ) + return LaneRunRecord(accepted, len(refusals), lane.max_pending, tuple(refusals), receipt, impaired_stream_outcome(receipt)) + + +def impaired_stream_outcome(receipt: StreamRunReceipt) -> BenchmarkWorkflowOutcomeV1: + """Bind an impaired streaming receipt to the closed workflow outcome.""" + counts = WorkflowCounts(len(PLANNED_ARMS), 0, max(1, receipt.declared_total), receipt.consumed_objects, 0) + return BenchmarkWorkflowOutcomeV1( + WorkflowStatus.IMPAIRED, + WorkflowPhase.ARM_EXECUTION, + receipt.reason_codes or (WorkflowReasonCode.INSTRUMENT_FAILURE,), + _digest("scale-stream-population"), + _digest("scale-stream-freeze"), + _digest("scale-stream-plan"), + _digest("scale-stream-workflow"), + False, + counts, + (WorkflowGate.ARM_EXECUTION,), + (), + receipt.runtime_ms, + "", + "", + None, + "", + ) + + +def operator_report_for_outcome(outcome: BenchmarkWorkflowOutcomeV1) -> bytes: + return operator_report_bytes(outcome, None) + + +def lane_refusal_texts(record: LaneRunRecord) -> tuple[str, ...]: + return tuple(str(refusal) for refusal in record.refusals) + tuple(code.value for code in record.receipt.reason_codes) + + +_DETECTOR_VOCABULARY = ( + "finding", + "findings", + "alert", + "alerts", + "detector", + "detection", + "true_positive", + "false_positive", + "false_alarm", + "precision", + "recall", + "vulnerability", +) +_INFRASTRUCTURE_VOCABULARY = ( + "cluster", + "kubernetes", + "k8s", + "node", + "nodes", + "pod", + "pods", + "datacenter", + "machine", + "machines", + "hostname", + "dns", +) +_VOCABULARY_PATTERN = re.compile( + "|".join(rf"\b{term}\b" for term in sorted(set(_DETECTOR_VOCABULARY + _INFRASTRUCTURE_VOCABULARY), reverse=True)), + re.IGNORECASE, +) + + +_CLOSED_SCHEMA_NAMESPACES = ("valid-detection-benchmark", "detection-core") + + +def vocabulary_findings(text: str) -> tuple[str, ...]: + """Detector or infrastructure diagnosis terms found in shared text. + + Closed schema namespaces (the benchmark's own product identifiers) are + normalized away first: they name the contracts, never a detector result. + """ + normalized = text + for namespace in _CLOSED_SCHEMA_NAMESPACES: + normalized = normalized.replace(namespace, "") + return tuple(match.lower() for match in _VOCABULARY_PATTERN.findall(normalized)) + + +_REDACTION_MARKERS = ( + b"/home/", + b"/tmp/", + b"SECRET", + b"confidential-ground-truth-judgment", + b"defect-present", + b"AKIA", + b"arn:aws", + b"https://", + b"http://", + b"aws_secret_access_key", +) + + +def redaction_findings(raw: bytes) -> tuple[str, ...]: + return tuple(marker.decode("ascii") for marker in _REDACTION_MARKERS if marker in raw) + + +def _execution_subject(environment: E2EEnvironment, case: E2EPopulation) -> str: + """Harvest the admission-review subject for this population's execution.""" + preflight = environment.orchestrator.preflight(case.run_request()) + product = environment.execute( + preflight, + review=None, + attempt_review=_attempt_review(case, preflight), + status_ref=case.status_ref, + ) + return product.manifest_subject_digest + + +class ScaleLifecycle: + """One execution-tier lifecycle: timed arms, spend, release, projection, replay, reporting. + + A single committed run-command lifecycle over the execution-tier + population: the preflight harvest mints the admission-review subject, + the run stages execute every planned arm (per-arm runtime receipts are + retained through the timing adapter proxy), commit the one shared spend, + derive the exact-scope projection inputs, publish the one validated core + replay, and render the deterministic redacted operator report. + """ + + def __init__(self) -> None: + self.population = execution_tier_population() + harvest = E2EEnvironment(self.population) + subject = _execution_subject(harvest, self.population) + self.environment = E2EEnvironment(self.population) + self.case = self.population + self.admission_review = _attestation(subject, _digest("scale-admission-producer"), self.population.disclosure) + self.environment.adapter = TimingAdapterProxy(self.environment.adapter) + self.loader = _LabelSource(self.case.labels, self.environment.store, self.case.freeze.population_digest) + self.publication = None + self.replay = None + self.release = None + self.context = self._operator_context() + 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( + self.context, run.BenchmarkRunRequestV1(self.case.run_request(), self._stages(), counts, 250) + ) + self.execution = self.environment.last_execution + self.arm_runtimes = tuple(self.environment.adapter.arm_runtimes) + self.projection = self._projection() + + def _operator_context(self): + return run.bound_operator_context( + run.validated_operator_configuration(_environ(), _evidence()), + self.environment.durable, + self.environment.transient, + self.environment.lifecycle(), + self.environment.custody_policy, + self.environment.case.report, + self.environment.case.transient_identity, + self.environment.case.transient_profile, + _SpyExecutor(), + ACCESS_POLICY, + ) + + def _adapter_request(self, execution): + case = self.case + return AdmissionCaseAdapterRequestV1( + repository=self.environment.repository, + custodian_access_policy_digest=ACCESS_POLICY, + execution=execution, + plan=case.plan, + selection=case.selection, + population_digest=case.freeze.population_digest, + input_count=len(case.manifest.input_digests), + custody=self.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("scale-adapter-admission"), case.disclosure), + release_review=lambda subject: _attestation(subject, _digest("scale-adapter-release"), case.disclosure), + bridged_store_identity=BRIDGE_STORE, + bridged_retention_policy_digest=BRIDGE_RETENTION, + ) + + def _stages(self): + case = self.case + + def _execution(preflight): + return self.environment.execute( + preflight, + review=self.admission_review, + attempt_review=_attempt_review(case, preflight), + status_ref=case.status_ref, + ) + + def _spend(execution): + preparation = derive_case_adapter_preparation(self._adapter_request(execution)) + prior = self.environment.store.current_log(case.freeze.population_digest) + receipt = record_population_use( + preparation.label_release_request, prior, E2E_CUSTODIAN, self.environment.custody_policy + ) + successor = append_population_use(prior, receipt, self.environment.custody_policy) + assert self.environment.store.compare_and_swap(prior.log_digest, successor) + head = self.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, + self.environment.repository, + ACCESS_POLICY, + labels, + case.freeze.positive_change_digests, + _scope_census(case.freeze), + ) + manifest = execution.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) + self.environment.repository.put_if_absent(content, reference=reference) + self.release = AdmissionSpendReleaseV1( + None, receipt.receipt_digest, True, len(raw), canonical.bytes_digest(raw), released, reference, + canonical.content_digest(value), + ) + return self.release + + def _replay(release): + self.replay = derive_case_adapter_replay(self._adapter_request(self.environment.last_execution), release) + return self.replay + + def _publication(replay_value): + declaration = replay_value.plan_manifest.declaration + self.publication = publish_scoped_replay( + ReplayPublicationRequestV1( + repository=self.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, + ) + ) + return self.publication + + return run.BenchmarkRunStagesV1(_execution, _spend, _replay, _publication) + + def _projection(self): + assert self.release is not None + rekeyed = replace( + self.release, + released_cases=tuple( + replace(row, case_input_digest=row.underlying_push_digest, case_digest="") + for row in self.release.released_cases + ), + ) + return project_exact_scopes( + ProjectionRequestV1( + release=rekeyed, execution=self.execution, selection=self.population.selection + ) + ) + + def render_again(self) -> bytes: + """Deterministic re-render through the committed status command.""" + request = run.BenchmarkStatusRequestV1( + workflow_digest=WORKFLOW, + now="2026-11-23T11:00:00Z", + population_digest=self.case.freeze.population_digest, + freeze_digest=self.case.freeze.freeze_digest, + plan_digest=self.replay.plan_manifest.manifest_digest, + outcome_reference=self.result.outcome_reference, + replay=self.replay, + ) + return run.benchmark_status_command(self.context, request).report_bytes + + +@lru_cache(maxsize=1) +def scale_lifecycle() -> ScaleLifecycle: + return ScaleLifecycle() + + +@lru_cache(maxsize=1) +def execution_tier_population() -> E2EPopulation: + """The execution-tier population the one lifecycle covers (see CORE_REPLAY_DECLARATION).""" + return E2EPopulation(pushes=_pushes(EXECUTION_TIER_PUSHES_PER_ECOSYSTEM)) + + +def replay_run() -> ScaleLifecycle: + """Committed-convention alias: the one lifecycle carries the core replay pass.""" + return scale_lifecycle()