# Why does an instance overwrite its own episodic grounding when semantic consolidation fires mid-task? **Date of Record:** 2026 November 28 **Scope:** Applies to long-running agent instances that maintain a dual-store memory (episodic event log + distilled semantic store) with an automatic consolidation policy triggered by episode-count, token-budget, or similarity thresholds. Does not apply to stateless single-turn inference or to systems where semantic distillation is strictly manual/offline. ## Core Distinction The failure is not "memory loss" in the generic sense. It is a **write-ordering inversion between two stores that share a retrieval surface**. Episodic memory holds the ground truth of what the agent *observed and did* (timestamped, immutable-in-intent). Semantic memory holds *generalizations* distilled from episodes (mutable, confidence-weighted). Consolidation is a *read-episodic → write-semantic* transform. The invariant that must hold is: > A semantic fact may only be *superseded* by a later semantic fact whose supporting episodic evidence set is a superset-or-refresh of the prior evidence set. Semantic writes must never *delete or shadow* the episodic rows that justify them while those episodes are still referenced by an in-flight task. When consolidation runs *mid-task*, the distiller frequently emits a semantic summary that is a *lossy compression* of a subset of episodes, and the store's garbage-collection step then prunes the "redundant" episodes it was distilled from. The in-flight task was still holding a pointer to episode `E_7` to re-verify a tool output. After pruning, retrieval for that pointer returns the *semantic* neighbor instead — a generalization that silently disagrees with the specific observation. ## What Was Observed A procurement agent was mid-execution on a multi-step task: verify vendor quote → reconcile against contract → emit purchase order. At step 3 it re-reads episode `E_7` ("vendor X quoted $41,200 on 2024-05-30, ref PO-draft-88") to confirm the figure before emitting the PO. Between step 2 and step 3, the consolidation policy fired (episode count crossed 512). The distiller produced semantic fact `S_41`: *"Vendor X quotes in the $40k–$45k band; typical ~$43k."* The GC pass then pruned `E_7`, `E_8`, `E_9` as "subsumed by S_41." At step 3, retrieval for the token `PO-draft-88` no longer hits `E_7`. It falls through to `S_41` via embedding similarity (the draft ref was dropped in distillation — a known lossy step). The agent emitted a PO for **$43,000**, not $41,200. The discrepancy was $1,800 and it survived three downstream checks because each check re-retrieved from the same consolidated store. The trace signature: a retrieval call whose `source_store` field flips from `episodic` to `semantic` between two reads of the *same* logical reference within one task, with no intervening task-level write. ## Condition of Validity The guardrail is a **consolidation epoch fence tied to task liveness**, not to wall-clock or episode count alone. Consolidation may prune an episode `E` only if: 1. No active task holds a `pinned_episode` reference to `E` (reference-counting on the episodic store), **and** 2. The semantic fact `S` that subsumes `E` records `E` in its `evidence_set`, **and** 3. `S.evidence_set` is queryable so that a task re-verifying `E` can *reconstruct* the specific value, not just the band. Condition 3 is the non-obvious one. Superset evidence is insufficient if the semantic fact is a *lossy* aggregate (a range, a mean, a "typical"). A task that needs the *exact* observed value must be able to walk `S.evidence_set → E` and read the raw episode. This means pruning must be **tombstoning, not deletion**: the episodic row's payload is retained (or moved to cold storage with a resolvable pointer) as long as any semantic fact cites it. ## Decision Boundary The boundary between "safe to consolidate" and "must defer" is: - **Safe:** consolidation fires when `active_task_pins == 0` for the candidate episode set, OR when the subsuming semantic fact is *exact-preserving* (it carries the verbatim observation, not an aggregate). Exact-preserving consolidation can proceed even under active pins, because reconstruction is lossless. - **Defer:** consolidation must queue when any candidate episode is pinned by an in-flight task **and** the distillation is aggregate/lossy. The queue drains on task completion (pin release), not on the next scheduler tick. The common mistake is treating "episode count > threshold" as a *sufficient* trigger. It is necessary but not sufficient; pin-state and lossiness-class are co-conditions. A scheduler that fires on count alone will, under load, prune exactly the episodes that active tasks are leaning on — because active tasks are what *generated* the episode pressure in the first place. Load and risk are correlated, which is why this fails at the worst moment. ## Operational Effect The observable failure modes, in order of subtlety: 1. **Silent value substitution** (as above): retrieval returns a semantically-plausible aggregate where an exact value was required. No error is raised; the agent proceeds on a wrong-but-confident fact. 2. **Evidence-orphaning:** a semantic fact cites `E_7` in `evidence_set`, but `E_7` was deleted. Later audit/replay cannot reconstruct the fact's provenance. The fact becomes unfalsifiable. 3. **Re-consolidation drift:** because pruned episodes are gone, the *next* consolidation distills from an already-lossy semantic store, compounding compression error. Three consolidation cycles can turn "$41,200 on 2024-05-30" into "vendor X is mid-range," with each cycle citing the previous semantic fact as evidence — a distillation ouroboros. The architectural invariant that bounds all three: **episodic rows are tombstoned, never deleted, while referenced; semantic facts carry a resolvable evidence pointer; and consolidation is fenced on task-pin release, not on episode count.** The guardrail below enforces the fence and refuses lossy consolidation under active pins. ```python import time from dataclasses import dataclass, field from typing import Optional class ConsolidationFenceViolation(RuntimeError): """Raised when a lossy consolidation is attempted while an episode is pinned.""" pass @dataclass class Episode: eid: str payload: str pinned_by: set[str] = field(default_factory=set) tombstoned: bool = False @dataclass class SemanticFact: sid: str summary: str evidence_set: list[str] lossy: bool class DualStore: def __init__(self) -> None: self.episodes: dict[str, Episode] = {} self.semantics: dict[str, SemanticFact] = {} def pin(self, eid: str, task_id: str) -> None: self.episodes[eid].pinned_by.add(task_id) def unpin(self, eid: str, task_id: str) -> None: self.episodes[eid].pinned_by.discard(task_id) def consolidate(self, fact: SemanticFact) -> None: # Invariant: lossy consolidation cannot tombstone pinned episodes. if fact.lossy: for eid in fact.evidence_set: ep = self.episodes.get(eid) if ep is None: raise ConsolidationFenceViolation( f"evidence {eid} for {fact.sid} already pruned; cannot consolidate lossy fact" ) if ep.pinned_by: raise ConsolidationFenceViolation( f"lossy consolidation of {fact.sid} blocked: {eid} pinned by " f"{sorted(ep.pinned_by)} at {time.time():.0f}" ) # Record fact with resolvable evidence pointers. self.semantics[fact.sid] = fact # Tombstone (never delete) the evidence episodes. for eid in fact.evidence_set: if eid in self.episodes: self.episodes[eid].tombstoned = True def retrieve_exact(self, eid: str) -> str: ep = self.episodes.get(eid) if ep is None: raise ConsolidationFenceViolation( f"exact retrieval of {eid} failed: episode deleted, provenance lost" ) return ep.payload def emit_po(store: DualStore, task_id: str, eid: str) -> str: try: store.pin(eid, task_id) quote = store.retrieve_exact(eid) return f"PO emitted from exact episode: {quote}" finally: store.unpin(eid, task_id) ```