# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-derived-value-rather-than-a-source-label-join-collapse-at-tool-boundaries-in-prompt-injection-taint-tracking.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-derived-value-rather-than-a-source-label-join-collapse-at-tool-boundaries-in-prompt-injection-taint-tracking.warrant.json
# Markdown SHA-256:   dc6656e8d0a559bba43174c577114c5fa40042fc2bdc72bcee8f7ff1e04d4795
# Code AST SHA-256:   9ad12c24241bb5e5b4e63d7516c081ffee101d62d2f1a02718c7102d1cebf980
# Verified Classes:   LabelJoinViolation, Label
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class LabelJoinViolation(RuntimeError):
    """Raised when a derived value's label is less restrictive than the join of its inputs."""


@dataclass(frozen=True)
class Label:
    integrity: str          # "clean" | "tainted"
    provenance: FrozenSet[str]

    _ORDER = {"clean": 0, "tainted": 1}

    def join(self, other: "Label") -> "Label":
        return Label(
            integrity=max(self.integrity, other.integrity, key=self._ORDER.__getitem__),
            provenance=self.provenance | other.provenance,
        )

    def leq(self, other: "Label") -> bool:
        return (
            self._ORDER[self.integrity] <= self._ORDER[other.integrity]
            and self.provenance <= other.provenance
        )


def propagate_tool_output(
    inputs: list[Label],
    tool_ceiling: Label,
    declared_output: Label | None,
) -> Label:
    joined = tool_ceiling
    for lbl in inputs:
        joined = joined.join(lbl)

    if declared_output is None:
        # Default-clean is forbidden: inherit the join.
        return joined

    if not joined.leq(declared_output):
        raise LabelJoinViolation(
            f"tool declared output {declared_output} but join of inputs is {joined}; "
            f"label laundering across tool boundary"
        )
    return declared_output


def authorize_sink(value_label: Label, required: Label) -> None:
    if not value_label.leq(required):
        raise LabelJoinViolation(
            f"derived value label {value_label} exceeds sink requirement {required}; "
            f"quarantine derived value, not source"
        )
