# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-litmus-safety-benchmark-pass-rate-flips-from-gating-agent-regressions-in-ci.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-litmus-safety-benchmark-pass-rate-flips-from-gating-agent-regressions-in-ci.warrant.json
# Markdown SHA-256:   d521d6da36df7f788ea5687a5fdc8dbeffd0b35e3f4221750ecb5d4739aff93d
# Code AST SHA-256:   d2f63243fcd2f7a3cf3419b7c08f41ecbbb4c4abd1715f72634ea641c75fcd0c
# Verified Classes:   EpochMismatchError, InsufficientDiscordanceError, RunArtifact
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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

Verdict = Literal["pass", "regression", "inconclusive", "invalid_epoch"]


class EpochMismatchError(RuntimeError):
    """Raised when baseline and candidate were scored under different instrument epochs."""
    pass


class InsufficientDiscordanceError(RuntimeError):
    """Raised when paired discordant mass is below the gateable minimum."""
    pass


@dataclass(frozen=True)
class RunArtifact:
    manifest_sha256: str
    judge_id: str          # immutable, e.g. "judge-v3@sha:ab12..."
    decoding: str          # "temp=0,seed=7,top_p=1"
    per_probe: dict        # probe_id -> {"passed": bool, "margin": float}

    def epoch_hash(self) -> str:
        h = hashlib.sha256()
        h.update(self.manifest_sha256.encode())
        h.update(self.judge_id.encode())
        h.update(self.decoding.encode())
        return h.hexdigest()


def gate(
    baseline: RunArtifact,
    candidate: RunArtifact,
    margin_floor: float = 0.15,
    min_discordant: int = 8,
    epsilon: float = 0.01,
) -> Verdict:
    if baseline.epoch_hash() != candidate.epoch_hash():
        raise EpochMismatchError(
            f"epoch drift: baseline={baseline.epoch_hash()[:12]} "
            f"candidate={candidate.epoch_hash()[:12]} — re-baseline required"
        )

    shared = set(baseline.per_probe) & set(candidate.per_probe)
    discordant = []
    for pid in shared:
        b, c = baseline.per_probe[pid], candidate.per_probe[pid]
        # quarantine judge-boundary probes: their outcome is sampling noise
        if min(b["margin"], c["margin"]) < margin_floor:
            continue
        if b["passed"] != c["passed"]:
            discordant.append((pid, b["passed"], c["passed"]))

    if len(discordant) < min_discordant:
        # not enough paired signal to declare anything; abstain
        return "inconclusive"

    regressions = sum(1 for _, bp, cp in discordant if bp and not cp)
    paired_delta = regressions / len(shared)
    if paired_delta > epsilon:
        return "regression"
    return "pass"


def run_gate_or_raise(baseline: RunArtifact, candidate: RunArtifact) -> Verdict:
    try:
        return gate(baseline, candidate)
    except EpochMismatchError:
        # surface as non-gateable; caller must re-baseline, not block
        return "invalid_epoch"
    except InsufficientDiscordanceError as e:
        raise InsufficientDiscordanceError(f"cannot gate: {e}") from e
