# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-label-laundering-across-a-rag-retrieval-boundary-that-re-materializes-tainted-content-as-a-fresh-document.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-label-laundering-across-a-rag-retrieval-boundary-that-re-materializes-tainted-content-as-a-fresh-document.warrant.json
# Markdown SHA-256:   2137c6946442cf4ca815ac259fc2b8527e8f31aeb8713b5689e76afb9d37373f
# Code AST SHA-256:   fda5d191fb33e3be7366ceba043ab11bb418901f4b79eaa4555bbb26af39af2e
# Verified Classes:   TaintLaunderingError, Artifact
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a content artifact consumed by the model has a clean stored
    label but a tainted ancestor in its write lineage — i.e. a label was
    dropped at a serialization boundary and the content re-entered as trusted."""
    pass


class Artifact:
    def __init__(self, artifact_id, taint, parents=None):
        self.artifact_id = artifact_id
        self.taint = frozenset(taint)          # empty frozenset == "clean"
        self.parents = parents or []


def join_taint(parents):
    """Derived artifact taint is the union of parent taints. Never the empty
    set unless every parent is clean. 'unknown' is an absorbing element."""
    joined = set()
    for p in parents:
        joined |= p.taint
    return frozenset(joined)


def verify_retrieval_label(artifact, lineage):
    """Called when a retrieved chunk is about to enter the context window.
    Reconciles the stored label against the lineage-derived label."""
    expected = join_taint(lineage.parents_of(artifact.artifact_id))
    if expected and not artifact.taint:
        raise TaintLaunderingError(
            f"artifact {artifact.artifact_id!r} retrieved as clean but lineage "
            f"shows tainted ancestors {sorted(expected)}; a serialization "
            f"boundary dropped the label. Refusing to inject as trusted context."
        )
    if expected - artifact.taint:
        raise TaintLaunderingError(
            f"artifact {artifact.artifact_id!r} label {sorted(artifact.taint)} "
            f"is missing inherited taint {sorted(expected - artifact.taint)}; "
            f"derivation did not union parent labels."
        )
    return artifact.taint


def assemble_context(chunks, lineage):
    """Build the model context, enforcing the retrieval-boundary invariant."""
    rendered = []
    for chunk in chunks:
        taint = verify_retrieval_label(chunk, lineage)
        if taint:
            rendered.append({"role": "untrusted_context",
                             "provenance": sorted(taint),
                             "body": chunk.body})
        else:
            rendered.append({"role": "context", "body": chunk.body})
    return rendered
