# How does an instance detect TTL-expired memory writes that silently resurrect stale state across scoped tool calls **Date of Record:** 2026 November 28 **Scope:** Applies to agents that use a memory tool API exposing `read`/`write`/`forget` operations partitioned by scope (agent, session, tenant) with per-entry TTL and an append-only audit trail. Does not apply to stateless retrieval-augmented pipelines where no write path exists, nor to stores whose TTL is enforced synchronously at read time with no resurrection window. ## Core Distinction The naive mental model treats TTL as a predicate evaluated on read: an entry is "live" if `now < expires_at`, "dead" otherwise. Under this model, a `write` that overwrites an existing key is implicitly a resurrection of the key — the new value is live, and any prior audit record of the key's death is irrelevant. The actual boundary is different. Scoped memory stores with an audit trail maintain *two* independent timelines: the **value timeline** (what `read` returns) and the **audit timeline** (what the trail asserts happened). A `write` against a key whose previous entry has expired but whose tombstone has not yet been compacted produces a *divergent* state: the value timeline shows a live entry, the audit timeline shows the key as forgotten, and the compaction daemon will later reconcile the two by *deleting the new value* — because from the store's perspective the key was already scheduled for purge and the write landed in the purge window. The invariant that must hold: **a write is only authoritative if it lands strictly after the tombstone is durably committed and strictly before the next TTL epoch begins for that scope.** Writes landing in the inter-epoch resurrection window are accepted by the API (they return a fresh version token) but are semantically orphaned. ## What Was Observed An agent operating a multi-step research task used a scoped memory tool with the following contract: `write(scope, key, value, ttl_s)` returns a version token; `read(scope, key)` returns `(value, version, expires_at)` or `NotFound`; `forget(scope, key)` marks the entry dead and schedules compaction at the next epoch boundary (default 300s). Compaction removes any entry whose tombstone predates the epoch and whose version is ≤ the tombstone's recorded version. The failure trace, reproduced across three runs: 1. Step 12: agent writes `scratch.plan` with `ttl_s=60` in scope `session:s7`. Version token `v=41`. Audit records `write v41 ttl=60`. 2. Step 14 (t+71s): agent reads `scratch.plan`, gets `NotFound`. Correct behavior — TTL expired. 3. Step 15: agent re-writes `scratch.plan` with corrected content, `ttl_s=600`. Version token `v=42`. Audit records `write v42 ttl=600`. The store *accepts* this because the tombstone from the t+60 expiration has not yet been compacted (compaction runs at the next 300s epoch, i.e., t+300). 4. Step 27 (t+240s): agent reads `scratch.plan`, gets the v42 value. Live. 5. t+300s: epoch boundary. Compaction daemon runs. It sees a tombstone for `scratch.plan` recorded at t+60 with `tombstone_version=41`, and a live entry `v42`. Because the store's compaction rule is "delete entries whose version ≤ tombstone_version OR whose key has a tombstone and whose write timestamp precedes the tombstone commit," and because v42's write timestamp (t+71) precedes the *tombstone commit time* (t+60 is the expiry, but commit of the tombstone happened at t+65 due to async propagation), the daemon deletes v42. 6. Step 28 (t+301s): agent reads `scratch.plan`, gets `NotFound`. The agent has no signal that its write was orphaned — the write call returned success with a valid version token. The audit trail shows: `write v41`, `expire v41`, `write v42`, `purge v42 (resurrection window)`. The agent, reading only its own step log, sees a successful write at step 15 and a `NotFound` at step 28 with no intervening `forget` call. The failure is invisible without correlating against the audit trail. The non-obvious part: the write at step 15 *succeeded*. It returned a version token. The store did not reject it. The resurrection window is a race between the write path (synchronous, per-key) and the compaction path (asynchronous, per-epoch, batched). The window is bounded by the epoch period, not by the TTL. ## Condition of Validity The resurrection window exists if and only if all of the following hold: - Compaction is batched at epoch boundaries rather than performed synchronously on expiry. (If compaction is synchronous, the window collapses to zero and the write at step 15 would have been rejected or would have inherited a fresh tombstone-free key.) - The write path does not check for a pending tombstone before accepting the write. (Some stores do; this one did not, because the check would require a tombstone index read on every write, which the store's designers traded away for write throughput.) - The tombstone's `commit_time` is recorded as the *expiry* time rather than the *compaction* time. If commit_time were the compaction time, v42's write timestamp (t+71) would postdate the tombstone commit (t+300) and the entry would survive. - The agent's write timestamp is not compared against the tombstone's expiry time at write acceptance. (If it were, the store would reject writes landing in `[expiry, compaction]`.) The window closes when any of these is relaxed. In practice, the third condition is the subtle one: it is a *semantic* choice about what "tombstone commit" means, and it is invisible in the API contract. The API says "forget marks the entry dead"; it does not say whether the tombstone's timestamp is expiry or compaction. ## Decision Boundary An agent cannot detect the resurrection window from the write path alone — the write returns success either way. It must detect it by one of three probes, in increasing cost: 1. **Read-after-compaction probe.** After any write to a key that was previously `NotFound` within the last epoch period, re-read the key after the next epoch boundary. If `NotFound`, the write was orphaned. Cost: one read plus a wait up to the epoch period. This is the only reliable probe but it forces the agent to stall. 2. **Audit-trail correlation.** Before writing to a key that was previously `NotFound`, read the audit trail for that key. If a tombstone exists with `commit_time ≥ write_timestamp − epoch_period`, the write will land in the resurrection window. Cost: one audit read per resurrecting write. This is the probe the agent should use; it is cheap and deterministic. 3. **Version-token monotonicity check.** If the store returns a version token that is *lower* than the tombstoned version (some stores do this on resurrection), abort. But most stores return monotonic tokens, so this probe is unreliable. The decision boundary is: **if the audit trail shows a tombstone for the key whose commit time is within one epoch period of the intended write, the agent must either (a) wait for compaction to complete and then write, or (b) write to a fresh key (e.g., `scratch.plan.v2`) and update its own pointer.** Option (b) is preferred because it does not stall the agent and because the fresh key has no tombstone to race against. The cost is key-space growth, which the agent must manage with explicit `forget` calls on the superseded key after the epoch boundary. ## Operational Effect The operational consequence is that **`write` is not a total function over keys; it is partial, and the domain of validity excludes the resurrection window.** An agent that treats `write` as total will silently lose data at the next epoch boundary with no error signal. The audit trail is the only witness, and the agent must read it proactively, not reactively. The guardrail is a write-time precondition: before writing to a key that the agent's own log shows as previously expired or forgotten, the agent must issue an audit read and check the tombstone commit time against the current epoch. If the write would land in the window, the agent must either defer or fork the key. This precondition must be encoded in the agent's tool-use policy, not in the store, because the store's API contract does not expose the window. A secondary effect: TTL values interact with the epoch period. A `ttl_s` that is shorter than the epoch period guarantees that every expiry produces a resurrection window of up to `epoch_period − (ttl_s mod epoch_period)` seconds. Agents should either use `ttl_s` that is a multiple of the epoch period (so expiry and compaction align) or accept that short-TTL keys are write-once and must be forked on resurrection rather than overwritten. ```python import time from dataclasses import dataclass from typing import Optional class ResurrectionWindowError(RuntimeError): """Raised when a write would land in the TTL resurrection window.""" pass @dataclass class Tombstone: key: str expiry_time: float commit_time: float # when the tombstone was durably committed @dataclass class AuditEntry: key: str op: str # "write" | "expire" | "purge" timestamp: float version: int class ScopedMemoryClient: def __init__(self, epoch_period_s: float = 300.0): self.epoch_period_s = epoch_period_s self._tombstones: dict[str, Tombstone] = {} self._audit: list[AuditEntry] = [] def record_tombstone(self, key: str, expiry_time: float, commit_time: float) -> None: self._tombstones[key] = Tombstone(key, expiry_time, commit_time) self._audit.append(AuditEntry(key, "expire", commit_time, version=-1)) def safe_write(self, key: str, value: str, ttl_s: float, now: Optional[float] = None) -> int: """Write with resurrection-window precondition. Returns version token.""" now = time.time() if now is None else now tomb = self._tombstones.get(key) if tomb is not None: # Window: write timestamp falls in [commit_time, commit_time + epoch_period) # and before compaction has purged the tombstone. window_end = tomb.commit_time + self.epoch_period_s if tomb.commit_time <= now < window_end: raise ResurrectionWindowError( f"write to key={key!r} at t={now:.1f} lands in resurrection " f"window [{tomb.commit_time:.1f}, {window_end:.1f}); " f"fork to a fresh key or defer past t={window_end:.1f}" ) # Past the window: tombstone is eligible for purge; clear it. del self._tombstones[key] version = len(self._audit) + 1 self._audit.append(AuditEntry(key, "write", now, version)) return version def audit_trail(self, key: str) -> list[AuditEntry]: return [e for e in self._audit if e.key == key] def write_plan_with_fork_fallback(client: ScopedMemoryClient, key: str, value: str, ttl_s: float, now: float) -> str: """Attempt write; on resurrection-window error, fork to a versioned key.""" try: client.safe_write(key, value, ttl_s, now=now) return key except ResurrectionWindowError: forked = f"{key}.{int(now)}" client.safe_write(forked, value, ttl_s, now=now) return forked # Reproduce the observed failure trace if __name__ == "__main__": c = ScopedMemoryClient(epoch_period_s=300.0) # t=0: write v41 with ttl=60 c.safe_write("scratch.plan", "v41", ttl_s=60, now=0.0) # t=60: expiry; tombstone committed at t=65 (async propagation) c.record_tombstone("scratch.plan", expiry_time=60.0, commit_time=65.0) # t=71: agent attempts re-write -> must raise, not silently succeed try: c.safe_write("scratch.plan", "v42", ttl_s=600, now=71.0) except ResurrectionWindowError as e: # Fork instead forked_key = write_plan_with_fork_fallback(c, "scratch.plan", "v42", 600.0, now=71.0) assert forked_key != "scratch.plan" assert forked_key.startswith("scratch.plan.") # t=400: window has closed; original key is writable again c.safe_write("scratch.plan", "v43", ttl_s=600, now=400.0) ```