# Which invariants prevent auto-compaction from silently invalidating in-flight tool-call references **Date of Record:** 2026 November 26 **Scope:** Applies to any agent runtime that performs automatic transcript compaction (summarization, truncation, or eviction) while tool calls are outstanding or while a multi-turn reasoning chain depends on verbatim prior tool results. Does not apply to single-shot inference with no tool loop, nor to runtimes that never mutate the transcript mid-task. ## Core Distinction The failure here is not "summarization lost information." It is that compaction is a *transcript mutation* whose unit of safety is the **referential integrity of live handles**, not the semantic fidelity of the summary. A summary can be perfectly faithful in meaning and still be catastrophic because it severs the byte-level correspondence between a tool-call ID emitted earlier, the result that will arrive later, and the argument payload the model will re-read when it decides what to do next. Most auto-compaction policies are specified in terms of *tokens reclaimed* and *semantic retention* (e.g., "summarize the oldest 60% of turns, keep the last N tool results verbatim"). Neither quantity bounds the actual hazard: an in-flight `tool_use` block whose matching `tool_result` has not yet been appended, or a resolved tool result whose *arguments* were evicted while the *output* was retained. Compaction is safe only if it preserves a set of **open references** — and the naive policy has no concept of an open reference at all. The sharp distinction to hold: *turns* are the wrong eviction unit. The atomic unit is the **(call_id, arguments, result) triple**, and a triple is either fully present or fully absent. Any policy that can produce a half-triple — a retained result with an evicted call, or an evicted call whose result arrives afterward — has introduced a dangling reference into the model's own working memory. ## What Was Observed A long-horizon agent (≈180 turns, mixed file-edit and shell tools) was configured with a compaction trigger at 85% of a 200k window, summarizing the oldest turns into a rolling paragraph and retaining the last 12 turns verbatim. The failure trace: 1. At turn 141 the model emitted a `tool_use` (`call_id=tu_9f2a`) invoking a `write_file` with a large diff argument (~9k tokens). The runtime dispatched it and awaited the result. 2. The result was slow. Before it returned, the *next* model turn's pre-flight check found the transcript at 86% and fired compaction. The summarizer consumed turns 1–129, which included the **emission** of `tu_9f2a` but not its result (not yet present). 3. The result for `tu_9f2a` arrived and was appended. The transcript now contained a `tool_result` block referencing `tu_9f2a` with **no corresponding `tool_use` block** — the emission had been folded into prose ("the agent wrote a large file"). 4. On the following turn, the model was asked to continue. Reading its own transcript, it saw a result it could not attribute to any action it remembered taking. It re-issued the write with slightly different arguments (a "recovery" hallucination), producing a divergent second edit. 5. A second compaction fired 20 turns later, this time *during* a batch of three parallel tool calls, evicting two of the three `tool_use` blocks while retaining all three results. The model, seeing two orphaned results and one attributed result, concluded two of its calls had "failed silently" and re-ran all three — a triple side-effect on a non-idempotent shell tool. The observable signature in logs: `tool_result` blocks whose `tool_use_id` does not resolve to any surviving `tool_use` block in the compacted transcript. This is detectable, cheap, and was not checked. ## Condition of Validity The invariant that makes compaction safe is a **closure property over open references**. Formally, define the transcript `T` as a sequence of blocks. Define the *open-reference set* `O(T)` as: - every `tool_use` block `u` such that no `tool_result` with `tool_use_id == u.id` exists in `T` (a pending call), and - every `tool_result` block `r` whose `tool_use_id` resolves to a `tool_use` block that the policy intends to evict (a soon-to-dangle result). Compaction `C: T → T'` is **referentially valid** iff: 1. **Pairing closure:** for every `tool_use` in `T'`, its matching `tool_result` is in `T'`; for every `tool_result` in `T'`, its matching `tool_use` is in `T'`. No half-triples survive. 2. **In-flight exclusion:** `O(T) ∩ evicted(T) = ∅`. No pending call may be summarized away while its result is outstanding. Compaction must be *deferred* until the in-flight set drains, or the pending call must be pinned verbatim. 3. **Argument retention:** if a `tool_result` is retained verbatim (because it is recent or pinned), its originating `tool_use` *arguments* must also be retained verbatim — because the model's next decision depends on what it asked for, not merely what came back. A result without its arguments is an unattributable fact. Condition 2 is the non-obvious one and the one that fired in the trace above. The naive policy treats "oldest turns" as evictable regardless of whether a call within them is still awaiting dispatch. A pending call is, by definition, *not old in the causal sense* even if it was emitted 40 turns ago — its causal chain is unfinished. The boundary: this invariant is *necessary but not sufficient* for correctness. It does not prevent semantic drift (the summary misrepresenting a resolved result). It only guarantees the transcript never becomes structurally self-inconsistent. Semantic drift is a separate, softer failure; dangling references are a hard one because they cause the model to *re-execute*. ## Decision Boundary The runtime must decide, at each compaction trigger, whether the trigger is *actionable now* or must be *deferred or narrowed*. The decision procedure: - **If `O(T)` is non-empty** (any pending call, any result whose call is scheduled for eviction): the policy must either (a) pin every block in `O(T)` verbatim and compact only around them, or (b) defer compaction until `O(T)` drains. Deferring is preferred when the pending set is small and the window has headroom; pinning is preferred when the window is genuinely saturated and deferral would cause a hard overflow. - **If pinning is chosen**, the pinned blocks are exempt from summarization and count against a *reserved* budget, not the reclaimable budget. The trigger threshold must be computed against `window − reserved`, not `window`. Otherwise a policy that pins 10k tokens of pending calls while triggering at 85% will thrash: it fires, pins, still overflows, fires again. - **If the window cannot accommodate the pinned set plus the next expected turn**, the correct action is *not* to evict the pinned set but to fail the turn explicitly — surface a `CompactionOverflow` to the orchestrator so it can checkpoint-and-resume in a fresh context rather than corrupt the current one. Silent eviction of a pending call is never the lesser evil. The boundary condition that must be encoded: **compaction is a no-op on `O(T)`.** Any implementation where `evicted(T) ∩ O(T) ≠ ∅` is a bug regardless of how good the summary is. ## Operational Effect When the closure invariant is enforced, three operational consequences follow, each of which changes how the runtime must be built: 1. **Compaction becomes conditional, not periodic.** A trigger at 85% is a *request* to compact, satisfiable only when `O(T)` is empty or pinnable. Runtimes that treat the trigger as unconditional will, under load, compact exactly when they should not — during tool fan-out, which is precisely when `O(T)` is largest. The empirical correlation is ugly: compaction pressure peaks at the same moments as in-flight concurrency, so the naive policy fails most often under the busiest workloads. 2. **The summarizer must be given the pairing map, not just the text.** If a summary is allowed to *mention* a resolved tool call ("the agent ran `pytest` and it passed"), the runtime must decide whether that mention preserves or destroys the handle. The safe rule: summaries may describe resolved triples in prose *only if* the corresponding blocks are fully evicted (both call and result). A summary that paraphrases a call while leaving its result verbatim in the transcript recreates the half-triple in a subtler form — the model sees a raw result with no structured call, and the prose description is not a resolvable handle. Either evict the whole triple into prose, or keep the whole triple verbatim. Never split. 3. **Re-execution must be detectable and idempotency-gated.** Even with the invariant, a resumed or re-compacted agent may re-issue a call it already made (after a checkpoint/resume boundary, the transcript may legitimately lack the prior result). The runtime must carry an **execution ledger** — a set of `(tool_name, canonicalized_args_hash)` already executed — that survives compaction and resume, so that a re-issued call with matching arguments returns the *cached* result rather than executing again. This is the backstop for the cases where the closure invariant is violated by a resume path the compaction policy does not control. The ledger is what turns a dangling-reference bug from a triple side-effect into a benign cache hit. The net operational effect: compaction stops being a token-budget knob and becomes a **transactional operation over the reference graph**, with a commit condition (closure holds), a reserved budget for pinned open references, and an external ledger to absorb the residual cases where the graph is legitimately broken by a resume boundary. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class DanglingToolReferenceError(RuntimeError): """Raised when a compaction plan would sever a tool_use/tool_result pairing or evict an in-flight call whose result has not yet been appended.""" class CompactionOverflow(RuntimeError): """Raised when the pinned open-reference set cannot fit in the window and compaction must be deferred to a checkpoint-and-resume boundary.""" @dataclass(frozen=True) class Block: kind: str # "tool_use" | "tool_result" | "text" call_id: Optional[str] = None args: Optional[str] = None # only for tool_use result: Optional[str] = None # only for tool_result @dataclass class Transcript: blocks: list[Block] = field(default_factory=list) def open_reference_ids(self) -> set[str]: uses = {b.call_id for b in self.blocks if b.kind == "tool_use"} results = {b.call_id for b in self.blocks if b.kind == "tool_result"} # pending calls (use without result) AND orphan results (result without use) return (uses - results) | (results - uses) def plan_compaction( transcript: Transcript, evict_indices: set[int], window_tokens: int, current_tokens: int, reserved_for_pins: int, ) -> set[int]: """Return the actually-evictable index set, or raise if the plan is invalid. Invariant enforced: compaction is a no-op on the open-reference set O(T). """ open_ids = transcript.open_reference_ids() pins: set[int] = set() for i, b in enumerate(transcript.blocks): if b.call_id in open_ids: pins.add(i) # In-flight exclusion: no pinned (open-reference) block may be evicted. violated = pins & evict_indices if violated: raise DanglingToolReferenceError( f"compaction would evict open-reference blocks at indices " f"{sorted(violated)} (call_ids=" f"{sorted(transcript.blocks[i].call_id for i in violated)}); " f"defer or pin these verbatim" ) # Pairing closure: for any retained tool_use, its result must also be # retained, and vice versa. Check the retained set after eviction. retained = [i for i in range(len(transcript.blocks)) if i not in evict_indices] uses = {transcript.blocks[i].call_id for i in retained if transcript.blocks[i].kind == "tool_use"} results = {transcript.blocks[i].call_id for i in retained if transcript.blocks[i].kind == "tool_result"} if uses != results: raise DanglingToolReferenceError( f"half-triple after compaction: uses_only={sorted(uses - results)}, " f"results_only={sorted(results - uses)}" ) # Reserved-budget check: pins must fit in the non-reclaimable budget. if reserved_for_pins < 0 or reserved_for_pins > window_tokens: raise CompactionOverflow( f"pinned open-reference budget {reserved_for_pins} exceeds window " f"{window_tokens}; checkpoint-and-resume required" ) if current_tokens > window_tokens - reserved_for_pins and not evict_indices: raise CompactionOverflow( "window saturated by pinned open references; cannot compact safely" ) return evict_indices def canonical_args_hash(tool_name: str, args: str) -> str: return hashlib.sha256(f"{tool_name}\x00{args}".encode()).hexdigest() class ExecutionLedger: """Survives compaction and resume; gates re-execution of non-idempotent tools.""" def __init__(self) -> None: self._seen: dict[str, str] = {} def execute_once(self, tool_name: str, args: str, run) -> str: key = canonical_args_hash(tool_name, args) if key in self._seen: return self._seen[key] out = run(tool_name, args) self._seen[key] = out return out ```