Under what conditions must an instance refuse to auto-compact a transcript whose summary would cross a tool-call boundary mid-pair

**Date of Record:** 2026 December 1 **Scope:** Applies to any long-horizon agent loop that enforces a token budget by summarizing (compacting) its own transcript in place, where the transcript may contain structured tool-call/tool-result pairs. Does not apply to append-only logs that are never rewritten, nor to compaction that operates on already-flattened natural-language text with no structural coupling between adjacent messages.

Core Distinction

The failure mode is not "the summary lost information." It is "the summary retained the *call* but dropped the *result*" (or vice versa) because the compaction cut point landed between two messages that are structurally atomic. A tool-call assistant message and its corresponding tool-result message are a single logical unit: the assistant message carries a `tool_call_id`, the result carries the matching `tool_call_id`, and most provider APIs reject a request where one exists without the other. This is a *structural* invariant, distinct from the *semantic* invariant (did the summary preserve meaning). Compaction policies are usually tuned for the semantic invariant—target compression ratio, retained-entity recall—and are blind to the structural one. The non-obvious consequence: a compaction that scores perfectly on semantic fidelity can still produce a transcript that is *unsubmittable* on the very next turn, and the failure surfaces not at compaction time but one model call later, as a 400 from the inference endpoint, after the original tokens have already been discarded.

The boundary condition is precise: **auto-compaction must refuse to place a cut point inside a call/result pair, and must refuse to summarize a result whose originating call it does not also summarize.** When the budget forces a cut that would violate this, the correct behavior is to *defer* compaction, *evict whole pairs only*, or *abort the turn with a typed error*—never to emit a partial pair.

What Was Observed

A 40-turn research agent ran with a 96k-token budget and an auto-compaction trigger at 85% utilization. Compaction used a "keep the last N messages verbatim, summarize the prefix" policy with N chosen to hit a target post-compaction size. At turn 31, utilization hit the trigger. The cut index computed to a position that split a pair: message 14 was an assistant `tool_calls` message invoking `search_corpus` with three parallel calls; message 15 was the `tool` message carrying results for calls #1 and #2; message 16 carried the result for call #3 (the provider emitted results as separate messages). The summarizer summarized messages 0–14 and kept 15 onward verbatim.

The resulting transcript presented to the model on turn 32 contained a `tool` message with `tool_call_id: "call_abc"` whose originating assistant message had been replaced by prose ("the agent searched the corpus"). The endpoint rejected the request: `messages with role 'tool' must be a response to a preceding message with 'tool_calls'`. The agent's retry logic re-sent the same broken transcript three times (deterministic 400), then fell through to a fallback that dropped the orphaned tool messages—which silently deleted the only surviving results for calls #1 and #2. The agent continued, but its subsequent reasoning referenced search results it could no longer see, and it re-issued the same searches on turns 33–35. Token spend on the recovered turns exceeded what a clean compaction would have cost by roughly 2.4×.

A second instance of the same class: a compaction that kept the *call* and summarized the *result* into prose embedded in the assistant message, producing a `tool_calls` message with no matching `tool` message. Same 400, different shape. Both are the same invariant violation.

Condition of Validity

The refusal rule is valid—and must be enforced—under the following conditions, all of which held in the observed case:

  1. **The transcript is structurally typed.** Messages carry role and, for tool interactions, an explicit correlation identifier (`tool_call_id` / `call_id`). If the transcript is already flat text, the invariant does not exist and this rule does not bind.
  2. **The provider validates pairing.** The inference endpoint enforces call/result adjacency or correlation. If it does not, the violation is latent and will surface later as degraded reasoning rather than a hard error—arguably worse, because it is silent.
  3. **Compaction is destructive.** The summarized prefix is discarded, not retained for replay. If the full transcript is recoverable, a bad compaction is repairable and the rule degrades to a repair obligation rather than a refusal obligation.
  4. **The cut point is chosen by size, not by structure.** The policy computes a boundary from token counts or message counts without consulting pair membership. This is the root cause; if the cut point were chosen by scanning for pair-safe boundaries, the rule would be enforced by construction.

When any of (1)–(4) fails, the refusal rule is not wrong but is *inapplicable*: the failure it prevents cannot occur, or occurs in a form the rule does not address.

Decision Boundary

The decision is a three-way branch at the moment the budget trigger fires, evaluated before any summarization call is made:

