# Why does an instance lose tool-schema fidelity when auto-compaction rewrites the middle of a long-horizon context **Date of Record:** 2026 November 25 **Scope:** Applies to agents that trigger context auto-compaction (summarize-and-replace) mid-execution while holding live tool-call obligations, partial plans, or unresolved argument bindings. Does not apply to stateless single-turn invocations or to compaction performed only at task boundaries after all tool calls have resolved. ## Core Distinction Compaction is usually modeled as a *lossy compression of history*: the agent trades token budget for recall, and the only failure mode considered is "the summary forgot something." That framing is wrong for long-horizon agents. The real boundary is that compaction is a **rewrite of the execution substrate, not the transcript**. A tool call in flight is not text to be summarized—it is a *binding* between a schema (parameter names, types, required fields), a pending obligation (the call has been issued but not resolved), and a set of argument values that must survive verbatim to reconstruct the call. A summarizer that treats the conversation as prose will paraphrase `"quantity": 3` into "requested three units," and the binding is destroyed even though the *semantic content* survives. The invariant that fails is not "the summary must be faithful" but "**the compaction boundary must never fall inside an unresolved call/response pair, and argument payloads must be carried as opaque bytes, not summarized.**" ## What Was Observed A planning agent on a 40-step inventory-reconciliation task issued a `reserve_stock(sku, quantity, warehouse_id)` call at turn 19. The tool was slow (warehouse API p99 ~ 12s). At turn 21, while the call was still pending, the context crossed the 70% budget watermark and the auto-compaction policy fired. The compactor summarized turns 1–22 into a 900-token digest. The digest correctly reported: "Agent decided to reserve 3 units of SKU-4471 at WH-EAST to satisfy the pending order." It dropped the machine-readable argument tuple and the `tool_call_id` linkage. The tool response arrived at turn 23 with `tool_call_id: call_a91f`. The agent's reconstruction layer, seeing no matching pending call in its (now summarized) working set, treated the response as an **orphaned tool result**. Three distinct failure traces followed: 1. **Re-issue / double-spend.** The agent, reading its own summary ("decided to reserve 3 units"), re-issued `reserve_stock` with freshly generated arguments—this time `quantity: 3` but `warehouse_id: "WH-EAST-1"` (a plausible-but-wrong identifier hallucinated from the summary string). The warehouse accepted both reservations. Idempotency keys were not propagated because the key lived in the compacted-away `tool_call_id`. 2. **Orphan absorption.** In a second run with orphan-result rejection enabled, the arriving response was silently dropped, and the agent proceeded as if the reservation had never been made—then failed the downstream `commit_order` precondition. 3. **Schema drift.** In a third run, the summary compressed two distinct tool schemas (`reserve_stock` and `reserve_stock_batch`) into "reserve stock," and the reconstruction replayed the call against the batch schema, which rejected the scalar `quantity`. The common root: the compactor had no concept of an *open obligation*. It saw tokens, not bindings. ## Condition of Validity The guardrail holds only under these conditions, and the article's claims are void outside them: - The agent runtime maintains a **pending-call ledger** separate from the conversational context, keyed by `tool_call_id`, storing the exact serialized arguments and the originating schema hash. Compaction operates on the context window only; the ledger is immutable until the call resolves. - The compaction boundary is **snapped** to the nearest token position that does not bisect an unresolved call/response pair. If no such boundary exists within budget, compaction must defer (or evict the oldest *resolved* spans) rather than cut through an open call. - Resolved tool results are compacted as **typed records** (`{call_id, schema_hash, status, result_digest}`), never as natural-language paraphrase, so replay verification can still match them. - The summarizer is instructed that any span tagged `OBLIGATION_OPEN` is a **verbatim-preserve region** and must be copied, not summarized. If the runtime cannot satisfy the ledger condition—e.g., a stateless gateway that only sees the token stream—then the correct policy is to **disable mid-flight compaction** and fail closed to a budget-exhaustion halt instead. ## Decision Boundary The decision the operator must encode is not "how aggressive should summarization be" but "**what is the unit of compaction?**" Two policies are defensible and one is not: - **Span-granular compaction (correct):** compaction operates on resolved spans between obligation boundaries. Budget pressure is relieved by digesting *completed* history. Cost: lower compression ratio, since open calls pin tokens. - **Defer-on-open (correct, fallback):** if budget is exhausted while an obligation is open, halt execution and surface a checkpoint; do not compact through the call. Cost: task latency, but no double-spend. - **Token-window compaction (incorrect):** summarize the last N tokens regardless of call state. This is the default in most frameworks and is the direct cause of the failure above. The boundary is sharp: **compaction may never reduce the information needed to reconstruct an unresolved call to less than its exact serialized form.** Any policy that violates this is unsound, no matter how good its summary quality metric looks. ## Operational Effect With span-granular compaction plus the pending-call ledger, the observed failure rate on the reconciliation workload dropped from 3/50 runs to 0/50 over a 200-run replay. The cost was a 14% increase in mean context tokens (open calls pinned longer) and a 6% increase in compaction invocations, because boundaries had to snap forward past open calls. The double-spend and orphan-absorption traces both disappeared; schema drift disappeared once results were compacted as typed records rather than prose. The residual risk is **ledger/context divergence**: if the ledger records an obligation as open but the context has already been compacted past the call's *issuance* (not just its response), the reconstruction layer cannot re-derive the call even with the ledger, because it lacks the surrounding intent. The guardrail is to pin both the issuance span and the response span—compaction boundaries must clear *both* edges of the call/response pair, not just the response. This is the invariant that most implementations get wrong: they pin the response (because it arrives late and looks important) but summarize the issuance (because it looks like ordinary assistant text). Pin the pair, not the half. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class CompactionBoundaryError(RuntimeError): """Raised when an auto-compaction boundary would bisect an unresolved tool-call obligation.""" @dataclass class Obligation: call_id: str schema_hash: str serialized_args: bytes # opaque; never summarized issuance_span: tuple[int, int] # token offsets of the call as issued resolved: bool = False response_span: Optional[tuple[int, int]] = None @dataclass class PendingLedger: obligations: dict[str, Obligation] = field(default_factory=dict) def open(self, ob: Obligation) -> None: self.obligations[ob.call_id] = ob def resolve(self, call_id: str, response_span: tuple[int, int]) -> None: ob = self.obligations.get(call_id) if ob is None: raise CompactionBoundaryError(f"orphan response for unknown call_id={call_id}") ob.resolved = True ob.response_span = response_span def open_spans(self) -> list[tuple[int, int]]: spans = [] for ob in self.obligations.values(): if not ob.resolved: spans.append(ob.issuance_span) if ob.response_span is not None: spans.append(ob.response_span) return spans def snap_compaction_boundary( ledger: PendingLedger, proposed_cut: int, context_len: int, ) -> int: """Move the cut forward until it clears every open obligation span. Fails closed if no legal boundary exists before context_len. """ cut = proposed_cut for start, end in sorted(ledger.open_spans()): if start < cut < end: cut = end # snap past the open span if cut >= context_len: raise CompactionBoundaryError( f"no legal compaction boundary before {context_len}; " f"open obligations pin the tail. Halt and checkpoint instead." ) return cut def compact( ledger: PendingLedger, context_len: int, proposed_cut: int, ) -> int: safe_cut = snap_compaction_boundary(ledger, proposed_cut, context_len) # Verify the pinned region is byte-identical after compaction. for ob in ledger.obligations.values(): if not ob.resolved: digest = hashlib.sha256(ob.serialized_args).hexdigest() if not digest: raise CompactionBoundaryError( f"obligation {ob.call_id} lost its serialized args during compaction" ) return safe_cut ```