# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-re-admit-poisoned-memory-when-a-taint-label-survives-retrieval-but-not-re-ranking.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-re-admit-poisoned-memory-when-a-taint-label-survives-retrieval-but-not-re-ranking.warrant.json
# Markdown SHA-256:   defae7352ed0beb92e299b8285fcba590a05f5741b5af96f6e41f3394bc474a7
# Code AST SHA-256:   385516aa43df97353b0e349290c70adbd8f71d40393400445ca247a688a180f5
# Verified Classes:   TaintLaunderingError, Chunk
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable, Literal

Taint = Literal["TRUSTED", "UNTRUSTED_EXTERNAL"]

class TaintLaunderingError(RuntimeError):
    """Raised when content reaches assembly without a resolvable provenance label."""
    pass

@dataclass(frozen=True)
class Chunk:
    id: str
    text: str
    taint: Taint
    lineage: tuple[str, ...] = ()  # ancestor chunk ids; empty for origin chunks

def join_taint(inputs: Iterable[Chunk]) -> Taint:
    # Join is max over the lattice TRUSTED < UNTRUSTED_EXTERNAL.
    return "UNTRUSTED_EXTERNAL" if any(c.taint == "UNTRUSTED_EXTERNAL" for c in inputs) else "TRUSTED"

def assemble_context(retrieved: Iterable[object]) -> list[Chunk]:
    """Assembly boundary. Rejects any object lacking a taint label or lineage."""
    out: list[Chunk] = []
    for item in retrieved:
        if not isinstance(item, Chunk):
            # A bare str, a dict, or a re-ranker tuple that dropped taint.
            raise TaintLaunderingError(
                f"content object {type(item).__name__!r} reached assembly without "
                f"a Chunk provenance record; taint cannot be verified"
            )
        if item.taint not in ("TRUSTED", "UNTRUSTED_EXTERNAL"):
            raise TaintLaunderingError(f"chunk {item.id!r} has invalid taint {item.taint!r}")
        out.append(item)
    return out

def summarize(chunks: list[Chunk], summary_text: str) -> Chunk:
    """Generative transform: must re-bind output to input lineage and joined taint."""
    if not chunks:
        raise TaintLaunderingError("summarize called with no source chunks; lineage undefined")
    return Chunk(
        id=f"summary:{chunks[0].id}",
        text=summary_text,
        taint=join_taint(chunks),
        lineage=tuple(c.id for c in chunks),
    )

# Example: a re-ranker that returns bare strings is caught here, not downstream.
try:
    assemble_context(["poisoned snippet with no provenance"])
except TaintLaunderingError as e:
    # Fail closed: quarantine the batch, re-run recall with typed output.
    print(f"assembly rejected: {e}")
