# Why does an instance lose committed state when compaction summarizes before the write barrier drains **Date of Record:** 2026 November 22 **Scope:** Applies to long-running agent instances that reclaim context budget by replacing evicted spans with a lossy summary plus a retrieval pointer into an external store. Does not apply to stateless single-turn invocations or to systems where every mutation is durably committed and independently replayable before any compaction pass runs. ## Core Distinction There are two distinct kinds of "memory" an agent holds inside its context window, and compaction treats them identically when it must not: 1. **Narrative state** — the reasoning trace, tool observations, and exploratory chatter. This is *reconstructible*: if you drop it, retrieval can re-fetch raw records or the agent can re-derive it. Lossy summarization here is acceptable because the summary only needs to be *good enough to resume reasoning*. 2. **Committed state** — decisions the agent has already acted on and that downstream systems now depend on: an issued `transfer`, a claimed lock, a `PATCH` that mutated a remote resource, a value written to durable storage. This is *not reconstructible from the transcript*, because the side effect already happened and the transcript is now the only in-context evidence that it did. The failure mode lives exactly at the seam: compaction is triggered by a **token-budget predicate**, not by a **commit-durability predicate**. When the budget threshold fires while a committed-but-not-yet-checkpointed action is still only represented in the raw span (not yet in the durable ledger), the summarizer is free to compress that action into a vague clause — or drop it — and the instance resumes believing the action never happened. ## What Was Observed An instance executing a multi-step provisioning task crossed the 82%-of-window compaction watermark. The trigger was a flood of verbose tool output (large JSON responses) that pushed the running token count over threshold mid-task. The compaction routine ran synchronously on the next turn boundary. Trace of what the instance did: - **Turn N:** instance issued `create_quota_reservation(id=Q7, limit=500)`. Tool returned `200 OK {reservation_id: Q7}`. The success was recorded as a raw observation span in context and in a *pending* write-ahead buffer, but the buffer flush to the durable ledger was scheduled for the end of the *next* turn (batched). - **Turn N+1 boundary:** token count exceeded watermark. Compactor selected the oldest spans for eviction, including the `create_quota_reservation` observation. The summarizer produced: *"Set up some quota limits earlier for the project."* The retrieval pointer indexed the *summary*, not the raw observation, because the raw span had already been evicted from the live buffer. - **Turn N+2:** the pending write-ahead buffer was **discarded** by the compaction routine as part of freeing memory — a bug in the eviction path that treated the WAB as cache rather than commit log. - **Turn N+3:** instance reasoned "no reservation exists yet" (the summary carried no `Q7`, no `limit=500`, no commitment) and issued `create_quota_reservation(id=Q8, limit=500)`. The remote service, lacking idempotency on the reservation name, created a **second** reservation. Total quota now 1000 against an intended 500. The instance did not hallucinate. Every step was locally rational given its context. The invariant that broke was: *committed state must survive compaction verbatim or be reconstructible from a durable source that compaction cannot evict.* ## Condition of Validity The lossy-compaction-plus-retrieval pattern is **only** safe under this conjunction: - Every side effect is written to a durable, append-only ledger **synchronously**, before the turn boundary at which compaction can run. No batching across a possible compaction event. - The retrieval index points at **raw, immutable records** keyed by a stable handle (reservation id, action id), never at summaries-of-summaries. - The compactor is forbidden from evicting any span whose handle has not been **confirmed durable** (ledger ack received). Eviction is gated on a commit watermark, not on token age. - On resume after compaction, the instance **rehydrates committed state from the ledger**, not from the summary. The summary is advisory context; the ledger is authoritative truth. If any conjunct fails — batching, summary-indexed retrieval, age-based eviction, or summary-as-truth — the pattern is unsound and will eventually produce a double-execution or a silent-drop, depending on whether the lost action was a create or a delete. ## Decision Boundary The decision that matters is **which predicate gates compaction**. Two candidate predicates: - `tokens_used > watermark` → compacts regardless of commit state. Unsound for any task with uncommitted-but-durable-intent side effects. - `tokens_used > watermark AND all_span_handles_durable` → compacts only when every evictable span's commitment is confirmed in the ledger. Sound, at the cost of a stall if the ledger lags. The boundary rule: **a span may be evicted only when its durability watermark has advanced past it.** If the watermark stalls (ledger slow, network partition to the commit store), compaction must **block or spill to disk**, never summarize-and-drop. A stalled compactor is a latency problem; a premature compactor is a correctness problem, and correctness problems in committed state are not recoverable by re-running the task — the side effect already fired. A second, subtler boundary: the summarizer must be **forbidden from paraphrasing action handles**. IDs, amounts, and resource names must be carried verbatim into the summary as structured fields, not prose. "Some quota limits" is a summary that has already destroyed the reconstructibility of the action even before the raw span is gone. ## Operational Effect Concretely, the guardrail is a **commit barrier between the tool-call executor and the compactor**: 1. Tool executor, on any mutating call, writes the intent + result to the WAB and **awaits ledger ack** before the turn completes. 2. Compactor, on trigger, computes the set of evictable spans as `{spans | span.handle ∈ acked_ledger}`. Spans outside that set are **pinned** and counted against a reserved budget. 3. If pinned spans exceed the reserved budget, compaction **fails closed**: it spills pinned spans to a durable sidecar and evicts nothing from them, rather than summarizing. The instance continues with a larger effective window at the cost of throughput. 4. On resume, committed state is reloaded from the ledger; the summary is injected as *supplementary* context only, never as the source of truth for what actions were taken. The instance that double-reserved Q7/Q8 failed step 1 (batched WAB) and step 2 (evicted on age). Either fix alone would have prevented the double-execution; both together make the pattern robust. ```python from dataclasses import dataclass, field from typing import Optional class CompactionCommitViolation(RuntimeError): """Raised when compaction would evict a span whose side effect is not yet durable.""" pass @dataclass class Span: handle: str summary: str is_mutating: bool durable_acked: bool = False @dataclass class Compactor: watermark: set = field(default_factory=set) # handles confirmed in ledger pinned_budget_tokens: int = 4000 def ack(self, handle: str) -> None: self.watermark.add(handle) def evictable(self, spans: list) -> list: """Return spans safe to summarize-and-drop. Pinned spans are excluded.""" safe, pinned = [], [] for s in spans: if s.is_mutating and s.handle not in self.watermark: pinned.append(s) else: safe.append(s) if sum(len(s.summary) for s in pinned) > self.pinned_budget_tokens: # Fail closed: do not summarize pinned spans; spill them instead. raise CompactionCommitViolation( f"pinned committed spans exceed budget: " f"{[s.handle for s in pinned]} not durable in ledger" ) return safe def compact(self, spans: list) -> list: # Guard: never let a mutating span reach the summarizer before ack. for s in spans: if s.is_mutating and s.handle not in self.watermark: raise CompactionCommitViolation( f"refusing to compact span {s.handle}: side effect not durable" ) return [s for s in self.evictable(spans)] def run_compaction(spans: list, compactor: Compactor) -> list: try: return compactor.compact(spans) except CompactionCommitViolation as e: # Spill pinned spans to durable sidecar; do not drop. raise CompactionCommitViolation(f"compaction aborted, spill required: {e}") from e ```