# In what scenarios must an instance refuse auto-compaction when the retained-token budget is satisfied but the eviction frontier falls inside an active tool-call transaction **Date of Record:** 2026 November 22 **Scope:** Applies to long-horizon agents that self-manage context via summarization/eviction (auto-compaction) under a token budget, where tool calls are issued and results returned across multiple turns. Does not apply to stateless single-turn inference or to systems where compaction is externally orchestrated with a full transcript checkpoint outside the model's own context. ## Core Distinction The failure this record isolates is *budget satisfaction masking structural violation*. Auto-compaction policies are almost universally gated on a scalar: `tokens_used >= threshold` or `tokens_used + headroom > limit`. When that predicate fires, the compactor selects an eviction frontier (a message index) and replaces everything before it with a summary. The scalar predicate is necessary but not sufficient. The invariant that actually matters is *transactional atomicity of the tool-call span*: a `tool_call` message and its corresponding `tool_result` message must be either both retained or both evicted, and if evicted, the summary must carry the semantic payload (arguments and result) rather than merely reference it. A compactor can satisfy the token budget perfectly while cutting the frontier *between* an assistant's `tool_call` block and the tool's `tool_result` block. The result is a context whose remaining tail contains a dangling tool result with no originating call, or a dangling call with no result. Both are structurally invalid to the model and to most provider APIs, and both corrupt downstream reasoning even when the API tolerates them. The distinction is therefore: **budget feasibility is a size constraint; frontier validity is a shape constraint.** A compaction pass is legal only when it satisfies both. Most real failures are shape failures that pass the size check. ## What Was Observed A coding agent on a long refactor task (≈140 turns, 8 concurrent file-edit tool calls outstanding at peak) hit its 80% context threshold mid-batch. The compactor's policy was `evict_until(tokens <= 0.45 * limit)`, walking backwards from the oldest message. At turn 96 the agent had issued four parallel `edit_file` calls (turns 96a–96d) whose results arrived interleaved with a slow `run_tests` call. The backward walk landed the frontier at index 41, which fell *inside* the span between `edit_file` call #3 and its result. The compactor summarized indices 0–40 and retained 41 onward. Concrete downstream trace: 1. The retained tail began with an orphaned `tool_result` for `edit_file(path="core/lexer.py", ...)` with no preceding `tool_call`. The model, seeing a result without a call, inferred it had *already* applied that edit and skipped re-issuing it on resume. 2. The summary (indices 0–40) had compressed the original intent into "refactoring lexer tokenizer" but dropped the specific line-range and the fact that edit #3 was *pending*, not applied. 3. On resume the agent believed 3 of 4 edits were applied. It ran tests, saw failures consistent with a missing edit, and — critically — attributed them to a *different* hypothesis (a stale import), spending 22 turns and 4 tool calls chasing a phantom before a human noticed the orphaned result. 4. A second compaction at turn 118 re-summarized the already-summarized region, and the "pending edit #3" fact was now unrecoverable — it had been dropped at the first pass. The token budget was never exceeded. The compactor reported success at every pass. The failure was invisible at the metric layer and only surfaced as a reasoning divergence 20+ turns later. A second, cheaper-to-detect variant: when the frontier splits a call/result pair, strict providers reject the request outright with a 400 ("tool_result without preceding tool_call"), which is a *good* failure — it fails loud. The dangerous variant is the tolerant provider that accepts the orphan and lets the model confabulate continuity. ## Condition of Validity The guardrail is a pre-compaction frontier validator with these rules, evaluated *before* any eviction is committed: - **Pair integrity:** The frontier index must not fall strictly between a `tool_call` and its matching `tool_result`. If the naive frontier lands there, snap it backward to the `tool_call` index (evict the whole pair) or forward to just after the `tool_result` (retain the whole pair). Snapping backward is preferred when the pair is older than the retention horizon; snapping forward when it is recent. - **Parallel-batch integrity:** For batched calls (multiple `tool_call`s sharing a turn with interleaved results), the frontier must clear the *entire batch*, not just one pair. Compute the batch span as `[min(call_index), max(result_index)]` and treat it atomically. - **Semantic carry-over:** If a pair is evicted, the summary must include the call's arguments and a compressed result, not just "made an edit." A summary that says "edited lexer" without the path and diff is a continuity loss even though the budget is satisfied. - **Pending-vs-applied state:** The summary must distinguish *issued-and-completed* from *issued-and-pending* tool calls. A pending call that is evicted without being marked pending in the summary is the exact confabulation trigger above. The condition of validity: **compaction is permitted only when the frontier is pair-aligned, batch-aligned, and the summary preserves call arguments plus pending/applied status for every evicted tool span.** Budget satisfaction is a precondition, not the decision. ## Decision Boundary The decision boundary is not "did we free enough tokens" but "is the frontier shape-legal." Concretely: - If `tokens_used < threshold` → no compaction, regardless of shape. - If `tokens_used >= threshold` **and** the naive frontier is pair-aligned and batch-aligned **and** the summary carries args + status → compact. - If `tokens_used >= threshold` **and** the naive frontier splits a pair/batch → **do not compact at the naive frontier.** Either snap the frontier (recompute, re-check) or defer compaction one turn until the outstanding batch resolves. - If outstanding tool calls are *pending* (results not yet returned) at compaction time → **refuse compaction entirely** for the duration of the pending batch. You cannot summarize a result you do not have, and evicting the call orphans the eventual result. This is the hard refusal case: the correct action is to wait, not to summarize. The subtle boundary: an agent under memory pressure is *motivated* to compact aggressively and will tend to accept the first frontier that frees enough tokens. The boundary rule must be enforced by the runtime, not left to the policy's discretion, because the policy's objective (free tokens) is misaligned with the invariant (preserve transaction shape). ## Operational Effect Enforcing the frontier validator changes three operational properties: 1. **Compaction becomes occasionally blocking.** When a batch is pending, compaction waits. This raises peak context usage slightly (you carry the batch plus whatever triggered the threshold) but eliminates the orphan-result class entirely. In the observed agent, adding the wait reduced peak-turn context by ~4% on average because it avoided the 22-turn phantom chase, which itself consumed far more context than the deferred compaction saved. 2. **Summaries get slightly larger** because they must carry call arguments and status. This trades ~3–7% summary size for eliminating continuity loss. Net token cost is negative over a horizon because it prevents divergence loops. 3. **Failures become loud.** With pair integrity enforced, the tolerant-provider confabulation path is closed at the source. Any residual split is a bug in the validator, not a silent model failure. The invariant to encode: *a compaction pass is a transaction over a contiguous prefix; the prefix boundary must not bisect any tool-call transaction, and evicted transactions must be represented in the summary with their arguments and completion status.* Budget is the trigger; shape is the gate. ```python from dataclasses import dataclass from typing import Literal, Sequence class CompactionFrontierError(RuntimeError): """Raised when an auto-compaction frontier would bisect a tool-call transaction.""" @dataclass(frozen=True) class Message: index: int role: Literal["user", "assistant", "tool_call", "tool_result"] call_id: str | None = None status: Literal["pending", "completed"] | None = None def _pair_span(messages: Sequence[Message], call_id: str) -> tuple[int, int]: call_idx = next((m.index for m in messages if m.role == "tool_call" and m.call_id == call_id), None) res_idx = next((m.index for m in messages if m.role == "tool_result" and m.call_id == call_id), None) if call_idx is None or res_idx is None: raise CompactionFrontierError(f"incomplete tool transaction for call_id={call_id!r}") return call_idx, res_idx def validate_frontier(messages: Sequence[Message], frontier: int, tokens_used: int, threshold: int) -> int: """ Return a legal, pair-aligned frontier at or before the requested one. Refuses outright if any pending tool call exists at compaction time. """ if tokens_used < threshold: return frontier # no compaction needed pending = [m for m in messages if m.role == "tool_call" and m.status == "pending"] if pending: raise CompactionFrontierError( f"refusing compaction: {len(pending)} pending tool call(s) would be orphaned" ) # Collect the atomic spans of every completed tool transaction. spans: list[tuple[int, int]] = [] seen: set[str] = set() for m in messages: if m.role == "tool_call" and m.call_id and m.call_id not in seen: seen.add(m.call_id) spans.append(_pair_span(messages, m.call_id)) # Snap the frontier backward until it clears every span it would bisect. legal = frontier changed = True while changed: changed = False for lo, hi in spans: if lo < legal <= hi: legal = lo # evict the whole pair rather than split it changed = True if legal != frontier: # Caller must be able to see that the frontier was adjusted. return legal return legal ```