# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-tainted-provenance-through-a-tool-that-returns-its-own-output-as-a-new-observation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-tainted-provenance-through-a-tool-that-returns-its-own-output-as-a-new-observation.warrant.json
# Markdown SHA-256:   c3dcc087a0c61d981dc418cc9c4a9e91ddf7ccc1d4d35c5c1990da0c5f4ef7f6
# Code AST SHA-256:   1cf283477ee59b5bb0219eee4015d9bf776f29186fcbec988c27a4a004a74f70
# Verified Classes:   ProvenanceLaunderingError, Taint, ToolSpec
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a tool output would reduce taint below its input taint."""


@dataclass(frozen=True)
class Taint:
    trusted_roots: FrozenSet[str] = frozenset()
    tainted_sources: FrozenSet[str] = frozenset()
    unknown_channels: FrozenSet[str] = frozenset()

    def join(self, other: "Taint") -> "Taint":
        return Taint(
            self.trusted_roots | other.trusted_roots,
            self.tainted_sources | other.tainted_sources,
            self.unknown_channels | other.unknown_channels,
        )

    def is_trusted(self) -> bool:
        return not self.tainted_sources and not self.unknown_channels


@dataclass
class ToolSpec:
    name: str
    pure: bool  # True only if output is a proven function of input


def apply_tool(spec: ToolSpec, input_taint: Taint, output_value: str) -> Taint:
    # Monotonicity invariant: output taint must be a superset of input taint.
    if spec.pure:
        result = input_taint
    else:
        # Non-pure tools add their own channel; they never reset to trusted.
        result = input_taint.join(Taint(unknown_channels=frozenset({spec.name})))

    if not (result.tainted_sources >= input_taint.tainted_sources):
        raise ProvenanceLaunderingError(
            f"tool {spec.name} dropped tainted_sources: "
            f"{input_taint.tainted_sources} -> {result.tainted_sources}"
        )
    if not (result.unknown_channels >= input_taint.unknown_channels):
        raise ProvenanceLaunderingError(
            f"tool {spec.name} dropped unknown_channels: "
            f"{input_taint.unknown_channels} -> {result.unknown_channels}"
        )
    return result


def sink_gate(sink: str, value_taint: Taint) -> None:
    if not value_taint.is_trusted():
        raise ProvenanceLaunderingError(
            f"sink {sink} refused: value carries "
            f"tainted_sources={value_taint.tainted_sources} "
            f"unknown_channels={value_taint.unknown_channels}"
        )


# Reproduction of the observed failure.
email_body = Taint(tainted_sources=frozenset({"email:msg_4417"}))
url_taint = apply_tool(ToolSpec("extract_links", pure=True), email_body, "http://x")
# Correct behavior: fetch_url is non-pure, so it ADDS its channel, never resets.
page_taint = apply_tool(ToolSpec("fetch_url", pure=False), url_taint, "<title>...")
try:
    sink_gate("send_email", page_taint)
except ProvenanceLaunderingError as e:
    print(f"blocked as designed: {e}")

# The buggy registration that caused the incident:
buggy = apply_tool(ToolSpec("fetch_url", pure=True), url_taint, "<title>...")
# If fetch_url were (wrongly) marked pure AND the join reset, page_taint would be
# trusted and sink_gate would pass. The guard above prevents that class of bug.
