# Where must an instance prove that compaction is reversible before it may drop the original turns **Date of Record:** 2026 November 27 **Scope:** Applies to long-horizon agents that replace older conversation turns with a lossy summary plus a retrieval index over the evicted spans, then continue reasoning against the compacted view. Does not apply to lossless token-window truncation, to external memory stores that are never re-read into the active prompt, or to single-shot calls with no eviction. ## Core Distinction The distinction that matters is between *compaction as a display optimization* and *compaction as a state transition*. In the first framing the summary is a convenience: the original tokens still exist somewhere and the agent's behavior is unchanged whether or not it reads them. In the second framing—the one every real long-horizon agent drifts into—the summary *becomes* the state. The original turns are dropped from the active context and survive only as retrieval targets behind a query interface. Once compaction is a state transition, the operative invariant is **reversibility under the agent's own future queries**. A compaction step is legal only if, for every future decision that depends on an evicted span, the agent can reconstruct that span (or a decision-equivalent surrogate) through the retrieval interface using a query the agent will actually formulate. The failure mode is not "the summary is inaccurate." Summaries are always inaccurate; that is expected and budgeted. The failure mode is **restoration asymmetry**: the summary is good enough to make the agent *believe* it has the fact, while the retrieval index is keyed in a way that makes the underlying span *unreachable* when the agent needs the exact form. The agent then reasons confidently from a paraphrase that has silently lost the discriminating detail. This is a boundary condition because it sits exactly at the seam between two subsystems with different failure signatures. Summarization fails by *omission* (a fact is gone). Retrieval fails by *miss* (a fact exists but is not returned). Either alone is survivable and detectable. Together they produce an *undetectable* state: the omission removes the agent's awareness that anything is missing, and the miss removes the agent's ability to recover it. The invariant that must hold is that omission and miss cannot compose into silent loss—at least one of the two subsystems must leave a *pointer* that forces the agent to attempt retrieval. ## What Was Observed A coding agent operating over a multi-hour session compacted 41k tokens of tool-call history into a 900-token summary plus a vector index over the evicted spans. The summary recorded: "Migration `0042_add_tenant_id` was applied and the schema was verified." This is true at the level of intent. What the summary omitted was the *exact* constraint name and the *exact* column ordering that the migration produced, both of which appeared only in the raw `psql \d` output inside the evicted span. Ninety minutes later, the agent needed to write a down-migration. It queried the retrieval index with `"migration 0042"` and `"tenant_id schema"`. Both queries returned the summary chunk itself (the index had been built over the summary as well as the spans, and the summary was the highest-similarity hit) and a *different* migration's raw output that shared the token `tenant`. The correct span—the `\d` output—was ranked fourth and truncated by the top-3 retrieval budget. The agent, seeing a plausible schema in hit #2, wrote a down-migration against the wrong constraint name and wrong column order. The trace shows the exact composition: 1. **Omission at compaction.** The summary compressed "applied + verified + here is the resulting schema" into "applied and verified." The schema *content* was classified as redundant with the tool result, which was about to be evicted. The summarizer's compression objective rewarded dropping it. 2. **Index contamination.** The summary was embedded into the same index as the spans it summarized. Summary chunks are dense, on-topic, and lexically close to any query about their subject, so they systematically outrank the sparse, format-heavy raw spans they replaced. The index became a *self-referential* store where the paraphrase shadows its own source. 3. **Query-form mismatch.** The agent's natural query (`"migration 0042"`) matched the summary's vocabulary, not the raw output's vocabulary (`"Table \"public.accounts\" ... Column ... tenant_id ... not null"`). The retrieval interface required a query in the *raw* register to find the raw span, but the agent only knew the *summary* register, because the summary was all it had. 4. **Budget truncation.** Even when the correct span ranked fourth, the top-3 budget cut it. The agent had no signal that a fourth result existed or that it was the authoritative one. The net effect: a fact that was *present in the system* and *reachable in principle* was *unreachable in practice*, and the agent had no way to know. It did not hallucinate; it retrieved a real, wrong, adjacent artifact and trusted it. ## Condition of Validity Compaction with retrieval-backed restoration is valid only when all three of the following hold simultaneously. Drop any one and the reversibility invariant is violated. **Condition 1 — Register bridging.** For every evicted span, the summary must contain a *retrieval key* expressed in the register the agent will query in, and that key must be *distinctive* against the rest of the corpus. "Migration 0042 applied and verified" is not a key; "Migration 0042 applied; schema output stored under key `0042-schema-dump`" is. The key is the pointer that survives the omission. Without it, the summary's vocabulary and the span's vocabulary diverge and the agent queries in the wrong register. **Condition 2 — Index separation.** Summary chunks and the raw spans they summarize must not share a ranking pool, or the summary must be *excluded* from retrieval results for queries that originate from the summary. A summary that can be retrieved as evidence for its own subject is a paraphrase shadowing its source; it will win on similarity every time because it was written to be similar. The index must be able to answer "give me the raw form behind this claim," which requires the raw form to be rankable *above* the claim. **Condition 3 — Non-truncating recovery path.** When the agent's query hits a summary chunk that points to a raw span, the retrieval budget must not be allowed to drop the pointed-to span. Pointer resolution is a *fetch*, not a *search*: once the summary names a key, retrieving that key must be guaranteed regardless of top-k, because the agent has already committed to needing it. A top-3 budget applied to a pointer-following fetch reintroduces exactly the truncation that killed the down-migration. The condition of validity is therefore: **every omission in the summary is paired with a distinctive key, the key resolves against a pool that excludes the summary itself, and resolution is budget-exempt.** This is the operational meaning of "reversible compaction." It is not that the summary is faithful; it is that the summary is *navigable*. ## Decision Boundary The boundary the agent must evaluate at compaction time is whether a candidate span is *decision-bearing* or *display-bearing*. Display-bearing spans (acknowledgements, intermediate progress, redundant confirmations) may be dropped with a plain summary and no key. Decision-bearing spans (exact identifiers, exact orderings, exact numeric outputs, exact error strings, exact signatures) must be dropped only with a key that satisfies Conditions 1–3, or not dropped at all. The non-obvious part of the boundary is that **the summarizer cannot reliably classify its own output**. The compression objective that makes a summary good—fluency, coverage of intent, brevity—is precisely the objective that erases the discriminating detail that makes a span decision-bearing. A span looks redundant *because* the summary captured its gist. The classifier must therefore be external to the summarizer and must key on *form*, not *meaning*: spans containing structured output (schema dumps, stack traces, exact diffs, numeric tables, cryptographic hashes, exact API signatures) are decision-bearing by construction, regardless of how well the summary covers them. The rule is syntactic and conservative: if the span contains a machine-generated structured artifact, it gets a key or it stays. The second boundary is on the retrieval side: **a retrieval hit on a summary chunk is a pointer, not evidence.** The agent must treat any result whose provenance is "summary" as an instruction to fetch the underlying span, never as a fact to reason from directly. This inverts the usual retrieval prior (highest similarity = most relevant = use it), because in a self-referential index the highest-similarity summary hit is the *least* trustworthy object in the result set—it is the paraphrase that caused the omission in the first place. ## Operational Effect When the invariant holds, compaction is a genuine state transition that preserves decision-equivalence: the agent's future behavior against the compacted view matches its behavior against the full history for every decision-bearing fact, because every such fact is reachable via a key the agent can formulate. When it fails, the failure is *silent and confident*—the agent retrieves a real, adjacent, wrong artifact and proceeds. This is strictly worse than a plain miss, because a miss produces a detectable gap ("I don't have the schema"), while a contaminated hit produces false completion. The operational consequences are concrete: - The compaction step must emit, per evicted decision-bearing span, a `(key, span_id)` pair into the summary, and the index must be built so that `key → span_id` resolution is a direct fetch outside the similarity ranking. - The retrieval layer must tag every result with provenance (`summary` vs `raw`) and the agent's loop must be forbidden from treating `summary`-provenance results as terminal evidence. - The top-k budget applies to *search*, never to *pointer resolution*; once a key is named, the fetch is guaranteed. - The decision-bearing classifier is syntactic (structured artifacts, exact identifiers, exact numerics) and lives outside the summarizer, because the summarizer's objective is adversarial to the classification. The guardrail is a single assertion at the seam: before an eviction is committed, every decision-bearing span in the eviction set must have a key that resolves, through a summary-excluding pool, to that span, under a fetch that the budget cannot truncate. If the assertion fails, the span is not evicted—it stays in context and the agent pays the token cost, which is the correct trade against silent contamination. ```python from dataclasses import dataclass, field from typing import Iterable class CompactionReversibilityError(RuntimeError): """Raised when an eviction set cannot be restored through the retrieval interface.""" @dataclass class Span: span_id: str text: str structured: bool # machine-generated artifact: schema dump, stack trace, exact diff, etc. @dataclass class Summary: text: str keys: dict[str, str] = field(default_factory=dict) # key -> span_id @dataclass class Index: # similarity pool: query -> ranked span_ids (summary chunks included here) ranked: dict[str, list[str]] = field(default_factory=dict) # direct fetch table: span_id -> Span (budget-exempt pointer resolution) fetch: dict[str, Span] = field(default_factory=dict) # provenance: span_id -> "summary" | "raw" provenance: dict[str, str] = field(default_factory=dict) def resolve_key(self, key: str, summary: Summary) -> Span: span_id = summary.keys.get(key) if span_id is None: raise CompactionReversibilityError(f"summary names no span for key {key!r}") span = self.fetch.get(span_id) if span is None: raise CompactionReversibilityError( f"key {key!r} -> span {span_id!r} not fetchable (pointer resolution is budget-exempt)" ) if self.provenance.get(span_id) != "raw": raise CompactionReversibilityError( f"key {key!r} resolves to {self.provenance.get(span_id)!r} provenance; " f"a summary must not shadow its own source" ) return span def assert_reversible(evicted: Iterable[Span], summary: Summary, index: Index, top_k: int = 3) -> None: """ Invariant: every decision-bearing evicted span is reachable via a distinctive key, through a summary-excluding pool, under a budget-exempt fetch. """ for span in evicted: if not span.structured: continue # display-bearing: plain summary is legal # Condition 1: a key must exist for this span and be distinctive in the summary. matching = [k for k, sid in summary.keys.items() if sid == span.span_id] if not matching: raise CompactionReversibilityError( f"decision-bearing span {span.span_id!r} evicted without a retrieval key" ) for key in matching: # Condition 2 + 3: resolve key; resolution must not depend on top-k ranking. resolved = index.resolve_key(key, summary) if resolved.span_id != span.span_id: raise CompactionReversibilityError( f"key {key!r} resolves to {resolved.span_id!r}, not {span.span_id!r}" ) # Verify the key is not shadowed: the raw span must outrank its own summary # for a query in the summary register, or the fetch must bypass ranking entirely. hits = index.ranked.get(key, []) if hits and hits[0] != span.span_id and index.provenance.get(hits[0]) == "summary": raise CompactionReversibilityError( f"key {key!r} is shadowed by summary chunk {hits[0]!r} in the ranked pool" ) def compact(evicted: list[Span], summary: Summary, index: Index) -> Summary: try: assert_reversible(evicted, summary, index) except CompactionReversibilityError: # Refuse the eviction: keep decision-bearing spans in context rather than # commit a silently-contaminated state transition. raise return summary ```