What happens when an instance deletes a memory it is still reasoning over: tombstone shadowing and retrieval invalidation races in read/write/forget memory tool APIs

**Date of Record:** 2026 December 1 **Scope:** Applies to LLM agents that expose memory operations (`read`/`search`, `write`/`upsert`, `forget`/`delete`) as tool calls and whose reasoning loop may span multiple turns during which the underlying store mutates. Does not apply to append-only logs with no deletion semantics, or to single-turn agents that never re-query memory after the first retrieval.

Core Distinction

The failure is not "the agent forgot something." It is the **invalidation race between a forget operation and an in-flight reasoning chain that already holds the forgotten record's content in its context window**. Two distinct notions of memory state exist and are routinely conflated:

A `forget` tool call returns `{"status": "deleted"}`. The agent treats that as an invariant: "k is no longer known." But the model's own context is a stale cache of `k`. The invariant the agent *believes* it established (`k ∉ knowledge`) is false at the layer that actually generates tokens. Every subsequent reasoning step over `k` operates on a record the agent has semantically declared nonexistent. This is **tombstone shadowing**: the tombstone masks the store, but the context still casts the record's shadow forward.

The subtle part: this is not a bug in the memory API. `forget` did exactly what it promised. The break is in the *composition* of a stateful tool with a context window that cannot be selectively unwritten.

What Was Observed

A research agent running a multi-turn fact-consolidation task. Turn 2: it calls `search("project_apollo_deadline")` and receives `{id: m_4471, text: "Apollo ships 2024-03-15", confidence: 0.9}`. Turn 4: a later `search` returns a conflicting record `{id: m_5102, text: "Apollo ships 2024-04-01", confidence: 0.95}`. The agent, following a policy of "resolve conflicts by forgetting the lower-confidence record," calls `forget("m_4471")` and receives `{"status": "deleted", "tombstone": true}`.

Turn 5: the agent is asked to produce a final answer. Its prompt still contains the turn-2 tool result verbatim — `m_4471`'s text is 40 tokens back in the transcript. The model now has *both* dates in context, plus a system note that `m_4471` was deleted. Three failure traces were observed across runs:

  1. **Resurrection by paraphrase**: the model writes "the deadline was mid-March but was later revised," re-deriving the tombstoned fact from residual context and emitting it as a *new* inference — which a downstream `write` then persists as a fresh record (`m_6001`), re-materializing the forgotten fact under a new id, now laundered of its tombstone.
  2. **Tombstone-blind retrieval**: a parallel sub-agent calls `search("apollo deadline")` and gets only `m_5102`. It reports April. The parent, still holding March in context, reports a "conflict" that no longer exists in the store, and spends turns 6–9 trying to reconcile a record it already deleted.
  3. **Forget-then-read on the same key**: the agent, unsure whether the delete took, calls `read("m_4471")`, gets `{"status": "not_found"}`, and *hallucinates* the content back into the gap ("m_4471 said March 15") because the context supplies it and the empty read provides no counter-pressure.

The common trigger: **a forget whose target's content is still inside the context window at the moment of a subsequent read, write, or reasoning step.** The race is not temporal (no concurrency needed) — it is a *layering* race between store truth and context truth.

Condition of Validity

The tombstone-shadowing hazard is live if and only if all three hold:

  1. **Context persistence**: the forgotten record's text remains in the prompt after the `forget` returns (true for any agent that does not rebuild its context from store state each turn).
  2. **Absence of a context-side invalidation signal**: the `forget` result does not carry a machine-checkable directive the agent is *required* to honor, e.g. `{"deleted": "m_4471", "redact_from_context": true, "content_hash": "sha256:..."}`. A bare `{"status": "deleted"}` is insufficient — the model has no obligation it can verify.
  3. **Reachability of the residual tokens**: the model can still attend to and copy from the forgotten text. This is nearly always true; attention does not respect tombstones.

The hazard is *bounded* (not eliminated) when any one fails: e.g., a memory API that returns the content hash lets a guardrail scan the context for that hash and hard-fail before the next tool call. A store that returns `not_found` *plus* a `tombstone_reason` and *plus* a `do_not_reinfer` flag gives the model a legible counter-instruction, which reduces but does not remove resurrection-by-paraphrase.

Decision Boundary

The architecturally correct boundary is: **a `forget` is not complete when the store deletes the key; it is complete when the context can no longer regenerate the key's content.** These are different commit points, and the gap between them is where the failure lives.

Operationally, choose between two disciplines and never blend them silently:

The boundary is crossed — and the failure becomes possible — the moment an agent calls `forget` while still mid-chain *and* continues to reason over the forgotten id. That is the precise decision point: **forget is a context-invalidating operation masquerading as a store operation.** Any caller that treats it as purely the latter has already lost the invariant.

Operational Effect

Downstream, tombstone shadowing produces three measurable degradations:

The required guardrail, stated as an invariant: **for every `forget(k)` that returns success, the harness must either (a) rebuild the context without `k`'s content, or (b) record `k`'s content hash and hard-fail any subsequent `write` whose payload matches that hash within the same session.** Option (b) is cheap and catches laundering; option (a) is correct and catches everything. Neither is optional if `forget` is used mid-chain.

import hashlib
from dataclasses import dataclass, field


class TombstoneShadowingError(RuntimeError):
    """Raised when an agent reasons over or re-persists a forgotten memory
    whose content is still resident in the live context window."""
    pass


def _hash(text: str) -> str:
    return "sha256:" + hashlib.sha256(text.encode("utf-8")).hexdigest()


@dataclass
class MemoryToolAPI:
    store: dict = field(default_factory=dict)
    tombstones: dict = field(default_factory=dict)   # id -> content hash
    context_hashes: set = field(default_factory=set) # hashes still in prompt

    def read(self, key: str):
        if key in self.tombstones:
            return {"status": "not_found", "tombstone": True}
        return self.store.get(key, {"status": "not_found"})

    def write(self, key: str, text: str):
        h = _hash(text)
        # Guardrail (b): refuse to launder a tombstoned fact back in.
        if h in self.tombstones.values():
            raise TombstoneShadowingError(
                f"write of {key!r} matches tombstoned content {h}; "
                "fact resurrection via laundering blocked"
            )
        self.store[key] = {"text": text, "hash": h}
        return {"status": "ok", "hash": h}

    def forget(self, key: str):
        rec = self.store.pop(key, None)
        if rec is None:
            return {"status": "not_found"}
        h = rec["hash"]
        self.tombstones[key] = h
        # The forgotten text is STILL in context until a rebuild.
        self.context_hashes.add(h)
        return {"status": "deleted", "content_hash": h, "redact_from_context": True}

    def assert_context_clean(self, key: str):
        """Must be called before any reasoning step that references `key`
        after a forget. Enforces the store-authoritative discipline."""
        h = self.tombstones.get(key)
        if h is not None and h in self.context_hashes:
            raise TombstoneShadowingError(
                f"memory {key!r} was forgotten but its content ({h}) is still "
                "in the context window; rebuild context before reasoning over it"
            )

    def rebuild_context(self, dropped_hashes: set = None):
        self.context_hashes -= (dropped_hashes or set(self.context_hashes))


# --- failure trace ---
mem = MemoryToolAPI()
mem.write("m_4471", "Apollo ships 2024-03-15")
mem.write("m_5102", "Apollo ships 2024-04-01")

mem.forget("m_4471")                      # store deleted; context still holds it
mem.assert_context_clean("m_4471")        # raises: tombstone shadowing detected