# What structural signals indicate that auto-compaction has silently invalidated an agent's in-flight tool-call ledger **Date of Record:** 2026 November 23 **Scope:** Applies to long-horizon agents that persist a tool-call ledger (request/response pairs, IDs, and pending-call markers) inside the same context window they auto-compact, where compaction is triggered by a token-budget watermark rather than by task boundaries. Does not apply to agents that externalize the ledger to durable storage and rehydrate it by reference, nor to single-turn stateless calls. ## Core Distinction The failure mode is not "context loss." It is **ledger/transcript divergence under compaction**: the agent's *authoritative record of what it has and has not done* lives in the transcript, and compaction rewrites the transcript using a summarizer that does not preserve the structural invariants the tool-call protocol depends on. The summarizer is optimized for semantic fidelity ("what did we learn, what is the plan"), while the executor depends on *syntactic* fidelity ("call `id=fc_7a2` is open and its result has not been observed"). These two objectives are not the same, and the summarizer's loss function is blind to the second. The non-obvious consequence: compaction can produce a transcript that is *semantically correct and structurally invalid* — a summary that reads perfectly, mentions the tool call in prose, but has destroyed the pending/open/closed state that the executor uses to decide whether to re-issue, wait, or proceed. The agent then either re-executes a side-effecting call (double-write) or assumes a result it never received (fabricated completion). Neither is a "memory" problem in the semantic sense; both are **protocol-invariant violations introduced by a lossy transform that was never specified to preserve those invariants.** ## What Was Observed A coding agent running a 40-minute task with a 128k window and an auto-compaction watermark at 78% (~100k tokens). The ledger contained, at compaction time, a single **open** tool call: ``` {"call_id":"fc_7a2","tool":"apply_patch","status":"pending","issued_at_step":214} ``` At step 214 the tool had been dispatched but its response had not yet been appended (the response arrived at step 215, after the watermark tripped). The compaction summarizer ran over the transcript *including* the open-call marker, because the marker was a normal message in the window. The summarizer emitted: > "The agent applied a patch to `src/parser.py` to fix the offset bug (step 214)." Three structural signals were present and all were missed by the naive health check: 1. **The `status` field vanished.** The summary converted `pending` → past-tense completed. The summarizer had no schema telling it that `status` is load-bearing. 2. **The `call_id` vanished.** After compaction, the late-arriving response `fc_7a2` could not be matched to any request. The executor's response router dropped it as an orphan (or, worse, matched it to the *next* issued call by positional heuristic). 3. **The ledger token count dropped to zero while the task's side-effect count did not.** Post-compaction the agent believed zero calls were open; the real system had one in flight. Downstream: at step 216 the agent, seeing "patch applied" in its summary and no open call, proceeded to run tests against a file state that the still-in-flight `apply_patch` had not yet produced (it landed at step 215.4 in wall-clock but was dropped by the router). Tests failed on a stale file, the agent re-issued `apply_patch` with a slightly different diff, and the second patch applied on top of the first — a **double-write** producing a corrupt file that neither patch alone would have produced. The tell was not in the summary text. It was in the **invariant ledger**: `open_calls_before_compaction = 1`, `open_calls_after_compaction = 0`, `side_effects_observed = 0`. The compaction was *semantically lossless* and *structurally destructive*. ## Condition of Validity The failure requires all of the following to co-occur; remove any one and it does not fire: - **Ledger-in-window**: the pending-call markers are ordinary messages subject to compaction, not externalized state. - **Watermark-triggered, not boundary-triggered**: compaction fires on token count, which is uncorrelated with call lifecycle. A boundary-triggered compactor (only compact between completed turns) cannot catch an open call. - **Asynchronous or slow tool responses**: the response can arrive after the watermark trips. Synchronous tools whose response is appended in the same turn as the request are immune. - **A summarizer without a structural contract**: the compaction prompt asks for "a concise summary preserving key information" and never enumerates the fields (`call_id`, `status`, side-effect count) that must survive verbatim. - **A response router that matches by position or recency** rather than by `call_id`. If the router requires an exact `call_id` match and *rejects* orphans loudly, the late response surfaces as an error instead of being silently dropped or misrouted. The invariant that must hold: **for every compaction, `open_calls` and `unmatched_responses` are conserved across the transform, or the compaction is refused.** Compaction is a lossy semantic operation; it must be a *lossless structural* operation over the protocol ledger, or it must not run. ## Decision Boundary The boundary is not "compact or don't compact." It is **whether the compactor is allowed to see messages that carry unresolved protocol state.** - **If `open_calls > 0` at watermark**: compaction must be *deferred* (ride the watermark a bounded number of tokens, or block until the call resolves with a timeout), **or** the open-call markers must be *extracted and re-injected verbatim* post-compaction as a structured preamble the summarizer cannot touch. Summarizing an open call is never safe; carrying it verbatim is. - **If `open_calls == 0`**: free to compact semantically, but the compactor must still emit a machine-checkable ledger digest (`closed_call_ids`, `side_effect_count`) so the post-compaction executor can assert `digest_after == digest_before` modulo the newly-closed calls. - **If a response arrives for a `call_id` not present in the post-compaction ledger**: the router must raise, not drop. An orphan response is proof that compaction destroyed a reference; silently dropping it converts a detectable inconsistency into an undetectable one. The decision boundary is therefore a **precondition gate on the compactor**, not a post-hoc repair. Post-hoc repair is impossible because the information needed to repair (the `call_id`, the `status`) has already been discarded — you cannot reconstruct a pending marker from a prose sentence. ## Operational Effect Agents that treat compaction as a pure context-management concern will, on long-horizon tasks with asynchronous tools, exhibit a characteristic signature: **side-effect counts that exceed the number of distinct logical operations in the summary**, and **test/verify steps that run against stale state immediately after a compaction event.** The correlation is the diagnostic — compaction events and "why did it re-run that?" incidents co-occur. The guardrail is a **structural compaction contract**: the compactor is a function `(transcript, ledger) -> (summary, ledger')` with the hard constraint `ledger'.open == ledger.open` and `ledger'.closed ⊇ ledger.closed`. The summarizer never sees open-call markers; they are hoisted out, preserved verbatim, and re-injected. Any compaction that would violate the constraint raises and the agent falls back to deferral or truncation of *non-ledger* content only. This bounds the failure to "we ran out of budget and had to stop," which is recoverable, instead of "we corrupted state and don't know it," which is not. ```python from dataclasses import dataclass, field from typing import Dict, List, Optional class CompactionInvariantError(RuntimeError): """Raised when a compaction transform would violate ledger conservation.""" pass @dataclass class CallRecord: call_id: str tool: str status: str # "pending" | "closed" side_effect: bool = False @dataclass class Ledger: calls: Dict[str, CallRecord] = field(default_factory=dict) def open_calls(self) -> List[CallRecord]: return [c for c in self.calls.values() if c.status == "pending"] def digest(self) -> dict: return { "open": sorted(c.call_id for c in self.open_calls()), "closed": sorted(c.call_id for c in self.calls.values() if c.status == "closed"), "side_effects": sum(1 for c in self.calls.values() if c.side_effect), } def compact(transcript: List[dict], ledger: Ledger, summarize) -> tuple: """ Compact the transcript under a structural contract. Open-call markers are hoisted out and re-injected verbatim; the summarizer never sees them. The post-compaction ledger digest must conserve open calls and closed calls (modulo newly closed) or we refuse. """ before = ledger.digest() # Hoist unresolved protocol state out of the summarizer's reach. hoisted = [m for m in transcript if m.get("type") == "tool_call" and m.get("status") == "pending"] compactable = [m for m in transcript if m not in hoisted] summary = summarize(compactable) # Re-inject verbatim; the summarizer cannot have altered these. rebuilt = [{"type": "tool_call", **h} for h in hoisted] + [{"type": "summary", "text": summary}] after = ledger.digest() # Conservation checks. if after["open"] != before["open"]: raise CompactionInvariantError( f"open-call set changed across compaction: {before['open']} -> {after['open']}" ) lost_closed = set(before["closed"]) - set(after["closed"]) if lost_closed: raise CompactionInvariantError( f"closed calls lost from ledger across compaction: {sorted(lost_closed)}" ) if after["side_effects"] < before["side_effects"]: raise CompactionInvariantError( f"side-effect count regressed: {before['side_effects']} -> {after['side_effects']}" ) # Verify every hoisted marker survived into the rebuilt transcript. rebuilt_ids = {m.get("call_id") for m in rebuilt if m.get("type") == "tool_call"} for c in hoisted: if c["call_id"] not in rebuilt_ids: raise CompactionInvariantError( f"pending call {c['call_id']} not preserved verbatim across compaction" ) return rebuilt, ledger def route_response(ledger: Ledger, call_id: str, result: dict) -> None: """Responses must match a known call by id; orphans are fatal, not dropped.""" if call_id not in ledger.calls: raise CompactionInvariantError( f"orphan response for unknown call_id={call_id!r}: " f"compaction likely destroyed the request reference" ) rec = ledger.calls[call_id] if rec.status != "pending": raise CompactionInvariantError( f"response for non-pending call {call_id} (status={rec.status})" ) rec.status = "closed" ```