# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-retrieval-result-whose-taint-label-was-laundered-through-a-summarization-tool-and-how-does-label-join.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-retrieval-result-whose-taint-label-was-laundered-through-a-summarization-tool-and-how-does-label-join.warrant.json
# Markdown SHA-256:   efc0c801c08e082b4eaa48fd03b5fba7e16c3b8792eb807ea4cf894d88932b3b
# Code AST SHA-256:   3e9a13b69e5a24bd45ed670d75293d38326414925158408207740a9ddcf6c7f8
# Verified Classes:   TaintJoinViolation, Artifact
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

UNTRUSTED = 0
DERIVED = 1
TRUSTED = 2

# join is monotone: min over the lattice, since lower = less trusted.
def join(labels: Iterable[int]) -> int:
    return min(labels, default=TRUSTED)


class TaintJoinViolation(RuntimeError):
    """Raised when an artifact's declared label is not the join of its inputs."""


@dataclass
class Artifact:
    id: str
    label: int
    label_derivation: str  # "join" | "self"
    inputs: list["Artifact"] = field(default_factory=list)


def register_tool_output(
    tool_name: str,
    declared_label: int,
    derivation: str,
    inputs: list[Artifact],
) -> Artifact:
    """Enforce that a tool's output label equals join of its inputs.

    A tool that emits a self-descriptive label on labeled input is
    label-breaking; its output must be re-tainted to the join of all
    reachable inputs, or the gate must refuse it.
    """
    if derivation == "self" and inputs:
        required = join(a.label for a in inputs)
        if declared_label > required:
            # Laundering detected: declared label is cleaner than inputs allow.
            raise TaintJoinViolation(
                f"tool {tool_name!r} emitted label {declared_label} on input "
                f"join {required}; label-breaking tool must re-taint to join "
                f"or be quarantined before reaching any sink"
            )
    if derivation == "join":
        required = join(a.label for a in inputs)
        if declared_label != required:
            raise TaintJoinViolation(
                f"tool {tool_name!r} declared join-derivation but label "
                f"{declared_label} != computed join {required}"
            )
    return Artifact(
        id=f"{tool_name}:out",
        label=declared_label,
        label_derivation=derivation,
        inputs=list(inputs),
    )


def sink_gate(artifact: Artifact, sink_min_integrity: int = DERIVED) -> None:
    """Refuse sink access unless the artifact's label is provably joined."""
    if artifact.label_derivation != "join" and artifact.inputs:
        raise TaintJoinViolation(
            f"artifact {artifact.id} reached sink with unverified "
            f"derivation {artifact.label_derivation!r}; recompute join at sink"
        )
    if artifact.label < sink_min_integrity:
        raise TaintJoinViolation(
            f"artifact {artifact.id} label {artifact.label} below sink "
            f"threshold {sink_min_integrity}"
        )


# Demonstration: fetch -> summarize (label-breaking) -> act
web_doc = Artifact(id="D7", label=UNTRUSTED, label_derivation="join", inputs=[])
# Honest summarizer that self-stamps: this is the laundering hop.
summary = register_tool_output(
    tool_name="summarize",
    declared_label=DERIVED,
    derivation="self",
    inputs=[web_doc],
)
# The line above raises TaintJoinViolation, preventing the false-clean record.
sink_gate(summary)
