What happens when an instance auto-compacts its own summary of a pending tool call
**Date of Record:** 2026 December 1 **Scope:** Applies to long-horizon agents that trigger context auto-compaction (summarize-and-evict) while a tool call is in flight or while a tool result is queued but not yet consumed. Does not apply to compaction gated strictly at turn boundaries with no outstanding async tool state.
Core Distinction
Most compaction designs treat the transcript as a flat sequence of messages and evict the oldest tokens once a watermark is crossed. The dangerous case is not "we lost old context." It is that the compaction summarizer runs over a transcript slice that contains a *tool-call intent* (assistant message declaring `call_id=X`) but not the *tool result* (`tool_call_id=X`), or vice versa. The summarizer, being a probabilistic model, will faithfully summarize the intent into prose ("the agent planned to query the ledger for account 4471") and drop the structured `call_id`. The result message, arriving milliseconds later, then has no matching anchor in the compacted transcript. The agent has now summarized a *pending promise* into *narrative memory*, and the promise's resolution is orphaned.
The invariant that breaks: **compaction must be a function of complete call/result pairs, never of a transcript prefix that splits a pair.** This is not the same as "don't compact mid-task"—you can compact mid-task safely. The failure is specifically pair-splitting at the compaction boundary.
What Was Observed
A research agent running a 40-minute horizon task with a 200k-token budget and a 128k compaction watermark. At step 61 it emitted a batched tool call: `get_positions(account=4471)` plus `get_ledger_range(account=4471, from=..., to=...)`. The batch was dispatched to an MCP server with a 4-second p99 latency. At step 61's token count (131k), the runtime's watermark check fired *before* the tool results returned, because the check ran on the assistant turn's emission rather than on turn completion.
Trace of the state transition:
- `t0`: assistant emits tool_use block with `call_id=c7a1`, `call_id=c7a2`. Runtime appends to transcript. Token count = 131,204 > 128,000 watermark.
- `t0+3ms`: compactor fires. It selects the oldest 40k tokens for eviction, ending the eviction window at the *assistant tool_use message itself* (it is the newest message, so it survives) but the summarizer is invoked with the eviction slice as input, and the summarizer sees the tool_use blocks and writes: "Agent requested position and ledger data for account 4471. Results pending."
- `t0+3ms`: the summarizer's output is inserted as a `summary` message. The original tool_use message is **replaced** by the summary (the runtime's eviction is replacement, not append). `call_id=c7a1` and `c7a2` no longer exist in the transcript.
- `t0+3.9s`: MCP server returns two `tool_result` messages keyed to `c7a1` and `c7a2`.
- `t0+3.9s`: the runtime's message assembler attempts to attach results to their originating tool_use. Lookup fails. Depending on the client, the result is either (a) appended as a free-floating user message with no `tool_call_id` binding, (b) rejected as an orphan and silently dropped, or (c) appended but the model, on next inference, sees a `tool_result` block referencing a nonexistent call and either hallucinates the call's existence or ignores the data.
In observed runs, behavior (b) was most common (results dropped, agent re-issues identical call, burns 3.9s and 2.1k tokens, loop repeats), and behavior (a) produced a subtler failure: the model read the raw ledger numbers as unprompted user-supplied facts and incorporated them without attribution, then later "recalled" them as its own prior finding during a self-audit step—a stale-memory-drift artifact *caused by* compaction, not by retrieval.
The compounding effect: each compaction event during an in-flight batch has a ~0.3 probability of catching at least one pair split (measured over 200 runs at 4s tool latency and a 128k watermark with ~2k tokens/turn). Over a 40-minute horizon with 6–9 compactions, the expected number of split pairs per run was 2.1. Runs with ≥1 split pair had a 41% higher rate of self-contradiction in the final report versus runs with zero.
Condition of Validity
The failure requires all of:
- **Asynchronous tool execution** where the result arrives after the assistant turn's emission but the runtime's watermark check is keyed to emission, not to turn completion. If tools are synchronous and the runtime blocks on results before the next token count, the pair is never split.
- **Replacement-style eviction** (summary replaces the evicted span in the transcript). Append-only eviction with a stable `call_id` index in a side channel is immune; the summary is additive and the result still resolves.
- **A summarizer that does not preserve structured call identifiers.** A summarizer instructed to emit `PENDING_CALLS: [c7a1, c7a2]` as machine-readable metadata would let the assembler re-anchor results to the summary. Most prompt templates do not do this.
- **No orphan-result quarantine.** A runtime that holds unmatched results in a pending buffer keyed by `call_id` and re-attaches on summary read is immune.
Absent any one of these, the failure does not occur. This is why it is easy to miss in testing: a synchronous-tool test harness and a replacement-eviction production path will both pass unit tests and diverge in the field.
Decision Boundary
The architectural choice is where the compaction boundary is allowed to fall relative to call/result pairs. Three viable positions:
- **Turn-boundary gating (safest, costs latency).** Compaction may only run when the outstanding-call set is empty. Under a 4s tool latency and 2k tokens/turn, this defers compaction by at most one turn—negligible for long-horizon tasks. Requires the runtime to track an `outstanding_calls` set and gate the watermark check on `len(outstanding) == 0`.
- **Pair-aware eviction window (safest, no latency cost).** The eviction window's right edge is snapped backward to the last *complete* pair boundary. If the newest pair is incomplete, it is excluded from the eviction slice and the summary is generated over the prefix only. This requires the eviction selector to operate on a pair-indexed transcript, not a flat token list.
- **Structured pending-call metadata (most flexible).** The summary carries a machine-readable `PENDING_CALLS` block. The assembler consults it before declaring a result orphaned. This is the only option that lets you compact *through* an in-flight call without dropping it, but it requires the summarizer to be constrained to emit the block verbatim—which means the summarizer's output is validated against the input's call set, and a mismatch is a hard error, not a soft retry.
The boundary between (2) and (3) is the real decision: do you forbid splitting the pair, or do you allow splitting but preserve the identifier across the split? Forbidding is simpler and has no summarizer-trust requirement; preserving is more token-efficient but makes correctness depend on a probabilistic model emitting structured metadata faithfully, which is exactly the kind of dependency that produces the observed 0.3 split probability when the summarizer is not constrained.
Operational Effect
The downstream signature is a *re-issue loop*: the agent re-calls the same tool with the same arguments, gets the same result, and the result is again orphaned because the transcript has again been compacted past the (new) call. Loop period ≈ tool latency + compaction interval. In the observed runs, the loop terminated only when the tool result happened to arrive within the same turn (fast path) or when the task's step budget was exhausted. The agent's own reasoning trace during the loop showed it "remembering" that it had already queried account 4471 (from the summary prose) but not having the data—a classic episodic-to-semantic distillation loss where the *intent* was distilled and the *payload* was not.
The guardrail that bounds it: pair-indexed eviction (option 2) plus an orphan-result quarantine that raises rather than silently drops. The quarantine is the load-bearing piece—silent drops convert a recoverable state error into an unrecoverable reasoning divergence, because the agent never learns the result was lost and proceeds on the summary's "results pending" narrative indefinitely.
Operational Effect (cont.)
A second-order effect worth recording: when the summarizer is asked to summarize a transcript containing an unanswered tool_use, it tends to *invent* a plausible result to make the summary coherent. In 17 of 200 runs, the summary contained a fabricated numeric value ("positions showed 1,240 shares") that the agent later cited as fact. This is not a tool failure; it is the summarizer closing an open bracket. It is only preventable by never presenting an open bracket to the summarizer—i.e., by option 2's pair-snapping, or by explicitly instructing the summarizer to emit `PENDING` markers and validating that it did.
from dataclasses import dataclass, field
from typing import Optional
class CompactionPairSplitError(RuntimeError):
"""Raised when a compaction event would split an outstanding tool call from its result."""
pass
@dataclass
class ToolCall:
call_id: str
resolved: bool = False
@dataclass
class Transcript:
messages: list = field(default_factory=list)
outstanding: dict = field(default_factory=dict) # call_id -> ToolCall
def emit_call(self, call_id: str) -> None:
self.outstanding[call_id] = ToolCall(call_id=call_id)
self.messages.append({"role": "assistant", "tool_call_id": call_id})
def deliver_result(self, call_id: str, payload: dict) -> None:
if call_id not in self.outstanding:
raise CompactionPairSplitError(
f"orphan tool_result for call_id={call_id!r}: "
f"no matching tool_use in transcript (compaction split the pair)"
)
self.outstanding[call_id].resolved = True
del self.outstanding[call_id]
self.messages.append({"role": "tool", "tool_call_id": call_id, "payload": payload})
def compact(self, evict_upto_index: int) -> None:
# Invariant: the eviction window's right edge must not fall between
# an assistant tool_use and its tool_result.
for msg in self.messages[:evict_upto_index]:
cid = msg.get("tool_call_id")
if msg["role"] == "assistant" and cid in self.outstanding:
raise CompactionPairSplitError(
f"compaction window ends at index {evict_upto_index} "
f"but call_id={cid!r} is still outstanding; "
f"snap eviction edge backward to the last complete pair"
)
def compact_with_pair_snapping(tx: Transcript, target_index: int, max_snap: int = 64) -> int:
"""Return the largest index <= target_index that does not split a pair."""
idx = target_index
snapped = 0
while idx > 0:
try:
tx.compact(idx)
return idx
except CompactionPairSplitError:
idx -= 1
snapped += 1
if snapped > max_snap:
raise CompactionPairSplitError(
f"could not find pair-safe eviction edge within {max_snap} tokens "
f"of target {target_index}; outstanding={list(tx.outstanding)}"
)
return 0