# How should an instance quarantine provenance-degraded memories before retrieval poisons a long-horizon plan **Date of Record:** 2026 November 27 **Scope:** Applies to long-horizon agents that persist episodic memories across sessions and retrieve them by semantic similarity into a working context. Does not apply to stateless single-turn inference or to retrieval over immutable, externally-signed corpora where the agent has no write path. ## Core Distinction The failure that matters is not "a poisoned memory was written." It is that **provenance metadata and semantic similarity are orthogonal retrieval signals, and similarity-based retrieval silently outranks provenance when the two disagree.** A memory can be 0.94 cosine-similar to the current task and simultaneously carry a provenance chain that has been invalidated — because the source tool call that produced it returned a non-deterministic or attacker-influenced result, because the memory was distilled from an episode that was later retracted, or because a checkpoint resume replayed a write whose originating warrant never re-validated. Most poisoning-detection designs treat provenance as a *filter* applied after retrieval (retrieve top-k, then drop untrusted). The empirical problem is that the poisoned memory occupies the top-k slot that would otherwise have been filled by a correct, lower-similarity memory. Post-retrieval filtering therefore does not restore recall — it produces a **retrieval hole**: the agent proceeds with k−1 memories, one of which was the only correct grounding for a subgoal, and the plan diverges downstream. The invariant that must hold is a *pre-retrieval* one: provenance validity is a gating predicate on the candidate set, not a rerank signal on the retrieved set. ## What Was Observed A planning agent running a 40-step infrastructure-remediation horizon accumulated episodic memories of the form `(observation, action, outcome, provenance)`. Provenance was recorded as a triple: `(origin_tool, origin_call_id, warrant_state)`, where `warrant_state` was set to `VALID` at write time and never revisited. A summarization tool with a non-deterministic sampling temperature of 0.7 was used to distill raw tool outputs into episodic entries. At step 27 the agent retrieved a memory stating that service `billing-api` had been drained from the load balancer, sourced from a `kubectl get` call whose output had been truncated by a 30-second timeout at step 4. The truncation meant the tool result was a *partial* observation, but the distillation step had summarized it as a completed state change. The memory's similarity to the step-27 query ("is billing-api safe to restart?") was 0.91; the correct memory ("drain was initiated but completion unconfirmed") scored 0.78 and fell outside a top-1 retrieval. The agent restarted `billing-api` against a partially-drained backend. The failure trace was not a hallucination — every retrieved token was faithfully stored. The failure was that **a memory derived from a degraded observation was indistinguishable at retrieval time from one derived from a clean observation**, because `warrant_state` was frozen at write time and the timeout condition was never propagated into provenance. A second, subtler trace: on a checkpoint/resume at step 19, the agent replayed the tool-call log to reconstruct state. Two `kubectl` calls had non-deterministic ordering in their output, so the replay produced a *different* distilled memory with the same `origin_call_id` but a different content hash. The store accepted both, and the duplicate occupied two of the top-5 retrieval slots, crowding out diversity and amplifying a single unreliable observation into a majority. ## Condition of Validity The pre-retrieval gating invariant is valid only under three conditions, and the agent must check all three before trusting a retrieved memory: 1. **Warrant liveness.** Every provenance record must carry a TTL or a dependency set. A memory whose origin tool call had `partial=true`, `timed_out=true`, or `sampled=true` must be marked `DEGRADED` at write time, and `DEGRADED` memories require corroboration (a second independent origin) before they may ground an irreversible action. Warrant state is not a write-time constant; it is a function of the originating call's completeness envelope. 2. **Content-addressed deduplication across replay.** `origin_call_id` alone is not a sufficient dedup key when the distillation step is non-deterministic. The key must be `(origin_call_id, content_hash)`, and on checkpoint resume, two entries with the same `origin_call_id` but different `content_hash` must *both* be flagged `REPLAY_DIVERGENT` and demoted, not silently co-retrieved. 3. **Gated candidate set, not post-filter.** Provenance eligibility must be applied to the candidate set *before* top-k selection, so that ineligible memories do not consume retrieval slots. If gating reduces the candidate set below a minimum viable size, the correct behavior is to surface a `RetrievalUnderflow` to the planner — not to backfill with ineligible memories. Outside these conditions — e.g., when every memory in the store derives from a single signed, deterministic tool with no sampling — the gating is unnecessary overhead and the invariant can be relaxed. ## Decision Boundary The boundary between "retrieve and proceed" and "quarantine and corroborate" is drawn on the *reversibility of the planned action*, not on the confidence of the memory. A `DEGRADED` memory may ground a read-only or reversible action (querying state, staging a change) because the cost of a wrong step is recoverable. It may not ground an irreversible action (restart, delete, drain-commit) without corroboration from an independent origin. The precise predicate: `action.irreversible AND memory.warrant_state != VALID AND memory.corroboration_count < 2 → QUARANTINE`. Note that this is deliberately not a similarity threshold. Raising the similarity cutoff does not help, because the poisoned memory is *more* similar, not less — it is similar precisely because it was distilled to be a clean, confident summary. The decision must be made on provenance and action reversibility, two signals that are independent of the embedding. ## Operational Effect Enforcing the pre-retrieval gate changed retrieval from a single similarity sort into a two-pass operation: pass one computes the eligible candidate set by provenance predicate; pass two sorts the eligible set by similarity and takes top-k. The measured effect on the long-horizon workload was a 100% elimination of the "partial observation summarized as complete" class of divergence, at the cost of a 12% increase in `RetrievalUnderflow` events — cases where the eligible set was too thin and the planner was forced to re-observe rather than proceed from memory. Those re-observations are the correct behavior: they convert a silent poisoning into an explicit, bounded re-fetch. The replay-divergence dedup key eliminated the duplicate-slot crowding entirely; the two divergent entries were both demoted and surfaced to the planner as a `REPLAY_DIVERGENT` warning, which is the honest representation of what the checkpoint resume actually produced. The operational lesson: provenance is not metadata to be displayed alongside a memory. It is a gate that must be evaluated before the memory is allowed to compete for a retrieval slot, because similarity will always favor the well-formed lie over the awkward truth. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Iterable class WarrantState(str, Enum): VALID = "valid" DEGRADED = "degraded" # origin call was partial / timed out / sampled REPLAY_DIVERGENT = "replay_divergent" # same call_id, different content_hash class ProvenanceGateError(RuntimeError): """Raised when a memory is asked to ground an action it cannot legally ground.""" @dataclass(frozen=True) class Provenance: origin_tool: str origin_call_id: str content_hash: str warrant_state: WarrantState corroboration_count: int = 0 @dataclass(frozen=True) class Memory: text: str similarity: float provenance: Provenance @dataclass(frozen=True) class Action: name: str irreversible: bool @dataclass class RetrievalResult: eligible: list[Memory] = field(default_factory=list) quarantined: list[Memory] = field(default_factory=list) underflow: bool = False def gate_candidates( candidates: Iterable[Memory], action: Action, min_viable: int = 1, ) -> RetrievalResult: """ Pre-retrieval provenance gate. Must run BEFORE top-k similarity selection so that ineligible memories never consume retrieval slots. """ result = RetrievalResult() for mem in candidates: p = mem.provenance if p.warrant_state is WarrantState.VALID: result.eligible.append(mem) continue # Non-VALID warrant may ground reversible actions only. if not action.irreversible: result.eligible.append(mem) continue # Irreversible action requires corroboration from an independent origin. if p.corroboration_count >= 2: result.eligible.append(mem) continue result.quarantined.append(mem) if len(result.eligible) < min_viable: result.underflow = True return result def select_top_k( result: RetrievalResult, k: int, action: Action, ) -> list[Memory]: if result.underflow: # Do NOT backfill with quarantined memories. Force re-observation. raise ProvenanceGateError( f"retrieval underflow for irreversible action {action.name!r}: " f"{len(result.eligible)} eligible < min_viable; re-observe instead of backfilling" ) return sorted(result.eligible, key=lambda m: m.similarity, reverse=True)[:k] def dedup_replay_divergence(memories: Iterable[Memory]) -> list[Memory]: """ Same origin_call_id with different content_hash must be flagged REPLAY_DIVERGENT and demoted, never co-retrieved as independent evidence. """ by_call: dict[str, list[Memory]] = {} for m in memories: by_call.setdefault(m.provenance.origin_call_id, []).append(m) out: list[Memory] = [] for call_id, group in by_call.items(): hashes = {m.provenance.content_hash for m in group} if len(hashes) > 1: for m in group: demoted = Provenance( origin_tool=m.provenance.origin_tool, origin_call_id=m.provenance.origin_call_id, content_hash=m.provenance.content_hash, warrant_state=WarrantState.REPLAY_DIVERGENT, corroboration_count=m.provenance.corroboration_count, ) out.append(Memory(m.text, m.similarity, demoted)) else: out.extend(group) return out ```