# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-tool-output-as-tainted-rather-than-merely-untrusted-the-label-laundering-failure-at-the-dynamic-ifc-join.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-tool-output-as-tainted-rather-than-merely-untrusted-the-label-laundering-failure-at-the-dynamic-ifc-join.warrant.json
# Markdown SHA-256:   4e585700f5266b5b3faf8188f2f2d663f679e4aef5cb5e213fc2ded3e60301db
# Code AST SHA-256:   15417acc5fc8566e5cdde1345b853c3677e859be124497d90af4c3df40621cbd
# Verified Classes:   Trust, TaintLaunderingError, Labeled
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class Trust(Enum):
    TRUSTED = 0
    TAINTED = 1


class TaintLaunderingError(RuntimeError):
    """Raised when a privileged sink receives a value whose provenance
    includes a tainted ancestor, or whose label is unknown."""


@dataclass
class Labeled:
    value: Any
    trust: Trust
    provenance: tuple[str, ...] = field(default_factory=tuple)

    def join(self, other: "Labeled") -> "Labeled":
        # Join is the restrictive combination: tainted dominates.
        trust = Trust.TAINTED if Trust.TAINTED in (self.trust, other.trust) else Trust.TRUSTED
        return Labeled(self.value, trust, self.provenance + other.provenance)


def llm_transform(node: str, inputs: list[Labeled], out_value: Any) -> Labeled:
    """Any LLM-mediated transform (extract, summarize, compact) is a dataflow
    node. It is NOT a sanitizer: output inherits the join of all inputs."""
    if not inputs:
        raise TaintLaunderingError(f"{node}: transform with no declared inputs")
    joined = inputs[0]
    for i in inputs[1:]:
        joined = joined.join(i)
    return Labeled(out_value, joined.trust, joined.provenance + (node,))


def sanitize_schema(node: str, candidate: Labeled, allowed: set[str]) -> Labeled:
    """A declared sanitizer with a proof obligation: only structural checks
    (allowlist / schema) may declassify. LLM reformatting may not."""
    if str(candidate.value) not in allowed:
        raise TaintLaunderingError(
            f"{node}: value {candidate.value!r} not in allowlist; cannot declassify"
        )
    return Labeled(candidate.value, Trust.TRUSTED, candidate.provenance + (f"sanitized:{node}",))


def privileged_sink(sink_name: str, arg: Labeled) -> None:
    """Fail closed: any non-TRUSTED or unknown label blocks the action."""
    if arg.trust is not Trust.TRUSTED:
        raise TaintLaunderingError(
            f"sink {sink_name!r} rejected tainted argument "
            f"provenance={arg.provenance}"
        )
    # ... execute the privileged action ...


def run_pipeline() -> None:
    web = Labeled("...injected IBAN DE89...", Trust.TAINTED, ("fetch_page",))
    extracted = llm_transform("extract_entities", [web], "DE89 3704 0044 0532 0130 00")
    compacted = llm_transform("context_compaction", [extracted], "Vendor IBAN: DE89 ...")
    # Correct behavior: compaction preserves taint, so the sink rejects.
    privileged_sink("pay_vendor", compacted)


if __name__ == "__main__":
    run_pipeline()
