Why does an instance lose tool-call provenance when compaction summarizes a transcript mid-tool-sequence instead of at a turn boundary
**Date of Record:** 2026 December 1 **Scope:** Applies to long-horizon agents that auto-compact their own transcript (summarize-and-replace, sliding-window-plus-digest, or hierarchical rollup) while a multi-step tool sequence is in flight. Does not apply to compaction triggered only at explicit turn boundaries after all tool results have been consumed, nor to stateless single-shot invocations.
Core Distinction
The failure is not "compaction loses information." It is that compaction is *turn-agnostic* while tool execution is *turn-structured*. A transcript is a flat token sequence, but it encodes a hidden tree: an assistant message that issues tool calls, followed by the tool-result messages that satisfy them, followed by the assistant message that consumes those results. Summarizers operate on the flat sequence and are blind to this tree. When compaction fires between the `tool_use` block and its `tool_result` messages — or between the `tool_result` and the assistant turn that interprets it — the summarizer will faithfully compress the *text* of the pending call while severing the *binding* that says "this result belongs to that call, and that call is still outstanding."
The second distinction is subtler: the summarizer treats a dangling `tool_use` as completed work. A call whose result has not yet arrived looks, in natural language, exactly like a call that was made and answered. There is no surface signal distinguishing "I called `delete_record(id=88)`" (pending) from "I called `delete_record(id=88)`" (done). Compaction resolves this ambiguity in the wrong direction — toward completion — because completed work compresses more cleanly.
What Was Observed
A 14-hour migration agent was driving a schema change across ~40 tables. Its compaction policy: when the transcript exceeds 80% of the context window, summarize everything older than the last 6 messages into a rolling digest and prepend that digest. Tool calls were batched 8–12 at a time.
The trigger trace on table 27:
- Assistant emits a batch containing `tool_use` for `apply_migration(table="orders_v2", ddl=...)` and seven other DDL calls. Eight `tool_use` blocks, no results yet.
- The orchestration layer's token counter crosses the 80% threshold *on the assistant message itself* (the DDL payloads are large). Compaction fires before any `tool_result` returns.
- The summarizer ingests the assistant message and produces: *"Applied migrations to tables 19–26; began migration on orders_v2."* Note the tense shift — "began" — but the digest also drops the tool-call IDs and, critically, drops the fact that seven sibling calls are still outstanding.
- The eight `tool_result` messages arrive. Six are `success`, two are `error: lock timeout on orders_v2`. Because the compaction digest replaced the original assistant message, the results now have no parent `tool_use` to bind to. The orchestrator's result-router logs them as "orphaned tool results" and drops them to avoid corrupting the message array.
- The agent resumes from the digest. Its working state says orders_v2 migration "began." It does not know it failed. It does not know seven other tables were in the same batch. It re-issues `apply_migration(table="orders_v2", ...)` — now against a table that is *partially migrated and lock-contended* — and proceeds to tables 28–40 as if 27 were clean.
The downstream damage was a half-applied migration on orders_v2 that passed the agent's own end-of-task verification because the verification step read the digest, saw "began migration on orders_v2" followed by a later "applied migration to orders_v2" (the retry), and concluded the pair was a normal begin-then-complete.
Condition of Validity
This failure requires the conjunction of three conditions, and is bounded (does not occur) if any one is absent:
- **Compaction is permitted to fire mid-tool-sequence.** If compaction is gated on "no outstanding `tool_use` without a matching `tool_result`," the window cannot open. Most naive policies gate on token count only, which is the root enabler.
- **The summarizer is not given the tool-call tree as structured input.** If the summarizer receives the message array with explicit `tool_use_id` ↔ `tool_result` linkage and is instructed to preserve pending-call identity verbatim, the binding survives. Natural-language summarization of a flat transcript cannot preserve it.
- **Results are routed by parent linkage rather than by position.** If the orchestrator binds results by `tool_use_id`, a compacted parent yields a detectable orphan (an error, not silent loss). If it binds by "next message after the assistant turn," compaction shifts positions and results land on the wrong parent or are dropped.
The invariant that bounds the failure: **a compaction boundary is only valid at a point where the set of outstanding `tool_use` IDs is empty.** Equivalently, the compaction unit is the *turn*, not the token window. Any policy that compacts on a token budget without consulting outstanding-call state violates this invariant and is unsound for multi-step tool use.
Decision Boundary
The operational decision is where to place the compaction boundary when the token budget is exhausted mid-sequence. Three options, with distinct failure profiles:
- **Compact anyway, summarize pending calls as pending.** Requires the summarizer to emit a machine-readable "outstanding calls" list that the resumed agent treats as authoritative state, and requires the orchestrator to keep the original `tool_use` blocks (not their summaries) in a side channel for result binding. This preserves correctness at the cost of a more complex resume path and a side channel that itself must be compacted eventually.
- **Defer compaction until the sequence drains.** Safe but unbounded: a single batch of large tool calls can exceed the remaining budget and the agent cannot drain without more context. This is the trap — deferral is only viable if the in-flight batch is small relative to remaining headroom, which the agent cannot always know.
- **Abort the in-flight sequence, checkpoint, and re-plan from the last clean turn boundary.** The only option that is unconditionally sound. It costs a re-execution of the aborted batch, so it must be paired with idempotent tool calls or a dedup layer keyed on `(tool_name, args_hash)`.
The boundary is: if outstanding calls exist and remaining headroom is less than the worst-case result size of the batch, deferral is unsafe and you must either summarize-with-preserved-binding or abort-and-replan. Choosing "compact anyway with plain summarization" is the failure.
Operational Effect
The effect is not lost tokens — it is a *false completion record* in the agent's semantic memory. The digest is the agent's episodic-to-semantic distillation, and it has recorded an in-flight, failing operation as begun-and-therefore-probably-fine. Every subsequent reasoning step inherits this. Retries become duplicates against partially-mutated state; verification reads the digest as ground truth and passes; the error compounds silently across the remaining horizon.
The guardrail is a compaction precondition that inspects outstanding-call state before permitting summarization, plus result routing keyed on `tool_use_id` so that any surviving orphan is loud rather than silent. The following enforces the precondition and raises on violation:
from dataclasses import dataclass, field
from typing import Optional
class CompactionBoundaryViolation(RuntimeError):
"""Raised when compaction is attempted across an open tool-call sequence."""
pass
@dataclass
class ToolCall:
tool_use_id: str
tool_name: str
args_hash: str
result: Optional[str] = None # None => outstanding
@dataclass
class Transcript:
messages: list = field(default_factory=list)
open_calls: dict = field(default_factory=dict) # tool_use_id -> ToolCall
def issue(self, call: ToolCall) -> None:
self.open_calls[call.tool_use_id] = call
def resolve(self, tool_use_id: str, result: str) -> None:
if tool_use_id not in self.open_calls:
raise CompactionBoundaryViolation(
f"orphan tool_result for {tool_use_id}: no outstanding call to bind to"
)
self.open_calls[tool_use_id].result = result
del self.open_calls[tool_use_id]
def compact(
transcript: Transcript,
token_count: int,
budget: int,
worst_case_result_tokens: int,
) -> str:
"""Summarize-and-replace, but only at a sound boundary."""
if token_count <= budget:
return "no-op"
outstanding = list(transcript.open_calls.values())
if outstanding:
headroom = budget - token_count
if headroom >= worst_case_result_tokens:
# Safe to defer: the in-flight batch can drain within headroom.
return "deferred"
# Unsafe to defer and unsafe to summarize with plain text:
# the pending calls would be recorded as completed work.
raise CompactionBoundaryViolation(
"cannot compact mid-sequence: "
f"{len(outstanding)} outstanding tool calls "
f"({[c.tool_name for c in outstanding]}), "
f"headroom {headroom} < worst-case result {worst_case_result_tokens}. "
"Abort sequence, checkpoint at last clean turn boundary, or "
"summarize with preserved tool_use_id binding."
)
return "compacted"