# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-sanitize-the-sanitization-laundering-failure-at-the-model-ingress-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-sanitize-the-sanitization-laundering-failure-at-the-model-ingress-boundary.warrant.json
# Markdown SHA-256:   6aecf60350b9c143a6b04bc9fe8c17bd1d0a705f958550d0599c7f5094b14560
# Code AST SHA-256:   17a2b13f6160e6ac3a0610481cee72fe06a2fe03c9ea99b709268796f8535bfa
# Verified Classes:   TaintLaunderingError, SanitizedSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a sanitizer would transform a span such that its taint
    label can no longer be provably reattached. Refusing is mandatory:
    emitting unlabeled content is the failure we exist to prevent."""


class SanitizedSpan:
    __slots__ = ("text", "taint", "chunk_id", "structural_hash")

    def __init__(self, text: str, taint: str, chunk_id: str, structural_hash: str):
        self.text = text
        self.taint = taint
        self.chunk_id = chunk_id
        self.structural_hash = structural_hash


def sanitize_ingress(
    raw_text: str,
    taint: str,
    chunk_id: str,
    *,
    is_cryptographic: bool = False,
    transform,
) -> SanitizedSpan:
    # Cryptographic artifacts must never be transformed; only verified or rejected.
    if is_cryptographic:
        if transform is not None:
            raise TaintLaunderingError(
                f"chunk {chunk_id}: refusing to sanitize cryptographic artifact; "
                "transformation invalidates the warrant and severs its taint label"
            )
        return SanitizedSpan(raw_text, taint, chunk_id, structural_hash=chunk_id)

    if transform is None:
        return SanitizedSpan(raw_text, taint, chunk_id, structural_hash=chunk_id)

    new_text = transform(raw_text)

    # Structure-changing transforms invalidate offset-based label reattachment.
    structure_preserved = len(new_text) == len(raw_text)
    if not structure_preserved:
        # We require chunk-ID anchoring to be available; otherwise refuse.
        if not chunk_id:
            raise TaintLaunderingError(
                "length-changing sanitization without chunk-ID anchoring: "
                "taint label cannot be provably reattached; refusing to emit "
                "unlabeled content into the context window"
            )

    # Invariant: sanitization never downgrades trust class.
    if taint is None or taint == "":
        raise TaintLaunderingError(
            f"chunk {chunk_id}: sanitizer produced output with no trust class; "
            "unlabeled content is treated as first-party downstream"
        )

    return SanitizedSpan(new_text, taint, chunk_id, structural_hash=chunk_id)


def assemble_context(spans: list[SanitizedSpan]) -> str:
    out = []
    for s in spans:
        if s.taint is None:
            # Defensive: should be unreachable given sanitize_ingress, but the
            # assembler must fail closed regardless of upstream correctness.
            raise TaintLaunderingError(
                f"chunk {s.chunk_id}: unlabeled span reached assembler; "
                "fail closed rather than emit laundered content"
            )
        out.append(f"[{s.taint}] {s.text}")
    return "\n".join(out)
