# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-provenance-label-as-irrevocable-across-a-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-provenance-label-as-irrevocable-across-a-tool-boundary.warrant.json
# Markdown SHA-256:   8258b33b729a802f3ff6aca6d693a7f97133ce9271dcf2c49ebd0804aabcd35a
# Code AST SHA-256:   377774915a057b619980bc4204a7c7aece3ff4183e61bd349993e44834b6403f
# Verified Classes:   Provenance, TaintResetError, Field
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import IntEnum
from typing import Iterable


class Provenance(IntEnum):
    TRUSTED = 0
    TAINTED = 1  # join is max; tainted dominates


def join(*labels: Provenance) -> Provenance:
    return max(labels, default=Provenance.TRUSTED)


class TaintResetError(RuntimeError):
    """Raised when a tool boundary attempts to declassify a lossy output."""


@dataclass(frozen=True)
class Field:
    name: str
    label: Provenance
    echoed: bool  # True if the tool may reproduce input bytes verbatim


# Tools whose output domain is a finite closed set may reset to tool trust.
# Echo-capable fields never reset, regardless of tool trust class.
CLOSED_DOMAIN_TOOLS = {"classify", "extract_date", "extract_currency"}


def label_tool_output(
    tool_name: str,
    tool_trust: Provenance,
    input_labels: Iterable[Provenance],
    output_fields: Iterable[Field],
) -> list[Field]:
    inputs = list(input_labels)
    closed = tool_name in CLOSED_DOMAIN_TOOLS
    result: list[Field] = []
    for f in output_fields:
        if f.echoed or not closed:
            # Lossy or echo field: provenance is the join, never a reset.
            new_label = join(tool_trust, *inputs)
        else:
            new_label = tool_trust
        # Enforce monotonicity: a label may only rise, never fall, at a boundary.
        if new_label < join(*inputs) and not closed:
            raise TaintResetError(
                f"tool {tool_name!r} field {f.name!r}: attempted declassification "
                f"of tainted input without closed output domain"
            )
        result.append(Field(f.name, new_label, f.echoed))
    return result


def gate_sink(sink: str, max_clearance: Provenance, args: dict[str, Field]) -> None:
    for name, f in args.items():
        if f.label > max_clearance:
            raise TaintResetError(
                f"sink {sink!r} refused: arg {name!r} label={f.label.name} "
                f"exceeds clearance {max_clearance.name}"
            )
