# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-provenance-clean-memory-write-the-write-time-vs-read-time-poisoning-boundary-in-persistent-agent-mem.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-provenance-clean-memory-write-the-write-time-vs-read-time-poisoning-boundary-in-persistent-agent-mem.warrant.json
# Markdown SHA-256:   9b0a474f63ede253f3f410a2df2326e4f8b4653d375de3d8f1f99216a915ae69
# Code AST SHA-256:   2080ef82614ead4f046edd4eaa6f5832020b72454f72dc88da4017670046171d
# Verified Classes:   TaintLaunderingError, MemoryRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a memory record's stamped trust tier exceeds its effective
    (min-over-ancestors) tier, or when its derivation ancestry is unresolvable."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    stamped_tier: int          # higher == more trusted
    content: str
    parents: list[str] = field(default_factory=list)


def effective_tier(record_id: str, store: dict[str, MemoryRecord],
                   _visiting: Optional[set[str]] = None) -> int:
    """Compute the taint-propagated tier: min over the derivation DAG.

    Unresolvable ancestry (missing edge or cycle) is strictly worse than a
    known-untrusted ancestor and must be rejected, never defaulted upward.
    """
    visiting = _visiting or set()
    if record_id in visiting:
        raise TaintLaunderingError(
            f"cycle in derivation DAG at {record_id!r}: ancestry unresolvable"
        )
    rec = store.get(record_id)
    if rec is None:
        raise TaintLaunderingError(
            f"missing ancestor {record_id!r}: derivation edge dropped, "
            f"effective tier cannot be bounded"
        )
    visiting.add(record_id)
    tier = rec.stamped_tier
    for parent_id in rec.parents:
        tier = min(tier, effective_tier(parent_id, store, visiting))
    visiting.discard(record_id)
    return tier


def gate_retrieval(record_id: str, store: dict[str, MemoryRecord],
                   required_tier: int) -> MemoryRecord:
    """Return the record only if its *effective* tier clears the gate.

    A record whose stamp clears the gate but whose effective tier does not is
    the taint-laundering signature: provenance-clean, content-poisoned.
    """
    rec = store[record_id]
    eff = effective_tier(record_id, store)
    if eff < rec.stamped_tier:
        raise TaintLaunderingError(
            f"record {record_id!r} stamped tier {rec.stamped_tier} exceeds "
            f"effective tier {eff}: distilled from lower-trust observation "
            f"without declassification — treat as tier {eff}, not "
            f"{rec.stamped_tier}"
        )
    if eff < required_tier:
        raise TaintLaunderingError(
            f"record {record_id!r} effective tier {eff} below gate "
            f"{required_tier}: tainted ancestry, reject"
        )
    return rec
