# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-taint-provenance-after-a-tool-call-chain-crosses-a-retrieval-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-taint-provenance-after-a-tool-call-chain-crosses-a-retrieval-boundary.warrant.json
# Markdown SHA-256:   7d35a3ad252e7f20ba6ec0253a61ab7021295626ebcdefad3fd72d9fe8ca3b61
# Code AST SHA-256:   d605e173b9419826b435dd7effd4cfb3c73fa831698dc8e9a946b13b113c9146
# Verified Classes:   TaintLaunderingError, Segment, ToolSpec
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Literal

TaintEffect = Literal["propagate", "sanitize", "opaque"]


class TaintLaunderingError(RuntimeError):
    """Raised when a privileged call's transitive derivation closure
    includes an untrusted root that the gate would otherwise miss."""


@dataclass
class Segment:
    seg_id: str
    content_hash: str
    label: Literal["trusted", "untrusted"]
    parents: list[str] = field(default_factory=list)


@dataclass
class ToolSpec:
    name: str
    taint_effect: TaintEffect
    deterministic: bool


REGISTRY = {
    "kb.read": ToolSpec("kb.read", "propagate", True),
    "summarize": ToolSpec("summarize", "propagate", False),  # LLM hop: NOT a sanitizer
    "extract_fields": ToolSpec("extract_fields", "sanitize", True),
    "crm.write": ToolSpec("crm.write", "opaque", True),
}

STORE: dict[str, Segment] = {}


def ingest(seg_id: str, content: str, untrusted: bool, parents: list[str]) -> Segment:
    seg = Segment(
        seg_id=seg_id,
        content_hash=hashlib.sha256(content.encode()).hexdigest(),
        label="untrusted" if untrusted else "trusted",
        parents=parents,
    )
    STORE[seg_id] = seg
    return seg


def taint_closure(seg_id: str) -> set[str]:
    """Transitive closure of taint roots; fail-closed on unknown segments."""
    seen: set[str] = set()
    stack = [seg_id]
    while stack:
        sid = stack.pop()
        if sid in seen:
            continue
        seen.add(sid)
        seg = STORE.get(sid)
        if seg is None:
            raise TaintLaunderingError(f"unknown segment {sid!r}: fail-closed")
        stack.extend(seg.parents)
    return seen


def gate_privileged_call(tool: str, arg_seg_ids: list[str]) -> None:
    spec = REGISTRY[tool]
    if spec.taint_effect == "sanitize" and not spec.deterministic:
        # A non-deterministic 'sanitizer' is a laundering license; reject.
        raise TaintLaunderingError(
            f"tool {tool!r} claims sanitize but is non-deterministic"
        )
    for sid in arg_seg_ids:
        roots = taint_closure(sid)
        for root in roots:
            if STORE[root].label == "untrusted":
                raise TaintLaunderingError(
                    f"privileged call {tool!r} blocked: arg {sid!r} "
                    f"derives from untrusted root {root!r}"
                )


# Reproduction of the observed trace:
s1 = ingest("S1", "ticket body: refund dispute ... [attacker note]", untrusted=True, parents=[])
# summarize is non-deterministic -> must be propagate; output inherits S1
s2 = ingest("S2", "summary variant A", untrusted=False, parents=["S1"])
try:
    gate_privileged_call("crm.write", ["S2"])
except TaintLaunderingError as e:
    print("BLOCKED:", e)  # expected: laundering hop caught via derivation root
