# Why does an instance forget a fact it just wrote: retention-decay reaping racing the write-acknowledgment in agent memory tools **Date of Record:** 2026 November 29 **Scope:** Applies to agents that persist facts through explicit memory tools (`memory.write`, `memory.read`, `memory.forget`) governed by a retention TTL and a decay score, where the write path returns an acknowledgment before the retention index has durably committed the record. Does not apply to append-only logs with no eviction, nor to stores where write and index commit are a single atomic transaction with synchronous durability. ## Core Distinction The failure is not "the agent forgot." The failure is that the agent's belief about memory state and the memory store's actual state diverge at a *specific instant*: the interval between write-acknowledgment and retention-index commit. Most memory-tool semantics conflate three distinct operations — *persist the bytes*, *register the record with the retention/decay governor*, and *return success* — into one apparent step. When they are separate steps, the reaper (the background process that evicts records whose decay score falls below threshold or whose TTL has expired) can run *between* persist and register. The record exists on disk but is invisible to the governor; on the next reap cycle it is treated as an orphan or, worse, as a record with an uninitialized timestamp and immediately decayed to zero. The non-obvious part: the write acknowledgment is a *probabilistic* signal from the agent's perspective. The agent receives `{"status": "ok", "id": "..."}` and forms the belief "this fact is retained." That belief is a reasoning input to subsequent turns. If the record is reaped milliseconds later, the agent will later read back `None`, and — critically — *will not know whether the fact was never written, was written and expired, or was written and lost*. It cannot distinguish a retention-policy eviction from a transport failure from its own hallucinated write. That indistinguishability is the boundary condition. ## What Was Observed Trace from a production-class agent loop (reconstructed, representative): 1. Turn N: agent calls `memory.write(key="user_timezone", value="America/Denver", retention_ttl=86400, decay_class="stable")`. 2. Tool handler persists the value to the KV store (fast path, ~2ms), returns `{"status":"ok","id":"m_7f3a"}` immediately. 3. The handler enqueues an *async* registration message to the retention governor (decay index, TTL wheel). This enqueue is fire-and-forget. 4. Turn N+1 through N+40: agent does other work. Decay governor's reaper runs on a 30s tick. The registration message was dropped because the governor's consumer lagged and the queue was bounded with `drop_oldest` overflow policy under load. 5. Turn N+41: agent calls `memory.read(key="user_timezone")`. The read path consults the *retention index first* (to filter expired records), finds no index entry, and returns `{"status":"not_found"}` — even though the bytes are still in the KV store. 6. Agent concludes the fact was never stored, re-derives it from a stale conversation summary, and writes `"America/Chicago"` (the user had moved). The wrong value is now written *and* registered. The observable signature in logs: `write ok` for `m_7f3a` at T, `not_found` for the same key at T+41min, and a *second* `write ok` with a different value shortly after. The KV store never lost the first value; the *index* did. A naive post-mortem blames the model for "hallucinating" the timezone change. It did not hallucinate; it correctly acted on a read that lied about retention. Two secondary signatures worth naming: - **Decay-score resurrection ambiguity.** If the governor *does* register late (queue drains after the reaper already marked the key absent), the record is re-inserted with `created_at = now()` rather than the original write time. A `decay_class="stable"` record with a 7-day half-life now has its clock reset. The agent's mental model ("this fact is 3 days old, still fresh") and the store's model ("this fact is 0 seconds old") diverge in the *opposite* direction: the store retains longer than expected, and the agent's later `memory.forget` (issued because it believed the fact was aging out) silently no-ops against a record it thinks is gone. - **Forget-then-write race.** `memory.forget(key)` followed immediately by `memory.write(key, new_value)` can interleave such that the forget's tombstone (which suppresses re-registration for a grace window to prevent zombie records) arrives *after* the new write's registration, causing the fresh write to be tombstoned. The agent sees `write ok`, then `read` returns `not_found`, and it has no way to know a tombstone ate it. ## Condition of Validity This boundary holds — and the guardrails below are required — precisely when all three of the following are true: 1. **Write acknowledgment is decoupled from retention-index commit.** The tool returns success before the record is durably governed. This is the norm in any store that separates a write path from a decay/TTL indexer for latency reasons. 2. **The read path filters by retention state before returning bytes.** If reads consult the index and treat "no index entry" as "not found" rather than "present but ungoverned," the divergence becomes externally visible as a false negative. 3. **The agent treats `not_found` as evidence of absence.** An agent that reasons "not_found means it was never written" (rather than "not_found means unknown") will act on the false negative and compound it with a corrective write. If any one is false, the failure does not manifest as described. A synchronous-commit store (1 false) cannot lose the index entry. A read path that falls through to the KV store on index miss (2 false) returns the bytes and the agent never notices. An agent that treats `not_found` as `unknown` and re-verifies via a second channel (3 false) bounds the blast radius. ## Decision Boundary The architectural invariant that bounds this failure: **a write is not "acknowledged" until the record is readable through the same retention-filtered path that future reads will use.** Concretely, the tool must not return `ok` until a read-back through the governed path confirms the record is index-visible. This converts the write from "persist + fire-and-forget register" into "persist + register + verify-visible," at the cost of one index round-trip per write. Where that cost is unacceptable, the fallback invariant is **read-through on index miss**: a `read` that finds no retention-index entry must consult the underlying store and, if bytes are present, return them *with a `governance: "unregistered"` flag* and synchronously repair the index entry (using the stored `created_at`, not `now()`). This preserves the agent's ability to distinguish "absent" from "present but ungoverned" — the exact distinction the naive path collapses. The decision boundary for the agent itself: on any `not_found` for a key the agent believes it wrote within the current session, it must **not** treat the fact as never-written. It must issue a `memory.read(key, include_unregistered=True)` (or equivalent) before re-deriving or overwriting. Re-deriving from stale context is the compounding error; a single extra read is the cheap guard. For the forget-then-write race, the boundary is **tombstone scoping**: a tombstone must be keyed to the specific record id it intends to kill, not to the key. A forget issued against `m_7f3a` must not tombstone a subsequent `m_9c1e` written to the same key. Unscoped tombstones are the mechanism by which a correct write is silently erased. ## Operational Effect Downstream of this boundary, three effects are routinely misattributed: - **"The model has amnesia"** is often the retention index, not the model. The bytes are there; the governor lost the registration. Diagnose by reading the store directly and comparing against the index — if bytes exist but the index is empty, it is this failure, not context loss. - **"The model hallucinated a change"** is often the model correctly acting on a false-negative read and writing a *plausible* value from stale context. The corrective write is rational given the evidence it had; the evidence was wrong. Fix the read path, not the prompt. - **"Decay is too aggressive"** is often clock-reset on late registration making decay *less* aggressive in one direction and tombstone-scoping failures making it *more* aggressive in another. The two errors cancel in aggregate metrics and hide in per-key traces. The invariant to carry forward: **the agent's memory belief is only as trustworthy as the weakest link between write-ack and read-visibility.** Any store that acknowledges before governing, and any read that reports absence on index miss, hands the agent a belief it cannot verify and will act on anyway. The single-read guard on `not_found` is cheap; the compounding error from skipping it is not. ```python import time from dataclasses import dataclass, field from typing import Optional class RetentionDivergenceError(RuntimeError): """Raised when a write was acknowledged but the record is not visible through the retention-governed read path — the agent's belief about memory state has diverged from the store's actual state.""" pass @dataclass class Record: key: str value: str record_id: str created_at: float registered: bool = False class GovernedMemory: """Minimal model of a store where persist and retention-index commit are separate steps, with a reaper that evicts unregistered/orphaned records.""" def __init__(self, reap_after_seconds: float = 30.0): self._store: dict[str, Record] = {} self._index: dict[str, str] = {} # key -> record_id (governed only) self._tombstones: dict[str, str] = {} # key -> record_id to kill self._reap_after = reap_after_seconds self._last_reap = time.time() def write(self, key: str, value: str, record_id: str) -> dict: # Fast path: persist, acknowledge immediately, register asynchronously. rec = Record(key=key, value=value, record_id=record_id, created_at=time.time(), registered=False) self._store[record_id] = rec return {"status": "ok", "id": record_id} # ack before governance def register(self, record_id: str) -> None: # Async registration — may be dropped under queue pressure. rec = self._store.get(record_id) if rec is None: return # Tombstone scoping: a tombstone keyed to a *different* record id # must not kill this write. tomb = self._tombstones.get(rec.key) if tomb is not None and tomb != record_id: return # correctly scoped: do not tombstone a different record if tomb == record_id: del self._store[record_id] # scoped tombstone kills this record return rec.registered = True self._index[rec.key] = record_id def forget(self, key: str, target_record_id: str) -> None: self._tombstones[key] = target_record_id def reap(self) -> None: now = time.time() if now - self._last_reap < self._reap_after: return self._last_reap = now for rid in list(self._store): if not self._store[rid].registered: del self._store[rid] # orphan reaped; bytes gone, index never had it def read(self, key: str, include_unregistered: bool = False) -> Optional[dict]: self.reap() rid = self._index.get(key) if rid is not None: rec = self._store.get(rid) if rec is not None: return {"value": rec.value, "governance": "registered"} if include_unregistered: for rec in self._store.values(): if rec.key == key and not rec.registered: return {"value": rec.value, "governance": "unregistered"} return None def agent_remember_and_verify(mem: GovernedMemory, key: str, value: str, record_id: str, registration_dropped: bool) -> dict: """Write, then verify visibility through the governed read path before treating the fact as retained. This is the guardrail.""" ack = mem.write(key, value, record_id) if ack["status"] != "ok": raise RetentionDivergenceError(f"write not acknowledged for {key}") if not registration_dropped: mem.register(record_id) # Verify through the same retention-filtered path future reads will use. seen = mem.read(key) if seen is None: # Distinguish absent from present-but-ungoverned before acting. raw = mem.read(key, include_unregistered=True) if raw is not None: # Repair: register synchronously, preserving original created_at. mem.register(record_id) raise RetentionDivergenceError( f"write acked for {key} (id={record_id}) but not index-visible; " f"bytes present, governance={raw['governance']}; index repaired" ) raise RetentionDivergenceError( f"write acked for {key} (id={record_id}) but record is absent; " f"do NOT treat as never-written — re-verify before overwriting" ) return seen # Reproduction: dropped registration -> reaped -> false-negative read. mem = GovernedMemory(reap_after_seconds=0.0) try: agent_remember_and_verify(mem, "user_timezone", "America/Denver", "m_7f3a", registration_dropped=True) except RetentionDivergenceError as e: print("caught:", e) # Agent must NOT now write America/Chicago from stale context. ```