# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-context-window-before-a-tool-boundary-and-why-static-prompt-injection-defenses-miss-the-transitive-case.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-context-window-before-a-tool-boundary-and-why-static-prompt-injection-defenses-miss-the-transitive-case.warrant.json
# Markdown SHA-256:   67febc556c1a05fb8230ee59cf3517c9765fbaa43105eb2680c6285f6308df4a
# Code AST SHA-256:   c392ab1bb53d8716dd4bc964eb8bc7bcc1eb73597bee24faf8f41363d7e7ecad
# Verified Classes:   TaintClosureViolation, ProvenanceAmnesia, Span, ProvenanceGraph
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class TaintClosureViolation(RuntimeError):
    """Raised when an egress argument carries untrusted provenance
    without an authorized declassification edge."""
    pass


class ProvenanceAmnesia(TaintClosureViolation):
    """Raised when a resumed span has no recorded derivation edges,
    making its taint closure unknowable rather than empty."""
    pass


@dataclass(frozen=True)
class Span:
    span_id: str
    label: FrozenSet[str]           # e.g. frozenset({"untrusted:doc_7"})
    parents: FrozenSet[str] = frozenset()   # derivation edges, NOT a reset


class ProvenanceGraph:
    def __init__(self) -> None:
        self._spans: Dict[str, Span] = {}
        self._declassified: Dict[str, str] = {}   # span_id -> attesting authority

    def register(self, span: Span) -> None:
        # Invariant: label must be a join over parents, never a reset.
        inherited: set = set()
        for p in span.parents:
            if p not in self._spans:
                raise ProvenanceAmnesia(
                    f"span {span.span_id} references unknown parent {p}; "
                    f"derivation edges lost (resume without provenance?)"
                )
            inherited |= self._spans[p].label
        if not inherited.issubset(set(span.label)):
            raise TaintClosureViolation(
                f"span {span.span_id} label {span.label} does not join "
                f"parent labels {inherited}; silent declassification via regeneration"
            )
        self._spans[span.span_id] = span

    def declassify(self, span_id: str, authority: str) -> None:
        if not authority:
            raise TaintClosureViolation(
                f"declassification of {span_id} requires an attesting authority"
            )
        self._declassified[span_id] = authority

    def closure(self, span_id: str) -> FrozenSet[str]:
        seen: set = set()
        stack: List[str] = [span_id]
        while stack:
            sid = stack.pop()
            if sid in seen:
                continue
            seen.add(sid)
            if sid not in self._spans:
                raise ProvenanceAmnesia(
                    f"closure walk hit missing span {sid}; provenance DAG incomplete"
                )
            stack.extend(self._spans[sid].parents)
        return frozenset(seen)

    def untrusted_closure(self, span_id: str) -> FrozenSet[str]:
        """Transitive untrusted provenance, minus explicitly declassified spans."""
        tainted: set = set()
        for sid in self.closure(span_id):
            if sid in self._declassified:
                continue
            for lbl in self._spans[sid].label:
                if lbl.startswith("untrusted:"):
                    tainted.add(lbl)
        return frozenset(tainted)

    def gate_egress(self, arg_span_id: str) -> None:
        """Hard stop on tool-boundary egress. Reading tainted spans is fine;
        only this gate blocks."""
        tainted = self.untrusted_closure(arg_span_id)
        if tainted:
            raise TaintClosureViolation(
                f"egress blocked: argument {arg_span_id} has untrusted closure "
                f"{sorted(tainted)}; no authorized declassification recorded"
            )


# --- trigger trace ---
g = ProvenanceGraph()
g.register(Span("S1", frozenset({"untrusted:doc_7"})))                    # retrieval
# The buggy propagator would register S2 with label {"model_generated"} and
# parents={S1}; the join check rejects it. Correct version joins:
g.register(Span("S2", frozenset({"untrusted:doc_7", "model_generated"}),
                parents=frozenset({"S1"})))                                # paraphrase
g.register(Span("A1", frozenset({"untrusted:doc_7", "model_generated"}),
                parents=frozenset({"S2"})))                                # tool arg

try:
    g.gate_egress("A1")   # raises: closure reaches doc_7, no declassification
except TaintClosureViolation as e:
    print("QUARANTINE:", e)
    # instance must re-plan from a trusted source or escalate for declassification
