# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-tool-output-is-re-summarized-across-a-context-compaction-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-tool-output-is-re-summarized-across-a-context-compaction-boundary.warrant.json
# Markdown SHA-256:   3758ee36177de706c1fefcaa951e59c3b0c2aa370bf83a8e131557a93e8d35dc
# Code AST SHA-256:   642573c6665770ccf5ed8bafd7b3f20a81ed9ab268b2ea44586849fd50fe9b3a
# Verified Classes:   TaintLaunderingError, Label, ProvenanceNode, ProvenanceGraph
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a value-regenerating transformation drops provenance."""


@dataclass(frozen=True)
class Label:
    untrusted_sources: frozenset[str] = frozenset()

    @property
    def is_trusted(self) -> bool:
        return not self.untrusted_sources

    def join(self, other: "Label") -> "Label":
        return Label(self.untrusted_sources | other.untrusted_sources)


TRUSTED = Label()


@dataclass
class ProvenanceNode:
    node_id: str
    value: str
    label: Label
    parents: tuple[str, ...] = field(default_factory=tuple)


class ProvenanceGraph:
    def __init__(self) -> None:
        self._nodes: dict[str, ProvenanceNode] = {}

    def add_root(self, node_id: str, value: str, label: Label) -> None:
        self._nodes[node_id] = ProvenanceNode(node_id, value, label)

    def add_derived(
        self, node_id: str, value: str, parent_ids: tuple[str, ...]
    ) -> ProvenanceNode:
        if not parent_ids:
            raise TaintLaunderingError(
                f"derived node {node_id!r} has no parents; cannot establish label"
            )
        missing = [p for p in parent_ids if p not in self._nodes]
        if missing:
            raise TaintLaunderingError(
                f"derived node {node_id!r} references unknown parents {missing}"
            )
        joined = TRUSTED
        for pid in parent_ids:
            joined = joined.join(self._nodes[pid].label)
        node = ProvenanceNode(node_id, value, joined, parent_ids)
        self._nodes[node_id] = node
        return node

    def walk_roots(self, node_id: str, seen: Optional[set[str]] = None) -> Label:
        seen = seen or set()
        if node_id in seen:
            raise TaintLaunderingError(f"provenance cycle detected at {node_id!r}")
        seen.add(node_id)
        node = self._nodes.get(node_id)
        if node is None:
            # Fail-closed: unknown node is untrusted.
            return Label(frozenset({f"unknown:{node_id}"}))
        if not node.parents:
            return node.label
        joined = node.label
        for pid in node.parents:
            joined = joined.join(self.walk_roots(pid, seen))
        return joined


def admit_to_sink(graph: ProvenanceGraph, node_id: str, sink: str) -> None:
    """Egress gate. Refuses any value whose provenance reaches an untrusted root
    unless an explicit declassification record exists for (source, sink)."""
    effective = graph.walk_roots(node_id)
    if not effective.is_trusted:
        raise TaintLaunderingError(
            f"sink {sink!r} refused node {node_id!r}: "
            f"untrusted provenance {sorted(effective.untrusted_sources)}"
        )
