# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-propagates-a-poisoned-document-s-taint-label-across-a-retrieval-boundary-it-did-not-own.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-propagates-a-poisoned-document-s-taint-label-across-a-retrieval-boundary-it-did-not-own.warrant.json
# Markdown SHA-256:   9cc7a390f0223fd564568ada8891b5117151c8b314b214881b7706d8c5b123c1
# Code AST SHA-256:   5f737018180e3bf387f26caad0529f053475685b1efb1849e83ef7861a6d54ea
# Verified Classes:   Severity, TaintLaunderingError, Artifact, ProvenanceStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class Severity(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1
    QUARANTINED = 2


class TaintLaunderingError(RuntimeError):
    """Raised when a derived artifact's asserted label understates its provenance."""


@dataclass
class Artifact:
    artifact_id: str
    text: str
    asserted_label: Severity
    source_ids: tuple[str, ...] = field(default_factory=tuple)


class ProvenanceStore:
    def __init__(self) -> None:
        self._artifacts: dict[str, Artifact] = {}

    def register(self, art: Artifact) -> None:
        self._artifacts[art.artifact_id] = art

    def closure_severity(self, artifact_id: str, _seen: frozenset[str] = frozenset()) -> Severity:
        if artifact_id in _seen:
            raise TaintLaunderingError(f"cycle in provenance graph at {artifact_id}")
        art = self._artifacts.get(artifact_id)
        if art is None:
            raise TaintLaunderingError(
                f"provenance edge points at unknown artifact {artifact_id}; closure cannot be walked"
            )
        if not art.source_ids:
            return art.asserted_label
        worst = art.asserted_label
        for sid in art.source_ids:
            worst = max(worst, self.closure_severity(sid, _seen | {artifact_id}))
        return worst


def admit_derived_note(
    store: ProvenanceStore,
    note: Artifact,
    max_allowed: Severity = Severity.UNTRUSTED,
) -> None:
    """Gate a distillation write. Rejects if asserted label understates provenance closure."""
    if not note.source_ids:
        raise TaintLaunderingError(
            f"note {note.artifact_id} carries no provenance edges; cannot prove it is untainted"
        )
    recomputed = store.closure_severity(note.artifact_id)
    if recomputed > note.asserted_label:
        raise TaintLaunderingError(
            f"note {note.artifact_id} asserts {note.asserted_label.name} "
            f"but provenance closure is {recomputed.name}; refusing write"
        )
    if recomputed > max_allowed:
        raise TaintLaunderingError(
            f"note {note.artifact_id} closure {recomputed.name} exceeds "
            f"admission ceiling {max_allowed.name}"
        )
    store.register(note)


# --- reproduction of the observed laundering trace ---
store = ProvenanceStore()
store.register(Artifact("D_adv", "...", Severity.QUARANTINED, source_ids=()))

# R1 distills D_adv and (buggily) asserts TRUSTED, keeping the leaf edge:
laundered = Artifact("note_R1", "summary of D_adv", Severity.TRUSTED, source_ids=("D_adv",))
store.register(laundered)

try:
    admit_derived_note(store, laundered)
except TaintLaunderingError as e:
    print(f"BLOCKED at first hop: {e}")

# R2 distills the note but drops the leaf edge -> closure cannot be walked:
truncated = Artifact("note_R2", "summary of note_R1", Severity.TRUSTED, source_ids=())
try:
    admit_derived_note(store, truncated)
except TaintLaunderingError as e:
    print(f"BLOCKED at truncation: {e}")
