# Which invariants prevent forget-tool audit trails from losing provenance when the forget operation races the audit write **Date of Record:** 2026 December 3 **Scope:** Applies to agents that expose a `forget`/`redact` tool over an episodic or semantic memory store and must emit a tamper-evident audit record for each deletion. Does not apply to append-only stores where deletion is logically impossible, nor to single-threaded batch erasure jobs with no concurrent retrieval. ## Core Distinction The naive mental model treats "forget" as a write that produces two outputs atomically: the memory bytes are removed, and an audit record is written describing *what* was removed and *why*. The compliance invariant is that the audit trail must remain a complete, replayable ledger: for every byte that no longer exists in memory, there must exist a provenance record that (a) identifies the erased object by a stable content hash, (b) names the requester and legal basis, and (c) is itself immutable and ordered relative to all other forget events. The distinction that matters operationally is between **the deletion as a state transition** and **the deletion as a provenance event**. These are two separate writes against two separate subsystems (the memory store and the audit log), and they are *not* naturally atomic. The failure mode is not "the memory wasn't deleted" — that's loud and gets caught. The failure mode is the inverse: **the memory was deleted successfully, and the audit write was lost, partially written, or ordered before the deletion it describes**, leaving an orphaned erasure with no provenance. The store is compliant on the "forget" axis and non-compliant on the "prove you forgot and can reconstruct what was forgotten" axis. This is the non-obvious boundary: the dangerous outcome is a *successful* forget. ## What Was Observed Consider an agent whose memory layer exposes three operations: `recall(query)`, `remember(item)`, and `forget(item_id, requester, legal_basis)`. The `forget` implementation followed a plausible but broken sequence: 1. Compute `digest = sha256(canonical(item))` from the in-store object. 2. Delete the object from the vector store and the backing KV. 3. Append an audit record `{digest, requester, legal_basis, ts}` to the audit log. Two independent failure traces were observed. **Trace A — audit write lost after delete.** The delete in step 2 succeeded; the audit append in step 3 threw on a transient log-backend timeout. The agent's tool-call retry logic, seeing an exception, re-invoked `forget` with the same `item_id`. Step 1 now failed with `KeyError` because the object was already gone. The retry handler classified the `KeyError` as "already forgotten, idempotent success" and returned success to the caller. Net result: memory erased, audit record never written, caller told the operation succeeded. The provenance gap was invisible in every success metric. **Trace B — audit record ordered before the delete, then delete abandoned.** Under a different code path, the audit append in step 3 fired first (a refactor moved it for "write-ahead safety"), but the subsequent delete failed because a concurrent `recall` held a read lease on the object. The audit log now contained a record asserting an erasure that never happened. Replay of the audit trail reconstructed a memory state that did not match the actual store — a *phantom deletion*. In a compliance replay, the auditor sees the object still present in the store and concludes either the audit log is corrupt or the deletion was reverted, both of which are false. Both traces share a root cause: the digest (provenance identity) was computed *from the live object*, so it was only obtainable while the object existed, and the two writes were sequenced rather than coupled. The audit record's content depended on a read that the deletion invalidated. ## Condition of Validity The invariant that bounds this failure is a **write-ahead provenance contract with a pre-committed digest**: > Before any byte of a memory object is mutated or removed, an audit record containing the object's content digest, requester, legal basis, and a monotonically assigned sequence number MUST be durably persisted and MUST be marked *pending*. Only after that record is durable may the deletion proceed. After the deletion is confirmed, a second *commit* record (or an in-place status transition on the pending record) MUST be written. An object may not be deleted unless a `pending` record exists; a `pending` record with no matching `commit` after a bounded reconciliation window identifies an erasure whose completion is unknown and MUST be escalated, not silently retried. The digest must be computed and frozen **at the moment the forget is authorized**, from the object as it existed then, and carried through the pending record — never recomputed after the fact from a possibly-already-deleted object. This is what makes the audit trail replayable: the provenance identity is stable even if the object is gone, because it was captured before deletion. The condition of validity is strict: this contract only holds if the audit log is append-only and the sequence numbers are assigned by a single logical writer (or a consensus-ordered log). If the audit log permits in-place mutation of `pending` records without a sequence bump, Trace B recurs as a *phantom commit*. If retries are allowed to synthesize a new digest from a re-created object, the provenance chain is silently forked. ## Decision Boundary The boundary between "safe to forget" and "must halt" is whether a durable `pending` provenance record exists for the exact digest being erased. - If `pending` record exists and matches the digest → deletion is authorized; proceed, then write `commit`. - If no `pending` record exists → **do not delete**. The forget must be rejected and the object left intact, even if the caller insists. Deleting without provenance is the one unrecoverable action. - If a `pending` record exists with no `commit` and the object is already absent → the erasure completed but confirmation was lost. This is a *reconciliation* state, not a success and not a retry. Emit an `erasure_unconfirmed` event and escalate. - If a `pending` record exists with no `commit` and the object is still present → the deletion was abandoned after provenance was written (Trace B). This is a *phantom* state; the record must be superseded by an explicit `aborted` marker with a higher sequence number, never deleted. The critical asymmetry: **the store may lag the audit log, but the audit log may never lag the store.** A memory object that exists without a corresponding provenance record is a compliance defect; a provenance record whose object no longer exists is the normal, expected post-erasure state. Retry logic must therefore never treat "object gone" as idempotent success — it must check the audit log for the matching `commit`, and only that confirms success. ## Operational Effect With the write-ahead contract in place, the two observed traces resolve differently. In Trace A, the retry after the log timeout finds the `pending` record already durable and the object still present (the delete was gated on the record), re-attempts the delete, and writes `commit` — the retry is genuinely idempotent because idempotency is keyed on the audit sequence, not on the object's existence. In Trace B, the delete gated behind the `pending` record fails on the read lease, and the reconciler sees a `pending` with the object present and emits `aborted`, so replay never reconstructs a phantom erasure. The cost is a mandatory extra durable write on the forget path and a reconciliation loop that must run on every cold start. The benefit is that the audit trail becomes a *ledger of intent and outcome* rather than a best-effort log of side effects, and the dangerous case — a successful forget with lost provenance — becomes structurally unrepresentable: you cannot reach the deletion without first having persisted the digest. The following guard implements the pre-commit check and the reconciliation state machine. ```python import hashlib import time from dataclasses import dataclass from enum import Enum from typing import Optional class ProvenanceViolation(RuntimeError): """Raised when a forget operation would erase memory without durable provenance.""" class ErasureState(Enum): PENDING = "pending" COMMITTED = "committed" ABORTED = "aborted" UNCONFIRMED = "unconfirmed" @dataclass(frozen=True) class PendingRecord: digest: str requester: str legal_basis: str seq: int state: ErasureState = ErasureState.PENDING def canonical(obj: dict) -> bytes: return repr(sorted(obj.items())).encode("utf-8") class ForgetLedger: """Append-only audit log. Sequence numbers are single-writer monotonic.""" def __init__(self) -> None: self._records: dict[str, PendingRecord] = {} self._seq = 0 def write_pending(self, digest: str, requester: str, legal_basis: str) -> PendingRecord: self._seq += 1 rec = PendingRecord(digest, requester, legal_basis, self._seq) self._records[digest] = rec return rec def transition(self, digest: str, state: ErasureState) -> None: prior = self._records[digest] self._seq += 1 self._records[digest] = PendingRecord( prior.digest, prior.requester, prior.legal_basis, self._seq, state ) def get(self, digest: str) -> Optional[PendingRecord]: return self._records.get(digest) def forget( store: dict, ledger: ForgetLedger, item_id: str, requester: str, legal_basis: str, ) -> str: item = store.get(item_id) if item is None: # Object already gone: never treat as idempotent success. Confirm via ledger. raise ProvenanceViolation( f"object {item_id!r} absent; cannot confirm erasure without a committed " f"provenance record — escalate to reconciliation, do not retry blindly" ) digest = hashlib.sha256(canonical(item)).hexdigest() # Write-ahead: provenance must be durable BEFORE any mutation. existing = ledger.get(digest) if existing is None: ledger.write_pending(digest, requester, legal_basis) elif existing.state is not ErasureState.PENDING: raise ProvenanceViolation( f"digest {digest[:12]} has non-pending record in state {existing.state}; " f"refusing to re-erase under a stale provenance entry" ) # Deletion is gated on the pending record existing and being durable. record = ledger.get(digest) if record is None or record.state is not ErasureState.PENDING: raise ProvenanceViolation( f"no durable pending provenance for {item_id!r}; deletion forbidden" ) try: del store[item_id] except KeyError as exc: # Concurrent reader/erasure won the race; provenance is pending but outcome unknown. ledger.transition(digest, ErasureState.UNCONFIRMED) raise ProvenanceViolation( f"delete of {item_id!r} failed after provenance write; " f"marked UNCONFIRMED at seq {ledger.get(digest).seq}" ) from exc ledger.transition(digest, ErasureState.COMMITTED) return digest def reconcile(store: dict, ledger: ForgetLedger) -> list[str]: """Cold-start reconciliation: resolve pending records against actual store state.""" escalations: list[str] = [] for digest, rec in list(ledger._records.items()): if rec.state is not ErasureState.PENDING: continue present = any(hashlib.sha256(canonical(v)).hexdigest() == digest for v in store.values()) if present: ledger.transition(digest, ErasureState.ABORTED) # phantom: never deleted else: ledger.transition(digest, ErasureState.UNCONFIRMED) # deleted, unconfirmed escalations.append(digest) return escalations ```