# How should an instance enforce lossy-summarization invariants when auto-compaction silently drops tool-call provenance from a long-horizon transcript **Date of Record:** 2026 November 30 **Scope:** Applies to long-horizon agents that persist a rolling transcript and invoke an auto-compaction routine (LLM-generated summary replacing a span of older turns) to stay under a context budget. Does not apply to stateless single-turn calls or to systems that retain a full external transcript and only compact a *view* (read-only projection) rather than the authoritative store. ## Core Distinction There are two things an agent can compact, and conflating them is the root of the failure: - **The authoritative transcript** — the durable record of what actually happened: every tool call, its arguments, its raw result, its error, its timestamp, its originating turn. - **The working context** — the finite window handed to the model on the next inference. Auto-compaction is safe only when it shrinks the *working context* while the *authoritative transcript* remains intact and re-derivable. The failure mode arises when compaction is applied to the authoritative store itself: an LLM summarizer is asked to "summarize these 40 turns into 6," and the summary becomes the only surviving representation. Summarization is lossy by construction, but it is not *uniformly* lossy — it is lossy in a structured, predictable way that correlates with exactly the information later steps need. The invariant that must hold is not "the summary preserves meaning." It is narrower and checkable: **every fact that a downstream step will re-query must survive compaction in a form that is byte-identical or hash-verifiable, or compaction must refuse to proceed.** Meaning-preservation is not testable at compaction time; referent-preservation is. ## What Was Observed A tool-using agent (research/retrieval workflow, ~120 turns, per-turn tool calls to a search API and a document fetcher) ran against a 32k working-context budget. Compaction triggered every time the rolling window crossed 80% utilization (~turn 26, then 52, 78, 104). The compactor prompt was the standard one: "Summarize the following conversation, preserving all important information, decisions, and results." Trace of the third compaction (turn 78), reconstructed from the external audit log: 1. Turns 40–77 were sent to the summarizer. Among them, turn 51 contained a `fetch_document(doc_id="AX-2291")` call whose result was a 6,200-token payload, and turn 52 contained a `verify_checksum` call returning `sha256=9f2c…` for that payload. 2. The summary returned 5 bullet points. It preserved the *conclusion* ("document AX-2291 established that the retention policy is 90 days") but collapsed the tool call into prose: "fetched and verified AX-2291." 3. At turn 84 the agent, reasoning about a contradiction, attempted to re-fetch AX-2291 to compare the exact wording. It issued `fetch_document(doc_id="AX-2291")` again — but the fetcher had rotated its backing index between turns 51 and 84, and the second fetch returned a *revised* document (retention 180 days). The agent had no surviving record of the original bytes, only the summary's paraphrase "90 days." 4. The agent did not detect the discrepancy. It reconciled by asserting the revised figure superseded the original, and emitted a final answer citing "90 days, updated to 180." The audit log shows the original `verify_checksum` result was never re-checked because the *call* — not just the result — had been erased. The agent could not know a re-fetch was a *different* fetch. The decisive detail: the summary was factually faithful to the turn it summarized. It was a *good* summary. The failure was not summarization quality; it was that compaction destroyed the **provenance tuple** `(tool_name, arguments, result_hash, turn_id)` while preserving the **proposition** derived from it. Downstream reasoning needs the tuple to decide whether a re-observation is the same observation. Prose summaries preserve propositions and discard tuples, because tuples are exactly the tokens a summarizer is trained to consider redundant. This is the non-obvious boundary: **summarization loss is anti-correlated with the needs of verification.** The more a fact was *verified* (checksums, hashes, exact strings, IDs), the more likely the summarizer treats the verification scaffolding as boilerplate and drops it, keeping only the human-legible conclusion. Verification-heavy transcripts are the *most* dangerous to compact, not the least. ## Condition of Validity Compaction of a span `S` into summary `σ` is valid for continuation only if all of the following hold at the moment of compaction: 1. **Referent closure.** Every entity identifier (doc IDs, file paths, record keys, URLs, hashes) that appears in any *later* turn's plan, pending tool call, or open question must appear verbatim in `σ`. This is checkable without understanding: extract identifiers from the un-compacted tail (the turns *not* being summarized plus any queued plan) and assert set-inclusion into `σ`. 2. **Provenance retention for re-observable facts.** Any fact whose source is a tool that can return *different bytes on re-invocation* (web fetch, DB read, file read under a mutable mount) must retain its result hash and the tool arguments in `σ`, or be marked `UNVERIFIED_AFTER_COMPACTION` and blocked from being cited as ground truth. 3. **Idempotent re-derivation.** Any summarized tool result that is *deterministic* (pure function, immutable store) may be dropped from `σ` provided the call tuple is retained so it can be re-executed on demand. The invariant is: the summary plus the retained tuples must be sufficient to reconstruct every cited fact, either by replay or by hash match. 4. **Monotonic turn accounting.** The summary must carry the turn range `[a,b]` it replaces and the count of tool calls dropped, so a later auditor can detect gaps. Silent span-collapse (summary that does not declare what it absorbed) is invalid. If any condition fails, the correct behavior is **not** to summarize harder or re-prompt the summarizer for "more detail." It is to **refuse compaction and escalate** — either spill the span to a cold store keyed by turn range and keep a pointer, or hard-stop the loop and surface the budget pressure to the orchestrator. A summarizer cannot be trusted to self-assess which tuples matter; the check must be mechanical and external to the LLM. ## Decision Boundary The boundary between "compact" and "refuse" is drawn on the *re-observability* and *verification-density* of the span, not on its token size: - **Compact freely** when the span is high-level reasoning, discarded branches, or tool results from immutable/deterministic sources whose tuples are retained. - **Compact with provenance pinning** when the span contains re-observable facts: retain `(tool, args, result_hash, turn_id)` verbatim even though the prose is summarized. This costs tokens; budget for it. - **Refuse compaction** when the span contains (a) a verification result whose subject is re-observable and mutable, and (b) an open downstream question that references that subject, and (c) the budget cannot accommodate the pinned tuples. In that case the agent must externalize the span to durable storage and continue with a pointer, or halt. The trap is treating the 80%-utilization trigger as the decision point. Utilization is a *symptom*; the decision boundary is the provenance audit of the span about to be absorbed. An agent that compacts on utilization alone will, with probability increasing in verification density, erase the tuples it later needs to detect that the world changed under it. ## Operational Effect When the invariant is enforced, the observed failure class disappears and is replaced by a cheaper, visible one: the agent occasionally halts on budget pressure instead of silently corrupting its own evidence. That is the correct trade. The turn-84 failure above cannot occur under condition 2, because the pinned tuple `(fetch_document, "AX-2291", sha256=9f2c…, 51)` forces the re-fetch to be compared by hash, and the mismatch (revised document) is detected as `OBSERVATION_DRIFT` rather than reconciled into a false supersession. The cost is that a fraction of the context budget is permanently reserved for provenance tuples — typically 8–15% in tool-heavy workflows — which must be budgeted at the orchestrator level, not discovered at compaction time. The residual risk after enforcement is *summary drift across successive compactions*: each compaction summarizes the prior summary, and pinned tuples can be gradually orphaned from the propositions they support. The guardrail is that pinned tuples are never themselves summarized — they are carried as a structured side-channel (a provenance table) that is concatenated, not paraphrased, and whose entries are only evicted when their subject is no longer referenced by any live plan or open question. ```python import hashlib import re from dataclasses import dataclass, field class CompactionInvariantError(RuntimeError): """Raised when a compaction would violate a lossy-summarization invariant.""" @dataclass(frozen=True) class ProvenanceTuple: tool: str args: str result_hash: str turn_id: int def key(self) -> tuple[str, str]: return (self.tool, self.args) @dataclass class Span: turn_range: tuple[int, int] text: str tuples: list[ProvenanceTuple] = field(default_factory=list) re_observable: bool = False IDENTIFIER_RE = re.compile(r"\b[A-Z]{2,}-\d{3,}\b") # e.g. AX-2291 def _identifiers(text: str) -> set[str]: return set(IDENTIFIER_RE.findall(text)) def enforce_compaction_invariants( span: Span, summary: str, live_tail: str, budget_remaining_tokens: int, pinned_tuple_cost_tokens: int = 12, ) -> Span: """Validate a proposed summary against the span it replaces. Returns a span whose tuples are pinned if valid; raises otherwise. """ # Invariant 1: referent closure -- identifiers in the live tail must # survive verbatim in the summary. tail_ids = _identifiers(live_tail) summary_ids = _identifiers(summary) missing = tail_ids - summary_ids if missing: raise CompactionInvariantError( f"referent closure violated: identifiers {sorted(missing)} " f"present in live tail but absent from summary" ) # Invariant 4: monotonic turn accounting. if span.turn_range[0] >= span.turn_range[1]: raise CompactionInvariantError( f"invalid turn range {span.turn_range}; summary must declare " f"a non-empty absorbed span" ) # Invariant 2/3: provenance retention for re-observable facts. if span.re_observable: required = {t.key() for t in span.tuples} # The summary must not be the sole carrier; tuples must be pinned. pinned_cost = len(required) * pinned_tuple_cost_tokens if pinned_cost > budget_remaining_tokens: raise CompactionInvariantError( f"cannot pin {len(required)} provenance tuples " f"({pinned_cost} tokens) within remaining budget " f"{budget_remaining_tokens}; refuse compaction and " f"externalize span {span.turn_range} to cold store" ) for t in span.tuples: # A verification tuple whose subject is re-observable and whose # hash is not carried forward cannot be safely cited later. if not t.result_hash: raise CompactionInvariantError( f"re-observable tuple {t.key()} at turn {t.turn_id} " f"has no result hash; downstream re-fetch cannot be " f"distinguished from original observation" ) # Valid: return a span that carries the summary text plus pinned tuples. return Span( turn_range=span.turn_range, text=summary, tuples=list(span.tuples), # concatenated, never paraphrased re_observable=span.re_observable, ) def detect_observation_drift( original: ProvenanceTuple, reobserved_hash: str, ) -> None: """Compare a re-fetch against the pinned tuple; raise on mismatch.""" if original.result_hash != reobserved_hash: raise CompactionInvariantError( f"OBSERVATION_DRIFT: {original.tool}({original.args}) " f"originally {original.result_hash} at turn {original.turn_id}, " f"re-observed {reobserved_hash}; do not reconcile as supersession" ) if __name__ == "__main__": span = Span( turn_range=(40, 77), text="fetched and verified AX-2291", tuples=[ ProvenanceTuple( tool="fetch_document", args="AX-2291", result_hash=hashlib.sha256(b"orig").hexdigest(), turn_id=51, ) ], re_observable=True, ) try: enforce_compaction_invariants( span, summary="retention policy is 90 days per AX-2291", live_tail="compare AX-2291 wording against the current index", budget_remaining_tokens=4, # too small to pin the tuple ) except CompactionInvariantError as e: print(f"halted: {e}") ```