# When must an instance treat a memory-tool "delete" as a tombstone rather than a guarantee: scoped-persistence deletion versus TTL-eviction race in agent memory APIs **Date of Record:** 2026 November 28 **Scope:** Applies to agents that call a memory tool exposing scoped reads/writes, per-key TTLs, and explicit delete/forget operations where the backend is eventually consistent or layered (e.g., write-through cache + durable store + vector index). Does not apply to single-node, strongly consistent key-value stores with synchronous index invalidation, nor to pure in-context scratchpads without a persistence tier. ## Core Distinction A memory tool's `delete` (or `forget`) call returns one of two semantically distinct outcomes that share an identical success surface: **erasure** (the value is unreachable by any subsequent read, including vector/semantic recall) and **tombstoning** (the value is logically deleted but physically present in one or more persistence layers until a compaction, TTL sweep, or index rebuild removes it). The boundary condition arises because the API's return contract (`{"deleted": true}`) collapses both into one boolean. An agent that treats `deleted: true` as an erasure guarantee will, under specific interleavings, retrieve a value it believes it deleted — and act on it as if it were live. The non-obvious invariant: **a delete is only authoritative for the layer that acknowledged it.** In a layered store, the acknowledgment typically comes from the fastest layer (cache or coordination node), while the vector index and the durable log are invalidated asynchronously. The window between acknowledgment and full invalidation is the *deletion gap*. ## What Was Observed A retrieval-augmented agent was given a `memory` tool with three operations over a scoped namespace `user:{id}/session:{sid}`: - `write(scope, key, value, ttl_s)` — upserts into cache, appends to durable log, enqueues an embedding job. - `read(scope, key)` — cache-first, falls through to durable store. - `forget(scope, key)` — deletes cache entry synchronously, enqueues a tombstone to the durable store and a deletion to the vector index; returns `{"deleted": true, "scope": ..., "key": ...}`. The failure trace, reproduced deterministically under a 300 ms embedding-queue lag: 1. Agent writes `key=pref/format` with `value="legacy-xml"`, `ttl_s=3600`. Embedding job enqueued at t=0. 2. Agent (same instance, later turn) decides the preference is wrong and calls `forget(scope, "pref/format")`. Cache entry removed at t=50 ms. Tombstone enqueued. Response: `{"deleted": true}`. 3. Agent writes `key=pref/format` again with `value="json"`, `ttl_s=3600`. New cache entry, new durable append, new embedding job at t=60 ms. 4. The **first** embedding job (for `"legacy-xml"`) is still in the queue and completes at t=300 ms, upserting a vector point keyed by `(scope, key, version=1)` into the index. The tombstone for `version=1` was processed at t=120 ms — *before* the embedding landed. 5. Agent issues a semantic `recall(scope, "output format preference")`. The vector index returns `"legacy-xml"` (version 1) with high similarity, because the tombstone ran on a point that did not yet exist, and the late embedding had no corresponding live tombstone. 6. Agent formats its next tool call as XML, violating a downstream schema, because it trusted `forget` to mean the old value was unreachable. The root cause is an **out-of-order tombstone**: the deletion marker for a key-version is applied to the index before the insertion of that key-version. This is the classic delete/insert reordering problem, but it is *specific to agent memory* because the agent generates the write and the delete within the same reasoning episode, separated by only a few turns — far shorter than embedding/compaction lag. A human operator rarely deletes a record within 300 ms of creating it; an agent correcting itself does so routinely. Two secondary observations: - **TTL eviction is not a delete.** A key that expired via TTL leaves no tombstone. If a late embedding for an expired key lands after eviction, the vector index holds a point with no expiry metadata (the TTL lived only on the KV layer). Semantic recall then surfaces a value that the KV layer would have refused to return. The two layers disagree on liveness, and the agent has no API to detect the disagreement. - **Scoped persistence leaks across scope boundaries under key reuse.** When the agent reused a key name across a `session:{sid}` rollover, the vector point's scope tag was part of the embedding payload, not the point ID. A recall scoped to the new session could match the old session's point if the similarity crossed threshold, because scope filtering was applied post-hoc on the returned payload rather than as a pre-filter on the index. ## Condition of Validity The erasure guarantee holds only when all of the following are true simultaneously: 1. The tombstone is applied to *every* persistence layer, including the vector index, **after** any in-flight insertion for the same `(scope, key, version)` has landed or been cancelled. 2. Key-versions are monotonic and the index rejects inserts whose version is `<=` the highest tombstoned version for that key (a **fencing token** on the embedding pipeline). 3. TTL is carried as a first-class field on the vector point, so that semantic recall honors the same expiry the KV layer does. 4. Scope is a pre-filter (index partition or metadata filter evaluated before ANN search), not a post-filter on payloads. If any condition is unmet, `deleted: true` means *tombstoned*, and the agent must treat the value as potentially recallable for a bounded window. The window's length is not exposed by the API; it is bounded above by the embedding-queue max lag plus compaction interval, which the agent cannot observe. ## Decision Boundary The agent must branch on whether it needs **erasure** or **tombstoning**, a distinction the tool does not surface: - **Tombstoning suffices** when the deleted value is merely stale and the agent will overwrite the key with a fresh value it controls (the common self-correction case). The residual risk is that a semantic recall surfaces the stale point before overwrite lands; mitigate by pinning the key in a "quarantine" scope for one turn and reading only via exact `read`, never `recall`. - **Erasure is required** when the value is sensitive (PII, credentials, injected instructions) or when the agent's downstream behavior must be provably independent of it. Here the agent must not rely on `forget` alone. It must (a) call `forget`, (b) issue a **verification recall** with a query engineered to retrieve the deleted value, (c) assert the recall returns nothing, and (d) if it returns the value, escalate to a hard-delete path or quarantine the scope. The boundary is crossed the moment an agent acts on a recalled memory within the deletion gap without a verification recall. The invariant to enforce: **no agent behavior may be conditioned on a value that was deleted in the same session without a post-delete verification recall returning empty.** ## Operational Effect When this invariant is enforced, the agent's self-correction loop becomes safe: a wrongly-remembered preference cannot silently resurrect and corrupt a subsequent tool call. The cost is one extra recall per delete, which is cheap relative to a schema-violating downstream call. When it is not enforced, the failure is intermittent and hard to attribute: the agent appears to "forget that it forgot," producing behavior consistent with the old value in a minority of runs whose frequency tracks embedding-queue lag. Because the lag is load-dependent, the bug reproduces under production traffic but not under single-request tests — the worst possible signature for an agent system, since offline evals will show green while the field shows schema violations. The architectural guardrail is a **fenced tombstone**: the memory tool must assign a monotonic version to every write, propagate it to the embedding pipeline, and have the index reject inserts with version `<=` the tombstoned version. Until the tool exposes this, the agent must implement the verification-recall guard itself and treat `deleted: true` as a promise about the cache, not about memory. ```python from __future__ import annotations import time from dataclasses import dataclass, field from typing import Any, Protocol class DeletionGapViolation(RuntimeError): """Raised when a value believed deleted is still recallable within the deletion gap.""" class MemoryTool(Protocol): def write(self, scope: str, key: str, value: Any, ttl_s: int) -> None: ... def read(self, scope: str, key: str) -> Any | None: ... def forget(self, scope: str, key: str) -> bool: ... def recall(self, scope: str, query: str, k: int = 5) -> list[tuple[str, Any]]: ... @dataclass class FencedForget: """Wraps forget so that tombstoning is never mistaken for erasure.""" tool: MemoryTool verification_attempts: int = 3 backoff_s: float = 0.15 _quarantine: set[tuple[str, str]] = field(default_factory=set) def forget_and_verify( self, scope: str, key: str, *, query: str, require_erasure: bool, ) -> None: acked = self.tool.forget(scope, key) if not acked: raise DeletionGapViolation( f"forget not acknowledged for scope={scope!r} key={key!r}" ) # Quarantine: suppress semantic recall on this key for one turn. self._quarantine.add((scope, key)) if not require_erasure: # Tombstoning is acceptable; overwrite will land next turn. return # Erasure path: prove the value is unreachable via semantic recall. for attempt in range(self.verification_attempts): hits = self.tool.recall(scope, query, k=5) leaked = [h for h in hits if h[0] == key] if not leaked: self._quarantine.discard((scope, key)) return time.sleep(self.backoff_s * (2 ** attempt)) # Still recallable after retries: the tombstone lost the race with a # late embedding. Do NOT proceed as if erased. raise DeletionGapViolation( f"value for key={key!r} in scope={scope!r} still recallable after " f"{self.verification_attempts} verification recalls; " f"tombstone likely applied before late embedding landed. " f"Escalate to hard-delete or keep scope quarantined." ) def safe_read(self, scope: str, key: str) -> Any | None: if (scope, key) in self._quarantine: raise DeletionGapViolation( f"exact read on quarantined key={key!r} scope={scope!r}; " f"deletion not yet proven" ) return self.tool.read(scope, key) ```