feat(valid-detection-benchmark): 9.2 remove replacement authority from legacy aggregate scoring

This commit is contained in:
Marius Ciepluch
2026-11-21 13:39:38 +01:00
parent 9ba0a9d4c5
commit 14bf931f01
3 changed files with 376 additions and 14 deletions
@@ -287,7 +287,7 @@
- Done when existing non-authorizing workflows remain usable for development and only reviewed replacement artifacts can enter V3 preflight.
- _Requirements: 2.1, 2.2, 2.3, 2.4, 2.5, 4.5, 4.6, 4.9, 5.1_
- _Boundary: Legacy Benchmark Integration_
- [ ] 9.2 Remove replacement authority from legacy aggregate scoring
- [x] 9.2 Remove replacement authority from legacy aggregate scoring
- Route replacement metrics, gates, case validation, proof validation, and replay exclusively through the V3 core facade.
- Keep old aggregate helpers available only for frozen historical replay and reject their output as a replacement admission root.
- Remove access-control-specific conversion or site-judgment ownership from the general replacement path.
+161 -13
View File
@@ -1,33 +1,181 @@
"""Paired scoring and the admission report for the access-control prover arm.
"""Scoring authority for the valid-detection benchmark (task 9.2).
Task 12.6 of the access-control-prover specification (Reqs 5.2, 12.4, 12.5,
12.7, 12.8, 12.9). The scorer consumes a validated admission manifest plus the
judgments measured on its population: it scores paired vulnerable/fixed twins
and reviewed ordinary changes, keeps sample counts and Wilson 95% intervals on
every rate, and returns NO-GO when the budget gate, the instrument gate or any
pre-registered quality criterion fails. Indeterminate pairs are reported as
indeterminate and never converted to clean results; ordinary changes whose
review found a real missing-authorization defect are refused before scoring.
The replacement admission path computes its metrics and gates, validates
cases, proofs, and replays exclusively through the pinned detection-core V3
facade reached via ``benchmarks.valid.core_conformance``; no benchmark-owned
scorer may substitute for that root. The legacy aggregate helpers below are
the frozen access-control prover pilot's paired scorer (task 12.6 of the
access-control-prover specification): they remain available only for
historical V2 replay, never own a replacement decision, and their pooled or
target-specific output is structurally refused as a replacement admission
root before the core boundary is reached.
"""
from __future__ import annotations
from collections.abc import Sequence
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from typing import Any, Protocol
from enum import StrEnum
from typing import Any, Protocol, TypeVar
from benchmarks.unseen import score
from openultrasast.core import canonical
from benchmarks.valid.core_conformance import decode_scoped_admission_v3, require_scoped_admission_v3
from openultrasast.core import canonical, evaluation_admission
from openultrasast.core.admission_case import AdmissionCaseRelease, AdmissionCaseResult
from openultrasast.core.admission_context import AdmissionValidationContext
from openultrasast.core.admission_report import AdmissionReplay, score_admission, validate_admission_replay
from openultrasast.core.admission_review import AdmissionManifestV2
from openultrasast.core.admission_spend import AdmissionPreparation
from openultrasast.core.custody import PopulationCustodyPort, PopulationUseReceipt
from openultrasast.core.evaluation_authority import EvaluationAdmissionManifestV3, EvaluationPlanManifestV3
from openultrasast.core.evaluation_feasibility import EvaluationFeasibilityV3
from openultrasast.core.evaluation_release import AdmissionCaseReleaseV3, ArmAdmissionCasesV3
from openultrasast.core.evaluation_replay import EvaluationReplayV3
from openultrasast.core.evaluation_report import ArmEvaluationReportV3
from openultrasast.core.evaluation_spend import EvaluationPreparationV3, EvaluationSpendBindingV3
from openultrasast.core.measurement import DenominatorPolicy
from openultrasast.core.readiness import ReadinessResult
__all__ = ["AdmissionCase", "AdmissionScoringError", "OrdinaryChange", "admission_report", "score_v2_admission"]
__all__ = [
"AdmissionCase",
"AdmissionScoringError",
"OrdinaryChange",
"ReplacementScoringRefusal",
"ReplacementScoringRefusalReason",
"V3_EVALUATION_SCHEMA",
"admission_report",
"decode_replacement_root",
"preflight_replacement_gates",
"score_replacement_replay",
"score_v2_admission",
"validate_replacement_replay",
]
V3_EVALUATION_SCHEMA = "openultrasast.detection-core.evaluation-admission.v3"
_RootT = TypeVar("_RootT")
class ReplacementScoringRefusalReason(StrEnum):
"""Closed reasons a root can be refused on the replacement scoring path."""
LEGACY_AGGREGATE_ROOT = "legacy_aggregate_root"
class ReplacementScoringRefusal(ValueError):
"""Refuse non-V3 roots on the replacement path with a closed reason."""
def __init__(self, reason: ReplacementScoringRefusalReason) -> None:
self.reason = reason
super().__init__(f"replacement_scoring_{reason.value}")
_LEGACY_AGGREGATE_KEYS = frozenset(
{
"fix_recall",
"flagged_ordinary_per_100",
"indeterminate_rate",
"verified_location_recall",
}
)
_LEGACY_REPORT_SCHEMA_PREFIX = "openultrasast.detection-core.admission-report."
def _is_legacy_aggregate_root(value: Mapping[object, object]) -> bool:
"""True when a mapping carries the legacy aggregate scorer's vocabulary."""
schema = value.get("schema_version")
return bool(_LEGACY_AGGREGATE_KEYS & set(value)) or (isinstance(schema, str) and schema.startswith(_LEGACY_REPORT_SCHEMA_PREFIX))
def _carries_legacy_aggregate(value: Mapping[object, object]) -> bool:
"""True when a pooled wrapper carries legacy aggregate output inside it."""
for item in value.values():
if isinstance(item, Mapping) and _is_legacy_aggregate_root(item):
return True
if isinstance(item, (list, tuple)) and any(isinstance(entry, Mapping) and _is_legacy_aggregate_root(entry) for entry in item):
return True
return False
def _refuse_legacy_aggregate_root(value: object) -> None:
"""Refuse legacy aggregate output (flat, target-specific, or pooled) as a replacement root."""
if not isinstance(value, Mapping):
return
if _is_legacy_aggregate_root(value) or _carries_legacy_aggregate(value):
raise ReplacementScoringRefusal(ReplacementScoringRefusalReason.LEGACY_AGGREGATE_ROOT)
def decode_replacement_root(schema: str, value: object, expected_type: type[_RootT]) -> _RootT:
"""Decode one replacement admission root through the pinned core facade.
Legacy aggregate scoring output (pooled or target-specific) is refused
here with a closed reason before the core boundary is reached; only an
exact V3 root decodes.
"""
_refuse_legacy_aggregate_root(value)
return decode_scoped_admission_v3(schema, value, expected_type)
def preflight_replacement_gates(
plan_manifest: EvaluationPlanManifestV3,
context: AdmissionValidationContext,
resolver: canonical.ContentResolver,
) -> EvaluationFeasibilityV3:
"""Derive replacement gate and metric feasibility only through the pinned facade."""
require_scoped_admission_v3()
return evaluation_admission.preflight_evaluation(plan_manifest, context, resolver)
def score_replacement_replay(
admission_manifest: EvaluationAdmissionManifestV3,
feasibility: EvaluationFeasibilityV3,
preparation: EvaluationPreparationV3,
receipt: PopulationUseReceipt,
spend_binding: EvaluationSpendBindingV3,
release: AdmissionCaseReleaseV3,
cases_by_arm: tuple[ArmAdmissionCasesV3, ...],
readiness: tuple[ReadinessResult, ...],
context: AdmissionValidationContext,
custody: PopulationCustodyPort,
resolver: canonical.ContentResolver,
) -> EvaluationReplayV3:
"""Replacement metrics, case validation, proof validation, and one replay.
Every argument is an exact core V3 root and the pinned facade derives all
metrics, gates, and the complete replay, so no alternative scorer exists
on this path.
"""
require_scoped_admission_v3()
return evaluation_admission.score_and_replay(
admission_manifest,
feasibility,
preparation,
receipt,
spend_binding,
release,
cases_by_arm,
readiness,
context,
custody,
resolver,
)
def validate_replacement_replay(
replay: EvaluationReplayV3,
context: AdmissionValidationContext,
custody: PopulationCustodyPort,
resolver: canonical.ContentResolver,
) -> tuple[ArmEvaluationReportV3, ...]:
"""Validate one complete replacement replay only through the pinned facade."""
_refuse_legacy_aggregate_root(replay)
require_scoped_admission_v3()
return evaluation_admission.validate_evaluation_replay(replay, context, custody, resolver)
# Frozen historical replay helpers (access-control prover pilot, task 12.6).
# These aggregate helpers never authorize replacement admission: any pooled or
# target-specific output they produce is refused at the replacement roots above.
_JUDGMENTS = ("unguarded", "discharged", "indeterminate")
@@ -0,0 +1,214 @@
"""Replacement scoring authority routed through the V3 core facade (task 9.2).
The replacement admission path must have no alternative scorer: metrics,
gates, case validation, proof validation, and replay delegate exclusively to
the pinned detection-core V3 facade. The legacy aggregate helpers remain
available only for frozen historical V2 replay, and pooled or target-specific
aggregate output is structurally refused as a replacement admission root.
"""
from __future__ import annotations
import sys
from hashlib import sha256
from pathlib import Path
from types import SimpleNamespace
import pytest
from test_core_evaluation_end_to_end import _complete_replay
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import benchmarks.valid.admission_run as admission_run # noqa: E402
from benchmarks.valid import admission_scoring # noqa: E402
from benchmarks.valid.admission_scoring import ( # noqa: E402
V3_EVALUATION_SCHEMA,
AdmissionCase,
AdmissionScoringError,
OrdinaryChange,
ReplacementScoringRefusal,
ReplacementScoringRefusalReason,
admission_report,
decode_replacement_root,
preflight_replacement_gates,
score_replacement_replay,
validate_replacement_replay,
)
from benchmarks.valid.core_conformance import decode_scoped_admission_v3 # noqa: E402
from benchmarks.valid.historical_authorization import PINNED_HISTORICAL_DIGESTS # noqa: E402
from openultrasast.core import evaluation_admission # noqa: E402
from openultrasast.core.evaluation_admission import EvaluationAdmissionV3Error # noqa: E402
from openultrasast.core.evaluation_replay import EvaluationReplayV3 # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
def _historical_manifest() -> SimpleNamespace:
return SimpleNamespace(
population_role="admission",
analyzer_revision="prover-fixture-1",
fact_set_digest="a" * 64,
acquisition_record_digest="b" * 64,
configuration_digest="c" * 64,
population_digest="d" * 64,
families=("access_control",),
)
def _historical_cases() -> tuple[AdmissionCase, ...]:
return (AdmissionCase("pair-1", "unguarded", "discharged", True, 1.0),)
def _historical_ordinary() -> tuple[OrdinaryChange, ...]:
return (OrdinaryChange("ordinary-1", "discharged", False),)
def _ordered_readiness(bundle: tuple) -> tuple:
readiness_by_digest = {item.result_digest: item for item in bundle[5][3]}
return tuple(readiness_by_digest[digest] for digest in bundle[3].plan_manifest.readiness_digests)
def test_replacement_seam_delegates_exclusively_to_the_pinned_core_facade(monkeypatch: pytest.MonkeyPatch) -> None:
bundle, replay, *_ = _complete_replay(monkeypatch)
reviewed_case = bundle[5]
feasibility = preflight_replacement_gates(bundle[3].plan_manifest, reviewed_case[0].context, bundle[4])
assert feasibility == evaluation_admission.preflight_evaluation(bundle[3].plan_manifest, reviewed_case[0].context, bundle[4])
scored = score_replacement_replay(
bundle[3],
feasibility,
bundle[7],
bundle[8],
bundle[9],
bundle[1],
bundle[2],
_ordered_readiness(bundle),
reviewed_case[0].context,
reviewed_case[0].port,
bundle[4],
)
assert scored == replay
assert scored.replay_digest == replay.replay_digest
reports = validate_replacement_replay(scored, reviewed_case[0].context, reviewed_case[0].port, bundle[4])
assert reports == replay.reports
assert decode_replacement_root(V3_EVALUATION_SCHEMA, scored, EvaluationReplayV3) is scored
def test_replacement_path_has_no_alternative_scorer(monkeypatch: pytest.MonkeyPatch) -> None:
def forbidden(*args: object, **kwargs: object) -> None:
pytest.fail("legacy aggregate scoring or access-control site judgment participated in replacement scoring")
monkeypatch.setattr(admission_scoring, "admission_report", forbidden)
monkeypatch.setattr(admission_scoring, "_refuse_inputs", forbidden)
monkeypatch.setattr(admission_scoring, "score_v2_admission", forbidden)
monkeypatch.setattr(admission_scoring.score, "rate", forbidden)
monkeypatch.setattr(admission_run, "site_judgment", forbidden)
monkeypatch.setattr(admission_run, "admission_pair_cases", forbidden)
monkeypatch.setattr(admission_run, "admission_ordinary", forbidden)
bundle, replay, *_ = _complete_replay(monkeypatch)
reviewed_case = bundle[5]
feasibility = preflight_replacement_gates(bundle[3].plan_manifest, reviewed_case[0].context, bundle[4])
scored = score_replacement_replay(
bundle[3],
feasibility,
bundle[7],
bundle[8],
bundle[9],
bundle[1],
bundle[2],
_ordered_readiness(bundle),
reviewed_case[0].context,
reviewed_case[0].port,
bundle[4],
)
assert scored == replay
assert validate_replacement_replay(scored, reviewed_case[0].context, reviewed_case[0].port, bundle[4]) == replay.reports
def test_legacy_aggregate_output_is_refused_as_replacement_admission_root(monkeypatch: pytest.MonkeyPatch) -> None:
bundle, replay, *_ = _complete_replay(monkeypatch)
legacy = admission_report(
_historical_manifest(),
_historical_cases(),
_historical_ordinary(),
coverage=1.0,
criteria={"min_fix_recall": 0.5},
)
assert legacy["decision"] == "GO"
for candidate in (legacy, dict(legacy, schema_version="openultrasast.detection-core.admission-report.v2")):
with pytest.raises(ReplacementScoringRefusal) as refusal:
decode_replacement_root(V3_EVALUATION_SCHEMA, candidate, EvaluationReplayV3)
assert refusal.value.reason is ReplacementScoringRefusalReason.LEGACY_AGGREGATE_ROOT
# The refusal fires before any context, custody, or resolver is consulted.
with pytest.raises(ReplacementScoringRefusal):
validate_replacement_replay(candidate, None, None, None)
with pytest.raises(EvaluationAdmissionV3Error):
decode_scoped_admission_v3(V3_EVALUATION_SCHEMA, candidate, EvaluationReplayV3)
assert decode_replacement_root(V3_EVALUATION_SCHEMA, replay, EvaluationReplayV3) is replay
def test_pooled_and_target_specific_aggregate_output_cannot_authorize_v3() -> None:
target_specific = admission_report(
_historical_manifest(),
_historical_cases(),
_historical_ordinary(),
coverage=1.0,
)
pooled = {
"aggregate": target_specific,
"constituents": ["access_control"],
"sample_counts": [1],
"weighting": [1.0],
}
wrapped = {"arms": [target_specific], "whole_population": pooled}
for candidate in (target_specific, pooled, wrapped):
with pytest.raises(ReplacementScoringRefusal) as refusal:
decode_replacement_root(V3_EVALUATION_SCHEMA, candidate, EvaluationReplayV3)
assert refusal.value.reason is ReplacementScoringRefusalReason.LEGACY_AGGREGATE_ROOT
with pytest.raises(ReplacementScoringRefusal):
validate_replacement_replay(candidate, None, None, None)
def test_legacy_aggregate_helpers_remain_available_for_frozen_historical_replay() -> None:
report = admission_report(
_historical_manifest(),
_historical_cases(),
_historical_ordinary(),
coverage=1.0,
criteria={"min_fix_recall": 0.5},
)
assert report["pairs"] == {"n": 1, "correct": 1}
assert report["decision"] == "GO"
assert report["failed_gates"] == []
bad_judgment = (AdmissionCase("pair-2", "nonsense", "discharged", True, 1.0),)
with pytest.raises(AdmissionScoringError, match="judgment"):
admission_report(_historical_manifest(), bad_judgment, _historical_ordinary(), coverage=1.0)
mislabeled = (OrdinaryChange("ordinary-2", "discharged", True),)
with pytest.raises(AdmissionScoringError, match="mislabeled"):
admission_report(_historical_manifest(), _historical_cases(), mislabeled, coverage=1.0)
def test_v2_and_historical_fixture_bytes_remain_byte_identical() -> None:
for relative, expected in sorted(PINNED_HISTORICAL_DIGESTS.items()):
content = (ROOT / relative).read_bytes()
assert content, f"historical fixture read zero bytes: {relative}"
assert sha256(content).hexdigest() == expected, f"historical fixture bytes changed: {relative}"
def test_replacement_modules_do_not_bind_legacy_scoring_or_site_judgment_helpers() -> None:
import benchmarks.valid.admission_execution as execution # noqa: F401
import benchmarks.valid.admission_orchestrator as orchestrator
forbidden = frozenset(
{"admission_report", "score_v2_admission", "site_judgment", "run_v2_admission", "admission_pair_cases", "admission_ordinary"}
)
for module in (orchestrator, execution):
bound = forbidden & set(vars(module))
assert not bound, f"{module.__name__} binds legacy scoring helpers: {sorted(bound)}"