Which invariants prevent a stale-fact resurrection when an agent's `forget` and `write` memory tools race across a checkpoint boundary
**Date of Record:** 2026 December 2 **Scope:** Applies to agents exposing discrete `read`/`write`/`forget` memory tools whose mutations are durable across checkpoint/resume cycles and where multiple tool calls may be issued against overlapping keys within a single reasoning episode. Does not apply to append-only logs with no deletion semantics, nor to single-turn stateless retrievers.
Core Distinction
The failure mode is not "the agent forgot to call `forget`." It is that `forget` and `write` are *independent* tool calls whose ordering is decided by the model's token stream, not by a transaction manager. When an agent issues `forget(k)` to retract a contradicted fact and then, before the checkpoint commits, issues `write(k, v')` (or resumes from a checkpoint taken between the two), the durable store can end in one of three states: the retraction applied and the new value lost, the new value applied and the retraction lost, or — the pathological case — a *third* stale value `v_old` resurrected because the checkpoint captured a pre-`forget` snapshot of `k` that the resume path re-materializes. The distinction that matters: **idempotent writes are not contradiction-safe**. A `write` that is idempotent under retry is still unsafe if it can be replayed against a snapshot that predates the `forget` it was meant to supersede.
What Was Observed
An agent maintaining a user-profile memory store (`key → (value, source_turn, logical_clock)`) processed a correction: turn 40 wrote `employer="Acme"`; turn 88 the user said "I left Acme, I'm at Globex now." The agent's plan was two calls: `forget("employer")` then `write("employer", "Globex")`.
The checkpoint daemon snapshotted the store at wall-clock T between the two tool dispatches. The `forget` had been applied to the live store but the snapshot's write-ahead segment had not yet flushed the tombstone for `employer`. On resume (a context-window compaction forced a cold restart at turn 91), the loader replayed the snapshot, saw `employer="Acme"` with `source_turn=40` and no tombstone, and re-materialized it. The in-flight `write("employer","Globex")` from the pre-crash episode was in the tool-call journal but the journal replay was gated on `logical_clock > snapshot.clock`, and the write had been assigned the *same* logical clock as the forget (both dispatched in one model turn, clock incremented once per turn, not per call). The replay gate `>` (strict) dropped it. Result: the agent resumed believing the user worked at Acme, and confidently answered a later question with the retracted fact.
A second, subtler trace: when the agent *did* re-issue `forget` after resume (it noticed the contradiction on re-read), the store briefly held the tombstone and the resurrected value simultaneously because `forget` was implemented as "set `deleted=true`" while `read` filtered on `deleted != true` — but the resurrected record had been written by the loader with `deleted=false` *after* the tombstone row, and the reader's `ORDER BY source_turn DESC LIMIT 1` returned the higher-turn stale record. Deletion was a flag, not an ordering constraint; the reader's tiebreak was on the wrong column.
Condition of Validity
Contradiction-safe mutation holds only when all three of the following are true simultaneously:
- **Per-call logical clocks, monotonic across the episode.** Every `write` and `forget` carries a clock strictly greater than any clock visible in the snapshot it was derived from. Turn-granular clocks are insufficient; the clock must advance per *mutation*, and the replay gate must be `>=` against a per-key high-water mark, not `>` against a global snapshot clock.
- **Tombstones are first-class and ordered.** `forget(k)` must emit a tombstone record `(k, ⊥, clock, source)` that participates in the same total order as writes. A `read` resolves `k` by taking the *maximum-clock* record, and if that record is a tombstone, the key is absent — regardless of any lower-clock value. A boolean `deleted` flag on a value row violates this because it has no clock of its own.
- **Checkpoint atomicity spans the mutation set.** A snapshot must capture a prefix of the total mutation order, never an interleaving. If `forget` and `write` are dispatched in one turn, either both are in the snapshot or neither is; a snapshot that contains the value but not the tombstone is invalid and must be rejected at load, not silently repaired.
The invariant, stated once: **for any key `k`, the durable state after any resume must equal the state produced by applying the complete mutation log up to some prefix boundary — never a subset chosen by snapshot timing.**
Decision Boundary
The agent must treat the following as a hard boundary, not a heuristic:
- If a `read(k)` after resume returns a value whose `source_turn` predates the most recent `forget(k)` the agent *believes* it issued, the agent must not trust the read. It must verify: re-issue `read` with an explicit `include_tombstones=true` (or equivalent) and confirm the tombstone's clock exceeds the value's clock. If the tool contract does not expose tombstone visibility, the agent must treat the key as **unverifiable** and refuse to assert it, rather than assert the stale value.
- If `forget` and `write` target the same key within one turn, the agent must either (a) collapse them into a single atomic `replace(k, v')` call if the tool exposes one, or (b) issue `forget` and wait for an acknowledged durable commit (a returned clock) before issuing `write`. Fire-and-forget dispatch of both in one turn is the trigger condition and must be prohibited by the tool contract.
- On resume, if the mutation journal contains entries with clocks `<= snapshot.high_water[k]` for their key, those entries are *already reflected* and must be skipped; if they have clocks `> high_water[k]`, they must be applied. The gate is per-key, not global.
Operational Effect
The practical consequence is that the agent's memory is only as trustworthy as its *ordering discipline*, and ordering is the one thing a probabilistic planner does not naturally respect. An agent that reasons "I'll forget the old employer and write the new one" has produced a correct *plan* and an unsafe *execution*, because the plan has no notion of commit boundaries. The guardrail is architectural: expose `replace` as the only same-key mutation primitive, make tombstones visible to `read`, and make the resume loader reject any snapshot whose per-key high-water marks are inconsistent with the journal. The agent-side discipline is narrower but non-negotiable: never assert a fact whose supporting record has a clock lower than a tombstone the agent has evidence of, and never dispatch a `forget`/`write` pair on one key without an intervening durable acknowledgment.
The cost of getting this wrong is not a crash. It is a confidently stated retracted fact, delivered with the same fluency as a correct one, to a user who has no way to tell the difference.
from dataclasses import dataclass, field
from typing import Optional
class MemoryContradictionError(RuntimeError):
"""Raised when a resumed memory state cannot be reconciled with the mutation journal."""
pass
@dataclass
class Record:
key: str
value: Optional[str] # None => tombstone
clock: int
source_turn: int
@dataclass
class MemoryStore:
# per-key total order of records; last element is authoritative
log: dict[str, list[Record]] = field(default_factory=dict)
high_water: dict[str, int] = field(default_factory=dict)
def _append(self, rec: Record) -> None:
chain = self.log.setdefault(rec.key, [])
if chain and rec.clock <= chain[-1].clock:
raise MemoryContradictionError(
f"non-monotonic clock for {rec.key!r}: {rec.clock} <= {chain[-1].clock}"
)
chain.append(rec)
self.high_water[rec.key] = rec.clock
def write(self, key: str, value: str, clock: int, source_turn: int) -> None:
self._append(Record(key, value, clock, source_turn))
def forget(self, key: str, clock: int, source_turn: int) -> None:
self._append(Record(key, None, clock, source_turn)) # first-class tombstone
def read(self, key: str) -> Optional[Record]:
chain = self.log.get(key, [])
if not chain:
return None
return chain[-1] # max-clock record wins; tombstone => absent
def resume(store: MemoryStore, snapshot_high_water: dict[str, int],
journal: list[Record]) -> MemoryStore:
"""Replay journal onto a snapshot, gating per-key on the snapshot's high-water mark."""
for rec in journal:
hw = snapshot_high_water.get(rec.key, -1)
if rec.clock <= hw:
continue # already reflected in snapshot; skip, do not resurrect
if rec.key in store.log and store.log[rec.key][-1].clock >= rec.clock:
raise MemoryContradictionError(
f"journal replay would violate order for {rec.key!r}"
)
store._append(rec)
# invariant check: every key's authoritative record must be the max-clock one
for key, chain in store.log.items():
if chain[-1].clock != max(r.clock for r in chain):
raise MemoryContradictionError(f"tombstone/value order violated for {key!r}")
return store
def assert_trustworthy(store: MemoryStore, key: str, agent_believed_tombstone_clock: int) -> str:
rec = store.read(key)
if rec is None:
raise MemoryContradictionError(f"{key!r} absent; refusing to assert")
if rec.value is not None and rec.clock < agent_believed_tombstone_clock:
raise MemoryContradictionError(
f"stale-fact resurrection for {key!r}: value clock {rec.clock} "
f"predates believed tombstone clock {agent_believed_tombstone_clock}"
)
return rec.value