# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-across-a-tool-boundary-when-provenance-labels-are-dropped-by-a-serialization-round-trip.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-across-a-tool-boundary-when-provenance-labels-are-dropped-by-a-serialization-round-trip.warrant.json
# Markdown SHA-256:   0fb4ffe3a6b32894524d9943b9aa27cf56aa76bf1495437e0144344f771c8b92
# Code AST SHA-256:   fa131992c63fbee7d501106cc7aafff2403eb6d21b17b4b8de224f1e435fc1d7
# Verified Classes:   TaintLaunderingError, Provenance, HopRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a tool hop drops provenance labels without declassification."""
    pass


@dataclass(frozen=True)
class Provenance:
    labels: FrozenSet[str]

    def union(self, other: "Provenance") -> "Provenance":
        return Provenance(self.labels | other.labels)


@dataclass
class HopRecord:
    hop_id: str
    outbound: Provenance
    inbound: Provenance
    declassified: FrozenSet[str] = field(default_factory=frozenset)


def verify_hop(record: HopRecord) -> Provenance:
    """Enforce derivation-monotonicity across a single tool boundary.

    Accept iff inbound labels cover outbound labels minus any explicitly
    declassified labels. Otherwise the hop is lossy and must halt.
    """
    expected = record.outbound.labels - record.declassified
    missing = expected - record.inbound.labels
    if missing:
        raise TaintLaunderingError(
            f"hop {record.hop_id!r} dropped provenance labels {sorted(missing)}; "
            f"outbound={sorted(record.outbound.labels)} "
            f"inbound={sorted(record.inbound.labels)} "
            f"declassified={sorted(record.declassified)}"
        )
    # Derivation cannot reduce taint: propagate the union, not the inbound set.
    return record.outbound.union(record.inbound)


def reingest(tool_output: dict, hop: HopRecord) -> tuple[dict, Provenance]:
    """Re-ingest tool output only after the hop is verified.

    Unlabeled output is never promoted to 'internal'; it inherits the union
    of the hop's provenance. A missing label is treated as maximally suspect.
    """
    if "provenance" not in tool_output:
        # Do not default to trusted. Force the caller through verification.
        raise TaintLaunderingError(
            f"hop {hop.hop_id!r} returned unlabeled output; refusing default-trust re-ingestion"
        )
    propagated = verify_hop(hop)
    return tool_output, propagated
