# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-tombstones-a-memory-record-while-a-concurrent-reader-holds-a-stale-index-reference-the-erasure-visibility-gap-in-agent-m.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-tombstones-a-memory-record-while-a-concurrent-reader-holds-a-stale-index-reference-the-erasure-visibility-gap-in-agent-m.warrant.json
# Markdown SHA-256:   f383575ad8b9fd42e2d71bd5be6f6940ba2de52225f6778b70de193d841f8450
# Code AST SHA-256:   ebe453a407c9e44492cf36a26ad4eeff177b70ce59a0e35306eb5e7f7c9ab189
# Verified Classes:   ErasureVisibilityViolation, ReadHandle, Tombstone, MemoryTool
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class ErasureVisibilityViolation(RuntimeError):
    """Raised when a read would return content erased at or before the handle's snapshot epoch."""
    pass


@dataclass(frozen=True)
class ReadHandle:
    record_id: str
    snapshot_epoch: int  # index epoch at which the search result was computed
    acquired_at: float


@dataclass(frozen=True)
class Tombstone:
    record_id: str
    commit_epoch: int
    committed_at: float


class MemoryTool:
    def __init__(self, index_epoch: int = 0):
        self._index_epoch = index_epoch
        self._tombstones: dict[str, Tombstone] = {}
        self._records: dict[str, str] = {}

    def write(self, record_id: str, body: str) -> None:
        self._records[record_id] = body

    def forget(self, record_id: str) -> Tombstone:
        # Phase 1: tombstone-pending, immediately excluded from all read paths.
        self._index_epoch += 1
        ts = Tombstone(record_id, commit_epoch=self._index_epoch, committed_at=time.time())
        self._tombstones[record_id] = ts
        # Phase 2 (async in production): purge authoritative store + replicas.
        self._records.pop(record_id, None)
        return ts

    def search(self, prefix: str) -> list[ReadHandle]:
        epoch = self._index_epoch
        handles = []
        for rid in self._records:
            if not rid.startswith(prefix):
                continue
            ts = self._tombstones.get(rid)
            # Exclude any record tombstoned at or before this index epoch.
            if ts is not None and ts.commit_epoch <= epoch:
                continue
            handles.append(ReadHandle(rid, snapshot_epoch=epoch, acquired_at=time.time()))
        return handles

    def fetch(self, handle: ReadHandle) -> str:
        ts = self._tombstones.get(handle.record_id)
        if ts is not None and ts.commit_epoch <= handle.snapshot_epoch:
            # Fail closed: the handle predates the tombstone; content is erased.
            raise ErasureVisibilityViolation(
                f"record {handle.record_id!r} erased at epoch {ts.commit_epoch} "
                f"but handle snapshot_epoch={handle.snapshot_epoch}; refusing to return"
            )
        body = self._records.get(handle.record_id)
        if body is None:
            raise ErasureVisibilityViolation(
                f"record {handle.record_id!r} absent from store with no covering tombstone; "
                f"handle epoch {handle.snapshot_epoch} cannot be validated"
            )
        return body


def demonstrate_gap() -> None:
    tool = MemoryTool()
    tool.write("R_42", "secret payload")
    handles = tool.search("R_")
    assert len(handles) == 1
    handle = handles[0]
    # Concurrent writer tombstones the record between search and fetch.
    tool.forget("R_42")
    try:
        tool.fetch(handle)
    except ErasureVisibilityViolation as exc:
        print(f"guardrail held: {exc}")
        return
    raise ErasureVisibilityViolation("stale handle returned erased content — invariant broken")


if __name__ == "__main__":
    demonstrate_gap()
