# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-taint-a-value-that-was-already-sanitized-before-a-second-mcp-egress-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-taint-a-value-that-was-already-sanitized-before-a-second-mcp-egress-boundary.warrant.json
# Markdown SHA-256:   7edfdbbc5619fd64a6bd252b69e1ffd46048bd9214016d5afaa9593aaed7d439
# Code AST SHA-256:   725025386c75b50939de9be79043ae5431ce2d7029e50cb639fa8da67fb90841
# Verified Classes:   TaintSinkMismatchError, TaintedValue
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintSinkMismatchError(RuntimeError):
    """Raised when a cached clean verdict is reused at a sink it was not minted for."""
    pass


@dataclass
class TaintedValue:
    value_id: str
    payload: Any
    # verdicts are keyed by sink_id, never by value alone
    clean_for_sink: dict[str, bool] = field(default_factory=dict)
    recombined: bool = False


def sanitize_for_sink(tv: TaintedValue, sink_id: str) -> TaintedValue:
    """Apply sink-specific sanitization and mint a verdict bound to that sink."""
    # (real implementation would strip/escape per the sink's grammar)
    tv.clean_for_sink[sink_id] = True
    tv.recombined = False
    return tv


def egress(tv: TaintedValue, sink_id: str, sink_grammar_known: bool) -> Any:
    """Forward a value across a boundary, enforcing per-sink taint validity."""
    if tv.recombined:
        raise TaintSinkMismatchError(
            f"value {tv.value_id} was recombined after sanitization; "
            f"re-taint required before egress to {sink_id}"
        )
    if not sink_grammar_known:
        # destination grammar unknown: prior verdicts cannot be trusted
        raise TaintSinkMismatchError(
            f"destination {sink_id} grammar unknown; cached verdicts invalid, "
            f"must re-sanitize for this sink"
        )
    if not tv.clean_for_sink.get(sink_id, False):
        # verdict was minted for a different sink (or none) -> re-taint and re-sanitize
        sanitize_for_sink(tv, sink_id)
        if not tv.clean_for_sink.get(sink_id, False):
            raise TaintSinkMismatchError(
                f"re-sanitization for {sink_id} failed for value {tv.value_id}"
            )
    return tv.payload
