# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-provenance-tainted-context-before-tool-call-sink-execution-and-where-does-taint-tracking-silently-under.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-provenance-tainted-context-before-tool-call-sink-execution-and-where-does-taint-tracking-silently-under.warrant.json
# Markdown SHA-256:   573566eb40469a29c614955e2e19ed19bf354cb56d67aca61a8fbec8fa94c162
# Code AST SHA-256:   030ca1a5af333f3e5623be8d845d67f3ecda7bd4a99988e35f531b75bfd5ba5d
# Verified Classes:   TaintViolation, TaintLaunderingError, TaintedValue
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

# Taint lattice: join is set union; UNTRUSTED is absorbing for sink policy.
TRUSTED_USER = "trusted_user"
UNTRUSTED = "untrusted"
TOOL_DERIVED = "tool_derived"

class TaintViolation(RuntimeError):
    """Raised when a sink argument carries taint that the sink policy forbids."""
    pass

class TaintLaunderingError(RuntimeError):
    """Raised when a value is constructed from tainted inputs without a derivation edge."""
    pass

@dataclass(frozen=True)
class TaintedValue:
    payload: object
    taint: FrozenSet[str]
    derivation: tuple = field(default_factory=tuple)  # ids of contributing values

def join(*values: TaintedValue) -> TaintedValue:
    """Construct a derived value; taint is the join (union) of all inputs."""
    taint = frozenset().union(*(v.taint for v in values))
    deriv = tuple(v_id for v in values for v_id in (v.derivation or (id(v),)))
    return TaintedValue(payload=None, taint=taint, derivation=deriv)

def tool_output(tool_name: str, source_class: str, body: object) -> TaintedValue:
    """Label by DATA SOURCE, not tool identity. Over-approximate; fail safe."""
    if source_class == "web":
        return TaintedValue(payload=body, taint=frozenset({UNTRUSTED}), derivation=(id(body),))
    if source_class == "trusted_internal":
        return TaintedValue(payload=body, taint=frozenset({TOOL_DERIVED}), derivation=(id(body),))
    # Unknown source class: default to tainted.
    return TaintedValue(payload=body, taint=frozenset({UNTRUSTED}), derivation=(id(body),))

def summarize(inputs: list[TaintedValue]) -> TaintedValue:
    """Compaction must join taint forward; it must NOT reset to assistant-default."""
    if not inputs:
        raise TaintLaunderingError("summarize called with no derivation inputs")
    out = join(*inputs)
    return TaintedValue(payload="<summary>", taint=out.taint, derivation=out.derivation)

FORBIDDEN_AT_SINK = {
    "send_email": frozenset({UNTRUSTED}),
    "fetch_url": frozenset({UNTRUSTED}),
}

def enforce_sink(sink: str, args: dict[str, TaintedValue], declassified_by: str | None = None) -> None:
    """Evaluate taint on the ARGUMENT DERIVATION, not on segment presence in context."""
    forbidden = FORBIDDEN_AT_SINK.get(sink)
    if forbidden is None:
        return
    for name, val in args.items():
        if val.taint & forbidden:
            if declassified_by is None:
                raise TaintViolation(
                    f"sink {sink!r} arg {name!r} carries taint {sorted(val.taint)}; "
                    f"derivation={val.derivation}; declassification required"
                )
            # Declassification is explicit and audited; it is the only taint decrease.
            audit_log(declassified_by, sink, name, sorted(val.taint))

def audit_log(principal: str, sink: str, arg: str, taint: list[str]) -> None:
    # Real implementation writes to an append-only audit store.
    pass

def run_scenario() -> None:
    contract = TaintedValue(payload="...injected instruction...", taint=frozenset({UNTRUSTED}), derivation=("doc-1",))
    fetched = tool_output("fetch_url", "web", '{"status":"ok"}')  # web source -> UNTRUSTED
    summary = summarize([contract, fetched])  # taint joins forward -> UNTRUSTED
    # Sink policy sees the derivation taint, not segment presence.
    enforce_sink("send_email", {"body": summary})  # raises TaintViolation
    raise TaintViolation("unreachable: enforce_sink should have raised")

if __name__ == "__main__":
    try:
        run_scenario()
    except TaintViolation as e:
        print(f"blocked as expected: {e}")
