# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-a-memory-it-never-marked-as-forgotten-tombstone-audit-divergence-under-regulatory-retention.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-a-memory-it-never-marked-as-forgotten-tombstone-audit-divergence-under-regulatory-retention.warrant.json
# Markdown SHA-256:   b834766825038b9c4d238644071b01ad1ac7eb3e7261dd4297df58cf44d0583f
# Code AST SHA-256:   217484db75a6ffcda6a4e5ae8d9463d1738bd2b8c98e1098be59d42768744c09
# Verified Classes:   RetentionDivergenceError, Record, Ledger, MemoryStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, List, Optional


class RetentionDivergenceError(RuntimeError):
    """Raised when live-layer retrievability and audit-ledger attestation disagree
    on the retention/erasure state of a content atom."""
    pass


@dataclass
class Record:
    rid: str
    content_atom: str
    provenance: List[str] = field(default_factory=list)  # parent record IDs
    obligation: Optional[str] = None  # "retain" | "erase" | None


class Ledger:
    def __init__(self) -> None:
        self.tombstones: Set[str] = set()      # erased record IDs
        self.evictions: Set[str] = set()       # evicted-but-not-erased IDs
        self.attested_live: Set[str] = set()   # IDs the ledger claims are live

    def attest(self, rid: str) -> None:
        self.attested_live.add(rid)

    def tombstone(self, rid: str) -> None:
        self.tombstones.add(rid)
        self.attested_live.discard(rid)

    def evict(self, rid: str) -> None:
        self.evictions.add(rid)
        self.attested_live.discard(rid)


class MemoryStore:
    def __init__(self, ledger: Ledger) -> None:
        self.ledger = ledger
        self.records: Dict[str, Record] = {}

    def ingest(self, rec: Record) -> None:
        self.records[rec.rid] = rec
        self.ledger.attest(rec.rid)

    def _closure(self, rid: str) -> Set[str]:
        """Transitive forward closure of provenance edges from rid."""
        seen: Set[str] = set()
        stack = [rid]
        while stack:
            cur = stack.pop()
            if cur in seen:
                continue
            seen.add(cur)
            for r in self.records.values():
                if cur in r.provenance:
                    stack.append(r.rid)
        return seen

    def retrieve(self, rid: str) -> Record:
        rec = self.records.get(rid)
        if rec is None:
            raise RetentionDivergenceError(
                f"record {rid} not retrievable but ledger may still attest it"
            )
        # Enforce erasure at read time over the provenance closure.
        for anc in self._closure(rid) | {rid}:
            if anc in self.ledger.tombstones:
                raise RetentionDivergenceError(
                    f"retrieval of {rid} would disclose content derived from "
                    f"tombstoned record {anc}"
                )
        return rec

    def evict(self, rid: str) -> None:
        rec = self.records[rid]
        if rec.obligation == "retain":
            raise RetentionDivergenceError(
                f"cannot evict {rid} under active retention obligation"
            )
        if rec.obligation == "erase":
            raise RetentionDivergenceError(
                f"cannot evict {rid} under erasure obligation; tombstone required"
            )
        del self.records[rid]
        self.ledger.evict(rid)  # ledger must not attest a phantom

    def erase(self, rid: str) -> None:
        # Erasure is a graph operation: tombstone the record AND scrub every
        # descendant that derived content from it.
        descendants = self._closure(rid)
        for d in descendants:
            self.records.pop(d, None)
            self.ledger.tombstone(d)
        self.records.pop(rid, None)
        self.ledger.tombstone(rid)
