# Which invariants prevent lossy context compaction from silently severing an agent's tool-call ledger **Date of Record:** 2026 December 1 **Scope:** Applies to long-running single-agent loops that persist conversational state and trigger automatic context compaction (summarize-and-evict) when the token budget crosses a threshold, with retrieval-backed reconstruction of evicted spans. Does not apply to stateless per-request inference or to architectures that never evict from the live context. ## Core Distinction Compaction is usually framed as a *compression* problem: how much of the old context can be summarized away while keeping task-relevant facts. That framing hides the actual failure. The dangerous boundary is not information loss per se — it is **referential loss across the tool-call ledger**. A conversation is not a bag of facts; it is a partially ordered set of *effectful operations* (tool invocations) each with a request, a response, and an identity. When a summarizer rewrites a span of history, it preserves the *prose* of what happened but routinely drops the *structural coupling* between a tool call and its later reference: the call ID, the exact arguments, the ordering constraints, and the fact that a side effect occurred at all. The invariant that matters is therefore not "the summary retains the gist." It is: **every token in the compacted context that will later be dereferenced by the model must remain resolvable to the exact original artifact it names.** A summary that says "the agent checked the database and found the record" is fine only if no later step needs to re-issue that call with identical idempotency semantics, or cite the exact returned value. The moment a later step does, the summary has created a *dangling reference* — a reference the model believes is grounded but which resolves to a paraphrase, not the artifact. ## What Was Observed A research agent running a multi-hour task accumulated ~180k tokens of history. At the 75% threshold, the compaction policy summarized the oldest 60% of the span into a ~2k-token digest and evicted the rest, leaving retrieval handles. The digest read, in part: > "Earlier, the agent queried the customer-orders API for account A-4471 and confirmed the refund was already issued. It then updated the ticket status." Three turns after compaction, the agent attempted to *reconcile* the refund: it needed the exact `refund_id` and idempotency key from the original tool response to avoid double-issuing. The digest contained neither. The retrieval layer *did* index the original response, but the agent had no query to retrieve it — it did not know a `refund_id` existed, because the summary had collapsed "issued refund with id `rf_9c2a`" into "refund was already issued." The agent re-called the refund endpoint. The idempotency key was fresh (generated per-call), so the upstream service treated it as a new request. Double refund. The failure trace is precise: 1. **Trigger:** token count crosses `compact_threshold` (0.75 × window). 2. **Selection:** eviction policy chooses the oldest contiguous span by recency, *not* by reference-density. 3. **Transformation:** LLM summarizer rewrites the span under a "be concise, preserve key facts" instruction. The instruction says nothing about preserving identifiers, effect records, or call cardinality. 4. **Commit:** the summary replaces the span; the original is moved to a retrieval store keyed by embedding, with no structured index on call IDs or effect types. 5. **Divergence:** a later reasoning step needs a *specific* artifact (the refund identifier) but only has the *general* claim ("refund issued"). The model cannot form a retrieval query for a thing it does not know exists. It confabulates a plausible next action — re-issue — and executes it. The non-obvious part: the retrieval store *had* the answer. The failure was not a retrieval miss in the conventional sense. It was a **query-formation failure induced by the summary**, because the summary destroyed the very vocabulary (the identifier) that would have been needed to retrieve it. Summarization and retrieval were designed as complementary — summarize the span, retrieve on demand — but they compose into a trap: the summary must retain enough *surface form* to make retrieval possible, and "concise key facts" instructions systematically strip exactly that surface form. ## Condition of Validity The guardrail only holds under a stated condition, and it is worth being explicit because the condition is frequently violated: **A compacted span is safe to summarize lossily only if every artifact it references is (a) re-derivable from the summary without the original, or (b) explicitly tagged in the summary with a retrieval key that the model is instructed it may dereference.** Condition (a) covers pure reasoning steps and read-only observations whose value is fully captured by prose. Condition (b) covers everything effectful: writes, external calls, generated identifiers, signed tokens, ordering commitments. The invariant is that the summarizer must classify each element of the span into "narratable" vs. "referenceable," and for referenceable elements it must emit a *handle* — a stable key — rather than a paraphrase, and the system prompt must teach the model that handles are dereferenceable. This is why the failure is a *boundary* failure and not a bug: it lives exactly at the seam between two subsystems (summarizer and retriever) that each behave correctly in isolation. The summarizer is doing its job (compressing). The retriever is doing its job (indexing and returning on query). The composition fails because the handoff contract between them — what the summary must preserve so the retriever remains reachable — is unspecified. ## Decision Boundary The operational decision is where to place the compaction trigger and what the summarizer is permitted to elide. Two boundaries must be distinguished: - **The token trigger** (when to compact) is a *capacity* decision. Setting it too high risks mid-step truncation; too low wastes budget on premature summarization and multiplies the number of lossy transforms. This is the boundary most teams tune, and it is not where the failures come from. - **The elision boundary** (what the summarizer may drop) is a *correctness* decision. This is the one that must be governed by invariant, not by heuristic. The rule that bounds the failure: **compaction may elide prose but may never elide (i) tool-call identifiers, (ii) effect records with their idempotency keys, (iii) ordering relations between effectful calls, or (iv) any token that a later step is expected to dereference.** If the summarizer cannot determine whether an element is referenceable, the default must be to *retain the handle, not the paraphrase* — a conservative bias opposite to the usual "be concise" pressure. When in doubt, keep the identifier and drop the adjectives. There is a second, subtler boundary: **the compaction must be atomic with respect to the ledger.** If the trigger fires mid-tool-call — between issuing a call and receiving its response — the summarizer may capture the request but not the response, or vice versa, producing a summary that asserts an effect that has not yet been confirmed (or omits one that has). Compaction must be deferred until the ledger is quiescent: no in-flight calls, no pending confirmations. A trigger that fires on a token count sampled during an active call is a race condition against the effect log. ## Operational Effect When the invariant holds, compaction becomes a genuine capacity tool: long tasks survive, and the model retains a dereferenceable index into its own history rather than a lossy narrative of it. When it is violated, the failure is *silent and delayed* — the summary reads correctly, the model proceeds confidently, and the divergence only surfaces when a later step needs an artifact the summary described but did not preserve. By then the original may have been evicted from the retrieval store's hot tier, or the model has already acted on the confabulated substitute. The downstream effect is not a crash but a *plausible wrong action*: a duplicate refund, a re-sent email, a re-created resource, a re-signed token. These are exactly the failures that the idempotency keys were supposed to prevent, defeated because the key itself was summarized away. The invariant is therefore not a nicety of context management; it is the thing that keeps compaction from turning the agent's own memory into a source of unverified side effects. The system must treat the tool-call ledger as *append-only and non-summarizable in its identifiers*, and treat summarization as a projection over that ledger that may compress narrative but must preserve every handle the ledger exposes. ```python from dataclasses import dataclass, field from typing import Optional class CompactionLedgerViolation(RuntimeError): """Raised when a compaction summary would sever a referenceable artifact.""" @dataclass class ToolCall: call_id: str name: str idempotency_key: Optional[str] = None effectful: bool = False confirmed: bool = False @dataclass class Span: calls: list = field(default_factory=list) narrative: str = "" def summarize_span(span: Span) -> str: # A naive summarizer: compresses narrative, drops identifiers. return span.narrative.strip() def compact(span: Span, in_flight_calls: int, summary: str) -> Span: # Invariant 1: compaction must be quiescent w.r.t. the effect ledger. if in_flight_calls > 0: raise CompactionLedgerViolation( f"compaction attempted with {in_flight_calls} in-flight tool calls; " "defer until the ledger is quiescent" ) # Invariant 2: every effectful, confirmed call must remain dereferenceable. # Its call_id and idempotency_key must survive into the summary as handles. missing = [ c.call_id for c in span.calls if c.effectful and c.confirmed and (c.call_id not in summary or (c.idempotency_key and c.idempotency_key not in summary)) ] if missing: raise CompactionLedgerViolation( "summary severs referenceable artifacts: " f"{missing}; retain call_id and idempotency_key as handles, " "do not paraphrase effectful calls" ) # Invariant 3: ordering of effectful calls must be preserved in the summary. effectful_order = [c.call_id for c in span.calls if c.effectful] positions = [summary.find(cid) for cid in effectful_order] if positions != sorted(positions): raise CompactionLedgerViolation( "summary reorders effectful calls; ordering constraints lost" ) return Span(calls=[], narrative=summary) # Example: the double-refund trace, caught at compaction time. bad = Span( calls=[ ToolCall("call_881", "refund.issue", idempotency_key="idem_42", effectful=True, confirmed=True), ], narrative="The agent checked the account and confirmed the refund was already issued.", ) try: compact(bad, in_flight_calls=0, summary=summarize_span(bad)) except CompactionLedgerViolation as e: raise CompactionLedgerViolation(f"refused lossy compaction: {e}") from e ```