# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tombstone-resurrection-when-a-forget-call-races-a-background-distillation-pass-in-scoped-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tombstone-resurrection-when-a-forget-call-races-a-background-distillation-pass-in-scoped-agent-memory.warrant.json
# Markdown SHA-256:   30cf4801b7de35d8447e2553652b4b717f9d7cfa642e458a43bc134bf3442292
# Code AST SHA-256:   c08b3643d2f8f2e79e4702032f0ebba00c82ae0e293d524a617105b4afaf5e59
# Verified Classes:   StaleEpochError, VerificationIncompleteError, ScopeEpoch, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleEpochError(RuntimeError):
    """Raised when a derived-memory write is fenced by a newer tombstone epoch."""


class VerificationIncompleteError(RuntimeError):
    """Raised when a forget call cannot prove absence of derived records."""


@dataclass
class ScopeEpoch:
    scope: str
    epoch: int

    def advance(self) -> int:
        self.epoch += 1
        return self.epoch


class MemoryStore:
    def __init__(self) -> None:
        self.episodic: dict[str, dict] = {}
        self.semantic: dict[str, dict] = {}
        self.tombstones: dict[str, int] = {}
        self.scopes: dict[str, ScopeEpoch] = {}

    def _scope(self, scope: str) -> ScopeEpoch:
        return self.scopes.setdefault(scope, ScopeEpoch(scope, 0))

    def write_episodic(self, scope: str, memory_id: str, text: str) -> int:
        epoch = self._scope(scope).epoch
        self.episodic[memory_id] = {"scope": scope, "text": text, "epoch": epoch}
        return epoch

    def forget(self, scope: str, memory_id: str) -> dict:
        tomb_epoch = self._scope(scope).advance()
        self.tombstones[memory_id] = tomb_epoch
        self.episodic.pop(memory_id, None)
        # Verification must run after tombstone commit and must reject any
        # derived row whose source_epoch is at or below the tombstone epoch.
        for sid, row in self.semantic.items():
            if row["source_memory_id"] == memory_id and row["source_epoch"] <= tomb_epoch:
                raise VerificationIncompleteError(
                    f"derived record {sid} survived forget of {memory_id} "
                    f"(source_epoch={row['source_epoch']} <= tombstone_epoch={tomb_epoch})"
                )
        return {"deleted": True, "verified": True, "tombstone_epoch": tomb_epoch}

    def distill_write(self, scope: str, source_memory_id: str, source_epoch: int, summary: str) -> None:
        current = self._scope(scope).epoch
        tomb = self.tombstones.get(source_memory_id, -1)
        # Write-time fence: both the scope epoch and any source tombstone must
        # permit this derived write, evaluated inside the insert transaction.
        if source_epoch < current or source_epoch <= tomb:
            raise StaleEpochError(
                f"refusing derived write for {source_memory_id}: "
                f"source_epoch={source_epoch}, scope_epoch={current}, tombstone_epoch={tomb}"
            )
        self.semantic[f"sem::{source_memory_id}::{source_epoch}"] = {
            "source_memory_id": source_memory_id,
            "source_epoch": source_epoch,
            "summary": summary,
        }


# Reproduction of the observed race:
store = MemoryStore()
epoch = store.write_episodic("tenant-a", "mem-1", "user's home address is ...")
# Distillation worker reads at epoch 6 (simulated as the pre-forget epoch).
snapshot_epoch = epoch
# Forget commits and advances the scope epoch.
store.forget("tenant-a", "mem-1")
# Worker now attempts to commit its stale summary.
try:
    store.distill_write("tenant-a", "mem-1", snapshot_epoch, "paraphrase of address")
except StaleEpochError as exc:
    print(f"fence held: {exc}")
