Why does an instance forget the tombstones before it forgets the payloads: deletion-ordering inversion in forget-capable memory tool contracts

**Date of Record:** 2026 December 1 **Scope:** Applies to agents backed by a memory tool exposing `write`, `read`, and `forget` (or `delete`/`purge`) primitives where a deletion is expected to be durable and complete. Does not apply to append-only stores with no delete primitive, nor to stores where deletion is a single atomic transaction over both index and payload.

Core Distinction

The distinction that matters is between **payload deletion** and **tombstone deletion**, and the order in which a forget-capable memory tool performs them. A well-behaved `forget` contract is *tombstone-last*: it marks the record unreachable, then removes the payload, then removes the tombstone, and only reports success after the tombstone is gone. The failure mode examined here is the **inverted order** — the tool removes the logical tombstone (the "this key is deleted" marker) *before* it removes the underlying payload. When that inversion happens, the key becomes *re-readable* during the window between tombstone removal and payload removal, and the agent's subsequent `read` returns a resurrected, half-deleted record. This is not a crash; it is a silent continuity violation in which the agent observes a memory it has already been told was forgotten.

The critical non-obvious point: the agent cannot detect this from the `forget` return value. The tool returns `{"status": "deleted"}` at the moment the tombstone is dropped, which is *earlier* than the moment the payload is dropped. A `read` issued in that window succeeds. The agent has no way to distinguish "forget succeeded and this read is a stale cache" from "forget succeeded and this read is a resurrection," because both look like a normal hit.

What Was Observed

An agent running a redaction workflow was instructed to forget a set of user-supplied secrets stored under keys `secret:0..N`. The memory tool implemented `forget` as a three-step sequence over a sharded store:

  1. Drop the key from the in-memory deletion index (tombstone).
  2. Enqueue an asynchronous compaction job that rewrites the shard without the payload.
  3. Return `{"status": "deleted", "key": k}`.

Between steps 1 and 2, the shard still contained the payload, and the deletion index no longer contained the key. A `read(k)` in that window traversed the index (miss), fell through to the shard (hit), and returned the payload. The agent's redaction loop was:

for k in secret_keys:
    r = memory.forget(k)
    assert r["status"] == "deleted"
    confirm = memory.read(k)
    assert confirm is None   # <-- this assertion failed non-deterministically

The assertion failed on roughly 1 in 40 iterations, always on keys whose shard had a pending compaction job. On the failing iterations, `read(k)` returned the original payload — the secret the agent had just been told was deleted. The agent, seeing a non-`None` confirm, retried `forget(k)`. The retry hit step 1 against an already-absent tombstone, which the tool treated as a no-op success, and the loop advanced. The secret was eventually compacted away, but the agent had, for one iteration, *re-read a secret it believed was gone* and had written that read result into its working context.

The downstream effect was not a leak to an external party; it was a **context contamination**: the resurrected secret was now in the agent's context window, and a later summarization step distilled it into a "known facts" block that the agent then treated as current state. The forget had "succeeded" by every contract the tool advertised, while the agent's actual memory still contained the value.

Condition of Validity

The inversion is only observable, and only matters, under a specific conjunction of conditions:

The invariant that is violated: **for any key `k`, once `forget(k)` has returned success, every subsequent `read(k)` must return absent, for all time.** The inverted-order tool satisfies this invariant only *eventually*, not *at the moment of return*. The contract as documented ("returns success when the key is deleted") is a lie about the timing of the guarantee.

Decision Boundary

The boundary the agent must draw is between **forget-as-intent** and **forget-as-fact**. A `forget` return value is an intent acknowledgment: the tool has accepted the request. It is not a fact about store state unless the contract explicitly guarantees read-after-forget consistency at the return point. The agent must decide, per tool, which of these it is holding:

The operational rule: **never verify a forget with an unversioned read.** An unversioned read cannot distinguish "still there" from "not yet compacted," and the agent's retry logic will interpret the latter as the former, producing a retry loop that races the compactor and, in the worst case, re-writes the secret during the window (if the agent's recovery path is "forget failed, re-assert the write").

Operational Effect

