# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-inherits-taint-through-an-mcp-tool-boundary-it-never-observed.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-inherits-taint-through-an-mcp-tool-boundary-it-never-observed.warrant.json
# Markdown SHA-256:   34bc0a03579f1d60ec59c287da3b915e78949cbe99c4c1722d6e92bfa799b966
# Code AST SHA-256:   28909d3b3be79c4d2e3700ef7060295269120ddc819b1a87ec88606f916d320e
# Verified Classes:   TaintLaunderingError, Labeled
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Optional


class TaintLaunderingError(RuntimeError):
    """Raised when an A2A result is promoted to trusted without a
    verifiable provenance chain to a trusted root."""


@dataclass(frozen=True)
class Labeled:
    value: str
    taint: FrozenSet[str]          # e.g. {"untrusted:user_msg"}
    provenance: FrozenSet[str] = field(default_factory=frozenset)


def a2a_join(parent_labels: FrozenSet[str],
             result: Labeled,
             digest_signed: bool) -> Labeled:
    """Join taint across an A2A handoff. Fail closed on missing provenance."""
    if not result.provenance and result.taint:
        # Sub-agent returned tainted value but no provenance digest:
        # cannot verify the chain, so the boundary itself is unknown.
        raise TaintLaunderingError(
            f"result carries taint {result.taint} but no provenance digest; "
            "cannot join across A2A boundary"
        )
    if result.provenance and not digest_signed:
        raise TaintLaunderingError(
            "provenance digest is unsigned; refusing to promote to trusted "
            "(adversarial laundering not bounded)"
        )
    joined = parent_labels | result.taint | result.provenance
    return Labeled(value=result.value, taint=joined, provenance=joined)


def guarded_sink(arg: Labeled, sink_name: str) -> None:
    """Side-effecting sink: re-validate against root, not just arg label."""
    if "untrusted" in "".join(arg.taint) or not arg.provenance:
        raise TaintLaunderingError(
            f"sink {sink_name!r} refused: arg taint={set(arg.taint)} "
            f"provenance={set(arg.provenance)}"
        )
    # ... perform write ...


def run_chain() -> None:
    parent = frozenset({"untrusted:user_msg"})
    # Worker W returns a summary derived from untrusted doc D, but the
    # A2A envelope dropped the provenance digest (the observed failure).
    w_result = Labeled(value="summary of D", taint=frozenset({"untrusted:doc_D"}),
                       provenance=frozenset())
    joined = a2a_join(parent, w_result, digest_signed=False)  # raises
    guarded_sink(joined, "post_summary")
