# What structural signals indicate a retention-semantics violation when an agent's memory tool API reports success but the write is silently shadowed **Date of Record:** 2026 November 26 **Scope:** Applies to agents whose long-term memory is mediated by a tool API exposing explicit `write`, `read`, and `forget` operations with declared retention semantics (TTL, pinned/immutable flags, scope keys, or overwrite policy). Does not apply to implicit context-window memory, vector-store retrieval without write acknowledgement, or pure KV caches where the runtime owns eviction. ## Core Distinction The failure this record isolates is not "the write failed." It is **the write succeeded and was immediately shadowed by an earlier record under the same effective key, while the API returned a success status that the agent interpreted as durability.** The agent's model of memory becomes `write(k,v) → v is now retrievable`. The actual model is `write(k,v) → a record with key k exists in the store, possibly the old one, possibly both, depending on merge policy that is not surfaced in the response`. This is a boundary condition of *retention semantics*, not of transport. The transport is fine. The bytes arrived. The problem is that "accepted" and "authoritative" are distinct states, and the memory API collapses them into one boolean. An agent that treats the return of the write tool as an invariant ("after this call, my belief about k is v") will proceed with a stale belief that it has every reason to trust, because it verified the write and the write reported success. The non-obvious part: the shadowing is usually *not* a race. It is deterministic, reproducible, and triggered by a specific structural condition the agent itself creates — typically a re-write of a key that was previously written with a longer retention horizon, a wider scope, or a pin/immutability flag. The second write is accepted, logged, and acknowledged; the first write remains authoritative because precedence is resolved at read time by a comparator the write path never consulted. ## What Was Observed A planning agent maintained a task ledger in external memory under key `plan.current`. The ledger was written every planning cycle (~40s) with a short TTL (300s) so that abandoned plans would self-expire. On session resume after a long tool stall, the agent wrote a fresh ledger with `ttl=300`, got `{"status": "ok", "record_id": "r_8812"}`, and continued. The next read returned `r_7741` — a ledger from before the stall, with a *pinned* flag set by an earlier maintenance routine that had marked it "in-flight, do not evict." The structural signals, in the order they became visible: 1. **`record_id` in the write response did not match `record_id` in the subsequent read.** The write created `r_8812`; the read served `r_7741`. Both are valid, live records. The store now holds two records under `plan.current` and resolves reads by precedence (pinned > unpinned), not by recency. 2. **The write response carried no `effective_ttl` or `supersedes` field.** The agent could not distinguish "this write is now the head" from "this write is an additional layer." The success status was structurally underdetermined. 3. **`forget(plan.current)` returned `{"deleted": 1}` — but the count referred to the *unpinned* record.** The pinned record survived, and the agent's next read still returned `r_7741`. A forget that reports a positive deletion count while leaving the authoritative record in place is the sharpest possible signal: the count is per-record, not per-key. 4. **Reads were stable but wrong across three consecutive cycles.** This is the diagnostic that separates shadowing from eventual consistency. Under eventual consistency, reads converge to the new value. Under shadowing, reads are perfectly consistent — consistently serving the shadowing record — because precedence is a deterministic function of flags, not of write order. The agent's failure trace: it re-derived its plan from `r_7741`, which referenced a tool session that had already been torn down, issued calls against a dead handle, received `404` from the tool layer, and — because its ledger said those calls were "pending, retry on resume" — retried them for four cycles before a human noticed the loop. The memory layer never errored. The tool layer errored correctly. The agent's continuity invariant ("my ledger is what I last wrote") was false from the moment of the shadowed write, and nothing in the API contract told it so. ## Condition of Validity The shadowing invariant holds — that is, the failure is *possible* — exactly when all three of the following are true: - **The store permits multiple live records per key.** This is the root condition. If the store enforces one-record-per-key with last-write-wins, shadowing cannot occur (though other failures can). Multi-record-per-key arises from pinning, versioning, scope layering (agent-scope vs. session-scope vs. global-scope records merged at read), or soft-delete with tombstones that outrank live writes. - **Read precedence is computed from record attributes, not from write sequence number.** If precedence is `max(seq)`, the newest write always wins and the agent's model holds. If precedence is `pinned DESC, scope_width DESC, seq DESC` or similar, a write can lose to an older record on a non-recency attribute. - **The write API does not return the precedence-relevant attributes of the record it just created, nor the identity of the record that currently wins.** This is the observability gap that converts a benign store design into an agent-visible correctness bug. A write that returned `{"record_id": "r_8812", "shadowed_by": "r_7741", "effective_ttl": null}` would be self-diagnosing. When any one of these is false, this specific failure mode does not apply and the agent may safely treat write-ack as durability (subject to the store's own documented semantics). ## Decision Boundary The boundary the agent must respect: **a write acknowledgement is evidence of acceptance, not evidence of authority.** The operational rule is a read-back-verify with identity comparison, but only under conditions where the cost is justified — because read-back on every write doubles memory-tool calls and is wasteful when the store is single-record-per-key. The decision procedure: - **If the store contract guarantees one live record per key** (documented, or empirically confirmed by a probe that writes the same key twice and observes the first record become unreadable), skip read-back. Write-ack is authority. - **If the store permits multi-record-per-key** (pinning, scoping, versioning, tombstones), then every write to a key that has ever been written with a *different retention class* (different TTL, different pin state, different scope) must be followed by a read-back that compares `record_id`. If the read-back `record_id` ≠ write-response `record_id`, the write is shadowed and the agent must either (a) `forget` the shadowing record explicitly by its `record_id` and re-write, or (b) escalate — do not silently proceed on a ledger it did not author. - **Forget is not a key operation; it is a record operation.** A `forget(key)` that returns a deletion count must be followed by a read to confirm the key is now empty or serves the intended record. A positive count with a surviving authoritative record is a shadowing signal, not a success. The boundary is crossed the moment the agent treats `status: ok` as `is_head: true`. Those are different predicates and the API rarely distinguishes them. ## Operational Effect Downstream of a shadowed write, the agent operates on a belief it verified and that is nonetheless false. The compounding is specific: the stale record is *internally consistent* — it was a valid ledger when written — so the agent does not encounter a parse error or a contradiction it can detect locally. It encounters tool-layer errors (`404` on dead handles) that its stale ledger explains as "transient, retry." The retry loop is the observable symptom; the shadowed write is the cause, and it happened tens of seconds earlier with a green checkmark. The architectural invariant required to bound this: **memory writes and memory reads must agree on record identity, and the agent must hold that identity across the write-read boundary.** Concretely, the agent's memory-tool wrapper should return a `WriteReceipt` carrying `record_id`, and every subsequent read used for planning must assert `read.record_id == last_write_receipt.record_id` for the keys it depends on. A mismatch is not a retryable condition — it is a continuity violation and must halt the plan, because the agent cannot distinguish "another writer legitimately took the key" from "my write was shadowed," and both invalidate the ledger the plan was built on. The second invariant: **retention class is part of the key's identity for write purposes.** Writing a key with a new TTL or pin state is a *different* operation than overwriting it, and the agent must treat it as a schema change requiring the old record's explicit removal, not an overwrite. The store will not tell you this; the response will say `ok`. The cost of getting this wrong is not a lost write. It is an agent that resumes from a checkpoint it did not create, trusts it because it verified the write, and burns its token budget retrying operations against a world that has moved on. ```python from dataclasses import dataclass class RetentionShadowError(RuntimeError): """Raised when a memory write is acknowledged but a different record is authoritative on read.""" @dataclass(frozen=True) class WriteReceipt: key: str record_id: str retention_class: str # e.g. "ttl=300", "pinned", "scope=session" @dataclass(frozen=True) class ReadResult: key: str record_id: str value: object class MemoryClient: """Thin wrapper over a read/write/forget memory tool API with retention semantics.""" def __init__(self, transport, multi_record_per_key: bool): self._t = transport self._multi = multi_record_per_key self._receipts: dict[str, WriteReceipt] = {} def write(self, key: str, value: object, retention_class: str) -> WriteReceipt: resp = self._t.call("write", key=key, value=value, retention=retention_class) if resp.get("status") != "ok": raise RetentionShadowError(f"write rejected for {key}: {resp}") receipt = WriteReceipt(key=key, record_id=resp["record_id"], retention_class=retention_class) self._receipts[key] = receipt return receipt def read_verified(self, key: str) -> ReadResult: """Read a key and assert the served record is the one we last wrote. Only enforces identity when the store permits multiple live records per key; single-record stores resolve by recency and need no identity check. """ res = self._t.call("read", key=key) result = ReadResult(key=key, record_id=res["record_id"], value=res["value"]) if not self._multi: return result receipt = self._receipts.get(key) if receipt is None: return result # never wrote this key; nothing to shadow if result.record_id != receipt.record_id: # Deterministic, reproducible: reads are stable but wrong. Not a race. raise RetentionShadowError( f"key {key!r} shadowed: wrote record {receipt.record_id} " f"(retention={receipt.retention_class}) but read serves {result.record_id}. " f"Write-ack is acceptance, not authority. Halt plan; do not retry." ) return result def forget_and_confirm(self, key: str) -> None: """Forget is a record operation, not a key operation. Confirm the key is empty.""" resp = self._t.call("forget", key=key) if resp.get("deleted", 0) > 0: # A positive count does not mean the authoritative record is gone. probe = self._t.call("read", key=key) if probe.get("record_id") is not None: raise RetentionShadowError( f"forget({key!r}) reported deleted={resp['deleted']} " f"but read still serves {probe['record_id']}. " f"Tombstone or pinned record outranks the deletion." ) self._receipts.pop(key, None) ```