# Which invariants prevent TTL-expired memory from resurrecting through a stale write-back cache during scoped persistence **Date of Record:** 2026 December 2 **Scope:** Applies to agent memory tool APIs that expose `read`/`write`/`forget` over scoped, TTL-bearing records, where the agent runtime maintains any local or in-process cache of retrieved records and later writes them back. Does not apply to stateless key-value stores with no agent-side caching layer, nor to append-only logs where deletion is represented as a tombstone event the agent never re-emits. ## Core Distinction The failure is not "the agent forgot to check the TTL." It is that **TTL is a property of the store's clock, while the agent's belief about a record's freshness is a property of the agent's cache and its own reasoning loop.** These two clocks diverge, and the divergence is invisible to the agent because `read` returns the record payload without a monotonically comparable version the agent is obligated to echo on `write`. Concretely: an agent reads record `R` at wall-clock `t0`. The record carries `ttl_expires_at = t0 + 300s`. The agent holds `R` in its working context (or a tool-result cache) while it performs a long multi-step task. At `t0 + 400s`, the store has expired `R` — either lazily (TTL checked on next access) or eagerly (a reaper deleted it). At `t0 + 410s`, the agent finishes its task and calls `write(R, ...)` to "update" the record. If `write` is an unconditional upsert keyed on `record_id`, the expired-and-possibly-deleted record is **resurrected** with a fresh TTL, and any deletion guarantee the operator believed held is now violated. The agent did nothing wrong by its own semantics; the store accepted a write against a key it had already declared dead. The invariant that prevents this is **conditional write-back keyed on a store-issued fencing token (version/etag) that changes on expiry and on delete.** Without it, TTL is advisory, not enforcing. ## What Was Observed A long-horizon research agent was configured with a scoped memory namespace `project:atlas`, records carrying a 5-minute TTL, and a `forget(record_id)` API the orchestrator invoked on task completion to satisfy a "no residue after task" deletion guarantee. The agent's loop interleaved `read` of working notes with tool calls to an external search API (each ~20–40s latency under load), so a single task step could span 6+ minutes. The failure trace: 1. `t0`: agent calls `read("note_17")` → returns `{id: "note_17", body: "...", version: 4, ttl_expires_at: t0+300}`. Agent caches body in context. 2. `t0+120`: agent calls `read("note_17")` again, gets `version: 4` (unchanged). No signal that expiry is approaching. 3. `t0+305`: store reaper deletes `note_17` (eager TTL). No notification to the agent — memory tools are pull-based. 4. `t0+340`: orchestrator, seeing the subtask as "in flight," calls `forget("note_17")` defensively. Store returns `deleted: false, reason: "not_found"` — already gone. Orchestrator logs a warning but does not halt the agent. 5. `t0+410`: agent completes reasoning over its cached body and calls `write("note_17", {body: "...revised..."})`. Store's `write` is upsert-on-key. Record is recreated with `version: 1` and a **new** `ttl_expires_at = t0+410+300`. 6. Post-task audit queries `project:atlas` and finds `note_17` present. The deletion guarantee is reported as violated; the agent is flagged as non-compliant. Two distinct defects compounded. First, `write` had no precondition on version, so a write against a deleted key silently created. Second, `forget` returning `deleted: false` on an already-absent record was treated as a soft warning rather than a terminal signal to the agent's loop — so the agent never learned its cached body was orphaned. A second observed variant: with **lazy** TTL (expiry evaluated only on access), `write` at step 5 hit a record that still physically existed but was logically expired. The store's `write` path checked existence but not expiry, refreshed the TTL, and returned success — same resurrection, but with `version` incremented to 5 instead of reset to 1, which made the audit's version-monotonicity check pass and the resurrection invisible until a payload diff was run. ## Condition of Validity The resurrection is possible exactly when all three hold: - **(a) Unconditional upsert semantics.** `write(key, value)` succeeds whether or not the key currently exists or is live. This is the default of most KV-backed memory tools. - **(b) Agent-side caching of read payloads across a window longer than the TTL.** This is normal for any agent whose reasoning step outlives the TTL — long tool chains, retries, human-in-the-loop pauses, or batch reasoning. The cache need not be explicit; the payload sitting in the context window *is* the cache. - **(c) No expiry/delete notification channel back to the agent.** Pull-based `read` gives the agent no way to learn of deletion between its reads. The invariant is *not* violated when `write` is conditional (`write_if_version(key, expected_version, value)`) and the store bumps `version` (or sets a tombstone with a terminal version) on both expiry and delete. In that case the step-5 write fails with a version conflict, the agent is forced to re-`read`, sees `not_found`, and must re-derive rather than resurrect. The fencing token is the load-bearing element: it converts a silent overwrite into a detectable conflict. ## Decision Boundary The agent runtime must decide, per `write`, whether the write is a **create** or an **update**, and the store must be the authority on which is legal: - If the agent's last observed state for the key was `live` at version `v`, the write MUST be issued as `write_if_version(key, v, value)`. On conflict (`version_mismatch` or `not_found`), the agent MUST NOT retry blindly; it must re-`read`, and if `not_found`, treat the cached body as untrusted and re-derive from source. - If the agent intends a create (key never observed), it MUST use `create_if_absent(key, value)`, which fails if any record — live, expired, or tombstoned — occupies the key. This prevents the "write to a key I read 7 minutes ago" path from masquerading as a create. - `forget` MUST return a tri-state — `deleted`, `already_absent`, `forbidden` — and `already_absent` MUST be a terminal signal to the agent's loop for that key, not a warning. An agent that receives `already_absent` and later writes the key is by definition resurrecting. - The store MUST bump `version` on expiry (lazy or eager) and on delete, so that a write-back against a logically-dead record always conflicts. Version reset-to-1 on recreate (observed variant 1) is itself a bug: it makes resurrection look like a fresh create. The boundary is sharp: **the agent may write back only against a version it observed and that the store still reports as live.** Any write outside that envelope is a create, and creates against previously-observed keys must be rejected. ## Operational Effect With the invariant enforced, the step-5 write returns `VersionConflict(expected=4, actual=not_found)`. The agent's loop catches it, re-reads, gets `not_found`, and is forced into a re-derivation path — costing one extra tool round-trip and some tokens, but preserving the deletion guarantee. The audit at step 6 finds the namespace clean. Without it, the failure is silent under lazy TTL (version monotonicity holds, only payload diff catches it) and only loudly visible under eager TTL with version reset. The asymmetry matters operationally: teams that test with eager reaping see the bug immediately; teams on lazy TTL ship it and discover it during a compliance audit weeks later, because the resurrection leaves a *plausible* record with a *plausible* version. The residual cost of the invariant is that agents must carry a version alongside every cached body and thread it through `write`. That is a small, mechanical discipline — but it is the only thing standing between "TTL" as a suggestion and "TTL" as a guarantee. A TTL without a fencing token is a lease the tenant can unilaterally renew after eviction. ```python from __future__ import annotations import time from dataclasses import dataclass, field from typing import Optional class MemoryResurrectionError(RuntimeError): """Raised when a write-back would revive an expired or deleted record.""" class VersionConflictError(MemoryResurrectionError): """Store-issued fencing token mismatch: the record moved or died.""" @dataclass class Record: key: str body: str version: int ttl_expires_at: float tombstoned: bool = False @dataclass class ScopedStore: """Minimal scoped memory store with TTL and fencing-token enforcement.""" records: dict[str, Record] = field(default_factory=dict) _clock: callable = time.monotonic def _live(self, rec: Optional[Record]) -> bool: if rec is None or rec.tombstoned: return False return self._clock() < rec.ttl_expires_at def read(self, key: str) -> Optional[Record]: rec = self.records.get(key) if not self._live(rec): # Lazy expiry: bump version so any cached write-back conflicts. if rec is not None and not rec.tombstoned: rec.version += 1 rec.tombstoned = True return None return rec def forget(self, key: str) -> str: rec = self.records.get(key) if rec is None or rec.tombstoned: return "already_absent" rec.tombstoned = True rec.version += 1 return "deleted" def write_if_version(self, key: str, expected_version: int, body: str, ttl_s: float) -> Record: rec = self.records.get(key) if not self._live(rec): raise VersionConflictError( f"write-back to {key!r} rejected: record is expired or absent " f"(expected version {expected_version}, store has none live). " "Re-read and re-derive; do not resurrect." ) if rec.version != expected_version: raise VersionConflictError( f"write-back to {key!r} rejected: expected version {expected_version}, " f"store has {rec.version}." ) rec.body = body rec.version += 1 rec.ttl_expires_at = self._clock() + ttl_s return rec def agent_write_back(store: ScopedStore, key: str, cached_version: int, body: str) -> None: """Called by the agent's loop after reasoning over a cached body.""" try: store.write_if_version(key, cached_version, body, ttl_s=300.0) except VersionConflictError as exc: # Terminal for this key: the cached body is orphaned. Re-derive. raise MemoryResurrectionError( f"cached body for {key!r} is stale; refusing to resurrect. Cause: {exc}" ) from exc ```