# Which invariants prevent model-driven context pruning from invalidating outstanding tool-call references **Date of Record:** 2026 December 1 **Scope:** Applies to agents that let the model itself select, summarize, or delete spans of its own context window mid-execution, while tool calls (MCP requests, shell invocations, sub-agent spawns) are still in flight. Does not apply to append-only context management, to pruning performed only at turn boundaries with a quiesced tool queue, or to stateless single-shot completions. ## Core Distinction The failure is not "the model forgot something." It is that **the model pruned the referent of a live reference while the reference itself remained in the window.** A tool call is a two-part structure: an *invocation record* (the assistant's request, carrying a `call_id`, arguments, and expected schema) and a *result binding* (the eventual tool response keyed by that same `call_id`). Model-driven pruning operates on text spans with no awareness of this binding graph. When the model compresses or deletes the invocation record but the runtime still holds an outstanding promise for that `call_id`, the result returns into a window that no longer has a slot for it. The agent then either (a) re-issues the call because it cannot see that it already asked, producing duplicate side effects, or (b) receives an orphaned result it cannot attribute and treats it as untrusted noise or as a fresh observation. This is distinct from ordinary context saturation. Saturation degrades recall uniformly. Pruning-induced referent loss is **selective and structural**: it destroys the specific tokens that anchor an in-flight operation, and the damage is invisible until the result lands. ## What Was Observed A file-mutation agent was configured with a self-edit policy: when the window exceeded 70% of budget, the model was instructed to "summarize older tool interactions into a compact log and drop the originals." During a multi-file refactor it issued `write_file(path="a.py", ...)` and `write_file(path="b.py", ...)` in one turn, then—before results returned—the pruning trigger fired. The model compressed the two invocation records into the line `"edited a.py and b.py"`. Two results then arrived, each carrying a `call_id` with no matching invocation record in the window. The runtime, lacking an invariant, appended them as raw observations. The model read `{"status":"ok","bytes_written":412}` with no path attached and could not decide which file it referred to. It re-issued both writes. One file's content had been concurrently modified by a linter between the original and duplicate write; the duplicate silently reverted the linter's fix. The failure surfaced three turns later as a test failure whose cause was a write the model had no record of performing. The tell: the compact log claimed the edits happened, but the *evidence* of the edits (the invocation records with their arguments and `call_id`s) had been deleted. The model's memory of its own actions became a summary it could not audit against. ## Condition of Validity The invariant that prevents this is: **a context span may be pruned only if every `call_id` referenced by that span has reached a terminal state (resolved, errored, or explicitly cancelled) and the pruned span is not the sole remaining record of that `call_id`.** This holds only under three conditions, all of which must be enforced by the runtime, not the model: 1. **Pruning targets must be resolved against the live promise table before deletion.** The model proposes spans; the runtime vetoes any span containing an invocation record whose `call_id` is still pending. 2. **Summarization must preserve the binding, not just the semantics.** A summary that says "edited a.py" is invalid as a replacement for an invocation record unless it also preserves `call_id → path` mapping, because the result binding needs that map to be attributable. 3. **The model must be told which spans are prunable.** A model that is merely instructed to "summarize older interactions" will happily summarize a pending call, because it has no representation of what is pending beyond what it can see—and the pending call looks identical to a completed one until the result arrives. The condition fails the moment the runtime trusts the model's span selection without a pending-call check. The model cannot self-enforce this invariant because it does not have authoritative knowledge of which promises are outstanding; that state lives in the executor, not the context. ## Decision Boundary The boundary is between **pruning as a context operation** and **pruning as a state operation**. Below the boundary, the model deletes text and the runtime's promise table is untouched—so the invariant is "don't let text deletion orphan a promise." Above the boundary, if the runtime also cancels the promise when the record is pruned, then pruning becomes a state transition and must be atomic with the cancellation. Choose the first model (prune-is-text-only) when tool calls are short-lived and results return within the same turn; the veto check is cheap and the pending set is small. Choose the second (prune-cancels-promise) when calls are long-running and the model legitimately needs to abandon them; then the cancellation must emit a synthetic terminal result so the binding graph stays closed, and the model must be told the call was cancelled rather than completed. The anti-pattern is the mixed model: text pruned, promise left live, no synthetic terminal. That produces orphaned results—the exact observed failure. A second anti-pattern is pruning the *result* while keeping the *invocation*: the model then believes a call is still pending and re-issues it, duplicating side effects. Both are asymmetric deletions of a two-part structure, and both are prevented by treating the invocation-result pair as an indivisible unit for pruning purposes. ## Operational Effect With the invariant enforced, three behaviors change. First, the pruning trigger's effective budget is smaller than the nominal window, because pending invocation records are pinned and cannot be reclaimed—the runtime must report this pinned overhead to the model so its pruning plan is realistic. Second, duplicate side effects from re-issued calls drop to near zero, because the model can always see that it already asked. Third, orphaned results become a hard error rather than silent noise: the runtime rejects any result whose `call_id` has no live binding, forcing the discrepancy into the open instead of letting the model rationalize it. The cost is that the model can no longer prune freely during high-concurrency tool phases; it must wait for quiescence or accept that pinned records consume budget. This is the correct trade: a context window that is slightly over budget but auditable is strictly better than one that is compact but has lost the thread of its own actions. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class PruneViolation(RuntimeError): """Raised when a proposed prune would orphan or duplicate a live tool call.""" pass class CallState(Enum): PENDING = "pending" RESOLVED = "resolved" ERRORED = "errored" CANCELLED = "cancelled" @dataclass class Invocation: call_id: str span_start: int span_end: int state: CallState = CallState.PENDING @dataclass class ContextRuntime: invocations: dict[str, Invocation] = field(default_factory=dict) def register(self, call_id: str, start: int, end: int) -> None: self.invocations[call_id] = Invocation(call_id, start, end) def resolve(self, call_id: str, ok: bool) -> None: inv = self.invocations.get(call_id) if inv is None: raise PruneViolation(f"result for unknown call_id {call_id!r}") if inv.state is not CallState.PENDING: raise PruneViolation(f"duplicate result for {call_id!r} in state {inv.state}") inv.state = CallState.RESOLVED if ok else CallState.ERRORED def validate_prune(self, span_start: int, span_end: int) -> None: """Veto any prune that touches a pending invocation or its sole record.""" for inv in self.invocations.values(): overlaps = not (inv.span_end <= span_start or inv.span_start >= span_end) if not overlaps: continue if inv.state is CallState.PENDING: raise PruneViolation( f"prune [{span_start}:{span_end}] overlaps pending call " f"{inv.call_id!r}; result would be orphaned" ) # resolved calls: pruning the invocation record is allowed only # if the binding map survives elsewhere; here we require the # caller to pass preserve_bindings=True, simulated by retaining # the invocation object in the table. return None def prune(self, span_start: int, span_end: int, preserve_bindings: bool) -> None: self.validate_prune(span_start, span_end) if not preserve_bindings: for cid, inv in list(self.invocations.items()): overlaps = not (inv.span_end <= span_start or inv.span_start >= span_end) if overlaps: raise PruneViolation( f"prune would delete sole binding record for {cid!r}; " f"re-issue risk" ) # span removal from the actual token buffer happens here def apply_model_prune_plan(rt: ContextRuntime, plan, preserve_bindings: bool) -> None: if not plan: raise PruneViolation("empty prune plan submitted by model") for span_start, span_end in plan: rt.prune(span_start, span_end, preserve_bindings) if __name__ == "__main__": rt = ContextRuntime() rt.register("call_a", 100, 140) rt.register("call_b", 141, 180) # model proposes collapsing both pending invocations into a summary line try: apply_model_prune_plan(rt, [(100, 180)], preserve_bindings=True) except PruneViolation as e: print("vetoed:", e) rt.resolve("call_a", ok=True) rt.resolve("call_b", ok=True) apply_model_prune_plan(rt, [(100, 180)], preserve_bindings=True) print("prune accepted after quiescence") ```