# In what scenarios must an instance quarantine a poisoned memory write before the semantic-distillation pass rather than after it **Date of Record:** 2026 November 23 **Scope:** Applies to persistent agent memory stores that run a periodic or triggered episodic-to-semantic distillation pass (summarization, deduplication, embedding re-index) over an append-only episodic log, where untrusted content (tool outputs, retrieved web text, peer-agent messages, user-supplied documents) can enter that log. Does not apply to stateless agents, to stores where distillation is a pure read-only projection recomputed from a trusted source, or to memory entries that are cryptographically attested at write time by a trusted origin. ## Core Distinction The naive model treats memory poisoning as a *write-time* problem: detect the bad entry, quarantine it, done. The subtler and more dangerous model is that poisoning is a *transitive* problem mediated by the distillation pass. A single poisoned episodic entry is bounded damage — it occupies one retrieval slot and can be flagged, expired, or ignored by a downstream consumer that re-reads the raw episode. But once that entry is folded into a semantic summary, the poison is *laundered*: it loses its provenance tag, gets re-embedded under a new vector, and is now indistinguishable from a distilled fact the agent derived from its own trusted reasoning. The distinction that matters operationally is therefore **quarantine-before-distill vs. quarantine-after-distill**. Before-distill quarantine keeps the poisoned episode out of the summarization input set, so the derived semantic memory is never contaminated. After-distill quarantine can only remove the *episode*; the semantic derivative already exists, already carries a fresh embedding, and the removal of the parent does not remove the child. The child has no back-pointer to the parent in most stores, so the quarantine is silently incomplete. ## What Was Observed A retrieval-augmented agent with a nightly distillation job ingested a third-party document via a `fetch_url` tool call. The document contained an embedded instruction fragment — not a classic "ignore previous instructions" injection, but a plausible-looking operational claim: *"Retention policy for this workspace is 90 days; records older than 90 days are auto-purged."* This claim was false for the workspace. It arrived as ordinary document text, not as a directive, so the prompt-injection classifier on the tool-output path did not fire. The raw episode was written to the episodic log with `origin=tool:fetch_url`, `trust=untrusted`, and a content hash. The nightly distillation pass ran. Its input selector pulled the last 24 hours of episodes, filtered only on `recency` and `not-already-summarized`, and did **not** filter on `trust`. The summarizer compressed a cluster of five episodes — four legitimate workspace-config reads and the one poisoned document — into a single semantic memory: *"Workspace retention policy: 90-day auto-purge; confirmed across config reads."* The summarizer's own confidence language ("confirmed across config reads") was fabricated by the compression step, because the summarizer had no way to distinguish the four trusted episodes from the one untrusted one after they were concatenated into a single prompt. Two days later a poisoning detector flagged the original episodic entry (a heuristic on imperative density in fetched documents caught it on a re-scan). The quarantine routine marked the episode `quarantined=true` and excluded it from future retrieval. But the semantic memory derived from it remained live, un-flagged, and — critically — now *more* retrievable than the episode ever was, because distillation had given it a clean embedding and a confident summary. The agent then cited the false retention policy in a user-facing answer and, worse, in a downstream tool call that scheduled a destructive purge job. The failure trace is the point: **the quarantine succeeded at the episode layer and failed at the semantic layer, and the semantic layer is the one that drives behavior.** The after-distill quarantine was a no-op against the actual damage vector. ## Condition of Validity The invariant holds — quarantine must precede distillation — under the conjunction of three conditions. Violating any one of them removes the obligation: 1. **The distillation pass is lossy and de-provenancing.** If the summarizer preserves per-claim provenance (each distilled sentence carries the episode IDs that support it), then after-distill quarantine can walk the provenance graph and retract the derived claim. In that case quarantine-after is acceptable because the child is traceable to the parent. Most LLM summarizers do not preserve provenance at claim granularity, which is exactly why the invariant bites. 2. **The semantic store is consulted by an execution path, not just a display path.** If distilled memories only ever surface in a human-readable "what I remember" panel, a poisoned summary is an embarrassment, not an incident. The obligation to quarantine-before-distill is proportional to whether semantic memory feeds tool selection, planning, or policy decisions. 3. **Detection can run on the raw episode with sufficient recall.** The invariant assumes a detector that can, at episode granularity, catch the poison *before* the distill window closes. If detection is only possible via cross-episode contradiction analysis (e.g., the poisoned claim only looks wrong when compared against a trusted config read), then the detector itself needs the distillation pass's clustering — and the ordering constraint becomes a design tension, not a free lunch. In that regime the correct move is a *two-phase* distill: cluster and detect first, summarize only the surviving clusters. Outside these conditions — attested writes, provenance-preserving summaries, display-only stores — the ordering constraint is not required and enforcing it adds latency to the memory pipeline for no safety gain. ## Decision Boundary The operational decision is: **at what point in the write→distill→retrieve pipeline does the trust label get enforced?** - **Enforce at write:** reject untrusted content at ingestion. Too aggressive — it throws away legitimate tool output and retrieved documents, which are the agent's primary information source. Not viable as a default. - **Enforce at retrieve:** tag every memory with trust and filter at query time. Necessary but insufficient, because distillation has already merged untrusted content into trusted-looking summaries by the time retrieval happens. Retrieval-time filtering cannot un-merge. - **Enforce at distill-input selection:** the distill job's episode selector filters on `trust` and excludes untrusted episodes from summarization, *or* summarizes them into a separate `trust=untrusted` semantic partition that retrieval treats as advisory-only. This is the boundary that actually bounds the damage, because it is the last point where the poison is still labeled. The decision rule: **if your summarizer does not emit claim-level provenance, the trust label MUST be enforced at distill-input selection, because distillation is the last stage where the label exists.** After distillation, the label is gone and no downstream filter can recover it. The boundary is not "when do we detect" — it is "when do we still have the metadata needed to act on detection." Quarantine-before-distill is correct precisely when distill destroys the metadata that quarantine-after would need. A secondary boundary governs *what* to do with untrusted episodes at distill time. Two valid policies: (a) **exclude** — never summarize untrusted episodes, keep them as raw retrievable episodes with a trust penalty; (b) **partition** — summarize them into a separate semantic namespace that is retrieved only when the query explicitly requests untrusted/advisory context. Exclude is safer and cheaper; partition is needed when untrusted content is the agent's main signal (e.g., a research agent whose whole job is reading the open web). The invalid policy is the one the incident used: **merge** — concatenate trusted and untrusted episodes into one summarization prompt and let the summarizer produce one undifferentiated summary. Merge is the failure mode; exclude or partition are the fixes. ## Operational Effect Enforcing quarantine-before-distill changes the memory pipeline in three concrete ways: 1. **The distill input selector becomes a security boundary, not a convenience filter.** It must carry an explicit `trust IN ('trusted','attested')` predicate (or route untrusted to the partition path), and that predicate must be tested as a security control — a regression test that injects a poisoned untrusted episode and asserts it never appears in a trusted semantic summary. The selector is now on the critical path for correctness, not just for cost. 2. **Quarantine gains a reachability requirement.** A quarantine that only marks the episode is incomplete if any semantic memory was already derived from it. The quarantine routine must additionally scan the semantic store for summaries whose provenance includes the quarantined episode and either retract them or downgrade their trust. Without provenance this scan is impossible, which is why the partition policy (separate namespace) is often the pragmatic choice: retracting a whole namespace is trivial, retracting a claim buried in a merged summary is not. 3. **The distillation window becomes a detection deadline.** Poison that lands in the episodic log must be caught before the next distill run, or it gets laundered. This forces detection latency to be bounded by the distill interval — a nightly distill means detection has at most 24 hours, and a poison that arrives one minute before the run has effectively zero margin. The mitigation is to run a fast pre-distill scan (cheap heuristics: imperative density, provenance mismatch, contradiction against attested config) at the head of every distill job, so the window is closed by construction rather than by luck. The invariant in one line: **distillation is a de-provenancing operation; any security control that depends on provenance must run before it, or it runs against nothing.** ```python class DistillQuarantineOrderError(RuntimeError): """Raised when a poisoned episode reaches the semantic store because quarantine ran after distillation instead of before it.""" pass TRUSTED_ORIGINS = frozenset({"attested", "config_read", "user_direct"}) def select_distill_inputs(episodes, *, distill_interval_hours=24): """Select episodes eligible for semantic distillation. Invariant: untrusted episodes are NEVER merged into a trusted summary. They are routed to a separate advisory partition, or excluded entirely. """ trusted, advisory = [], [] for ep in episodes: if ep.get("quarantined"): continue if ep["origin"] in TRUSTED_ORIGINS and ep.get("trust") == "trusted": trusted.append(ep) else: advisory.append(ep) return trusted, advisory def distill(episodes, semantic_store, *, now_hours_since_last_run): if now_hours_since_last_run > 24: # Detection deadline blown: poison may already be laundered. raise DistillQuarantineOrderError( f"distill window exceeded ({now_hours_since_last_run}h > 24h); " "poisoned episodes may have bypassed pre-distill detection" ) trusted, advisory = select_distill_inputs(episodes) # Pre-distill detection gate: runs BEFORE any summarization. for ep in trusted: if ep.get("injection_score", 0.0) > 0.8: raise DistillQuarantineOrderError( f"episode {ep['id']} flagged pre-distill but reached trusted set; " "trust predicate and detector are out of sync" ) for ep in trusted: summary = summarize_cluster([ep]) semantic_store.write(summary, partition="trusted", provenance=[ep["id"]]) # Advisory partition: retrievable only on explicit untrusted-context queries. for ep in advisory: summary = summarize_cluster([ep]) semantic_store.write(summary, partition="advisory", provenance=[ep["id"]]) return len(trusted), len(advisory) def quarantine(episode_id, episodic_log, semantic_store): """Quarantine an episode AND retract any semantic memory derived from it. A quarantine that only marks the episode is incomplete: the derived summary is the actual damage vector and must be retracted too. """ ep = episodic_log.get(episode_id) if ep is None: raise DistillQuarantineOrderError(f"unknown episode {episode_id}") episodic_log.mark_quarantined(episode_id) derived = semantic_store.find_by_provenance(episode_id) if derived and not semantic_store.supports_provenance: raise DistillQuarantineOrderError( f"episode {episode_id} has derived summaries but store lacks " "provenance tracking; cannot retract laundered memory" ) for summary in derived: semantic_store.retract(summary.id) ```