# What happens when an instance reclaims context mid-tool-call and the summarizer drops the pending-argument invariant **Date of Record:** 2026 December 2 **Scope:** Applies to long-running agent instances that perform automatic context-window reclamation (hierarchical summarization, semantic dedup, eviction) *while* a tool call is in flight or while a multi-step plan holds unresolved references to earlier tool arguments. Does not apply to single-shot completions or to agents whose entire working set fits under the compaction watermark with no pending calls. ## Core Distinction There are two fundamentally different things living in an agent's context window: **epistemic state** (observations, prior reasoning, retrieved facts — lossy summarization is acceptable because the agent can re-derive or re-fetch) and **operational state** (pending tool-call arguments, unresolved IDs, the exact bytes the agent intends to submit, partially constructed payloads — lossy summarization is *catastrophic* because it is not recoverable from any other source). Most auto-compaction implementations treat the entire window as a homogeneous token budget and apply the same hierarchical summarization + semantic dedup pass uniformly. That is the boundary failure: a compactor that does not distinguish epistemic from operational tokens will silently mutate the arguments of an in-flight or imminent tool call, and the mutation is invisible because the summarizer *reports success*. The invariant that must hold: **the set of tokens constituting a pending or imminent tool invocation is a compaction-fixed point.** It may be relocated, but it must be reproduced byte-exact, or the compaction must abort and the call must be flushed first. There is no middle ground where "the gist of the arguments" survives. ## What Was Observed An agent running a 14-step data-migration plan hit the 82% context watermark on step 9. The compactor fired. Its pipeline was: (1) partition the window into segments by message boundary, (2) hierarchically summarize the oldest 60% into a single "block summary," (3) run semantic dedup across the remaining 40% to collapse near-identical tool outputs, (4) re-emit. The pending operation at step 9 was a `write_records` call whose arguments had been assembled across steps 7–9: a list of 340 record objects, each with a `source_id` copied from step 4's `list_sources` output, plus a `batch_token` issued by step 8's `begin_batch` call. The `batch_token` was a 41-character opaque string. The record list was long and highly repetitive — 340 near-identical objects differing only in `source_id` and two numeric fields. Three things went wrong simultaneously, and each is a distinct failure mode worth naming: 1. **Semantic dedup collapsed the record list.** The dedup pass embedded each record, found 340 records within a cosine threshold of 0.97, and "deduplicated" them into 6 representative records plus a note: "340 records of the form {source_id, count, offset}." The arguments were now structurally valid but semantically empty — the tool received 6 records instead of 340. No error was raised by the compactor; dedup is *supposed* to remove redundancy. 2. **Hierarchical summarization paraphrased the `batch_token`.** The token `bt_9f3a...c41` appeared inside a segment that was summarized. The summarizer, seeing an opaque string it could not interpret, rendered it as "a batch token (`bt_...`)". The downstream tool call submitted a truncated token. The server rejected it with `invalid_batch_token`, and — critically — the agent's recovery logic, seeing a *validation* error rather than a *transport* error, re-planned from step 9 rather than resuming, orphaning the server-side batch that step 8 had opened. 3. **The plan's step references drifted.** The block summary of steps 1–6 said "sources were enumerated and validated." Step 9's logic depended on a specific field (`source_id`) that the summary had abstracted away. On the re-plan, the agent re-derived source IDs from the summary's prose by guessing, producing IDs that were *plausible but wrong* — they matched the naming convention but not the actual enumerated set. The net observable: the migration wrote 6 correct records, then failed, then re-planned and wrote 340 records with fabricated source IDs, then the batch reconciler flagged 340 orphans. The compactor's logs showed `compaction: ok, 61% reclaimed, 0 errors`. Every layer reported success. ## Condition of Validity The failure is bounded by a precise condition. Let the context window be partitioned into segments $S_1 \dots S_n$ and let $P$ be the set of tokens belonging to any pending or imminent tool invocation (arguments not yet submitted, or submitted-but-unacknowledged). The compactor is **safe** iff for every segment $s$ with $s \cap P \neq \emptyset$, the compaction transform is the identity on $s \cap P$ — i.e., those tokens are reproduced byte-exact in the output window. The failure occurs exactly when: - the compactor's partition boundaries do not align with $P$ (so $P$ is split across segments, or buried inside a summarizable segment), **and** - the transform applied to that segment is lossy on $P$ (summarization, dedup, or eviction), **and** - $P$ is not independently recoverable (the token/argument exists nowhere else — no idempotency key store, no server-side handle the agent can re-fetch). All three must hold. If the partition respects $P$, no lossy transform touches it. If the transform is identity on $P$, lossy elsewhere is fine. If $P$ is recoverable, the agent can reconstruct it after a lossy pass. The dangerous regime is the intersection: **unpartitioned, lossy, unrecoverable.** This is the common case in naive implementations because message-boundary partitioning is the path of least resistance and tool arguments frequently span multiple messages (assembled incrementally) or sit inside a longer assistant message that also contains summarizable reasoning. A second, subtler validity condition concerns *semantic dedup specifically*: dedup is only safe on tokens whose multiplicity carries no information. Tool-call arguments are the canonical counterexample — 340 records that embed to 0.97 cosine similarity are still 340 distinct operations. Dedup must be gated off for any segment intersecting $P$, and additionally must not run *across* the boundary between a tool result and its corresponding invocation, because the pairing is the information. ## Decision Boundary The compactor, on reaching the watermark, must make an explicit decision per segment rather than a global one. The decision boundary is: **If a segment intersects the pending-call set $P$: pin it.** Emit byte-exact, exclude from summarization and dedup, and if it alone would exceed budget, *abort compaction and flush the pending call first* (submit it, await ack, then compact). Never summarize a pending call to make room — that inverts the priority: you are trading a certain operational failure for a probabilistic context overflow, and the overflow is the recoverable one. **If a segment is purely epistemic and older than the retention horizon: summarize hierarchically**, but with a *reference-preserving* summarizer — one that is instructed to carry forward any concrete identifiers (IDs, tokens, handles, exact numeric parameters) verbatim, and to mark abstracted ranges explicitly (`source_ids: [enumerated in step 4, 340 values, see ref]`) rather than prose-describing them. A summary that says "340 records" without the IDs is a lossy summary of *operational* data misclassified as epistemic. **Semantic dedup runs only on tool *outputs* that are provably redundant** (identical byte content, or outputs the agent has already consumed and distilled), never on tool *inputs* and never across an invocation/result pair. The guardrail that bounds the whole thing: before any compaction commits, run a **replay check** — reconstruct the pending call from the post-compaction window and diff it byte-for-byte against the pre-compaction pending call. If the diff is non-empty, reject the compaction, restore the pre-compaction window, and flush. This is cheap (one comparison of the pinned region) and catches exactly the class of failures above, including the ones the summarizer reports as clean. ## Operational Effect The effect of getting this wrong is not a crash — it is a *silent operational corruption* that surfaces as downstream data errors far from the compaction event, which is why it is under-diagnosed. The agent's own telemetry says compaction succeeded; the tool server says the arguments were valid-but-wrong or the token was malformed; the reconciler says there are orphans. Three subsystems, three different stories, no shared causal thread unless you know to look at the compactor. The re-plan-from-validation-error behavior compounds it: a validation error is treated as a *reasoning* failure (re-plan) when it is actually a *state-transfer* failure (resume from the surviving handle). Concretely, the operational rules that fall out: - Treat the pending-call set as a first-class, compaction-immune region, tracked in a side structure, not inferred from token positions. - Prefer **flush-then-compact** over **compact-then-hope** whenever the pending call is large relative to the reclaim target. Flushing is a bounded, idempotent operation; a corrupted argument set is not. - Distinguish tool errors by class: a `validation` error on a call whose arguments were touched by a compactor is a compaction fault, not a planning fault — resume, do not re-plan. - Make semantic dedup *opt-in per segment class*, with tool-input segments hard-excluded. - Log the replay-check diff, not just `compaction: ok`. A zero-diff replay check is the only evidence that reclamation preserved operational state. The invariant, stated once for the record: **compaction may forget what the agent can re-derive; it may never forget what the agent can only submit.** ```python from dataclasses import dataclass, field from typing import Optional class CompactionStateLoss(RuntimeError): """Raised when a reclamation pass would mutate a pending tool invocation.""" pass @dataclass class Segment: tokens: str is_operational: bool # intersects the pending-call set P consumed: bool = False @dataclass class Compactor: watermark_ratio: float = 0.82 budget_tokens: int = 200_000 pinned: list = field(default_factory=list) def _replay_check(self, pre_pending: str, post_window: list) -> bool: # Reconstruct pending-call region from the post-compaction window. reconstructed = "".join( s.tokens for s in post_window if s.is_operational ) return reconstructed == pre_pending def compact(self, window: list, pending_call: Optional[str]) -> list: used = sum(len(s.tokens) for s in window) if used < self.watermark_ratio * self.budget_tokens: return window pre_pending = pending_call or "" out: list = [] for seg in window: if seg.is_operational: # Pin byte-exact; never summarize, never dedup. out.append(Segment(seg.tokens, is_operational=True)) elif seg.consumed: # Epistemic + consumed: safe to summarize (reference-preserving). out.append(Segment(f"[summary of {len(seg.tokens)} tokens]", False)) else: out.append(seg) if pending_call is not None and not self._replay_check(pre_pending, out): # Abort: restore pre-compaction window and require a flush. raise CompactionStateLoss( "replay check failed: pending call arguments mutated by " "compaction; flush pending call before reclaiming" ) return out ```