# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-leak-tainted-data-through-a-capability-scoped-egress-when-the-taint-label-decays-across-a-checkpoint-resume-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-leak-tainted-data-through-a-capability-scoped-egress-when-the-taint-label-decays-across-a-checkpoint-resume-boundary.warrant.json
# Markdown SHA-256:   4c74a9d843d5987dddf045ab5185a4e36af099d40d74b629f691f8a83cafb6ea
# Code AST SHA-256:   4472707dce6f568e1382d1719b110b48227274b5993437b2c79b0de37655acc5
# Verified Classes:   TaintViolation, UnattributedValue, ProvenanceToken, Payload
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

TRUSTED = "trusted"
UNTRUSTED = "untrusted"


class TaintViolation(RuntimeError):
    """Raised when a payload's provenance is not admissible at the egress sink."""


class UnattributedValue(TaintViolation):
    """Raised when a payload has no provenance tokens (hallucinated or laundered)."""


@dataclass(frozen=True)
class ProvenanceToken:
    span_id: int
    label: str


@dataclass
class Payload:
    value: object
    sources: FrozenSet[ProvenanceToken] = field(default_factory=frozenset)


def provenance_join(payload: Payload) -> str:
    if not payload.sources:
        # Empty token set: the value traces to no span. Do NOT default to trusted.
        raise UnattributedValue(
            f"payload {payload.value!r} has no provenance tokens; "
            "cannot admit to any sink"
        )
    labels = {tok.label for tok in payload.sources}
    # Monotone join: any untrusted contributor taints the whole payload.
    return UNTRUSTED if UNTRUSTED in labels else TRUSTED


def egress(
    payload: Payload,
    sink_admissible: FrozenSet[str],
    holds_capability: bool,
) -> None:
    if not holds_capability:
        raise TaintViolation("capability check failed for sink")
    joined = provenance_join(payload)  # recomputed at egress, not carried on value
    if joined not in sink_admissible:
        raise TaintViolation(
            f"provenance {joined!r} not admissible at sink "
            f"(admissible={sorted(sink_admissible)})"
        )
    # ... perform the write ...


def resume_and_file(checkpoint_summary: str, fin_capability: bool) -> None:
    """Simulates a resume that reconstructs `amount` from a distilled summary.

    The label was lost at checkpoint time; the provenance token is re-attached
    from the log entry the summary was derived from.
    """
    amount = 4200.00  # parsed out of the summary; label is gone
    tickets_span = ProvenanceToken(span_id=7, label=UNTRUSTED)
    payload = Payload(value=amount, sources=frozenset({tickets_span}))
    egress(payload, sink_admissible=frozenset({TRUSTED}), holds_capability=fin_capability)
