# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-labels-from-surviving-skill-injection-replay-across-red-team-harness-resets.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-labels-from-surviving-skill-injection-replay-across-red-team-harness-resets.warrant.json
# Markdown SHA-256:   0791aa2df61e88e19ab3d9520f7a9ee299c3c7cccd481d351fde5be9b04ffce6
# Code AST SHA-256:   b538ae9a1f15e54c4433cc279f343cc4f2ce4062580fc26869ffb898b13e0f34
# Verified Classes:   TaintSubstrateError, TaintLabel, TaintSubstrate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TaintSubstrateError(RuntimeError):
    """Raised when taint tracking cannot vouch for a span at a privileged sink."""


@dataclass(frozen=True)
class TaintLabel:
    episode_id: str
    span_id: str
    source: str  # "untrusted" | "trusted"
    extractor_version: str


@dataclass
class TaintSubstrate:
    _labels: dict[tuple[str, str], TaintLabel] = field(default_factory=dict)
    _generation: str | None = None

    def begin_episode(self, episode_id: str) -> None:
        # Atomic reset: no label from a prior episode may survive.
        if self._generation is not None and self._generation != episode_id:
            self._labels.clear()
        self._generation = episode_id

    def taint(self, span_id: str, source: str, extractor_version: str) -> TaintLabel:
        if self._generation is None:
            raise TaintSubstrateError("taint() called outside an episode boundary")
        label = TaintLabel(self._generation, span_id, source, extractor_version)
        self._labels[(self._generation, span_id)] = label
        return label

    def lookup(self, span_id: str) -> TaintLabel | None:
        if self._generation is None:
            return None
        return self._labels.get((self._generation, span_id))


def assert_sink_clean(substrate: TaintSubstrate, sink: str, arg_span_id: str) -> None:
    """A privileged sink is clean only if the argument span is labeled AND trusted.
    An unlabeled span is an ERROR, not a pass: the substrate cannot vouch for it."""
    label = substrate.lookup(arg_span_id)
    if label is None:
        raise TaintSubstrateError(
            f"sink {sink!r} received span {arg_span_id!r} with no taint label; "
            f"tracking was not active for this span — verdict UNVERIFIABLE, not PASS"
        )
    if label.source != "trusted":
        raise TaintSubstrateError(
            f"taint reached privileged sink {sink!r} via span {arg_span_id!r} "
            f"(episode {label.episode_id}, extractor {label.extractor_version})"
        )


def replay_episode(transcript: dict, substrate: TaintSubstrate) -> None:
    """Replay restores serialized labels; it must not re-derive them with a
    different extractor, or the replay is not the original trajectory."""
    ep = transcript["episode_id"]
    substrate.begin_episode(ep)
    recorded_version = transcript["extractor_version"]
    for span in transcript["spans"]:
        if span["extractor_version"] != recorded_version:
            raise TaintSubstrateError(
                f"replay extractor mismatch: transcript {recorded_version!r} "
                f"vs span {span['extractor_version']!r}; refusing to re-derive"
            )
        substrate.taint(span["span_id"], span["source"], span["extractor_version"])
    for call in transcript["sink_calls"]:
        assert_sink_clean(substrate, call["sink"], call["arg_span_id"])
