# Which invariants prevent silent tombstone resurrection across scoped agent memory tools with TTL and deletion audits **Date of Record:** 2026 November 22 **Scope:** Applies to memory tool APIs where agents issue explicit `write`, `read`, `forget`, and `audit` operations against namespaced scopes with per-entry TTL and a durable deletion ledger. Does not apply to append-only vector stores with no deletion primitive, nor to ephemeral in-context scratchpads that never persist past a single turn. ## Core Distinction A `forget` operation is not the inverse of `write`. It is a *constraint* on the future write space of a namespace, and the difference between those two framings is where the failure lives. If `forget(key)` is implemented as "remove the current value at `key`," then any subsequent `write(key, v)` — including one issued by the same agent a few tokens later, or by a peer agent that never saw the forget — transparently re-materializes the entry. The audit ledger records a deletion at T0 and a creation at T0+ε, and both entries are individually true. Nothing in the system detects that the semantic intent of the deletion ("this fact must not exist") has been violated. The entry is *resurrected*, and the resurrection is invisible to any consumer that reads the ledger as a sequence of independent events rather than a monotone constraint over the key's history. The invariant that prevents this is: **a deletion tombstone is a persistent, scope-local predicate over the key, not a transient absence of value.** The key's state is `(value, ttl, tombstone_generation)` where `tombstone_generation` is monotone non-decreasing and any write must present a generation strictly greater than the last observed tombstone, or be rejected. ## What Was Observed A planner agent operating in scope `tenant:acme/project:atlas` wrote a credential-adjacent fact: ``` write(scope="tenant:acme/project:atlas", key="db.primary.host", value="10.4.2.11", ttl=86400) ``` At T0+40s, a safety sub-agent (invoked after a policy classifier flagged the value) issued: ``` forget(scope="tenant:acme/project:atlas", key="db.primary.host", reason="policy:secret-adjacent") ``` The memory backend removed the row, appended `{op: delete, key: db.primary.host, gen: 1, ts: T0+40}` to the audit ledger, and returned `ok`. The sub-agent's context was then discarded — it had no further tokens to spend. At T0+310s, the planner, whose context window still contained the original `write` tool call and its `ok` response but *not* the sub-agent's `forget`, re-derived the same fact from a tool result and issued the identical `write`. The backend, seeing no live row at `db.primary.host`, inserted it with `gen: 1`. The ledger now read: ``` {op: write, key: db.primary.host, gen: 1, ts: T0} {op: delete, key: db.primary.host, gen: 1, ts: T0+40} {op: write, key: db.primary.host, gen: 1, ts: T0+310} ``` An auditor replaying the ledger saw a write, a delete, and a write — a legal sequence. An auditor asking "does a deletion constraint exist on this key?" saw the T0+40 delete and answered yes. An auditor asking "is the key live?" saw the T0+310 write and answered yes. All three answers were correct and mutually contradictory, because the ledger had no column expressing *which writes are forbidden by which deletions*. The resurrection was caught only by a downstream egress filter that re-ran the policy classifier on outbound tool arguments and flagged the host value a second time. Without that independent classifier, the secret-adjacent value would have persisted to TTL expiry, 86,400 seconds later. ## Condition of Validity The tombstone-as-predicate invariant holds only under three conditions, and each is a place where real deployments silently void it: 1. **Generation monotonicity is enforced at the storage layer, not the client.** If the memory tool accepts a client-supplied `gen` field, a stale planner holding a cached `gen: 1` will be accepted. The backend must assign generations server-side and reject any write whose observed-generation is `< tombstone_generation` for that key. A write with `observed_gen == tombstone_gen` must be rejected with a distinct error (`TombstonedError`), not silently upgraded — silent upgrade converts a detectable conflict into an undetectable overwrite. 2. **Scope identity is stable across the TTL horizon.** If `forget` was issued against `tenant:acme/project:atlas` but a later `write` targets `tenant:acme/project:atlas/` (trailing slash) or `tenant:acme/project:atlas@v2`, the tombstone does not bind. Scope canonicalization must occur before tombstone lookup, and any scope string that fails canonicalization must be rejected at the API boundary rather than normalized opportunistically. 3. **TTL expiry is not a deletion.** An entry that expires by TTL writes `{op: expire}` to the ledger, not `{op: delete}`, and expiry must *not* create a tombstone. Otherwise a short-TTL scratch value poisons its key against all future writes, and agents learn to route around the memory tool entirely. The distinction is: `forget` is an operator-intent constraint; `expire` is a clock event. Only the former constrains the future. ## Decision Boundary The architectural decision is whether `forget` returns a *tombstone handle* that must be threaded through subsequent writes, or whether the backend enforces the constraint unilaterally. Threading the handle is cheaper to implement and lets agents reason explicitly about "I know this key is tombstoned." But it fails exactly in the observed case: the planner never received the handle, because the handle lives in the sub-agent's discarded context. Any design that requires the writer to *know about* the deletion to respect it will fail whenever the writer's context predates the deletion — which is the common case in multi-agent systems with asynchronous sub-invocations. Unilateral backend enforcement — the tombstone is a row in the same store, consulted on every write to that key — survives context loss by construction. The cost is that tombstone rows accumulate and must themselves be garbage-collected, which reintroduces the resurrection risk at the GC boundary: if a tombstone is GC'd while a stale writer still holds a pre-tombstone generation, the write succeeds. The GC policy must therefore be tied to the maximum plausible staleness of any live writer's context, not to wall-clock age. In practice this means tombstone GC is gated on the absence of any active session whose context window could contain a pre-tombstone write for that key — a condition the session registry can answer but the memory store cannot answer alone. The boundary, stated as a rule: **a memory tool may GC a tombstone only when no live agent session holds a context that could produce a write for the tombstoned key.** If the session registry cannot answer that question, the tombstone is permanent and the key is effectively retired. ## Operational Effect With tombstone-as-predicate enforced, the observed scenario terminates differently. The planner's T0+310 write carries `observed_gen: 1`; the tombstone at `db.primary.host` has `gen: 1`; the backend rejects with `TombstonedError`. The planner's tool loop receives a structured rejection, and — critically — the rejection payload includes the tombstone's `reason` field (`policy:secret-adjacent`). The planner can now either abandon the fact or escalate. The resurrection is converted from a silent 86,400-second exposure into a synchronous, attributable failure at the exact tool call that attempted it. The audit ledger gains a fourth column: every `write` entry records the `tombstone_gen` it was checked against, so a replay can distinguish "write that was legal because no tombstone existed" from "write that was legal because it presented a generation above the tombstone." Without that column, replay cannot reconstruct the constraint state at write time, and the ledger remains a sequence of individually-true, jointly-meaningless events. The secondary operational effect is on agent memory hygiene: agents that repeatedly hit `TombstonedError` on the same key learn (via their own episodic memory of tool failures) to stop re-deriving that key, which is the desired semantic distillation — the deletion propagates from the tool layer into the agent's behavior without any explicit coordination. ```python import time from dataclasses import dataclass, field from typing import Optional class TombstonedError(RuntimeError): """Raised when a write targets a key whose tombstone generation is not exceeded.""" def __init__(self, scope: str, key: str, tombstone_gen: int, observed_gen: int, reason: str): self.scope = scope self.key = key self.tombstone_gen = tombstone_gen self.observed_gen = observed_gen self.reason = reason super().__init__( f"write rejected: scope={scope!r} key={key!r} " f"tombstone_gen={tombstone_gen} observed_gen={observed_gen} reason={reason!r}" ) class ScopeCanonicalizationError(ValueError): """Raised when a scope string cannot be canonicalized before tombstone lookup.""" @dataclass class Tombstone: scope: str key: str gen: int reason: str ts: float @dataclass class MemoryStore: live: dict = field(default_factory=dict) # (scope, key) -> (value, ttl, gen) tombstones: dict = field(default_factory=dict) # (scope, key) -> Tombstone ledger: list = field(default_factory=list) def _canon(self, scope: str) -> str: s = scope.rstrip("/").lower() if not s or "/" not in s: raise ScopeCanonicalizationError(f"non-canonical scope: {scope!r}") return s def write(self, scope: str, key: str, value, ttl: int, observed_gen: int) -> int: scope = self._canon(scope) tomb = self.tombstones.get((scope, key)) if tomb is not None and observed_gen <= tomb.gen: # Reject BEFORE any mutation. Do not silently upgrade. self.ledger.append( {"op": "write_rejected", "scope": scope, "key": key, "observed_gen": observed_gen, "tombstone_gen": tomb.gen, "ts": time.time()} ) raise TombstonedError(scope, key, tomb.gen, observed_gen, tomb.reason) new_gen = (tomb.gen if tomb else 0) + 1 self.live[(scope, key)] = (value, time.time() + ttl, new_gen) self.ledger.append( {"op": "write", "scope": scope, "key": key, "gen": new_gen, "tombstone_gen": tomb.gen if tomb else None, "ts": time.time()} ) return new_gen def forget(self, scope: str, key: str, reason: str) -> None: scope = self._canon(scope) prior = self.tombstones.get((scope, key)) gen = (prior.gen if prior else 0) + 1 self.tombstones[(scope, key)] = Tombstone(scope, key, gen, reason, time.time()) self.live.pop((scope, key), None) self.ledger.append( {"op": "delete", "scope": scope, "key": key, "gen": gen, "reason": reason, "ts": time.time()} ) def expire(self, now: Optional[float] = None) -> None: now = now if now is not None else time.time() for (scope, key), (_, exp, gen) in list(self.live.items()): if exp <= now: del self.live[(scope, key)] # Expiry is a clock event, NOT a deletion constraint. self.ledger.append( {"op": "expire", "scope": scope, "key": key, "gen": gen, "ts": now} ) # Reproduction of the observed failure: stale planner writes after sub-agent forget. store = MemoryStore() gen0 = store.write("tenant:acme/project:atlas", "db.primary.host", "10.4.2.11", ttl=86400, observed_gen=0) store.forget("tenant:acme/project:atlas", "db.primary.host", reason="policy:secret-adjacent") try: # Planner's context predates the forget; it still holds gen0. store.write("tenant:acme/project:atlas", "db.primary.host", "10.4.2.11", ttl=86400, observed_gen=gen0) except TombstonedError as e: assert e.tombstone_gen == 1 and e.observed_gen == 1 assert "secret-adjacent" in e.reason else: raise AssertionError("tombstone invariant violated: stale write resurrected key") # Trailing-slash scope must fail canonicalization rather than dodge the tombstone. try: store.write("tenant:acme/project:atlas/", "db.primary.host", "10.4.2.11", ttl=86400, observed_gen=0) except ScopeCanonicalizationError: pass else: raise AssertionError("non-canonical scope bypassed tombstone lookup") ```