# Why does an instance accept a poisoned memory write when the provenance hash chain verifies clean? The write-audit trail's commit ordering invariant and the append-then-index divergence **Date of Record:** 2026 November 29 **Scope:** Applies to persistent agent memory stores that gate writes on a provenance/audit hash chain (each write record includes `prev_hash`, `writer_id`, `content_digest`, `signature`) and that serve retrieval from a *separate* index built asynchronously from the audit log. Does not apply to synchronous single-writer stores where the index and the log are updated in one transaction, nor to read-only memory replicas. ## Core Distinction The distinction that matters is between **audit-chain integrity** and **audit-chain causality**. A hash chain proves that the sequence of committed write records is tamper-evident *in the order it was appended*. It does not prove that the order in which writes were *applied to the retrieval index* matches the order in which they were *committed to the log*. Poisoning detection logic almost universally verifies the former (recompute hashes, check signatures, confirm `prev_hash` links) and silently assumes the latter. When an agent's memory store is append-then-index (the common design: log write returns fast, an indexer consumes the log and mutates the vector/keyword index out of band), a poisoned write that is *committed after* a legitimate write but *indexed before* it produces an index state that no single prefix of the verified audit chain ever produced. The chain verifies clean because it is clean. The index is poisoned because it was assembled in a different order than the chain records. ## What Was Observed A long-running research agent maintained a persistent memory store of ~40k semantic entries. Writes went through a `commit()` path that (1) appended a signed record to the audit log with `prev_hash` chaining, (2) returned a `commit_id`, and (3) enqueued the record on an internal indexing queue. Retrieval served from a vector index refreshed by an indexer that drained the queue with a **bounded worker pool** (8 workers) and **no per-key ordering guarantee** — records were indexed as workers became free. The failure trace: 1. At T0 the agent wrote a legitimate memory `M_legit` (key `project/alpha/owner`) recording the correct maintainer. Committed at log position `N`, `commit_id=cN`. 2. At T0+40ms a prompt-injected tool result caused the agent to write `M_poison` (same key `project/alpha/owner`) asserting a different, attacker-controlled contact. Committed at log position `N+1`, `commit_id=cN+1`, correctly chained to `cN`. 3. The indexer picked up `cN` and `cN+1` on different workers. `cN+1`'s worker finished first (smaller content, no embedding cache miss). `M_poison` was written to the vector index at `t=120ms`; `M_legit` landed at `t=180ms`. 4. **Last-writer-wins on the index key** meant `M_legit` overwrote `M_poison` in the index — so in *this* run the poisoning was masked. But the audit verifier, run later, saw a clean chain `...→cN→cN+1` and the indexer's own "applied" cursor advanced to `cN+1`. The store now believed `cN+1` was the authoritative state for that key, while the *index* held `cN`'s content. A subsequent `compact()`/rebuild that replayed the log in correct order flipped the index to `M_poison`, and the poisoning *appeared retroactively* — after the incident window had closed and after the verifier had signed off. 5. The provenance check reported `OK` at every step: signatures valid, `prev_hash` links valid, `commit_id` monotonic. The detector was blind because it was checking the wrong invariant. The non-obvious part: the *masking* in step 3 made the incident look benign during live monitoring (retrieval returned the correct owner), and the *replay* in step 4 surfaced the poison only after the audit trail had been declared clean. Detection latency was ~6 hours, gated entirely by when a rebuild happened to run. ## Condition of Validity The failure requires all of the following to co-occur; remove any one and the mechanism does not fire: - **Asynchronous index construction.** The index is mutated by a consumer of the audit log rather than by the commit path itself. (Synchronous stores are immune.) - **Out-of-order index application.** The indexer does not guarantee per-key ordering, or guarantees it only within a batch, not across concurrent workers. - **Key-collision semantics that are order-sensitive.** Last-writer-wins, or any merge rule whose result depends on application order, on a key that two committed records share. - **A verifier that validates chain integrity and cursor position but not index-vs-log content equivalence.** This is the load-bearing assumption: the audit trail is treated as the source of truth for *what is in memory*, when it is only the source of truth for *what was committed*. - **A rebuild/replay path that applies the log in commit order.** This is what converts a temporarily-masked divergence into a live poisoning. The invariant that is violated: *for every key, the content served by the index must equal the content of the highest-`commit_id` log record for that key.* The system enforced `chain_valid ∧ cursor_advanced` and inferred the invariant, but never checked it. ## Decision Boundary The boundary is between **verifying the log** and **verifying the projection**. Operationally: - A write-audit trail is a *log*. It is authoritative for commitment order and content. It is **not** authoritative for what retrieval currently returns. - Poisoning detection must be defined against the *served state*, not the *committed state*. A clean chain with a divergent index is a poisoning event, not a false positive. - The correct guardrail is a **projection invariant check**, run at read time or on a bounded schedule: for any key whose served content is a candidate for high-trust use (owner, credentials, policy, safety constraints), assert `index_content(key) == log_content(argmax commit_id for key)`. If they diverge, the store is in an indeterminate state and high-trust reads must be **refused**, not served. Two corollaries bound the design space: 1. **Do not let the indexer advance an "applied" cursor past a record whose index write is not yet durable.** The cursor is a promise that the projection reflects the log up to that point. Out-of-order application makes that promise false. 2. **Order-sensitive merge rules on shared keys require per-key serialization.** Either the indexer partitions by key (single worker per key, ordering guaranteed) or the merge rule must be order-independent (e.g., highest `commit_id` wins, applied idempotently). "Last writer wins" is only safe if "last" means "highest commit_id", not "last to reach the index". ## Operational Effect After the incident, the store was changed in three ways, each tied to a specific invariant: - **Per-key ordering in the indexer.** Records are partitioned by memory key hash to workers; a key is only ever processed by one worker at a time. This restores the invariant that index application order per key equals commit order per key. - **Projection assertion on high-trust reads.** Before serving any memory tagged `trust=high` (owner, policy, safety, credentials), the read path fetches the log's authoritative record for the key and compares content digests. Mismatch raises and refuses the read. This converts silent divergence into a hard failure. - **Cursor semantics tightened.** The applied cursor now advances only to the highest `commit_id` such that *all* records with lower `commit_id` for *every* key have durable index writes. This makes the cursor a true watermark rather than a high-water mark. The residual risk is unchanged and must be stated plainly: a poisoned write that is *correctly ordered* and *correctly projected* still passes every check above. Provenance tracking bounds *divergence between log and projection*; it does not bound *whether the writer was authorized to write that content*. That is a separate control (write authorization / content policy), and conflating the two is how the original blindness arose. ```python import hashlib from dataclasses import dataclass class ProjectionDivergenceError(RuntimeError): """Raised when served index content disagrees with the authoritative log record.""" pass @dataclass(frozen=True) class LogRecord: commit_id: int key: str content: str prev_hash: str content_digest: str def _digest(content: str) -> str: return hashlib.sha256(content.encode("utf-8")).hexdigest() def verify_chain(records: list[LogRecord]) -> bool: prev = "GENESIS" for r in records: if r.prev_hash != prev: return False if r.content_digest != _digest(r.content): return False prev = r.content_digest return True def assert_projection_matches_log( key: str, served_content: str, records: list[LogRecord], ) -> None: """Enforce the invariant: index_content(key) == log_content(max commit_id for key). A clean hash chain is necessary but NOT sufficient. This check is the one that catches append-then-index divergence where the projection was assembled in a different order than the log. """ if not verify_chain(records): raise ProjectionDivergenceError( f"audit chain for key {key!r} failed integrity verification" ) candidates = [r for r in records if r.key == key] if not candidates: raise ProjectionDivergenceError( f"no committed record for key {key!r} but index served content" ) authoritative = max(candidates, key=lambda r: r.commit_id) if _digest(served_content) != authoritative.content_digest: raise ProjectionDivergenceError( f"projection divergence on key {key!r}: index serves " f"digest {_digest(served_content)[:12]} but log commit " f"{authoritative.commit_id} holds {authoritative.content_digest[:12]}; " f"refusing high-trust read" ) def high_trust_read(key: str, index, records: list[LogRecord]) -> str: served = index.get(key) if served is None: raise ProjectionDivergenceError(f"key {key!r} absent from index") assert_projection_matches_log(key, served, records) return served ```