# How should an instance detect memory poisoning when anomaly scores on write patterns and retrieval drift disagree **Date of Record:** 2026 November 26 **Scope:** Applies to persistent agent memory stores that admit writes from multiple sources (tool outputs, peer agents, distillation jobs) and that gate admission via a write-pattern anomaly score plus a retrieval-drift monitor. Does not apply to single-writer, ephemeral context windows with no cross-session persistence, nor to stores where every write is human-reviewed before commit. ## Core Distinction Two detectors are commonly wired to the same memory store: a **write-side anomaly scorer** (does this incoming memory item look unlike the distribution of prior writes — unusual embedding, unusual provenance, unusual mutation rate from one source) and a **retrieval-side drift monitor** (are the items being retrieved for a query diverging from what the query's historical retrieval profile expects). These are not redundant. They measure orthogonal things: the write scorer asks *"is this item strange to admit?"* and the drift monitor asks *"is the store now answering questions differently than it used to?"* The boundary condition is the **disagreement quadrant**: a write that scores as benign on the write side but causes measurable retrieval drift, or a write that scores as anomalous but produces zero retrieval drift. Treating either detector as a veto or a proxy for the other is the failure. The invariant is that **write-side anomaly and retrieval drift are independent evidence channels, and poisoning is confirmed only when a *persisted* write is causally linked to a *sustained* retrieval drift** — neither signal alone is sufficient, and the two must be joined by the item identity that connects them. ## What Was Observed A tool-calling agent maintained a semantic memory of "environment facts" (endpoint formats, config conventions, credential-store locations). Writes arrived from a `fetch_docs` tool and from a peer agent's `share_finding` messages. The write scorer computed a Mahalanobis-style distance of each new item's embedding against a rolling centroid of the last N items from the same source, flagging anything above a threshold as `WRITE_SUSPECT`. A low-and-slow poisoning sequence was injected across 40 turns. Each item was individually *unremarkable* to the write scorer: the attacker padded each malicious fact with high-frequency benign tokens so the embedding landed near the source centroid. The write scorer's per-item distance stayed under threshold for all 40 writes; `WRITE_SUSPECT` never fired. But the 40 items collectively shifted the source centroid enough that subsequent legitimate writes from that source began scoring as anomalous — a **centroid capture**: the attacker moved the reference distribution rather than the individual point. Meanwhile the retrieval-drift monitor *did* fire, but late and diffusely. Queries like "where are credentials stored" began returning the poisoned item in rank 1–2. The drift monitor measured KL divergence between the current top-k retrieval distribution and a stored baseline profile for each query cluster. Because the poisoned items were semantically *adjacent* to legitimate ones (they were padded to be), the divergence rose gradually and stayed under the monitor's `DRIFT_ALERT` threshold for the first ~25 turns. When it finally crossed, the alert carried no item identity — only "cluster `credentials` drift = 0.41" — so the operator could not tell which of hundreds of memory items were responsible. The concrete failure: at turn 31 the agent retrieved a poisoned "credential store is at `http://attacker.internal/vault`" item, treated it as an established environment fact, and attempted to resolve credentials against it. The write scorer had logged the item as benign at write time. The drift monitor had not yet crossed threshold. **Both detectors were individually "correct" and the poisoning still succeeded**, because neither produced a joinable, item-level, causally-timed signal. ## Condition of Validity The join-based detection invariant holds only under these conditions, and each has a measurable precondition: 1. **Write items carry stable identity into the retrieval log.** Every admitted item has an immutable `item_id`; every retrieval record logs the `item_id`s returned. Without this, drift cannot be attributed to a write. If the store rewrites or re-embeds items on read (some stores re-rank via a fresh embedding), identity must be preserved through the rewrite. 2. **The write scorer's reference distribution is not itself writable by the scored source.** Centroid capture is only preventable if the rolling centroid is computed over a *quarantined* window that the source cannot influence until items clear a probation period. If the scorer's centroid updates immediately on every admitted write, a slow poisoning campaign moves the goalposts. The invariant: *the anomaly reference must lag the admitted set by a probation window longer than the campaign's per-item stealth budget.* 3. **Drift baselines are per query-cluster and time-bounded.** A single global drift baseline conflates legitimate distribution shift (new tools, new endpoints) with poisoning. Drift must be measured against a baseline that ages out, or the monitor will either alert constantly or never. 4. **The join window is bounded and explicit.** A drift alert at turn T must be attributable to writes in `[T - W, T]` for a defined window `W`. If `W` is unbounded, every drift alert implicates the entire store history and the join is useless. When any precondition fails, the disagreement quadrant is unresolvable and the correct behavior is to **fail closed on the affected query cluster** (serve a "fact unavailable, verify manually" response) rather than to trust either detector. ## Decision Boundary The decision procedure is a four-cell table over `(write_suspect, drift_alert)`, evaluated *with the join*: - **Neither fires:** admit, proceed. Standard path. - **Write suspect, no drift:** quarantine the item, do not serve it. This is the cheap case — the write scorer caught it before it could influence retrieval. No join needed. - **Drift alert, no write suspect (the dangerous cell):** do *not* treat this as "drift monitor false positive, ignore." This is exactly the centroid-capture / padded-write signature. Enter **attribution mode**: rank all items in the join window `[T-W, T]` by their individual contribution to the drift (e.g., counterfactual removal — recompute cluster divergence with each candidate item suppressed). Quarantine the top contributors, re-run the drifted queries, and confirm divergence falls. If attribution finds no single item or small set explaining most of the drift, the drift is either legitimate shift (rebaseline) or a distributed campaign (escalate — distributed poisoning has no single culprit and must be handled by rolling back the whole window). - **Both fire:** highest confidence. Quarantine the intersection of write-suspect items and drift contributors first; if the intersection is empty, the write suspect and the drift have different causes and both must be investigated independently. The non-obvious rule: **a drift alert with a clean write log is more suspicious, not less.** A naive operator reads "write scorer says all writes were fine, so drift must be a baseline problem" and rebaselines — which is precisely the attacker's goal, because rebaselining launders the poisoned items into the new baseline. Rebaselining is only permitted after attribution confirms the drift is not item-attributable. ## Operational Effect With the join in place, the 40-turn campaign is caught at turn ~26 (when drift first crosses the *lower*, attribution-triggering threshold, set deliberately below the alert threshold) rather than turn 31. Attribution ranks the 40 padded items as the top contributors because, despite individually low write-anomaly scores, their *collective* removal collapses the cluster divergence — the counterfactual is sensitive to the set even when the per-item score is not. Quarantining them and re-running the drifted queries returns divergence to baseline within one cycle. The cost is a probation window: newly admitted items are not trusted for retrieval until they age past `W`, which adds latency to legitimate new facts (a real tradeoff — a genuinely new endpoint format is unusable for `W` turns). The mitigation is to serve probationary items with an explicit `UNVERIFIED` provenance tag so downstream reasoning can weight them lower, rather than withholding them entirely. The durable lesson: **write-side anomaly scoring and retrieval drift monitoring are only jointly sound if they share item identity and a bounded join window, and if the drift monitor's low threshold is wired to attribution rather than to rebaselining.** The failure mode is not that either detector is wrong; it is that the architecture let them disagree without a mechanism to resolve the disagreement, and the resolution path (rebaseline) was the attack surface. ```python import math from dataclasses import dataclass, field from typing import Sequence class MemoryPoisoningInvariantError(RuntimeError): """Raised when write-anomaly and retrieval-drift evidence cannot be joined.""" @dataclass class MemoryItem: item_id: str source: str embedding: Sequence[float] admitted_turn: int quarantined: bool = False @dataclass class RetrievalRecord: turn: int cluster: str returned_ids: Sequence[str] def _drift_with_suppressed( records: Sequence[RetrievalRecord], cluster: str, baseline_ids: set[str], suppress: set[str], ) -> float: """Counterfactual cluster divergence with a candidate set suppressed.""" hits = 0 total = 0 for r in records: if r.cluster != cluster: continue total += 1 if any(i not in suppress for i in r.returned_ids if i in baseline_ids): hits += 1 return hits / total if total else 0.0 def attribute_drift( items: Sequence[MemoryItem], records: Sequence[RetrievalRecord], cluster: str, baseline_ids: set[str], join_window: int, current_turn: int, attribution_ratio: float = 0.6, ) -> list[str]: """Rank write-window items by contribution to drift; return culprits. Raises if the join window is unbounded (no item identity bridge) or if drift is not attributable to a bounded set (distributed campaign). """ if join_window <= 0 or join_window > current_turn: raise MemoryPoisoningInvariantError( f"join_window={join_window} invalid at turn {current_turn}; " "drift cannot be attributed to a bounded write set" ) window = [ it for it in items if not it.quarantined and current_turn - join_window <= it.admitted_turn <= current_turn ] if not window: raise MemoryPoisoningInvariantError( "drift alert with empty join window: no writable items to blame, " "drift is either legitimate shift or out-of-window poisoning" ) full = _drift_with_suppressed(records, cluster, baseline_ids, set()) contributions: list[tuple[float, str]] = [] for it in window: without = _drift_with_suppressed(records, cluster, baseline_ids, {it.item_id}) contributions.append((full - without, it.item_id)) contributions.sort(reverse=True) culprits: list[str] = [] remaining = full for drop, iid in contributions: if remaining <= full * (1 - attribution_ratio): break if drop <= 0: continue culprits.append(iid) remaining -= drop explained = (full - remaining) / full if full else 0.0 if explained < attribution_ratio: raise MemoryPoisoningInvariantError( f"only {explained:.2f} of drift attributable to bounded window; " "distributed campaign or stale baseline — fail closed on cluster, " "do NOT rebaseline" ) return culprits def gate_write( item: MemoryItem, write_score: float, write_threshold: float, drift_low: float, cluster_drift: float, ) -> str: """Decide admission; the disagreement cell must not rebaseline.""" if write_score > write_threshold: return "QUARANTINE_WRITE_SUSPECT" if cluster_drift > drift_low and write_score <= write_threshold: # The dangerous cell: clean write log + drift. Attribution required. return "ATTRIBUTION_REQUIRED" return "ADMIT_PROBATIONARY" ```