# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-re-derive-sanitized-output-from-tainted-intermediate-state-rather-than-sanitizing-at-the-point-of-emissio.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-re-derive-sanitized-output-from-tainted-intermediate-state-rather-than-sanitizing-at-the-point-of-emissio.warrant.json
# Markdown SHA-256:   83054bef942c4bd6cef624e7fc9acec3e15573c5688dc831e207aac70ea20551
# Code AST SHA-256:   33283c5bf3d7719b4eea82392cb40e35ede54c4e6569b155f3f84c18808fc339
# Verified Classes:   TaintLaunderingError, Labeled
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when a re-derivation step consumed tainted input but its output
    is about to be emitted as if untainted. This is a soundness violation of
    the emission-point sanitizer, not a data error."""


@dataclass
class Labeled:
    text: str
    labels: frozenset[str] = field(default_factory=frozenset)

    @property
    def tainted(self) -> bool:
        return bool(self.labels)


def rederive(inputs: Iterable[Labeled], output_text: str) -> Labeled:
    """Any model-mediated transformation. Output inherits the JOIN of all
    input labels; provenance of individual spans is destroyed."""
    joined: frozenset[str] = frozenset()
    for item in inputs:
        joined |= item.labels
    return Labeled(text=output_text, labels=joined)


def emit_sanitized(value: Labeled, *, sanitizer_claims_clean: bool) -> str:
    """Emission boundary. The sanitizer may only strip taint if provenance
    is unbroken. If the value was produced by a re-derivation that consumed
    tainted input, the sanitizer's 'clean' verdict is a false negative and
    must not be trusted."""
    if value.tainted and sanitizer_claims_clean:
        raise TaintLaunderingError(
            f"refusing to emit: re-derived value carries labels {sorted(value.labels)} "
            f"but sanitizer reported clean; span provenance is broken by re-derivation"
        )
    if value.tainted:
        raise TaintLaunderingError(
            f"refusing to emit: value remains tainted with {sorted(value.labels)}; "
            f"re-derive from clean sources or route to quarantine sink"
        )
    return value.text


def pipeline_step(docs: list[Labeled], summary_text: str) -> str:
    derived = rederive(docs, summary_text)
    # A span-matching sanitizer would find no overlapping tainted spans in the
    # summary and claim clean. We must not honor that claim.
    return emit_sanitized(derived, sanitizer_claims_clean=True)


if __name__ == "__main__":
    untrusted = Labeled("retry budget is 3", frozenset({"untrusted:retrieval"}))
    # Summarizer paraphrases; span provenance is destroyed but value survives.
    try:
        pipeline_step([untrusted], "The configured retry budget is three.")
    except TaintLaunderingError as exc:
        print(f"blocked: {exc}")