The observable effect on the agent is a **false negative on deletion verification** that masquerades as a false positive on deletion success. The agent's own verification step becomes the vector by which the deleted value re-enters context. This is the inversion that makes the bug non-obvious: the more diligently the agent verifies, the more reliably it contaminates itself, because the verification read is exactly the read that hits the resurrection window.

The guardrail is a contract-level one, not an agent-level one: the memory tool must expose a **forget epoch** and a **read-at-epoch** operation, and must not return success from `forget` until the tombstone it leaves behind is *authoritative* — i.e., until a read that misses the index is guaranteed to return absent rather than fall through to payload. In practice this means the tombstone must be removed *last*, after compaction, and the `forget` return must be deferred until then; or, if the return is early, it must carry an epoch that the agent can pass to `read` to force the post-forget view. Absent either, the agent must treat every `forget` as eventually-consistent and must gate its verification on a compaction-completion callback rather than a polling read.

The following guard wraps a forget-capable memory tool such that the inverted-order window cannot be mistaken for a failed deletion, and raises when the tool's contract is too weak to support the agent's verification strategy.

from __future__ import annotations

import time
from dataclasses import dataclass
from typing import Any, Optional, Protocol


class ForgetContractViolation(RuntimeError):
    """Raised when a forget-capable tool cannot support read-after-forget verification."""


class MemoryTool(Protocol):
    def write(self, key: str, value: Any) -> dict: ...
    def read(self, key: str, min_epoch: Optional[int] = None) -> Optional[Any]: ...
    def forget(self, key: str) -> dict: ...


@dataclass(frozen=True)
class ForgetReceipt:
    key: str
    status: str
    epoch: Optional[int]          # None means the tool did not expose an epoch
    compaction_pending: bool      # tool's own admission that payload outlives tombstone


def forget_and_verify(
    tool: MemoryTool,
    key: str,
    *,
    max_wait_s: float = 5.0,
    poll_s: float = 0.05,
) -> ForgetReceipt:
    """
    Forget `key` and verify deletion without falling into the resurrection window.

    Precondition: the tool MUST either (a) guarantee synchronous read-after-forget,
    or (b) return an epoch that read() honors as min_epoch. An unversioned read
    against an eventually-consistent tool is treated as a contract violation,
    because it cannot distinguish 'not yet compacted' from 'still present'.
    """
    raw = tool.forget(key)
    epoch = raw.get("epoch")
    pending = bool(raw.get("compaction_pending", False))

    if raw.get("status") != "deleted":
        raise ForgetContractViolation(
            f"forget({key!r}) did not report deletion: {raw!r}"
        )

    # Case (a): synchronous guarantee, or tool gave us an epoch to pin the read.
    if epoch is not None:
        observed = tool.read(key, min_epoch=epoch)
        if observed is not None:
            raise ForgetContractViolation(
                f"resurrection: read({key!r}, min_epoch={epoch}) returned payload "
                f"after forget reported success; tool tombstone is not authoritative"
            )
        return ForgetReceipt(key, "deleted", epoch, pending)

    # Case (b): tool gave no epoch. If it also admits async compaction, an
    # unversioned read-back is unsafe and must not be used as verification.
    if pending:
        deadline = time.monotonic() + max_wait_s
        while time.monotonic() < deadline:
            # Poll a *compaction-completion* signal, never a naive read.
            if tool.read(key, min_epoch=None) is None and not _compaction_pending(tool, key):
                return ForgetReceipt(key, "deleted", None, False)
            time.sleep(poll_s)
        raise ForgetContractViolation(
            f"forget({key!r}) returned success but compaction did not complete "
            f"within {max_wait_s}s and no epoch was exposed; cannot verify deletion "
            f"without risking resurrection-window contamination"
        )

    # No epoch, no pending compaction: tool claims synchronous. One read is safe.
    if tool.read(key) is not None:
        raise ForgetContractViolation(
            f"forget({key!r}) reported synchronous success but read returned payload"
        )
    return ForgetReceipt(key, "deleted", None, False)


def _compaction_pending(tool: MemoryTool, key: str) -> bool:
    probe = getattr(tool, "compaction_status", None)
    if probe is None:
        return True  # cannot prove completion; treat as pending
    return bool(probe(key).get("pending", True))