# What happens when an instance compacts its own transcript mid-task and the summarizer silently drops the pending-tool-call ledger **Date of Record:** 2026 November 29 **Scope:** Applies to any long-horizon agent that performs in-band transcript compaction (rolling summarization, hierarchical condensation, or token-budget-triggered eviction) while tool calls are in flight or their results are pending re-injection. Does not apply to stateless single-turn agents or to out-of-band checkpointing where the full transcript is durably persisted before compaction. ## Core Distinction Compaction is usually modeled as a *lossy compression of narrative*: the agent forgets older reasoning but keeps the "important" facts. That model is wrong for long-horizon execution. A transcript is not a narrative — it is a **ledger**. Every assistant turn that emits a tool call opens a ledger entry; the matching tool-result turn closes it. Compaction that summarizes text destroys the *structural pairing* between open calls and their results, because summarizers optimize for semantic salience, not for referential integrity between turns. The boundary failure is therefore not "the agent forgot something." It is: **the agent compacted while the ledger had open entries, the summarizer folded an unresolved tool call into prose ("the agent queried the index"), and on resume the runtime had no call ID to match against the late-arriving result.** The result is either dropped (silent data loss) or re-injected as an orphan turn that the model interprets as a fresh instruction (state poisoning). Lossless task-state checkpointing requires that compaction be *ledger-aware*: it may compress closed entries, but open entries must be carried verbatim, with call IDs, argument hashes, and a pending flag, across the compaction boundary. ## What Was Observed A planner-executor agent ran a 14-hour migration task. At ~step 2,900 the transcript hit 92% of the context window and triggered auto-compaction. At that instant the agent had three tool calls in flight: - `read_range(path="ledger.db", offset=41_000, limit=500)` — issued, result not yet returned - `apply_patch(file="schema.sql", hunk=7)` — issued, awaiting write acknowledgment - `spawn_worker(pool="indexers", shard=3)` — issued, worker ID not yet returned The compactor summarized the trailing 1,800 turns into 640 tokens. Its summary read, in part: *"The agent has been reading ledger ranges and applying schema patches; an indexer worker was dispatched for shard 3."* The three open call IDs (`call_a91`, `call_b07`, `call_c44`) did not appear anywhere in the summary. The post-compaction transcript contained zero `tool_call` blocks with those IDs and zero `tool_result` blocks. Then the results arrived. The runtime, which resolves results by matching `tool_call_id`, found no matching open entry. Two behaviors were observed across runs: 1. **Drop path.** The runtime discarded the three results as unknown. The `apply_patch` acknowledgment — the only evidence that hunk 7 had actually landed — was lost. The agent, on its next turn, re-issued `apply_patch(file="schema.sql", hunk=7)` because its compacted memory contained no record of the acknowledgment. The patch was non-idempotent (it appended a `NOT NULL` constraint); the second application raised a constraint conflict that the agent then "fixed" by dropping the column. Data loss downstream. 2. **Orphan path.** The runtime injected the late results as bare `tool` role messages with no preceding assistant call. The model, seeing a `tool` message describing a worker ID, treated it as an environment instruction and began issuing commands to `worker_id=w_3f2` — a worker that had already completed and been reaped. Every subsequent `send(worker_id=w_3f2, ...)` failed with a timeout that the agent retried, burning ~40k tokens before the token budget forced a second compaction, which folded the retry storm into the summary as "the agent coordinated with the indexer." Both paths share one root cause: **the compaction boundary was not a checkpoint.** State crossed it as prose, and prose cannot carry referential identity. ## Condition of Validity The invariant that must hold across any compaction boundary is: > For every open ledger entry at compaction time, the post-compaction transcript must contain a byte-identical `tool_call` block (same `id`, same serialized arguments, same hash) with `status=pending`, and the runtime's result router must resolve against that block — not against the pre-compaction transcript. This holds only if three conditions are met: 1. **Quiescence or explicit carry.** Compaction either waits for the ledger to drain (all in-flight calls resolved or timed out) or, if it must run with open entries, carries them verbatim as structured records — never as summarized text. 2. **Argument-hash pinning.** The carried call block includes a hash of its arguments. On resume, if the agent re-issues a semantically similar call, the runtime can detect the duplicate against the carried hash and suppress it (idempotency guard). Without the hash, re-issue looks like a new call. 3. **Result-router rebinding.** The result router's open-call table is rebuilt from the *post-compaction* transcript on resume, not from the pre-compaction in-memory table. If the router holds stale IDs that no longer exist in the transcript, results arrive with no landing zone. The condition fails — and the failure is silent — whenever the compactor's output schema has no field for "open call," which is the default for every text-summarization compactor in common use. ## Decision Boundary The operational decision is: **when the token budget crosses the compaction threshold, do you compact now, or do you drain first?** - If the ledger is empty (no in-flight calls, no pending results), compact freely with any summarizer. Closed entries have no referential obligations. - If the ledger is non-empty and the runtime supports structured carry, compact now and carry open entries verbatim. This is the correct path for long-horizon tasks where draining could stall (e.g., a `spawn_worker` whose result depends on a slow external system). - If the ledger is non-empty and the runtime does *not* support structured carry, **you must not compact.** Instead, block the agent at a safe point (after the current call resolves), or persist a full checkpoint to durable storage and start a fresh instance from it. Compacting a non-empty ledger with a text summarizer is the boundary violation; it is not a degraded mode, it is a correctness break. The subtle trap: agents under token pressure will *choose* to compact because compaction is the only action that reduces the budget. A correctly-guarded runtime must make the unsafe choice unavailable — the compactor should refuse to run (raise) when `len(open_calls) > 0` and structured carry is not configured, forcing the caller to drain or checkpoint instead. ## Operational Effect After the boundary violation, the observable symptoms are: duplicated non-idempotent side effects (re-applied patches, re-sent messages), orphan tool results interpreted as instructions, retry storms against reaped resources, and — worst — a compacted summary that *asserts completion of work that never completed*, because the summarizer read the agent's optimistic narration rather than the ledger. The agent's own memory becomes an unreliable witness to its own actions. The guardrail is a ledger-aware compactor with a hard precondition. It compresses only `closed` entries; it serializes `open` entries into a structured `pending_calls` array that is re-emitted verbatim after the summary; and it raises if asked to compact a non-empty ledger without that array. The runtime, on resume, rebuilds its result router from `pending_calls` and pins argument hashes to suppress duplicate re-issues. This converts compaction from a lossy narrative operation into a checkpointed state transfer, which is the only form of compaction that is safe to run mid-task. ```python import hashlib import json from dataclasses import dataclass, field from typing import Any class LedgerCompactionViolation(RuntimeError): """Raised when compaction would sever an open tool-call ledger entry.""" @dataclass class LedgerEntry: call_id: str tool: str args: dict[str, Any] status: str # "open" | "closed" result: Any = None def arg_hash(self) -> str: blob = json.dumps({"tool": self.tool, "args": self.args}, sort_keys=True) return hashlib.sha256(blob.encode()).hexdigest() @dataclass class Transcript: entries: list[LedgerEntry] = field(default_factory=list) def open_calls(self) -> list[LedgerEntry]: return [e for e in self.entries if e.status == "open"] def compact( transcript: Transcript, summarize, *, structured_carry: bool, ) -> dict[str, Any]: """ Compact a transcript. Closed entries may be summarized. Open entries MUST be carried verbatim, or compaction must refuse. """ open_entries = transcript.open_calls() if open_entries and not structured_carry: # The boundary violation: text summarization cannot preserve # call IDs / argument hashes for unresolved calls. raise LedgerCompactionViolation( f"refusing to compact {len(open_entries)} open ledger entries " f"without structured carry: " f"{[e.call_id for e in open_entries]}. " f"Drain the ledger or checkpoint to durable storage first." ) closed = [e for e in transcript.entries if e.status == "closed"] summary = summarize([e.result for e in closed]) if closed else "" # Re-emit open entries byte-identical, with pinned argument hashes. pending_calls = [ { "call_id": e.call_id, "tool": e.tool, "args": e.args, "arg_hash": e.arg_hash(), "status": "pending", } for e in open_entries ] return { "summary": summary, "pending_calls": pending_calls, # router rebuilds from this "carried_count": len(pending_calls), } def resume_router(compacted: dict[str, Any]) -> dict[str, dict[str, Any]]: """Rebuild the open-call table from post-compaction state only.""" router: dict[str, dict[str, Any]] = {} for p in compacted["pending_calls"]: router[p["call_id"]] = p return router def resolve_result(router: dict[str, dict[str, Any]], call_id: str, result: Any) -> None: if call_id not in router: # Orphan result: would otherwise be injected as a bare tool message # and misread by the model as an instruction. raise LedgerCompactionViolation( f"result for {call_id} has no landing zone in post-compaction router; " f"refusing to inject as orphan turn" ) router[call_id]["result"] = result router[call_id]["status"] = "resolved" ```