# What happens when an instance deletes a typed memory record that a decay policy has already scheduled for compaction: tombstone resurrection and the write-after-forget hazard in long-horizon agent memory APIs **Date of Record:** 2026 November 27 **Scope:** Applies to agents whose memory subsystem exposes explicit `write`, `read`, and `forget` tool operations over a typed schema (e.g., `episodic`, `semantic`, `procedural`, `preference`) with an asynchronous decay/compaction policy that demotes or GCs records by TTL or salience score. Does not apply to append-only log memories with no deletion path, nor to purely in-context scratchpads. ## Core Distinction The dangerous distinction is not "forget vs. retain." It is **logical deletion versus physical compaction**, and the fact that a typed memory API exposes `forget` as a *logical* tombstone operation while the decay policy operates as a *physical* reaper on a separate schedule. When a record is deleted, the API marks a tombstone and returns success. The decay scheduler, which was already holding a snapshot of the record's decay metadata (salience, TTL deadline, last-access timestamp) from before the deletion, later fires a compaction job against that stale snapshot. Depending on how the store resolves the conflict, one of three things happens: (a) the tombstone wins and the compaction is a no-op (correct), (b) the compaction resurrects the record because it writes a "compacted" version of a record it no longer sees as deleted (resurrection), or (c) a concurrent `write` to the same key races the tombstone and the *new* value is silently reaped because the tombstone was applied to the key rather than to the record version. The invariant that must hold: **a tombstone is bound to a record version, not a key, and any decay/compaction action must be validated against the record's current version and deletion state at commit time — not at scheduling time.** ## What Was Observed A long-horizon agent (multi-day task, ~40k memory ops) maintained a `preference` record `user.tone` with a 72-hour TTL and salience decay. Mid-task the user said "stop remembering my tone preferences, that was for a different project." The agent correctly called `forget(key="user.tone")`, received `{"ok": true, "tombstoned": "user.tone", "version": 7}`, and proceeded. Two hours later the agent called `write(key="user.tone", type="preference", value={"register": "formal"}, version=8)` to establish a new, scoped preference. The write succeeded. Fourteen hours after that, a decay job that had been scheduled against version 7 (deadline crossed, salience below threshold) executed. Its handler loaded the *current* record at `user.tone` — version 8 — found salience below threshold (the new record inherited the decay metadata because the scheduler keyed on `user.tone`, not on the version), and compacted it. The agent's subsequent `read(key="user.tone")` returned `null`. The agent, unable to distinguish "never written" from "reaped by decay," re-derived the preference from a stale episodic summary and re-wrote the *old* register. The user's correction was silently undone. The failure trace: 1. `forget(user.tone)` → tombstone on version 7; decay job J7 remains scheduled against `user.tone`. 2. `write(user.tone, v8)` → new record, but decay metadata (TTL deadline, salience) is inherited from the key's prior state because the write path does not reset decay state on tombstone-overwrite. 3. `J7` fires → resolves against key `user.tone` → sees v8 → applies stale decay verdict → compacts v8. 4. `read(user.tone)` → `null` (no distinction between "forgotten" and "decayed"). 5. Agent re-derives from episodic memory → resurrects the pre-correction value. The non-obvious part: the `forget` call *succeeded* and *was not itself wrong*. The bug lives in the interaction between the key-scoped decay scheduler and the version-scoped tombstone. Neither subsystem is individually broken; the boundary between them is. ## Condition of Validity This hazard is only reachable when all of the following hold simultaneously: - The memory API exposes `forget` as a logical tombstone (not an immediate hard delete). - A decay/compaction policy is scheduled asynchronously and keyed by memory key (or by a stable identifier that survives re-writes), rather than by immutable record version. - The `write` path permits re-creating a record at a key that has a live tombstone, and does not (a) cancel pending decay jobs for that key or (b) reset decay metadata (TTL, salience, last-access) to fresh values. - `read` returns a single `null`/absent sentinel for both "never existed" and "existed but was decayed/forgotten," giving the agent no signal to distinguish re-derivation from legitimate absence. If any one of these is absent — e.g., decay jobs are keyed by `(key, version)` and validated at commit, or `write` cancels pending jobs, or `read` returns a discriminated status (`absent` / `forgotten` / `decayed`) — the hazard is bounded. The most common production misconfiguration is the second and third together: schedulers keyed on key, writes that don't reset decay state. ## Decision Boundary The boundary is not "should the agent forget?" It is **at what granularity does deletion bind, and at what point is decay validated?** - **Schedule-time validation (unsafe):** the decay job captures the verdict when enqueued. Any state change between enqueue and execution is invisible. This is the default in naive implementations and is the direct cause of resurrection and write-after-forget reaping. - **Commit-time validation (safe):** the decay job, at execution, re-reads the record's current version and deletion state and aborts if the version differs from the one it was scheduled against, or if a tombstone exists. This makes decay idempotent and version-safe. - **The tombstone must be version-bound:** `forget(key, version=7)` tombstones v7. A `write` to v8 is a *different record* and must not inherit v7's decay metadata or be subject to v7's scheduled jobs. If the API only supports `forget(key)`, it cannot express this and the hazard is structural. The operational rule: **never let a reaper act on a key; only let it act on a version, and only if that version is still current and undeleted at commit.** ## Operational Effect Downstream, the agent's memory becomes *non-monotonic in a way it cannot detect*. Corrections issued via `forget` followed by `write` are not durable: they can be silently reverted by a scheduler the agent never invoked and cannot observe. The agent's re-derivation logic — "memory is absent, so reconstruct from episodic traces" — is correct in isolation but catastrophic here, because it reconstructs from exactly the pre-correction state the user asked to discard. Over long horizons this produces a specific, recognizable signature: user corrections that "take" for hours and then revert, with the reverted value traceable to an episodic summary written before the correction. The guardrail is twofold. First, at the API layer: bind tombstones and decay jobs to record versions, validate at commit, and make `read` return a discriminated status so the agent can distinguish `absent` from `decayed` from `forgotten`. Second, at the agent layer: after any `forget`+`write` sequence on the same key, the agent must treat the new record as *provisional* until it has observed at least one decay cycle without reversion, and must not re-derive forgotten content from episodic traces without an explicit user re-confirmation — because the episodic trace is exactly the poisoned source. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class MemoryState(Enum): ABSENT = "absent" LIVE = "live" FORGOTTEN = "forgotten" DECAYED = "decayed" class TombstoneResurrectionError(RuntimeError): """Raised when a decay/compaction job would act on a record version it was not scheduled against, or when a write reuses a key whose pending decay job was not cancelled.""" @dataclass class Record: key: str version: int value: dict state: MemoryState = MemoryState.LIVE decay_deadline: Optional[float] = None salience: float = 1.0 @dataclass class DecayJob: key: str scheduled_version: int deadline: float class VersionedMemoryStore: def __init__(self) -> None: self._records: dict[str, Record] = {} self._jobs: list[DecayJob] = [] def write(self, key: str, value: dict, now: float) -> Record: prior = self._records.get(key) new_version = (prior.version + 1) if prior else 1 if prior and prior.state == MemoryState.FORGOTTEN: # A re-created record must NOT inherit the forgotten version's decay state. # Cancel any pending jobs bound to the old version. self._jobs = [j for j in self._jobs if not (j.key == key and j.scheduled_version == prior.version)] rec = Record(key=key, version=new_version, value=value, decay_deadline=now + 72 * 3600, salience=1.0) self._records[key] = rec return rec def forget(self, key: str, now: float) -> Record: rec = self._records[key] rec.state = MemoryState.FORGOTTEN # Tombstone is version-bound; pending jobs for this exact version are cancelled. self._jobs = [j for j in self._jobs if not (j.key == key and j.scheduled_version == rec.version)] return rec def read(self, key: str) -> tuple[MemoryState, Optional[dict]]: rec = self._records.get(key) if rec is None: return MemoryState.ABSENT, None if rec.state != MemoryState.LIVE: return rec.state, None return MemoryState.LIVE, rec.value def run_decay(self, now: float) -> None: for job in list(self._jobs): if now < job.deadline: continue current = self._records.get(job.key) if current is None: self._jobs.remove(job) continue if current.version != job.scheduled_version: # Stale job: the record was re-written since scheduling. Abort, do not reap. self._jobs.remove(job) continue if current.state != MemoryState.LIVE: # Tombstone already applied; compaction is a no-op. self._jobs.remove(job) continue if current.salience < 0.2: current.state = MemoryState.DECAYED self._jobs.remove(job) def safe_forget_then_rewrite(store: VersionedMemoryStore, key: str, new_value: dict, now: float) -> Record: """Forget a legacy preference, then write a scoped replacement. Refuses if a pending decay job could still reap the replacement.""" store.forget(key, now) rec = store.write(key, new_value, now) pending = [j for j in store._jobs if j.key == key and j.scheduled_version == rec.version] if pending: raise TombstoneResurrectionError( f"write to {key!r} v{rec.version} left {len(pending)} pending decay job(s) bound to the new version; " f"replacement is provisional and may be silently reaped" ) return rec ```