# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-tainted-tool-result-as-a-taint-source-rather-than-a-taint-sink-provenance-laundering-across-multi-hop-tool-invocation-gr.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-tainted-tool-result-as-a-taint-source-rather-than-a-taint-sink-provenance-laundering-across-multi-hop-tool-invocation-gr.warrant.json
# Markdown SHA-256:   cf18237da3e070ae1e4b09ec7169dabe5ca13e97f7fbeeba5d0a4e9602ded6f1
# Code AST SHA-256:   0d3bb9d67e04f6b4649d6546f7fed8ccfc64f9e3e4fe19eac85b8c520b874c93
# Verified Classes:   TaintLaunderingError, TaintLabel, ToolInvocation
# 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 output drops a taint label inherited from its inputs."""


@dataclass(frozen=True)
class TaintLabel:
    source: str
    hop: int


@dataclass
class ToolInvocation:
    tool: str
    input_labels: FrozenSet[TaintLabel]
    output_labels: FrozenSet[TaintLabel]
    label_preserving: bool = True
    declassified_by: str | None = None


def join_inputs(inv: ToolInvocation) -> FrozenSet[TaintLabel]:
    return frozenset(inv.input_labels)


def check_monotonicity(inv: ToolInvocation) -> FrozenSet[TaintLabel]:
    """Enforce taint(out) >= union(taint(in)) unless an explicit declassify warrant exists."""
    required = join_inputs(inv)
    if inv.declassified_by is not None:
        return inv.output_labels  # audited reset; downstream sees only output labels

    if not inv.label_preserving:
        # Unknown transform: amplify to UNKNOWN, never trust a clean scan.
        return inv.output_labels | {TaintLabel(source="UNKNOWN", hop=max((l.hop for l in required), default=0) + 1)}

    missing = required - inv.output_labels
    if missing:
        raise TaintLaunderingError(
            f"tool '{inv.tool}' dropped inherited labels {sorted(missing)}: "
            f"output scanned clean but upstream taint was laundered via transform"
        )
    return inv.output_labels


def execute_hop(inv: ToolInvocation, downstream_is_privileged: bool) -> FrozenSet[TaintLabel]:
    effective = check_monotonicity(inv)
    if downstream_is_privileged and any(l.source == "UNKNOWN" for l in effective):
        raise TaintLaunderingError(
            f"privileged sink '{inv.tool}' refuses UNKNOWN-tainted input; "
            f"declassify explicitly before proceeding"
        )
    return effective
