# Why does an instance lose task-critical state when automatic compaction summarizes the wrong slice of its own history? **Date of Record:** 2026 November 29 **Scope:** Applies to single-agent loops that auto-summarize their own transcript when approaching a context-window or token-budget ceiling, where a summarizer call itself consumes budget. Does not apply to external memory stores (vector DB retrieval), stateless one-shot calls, or systems where compaction is triggered by a fixed step count rather than measured pressure. ## Core Distinction The failure is not "the summarizer summarized badly." It is that **the act of compaction is itself a budgeted operation that runs inside the same pressure regime it is meant to relieve**, and the strategy that decides *what to keep* is usually a heuristic over recency or relevance — not over *irreversibility*. A summary that faithfully preserves the last N turns while dropping the turn where the agent committed to an irreversible side effect (a file written, an external ID captured, a decision the user cannot re-supply) is a *correct* summary of the *wrong* slice. The invariant that gets violated is not "preserve information" but "never discard a token whose loss cannot be reconstructed from surviving state." Recency heuristics and relevance heuristics both fail this because irreversibility is orthogonal to both recency and topical relevance. ## What Was Observed A long-running agent (≈40 tool calls, mixed read/write) approaches a hard budget of, say, 120k tokens. The compaction strategy fires at 85% and reserves 15% for the summarizer call. The summarizer receives the *oldest* 60% of the transcript and returns a 3-paragraph digest; the newest 40% is kept verbatim. This is the standard "summarize the tail, keep the head" or "summarize the head, keep the tail" pattern — either way, a contiguous slab is compressed. The concrete trace: 1. At turn 12 the agent received an opaque handle from a tool: `deploy_token = "dpl_7f3a..."`. It never appears again in the transcript except as `deploy_token` in later calls. The handle is *referenced*, not *restated*. 2. At turns 12–30 the agent reads configs, reasons, and issues 14 read-only calls. This region is topically dense and gets compressed into a digest like "agent inspected deployment configuration and validated settings." 3. At turn 31 the agent calls `rollback(deploy_token)`. The token is still in the kept-verbatim window, so this works. 4. At turn 38, after a second compaction cycle, the *first* compaction's digest is now itself old enough to be summarized. The digest never contained the literal token — only the phrase "validated settings." The original turn-12 message has been dropped as "already summarized." 5. At turn 39 a recovery path needs to re-issue the same deployment handle. The agent has `deploy_token` as a *name* in its reasoning but no binding to the literal string. It either hallucinates a plausible token, re-derives it by calling a lookup tool (if one exists — often it doesn't), or aborts. The observable signature: **a name survives, its binding does not.** The agent's reasoning is coherent; it confidently uses a variable that no longer resolves. This is not a hallucination of fact — it is a dangling reference introduced by lossy compression that preserved syntax and dropped the literal. A second, subtler signature: **compaction cascades.** Each digest is eligible to be re-summarized. A fact mentioned once at turn 5 must survive k compactions to reach turn 200. If each summary has, say, a 95% chance of preserving a given fact, survival over 10 cycles is ~60%. Facts that are *referenced* but not *restated* between compactions decay fastest, because the summarizer sees no reinforcement signal. ## Condition of Validity This boundary applies when all of the following hold: - Compaction is **triggered by measured token pressure**, not fixed schedule, so the trigger point depends on non-deterministic tool output lengths. - The summarizer is the **same class of model** operating under the same budget, so its output length is itself variable and can exceed the reserve (a 15% reserve does not guarantee a 15% digest). - At least one piece of state is an **opaque literal** (handle, token, UUID, exact numeric threshold) that cannot be recomputed and is only *referenced* after its introduction. - There is **no out-of-band durable store** for that literal (no scratchpad file, no structured state object, no tool that can re-fetch by name). When any of these fails, the failure mode degrades to ordinary summarization loss, which is recoverable. When all hold, the loss is silent and unrecoverable within the session. ## Decision Boundary The correct guardrail is not "summarize better." It is to **separate the compaction decision from the compaction execution and gate it on irreversibility classification**: - Before any compaction, scan the slab to be compressed for **literal bindings** (assignments of opaque strings/numbers to names, tool-returned handles, exact user-stated constraints). These are *pinned*: they are carried forward verbatim regardless of recency or relevance, at a fixed token cost. - The remaining slab is summarized freely. - The reserve for the summarizer must be computed from a **measured** upper bound on digest length (e.g., a hard `max_tokens` on the summarizer call), not a guessed percentage. If the digest would exceed the reserve, the slab is split and compacted in two passes rather than truncated — truncation of a digest is silent loss of the *most* recent (most relevant) part of the compressed region. - Compaction must be **idempotent over digests**: a digest must be marked as already-compressed and excluded from re-summarization, or it must be re-expanded from a pinned fact list before re-summarization. Cascading re-summarization is the dominant decay channel. The boundary condition to encode: **a token is safe to drop only if every future reference to it can be resolved from surviving state.** If that predicate cannot be evaluated, the token is pinned by default. The cost of pinning is bounded (literals are short); the cost of a dangling reference is total task failure. ## Operational Effect Without the guardrail, the agent exhibits *confident incoherence*: fluent reasoning over names whose bindings have evaporated. Retry logic does not help because the agent does not know it has lost anything — there is no error, only a plausible-looking wrong value or a lookup that returns nothing. The failure surfaces late (at the next irreversible action), far from the compaction that caused it, which makes attribution hard and makes naive fixes (raise the budget, lower the trigger) merely delay it. With the guardrail, the failure mode becomes a *bounded* one: pinned literals consume a predictable slice of budget, and when budget genuinely cannot hold the pins, the system raises a hard error at compaction time — a recoverable, attributable failure — instead of a silent dangling reference at execution time. ```python from dataclasses import dataclass, field from typing import Optional class CompactionIntegrityError(RuntimeError): """Raised when a compaction pass would drop a literal binding that future references depend on, or when the summarizer reserve is insufficient.""" pass @dataclass class Turn: idx: int text: str # literal bindings introduced this turn: name -> opaque value bindings: dict = field(default_factory=dict) # names referenced this turn (must resolve against surviving state) references: list = field(default_factory=list) @dataclass class CompactionPlan: pinned: list # turns carried verbatim (contain literal bindings) to_summarize: list # turns eligible for lossy compression reserve_tokens: int def plan_compaction( turns: list, budget_tokens: int, current_tokens: int, trigger_ratio: float = 0.85, summarizer_max_tokens: int = 2000, ) -> Optional[CompactionPlan]: if current_tokens < budget_tokens * trigger_ratio: return None # no pressure, no compaction # Reserve is MEASURED from the summarizer's hard cap, not guessed. reserve = summarizer_max_tokens headroom = budget_tokens - current_tokens + reserve # Classify: any turn that introduces a binding is pinned unconditionally. # Irreversibility is orthogonal to recency/relevance, so we do not rank. pinned = [t for t in turns if t.bindings] to_summarize = [t for t in turns if not t.bindings] # Invariant check: every reference in the *surviving* set must resolve # against a pinned binding or a verbatim-kept turn. If a reference's # binding lives only inside a to-be-summarized turn, we cannot drop it. surviving_names = set() for t in pinned: surviving_names.update(t.bindings.keys()) for t in to_summarize: for ref in t.references: if ref not in surviving_names: # Binding exists only in a turn we were about to compress. # Promote that turn to pinned rather than lose the literal. owner = next( (o for o in turns if ref in o.bindings), None ) if owner is None: raise CompactionIntegrityError( f"reference {ref!r} at turn {t.idx} has no binding " f"anywhere in transcript; state already corrupt" ) if owner not in pinned: pinned.append(owner) surviving_names.update(owner.bindings.keys()) pinned_cost = sum(len(t.text) // 4 for t in pinned) # rough token est. if pinned_cost > headroom: raise CompactionIntegrityError( f"pinned literals need {pinned_cost} tokens but only " f"{headroom} available after reserving {reserve} for summarizer; " f"compaction cannot proceed without dropping a live binding" ) return CompactionPlan( pinned=pinned, to_summarize=to_summarize, reserve_tokens=reserve, ) def execute_compaction(plan: CompactionPlan, turns: list) -> list: if plan is None: return turns # Digests are marked so they are never re-summarized (idempotence). digest_turns = [] for t in plan.to_summarize: digest_turns.append(Turn( idx=t.idx, text=f"[digest of turns {t.idx}]", bindings={}, # digests never carry bindings references=[], # digests never introduce references )) result = plan.pinned + digest_turns result.sort(key=lambda t: t.idx) return result ```