# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-poisoned-document-propagation-across-a-taint-aware-retrieval-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-poisoned-document-propagation-across-a-taint-aware-retrieval-boundary.warrant.json
# Markdown SHA-256:   6fa18dff3ec0c4314cc9e7952ba2557ed105f5fa59a4f64485cb438496b11561
# Code AST SHA-256:   c98c34a59ab460f69c28237713f5f8fa5508c9e9d1c4bbe4f5688f091495b557
# Verified Classes:   TaintLaunderingError, Artifact
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a derived artifact reaches an action gate with untrusted ancestry
    but a clean taint label, or when a transform attempts to drop taint."""


@dataclass(frozen=True)
class Artifact:
    payload: str
    tainted: bool
    ancestry: FrozenSet[str] = field(default_factory=frozenset)


def summarize(parent: Artifact, summarizer) -> Artifact:
    # The transform MUST propagate taint and ancestry. Returning a bare str
    # here is the laundering point observed in the field.
    text = summarizer(parent.payload)
    if not parent.tainted and parent.ancestry:
        # ancestry without taint is an inconsistent state; refuse.
        raise TaintLaunderingError(
            f"artifact has ancestry {parent.ancestry} but taint=false"
        )
    return Artifact(
        payload=text,
        tainted=parent.tainted,          # monotone: OR over parents
        ancestry=parent.ancestry | {parent.payload[:16]},
    )


def gate_action(node: Artifact, declassification_log: dict) -> None:
    if node.tainted and node.payload[:16] not in declassification_log:
        raise TaintLaunderingError(
            "tainted artifact reached action gate without a declassification "
            f"record; ancestry={sorted(node.ancestry)}"
        )
    # only reached if clean or explicitly declassified


def ingest_external(doc_id: str, text: str) -> Artifact:
    return Artifact(payload=text, tainted=True, ancestry=frozenset({doc_id}))
