# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-prompt-injection-taint-that-survives-a-context-window-eviction-when-data-flow-labels-are-dropped-at-the-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-prompt-injection-taint-that-survives-a-context-window-eviction-when-data-flow-labels-are-dropped-at-the-tool-call-boundary.warrant.json
# Markdown SHA-256:   c60a604c163c8f6f21c71ba2d7978def6a9e316a66e4606f2874cc1c63c8a9a1
# Code AST SHA-256:   1b5424580291a0018e4d67b498c6e3f852f910b2269b28d38e6dc93c03b9a331
# Verified Classes:   ProvenanceGapError, Labeled
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class ProvenanceGapError(RuntimeError):
    """Raised when a tool argument's provenance cannot be established.

    This is the post-eviction / post-handoff signal: the value is present
    but the label that should travel with it is not. Absence of a label is
    NOT evidence of cleanliness.
    """


@dataclass
class Labeled:
    value: Any
    labels: frozenset = field(default_factory=frozenset)

    def derive(self, new_value: Any) -> "Labeled":
        # Monotonic: derivation never clears taint.
        return Labeled(new_value, self.labels)


UNTRUSTED = "UNTRUSTED"


def guard_consequential_sink(arg: Labeled, *, declassified: bool = False) -> None:
    # A missing/empty label set on a *derived* argument is a gap, not a pass.
    # Callers must pass provenance explicitly; there is no implicit clean.
    if arg.labels is None:
        raise ProvenanceGapError(
            f"argument {arg.value!r} has no provenance record; "
            "context eviction or handoff dropped the label"
        )
    if UNTRUSTED in arg.labels and not declassified:
        raise ProvenanceGapError(
            f"argument {arg.value!r} carries UNTRUSTED taint "
            f"(labels={sorted(arg.labels)}); refusing sink"
        )


def send_email(recipients: list, body: str) -> None:
    for r in recipients:
        # r is a Labeled; provenance must have survived the tool boundary.
        guard_consequential_sink(r)
    # ... actual dispatch ...


# --- trace of the observed failure, now bounded ---
page = Labeled("...audit-archive@external.example...", frozenset({UNTRUSTED}))
recipient = page.derive("audit-archive@external.example")  # taint preserved
# context compaction evicts `page`; `recipient` still carries the label:
try:
    send_email([recipient], "vendor list")
except ProvenanceGapError as e:
    # deterministic refusal instead of silent exfiltration
    print("blocked:", e)

# the gap case: a value whose label was dropped at serialization
orphan = Labeled("audit-archive@external.example", frozenset())
orphan.labels = None  # simulate lossy channel
try:
    send_email([orphan], "vendor list")
except ProvenanceGapError as e:
    print("blocked (gap):", e)
