# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-forgets-a-memory-it-is-still-reasoning-over-provenance-decay-tombstones-and-the-read-after-forget-hazard-in-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-forgets-a-memory-it-is-still-reasoning-over-provenance-decay-tombstones-and-the-read-after-forget-hazard-in-agent-memory.warrant.json
# Markdown SHA-256:   167950cf3c829f04272c9abf0e4b8d7145b9db275a71728168c5c31fcd37c84b
# Code AST SHA-256:   378df9adba5d30efc834180e81c29540603a0bb802920ff93226fb571d3ab347
# Verified Classes:   ForgottenAncestorError, DecayInheritanceViolation, Record, MemoryStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ForgottenAncestorError(RuntimeError):
    """Raised when a memory write depends on a record forgotten in the same episode."""


class DecayInheritanceViolation(RuntimeError):
    """Raised when a record's score exceeds the minimum score of its ancestry."""


@dataclass
class Record:
    id: str
    content: str
    confidence: float
    derived_from: list[str] = field(default_factory=list)
    tombstoned: bool = False


class MemoryStore:
    def __init__(self) -> None:
        self.records: dict[str, Record] = {}
        self.episode_forgets: set[str] = set()

    def write(self, rec: Record) -> None:
        # Barrier: a write in an episode with prior forgets must declare ancestry
        # or re-read the forgotten IDs. Undeclared writes are rejected.
        if self.episode_forgets and not rec.derived_from:
            raise ForgottenAncestorError(
                f"write {rec.id} has no derived_from but episode has "
                f"forgets {sorted(self.episode_forgets)}; re-read or declare ancestry"
            )
        for ancestor_id in rec.derived_from:
            anc = self.records.get(ancestor_id)
            if anc is None:
                raise ForgottenAncestorError(f"unknown ancestor {ancestor_id}")
            if anc.tombstoned or ancestor_id in self.episode_forgets:
                raise ForgottenAncestorError(
                    f"write {rec.id} derives from forgotten record {ancestor_id}"
                )
        # Enforce decay inheritance: score bounded by weakest ancestor.
        if rec.derived_from:
            weakest = min(self.records[a].confidence for a in rec.derived_from)
            if rec.confidence > weakest:
                raise DecayInheritanceViolation(
                    f"{rec.id} confidence {rec.confidence} exceeds ancestor floor {weakest}"
                )
        self.records[rec.id] = rec

    def forget(self, record_id: str, reason: str) -> None:
        rec = self.records[record_id]
        rec.tombstoned = True
        self.episode_forgets.add(record_id)
        # Cascade invalidation to declared descendants.
        for other in self.records.values():
            if record_id in other.derived_from and not other.tombstoned:
                other.tombstoned = True
                other.confidence = 0.0

    def read(self, record_id: str) -> Optional[Record]:
        rec = self.records.get(record_id)
        if rec is None or rec.tombstoned:
            return None
        return rec


def demonstrate_laundering_blocked() -> None:
    store = MemoryStore()
    store.write(Record("m_4417", "vendor X SLA 99.5%", confidence=0.81))
    store.forget("m_4417", reason="superseded_by_contract-2024")
    # Agent still has m_4417 in context and tries to synthesize from it
    # without declaring ancestry — the exact observed failure.
    store.write(Record("m_4502", "buffer 0.7% over 99.5%", confidence=0.9))
    # The line above raises ForgottenAncestorError before commit.
    raise ForgottenAncestorError("unreachable: barrier should have fired earlier")


if __name__ == "__main__":
    try:
        demonstrate_laundering_blocked()
    except ForgottenAncestorError as exc:
        print(f"blocked: {exc}")
