# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-deleted-memory-through-a-scoped-namespace-tombstone-gap-under-ttl-expiry-and-auditable-deletion.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-deleted-memory-through-a-scoped-namespace-tombstone-gap-under-ttl-expiry-and-auditable-deletion.warrant.json
# Markdown SHA-256:   a420cb943ac804d1e5e83f9f446cd2fb128f99d534209933a54283e87c8fa2bb
# Code AST SHA-256:   d93ac5c0e55703f7d6b8622616cfead558145da9faceb3500d60f15c4efb8a24
# Verified Classes:   ResurrectionTombstoneGap, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ResurrectionTombstoneGap(RuntimeError):
    """Raised when a forgotten entry is still reachable through a read path."""
    pass


@dataclass
class MemoryStore:
    entries: dict = field(default_factory=dict)          # canonical_key -> bytes
    tombstones: set = field(default_factory=set)          # canonical keys
    semantic_index: dict = field(default_factory=dict)    # query -> canonical_key
    alias_map: dict = field(default_factory=dict)         # alias -> canonical
    compaction_epoch_complete: bool = True


def canonicalize(key: str) -> str:
    # Normalize separators so tombstone and read keys agree byte-for-byte.
    return key.replace("::", ":").strip(":")


def forget(store: MemoryStore, key: str, audit_log: list) -> str:
    ck = canonicalize(key)
    store.tombstones.add(ck)
    audit_log.append({"audit": "logical_delete", "key": ck})
    return "logical"  # bytes may survive in index/replica until compaction


def safe_hydrate(store: MemoryStore, resolved_key: str) -> Optional[bytes]:
    """Single chokepoint: canonicalize AFTER all transformations, then check tombstone."""
    ck = canonicalize(resolved_key)
    if ck in store.tombstones:
        return None
    return store.entries.get(ck)


def semantic_read(store: MemoryStore, query: str) -> Optional[bytes]:
    raw_key = store.semantic_index.get(query)
    if raw_key is None:
        return None
    return safe_hydrate(store, raw_key)


def verify_forget(store: MemoryStore, key: str, query: str) -> None:
    """Replay the surfacing query; a hit means the tombstone gap is live."""
    ck = canonicalize(key)
    if ck not in store.tombstones:
        raise ResurrectionTombstoneGap(f"no tombstone recorded for {ck}")
    hit = semantic_read(store, query)
    if hit is not None:
        raise ResurrectionTombstoneGap(
            f"forgotten key {ck} resurrected via semantic path for query {query!r}; "
            f"compaction_epoch_complete={store.compaction_epoch_complete}"
        )
    if not store.compaction_epoch_complete:
        raise ResurrectionTombstoneGap(
            f"deletion of {ck} is logical only; compaction epoch still open, "
            f"treat entry as quarantined and do not echo"
        )
