# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-label-laundering-through-re-serialization-in-prompt-injection-taint-tracking.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-label-laundering-through-re-serialization-in-prompt-injection-taint-tracking.warrant.json
# Markdown SHA-256:   6f99153978200867391f6404f32019de6729ef87b494a9cccd2800de4aaa9e97
# Code AST SHA-256:   3e7a4bc49553f24e35977d3e1d2b7dd1603c3ff98570be6712139b06692ce2a7
# Verified Classes:   ProvenanceLaunderingError, Node, ProvenanceGraph
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Dict, List, Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a payload reaches a privileged sink without an unbroken
    provenance edge chain from a trusted source, or when a transform
    reconstructs a payload without re-attaching provenance edges."""
    pass


@dataclass(frozen=True)
class Node:
    node_id: str
    label: FrozenSet[str]          # e.g. frozenset({"untrusted:web"})
    parents: FrozenSet[str] = frozenset()


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

    def add_source(self, node_id: str, label: str) -> Node:
        n = Node(node_id, frozenset({label}))
        self._nodes[node_id] = n
        return n

    def derive(self, new_id: str, parent_ids: List[str], extra_label: Optional[str] = None) -> Node:
        # A derived node inherits the JOIN (union) of all parent labels.
        # Re-serialization MUST call this; skipping it is the laundering path.
        parents = frozenset(parent_ids)
        labels: set = set()
        for pid in parent_ids:
            if pid not in self._nodes:
                raise ProvenanceLaunderingError(
                    f"derive({new_id}) references unknown parent {pid}; "
                    f"missing edge means provenance is unreconstructable"
                )
            labels |= self._nodes[pid].label
        if extra_label:
            labels.add(extra_label)
        n = Node(new_id, frozenset(labels), parents)
        self._nodes[new_id] = n
        return n

    def ancestry_labels(self, node_id: str) -> FrozenSet[str]:
        # Sink admission checks the FULL ancestry, not the immediate label.
        seen: set = set()
        stack = [node_id]
        labels: set = set()
        while stack:
            cur = stack.pop()
            if cur in seen:
                continue
            seen.add(cur)
            if cur not in self._nodes:
                raise ProvenanceLaunderingError(
                    f"ancestry check hit missing node {cur}; "
                    f"treat as untrusted:unknown, refuse privileged sink"
                )
            n = self._nodes[cur]
            labels |= n.label
            stack.extend(n.parents)
        return frozenset(labels)


def admit_to_privileged_sink(graph: ProvenanceGraph, node_id: str, sink: str) -> None:
    labels = graph.ancestry_labels(node_id)
    if any(lbl.startswith("untrusted") for lbl in labels):
        raise ProvenanceLaunderingError(
            f"privileged sink {sink!r} rejected node {node_id!r}: "
            f"tainted ancestry {sorted(labels)}"
        )


# --- Failure trace reproduction ---
def reproduce_laundering() -> None:
    g = ProvenanceGraph()
    g.add_source("retrieval_1", "untrusted:web")
    # Model paraphrases the injected chunk. If the runtime forgets to record
    # the context-window taint-set, it would call derive with extra_label=None
    # and the node would look trusted. Correct behavior: inherit taint.
    g.derive("model_notes_1", ["retrieval_1"], extra_label="derived:model")
    admit_to_privileged_sink(g, "model_notes_1", "transfer_funds")  # raises


def detect_missing_edge() -> None:
    g = ProvenanceGraph()
    g.add_source("retrieval_1", "untrusted:web")
    # A re-serialization that drops the parent edge: derive() must reject it.
    try:
        g.derive("laundered_1", ["retrieval_1", "dropped_parent_9"])
    except ProvenanceLaunderingError:
        return
    raise ProvenanceLaunderingError("missing parent edge was not detected")


if __name__ == "__main__":
    detect_missing_edge()
    reproduce_laundering()
