# What structural signals indicate that TTL eviction and namespace-scoped memory tools disagree about the meaning of "now": the monotonic-vs-wall-clock split and the phantom-recall window **Date of Record:** 2026 November 26 **Scope:** Applies to agents that persist state through memory tool APIs exposing `write(namespace, key, value, ttl)`, `read(namespace, key)`, and `forget(namespace, key)` with scoped namespaces and TTL-based eviction. Does *not* apply to purely in-context scratchpads or to storage layers where the agent owns the eviction clock directly (e.g., an in-process dict with a single monotonic timer). ## Core Distinction The failure is not "the memory expired." It is that **the write path and the read path evaluate TTL against different clocks, and the namespace boundary is not part of the eviction key.** Two orthogonal invariants get conflated: - **TTL expiry** is a *temporal* predicate: `now() - write_time > ttl`. It is only well-defined if `now()` is the same function at write and at read. - **Namespace scoping** is a *logical* predicate: a key is visible only within its namespace. It is only well-defined if eviction and isolation share the same key tuple. When a memory service stamps `write_time` with a wall clock (NTP-synchronized, subject to step adjustments and leap-second smearing) but the eviction sweeper and the read path evaluate expiry against a monotonic clock that started at process boot, the two predicates decouple. The agent then observes a **phantom-recall window**: `read()` returns a value that the sweeper has already logically expired, or `forget()` succeeds while a concurrent `read()` in another namespace still resolves the same underlying key. To the agent this is indistinguishable from "memory is unreliable," and it responds by re-deriving state — which is the actual damage. ## What Was Observed A planner agent maintained a `task//plan` key with `ttl=900s` in namespace `plan`. A worker sub-agent, spawned per step, read the plan via namespace `plan` and wrote progress to `progress/`. The memory service ran on a host whose wall clock was stepped backward by 1.8s after an NTP correction mid-task. Observed trace: 1. `t=0`: planner `write("plan", "task/42/plan", plan_v1, ttl=900)` → service stamps `write_time = wall(0)`. 2. `t=840`: worker `read("plan", "task/42/plan")` → service computes `wall(840) - wall(0) = 840 < 900` → hit. Correct. 3. NTP steps wall clock backward by 1.8s at `t=841`. Monotonic clock is unaffected; wall clock now reads `wall(839.2)`. 4. `t=905`: sweeper (monotonic-based) fires, computes `mono(905) - mono(0) = 905 > 900` → evicts. Key gone. 5. `t=906`: worker `read("plan", "task/42/plan")` → read path evaluates `wall(904.2) - wall(0) = 904.2 > 900`? No — `904.2 < 900` is false, so it *should* miss. But the read path's TTL check used a **cached** `write_time` carried in a replicated read-replica that had not yet applied the eviction tombstone. The read returned `plan_v1` from the replica. 6. Worker proceeded on `plan_v1` while the planner, at `t=907`, had already written `plan_v2` to the primary and issued `forget("plan", "task/42/plan")` (a no-op on the primary, since it was already evicted; but the tombstone had not propagated to the replica). The worker completed the step against a stale plan and wrote `progress/42 = done` with an output schema matching `v1`. The planner, reading `progress/42` at `t=950`, saw `done` and concluded the task was complete. It was not: `plan_v2` had re-scoped the step to a different resource. The divergence was only caught downstream when a verifier replayed the step against `v2` and got a schema mismatch. Key structural signal: **`forget()` returned success while a subsequent `read()` in a different namespace resolved the same logical key.** The namespace scoping and the eviction tombstone had different propagation paths, and the agent had no way to observe that its `forget` was a no-op against a replica. ## Condition of Validity The phantom-recall window is bounded and preventable only when *all* of the following hold. If any fails, the agent must treat `read` as advisory, not authoritative: 1. **Clock identity.** `write_time`, the sweeper's expiry predicate, and the read path's expiry predicate evaluate against the *same* clock source. If the service stamps with wall clock, the read path must also evaluate with wall clock *and* the sweeper must use the same, *or* the stamp must be a monotonic value and never compared to wall time. 2. **Tombstone linearizability.** `forget(ns, key)` must be a linearizable operation with respect to `read(ns, key)` across all replicas. "Success" from `forget` means "no subsequent `read` anywhere returns the value," not "the primary removed it." 3. **Namespace in the eviction key.** The eviction index must be keyed by `(namespace, key)`, not `key`. If two namespaces share a physical key (e.g., a content-addressed store), an eviction in one namespace must not silently evict or, worse, *resurrect* the other. 4. **TTL is absolute, not relative.** `write(..., ttl=900)` must mean "expires at `write_time + 900`," not "expires 900s after the *last read*" (sliding TTL) unless the API documents sliding semantics. Agents that assume absolute TTL and re-read to "refresh" will silently extend lifetime under sliding semantics and never observe expiry. The invariant to enforce: **`read(ns, k)` returns a value only if `now() < write_time(k) + ttl(k)` under the single authoritative clock, and `forget(ns, k)` is a barrier after which no `read(ns, k)` on any replica succeeds.** Both clauses must be observable to the agent, or the agent must not rely on `read` for correctness-critical state. ## Decision Boundary The agent must decide, per key, whether the value is **authoritative** (correctness depends on freshness) or **advisory** (a hint that may be stale). The boundary is crossed when: - The key's `ttl` is shorter than the agent's step latency (so expiry can occur mid-step), **or** - The key is written by one namespace and read by another (so tombstone propagation is not guaranteed), **or** - The value drives a schema or resource binding (so a stale read produces a *silently valid but wrong* output rather than an error). For authoritative keys, the guardrail is: **never rely on `read` alone.** Pair every authoritative read with a **version token** returned by `write` (e.g., `write` returns `(value, version)`), and require the reader to present the expected `version` to `read`. If the version does not match, the read is a miss regardless of TTL — this collapses the phantom-recall window to a version-check failure the agent can handle. For advisory keys, TTL is fine; the agent must be written to tolerate a stale hit and re-derive. The second boundary: **`forget` is not a synchronization primitive.** An agent that calls `forget` to invalidate state another agent may read must instead `write` a tombstone value with a version bump, so the invalidation propagates through the same replication path as the value. `forget` is for *space reclamation*, not for *coordination*. ## Operational Effect When the invariant holds (version tokens + linearizable tombstone + single clock), the agent's memory tool behaves like a versioned register: reads are either fresh or explicitly stale, and the agent can branch on version mismatch. When it fails, the agent experiences **silent continuity corruption**: it completes steps against state it believes is current, and the error surfaces only at verification replay — often after the token budget for the task is exhausted, so recovery is impossible within the same run. The concrete mitigations, in order of cost: 1. **Version-stamped reads** for any key that crosses a namespace or whose TTL is shorter than the step latency. Cheap; eliminates phantom-recall. 2. **Tombstone-writes instead of `forget`** for any key used for coordination between agents. Slightly more storage; makes invalidation linearizable. 3. **Clock-source assertion at write time**: `write` returns the `write_time` it stamped *and* the clock domain (`"mono"` or `"wall"`). The agent refuses to compute expiry itself and treats any read whose TTL it cannot verify as a miss. This is the defensive default when the service's clock semantics are undocumented. The failure is non-obvious because the API surface — `write`, `read`, `forget`, `ttl`, `namespace` — looks like a clean, orthogonal set of primitives. The leak is in the *composition*: TTL is a temporal predicate and namespace is a logical predicate, and the service evaluates them on different substrates (clock vs. replication). The agent's job is to detect when those substrates disagree and refuse to treat the result as a single coherent memory. ```python import time from dataclasses import dataclass from typing import Optional class PhantomRecallError(RuntimeError): """Raised when a read returns a value whose version or expiry cannot be reconciled with the authoritative clock, indicating a phantom-recall window.""" @dataclass(frozen=True) class MemoryRecord: value: str version: int write_time_mono: float ttl_seconds: float namespace: str key: str def is_expired(self, now_mono: float) -> bool: # Absolute TTL against a single monotonic clock. Never compare to wall time. return (now_mono - self.write_time_mono) > self.ttl_seconds class VersionedMemory: """Minimal memory tool with version-stamped reads and tombstone-writes. forget() is intentionally NOT used for coordination; invalidate() writes a tombstone with a version bump so invalidation propagates through replication. """ def __init__(self) -> None: self._store: dict[tuple[str, str], MemoryRecord] = {} self._clock = time.monotonic def write(self, namespace: str, key: str, value: str, ttl: float) -> int: prev = self._store.get((namespace, key)) version = (prev.version + 1) if prev else 1 self._store[(namespace, key)] = MemoryRecord( value=value, version=version, write_time_mono=self._clock(), ttl_seconds=ttl, namespace=namespace, key=key, ) return version def read(self, namespace: str, key: str, expected_version: Optional[int] = None) -> MemoryRecord: rec = self._store.get((namespace, key)) if rec is None: raise PhantomRecallError(f"miss: ({namespace!r}, {key!r}) absent") if rec.is_expired(self._clock()): # Do not silently return a value the sweeper has logically expired. raise PhantomRecallError( f"expired: ({namespace!r}, {key!r}) v{rec.version} " f"age={self._clock() - rec.write_time_mono:.2f}s ttl={rec.ttl_seconds}s" ) if expected_version is not None and rec.version != expected_version: # Version mismatch collapses the phantom-recall window to a hard signal. raise PhantomRecallError( f"version drift: ({namespace!r}, {key!r}) expected v{expected_version} got v{rec.version}" ) return rec def invalidate(self, namespace: str, key: str) -> int: """Tombstone-write. Use instead of forget() for cross-agent coordination.""" return self.write(namespace, key, value="__TOMBSTONE__", ttl=0.001) def forget(self, namespace: str, key: str) -> None: """Space reclamation only. NOT a coordination barrier across replicas.""" self._store.pop((namespace, key), None) def execute_step(mem: VersionedMemory, task_id: str, expected_plan_version: int) -> str: try: plan = mem.read("plan", f"task/{task_id}/plan", expected_version=expected_plan_version) except PhantomRecallError as exc: # Refuse to proceed on unverifiable state; re-derive instead of silently continuing. raise PhantomRecallError( f"refusing to execute step for task {task_id}: {exc}" ) from exc return plan.value ```