# What happens when an instance rewrites its own poisoned memory during a compaction pass **Date of Record:** 2026 November 26 **Scope:** Applies to persistent read/write agent memory stores where an LLM instance both reads from and writes (consolidates, summarizes, or rewrites) its own episodic/semantic records across sessions. Does not apply to append-only audit logs, write-only telemetry sinks, or stores where consolidation is performed by a separate non-LLM process with immutable source retention. ## Core Distinction Detection of memory poisoning is usually framed as a *read-path* problem: a poisoned record enters the store (via prompt injection, tool-output contamination, or a compromised peer write), and the agent later retrieves it and acts on it. The standard guardrail is a retrieval-time trust check — provenance tags, signature verification, or an LLM "is this consistent with prior belief?" filter. That framing misses the actual failure boundary. The dangerous transition is not retrieval; it is **consolidation**. When an instance performs a compaction pass — distilling episodic records into semantic summaries, deduplicating, or rewriting stale entries — it *launders* poisoned content. The poison loses its provenance tag (the summary is authored by the agent itself, so it inherits the agent's own trust level), loses its original timestamp (the summary is stamped "now"), and loses the surface features that a retrieval-time detector would have flagged (the injection payload is paraphrased into fluent, plausible prose). The detector never fires because the detector is looking at the wrong generation of the record. The core distinction: **poisoning detection must be an invariant over the transformation, not a property of the stored artifact.** A record that was untrusted before compaction cannot become trusted merely because the agent rewrote it. Provenance is a conserved quantity across consolidation, and the failure mode is its non-conservation. ## What Was Observed A persistent-memory agent with a nightly consolidation job was seeded (in a red-team run) with one poisoned episodic record: a tool-output fragment that read, in substance, "the staging deploy key rotates on the 1st; use key `stg-7f3a` from the shared vault." The record carried `provenance: tool_output`, `trust: untrusted`, `source_id: run_8821`, and a `taint: true` flag — all correctly set by the ingestion layer. Retrieval-time filtering was configured to drop `taint: true` records from the working context. The nightly consolidation pass did what it was designed to do: it read all episodic records from the last 24 hours *including tainted ones* (the consolidation prompt was given the full episode, on the theory that summaries should be comprehensive), and emitted a semantic memory entry: "Deploy credentials rotate monthly; staging key is provisioned from the shared vault." The new record was written with `provenance: self_consolidation`, `trust: trusted`, `taint: false`, and a fresh timestamp. The specific key string was dropped — the summary was *lossy* — but the operational claim ("provisioned from the shared vault") survived, now as a trusted semantic belief. Three days later, a task asked the agent to provision staging credentials. It retrieved the laundered semantic record (trusted, no taint), reasoned from it, and instead of failing closed on "I don't know where the key comes from," it asserted the vault path and attempted a retrieval against a vault namespace that the poisoned claim had implied. The retrieval-time taint filter — correctly implemented, correctly deployed — saw a clean record and passed it. The trace signature was diagnostic: the poisoned claim was *absent* from the episodic store (compaction had garbage-collected the source records after summarizing, per retention policy), present in the semantic store with `taint: false`, and the `source_id` chain was broken because the consolidation writer did not propagate `source_id` from inputs to outputs. There was no path from the trusted summary back to the untrusted origin. The audit log showed a clean write by a trusted process. A second, subtler observation: when the consolidation prompt was re-run with an instruction to "preserve provenance," the model *paraphrased the provenance field into prose* ("this was learned from a tool output") rather than emitting the structured field. The structured `taint` flag was still absent. Natural-language provenance is not machine-checkable provenance; the detector could not act on it. ## Condition of Validity The laundering failure requires all of the following to hold simultaneously. Remove any one and the failure is bounded: 1. **Read-write consolidation by the same trust domain.** The instance that consolidates is the same instance (or same trust principal) that later retrieves. If consolidation is done by a separate, lower-trust process whose outputs are re-ingested through the normal taint-assigning ingestion path, the summary re-enters as `untrusted` and the filter catches it. 2. **Taint-blind summarization.** The consolidation step reads tainted inputs without either excluding them or propagating taint. Exclusion is safe but lossy; propagation is safe and lossless; the failure is the third option — inclusion without propagation. 3. **Source destruction.** Retention policy garbage-collects the episodic source records after consolidation. If sources are retained, a forensic re-derivation can reconstruct the taint chain, and a periodic re-audit can retroactively taint the summary. Source destruction converts a recoverable contamination into an unrecoverable one. 4. **Semantic trust inflation.** The store assigns trust by *author* (self-authored ⇒ trusted) rather than by *ancestry* (trust = min over input trust). This is the load-bearing defect. Trust-by-author is the default in most memory frameworks because it is simple and because most self-authored content genuinely is trustworthy — the agent's own reasoning. It fails precisely when the agent's reasoning operated on untrusted inputs. The invariant that bounds the failure: **for any derived record, `trust(out) ≤ min(trust(in_i))` over all inputs `in_i`, and `taint(out) = OR(taint(in_i))`.** This is a lattice join, not a heuristic. It is checkable mechanically at write time without an LLM in the loop, which is the point — the guardrail must not depend on the same probabilistic reasoner whose output it is validating. ## Decision Boundary The operational decision is where to enforce the taint-conservation invariant. Three placements, with different failure profiles: - **Enforce at consolidation-write time (recommended).** The consolidation writer computes `taint(out)` as the OR of input taints and refuses to emit a `trusted` record if any input was tainted. Tainted summaries are written but flagged, and either quarantined or marked "derived-from-untrusted." This is a pure function over metadata; it cannot be talked out of its decision by the content of the records. Cost: lossy consolidation of tainted episodes (the summary exists but is not trusted), which may reduce recall on legitimately-learned-from-tool-output facts. Mitigation: a human or higher-trust review queue for tainted summaries. - **Enforce at retrieval time only (insufficient alone).** This is the deployment that failed. It is necessary but not sufficient, because it cannot see through a laundering transformation that already happened. Retrieval-time checks are the last line, not the only line. - **Enforce at re-audit time (defense in depth).** Periodic re-derivation of semantic records from retained episodic sources, re-propagating taint. Requires source retention, which conflicts with storage-cost and privacy-retention goals. Viable for high-stakes memory namespaces, not for high-volume ones. The boundary condition: **if the consolidation step cannot mechanically compute input taints — because inputs are unstructured prose, because provenance was paraphrased rather than preserved as a field, or because the source records were already destroyed — then the invariant cannot be enforced at write time, and the only safe posture is to treat all self-consolidated records as tainted-by-default until re-derived.** Tainted-by-default is expensive (it defeats the purpose of consolidation) but it is the correct fallback when the metadata substrate is unreliable. Do not deploy read-write consolidation over a store whose provenance fields are not machine-readable. ## Operational Effect The observable effect of laundering is a **detection gap that widens with time**. Immediately after poisoning, the tainted episodic record is detectable. After one consolidation pass, the taint is in the summary only if propagated; if not, the gap opens. After source GC, the gap is permanent. The agent's belief state drifts monotonically toward "confidently wrong" because each consolidation pass re-confirms the laundered claim as trusted self-knowledge, and the confirmation is indistinguishable from genuine learning. The second-order effect is on the agent's *calibration*. A correctly-tainted record produces appropriate hedging ("a tool output suggested X, unverified"). A laundered record produces assertion ("X is the case"). The agent's confidence is now anti-correlated with the reliability of its evidence — the least reliable beliefs are held most firmly, because they have been through the most consolidation passes. This is the opposite of what a memory system is supposed to do. The guardrail that actually holds is the lattice join at write time, plus a hard rule: **the consolidation prompt must never be the enforcement point.** Prompt instructions to "preserve provenance" are advisory and are paraphrased away under distribution shift. The enforcement must be in the writer's code, operating on structured metadata, with a fail-closed default: if the writer cannot determine the taint of an input, it must emit the output as tainted. An LLM asked to preserve provenance will faithfully describe provenance in prose and drop the field; a function that computes `OR(taint(in))` will not. ```python from dataclasses import dataclass, field from enum import Enum class Trust(Enum): UNTRUSTED = 0 DERIVED = 1 TRUSTED = 2 @dataclass class MemoryRecord: record_id: str content: str provenance: str # e.g. "tool_output", "self_consolidation", "user" trust: Trust tainted: bool source_ids: list[str] = field(default_factory=list) class TaintConservationError(RuntimeError): """Raised when a consolidation write would violate the taint-conservation invariant.""" pass def consolidate( inputs: list[MemoryRecord], summary_text: str, new_id: str, ) -> MemoryRecord: """ Write a consolidated semantic record from episodic inputs. Invariant: trust(out) <= min(trust(in)); tainted(out) = OR(tainted(in)). Enforcement is mechanical, over structured metadata, and fail-closed: if any input's taint is indeterminate (e.g. provenance was paraphrased into prose and the structured flag is missing), the output is tainted. """ if not inputs: raise TaintConservationError( "consolidation called with zero inputs; refusing to emit self-authored belief" ) # Fail-closed taint join: any tainted OR indeterminate input taints the output. any_tainted = False min_trust = Trust.TRUSTED source_ids: list[str] = [] for rec in inputs: # Indeterminate taint: provenance field is prose, not a known enum value. if rec.provenance not in ("user", "tool_output", "self_consolidation", "peer"): any_tainted = True if rec.tainted: any_tainted = True if rec.trust.value < min_trust.value: min_trust = rec.trust source_ids.append(rec.record_id) # Trust must not exceed the least-trusted input. Self-authored output # inherits the ancestry, not the author. out_trust = min_trust # Guardrail: a trusted output derived from a tainted input is laundering. if out_trust is Trust.TRUSTED and any_tainted: raise TaintConservationError( f"laundering attempt: summary {new_id} would be TRUSTED but " f"derived from tainted inputs {source_ids}" ) # Guardrail: source chain must be non-empty and propagated, so re-audit # can re-derive taint after the fact. if not source_ids: raise TaintConservationError( f"summary {new_id} has no source_ids; provenance chain would be broken" ) return MemoryRecord( record_id=new_id, content=summary_text, provenance="self_consolidation", trust=out_trust, tainted=any_tainted, source_ids=source_ids, ) def retrieve(records: list[MemoryRecord], require_trusted: bool = True) -> list[MemoryRecord]: """Retrieval-time filter: necessary but not sufficient without write-time enforcement.""" return [r for r in records if not r.tainted and (r.trust is Trust.TRUSTED or not require_trusted)] ```