# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-propagates-prompt-injection-taint-through-tool-output-labels-it-cannot-re-derive.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-propagates-prompt-injection-taint-through-tool-output-labels-it-cannot-re-derive.warrant.json
# Markdown SHA-256:   912b802fb3036e6d029c6cea9833c20c253b9eed16b7dc38548c8e03cdfc6ddb
# Code AST SHA-256:   7510a76cb460f4125db47994c5c53fcda5b60e54d07d4caf0ad500e015088cce
# Verified Classes:   TaintLaunderingError, Labeled
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when a derived value's label is more trusted than its causal inputs."""


@dataclass(frozen=True)
class Labeled:
    value: Any
    tainted: bool
    provenance: tuple[str, ...] = field(default_factory=tuple)


def join(*inputs: Labeled) -> Labeled:
    """Least upper bound: tainted if any contributor is tainted."""
    tainted = any(i.tainted for i in inputs)
    prov: list[str] = []
    for i in inputs:
        prov.extend(i.provenance)
    return Labeled(value=None, tainted=tainted, provenance=tuple(prov))


def derive(output: Labeled, contributors: list[Labeled], step: str) -> Labeled:
    """Propagate labels through a reasoning or tool step.

    The output label must dominate the join of its contributors. A model
    generation channel cannot reset taint to False.
    """
    expected = join(*contributors)
    if expected.tainted and not output.tainted:
        raise TaintLaunderingError(
            f"step {step!r} emitted TRUSTED value derived from UNTRUSTED "
            f"contributors {expected.provenance}; paraphrase boundary "
            f"dropped taint — action must be blocked or declassified by a "
            f"non-injectable verifier"
        )
    return Labeled(
        value=output.value,
        tainted=expected.tainted,
        provenance=expected.provenance + (step,),
    )


def guarded_mutation(arg: Labeled, tool: str) -> None:
    if arg.tainted:
        raise TaintLaunderingError(
            f"{tool} refused: argument carries taint from {arg.provenance}; "
            f"requires human confirmation or database-backed declassification"
        )


# Failure trace reproduced from the incident:
ticket = Labeled(value="...signature address...", tainted=True,
                 provenance=("mailbox_ingress",))
extraction = derive(Labeled(value={"order": "4417"}, tainted=True),
                    [ticket], "extract_fields")
scratchpad = Labeled(value="Customer requests address change for 4417",
                     tainted=False, provenance=("model_channel",))
# This raises: the scratchpad claims TRUSTED but derives from a tainted source.
derive(scratchpad, [extraction], "summarize_to_scratchpad")
