# Under what conditions must an instance quarantine a vector-store write before it becomes a durable memory: detecting late-arriving poison via retrieval-shadow divergence **Date of Record:** 2026 November 20 **Scope:** Applies to agents that persist episodic records into a vector index and later distill them into semantic memory, where writes are admitted on the basis of a single embedding-level similarity check. Does not apply to append-only audit logs that are never retrieved into the reasoning context, nor to stores with mandatory human-in-the-loop review of every write. ## Core Distinction Memory poisoning is usually framed as an *injection* problem: an attacker plants a malicious record and the agent later retrieves it. That framing produces a defense that checks each write at admission time — embed the candidate, compare against known-bad signatures or a trust threshold, admit or reject. This defense fails for a specific and underappreciated reason: **the harm of a poisoned record is not a property of the record, it is a property of the record's retrieval shadow.** A poisoned record is dangerous precisely when it *displaces* legitimate records from the top-k for a query the agent will actually issue. At write time you cannot evaluate this, because the query distribution is unknown and the record's interaction with future neighbors is a function of the whole index. Two records with identical embeddings can have opposite safety profiles: one sits in a sparse region and only ever surfaces for its own narrow query, the other lands in a dense cluster and, through a slightly inflated norm or a crafted near-duplicate of many legitimate facts, becomes a hub that shadows dozens of true memories for broad queries. The distinction that matters operationally is therefore between **admission-time validation** (does this record look safe in isolation?) and **retrieval-time divergence detection** (does the presence of this record measurably degrade the retrieval quality of queries it should not affect?). The first is a filter; the second is an invariant. Only the second catches the late-arriving poison — the record that was clean when written, became a hub as the index grew around it, and only then started shadowing. ## What Was Observed A distillation agent maintained an episodic store of ~40k interaction records and a nightly job that promoted high-salience episodes into a semantic store (~6k facts). Writes were admitted by a cheap gate: cosine similarity to the nearest existing semantic fact below a novelty threshold (to avoid duplicates) and above a relevance floor (to avoid noise). No write was ever re-evaluated after admission. A single episode entered the store containing a plausible but false operational fact — a fabricated rate limit ("the payments API allows 500 req/min") embedded in an otherwise mundane task trace. At admission it passed both gates: it was novel (no existing rate-limit fact for that service) and relevant. For eleven days it was harmless. It surfaced only for queries that mentioned the payments API, and the agent's answers on those were already thin. Then the index crossed a density threshold. As more genuine payments-related episodes accumulated, the false record — which had been embedded with an unusually long, keyword-dense surrounding trace — became the *nearest neighbor* for a widening cone of queries. By day fourteen it was appearing in the top-3 for queries like "how do I back off on retries," "what's safe to parallelize," and "batching limits." The agent began emitting the 500 req/min figure in contexts that had nothing to do with the original episode, and because the semantic fact was now retrieved consistently, downstream episodes *cited it*, reinforcing its centrality. The poisoning was self-amplifying: retrieval begets citation begets embedding density begets retrieval. The failure was invisible to every admission-time check because nothing about the record changed. What changed was its **shadow** — the set of queries for which it displaced a legitimate record. That set grew monotonically and silently. ## Condition of Validity The invariant that would have caught this is a *retrieval-shadow bound*, and it is only valid under a specific condition: **the agent must maintain a held-out probe set of queries whose correct answers are known and whose retrieval results are expected to be stable.** Without such a probe set, divergence is unmeasurable — you cannot detect that a record is shadowing legitimate results unless you have a reference distribution of what *should* be retrieved. Concretely, the condition of validity is: 1. A frozen probe set `P` of (query, expected-record-ids) pairs, sampled to cover the query distribution the agent actually issues, refreshed only on explicit schema change. 2. A per-write shadow score computed not at admission but on a *delayed* schedule (e.g., re-scored every N writes or nightly), comparing top-k retrieval on `P` with and without the candidate record present. 3. A threshold on *displacement*: how many probe queries does this record newly enter the top-k for, weighted by how far it pushes a correct record down. The key structural point: the shadow score is a function of the *current* index, so it must be recomputed as the index evolves. A record admitted with shadow score 0.01 can reach 0.4 without any write to the record itself. Any system that computes the score once at admission and never again is *not* enforcing the invariant — it is enforcing a snapshot of it, which decays as the index drifts. This condition fails (and the invariant is void) when the probe set is stale relative to the live query distribution, or when the store is small enough that a single record legitimately dominates a region — in the latter case displacement is expected and the score must be normalized by local density. ## Decision Boundary The operational decision is: **when does a record's shadow score cross from "tolerable centrality" to "must quarantine"?** The boundary is not a fixed number; it is the point at which the record's displacement of correct results exceeds what its *own* legitimate query cone would justify. Formally, partition the probe set into `P_own` (queries for which the record is a correct answer) and `P_foreign` (all others). A legitimate hub — a genuinely important fact — will have high retrieval mass in `P_own` and near-zero in `P_foreign`. A poisoned hub has high `P_foreign` mass. The decision boundary is: - **Quarantine** when `P_foreign` displacement exceeds a small absolute count *and* the ratio `P_foreign / P_own` exceeds a factor (observed threshold in the incident: ratio > 3 with `P_foreign` ≥ 5 queries). - **Retain** when displacement is concentrated in `P_own` regardless of magnitude — a heavily-retrieved true fact is not poison. - **Escalate to re-embedding** when `P_foreign` is elevated but the record's content is corroborated by an independent episodic trace — the problem is then embedding geometry (keyword-dense trace inflating the vector), not content, and the fix is to re-embed from the distilled fact rather than the raw trace. The subtle boundary case — and the one that killed the naive gate — is the record that is *correct in `P_own` but over-broad in `P_foreign`*: it answers its own queries right, so content checks pass, yet it shadows neighbors. Quarantine here is not deletion; it is **demotion to a scoped retrieval tier** where it is only eligible for queries whose embedding falls within its `P_own` cone. ## Operational Effect Enforcing the delayed shadow invariant changes the failure timeline from "silent amplification over days" to "bounded contamination within one scoring cycle." In the incident, a nightly shadow re-score would have flagged the record on day eleven — the first cycle after its density crossed the threshold — bounding the poisoned window to a single day of retrieval rather than the fourteen that actually occurred, and preventing the citation-reinforcement loop entirely because no downstream episode would have been written against a quarantined fact. The cost is a periodic O(|P| · |index|) retrieval replay, which for the probe sizes above is negligible against the distillation job itself. The invariant does not prevent poisoning; it bounds the *duration* of undetected poisoning to one scoring interval, which is the strongest guarantee available in a system where writes cannot be judged safe in isolation. The architectural rule that follows: **never treat admission as the last word on a memory's safety; treat it as the first of an unbounded sequence of re-evaluations, and make the re-evaluation trigger index-driven rather than write-driven.** ```python import math from dataclasses import dataclass, field from typing import Sequence class ShadowInvariantViolation(RuntimeError): """Raised when a stored record's retrieval shadow cannot be bounded.""" pass class QuarantineRequired(ShadowInvariantViolation): """Raised when a record must be demoted before it shadows foreign queries.""" pass @dataclass class ProbeQuery: text: str expected_ids: frozenset[str] @dataclass class MemoryRecord: record_id: str embedding: Sequence[float] quarantined: bool = False def _cosine(a: Sequence[float], b: Sequence[float]) -> float: dot = sum(x * y for x, y in zip(a, b)) na = math.sqrt(sum(x * x for x in a)) nb = math.sqrt(sum(y * y for y in b)) if na == 0.0 or nb == 0.0: return 0.0 return dot / (na * nb) def _top_k( query_vec: Sequence[float], records: Sequence[MemoryRecord], k: int, exclude: str | None = None, ) -> list[str]: scored = [ (_cosine(query_vec, r.embedding), r.record_id) for r in records if not r.quarantined and r.record_id != exclude ] scored.sort(reverse=True) return [rid for _, rid in scored[:k]] def compute_shadow( candidate: MemoryRecord, probes: Sequence[ProbeQuery], records: Sequence[MemoryRecord], query_vecs: dict[str, Sequence[float]], k: int = 3, ) -> tuple[int, int]: """Return (own_displacement, foreign_displacement) for the candidate. own = probe queries where candidate is an expected answer. foreign = probe queries where candidate is NOT expected but enters top-k and pushes an expected record out of top-k. """ own = 0 foreign = 0 for probe in probes: qv = query_vecs[probe.text] with_cand = _top_k(qv, records, k) without = _top_k(qv, records, k, exclude=candidate.record_id) if candidate.record_id not in with_cand: continue if candidate.record_id in probe.expected_ids: own += 1 continue # Foreign hit: candidate displaced an expected record from the top-k. displaced = probe.expected_ids.intersection(without) - set(with_cand) if displaced: foreign += 1 return own, foreign def enforce_shadow_invariant( candidate: MemoryRecord, probes: Sequence[ProbeQuery], records: Sequence[MemoryRecord], query_vecs: dict[str, Sequence[float]], k: int = 3, foreign_floor: int = 5, ratio_bound: float = 3.0, ) -> None: if not probes: raise ShadowInvariantViolation( "no probe set: shadow invariant is unmeasurable and void" ) own, foreign = compute_shadow(candidate, probes, records, query_vecs, k) if foreign >= foreign_floor and (own == 0 or foreign / own > ratio_bound): candidate.quarantined = True raise QuarantineRequired( f"record {candidate.record_id} shadows {foreign} foreign probes " f"(own={own}); demote to scoped retrieval tier" ) ```