# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-erases-a-memory-key-that-a-concurrent-reader-has-already-resolved-the-tombstone-shadow-invariant-in-read-write-forget-me.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-erases-a-memory-key-that-a-concurrent-reader-has-already-resolved-the-tombstone-shadow-invariant-in-read-write-forget-me.warrant.json
# Markdown SHA-256:   550ee1e8f8cadfb032d33e13e3c70b6cdce7b5aadcaa2b3974d90ce3c17532ec
# Code AST SHA-256:   138e295340a43b4c205a18497abe7f506bb5aaa4145bfb63bb52dc1578f11163
# Verified Classes:   ErasureFault, StaleHandleFault, Handle, Tombstone, MemoryStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ErasureFault(RuntimeError):
    """Raised when a dereference would return content already certified as erased.

    This is a typed, explicit fault — distinct from 'absent'. Returning empty
    would let the caller re-derive the erased content under a new key.
    """
    pass


class StaleHandleFault(RuntimeError):
    """Raised when a resolved handle predates the current index epoch but is not erased."""
    pass


@dataclass(frozen=True)
class Handle:
    key: str
    chunk_id: str
    resolved_epoch: int


@dataclass(frozen=True)
class Tombstone:
    key: str
    erased_at: float
    epoch: int


class MemoryStore:
    def __init__(self) -> None:
        self._index_epoch = 0
        self._tombstones: dict[str, Tombstone] = {}
        self._chunks: dict[str, str] = {}
        self._key_to_chunk: dict[str, str] = {}

    def write(self, key: str, content: str) -> Handle:
        self._index_epoch += 1
        chunk_id = f"chunk_{len(self._chunks):x}"
        self._chunks[chunk_id] = content
        self._key_to_chunk[key] = chunk_id
        return Handle(key=key, chunk_id=chunk_id, resolved_epoch=self._index_epoch)

    def resolve(self, key: str) -> Handle:
        if key in self._tombstones:
            raise ErasureFault(f"key {key!r} is erased; cannot resolve")
        if key not in self._key_to_chunk:
            raise KeyError(key)
        return Handle(key=key, chunk_id=self._key_to_chunk[key], resolved_epoch=self._index_epoch)

    def forget(self, key: str, now: float) -> Tombstone:
        self._index_epoch += 1
        ts = Tombstone(key=key, erased_at=now, epoch=self._index_epoch)
        self._tombstones[key] = ts
        self._key_to_chunk.pop(key, None)
        # Provenance-closed erasure is the caller's contract; a real store
        # must also invalidate derivatives here or return 'partial'.
        return ts

    def dereference(self, handle: Handle, now: float) -> str:
        ts: Optional[Tombstone] = self._tombstones.get(handle.key)
        if ts is not None and now > ts.erased_at:
            # The core invariant: tombstone checked at dereference, not resolution.
            raise ErasureFault(
                f"handle for {handle.key!r} (chunk {handle.chunk_id}) dereferenced "
                f"after erasure at {ts.erased_at}; content must not be returned"
            )
        if handle.resolved_epoch < self._index_epoch and ts is None:
            raise StaleHandleFault(
                f"handle epoch {handle.resolved_epoch} < index epoch {self._index_epoch}; re-resolve"
            )
        return self._chunks[handle.chunk_id]


def audited_read(store: MemoryStore, key: str, now: float) -> str:
    """Resolve then dereference — the window between the two is where resurrection lives."""
    handle = store.resolve(key)
    try:
        return store.dereference(handle, now)
    except ErasureFault:
        # Re-raise as the same typed fault; never swallow into empty string.
        raise
