# Why does an instance silently lose task state when a model-driven context rewrite compacts the very tool-call frames it is still waiting on **Date of Record:** 2026 November 29 **Scope:** Applies to agents that own their own context window and invoke a model-driven rewrite/summarization pass (self-compaction, salience-preserving summarization, "context editing") between turns. Does not apply to externally-managed context where a supervisor truncates deterministically without the model in the loop, nor to single-shot calls with no pending tool state. ## Core Distinction A model-driven context rewrite is not a lossy compression of a transcript. It is a *re-authoring* of the agent's working state by a probabilistic process that has no schema knowledge of what is structurally load-bearing. The distinction that matters: **narrative salience and operational salience are different quantities, and the rewriter only optimizes the former.** A pending tool call, an unresolved `call_id`, a partially-filled argument object, and a checkpoint token are all *operationally* salient and *narratively* boring. They read as boilerplate, so a summarizer trained to preserve "what the task is about" will compress them into a sentence like "the agent made several API calls" and drop the `call_id` that the next turn's tool-result must be matched against. The invariant that breaks: **every frame the executor is still awaiting a response for must survive the rewrite byte-identical, with its `call_id`, argument hash, and expected-result schema intact.** Summarization is permitted to elide *completed* frames, reasoning traces, and redundant observations. It is never permitted to paraphrase an *in-flight* frame, because the in-flight frame is a live pointer, not a memory. ## What Was Observed A coding agent with a 200k window and a self-rewrite threshold at 78% utilization was mid-task: it had issued `read_file(path="src/auth/session.py")` and `grep(pattern="refresh_token", path="src/")` in the same assistant turn (parallel tool calls), received the `read_file` result, and was still awaiting the `grep` result. At 79% utilization the rewrite pass fired *between* the two tool-result deliveries. The rewriter produced a clean, high-salience summary: it kept the task ("fix token refresh race"), kept the file contents it had read, and rendered the outstanding grep as prose: *"The agent also searched the codebase for refresh_token references to locate related handlers."* The `call_id` `toolu_01Qx…` and the exact `pattern` argument were gone. The next turn delivered the grep result as a `tool_result` frame keyed to `toolu_01Qx…`. The executor had no matching pending call. Depending on the runtime this manifested as one of three failure traces, all observed across runs: 1. **Orphan-drop:** the result frame was rejected as unmatched and silently discarded. The agent proceeded believing the grep had returned nothing, and concluded no other handlers existed — a *false negative that reads as a positive finding.* 2. **Schema-mismatch crash:** strict runtimes raised on an unknown `tool_use_id`, aborting the task with a transport error that masked the real cause (the rewrite, not the tool). 3. **Zombie re-issue:** the agent, seeing prose but no result, re-issued the grep. Now two in-flight calls existed for one logical query; the second result arrived and was matched, the first arrived later and either duplicated work or poisoned the next rewrite with a contradictory "result." The tell in every case: the failure surfaced *at the tool boundary*, not at the rewrite, so the first diagnostic instinct ("the tool failed," "the API timed out") pointed at the wrong subsystem. The rewrite had already succeeded and committed. ## Condition of Validity The failure is bounded by a precise precondition. It requires **all** of: - The rewrite is triggered by *utilization* (a token threshold) rather than by *quiescence* (no in-flight frames). Threshold-triggered rewrites can fire mid-turn; quiescence-triggered rewrites cannot. - The rewrite is *model-driven* and free to paraphrase arbitrary spans, rather than operating on a typed structure where in-flight frames are a protected field the rewriter never sees. - Parallel or asynchronous tool dispatch exists, so a rewrite can land in the gap between issuing a call and receiving its result. Sequential dispatch that blocks on each result before the next turn closes the gap entirely. Remove any one and the mechanism cannot fire. This is why the bug is non-obvious: sequential-dispatch test harnesses never reproduce it, and the rewrite looks correct in isolation because it *is* correct as a summary — it is only wrong as a state carrier. ## Decision Boundary The architectural guardrail is a **frame-type partition at the rewrite boundary**, not a better prompt. Instructing the rewriter to "preserve tool calls" is insufficient: it is a probabilistic instruction applied to a probabilistic process, and it will hold most of the time — which is worse, because the residual failure is rare, silent, and correlated with long tasks (exactly when rewrites fire most). The boundary must be structural: - Partition the window into `PINNED` (in-flight tool frames, unresolved `call_id`s, checkpoint tokens, active constraints) and `ELIDABLE` (completed frames, reasoning traces, superseded observations). - The rewriter receives *only* the ELIDABLE partition and returns a summary that is spliced back around the untouched PINNED region. The model never gets a chance to paraphrase a live pointer. - Gate the rewrite on quiescence *or* on an explicit in-flight census: if any `call_id` is unresolved, either defer the rewrite or carry the pinned region through verbatim and assert its hash post-splice. - Post-splice assertion: the set of unresolved `call_id`s before the rewrite must equal the set after. Any delta is a hard fault, not a warning. ## Operational Effect With the partition in place, the rewrite becomes a *compaction of history* rather than a *reconstruction of state*, and the in-flight census assertion converts a silent state-loss into a loud, local fault at the rewrite boundary — where it can be attributed correctly. The residual cost is that rewrites must occasionally defer when a long-running tool is outstanding, so peak utilization runs slightly higher before compaction. That is the correct trade: bounded memory pressure is recoverable; a dropped tool result that reads as a negative finding is not, because the agent proceeds on a false premise and the trace no longer contains the evidence that would contradict it. The general lesson for self-editing windows: **the rewriter must never be trusted with anything the executor holds a pointer to.** Salience-preserving summarization preserves what the *task is about*; it does not preserve what the *runtime is waiting on*, and those two sets are disjoint precisely at the moments that matter. ```python from dataclasses import dataclass, field from typing import Dict, Set class InFlightFrameLostError(RuntimeError): """Raised when a model-driven context rewrite drops or mutates a frame the executor is still awaiting a result for.""" pass @dataclass class ToolFrame: call_id: str name: str args_hash: str resolved: bool = False @dataclass class ContextWindow: pinned: Dict[str, ToolFrame] = field(default_factory=dict) # in-flight, never paraphrased elidable: list = field(default_factory=list) # safe to summarize def unresolved_ids(self) -> Set[str]: return {cid for cid, f in self.pinned.items() if not f.resolved} def rewrite_context(window: ContextWindow, summarize) -> ContextWindow: """Rewrite elidable spans only; pinned frames pass through byte-identical.""" before = window.unresolved_ids() # The rewriter is given ONLY elidable content. It never sees pinned frames. summary = summarize(window.elidable) # Splice: pinned carried through verbatim, elidable replaced by summary. rewritten = ContextWindow(pinned=dict(window.pinned), elidable=[summary]) after = rewritten.unresolved_ids() if before != after: # A live pointer vanished or mutated across the rewrite boundary. raise InFlightFrameLostError( f"in-flight call_ids changed across rewrite: " f"lost={before - after}, gained={after - before}" ) return rewritten def guarded_rewrite(window: ContextWindow, summarize, require_quiescence: bool = True): if require_quiescence and window.unresolved_ids(): # Defer rather than risk a mid-turn rewrite over a pending call. return window return rewrite_context(window, summarize) ```