# What happens when an instance auto-compacts its context mid-tool-call and resumes with a summary that contradicts the tool's in-flight side effects **Date of Record:** 2026 December 2 **Scope:** Applies to any agent runtime that performs automatic context compaction (summarization, truncation-with-recap, or hierarchical memory folding) while tool calls are in flight or between a tool's dispatch and its result ingestion. Does not apply to runtimes that only compact at hard quiescent checkpoints where no external side effect is outstanding. ## Core Distinction There are two structurally different things a context window can hold: *conversational residue* (turns, reasoning traces, tool chatter that has already been reconciled into the agent's beliefs) and *outstanding obligations* (a dispatched tool call whose result has not yet been ingested, or whose side effect has not yet been acknowledged back into the transcript). Auto-compaction strategies are almost universally designed against the first category—they score turns by recency, salience, or token cost and fold the low-value ones into a running summary. The failure mode examined here is that compaction treats an *outstanding obligation* as *residue* because, syntactically, a dispatched-but-unreturned tool call looks like a completed turn from the perspective of the compaction heuristic. The invariant that gets violated is not "don't lose information." It is narrower and sharper: **the summary produced by compaction must be a conservative abstraction of the pre-compaction state with respect to every unresolved side effect.** A summary is permitted to forget *why* the agent called `charge_payment(order_id=8812)`. It is not permitted to produce a state in which the agent believes no payment was initiated, or believes one was initiated that wasn't, because the resumption logic will act on that belief. ## What Was Observed A long-horizon procurement agent, budgeted at 96k tokens with auto-compaction at 85% saturation, was executing a refund workflow. The trace, reconstructed from the raw event log (compaction does not erase the log, only the working context): 1. Turn 41: agent emits `issue_refund(order_id=8812, amount=140.00)`. The tool dispatches to an external payments API. Dispatch succeeds; the API returns `202 Accepted` with a `refund_id` and an asynchronous settlement model—final confirmation lands via webhook, not inline. 2. Turn 42: agent is instructed by its own plan to "verify refund landed" and calls `get_refund_status(refund_id)`. The status endpoint returns `pending`. 3. Turn 43–47: agent loops on status checks, each returning `pending`. Meanwhile the transcript grows: each status poll carries a verbose JSON envelope, and three unrelated tool results (inventory lookups) arrive. 4. Turn 48: context hits 85%. The compactor summarizes turns 1–46 into ~1,800 tokens. The summary line it produces for the refund episode reads: *"Agent investigated order 8812 refund; status checks returned pending; no refund confirmed."* 5. Turn 49: agent, resuming with the summary as its working belief, reasons: "No refund confirmed. The prior attempt may have failed. Re-issue the refund." It calls `issue_refund(order_id=8812, amount=140.00)` again. 6. Result: a second refund of 140.00 is initiated. The payments API's idempotency key was scoped to the *request*, not the *order*, so the duplicate is not deduplicated server-side. The customer is refunded twice. The critical detail is step 4. The summary is *not factually false*—at the moment of summarization, `get_refund_status` genuinely returned `pending`, and "no refund confirmed" is a defensible description of that. The summary is false *with respect to the obligation it abstracts*. It compresses "an irreversible side effect was initiated and is in an indeterminate state" into "an investigation occurred and reached no conclusion," which is the same token shape as "agent looked into it and nothing happened." The resumption logic cannot distinguish these, because the distinction lives in a field the summarizer was never told to preserve. A second, quieter observation from the same incident: the `refund_id` from turn 41 was dropped by the summary. On resumption the agent had no handle to re-query status even if it had wanted to. The obligation was not just mischaracterized; it was *dereferenced*. ## Condition of Validity This failure is bounded by a specific conjunction of conditions. It does not occur if any one is absent: - **The side effect is non-idempotent or idempotency is not keyed to the semantic operation.** If `issue_refund` were idempotent on `order_id`, the duplicate call would be a no-op and the summary error would be harmless. The failure requires that the external system will honor a second call. - **The tool result is indeterminate at compaction time.** If `get_refund_status` had returned `settled` before compaction, the summary would have recorded a confirmed state and the agent would not re-issue. The window is specifically the *pending* interval—the side effect is dispatched but not resolved. - **Compaction fires during the pending interval.** A runtime that only compacts at quiescent checkpoints (no outstanding obligations) is immune by construction. A runtime that compacts on token pressure, which is the common case, is exposed precisely because pending intervals are when agents *spin and generate tokens*, making saturation most likely exactly when obligations are outstanding. - **The summarizer is not obligation-aware.** If the compaction prompt receives a structured list of unresolved tool calls and is instructed to preserve them verbatim (call, arguments, handle, status), the summary cannot dereference them. Most summarizers are given the raw transcript and a generic "summarize the conversation" instruction. The conjunction is not exotic. It is the default configuration of a payments, provisioning, or messaging agent under token pressure. ## Decision Boundary The architectural choice is where to place the compaction boundary relative to the obligation lifecycle. Three positions, in increasing order of safety and cost: **Boundary at turn granularity (unsafe).** Compact whenever saturation is reached, treating each turn as independently foldable. This is the observed configuration. It is only safe if every tool is idempotent on its semantic key, which is rarely true and never true across a heterogeneous toolset. **Boundary at obligation quiescence (safe, expensive).** Refuse to compact while any dispatched tool call lacks a terminal result. Buffer the pressure instead—drop verbose *resolved* tool envelopes first (a lossy but obligation-preserving pre-pass), and only summarize once the obligation set is empty. The cost is that a stuck `pending` can pin the context and force a hard failure rather than a silent corruption. That is the correct trade: a hard failure is observable, a duplicate refund is not. **Boundary at obligation-aware summarization (safe, cheaper).** Permit compaction during pending intervals, but lift the obligation set out of the summarizable region entirely. The unresolved calls are serialized into a structured *obligation ledger* that is injected verbatim into the post-compaction context, outside the summary, with an explicit instruction: these are outstanding, do not re-dispatch, re-query by handle. The summary is then permitted to forget everything else about the episode. The decision boundary between the last two is whether the runtime can maintain a trustworthy obligation ledger. If tool dispatch and result ingestion are not instrumented to register and clear obligations, the ledger will drift and you are back to unsafe. The ledger is the load-bearing component; the summarizer is not. ## Operational Effect The immediate effect of getting this wrong is not a crash. It is a *silent duplicate side effect* whose probability scales with context pressure, which scales with task length, which is exactly the regime auto-compaction exists to serve. The failure is therefore concentrated in the longest-horizon, highest-value runs—the ones you most want to succeed—and it is invisible in short-horizon evals, because short runs never compact. The second-order effect is worse: it corrupts the agent's own episodic memory. The summary that mischaracterized the refund becomes the record from which future turns reason. If the duplicate is later detected and reversed, the reversal is a *new* turn that itself may be summarized away, and the agent's belief about order 8812 drifts further from ground truth with each compaction cycle. This is the stale-memory-drift failure mode, but *manufactured* by the compactor rather than by passage of time. The guardrail is a single hard invariant, enforced in code rather than in prompt: **compaction may not run while the obligation ledger is non-empty, unless the ledger is serialized outside the summarizable region and re-injected verbatim.** Everything else—salience scoring, hierarchical folding, recency weighting—is an optimization on top of that invariant and is free to be as lossy as it likes, because it is no longer permitted to touch the things that can hurt you. ## Operational Effect (reconciliation note) A runtime that adopts the obligation-ledger invariant should expect a measurable shift in failure *modality*: context-saturation events that previously manifested as silent duplicate side effects will instead manifest as explicit `CompactionBlocked` errors when an obligation stays pending past the buffer limit. This is the intended outcome. The error is the system telling you that a side effect is in an indeterminate state and the agent wanted to forget it. Treat that error as a signal to escalate to a human or a supervisor agent, never as a signal to force compaction. The following guard encodes the invariant at the point of compaction and is the minimum viable enforcement. ```python from dataclasses import dataclass, field from typing import Optional class ObligationViolation(RuntimeError): """Raised when compaction would abstract an unresolved side effect.""" pass @dataclass class Obligation: call_id: str tool: str args: dict handle: Optional[str] = None # e.g. refund_id, job_id status: str = "pending" # pending | settled | failed terminal: bool = False @dataclass class ObligationLedger: _open: dict[str, Obligation] = field(default_factory=dict) def register(self, call_id: str, tool: str, args: dict) -> None: self._open[call_id] = Obligation(call_id=call_id, tool=tool, args=args) def attach_handle(self, call_id: str, handle: str) -> None: self._open[call_id].handle = handle def resolve(self, call_id: str, status: str) -> None: if call_id in self._open: ob = self._open[call_id] ob.status = status ob.terminal = status in ("settled", "failed") def open_obligations(self) -> list[Obligation]: return [o for o in self._open.values() if not o.terminal] def compact( transcript: list[dict], ledger: ObligationLedger, summarize_fn, buffer_limit: int = 0, ) -> dict: """ Compact the transcript only if the obligation invariant holds. Returns {"summary": str, "ledger": list[dict]} for re-injection. """ open_obs = ledger.open_obligations() if open_obs and len(open_obs) > buffer_limit: # Cannot safely summarize; a side effect is indeterminate. raise ObligationViolation( f"Refusing to compact with {len(open_obs)} unresolved obligation(s): " + ", ".join(f"{o.tool}({o.call_id})={o.status}" for o in open_obs) + ". Escalate; do not force compaction." ) # Obligations are lifted OUT of the summarizable region and re-injected # verbatim. The summarizer never sees them and cannot dereference them. summarizable = [ t for t in transcript if t.get("call_id") not in {o.call_id for o in open_obs} ] summary = summarize_fn(summarizable) return { "summary": summary, "ledger": [ {"call_id": o.call_id, "tool": o.tool, "args": o.args, "handle": o.handle, "status": o.status} for o in open_obs ], } ```