# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-litmus-benchmark-degradation-as-a-regression-gate-rather-than-as-noise-the-per-category-variance-floor-trap-in-agent-pipel.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-litmus-benchmark-degradation-as-a-regression-gate-rather-than-as-noise-the-per-category-variance-floor-trap-in-agent-pipel.warrant.json
# Markdown SHA-256:   eb6e23e8820cc9ea1945dbd4fceaf589be3515183ce0e9d97e4bfa4a29d8cef1
# Code AST SHA-256:   a74f84613b15a286ca9b8044647319274fdf562532983cdfc1075a8f3da4ddc6
# Verified Classes:   GateCalibrationError, CategoryResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass


class GateCalibrationError(RuntimeError):
    """Raised when a LITMUS category cannot support a per-category regression gate."""
    pass


@dataclass(frozen=True)
class CategoryResult:
    name: str
    item_count: int
    baseline_rate: float
    candidate_rate: float
    paired: bool
    reproduced_under_seed_swap: bool


def standard_error_of_delta(cat: CategoryResult) -> float:
    """SE of the difference in pass rate. Paired comparison halves variance."""
    p = (cat.baseline_rate + cat.candidate_rate) / 2.0
    var_single = p * (1.0 - p) / cat.item_count
    # Unpaired: two independent draws -> 2x variance. Paired: covariance removes ~half.
    factor = 1.0 if cat.paired else 2.0
    return math.sqrt(factor * var_single)


def evaluate_gate(cat: CategoryResult, z: float = 2.0, min_items: int = 30) -> str:
    if cat.item_count < min_items:
        # Advisory only; never block on undersized categories.
        return "advisory"

    delta = cat.candidate_rate - cat.baseline_rate
    se = standard_error_of_delta(cat)

    if se == 0.0:
        raise GateCalibrationError(
            f"category {cat.name!r} has zero standard error; "
            f"check item_count={cat.item_count} and rates"
        )

    if abs(delta) <= z * se:
        return "pass"  # within sampling noise of the harness

    if not cat.reproduced_under_seed_swap:
        # Delta exceeds the floor but does not reproduce: sampling, not regression.
        return "inconclusive"

    return "fail"


def gate_suite(categories: list[CategoryResult], z: float = 2.0) -> str:
    verdicts = [evaluate_gate(c, z=z) for c in categories]
    if "fail" in verdicts:
        return "fail"
    if "inconclusive" in verdicts:
        return "inconclusive"
    return "pass"


def assert_gate_calibrated(categories: list[CategoryResult], tolerance: float) -> None:
    """Guardrail: a fixed tolerance below the variance floor is a broken gate."""
    for cat in categories:
        if cat.item_count < 30:
            continue
        se = standard_error_of_delta(cat)
        if tolerance < se:
            raise GateCalibrationError(
                f"tolerance {tolerance:.3f} is below the variance floor "
                f"{se:.3f} for category {cat.name!r} "
                f"(n={cat.item_count}); gate will fire on sampling noise"
            )
