# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-quarantine-taint-that-re-enters-through-a-memory-write-it-authorized-before-the-taint-label-existed.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-quarantine-taint-that-re-enters-through-a-memory-write-it-authorized-before-the-taint-label-existed.warrant.json
# Markdown SHA-256:   c9b6862d3371f8d232de666cb67c8ede9ad0df4f6d138324b6c89418a11fd98f
# Code AST SHA-256:   76c4908c9106cd47eaeafbb4d85a4eda97613175058a31b4a3a7fb919baf8f1c
# Verified Classes:   Taint, TaintLaunderingError, MemoryObject, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class Taint(IntEnum):
    TRUSTED = 0
    DERIVED_SELF = 1
    DERIVED_UNTRUSTED = 2
    UNTRUSTED = 3


def join(taints: Iterable[Taint]) -> Taint:
    return max(taints, default=Taint.TRUSTED)


class TaintLaunderingError(RuntimeError):
    """Raised when a memory write cannot prove its derivation chain is taint-closed."""


@dataclass
class MemoryObject:
    key: str
    value: str
    taint: Taint
    derived_from: tuple[str, ...] = field(default_factory=tuple)


class MemoryStore:
    def __init__(self) -> None:
        self._objects: dict[str, MemoryObject] = {}

    def write(self, obj: MemoryObject, derivation_inputs: Iterable[MemoryObject] | None) -> None:
        # A derivation function that cannot report its inputs is treated as untrusted.
        if derivation_inputs is None:
            expected = Taint.UNTRUSTED
        else:
            expected = join(i.taint for i in derivation_inputs)
        # The declared taint must be at least as restrictive as the joined inputs.
        if obj.taint < expected:
            raise TaintLaunderingError(
                f"memory write {obj.key!r} declares taint={obj.taint.name} "
                f"but derivation inputs require {expected.name}; "
                f"closure invariant violated (label dropped before persist)"
            )
        self._objects[obj.key] = obj

    def retrieve(self, key: str) -> MemoryObject:
        obj = self._objects.get(key)
        if obj is None:
            raise TaintLaunderingError(f"memory object {key!r} not found")
        # Fail closed: an object with no recorded derivation chain is untrusted.
        if obj.taint == Taint.TRUSTED and not obj.derived_from:
            raise TaintLaunderingError(
                f"memory object {key!r} claims TRUSTED with no derivation chain; "
                f"treating as potential laundering vector"
            )
        return obj


def guarded_remember(
    store: MemoryStore,
    key: str,
    value: str,
    source_taint: Taint,
    derivation_inputs: Iterable[MemoryObject] | None,
) -> None:
    obj = MemoryObject(
        key=key,
        value=value,
        taint=source_taint,
        derived_from=tuple(i.key for i in derivation_inputs) if derivation_inputs else (),
    )
    store.write(obj, derivation_inputs)
