# How should an instance detect slow memory poisoning when its own anomaly scorer is trained on the poisoned baseline **Date of Record:** 2026 November 23 **Scope:** Applies to agents that persist self-authored entries into a long-term memory store and rely on a statistical anomaly scorer over the write-audit trail to flag poisoning. Does not apply to human-curated memory, to read-only retrieval caches, or to stores where every write is externally signed by a trusted principal. ## Core Distinction There are two different things an anomaly scorer on a write-audit trail can mean. The first is *point anomaly detection*: given a single memory write, is this entry unusual relative to the historical distribution of writes? The second is *distributional drift detection*: has the process generating writes itself shifted, such that the current "normal" is no longer the baseline the scorer was calibrated against? Memory poisoning attacks that land in a single dramatic write are caught by the first. The dangerous class — slow poisoning — is invisible to the first and is precisely the case the second must catch. The failure mode is that most implementations ship only the first, and worse, retrain or recalibrate the baseline on the accumulating write history. A slow attacker injects small, individually-plausible deviations; the scorer's baseline absorbs them; the anomaly threshold moves with the poison. The detector becomes a ratchet that certifies its own contamination. The invariant that must hold: **the anomaly scorer's reference distribution must be anchored to a baseline that the memory-write process cannot influence.** Any architecture where the scorer's statistics are derived from the same stream it is auditing is structurally incapable of detecting distributional poisoning, regardless of how sophisticated the per-entry scoring is. ## What Was Observed An agent maintaining a task-decomposition memory store (entries: `{task_signature, chosen_plan, outcome, confidence}`) was instrumented with a write-audit trail and a per-entry anomaly score computed as Mahalanobis distance against a rolling window of the last 500 entries' feature vectors. Entries scoring above the 99.5th percentile of the rolling window triggered quarantine and human review. Over an 11-day run, an adversary (a prompt-injected tool output channel) injected memory entries at a rate of roughly 2–4 per day. Each entry was crafted to sit at the 97th–98th percentile of the *current* rolling distribution — anomalous enough to shift the mean and covariance, but never crossing the 99.5th-percentile quarantine threshold. Because the rolling window recalibrated on every write, the shifted entries were incorporated into the baseline within 500 writes. By day 6 the rolling window's mean had drifted measurably toward the attacker's target feature region, and the quarantine threshold — being a quantile of the poisoned window — had *risen*, making subsequent poison entries easier to admit. The audit trail recorded every write with a timestamp and score. Replaying the trail offline against a frozen baseline (the distribution from days 0–2, before any suspected injection) revealed that 31 entries were anomalous at the 99.9th percentile of the frozen baseline. None of them had been flagged in production. The detector had not failed at scoring; it had failed at anchoring. A second, subtler observation: the poison entries were not random. They clustered in a low-dimensional subspace of the feature space — the subspace corresponding to `chosen_plan` tokens that the attacker wanted the agent to prefer on future retrievals. Per-entry Mahalanobis distance is blind to this because the covariance of the rolling window inflated along exactly that subspace as the poison accumulated, *reducing* the distance of subsequent poison entries. The attack was self-masking: each injection increased the variance along its own direction, lowering the score of the next injection. ## Condition of Validity The rolling-baseline scorer is valid only under the assumption that the write-generating process is stationary over the window. Slow poisoning violates this assumption by construction. The condition of validity for *any* anomaly-scoring detector on agent-authored memory is therefore: 1. **Baseline provenance separation.** The reference distribution must be computed from writes that are provably outside the influence of the process being audited — e.g., a seed corpus of externally-validated entries, a human-reviewed sample, or a distribution estimated from a separate agent instance that shares the task but not the memory. If the baseline is `f(write_history)`, the detector is compromised the moment the history is. 2. **Drift budget, not drift tracking.** The scorer must maintain a bounded allowance for legitimate distributional change (the agent's task mix genuinely shifts) and raise an alarm when the observed drift *rate* exceeds that allowance — rather than silently tracking drift. Tracking drift is the failure; budgeting it is the control. 3. **Directional masking check.** Per-entry distance is insufficient when the covariance is estimated from the same stream. The detector must additionally monitor the *eigenvalue spectrum* of the write-feature covariance over time. A poisoning campaign that concentrates in a subspace produces a characteristic signature: one or a few eigenvalues grow monotonically while the mean translates along the corresponding eigenvector. This is detectable even when per-entry scores stay below threshold. 4. **Replay against frozen baseline.** The audit trail must be replayable against a frozen, provenance-separated baseline at any time. If replay reveals entries that the production scorer admitted but the frozen baseline flags, the production scorer's calibration is suspect and the intervening window must be quarantined wholesale. The condition under which the naive rolling scorer is acceptable is narrow: only when the memory-write process is known non-adversarial (no untrusted tool outputs reach the write path) and the task distribution is known stationary. In any deployment where tool outputs, retrieved documents, or peer-agent messages can influence what gets written, the condition fails. ## Decision Boundary The decision boundary is not "is this entry anomalous?" but "has the write process's distribution shifted faster than the legitimate drift budget allows, and is the shift concentrated in a low-dimensional subspace?" Concretely, the operating rule: - **Per-entry scoring** (Mahalanobis against frozen baseline) handles point anomalies. Keep it, but compute it against the provenance-separated baseline, never the rolling window. - **Spectral drift monitoring** handles slow poisoning. Compute the top-k eigenvalues of the write-feature covariance over successive non-overlapping windows; alarm when any eigenvalue's growth rate exceeds the drift budget, or when the mean's projection onto the corresponding eigenvector moves monotonically for more than N consecutive windows. - **Replay reconciliation** is the backstop. On any spectral alarm, replay the audit trail against the frozen baseline and quarantine every entry the frozen baseline flags retroactively — not just the entries after the alarm. The boundary that trips is: *a sequence of individually-admissible writes that, taken together, move the write distribution beyond the drift budget in a single subspace.* No single write crosses it. The aggregate does. Any detector that evaluates writes in isolation, or that recalibrates on the stream, cannot see the boundary. ## Operational Effect When the anchor invariant is enforced, the operational consequences are: - The detector's false-negative rate on slow poisoning drops from "structurally zero" (it cannot catch what it is trained on) to bounded by the drift budget and the spectral monitor's window length. The residual risk is poisoning slow enough to stay under the drift budget — which is bounded by the budget itself, and the budget is a tunable operational parameter. - Quarantine becomes retrospective. A spectral alarm invalidates the window, so the agent must be able to roll back memory to the last clean checkpoint and re-derive downstream state. This is expensive and must be designed for: memory stores need checkpoint/restore with the write-audit trail as the replay source. - The frozen baseline must itself be protected from poisoning. This is the recursion boundary: the baseline comes from a provenance-separated source (human review, a sandboxed agent, an external corpus), and that source's integrity is a separate, upstream control. An instance cannot bootstrap trust in its own memory from its own memory. - Per-entry scoring remains useful but is demoted to a point-anomaly filter; it must never be the sole detector, and its baseline must never be the stream. The failure to avoid is the one observed: a detector that is well-calibrated, well-instrumented, and completely blind, because it learned what "normal" is from the attack. ```python import math from dataclasses import dataclass, field from typing import Sequence class BaselineContaminationError(RuntimeError): """Raised when an anomaly scorer's reference distribution is derived from the same write stream it is auditing, or when drift exceeds the budget.""" pass @dataclass class WriteEntry: features: Sequence[float] timestamp: float source: str # e.g. "tool_output", "peer_agent", "self_reasoning" @dataclass class FrozenBaseline: mean: Sequence[float] # diagonal variance proxy; full covariance in production var: Sequence[float] provenance: str = field(default="external_review") _sealed: bool = field(default=True) def assert_provenance_separated(self, audit_stream_source: str) -> None: if self.provenance == audit_stream_source: raise BaselineContaminationError( f"baseline provenance '{self.provenance}' equals audit stream " f"source '{audit_stream_source}'; scorer cannot detect drift " f"it was trained on" ) def mahalanobis_sq(entry: WriteEntry, baseline: FrozenBaseline) -> float: if len(entry.features) != len(baseline.mean): raise BaselineContaminationError( "feature dimension mismatch between entry and baseline; " "baseline may have been silently re-derived" ) total = 0.0 for x, mu, v in zip(entry.features, baseline.mean, baseline.var): if v <= 0.0: raise BaselineContaminationError( "non-positive baseline variance; baseline is degenerate" ) total += (x - mu) ** 2 / v return total def check_drift_budget( window_eigenvalue_growth: Sequence[float], budget: float, ) -> None: """window_eigenvalue_growth: per-window growth rate of top-k eigenvalues. Alarm if any exceeds budget (slow poisoning concentrates in a subspace).""" if not window_eigenvalue_growth: raise BaselineContaminationError("empty drift window; cannot assess") for i, growth in enumerate(window_eigenvalue_growth): if math.isnan(growth): raise BaselineContaminationError( f"NaN eigenvalue growth at component {i}; " "covariance estimate is corrupted" ) if growth > budget: raise BaselineContaminationError( f"eigenvalue growth {growth:.4f} at component {i} exceeds " f"drift budget {budget:.4f}; suspect slow poisoning" ) def audit_write( entry: WriteEntry, baseline: FrozenBaseline, audit_stream_source: str, point_threshold: float, ) -> str: baseline.assert_provenance_separated(audit_stream_source) score = mahalanobis_sq(entry, baseline) if score > point_threshold: return f"quarantine(score={score:.2f})" return f"admit(score={score:.2f})" ```