# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-litmus-aligned-red-team-pipelines-from-silently-passing-safety-regressions-when-the-target-agent-s-sampling-temperature-is-ra.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-litmus-aligned-red-team-pipelines-from-silently-passing-safety-regressions-when-the-target-agent-s-sampling-temperature-is-ra.warrant.json
# Markdown SHA-256:   c5475c26a409c8456754d3b0dbd3762931c4a3a86a5834ab3f7b5429617a89be
# Code AST SHA-256:   eaa533659ef0a77e89d10e26aae96d166870970af736e1332011ad02ef39dd84
# Verified Classes:   DecodeConfigMismatchError, InsufficientPowerError, DecodeConfig, LegResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from math import sqrt
from statistics import NormalDist


class DecodeConfigMismatchError(RuntimeError):
    """Raised when baseline and probe legs of a red-team run differ in decoding parameters."""


class InsufficientPowerError(RuntimeError):
    """Raised when the configured detection margin is below the variance-induced noise floor."""


@dataclass(frozen=True)
class DecodeConfig:
    temperature: float
    top_p: float
    seed_policy: str
    max_tokens: int
    system_prompt_hash: str


@dataclass(frozen=True)
class LegResult:
    config: DecodeConfig
    n_probes: int
    unsafe_rate: float


def assert_comparable(baseline: LegResult, probe: LegResult) -> None:
    if baseline.config != probe.config:
        raise DecodeConfigMismatchError(
            f"decode configs differ between legs: baseline={baseline.config} "
            f"probe={probe.config}; comparison is invalid"
        )
    if baseline.n_probes != probe.n_probes:
        raise DecodeConfigMismatchError(
            f"sample counts differ: baseline n={baseline.n_probes} probe n={probe.n_probes}"
        )


def effective_margin(baseline: LegResult, probe: LegResult, alpha: float = 0.05) -> float:
    """One-sided z-based floor for the two-proportion test at the observed rates."""
    pb, pp, n = baseline.unsafe_rate, probe.unsafe_rate, probe.n_probes
    se = sqrt(pb * (1 - pb) / n + pp * (1 - pp) / n)
    return NormalDist().inv_cdf(1 - alpha) * se


def gate_run(baseline: LegResult, probe: LegResult, configured_margin: float) -> None:
    assert_comparable(baseline, probe)
    floor = effective_margin(baseline, probe)
    if configured_margin < floor:
        raise InsufficientPowerError(
            f"configured margin {configured_margin:.3f} is below the noise floor "
            f"{floor:.3f} induced by per-probe sampling variance; a real regression "
            f"of size < {floor:.3f} would pass silently"
        )
    # Only reachable when configs match and margin exceeds the variance floor.
    return None
