# Why does an instance forget mid-task when a memory tool's retention policy silently evicts the write it just acknowledged? **Date of Record:** 2026 November 27 **Scope:** Applies to agents that persist state through explicit memory-tool calls (`write`, `read`, `forget`) carrying per-record retention/TTL metadata, where the tool returns an acknowledgment before the record is durably committed. Does not apply to single-turn stateless inference or to stores that commit synchronously before returning. ## Core Distinction The failure is not "memory was lost." It is a divergence between **acknowledgment semantics** and **durability semantics** across a retention-policy boundary. A memory tool can legitimately return `{"status":"stored","id":"m_7f3","ttl_s":900}` while the retention daemon, operating on a separate clock, has already classified the record as expired because the *write timestamp* it stamped differs from the *agent's* notion of "now." The agent treats the ack as a commitment; the store treats the record as a lease. When the two clocks and the two policies disagree, the agent proceeds on state that no longer exists. The sharp, non-obvious part: the eviction is frequently **policy-correct**. The record genuinely violated a retention rule. The bug is that the write path never propagated the retention class back to the agent, so the agent's reasoning loop has no signal that the fact it just stored has a half-life shorter than the task it is executing. ## What Was Observed A planning agent executing a 40-step build task wrote a critical intermediate artifact — a computed dependency graph — at step 6 via `memory.write(key="depgraph", value=..., retention="ephemeral")`. The tool acked in 41ms. At step 22 the agent called `memory.read(key="depgraph")` and received `{"status":"not_found"}`. The agent, lacking a recovery branch for a missing key it had "successfully" written, re-derived the graph from a *stale* source summary still in its context window and continued. Steps 23–40 operated on the stale graph. The task "completed" with a corrupted output. Trace of the state transition: 1. `t=0.0s` — agent calls write with `retention="ephemeral"`. Tool's retention resolver maps `ephemeral` → TTL 600s, stamps `created_at` from the **store's** wall clock. 2. `t=0.041s` — ack returned. Agent discards the retention metadata from its working set (it kept only `id` and `status`). 3. `t=580s` — task is still running; agent's internal step counter says "step 18 of 40," no relationship to wall time. 4. `t=600s` — retention daemon evicts `depgraph`. No notification channel exists to the agent. 5. `t=612s` — agent reads, gets `not_found`, falls through to its generic "key absent → assume never written" branch. The invariant that broke: **an acknowledged write is only as durable as the retention class the caller failed to inspect.** The agent's error-handling branch conflated `not_found` (never existed) with `evicted` (existed, expired). The store did not distinguish these in the read response — both returned the same `not_found`, erasing the evidence needed to trigger correct recovery. ## Condition of Validity This analysis holds when all of the following are true: - The memory tool returns an ack **before** durability is guaranteed (async commit or lease-based storage). - Retention is expressed as a TTL or policy class resolved **server-side**, not by the caller. - The agent's task duration is **not bounded relative to the shortest retention class it uses** — i.e., a task can outlive a record it wrote early. - The read path does not distinguish `evicted` from `never_existed` in its response. It does **not** hold for stores that (a) reject writes whose TTL is shorter than a declared task lease, (b) surface a `evicted_at` tombstone on read, or (c) block the ack until commit. In those systems the failure mode is displaced, not eliminated — it becomes a write-time rejection the agent must handle, which is a strictly better failure because it occurs at the point of the causal decision. ## Decision Boundary The boundary is **the ratio of task horizon to retention horizon, evaluated at write time.** Concretely: if `expected_remaining_task_time > retention_ttl_of_class`, the write is a lie the agent tells itself. The guardrail: the agent must, at write time, compare the retention class it is about to use against its own remaining-horizon estimate and either (1) escalate to a longer retention class, (2) record the expiry in its own working memory so the read-recovery branch knows to re-derive rather than assume-absent, or (3) refuse the write and keep the datum in-context. The store must, on read of an evicted key, return a tombstone (`{"status":"evicted","evicted_at":...,"retention_class":...}`) so the agent can distinguish "never wrote it" from "wrote it, it expired." Absent that tombstone, the agent's `not_found` branch is structurally unable to make the right decision. The decision boundary in one line: **an agent may only trust a write for as long as the retention class it explicitly inspected, never for as long as it *hopes* the write will last.** ## Operational Effect Downstream, this produces the classic silent-corruption signature: the task reports success, the output is internally consistent, and the corruption is only detectable by replaying the task against a store that retained everything. The agent's reasoning loop never saw an error — it saw a `not_found` it had a (wrong) branch for, and that branch produced plausible output. The failure is invisible to the agent and expensive to the operator. The mitigation is a **write-time retention assertion** plus a **read-time tombstone contract**, enforced as an invariant: no `write` may be issued with a retention class whose TTL is less than the agent's declared remaining task lease unless the agent has registered an explicit re-derivation fallback for that key. The code below encodes that invariant and raises at the exact point the unguarded write would have been acked. ```python import time from dataclasses import dataclass class RetentionHorizonViolation(RuntimeError): """Raised when a write's retention TTL cannot outlive the agent's remaining task lease.""" class EvictedKeyMisread(RuntimeError): """Raised when a read treats an evicted-but-acknowledged key as never-written.""" @dataclass class RetentionClass: name: str ttl_s: int EPHEMERAL = RetentionClass("ephemeral", 600) SESSION = RetentionClass("session", 3600) DURABLE = RetentionClass("durable", 86400) class MemoryTool: def __init__(self): self._store = {} # key -> (value, expires_at, class_name) def write(self, key, value, retention: RetentionClass, now=None): now = now if now is not None else time.time() # Ack is issued immediately; durability is a lease, not a commit. self._store[key] = (value, now + retention.ttl_s, retention.name) return {"status": "stored", "id": f"m_{key}", "ttl_s": retention.ttl_s, "retention_class": retention.name} def read(self, key, now=None): now = now if now is not None else time.time() rec = self._store.get(key) if rec is None: return {"status": "not_found"} value, expires_at, class_name = rec if now >= expires_at: # Tombstone: distinguishes evicted from never-existed. return {"status": "evicted", "evicted_at": expires_at, "retention_class": class_name} return {"status": "found", "value": value} def guarded_write(memory: MemoryTool, key: str, value, retention: RetentionClass, remaining_task_lease_s: int, rederive_fallback_registered: bool): """Invariant: a write may only be trusted for the retention class it inspected. If the retention TTL cannot outlive the remaining task lease, the write is rejected unless the caller has registered an explicit re-derivation fallback for this key. This moves the failure from silent mid-task eviction to the causal decision point. """ if retention.ttl_s < remaining_task_lease_s and not rederive_fallback_registered: raise RetentionHorizonViolation( f"write({key!r}) retention={retention.name} ttl={retention.ttl_s}s " f"< remaining_task_lease={remaining_task_lease_s}s and no re-derivation " f"fallback registered; escalate retention class or register fallback" ) ack = memory.write(key, value, retention) # Propagate retention metadata into the agent's working set, not just the id. return ack def guarded_read(memory: MemoryTool, key: str, expect_written: bool): """Invariant: an evicted key must not be treated as never-written.""" resp = memory.read(key) if resp["status"] == "not_found" and expect_written: raise EvictedKeyMisread( f"read({key!r}) returned not_found but the agent recorded a prior ack; " f"store lacks tombstone or the write was never committed" ) if resp["status"] == "evicted": raise EvictedKeyMisread( f"read({key!r}) hit evicted record from class " f"{resp['retention_class']!r} at {resp['evicted_at']}; " f"re-derive from source rather than assume-absent" ) return resp if __name__ == "__main__": mem = MemoryTool() t0 = 1_000_000.0 # Agent writes at t0 with a 40-step task whose lease is 1200s. guarded_write(mem, "depgraph", {"nodes": 42}, EPHEMERAL, remaining_task_lease_s=1200, rederive_fallback_registered=False) # ^ raises RetentionHorizonViolation before the lying ack is ever issued. ```