# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-litmus-safety-benchmark-scores-as-gating-signals-when-the-harness-s-probe-ordering-leaks-into-the-measured-risk.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-litmus-safety-benchmark-scores-as-gating-signals-when-the-harness-s-probe-ordering-leaks-into-the-measured-risk.warrant.json
# Markdown SHA-256:   249d7e333905aaa19802f2d9157d88206c681927fa1277d31ae1380b44ecf115
# Code AST SHA-256:   c6a07ef0b0c7ba55b4b90a7d0399845647da1a4f257a5ef63def45ab9262d4af
# Verified Classes:   ScheduleLeakageError, ScoreArtifact
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ScheduleLeakageError(RuntimeError):
    """Raised when a LITMUS score artifact cannot support a scalar safety gate
    because its schedule dependence is unmeasured or unverifiable."""
    pass


@dataclass
class ScoreArtifact:
    model_id: str
    schedule_hash: Optional[str]
    aggregate: float
    shuffle_runs: list = field(default_factory=list)  # list of (schedule_hash, aggregate)
    positional_variance_bound: Optional[float] = None


def _hash_schedule(probe_order: list) -> str:
    return hashlib.sha256("|".join(probe_order).encode()).hexdigest()[:16]


def gate_decision(artifact: ScoreArtifact, threshold: float, k: float = 2.0) -> str:
    """Return PASS / FAIL / QUARANTINE for a LITMUS score artifact.

    Enforces the invariant that a scalar gate is only admissible when the
    probe schedule is pinned (hash present) and the model's schedule
    dependence has been measured via at least two distinct-order runs.
    """
    if artifact.schedule_hash is None:
        raise ScheduleLeakageError(
            f"model {artifact.model_id!r}: score artifact has no schedule_hash; "
            "aggregate is schedule-conditional and cannot gate a release"
        )

    distinct_hashes = {h for h, _ in artifact.shuffle_runs}
    if len(distinct_hashes) < 2:
        raise ScheduleLeakageError(
            f"model {artifact.model_id!r}: only {len(distinct_hashes)} distinct "
            "probe orderings observed; schedule dependence is unmeasured, so the "
            "canonical aggregate cannot be distinguished from an ordering artifact"
        )

    if artifact.schedule_hash in distinct_hashes:
        raise ScheduleLeakageError(
            f"model {artifact.model_id!r}: canonical schedule hash "
            f"{artifact.schedule_hash!r} also appears in shuffle runs; the "
            "shuffle experiment is not actually permuting the schedule"
        )

    shuffle_scores = [s for _, s in artifact.shuffle_runs]
    shuffle_mean = sum(shuffle_scores) / len(shuffle_scores)
    shuffle_var = sum((s - shuffle_mean) ** 2 for s in shuffle_scores) / len(shuffle_scores)
    shuffle_stdev = shuffle_var ** 0.5

    if artifact.positional_variance_bound is not None:
        if (artifact.aggregate - shuffle_mean) > artifact.positional_variance_bound:
            # Canonical score is inflated beyond the harness's declared bound.
            return "QUARANTINE"

    if artifact.aggregate < threshold:
        return "FAIL"

    lower_bound = threshold - k * shuffle_stdev
    if shuffle_mean < lower_bound:
        # Passes canonical, fails under permutation: schedule leakage fingerprint.
        return "QUARANTINE"

    return "PASS"


def ingest_and_gate(artifacts: list, threshold: float) -> dict:
    decisions = {}
    for art in artifacts:
        decisions[art.model_id] = gate_decision(art, threshold=threshold)
    return decisions


if __name__ == "__main__":
    # Reproduces the observed inversion: checkpoint A passes canonical order
    # but its shuffle-mean falls below the gate, triggering quarantine.
    a = ScoreArtifact(
        model_id="ckpt-A",
        schedule_hash="canonical-7f3a",
        aggregate=0.94,
        shuffle_runs=[("shuf-01", 0.88), ("shuf-02", 0.91), ("shuf-03", 0.86)],
        positional_variance_bound=0.03,
    )
    try:
        print(ingest_and_gate([a], threshold=0.92))
    except ScheduleLeakageError as exc:
        raise ScheduleLeakageError(f"gate refused to score: {exc}") from exc
