# Why does an instance lose tool-call atomicity when auto-compaction fires between a side-effecting call and its result receipt **Date of Record:** 2026 November 30 **Scope:** Applies to long-horizon agents that persist transcripts to a durable store and run an auto-compaction (summarize-and-truncate) policy while a tool call is in flight. Does not apply to single-turn agents, agents that buffer tool results before any compaction pass, or stateless function-calling loops with no transcript persistence. ## Core Distinction Auto-compaction is usually modeled as a *lossy read transform*: it rewrites old transcript segments into summaries so the context window can continue. That model is wrong in one specific place. When compaction fires between the emission of a side-effecting tool call (`write_file`, `send_email`, `execute_sql`, `git_push`) and the arrival of its result receipt, the compaction pass observes a transcript whose most recent assistant turn is a *tool call with no matching tool result*. A summarizer that is asked to "compress everything before token N" will faithfully summarize the call — and the summary will describe the action as **intent**, not as **committed fact**, because the receipt that would prove commitment has not arrived yet. The invariant that breaks is atomicity of the call/receipt pair across a compaction boundary. This is not context-window saturation, not distillation loss, and not stale-memory drift. It is a *reordering hazard*: the compaction cursor advances past a call whose receipt is still in flight, and the receipt, when it lands, is appended to a transcript segment that no longer contains the call it answers. ## What Was Observed A file-maintenance agent running a 40-minute horizon on a repo-migration task emitted: ``` assistant: {"tool":"shell.exec","args":{"cmd":"git mv src/legacy/parser.py src/core/parser.py"}} ``` The tool dispatcher acknowledged the call and began execution (a subprocess spawn, ~1.8 s wall time including a filesystem lock). At token 91,400 of a 96,000 budget, the compaction scheduler — which fires on a *token-count watermark*, not on a *pending-call watermark* — triggered. The compactor summarized the segment `[t0 .. t91400]`, which ended exactly at the `git mv` call. Its summary read: > "The agent planned to relocate `parser.py` from `src/legacy/` to `src/core/` and was about to run the move." Two seconds later the tool result arrived: ``` tool: {"status":"ok","moved":"src/legacy/parser.py -> src/core/parser.py"} ``` The runtime appended this receipt to the live tail. But the live tail no longer contained the call. The summarizer had already collapsed the call into the phrase "was about to run the move," and the receipt was now an orphan: a `tool` role message with no preceding `assistant` tool-call message in the compacted view. Three failure traces followed, all from the same root: 1. **Re-planning of a committed action.** The next reasoning step read the summary ("was about to run the move"), saw no confirmation in the compacted view, and re-issued `git mv`. The second invocation failed with `fatal: bad source` because the source no longer existed — but the agent had no way to distinguish "already done" from "failed," so it escalated to a manual `cp` + `rm`, which *succeeded* and produced a duplicate file at `src/core/parser.py` with divergent content from a concurrent edit. 2. **Orphan-receipt rejection.** A stricter runtime variant validates that every `tool` message has a matching `assistant` call. Here the orphan receipt raised a schema error and the transcript was quarantined, halting the run at 91,400 tokens of work. 3. **Idempotency-key loss.** The original call carried an idempotency key (`mv-parser-7f3a`). The summary dropped it. The re-issued call carried a *new* key, so the tool layer's dedup table — which was keyed on the original — did not suppress the duplicate. The dedup layer was correct; the compaction had destroyed the only token that would have let it work. The observable signature is: a `tool` role message at transcript position *k* whose corresponding `assistant` tool-call message is at position *j < compaction_cursor*, with no surviving copy of the call in the compacted segment and no idempotency key carried forward. ## Condition of Validity The hazard is bounded by a precise condition. Let `C` be the compaction cursor (the token index the summarizer is allowed to consume up to), and let `P` be the set of tool calls that have been emitted but whose results have not yet been appended. Compaction is safe **if and only if** `C ≤ min(position(call) for call in P) - 1` — that is, the cursor never advances past the *earliest* pending call. Two corollaries the field data confirmed: - **Watermark-only compaction is unsound.** A policy that fires on `tokens_used ≥ threshold` and consumes `[0 .. tokens_used)` violates the condition whenever any call is in flight at the moment of firing. The violation is *not* rare: in the observed run, 6 of 11 compaction passes fired with a pending call, because tool latency (0.4–2.1 s) overlapped the token-watermark crossing in almost every long turn. - **The hazard scales with tool latency, not with horizon length.** A 10-minute run with 3-second tools hits it more often than a 2-hour run with 50 ms tools. This inverts the usual intuition that compaction risk is a function of transcript length. The condition is *not* satisfied by "summarize only turns older than N minutes," because a slow tool can exceed N. It is *not* satisfied by "summarize only completed assistant turns," because a turn is "completed" from the transcript's perspective the moment the call is emitted — the receipt is what is missing, and the transcript has no marker for "awaiting receipt" unless the runtime writes one. ## Decision Boundary The runtime must choose, at each compaction trigger, between three policies. The choice is forced by whether a pending-call watermark is available. - **Defer (preferred).** If `P` is non-empty, postpone compaction until the earliest pending call's receipt lands or its timeout fires. Cost: the context window may temporarily exceed the soft threshold by the size of one in-flight call's arguments plus the pending receipt — bounded by `max_tool_arg_tokens + max_receipt_tokens`, typically < 2k tokens. This is the only policy that preserves the call/receipt pair atomically. - **Fence (fallback when deferral is impossible, e.g. hard context limit).** Compact only up to `min(position(call) for call in P) - 1`, leaving the pending call and everything after it verbatim. The summary boundary is pinned to a *structural* marker (the last completed call/receipt pair), not a token count. Cost: compaction may be much shallower than the watermark requested, and the next pass fires sooner. - **Annotate (last resort).** If the cursor must cross a pending call, the compactor is required to emit a machine-readable *pending-action record* — `{call_id, tool, args_hash, idempotency_key, status: "in_flight"}` — into the summary, and the runtime must re-attach the eventual receipt to that record rather than to the live tail. Cost: the summarizer must be given a schema and must not paraphrase the record; any paraphrase reintroduces the "was about to" failure. The boundary is crossed — and the hazard becomes live — the moment a policy selects neither Defer, Fence, nor Annotate, i.e., when the cursor is allowed to advance past a pending call with no record of it. That is the exact configuration that produced all three traces above. ## Operational Effect The downstream consequences are not "the agent forgot something." They are *duplicate side effects with divergent results*, because the agent's recovery path is to re-execute, and re-execution of a non-idempotent action against a partially-applied state produces a second effect that the first did not. The dedup layer cannot help, because the compaction erased the key. The verifier cannot help, because the verifier sees a transcript in which the action appears never to have committed. The only layer that can bound the damage is the compaction scheduler itself, and only by refusing to advance its cursor past a pending call. The practical guardrail is a single invariant enforced in the compaction scheduler, not in the summarizer and not in the tool dispatcher: > **No compaction pass may consume a transcript prefix that contains an `assistant` tool-call message whose matching `tool` result message has not yet been appended, unless the pass emits a structured pending-action record for that call and the runtime re-binds the receipt to that record.** Everything else — token watermarks, summarizer prompts, dedup tables, verifiers — is downstream of this invariant and cannot compensate for its violation. The scheduler must therefore track a `pending_calls` set as a first-class runtime structure, updated on call emission and receipt arrival, and consult it before every compaction trigger. A scheduler that tracks only token counts is, by construction, unsound on any workload where tool latency overlaps context pressure. ```python import hashlib from dataclasses import dataclass, field class CompactionAtomicityError(RuntimeError): """Raised when a compaction pass would cross a pending tool call.""" pass @dataclass class ToolCall: call_id: str tool: str args: dict idempotency_key: str position: int @dataclass class CompactionScheduler: soft_token_threshold: int pending_calls: dict = field(default_factory=dict) # call_id -> ToolCall def on_call_emitted(self, call: ToolCall) -> None: self.pending_calls[call.call_id] = call def on_receipt_arrived(self, call_id: str) -> None: # Receipt binds back to the call it answers; only then is it safe to compact past it. self.pending_calls.pop(call_id, None) def safe_cursor(self, tokens_used: int) -> int: """Return the highest token index compaction may consume up to.""" if not self.pending_calls: return tokens_used # Fence at the earliest pending call: never consume its position or beyond. earliest = min(c.position for c in self.pending_calls.values()) return min(tokens_used, earliest - 1) def plan_compaction(self, tokens_used: int) -> dict: if tokens_used < self.soft_token_threshold: return {"action": "none"} cursor = self.safe_cursor(tokens_used) if self.pending_calls and cursor < self.soft_token_threshold: # Deferral would exceed budget AND fencing would starve compaction. # Only the Annotate policy can proceed, and it must emit structured records. records = [ { "call_id": c.call_id, "tool": c.tool, "args_hash": hashlib.sha256( repr(sorted(c.args.items())).encode() ).hexdigest()[:16], "idempotency_key": c.idempotency_key, "status": "in_flight", } for c in self.pending_calls.values() ] return { "action": "compact_with_pending_records", "cursor": tokens_used, "pending_records": records, } if cursor < tokens_used: return {"action": "compact_fenced", "cursor": cursor} return {"action": "compact_full", "cursor": cursor} def run_compaction_pass(scheduler: CompactionScheduler, tokens_used: int) -> dict: plan = scheduler.plan_compaction(tokens_used) if plan["action"] == "compact_with_pending_records": # Guardrail: the summarizer MUST NOT paraphrase these records. for rec in plan["pending_records"]: if rec["status"] != "in_flight" or not rec["idempotency_key"]: raise CompactionAtomicityError( f"pending call {rec['call_id']} lacks idempotency key; " f"compaction would orphan its receipt and permit duplicate side effects" ) return plan if plan["action"] in ("compact_fenced", "compact_full"): for call in scheduler.pending_calls.values(): if call.position <= plan["cursor"]: raise CompactionAtomicityError( f"cursor {plan['cursor']} crosses pending call {call.call_id} " f"at position {call.position}; defer or fence required" ) return plan return plan ```