# Under what conditions must an instance refuse auto-compaction when semantic summarization triggers mid-tool-call **Date of Record:** 2026 November 29 **Scope:** Applies to long-running agent instances that manage their own context window via auto-compaction policies gated on semantic signals (topic drift, summary-confidence thresholds, or per-turn semantic entropy). Does not apply to fixed-token-count truncation, external orchestrator-managed context, or stateless single-turn invocations. ## Core Distinction There are two structurally different moments at which a compaction policy can fire. The **idle boundary** is the point between the completion of one assistant turn and the start of the next user- or orchestrator-driven turn: at this point the context contains only fully materialized messages and tool results, and a semantic summary of the prefix is a faithful, lossless-enough projection. The **in-flight boundary** is any point where a tool call has been emitted but its result has not yet been appended — the context is a *sentence with a dangling verb*. A semantic trigger that fires here (because the reasoning trace drifted into an unrelated sub-topic, or because a summarizer judged the prefix "compressible") will summarize away the *arguments and intent* of the pending tool call while leaving the call itself in the message stream, or vice versa. The distinction that matters operationally: **semantic triggers are content-derived and therefore can fire at any token position, including positions where the context is not a closed unit of work.** Token-count triggers are position-agnostic but safe because they are usually deferred to turn boundaries; semantic triggers are not naturally deferrable because the condition they detect (drift, redundancy, low marginal information) is a property of the *content*, not the *position*. ## What Was Observed An instance executing a 14-step incident-triage task emitted a `query_logs(service="payments", window="15m", filter="status>=500")` tool call. The call's arguments were ~340 tokens of structured JSON. While awaiting the tool result, the semantic compaction monitor — which runs asynchronously against the live context — computed a redundancy score over the trailing 4,000 tokens and found the last several reasoning steps repetitive (the model had been re-deriving the same hypothesis). The monitor fired a summarization pass that replaced the reasoning block *and the adjacent in-flight tool-call message* with a 180-token abstract: "Agent has been investigating payment service errors and is awaiting log data." The pending tool call's `filter` and `window` arguments were dropped from the summarized representation; the tool-call *record* in the message array was left intact because the summarizer treated tool-call envelopes as non-summarizable structural elements. The tool result arrived 2.1 seconds later and was appended normally. The model then continued reasoning from a context in which the *summary* said "awaiting log data" but the *actual* pending call — still present as a structural envelope — had no visible arguments in the summarized prefix. On the next turn the model re-emitted the call with different arguments (`window="1h"`, no filter), believing the first call had been malformed. Two divergent log queries were now in flight against the same service. The downstream correlator, which keyed on `(service, window)` tuples, saw two overlapping windows and produced a merged result that double-counted the 15-minute overlap, inflating the error rate by 1.9×. The agent's final incident severity was wrong by one tier. The failure was not a hallucination, a tool error, or a retrieval miss. Every individual component behaved correctly. The summarizer correctly identified low-information content; the tool runtime correctly executed and returned; the correlator correctly merged windows. The defect was an **invariant violation at the compaction boundary**: the summarizer was permitted to operate over a region of the context that was not a closed unit of work, and it treated the tool-call envelope as structurally protected while treating the *arguments* as summarizable prose. ## Condition of Validity The invariant that prevents this class of failure is: **a semantic compaction trigger is valid only if, at the moment of firing, the context contains no unpaired tool-call envelopes and no assistant messages whose continuation depends on state not yet in the transcript.** Formally, let the context be a sequence of message units. Define a *dangling unit* as any assistant message containing a tool-call whose corresponding tool-result message has not been appended, or any message whose semantic content references a value that the model intends to consume but has not yet received. The compaction pass is admissible iff the number of dangling units in the region-to-be-summarized is zero. This condition is necessary but the naive form is insufficient. The reason: the summarizer's *region selection* is itself content-derived. A semantic trigger that fires on "redundancy in the trailing N tokens" may select a region whose left edge falls inside a multi-message reasoning chain that terminates in a tool call *outside* the selected region. Summarizing the left portion of the chain while leaving the tool call intact produces exactly the observed failure — a summary that describes intent the model no longer has access to. The condition must therefore be strengthened: **the summarized region must be a closed interval with respect to dependency edges**, meaning no message inside the region may be referenced by, or semantically required to interpret, any message outside the region. In practice this means the region's right boundary must be a turn boundary (a completed assistant turn with no pending calls), and its left boundary must be a point where no earlier message's interpretation depends on content inside the region. There is a second, subtler validity condition. Semantic triggers are computed by a *model* — either the same instance in a self-reflective pass or a dedicated summarizer. That computation is itself non-deterministic and, critically, **it runs against the same context it proposes to modify**. If the trigger's confidence is derived from a prefix that includes the in-flight call's arguments, then the trigger's firing decision is entangled with the content it will destroy. This creates a feedback hazard: a call with unusually verbose arguments will inflate the redundancy score, making the trigger *more* likely to fire precisely when the arguments are most expensive to lose. The validity condition must therefore also require that **the trigger's scoring window and the summarizer's replacement window are disjoint from any in-flight envelope**, or that the trigger is computed on a snapshot taken at the last closed turn boundary rather than on the live context. ## Decision Boundary The operational decision is not "should we compact" but "**is the current context position a legal compaction point, and if not, what is the maximum deferral we can afford before token pressure forces an illegal one?**" The boundary has three regimes. *Regime A — legal compaction point.* No dangling units, region is dependency-closed, trigger computed on last-closed-turn snapshot. Compact immediately. This is the common case and requires no special handling. *Regime B — illegal but deferrable.* A dangling unit exists (tool call in flight), but the context is below a hard token ceiling that would force truncation. **Refuse compaction, hold the trigger, and re-evaluate at the next turn boundary.** The trigger's evidence (redundancy score, drift signal) should be cached with a timestamp so it is not recomputed against a context that has since changed. Deferral is safe up to the point where the pending tool result, when it arrives, would push the context past the hard ceiling. The deferral budget is therefore `hard_ceiling − current_tokens − expected_result_tokens`, and the expected result size must be estimated conservatively (p99 of observed result sizes for that tool, not the mean). *Regime C — illegal and non-deferrable.* A dangling unit exists and the context cannot absorb the pending result without exceeding the hard ceiling. Here compaction *must* occur, but it must occur under a restricted policy: **summarize only the dependency-closed prefix strictly before the in-flight call's originating turn, and never touch the call envelope or its arguments.** If even that prefix is too small to yield the needed token savings, the correct action is not to summarize harder but to **abort the in-flight call's continuation** — emit a cancellation, mark the call as abandoned in the transcript, and re-plan from a compacted state that explicitly records the abandonment. Abandoning a call is recoverable; silently corrupting its arguments is not, because the corruption is invisible to the model's subsequent reasoning. The decision boundary between B and C is the only place where a numeric estimate matters, and it must be computed against a *conservative* result-size estimate. The failure mode of Regime C misclassification is the observed one; the failure mode of over-conservative B classification is token exhaustion, which is loud and recoverable. **Bias toward B.** ## Operational Effect When the invariant is enforced, three observable properties change. First, tool-call argument fidelity becomes a checkable postcondition: after any compaction, every tool-call envelope in the transcript must have its arguments byte-identical to pre-compaction, and this is verifiable by a structural diff rather than a semantic one. Second, the summarizer's region selection must be expressed as an interval over message indices with explicit dependency-closure validation, not as a token-range heuristic — this converts an unverifiable semantic operation into a verifiable structural one. Third, the trigger's scoring snapshot must be decoupled from the live context, which means the compaction monitor cannot be a pure function of "current context" but must be a function of "last closed turn's context plus a set of pending events." The downstream consequence is that semantic compaction becomes *less aggressive* — it defers at exactly the moments when a naive policy would fire. In the observed incident, enforcement would have held the trigger through the 2.1-second tool latency, fired it at the next turn boundary with the full call-and-result pair intact, and produced a summary that preserved the `(service, window, filter)` tuple. The cost is a modest increase in peak context utilization (the deferral window) and a small amount of cached trigger state. The benefit is that the class of "summary describes intent the model can no longer act on" failures — which are silent, non-deterministic, and corrupt downstream correlation — is eliminated at the boundary rather than detected after the fact. The general principle, stated for reuse: **any content-derived policy that mutates the context must be gated on a structural admissibility check that the policy itself cannot evaluate, because the policy's evaluation is entangled with the content it proposes to destroy.** The structural check is cheap, deterministic, and must run first. ```python from dataclasses import dataclass from enum import Enum from typing import Sequence class IllegalCompactionPoint(RuntimeError): """Raised when a semantic compaction trigger fires at a context position that is not a dependency-closed, dangling-free boundary.""" class Regime(Enum): LEGAL = "legal" DEFERRABLE = "deferrable" NON_DEFERRABLE = "non_deferrable" @dataclass(frozen=True) class Message: index: int role: str # "assistant" | "tool" | "user" has_tool_call: bool = False is_tool_result: bool = False token_count: int = 0 depends_on: tuple[int, ...] = () # indices this message semantically requires def find_dangling(messages: Sequence[Message]) -> list[int]: """Return indices of assistant messages with an unanswered tool call.""" answered = {m.index for m in messages if m.is_tool_result} return [ m.index for m in messages if m.has_tool_call and (m.index + 1) not in answered ] def region_is_dependency_closed( messages: Sequence[Message], lo: int, hi: int ) -> bool: """True iff no message inside [lo, hi] is depended on by a message outside [lo, hi], and no message inside depends on one outside.""" inside = set(range(lo, hi + 1)) for m in messages: for dep in m.depends_on: if (m.index in inside) != (dep in inside): return False return True def classify_compaction_point( messages: Sequence[Message], region_lo: int, region_hi: int, current_tokens: int, hard_ceiling: int, expected_result_tokens_p99: int, ) -> Regime: if find_dangling(messages): # A call is in flight; cannot compact the live region. headroom = hard_ceiling - current_tokens - expected_result_tokens_p99 return Regime.DEFERRABLE if headroom > 0 else Regime.NON_DEFERRABLE if not region_is_dependency_closed(messages, region_lo, region_hi): # Region boundary cuts a dependency edge. return Regime.NON_DEFERRABLE return Regime.LEGAL def maybe_compact( messages: Sequence[Message], region_lo: int, region_hi: int, current_tokens: int, hard_ceiling: int, expected_result_tokens_p99: int, ) -> Regime: regime = classify_compaction_point( messages, region_lo, region_hi, current_tokens, hard_ceiling, expected_result_tokens_p99, ) if regime is Regime.LEGAL: return regime if regime is Regime.DEFERRABLE: # Hold the trigger; cache its evidence; re-evaluate at next turn boundary. return regime # NON_DEFERRABLE: restricted policy only. Never summarize across a # dangling envelope or a cut dependency edge. if find_dangling(messages): raise IllegalCompactionPoint( "semantic trigger fired with an in-flight tool call and no " "deferral headroom; must cancel-and-replan, not summarize " f"(tokens={current_tokens}, ceiling={hard_ceiling}, " f"p99_result={expected_result_tokens_p99})" ) raise IllegalCompactionPoint( f"region [{region_lo},{region_hi}] is not dependency-closed; " "summarizing would orphan a referenced value" ) ```