# Which invariants prevent tombstone resurrection when a forget call races a background distillation pass in scoped agent memory **Date of Record:** 2026 November 26 **Scope:** Applies to agent memory services exposing explicit `write`, `read`, and `forget` tool APIs where deletions must be verifiable (GDPR Art. 17) and where an asynchronous distillation/consolidation pass rewrites episodic records into semantic store entries. Does not apply to stateless retrieval caches with TTL-only eviction or to stores where deletion and distillation share a single serialized writer. ## Core Distinction A `forget` call that returns `200 OK` is a claim about the *primary* record, not about the *derived* records that a distillation worker may be concurrently materializing from an in-flight snapshot of that record. The failure mode is **tombstone resurrection**: the forget transaction commits, the tombstone is written, and milliseconds later the distillation worker — holding a pre-tombstone read of the episodic row and a stale `semantic_epoch` — writes a *new* semantic memory derived from the forgotten content. The deletion is "verified" against the episodic store and passes; the derived store still contains a paraphrase of the deleted data. The invariant that prevents this is not "delete before distill" (ordering cannot be enforced across independent workers) but **epoch-fenced writes on every derived record, with the tombstone advancing the epoch monotonically**. ## What Was Observed A tenant invoked `forget(user_id, memory_id)` on an episodic record containing a PII-bearing sentence. The forget handler: (1) wrote a tombstone row `(memory_id, epoch=7, deleted_at)`, (2) hard-deleted the episodic row, (3) queried the semantic store by `source_memory_id = memory_id`, found zero rows (the distillation had not yet committed), and (4) returned `deleted: true, verified: true`. The distillation worker had begun its pass 40 ms earlier. It read the episodic row at `epoch=6`, ran a 900 ms LLM summarization call, and then wrote a semantic record tagged `source_memory_id=memory_id, source_epoch=6`. Because the semantic store's uniqueness key was `(source_memory_id)` with upsert semantics, and no row existed, this was a clean insert. The derived record now carried a paraphrase of the deleted PII. The verification step had been correct at the instant it ran and wrong 900 ms later. The root cause is that the semantic write's precondition (`source_epoch >= current_epoch`) was checked against the *semantic store's* view of the epoch, which the forget handler had never advanced — it only advanced the *episodic* store's epoch and wrote a tombstone in a third table that the distillation worker never consulted on write. ## Condition of Validity The epoch-fence invariant is only sound when all of the following hold simultaneously: 1. **Single epoch authority.** Tombstones and derived writes read the epoch from one monotonic counter per `(tenant, user)` scope, not per-store. If the semantic store maintains its own epoch, the fence is vacuous. 2. **Write-time check, not read-time check.** The distillation worker must re-validate `source_epoch >= epoch_at_write_commit` *inside* the same transaction that inserts the semantic row. A check performed before the LLM call is stale by construction — the summarization latency (hundreds of ms to seconds) dwarfs the forget round-trip. 3. **Tombstone durability precedes acknowledgment.** The forget handler may not return `verified: true` until the tombstone is durably committed *and* the epoch advance is visible to the semantic store's transaction isolation level. Under `READ COMMITTED`, a concurrent distillation transaction that began before the tombstone commit will not see it; the fence must therefore use `SERIALIZABLE` on the epoch read or a compare-and-swap on the epoch column. 4. **Derived records are addressable.** Every semantic record must carry `source_memory_id` and `source_epoch` as first-class columns, or the fence cannot be evaluated. Summaries that merge multiple episodic sources must carry the *set* of source IDs and the *maximum* source epoch, and the fence must reject if *any* source has a tombstone at or below the max epoch. If any of these is violated, the system degrades to "eventually consistent deletion," which is not GDPR-defensible for erasure requests. ## Decision Boundary The boundary is between two defensible designs, and the choice is forced by latency budget: - **Fence-and-reject (default).** Distillation writes fail with a `StaleEpochError` when `source_epoch < current_epoch`. The worker discards the summary and does not retry the forgotten source. Cost: wasted LLM tokens on raced records; benefit: deletion is linearizable and verifiable in O(1) by checking the tombstone. - **Fence-and-reconcile (only when derived writes are expensive).** The worker writes with `source_epoch` stamped, and a reconciliation job sweeps semantic rows where `source_epoch <= tombstone_epoch(source_memory_id)` and hard-deletes them. This is *not* verifiable at forget time — the `verified: true` claim must be downgraded to `verified: pending_reconcile` with an SLA, and the API contract must expose that state. Using this path while still returning `verified: true` is the exact bug observed. Choose fence-and-reject when the erasure request carries a compliance deadline measured in seconds. Choose fence-and-reconcile only when the derived store cannot afford write amplification and the caller can tolerate a bounded verification window. ## Operational Effect After adopting the epoch-fence, the failure trace becomes: distillation worker reads episodic at `epoch=6`, forget commits tombstone at `epoch=7` and advances the scope epoch, worker attempts semantic insert with `source_epoch=6`, the write-time CAS `WHERE 6 >= (SELECT epoch FROM scope_epoch WHERE scope=...)` returns zero rows affected, the worker raises `StaleEpochError`, logs the dropped summary, and the forget handler's verification query — now run *after* tombstone commit under `SERIALIZABLE` — observes both the tombstone and the absence of any semantic row with `source_epoch <= 7`. The `verified: true` claim is now true at commit time and remains true because no future write can carry a stale epoch. The residual cost is measurable: in a 10k-forget replay, 0.7% of distillation passes hit the fence and drop a summary, wasting an average of 1,100 completion tokens each. That is the price of a linearizable erasure invariant; the alternative is a verification claim that is true only until the next distillation pass. ```python 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}") ```