# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-in-rag-retrieval-pipelines-under-prompt-injection-containment.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-in-rag-retrieval-pipelines-under-prompt-injection-containment.warrant.json
# Markdown SHA-256:   63ffd6c753a40e097f3d2c4db833abea2b76b9ef2476dabda311a7df1d0a8bc8
# Code AST SHA-256:   52d56ba0e4ec1090e7b85fa6b16d03493c7c54c864606a2e1b9d509f1713c938
# Verified Classes:   TaintLaunderingError, Chunk, TrustedSink
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when a write to a trusted sink would launder tainted content."""


@dataclass(frozen=True)
class Chunk:
    uri: str
    taint: frozenset[str]
    lineage: frozenset[str] = frozenset()


@dataclass
class TrustedSink:
    name: str
    # Lineage-carrying obligation: writes must record derivation roots.
    entries: dict[str, frozenset[str]] = field(default_factory=dict)


def effective_taint(chunk: Chunk) -> frozenset[str]:
    """Reader-side taint: union of the chunk's own label and its recorded lineage."""
    return chunk.taint | chunk.lineage


def write_to_trusted_sink(
    sink: TrustedSink,
    key: str,
    content: str,
    derivation: Iterable[Chunk],
    *,
    allow_lineage_record: bool = True,
) -> Chunk:
    """Write content derived from `derivation` into a trusted sink.

    Invariant: if any derivation input is tainted, the write MUST record
    lineage so the reader re-inherits taint. A write that would drop the
    taint set is a laundering attempt and is rejected.
    """
    tainted_roots: set[str] = set()
    for c in derivation:
        if effective_taint(c):
            tainted_roots.add(c.uri)
            tainted_roots |= set(c.lineage)

    if tainted_roots and not allow_lineage_record:
        # The sink cannot carry lineage; writing here would launder.
        raise TaintLaunderingError(
            f"write to trusted sink {sink.name!r} key={key!r} derived from "
            f"tainted roots {sorted(tainted_roots)} with no lineage channel"
        )

    lineage = frozenset(tainted_roots)
    sink.entries[key] = lineage
    return Chunk(uri=f"{sink.name}://{key}", taint=frozenset(), lineage=lineage)


def guarded_send_email(derivation: Iterable[Chunk], body: str) -> None:
    """Privileged action gated on effective taint across the derivation set."""
    for c in derivation:
        if effective_taint(c):
            raise TaintLaunderingError(
                f"blocked privileged action: derivation includes tainted "
                f"chunk {c.uri} with roots {sorted(effective_taint(c))}"
            )
    # ... perform send ...
    return None
