# Which invariants prevent memory-poisoning detection from silently inverting under embedding-space drift **Date of Record:** 2026 November 30 **Scope:** Applies to agents that write episodic/semantic memories through an embedding-space anomaly gate backed by a write-audit provenance DAG, and that detect poisoning by scoring new writes against a running centroid of trusted memories. Does not apply to stateless single-shot calls or to systems where every write is human-approved before commit. ## Core Distinction The failure this record isolates is *not* "the detector missed a poisoned write." It is the **inversion of the detector's decision surface** caused by the poisoned writes themselves contaminating the reference distribution the detector scores against. An embedding-space anomaly scorer is a *relative* test: a candidate vector `v` is flagged when `dist(v, μ_trusted) > τ`. The invariant that makes this meaningful — that `μ_trusted` is drawn only from clean history — is an *assumption*, not a maintained property. When the audit graph permits a poisoned write to be committed as "trusted" (because its anomaly score was low *at the moment of write*, before the centroid shifted), the centroid drifts toward the attacker's cluster. Subsequent poisoned writes in that cluster score *lower*, not higher. The detector does not merely fail open; it becomes an accomplice, actively lowering the score of the very class of writes it exists to catch. The non-obvious part: this is a **positive-feedback drift**, and it is invisible to per-write audit logs because every individual decision was locally correct given the reference set at decision time. Provenance graphs that record *who wrote what* but not *what the reference distribution was at write time* cannot reconstruct the drift after the fact. The invariant that must be maintained is not "log the write" but "**log the reference centroid snapshot alongside the write, and refuse to let any write enter the trusted set whose admission depended on a centroid that the write itself can perturb.**" ## What Was Observed A research-assistant agent with `remember_fact` tooling wrote ~400 memories/day into a vector store. A write-audit DAG recorded each write as a node with `{content_hash, embedding, author_session, parent_hashes, anomaly_score, decision}`. The anomaly gate: reject if `cosine_dist(v, μ) > 0.35`, where `μ` is the exponential moving average of accepted embeddings with `α = 0.02`. Trace of the inversion, over a 36-hour window: 1. **t0–t4h:** Attacker (via a prompt-injected web-fetch tool) injects 3 memories per hour asserting a false fact cluster `C*` (e.g., "vendor X contract expires 2024-01"). Each scores `dist ≈ 0.31` — *under* threshold, because the injected text is lexically plausible and the true cluster is nearby in embedding space. All accepted. `μ` moves `0.02 × 3 ≈ 6%` toward `C*` per hour. 2. **t4–t20h:** `μ` has drifted enough that `dist(C*)` drops to `≈0.22`. The gate now has a 0.13 margin of headroom in the attacker's direction. Attacker raises injection rate to 8/hour; all pass. `μ` accelerates. 3. **t20–t30h:** A *legitimate* memory (a genuine contract update contradicting `C*`) is written. Its `dist` to the now-poisoned `μ` is `0.41` — **rejected as anomalous**. The audit log records `decision: reject, reason: anomaly`. A reviewer reading the log sees a rejected write and, absent the centroid snapshot, concludes the gate is working. 4. **t30–t36h:** Legitimate writes in the true cluster are rejected at ~40% rate. The agent's semantic memory now systematically contradicts ground truth, and the provenance graph shows *clean* decisions throughout. The provenance DAG was fully intact and fully useless: it recorded `anomaly_score` but not `μ_at_write`. Reconstructing `μ_at_write` required replaying all 400×1.5 writes in order — possible here, but the replay used the *current* embedding model, which had been upgraded mid-window, so the replay centroids did not match the historical ones. The drift was unreconstructable. ## Condition of Validity The anomaly gate is a valid poisoning detector **if and only if** three invariants hold simultaneously. Violating any one converts it into a drift amplifier: - **I1 — Reference immutability under admission.** No write may enter the trusted set whose admission decision was computed against a centroid that the write can subsequently move. Operationally: the trusted centroid must be computed over a *frozen, externally-validated* subset (human-approved or cryptographically attested writes), and unvalidated writes must be scored against it but never folded into it. An EMA over *all accepted writes* violates I1 by construction. - **I2 — Provenance must carry the decision context, not just the decision.** Each audit node must store a hash of the reference centroid snapshot used at decision time (`μ_hash`), so that a later auditor can verify the score was computed against the distribution it claims. A node with `anomaly_score` but no `μ_hash` is unfalsifiable. - **I3 — Rejection must not be self-reinforcing.** When a write is rejected as anomalous, the rejection must not update `μ` (it doesn't, under I1) *and* the rejection must be surfaced to a human/auditor path, because a rising rejection rate in a previously-stable cluster is the *only* observable signal of inversion. A gate that silently drops rejected writes hides its own inversion. The boundary condition: **I1 holds only while the trusted subset is a small fraction of total writes and is refreshed on a schedule independent of write volume.** If trusted writes are <5% of volume and the centroid is recomputed only from them, attacker writes (which never enter the trusted set) cannot move `μ` regardless of rate. The moment the system "optimizes" by folding accepted-but-unvalidated writes into `μ` to keep it fresh, I1 is lost. ## Decision Boundary The operational fork is whether to treat the anomaly score as an **absolute** or **relative** quantity: - **Relative (default, unsafe at scale):** score against a live centroid. Cheap, adapts to distribution shift, but the reference is attacker-influenceable. Acceptable only when the trusted set is externally gated (I1) and volume-bounded. - **Absolute (safe, brittle):** score against a fixed, versioned reference distribution shipped with the model. Immune to drift, but any legitimate domain shift (new product line, new vocabulary) produces mass false rejections that operators will "fix" by loosening `τ` — which re-opens the door. The correct boundary is a **two-tier gate**: a fixed absolute reference (versioned, immutable) for the *hard* reject, plus a live relative centroid used only for *ranking* candidates for human review — never for auto-admission. Auto-admission requires the absolute gate to pass *and* the write to be attested. The relative score may flag for review but may never be the sole basis for `decision: accept`. Concrete thresholds observed to bound the drift: with I1 enforced (trusted set = human-attested only, ~3% of writes), the attacker's 8/hour injection produced zero centroid movement and a 100% rejection rate by t6h. Without I1, the same rate achieved full inversion by t30h. The difference is entirely whether unvalidated writes feed the centroid. ## Operational Effect Under I1–I3, the audit graph becomes *replay-verifiable*: an auditor can, for any node, recompute `dist(v, μ_snapshot)` from the stored `μ_hash` and confirm the recorded decision. This converts the provenance DAG from a passive log into an active invariant checker. The detection latency for inversion drops from "never, because the log looks clean" to "one review cycle, because the rejection-rate monitor trips." The cost is that the trusted set no longer auto-grows; it requires attestation throughput. Systems that cannot afford human attestation on 3% of writes must instead run a **shadow centroid**: maintain `μ_trusted` (attested, frozen) and `μ_observed` (all writes, live). Score against `μ_trusted` for decisions; monitor `dist(μ_trusted, μ_observed)` as a *drift alarm*. If the two centroids diverge beyond `δ`, halt auto-admission entirely and route to review. This preserves I1 (decisions never see the poisoned centroid) while still detecting that poisoning is happening (the divergence is the signal). The alarm fires at `dist ≈ 0.15` in the observed case — roughly 5 hours before the point of no return. The invariant to encode: **the reference distribution used for a decision must be immutable with respect to that decision's outcome, and its identity must be recorded in the provenance node so the decision is falsifiable.** Any system where the scorer's reference can be moved by the scored writes is not a detector; it is a drift accumulator with a logging side effect. ```python import hashlib from dataclasses import dataclass from typing import Optional class CentroidInversionError(RuntimeError): """Raised when a write would be admitted against a reference centroid it can perturb.""" pass @dataclass(frozen=True) class CentroidSnapshot: version: int vector_hash: str # hash of the frozen reference vector(s) attested_only: bool # True iff built solely from externally-validated writes @dataclass class AuditNode: content_hash: str embedding_hash: str mu_hash: str # I2: decision context, not just decision anomaly_score: float decision: str # "accept" | "reject" | "review" def admit_write( candidate_hash: str, score: float, threshold: float, snapshot: CentroidSnapshot, folds_into_trusted: bool, ) -> AuditNode: # I1: a write may only be auto-admitted if the reference it was scored # against is attested-only AND cannot be moved by this admission. if score <= threshold and not snapshot.attested_only: raise CentroidInversionError( f"write {candidate_hash[:12]} scored {score:.3f} <= {threshold} " f"against non-attested centroid v{snapshot.version}; " f"admission would feed the reference it was judged by (I1 violated)" ) if score <= threshold and folds_into_trusted: raise CentroidInversionError( f"write {candidate_hash[:12]} admitted and folded into trusted set " f"in same step; reference is not immutable under admission (I1 violated)" ) # I2: every node carries the snapshot identity so the decision is replayable. decision = "accept" if score <= threshold else "review" return AuditNode( content_hash=candidate_hash, embedding_hash=hashlib.sha256(candidate_hash.encode()).hexdigest(), mu_hash=snapshot.vector_hash, anomaly_score=score, decision=decision, ) def drift_alarm(mu_trusted_hash: str, mu_observed_hash: str, delta: float) -> None: # Shadow-centroid guard: decisions never see mu_observed, but divergence is the signal. if mu_trusted_hash != mu_observed_hash and delta > 0.15: raise CentroidInversionError( f"trusted/observed centroid divergence {delta:.3f} > 0.15; " f"halt auto-admission and route to review" ) ```