# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-launder-a-poisoned-memory-through-its-own-successful-re-derivation-the-taint-decay-invariant-in-trust-scored-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-launder-a-poisoned-memory-through-its-own-successful-re-derivation-the-taint-decay-invariant-in-trust-scored-stores.warrant.json
# Markdown SHA-256:   395a25bb3dfce996b963544917a4260533030d71fefabd921e5f99a50ac3e148
# Code AST SHA-256:   0150785244c6e1231d0afa932ea65ab5170233e65b9c4a1a933c99003d396351
# Verified Classes:   TaintLaunderingError, MemoryRecord, TrustScoredStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field

TRUST_THRESHOLD = 0.6
MAX_DERIVATION_DEPTH = 8

class TaintLaunderingError(RuntimeError):
    """Raised when a write would assign a derived record more trust than its premises allow."""
    pass

@dataclass
class MemoryRecord:
    rid: str
    authored_trust: float
    tainted: bool = False
    derived_from: list[str] = field(default_factory=list)
    effective_trust: float = 0.0

class TrustScoredStore:
    def __init__(self):
        self.records: dict[str, MemoryRecord] = {}

    def _resolve(self, rid: str, depth: int = 0) -> MemoryRecord:
        if depth > MAX_DERIVATION_DEPTH:
            # fail-closed: unknown-depth ancestry is treated as fully tainted
            raise TaintLaunderingError(f"derivation depth cap exceeded at {rid}")
        rec = self.records[rid]
        if not rec.derived_from:
            rec.effective_trust = rec.authored_trust
            return rec
        parents = [self._resolve(p, depth + 1) for p in rec.derived_from]
        ceiling = min(p.effective_trust for p in parents)
        rec.effective_trust = min(rec.authored_trust, ceiling)
        rec.tainted = rec.tainted or any(p.tainted for p in parents)
        return rec

    def write(self, rec: MemoryRecord) -> MemoryRecord:
        if rec.derived_from:
            parents = [self._resolve(p) for p in rec.derived_from]
            ceiling = min(p.effective_trust for p in parents)
            if rec.authored_trust > ceiling:
                raise TaintLaunderingError(
                    f"record {rec.rid} claims trust {rec.authored_trust} "
                    f"but derivation ceiling is {ceiling}; would launder taint"
                )
            rec.effective_trust = min(rec.authored_trust, ceiling)
            rec.tainted = rec.tainted or any(p.tainted for p in parents)
        else:
            rec.effective_trust = rec.authored_trust
        self.records[rec.rid] = rec
        return rec

    def retrieve(self, rid: str) -> MemoryRecord | None:
        rec = self._resolve(rid)
        if rec.tainted or rec.effective_trust < TRUST_THRESHOLD:
            return None
        return rec
