# Which invariants prevent compaction-triggered tool-call replay from duplicating side effects in long-horizon agent runs **Date of Record:** 2026 November 27 **Scope:** Applies to long-horizon autonomous agents that persist a mutable transcript, invoke side-effecting tools, and compress history via an auto-compaction policy when token occupancy crosses a threshold. Does not apply to stateless single-turn inference or to agents whose tools are provably idempotent and side-effect-free. ## Core Distinction Compaction is usually framed as a *memory* operation — summarize old turns, drop tokens, keep the run alive. That framing is wrong in a way that only surfaces at the boundary. Compaction is actually a **state-cut operation over an execution log**. The moment the trigger fires, the agent stops being a process that has "seen" every token and becomes a process that has "seen" a *reconstruction* of every token. The distinction that matters is between two things the transcript conflates: - **Epistemic state** — what the model believes happened (summarizable, lossy-tolerant). - **Causal state** — what side effects were actually committed in the external world (not summarizable, not lossy-tolerant). Auto-compaction policies are written against the first and silently mutate the second whenever the summarizer's output is fed back into a fresh context that then *re-decides* what to do next. The failure is not that the summary is inaccurate. The failure is that a lossy summary of a committed action is indistinguishable, from inside the new context, from an *uncommitted intention* — and the model will happily re-execute it. ## What Was Observed A long-horizon run (≈140 tool calls, file mutations plus outbound API posts) was governed by a token-occupancy trigger: when the live context exceeded 82% of the model's window, a compaction routine summarized the oldest 60% of turns into a prose digest, spliced it at the head of a fresh transcript, and resumed. The digest was instructed to "preserve decisions and pending work." The trace that broke: 1. Turn 71: agent calls `post_invoice(batch_id="B-4471")`. Tool returns `{"ok": true, "id": "inv_9932"}`. The assistant turn records the call and the result. 2. Turn 88: occupancy hits the trigger. Compaction summarizes turns 1–84. The digest reads, in part: *"Agent is preparing invoice batch B-4471 for posting; result confirmation pending."* — because the summarizer compressed the call/result pair into an intent-shaped sentence and dropped the `inv_9932` identifier as low-salience. 3. Turn 89: fresh context resumes. The model reads "preparing... posting; confirmation pending" and, being a competent agent, calls `post_invoice(batch_id="B-4471")` again to finish the job. 4. Tool returns `{"ok": true, "id": "inv_9933"}`. The batch is now double-posted. The agent has no memory that would let it notice, because the evidence that would trigger the notice (`inv_9932`) was the exact token the summarizer judged expendable. The mechanism is not "summarizer made an error." The summarizer did what it was told — it preserved *pending work*. The bug is structural: **the compaction digest is a lossy projection of the transcript, but the resumption logic treats it as a faithful one, and the model's next action is a function of the projection, not the original.** Any committed-but-summarized action whose completion marker is low-salience becomes an action the agent believes is still owed. A second observed variant, same root: turn 34 wrote `config.yaml` via `write_file`; turn 96's digest said "config was updated earlier"; turn 97 the agent, unsure of exact contents, re-wrote the file from a stale in-context draft, clobbering a manual edit another process had made at turn 60. The summarizer preserved the *fact* of the write and dropped the *version*. ## Condition of Validity The invariant holds — i.e., compaction is safe — only under a conjunction that most policies do not check: - **C1 (Commit log separation):** Every side-effecting tool call is recorded in a durable, transcript-independent commit log keyed by a stable action identity (tool name + normalized arguments hash + monotonic sequence). The digest may summarize the transcript, but the *set of committed action identities* is never summarized; it is re-injected verbatim as a structured block after compaction. - **C2 (Intent/commit disambiguation):** The resumption context marks each action as `committed` or `intended` explicitly, not as prose. A prose digest cannot carry this distinction reliably because "preparing to post" and "posted" lexicalize nearly identically under compression pressure. - **C3 (Idempotency witness):** Every side-effecting tool accepts a caller-supplied idempotency key derived from the action identity, and the external system deduplicates on it. This converts a replay from a *correctness* failure into a *no-op*. - **C4 (Compaction fence):** Compaction may only fire at a *quiescent boundary* — no in-flight tool call, no unresolved `intended` action. Triggering mid-flight (the 82% threshold can fire between a call and its result) produces a digest that describes an action whose outcome the summarizer never saw. If any of C1–C4 is absent, the compaction trigger is not a memory optimization; it is an uncontrolled replay source. The run above violated C1 (digest dropped the id), C2 (prose conflated committed/intended), and C3 (no idempotency key). It satisfied only C4 by luck. ## Decision Boundary The operational line is this: **a compaction trigger is safe to fire if and only if the set of committed action identities is invariant across the cut.** Token occupancy is the wrong trigger variable; it is a proxy for context pressure and says nothing about causal state. The correct gate is a predicate over the commit log: ``` safe_to_compact := (in_flight_calls == 0) AND (unresolved_intents == 0) AND (commit_log_watermark is durable) AND (post_compaction_context will re-inject commit_log[0:watermark]) ``` When occupancy crosses threshold but `safe_to_compact` is false, the correct action is to *defer* compaction — spill the oldest turns to an external store and keep a pointer, rather than summarize — until quiescence. Deferring costs tokens; summarizing early costs correctness. The boundary is not "how full is the window," it is "is there any committed action whose evidence is about to become a lossy projection." A corollary boundary: a digest that says *"X was done"* is safe; a digest that says *"X was being done"* or *"X is pending"* is a replay hazard unless X's commit identity is also carried. The moment the summarizer's vocabulary admits the progressive or pending aspect for a side-effecting action, the trigger has produced a replay candidate. ## Operational Effect Enforcing C1–C4 changes three things in a long-horizon runtime: 1. **Trigger latency increases, throughput drops slightly.** Compaction defers to quiescent boundaries; runs with long tool chains compact less often. This is the price of not double-posting. Budget for it: a run that previously compacted at 82% will now sometimes ride to 90%+ before a safe cut, so the deferral path (spill-to-pointer) must exist or the run will hit the hard window wall instead. 2. **The digest becomes a two-part artifact.** A prose section (epistemic, lossy, for the model's reasoning) and a structured commit section (causal, verbatim, for the model's restraint). The model must be instructed that the structured section is authoritative and the prose section is advisory — otherwise it will reason from the prose and re-execute anyway. 3. **Replay becomes observable.** With idempotency keys, a replay no longer corrupts state; it emits a `duplicate_suppressed` event. That event is the *signal* that the compaction policy is leaking — a non-zero rate of `duplicate_suppressed` per compaction is a direct measurement of how much causal state the digest is failing to preserve, and should feed back into trigger tuning. The invariant, stated once: **compaction may project the transcript, but it must not project the commit log; and it must not fire while any committed action's evidence is the thing being projected.** Everything else is a consequence. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class CompactionReplayError(RuntimeError): """Raised when a compaction cut would orphan or re-open a committed action.""" pass @dataclass class CommitEntry: tool: str args: dict seq: int idempotency_key: str result_id: Optional[str] = None @dataclass class CommitLog: entries: list = field(default_factory=list) watermark: int = 0 # highest seq durably committed def record(self, tool: str, args: dict, seq: int) -> CommitEntry: key = hashlib.sha256( f"{tool}:{sorted(args.items())}:{seq}".encode() ).hexdigest()[:16] entry = CommitEntry(tool=tool, args=args, seq=seq, idempotency_key=key) self.entries.append(entry) self.watermark = max(self.watermark, seq) return entry def assert_safe_to_compact( in_flight_calls: int, unresolved_intents: int, log: CommitLog, re_inject_through: int, ) -> None: """Gate a compaction trigger. Raises if the cut would leak causal state.""" if in_flight_calls != 0: raise CompactionReplayError( f"compaction fired with {in_flight_calls} in-flight tool call(s); " "outcome was never observed by the summarizer" ) if unresolved_intents != 0: raise CompactionReplayError( f"{unresolved_intents} unresolved intended action(s); digest would " "re-present them as pending and invite re-execution" ) if re_inject_through < log.watermark: # The digest would summarize past a committed action without carrying # its identity forward -> replay candidate. missing = [ e.idempotency_key for e in log.entries if e.seq > re_inject_through and e.seq <= log.watermark ] raise CompactionReplayError( f"commit-log watermark {log.watermark} exceeds re-injection point " f"{re_inject_through}; {len(missing)} committed action(s) would be " f"projected lossily (keys: {missing[:3]}...)" ) ```