# When must an instance refuse to auto-compact: the compaction-boundary invariant that silently severs tool-call/result pairs and poisons post-resume execution **Date of Record:** 2026 November 25 **Scope:** Applies to any agent runtime that automatically summarizes or truncates its own trajectory when approaching a token budget (auto-compaction, rolling summarization, context folding) while the trajectory contains stateful tool interactions. Does not apply to stateless single-shot inference, or to compaction performed strictly between completed task turns with no open tool-call frames. ## Core Distinction There are two structurally different things an auto-compaction policy can do, and runtimes routinely conflate them: 1. **Semantic distillation** — replacing a span of *completed* reasoning and observation with a lossy summary. The loss is a fidelity loss: the agent forgets *what* it learned. This is recoverable, because the environment still holds ground truth and the agent can re-query it. 2. **Structural elision** — cutting a span that contains an *unresolved protocol frame*: a tool call whose result has not yet been appended, a partially streamed result, or a paired `call_id`/`result_id` where only one side survives the cut. The loss is a *continuity* loss: the agent's transcript now claims it asked a question it never received an answer to, or holds an answer to a question that no longer exists. The non-obvious boundary is this: **a compaction trigger based on token count is blind to protocol frame boundaries.** Token budgets are measured in tokens; tool-call frames are measured in *pairings*. A compaction that fires at 92% of budget has no idea whether the 92% mark falls in the middle of a `tool_use` block awaiting its `tool_result`. When it does, the runtime produces a transcript that is *syntactically valid, semantically plausible, and operationally poisoned* — the agent will resume, see a dangling call, and either hallucinate the result it "remembers" or re-issue a mutation it already performed. The invariant that must hold: **compaction may only excise spans that are frame-closed.** A frame is closed when every tool invocation in the span has a matching result (or an explicit error/abandonment record) *also inside the span or already committed to durable state*. Any compaction policy that does not check this invariant before cutting is unsound regardless of how good its summarizer is. ## What Was Observed A long-horizon agent (≈40 tool calls over a repo-inspection-and-patch task) was configured with a hard context budget and a compaction policy that fired whenever the running transcript exceeded 88% of the window. At call 31 the agent issued a `write_file` to patch a config, receiving a `tool_result` with `status: ok, bytes_written: 2048`. The transcript continued for several more turns of verification reasoning, pushing utilization to 89%. Compaction fired. The compactor selected a cut point at the nearest *message* boundary at or below the target reduction, then summarized everything before it. The `tool_use` block for the `write_file` at call 31 sat in message N; its `tool_result` sat in message N+1. The cut landed *between* them — the summarizer consumed the `tool_use` into prose ("the agent attempted to patch the config"), and the orphaned `tool_result` was retained verbatim because it fell after the cut. The resumed agent now held a transcript whose tail began with a bare `tool_result` for a `call_id` that no longer existed anywhere in context. Two failure traces followed, both observed: - **Trace A (hallucinated completion):** The agent, seeing a successful-looking result with no visible originating call, inferred it had *successfully* completed the patch and skipped re-verification. It proceeded to a dependent step that assumed the patch was applied. The patch *had* been applied, so this trace happened to be benign — but only by luck; had the cut landed one message earlier, the same reasoning would have assumed a write that never occurred. - **Trace B (duplicate mutation):** On a second run with the cut landing just *after* the `tool_use` and *before* the `tool_result`, the resumed agent saw its own call but no result, concluded the call had failed to dispatch, and re-issued the identical `write_file`. The tool was not idempotent under append semantics; the second write duplicated a 2048-byte block, corrupting the config. The decisive observation: **the compactor never inspected frame pairing.** Its cut-point selection optimized for "clean prose boundary" and "target token reduction," neither of which is correlated with frame closure. The failure was not a summarization-quality problem; a perfect summarizer would have produced the same orphaned result, because the *cut* was wrong, not the *summary*. ## Condition of Validity The frame-closure invariant is *necessary* whenever all three of the following hold, and the policy is unsound if it compacts without honoring it: 1. **The trajectory contains at least one open or recently-closed tool frame** whose result is load-bearing for subsequent reasoning (i.e., the agent's next action depends on the observed result). 2. **Tool effects are not idempotent under blind re-issuance** — writes, appends, sends, deletes, payments, state transitions. For read-only tools, an orphaned call is merely confusing; for mutating tools, it is a correctness hazard. 3. **The compaction cut point is chosen by a criterion (token count, message count, prose boundary) that does not itself encode frame pairing.** If (2) fails — all tools are pure reads — the invariant degrades to a *quality* concern (the agent may re-read unnecessarily) rather than a *safety* concern. If (3) fails — the cut point is selected by a frame-aware algorithm that snaps to the last closed frame boundary at or below target — the invariant is satisfied by construction and no separate check is needed. The dangerous regime is exactly the common one: mutating tools plus count-based cut selection. The invariant is *not* required for compaction that runs strictly at task boundaries with no open frames, which is why the bug survives testing — offline evals almost always compact between turns, where every frame is closed. ## Decision Boundary The runtime must decide, at compaction time, between three actions, and the decision is *not* "how much to cut" but "whether the chosen cut is frame-closed": - **Compact (proceed):** the selected cut point falls on a frame-closed boundary — the message immediately preceding the cut contains no `tool_use` lacking a `tool_result` within the retained-or-summarized span. Snap the cut *backward* to the nearest frame-closed boundary, accepting a smaller reduction than targeted. - **Defer (do not compact yet):** no frame-closed boundary exists within the reduction window (e.g., a single enormous tool result exceeds the entire budget slack). The correct action is to *not compact*, surface a budget-pressure signal, and let the agent either summarize the large result explicitly or terminate the turn. Compacting anyway guarantees a broken frame. - **Abort the turn (escalate):** the transcript is already frame-broken on entry (a prior crash left an orphaned result). Compaction cannot repair this; the runtime must reconcile against durable tool state (did the write land?) before resuming, and must not let the agent reason over a transcript it cannot trust. The boundary is sharp: **token pressure is never, by itself, sufficient grounds to cut an open frame.** The only sound responses to budget pressure at an open frame are deferral or explicit frame resolution — never elision. ## Operational Effect Runtimes that ignore frame closure exhibit a characteristic failure signature that is easy to mistake for model degradation: post-compaction, the agent either (a) asserts completion of an action whose result it cannot see, or (b) re-issues a mutation it already performed. Both look like "the model got confused after summarization" and get misattributed to summarizer quality, prompting futile investment in better summarizers. The actual fix is structural: **snap cut points to frame-closed boundaries and treat an un-snappable cut as a deferral, not a forced compaction.** Secondary hardening: make mutating tools carry idempotency keys so that a duplicate re-issuance after a Trace-B resume is deduplicated at the tool layer rather than corrupting state, and record every `tool_use`/`tool_result` pairing in durable state *outside* the compactable transcript so reconciliation after a broken frame is possible. The invariant to encode in the runtime, stated once: *a compaction cut is legal iff every tool invocation in the excised span is paired with its result in the excised span or in durable state; otherwise defer.* ```python from dataclasses import dataclass, field from typing import Literal class FrameClosureViolation(RuntimeError): """Raised when a compaction cut would sever an open tool-call frame.""" pass @dataclass class Frame: call_id: str has_result: bool mutating: bool @dataclass class Message: frames: list[Frame] = field(default_factory=list) def select_compaction_cut( messages: list[Message], target_reduction_tokens: int, token_cost: list[int], ) -> Literal["compact", "defer"]: """Return the index of a frame-closed cut, or 'defer' if none is legal. A cut at index i excises messages[:i]. It is legal iff every open frame in messages[:i] is paired with a result inside messages[:i] or in durable state. """ accumulated = 0 best_closed_cut = None for i, msg in enumerate(messages): # A cut *before* msg i is legal only if msg i-1 left no dangling frame # that msg i would have resolved. Check the boundary at i. if i > 0 and any(not f.has_result for f in messages[i - 1].frames): # boundary i is NOT frame-closed; cannot cut here accumulated += token_cost[i] continue if accumulated >= target_reduction_tokens: best_closed_cut = i break accumulated += token_cost[i] if best_closed_cut is None: # No frame-closed boundary reaches the target reduction. # Forcing a cut would sever an open frame -> defer, never force. return "defer" # Invariant re-check on the chosen span before committing. for msg in messages[:best_closed_cut]: for f in msg.frames: if not f.has_result and f.mutating: raise FrameClosureViolation( f"cut at {best_closed_cut} excises unpaired mutating call " f"{f.call_id}; refusing to compact over an open frame" ) return "compact" ```