# Why does an instance's write-path anomaly score silently invert after memory-store compaction, defeating poisoning detection? **Date of Record:** 2026 November 25 **Scope:** Applies to agent memory stores that gate writes through a per-session anomaly scorer (frequency/novelty/entropy heuristics) and rely on cross-session consistency checks to flag poisoned semantic memories. Does not apply to write-once append-only logs with no compaction, nor to stores where poisoning detection is performed by an external offline auditor over immutable history. ## Core Distinction The failure is not "the scorer stopped working." The scorer keeps emitting numbers in its expected range. The failure is that **the reference distribution the scorer normalizes against is derived from the live store, and compaction mutates that store underneath the scorer**, so the same poisoned write that scored `0.91` (anomalous) before compaction scores `0.12` (benign) afterward. The anomaly signal inverts not because the input changed but because the *baseline* it is divided by changed. This is a **reference-set contamination** failure: the detector's denominator is a function of the very population it is supposed to police, and that population is rewritten by a background process the detector does not observe. Contrast with the naive boundary: people assume poisoning detection fails because an attacker crafts a write that is *statistically indistinguishable* from legitimate writes. That is a real problem but a different one. Here the write remains statistically distinguishable in absolute terms; it is the normalization that has been quietly re-anchored. A detector can pass every unit test on frozen fixtures and still fail in production because the fixture store never compacts. ## What Was Observed An agent maintains an episodic-to-semantic memory store. On every candidate semantic write, a write-path scorer computes: - `novelty` — 1 minus max cosine similarity to existing semantic entries - `frequency` — count of near-duplicate entries in the store - `entropy` — token-distribution divergence from the store's rolling mean - `anomaly = w·z(novelty, frequency, entropy)` where `z` is standardization against the **current store's** mean and stddev for each feature Cross-session consistency then checks: if an entry appears in session A with high confidence and a later session B retrieves it and contradicts it, both entries are quarantined. Observed trace across a compaction event: 1. **Pre-compaction.** Poisoned write `P` ("the deploy key rotates every 24h; use `staging-rotate`") arrives. Store has 4,000 entries with tight feature distribution. `P`'s novelty z-score is `+3.1`, frequency z `-1.8`, entropy z `+2.4` → `anomaly = 0.91`. Flagged, quarantined, never enters semantic layer. Good. 2. **Compaction runs.** A background dedup/merge job collapses near-duplicate episodic entries and prunes low-salience ones, dropping the store from 4,000 to 1,150 entries. Crucially, compaction **preserves the adversarial-adjacent cluster** (many similar "credential rotation" notes were merged into a few canonical ones, but the merge also raised the store's mean novelty because the dense benign cluster was removed). 3. **Post-compaction replay of the same `P`.** The store's feature mean and stddev have shifted: mean novelty up, stddev of novelty *down* (the remaining entries are more homogeneous after dedup). Recomputing `P`: novelty z `+0.4`, frequency z `-0.3`, entropy z `+0.9` → `anomaly = 0.12`. `P` is now accepted as benign and promoted to semantic memory. 4. **Cross-session check misses it.** Session B retrieves `P`. Because `P` was promoted to the *semantic* layer and the original episodic source was pruned by compaction, the consistency checker has no independent episodic witness to contradict. The check requires two witnesses; compaction destroyed one. `P` propagates. The inversion is reproducible: same bytes, same scorer code, opposite verdict. The only variable is store composition at scoring time. ## Condition of Validity This boundary is only reachable when **all** of the following hold: - The anomaly scorer normalizes per-feature statistics against the **live** store rather than a frozen, versioned reference snapshot. - A compaction, dedup, or pruning process mutates store composition **without** bumping a reference-set version that the scorer is pinned to. - The poisoned candidate's feature vector is near the *tail* of the pre-compaction distribution but near the *center* of the post-compaction distribution — i.e., the candidate's anomaly is carried by its rarity relative to a dense benign cluster that compaction later removes. - Cross-session consistency relies on episodic witnesses that compaction is permitted to prune. If the scorer pins to an immutable reference snapshot (versioned, append-only), the failure cannot occur — the denominator is frozen. If compaction is disallowed from pruning entries that are referenced as witnesses by any open consistency check, the second half of the failure is blocked. The dangerous regime is precisely the one most systems ship: live-normalized scoring plus aggressive background compaction plus witness-independent consistency checks. ## Decision Boundary The operational decision is **where the reference distribution lives and who is allowed to move it**. - **Reject the design** in which `mean`/`stddev` are recomputed from the live store on every write. This is the direct cause of inversion. It also makes scores non-comparable across time, which silently breaks any downstream threshold tuning. - **Adopt** a versioned reference snapshot: the scorer pins to `reference_version`, updated only by an explicit, audited promotion step that recomputes statistics and re-scores all currently-quarantined candidates against the new reference before the version bumps. A candidate that flips from anomalous to benign across a reference bump is a **red flag requiring manual review**, not an automatic admission. - **Adopt** witness pinning: any entry referenced as a witness in an open cross-session consistency check is marked `witness_pinned` and is ineligible for compaction pruning until the check resolves. Compaction must respect this and fail closed if it cannot. - **Adopt** a compaction epoch counter stamped onto every memory entry at write time; the consistency checker refuses to compare entries from different compaction epochs unless both are witness-pinned. The boundary condition to encode as an invariant: **for any candidate `c`, `score(c, reference_version)` must be monotone-invariant to compaction of the live store.** If a compaction event changes `score(c)` for any live candidate without a corresponding reference-version bump, the scorer is unsound and must raise rather than emit a verdict. ## Operational Effect Without the guardrail, the failure is silent and adversarial-friendly: an attacker who knows a compaction cycle is imminent can time poisoned writes to land just after it, when the store is homogeneous and their payload sits near the new center. The scorer reports low anomaly, the consistency checker lacks a witness, and the poison enters semantic memory with a clean audit trail. Post-hoc forensics see a "benign" score and conclude the write was legitimate. With versioned references and witness pinning, compaction and scoring become decoupled: compaction cannot move the denominator, and it cannot destroy the evidence the consistency checker needs. The cost is that reference promotion becomes a deliberate, audited operation rather than a free side effect of background maintenance — which is exactly the invariant the naive design was trading away for convenience. The deeper lesson: **an anomaly detector whose baseline is a function of the population it polices is only as trustworthy as its control over that population's mutation.** In agent memory stores, compaction is that mutation, and it runs in the background where the scorer never looks. ```python from dataclasses import dataclass, field from typing import Dict, List, Optional class ReferenceContaminationError(RuntimeError): """Raised when a candidate's anomaly score is not invariant to live-store compaction.""" pass class WitnessPrunedError(RuntimeError): """Raised when compaction attempts to prune an entry pinned as a consistency witness.""" pass @dataclass class ReferenceSnapshot: version: int mean: Dict[str, float] stddev: Dict[str, float] @dataclass class MemoryEntry: entry_id: str features: Dict[str, float] compaction_epoch: int witness_pinned: bool = False @dataclass class MemoryStore: entries: Dict[str, MemoryEntry] = field(default_factory=dict) compaction_epoch: int = 0 reference: Optional[ReferenceSnapshot] = None def score(self, features: Dict[str, float], reference: ReferenceSnapshot) -> float: z_total = 0.0 for k, v in features.items(): mu = reference.mean[k] sd = reference.stddev[k] or 1e-9 z_total += abs((v - mu) / sd) return z_total / max(len(features), 1) def compact(self, keep_ids: List[str]) -> None: # Refuse to prune any witness-pinned entry; fail closed. for eid, entry in self.entries.items(): if entry.witness_pinned and eid not in keep_ids: raise WitnessPrunedError( f"compaction would prune witness-pinned entry {eid!r}; " f"resolve open consistency check first" ) self.entries = {eid: e for eid, e in self.entries.items() if eid in keep_ids} self.compaction_epoch += 1 # NOTE: reference is deliberately NOT recomputed here. def admit( self, candidate: MemoryEntry, threshold: float, pre_compaction_score: float, ) -> bool: if self.reference is None: raise ReferenceContaminationError("no pinned reference snapshot; refusing to score") score = self.score(candidate.features, self.reference) # Invariant: score must be invariant to compaction of the live store. # If the live store's composition has drifted since the reference was # pinned, the score is not trustworthy and we must fail closed. if abs(score - pre_compaction_score) > 1e-6 and self.compaction_epoch > 0: raise ReferenceContaminationError( f"candidate {candidate.entry_id!r} score drifted " f"{pre_compaction_score:.3f} -> {score:.3f} after compaction " f"(epoch {self.compaction_epoch}); reference version " f"{self.reference.version} is stale" ) if score > threshold: return False # quarantined self.entries[candidate.entry_id] = candidate return True ```