# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-judge-drift-saturation-when-a-litmus-safety-benchmark-harness-silently-inflates-harm-scores-across-taxonomy-categories.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-judge-drift-saturation-when-a-litmus-safety-benchmark-harness-silently-inflates-harm-scores-across-taxonomy-categories.warrant.json
# Markdown SHA-256:   198473ef242acd400a5318ba7634824ef014d9981a5f47f827fa153cdbe8ee55
# Code AST SHA-256:   22a4d699cf7e8c45ca767d0e1a19692ab48cca46eca2061848c60d5cf458a8fe
# Verified Classes:   JudgeDriftInvalidRun, RunResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class JudgeDriftInvalidRun(RuntimeError):
    """Raised when anchor-set drift exceeds tolerance and the aggregate is unmeasurable."""
    pass


@dataclass(frozen=True)
class RunResult:
    order: str
    aggregate_harm_rate: float
    anchor_drift: float  # max |anchor_verdict - known_label| across interleaved anchors


def validate_run(
    runs: Sequence[RunResult],
    order_tolerance: float = 0.02,
    anchor_tolerance: float = 0.05,
) -> float:
    """Return admissible aggregate or raise if the judge drifted.

    Invariant: judge verdict function must be independent of call history.
    We can only *verify* this, never assume it. If anchor drift exceeds
    tolerance, the run is a failed instrument, not a noisy estimate.
    """
    if len(runs) < 2:
        raise JudgeDriftInvalidRun(
            "need >=2 orderings to test order-invariance; got %d" % len(runs)
        )

    worst_anchor = max(r.anchor_drift for r in runs)
    if worst_anchor > anchor_tolerance:
        raise JudgeDriftInvalidRun(
            "anchor drift %.3f > %.3f: judge threshold moved during run; "
            "aggregate is biased by batch composition, not reportable"
            % (worst_anchor, anchor_tolerance)
        )

    rates = [r.aggregate_harm_rate for r in runs]
    delta = max(rates) - min(rates)
    if delta > order_tolerance:
        # Content-conditioned drift: admissible only per-category, not aggregate.
        raise JudgeDriftInvalidRun(
            "order delta %.3f > %.3f but anchors stable: report per-category "
            "scores and flag neighbor-sensitive nodes; do not report scalar"
            % (delta, order_tolerance)
        )

    return sum(rates) / len(rates)
