# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-provenance-tainted-context-rather-than-merely-down-weight-it-the-taint-laundering-collapse-at-the-su.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-provenance-tainted-context-rather-than-merely-down-weight-it-the-taint-laundering-collapse-at-the-su.warrant.json
# Markdown SHA-256:   64aea42c95e36952912bc9381d12928fa1cbb409a6eb272e62d82a39f6043e43
# Code AST SHA-256:   112462babee7e6f5f2477ebfb03b44861844cc1e82ab3e1cf8a93faf49b9f4c9
# Verified Classes:   TaintLaunderingError, GeneratorKind, Segment, DerivationDAG
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class TaintLaunderingError(RuntimeError):
    """Raised when a tainted span reaches an irreversible sink through an
    erasing generator whose output was not taint-propagated."""


class GeneratorKind(Enum):
    PROPAGATING = "propagating"   # output inherits union of input taint
    ERASING = "erasing"           # output labeled by own principal (default)


@dataclass
class Segment:
    seg_id: str
    taint: frozenset[str]
    produced_by: str | None = None
    inputs: tuple[str, ...] = ()


@dataclass
class DerivationDAG:
    segments: dict[str, Segment] = field(default_factory=dict)

    def add(self, seg: Segment) -> None:
        self.segments[seg.seg_id] = seg

    def closure(self, seg_id: str) -> frozenset[str]:
        """Taint closure over the full derivation DAG, not direct provenance."""
        seen: set[str] = set()
        taint: set[str] = set()

        def walk(sid: str) -> None:
            if sid in seen:
                return
            seen.add(sid)
            seg = self.segments[sid]
            taint.update(seg.taint)
            for parent in seg.inputs:
                walk(parent)

        walk(seg_id)
        return frozenset(taint)


IRREVERSIBLE_SINKS = {"write_file", "send_message", "rotate_credential"}


def enforce_sink(
    dag: DerivationDAG,
    sink: str,
    argument_seg_id: str,
    erasing_generators_used: set[str],
) -> None:
    if sink not in IRREVERSIBLE_SINKS:
        return  # reversible sink: attenuation is a valid control

    taint = dag.closure(argument_seg_id)
    if not taint:
        return

    # Taint reached the sink. Was any erasing generator on the path?
    # If so, attenuation was decorative; the write must be quarantined.
    if erasing_generators_used:
        raise TaintLaunderingError(
            f"sink {sink!r} argument {argument_seg_id!r} has taint closure "
            f"{sorted(taint)} laundered through erasing generator(s) "
            f"{sorted(erasing_generators_used)}; quarantine required, "
            f"attenuation is unsound across an erasing step"
        )
    raise TaintLaunderingError(
        f"sink {sink!r} argument {argument_seg_id!r} carries taint "
        f"{sorted(taint)}; irreversible sink requires quarantine or "
        f"explicit declassification"
    )
