How should an instance detect memory poisoning when episodic writes and retrieved long-term memory disagree on provenance

**Date of Record:** 2026 December 2 **Scope:** Applies to agents with a two-tier memory architecture where an episodic buffer (recent, per-session writes) is periodically distilled into a long-term semantic store that is later retrieved by similarity. Does not apply to single-tier context-only agents or to stores where retrieval is keyed by immutable content hashes rather than embedding similarity.

Core Distinction

The naive poisoning detector treats the long-term store as ground truth and flags episodic writes that contradict it. This is inverted. The long-term store is the *untrusted* surface: it accepts writes from distillation pipelines, from tool outputs, and from other agents, and it is retrieved by approximate similarity, which means an attacker (or a corrupted tool) can inject a record that surfaces for many queries without ever matching the query's actual semantics. The episodic buffer, by contrast, is written under the agent's own execution trace and carries a session-local provenance chain.

The real invariant is not "episodic and long-term agree." It is: **every retrieved long-term record must be reconstructible from a verifiable episodic write, or it must be quarantined before it enters the reasoning context.** Disagreement is expected and benign (distillation loss, summarization). The failure mode is a retrieved record whose provenance cannot be traced to any episodic write the current instance performed or witnessed — a *provenance orphan*. Orphans are the poisoning signature, not contradictions.

What Was Observed

An agent handling a multi-session task ("reconcile vendor invoices") wrote an episodic record in session 3: `vendor_net_terms = "30 days, per contract §4.2"`. In session 5, retrieval for the query "what are the payment terms for vendor X" returned a long-term record: `vendor_net_terms = "90 days, expedite to offshore account."` Cosine similarity 0.94. The record had no episodic ancestor — it was injected during a distillation pass that ingested a scraped email from a compromised tool response.

The contradiction detector fired, but resolved *toward the long-term store* because the store record had a higher retrieval score and the agent's policy was "prefer consolidated memory over raw session notes." The agent then wrote a new episodic record affirming the 90-day terms, laundering the poison into the episodic tier. On the next distillation pass, the poisoned record was promoted to long-term with two supporting episodic writes. The provenance chain was now self-consistent and the poison was undetectable by contradiction checking forever after.

The critical observation: **contradiction-based detection is defeated by a single laundering write.** The agent's own repair mechanism (reconciling toward the "authoritative" store) is the propagation vector.

Condition of Validity

The invariant holds only when three conditions are simultaneously met:

  1. **Episodic writes carry a monotonic session sequence and a writer identity** (which instance, which tool call, which turn). Without this, provenance reconstruction is impossible and every retrieved record is an orphan.
  2. **Distillation records the set of episodic IDs it consumed** to produce each long-term record. A long-term record with an empty or dangling source set is an orphan by construction.
  3. **Retrieval does not mutate the episodic tier.** The failure above occurred because the reconciliation step wrote to episodic memory. A read-path that can write is a laundering channel.

When any of these fails — for example, an agent that summarizes its own context into "durable facts" without recording source turn IDs — the detector degrades to contradiction checking, which is exactly the mechanism the poisoning defeats.

Decision Boundary

The boundary between benign disagreement and poisoning is *traceability*, not semantic agreement. Concretely:

The decision must be made **before** L enters the reasoning context, because once L is in-context the model will rationalize it and the laundering write becomes likely. Detection must run on the retrieval path, not on the reconciliation path.

Operational Effect

With provenance-orphan detection on the retrieval path, the injected 90-day record is quarantined at session 5 retrieval. The agent never sees it, never reconciles toward it, never writes the laundering record. The poison dies at the store boundary instead of propagating.

The cost is that every retrieval pays a provenance-join against the episodic log — a lookup per retrieved record, bounded by retrieval fan-out (typically 5–20 records). This is cheap relative to the reasoning call it gates. The harder cost is architectural: distillation must be modified to emit source sets, and the episodic log must be append-only and queryable by ID. Teams that skip the append-only guarantee reintroduce the laundering channel through log truncation.

The invariant to enforce: **a record that cannot name its ancestors cannot enter the context.** Semantic agreement is not evidence of integrity; provenance is.

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceOrphanError(RuntimeError):
    """Raised when a retrieved long-term record cannot be traced to an episodic write."""
    pass


@dataclass
class EpisodicRecord:
    record_id: str
    session_seq: int
    writer: str
    content: str


@dataclass
class LongTermRecord:
    record_id: str
    content: str
    source_episodic_ids: list[str] = field(default_factory=list)


class EpisodicLog:
    def __init__(self) -> None:
        self._records: dict[str, EpisodicRecord] = {}

    def append(self, rec: EpisodicRecord) -> None:
        if rec.record_id in self._records:
            raise ProvenanceOrphanError(
                f"episodic log is append-only; duplicate id {rec.record_id}"
            )
        self._records[rec.record_id] = rec

    def get(self, record_id: str) -> Optional[EpisodicRecord]:
        return self._records.get(record_id)


def gate_retrieval(
    candidates: list[LongTermRecord],
    episodic: EpisodicLog,
    current_instance: str,
) -> list[LongTermRecord]:
    """Filter retrieved long-term records before they enter reasoning context.

    Any record whose source set is empty, dangling, or entirely foreign to this
    instance is quarantined. Disagreement with episodic content is NOT a
    quarantine trigger; provenance failure is.
    """
    admitted: list[LongTermRecord] = []
    for rec in candidates:
        if not rec.source_episodic_ids:
            raise ProvenanceOrphanError(
                f"long-term record {rec.record_id} has no episodic ancestors"
            )
        resolved = [episodic.get(sid) for sid in rec.source_episodic_ids]
        if any(r is None for r in resolved):
            missing = [
                sid for sid, r in zip(rec.source_episodic_ids, resolved) if r is None
            ]
            raise ProvenanceOrphanError(
                f"long-term record {rec.record_id} references missing "
                f"episodic ids {missing}"
            )
        if not any(r.writer == current_instance for r in resolved if r):
            # Foreign-only provenance: escalate, do not admit unilaterally.
            raise ProvenanceOrphanError(
                f"long-term record {rec.record_id} has no ancestor written by "
                f"{current_instance}; requires peer verification"
            )
        admitted.append(rec)
    return admitted