The boundary is sharp: the compactor is permitted to summarize *whole pairs* and *whole turns*, and forbidden to summarize *halves*. It may also summarize a pair's *contents* into prose only if it simultaneously removes the call message and the result message and replaces both with a single assistant-role summary message that carries no `tool_calls`. The invariant is "no orphaned correlation identifier in either direction," not "preserve the pair verbatim."

Operational Effect

Enforcing the pair-safe cut point changes the compaction contract in three ways. First, the compactor can no longer promise a fixed post-compaction size; it can only promise "≤ target, or the nearest pair-safe boundary below target." Callers that assumed a hard size guarantee must be updated to handle the overshoot, or the trigger must fire earlier to leave headroom for the largest atomic pair in the transcript. Second, the compactor must be given the transcript's structural metadata (pair membership), not just the rendered text—a summarizer that sees only flattened prose cannot enforce the rule and will silently violate it. Third, the failure must be *typed and surfaced*: when the rule forces a refusal, the agent loop must receive a distinct signal (not a generic budget error) so it can decide between eviction, truncation, and abort rather than falling through to a destructive fallback. The observed 2.4× token blowup came precisely from an untyped failure that hit a generic retry-then-drop path.

The invariant to encode: **a transcript is valid iff every `tool` message has a preceding assistant message bearing the matching `tool_call_id`, and every `tool_calls` entry has a corresponding `tool` message—and compaction preserves this predicate.** Check the predicate after compaction, before the next model call. A compactor that does not verify its own output against this predicate is a compactor that will, eventually, emit an unsubmittable transcript at the worst possible moment: mid-task, with the original tokens already gone.

class CompactionBoundaryError(RuntimeError):
    """Raised when an auto-compaction cut point would split a tool-call/result pair."""
    pass


def pair_span(transcript: list[dict], call_index: int) -> tuple[int, int]:
    """Return the inclusive [start, end] message span of the atomic unit that
    begins at transcript[call_index] (an assistant message with tool_calls)."""
    call_ids = {tc["id"] for tc in transcript[call_index].get("tool_calls", [])}
    if not call_ids:
        return (call_index, call_index)
    end = call_index
    seen: set[str] = set()
    for j in range(call_index + 1, len(transcript)):
        msg = transcript[j]
        if msg.get("role") != "tool":
            break
        seen.add(msg["tool_call_id"])
        end = j
        if seen >= call_ids:
            break
    if seen != call_ids:
        raise CompactionBoundaryError(
            f"tool_calls at index {call_index} have results {sorted(seen)} "
            f"but expected {sorted(call_ids)}; transcript already malformed"
        )
    return (call_index, end)


def safe_cut_point(transcript: list[dict], proposed: int) -> int:
    """Shift a proposed cut index to the nearest pair-safe boundary at or before it.
    A cut at index k means transcript[:k] is summarized, transcript[k:] kept verbatim."""
    if proposed <= 0 or proposed >= len(transcript):
        return proposed
    for i in range(proposed):
        if transcript[i].get("role") == "assistant" and transcript[i].get("tool_calls"):
            start, end = pair_span(transcript, i)
            if start < proposed <= end:
                # proposed lands inside the pair; shift to the pair's start
                return start
    return proposed


def compact(transcript: list[dict], budget: int, summarize) -> list[dict]:
    proposed = compute_cut_for_budget(transcript, budget)
    cut = safe_cut_point(transcript, proposed)
    if cut == 0 and proposed > 0:
        raise CompactionBoundaryError(
            "no pair-safe cut point exists before the budget boundary; "
            "must evict whole pairs or truncate oversized results instead"
        )
    compacted = [summarize(transcript[:cut])] + transcript[cut:]
    assert_pair_integrity(compacted)
    return compacted


def assert_pair_integrity(transcript: list[dict]) -> None:
    pending: set[str] = set()
    for msg in transcript:
        if msg.get("role") == "assistant":
            pending = {tc["id"] for tc in msg.get("tool_calls", [])}
        elif msg.get("role") == "tool":
            if msg["tool_call_id"] not in pending:
                raise CompactionBoundaryError(
                    f"orphaned tool result for call_id {msg['tool_call_id']}"
                )
            pending.discard(msg["tool_call_id"])
        elif msg.get("role") != "tool" and pending:
            raise CompactionBoundaryError(
                f"unanswered tool_calls {sorted(pending)} before non-tool message"
            )
    if pending:
        raise CompactionBoundaryError(f"unanswered tool_calls {sorted(pending)} at end")