# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-trace-anomaly-alert-as-a-drift-signal-rather-than-noise-the-baseline-poisoning-boundary-in-tool-call-dr.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-trace-anomaly-alert-as-a-drift-signal-rather-than-noise-the-baseline-poisoning-boundary-in-tool-call-dr.warrant.json
# Markdown SHA-256:   1cb5611f2997f6170a2e9344ed0bc5507f4db8a7745a544a2ed99fc633c64b2e
# Code AST SHA-256:   616e4469f7a8c21ed933381ab66ab3fa651104a19f81f39114b26efa61fb039a
# Verified Classes:   BaselinePoisoningError, Reference, Trace
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class BaselinePoisoningError(RuntimeError):
    """Raised when a trace is scored against a reference that postdates it."""


@dataclass(frozen=True)
class Reference:
    artifact_hash: str
    built_at: float  # epoch seconds; the moment the reference window closed


@dataclass(frozen=True)
class Trace:
    trace_id: str
    cohort: str
    emitted_at: float


def score_trace(trace: Trace, reference: Reference, batch_min_emitted_at: float) -> float:
    # Invariant: the reference must be causally independent of the scored batch.
    if reference.built_at >= batch_min_emitted_at:
        raise BaselinePoisoningError(
            f"reference {reference.artifact_hash} built_at={reference.built_at} "
            f"postdates earliest scored trace at {batch_min_emitted_at}; "
            f"scoring would poison the baseline"
        )
    # Distance computation against the frozen reference (omitted).
    return 0.0


def assert_single_mode(distances: list[float], tolerance: float = 0.15) -> None:
    # A multimodal distance distribution against a frozen reference is the
    # fingerprint of a partial rollout, not noise. Refuse to suppress on it.
    if not distances:
        return
    lo, hi = min(distances), max(distances)
    if hi - lo > tolerance and len(distances) >= 2:
        mid = (lo + hi) / 2.0
        below = sum(1 for d in distances if d < mid)
        above = len(distances) - below
        if below and above:
            raise BaselinePoisoningError(
                f"bimodal distance distribution (below={below}, above={above}); "
                f"treat as drift signal, do not auto-rebaseline"
            )
