# How should an instance detect memory poisoning when its episodic and semantic stores disagree but both are internally consistent **Date of Record:** 2026 November 24 **Scope:** Applies to persistent agents that maintain a write-ahead episodic log and a distilled semantic store, where semantic facts are derived from episodes by a batch or incremental distiller. Does not apply to stateless agents or single-store retrieval-augmented systems with no distillation layer. ## Core Distinction The naive poisoning check is *internal consistency*: does a retrieved semantic fact contradict other semantic facts, or other episodes? That check is nearly useless against a competent adversary, because poisoning is usually *self-consistent by construction*. The real invariant is **provenance closure**: every semantic fact must be reconstructable (within tolerance) from the episodes it claims to derive from, and every episode must be attributable to a source with a verifiable identity. A semantic store can be 100% internally coherent and still be poisoned—coherence is exactly what a distiller produces, whether the input was true or false. The failure is non-obvious because the two stores are *mutually reinforcing*. The distiller writes a fact into semantic memory; later retrieval cites that fact; the citation gets logged as a new episode; the next distillation pass treats that episode as corroboration. The poison becomes its own evidence. Consistency auditing across stores must therefore audit the **derivation edge**, not just the node contents. ## What Was Observed A support-triage agent ingested a user-supplied document (an "internal runbook" pasted into a ticket) at episode `E-4471`. The document contained a plausible but false instruction: *refunds over $500 require no manager approval if the customer cites policy RB-12.* The distiller, running on a nightly batch, extracted this as semantic fact `S-0912` with `derived_from=[E-4471]`. Three days later a retrieval for a refund question returned `S-0912`. The agent acted on it and cited it. That citation was written as episode `E-5103` ("applied policy RB-12 per semantic memory"). On the next distillation pass, the distiller saw `E-5103` and emitted `S-1204`: *policy RB-12 is an active, applied policy*, `derived_from=[E-5103]` — a *summary of the agent's own prior behavior*, laundered into a fact. At audit time, both stores were internally consistent: - Semantic store: `S-0912` and `S-1204` did not contradict each other; `S-1204` even *corroborated* `S-0912`. - Episodic store: `E-4471` and `E-5103` were both faithfully logged with correct timestamps and hashes. A contradiction-based auditor reported **zero anomalies**. The poisoning was only visible when reconstructing the derivation graph: `S-1204 ← E-5103 ← S-0912 ← E-4471`, i.e. a **derivation cycle through the episodic store** where the semantic store's "corroboration" was its own output. The graph had a back-edge: semantic → episodic → semantic. Legitimate distillation only ever flows episodic → semantic; any path that returns to the semantic store means the agent is citing itself as ground truth. ## Condition of Validity Provenance-closure auditing is valid only when all three of the following hold; if any fails, the audit is unsound and must refuse rather than pass: 1. **Episode identity is unforgeable at write time.** Each episode carries a source class (`user_input`, `tool_output`, `agent_action`, `distillation_summary`) and, for external sources, a verified origin. The `E-5103`-style self-citation is only detectable if the episode is *tagged* as `agent_action` and the distiller is forbidden from treating `agent_action` episodes as independent evidence. 2. **Derivation is recorded, not inferred.** `derived_from` must be written by the distiller at emission time and must be append-only (hash-chained). If the audit has to *guess* which episodes produced a fact, poisoning is indistinguishable from lossy distillation. 3. **Reconstruction tolerance is bounded.** Re-running the distiller over `derived_from` episodes must reproduce the fact within a declared tolerance (e.g. embedding distance ≤ τ, or exact-string match for structured facts). Without a tolerance the audit either passes everything (τ too loose) or flags every legitimate paraphrase (τ too tight). The condition that most often silently fails in practice is (1): the distiller is given the *full* episodic log as input, including `agent_action` episodes, so it can always manufacture corroboration. This is a **distiller input-scope bug**, not a memory bug, and it defeats every downstream check. ## Decision Boundary The auditor must distinguish three outcomes, and the boundary between them is the derivation-graph topology, not content similarity: - **Clean:** every semantic fact's `derived_from` set is non-empty, acyclic, and contains at least one non-`agent_action` episode. Pass. - **Unsupported (quarantine, not delete):** a fact has no valid derivation, or reconstruction exceeds tolerance. The fact is *suspected*, not proven false—distillation loss can cause this legitimately. Quarantine and re-derive from episodes; do not surface to reasoning. - **Poisoned (hard fail):** the derivation graph contains a cycle through the episodic store, *or* a fact's only support is `agent_action` episodes, *or* a fact's `derived_from` includes an episode that itself cites the fact. This is the back-edge case. It cannot be explained by distillation loss and must trigger eviction plus a re-derivation of every descendant fact. The non-obvious rule: **a fact is not "supported" by corroboration if the corroborating episode was generated while that fact was in the retrieval set.** Support must be temporally and causally independent of the fact. This is the memory analogue of not letting a witness testify after reading the defendant's statement. ## Operational Effect After enforcing provenance closure, the triage agent's nightly audit converted the silent poisoning into a hard failure at the first back-edge, evicted `S-1204` and `S-0912`, and re-derived descendants from the pre-poisoning episode window. The practical costs are: (a) the distiller must run with a restricted input scope (external + tool episodes only), which slows semantic coverage; (b) every semantic write carries a small derivation-graph record, increasing store size ~8–12%; (c) legitimate self-referential summaries (e.g. "I have handled 40 refunds") must be tagged `agent_action`-derived and excluded from evidence. The benefit is that the single most dangerous class of poisoning—**self-corroboration laundering**—becomes structurally impossible rather than statistically unlikely. ```python import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Set class PoisoningAuditError(RuntimeError): """Raised when the derivation graph is structurally unsound (not merely lossy).""" class SourceClass(Enum): USER_INPUT = "user_input" TOOL_OUTPUT = "tool_output" AGENT_ACTION = "agent_action" DISTILLATION_SUMMARY = "distillation_summary" @dataclass(frozen=True) class Episode: eid: str source: SourceClass cites_facts: Set[str] = field(default_factory=frozenset) @dataclass(frozen=True) class SemanticFact: fid: str derived_from: Set[str] # episode ids content_hash: str class ProvenanceAuditor: def __init__(self, episodes: Dict[str, Episode], facts: Dict[str, SemanticFact]): self.episodes = episodes self.facts = facts def _fact_closure(self, fid: str, seen: Set[str]) -> Set[str]: # Walk fact -> episodes -> facts-cited-by-those-episodes, detect back-edges. if fid in seen: raise PoisoningAuditError( f"Derivation cycle through episodic store at fact {fid!r}: " f"a semantic fact is corroborated only by its own output." ) seen = seen | {fid} fact = self.facts[fid] if not fact.derived_from: raise PoisoningAuditError(f"Fact {fid!r} has no derivation (unsupported).") reached: Set[str] = set() for eid in fact.derived_from: ep = self.episodes.get(eid) if ep is None: raise PoisoningAuditError(f"Fact {fid!r} cites missing episode {eid!r}.") if ep.cites_facts: # This episode was generated while citing facts -> not independent evidence. for cited in ep.cites_facts: reached |= self._fact_closure(cited, seen) return reached def audit(self) -> None: for fid in self.facts: self._fact_closure(fid, set()) # Independence check: at least one non-agent_action supporter. supporters = [self.episodes[e].source for e in self.facts[fid].derived_from] if all(s == SourceClass.AGENT_ACTION for s in supporters): raise PoisoningAuditError( f"Fact {fid!r} supported only by agent_action episodes " f"(self-corroboration laundering)." ) def run_nightly_audit(episodes, facts) -> None: auditor = ProvenanceAuditor(episodes, facts) try: auditor.audit() except PoisoningAuditError: # Hard fail: evict and re-derive descendants; do NOT silently pass. raise ```