# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-a-forgotten-memory-through-a-stale-embedding-index-after-a-right-to-forget-tombstone.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-a-forgotten-memory-through-a-stale-embedding-index-after-a-right-to-forget-tombstone.warrant.json
# Markdown SHA-256:   1bfefd845116065ba7e91f163b68addc832c02f61039a18f13313efed5695459
# Code AST SHA-256:   c9aa58d38e89f02851f1409b1a081ac559fff4e790aeaf2265f714fc12bd3868
# Verified Classes:   ForgetRaceError, Record, Candidate, RecordStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class ForgetRaceError(RuntimeError):
    """Raised when a candidate memory cannot be safely admitted to context."""
    pass

@dataclass
class Record:
    memory_id: str
    principal_id: str
    payload: str
    state: str  # "active" | "tombstoned"
    version: int

@dataclass
class Candidate:
    memory_id: str
    principal_id: str   # from stale index metadata
    payload_snapshot: str  # MUST NOT be used for content
    score: float

class RecordStore:
    def __init__(self):
        self._rows: dict[str, Record] = {}
        self.audit: list[dict] = []

    def get(self, memory_id: str) -> Optional[Record]:
        return self._rows.get(memory_id)

    def forget(self, memory_id: str, principal_id: str) -> None:
        r = self._rows[memory_id]
        r.state = "tombstoned"
        r.version += 1
        self.audit.append({"event": "FORGET", "memory_id": memory_id,
                           "principal": principal_id})

def admit_candidate(store: RecordStore, cand: Candidate,
                    requesting_principal: str,
                    active_cache: dict[str, Record]) -> Record:
    # Admission gate: record layer is the only source of truth.
    rec = active_cache.get(cand.memory_id)
    if rec is None:
        rec = store.get(cand.memory_id)
        if rec is None:
            raise ForgetRaceError(
                f"candidate {cand.memory_id} has no authoritative record")
        if rec.state == "active":
            active_cache[cand.memory_id] = rec

    if rec.state != "active":
        store.audit.append({"event": "FORGET_RACE_SUPPRESSED",
                            "memory_id": cand.memory_id,
                            "principal": requesting_principal})
        raise ForgetRaceError(
            f"candidate {cand.memory_id} is tombstoned; "
            f"snapshot payload must not be admitted")

    if rec.principal_id != requesting_principal:
        raise ForgetRaceError(
            f"candidate {cand.memory_id} owned by {rec.principal_id}, "
            f"not {requesting_principal}")

    # Only now is the content permitted to enter context.
    return rec
