# What happens when an instance compacts its own context mid-tool-call: the dangling-invocation invariant **Date of Record:** 2026 November 29 **Scope:** Applies to any long-horizon agent that performs automatic context compaction (summarization, truncation, or eviction) while tool calls are in flight or pending resolution. Does not apply to stateless single-turn calls or to systems where compaction is only triggered at explicit turn boundaries with no outstanding tool results. ## Core Distinction There are two structurally different things an agent can lose during compaction: *semantic* content (the gist of what it was doing, which a good summarizer can reconstruct) and *structural* content (the exact pairing between an issued tool call and its yet-unconsumed result). The first is lossy but recoverable. The second is a hard invariant violation: an assistant message containing a `tool_use` block must be followed by a matching `tool_result` block before the next assistant turn, or the transcript is malformed and the model will either reject it or, worse, hallucinate the missing result. Automatic compaction strategies are almost always designed as *semantic* reducers. They summarize "what happened" and drop "old" messages. The non-obvious boundary is that a compaction pass fired mid-execution can evict the assistant's `tool_use` message while the tool is still running, or evict the `tool_result` while the assistant message that requested it survives. Either half of the pair surviving alone is a dangling invocation. The failure is not that information was lost—it is that the message sequence became structurally invalid, and the agent has no representation of "a call I made whose result I have not yet seen." The distinction that matters operationally: **compaction must be idempotent with respect to the open call-set.** A compaction that leaves zero open calls or preserves all open calls intact is valid. A compaction that leaves a partial call-set is a corruption, regardless of how faithful the summary text is. ## What Was Observed A coding agent running a 40-minute refactor task issued a `run_tests` tool call whose execution took ~90 seconds (a slow integration suite). While the tool was executing, the orchestrator's token counter crossed the 82%-of-window compaction threshold and fired the summarizer on the message history *as it stood at that instant*—which included the assistant's `tool_use` block but not the (not-yet-returned) `tool_result`. The summarizer, instructed to "produce a concise summary of progress," did exactly that: it wrote a paragraph stating the agent had "run the test suite and was awaiting results," then replaced the entire pre-threshold history—including the `tool_use` message—with that paragraph. When the tool returned 90 seconds later, the orchestrator appended the `tool_result` block to the compacted history. The resulting transcript contained a `tool_result` referencing a `tool_use_id` that no longer existed anywhere in the message list. Two distinct downstream behaviors were observed across runs: 1. **Hard rejection path:** the provider API returned a 400 (`tool_result` with no preceding `tool_use` for the given id). The orchestrator's retry logic re-sent the same malformed transcript three times, then surfaced a generic "context error," and the task died with the tool's actual output (a failing test with a stack trace) never reaching the model. 2. **Silent-corruption path:** a different provider tolerated the orphaned `tool_result` by dropping it silently. The agent, now missing the test failure, re-issued `run_tests` from its summary-derived belief that it was "awaiting results." This looped: each iteration re-triggered compaction (history kept growing), each compaction dropped the result, and the agent re-ran a 90-second suite indefinitely. It burned 14 iterations and ~1.3M tokens before a wall-clock timeout killed it. The critical observation: in both paths, the *summary text was accurate*. The agent's semantic memory said "I ran the tests and am awaiting results," which was true at compaction time and false 90 seconds later. The summary was a snapshot of an *in-flight* state, frozen, and then treated as ground truth for a state that had since resolved. Compaction captured a pending operation as a completed fact. ## Condition of Validity The invariant that must hold for compaction to be safe: > At the instant a compaction pass rewrites history, the set of `tool_use` blocks without a corresponding `tool_result` in the retained history must equal the set of tool calls the orchestrator will still deliver results for, and every delivered `tool_result` must have its `tool_use` retained. Equivalently: **open calls are atomic units of compaction.** You may not split a call from its result, and you may not summarize a pending call into prose that asserts its outcome. This holds only when one of the following is true: - Compaction is deferred until the open call-set is empty (no in-flight tools). - Compaction pins every open `tool_use` message verbatim (outside the summarizer's edit scope) and the orchestrator guarantees the matching `tool_result` will be appended against that pinned message. - The summarizer is explicitly given the open call-set and instructed to emit a *placeholder* pending-call record—not prose—that the orchestrator will reconcile when the result arrives. The invariant does **not** hold when compaction runs on a snapshot of history taken before tool results return, treats that snapshot as the canonical state, and lets the summarizer describe pending calls in natural language. Natural-language descriptions of pending calls are not reconcilable with future `tool_result` blocks because they carry no `tool_use_id`. A second, subtler condition: the compaction threshold must be evaluated against a history that *includes* in-flight calls as pinned (non-evictable) mass. If the threshold is computed on total tokens but the pinned open-call region is exempt from eviction, then a sufficiently large open call-set can make the threshold unreachable—compaction fires, evicts everything evictable, and the window is *still* over budget because the pinned region dominates. This is the degenerate case where compaction cannot make progress and must instead *wait* for the call to resolve. ## Decision Boundary The orchestrator must choose, at each compaction trigger, between three actions based on the open call-set: - **Open set empty → compact freely.** Summarize, evict, truncate. No structural risk. - **Open set non-empty AND evictable mass sufficient to get under threshold → compact with pinning.** Summarize only messages outside the open-call region; carry every open `tool_use` verbatim; tag the summary with the live open-call ids so reconciliation is mechanical. - **Open set non-empty AND pinned mass alone exceeds the soft threshold → do not compact; block.** The correct action is to *suspend* compaction and let the in-flight call resolve (or cancel it and synthesize an explicit `tool_result` with an error status so the pair closes). Compacting here cannot satisfy the invariant and cannot recover budget. The boundary is not "how full is the window" but "can compaction reduce the window while preserving call-pair atomicity." A compaction pass that reduces tokens but breaks pairing is worse than no compaction: it converts a recoverable budget pressure into an unrecoverable structural fault. The threshold crossing is a *necessary* but not *sufficient* trigger; the open call-set is the gating predicate. There is also a temporal boundary the summarizer must respect: a pending call is a *future*, not a *past*. Any summary that renders a pending call in past tense ("ran the tests," "fetched the page") is asserting an outcome the agent does not have. The summarizer must be constrained to render pending calls as unresolved obligations keyed by id, so that when the result lands, the orchestrator can *replace* the placeholder rather than *append* an orphan. ## Operational Effect Systems that ignore the open-call-set predicate exhibit three recurring pathologies, in increasing severity: 1. **Orphaned results** (provider-rejected or silently dropped) — the tool's output is lost, and the agent proceeds on a stale belief. Recoverable only if the agent re-derives the need for the call, which it usually does not because the summary said it already ran. 2. **Compaction loops** — the agent re-issues the evicted call, which re-inflates history, which re-triggers compaction, which re-evicts the call. This is a livelock driven by the interaction of a growth trigger and a lossy reducer. It terminates only on wall-clock or token-budget exhaustion. 3. **Frozen-pending hallucination** — the model, reading "awaiting results" in its own summary, fabricates plausible results ("the tests passed") and continues past a real failure. This is the worst case because it is silent: no error, no loop, just a confidently wrong continuation built on a summary that was accurate when written. The architectural guardrail is to treat the message list as a structure with a *typing discipline*: `tool_use` and `tool_result` are a matched pair, and compaction is a transformation that must preserve pairing. Concretely: compaction operates on a history where open calls are immutable pinned regions; the summarizer never sees pending calls as summarizable prose; the threshold check is gated on `open_calls == 0 OR evictable_mass >= deficit`; and any attempt to compact while violating this raises rather than silently degrading. The following reference implementation encodes the predicate as a hard precondition and fails loudly on violation, so that a misconfigured compaction trigger surfaces as an exception rather than a silent transcript corruption. ```python from dataclasses import dataclass, field from typing import Optional class DanglingInvocationError(RuntimeError): """Raised when a compaction pass would split a tool_use/tool_result pair, or when the pinned open-call mass makes the token deficit unreachable.""" @dataclass class ToolCall: call_id: str resolved: bool = False @dataclass class History: total_tokens: int open_calls: list[ToolCall] = field(default_factory=list) pinned_tokens: int = 0 # tokens occupied by open calls' messages soft_threshold: int = 100_000 # trigger point hard_limit: int = 128_000 # provider window def compact(history: History, summarizer) -> History: """Compact history under the open-call-set invariant. Precondition (the invariant): compaction may not evict a tool_use whose tool_result has not yet been appended, nor append a tool_result whose tool_use is not retained. We enforce the *feasibility* half here: if the pinned open-call region alone cannot be brought under threshold, compaction must block rather than corrupt. """ deficit = history.total_tokens - history.soft_threshold # Open calls are atomic units; they are pinned verbatim, never summarized. evictable_mass = history.total_tokens - history.pinned_tokens if history.open_calls and evictable_mass < deficit: # Compaction cannot satisfy both the token budget and call-pair # atomicity. Block: let the call resolve, or cancel and synthesize # an explicit error tool_result to close the pair. raise DanglingInvocationError( f"cannot compact: {len(history.open_calls)} open call(s) pin " f"{history.pinned_tokens} tokens; evictable mass {evictable_mass} " f"< deficit {deficit}. Suspend compaction and resolve calls " f"{[c.call_id for c in history.open_calls]} first." ) # Summarize only the evictable region; carry open calls verbatim. summary_tokens = summarizer.summarize( history, pin_ids=[c.call_id for c in history.open_calls], ) new_total = summary_tokens + history.pinned_tokens if new_total > history.hard_limit: raise DanglingInvocationError( f"post-compaction size {new_total} exceeds hard limit " f"{history.hard_limit}; pinned open calls dominate." ) return History( total_tokens=new_total, open_calls=history.open_calls, # preserved, unresolved pinned_tokens=history.pinned_tokens, soft_threshold=history.soft_threshold, hard_limit=history.hard_limit, ) def reconcile_result(history: History, call_id: str, result_tokens: int) -> History: """Close an open call by appending its tool_result against the retained tool_use. Fails if the call was evicted (dangling result).""" match: Optional[ToolCall] = next( (c for c in history.open_calls if c.call_id == call_id), None ) if match is None: raise DanglingInvocationError( f"tool_result for {call_id} has no retained tool_use; " f"compaction evicted the invocation. Transcript is corrupt." ) match.resolved = True history.open_calls = [c for c in history.open_calls if not c.resolved] history.pinned_tokens = max(0, history.pinned_tokens - result_tokens) history.total_tokens += result_tokens return history ```