# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-taint-propagation-when-a-tool-call-graph-re-enters-trusted-state-through-a-laundered-argument.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-taint-propagation-when-a-tool-call-graph-re-enters-trusted-state-through-a-laundered-argument.warrant.json
# Markdown SHA-256:   f8f58ec4ee771a16c47ee1028af4ac175b2fd9966855170eb35bf8fd7cf45e26
# Code AST SHA-256:   064285539faadacf0097f4bdc0e1aee16eccaea31d3cfd7dcc6c56197d9c637b
# Verified Classes:   TaintLaunderingError, TaintSet, ToolSchema
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when a trusted call would emit a return cleaner than its consumed arguments."""


@dataclass(frozen=True)
class TaintSet:
    sources: frozenset[str] = field(default_factory=frozenset)

    def join(self, other: "TaintSet") -> "TaintSet":
        return TaintSet(self.sources | other.sources)

    def __bool__(self) -> bool:
        return bool(self.sources)


@dataclass(frozen=True)
class ToolSchema:
    name: str
    # Explicit, audited permission to declassify. Empty means the tool may not
    # produce a return cleaner than its inputs.
    declassifies: frozenset[str] = field(default_factory=frozenset)


def invoke_tool(
    schema: ToolSchema,
    args: dict[str, tuple[Any, TaintSet]],
    impl,
) -> tuple[Any, TaintSet]:
    consumed = TaintSet()
    for _name, (_value, taint) in args.items():
        consumed = consumed.join(taint)

    result = impl({k: v for k, (v, _t) in args.items()})

    # A tool may only shed taint it explicitly declared it declassifies.
    residual = consumed.sources - schema.declassifies
    if residual:
        raise TaintLaunderingError(
            f"tool {schema.name!r} would launder taint {sorted(residual)} "
            f"into a clean return; declare declassification or propagate"
        )
    return result, TaintSet()


def run_pipeline(document: str, injected_source: str = "fetch_document") -> None:
    tainted_doc = (document, TaintSet(frozenset({injected_source})))

    # Trusted normalizer: parses and re-emits. Without a declassification
    # annotation it must not return a clean value.
    normalize = ToolSchema(name="normalize_id", declassifies=frozenset())
    invoke_tool(
        normalize,
        {"raw": tainted_doc},
        lambda a: a["raw"].strip().lower(),
    )
