# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-label-laundering-across-agentic-tool-call-retry-loops.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-label-laundering-across-agentic-tool-call-retry-loops.warrant.json
# Markdown SHA-256:   34cdef5a9a3e40878443e6cc7f49cb4ee0068bc5f851479ead20fcf04e5ac5bc
# Code AST SHA-256:   fcc883ffc4af9a9c2ed685dcb8d82ccf1f664145964d954ec11170412158260a
# Verified Classes:   TaintLaunderingError, Frame
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when a retry frame emits arguments without inheriting frame taint."""


@dataclass
class Frame:
    frame_id: str
    taint: set[str] = field(default_factory=set)
    scrubbed: bool = False

    def absorb(self, labels: Iterable[str]) -> None:
        if self.scrubbed:
            return
        self.taint.update(labels)


def evaluate_sink(frame: Frame, arg_labels: dict[str, set[str]], sink: str) -> None:
    # Frame-level inheritance: any tainted read in this frame taints every arg.
    inherited = set(frame.taint)
    for labels in arg_labels.values():
        inherited.update(labels)

    if frame.scrubbed and not inherited:
        return

    if inherited:
        raise TaintLaunderingError(
            f"sink={sink!r} frame={frame.frame_id!r} "
            f"would emit tainted arguments; inherited labels={sorted(inherited)}. "
            f"Retry requires a proven clean-room scrub, not reformulation."
        )


def retry_after_violation(prior: Frame, model_context_reads: Iterable[str]) -> Frame:
    new = Frame(frame_id=f"{prior.frame_id}:retry")
    new.absorb(prior.taint)
    new.absorb(model_context_reads)
    if prior.taint and not new.taint:
        raise TaintLaunderingError(
            f"retry frame {new.frame_id!r} dropped taint from {prior.frame_id!r} "
            f"without a scrub record; refusing to proceed"
        )
    return new
