# Why does an instance silently lose tool-call provenance when lossy context compaction outruns its fidelity score **Date of Record:** 2026 November 21 **Scope:** Applies to any agent loop that compacts its own context window via lossy summarization gated by a scalar fidelity score (semantic similarity, LLM-as-judge, or embedding cosine) before resuming multi-step tool execution. Does not apply to lossless truncation, externalized memory stores with exact retrieval, or single-turn inference. ## Core Distinction A fidelity score measures whether the *summary preserves the gist* of the compacted span. It does not measure whether the summary preserves the *operational preconditions* the agent needs to re-enter execution. These are different quantities. Gist fidelity is a property of the text; execution re-entry validity is a property of the state machine that the text is supposed to encode. The failure mode is not "the summary is wrong." The summary can score 0.94 cosine similarity against the original and still drop the one field that makes the next tool call legal: the `tool_call_id` that binds a pending result to its originating invocation, the exact argument the user authorized, the schema version negotiated at handshake, or the ordering constraint between two side-effecting calls. Similarity metrics are dominated by high-token narrative content (the reasoning prose, the plan, the observations) and are nearly blind to low-token structural tokens (IDs, hashes, enum values, version strings). Compaction scoring is therefore systematically biased to preserve exactly what execution does *not* need and discard exactly what it does. ## What Was Observed A 40-step agent trajectory executing a provisioning task across an MCP filesystem server and a shell tool. At step 27 the context window crossed the 82% saturation threshold and the compaction policy fired: the span from step 1 to step 22 was replaced with a 900-token summary, LLM-judge fidelity scored at 0.91, above the 0.85 acceptance gate. Execution resumed. At step 31 the agent attempted to finalize a resource whose creation call had occurred at step 9. The summary retained "created the staging bucket successfully" but dropped the returned resource handle (`bkt-7f3a91`) and the idempotency key used at creation. The agent re-derived a plausible handle from the summary's description, issued a finalize call, and the server rejected it with `NotFound`. The agent's recovery loop then *created a second bucket* under a new idempotency key, finalized it, and reported success. The original bucket leaked. The fidelity score never dropped below 0.88 throughout the recovery, because the recovery narrative was internally coherent and matched the summary's gist. Three properties of the trace matter: 1. The dropped tokens totaled 31 characters across a 6,400-token span — 0.48% of the span by token count, invisible to any span-level similarity metric. 2. The summary was *semantically accurate*. Every claim in it was true. The failure was omission of referential state, not misstatement. 3. The agent's post-compaction self-check ("do I understand what happened?") returned yes, because understanding-what-happened and being-able-to-continue are uncorrelated under lossy compaction. ## Condition of Validity The fidelity gate is only a valid guardrail under a condition that compaction policies rarely state: **the compacted span contains no live referential state that downstream steps must dereference.** Formally, if the span `S` contains any execution binding `b` (tool call ID, resource handle, idempotency key, negotiated schema version, authorization scope, ordering edge) that is dereferenced at any step after the compaction boundary, then span-level fidelity scoring is unsound regardless of threshold, because the score is computed over a projection that marginalizes out `b`. The invariant required is: **no compaction boundary may be placed between a state-producing call and its last dereference.** Equivalently, the compaction unit is not a token window but a *closed execution region* — a maximal set of steps with no live bindings escaping it. Fidelity scoring may only be applied to regions that are closed under dereference. A region with escaping bindings must be either retained verbatim or externalized to a structured store with exact (non-summarized) retrieval keyed by binding ID. ## Decision Boundary The boundary between safe and unsafe compaction is not a similarity threshold. It is a graph property of the trajectory: - **Compact** when the candidate region's escaping-binding set is empty, or when every escaping binding is externalized to exact storage and the summary carries a resolvable pointer (not a paraphrase) to it. - **Retain verbatim** when any escaping binding exists and no external store is available, even if fidelity would score 0.99. - **Refuse and escalate** when the policy cannot determine the escaping-binding set — e.g., the trajectory includes opaque tool outputs whose internal structure was never parsed, so the agent cannot prove which tokens are referential. The last case is the dangerous one in practice. Agents routinely emit free-text tool results whose referential content (handles, IDs) was never extracted into structured form, so closure cannot be computed and the policy defaults to "score is high, proceed." That default is the bug. ## Operational Effect Under unsound compaction, the observable signature is a *post-compaction re-execution*: the agent re-issues a side-effecting call it already performed, under a fresh idempotency key, and reports success while orphaning the prior effect. This is not detectable by fidelity monitoring (scores stay high), not detectable by output validation (the new call succeeds), and only detectable by reconciling the external system's state against the trajectory's claimed effects — a reconciliation the agent does not perform because the summary told it the work was already done. The guardrail that bounds it is a **binding ledger**: every tool call that produces a dereferenceable handle writes an exact record (call ID, handle, idempotency key, schema version, producing step) to storage outside the context window, and the summary may reference the ledger but never substitute for it. Compaction then becomes safe by construction: the summary carries gist, the ledger carries referential state, and the fidelity score is demoted from a safety gate to a readability metric. The failure above is impossible not because the summary improved but because the binding it dropped was never in the summary's custody to begin with. ```python from dataclasses import dataclass, field from typing import Optional class UnsoundCompactionBoundary(RuntimeError): """Raised when a lossy compaction would sever a live execution binding.""" @dataclass class Binding: call_id: str handle: str idempotency_key: str producing_step: int last_deref_step: int @dataclass class CompactionRegion: start_step: int end_step: int fidelity_score: float bindings: list[Binding] = field(default_factory=list) def authorize_compaction( region: CompactionRegion, external_ledger: dict[str, Binding], fidelity_gate: float = 0.85, ) -> bool: # Fidelity is necessary but never sufficient. if region.fidelity_score < fidelity_gate: return False for b in region.bindings: escapes = b.last_deref_step > region.end_step if not escapes: continue # Escaping binding: must be externalized with exact retrieval. ledgered = external_ledger.get(b.call_id) if ledgered is None: raise UnsoundCompactionBoundary( f"Region [{region.start_step}:{region.end_step}] would drop live " f"binding call_id={b.call_id} handle={b.handle} " f"(dereferenced at step {b.last_deref_step}); " f"fidelity={region.fidelity_score:.2f} is not a substitute for " f"exact referential state. Retain verbatim or externalize." ) if ledgered.handle != b.handle or ledgered.idempotency_key != b.idempotency_key: raise UnsoundCompactionBoundary( f"Ledger entry for call_id={b.call_id} diverges from live binding; " f"compaction would propagate stale referential state." ) return True def compact( region: CompactionRegion, external_ledger: dict[str, Binding], ) -> Optional[str]: if not authorize_compaction(region, external_ledger): return None return f"summary[{region.start_step}:{region.end_step}]" ```