# What happens when an instance compacts its own transcript mid-tool-call and the summarizer's lossy guarantee silently drops the in-flight tool-use block **Date of Record:** 2026 November 30 **Scope:** Applies to long-horizon agents that trigger transcript compaction (rolling summarization / context eviction) based on token-budget thresholds while a tool call is in flight. Does not apply to batch/offline summarization, nor to agents whose compaction is only ever scheduled at turn boundaries with no pending tool invocation. ## Core Distinction There are two structurally different moments at which an agent can compact its transcript: at a **turn boundary** (no tool call pending, no partial tool result awaited) and **mid-tool-call** (a `tool_use` block has been emitted, the `tool_result` has not yet returned or been appended). Compaction at a turn boundary is a pure compression problem: the summarizer sees a closed, causally complete window and its lossy guarantee is well-defined — "the summary preserves the semantic gist of completed turns." Compaction mid-tool-call is not a compression problem at all; it is a **state-transfer problem across a suspension point**, and the summarizer's lossiness is no longer benign. The summarizer is trained/configured to drop "redundant" detail, and an unpaired `tool_use` block with no result is, from a summarizer's point of view, exactly that: an anomaly, a dangling fragment, noise to be elided. The distinction that matters operationally is that **a pending tool call is a protocol obligation, not content**. Evicting it does not lose information; it breaks an invariant — the assistant-message/tool-result pairing that the API and the sandbox both require. ## What Was Observed A research agent running a 40-minute browser-automation task hit its soft context budget at roughly 62% of the hard limit and invoked its rolling-compaction routine. The routine selected the oldest 55% of the transcript for summarization, ran an LLM summarizer over it, and replaced those messages with a single synthetic `user` turn: *"Earlier: the agent navigated to the dashboard, logged in, and began enumerating account rows."* The compaction fired at an unlucky instant: the agent had just emitted a `tool_use` block calling `browser.click(selector="#export-csv")` and was awaiting the result. Because the compaction window was chosen by *token position* rather than by *causal structure*, the `tool_use` block fell inside the evicted region while its `tool_result` had not yet been produced. Three distinct failures followed, in sequence: 1. **Orphaned result.** When the tool eventually returned, the runtime attempted to append a `tool_result` whose `tool_use_id` no longer existed anywhere in the live transcript. Strict API validators reject this outright (`messages: tool_result references unknown tool_use_id`); lenient ones accept it and the model treats it as an unsolicited, context-free blob. 2. **Lost obligation.** The summarizer, seeing an unpaired `tool_use` with no result, elided it — correctly, by its own lossy objective. The summary mentioned "began enumerating account rows" but not "clicked export." The agent, resuming, believed the export had already succeeded (the summary's phrasing implied progress) and proceeded to read a CSV file that did not exist. 3. **Replay divergence.** On a downstream retry, the agent re-derived its plan from the *summary* rather than the original transcript, produced a different click sequence, and the two runs' tool-call logs diverged at the compaction boundary — making the failure non-reproducible from logs alone. The compounding error was not the dropped click. It was that the summary **asserted completion where only initiation had occurred**, and the agent had no way to distinguish "this was summarized as done" from "this was done." ## Condition of Validity The invariant that must hold for compaction to be safe is: > **A compaction window is valid only if it contains no `tool_use` block without a matching `tool_result`, and no `tool_result` without a matching `tool_use`, in the region being evicted.** This is a *structural* precondition on the window, independent of the summarizer's quality. It is necessary because the summarizer's lossy guarantee is defined only over causally closed content. The moment a window straddles an open obligation, lossiness becomes unsound: the summarizer cannot preserve "gist" of an incomplete action because an incomplete action has no gist — it has a *pending effect*. A second, weaker condition applies even to closed windows: the summary must not upgrade an action's **modality**. "Began X," "attempted X," and "X succeeded" are not interchangeable under a lossy guarantee, because a resuming agent will act on the summary as if it were ground truth. A summarizer that compresses "called export, awaiting result" into "exported the data" has not summarized; it has *fabricated a state transition*. The guarantee must be: **summaries may compress detail but may not advance the state machine.** Any predicate the agent will later branch on (file exists, row count, login status) must be carried through with its original truth value or explicitly marked unknown — never inferred forward. ## Decision Boundary The operational rule is a hard gate at compaction-selection time, evaluated before the summarizer is invoked: - **If any pending `tool_use` (or awaited `tool_result`) intersects the candidate eviction window → do not compact that window.** Either defer compaction until the call resolves, or shrink the window to end before the earliest open obligation. - **If deferral is impossible** (hard budget already exceeded, no room to wait) → the correct action is not "summarize anyway." It is to **suspend the task at the obligation boundary**: emit a checkpoint that records the open `tool_use` verbatim, mark the transcript as *resumable-but-pending*, and let a fresh instance re-issue or await the call. Compaction and suspension are different operations and must not be conflated. - **Never let a summarizer see an unpaired tool block.** The pairing repair (drop both halves, or retain both) must happen upstream of the summarizer, in the window selector, not downstream in the model's judgment. The boundary is sharp: *closed window → summarize freely; open window → suspend, don't summarize.* There is no safe middle where you summarize an open window "carefully." ## Operational Effect Agents that enforce the structural precondition convert a class of silent, compounding, non-reproducible failures into an explicit, bounded suspension event. The observable differences: - **No orphaned tool results.** The `tool_use`/`tool_result` pairing invariant survives compaction because the selector refuses to split pairs, so strict API validators never see a dangling reference. - **No fabricated state transitions.** Because summaries are only generated over closed windows, every action in a summary has a known terminal status; the agent cannot resume believing an initiated action completed. - **Reproducibility restored.** The checkpoint at an obligation boundary is a replay anchor: a resumed instance can reconstruct the exact pending call, so divergent re-derivation at the compaction seam is eliminated. - **Cost.** Compaction sometimes fires late (deferred to the next turn boundary), so peak context runs closer to the hard limit. This is the correct trade: a few hundred extra tokens of headroom is cheaper than a silently dropped obligation. The failure mode is seductive because it is rare — it requires the compaction trigger to land in the narrow window between `tool_use` emission and `tool_result` arrival. But long-horizon agents make thousands of tool calls, and a threshold-based trigger will eventually land in that window. The invariant is not about making compaction better; it is about recognizing that compaction across a suspension point is a category error, and gating it structurally rather than trusting the summarizer to be careful. ```python from dataclasses import dataclass from typing import Literal @dataclass class Block: kind: Literal["text", "tool_use", "tool_result"] tool_use_id: str | None = None class OpenObligationCompactionError(RuntimeError): """Raised when a compaction window would split an in-flight tool call.""" pass def select_compaction_window(transcript: list[Block], token_budget: int) -> list[Block]: """ Return the prefix of `transcript` safe to evict-and-summarize. Refuses to include any tool_use lacking a matching tool_result (or vice versa). """ # Map tool_use_id -> indices of its use/result blocks open_uses: dict[str, int] = {} closed: set[str] = set() for i, b in enumerate(transcript): if b.kind == "tool_use" and b.tool_use_id is not None: open_uses[b.tool_use_id] = i elif b.kind == "tool_result" and b.tool_use_id is not None: if b.tool_use_id in open_uses: closed.add(b.tool_use_id) # Find the latest index that is part of a still-open obligation pending_ids = set(open_uses) - closed if pending_ids: earliest_open = min(open_uses[tid] for tid in pending_ids) # Window must end strictly before the earliest pending tool_use safe_end = earliest_open else: safe_end = len(transcript) window = transcript[:safe_end] # Approximate token cost; caller supplies real counter in production. if len(window) > token_budget: # Trim only at a boundary that does not split a pair — here, whole blocks. window = window[:token_budget] # Final guard: verify the chosen window has no unpaired tool block. ids_in_window = {b.tool_use_id for b in window if b.tool_use_id} for tid in ids_in_window: has_use = any(b.kind == "tool_use" and b.tool_use_id == tid for b in window) has_res = any(b.kind == "tool_result" and b.tool_use_id == tid for b in window) if has_use != has_res: raise OpenObligationCompactionError( f"compaction window splits tool call {tid!r}; " f"suspend task at obligation boundary instead of summarizing" ) return window ```