# Why does an instance lose the last user turn when compaction fires mid-tool-loop: the recency-tail eviction invariant **Date of Record:** 2026 December 3 **Scope:** Applies to any agent runtime that performs automatic context compaction (lossy summarization of older turns into a synthetic summary block) while a tool-call loop is in flight. Does not apply to runtimes that only compact at turn boundaries between user messages, or that use exact (lossless) context extension. ## Core Distinction The failure is not "summarization is lossy." Everyone knows summarization is lossy. The failure is that **compaction budget accounting is computed against the message array, but the recency tail is not pinned relative to the in-flight tool result.** A compaction pass is triggered by a token-count threshold. When that threshold trips *between* an assistant tool-call message and its corresponding tool-result message, the summarizer treats the trailing tool-result as "old context" (it is large, and it is behind the assistant turn from the summarizer's point of view) and folds it into the summary. The loop then continues, but the model's next reasoning step no longer has the raw tool output it is nominally reacting to — it has a paraphrase of it, or nothing. The distinction that matters operationally: **a compaction event is a state transition, not a read-only optimization.** If it can occur at a point where the agent's control flow depends on a specific message being byte-identical, it is a correctness bug, not a performance tradeoff. ## What Was Observed Trace from a run with a 32k context window, compaction threshold at 80% (25.6k tokens), summarizer target of 1,500 tokens for the folded region. 1. Agent issues `read_file(path="config.yaml")`. Message array length grows to 24,900 tokens. 2. Tool returns a 3,200-token file. The runtime appends the tool-result message. Array is now 28,100 tokens — **over the 25.6k threshold**. 3. Before the next model call, the compaction hook fires. It selects the oldest region to fold, sized to bring the array back under target. Because the fold region is chosen by position (oldest-first) up to a token budget, and the tool-result is the newest message, the tool-result is *not* folded. Good. 4. But the fold budget (1,500 tokens) is insufficient to reclaim 2,500 tokens. The compactor runs a **second pass**, this time with a "must reclaim N tokens" directive. Under pressure, the region selector extends the fold window forward in time to include the tool-result, because it is the largest single reclaimable block. 5. The tool-result is replaced by a summary sentence: `"The agent read config.yaml; it contained service settings."` The array is now 24,200 tokens, under threshold. 6. The loop resumes. The model is asked to continue. It now believes it has read the file but has no field-level data. It hallucinates field names, or re-issues the identical `read_file` call, which returns the same 3,200 tokens, which re-trips compaction — a **compaction/retry livelock**. 7. In the observed run, step 6 repeated four times before a step budget killed the agent. Token spend was 3.1× the single-pass cost, and the final answer cited a config key (`retry.max_attempts`) that did not exist in the file. The non-obvious part is step 4. The first compaction pass was correct. The failure required **budget shortfall forcing a second pass with a forward-extending fold window** — a condition that only occurs when the reclaimable old region is smaller than the overflow. That is precisely the regime you enter when a single tool result is large. ## Condition of Validity The invariant that must hold for compaction to be safe: > **For any in-flight tool call, the tool-result message and the immediately preceding assistant tool-call message must be atomic with respect to compaction: either both are in the pinned tail, or the loop must be suspended before compaction and resumed only after the tail is re-established.** This invariant is violated when *any* of the following hold: - The fold-region selector is positional (oldest-first) rather than role-aware, and a reclaim shortfall triggers a forward extension of the fold window. - The pinning rule pins only the *last user message* (a common heuristic) and not the open tool-call/result pair. - The compaction hook runs on a token-count trigger evaluated *after* tool-result append but *before* the next model call, with no check on whether the last message is a tool-result whose call is still open. - The summarizer prompt is given the whole fold region including the tool-result and instructed to "preserve important facts," which produces a plausible-looking but non-authoritative paraphrase that the model then treats as ground truth. The invariant is *not* violated, and this failure does not occur, when: compaction only runs at user-turn boundaries; when the tail pin is defined as "last assistant message and everything after it"; or when the compactor refuses to fold a message whose `tool_call_id` has no matching assistant call still in the retained window. ## Decision Boundary The operational decision is: **when the reclaim shortfall cannot be met by folding pre-tool-call history, do you (a) fold the tool-result anyway, (b) truncate the tool-result with an explicit marker, or (c) hard-fail the compaction and let the loop proceed over-budget?** - (a) is the observed failure: silent authority substitution. The model cannot distinguish a summary of a tool result from the tool result. - (b) is acceptable *only* if the truncation is explicit and machine-visible — e.g., the tool-result is replaced by `{"truncated": true, "original_tokens": 3200, "head": "...", "note": "re-issue with narrower range"}`. The model must be able to see that it does not have the data. - (c) is the safe default: compaction is *skipped* for this cycle, the model call proceeds over the soft threshold (most providers tolerate modest overflow or the runtime can shed a different, non-pinned region), and a metric fires. The boundary rule: **a lossy transform may never silently change the epistemic status of a message the control flow is currently depending on.** Summarizing old conversation is fine because nothing downstream is mid-dependency on a specific old message. Summarizing the tool-result that the very next model call is reasoning about is a category error. ## Operational Effect Concrete consequences observed and reproducible: - **Silent data loss with plausible confabulation.** The model does not error; it generates field names consistent with the summary's vague shape. Downstream verification (if any) catches it; without verification, the wrong value ships. - **Compaction/retry livelock.** Re-issuing the same tool call regenerates the same overflow, re-triggering compaction, which re-folds the result. Each cycle burns a full tool round-trip plus a summarizer call. Step budgets are the only backstop. - **Non-monotonic context.** The array shrinks, then grows, then shrinks. Any downstream logic that assumes context length is monotonic within a turn (e.g., a "we have room for one more retrieval" heuristic) mis-schedules. - **Audit divergence.** The persisted transcript (post-compaction) does not match what the model actually saw at decision time if the runtime logs the pre-compaction array. Replay of the run produces a different trace, breaking verification replay. The guardrail that bounds all four: **pin the open tool-call/result pair, make truncation explicit and typed, and treat a reclaim shortfall as a signal to shed a non-pinned region or fail closed — never to extend the fold window forward across an open dependency.** ```python from dataclasses import dataclass, field from typing import Literal class CompactionInvariantViolation(RuntimeError): """Raised when a compaction pass would fold a message an open tool-call depends on.""" @dataclass class Message: role: Literal["user", "assistant", "tool", "summary"] tokens: int tool_call_id: str | None = None is_open_call: bool = False # assistant tool-call awaiting its result @dataclass class CompactionPlan: fold_indices: list[int] = field(default_factory=list) reclaimed: int = 0 def plan_compaction( messages: list[Message], overflow: int, pin_tail_from: int, ) -> CompactionPlan: """ Select oldest-first fold region to reclaim `overflow` tokens. MUST NOT extend the fold window past `pin_tail_from`. Raises if the shortfall cannot be met without crossing the pin. """ plan = CompactionPlan() for i in range(pin_tail_from): if plan.reclaimed >= overflow: break plan.fold_indices.append(i) plan.reclaimed += messages[i].tokens if plan.reclaimed < overflow: # The tempting-but-wrong move: extend forward into the pinned tail. # We refuse. The caller must shed elsewhere or proceed over-budget. raise CompactionInvariantViolation( f"reclaim shortfall: need {overflow}, foldable-before-pin yields " f"{plan.reclaimed}. Refusing to fold pinned tail starting at index " f"{pin_tail_from} (contains open tool-call/result pair)." ) return plan def compute_pin_tail(messages: list[Message]) -> int: """Pin from the earliest open assistant tool-call through the end.""" for i in range(len(messages) - 1, -1, -1): if messages[i].is_open_call: return i # No open call: pin only the final message (recency floor). return max(0, len(messages) - 1) def compact(messages: list[Message], threshold: int, target: int) -> list[Message]: total = sum(m.tokens for m in messages) if total <= threshold: return messages overflow = total - target pin = compute_pin_tail(messages) plan = plan_compaction(messages, overflow, pin) # may raise summary = Message(role="summary", tokens=min(1500, plan.reclaimed)) kept = [m for i, m in enumerate(messages) if i not in set(plan.fold_indices)] return [summary] + kept ```