# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-retrieval-chunk-as-tainted-label-join-vs-label-replace-at-tool-output-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-retrieval-chunk-as-tainted-label-join-vs-label-replace-at-tool-output-boundaries.warrant.json
# Markdown SHA-256:   234a421656cc4f9b85b8592e1c60f4a7fe2ff31b8d32c558399a058d31d3af1d
# Code AST SHA-256:   63ccfe3d487a470045169fbb069cf650f3125db4284bdb9738ba41849e7549e2
# Verified Classes:   Trust, TaintViolation, Chunk
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import IntEnum

class Trust(IntEnum):
    UNTRUSTED = 0
    TRUSTED = 1

def join(a: Trust, b: Trust) -> Trust:
    # Least upper bound: labels only move up.
    return Trust(max(a, b))

class TaintViolation(RuntimeError):
    """Raised when a derivative tool would lower the label of its input,
    or when a tainted chunk reaches a privileged sink without declassification."""
    pass

@dataclass(frozen=True)
class Chunk:
    id: str
    label: Trust
    text: str

def call_derivative_tool(tool_name: str, arg: Chunk, tool_trust: Trust) -> Chunk:
    if tool_trust < arg.label:
        # A tool cannot be more trusted than the data it derives from.
        raise TaintViolation(
            f"tool {tool_name!r} trust={tool_trust.name} would downgrade "
            f"input label={arg.label.name} on chunk {arg.id!r}"
        )
    return Chunk(id=f"{tool_name}:{arg.id}", label=join(arg.label, tool_trust), text=arg.text)

def declassify(chunk: Chunk, purpose: str, authorized_purpose: str) -> Chunk:
    if purpose != authorized_purpose:
        raise TaintViolation(
            f"declassification of {chunk.id!r} for purpose {purpose!r} "
            f"not covered by authorization {authorized_purpose!r}"
        )
    return Chunk(id=chunk.id, label=Trust.TRUSTED, text=chunk.text)

def privileged_sink(chunk: Chunk, sink: str) -> None:
    if chunk.label != Trust.TRUSTED:
        raise TaintViolation(
            f"tainted chunk {chunk.id!r} (label={chunk.label.name}) reached "
            f"privileged sink {sink!r} without declassification"
        )
    # ... perform the privileged action ...
