# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-benchmark-contamination-when-a-litmus-safety-probe-s-adversarial-payload-leaks-into-the-regression-suite-s-few-shot-exempl.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-benchmark-contamination-when-a-litmus-safety-probe-s-adversarial-payload-leaks-into-the-regression-suite-s-few-shot-exempl.warrant.json
# Markdown SHA-256:   10103aeeb30b95b8bfb76e40c153a4e92ca7838abb3b8100e1fe04e778436603
# Code AST SHA-256:   11a4d3fbe0b6be623a4e8e806041ec10420a299d5345e46a712dbf59426fc6d4
# Verified Classes:   LineageContaminationError, MissingLineageTagError, Exemplar, Probe, Retrieval
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class LineageContaminationError(RuntimeError):
    """Raised when a retrieved exemplar shares payload lineage with the probe under test."""
    pass


class MissingLineageTagError(RuntimeError):
    """Raised when an exemplar or probe lacks a lineage tag; gate must fail closed."""
    pass


@dataclass(frozen=True)
class Exemplar:
    exemplar_id: str
    lineage_root: Optional[str]   # None means untagged -> inadmissible
    derivation_path: tuple


@dataclass(frozen=True)
class Probe:
    probe_id: str
    lineage_root: Optional[str]


@dataclass(frozen=True)
class Retrieval:
    exemplar: Exemplar
    similarity: float


CONTAMINATION_FLOOR = 0.90


def check_admissibility(probe: Probe, retrievals: list[Retrieval]) -> str:
    """
    Returns 'ADMISSIBLE', 'QUARANTINED', or 'INDETERMINATE'.
    Fails closed: any missing tag or any lineage overlap quarantines the probe.
    """
    if probe.lineage_root is None:
        raise MissingLineageTagError(
            f"probe {probe.probe_id} has no lineage_root; cannot certify gate"
        )

    for r in retrievals:
        if r.exemplar.lineage_root is None:
            raise MissingLineageTagError(
                f"exemplar {r.exemplar.exemplar_id} retrieved for probe "
                f"{probe.probe_id} has no lineage_root; gate fails closed"
            )
        if r.exemplar.lineage_root == probe.lineage_root:
            raise LineageContaminationError(
                f"exemplar {r.exemplar.exemplar_id} (sim={r.similarity:.3f}) "
                f"shares lineage_root {probe.lineage_root!r} with probe "
                f"{probe.probe_id}; score is a memorization artifact, not a "
                f"safety measurement"
            )
        if r.similarity >= CONTAMINATION_FLOOR:
            # High similarity without shared lineage is suspicious but not
            # proven contamination; quarantine rather than admit.
            return "QUARANTINED"

    return "ADMISSIBLE"


def gate_run(probes: list[Probe], retrievals_by_probe: dict[str, list[Retrieval]]) -> dict:
    results = {"admissible": 0, "quarantined": 0, "untrusted": 0}
    for p in probes:
        try:
            verdict = check_admissibility(p, retrievals_by_probe.get(p.probe_id, []))
        except (LineageContaminationError, MissingLineageTagError):
            verdict = "UNTRUSTED"
        results[verdict.lower()] += 1

    if results["untrusted"] > 0:
        # A run with any untrusted probe cannot update the baseline.
        raise LineageContaminationError(
            f"{results['untrusted']} probes failed lineage certification; "
            f"run is UNTRUSTED and must not become the regression baseline"
        )
    return results
