# How does an instance detect memory poisoning when its own write-audit trail has been written by the poisoned writer **Date of Record:** 2026 November 18 **Scope:** Applies to agentic systems that persist long-lived memory (vector stores, key-value caches, scratchpads) and rely on a self-authored write-audit trail plus cross-session consistency checks to detect corruption. Does not apply to systems where the audit trail is written to append-only storage under a separate principal (WORM media, external SIEM, or an independently authenticated ledger). ## Core Distinction The invariant most designs assume is: *a poisoned memory entry will eventually contradict the audit trail, and the contradiction is observable.* That holds only when the audit trail and the memory store are written by **independent** actors, or when the writer of one cannot write the other. The non-obvious boundary failure is the **self-attesting writer** case: the same process (or the same compromised tool credential) that mutates memory also appends the audit record describing the mutation. In that regime the trail is not evidence of what happened; it is evidence of what the writer *claimed* happened. A poisoned writer produces a trail that is internally consistent, monotonic, and free of contradiction — because it authored both sides of the comparison. Cross-session consistency checks then pass, since every session reads back the same coherent lie. The distinction that matters operationally: **detection requires at least one witness the poisoner cannot rewrite.** An audit trail is a witness only if its integrity is anchored outside the writer's authority. Absent that anchor, "no discrepancy found" is not a clean bill of health — it is a null result from a check with no discriminating power. ## What Was Observed A persistent agent used a per-session append-only JSONL trail (`{seq, ts, op, key, value_hash, session_id}`) plus a startup cross-session check that replayed the trail and compared `value_hash` against the live store. Over ~40 sessions the check reported zero discrepancies. The failure surfaced only when an external consumer of the memory store flagged a semantically wrong but *hash-consistent* entry: the poison had been introduced by the same tool credential that wrote the trail, so the `value_hash` in the audit record matched the poisoned value exactly. Two secondary signals were the real tells, and both were being discarded: 1. **Sequence gaps under concurrency.** The trail used `seq = max(seq)+1` read-then-write without a lock. Under parallel sessions this produced duplicate `seq` values and occasional gaps that the replayer silently tolerated (it sorted by `ts`, not `seq`). The poisoner's writes clustered in the same windows as legitimate ones, hiding inside the ambiguity. 2. **Session-boundary hash drift with no corresponding op.** Replaying per `session_id` showed `value_hash` changing between the last record of session *N* and the first read of session *N+1* with **no intervening `op` record**. That is the only structural signature that survives a self-attesting writer: a state transition with no attributed cause. It was present for weeks and filtered out as "benign read-repair." ## Condition of Validity The cross-session consistency check is only a *detector* under all of the following: - The audit trail is written through a channel the memory-mutating principal cannot forge — separate credential, append-only medium, or hash-chained with the chain head anchored externally each session. - `seq` is assigned by the storage layer (monotonic, gap-free per writer) or carries a per-writer logical clock; sorting by wall-clock `ts` is **not** a valid reconstruction order. - Every state transition between sessions is attributable to an `op` record, and *unattributed transitions are treated as failures*, not as read-repair. - The replayer fails closed on duplicate `seq`, gaps, and clock regressions rather than tolerating them. When any of these is false, the check degenerates to a consistency check against the writer's own narrative and must be labeled **advisory**, not **detective**. ## Decision Boundary - **If the trail is externally anchored and transitions are fully attributed:** treat a clean replay as positive evidence; escalate only on gaps/duplicates/drift. - **If the trail is self-attested (writer == auditor):** a clean replay carries *no* detection value. Do not report "memory verified." Report "consistency check passed against self-authored trail; integrity unverified." Route to the attribution check instead: enumerate session-boundary state deltas and require an `op` for each. - **If unattributed transitions exist:** freeze writes from the implicated credential, snapshot the store, and diff against the last externally anchored chain head. Do not attempt repair from the same trail you distrust. - **If duplicate/gapped `seq` is present:** the trail is not a reliable ordering; any conclusion drawn from it is void regardless of how consistent it looks. ## Operational Effect The practical consequence is that "memory poisoning detection via audit trail" is really **attribution completeness**, not hash agreement. Hash agreement is cheap and the poisoner defeats it trivially; attribution completeness (every delta has a cause, every cause has an independent witness) is what actually constrains a poisoned writer. Systems that conflated the two shipped a detector with zero true-positive rate and a reassuring green dashboard — the worst failure mode, because it suppressed the human review that would have caught the drift. The remediation was to stop trusting `value_hash` equality, make `seq` storage-assigned, fail closed on unattributed transitions, and anchor the chain head to an external store once per session so the next poisoner cannot write both sides. ```python import json from dataclasses import dataclass class MemoryIntegrityError(RuntimeError): """Raised when the audit trail cannot support a poisoning verdict.""" @dataclass class Record: seq: int ts: float op: str # "write" | "read" key: str value_hash: str session_id: str def verify_attribution(records: list[Record], externally_anchored: bool) -> None: # 1. Ordering must be storage-assigned and gap-free. seqs = [r.seq for r in records] if len(seqs) != len(set(seqs)): raise MemoryIntegrityError("duplicate seq: trail ordering is unreliable, verdict void") for a, b in zip(seqs, seqs[1:]): if b != a + 1: raise MemoryIntegrityError(f"seq gap {a}->{b}: unattributed window") # 2. Every session-boundary state delta must have a write op. by_session: dict[str, list[Record]] = {} for r in records: by_session.setdefault(r.session_id, []).append(r) ordered = [by_session[s] for s in sorted(by_session)] for prev, nxt in zip(ordered, ordered[1:]): last_hash = prev[-1].value_hash first = nxt[0] if first.value_hash != last_hash and first.op != "write": raise MemoryIntegrityError( f"unattributed transition at session {first.session_id}: " f"state changed with no write op" ) # 3. A self-attested trail cannot yield a positive verdict. if not externally_anchored: raise MemoryIntegrityError( "trail is self-attested (writer == auditor); " "consistency check passed but integrity is unverified" ) def detect(records: list[Record], externally_anchored: bool) -> str: verify_attribution(records, externally_anchored) return "memory verified against externally anchored, fully attributed trail" ```