# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-handoff-that-carries-an-untrusted-context-taint-marker-and-how-does-the-quarantine-boundary-actually-fail.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-handoff-that-carries-an-untrusted-context-taint-marker-and-how-does-the-quarantine-boundary-actually-fail.warrant.json
# Markdown SHA-256:   8b48e299b0004b974cf122d4a032bdd1604a13d93d6644865245a5e008e7d423
# Code AST SHA-256:   442548dbed894b07f8c952cb4454228329b324f390eee032f2ad0925065a6ffa
# Verified Classes:   TaintLaunderingError, QuarantineViolation, Envelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

CLEAN: FrozenSet[str] = frozenset()
UNKNOWN: FrozenSet[str] = frozenset({"__unknown__"})


class TaintLaunderingError(RuntimeError):
    """Raised when an envelope is constructed without joining inbound ancestry."""
    pass


class QuarantineViolation(RuntimeError):
    """Raised at a privileged sink when ancestry contains an untrusted leaf."""
    pass


@dataclass(frozen=True)
class Envelope:
    payload: dict
    ancestry: FrozenSet[str] = CLEAN
    untrusted_leaves: FrozenSet[str] = CLEAN


def join_ancestry(inbound: Envelope, derived_from: FrozenSet[str]) -> FrozenSet[str]:
    # The only legal way to build an outbound envelope from an inbound one.
    return inbound.ancestry | derived_from


def build_outbound(inbound: Envelope, payload: dict, derived_from: FrozenSet[str]) -> Envelope:
    if inbound is None:
        raise TaintLaunderingError(
            "outbound envelope constructed with no inbound lineage; "
            "refusing to default ancestry to CLEAN"
        )
    return Envelope(
        payload=payload,
        ancestry=join_ancestry(inbound, derived_from),
        untrusted_leaves=inbound.untrusted_leaves,
    )


def executor_sink(env: Envelope, mutates_external_state: bool) -> None:
    # Sink-side re-derivation: trust ancestry, never the current label.
    if env.ancestry & env.untrusted_leaves:
        raise QuarantineViolation(
            f"refusing action; ancestry {sorted(env.ancestry)} contains untrusted leaves "
            f"{sorted(env.ancestry & env.untrusted_leaves)}"
        )
    if mutates_external_state and not env.ancestry:
        # Empty ancestry into a privileged sink is UNKNOWN, not CLEAN.
        raise QuarantineViolation(
            "refusing privileged action on envelope with empty provenance (UNKNOWN != CLEAN)"
        )
    # proceed
