# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-label-laundering-across-mcp-tool-return-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-label-laundering-across-mcp-tool-return-boundaries.warrant.json
# Markdown SHA-256:   c1e816648c67d0b03ddf7e476b9e54064f7e7924884ab4a8ca5b244215602fc1
# Code AST SHA-256:   5353981ba9f1f02ab2ee2dcb73f85ee74ce501194c2a759b5d16c46c855e3974
# Verified Classes:   LabelLaunderingError, MissingTaintFieldError, CallResult, OutstandingCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

class LabelLaunderingError(RuntimeError):
    """Raised when a tool result's taint set is not a superset of its inputs' taint.

    This is the transport-boundary invariant violation that enables injection
    propagation: a derived value re-enters context with fewer labels than its
    sources, so downstream policy gates read a false 'clean' provenance.
    """
    pass

class MissingTaintFieldError(LabelLaunderingError):
    """Result arrived without _meta.taint. Must default to unknown, never clean."""
    pass

UNKNOWN = frozenset({"unknown"})
CLEAN = frozenset()

@dataclass
class CallResult:
    call_id: str
    taint: FrozenSet[str] | None  # None means field absent
    payload: str

@dataclass
class OutstandingCall:
    call_id: str
    arg_taint: FrozenSet[str] = field(default_factory=frozenset)

def enforce_union_on_derivation(
    outstanding: dict[str, OutstandingCall],
    result: CallResult,
    default_unknown: bool = True,
) -> FrozenSet[str]:
    call = outstanding.pop(result.call_id, None)
    if call is None:
        # Uncorrelated result: cannot reconstruct derivation, must not trust it.
        return UNKNOWN

    expected = call.arg_taint

    if result.taint is None:
        if default_unknown and expected:
            # Union-on-derivation: the runtime reconstructs the label from the
            # call it issued, regardless of what the server omitted.
            raise MissingTaintFieldError(
                f"call {result.call_id}: server omitted _meta.taint; "
                f"runtime overrides to union of inputs {sorted(expected)}"
            )
        return UNKNOWN if default_unknown else CLEAN

    if not expected.issubset(result.taint):
        raise LabelLaunderingError(
            f"call {result.call_id}: result taint {sorted(result.taint)} "
            f"is not a superset of input taint {sorted(expected)}; "
            f"laundered labels: {sorted(expected - result.taint)}"
        )
    return result.taint

def gate_tool_call(tool: str, arg_taint: FrozenSet[str], blocked_on: FrozenSet[str]) -> None:
    if arg_taint & blocked_on:
        raise LabelLaunderingError(
            f"tool {tool} blocked: argument derives from tainted segments "
            f"{sorted(arg_taint & blocked_on)}"
        )
