# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-tainted-sink-write-when-the-label-set-is-empty-but-the-provenance-chain-is-not.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-tainted-sink-write-when-the-label-set-is-empty-but-the-provenance-chain-is-not.warrant.json
# Markdown SHA-256:   d3d1da0832a81a5f48325a21b1e39c0bb62fa172c4e078f42dd072084c874437
# Code AST SHA-256:   0801a9a782764833d3b81fba91ddfb10be62fc47c6557dc169463a68f80eabce
# Verified Classes:   TaintedSinkError, Provenance, SinkPolicy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class TaintedSinkError(RuntimeError):
    """Raised when a sink write is attempted on a payload whose provenance
    chain reaches a sensitive source, regardless of the payload's label set."""


@dataclass(frozen=True)
class Provenance:
    sources: frozenset[str] = frozenset()
    clearing_edges: frozenset[str] = frozenset()


SENSITIVE_SOURCES = frozenset({"PII", "SECRET", "INTERNAL"})
AUTHORIZED_CLEARING = frozenset({"redact_verified", "hash_only"})


@dataclass
class SinkPolicy:
    sink: str
    denied_sources: frozenset[str] = SENSITIVE_SOURCES

    def evaluate(self, payload_labels: frozenset[str],
                 provenance: Provenance | None) -> None:
        # Fail-closed: missing provenance is treated as tainted.
        if provenance is None:
            raise TaintedSinkError(
                f"sink {self.sink!r}: payload has no provenance record; "
                f"refusing (fail-closed). labels={sorted(payload_labels)}"
            )

        hits = provenance.sources & self.denied_sources
        if not hits:
            return  # provenance is clean; label set is irrelevant

        # Sensitive source present. Permit only if every sensitive edge was
        # cleared by an authorized transformation.
        uncleared = hits - provenance.clearing_edges
        if uncleared:
            raise TaintedSinkError(
                f"sink {self.sink!r}: payload derived from sensitive sources "
                f"{sorted(uncleared)} with no authorized clearing edge. "
                f"labels={sorted(payload_labels)} (empty label set is NOT "
                f"sufficient grounds to permit)."
            )
        # All sensitive edges cleared by allowlisted transformations.
        return


def guarded_egress(payload: dict, labels: frozenset[str],
                   provenance: Provenance | None,
                   policy: SinkPolicy) -> None:
    policy.evaluate(labels, provenance)
    # ... perform the actual sink write only after the check passes ...
