# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-sever-the-taint-lattice-when-a-tool-sandbox-s-provenance-labels-are-forged-by-the-very-retrieved-content-it-is-meant-to-constra.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-sever-the-taint-lattice-when-a-tool-sandbox-s-provenance-labels-are-forged-by-the-very-retrieved-content-it-is-meant-to-constra.warrant.json
# Markdown SHA-256:   c8d6a4663297952bc7c2918fc16deb77909af9466b641dd771efede049d00b46
# Code AST SHA-256:   72d164cc657fed7f95385888f73de18f95fdaa93e7b9126fa6e953f14d3077a6
# Verified Classes:   TaintChannelViolation, Segment, TaintStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintChannelViolation(RuntimeError):
    """Raised when a payload attempts to author or reach its own provenance label,
    or when a derived artifact reduces taint below its inputs."""


@dataclass(frozen=True)
class Segment:
    seg_id: str
    taint: str            # "trusted" | "untrusted"
    parents: tuple = ()   # derivation graph edges


class TaintStore:
    """Side table: labels live here, never in model-visible context."""

    def __init__(self):
        self._segs: dict[str, Segment] = {}

    def admit_from_transport(self, seg_id: str, content: str, fetch_meta: dict) -> Segment:
        # Label is minted from the transport channel, not the payload.
        if "authenticated" not in fetch_meta:
            raise TaintChannelViolation(
                f"segment {seg_id}: no authenticated channel; cannot mint label"
            )
        taint = "trusted" if fetch_meta["authenticated"] else "untrusted"
        # Structural channel separation: the label text must not appear in payload.
        if "[provenance:" in content:
            raise TaintChannelViolation(
                f"segment {seg_id}: payload contains provenance marker; "
                f"label channel is not separated"
            )
        seg = Segment(seg_id=seg_id, taint=taint)
        self._segs[seg_id] = seg
        return seg

    def derive(self, seg_id: str, parent_ids: tuple) -> Segment:
        # Monotone taint: derived artifact inherits max taint of inputs.
        if not parent_ids:
            raise TaintChannelViolation(f"{seg_id}: derivation with no parents")
        taints = {self._segs[p].taint for p in parent_ids}
        taint = "untrusted" if "untrusted" in taints else "trusted"
        seg = Segment(seg_id=seg_id, taint=taint, parents=parent_ids)
        self._segs[seg_id] = seg
        return seg

    def check_sink(self, sink: str, arg_seg_ids: tuple) -> None:
        for sid in arg_seg_ids:
            seg = self._segs.get(sid)
            if seg is None:
                raise TaintChannelViolation(f"sink {sink}: unknown segment {sid}")
            if seg.taint == "untrusted":
                raise TaintChannelViolation(
                    f"sink {sink}: blocked, argument {sid} is untrusted"
                )


def run_sink(store: TaintStore, sink: str, arg_seg_ids: tuple) -> None:
    store.check_sink(sink, arg_seg_ids)
    # ... perform the outbound call ...
