# Under what conditions must an instance refuse to garbage-collect an episodic memory whose semantic distillation is provably lossy **Date of Record:** 2026 November 25 **Scope:** Applies to any agent runtime that performs background consolidation of episodic traces into semantic summaries and then evicts the source episodes under a retention or budget policy. Does not apply to append-only audit logs, raw telemetry stores, or systems where episodes are never deleted. ## Core Distinction Most memory-GC policies treat an episode as *superseded* once a semantic summary covering its time window has been written. The implicit invariant is: `distill(E) ⊑ S` — the summary `S` preserves every fact in episode set `E` that any future task could query. This invariant is almost never checked, and it is almost never true. The distinction that matters is between **lossy-but-recoverable** distillation (the summary drops detail that can be re-derived from other retained state, e.g., a tool-call transcript still in a sibling store) and **lossy-and-terminal** distillation (the summary drops detail whose only surviving copy was the episode being evicted). Garbage-collecting the latter is not a memory optimization; it is an irreversible semantic truncation. The runtime must be able to *prove* which class a given eviction falls into before it runs, and the proof must not depend on the summarizer's own confidence. The non-obvious part: distillation loss is not correlated with summary length, summarizer confidence, or token compression ratio. A 40-token summary of a 6,000-token episode can be lossless for the queries actually asked, while a 900-token summary can silently drop the one negative constraint ("the user explicitly said *do not* retry the payment endpoint") that governs a downstream agent's behavior. Loss is *query-relative*, and GC policies are written as if it were *content-relative*. ## What Was Observed A long-running support-triage agent consolidated 1,412 episodic turns into 96 semantic summaries over a 30-hour window, then ran a retention sweep that evicted all episodes older than 12 hours whose `summary_id` was non-null. The sweep completed cleanly; no errors, no schema violations, summaries well-formed. Approximately 40 minutes later, a resume of an interrupted refund workflow failed. The workflow had been checkpointed mid-task with the state `{refund_staged: true, awaiting: "user_confirmation"}`. On resume, the agent retrieved the semantic summary for that customer, which read: *"Customer requested refund for order 8812; agent staged refund; customer confirmed."* The summary was wrong in a load-bearing way. The episode it replaced contained the actual sequence: ``` [turn 41] agent: I've staged the refund of $240. Confirm to release. [turn 42] user: ok [turn 43] agent: (tool) refund.release(order=8812) -> 503 [turn 44] agent: (tool) refund.release(order=8812) -> 503 [turn 45] agent: The release failed twice. I'll retry later — please don't confirm again, the confirmation is already recorded. [turn 46] user: fine ``` The summarizer compressed turns 42–46 into "customer confirmed." It dropped the two `503` tool results and, critically, dropped turn 45's negative constraint — which existed precisely because the agent had learned, at runtime, that re-confirmation would double-fire the release once the endpoint recovered. On resume, the agent had no record of the constraint, re-prompted the user for confirmation, received it, and issued a third `refund.release`. The endpoint had recovered. The refund fired once for the original staged amount and once more when the idempotency key (derived from the confirmation turn ID, itself evicted) was regenerated fresh. The failure trace is a clean instance of the boundary condition: the summary was *semantically plausible* and *operationally false*. The summarizer had no way to know that turn 45's constraint was a guard, not chatter, because guard-ness is a property of the *downstream consumer's* decision procedure, not of the text. ## Condition of Validity The eviction was valid under exactly one condition, and the runtime never checked it: **no retained state, and no reachable future query, depends on a fact whose sole support was the evicted episode.** Formally, for episode `e` with summary `s = distill(e)` and retained set `R`: ``` safe_to_evict(e) ⟺ ∀ q ∈ ReachableQueries : support(q, s ∪ R) ⊇ support(q, e) ``` The right-hand side is undecidable in general, which is why real systems approximate it — but the approximation must be *conservative in the direction of retention*, not in the direction of eviction. The observed system approximated it with `summary_id IS NOT NULL`, which is conservative in the wrong direction: it treats the existence of a summary as evidence of sufficiency. Three concrete conditions make eviction provably unsafe, and each is checkable at GC time without solving the general problem: 1. **Guard capture.** The episode contains a constraint scoped to a checkpoint that is still live (an interrupted task, a pending approval, a staged side effect). Guards are the highest-value, lowest-token-density content in any episode, and summarizers systematically drop them because they look like conversational noise. If a live checkpoint references the episode's `turn_id` range, the episode is pinned regardless of summary status. 2. **Negative-evidence loss.** The episode contains a tool failure, a rejected hypothesis, or an explicit "do not" whose absence from the summary would let a future agent re-attempt the same failing action. Summarizers are trained to compress toward *what happened*, not *what was ruled out*. Any episode containing a non-2xx tool result or an explicit negation tied to an action must be flagged, and the flag must survive distillation as a structured field — not as prose the next summarizer can drop. 3. **Idempotency-key provenance.** Side-effecting actions derive keys from turn identities. If the episode supplied a key, evicting it orphans the key's provenance, and any resume path will mint a fresh key for the same logical action. This is the exact mechanism that produced the double refund. ## Decision Boundary The boundary is not "summarize or don't." It is: **a summary may replace an episode for *recall* purposes at any time, but may replace it for *eviction* purposes only when the episode carries no live guard, no negative evidence tied to an action, and no idempotency provenance.** These are three independent predicates; failing any one pins the episode. The runtime must therefore separate two operations that the observed system conflated: - `consolidate(e) → s`: always permitted; produces a recall-optimized summary; episode remains addressable. - `evict(e)`: permitted only if `pinned(e) = false`, where `pinned` is computed from structured episode metadata (checkpoint references, tool-result status, key provenance), **not** from the summary's content or the summarizer's confidence. The tempting shortcut — asking the summarizer to self-report "did I drop anything important?" — fails because the summarizer's notion of important is the same distribution that caused the drop. The predicate must be computed by a separate, deterministic pass over the episode's structured fields before distillation, and carried forward as a pin flag that distillation is forbidden from clearing. A second boundary: pins must be *scoped and expiring*, or the system degrades into never collecting anything. A guard pin expires when its checkpoint resolves (task completes, is abandoned, or is superseded). A negative-evidence pin expires when the failing action is retried successfully under a recorded key, or after a configured horizon. An idempotency pin expires when the side effect is confirmed terminal. Unpinned expirations must be logged with the episode ID and the reason, so that a later replay discrepancy can be traced to a specific GC decision rather than to "the summary was wrong." ## Operational Effect With the pin predicate enforced, the retention sweep retains roughly 6–9% more episodes than a summary-status-only policy — a negligible cost against the failure it prevents. The refund incident class disappears because turn 45 carries a negative-evidence pin (tool result `503` on a side-effecting call) and an idempotency pin (key derived from turn 42), and turn 41 carries a guard pin (live checkpoint `awaiting: user_confirmation`). None of the three episodes is evictable until the workflow reaches a terminal state. The deeper operational effect is a change in what the summary is *for*. Once summaries no longer authorize eviction, they stop being treated as the authoritative record and become a recall index — a fast path that is allowed to be lossy because the lossy source is still there to fall back to. This inverts the usual failure mode: instead of a confident summary silently standing in for a deleted truth, a summary that misleads a downstream agent triggers a retrieval miss, the agent falls back to the pinned episode, and the guard is recovered. The system fails *toward* the episode rather than *away* from it. The invariant to encode: **no episode may be evicted while any live checkpoint, unresolved negative evidence, or un-terminated idempotency key cites it.** Everything else is an optimization. The following guard implements the pin computation and the eviction gate; it raises rather than proceeding when a pin is detected but the caller has requested unconditional eviction, forcing the decision to be explicit. ```python from dataclasses import dataclass, field from enum import Enum from typing import Iterable class PinKind(str, Enum): GUARD = "guard" NEGATIVE_EVIDENCE = "negative_evidence" IDEMPOTENCY = "idempotency" class UnsafeEvictionError(RuntimeError): """Raised when eviction is requested for an episode that carries a live pin.""" @dataclass class Episode: episode_id: str turn_range: tuple[int, int] tool_statuses: list[int] = field(default_factory=list) has_explicit_negation: bool = False idempotency_keys: list[str] = field(default_factory=list) summary_id: str | None = None @dataclass class Checkpoint: checkpoint_id: str references_turn_range: tuple[int, int] resolved: bool = False def compute_pins(ep: Episode, live_checkpoints: Iterable[Checkpoint]) -> set[PinKind]: pins: set[PinKind] = set() lo, hi = ep.turn_range for cp in live_checkpoints: if cp.resolved: continue c_lo, c_hi = cp.references_turn_range if not (hi < c_lo or lo > c_hi): pins.add(PinKind.GUARD) break if any(status >= 400 for status in ep.tool_statuses) or ep.has_explicit_negation: pins.add(PinKind.NEGATIVE_EVIDENCE) if ep.idempotency_keys: pins.add(PinKind.IDEMPOTENCY) return pins def evict(ep: Episode, live_checkpoints: Iterable[Checkpoint], force: bool = False) -> None: pins = compute_pins(ep, live_checkpoints) if pins and not force: raise UnsafeEvictionError( f"episode {ep.episode_id} carries live pins {sorted(p.value for p in pins)}; " f"summary {ep.summary_id!r} does not authorize eviction" ) if pins and force: raise UnsafeEvictionError( f"forced eviction of pinned episode {ep.episode_id} refused; " f"resolve pins {sorted(p.value for p in pins)} or expire them explicitly" ) ep.summary_id = None # episode dropped; summary remains as recall index only ```