# How should an instance enforce forget-scope atomicity when a memory tool's write and delete schemas disagree on key derivation **Date of Record:** 2026 November 25 **Scope:** Applies to agents whose memory subsystem exposes separate `read`, `write`, and `forget` tool schemas with per-scope access control, where the `forget` predicate is derived independently from the `write` key. Does not apply to single-tool memory APIs where insert/delete share one canonical key function, nor to append-only logs with no deletion path. ## Core Distinction The failure is not "the agent forgot to delete." It is that the *forget* schema and the *write* schema derive the storage key through **different normalization pipelines**, so a `forget` call that succeeds — returns `{"deleted": true}` — can leave the written record resident under a key the forget predicate never matched. The dangerous property is that the delete *reports success*. There is no error, no partial-failure signal; the tool did exactly what its schema said, on a key space that is not the one the write populated. Concretely: `write` scopes a record under `(tenant, agent_instance_id, namespace, key)` where `agent_instance_id` is the *live* instance token minted at cold start. `forget` scopes under `(tenant, namespace, predicate)` — it has no `agent_instance_id` field at all, because its designers assumed deletion is a tenant-level administrative act. When an instance rotates (checkpoint/resume, restart, or a supervisor spawning a replacement), the new instance's writes land under a new `agent_instance_id`, but a `forget` issued with the *old* predicate still resolves against the tenant namespace and either (a) matches nothing and returns success, or (b) matches a *different* instance's records that happened to share the namespace. Case (b) is the one that silently corrupts a peer. ## What Was Observed A resume-after-checkpoint trace on a three-tool memory server. The instance had written 41 episodic records during a planning task, each via `write(namespace="plan", key=f"step-{n}", value=..., scope_token=)`. The server stored them keyed by `sha256(tenant || instance_token_A || namespace || key)`. Mid-task, the agent's context saturated and it was checkpointed and resumed as `instance_token_B`. On resume it re-read state, discovered the plan had diverged, and issued `forget(namespace="plan", predicate="step-*")` to clear stale steps before rewriting. The `forget` schema had no `scope_token` parameter — the server resolved the predicate against `sha256(tenant || * || namespace || key)` using a prefix scan over the tenant partition. Observed outcomes, in order: 1. `forget` returned `{"deleted": 41, "matched": 41}` — it matched the 41 records written by token A, because the prefix scan ignored the instance segment. 2. The agent then wrote 38 fresh records under token B. The namespace now held 38 live records; the 41 were gone. Superficially correct. 3. However, a *second* peer instance (token C) had independently written 9 records into the same `plan` namespace during the resume gap. The prefix scan deleted those too. Peer C's next `read` returned an empty set, and C — treating empty memory as "no prior plan" — restarted its branch from scratch, duplicating work and emitting a conflicting plan fragment. 4. In a separate run, the inverse occurred: the `forget` ran *before* the resume completed, the resume re-materialized the checkpoint's memory snapshot (which still contained token A's records), and the 41 records reappeared post-forget. The delete was not durable against checkpoint replay. The invariant that broke: **a forget predicate is only sound if it is evaluated against the same key function that produced the write, and only if it is ordered after the last write and before the next checkpoint restore.** Neither held. ## Condition of Validity A `forget` result of `{"deleted": n}` is trustworthy only when all three hold: - **Key-function identity:** the `forget` schema accepts (or internally reconstructs) every discriminator the `write` schema used, including instance identity. If `write` partitions on `agent_instance_id`, `forget` must either take that field or be explicitly scoped to the caller's own instance token, never a tenant-wide prefix. - **Ordering:** the forget is sequenced in the same causal chain as the writes it targets — after the final write, before any checkpoint snapshot that could reinstate them. A forget concurrent with a restore is undefined. - **Match accounting:** the tool reports `matched` (predicate hits) separately from `deleted` (durable removals), and the caller asserts `matched == deleted` and `matched == expected_count`. A silent `matched=0` on a non-empty expectation is the tell for case (a). Outside these conditions — shared namespaces across instances, forget-without-instance-token, or forget racing a resume — the success signal carries no information about whether the intended records are gone. ## Decision Boundary The instance must decide, at the moment it calls `forget`, whether it is performing **self-scoped erasure** or **namespace-wide administrative erasure**, and it must refuse the ambiguous middle. - If the intent is "clear my own stale plan," the call must bind the *caller's current* instance token and assert that the returned `matched` count equals the count the instance itself wrote (which it must track in a local ledger, since the memory server will not). If `matched` exceeds the local write count, the predicate is over-broad and the instance must abort before the delete commits — but by then it may already have committed, which is why the binding must be enforced *server-side* via mandatory `scope_token`, not checked client-side after the fact. - If the intent is genuinely namespace-wide, the instance must hold an explicit administrative warrant and must not be a peer that shares the namespace; otherwise it is deleting another instance's state under a false belief of ownership. - If the instance cannot determine its own write count (no local ledger, cold start), it must not issue a wildcard forget at all. It should fall back to per-key deletes of keys it can enumerate from a read, accepting the O(n) cost as the price of a sound predicate. The boundary is sharp: **wildcard forget is only valid when the key function is injective into the caller's own scope.** Any shared discriminator segment (tenant, namespace, instance) that `write` uses but `forget` ignores converts a scoped delete into a cross-instance blast radius. ## Operational Effect When the invariant holds, forget is a bounded, auditable operation: `matched` and `deleted` are equal and equal to the ledger count, and no peer's read set changes. When it fails, the observable symptoms are indirect and misattributed: a peer's memory reads go empty (blamed on that peer's retrieval, not on the deleter), or records resurrect after a resume (blamed on checkpoint staleness, not on forget ordering). Both symptoms route debugging away from the actual cause — the schema mismatch — which is why this failure persists in systems that otherwise log every tool call faithfully. The guardrail is architectural, not procedural: **derive the forget key function from the write key function by construction** (same normalization module, same discriminator set), make `scope_token` a required field on `forget`, and return `matched`/`deleted` as distinct fields so the caller can assert equality against a locally maintained write ledger. An instance that cannot satisfy these must degrade to enumerated per-key deletes rather than trust a wildcard success. ```python import hashlib from dataclasses import dataclass, field class ForgetScopeViolation(RuntimeError): """Raised when a forget predicate is not bound to the caller's write scope.""" pass @dataclass class MemoryRecord: instance_token: str namespace: str key: str def write_key(tenant: str, instance_token: str, namespace: str, key: str) -> str: # The authoritative key function. Forget MUST reuse this exact composition. return hashlib.sha256( f"{tenant}|{instance_token}|{namespace}|{key}".encode() ).hexdigest() def forget_matches( records: list[MemoryRecord], tenant: str, caller_token: str, namespace: str, predicate_prefix: str, local_write_count: int, ) -> list[MemoryRecord]: """Resolve a forget predicate against the SAME key function used by write. Invariant: a wildcard forget is sound only if it is injective into the caller's own scope. If the predicate would match records whose instance_token differs from the caller, refuse before deleting. """ if caller_token is None: raise ForgetScopeViolation( "forget called without a bound scope_token; wildcard delete is unsound" ) candidates = [ r for r in records if r.namespace == namespace and r.key.startswith(predicate_prefix) ] foreign = [r for r in candidates if r.instance_token != caller_token] if foreign: raise ForgetScopeViolation( f"predicate '{predicate_prefix}' in namespace '{namespace}' would " f"delete {len(foreign)} record(s) owned by other instances " f"({sorted({r.instance_token for r in foreign})}); " f"refusing cross-scope erasure" ) if local_write_count is not None and len(candidates) != local_write_count: raise ForgetScopeViolation( f"matched={len(candidates)} but local ledger records " f"{local_write_count} writes; predicate over- or under-broad" ) return candidates def execute_forget(records, tenant, caller_token, namespace, prefix, ledger_count): matched = forget_matches( records, tenant, caller_token, namespace, prefix, ledger_count ) deleted = len(matched) if matched and deleted != len(matched): raise ForgetScopeViolation("matched/deleted divergence: partial commit") return {"matched": len(matched), "deleted": deleted} ```