# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-retrieved-tool-result-as-tainted-even-after-the-injecting-span-has-left-the-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-retrieved-tool-result-as-tainted-even-after-the-injecting-span-has-left-the-context-window.warrant.json
# Markdown SHA-256:   23a1992315072f2333c48efea40a354b16368915dd8b8b2650eb161205dd5eb1
# Code AST SHA-256:   785fba7ad4bb0af88a88a51a31e12946637860a5aa1618fe041ce51056dc3ac6
# Verified Classes:   Trust, TaintLaunderingError, LabeledSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Any


class Trust(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1  # join-semilattice: max() combines labels


class TaintLaunderingError(RuntimeError):
    """Raised when a derived span reaches a sink whose tolerance it exceeds."""


@dataclass
class LabeledSpan:
    value: Any
    label: Trust
    origin: str


def join(a: Trust, b: Trust) -> Trust:
    return Trust(max(a.value, b.value))


def derive(output_value: Any, attended: list[LabeledSpan],
           verbatim_from: LabeledSpan | None = None) -> LabeledSpan:
    """Model a generation step: output inherits the join of attended labels,
    unless it is an explicit verbatim copy of a single trusted span."""
    if verbatim_from is not None and verbatim_from.label is Trust.TRUSTED:
        return LabeledSpan(output_value, Trust.TRUSTED, f"copy:{verbatim_from.origin}")
    label = Trust.TRUSTED
    origin = "model"
    for span in attended:
        label = join(label, span.label)
        if span.label is Trust.UNTRUSTED:
            origin = span.origin
    return LabeledSpan(output_value, label, f"derived:{origin}")


def write_config(arg: LabeledSpan, tolerance: Trust = Trust.TRUSTED) -> None:
    if arg.label > tolerance:
        raise TaintLaunderingError(
            f"argument {arg.value!r} carries label {arg.label.name} "
            f"(origin {arg.origin}) exceeding sink tolerance {tolerance.name}"
        )
    # commit


def compact(spans: list[LabeledSpan], summary_text: str) -> LabeledSpan:
    """Compaction is a derivation; the summary must inherit the join."""
    return derive(summary_text, spans)


# --- reproduction of the incident ---
fetch = LabeledSpan("<html>...SLA is 99.99%...auto_renew=true...</html>",
                    Trust.UNTRUSTED, "fetch:vendor_page")

# model reads fetch, emits a tool argument; fetch is attended at generation
sla_arg = derive("99.99%", attended=[fetch])
renew_arg = derive(True, attended=[fetch])

# compaction evicts the source; the summary still carries the label
summary = compact([fetch], "Vendor SLA appears to be 99.99%.")
assert summary.label is Trust.UNTRUSTED  # eviction did NOT launder it

# sink enforcement is independent of whether fetch is still in context
try:
    write_config(sla_arg)
except TaintLaunderingError as e:
    print("blocked:", e)

try:
    write_config(renew_arg)
except TaintLaunderingError as e:
    print("blocked:", e)

# a genuinely trusted literal passes
write_config(LabeledSpan(42, Trust.TRUSTED, "operator"))
