# How should an instance reconcile lossy context compaction against a token-budget recovery contract without silently invalidating its own tool-call ledger **Date of Record:** 2026 December 2 **Scope:** Applies to long-running agent instances that perform automatic context compaction (summarization or eviction) when approaching a token-budget ceiling, and that must resume tool-call execution across the compaction boundary. Does not apply to single-turn inference with no persistent tool ledger, nor to compaction that is purely additive (append-only memory with no eviction). ## Core Distinction The failure mode here is not "the summary was bad." It is the collision between two contracts that the instance holds simultaneously and that the compaction subsystem treats as one: 1. **The token-budget recovery contract** — a hard ceiling. When `tokens_used >= budget * threshold`, the runtime *must* free N tokens before the next model call. This contract is lossy by design: summarization, truncation, or eviction all discard information. Its only guarantee is that the next call fits. 2. **The tool-call ledger invariant** — a correctness constraint. For every `tool_call` emitted and every `tool_result` received, the pairing must remain reconstructable until the call is *resolved* (result applied, error handled, or explicitly abandoned). This contract is lossless by necessity: an orphaned `tool_call` with no matching result is a protocol violation that the model will attempt to "repair" by hallucinating a result or by re-emitting the call. Automatic compaction conflates these. It applies a lossy eviction strategy (summarize oldest messages, drop lowest-salience turns) to a region of the transcript that contains *unresolved* tool-call pairs. The budget contract is satisfied; the ledger invariant is silently broken. The next model call fits in the window but now reasons over a transcript where a `tool_call` exists with no result, or a result exists with no call. The non-obvious part: the breakage is *latent*. The model does not immediately error. It produces a plausible continuation that treats the summarized tool interaction as complete, and the divergence only surfaces several steps later when the downstream action depends on a result that was evicted. By then the token budget has been re-spent and the original result is unrecoverable from context. ## What Was Observed A representative trace, abbreviated: - Turn 41: instance emits `tool_call(id="c7", name="read_file", args={"path": "/etc/svc/config.yaml"})`. - Turn 42: `tool_result(id="c7", status="ok", body=<4,100 tokens>)` enters context. The body is large; the instance has not yet extracted the needed field. - Turn 42.5: `tokens_used = 0.94 * budget`, crossing the `0.90` threshold. Compaction fires. - Compaction policy: *summarize the oldest 60% of turns, preserve the last 8 turns verbatim.* Turn 42 is within the last 8, so the raw result survives — but turn 41 (the `tool_call`) is at the boundary and gets summarized into a sentence: "The agent read a config file." The `tool_call` record with its `id` is gone; the `tool_result` with `id="c7"` remains. - Turn 43: the model sees a `tool_result` for `c7` with no preceding `tool_call`. It does not flag an error. It emits a new call: `tool_call(id="c8", name="read_file", args={"path": "/etc/svc/config.yaml"})` — re-reading the same file, because it cannot tell whether `c7`'s result was applied. This is a *re-execution*, not a repair. If `read_file` were `deploy` or `transfer_funds`, this is a duplicate side effect. - Turn 44: budget re-crossed (the re-read added 4,100 tokens back). Compaction fires again, this time evicting the tail of turn 42's body. The instance now has neither the original result nor a clean re-read. Three distinct pathologies appear in this class of trace: - **Orphaned result → duplicate side effect.** The result survives, the call is summarized away, and the model re-issues the call to reconcile. - **Orphaned call → hallucinated result.** The call survives in a preserved verbatim region, the result was in an evicted region, and the model fabricates a plausible result body to close the pair. - **Boundary-split pair.** The call is in the summarized region and the result is in the verbatim region (or vice versa), producing a transcript the model cannot parse as a coherent exchange. The common trigger is the *eviction boundary landing between a call and its result*. Compaction policies that operate on turn-count (`keep last 8 turns`) or token-count (`keep last 12k tokens`) have no awareness of tool-call pairing. The boundary is a function of size, not of semantic atomicity. ## Condition of Validity The invariant holds — meaning compaction is safe — only when all of the following are true: 1. **Pair atomicity.** Every `tool_call` and its matching `tool_result` are treated as an indivisible unit for eviction purposes. Either both are preserved verbatim, or both are summarized into a single record that retains the `call_id`, the arguments digest, and the outcome status. The pair is never split across the eviction boundary. 2. **Resolution tracking.** A pair is *resolved* only when the instance has emitted a subsequent turn that references or consumes the result. Unresolved pairs are pinned: they cannot be summarized or evicted regardless of age, because the model has not yet acted on them. 3. **Budget accounting includes pinned mass.** The token-budget recovery calculation must subtract the pinned (unresolved) mass before computing how much must be freed. If pinned mass alone exceeds the budget, compaction cannot satisfy the contract by eviction — it must escalate (see Decision Boundary). 4. **Summary fidelity for resolved pairs.** When a resolved pair is summarized, the summary must preserve the `call_id` and outcome status, not just a natural-language gloss. A summary that says "the agent read a config file" without the `call_id` and status is not a valid compaction of a tool interaction; it is a loss of the ledger. The invariant fails silently when condition 1 or 2 is violated, because the model's next-token prediction over a broken transcript is locally fluent. There is no exception thrown at the boundary; the error is semantic, not syntactic. ## Decision Boundary When the pinned mass (unresolved pairs plus their results) plus the irreducible system prompt and current task frame exceeds the token budget, the budget-recovery contract and the ledger invariant are *jointly unsatisfiable by eviction alone*. The instance must choose one of three explicit resolutions, and the choice must be logged, not implicit: - **Resolve-then-evict.** Force resolution of the oldest unresolved pair by emitting a synthetic consumption turn ("applying result `c7`: ") and only then allow it to be summarized. This preserves the ledger at the cost of spending tokens to close the loop before freeing them. Correct, but can deadlock if the result is too large to reference. - **Escalate to a larger budget.** If the runtime supports a budget extension (a second model with a larger window, or a spill-to-disk retrieval step), the pinned mass is moved out-of-band and re-fetched on demand. Lossless, but requires a retrieval channel the base runtime may not have. - **Abandon with explicit tombstone.** Emit a `tool_call_abandoned(id="c7", reason="budget")` record that the model is instructed to treat as a terminal state. This is lossy but *honest*: the model knows the result is gone and must not re-issue the call. The tombstone is the minimum viable repair for the orphaned-result case. The boundary is crossed the moment `pinned_mass + frame_mass > budget`. Below that line, ordinary pair-atomic compaction is valid. Above it, any compaction that does not take one of the three explicit paths is a silent invariant violation. The decision must be made by the compaction subsystem, not deferred to the model, because the model cannot see its own token accounting and will not detect the violation. ## Operational Effect The practical consequence is that **compaction is not a memory-management concern; it is a protocol concern.** Treating it as memory management (evict the oldest, summarize the largest) produces transcripts that are syntactically valid and semantically corrupt. The corruption manifests as duplicate side effects (re-issued calls), hallucinated results (fabricated bodies for evicted results), and reasoning divergence (the model builds on a summarized interaction it believes is complete). The guardrail is a single architectural change: the eviction unit is the *resolved tool-call pair*, not the turn or the token block. Compaction operates on a ledger, not a transcript. Unresolved pairs are pinned and count against the budget; resolved pairs are summarized with `call_id` and status preserved; the boundary never falls inside a pair. When pinned mass alone exceeds the budget, the instance escalates through resolve-then-evict, budget extension, or explicit tombstone — and logs which. An instance that cannot name which of the three paths it took at a compaction boundary has, by definition, taken the fourth path: silent corruption. ```python from dataclasses import dataclass, field from typing import Literal class CompactionLedgerViolation(RuntimeError): """Raised when a compaction plan would split or orphan a tool-call pair.""" pass @dataclass class ToolPair: call_id: str call_tokens: int result_tokens: int resolved: bool = False @property def mass(self) -> int: return self.call_tokens + self.result_tokens @dataclass class CompactionPlan: budget: int frame_mass: int pairs: list[ToolPair] = field(default_factory=list) def pinned_mass(self) -> int: return sum(p.mass for p in self.pairs if not p.resolved) def evictable_mass(self) -> int: return sum(p.mass for p in self.pairs if p.resolved) def plan_eviction(self, must_free: int) -> list[str]: """Return call_ids eligible for lossy summarization, oldest resolved first. Raises if the plan cannot free `must_free` without touching pinned mass or splitting a pair. """ if self.pinned_mass() + self.frame_mass > self.budget: raise CompactionLedgerViolation( f"pinned mass {self.pinned_mass()} + frame {self.frame_mass} " f"exceeds budget {self.budget}; eviction alone cannot satisfy " f"the budget contract without violating the ledger invariant. " f"Escalate: resolve-then-evict, extend budget, or tombstone." ) freed, evicted = 0, [] for pair in self.pairs: if pair.resolved and freed < must_free: evicted.append(pair.call_id) freed += pair.mass if freed < must_free: raise CompactionLedgerViolation( f"only {freed} tokens evictable from resolved pairs, " f"need {must_free}; remaining mass is pinned or frame." ) return evicted def compact(plan: CompactionPlan, must_free: int) -> list[str]: evicted = plan.plan_eviction(must_free) for cid in evicted: pair = next(p for p in plan.pairs if p.call_id == cid) if not pair.resolved: # Defensive: plan_eviction already filtered, but the invariant # must hold at the point of mutation, not only at planning time. raise CompactionLedgerViolation( f"attempted to evict unresolved pair {cid}; refusing." ) return evicted ```