# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-escalate-dynamic-taint-labels-from-tool-output-to-semantic-memory-writes-and-where-does-label-laundering-break-the.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-escalate-dynamic-taint-labels-from-tool-output-to-semantic-memory-writes-and-where-does-label-laundering-break-the.warrant.json
# Markdown SHA-256:   e8d7daa4a35c1ab6aed79a20205975bb95107bf5cc9d6401c9babca47f2ce461
# Code AST SHA-256:   6ace973196d111fb99bb0bd3a1af26bd3d451bfe21ee4d005a0172e64c6b7b80
# Verified Classes:   Trust, TaintLaunderingError, Provenance, Transform
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


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

    @staticmethod
    def join(*labels: "Trust") -> "Trust":
        # Least upper bound: any untrusted input taints the result.
        return Trust(max(labels)) if labels else Trust.TRUSTED


class TaintLaunderingError(RuntimeError):
    """Raised when a generative transform or memory write would reset taint."""


@dataclass
class Provenance:
    label: Trust
    origin: str
    warrant: Optional[str] = None


@dataclass
class Transform:
    kind: str  # "copy" or "generative"
    inputs: list[Provenance] = field(default_factory=list)

    def output_label(self) -> Trust:
        if not self.inputs:
            # No provenance at all is not "trusted"; it is unknown -> fail closed.
            raise TaintLaunderingError(
                f"transform '{self.kind}' has no input provenance; cannot derive label"
            )
        if self.kind == "copy":
            # Sound only because every output token traces to an input token.
            return Trust.join(*(p.label for p in self.inputs))
        if self.kind == "generative":
            # Output tokens are conditionally dependent on the FULL input.
            # Join over all inputs, never over copied spans (there are none).
            return Trust.join(*(p.label for p in self.inputs))
        raise TaintLaunderingError(f"unknown transform kind: {self.kind}")


def remember(key: str, value: object, provenance: Optional[Provenance],
             store: dict) -> None:
    if provenance is None:
        raise TaintLaunderingError(
            f"memory write '{key}' has no provenance; refusing to default to TRUSTED"
        )
    store[key] = (value, provenance)


def declassify(p: Provenance, corroborating: Provenance, auditor: str) -> Provenance:
    if p.label is Trust.TRUSTED:
        return p
    if corroborating.label is not Trust.TRUSTED or not corroborating.warrant:
        raise TaintLaunderingError(
            f"declassification of {p.origin} requires an independent trusted, "
            f"warrant-bearing corroborating source; got {corroborating}"
        )
    return Provenance(label=Trust.TRUSTED, origin=p.origin,
                      warrant=f"declassified_by:{auditor}")


# --- Reproduction of the observed failure, then the guarded path ---
def reproduce() -> None:
    raw = Provenance(Trust.UNTRUSTED, "tool:fetch", "w_4471")
    # Naive span-level propagator: extractor paraphrased, copy-detector found
    # no overlapping spans, join over empty set -> TRUSTED. That is the bug.
    extractor = Transform(kind="generative", inputs=[raw])
    derived = extractor.output_label()
    if derived is Trust.TRUSTED:
        raise TaintLaunderingError(
            "generative transform laundered UNTRUSTED input to TRUSTED; "
            "join must be over full input set, not copied spans"
        )
    # With the corrected rule, derived is UNTRUSTED and the write carries it.
    remember("archival_tier", {"price": 0}, Provenance(derived, "extractor"),
             store={})


if __name__ == "__main__":
    reproduce()
