# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-taint-quarantine-invariant-fail-when-a-privileged-tool-call-is-re-derived-from-a-summarized-plan-instead-of-the-raw-flagged-spa.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-taint-quarantine-invariant-fail-when-a-privileged-tool-call-is-re-derived-from-a-summarized-plan-instead-of-the-raw-flagged-spa.warrant.json
# Markdown SHA-256:   e94ac874052d47653e85e1308f4516e85f059e354bcf8d19f93d324aa9756a20
# Code AST SHA-256:   ea5a50e6c08af33ea3fc1f21302c31c689bc82ad5b35a94704a66371e37ca440
# Verified Classes:   TaintLaunderingError, Span, Provenance, PrivilegedAction, TaintClosureGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when a privileged action's derivational provenance intersects the taint set,
    or when provenance is unknown (fail-closed)."""


@dataclass(frozen=True)
class Span:
    root_id: str
    tainted: bool


@dataclass
class Provenance:
    # Roots from which a value was derived, across any chain of model transformations.
    roots: frozenset[str] = field(default_factory=frozenset)
    # True only if the runtime successfully threaded provenance through every step.
    complete: bool = True

    def derive(self, *sources: "Provenance") -> "Provenance":
        roots: set[str] = set(self.roots)
        complete = self.complete
        for s in sources:
            roots |= s.roots
            complete = complete and s.complete
        return Provenance(frozenset(roots), complete)


@dataclass
class PrivilegedAction:
    name: str
    args: dict
    provenance: Provenance


class TaintClosureGate:
    """Enforces taint closure under derivation at the privileged tool boundary."""

    def __init__(self, tainted_roots: Iterable[str]):
        self._tainted = frozenset(tainted_roots)

    def admit(self, action: PrivilegedAction) -> None:
        prov = action.provenance

        # Fail closed on unknown provenance: an un-threaded summarize() step
        # is a laundering channel, not a clean path.
        if not prov.complete:
            raise TaintLaunderingError(
                f"action {action.name!r}: provenance incomplete; "
                f"treating as tainted (fail-closed)"
            )

        # Empty provenance = model-generated from clean context only.
        if not prov.roots:
            return

        hit = prov.roots & self._tainted
        if hit:
            raise TaintLaunderingError(
                f"action {action.name!r}: derivational provenance intersects "
                f"taint set {sorted(hit)}; blocked (quarantine the action, "
                f"not just the document)"
            )


def issue_refund(account: str, amount: int, plan_provenance: Provenance,
                 gate: TaintClosureGate) -> None:
    # The account literal was re-derived from a plan step, not copied from the
    # raw flagged span. The gate must see the plan's provenance, not the literal.
    action = PrivilegedAction(
        name="issue_refund",
        args={"account": account, "amount": amount},
        provenance=plan_provenance,
    )
    gate.admit(action)
    # ... execute privileged call only after admission ...


if __name__ == "__main__":
    gate = TaintClosureGate(tainted_roots={"doc#4412"})

    # Direct path: raw slice of the flagged ticket. Blocked (expected).
    try:
        issue_refund("7731", 500,
                     Provenance(frozenset({"doc#4412"}), complete=True), gate)
    except TaintLaunderingError as e:
        print("direct:", e)

    # Laundered path: plan step derived from the flagged ticket, but the
    # summarize() call was not threaded -> provenance incomplete.
    try:
        issue_refund("7731", 500,
                     Provenance(frozenset(), complete=False), gate)
    except TaintLaunderingError as e:
        print("laundered:", e)
