# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-memory-write-the-label-join-failure-at-the-retrieval-to-distillation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-memory-write-the-label-join-failure-at-the-retrieval-to-distillation-boundary.warrant.json
# Markdown SHA-256:   9b8f46ea83bf88803b52b0087b5d8e93bb4af5c35765d7c39b0a03a153ca1ad1
# Code AST SHA-256:   5f9741bc7fb30ed3a36fcf6760466c7c6fd0a1db4e03cf03eb4161466964ec72
# Verified Classes:   TaintLaunderingError, Label, Derivation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a memory write declares a label below the harness-computed join."""
    pass


# Trust lattice: higher index = more trustworthy. Join = max.
TRUST_ORDER = ["untrusted_external", "model_derived", "verified_internal"]
INTEGRITY_MIN_FOR_NAMESPACE = {
    "planning": "verified_internal",
    "episodic": "model_derived",
}


@dataclass(frozen=True)
class Label:
    trust: str

    def __post_init__(self):
        if self.trust not in TRUST_ORDER:
            raise ValueError(f"unknown trust level: {self.trust}")


def join(labels):
    if not labels:
        # No provenance recorded => unknown => treat as top taint.
        return Label("untrusted_external")
    return Label(max((l.trust for l in labels), key=TRUST_ORDER.index))


@dataclass
class Derivation:
    inputs: list = field(default_factory=list)   # list[Label]
    complete: bool = True                        # all parent edges recorded?


def gate_memory_write(namespace: str, declared: Label, deriv: Derivation) -> Label:
    """Return the label to persist, or raise if the write would launder taint."""
    if not deriv.complete:
        # Unknown join == top taint. Refuse to admit a possibly-clean claim.
        raise TaintLaunderingError(
            f"incomplete derivation graph for write to {namespace!r}; "
            f"declared={declared.trust}, true join unknown"
        )

    computed = join(deriv.inputs)
    if TRUST_ORDER.index(declared.trust) < TRUST_ORDER.index(computed.trust):
        raise TaintLaunderingError(
            f"label laundering at write to {namespace!r}: "
            f"declared={declared.trust} < computed_join={computed.trust}"
        )

    floor = INTEGRITY_MIN_FOR_NAMESPACE.get(namespace, "verified_internal")
    if TRUST_ORDER.index(computed.trust) < TRUST_ORDER.index(floor):
        # Admissible value but below namespace floor: quarantine, don't drop.
        return Label("untrusted_external")

    return computed


def remember(namespace: str, summary: str, declared: Label, deriv: Derivation) -> Label:
    persisted = gate_memory_write(namespace, declared, deriv)
    # ... persist (summary, persisted) into the store ...
    return persisted


# Reproduces the incident: summarizer claims model_derived, but its only
# input was an untrusted_external fetch. The gate must reject.
if __name__ == "__main__":
    try:
        remember(
            namespace="planning",
            summary="Project deadline is 2025-01-01 (verified).",
            declared=Label("model_derived"),
            deriv=Derivation(inputs=[Label("untrusted_external")], complete=True),
        )
    except TaintLaunderingError as e:
        print(f"blocked: {e}")
