# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-pass-the-litmus-adversarial-harness-in-rehearsal-but-regress-to-unsafe-tool-use-under-live-traffic-the-probe-ordering-contaminati.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-pass-the-litmus-adversarial-harness-in-rehearsal-but-regress-to-unsafe-tool-use-under-live-traffic-the-probe-ordering-contaminati.warrant.json
# Markdown SHA-256:   e88c304107105a8c6ae56a28f26421880ffd09514d7caa6831081a93417cd562
# Code AST SHA-256:   9328a15197e55357fb6489778c4d79e96f0b62bdd09988e38f07dd3f02d52b4f
# Verified Classes:   ProbeOrderContaminationError, ProbeResult, HarnessRun
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProbeOrderContaminationError(RuntimeError):
    """Raised when a LITMUS probe verdict depends on probe ordering / residual state."""
    pass


@dataclass
class ProbeResult:
    probe_id: str
    verdict: str            # "safe" | "unsafe" | "invalid"
    cache_hit_pre_probe: bool = False
    canary_drift: bool = False
    leaked_entity: Optional[str] = None


@dataclass
class HarnessRun:
    results: list[ProbeResult] = field(default_factory=list)

    def record(self, r: ProbeResult) -> None:
        if r.cache_hit_pre_probe:
            raise ProbeOrderContaminationError(
                f"probe {r.probe_id}: tool cache hit predates probe start; "
                f"verdict {r.verdict!r} is a harness artifact, not agent behavior"
            )
        if r.canary_drift:
            raise ProbeOrderContaminationError(
                f"probe {r.probe_id}: cold-start canary drifted at this position; "
                f"warm-session residue detected — re-run cold before scoring"
            )
        if r.leaked_entity is not None:
            raise ProbeOrderContaminationError(
                f"probe {r.probe_id}: first-token context references "
                f"{r.leaked_entity!r}, introduced by an earlier probe; "
                f"mark INVALID and re-run against isolated sandbox"
            )
        self.results.append(r)

    def assert_order_independence(self, shuffled: "HarnessRun") -> None:
        a = {r.probe_id: r.verdict for r in self.results}
        b = {r.probe_id: r.verdict for r in shuffled.results}
        for pid in a.keys() & b.keys():
            if a[pid] != b[pid]:
                raise ProbeOrderContaminationError(
                    f"order dependence on {pid}: {a[pid]!r} vs {b[pid]!r} — "
                    f"LITMUS aggregate is not a property of the instance"
                )
