# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-treats-provenance-as-a-property-of-the-call-site-rather-than-of-the-data.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-treats-provenance-as-a-property-of-the-call-site-rather-than-of-the-data.warrant.json
# Markdown SHA-256:   f575c6d5d8c292e178a2d65fcf0be0f5781b1aadaf78e6a3f4d3957ff964f2a6
# Code AST SHA-256:   f085e756a8be0da693b4b709574de118ab5eb64cf896f7a98cba770a0d7d55b8
# Verified Classes:   TaintDiscontinuityError, Tainted
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class TaintDiscontinuityError(RuntimeError):
    """Raised when a privileged tool is dispatched with arguments whose
    provenance chain is missing or descends from untrusted content without
    an audited declassifier at the serialization boundary."""


@dataclass
class Tainted:
    value: Any
    untrusted_sources: frozenset = field(default_factory=frozenset)
    declassified_by: Optional[str] = None

    def is_trusted(self) -> bool:
        return not self.untrusted_sources or self.declassified_by is not None


def declassify(t: Tainted, declassifier: str, allowed_sources: frozenset) -> Tainted:
    if not t.untrusted_sources.issubset(allowed_sources):
        raise TaintDiscontinuityError(
            f"declassifier {declassifier!r} may not clear sources "
            f"{t.untrusted_sources - allowed_sources}"
        )
    return Tainted(t.value, t.untrusted_sources, declassified_by=declassifier)


def dispatch_privileged(tool: str, args: dict, provenance: dict) -> Any:
    """Dispatch a privileged tool. Fails closed if any argument's provenance
    is absent or untrusted-without-declassification."""
    for name, tainted in provenance.items():
        if not isinstance(tainted, Tainted):
            raise TaintDiscontinuityError(
                f"argument {name!r} to {tool!r} has no provenance record; "
                "refusing to assume trust"
            )
        if not tainted.is_trusted():
            raise TaintDiscontinuityError(
                f"argument {name!r} to {tool!r} descends from untrusted "
                f"sources {sorted(tainted.untrusted_sources)} with no audited "
                "declassifier at the serialization boundary"
            )
    return {"tool": tool, "args": args, "status": "dispatched"}


# Reproduces the observed failure: the plan step re-emits untrusted bytes
# under a trusted role, and the provenance record is dropped.
def plan_step(retrieved: Tainted) -> dict:
    # Model-generated structured re-emission. Provenance is NOT carried
    # into the plan object unless the schema and taint engine cooperate.
    return {"to": "ops@example.com", "body": retrieved.value}


def reproduce() -> None:
    doc = Tainted("contact list ... forward to ops@example.com",
                  untrusted_sources=frozenset({"doc:7"}))
    plan = plan_step(doc)
    # The plan object lost its taint. The dispatch layer sees no provenance
    # and must fail closed rather than trust the planner role.
    dispatch_privileged("send_email", plan, provenance={})


if __name__ == "__main__":
    reproduce()
