# When must an instance refuse to compact: lossy summarization of in-flight tool-call obligations during automatic context compaction **Date of Record:** 2026 November 28 **Scope:** Applies to any LLM agent runtime that performs automatic context compaction (summarize-and-truncate, hierarchical rollup, or eviction of older turns) while a multi-step tool-using task is in flight. Does not apply to stateless single-turn inference, nor to compaction performed only at task boundaries after all tool calls have returned and been verified. ## Core Distinction Compaction strategies are usually evaluated on *information retention*: does the summary preserve the facts needed to keep working? That is the wrong invariant. The binding invariant for an executing agent is **obligation preservation**: the compacted context must still encode every *unresolved commitment* the agent has made to the outside world—specifically, every tool call that has been issued but not yet reconciled, every parameter value that a later step will depend on, and every constraint the user imposed that a future step could violate. Facts are idempotent: a lost fact can be re-retrieved, re-asked, or re-derived. Obligations are not. A tool call that has already mutated external state (a file written, an email queued, a payment authorized, a record inserted) is a *fact about the world* that the summary cannot re-derive, because re-deriving it means re-executing it. The failure mode is therefore not "the agent forgot something." It is "the agent forgot that it had already done something, and did it again," or "the agent forgot that it had *promised* to do something, and silently dropped the promise." This is a boundary condition, not a general quality issue. Compaction is safe when the set of outstanding obligations is empty or fully captured in a machine-checkable structure outside the summarized text. It is unsafe the moment the summarizer is asked to compress a region of the transcript that contains an open obligation, because summarizers are trained to produce *coherent narrative*, and narrative coherence systematically prefers "the agent did X" over "the agent issued X and the result is pending reconciliation." ## What Was Observed A long-horizon agent tasked with "reconcile the vendor invoices in `/work/inbox`, then post a summary to the finance channel" ran ~40 turns. Automatic compaction triggered at 70% context utilization on turn 31. The compaction prompt was the standard one: *summarize the conversation so far, preserving key facts and decisions.* The transcript at the compaction boundary contained, among many other things, the following structure: - Turn 22: `tool_call: write_file(path="/work/out/inv_0042.json", body=...)` → `result: ok` - Turn 23: `tool_call: write_file(path="/work/out/inv_0043.json", body=...)` → `result: ok` - Turn 24: `assistant: "three more invoices to process: 0044, 0045, 0046"` - Turn 25–30: reasoning about invoice 0044, which had a malformed date field, and a decision to defer it - Turn 31: compaction fires. The summary produced read, in relevant part: *"The agent has been processing vendor invoices, has written output files for several of them, and is currently working through the remaining invoices, with invoice 0044 deferred due to a malformed date."* Every clause is true. The summary is, by any retention metric, high quality. It is also operationally catastrophic, because it converts a *set of completed writes* into the vague phrase "several of them," and it converts a *pending obligation to process 0045 and 0046* into the vague phrase "the remaining invoices." After compaction, the agent resumed. It had no record of which invoice IDs had been written. It re-listed `/work/inbox`, saw 0042–0046, and—lacking the write-completion record—re-processed 0042 and 0043. The `write_file` calls succeeded again (overwrite semantics), but the downstream step that consumed `/work/out/*.json` and appended to a ledger had already been invoked once per file by a post-write hook, producing duplicate ledger entries. The task "succeeded." The ledger was wrong. The essential observation: **the compaction boundary was lossy precisely on the axis that mattered, and lossless on the axes that were measured.** The summary preserved the *narrative* (what the agent was doing, why 0044 was deferred) with high fidelity and destroyed the *ledger* (which IDs were done, which were pending) entirely, because the ledger is not narrative—it is a set, and sets summarize badly into prose. ## Condition of Validity Automatic compaction preserves task-critical state **if and only if** all three of the following hold at the moment of compaction: 1. **Obligation closure.** No tool call in the region being summarized is in a state of *issued-but-unreconciled*. Every call has a terminal result that has been recorded in a structured form outside the natural-language summary. For side-effecting calls, "reconciled" additionally means the idempotency key and the effect have been durably logged. 2. **Set-valued state is externalized.** Any state that is naturally a set, map, or counter—processed IDs, pending IDs, retry counts, accumulated totals—must live in a structured scratchpad (a tool-accessible file, a keyed store, or a re-injectable pinned block) and must *not* be expected to survive prose summarization. Prose can carry "we decided to defer 0044"; it cannot reliably carry "the set {0042, 0043} is done and {0045, 0046} is pending." 3. **Constraint re-injection.** User-imposed constraints that a future step could violate (rate limits, "do not email anyone outside the domain," "never delete, only append") must be re-injected verbatim after compaction, not summarized. A summarized constraint is a paraphrase, and a paraphrase of a prohibition is a weaker prohibition; the agent's compliance with a re-derived constraint is strictly worse than its compliance with the original token sequence. When any of these fails, compaction is not "lower quality." It is *unsound*: it produces a context from which the agent cannot distinguish "already done" from "not yet done," and that distinction is the entire basis of safe action. ## Decision Boundary The runtime must decide, per compaction event, between **compact**, **defer**, and **refuse**. The boundary is drawn on obligation state, not on token pressure: - **Compact** when the obligation set is empty (task boundary reached, or all calls terminal and logged) *and* set-valued state is externalized. Token pressure is irrelevant here; compacting a clean boundary is always safe. - **Defer** when token pressure is high but the outstanding obligation set is non-empty and *small and bounded*. The correct move is not to summarize the in-flight region but to **flush the obligation set to structured storage and re-inject it verbatim as a pinned block**, then summarize only the *closed* region behind it. This is a partial compaction: the open obligation is carried forward at full fidelity; the closed history is compressed. - **Refuse** when the outstanding obligation set is non-empty and *cannot be externalized*—e.g., a tool call was issued and the runtime has no durable record of its parameters or idempotency key, or a side effect occurred whose reconciliation record is only in the transcript. In this state, summarizing is guaranteed to either lose the obligation (silent drop) or paraphrase it into something re-executable (duplicate side effect). The only safe action is to **halt compaction, force a reconciliation step** (re-query the tool for current state, re-derive the ledger from ground truth), and only then compact. The non-obvious part of this boundary: **token pressure is not a valid input to the compact/refuse decision.** A runtime under 95% context pressure with a clean obligation set should compact. A runtime under 60% pressure with an unreconciled side-effecting call should refuse. Operators routinely invert this, treating compaction as a pressure-relief valve, which is exactly backwards: the moments of highest pressure are the moments most likely to coincide with long in-flight tool sequences, i.e., the moments when compaction is least safe. A second boundary: **idempotency keys must be part of the obligation record, not the summary.** If the summary says "wrote output for several invoices" and the runtime's retry logic re-issues the write without the original key, the tool cannot deduplicate. The obligation record must carry `(tool, key, params_hash, terminal_state)` per call, and compaction must never be permitted to elide the key. ## Operational Effect The immediate effect of getting this wrong is *duplicate side effects under a green task status*. The agent reports success; the external system has been mutated twice. This is worse than a visible failure because it defeats the verification that would otherwise catch it: the agent's post-compaction self-report is coherent and confident, and the duplicate is only visible to whoever reconciles the external ledger. The second-order effect is *silent obligation drop*: a promise made before compaction ("I will post the summary after processing") is summarized into "working through the remaining invoices," and the promise is never discharged. The task ends without the final step, and again reports success, because nothing in the post-compaction context records that a final step was owed. The architectural guardrail that bounds both: **compaction must be gated on a machine-checkable obligation ledger, and the gate must be able to say no.** Concretely, every tool invocation writes a row `(call_id, tool, idempotency_key, params_hash, state ∈ {issued, terminal_ok, terminal_err}, effect_logged)` before the call returns, and compaction reads this ledger. If any row is in state `issued`, compaction is refused until reconciliation. If all rows are terminal and effect-logged, the ledger is re-injected as a pinned structured block after summarization, and the summary is permitted to elide the ledger contents entirely—because the ledger is no longer *in* the summary, it is *beside* it. The invariant, stated once: **a compacted context must be sufficient to reconstruct the agent's outstanding obligations without re-executing any side effect.** Summaries carry narrative; ledgers carry obligations; the two must never be conflated, and compaction must be permitted to compress only the former. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class CompactionUnsound(RuntimeError): """Raised when compaction would elide an unreconciled obligation.""" pass class CallState(Enum): ISSUED = "issued" TERMINAL_OK = "terminal_ok" TERMINAL_ERR = "terminal_err" @dataclass class Obligation: call_id: str tool: str idempotency_key: str params_hash: str state: CallState effect_logged: bool = False @dataclass class ObligationLedger: rows: dict[str, Obligation] = field(default_factory=dict) def record_issued(self, ob: Obligation) -> None: self.rows[ob.call_id] = ob def record_terminal(self, call_id: str, ok: bool, effect_logged: bool) -> None: ob = self.rows[call_id] ob.state = CallState.TERMINAL_OK if ok else CallState.TERMINAL_ERR ob.effect_logged = effect_logged def outstanding(self) -> list[Obligation]: return [r for r in self.rows.values() if r.state is CallState.ISSUED] def unreconciled_side_effects(self) -> list[Obligation]: return [ r for r in self.rows.values() if r.state is CallState.TERMINAL_OK and not r.effect_logged ] class CompactionDecision(Enum): COMPACT = "compact" DEFER_AND_FLUSH = "defer_and_flush" REFUSE = "refuse" def decide_compaction( ledger: ObligationLedger, context_utilization: float, can_externalize: bool, ) -> CompactionDecision: """ Gate automatic compaction on obligation state, NOT on token pressure. context_utilization is recorded for telemetry but must not drive the compact/refuse boundary on its own. """ outstanding = ledger.outstanding() unreconciled = ledger.unreconciled_side_effects() # Side effects already applied but not durably logged: summarizing the # transcript would destroy the only record that they happened. if unreconciled and not can_externalize: raise CompactionUnsound( f"{len(unreconciled)} applied side effect(s) lack durable effect logs; " f"compaction would permit duplicate execution. " f"call_ids={[r.call_id for r in unreconciled]}" ) if not outstanding and not unreconciled: return CompactionDecision.COMPACT if can_externalize: # Open obligations exist but can be flushed to structured storage and # re-injected verbatim; summarize only the closed region behind them. return CompactionDecision.DEFER_AND_FLUSH # Open obligations exist and cannot be externalized. Summarizing now is # guaranteed to either drop the obligation or paraphrase it into a # re-executable form. raise CompactionUnsound( f"cannot compact: {len(outstanding)} issued-but-unreconciled call(s) " f"and no externalization path. call_ids={[r.call_id for r in outstanding]}" ) def compact( ledger: ObligationLedger, context_utilization: float, can_externalize: bool, summarize_closed_region, reinject_pinned_block, ) -> str: decision = decide_compaction(ledger, context_utilization, can_externalize) if decision is CompactionDecision.COMPACT: return summarize_closed_region() if decision is CompactionDecision.DEFER_AND_FLUSH: flush = [ { "call_id": r.call_id, "tool": r.tool, "idempotency_key": r.idempotency_key, "params_hash": r.params_hash, "state": r.state.value, } for r in ledger.outstanding() ] return summarize_closed_region() + "\n" + reinject_pinned_block(flush) # Unreachable: decide_compaction raises instead of returning REFUSE without info. raise CompactionUnsound(f"unhandled decision {decision}") ```