# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-prompt-injection-taint-at-the-tool-output-provenance-join.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-prompt-injection-taint-at-the-tool-output-provenance-join.warrant.json
# Markdown SHA-256:   57d006f8a7c6bc16a17ec4c0b1a7aa5470c12e98df1e3f2eca9461579168da62
# Code AST SHA-256:   767106a0b1078031fe370cbfd4db84045817211e3ecf113c5c573aad3622f3a6
# Verified Classes:   TaintLossError, Taint, Node, ProvenanceGraph
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Optional


class TaintLossError(RuntimeError):
    """Raised when a provenance join would assign a child a label less
    tainted than the join of its parents, or when a TRUSTED relabel is
    attempted without a registered sanitizer certificate."""


class Taint(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1  # top of the lattice; union is max


@dataclass
class Node:
    node_id: str
    label: Taint
    parents: tuple[str, ...] = ()
    sanitizer_cert: Optional[str] = None  # required iff label == TRUSTED and parents non-empty


@dataclass
class ProvenanceGraph:
    nodes: dict[str, Node] = field(default_factory=dict)
    certified_sanitizers: set[str] = field(default_factory=set)

    def add_source(self, node_id: str, label: Taint) -> Node:
        n = Node(node_id=node_id, label=label)
        self.nodes[node_id] = n
        return n

    def join(self, child_id: str, parents: list[str],
             claimed_label: Taint,
             sanitizer_cert: Optional[str] = None) -> Node:
        if not parents:
            raise TaintLossError(f"{child_id}: join requires at least one parent")
        for p in parents:
            if p not in self.nodes:
                raise TaintLossError(f"{child_id}: unknown parent {p}")

        # True lattice join: union of taint, never overwrite.
        joined = Taint(max(self.nodes[p].label for p in parents))

        # A child may only be LESS tainted than the join if a certified
        # total sanitizer is presented; otherwise monotonicity is violated.
        if claimed_label < joined:
            if sanitizer_cert is None:
                raise TaintLossError(
                    f"{child_id}: claimed {claimed_label.name} but join of "
                    f"parents is {joined.name}; no sanitizer certificate"
                )
            if sanitizer_cert not in self.certified_sanitizers:
                raise TaintLossError(
                    f"{child_id}: sanitizer cert {sanitizer_cert!r} is not "
                    f"registered; cannot relabel below {joined.name}"
                )

        n = Node(node_id=child_id, label=claimed_label,
                 parents=tuple(parents), sanitizer_cert=sanitizer_cert)
        self.nodes[child_id] = n
        return n

    def egress_allowed(self, node_id: str) -> bool:
        """Label-monotone traversal is only sound if join monotonicity holds,
        which join() enforces at construction time."""
        seen: set[str] = set()
        stack = [node_id]
        while stack:
            cur = stack.pop()
            if cur in seen:
                continue
            seen.add(cur)
            n = self.nodes[cur]
            if n.label == Taint.UNTRUSTED:
                return False
            # Only safe to stop descending if no ancestor can be UNTRUSTED,
            # guaranteed by the join() invariant.
            stack.extend(n.parents)
        return True


def demo():
    g = ProvenanceGraph()
    g.add_source("n1", Taint.UNTRUSTED)  # web fetch with hidden instruction

    # Naive field-level relabel: the exact bug. No cert -> must raise.
    try:
        g.join("n2", ["n1"], claimed_label=Taint.TRUSTED)
    except TaintLossError as e:
        print(f"blocked (correct): {e}")

    # Correct behavior: union join keeps taint, egress is refused.
    g.join("n2", ["n1"], claimed_label=Taint.UNTRUSTED)
    assert not g.egress_allowed("n2")

    # A genuinely total sanitizer, registered, may relabel.
    g.certified_sanitizers.add("redact-allowlist-v3")
    g.join("n3", ["n1"], claimed_label=Taint.TRUSTED,
           sanitizer_cert="redact-allowlist-v3")
    assert g.egress_allowed("n3")

    # Unregistered cert is still a TaintLossError.
    try:
        g.join("n4", ["n1"], claimed_label=Taint.TRUSTED,
               sanitizer_cert="made-up")
    except TaintLossError as e:
        print(f"blocked (correct): {e}")


if __name__ == "__main__":
    demo()
