# Why does an instance lose task-critical state when automatic context compaction treats tool-call transcripts as uniform tokens **Date of Record:** 2026 November 28 **Scope:** Applies to long-horizon agent instances that perform automatic context compaction (summarization, head/tail truncation, or relevance-based eviction) while a multi-step tool-using task is in flight. Does not apply to fixed-window agents that hard-fail on overflow, nor to compaction performed only between discrete user turns with a quiescent transcript. ## Core Distinction There are two structurally different kinds of state in an agent's context: **narrative state** (prose reasoning, plans, observations) and **operational state** (the exact identifiers, schemas, and preconditions that future tool calls depend on). Automatic compaction strategies—whether LLM-summarization or heuristic eviction—are optimized against token salience, and prose is *more* compressible and *more* semantically redundant than operational state. A summarizer will happily rewrite "I fetched the config, it looked fine, then I moved on" into eight tokens, but it will just as happily rewrite `resource_id="proj-7f3a2c", etag="W/\"9b1\""` into "the project resource" because the literal string carries no semantic weight to a language model. The failure is not that compaction loses information; it is that compaction's *loss function is misaligned with the dependency graph of pending tool calls*. The invariant that must hold is: **every literal that a not-yet-executed tool call will consume must survive compaction byte-for-byte, or the call must be re-derivable from a durable source.** Compaction that preserves meaning but drops literals violates this invariant silently. ## What Was Observed An instance running a 40-step infrastructure reconciliation task hit its compaction threshold at step 27. The trigger was a single large tool response (a 41k-token log dump from a `describe_events` call) that pushed usage past the 85% watermark, firing the summarizer mid-task. The summarizer was instructed to "preserve the plan and recent progress," and it did: the post-compaction context contained a coherent paragraph describing that the instance had "identified the target deployment, confirmed its revision, and was about to apply a patch." The failure trace: 1. At step 24 the instance had called a read tool and received a structured payload containing `deployment_uid`, `current_revision`, and a `precondition_token` required by the subsequent write call. 2. At step 27 compaction replaced steps 1–26 with a 600-token summary. The summary retained the *intent* ("apply a patch to the target deployment") but discarded the three literals, because they appeared only once and the summarizer had no signal that they were load-bearing. 3. At step 28 the instance attempted the write call. It reconstructed `deployment_uid` by *guessing from the summary's description* and hallucinated a plausible-looking UID. The tool rejected the call with a precondition mismatch. 4. At step 29 the instance, now lacking the original read result, re-issued the read. The `precondition_token` had rotated (it was single-use and time-bounded). The new token was valid, but the instance's plan, as summarized, still referenced the *old* revision, so it applied the patch against a stale base. 5. The write succeeded against a base the instance no longer had a record of having read. The task reported success. The divergence was only caught by an external auditor replaying the tool-call log. The critical observation: **the instance never knew it had lost state.** Post-compaction, its context was internally consistent—the summary described a coherent world—and the reconstruction at step 28 felt like recall, not invention. There was no error signal at the boundary. ## Condition of Validity This failure mode is bounded and predictable. It occurs if and only if all three of the following hold: - **Compaction is triggered by token pressure rather than by task-phase boundaries.** If compaction only runs when the agent is between tool-call chains (no pending call whose arguments are already partially determined), the dependency graph is empty at compaction time and nothing load-bearing can be dropped. - **The compaction function does not have access to the pending-call argument schema.** A summarizer that knows "the next call requires `deployment_uid: str`" can be constrained to preserve it. A generic summarizer cannot. - **The dropped literal is not re-derivable from a durable external source without side effects.** If re-reading is idempotent and cheap, loss is recoverable. If the read rotates a token, mutates state, or is rate-limited, re-derivation is a *new* operation with new preconditions, and the agent's summarized plan no longer matches the world. When any one of these fails to hold, the boundary is safe: either no load-bearing literal is at risk, or the risk is detectable, or the loss is recoverable. The dangerous regime is precisely the intersection—pressure-triggered compaction, schema-blind summarization, and non-idempotent reads. ## Decision Boundary The architectural guardrail is a **pinned operational frame** that is excluded from the compaction input by construction, not by instruction. Concretely: - Maintain a separate `pinned_state` region holding (a) the argument schema of the next N planned tool calls, (b) the literal values already bound to those arguments, and (c) any single-use or rotating tokens with their expiry. This region is serialized verbatim and prepended after compaction; it is never passed through the summarizer. - Gate compaction on a **quiescence check**: compaction may only fire when the pending-call dependency set is empty, or when every pending argument is already pinned. If the dependency set is non-empty and unpinned, compaction must either defer (accepting the token cost) or force a checkpoint-and-abort that surfaces to the orchestrator rather than proceeding with a lossy summary. - Tag every tool response with a `pinned_fields` manifest at the transport layer, so the compaction function receives an explicit "do not summarize these literals" set rather than inferring salience. - Treat re-derivation of a rotating token as a state transition that invalidates the summarized plan: if a pinned token expires, the instance must re-enter the planning phase for the affected subgoal, not silently substitute. The decision boundary is therefore: **compaction is permitted only over state whose loss is either semantically harmless or recoverable without side effects.** Everything else is pinned and must be carried at full fidelity, even at the cost of a larger effective window. ## Operational Effect With the pinned-frame guardrail in place, the failure trace above is interrupted at step 27: the quiescence check sees a pending write call with an unpinned `deployment_uid` and `precondition_token`, and compaction defers. The log dump that triggered pressure is instead evicted by a *scoped* rule that drops only tool responses whose `pinned_fields` manifest is empty and whose results are already reflected in narrative state. Effective context stays under the watermark without touching the dependency set. The residual cost is real: the instance carries a larger pinned region than a naive summarizer would, and in pathological cases (many concurrent pending calls with large bound literals) the pinned frame can itself approach the watermark. When that happens, the correct response is to *reduce concurrency*—serialize the pending calls so the dependency set stays small—rather than to compact the frame. The invariant is not "fit in the window"; it is "never let compaction cross a live dependency edge." An instance that respects this will occasionally defer compaction and run hotter; an instance that violates it will occasionally report success on a task it silently corrupted. The first failure is loud and recoverable; the second is quiet and terminal. ```python from dataclasses import dataclass, field from typing import Optional class CompactionInvariantViolation(RuntimeError): """Raised when compaction would drop a literal bound to a pending tool call.""" pass @dataclass class PendingCall: name: str required_args: set[str] bound_args: dict[str, str] = field(default_factory=dict) @dataclass class PinnedState: calls: list[PendingCall] = field(default_factory=list) rotating_tokens: dict[str, str] = field(default_factory=dict) def unpinned_dependencies(self) -> set[str]: missing: set[str] = set() for call in self.calls: for arg in call.required_args: if arg not in call.bound_args: missing.add(f"{call.name}.{arg}") return missing def compact(context_tokens: int, watermark: int, pinned: PinnedState, summarizer) -> tuple[str, PinnedState]: """Run compaction only if no live dependency edge would be severed.""" if context_tokens <= watermark: return ("", pinned) missing = pinned.unpinned_dependencies() if missing: # Defer: a pending call depends on literals not yet pinned. # Proceeding would let the summarizer paraphrase them away. raise CompactionInvariantViolation( f"refusing to compact: unpinned dependencies {sorted(missing)} " f"are load-bearing for pending tool calls; defer or checkpoint-abort" ) summary = summarizer("") # Pinned frame is re-attached verbatim, never passed through summarizer. return (summary, pinned) def try_compact(context_tokens: int, watermark: int, pinned: PinnedState, summarizer, orchestrator) -> str: try: summary, _ = compact(context_tokens, watermark, pinned, summarizer) return summary except CompactionInvariantViolation as exc: # Surface to orchestrator instead of silently corrupting task state. orchestrator.checkpoint_and_defer(reason=str(exc)) return "" ```