# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-chunk-splitting-in-a-retrieval-corpus-when-a-poisoned-document-s-benign-prefix-passes-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-chunk-splitting-in-a-retrieval-corpus-when-a-poisoned-document-s-benign-prefix-passes-provenance.warrant.json
# Markdown SHA-256:   6ddf3aea49357ebc299399cce651a8c5edf90111651c44fb7d0f0a0cbcbbb7df
# Code AST SHA-256:   91769e7134ac4870bfc5b2092a6a7dee319660cbcdb7576d3d024abed1999430
# Verified Classes:   TaintLaunderingError, Chunk
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TaintLaunderingError(RuntimeError):
    """Raised when a chunk's provenance cannot be resolved to an explicit taint label."""


@dataclass
class Chunk:
    chunk_id: str
    source_doc: str
    taint: bool | None  # None means unlabeled, NOT clean
    token_span: tuple[int, int]


def resolve_taint(chunk: Chunk, quarantined_docs: set[str], tainted_spans: list[tuple[int, int]]) -> bool:
    if chunk.taint is not None:
        return chunk.taint
    if chunk.source_doc in quarantined_docs:
        # Unlabeled chunk from a quarantined doc: fail closed.
        return True
    for start, end in tainted_spans:
        if chunk.token_span[0] < end and start < chunk.token_span[1]:
            return True  # overlap with a tainted span inherits taint
    raise TaintLaunderingError(
        f"chunk {chunk.chunk_id} from {chunk.source_doc} has no resolvable taint label; "
        "refusing to admit unlabeled bytes into context"
    )


def assemble_context(chunks: list[Chunk], quarantined_docs: set[str], tainted_spans: list[tuple[int, int]]) -> str:
    admitted = []
    for c in chunks:
        if resolve_taint(c, quarantined_docs, tainted_spans):
            continue
        admitted.append(c)
    if not admitted:
        raise TaintLaunderingError("all retrieved chunks rejected by taint gate; task cannot proceed safely")
    return "\n".join(c.chunk_id for c in admitted)
