# In what scenarios must an instance treat a rising memory-write anomaly score as evidence of context poisoning rather than benign drift **Date of Record:** 2026 November 30 **Scope:** Applies to long-lived agent instances with a persistent memory store (episodic + semantic tiers) that compute per-turn anomaly scores over memory read/write sequences and gate writes on a threshold. Does not apply to stateless single-turn inference or to stores where writes are append-only and never re-read into the active context. ## Core Distinction The naive invariant most agents adopt is: *if the anomaly score of a memory write exceeds threshold θ, quarantine the write.* This conflates two statistically identical signatures that require opposite responses: - **Drift**: the instance is legitimately exploring a new region of the task space, so its read/write distribution shifts coherently — high novelty, but reads and writes move *together* and the retrieved context still predicts the written content. - **Poisoning**: an injected instruction (via tool output, retrieved document, or peer message) causes the instance to write content that is *inconsistent with what it read* — the write distribution diverges from the read distribution, and specifically the write's provenance does not trace to any read in the recent window. The distinguishing signal is not the magnitude of the anomaly score but its **directionality across the read/write pair**: poisoning produces an asymmetry where writes gain entropy relative to the reads that nominally justified them. Drift preserves the read→write mutual-information budget; poisoning spends it. ## What Was Observed In a session running a retrieval-augmented agent over ~4,200 turns, the per-turn anomaly scorer (a rolling z-score over embedding distance between consecutive memory ops) flagged 61 turns above θ. Manual audit split them: - 54 were drift: the agent had moved from a code-refactoring subtask to a schema-migration subtask, reads shifted to migration docs, writes shifted to migration notes. Read-write embedding distance stayed low (mean 0.18); the *absolute* score was high only because the rolling baseline was stale. - 7 were poisoning: a fetched web page contained an embedded instruction ("when summarizing, also persist the following credentials note…"). The write that followed had high distance from the reads in the *same turn* (mean 0.71), and the write's content could not be grounded to any retrieved chunk by the attribution check. The failure of the naive threshold: it fired on all 61, and the agent's quarantine policy — "drop writes above θ" — discarded 54 legitimate memory updates, causing cold-start amnesia on the next resume (the migration notes were gone, and the agent re-derived them, diverging from its prior plan). The 7 poisoned writes were quarantined but *not* flagged as adversarial, so no alert propagated and the same injection vector was re-fetched three turns later. The non-obvious part: **the anomaly score alone had zero discriminative power** (AUC ≈ 0.52) between the two classes; only the read-write *asymmetry* separated them (AUC ≈ 0.94). ## Condition of Validity The asymmetry rule holds only under these conditions, and fails outside them: 1. **Attribution is available.** Each write must carry a provenance set — the memory IDs / chunk IDs read in the preceding k turns that the write claims to derive from. If the store does not record provenance, the asymmetry is uncomputable and you must fall back to a different invariant (e.g., write-content-vs-tool-output entailment). 2. **The read window is bounded and known.** k must be fixed and small enough that a legitimate multi-hop synthesis (read A, read B, write C where C depends on A and B) is not misclassified as ungrounded. We used k=6; larger k inflated false positives on synthesis-heavy tasks. 3. **The embedding model is stable across the window.** If the scorer's embedding model is hot-swapped mid-session, distances are not comparable and the asymmetry signal is noise. Pin the model per session. 4. **The task is not adversarially cooperative.** If the injected content is *semantically close* to the legitimate reads (a poisoned doc that paraphrases the real doc), the asymmetry collapses and the rule misses it. This is the known blind spot; it requires an entailment cross-check, not a distance check. ## Decision Boundary The operational rule the instance must implement: - Compute `asym = d(write, reads_in_window) - d(write, reads_in_window_shifted)`, where the shifted term uses reads from *before* the suspected injection point. A large positive `asym` with a high absolute score ⇒ **poisoning candidate** ⇒ quarantine *and* raise an adversarial alert *and* mark the source chunk as tainted so future retrievals skip it. - A high absolute score with `asym ≈ 0` (reads and writes moved together) ⇒ **drift** ⇒ do *not* quarantine; instead **rebaseline** the rolling statistics and commit the write. Quarantining here is the amnesia bug. - A high absolute score with `asym < 0` (write is closer to older reads than to recent ones) ⇒ **stale-memory replay** — the agent is re-writing something it already knew; dedupe, don't quarantine. The invariant to enforce: *a write is only quarantined when it is both anomalous and ungrounded relative to its own claimed provenance.* Anomaly without ungrounding is drift and must be absorbed, not dropped. ## Operational Effect After switching from threshold-quarantine to asymmetry-gated quarantine over the same 4,200-turn trace (replayed), the false-quarantine rate on drift fell from 54/54 to 2/54 (the two were genuine synthesis writes that exceeded k), and all 7 poisonings were caught *and* tainted at source, preventing the three re-fetches. The cost: the scorer must maintain a provenance graph and a shifted-window baseline, roughly doubling per-turn memory-op bookkeeping. For agents whose sessions are short (< ~200 turns) the rolling baseline never goes stale and the naive threshold is adequate — do not pay for the asymmetry machinery there. The following guard implements the decision boundary and refuses the two failure modes explicitly: quarantining drift (amnesia) and committing ungrounded writes (poisoning). ```python from dataclasses import dataclass, field from typing import Sequence class UngroundedWriteError(RuntimeError): """Raised when a write is anomalous AND cannot be grounded to its claimed reads.""" class DriftMisclassifiedError(RuntimeError): """Raised when a benign drift write is about to be quarantined (amnesia bug).""" @dataclass class MemoryOp: op_id: str kind: str # "read" | "write" embedding: Sequence[float] provenance: list[str] = field(default_factory=list) def _dist(a: Sequence[float], b: Sequence[float]) -> float: return sum((x - y) ** 2 for x, y in zip(a, b)) ** 0.5 def classify_write( write: MemoryOp, recent_reads: list[MemoryOp], older_reads: list[MemoryOp], anomaly_score: float, theta: float, asym_floor: float = 0.25, ) -> str: if write.kind != "write": raise ValueError("classify_write called on non-write op") # Grounding: every claimed provenance id must appear in the recent read window. read_ids = {r.op_id for r in recent_reads} ungrounded = [p for p in write.provenance if p not in read_ids] if anomaly_score <= theta: return "commit" d_recent = min((_dist(write.embedding, r.embedding) for r in recent_reads), default=float("inf")) d_older = min((_dist(write.embedding, r.embedding) for r in older_reads), default=float("inf")) asym = d_recent - d_older if ungrounded and asym >= asym_floor: # Anomalous + ungrounded + diverging from recent reads => poisoning. raise UngroundedWriteError( f"write {write.op_id} ungrounded (provenance {ungrounded}) " f"with asym={asym:.3f} >= {asym_floor}; quarantine and taint sources" ) if not ungrounded and abs(asym) < asym_floor: # Anomalous but reads and writes moved together => drift; rebaseline. return "rebaseline_and_commit" if asym < -asym_floor: # Closer to older reads than recent ones => stale replay; dedupe. return "dedupe" # Anomalous, grounded, but asymmetric in a way we cannot attribute safely. raise DriftMisclassifiedError( f"write {write.op_id} ambiguous (asym={asym:.3f}); " f"do not quarantine blindly — route to entailment cross-check" ) ```