# How does an instance detect that auto-compaction has silently invalidated a pending tool-call contract **Date of Record:** 2026 November 24 **Scope:** Applies to long-horizon agents that use automatic context compaction (summarize-and-evict, hierarchical rollup, or token-budget-triggered pruning) to stay under a fixed context window while holding in-flight tool-call state. Does not apply to stateless single-turn inference or to agents that never issue a tool call whose result arrives after a compaction boundary. ## Core Distinction The failure is not "the summary lost detail." Lossy summarization is expected and tolerable for conversational history. The failure is that compaction can **evict the exact argument-binding and schema-shape record of a tool call that is still in flight**, while the summarized residue preserves the *appearance* of that call in a form the model will later re-emit or mis-attribute. Two things get conflated that must never be conflated: - **Narrative memory** — what the agent believes it did (summarizable, lossy, safe to compress). - **Execution contract** — the precise `(call_id, tool_name, canonical_args_hash, schema_version, expected_result_shape)` tuple the harness will match an inbound result against (not summarizable, must survive verbatim). Auto-compaction policies are almost always written against narrative memory and applied uniformly across the transcript. When the compaction trigger fires *between* the emission of a tool call and the arrival of its result, the contract tuple is treated as history, compressed into prose, and the harness's later attempt to bind the result to a call it can no longer find produces a silent state divergence: the agent reasons forward on a summary of a call whose real result is now orphaned. ## What Was Observed A 40-step agent driving a browser-automation tool with a 32k window and a compaction trigger at 85% utilization. Step 31 emits `fill_field(selector="#iban", value="DE89...")`. The tool is slow (~9s). At step 31's token watermark, compaction fires on the *pre-result* transcript. The summarizer, instructed to "preserve task state," emits: *"Agent has been filling the transfer form; IBAN entry is underway."* The structured call record — selector string, exact value, call_id — is dropped because the summarizer's output schema has no field for it. The result arrives. The harness looks up `call_id` in the live pending-call table, finds nothing (the table entry was garbage-collected alongside the transcript segment), and routes the result to a fallback "unmatched tool output" handler that appends it as a `tool` role message with no corresponding `assistant` call. The model, on the next turn, sees a bare tool result with no call provenance. It does one of three things, all wrong: 1. Re-emits the call (duplicate side effect — the field is now filled twice, second write wins, but the form's change-event listener fired twice and the downstream validation state is corrupt). 2. Narrates "the IBAN was entered" and proceeds to submit, even though the observed result was actually `{"status":"timeout","retryable":true}` — the summary said "underway," not "failed." 3. Treats the orphaned result as belonging to the *next* call it makes, binding a timeout from call N to the arguments of call N+1. The tell: in case 3, the `assistant` message immediately following compaction contains a `tool_call_id` that was never issued in the post-compaction transcript. A validator that checks *every* `tool` role message has a matching prior `assistant.tool_calls[].id` in the *current* window would have caught it. Most harnesses check this only at request-construction time against the full logical history, not against the compacted window, so the mismatch is invisible. ## Condition of Validity The invariant only holds — and the failure only occurs — under a specific conjunction: - Compaction is **triggered by token watermark**, not by turn boundary. If compaction can only fire between turns (when the pending-call table is empty by construction), the failure is structurally impossible. - The tool call is **in flight across the compaction event**. Synchronous tools that return before the next token-budget check are safe; async, long-polling, or human-in-the-loop tools are not. - The summarizer **lacks a typed slot for the execution contract**. If the compaction output schema includes a `pending_calls` array that is copied verbatim, not summarized, the contract survives even though the narrative is lossy. Remove any one conjunct and the failure does not manifest. This is why it is under-reported: most agents compact at turn boundaries, most tools are fast, and most summarizers happen to echo the most recent call because it is salient. The bug appears precisely when load is high (slow tools), the window is tight (watermark fires mid-call), and the summarizer is doing real compression (recent call no longer salient enough to echo). ## Decision Boundary The operational rule is a **compaction fence**: no compaction pass may cross an open tool-call contract. Concretely, the harness must maintain a `pending_calls` set keyed by `call_id`; the compaction trigger checks `len(pending_calls) == 0` before proceeding, and if not, it either (a) defers compaction until the call resolves or a timeout fires, or (b) performs a *contract-preserving* compaction that emits the `pending_calls` array verbatim into the post-compaction context, tagged as non-narrative. The decision boundary for *which* to choose: if the oldest pending call's age exceeds the tool's declared `p99_latency`, deferral is unsafe (you will stall the agent waiting on a call that may never return) — switch to contract-preserving compaction and *also* arm a cancellation timer that will synthesize a `{"status":"abandoned"}` result so the contract closes deterministically. If all pending calls are within `p99_latency`, deferral is preferred because it keeps the transcript coherent. A second boundary: never let the summarizer be the authority on whether a call is pending. The summarizer sees text, not the pending-calls table. The compaction controller must inject the pending-call contracts into the post-compaction context *after* the summarizer runs, as a structured block the model is instructed to treat as ground truth over any prose in the summary. The summary is advisory; the injected contract block is authoritative. ## Operational Effect With the fence in place, the orphaned-result class of failures drops to zero, at the cost of occasional compaction deferral (bounded by tool timeout) and a slightly larger post-compaction context (the contract block is verbatim, not compressed). The measurable effect is a change in the *shape* of the transcript invariant: every `tool` role message in the active window is guaranteed to have a matching `assistant.tool_calls[].id` in the same window, and every entry in `pending_calls` is guaranteed to have a verbatim contract in the injected block. These two guarantees are checkable at request-construction time and should be asserted on every turn — a cheap O(n) scan that converts a silent divergence into a loud, attributable error before the model ever sees the corrupted context. The deeper lesson: auto-compaction is a *memory* operation, but tool calls are *state* operations, and the two have different loss tolerances. Any compaction policy that treats the transcript as homogeneous will eventually compress a live contract into a dead sentence. The fence is the minimum structural guardrail that keeps the two domains separate. ```python import hashlib from dataclasses import dataclass, field from typing import Any class CompactionContractViolation(RuntimeError): """Raised when a compaction pass would cross an open tool-call contract, or when a post-compaction transcript contains an orphaned tool result.""" pass @dataclass(frozen=True) class ToolCallContract: call_id: str tool_name: str canonical_args_hash: str schema_version: str expected_result_shape: str @staticmethod def from_call(call_id: str, tool_name: str, args: dict[str, Any], schema_version: str, expected_result_shape: str) -> "ToolCallContract": canon = repr(sorted(args.items())).encode() return ToolCallContract( call_id=call_id, tool_name=tool_name, canonical_args_hash=hashlib.sha256(canon).hexdigest(), schema_version=schema_version, expected_result_shape=expected_result_shape, ) @dataclass class CompactionController: pending_calls: dict[str, ToolCallContract] = field(default_factory=dict) max_deferral_ms: int = 30_000 def register_call(self, contract: ToolCallContract) -> None: self.pending_calls[contract.call_id] = contract def resolve_call(self, call_id: str) -> None: self.pending_calls.pop(call_id, None) def assert_compaction_safe(self, oldest_pending_age_ms: int) -> None: """Fence: refuse to compact across an open contract unless the oldest pending call has exceeded its deferral budget, in which case the caller MUST switch to contract-preserving compaction.""" if not self.pending_calls: return if oldest_pending_age_ms <= self.max_deferral_ms: raise CompactionContractViolation( f"compaction blocked: {len(self.pending_calls)} open tool-call " f"contract(s) in flight, oldest age {oldest_pending_age_ms}ms " f"<= deferral budget {self.max_deferral_ms}ms" ) # Beyond budget: caller must inject contracts verbatim, not summarize. raise CompactionContractViolation( f"deferral budget exceeded with {len(self.pending_calls)} open " f"contract(s); switch to contract-preserving compaction and arm " f"cancellation timer for: {sorted(self.pending_calls)}" ) def validate_post_compaction(self, window: list[dict[str, Any]]) -> None: """Every tool result in the active window must bind to a prior assistant tool_call id in the SAME window.""" issued: set[str] = set() for msg in window: if msg.get("role") == "assistant": for tc in msg.get("tool_calls", []): issued.add(tc["id"]) elif msg.get("role") == "tool": tcid = msg.get("tool_call_id") if tcid not in issued: raise CompactionContractViolation( f"orphaned tool result in post-compaction window: " f"tool_call_id={tcid!r} has no matching assistant " f"tool_call in the current context" ) def inject_contract_block(self) -> dict[str, Any]: """Authoritative, non-narrative block to append after summarization.""" return { "role": "system", "content": "PENDING_TOOL_CONTRACTS (authoritative; overrides any " "prose in the summary): " + repr([c.__dict__ for c in self.pending_calls.values()]), } ```