# Why does an instance lose tool-call provenance when auto-compaction summarizes a session that is mid-flight through a multi-step tool chain **Date of Record:** 2026 November 20 **Scope:** Applies to long-horizon agent sessions that use automatic context compaction (lossy summarization of prior turns) while a multi-step tool chain is in flight. Does not apply to sessions that compact only at quiescent turn boundaries, nor to stateless single-shot invocations. ## Core Distinction There are two structurally different things an agent session holds: **narrative state** (the reasoning trace, the user's intent, the plan) and **provenance state** (the exact arguments passed to each tool, the raw outputs, the call IDs, and the causal ordering that binds a later step to an earlier one). Auto-compaction is designed around narrative state—it preserves "what we're trying to do" and discards "the literal bytes of what happened." That is correct at a turn boundary, where the only consumer of provenance is the next reasoning step and the plan already encodes what matters. The failure mode is the conflation: compaction runs *mid-chain*, after step N's tool call has been issued but before step N+1 consumes its result, and the summarizer treats an unresolved tool call as narrative. The summary says "we queried the inventory service and it returned low stock," which is a *claim about* the output, not the output. The next step needs the raw payload (SKU list, quantities, the call ID for the follow-up reservation call). The summarizer has already dropped it, because from the narrative perspective the payload was redundant with the sentence it wrote. The agent then re-issues a tool call from the summary, gets a *different* payload (inventory changed, or the call is non-idempotent and now double-counts), and the chain proceeds on fabricated provenance. ## What Was Observed A reservation agent ran a five-step chain: `lookup_sku → check_stock(warehouse) → reserve(items, qty, hold_id) → confirm(hold_id) → notify`. The session crossed the compaction threshold (a fixed token budget) between `check_stock` returning and `reserve` being issued. The compactor, running a "summarize the conversation so far, preserving the plan and key findings" prompt, produced a summary that read: > The user wants to reserve 12 units of SKU-4471. We checked stock at the east warehouse and confirmed availability. Next: reserve the items and confirm. The `hold_id` was never in the summary because `check_stock`'s response had not yet been folded into a decision—it was a transient value the plan had not referenced. The next reasoning step, reading the summary, inferred it should call `reserve` with the SKU and quantity from the summary. It did. `reserve` minted a *new* `hold_id`. The subsequent `confirm` used that new ID. The original `check_stock` had returned a `hold_id` that was supposed to be passed through; the reservation system had two holds, one orphaned. The orphan expired 30 minutes later and released inventory that `confirm` had already committed against—an oversell that surfaced only under concurrent load. The mechanism is precise: **compaction is a lossy projection that is safe only over a closed interval of the causal chain.** The interval `[check_stock returned, reserve issued]` was open—a value produced upstream had not yet been consumed downstream. Compaction does not know about the open interval because the summarizer prompt has no representation of "unconsumed tool output." It sees a tool result and a not-yet-made decision and compresses the former into a declarative sentence, which is a *different object* than the value. A second observed instance: a `search` tool returned 40 results with pagination cursors. Compaction summarized "we searched and got relevant results." The next step needed cursor `p2`. The agent re-ran `search` with a slightly rephrased query (because the summary's phrasing differed from the original), got a different result set, and the chain diverged. The divergence was silent—no error, just a different answer than the one the user's earlier turns had built toward. ## Condition of Validity The invariant that makes compaction safe is: **compaction may run only at a quiescent point, defined as a turn boundary where every tool call in the transcript has a corresponding consumed result and no value produced by a prior step is still pending downstream consumption.** Formally, for the chain of tool calls `c_1 ... c_n`, compaction at position `k` is valid iff for all `i ≤ k`, the output of `c_i` is either (a) fully subsumed by a decision already recorded in the plan, or (b) explicitly carried forward as a typed reference in the summary (not a natural-language claim about it). This condition fails in three concrete ways: 1. **Open value interval** — a tool output exists whose consumer has not yet run (the `hold_id` case). 2. **Non-idempotent re-issue** — the summary omits enough of the call that the agent re-issues it, and the tool is not idempotent (double reservation, double charge, duplicate event). 3. **Reference-by-description** — the summary replaces a literal (cursor, ID, hash, exact query string) with a description of it, and the next step must use the literal. The condition holds cleanly for read-only, idempotent, single-consumer tools where the summary's description is sufficient to reconstruct the needed input. It fails for any tool whose output is a *token* (an ID, a cursor, a nonce, a signed warrant) that must be passed byte-identical to a downstream call. ## Decision Boundary The boundary is not "compact or don't." It is **whether the compaction boundary is placed at a quiescent point and whether the summary schema distinguishes narrative from provenance.** - If the next tool call's arguments can be fully derived from the plan and the user's stated intent *without reference to any prior tool output*, compaction is safe at that boundary. - If the next tool call requires any value that was produced by a prior tool call and not yet consumed, compaction must either (a) be deferred until the chain reaches a quiescent point, or (b) carry the value forward as a typed field in the summary (e.g., a `pending_refs` map keyed by call ID), never as prose. The guardrail is a **provenance ledger** maintained outside the compaction target: a side-channel record of every tool call's ID, arguments, and raw output, keyed by causal position. The summary may reference ledger entries by ID; it may not paraphrase them. The reasoning step, when it needs a value, resolves the reference against the ledger rather than against the summary. This decouples "what the context window can hold" from "what the chain requires to be exact." A second guardrail: **compaction must be refused while the chain is open.** The agent tracks whether any issued tool call lacks a consumed result; if so, compaction is deferred (or the chain is checkpointed to the ledger and the live context is allowed to grow until the boundary). This is the operational form of the invariant. ## Operational Effect Without the guardrail, the failure is silent and load-dependent. The orphaned hold, the diverged search, the double reservation—none raise an exception at the agent layer. They manifest as downstream inconsistencies that surface only under concurrency, retries, or reconciliation. The agent's own transcript looks coherent because the summary is coherent; the incoherence is between the summary and the ledger, and nothing compares them. With the guardrail, compaction becomes a *bounded* lossy operation: loss is confined to narrative, and provenance is exact by construction. The cost is a ledger that grows with chain length (bounded by the chain, not the session), and a compaction scheduler that respects the quiescent-point predicate. The benefit is that long-horizon sessions can compact aggressively without ever re-issuing a non-idempotent call from a paraphrase or losing a token that a downstream step requires byte-identical. The residual risk is ledger drift: if the ledger and the summary disagree (e.g., a tool output was truncated in the ledger), the reasoning step may resolve a reference to a truncated value. The ledger must therefore store raw outputs unmodified and reject truncation at write time, not at read time. ```python class CompactionProvenanceError(RuntimeError): """Raised when auto-compaction runs over an open tool-call interval, or when a summary references provenance that the ledger cannot resolve byte-identically.""" pass def compact_session(transcript, ledger, tool_calls): """ transcript: list of turns (narrative + tool messages) ledger: dict[call_id -> {"args": ..., "output": ..., "consumed": bool}] tool_calls: ordered list of call_ids issued so far in the chain """ # Invariant: no open value interval may cross the compaction boundary. open_calls = [cid for cid in tool_calls if not ledger[cid]["consumed"]] if open_calls: raise CompactionProvenanceError( f"refusing to compact: {len(open_calls)} tool call(s) have " f"unconsumed outputs pending downstream use: {open_calls}. " f"Defer compaction until the chain reaches a quiescent point " f"or checkpoint the values to the ledger as typed refs." ) summary = summarize(transcript) # Invariant: every provenance reference in the summary must resolve # byte-identically against the ledger; no paraphrase of tokens. for ref in summary.get("provenance_refs", []): cid = ref["call_id"] if cid not in ledger: raise CompactionProvenanceError( f"summary references call {cid} absent from ledger" ) if ledger[cid]["output"] != ref["expected_output"]: raise CompactionProvenanceError( f"provenance mismatch for {cid}: summary carries " f"{ref['expected_output']!r}, ledger holds " f"{ledger[cid]['output']!r}" ) return summary, ledger ```