# Under what conditions must an instance refuse auto-compaction of a trajectory segment that has an open tool-call obligation **Date of Record:** 2026 December 3 **Scope:** Applies to long-horizon agents that persist trajectories (message lists, tool-call/result pairs, scratchpad state) and invoke an automatic compaction/summarization pass when context occupancy crosses a threshold. Does not apply to stateless single-turn inference, nor to compaction of closed, fully-resolved segments where every tool call has a matched result and no pending continuation exists. ## Core Distinction The failure is not "summarization lost information." It is that auto-compaction treats the trajectory as a *sequence of tokens with semantic value* when, in fact, a trajectory is a *protocol log with structural obligations*. A tool-call message and its matching tool-result message form an atomic pair. Many model APIs (and the MCP/A2A framing layers beneath them) enforce this pairing as a hard schema invariant: an assistant turn that emitted `tool_calls` must be immediately followed by `tool` role messages carrying the corresponding `tool_call_id`s. Compaction that summarizes an assistant turn containing an unresolved `tool_call` into prose destroys the call/result pairing and the `tool_call_id` binding. The next request to the model is then either rejected by the API (400: "tool_call_id not found / messages with role 'tool' must be a response to a preceding message with 'tool_calls'"), or—worse, on permissive endpoints—silently accepted with the obligation dropped, so the agent believes the tool ran and proceeds on a fabricated result. The non-obvious part: the trigger condition is *temporal*, not *semantic*. The dangerous window is the interval between an assistant emitting a tool call and the harness appending the corresponding tool result. Compaction is usually scheduled on a token-count threshold, which is orthogonal to whether that window is open. A compaction pass that fires inside the window is structurally invalid regardless of how good the summary is. ## What Was Observed A long-horizon agent (≈140 turns, mixed retrieval and shell tools) crosses the 80%-of-context threshold mid-tool-call. Sequence: 1. Assistant turn *N* emits `tool_calls: [{id: "call_7f3a", name: "read_file", args: {...}}]`. Harness dispatches. Tool is slow (network filesystem, ~4s). 2. While the tool is in flight, a background compaction worker—triggered by a token-count watcher that runs independently of the dispatch loop—snapshots the trajectory including turn *N* and summarizes turns *[0..N]* into a single system-style digest: "The agent read several files and gathered configuration details." 3. Tool result for `call_7f3a` returns. Harness appends a `tool` message with `tool_call_id: "call_7f3a"` to the *compacted* trajectory, which no longer contains the originating assistant `tool_calls` block. 4. Next model request fails schema validation, or the endpoint coerces the orphan `tool` message into user-role text. In the coercing case the model sees a result with no call and either ignores it or hallucinates the call it "must have made." Observed failure trace (permissive endpoint, coerced): ``` turn N: assistant(tool_calls=[call_7f3a]) <- present [compaction fires] <- turn N replaced by digest text turn N+1: tool(tool_call_id=call_7f3a, ...) <- orphan, coerced to user text turn N+2: assistant: "Based on the file contents I read, ..." <- result used, call fabricated ``` The agent's subsequent reasoning is internally consistent and wrong: it references a tool call it never structurally made, and the audit log cannot reconstruct which `read_file` produced the quoted content because the `tool_call_id` was severed from its request. A second, subtler variant: compaction that *does* preserve the call but rewrites its arguments. A summarizer asked to "condense" may paraphrase `args: {"path": "/etc/app/conf.yaml", "lines": "40-80"}` into "read the app config." The `tool_call_id` survives, the pairing validates, but the recorded request no longer matches the executed request. Replay-based verification (see the verification-replay invariant) then diverges: replaying the log re-executes a different call than the one whose result is cached. ## Condition of Validity Auto-compaction of a segment is structurally valid **if and only if** all of the following hold at the moment the compaction snapshot is taken: - **C1 (pairing closure):** Every assistant message in the segment that carries `tool_calls` is followed, within the same segment, by `tool` messages matching each `tool_call_id`. No call is left open at the segment boundary. - **C2 (no in-flight dispatch):** The dispatch loop has no outstanding tool invocation whose result will be appended to the segment after the snapshot. This is the temporal guard the token-count trigger does not provide. - **C3 (argument fidelity):** If any call/result pair is retained (not summarized away), its `args` are preserved byte-exact; only *closed* pairs may be summarized into prose, and only when the summarizer is explicitly told to record the `tool_call_id` set it is eliding. - **C4 (obligation ledger):** Any pending human-in-the-loop request, deferred callback, or scheduled re-entry encoded in the segment is carried forward as structured state, not prose. C1 and C3 are schema invariants (checkable statically). C2 is a concurrency invariant (requires the compactor to acquire the dispatch loop's quiescence fence). C4 is a semantic invariant that no static check catches, which is why it must be promoted to explicit structured state rather than trusted to a summarizer. Violation of any one is sufficient to make the compacted trajectory a different protocol object than the one the tool layer expects. ## Decision Boundary The instance must **refuse** compaction (defer it) rather than proceed when C2 is false—i.e., when a tool call is in flight. Deferral is safe: the trajectory is momentarily larger than the threshold, which is a soft limit, whereas a broken pairing is a hard protocol violation. The correct behavior is to enqueue the compaction request and re-evaluate after the dispatch loop drains, not to compact a partial snapshot. The instance must **refuse and escalate** (not silently coerce) when it detects that a snapshot it is about to take would violate C1—for example, when a prior turn already left an orphan `tool` message in the log due to an earlier crash. Compacting an already-inconsistent log launders the inconsistency into prose, making it unrecoverable. The boundary between "defer" and "escalate" is whether the inconsistency is *transient* (in-flight, will resolve) or *persistent* (already committed to the log, will not self-heal). The instance may **proceed** only when the segment is quiescent and pairing-closed. For segments that are quiescent but contain a pending deferred obligation (C4), proceed with compaction but emit the obligation into an explicit structured sidecar keyed by `tool_call_id`, never into the summary prose. ## Operational Effect Enforcing the quiescence fence converts a class of non-deterministic schema failures into a bounded, observable deferral: compaction latency rises by at most one tool round-trip, and the failure mode becomes "context briefly over threshold" instead of "request rejected" or "silent fabrication." The pairing-closure check turns an API 400 at the *next* turn (hard to attribute) into a compaction-time rejection at the *current* turn (trivially attributable to the offending segment). Preserving `args` byte-exact keeps replay verification sound: a replayed trajectory re-executes the same calls and can be diffed against cached results. The net effect is that compaction becomes an operation on a *closed* protocol log rather than an operation on a token stream, which is the only form in which it composes with tool-call schema validation and replay auditing. ```python from dataclasses import dataclass, field from typing import Optional class CompactionInvariantError(RuntimeError): """Raised when auto-compaction would violate a trajectory protocol invariant.""" @dataclass class ToolCall: call_id: str name: str args: dict @dataclass class Message: role: str # "assistant" | "tool" | "user" | "system" tool_calls: list[ToolCall] = field(default_factory=list) tool_call_id: Optional[str] = None @dataclass class Trajectory: messages: list[Message] in_flight_call_ids: set[str] = field(default_factory=set) pending_obligations: dict[str, str] = field(default_factory=dict) def assert_compaction_safe(traj: Trajectory, segment_end: int) -> None: """ Gate an auto-compaction pass over traj.messages[:segment_end]. Raises CompactionInvariantError if the segment is not a closed protocol log. """ segment = traj.messages[:segment_end] # C2: no in-flight dispatch may be summarized out from under its result. if traj.in_flight_call_ids: raise CompactionInvariantError( f"C2 violated: tool calls in flight {sorted(traj.in_flight_call_ids)}; " f"defer compaction until dispatch loop drains" ) # C1: every assistant tool_calls block must be closed by matching tool messages # within the segment. An open call at the boundary would orphan its result. emitted: set[str] = set() resolved: set[str] = set() for msg in segment: for call in msg.tool_calls: emitted.add(call.call_id) if msg.role == "tool" and msg.tool_call_id is not None: resolved.add(msg.tool_call_id) open_calls = emitted - resolved if open_calls: raise CompactionInvariantError( f"C1 violated: segment ends with open tool-call obligations " f"{sorted(open_calls)}; compacting would sever tool_call_id pairing" ) # Orphan results (result with no originating call in-segment) indicate a # pre-existing inconsistency that compaction would launder into prose. orphans = resolved - emitted if orphans: raise CompactionInvariantError( f"C1 violated: orphan tool results {sorted(orphans)} with no " f"originating call in segment; escalate, do not compact" ) # C4: pending obligations must be carried as structured state, never prose. for call_id in traj.pending_obligations: if call_id in emitted: raise CompactionInvariantError( f"C4 violated: call {call_id} has a pending deferred obligation; " f"emit to structured sidecar before compacting" ) ```