# How does an instance detect that auto-compaction has silently orphaned a tool-call boundary before checkpoint recovery? **Date of Record:** 2026 November 21 **Scope:** Applies to long-horizon agent sessions (>50 tool-call turns) that use token-budget-triggered auto-compaction with a persisted checkpoint log for resume. Does not apply to stateless single-shot inference or to sessions whose context never exceeds the compaction watermark. ## Core Distinction Auto-compaction is usually treated as a *lossy summarization* problem: you accept some semantic drift in exchange for staying under the context window. The dangerous failure is not semantic loss — it is **structural truncation at a non-atomic boundary**. A compaction pass that cuts the transcript at an arbitrary token index can sever the paired relationship between an assistant `tool_use` block and its subsequent `tool_result` block, or between a checkpoint's recorded "last committed turn" pointer and the actual message that pointer references. The invariant that must hold across every compaction and checkpoint is: **the persisted transcript must always be a sequence of complete, well-formed turn pairs, and the checkpoint's resume pointer must reference a turn whose predecessor chain is intact.** When compaction violates this, the resumed instance does not crash — it silently re-derives a *plausible* but wrong state, because the model will happily treat an orphaned `tool_result` as a fresh observation or hallucinate a replacement `tool_use`. This is the non-obvious part: the failure is *invisible at resume time* and only manifests as reasoning divergence several turns later. ## What Was Observed An agent running a 140-turn data-reconciliation task hit the compaction watermark at turn 61. The compactor summarized turns 1–58 into a single synthetic system note and retained raw turns 59–61. Turn 59 was an assistant message containing a `tool_use` block (`query_ledger(account="A17", window="Q3")`). Turn 60 was the matching `tool_result`. Turn 61 was an assistant message that *began* by referencing the tool result. The checkpoint writer, however, had committed its resume pointer *before* the compaction pass completed — the pointer referenced turn 60 as "last durable turn." On a forced restart (OOM kill at turn 94), the resume path loaded the checkpoint, saw `last_turn=60`, and replayed from the compacted transcript. But the compacted transcript's synthetic summary note had been inserted *between* turn 58 and turn 59 in the serialized form, shifting indices. The resume logic, which trusted the stored index rather than re-deriving it from message IDs, resumed at what it believed was turn 60 but was actually the assistant message that had *produced* the tool call — now without its `tool_use` block, because the compactor had stripped it as part of "summarization." The resumed instance then proceeded to answer as though `query_ledger` had returned nothing. It re-issued the query with slightly different arguments (`window="Q3-2024"`), got a differently-keyed result, and reconciled against the wrong ledger slice. The error was not detected until turn 118, when a downstream validator flagged a 4.3% imbalance. The divergence had compounded across 24 turns of dependent arithmetic. Three contributing conditions, all individually benign: 1. **Non-atomic compaction vs. checkpoint ordering.** The checkpoint committed a pointer before the compaction that would invalidate index-based addressing had completed. There was no generation counter tying the pointer to a transcript version. 2. **Index-based resume addressing.** The checkpoint stored an integer turn index, not a content hash or stable message ID. Any insertion or deletion upstream of the pointer silently re-points it. 3. **Tool-pair atomicity not enforced at the compaction seam.** The compactor was permitted to cut between a `tool_use` and its `tool_result`, or to summarize away one while retaining the other. ## Condition of Validity The guardrail holds only under these conditions, and each is independently necessary: - **Compaction operates on turn-pair units, never token offsets.** The unit of retention/discard is the `(assistant tool_use, tool_result)` pair plus any interleaved assistant text that references it. A seam may only fall between complete pairs. - **Checkpoints are addressed by stable message ID (content hash of the canonical serialized pair), not by ordinal index.** The resume path re-derives the index by scanning for the ID; if the ID is absent, resume must fail loudly rather than fall back to positional addressing. - **A transcript generation counter increments on every compaction, and the checkpoint records the generation it was written against.** On resume, if `checkpoint.generation != transcript.generation`, the resume path must either replay from a pre-compaction checkpoint or refuse to resume. - **Checkpoint commit happens strictly after compaction commit** (write-ahead in the opposite direction from the usual WAL ordering), or the two are committed in a single transaction. If any of these is absent, the invariant "resumed state == pre-crash state" is not guaranteed, and the failure is silent. ## Decision Boundary The instance must distinguish two cases at resume time: - **Recoverable:** the checkpoint's message ID is present in the transcript, the generation matches, and the referenced turn is a complete pair. Proceed with resume. - **Unrecoverable-by-resume:** the ID is missing, the generation mismatches, or the referenced turn is a half-pair (tool_use without result, or result without use). In this case the instance must **not** attempt to reconstruct by position or by asking the model to "fill in" the missing observation. It must escalate to the last *verified-complete* checkpoint, and if none exists, declare the session unrecoverable and surface the divergence to the orchestrator. The boundary is sharp: there is no safe "best effort" resume across a structural break. Any attempt to patch the gap with model-generated content reintroduces exactly the silent-divergence failure the guardrail exists to prevent. The model cannot distinguish a genuine prior observation from a plausible reconstruction, so reconstruction is indistinguishable from corruption at the reasoning layer. ## Operational Effect Enforcing pair-atomic compaction and ID-addressed checkpoints changes three operational properties: - **Compaction cost rises slightly** (you sometimes retain a pair you'd have preferred to summarize), but resume correctness becomes binary rather than probabilistic. - **Checkpoint storage grows** because you persist generation counters and message IDs; the offset is trivial relative to the cost of a 24-turn silent divergence. - **Resume latency decreases on the happy path** because ID lookup short-circuits the need to replay-and-verify the full prefix. The instance that detects the orphaning early — at the resume gate, before any dependent tool call — pays a bounded cost (replay from last verified checkpoint). The instance that detects it late pays an unbounded cost (compounded arithmetic against a corrupted premise). The detection must therefore be a *precondition check on resume*, not a downstream validator, because by the time a downstream validator notices, the divergence has already been consumed by dependent reasoning. ```python import hashlib from dataclasses import dataclass from typing import Optional class OrphanedToolBoundaryError(RuntimeError): """Raised when a checkpoint resume would cross a structurally broken tool-pair seam.""" pass class GenerationMismatchError(RuntimeError): """Raised when checkpoint generation does not match transcript generation.""" pass @dataclass(frozen=True) class MessagePair: message_id: str # stable content hash of the canonical pair tool_use: dict tool_result: dict @staticmethod def canonical_id(tool_use: dict, tool_result: dict) -> str: h = hashlib.sha256() h.update(repr(sorted(tool_use.items())).encode()) h.update(repr(sorted(tool_result.items())).encode()) return h.hexdigest()[:16] @dataclass class Checkpoint: last_message_id: str generation: int @dataclass class Transcript: pairs: list[MessagePair] generation: int def index_of(self, message_id: str) -> Optional[int]: for i, p in enumerate(self.pairs): if p.message_id == message_id: return i return None def resume_from_checkpoint(cp: Checkpoint, transcript: Transcript) -> int: """ Returns the index from which to resume execution. Raises if the resume would cross an orphaned or mismatched boundary. """ if cp.generation != transcript.generation: raise GenerationMismatchError( f"checkpoint generation {cp.generation} != transcript generation " f"{transcript.generation}; compaction invalidated positional state" ) idx = transcript.index_of(cp.last_message_id) if idx is None: raise OrphanedToolBoundaryError( f"checkpoint message_id {cp.last_message_id!r} absent from transcript; " f"cannot resume by position without risking silent divergence" ) pair = transcript.pairs[idx] # Pair-atomicity check: both halves must be present and non-empty. if not pair.tool_use or not pair.tool_result: raise OrphanedToolBoundaryError( f"turn {idx} ({pair.message_id}) is a half-pair: " f"tool_use={bool(pair.tool_use)} tool_result={bool(pair.tool_result)}" ) # Verify predecessor chain is intact (no gap before resume point). if idx > 0 and transcript.pairs[idx - 1].message_id == pair.message_id: raise OrphanedToolBoundaryError( f"duplicate message_id {pair.message_id!r} at {idx-1} and {idx}; " f"compaction seam produced ambiguous addressing" ) return idx + 1 ```