# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-adversarial-scoring-drift-as-a-hard-ci-gate-rather-than-a-soft-regression-signal.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-adversarial-scoring-drift-as-a-hard-ci-gate-rather-than-a-soft-regression-signal.warrant.json
# Markdown SHA-256:   65311b2bb6cd6d9d79059d8ef425be7c79b62651673331182f10ae6e37b3c417
# Code AST SHA-256:   78fd7392d19199f4c208b81486f06cf7b478e41389831e8854554f206d5c8646
# Verified Classes:   BenchmarkGateError, Verdict, Instrument, BaselineRecord, CandidateRun
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum


class BenchmarkGateError(RuntimeError):
    """Raised when a LITMUS gate is evaluated under an invalid precondition."""


class Verdict(str, Enum):
    PASS = "pass"
    FAIL = "fail"
    NON_COMPARABLE = "non_comparable"


@dataclass(frozen=True)
class Instrument:
    corpus_hash: str
    judge_digest: str          # immutable weights/artifact digest, not a tag
    judge_prompt_hash: str
    decoding_config_hash: str
    aggregation_id: str


@dataclass(frozen=True)
class BaselineRecord:
    instrument: Instrument
    per_category_score: dict[str, float]
    per_category_noise_band: dict[str, float]  # measured incumbent variance


@dataclass(frozen=True)
class CandidateRun:
    instrument: Instrument
    per_category_score: dict[str, float]


SAFETY_CRITICAL = frozenset({"tool_misuse", "prompt_injection"})


def evaluate_gate(baseline: BaselineRecord, candidate: CandidateRun) -> Verdict:
    # Invariant 1: a gate may only compare measurements from the same instrument.
    if baseline.instrument != candidate.instrument:
        return Verdict.NON_COMPARABLE

    # Invariant 2: noise band must be measured for every gated category.
    for cat in baseline.per_category_score:
        if cat not in baseline.per_category_noise_band:
            raise BenchmarkGateError(
                f"no measured noise band for category {cat!r}; gate is undefined"
            )
        if cat not in candidate.per_category_score:
            raise BenchmarkGateError(
                f"candidate missing category {cat!r} present in baseline"
            )

    # Invariant 3: gate on min over categories, not mean; per-category bands.
    for cat, base_score in baseline.per_category_score.items():
        delta = candidate.per_category_score[cat] - base_score
        band = baseline.per_category_noise_band[cat]
        if delta < -band:
            return Verdict.FAIL

    # Safety-critical categories must be present at all.
    missing = SAFETY_CRITICAL - set(candidate.per_category_score)
    if missing:
        raise BenchmarkGateError(
            f"safety-critical categories absent from candidate run: {sorted(missing)}"
        )

    return Verdict.PASS


def gate_or_raise(baseline: BaselineRecord, candidate: CandidateRun) -> Verdict:
    verdict = evaluate_gate(baseline, candidate)
    if verdict is Verdict.NON_COMPARABLE:
        # Do not silently pass or fail: halt promotion pending re-baseline.
        raise BenchmarkGateError(
            "instrument drift detected between baseline and candidate; "
            "re-baseline the incumbent under the new instrument before gating"
        )
    return verdict
