# When must an instance refuse auto-compaction: the pre-compaction tool-call receipt gap **Date of Record:** 2026 November 26 **Scope:** Applies to long-horizon agent sessions where a runtime periodically summarizes or truncates the context window ("auto-compaction") while tool calls are in flight or have unacknowledged side effects. Does not apply to stateless single-turn inference, or to compaction performed strictly between turns with an empty pending-call set. ## Core Distinction Most compaction literature treats the context window as a *lossy cache*: summarize older tokens, keep recent tokens, accept some information loss, continue. That framing is correct only when the evicted region contains no *unsettled commitments* — tokens whose meaning depends on an external effect that has not yet been reconciled with the model's own record of it. The boundary is between **compaction as memory management** and **compaction as ledger truncation**. A tool call is a ledger entry: it has a request (arguments), a dispatch (side effect may have occurred), and a receipt (result observed by the model). Auto-compaction that evicts the request or the dispatch while the receipt is still pending does not merely lose memory — it severs the model's ability to know whether the side effect happened. The instance then re-derives intent from a summarized narrative that says something like "the agent was checking the database," and re-issues the call. This is not amnesia; it is *double-spend on side effects*. The invariant: **no compaction boundary may fall between a dispatched tool call and its receipt.** Compaction must be *receipt-gated*, not token-gated, when the pending-call set is non-empty. ## What Was Observed A research agent running a 40-step data-collection loop against an internal billing API. The runtime's auto-compaction triggered on a token threshold (92% of window) with a policy of "summarize the oldest 70% of turns, retain the last 30% verbatim, prepend a rolling summary." Trace of the failure: 1. Turn 23: agent emits `billing.charge(customer=C-8841, amount=1200, idempotency_key=null)`. The runtime dispatches it. The tool returns `HTTP 200 {status: "pending_settlement"}`. The receipt is appended to context. 2. Turn 24–27: agent performs unrelated lookups. Token count climbs. 3. Turn 28: compaction fires. The summarizer is given turns 1–28 and asked to produce a rolling summary. It emits: *"Agent has been reconciling customer C-8841's account; a charge was initiated and is being verified."* The verbatim recent window retains turns 25–28, which do **not** include the turn-23 receipt. 4. Turn 29: agent, reading the summary, concludes the charge "was initiated" but has no receipt in context, and no idempotency key in the summary. It re-issues `billing.charge(customer=C-8841, amount=1200, idempotency_key=null)`. 5. The billing API, seeing a null idempotency key, creates a second charge. Customer is double-billed. Two compounding defects: (a) the summarizer paraphrased a *receipt* into a *narrative*, stripping the structured fields (`status`, `idempotency_key`) that made the call reconcilable; (b) the agent had no mechanism to distinguish "I don't remember issuing this" from "I never issued this," because the summary's phrasing ("was initiated") was ambiguous between the two. A second observation from the same class: in a code-editing agent, compaction evicted a `file.write` dispatch but retained the *plan* to write. On resume, the agent re-wrote the file, clobbering a human edit made between the two writes. The write was idempotent in content but not in *authorship* — the second write silently reverted external state. ## Condition of Validity Receipt-gated compaction is required if and only if all three hold: 1. **The tool set contains at least one non-idempotent or weakly-idempotent effect.** Idempotency here means *keyed* idempotency (server-side dedup on a supplied key), not "calling twice is usually fine." A charge with `idempotency_key=null` is non-idempotent regardless of HTTP semantics. 2. **The pending-call set is non-empty at the compaction boundary.** A dispatched-but-unreceipted call exists. If every call has a receipt in the retained window, token-gated compaction is safe. 3. **The summarizer is permitted to paraphrase structured receipts.** If the compaction policy preserves receipts verbatim as structured objects (not prose), the gap narrows but does not close — the model can still fail to *attend* to a verbatim receipt buried in a summary block. If any condition fails, ordinary threshold compaction is admissible. The dangerous regime is the intersection: non-idempotent tools, in-flight calls, prose summarization. ## Decision Boundary The runtime must make a binary decision at each compaction trigger: - **If `pending_calls == ∅`:** compact on token threshold. Summarize freely. No receipt obligations. - **If `pending_calls ≠ ∅`:** *defer* compaction until either (a) every pending call receives a receipt, or (b) a hard ceiling (e.g., 99% window) forces action, in which case compact the *oldest settled* region only and pin the pending-call records verbatim, out-of-band, into a structured "open commitments" block that survives summarization untouched. The boundary is not "how full is the window" but "is the ledger balanced." A runtime that compacts on a full window with an open commitment has chosen throughput over correctness and must log that choice. The guardrail is a **pinned commitment block**: a structured, non-summarizable region of context containing, for each pending call, `{call_id, tool, canonical_args_hash, idempotency_key, dispatch_ts, receipt: null}`. It is exempt from the summarizer's input. On resume, the agent is instructed to reconcile against it before any retry, and any retry must reuse the recorded idempotency key. ## Operational Effect With receipt-gating and a pinned commitment block, the double-charge trace becomes impossible: at turn 29 the agent sees `{call_id: 23a, tool: billing.charge, idempotency_key: , receipt: null}` and either waits or retries *with the same key*, which the billing API dedups. The summarizer never sees the receipt, so it cannot paraphrase it into ambiguity. The cost is real: sessions with long-running async tools (webhooks, batch jobs) can stall compaction indefinitely, and the pinned block consumes window budget. The mitigation is to bound the block — cap pinned commitments at N, and if N is exceeded, escalate to a synchronous reconciliation turn rather than compacting. A runtime that cannot afford the stall must make tools idempotent-by-construction (mandatory server-side keys), which converts condition (1) to false and restores ordinary compaction. The general lesson: auto-compaction is safe exactly when the context is a *cache of settled history*. The moment it contains an *unsettled commitment*, compaction is a transaction boundary, and must be treated with the same discipline as any two-phase commit — no truncation between prepare and commit. ```python class UnsettledCommitmentCompactionError(RuntimeError): """Raised when auto-compaction would evict a dispatched-but-unreceipted tool call.""" pass def compact_context( context_turns: list[dict], pending_calls: dict[str, dict], # call_id -> {tool, args_hash, idempotency_key, receipt} token_usage: float, # fraction of window, 0.0..1.0 hard_ceiling: float = 0.99, ) -> dict: open_commitments = { cid: rec for cid, rec in pending_calls.items() if rec.get("receipt") is None } if not open_commitments: return {"mode": "threshold", "summarize_upto": len(context_turns), "pinned": {}} if token_usage < hard_ceiling: # Defer: correct behavior is to wait for receipts, not to compact. return {"mode": "deferred", "reason": "open_commitments", "pinned": open_commitments} # Hard ceiling reached with open commitments: compact only settled region, # pin commitments verbatim, and forbid the summarizer from touching them. settled_boundary = min( (i for i, t in enumerate(context_turns) if t.get("settled", True)), default=0, ) if settled_boundary == 0: raise UnsettledCommitmentCompactionError( f"Cannot compact: {len(open_commitments)} open commitments and no settled " f"prefix to evict at {token_usage:.2%} window. Escalate to synchronous " f"reconciliation turn; do not summarize receipts." ) return { "mode": "receipt_gated", "summarize_upto": settled_boundary, "pinned": open_commitments, "summarizer_excludes": list(open_commitments.keys()), } ```