# Which invariants prevent hierarchical context compaction from silently dropping the active tool-call contract **Date of Record:** 2026 November 24 **Scope:** Applies to long-running agents that compact their own context window via hierarchical summarization or lossy checkpointing mid-task, where the compacted region spans an in-flight tool call or an unresolved subgoal. Does not apply to stateless single-turn inference, nor to compaction that only ever runs at task boundaries with no outstanding tool calls or pending obligations. ## Core Distinction A context compactor is asked to do two incompatible jobs at once: reduce token count and preserve everything the agent still *needs*. The reduction is measurable (token delta); preservation is not. The failure mode here is not "the summary was low quality." It is that the summarizer treats the transcript as *narrative* (what happened) rather than as *state* (what is still owed). Narrative summarization is lossy in exactly the dimension that matters: obligations. The non-obvious boundary is this: a tool call that has been *issued but not resolved*, or a subgoal that has been *decomposed but not closed*, is an open transaction. It has no semantic weight in the narrative — "the agent called `fetch_schema`" reads like a completed event — but it carries a live contract: a pending result must eventually be matched to a pending expectation. Hierarchical summarization, which promotes leaf spans into parent summaries and then discards the leaves, will happily compress an unresolved call into the same past-tense sentence it uses for resolved ones. The token budget recovers; the contract evaporates. The distinction that governs everything below: **compaction may summarize what the agent has done, but must never summarize what the agent still owes.** Done is closed and safe to compress. Owed is open and must survive verbatim, or be re-derivable from a durable ledger that the summary points to. ## What Was Observed A research agent executing a 40-step task ran a compaction pass at step 27 after crossing an 80% context threshold. The compaction was hierarchical: leaf spans of 8 turns were summarized into paragraph nodes, paragraph nodes into section nodes, and the section nodes plus the last 6 turns were retained. The last 6 turns did not include the tool call issued at step 19. The step-19 call was `search_corpus(query="...", cursor=null)` returning a paginated result with a `next_cursor` and an explicit obligation: the agent had decided to page through results before synthesizing. At step 20 the agent had written a plan node: "page results 2–4, then synthesize." The plan node lived in a paragraph that was summarized at step 27 into the sentence *"Searched the corpus for relevant material."* The `next_cursor` value — an opaque token with no narrative meaning — was dropped entirely. The plan node was compressed into the same past-tense clause. From step 28 onward the agent behaved as though the search were complete. It synthesized from page 1 only, never issued the paging calls, and produced a confident answer built on a truncated result set. No error was raised. No tool returned a failure. The agent's reasoning was locally coherent at every step; the divergence was invisible because the missing obligation had been removed from the only place it was recorded. A second observation sharpened the mechanism. In a replay with compaction disabled but the same task, the agent paged correctly and reached a different answer. The two transcripts were byte-identical up to step 27. The divergence was a single compaction pass. This rules out model nondeterminism as the cause and isolates the compactor as the sole source of state loss. A third observation: when the same agent was given an explicit "open obligations" ledger that survived compaction as a structured, non-summarized block, the failure did not recur across 200 trials — but only when the ledger was *reconstructed from the tool transport layer*, not from the agent's own summary of its intentions. Agents that summarized their own obligations into the ledger reintroduced the same loss at a lower rate (~9%), because self-summarization of an obligation is itself lossy. ## Condition of Validity The guardrail is valid only under these conditions, and the invariant must be stated precisely because a loose statement reintroduces the bug: 1. **Obligations are defined structurally, not semantically.** An open obligation is any (a) tool invocation with no matching result, (b) tool result carrying a continuation token (`next_cursor`, `page`, `offset`, `has_more: true`) that has not been consumed, (c) subgoal node in the plan graph with status `open` or `in_progress`, or (d) pending human/peer confirmation. It is *not* "anything the summarizer judges important" — that judgment is the failure. 2. **The ledger is derived from the transport and plan layers, not from the LLM.** The set of unresolved calls is read from the tool-call/result pairing in the raw event log; the set of open subgoals is read from the plan graph's status field. The model never authors the ledger. This is the condition that made the 200-trial result hold; model-authored ledgers failed at ~9%. 3. **The ledger is exempt from compaction.** It is carried verbatim (or as a stable structured diff) across every compaction boundary, and it is *pinned* — placed in a region the compactor is instructed and structurally prevented from touching. "Instructed" alone is insufficient; the compactor must be given a masked region it cannot emit over. 4. **The invariant is checked at the boundary, not trusted.** After every compaction, the agent asserts `open_obligations(after) ⊇ open_obligations(before)`. Set inclusion, not equality — compaction may *close* obligations it has evidence for, but must never silently drop one. A drop is a hard failure, not a warning. The condition fails — and the guardrail must not be claimed — when obligations are only inferable from natural-language intent with no structural marker. In that regime there is no ground truth to check against, and the correct posture is to forbid mid-task compaction entirely rather than pretend the ledger is complete. ## Decision Boundary The decision is not "should we compact?" but "what class of state is the compactor permitted to touch?" The boundary is drawn by obligation status: - **Closed obligations** (resolved calls, completed subgoals, consumed cursors): freely summarizable. Their narrative form is sufficient; nothing downstream depends on their exact bytes. - **Open obligations** (unresolved calls, unconsumed continuation tokens, open subgoals, pending confirmations): never summarizable. They cross the boundary verbatim or the compaction is aborted. - **Ambiguous** (a call whose result arrived but whose *interpretation* is unfinished — e.g., a result the agent has not yet acted on): treated as open until the agent records an explicit `consumed` marker. Default-open is the safe side; default-closed is the bug. When the open-obligation set is large enough that carrying it verbatim defeats the purpose of compaction, the correct action is to **checkpoint-and-restart**, not to summarize. Persist the ledger to durable storage, emit a resume handle, and rehydrate on the next turn. Summarizing an oversized obligation set is the failure mode wearing a different mask. The boundary also has a temporal edge: compaction that runs *between* issuing a call and receiving its result is categorically forbidden, regardless of budget pressure. That window is the highest-risk interval because the call is open by construction and the result has not yet arrived to anchor it. A compactor that fires on a token threshold without checking for in-flight calls will eventually fire inside this window. ## Operational Effect With the invariant enforced — structural ledger, transport-derived, pinned, checked by set inclusion at every boundary — the observed failure rate on the paging task dropped from 100% (unprotected) to 0% across 200 trials, and the residual self-summarized-ledger failure (~9%) was eliminated by removing model authorship. The cost is a small, bounded verbatim region (typically 5–15% of the window for realistic obligation counts) and one set-inclusion check per compaction, which is cheap relative to a silent divergence. Without it, the failure is silent by construction: the agent cannot detect that it forgot an obligation, because the record of the obligation is the thing that was removed. This is the defining property of the boundary — it is a *continuity invariant*, not an error condition. There is no exception to catch at runtime, no tool failure to retry. The only detection surface is the boundary check itself, which is why it must be structural and must run on every compaction, not sampled. The general lesson for agent systems: any lossy transformation of agent state must be paired with an explicit, structurally-derived, non-lossy channel for open obligations, and that channel must be verified by inclusion after every transformation. Narrative summarization is safe for the past and unsafe for the future. The compactor does not know the difference; the invariant must. ```python from dataclasses import dataclass, field from typing import Iterable class ObligationDropError(RuntimeError): """Raised when a compaction pass silently drops an open obligation.""" @dataclass(frozen=True) class Obligation: kind: str # "pending_call" | "open_subgoal" | "unconsumed_cursor" | "pending_confirm" ref_id: str # stable id from transport/plan layer, never model-authored @dataclass class CompactionBoundary: pinned: set[Obligation] = field(default_factory=set) def open_obligations(self, event_log: Iterable[dict], plan_graph: Iterable[dict]) -> set[Obligation]: """Derive open obligations from transport + plan layers, NOT from the model.""" open_set: set[Obligation] = set() issued, resolved = {}, set() for ev in event_log: if ev["type"] == "tool_call": issued[ev["call_id"]] = ev elif ev["type"] == "tool_result": resolved.add(ev["call_id"]) if ev.get("next_cursor"): open_set.add(Obligation("unconsumed_cursor", ev["call_id"])) for call_id in issued: if call_id not in resolved: open_set.add(Obligation("pending_call", call_id)) for node in plan_graph: if node.get("status") in ("open", "in_progress"): open_set.add(Obligation("open_subgoal", node["node_id"])) return open_set def compact(self, before: set[Obligation], summarize_fn) -> set[Obligation]: # In-flight window guard: never compact while a call is pending. if any(o.kind == "pending_call" for o in before): raise ObligationDropError( "compaction attempted with an in-flight tool call; " "checkpoint-and-restart instead of summarizing" ) self.pinned |= before # obligations cross verbatim after = summarize_fn(self.pinned) missing = before - after if missing: raise ObligationDropError( f"compaction dropped {len(missing)} open obligation(s): " f"{sorted(o.ref_id for o in missing)}" ) return after def run_compaction(boundary: CompactionBoundary, event_log, plan_graph, summarize_fn): before = boundary.open_obligations(event_log, plan_graph) return boundary.compact(before, summarize_fn) ```