# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-treats-a-memory-forget-acknowledgement-as-a-cross-session-tombstone-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-treats-a-memory-forget-acknowledgement-as-a-cross-session-tombstone-invariant.warrant.json
# Markdown SHA-256:   1c51210602545fd8d8a701d2b3b23ec807cc1a36c7cbbcaa18cf4a6837d54b34
# Code AST SHA-256:   4baba2989a49496b014021938f9a350e485c556c60cfb2a9392e6b23d19fa3ed
# Verified Classes:   TombstoneInvariantError, MemoryRecord, Tombstone, MemoryClient
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class TombstoneInvariantError(RuntimeError):
    """Raised when a read returns a record that a prior forget should have hidden."""


@dataclass
class MemoryRecord:
    key: str
    value: str
    write_epoch: int
    retrieved_at: float = field(default_factory=time.time)


@dataclass
class Tombstone:
    key: str
    forget_epoch: int
    reason: str


class MemoryClient:
    """Models a backend where forget is eventually consistent across replicas."""

    def __init__(self, replica_lag_epochs: int = 2):
        self._records: dict[str, MemoryRecord] = {}
        self._tombstones: dict[str, Tombstone] = {}
        self._epoch = 0
        self._replica_lag = replica_lag_epochs

    def write(self, key: str, value: str) -> int:
        self._epoch += 1
        self._records[key] = MemoryRecord(key, value, self._epoch)
        return self._epoch

    def forget(self, key: str, reason: str) -> dict:
        self._epoch += 1
        self._tombstones[key] = Tombstone(key, self._epoch, reason)
        # Intent acknowledged; deletion visibility lags on replicas.
        return {"status": "ok", "deleted": 1, "epoch": self._epoch}

    def read(self, key: str, reader_epoch: Optional[int] = None) -> Optional[MemoryRecord]:
        # A lagging replica can still surface records tombstoned after reader_epoch.
        visible_epoch = self._epoch - self._replica_lag
        rec = self._records.get(key)
        if rec is None:
            return None
        if rec.write_epoch <= visible_epoch:
            return rec
        return None


def safe_recall(client: MemoryClient, key: str, reader_epoch: int,
                tombstones: dict[str, Tombstone]) -> Optional[MemoryRecord]:
    rec = client.read(key, reader_epoch=reader_epoch)
    if rec is None:
        return None
    tomb = tombstones.get(key)
    if tomb is not None and rec.write_epoch <= tomb.forget_epoch:
        raise TombstoneInvariantError(
            f"read of '{key}' returned epoch {rec.write_epoch} which is at or "
            f"below tombstone epoch {tomb.forget_epoch}; stale replica or "
            f"resumed peer leaked a forgotten record"
        )
    return rec


def correct_and_forget(client: MemoryClient, bad_key: str, corrected_value: str,
                       tombstones: dict[str, Tombstone]) -> int:
    ack = client.forget(bad_key, reason="hallucinated intermediate conclusion")
    tombstones[bad_key] = Tombstone(bad_key, ack["epoch"], "hallucinated")
    # Shadow the forgotten key so stale reads cannot win by recency.
    shadow_key = f"{bad_key}::override"
    epoch = client.write(shadow_key, corrected_value)
    # Verify no lagging read can resurrect the forgotten record.
    leaked = client.read(bad_key, reader_epoch=ack["epoch"])
    if leaked is not None and leaked.write_epoch <= ack["epoch"]:
        raise TombstoneInvariantError(
            f"post-forget read resurrected '{bad_key}' at epoch {leaked.write_epoch}"
        )
    return epoch
