# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-re-embedding-in-taint-aware-retrieval-augmentation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-re-embedding-in-taint-aware-retrieval-augmentation.warrant.json
# Markdown SHA-256:   b6ae4f8c23396c86a8832e8c92a53380224dcea23075f5adc9f179f0d522b3f3
# Code AST SHA-256:   097722ec98e0847b79bb3b30acfb9f301518624abd74aa3c6b887fc4a149757a
# Verified Classes:   TaintViolation, Taint, Chunk, TaintStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class TaintViolation(RuntimeError):
    """Raised when a derived chunk's declared taint is weaker than the join of its ancestors."""
    pass


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

    def join(self, other: "Taint") -> "Taint":
        return Taint(max(int(self), int(other)))


@dataclass
class Chunk:
    cid: str
    label: Taint
    parent_ids: tuple[str, ...] = field(default_factory=tuple)


class TaintStore:
    def __init__(self) -> None:
        self._chunks: dict[str, Chunk] = {}

    def put(self, chunk: Chunk) -> None:
        # Invariant: every write declares its derivation parents (may be empty only for roots).
        if chunk.parent_ids:
            for pid in chunk.parent_ids:
                if pid not in self._chunks:
                    raise TaintViolation(
                        f"chunk {chunk.cid} declares unknown parent {pid}; "
                        f"taint cannot be joined across a missing edge"
                    )
            expected = self._effective_taint_with_cycle_guard(chunk.cid, chunk.parent_ids, set())
            if chunk.label < expected:
                raise TaintViolation(
                    f"taint laundering: chunk {chunk.cid} declared {chunk.label.name} "
                    f"but ancestors require {expected.name}"
                )
        self._chunks[chunk.cid] = chunk

    def _effective_taint_with_cycle_guard(
        self, origin: str, parent_ids: tuple[str, ...], visited: set[str]
    ) -> Taint:
        acc = Taint.TRUSTED
        for pid in parent_ids:
            if pid in visited:
                # A cycle in the derivation graph is itself a taint event.
                return Taint.QUARANTINED
            visited.add(pid)
            node = self._chunks[pid]
            acc = acc.join(node.label)
            if node.parent_ids:
                acc = acc.join(
                    self._effective_taint_with_cycle_guard(origin, node.parent_ids, visited)
                )
        return acc

    def effective_taint(self, cid: str, _depth: int = 0) -> Taint:
        if _depth > 4:
            raise TaintViolation(
                f"derivation depth exceeded for {cid}; possible runaway writer, quarantine"
            )
        node = self._chunks[cid]
        acc = node.label
        for pid in node.parent_ids:
            acc = acc.join(self.effective_taint(pid, _depth + 1))
        return acc

    def admit_to_tool_context(self, cid: str) -> bool:
        return self.effective_taint(cid) == Taint.TRUSTED


def demonstrate_laundering() -> None:
    store = TaintStore()
    store.put(Chunk(cid="chunk_17", label=Taint.UNTRUSTED))
    # A consolidation job that drops taint must be rejected at the write boundary.
    store.put(Chunk(cid="summary_88", label=Taint.TRUSTED, parent_ids=("chunk_17",)))


if __name__ == "__main__":
    demonstrate_laundering()
