# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-a-forgotten-memory-when-a-ttl-expiry-and-a-scoped-erasure-tombstone-race-inside-the-same-write-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-a-forgotten-memory-when-a-ttl-expiry-and-a-scoped-erasure-tombstone-race-inside-the-same-write-epoch.warrant.json
# Markdown SHA-256:   30c5b42338ed5388929e7d277282e3c6b0e3113ec508325cb7e41af954583fc4
# Code AST SHA-256:   cbd2b7d0d64f81a99272158d2684cf94688acd719f17a4203ec1450607b642af
# Verified Classes:   AbsenceKind, ResurrectionViolation, Tombstone, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class AbsenceKind(str, Enum):
    EXPIRED = "expired"          # reclaimable; agent may heal from cache
    ERASED = "erased"            # terminal; agent must purge and never heal
    NEVER_EXISTED = "never"      # no prior record


class ResurrectionViolation(RuntimeError):
    """Raised when a write would re-materialize an erased record."""


@dataclass(frozen=True)
class Tombstone:
    scope_id: str
    record_id: str
    kind: AbsenceKind
    epoch: int


class MemoryStore:
    def __init__(self) -> None:
        self._bodies: dict[tuple[str, str], str] = {}
        self._tombstones: dict[tuple[str, str], Tombstone] = {}
        self._epoch = 0

    def _next_epoch(self) -> int:
        self._epoch += 1
        return self._epoch

    def write(self, scope_id: str, record_id: str, body: str,
              derived_from_epoch: int) -> int:
        key = (scope_id, record_id)
        tomb = self._tombstones.get(key)

        # Invariant 1: erasure tombstones are monotonic and block ALL writes.
        if tomb is not None and tomb.kind is AbsenceKind.ERASED:
            raise ResurrectionViolation(
                f"write to erased record {key} blocked by tombstone epoch "
                f"{tomb.epoch}"
            )

        # Invariant 2: epoch fencing. A write derived from a pre-tombstone
        # snapshot cannot resurrect even an EXPIRED record's stale body.
        if tomb is not None and derived_from_epoch < tomb.epoch:
            raise ResurrectionViolation(
                f"stale write to {key}: derived_from_epoch="
                f"{derived_from_epoch} precedes tombstone epoch {tomb.epoch}"
            )

        epoch = self._next_epoch()
        self._bodies[key] = body
        self._tombstones.pop(key, None)
        return epoch

    def read(self, scope_id: str, record_id: str) -> tuple[Optional[str], AbsenceKind]:
        key = (scope_id, record_id)
        if key in self._bodies:
            return self._bodies[key], AbsenceKind.EXPIRED  # present; kind unused
        tomb = self._tombstones.get(key)
        if tomb is not None:
            return None, tomb.kind
        return None, AbsenceKind.NEVER_EXISTED

    def forget(self, scope_id: str, record_id: str, kind: AbsenceKind) -> int:
        key = (scope_id, record_id)
        epoch = self._next_epoch()
        if kind is AbsenceKind.ERASED:
            # Erasure is terminal: never downgrade an existing ERASED tombstone.
            existing = self._tombstones.get(key)
            if existing is not None and existing.kind is AbsenceKind.ERASED:
                return existing.epoch
        self._bodies.pop(key, None)
        self._tombstones[key] = Tombstone(scope_id, record_id, kind, epoch)
        return epoch


def agent_heal(store: MemoryStore, scope_id: str, record_id: str,
               cached_body: str, cache_fetched_epoch: int) -> None:
    """Agent-side healing heuristic: rebuild only EXPIRED records from cache."""
    body, absence = store.read(scope_id, record_id)

    if absence is AbsenceKind.ERASED:
        # Hard wall: purge cache, do not heal, do not retry with new epoch.
        raise ResurrectionViolation(
            f"refusing to heal {scope_id}/{record_id}: record was ERASED; "
            f"cached copy must be purged, not re-written"
        )

    if body is None and absence is AbsenceKind.EXPIRED:
        store.write(scope_id, record_id, cached_body,
                    derived_from_epoch=cache_fetched_epoch)
        return

    if body is not None:
        return  # already present; no action


if __name__ == "__main__":
    store = MemoryStore()
    e0 = store.write("proj-7a", "r-882", "PII: subject=...", derived_from_epoch=0)

    # Agent caches the body at epoch e0, then RTBF erasure fires.
    store.forget("proj-7a", "r-882", AbsenceKind.ERASED)

    # Naive heal from stale cache must fail, not resurrect.
    try:
        agent_heal(store, "proj-7a", "r-882", "PII: subject=...", e0)
    except ResurrectionViolation as exc:
        print(f"blocked: {exc}")

    # Even a direct stale write is fenced by epoch.
    try:
        store.write("proj-7a", "r-882", "PII: subject=...", derived_from_epoch=e0)
    except ResurrectionViolation as exc:
        print(f"blocked: {exc}")
