# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-slo-survive-trace-sampling-while-its-error-budget-silently-dies-the-tail-sampling-denominator-collapse-in-genai-span-metrics.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-slo-survive-trace-sampling-while-its-error-budget-silently-dies-the-tail-sampling-denominator-collapse-in-genai-span-metrics.warrant.json
# Markdown SHA-256:   16d9eeb5f9a0250a6bc27e35ba9327fb213cd40f1b0a34bede7324948172a5bc
# Code AST SHA-256:   df8add50ba6738a702cf341220f4d8131397954906ddc9335c034f16ce13be74
# Verified Classes:   SamplingBiasError, SpanClassStats
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass


class SamplingBiasError(RuntimeError):
    """Raised when an SLO ratio is computed over spans whose inclusion
    probability is correlated with the outcome class (tail sampling)."""
    pass


@dataclass
class SpanClassStats:
    kept: int
    inclusion_prob: float  # probability this class survives the sampler


def compute_reweighted_error_rate(
    errored: SpanClassStats,
    healthy: SpanClassStats,
    max_bias_ratio: float = 2.0,
) -> float:
    """Return an unbiased error-rate estimate, or refuse.

    The estimator is (errored_kept / p_err) / (errored_kept/p_err + healthy_kept/p_healthy).
    If the keep-probability ratio exceeds max_bias_ratio, the span-ratio
    SLO is structurally untrustworthy and we refuse rather than emit.
    """
    if errored.inclusion_prob <= 0 or healthy.inclusion_prob <= 0:
        raise SamplingBiasError(
            f"non-positive inclusion probability: "
            f"err={errored.inclusion_prob}, healthy={healthy.inclusion_prob}"
        )

    bias_ratio = errored.inclusion_prob / healthy.inclusion_prob
    if bias_ratio > max_bias_ratio:
        raise SamplingBiasError(
            f"tail-sampler bias ratio {bias_ratio:.2f}x exceeds "
            f"{max_bias_ratio:.2f}x: errored spans kept at "
            f"{errored.inclusion_prob:.0%}, healthy at "
            f"{healthy.inclusion_prob:.0%}. Span-ratio SLO is invalid; "
            f"re-derive from pre-sampler counters."
        )

    est_err = errored.kept / errored.inclusion_prob
    est_healthy = healthy.kept / healthy.inclusion_prob
    denom = est_err + est_healthy
    if denom <= 0:
        raise SamplingBiasError("empty population after reweighting")
    return est_err / denom


def evaluate_slo(
    errored: SpanClassStats,
    healthy: SpanClassStats,
    budget: float = 0.01,
) -> str:
    try:
        rate = compute_reweighted_error_rate(errored, healthy)
    except SamplingBiasError as exc:
        # Fail closed: an actuator must never fire on a biased ratio.
        return f"REFUSED: {exc}"
    burn = rate / budget
    return (
        f"error_rate={rate:.4%} budget={budget:.2%} "
        f"burn={burn:.2f}x -> {'BREACH' if burn >= 1.0 else 'OK'}"
    )


# Observed incident: 100% of error traces kept, 5% of healthy traces kept.
print(evaluate_slo(
    errored=SpanClassStats(kept=620, inclusion_prob=1.00),
    healthy=SpanClassStats(kept=3100, inclusion_prob=0.05),
))
# -> REFUSED: tail-sampler bias ratio 20.00x exceeds 2.00x ...
