# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-tombstone-as-a-read-barrier-rather-than-a-deletion-receipt.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-tombstone-as-a-read-barrier-rather-than-a-deletion-receipt.warrant.json
# Markdown SHA-256:   da76dc835fbcffdad228f624356501fcea5bea6370ebef6d6756be55cfb879b3
# Code AST SHA-256:   2fc3271367e5c15eb98698c42dcb0e6a8379ca401e3aa5c49ed9aee45458c7ac
# Verified Classes:   TombstoneBarrierViolation, Record, MemoryStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TombstoneBarrierViolation(RuntimeError):
    """Raised when a derived record is served despite a tombstoned ancestor."""


@dataclass
class Record:
    id: str
    text: str
    source_ids: list[str] = field(default_factory=list)
    tombstoned: bool = False


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

    def write(self, rec: Record) -> None:
        self._records[rec.id] = rec
        for src in rec.source_ids:
            self._dependents.setdefault(src, set()).add(rec.id)

    def forget(self, memory_id: str) -> None:
        # Tombstone the address synchronously; propagation is the caller's job.
        rec = self._records.get(memory_id)
        if rec is None:
            raise TombstoneBarrierViolation(f"forget on unknown id {memory_id}")
        rec.tombstoned = True

    def _has_tombstoned_ancestor(self, rec_id: str, seen: Optional[set[str]] = None) -> bool:
        seen = seen or set()
        if rec_id in seen:
            return False
        seen.add(rec_id)
        rec = self._records.get(rec_id)
        if rec is None:
            return False
        if rec.tombstoned:
            return True
        return any(self._has_tombstoned_ancestor(s, seen) for s in rec.source_ids)

    def read(self, rec_id: str) -> Record:
        rec = self._records.get(rec_id)
        if rec is None:
            raise TombstoneBarrierViolation(f"read on unknown id {rec_id}")
        if rec.tombstoned:
            # Tombstone is a barrier, not a null read: callers must handle it.
            raise TombstoneBarrierViolation(f"{rec_id} is tombstoned; barrier active")
        if self._has_tombstoned_ancestor(rec_id):
            # A derived record whose ancestor was forgotten must not be served.
            raise TombstoneBarrierViolation(
                f"{rec_id} derives from a tombstoned source; re-derive before serving"
            )
        return rec
