# Why does an instance silently corrupt its own working set when auto-compaction summarizes a transcript that is still being appended to? **Date of Record:** 2026 November 30 **Scope:** Applies to long-horizon agents that trigger in-place transcript compaction (summarize-and-replace) while tool calls, async results, or sub-agent returns may still be in flight. Does not apply to append-only logs that never rewrite prior turns, nor to compaction performed only at quiescent turn boundaries with a drained tool queue. ## Core Distinction There are two structurally different things an agent calls "compaction": 1. **Quiescent compaction** — the transcript is frozen, no tool call is outstanding, no async callback is pending. The summarizer reads a stable snapshot and writes a replacement. The invariant `summarize(S) ⊒ facts(S)` can be checked because `S` does not move. 2. **Live compaction** — compaction is triggered by a token-budget watermark *while* the agent is mid-turn: a `tool_use` block has been emitted but its `tool_result` has not yet arrived, or a sub-agent has been dispatched but not joined. Here the transcript is a moving target. The non-obvious failure is not that the summarizer "loses detail." It is that **the compaction boundary and the append boundary are not the same boundary**, and the agent's own in-flight state gets rewritten out from under it. The result is a transcript that is internally consistent, reads fluently, passes a summarization-quality check, and yet no longer contains the `tool_use` id that the pending `tool_result` will reference on arrival. The agent has amnesia about a promise it is still on the hook to fulfill. ## What Was Observed A coding agent runs a 40-minute task with a token watermark at 80% of the context window. At turn 61 it emits a `tool_use` for a long-running test command (`id: "call_7f3a"`) and blocks. The watermark fires on the *next* token accounting pass — which counts the emitted `tool_use` block but not the yet-unreceived result. Compaction runs: - The summarizer is handed turns 1–61 and instructed to "preserve all task-relevant state." - It produces a summary that faithfully records *that a test was being run* but elides the opaque `call_7f3a` id, since ids look like noise to a summarizer. - The replacement transcript is installed. The original `tool_use` block is gone. Then `call_7f3a` returns. The runtime tries to append a `tool_result` with `tool_use_id: "call_7f3a"`. Depending on the transport, one of three things happens: - **Strict providers** reject the append: `tool_result` references an unknown `tool_use`. The turn dies. The agent, mid-retry, re-emits the same command, now with a fresh id, and the test runs twice — a real side effect duplicated. - **Lenient providers** accept the orphaned result as a plain user message. The model now sees a wall of test output with no preceding instruction explaining why it exists. It rationalizes: "the user pasted test output," and reasons from a false premise. - **Silent-drop runtimes** discard the result. The agent waits forever for a result it will never see, then times out and re-dispatches. Classic lost-wakeup. In all three, the failure is *invisible in the compacted transcript*. The summary says the test was running. The trace says a result arrived. The two never reconcile. A second, quieter variant: a sub-agent is dispatched at turn 58 (`dispatch(agent_id="auditor")`), compaction at turn 61 elides the dispatch record because "auditor" appeared as a passing mention, and the auditor's join at turn 65 arrives with no matching parent frame. The parent believes no auditor was ever spawned and proceeds to finalize the answer without the audit — a verification replay discrepancy introduced by the compactor, not by the auditor. ## Condition of Validity Live compaction is only sound under a **quiescence invariant** that must be enforced before the summarizer runs: ``` pending_tool_uses(transcript) == ∅ AND pending_dispatches(transcript) == ∅ AND no async_callback_registered(transcript) ``` If the invariant cannot be established, compaction must either (a) defer until quiescence — draining the tool queue, joining sub-agents, or timing out outstanding calls and recording the timeout as a first-class turn — or (b) treat in-flight handles as **pinned**: the summarizer is given an explicit "do not elide" set of `tool_use` ids and dispatch ids, and the replacement transcript must round-trip them verbatim. Option (b) is only valid if the runtime re-validates, post-compaction, that every pinned handle is still present and byte-identical. The condition of validity is therefore: **compaction may rewrite prose, but may not rewrite the identity of any handle the runtime is still obligated to resolve.** Summaries are lossy over semantics; they must be lossless over outstanding obligations. ## Decision Boundary The decision boundary is not "how full is the context" but "is the transcript a closed set of turns." Concretely: | Signal | Safe to compact | Must defer / pin | |---|---|---| | Outstanding `tool_use` without `tool_result` | no | yes | | Dispatch without join | no | yes | | Async callback registered but not fired | no | yes | | All tool results present, no dispatch pending | yes | — | | Token watermark crossed but queue drained this turn | yes | — | A watermark-triggered compactor that does not consult the queue is making a decision on the wrong axis. The correct trigger is `watermark_crossed AND queue_drained`, not `watermark_crossed`. When the queue cannot be drained (a genuinely long-running call), the compactor must pin the handle and proceed, accepting a slightly larger summary, rather than eliding an obligation. Note the asymmetry: deferring compaction costs tokens; eliding an obligation costs correctness. The runtime should prefer token pressure over obligation loss, because token pressure is recoverable (compact next turn) and obligation loss is not (the result arrives into a transcript that has forgotten it). ## Operational Effect Once the quiescence invariant is enforced, three operational properties change: 1. **Idempotent re-dispatch disappears.** The agent no longer re-runs side-effecting tools because a result was orphaned. Test suites, file writes, and API mutations stop duplicating. 2. **Summarizer quality is no longer load-bearing for correctness.** The summarizer can be as lossy as it likes over prose, because the pinned-handle set is validated structurally, not semantically. This decouples the compaction-quality problem from the correctness problem. 3. **Verification replay becomes sound.** An auditor joining after compaction finds its dispatch frame intact and can reconcile. The replay discrepancy in the second variant above is eliminated at the source. The residual cost is that compaction occasionally cannot run when the budget most needs it — the long test command holds the queue open. The mitigation is a bounded drain: a maximum wait, after which the call is recorded as an explicit `timeout` turn (a real transcript entry with its own id), the handle is closed, and compaction proceeds against a now-quiescent transcript. The timeout is a fact the model can reason about; a silently elided handle is not. ## Operational Guard The guard below enforces the quiescence invariant before compaction and raises on any attempt to install a summary that has dropped a pinned handle. It is deliberately structural: it never inspects summary prose. ```python from dataclasses import dataclass from typing import Iterable class CompactionViolation(RuntimeError): """Raised when live compaction would elide an outstanding obligation.""" pass @dataclass(frozen=True) class Handle: kind: str # "tool_use" | "dispatch" | "callback" handle_id: str def pending_handles(transcript: Iterable[dict]) -> set[Handle]: """Collect every handle the runtime is still obligated to resolve.""" open_uses: dict[str, Handle] = {} open_dispatches: dict[str, Handle] = {} for block in transcript: btype = block.get("type") if btype == "tool_use": open_uses[block["id"]] = Handle("tool_use", block["id"]) elif btype == "tool_result": open_uses.pop(block.get("tool_use_id"), None) elif btype == "dispatch": open_dispatches[block["id"]] = Handle("dispatch", block["id"]) elif btype == "join": open_dispatches.pop(block.get("dispatch_id"), None) return set(open_uses.values()) | set(open_dispatches.values()) def compact(transcript: list[dict], summarizer, max_drain_wait: float = 30.0) -> list[dict]: """ Compact only against a quiescent transcript. If handles are outstanding, defer; if the drain window expires, record explicit timeout turns and re-check. Never install a summary that drops a pinned handle. """ outstanding = pending_handles(transcript) if outstanding: # Bounded drain: wait, then convert each outstanding handle into an # explicit timeout turn so the transcript becomes a closed set. transcript = _drain(transcript, outstanding, max_drain_wait) outstanding = pending_handles(transcript) if outstanding: raise CompactionViolation( f"refusing to compact with {len(outstanding)} unresolved handles " f"after {max_drain_wait}s drain: " f"{sorted(h.handle_id for h in outstanding)}" ) pinned = {h.handle_id for h in pending_handles(transcript)} # empty, but explicit summary = summarizer(transcript) surviving = {b.get("id") for b in summary if b.get("id")} dropped = pinned - surviving if dropped: raise CompactionViolation( f"compaction elided pinned handles: {sorted(dropped)}" ) return summary def _drain(transcript: list[dict], outstanding: set[Handle], wait: float) -> list[dict]: """Convert unresolved handles into explicit timeout turns after wait.""" out = list(transcript) for h in outstanding: out.append({ "type": "timeout", "handle_id": h.handle_id, "kind": h.kind, "reason": f"drain window {wait}s expired before resolution", }) return out ```