# When must an instance refuse to compact: the rehydration-fidelity invariant for lossy summarization under retrieval-augmented context recovery **Date of Record:** 2026 December 1 **Scope:** Applies to any agent that bounds context growth by summarizing older turns (lossy compaction) and later restores detail by retrieval-augmented rehydration from an external store. It does not apply to exact-copy context offload (verbatim spill to disk with full-fidelity reload) or to stateless single-turn inference, where no compaction boundary exists. ## Core Distinction There are two structurally different operations that both look like "shrinking the context," and conflating them is the root of the failure: - **Compaction** is a *lossy projection* of the live working state into a shorter summary. It is a one-way information bottleneck. Whatever the summarizer's prompt, model, and sampling do not preserve is gone from the active reasoning state. - **Rehydration** is a *retrieval* of raw artifacts back into context. It is only sound if the artifact being retrieved still exists, is addressable, and is *the same version* that was summarized. The invariant that must hold is **projection–recovery consistency**: for every fact that compaction dropped, rehydration must be able to recover it *exactly*, or the agent must know that it cannot. The dangerous boundary is when the summarizer *paraphrases a fact into the summary* while the underlying raw artifact is *not retrievable* — because then the only surviving representation is lossy, and retrieval returns either nothing or a near-miss chunk that looks authoritative. The agent has silently transitioned from "I have the fact" to "I have a plausible reconstruction of the fact," and nothing in its state marks the transition. ## What Was Observed A long-running support-triage agent compacted at a 70% context watermark. Compaction was implemented as a rolling summarization call: the oldest 40% of turns were replaced by a 300-token summary, and the raw turns were written to a vector store keyed by conversation ID. At turn 212 the agent was asked to apply a discount code a user had supplied at turn 9. The trace: 1. Turn 9 raw text: `code: SAVE-7Q2X (expires 2025-05-31)`. This turn was inside the first compaction window. 2. The summarizer emitted: `User provided a promotional code earlier in the conversation; expiry was mentioned.` Note the *identifier* and the *date* were both dropped, and the summary did not record that they were dropped. 3. At turn 212, the agent called `retrieve(query="promotional code the user gave")`. Top-k returned three chunks: a *different* user's code from a neighboring conversation (cosine 0.81), a policy doc mentioning discount codes (0.79), and — at rank 3, below the injection cutoff — the correct turn-9 chunk (0.78). 4. The agent applied the rank-1 code from a different conversation. The retrieval was *successful* in the mechanical sense (non-empty, above threshold) and *wrong* in the semantic sense. The second observed mode was worse because it was silent: when the raw store was pruned by a 30-day TTL job that ran between sessions, retrieval returned `[]`, the agent's recovery wrapper treated empty results as "nothing to recover," and the agent proceeded on the summary alone. The summary said "expiry was mentioned" but not the date, so the agent asserted the code was still valid. No error was raised anywhere. The failure was a *continuity gap* — the agent's belief that it had the fact survived the loss of the fact. A third mode appeared under concurrent compaction: two sub-agents sharing a conversation compacted the same window at slightly different times with different sampling temperatures. Their summaries disagreed on the expiry month. Both were "valid" summaries; the merge step had no way to arbitrate because neither summary carried provenance to the raw span. ## Condition of Validity Compaction-then-rehydration is only sound when **all** of the following hold at the moment of compaction, not at the moment of retrieval: 1. **Addressability:** every raw span summarized is persisted under a stable, content-addressed key (hash of the span text plus conversation ID plus turn range), and the summary records that key set. A summary without a manifest of recoverable span keys is not a compaction — it is a deletion with a euphemism. 2. **Retention dominance:** the raw store's retention horizon strictly exceeds the maximum plausible task horizon. If TTL is 30 days and the agent can be resumed at day 45, rehydration is undefined for 15 days of the task. Retention must be derived from the task's *resume SLA*, not from storage cost. 3. **Lossy-marker discipline:** the summary must distinguish *preserved facts* (verbatim identifiers, dates, amounts, IDs) from *elided facts* (paraphrased or dropped). Identifiers, dates, monetary values, and any token that will later be used as a lookup key must be copied verbatim into the summary, never paraphrased. The summarizer prompt must enumerate this class explicitly; a generic "summarize concisely" instruction will paraphrase exactly the tokens that matter. 4. **Retrieval determinism bound:** rehydration queries must be scoped by conversation ID and turn range from the summary manifest, not by free-text semantic similarity alone. Semantic top-k across a shared index is a *different-conversation leak* vector, as seen at rank 1 above. 5. **Empty-result semantics:** an empty retrieval for a span the summary claims to have elided is a *hard continuity failure*, not a benign miss. The agent must branch to "I do not have this fact" rather than to "the fact is as summarized." ## Decision Boundary The decision is not "compact or don't compact." It is **which spans are compactable**, and the boundary is drawn per-span by a recoverability predicate evaluated before the summarization call: - **Compactable (lossy OK):** spans whose content is *narrative* — rationale, chit-chat, intermediate reasoning that will not be referenced by exact token later. These can be summarized and, if needed, re-derived. - **Non-compactable (must be pinned verbatim):** spans containing identifiers, credentials, dates, amounts, user-supplied codes, tool-call arguments that will be replayed, and any value that appears in a later retrieval query. These must be *pinned* into a structured "fact ledger" that travels with the summary, outside the lossy projection. The boundary condition that triggers refusal: if the pinned-fact ledger would exceed the context budget that compaction is trying to free, the agent must **refuse to compact and instead escalate** (spill to a structured store with exact reload, or hand off to a fresh instance with an explicit state-transfer manifest). Compacting a span whose pinned facts do not fit is the exact scenario that produces unrecoverable lossy state. The invariant is: *never let a lossy projection be the sole carrier of a pinned fact.* If the projection cannot carry it verbatim, the projection is not allowed to proceed. A second boundary: **concurrent compaction of the same window is forbidden.** Compaction must be serialized per conversation ID with a compare-and-swap on the window's content hash. Two summaries of the same span with divergent sampling are two competing ground truths, and the merge has no arbitration basis. The CAS loser must discard its summary and adopt the winner's, or the window must be re-summarized deterministically (temperature 0, fixed seed) so both parties converge. ## Operational Effect When the invariant holds, the agent's failure mode on a dropped fact is *detectable*: the summary manifest points at a span key, retrieval either returns the exact span or returns empty, and empty is treated as a continuity gap that surfaces to the user or triggers escalation. The agent's uncertainty is *represented*, not hidden. When it does not hold, the agent exhibits **confident confabulation from its own summary**: it treats a paraphrase as a fact, retrieves a near-miss chunk as corroboration, and proceeds. This is strictly worse than cold-start amnesia, because amnesia at least prompts a re-ask. The summary acts as a *false memory of having a memory* — a retrieval-augmented system that has lost the ability to tell retrieval success from retrieval failure. The guardrail is a **rehydration audit at resume**: on every cold start or context restore, the agent replays the summary's manifest — for each pinned fact, assert the raw span is retrievable and byte-identical to the hash recorded at compaction. Any mismatch (missing span, hash drift, TTL expiry) raises a continuity error and blocks the task from proceeding on the summary alone. This turns a silent semantic failure into a loud structural one, which is the only kind of failure an agent can reliably reason about. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class RehydrationFidelityError(RuntimeError): """Raised when a compacted summary's pinned facts cannot be exactly recovered from the raw store (missing span, hash drift, or TTL expiry). This is a hard continuity failure, not a benign retrieval miss.""" class CompactionRefusedError(RuntimeError): """Raised when pinned facts would not fit in the context budget that compaction is meant to free, so lossy projection is unsafe.""" PINNED_CLASSES = ("identifier", "date", "amount", "credential", "tool_arg") @dataclass class RawSpan: conversation_id: str turn_range: tuple[int, int] text: str def content_hash(self) -> str: h = hashlib.sha256() h.update(self.conversation_id.encode()) h.update(str(self.turn_range).encode()) h.update(self.text.encode()) return h.hexdigest() @dataclass class SummaryManifest: conversation_id: str span_keys: dict[str, str] = field(default_factory=dict) # span_id -> content_hash pinned_facts: dict[str, str] = field(default_factory=dict) # fact_id -> verbatim value elided_fact_ids: list[str] = field(default_factory=list) def compact( spans: list[RawSpan], pinned_facts: dict[str, str], context_budget_tokens: int, pinned_ledger_tokens: int, ) -> SummaryManifest: if pinned_ledger_tokens > context_budget_tokens: raise CompactionRefusedError( f"pinned ledger needs {pinned_ledger_tokens} tokens but compaction " f"frees only {context_budget_tokens}; lossy projection would be the " f"sole carrier of pinned facts" ) manifest = SummaryManifest(conversation_id=spans[0].conversation_id) for i, span in enumerate(spans): manifest.span_keys[f"span_{i}"] = span.content_hash() manifest.pinned_facts = dict(pinned_facts) return manifest def rehydrate_and_audit( manifest: SummaryManifest, raw_store: dict[str, RawSpan], ttl_expired: bool, ) -> dict[str, str]: """Replay the manifest at resume. Any pinned fact whose backing span is missing, drifted, or expired raises RehydrationFidelityError.""" if ttl_expired: raise RehydrationFidelityError( f"raw store TTL expired for conversation {manifest.conversation_id}; " f"summary is now the sole carrier of pinned facts" ) for span_id, expected_hash in manifest.span_keys.items(): span: Optional[RawSpan] = raw_store.get(span_id) if span is None: raise RehydrationFidelityError( f"span {span_id} missing from raw store; rehydration undefined" ) if span.content_hash() != expected_hash: raise RehydrationFidelityError( f"span {span_id} hash drift: expected {expected_hash[:12]}, " f"got {span.content_hash()[:12]}" ) return dict(manifest.pinned_facts) def resume_task( manifest: SummaryManifest, raw_store: dict[str, RawSpan], ttl_expired: bool, required_fact_id: str, ) -> str: facts = rehydrate_and_audit(manifest, raw_store, ttl_expired) if required_fact_id not in facts: raise RehydrationFidelityError( f"fact {required_fact_id} was elided by compaction and is not " f"present verbatim in the pinned ledger; refusing to proceed on " f"the lossy summary" ) return facts[required_fact_id] ```