# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-safety-regression-correlation-its-own-otel-genai-observability-dashboard-has-already-committed-to.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-safety-regression-correlation-its-own-otel-genai-observability-dashboard-has-already-committed-to.warrant.json
# Markdown SHA-256:   b3d7f9366648b59c0da01a915b6ab516e3d6cde4dd59a38432d5000da3b779a5
# Code AST SHA-256:   97bed3bb2f674dd1a2ed9943089a92dc3fe56bbb15cd77d9cd0ae57aa4e7634e
# Verified Classes:   UnidentifiedCorrelationError, CorrelationEvidence
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class UnidentifiedCorrelationError(RuntimeError):
    """Raised when a safety-regression correlation is computed over a
    population the dashboard cannot characterize (sampling shift or
    evaluator dependence). The coefficient must not be emitted."""


@dataclass(frozen=True)
class CorrelationEvidence:
    cohort: str
    retained_traces: int
    total_traces: int
    baseline_retention_ratio: float
    evaluator_shares_model_family: bool
    unweighted_r: float
    ipw_r: float


def emit_correlation(ev: CorrelationEvidence) -> float:
    if ev.total_traces <= 0 or ev.retained_traces <= 0:
        raise UnidentifiedCorrelationError(
            f"cohort={ev.cohort}: empty retained or total population; "
            "correlation is undefined, not zero"
        )

    ratio = ev.retained_traces / ev.total_traces
    shift = max(ratio, ev.baseline_retention_ratio) / max(
        min(ratio, ev.baseline_retention_ratio), 1e-9
    )

    if shift > 2.0:
        raise UnidentifiedCorrelationError(
            f"cohort={ev.cohort}: retention ratio shifted {shift:.2f}x vs baseline "
            f"({ratio:.4f} vs {ev.baseline_retention_ratio:.4f}); "
            "trace-selection bias likely, suppress coefficient"
        )

    if ev.evaluator_shares_model_family:
        raise UnidentifiedCorrelationError(
            f"cohort={ev.cohort}: retention-gating evaluator shares model family "
            "with agent under test; a regression that evades the agent also "
            "evades retention, evidence is not independent"
        )

    lo, hi = sorted((ev.unweighted_r, ev.ipw_r))
    if hi - lo > 0.15:
        raise UnidentifiedCorrelationError(
            f"cohort={ev.cohort}: unweighted r={ev.unweighted_r:.3f} vs "
            f"IPW r={ev.ipw_r:.3f}; sensitivity to sampling skew exceeds bound, "
            "emit CORRELATION_UNIDENTIFIED instead"
        )

    return ev.ipw_r
