# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-forget-tool-call-from-resurrecting-deleted-memory-through-the-retrieval-index.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-forget-tool-call-from-resurrecting-deleted-memory-through-the-retrieval-index.warrant.json
# Markdown SHA-256:   dfa99df1cce578ae235c7075e6995d5be9e951c8e24d2269c9bca6a134d9994b
# Code AST SHA-256:   843256b8758e6fd849b1270d9dc613b7df57bc4cb88f67ec40c4134b31426c1c
# Verified Classes:   ForgetInvariantViolation, MemorySubsystem
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ForgetInvariantViolation(RuntimeError):
    """Raised when a recall surfaces content from an id that was already forgotten."""
    pass


class MemorySubsystem:
    def __init__(self):
        self.records = {}
        self.tombstones = {}          # id -> epoch at which it was forgotten
        self.epoch = 0

    def forget(self, mem_id: str) -> int:
        self.epoch += 1
        self.records.pop(mem_id, None)
        self.tombstones[mem_id] = self.epoch
        return self.epoch

    def recall(self, mem_id: str, observed_epoch: int) -> str:
        # Read-time tombstone filter: the invariant lives here, not in forget().
        if mem_id in self.tombstones:
            tomb_epoch = self.tombstones[mem_id]
            if observed_epoch < tomb_epoch:
                raise ForgetInvariantViolation(
                    f"recall of {mem_id} at epoch {observed_epoch} predates "
                    f"tombstone epoch {tomb_epoch}; result is poisoned"
                )
            raise ForgetInvariantViolation(
                f"{mem_id} is tombstoned at epoch {tomb_epoch}; must not be served"
            )
        return self.records.get(mem_id, "")


def guarded_recall_after_forget(mem: MemorySubsystem, mem_id: str,
                                recall_epoch: int) -> str:
    try:
        return mem.recall(mem_id, recall_epoch)
    except ForgetInvariantViolation as exc:
        # Do not fall back to heuristics; surface the gap for escalation.
        raise ForgetInvariantViolation(
            f"forgetting guarantee broken for {mem_id}: {exc}"
        ) from exc
