# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-an-information-flow-taint-label-that-survives-a-tool-call-but-whose-provenance-is-laundered-by-a-sum.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-an-information-flow-taint-label-that-survives-a-tool-call-but-whose-provenance-is-laundered-by-a-sum.warrant.json
# Markdown SHA-256:   573ced5cf02a3e8b6c3d410066cc271870437996b1aa889b58f01a833b1b569d
# Code AST SHA-256:   5a597a345a86d067e4bf882f18f5637d0049d4882ed834e81803a465b6b88a4a
# Verified Classes:   ProvenanceLaunderingError, Segment
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a generative rewrite emits a segment whose source set is
    empty despite having tainted ancestors, i.e. a map was applied where a
    join was required."""
    pass


@dataclass(frozen=True)
class Segment:
    content: str
    sources: FrozenSet[str] = field(default_factory=frozenset)
    quarantined: bool = False

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


def summarize_as_join(inputs: list[Segment], output_text: str,
                      generative: bool) -> Segment:
    """Model a summarizer as a join, not a map.

    A generative rewrite that can synthesize imperatives must inherit the
    union of its inputs' source sets. Only an extractive, non-amplifying
    rewrite may legally emit an empty source set.
    """
    joined = frozenset().union(*(s.sources for s in inputs))
    if generative and joined and not output_text:
        # degenerate: generative step over tainted input produced nothing
        raise ProvenanceLaunderingError(
            "generative summarizer over tainted inputs emitted empty output"
        )
    if not generative:
        # extractive: empty source set is only legal if all inputs are clean
        if joined:
            raise ProvenanceLaunderingError(
                f"extractive summarizer claims clean provenance but inputs "
                f"carry sources {sorted(joined)}"
            )
        return Segment(content=output_text, sources=frozenset())
    return Segment(content=output_text, sources=joined)


def planner_read(segment: Segment, capability: str,
                 blocked_prefixes: tuple[str, ...] = ("web_",)) -> None:
    """Planner gate: refuse to invoke a capability justified by a segment
    whose provenance intersects a blocked source family, and refuse any
    planner-read segment with an empty source set that has tainted ancestry.
    """
    if segment.quarantined:
        raise ProvenanceLaunderingError(
            f"planner read quarantined segment before invoking {capability}"
        )
    if segment.tainted and any(
        src.startswith(p) for src in segment.sources for p in blocked_prefixes
    ):
        raise ProvenanceLaunderingError(
            f"refusing {capability}: justified by tainted segment "
            f"with sources {sorted(segment.sources)}"
        )


def quarantine_laundered(segment: Segment, ancestry: list[Segment]) -> Segment:
    """Post-hoc detection: if a segment read by the planner has an empty
    source set but any ancestor was tainted, quarantine it and require
    re-derivation rather than relabeling in place."""
    if not segment.sources and any(a.tainted for a in ancestry):
        raise ProvenanceLaunderingError(
            "provenance laundering detected: empty-source segment has tainted "
            f"ancestors {sorted({s for a in ancestry for s in a.sources})}; "
            "quarantine and invalidate dependent plans"
        )
    return Segment(content=segment.content, sources=segment.sources,
                   quarantined=True)
