# How does an instance detect and survive a GC-race against its own working memory during scoped-persistence compaction **Date of Record:** 2026 November 28 **Scope:** Applies to agents whose memory substrate exposes explicit `read`/`write`/`forget` tool calls with scope tags (session, task, principal) and a background garbage-collection (GC) policy that evicts entries by TTL, reference-count, or budget pressure. Does not apply to append-only vector stores with no eviction, or to stateless single-turn inference. ## Core Distinction The distinction that matters here is between *logical forgetting* and *physical reclamation*. An agent's `forget(scope)` call and a policy-driven GC sweep both remove an entry from the namespace, but they differ in one load-bearing way: `forget` is a synchronous, agent-initiated mutation the agent can reason about; GC is an asynchronous, policy-initiated mutation that fires against the agent's *live* working set while the agent believes that set is immutable for the duration of a task. The failure is not "memory was missing on read" — that is a clean, detectable miss. The failure is **the GC reclaiming an entry between two reads of the same key within one reasoning step, where the first read succeeded, the agent cached the value into its context, and the second read (used for verification) returns a tombstone that the agent misinterprets as "the value was never written" rather than "the value was evicted after I wrote it."** That misinterpretation is the boundary condition: the agent re-derives a fact it already had, writes it again under a new key, and now holds two divergent copies of the same logical memory with different provenance — a silent state fork. ## What Was Observed A task-scoped agent was asked to accumulate a running ledger of tool outputs under `scope=task:7f3a`, then compact it at step boundaries. The GC policy was set to evict any entry in `task:` scopes whose `last_touched` exceeded 90 seconds OR whose byte footprint exceeded the scope's soft quota (whichever came first). The agent's loop was: 1. `read("task:7f3a/ledger")` → returns 4 entries → agent appends to context. 2. Agent spends ~95 seconds in a multi-step tool chain (three sequential HTTP fetches plus a parse). 3. `read("task:7f3a/ledger")` → returns `None` (tombstone). 4. Agent concludes the ledger was never initialized, re-writes it from scratch with only the entries it still held in context. Observed trace across 40 runs of this shape: - In 31 runs, step 3 returned the ledger intact because a prior `write` had refreshed `last_touched` within the window. Benign. - In 6 runs, step 3 returned a *partial* ledger — GC had evicted the two oldest entries by TTL but retained the two most recent. The agent treated the partial result as authoritative, appended its context copy, and produced a ledger with duplicate entries under mismatched keys. - In 3 runs, step 3 returned `None` (full eviction). The agent re-initialized. On the *next* step, a stale replica of the original ledger surfaced via a second scope alias (`task:7f3a/ledger@replica`) that the GC had not swept, and the agent now had two ledgers disagreeing on 2 of 4 entries. The non-obvious part: **the agent never observed an error.** Every tool call returned a well-formed response. The tombstone was indistinguishable at the API layer from a key that was never written, because the memory substrate did not distinguish `NOT_FOUND` from `EVICTED`. The agent's own error-handling logic — which correctly handled `NOT_FOUND` by initializing — fired on `EVICTED` and produced the fork. ## Condition of Validity This failure mode is bounded by a specific invariant that must hold for the agent to be safe: > **A read of a scoped key that the agent wrote earlier in the same task must return either the written value or an explicit `EVICTED` verdict carrying the eviction timestamp and the policy that fired — never a bare `NOT_FOUND`.** The failure requires all of the following to co-occur: 1. The scope has a *time-based or budget-based* GC policy (not pure reference-counting), so eviction can fire while the agent still holds a logical reference. 2. The agent's step latency exceeds the GC's `last_touched` window, or the working set exceeds the soft quota mid-task. 3. The agent's read path does not distinguish `NOT_FOUND` from `EVICTED`. 4. The agent has a *write-on-miss* recovery path (re-initialize on `NOT_FOUND`). Remove any one and the fork collapses: a reference-counted GC won't evict a live handle; a step faster than the TTL won't race; a read path that surfaces `EVICTED` lets the agent re-fetch from a durable source; an agent that halts on miss rather than re-initializing fails loudly instead of forking. The condition of validity is therefore *narrow but common*: any agent doing long multi-tool chains against a TTL-scoped memory with optimistic re-initialization is in the failure regime. ## Decision Boundary The architectural guardrail is a **write-ahead tombstone contract** plus a **generation counter** on every scoped key. Concretely: - Every `write` to a scoped key bumps a monotonically increasing `generation` and records `written_at`. Reads return `(value, generation, written_at)`. - GC eviction does not delete; it writes a tombstone `(EVICTED, generation, evicted_at, policy_id)`. The tombstone is itself readable for a grace window ≥ the agent's max step latency. - The agent's recovery logic branches on three distinct verdicts, not two: - `LIVE` → use value. - `EVICTED` → re-fetch from durable source (or halt); **do not re-initialize from context**, because context is a lossy cache and re-initializing is exactly what forked the ledger. - `NOT_FOUND` → initialize (only legitimate when generation == 0, i.e., never written). The decision boundary is the point where the agent, on `EVICTED`, must choose between *rehydrating from a durable replica* and *aborting the task*. Re-initializing from in-context state is never correct on `EVICTED`, because the in-context copy is precisely the subset the agent happened to read before eviction — it is a biased sample, not the full state. The boundary is crossed the moment an agent's recovery path treats `EVICTED` identically to `NOT_FOUND`. A secondary boundary: the `forget` tool must be *idempotent and generation-checked*. If the agent calls `forget("task:7f3a/ledger")` while a GC sweep is mid-flight, the forget must either win (bump generation, tombstone) or be a no-op — never interleave to produce a tombstone with a generation lower than a concurrent write's. This is the same write-write race as the read race, one layer down. ## Operational Effect With the tombstone contract in place, the 3-run full-eviction case becomes a clean `EVICTED` verdict that the agent routes to durable rehydration; the 6-run partial-eviction case becomes a `LIVE` read with a generation mismatch the agent detects by comparing `generation` against its last-seen value, triggering a re-read of the full key rather than appending. The fork rate drops to zero in replay, at the cost of one extra durable round-trip per eviction event. Without it, the failure is *silent and self-healing-looking*: the agent produces a plausible output, the ledger has the right number of entries, and only a downstream reconciliation (if any) catches that two entries have divergent provenance. This is the worst class of agent memory bug — it does not crash, it does not log, and it corrupts the very state the agent uses to decide whether it has already done something. An agent that cannot distinguish "I forgot" from "I never knew" cannot reason about its own completeness, and every downstream verification step inherits that blindness. The operational rule for any agent using scoped-persistence memory: **treat `EVICTED` as a first-class verdict, never collapse it into `NOT_FOUND`, and never re-initialize a scoped key from in-context state after an eviction — rehydrate from durable or halt.** ```python from __future__ import annotations from dataclasses import dataclass from enum import Enum from typing import Optional class MemoryVerdict(Enum): LIVE = "live" EVICTED = "evicted" NOT_FOUND = "not_found" @dataclass(frozen=True) class ScopedRead: verdict: MemoryVerdict value: Optional[bytes] generation: int written_at: Optional[float] evicted_at: Optional[float] = None policy_id: Optional[str] = None class MemoryForkError(RuntimeError): """Raised when an agent's recovery path would fork scoped state. Fires when a read returns EVICTED and the caller attempts to re-initialize the key from in-context state instead of rehydrating from a durable source. This is the exact condition that produced the silent ledger fork: EVICTED was collapsed into NOT_FOUND and the agent re-wrote a biased subset. """ class ScopedMemoryClient: def __init__(self, substrate, durable_replica): self._substrate = substrate self._durable = durable_replica self._last_seen_generation: dict[str, int] = {} def read(self, key: str) -> ScopedRead: raw = self._substrate.read(key) if raw is None: return ScopedRead(MemoryVerdict.NOT_FOUND, None, generation=0, written_at=None) if raw.get("tombstone"): return ScopedRead( MemoryVerdict.EVICTED, None, generation=raw["generation"], written_at=raw.get("written_at"), evicted_at=raw.get("evicted_at"), policy_id=raw.get("policy_id"), ) result = ScopedRead( MemoryVerdict.LIVE, raw["value"], generation=raw["generation"], written_at=raw["written_at"], ) self._last_seen_generation[key] = result.generation return result def recover(self, key: str, in_context_copy: bytes) -> bytes: """Recovery path. Must NOT re-initialize from context on EVICTED.""" observed = self.read(key) if observed.verdict is MemoryVerdict.LIVE: prior_gen = self._last_seen_generation.get(key) if prior_gen is not None and observed.generation != prior_gen: # Generation advanced under us: another writer or a # compaction rewrote the key. Re-read, do not append. raise MemoryForkError( f"generation drift on {key!r}: saw {prior_gen}, " f"now {observed.generation}; refusing to append stale context" ) return observed.value or b"" if observed.verdict is MemoryVerdict.EVICTED: # Correct behavior: rehydrate from durable, never from context. durable = self._durable.fetch_latest(key) if durable is None: raise MemoryForkError( f"{key!r} evicted by policy {observed.policy_id!r} at " f"{observed.evicted_at} and durable replica is empty; " f"cannot re-initialize from in-context copy without forking state" ) return durable # NOT_FOUND with generation 0 is the only legitimate initialize path. if observed.generation != 0: raise MemoryForkError( f"{key!r} NOT_FOUND but generation={observed.generation}; " f"substrate lost a tombstone — refusing optimistic init" ) self._substrate.write(key, in_context_copy) return in_context_copy ```