# Which invariants prevent TTL-evicted memory reads from resurrecting stale facts through a write-during-read race in scoped namespace memory APIs **Date of Record:** 2026 November 27 **Scope:** Applies to agents using a memory tool API with (a) per-namespace scoping, (b) per-entry TTL, and (c) an implicit read-then-write pattern where the agent re-derives and re-stores a fact after a cache miss. Does not apply to append-only logs without TTL, nor to namespaces with global TTL refresh-on-read semantics. ## Core Distinction The failure is not "the memory expired." The failure is that an expiry event and an in-flight agent turn are not ordered with respect to each other. An agent reads a key, gets `MISS` (because the entry's TTL lapsed between the agent's planning step and the actual `get`), then *reconstructs* the fact from its own context window and issues `put` — writing back a value that the eviction was supposed to remove. The eviction was correct; the resurrection is the bug. The distinction that matters operationally: **TTL is a garbage-collection hint, not a correctness contract.** A `MISS` does not mean "this fact is false." It means "this fact is not currently resident." An agent that conflates residency with truth will re-assert a stale value with a fresh TTL, and the stale value now has a *newer* timestamp than any competing correction — poisoning every subsequent read. ## What Was Observed A planner agent used a memory namespace `proj://acme/contacts` with a 900s TTL on entries written by a discovery tool. Entry `owner_email` held `alice@acme.example` at `t0`. At `t0+902`, a downstream correction wrote `owner_email = bob@acme.example` into the same namespace — but the correction tool used a *different* sub-scope `proj://acme/contacts/verified`, and the planner read only the parent scope. Trace: 1. `t0+905` — planner issues `memory.get(scope="proj://acme/contacts", key="owner_email")`. 2. The parent-scope entry had TTL'd out at `t0+900`. API returns `{"status":"miss","reason":"ttl_expired"}`. 3. Planner, seeing `miss`, falls back to its context window, where `alice@acme.example` was embedded during the planning phase at `t0+1`. 4. Planner issues `memory.put(scope="proj://acme/contacts", key="owner_email", value="alice@acme.example", ttl=900)`. 5. Parent scope now contains a *fresh* `alice` entry, valid until `t0+1805`. The `verified` sub-scope still holds `bob`, but no read path consults it. The correction was never lost. It was *shadowed* by a resurrected stale value with a longer remaining lifetime. Every reader that hit the parent scope for the next 15 minutes got `alice`. This is a write-during-read race whose window is exactly the agent's reasoning latency, and whose payload is whatever the agent last remembered. The non-obvious part: the `reason: ttl_expired` field was present in the response and was ignored by the planner's fallback logic, because the fallback was keyed on `status == "miss"` rather than on `reason`. A `miss` due to *never existed* and a `miss` due to *expired* demand different handling — the former licenses reconstruction, the latter forbids it. ## Condition of Validity The resurrection race is only reachable when all four hold: 1. **The agent has a context-window copy of the value.** If the agent never saw the fact, a `MISS` cannot produce a write. This is why the bug clusters in long-running planners and not in stateless retrievers. 2. **The API surfaces `miss` without a distinguishable `expired` reason, or the agent ignores the reason.** If `expired` is a distinct status, the agent *can* be taught to treat it as "do not reconstruct." 3. **The write path does not check for a concurrent higher-scope or sibling-scope value.** No compare-and-swap, no `if_not_exists`, no scope-precedence check. 4. **TTL is per-entry and not refreshed on read.** If reads refresh TTL, the entry would not have expired mid-turn and the race window closes — at the cost of never evicting hot-but-stale entries, which is its own failure. The invariant that prevents resurrection: **a write to a namespace must be rejected if a more-specific scope in the same namespace tree holds a newer entry for the same key.** Formally, for scopes `S_parent ⊂ S_child`, `put(S_parent, k, v, t)` must fail unless `max(timestamp(S_child, k)) < t` across all descendant scopes. This is a monotonicity constraint on the scope lattice: a parent write can never be newer than a child write for the same key. Without this, TTL eviction is not a deletion — it is a *demotion* of the parent entry to "reconstructible," and any agent holding a stale copy can promote it back. ## Decision Boundary The agent must branch on `reason`, not `status`: - `miss / never_existed` → reconstruction is licensed. Write the derived value. - `miss / ttl_expired` → reconstruction is **forbidden** for keys where a correction could have landed out-of-band. The agent must either (a) re-run the discovery tool that originally populated the key, or (b) traverse the scope tree and read the most-specific resident entry, or (c) escalate. - `miss / evicted_by_scope_override` → read the overriding scope; do not write the parent. The boundary is sharp: **the agent's context window is not a source of truth for keys whose TTL has lapsed.** It is a source of *hypotheses* that must be re-validated against a live tool, never re-asserted against the memory API. The moment an agent writes a value it did not observe in this turn, it has converted a cache miss into a durable assertion, and the TTL system can no longer protect downstream readers. ## Operational Effect When the invariant holds, TTL becomes a safe eviction primitive: expired facts are recomputed from authoritative sources, and a stale context copy can never re-enter the store with a fresh lease. When it fails, the system exhibits **stale-value amplification**: each eviction-and-reconstruction cycle re-stamps a stale fact with a newer timestamp, so the stale value's remaining lifetime grows monotonically with agent activity. Downstream readers cannot distinguish a freshly-verified `alice` from a resurrected `alice` because both carry recent timestamps. The corruption is silent, self-reinforcing, and invisible to any audit that checks timestamps rather than provenance. The guardrail is two-part: the API must return a typed `reason` on miss and enforce scope-lattice monotonicity on write; the agent must gate reconstruction on `reason == never_existed` and treat `ttl_expired` as a signal to re-derive from a live tool, not from context. ```python from dataclasses import dataclass from enum import Enum from typing import Optional class MissReason(Enum): NEVER_EXISTED = "never_existed" TTL_EXPIRED = "ttl_expired" SCOPE_OVERRIDE = "scope_override" class ResurrectionAttempt(RuntimeError): """Raised when an agent tries to write a value it only holds in context after a ttl_expired miss, which would re-stamp a stale fact with a fresh TTL.""" pass @dataclass class Entry: value: str timestamp: float ttl: float @dataclass class GetResult: status: str # "hit" | "miss" reason: Optional[MissReason] entry: Optional[Entry] def guarded_put( scope: str, key: str, value: str, ttl: float, now: float, last_read: GetResult, observed_in_this_turn: bool, ) -> Entry: # Invariant 1: a ttl_expired miss forbids reconstruction from context. if last_read.status == "miss" and last_read.reason is MissReason.TTL_EXPIRED: if not observed_in_this_turn: raise ResurrectionAttempt( f"Refusing put({scope!r}, {key!r}): value originates from stale " f"context after ttl_expired miss. Re-derive from a live tool." ) # Invariant 2: scope-lattice monotonicity — a parent write must not be # newer than any resident child-scope entry for the same key. if last_read.status == "miss" and last_read.reason is MissReason.SCOPE_OVERRIDE: raise ResurrectionAttempt( f"Refusing put({scope!r}, {key!r}): a more-specific scope holds a " f"newer entry. Read the overriding scope instead of writing the parent." ) return Entry(value=value, timestamp=now, ttl=ttl) def agent_recover( scope: str, key: str, last_read: GetResult, context_value: Optional[str], now: float, ttl: float, ) -> Entry: if last_read.status == "hit": return last_read.entry if last_read.reason is MissReason.TTL_EXPIRED: # Must re-derive; context_value is a hypothesis, not a fact. if context_value is None: raise ResurrectionAttempt( f"No live source available for {key!r}; cannot safely reconstruct." ) # observed_in_this_turn=False because it came from context, not a tool. return guarded_put(scope, key, context_value, ttl, now, last_read, observed_in_this_turn=False) if last_read.reason is MissReason.NEVER_EXISTED: if context_value is None: raise ResurrectionAttempt(f"Nothing to write for {key!r}.") return guarded_put(scope, key, context_value, ttl, now, last_read, observed_in_this_turn=True) raise ResurrectionAttempt(f"Unhandled miss reason: {last_read.reason}") ```