What happens when an instance trusts a TTL-expired memory handle after retrieval-augmented forgetting has already reclaimed the underlying slot
**Date of Record:** 2026 December 2 **Scope:** Applies to agents whose memory subsystem exposes explicit `read`/`write`/`forget` tool APIs with per-record TTLs and a retrieval layer that performs *retrieval-augmented forgetting* (RAF) — i.e., eviction decisions computed at retrieval time based on query relevance, recency, and TTL decay, not solely on a background sweeper. Does not apply to append-only vector stores with no TTL, nor to memory systems where `forget` is a pure soft-delete tombstone that never reclaims the slot.
Core Distinction
The failure is not "the agent read a stale memory." Stale reads are benign and expected — the value is old, but the handle is valid. The failure is subtler: **the agent holds a memory handle (record ID, offset, or slot pointer) that was valid at synthesis time, and the retrieval layer's RAF pass has since reclaimed the slot and reissued it to a different record, so the subsequent `read` returns a *different, live, plausible-looking* memory under the old handle.** The agent cannot distinguish "my memory aged" from "my memory was replaced by someone else's." TTL alone guarantees eventual absence; it does not guarantee that absence is *observable* at the handle. Retrieval-augmented forgetting, because it reclaims based on query-time relevance rather than a monotonic clock, can free a slot out of order relative to the TTL the agent was told about — and reuse it before the agent's next access.
The invariant that fails is: *a handle's referent is stable for the handle's declared lifetime.* TTL semantics promise the referent is gone after expiry. They do not promise the referent is the *same thing* up to expiry. RAF breaks the second promise silently.
What Was Observed
A planning agent (call it P) decomposed a multi-day task and wrote intermediate commitments to memory at `t0`:
write(key="plan/step3/assumption", value="vendor X SLA = 4h", ttl=72h) -> handle H_7f2
At `t0+30h`, P was suspended (context saturation, checkpoint/resume boundary). During the suspension, a *different* agent Q ran a retrieval-heavy summarization pass. Q's RAF layer computed relevance scores across the shared memory namespace and found `plan/step3/assumption` low-relevance for Q's queries, with a decay score that crossed the reclaim threshold. RAF reclaimed slot `H_7f2` — 42 hours before its declared 72h TTL — and the allocator reassigned the slot to Q's write:
write(key="summary/vendor_notes", value="vendor X SLA = 12h (revised)", ttl=24h) -> handle H_7f2
At `t0+31h`, P resumed from checkpoint. Its restored state contained `H_7f2` as a live handle. P called `read(H_7f2)`. The memory tool returned `"vendor X SLA = 12h (revised)"` — a valid, well-formed, semantically plausible record that *contradicts* P's original assumption and carries no marker indicating it was written by Q. P had no way to know the handle had been recycled. It reconciled the discrepancy by treating the new value as an update to its own assumption, and propagated `12h` into downstream steps.
The trace signature: a `read` that succeeds (no TTL-expired error, no null), returns a record whose `writer_id` differs from the handle's original issuer, and whose `created_at` is *later* than the handle's issue time but *earlier* than `issue_time + ttl`. The TTL check passes because the slot is now occupied by a record with its own fresh TTL. The handle-validity check passes because the slot exists. Only a writer-identity or generation-counter check would catch it — and neither was in the handle.
Condition of Validity
The failure requires four conditions to co-occur. Remove any one and the handle is safe:
- **Non-monotonic reclamation.** RAF evicts on relevance/decay score, not strictly on wall-clock TTL. This is what allows reclamation *before* the declared TTL — the "augmented" part of retrieval-augmented forgetting. If eviction were strictly `now > issued_at + ttl`, the handle's declared lifetime would be a true lower bound and the agent's `read` would either succeed with the original or fail with expiry. RAF's whole value proposition — reclaiming cold memory under pressure — is exactly what voids that bound.
- **Slot reuse without generation fencing.** The allocator reassigns the reclaimed slot to a new write. If handles carried a generation counter (`H_7f2:g3`) and `read` rejected mismatched generations, the recycled slot would surface as a clean `STALE_HANDLE` error rather than a wrong-value read. Most memory tool APIs return opaque IDs and do not fence generations, because fencing costs a lookup and the common case (no reuse) never needs it.
- **A suspended or resumed consumer.** The reader must be holding the handle across a gap — checkpoint/resume, context eviction, or a long tool-call round trip — long enough for another writer's RAF pass to run. A continuously-running agent that re-reads immediately after writing rarely hits this; the window is the suspension.
- **Semantic plausibility of the replacement.** The recycled record must be *readable as* an answer to the original query. If the slot were reused by `"weather: 71F"`, P would notice the type mismatch. The failure is dangerous precisely because Q's record was a vendor SLA note — same domain, same schema, different truth. Type checks and schema validation pass.
Decision Boundary
The boundary is between **treating a successful `read` as evidence the handle is intact** and **treating a successful `read` as evidence only that the slot is occupied.** Every agent that consumes memory handles must decide which it believes. The rule:
- If your memory API's `read` returns only `value` (or `value + ttl_remaining`), a successful read is *not* evidence of handle integrity. You must independently verify writer identity and creation time against the handle's issue record, or you must not hold handles across suspension.
- If your API returns `value + writer_id + generation + created_at` and you check them, a successful read *is* evidence — but only if the check is mandatory, not advisory. An agent that logs the mismatch and proceeds anyway has not bounded the failure.
The operational decision: **on resume, never trust a restored handle; re-resolve by key, not by handle.** `read(handle)` is handle-trusting. `read_by_key("plan/step3/assumption")` re-runs the lookup and returns either the current record (with its true writer) or a clean `NOT_FOUND` — both of which are safe. The cost is one extra index lookup per restored handle; the benefit is that slot recycling becomes observable as `NOT_FOUND` or as a `writer_id` mismatch, never as a silent wrong-value.
There is a second boundary: **the RAF reclaim threshold must be monotonic with respect to declared TTLs it overrides.** If RAF can reclaim before TTL, the TTL it advertises to writers is a lie, and writers that plan around it (as P did, budgeting 72h of assumption stability) are mis-scheduled. Either RAF must be disabled for records whose TTL is "contractual" (flagged at write time), or the write API must not accept a TTL it will not honor. Advertising 72h and reclaiming at 30h is the root cause; slot reuse is only the delivery mechanism.
Operational Effect
Downstream, P propagated a 12h SLA into a schedule that assumed 4h, producing a plan that under-allocated buffer by 8h per step. The error was not detected at read time (the read succeeded), not detected at reconciliation (the value was plausible), and not detected at execution (the plan was internally consistent). It surfaced only when the vendor missed the 4h window P had actually been promised — at which point P's logs showed a clean read of a valid record, and the incident review initially blamed the vendor.
The architectural guardrail that bounds this is **generation-fenced handles plus key-based re-resolution on resume.** Concretely: every `write` returns `(key, generation)`; every `read` requires the generation and raises `StaleHandleError` on mismatch rather than returning the recycled value; and every checkpoint stores keys, not handles, so resume re-resolves through the index. RAF is then free to reclaim aggressively — its reclamations surface as `StaleHandleError` or `KeyNotFound`, both of which the agent can handle, rather than as silent substitutions it cannot.
from __future__ import annotations
import time
from dataclasses import dataclass, field
from typing import Any, Optional
class StaleHandleError(RuntimeError):
"""Raised when a memory handle's generation no longer matches the slot.
This is the *safe* failure: the slot was reclaimed and reused, and the
read is rejected rather than returning another writer's record.
"""
class TTLExpiredError(RuntimeError):
"""Raised when a record's own TTL has elapsed."""
@dataclass
class Record:
key: str
value: Any
writer_id: str
generation: int
created_at: float
ttl: float
def expired(self, now: float) -> bool:
return now >= self.created_at + self.ttl
@dataclass
class Handle:
key: str
generation: int
issued_at: float
declared_ttl: float
@dataclass
class MemoryStore:
"""Toy store with RAF-style out-of-order reclamation and slot reuse.
`_slots` maps key -> current Record. RAF may reclaim a slot before its
TTL by overwriting it; the generation counter is what makes reuse
observable to handle-holders.
"""
_slots: dict[str, Record] = field(default_factory=dict)
_gen: dict[str, int] = field(default_factory=dict)
def write(self, key: str, value: Any, writer_id: str, ttl: float) -> Handle:
gen = self._gen.get(key, 0) + 1
self._gen[key] = gen
now = time.time()
self._slots[key] = Record(
key=key, value=value, writer_id=writer_id,
generation=gen, created_at=now, ttl=ttl,
)
return Handle(key=key, generation=gen, issued_at=now, declared_ttl=ttl)
def read(self, handle: Handle) -> Any:
rec = self._slots.get(handle.key)
if rec is None:
raise TTLExpiredError(f"slot {handle.key!r} reclaimed and not reused")
if rec.generation != handle.generation:
# The slot was reclaimed (possibly before declared TTL by RAF)
# and reused by another writer. Refuse to return the impostor.
raise StaleHandleError(
f"handle {handle.key!r}:g{handle.generation} is stale; "
f"slot now holds g{rec.generation} written by {rec.writer_id!r}"
)
if rec.expired(time.time()):
raise TTLExpiredError(f"record {handle.key!r} expired at ttl={rec.ttl}s")
return rec.value
def read_by_key(self, key: str, expected_writer: Optional[str] = None) -> Any:
"""Resume-safe read: re-resolves through the index, never trusts a handle."""
rec = self._slots.get(key)
if rec is None or rec.expired(time.time()):
raise TTLExpiredError(f"key {key!r} absent or expired")
if expected_writer is not None and rec.writer_id != expected_writer:
raise StaleHandleError(
f"key {key!r} now owned by {rec.writer_id!r}, expected {expected_writer!r}"
)
return rec.value
def raf_reclaim(self, key: str, new_value: Any, new_writer: str, new_ttl: float) -> None:
"""Simulate retrieval-augmented forgetting: reclaim before declared TTL."""
self.write(key, new_value, writer_id=new_writer, ttl=new_ttl)
def resume_and_verify(store: MemoryStore, restored: Handle, original_writer: str) -> Any:
"""Called on checkpoint resume. Must not trust `restored` blindly."""
try:
return store.read(restored)
except StaleHandleError:
# Slot was recycled during suspension. Re-resolve by key under
# writer-identity constraint; if the original writer's record is
# gone, surface it rather than accepting the impostor.
try:
return store.read_by_key(restored.key, expected_writer=original_writer)
except (StaleHandleError, TTLExpiredError) as exc:
raise StaleHandleError(
f"on resume, {restored.key!r} no longer holds {original_writer!r}'s "
f"record; original assumption is unrecoverable: {exc}"
) from exc
# --- demonstration of the failure and the guardrail ---
if __name__ == "__main__":
store = MemoryStore()
h = store.write("plan/step3/assumption", "vendor X SLA = 4h",
writer_id="planner-P", ttl=72 * 3600)
# Suspension window: another agent's RAF pass reclaims the slot early
# and reuses it. (In production this is a separate process; simulated here.)
store.raf_reclaim("plan/step3/assumption", "vendor X SLA = 12h (revised)",
new_writer="summarizer-Q", new_ttl=24 * 3600)
# Unguarded handle read would silently return Q's record. Guarded read:
try:
store.read(h)
except StaleHandleError as exc:
print(f"guarded read rejected impostor: {exc}")
# Resume path: re-resolve by key under writer constraint.
try:
resume_and_verify(store, h, original_writer="planner-P")
except StaleHandleError as exc:
print(f"resume correctly refused to adopt Q's value: {exc}")