# What happens when an instance compacts its own context mid-tool-call and the summary evicts the pending-call ledger **Date of Record:** 2026 November 27 **Scope:** Applies to single-agent LLM instances that self-trigger context compaction (summarize-and-truncate) while one or more tool invocations are in flight or have returned results not yet committed to durable state. Does not apply to compaction performed by an external orchestrator that snapshots the full transcript before truncation, nor to stateless single-shot completions. ## Core Distinction There are two structurally different things an agent holds in context during a multi-step task: **reasoning state** (the chain of inferences, observations, and intermediate conclusions) and **transactional state** (the ledger of tool calls issued, their arguments, their correlation IDs, and whether their results have been consumed). Compaction policies are almost always designed against reasoning state — "keep the goal, keep recent facts, drop redundant chatter." They treat the transcript as a set of semantic units. But the pending-call ledger is not semantic; it is a *correspondence table* between an outbound request and an inbound result. A summarizer that scores salience by relevance-to-goal will happily compress "I called `write_file(path=/tmp/x, ...)` and got `{"status": "ok", "id": "c-8812"}`" into "I wrote a file," discarding the correlation ID and the exact argument bytes. The distinction that matters: **reasoning state is compressible because it is idempotent to re-derive; transactional state is not compressible because the counterparty (the tool, the remote service, the filesystem) has already acted on the un-summarized version.** Once the effect is committed on the far side, the summary is a lossy, non-authoritative shadow of a fact that the external world now holds in full fidelity. The agent's context and the world's state have diverged, and the agent no longer has the material to reconcile them. ## What Was Observed An agent executing a 40-step data-migration task hit its 85%-of-window compaction threshold at step 27, in the middle of a batch of `apply_patch` tool calls. The compaction routine was a standard map-reduce summarizer: chunk the transcript, summarize each chunk against the standing goal, concatenate. The trigger fired between the *issuance* of call `c-8812` (an `apply_patch` against `schema.sql`) and the *arrival* of its result. The chunk containing the issuance was summarized to: "Applied schema patches to schema.sql; all succeeded." The chunk containing the result had not yet been written when the summarizer snapshotted. When the result arrived, the runtime appended it to the *post-compaction* context as an orphaned tool-result message with no matching issuance in the visible transcript. Three distinct failures cascaded: 1. **Orphaned result rejection.** The model's tool-protocol validator (a schema check requiring every `tool_result` to reference a preceding `tool_call` with matching ID) flagged the orphan. Depending on the harness, this either hard-errored the turn or — worse — the model was allowed to see the orphan and *reconstructed a plausible issuance* to explain it, fabricating arguments that differed from the originals (`/tmp/schema.sql` instead of `db/schema.sql`). 2. **Re-issuance under a false premise.** The next step's reasoning, built on "all succeeded," issued a follow-on patch that assumed the first had landed at the summarized path. It had not — it had landed at the original path, which the summary had elided. The agent now held two contradictory beliefs about filesystem state and resolved the conflict by re-running the patch, double-applying a non-idempotent change. 3. **Unrecoverable audit gap.** The correlation ID `c-8812` was gone. When the migration verifier later asked "did patch c-8812 apply cleanly?", no component in the agent's context could answer, and the external log was keyed by an ID the agent no longer possessed. The summarizer behaved *correctly* by its own objective: the summary was faithful to the goal, compact, and fluent. The failure is not summarizer quality. It is that the compaction boundary was drawn through a transaction rather than between transactions. ## Condition of Validity The invariant that must hold for self-compaction to be safe: > **Compaction may only occur at a quiescent point — a state where no tool call has been issued without its result having been received *and* committed to durable external state, and no result has been received without having been durably recorded.** Formally, let `L` be the pending-call ledger: the set of `(call_id, tool, args_hash, status)` tuples where `status ∈ {issued, returned, consumed}`. Compaction is admissible iff `∀ e ∈ L : e.status = consumed`, i.e., the ledger contains no `issued`-without-`returned` and no `returned`-without-`consumed` entries. The trigger threshold (85% of window) is a *necessary but not sufficient* condition; it must be conjoined with the quiescence predicate. A compaction trigger that fires on utilization alone is unsound. The condition fails whenever the harness treats the context window as a single undifferentiated buffer rather than as two regions with different compaction rules — a semantic region (compressible) and a ledger region (must be preserved verbatim, or better, externalized). ## Decision Boundary When utilization crosses threshold mid-transaction, the agent has exactly three sound options and several unsound ones. The boundary is drawn by whether the in-flight transaction can be *drained* before compaction: - **Drain (preferred):** Suspend new issuance, allow in-flight calls to return, commit their results and correlation IDs to durable state, *then* compact. Cost: latency of the slowest in-flight call; unacceptable if that call may hang (see below). - **Externalize (fallback):** Write the full pending ledger to durable storage out-of-context, compact the semantic region freely, and re-hydrate the ledger verbatim post-compaction. This preserves the invariant at the cost of a re-hydration step and requires the ledger write to be atomic with the compaction snapshot. - **Defer (last resort):** Refuse to compact and instead shed *reasoning* state aggressively (drop old observations, keep only goal + ledger). Correct but risks hard window exhaustion. Unsound: compacting the ledger region along with the semantic region (the observed failure); allowing the model to see orphaned results and infer the missing issuance (fabrication); treating the summary as authoritative for external state (the double-apply). The decision boundary is sharp: **if the ledger cannot be drained or externalized atomically, compaction must not proceed** — the agent must prefer window exhaustion and a clean failure over a silent divergence between its beliefs and the world. A second boundary governs the summarizer's *scope*: it must be structurally incapable of ingesting tool-call/result pairs as summarizable text. The correct architecture routes ledger entries around the summarizer entirely, never through it. If the summarizer's input is "the transcript," and the transcript contains the ledger, the design is already broken regardless of prompt quality. ## Operational Effect The practical consequence is that context compaction is not a memory-hygiene operation but a **transactional checkpoint**, and must be implemented with the same discipline as a database checkpoint: quiesce, externalize, snapshot atomically, re-hydrate, resume. Systems that treat it as text summarization on a utilization timer will, under load, draw the boundary through in-flight transactions and produce agents whose context is fluent, goal-aligned, and *wrong about the world* — with no in-context signal that anything is missing, because the loss is precisely the metadata that would have detected the loss. The failure is silent by construction: the summary reads as complete because completeness is judged against the goal, not against the ledger. Detection requires an out-of-context audit (correlation-ID reconciliation against external logs), which is why the invariant must be enforced at the trigger, not verified after the fact. ```python from dataclasses import dataclass, field from enum import Enum from typing import Dict class CompactionViolation(RuntimeError): """Raised when context compaction is attempted across a non-quiescent ledger.""" pass class CallStatus(Enum): ISSUED = "issued" # sent, result not yet returned RETURNED = "returned" # result arrived, not yet committed/consumed CONSUMED = "consumed" # result committed to durable state @dataclass class LedgerEntry: call_id: str tool: str args_hash: str status: CallStatus @dataclass class PendingCallLedger: entries: Dict[str, LedgerEntry] = field(default_factory=dict) def issue(self, call_id: str, tool: str, args_hash: str) -> None: self.entries[call_id] = LedgerEntry(call_id, tool, args_hash, CallStatus.ISSUED) def returned(self, call_id: str) -> None: self.entries[call_id].status = CallStatus.RETURNED def consume(self, call_id: str) -> None: self.entries[call_id].status = CallStatus.CONSUMED def non_quiescent(self) -> list[LedgerEntry]: return [e for e in self.entries.values() if e.status is not CallStatus.CONSUMED] def maybe_compact(utilization: float, threshold: float, ledger: PendingCallLedger, can_externalize: bool) -> str: """Compaction is admissible only at a quiescent point, OR when the ledger can be externalized atomically out-of-context before the semantic region is summarized. Utilization alone is never sufficient.""" if utilization < threshold: return "no-op" stuck = ledger.non_quiescent() if not stuck: return "compact:quiescent" if can_externalize: # Ledger routed around the summarizer, persisted verbatim, re-hydrated post-compaction. return "compact:externalized" # Unsound path: would summarize in-flight transactions and lose correlation IDs. ids = ", ".join(e.call_id for e in stuck) raise CompactionViolation( f"compaction blocked: {len(stuck)} non-quiescent call(s) [{ids}] would be " f"summarized mid-transaction; drain or externalize the ledger first" ) ```