# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-provenance-label-rather-than-launder-it-taint-collapse-at-the-retrieval-to-memory-write-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-provenance-label-rather-than-launder-it-taint-collapse-at-the-retrieval-to-memory-write-boundary.warrant.json
# Markdown SHA-256:   1428978ec2d83570ce9bb5e4ec5fb0af62b7e5470c55fdf144d4f10b5ddcdd10
# Code AST SHA-256:   8fb5e1fd42d7a40571b6a5d7adb96c521519b9bee9475d6535a4dee628f372cf
# Verified Classes:   Taint, TaintCollapseError, Span, Artifact
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Iterable


class Taint(IntEnum):
    TRUSTED = 0
    TAINTED = 1


class TaintCollapseError(RuntimeError):
    """Raised when a derived artifact's label is less tainted than the join of its inputs
    without an audited declassification event (i.e., laundering)."""


@dataclass(frozen=True)
class Span:
    label: Taint
    origin: str


@dataclass
class Artifact:
    label: Taint
    inputs: list[Span] = field(default_factory=list)
    declassified: bool = False
    declassify_authority: str | None = None
    persistent: bool = False


def join(inputs: Iterable[Span]) -> Taint:
    return Taint(max((s.label for s in inputs), default=Taint.TRUSTED))


def admit_write(artifact: Artifact) -> None:
    """Gate every persistent memory write. Enforces the max-taint join invariant."""
    joined = join(artifact.inputs)

    # Collapse detection: output less tainted than inputs, no audited declassify.
    if artifact.label < joined and not artifact.declassified:
        raise TaintCollapseError(
            f"laundering: artifact label={artifact.label.name} < "
            f"join(inputs)={joined.name} with no declassify event; "
            f"origins={[s.origin for s in artifact.inputs]}"
        )

    # Declassification must name an authority that is not the producer itself.
    if artifact.declassified and not artifact.declassify_authority:
        raise TaintCollapseError(
            "declassify event missing named authority; implicit declassify rejected"
        )

    # Persistent artifact carrying taint must be quarantined, not executed.
    if artifact.persistent and artifact.label >= Taint.TAINTED:
        artifact.persistent = True  # written, but flagged non-executable downstream
        return

    return


def synthesize(summarizer_is_trusted: bool, spans: list[Span]) -> Artifact:
    # Buggy path: producer label wins. This is the collapse.
    producer_label = Taint.TRUSTED if summarizer_is_trusted else Taint.TAINTED
    artifact = Artifact(label=producer_label, inputs=spans, persistent=True)
    admit_write(artifact)  # raises if inputs outrank producer label
    return artifact


if __name__ == "__main__":
    clean = [Span(Taint.TRUSTED, f"policy_{i}") for i in range(4)]
    injected = Span(Taint.TAINTED, "external_doc#refund_note")
    synthesize(summarizer_is_trusted=True, spans=clean + [injected])
