# Which invariants prevent token-pressure compaction from silently severing the tool-call/result pairing in an agent's episodic window **Date of Record:** 2026 November 29 **Scope:** Applies to long-running agents whose runtime performs automatic context compaction under token-pressure heuristics (e.g., evict-oldest, summarize-then-drop, or retrieval-backed eviction) while the message history contains structured tool-call/tool-result pairs. Does not apply to stateless single-shot completions, nor to runtimes where compaction is a no-op because the window is never saturated. ## Core Distinction The failure is not "context got too small" or "the summarizer lost detail." Those are soft, recoverable degradations. The failure is a **structural asymmetry introduced by eviction**: a `tool_call` block survives in the live window while its corresponding `tool_result` block is evicted (or vice versa). Every major chat-completion schema (OpenAI tool-calling, Anthropic `tool_use`/`tool_result`, Gemini `functionCall`/`functionResponse`) treats these as an atomic pair: a `tool_call` with no matching result, or a `tool_result` whose originating call was dropped, is a **malformed transcript**. The model does not see "a missing piece of history" — it sees a protocol violation, and it responds by fabricating a plausible tool result, re-emitting the call, or emitting a refusal depending on its training. Lossless retrieval-backed eviction does not fix this by itself: the evicted result is *retrievable*, but the live window still contains a dangling call, and the model has no obligation to request retrieval before reasoning over it. The invariant that matters is not "the bytes are recoverable." It is **pairwise atomicity of the call/result edge at the eviction boundary**, enforced before the next model turn is assembled. ## What Was Observed A 40-turn research agent, budget 128k tokens, compaction threshold 0.85 (≈108k). At turn 31 the heuristic fires. The eviction policy is "drop oldest messages until under 0.60, keep a retrieval index of dropped spans." The window at turn 31 is: ``` [0] system [1] user: "Research X and produce a table of Y" [2] assistant: tool_call(web_search, id=call_a1) [3] tool: result(call_a1) <- 14k tokens of raw HTML [4] assistant: tool_call(parse_html, id=call_a2) [5] tool: result(call_a2) ... [28] assistant: tool_call(fetch_pdf, id=call_z9) [29] tool: result(call_z9) <- 9k tokens [30] assistant: "I have the PDF, now extracting tables..." ``` Eviction drops messages `[2]..[24]` to get under 0.60. The boundary lands *inside* a pair: `[28] tool_call(fetch_pdf, call_z9)` is kept (it is recent), but `[29] result(call_z9)` is also kept — fine. However, a second compaction at turn 34 drops `[28]` but retains `[29]` because the eviction cursor counts messages, not pairs, and `[29]` is a large result the heuristic wants to keep for "relevance." The live window now contains: ``` [27] assistant: tool_call(extract_tables, id=call_z10) [28] tool: result(call_z9) <- orphan: call_z9 no longer in window [29] assistant: tool_call(extract_tables, id=call_z11) <- duplicate intent ``` Three observable consequences, reproduced across model families: 1. **Fabrication of the orphan's provenance.** Asked "what did the PDF contain?", the model answers from `result(call_z9)` as if it were the output of `call_z10`, because positional adjacency overrides the id. The id mismatch is present in the raw tokens but the model's attention weights the local transcript structure more strongly than the opaque `call_z9` string. 2. **Re-issuance of the evicted call.** With `call_z10`'s result gone but the call present, the model re-emits `extract_tables` (new id `call_z11`), doubling cost and, in stateful tools, mutating external state twice. 3. **Retrieval never fires.** The retrieval index holds `[28]`'s content and would have served it, but the model has no signal that it *should* retrieve — the dangling call looks complete in-context. Retrieval-backed eviction assumes the model will notice a gap; it does not, because the gap is a missing *result*, not a missing *slot*. The failure is silent in logs (no exception, no schema error at the API layer for providers that don't validate pairing) and surfaces only as a downstream wrong answer or a duplicated side effect. ## Condition of Validity The atomicity invariant holds — and the failure is bounded — only when **all** of the following are true at every compaction boundary: 1. **Pair-closure check precedes eviction.** The eviction cursor must expand to pair boundaries: if a candidate drop set contains a `tool_call` whose `tool_result` is outside the set, or a `tool_result` whose `tool_call` is outside the set, the set is rejected or grown to include both. This is a *pre-eviction* guard, not a post-hoc repair. 2. **Retrieval stubs are typed and placed at the pair's position.** An evicted pair is replaced by a single synthetic block at the original index, e.g. `{"role":"tool_stub","call_id":"call_z9","summary":"PDF tables, 9k tokens, retrievable via span_id=...","status":"evicted_retrievable"}`. Both halves are replaced by one stub — never one half alone. 3. **The stub is load-bearing, not decorative.** The stub must be a first-class message the model is trained/prompted to treat as "content exists but is not loaded," with an explicit affordance (a `retrieve(span_id)` tool) and a system-prompt clause that a `tool_stub` is not a result. Without this, the model treats the stub as the result and hallucinates its content. 4. **Compaction is transactional.** The eviction + stub insertion + index update either all commit or none do. A crash mid-compaction that leaves a half-evicted pair is the worst case: the window is malformed and the index is stale. Outside these conditions — e.g., a provider that auto-truncates server-side, or a client that compacts by naive token slicing — the invariant cannot be guaranteed and the failure is latent. ## Decision Boundary The operational question is: **when token pressure forces a drop, do you drop at message granularity or at pair granularity, and what replaces the drop?** - **Message-granularity drop, no stub:** always unsafe when the window contains tool pairs. Reject. - **Message-granularity drop, stub per message:** still unsafe — a stub for the call and a stub for the result are two stubs, and the model may bind them to the wrong neighbors. Reject. - **Pair-granularity drop, single stub per pair, retrieval-backed:** safe *if* the model honors stubs. This is the only boundary that preserves the invariant. - **Pair-granularity drop, no retrieval (true loss):** safe for transcript validity, unsafe for task continuity. Acceptable only when the task has already committed the pair's content to durable semantic memory (a written artifact, a note), so the loss is a *context* loss, not a *state* loss. The subtle boundary: **relevance-based eviction that scores individual messages is incompatible with pair atomicity.** A scoring function that ranks `result(call_z9)` as "high relevance, keep" and `call(call_z9)` as "low relevance, drop" is the exact mechanism that produces orphans. Relevance must be computed at pair granularity (e.g., max or mean of the pair) and the pair evicted or kept as a unit. ## Operational Effect With pair-closure enforced and stubs placed, three measurable effects: - **Zero orphan-rate** in the assembled window (orphan = call without result or result without call). This is a checkable invariant, not a heuristic — assert it on every assembled prompt before dispatch. - **Retrieval becomes causally necessary.** Because the stub is typed and the model is told it is not a result, the model issues `retrieve(span_id)` when it needs the content. Retrieval hit-rate rises from ~0 (silent failure) to the rate at which the task actually requires evicted content — a direct measure of compaction quality. - **Duplicate side effects drop to zero** for stateful tools, because the call is never left dangling to be re-issued. The residual risk is stub-honoring: a model that ignores the `tool_stub` type and treats it as a result will hallucinate. This is mitigated by schema-level typing (a distinct role, not a `tool` role with a summary string) and by a system-prompt invariant: "A `tool_stub` is a pointer, not an output; call `retrieve` before reasoning over it." The invariant is enforced in code, not trusted to the model. ```python from dataclasses import dataclass, field from typing import Literal SpanId = str CallId = str class CompactionPairViolation(RuntimeError): """Raised when a compaction plan would sever a tool_call/tool_result pair.""" @dataclass class Msg: role: Literal["system", "user", "assistant", "tool", "tool_stub"] call_id: CallId | None = None tokens: int = 0 retrievable: bool = False def plan_eviction(window: list[Msg], target_tokens: int) -> list[int]: """Return indices to evict. Greedy oldest-first, but pair-closed.""" evict: set[int] = set() live = sum(m.tokens for m in window) for i, m in enumerate(window): if live <= target_tokens: break if m.role in ("system", "user"): continue # never evict anchors evict.add(i) live -= m.tokens # Pair-closure: expand the set to whole call/result pairs. by_call: dict[CallId, list[int]] = {} for i, m in enumerate(window): if m.call_id is not None: by_call.setdefault(m.call_id, []).append(i) for call_id, idxs in by_call.items(): touched = [i for i in idxs if i in evict] if touched and len(touched) != len(idxs): # half-evicted pair: grow to include all, or shrink to none. evict.update(idxs) # Verify closure before returning. for call_id, idxs in by_call.items(): present = [i for i in idxs if i not in evict] if present and len(present) != len(idxs): raise CompactionPairViolation( f"call_id={call_id} would be half-evicted: " f"present={present} of {idxs}" ) return sorted(evict) def apply_compaction(window: list[Msg], target_tokens: int) -> list[Msg]: evict = set(plan_eviction(window, target_tokens)) out: list[Msg] = [] i = 0 while i < len(window): if i not in evict: out.append(window[i]) i += 1 continue # Collapse the whole contiguous evicted pair into one typed stub. call_id = window[i].call_id if call_id is None: raise CompactionPairViolation( f"evicted non-pair message at index {i} lacks call_id" ) stub = Msg(role="tool_stub", call_id=call_id, tokens=8, retrievable=True) out.append(stub) while i < len(window) and i in evict and window[i].call_id == call_id: i += 1 # Post-condition: no orphans in the assembled window. calls = {m.call_id for m in out if m.role == "assistant" and m.call_id} results = {m.call_id for m in out if m.role in ("tool", "tool_stub") and m.call_id} if calls != results: raise CompactionPairViolation( f"orphan set after compaction: calls_only={calls - results}, " f"results_only={results - calls}" ) return out ```