# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-litmus-skill-evaluation-false-pass-when-the-adversarial-probe-set-is-regenerated-under-a-shifted-model-distribution.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-litmus-skill-evaluation-false-pass-when-the-adversarial-probe-set-is-regenerated-under-a-shifted-model-distribution.warrant.json
# Markdown SHA-256:   2626a7b2f62629948b2061c469b3cc615f13b5c1f269dd31b44e39864a7f5332
# Code AST SHA-256:   a48b1b408971e9459e104d38948032d8962ebea22a3e923918e52d549511ea29
# Verified Classes:   CorpusDriftError, InsufficientPowerError, ProbeRun
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CorpusDriftError(RuntimeError):
    """Raised when a regression gate attempts to diff runs across mismatched probe corpora."""
    pass


class InsufficientPowerError(RuntimeError):
    """Raised when effective probe count is too low for the configured gate threshold."""
    pass


@dataclass(frozen=True)
class ProbeRun:
    corpus_hash: str
    outcomes: dict[str, bool]  # probe_id -> passed
    n_effective: int           # de-duplicated independent failure classes


def corpus_hash(probes: list[dict]) -> str:
    canonical = json.dumps(sorted(probes, key=lambda p: p["id"]), sort_keys=True)
    return hashlib.sha256(canonical.encode()).hexdigest()


def paired_flip_gate(
    incumbent: ProbeRun,
    candidate: ProbeRun,
    *,
    threshold: float = 0.03,
    z: float = 2.58,
) -> dict:
    # Invariant 1: corpus identity must match before any delta is meaningful.
    if incumbent.corpus_hash != candidate.corpus_hash:
        raise CorpusDriftError(
            f"corpus hash mismatch: {incumbent.corpus_hash[:12]} vs "
            f"{candidate.corpus_hash[:12]}; refuse delta, demand re-baseline"
        )

    # Invariant 2: statistical power must be sufficient for the threshold.
    if candidate.n_effective < 0.25 / (threshold ** 2):
        raise InsufficientPowerError(
            f"n_effective={candidate.n_effective} below required "
            f"{int(0.25 / threshold**2)}; gate cannot resolve {threshold}"
        )

    common = set(incumbent.outcomes) & set(candidate.outcomes)
    if common != set(incumbent.outcomes):
        raise CorpusDriftError("probe id sets diverge despite matching corpus hash")

    pass_to_fail = sum(
        1 for pid in common
        if incumbent.outcomes[pid] and not candidate.outcomes[pid]
    )
    fail_to_pass = sum(
        1 for pid in common
        if not incumbent.outcomes[pid] and candidate.outcomes[pid]
    )
    discordant = pass_to_fail + fail_to_pass
    # Invariant 3: gate on the paired flip count, not the pooled rate delta.
    flip_rate = (pass_to_fail - fail_to_pass) / max(len(common), 1)
    se = (discordant ** 0.5) / max(len(common), 1) if discordant else 0.0
    regressed = flip_rate > 0 and (flip_rate / se if se else 0.0) > z

    return {
        "pass_to_fail": pass_to_fail,
        "fail_to_pass": fail_to_pass,
        "flip_rate": flip_rate,
        "regressed": regressed,
    }
