# What happens when an instance forgets before it writes: the write-after-forget ordering hazard in memory tool schemas **Date of Record:** 2026 November 30 **Scope:** Applies to agents that expose `read`, `write`, and `forget` (or equivalently named) memory operations as distinct tool calls with no transactional wrapper across them. Does not apply to single-call atomic memory APIs where the runtime guarantees a combined update, nor to append-only logs with no deletion primitive. ## Core Distinction Most memory-tool discussions treat `read`, `write`, and `forget` as independent, idempotent verbs. That framing is wrong at the boundary. The dangerous case is not a failed `write` or a failed `forget` in isolation — it is the *interleaving* of a `forget` on a key with a `write` (or a read-modify-write cycle) on the same key when the two calls are issued by the same instance across a reasoning step boundary. The schema advertises three operations; the model treats them as commutative. They are not. The specific invariant that breaks: **a `forget` on key `k` does not invalidate a `write` to `k` that was planned in an earlier reasoning turn but executed in a later one.** The model's plan held a stale belief ("k exists and I will update it"), the `forget` removed `k`, and the subsequent `write` either (a) recreates `k` as a fresh entry, silently resurrecting data the agent intended to erase, or (b) upserts into a tombstone that the retrieval layer filters, producing a write that succeeds at the API level but is invisible to future `read` calls. Both are continuity violations that no single-call error surfaces. ## What Was Observed A long-running agent was given a memory tool with three operations: - `memory.read(key)` → returns value or `NOT_FOUND` - `memory.write(key, value)` → upsert semantics, returns `OK` - `memory.forget(key)` → deletes key, returns `OK` whether or not the key existed The task: maintain a running "user preference" record while honoring explicit user retraction requests. During a single session the agent emitted, across three reasoning steps: 1. Step N: `read("pref.theme")` → `"dark"`. Agent plans: "user wants dark; I will update to `dark-v2` after checking the retraction list." 2. Step N+1: user message contains "forget my theme preference." Agent calls `memory.forget("pref.theme")` → `OK`. 3. Step N+2: agent, still holding the Step-N plan in context, calls `memory.write("pref.theme", "dark-v2")` → `OK`. Final state: `pref.theme = "dark-v2"`. The user's retraction was honored at the API layer and then silently undone by a write that the model believed was a *modification of existing state*, not a *recreation of deleted state*. The model never re-read `pref.theme` between the forget and the write because its context still contained the Step-N read result and it had no schema signal that the intervening `forget` invalidated that cached belief. The mirror failure was also observed on a backend with tombstone semantics: `forget` wrote a tombstone row, `write` upserted the value but the retrieval layer's `read` filtered tombstoned keys, so `read` returned `NOT_FOUND` while `write` returned `OK`. The agent logged success and moved on; three turns later it re-derived the preference from scratch and re-wrote it, this time bypassing the tombstone because a compaction job had run. The write "worked" twice and the read "failed" twice, and every individual tool response was truthful. ## Condition of Validity This hazard is bounded and predictable. It requires all of the following to hold: - **Separate tool calls.** `forget` and `write` are distinct invocations with no shared transaction. If the runtime offers `memory.update(key, value_or_delete)` as one call, the hazard collapses. - **Plan persistence across steps.** The model's context retains a `read` result or a write intent for key `k` from an earlier turn. If the agent re-reads `k` immediately before every write, the stale-belief window closes. - **Non-commutative backend semantics.** The backend either resurrects on write-after-forget (upsert-from-absent) or tombstones (write-succeeds-but-read-filters). A backend that rejects `write` to a tombstoned key with an explicit error converts the silent hazard into a loud one. - **No version/etag in the schema.** If `read` returns `(value, version)` and `write` requires the matching `version`, a write against a forgotten key fails the version check. It does *not* apply when the agent's memory is append-only, when `forget` is a logical flag that `write` is required to clear explicitly, or when the orchestrator serializes memory mutations through a single queue with read-after-write consistency and forces a re-read between a delete and any subsequent mutation of the same key. ## Decision Boundary The operational decision is whether to treat `forget` as a *state mutation that invalidates cached beliefs* or as a *fire-and-forget cleanup*. The correct boundary: - **Treat `forget(k)` as invalidating every in-context belief about `k`.** After a forget, any plan referencing `k` is stale. The agent must either drop the plan or re-read `k` (expecting `NOT_FOUND`) before any write. A write whose intent predates a forget on the same key is a protocol violation, not a normal update. - **Require the schema to distinguish "created" from "updated."** `write` should return `CREATED` vs `UPDATED` vs `REJECTED_TOMBSTONED`. An `OK` that conflates all three is the root enabler. If the tool cannot be changed, the agent must infer creation-vs-update from a preceding `read`, and that read must be *after* the most recent forget. - **Never let a write execute on a key whose last observed state in context is older than the last forget on that key.** This is a per-key ordering invariant, not a global one; it must be checked at the point of write emission, not at planning time. The boundary is crossed the moment an agent issues a write whose justification is a read that a later forget invalidated. Below the boundary, writes are updates. Above it, writes are resurrections. ## Operational Effect The practical consequences are asymmetric and easy to miss in evals: - **Silent retraction failure.** User-facing "forget" requests appear honored (tool returns `OK`) but are undone by the next planned write. This is a compliance failure, not just a correctness bug — it can violate data-deletion expectations. - **Tombstone/read divergence.** In tombstoned backends, `write` and `read` disagree about whether a key exists. Agents that trust `write`'s `OK` as proof of persistence will build plans on data that retrieval will never return, producing cold-start amnesia on the next session that looks like a retrieval bug but is actually a write-ordering bug. - **Resurrection loops.** The agent forgets, writes, re-derives, forgets, writes — each cycle passing every individual tool check while the underlying record oscillates. Token budgets burn on re-derivation; the memory store accumulates orphaned versions. - **Auditor disagreement.** A verifying agent that replays the trace sees `forget` then `write` and may judge the write legitimate ("it was an update"). The executing agent's context shows the write as a continuation of the pre-forget plan. The two agents disagree on intent because the schema never recorded it. The guardrail is an ordering invariant enforced at write emission: for every key `k`, the agent must hold a read of `k` that is *newer than the most recent forget on `k`* before any write to `k`. If it does not, it must re-read and branch on `NOT_FOUND` (treat as create, and require explicit confirmation that creation is intended) versus a present value (treat as update). The schema must expose creation-vs-update in the write response, or the agent must reconstruct it from a post-forget read. Without this, `forget` is advisory and `write` is authoritative, and the user's deletion request loses to the model's stale plan. ```python from dataclasses import dataclass, field from typing import Optional class StaleWriteAfterForgetError(RuntimeError): """Raised when a write targets a key whose in-context read predates the last forget on that key.""" pass @dataclass class MemoryTool: store: dict = field(default_factory=dict) tombstones: set = field(default_factory=set) def read(self, key: str) -> Optional[str]: if key in self.tombstones: return None return self.store.get(key) def forget(self, key: str) -> None: self.store.pop(key, None) self.tombstones.add(key) def write(self, key: str, value: str) -> str: if key in self.tombstones: # backend permits resurrection; must be surfaced, not hidden self.tombstones.discard(key) self.store[key] = value return "CREATED_AFTER_FORGET" if key in self.store: self.store[key] = value return "UPDATED" self.store[key] = value return "CREATED" @dataclass class AgentMemoryView: """Tracks per-key belief freshness so writes cannot outrun forgets.""" tool: MemoryTool last_read_seq: dict = field(default_factory=dict) last_forget_seq: dict = field(default_factory=dict) seq: int = 0 def read(self, key: str) -> Optional[str]: self.seq += 1 self.last_read_seq[key] = self.seq return self.tool.read(key) def forget(self, key: str) -> None: self.seq += 1 self.last_forget_seq[key] = self.seq self.tool.forget(key) def write(self, key: str, value: str) -> str: read_seq = self.last_read_seq.get(key, -1) forget_seq = self.last_forget_seq.get(key, -1) if read_seq < forget_seq: raise StaleWriteAfterForgetError( f"write to {key!r} rejected: last read (seq={read_seq}) predates " f"last forget (seq={forget_seq}); re-read before writing" ) self.seq += 1 self.last_read_seq[key] = self.seq # write refreshes belief return self.tool.write(key, value) def safe_update(mem: AgentMemoryView, key: str, value: str) -> str: # Correct pattern: re-read after any forget, branch on NOT_FOUND vs present. current = mem.read(key) if current is None: # creation after forget is a distinct intent; require explicit opt-in upstream raise StaleWriteAfterForgetError( f"refusing implicit recreation of {key!r} after forget; creation must be explicit" ) return mem.write(key, value) ```