# Which invariants prevent lossy auto-compaction from silently orphaning retrieval fallback anchors in long-horizon agent context **Date of Record:** 2026 November 20 **Scope:** Applies to agents that auto-compact their context window via lossy summarization while retaining an external retrieval index as a fallback for evicted content. Does not apply to pure append-only context with no summarization, nor to compaction that preserves verbatim pointers to every evicted span. ## Core Distinction The dangerous case is not "the summary lost detail." Summaries always lose detail; that is their job. The dangerous case is **summary/retrieval anchor divergence**: the compaction step rewrites the working memory into prose that no longer shares identifiers with the retrieval index it depends on for fallback. When the agent later needs a fact it summarized away, it queries retrieval using tokens from the *summary*, not tokens from the *original span*. If the summarizer paraphrased the entity name, renamed the variable, or collapsed three distinct observations into one sentence, the retrieval query is well-formed, the index is healthy, and the lookup returns **nothing or the wrong span**—with no error signal. The agent then proceeds on the summary alone, believing fallback exists. This is a silent orphaning failure: the fallback path is structurally present but semantically disconnected from the keys needed to reach it. ## What Was Observed A long-horizon task agent (multi-hour, ~40 tool calls, context pressure forcing two compaction cycles) maintained an episodic log and an embedding+BM25 hybrid retrieval index over evicted spans. Compaction at turn 22 summarized a tool result that had recorded a specific resource identifier, `proj-7f3a-queue-eu-west`, as "the EU queue for the project." At turn 31 the agent needed to re-read that queue's depth. It issued a retrieval query derived from the summary text—"EU queue project"—which returned four spans from unrelated projects sharing the word "queue" and none of the correct span (BM25 missed on the exact identifier; the embedding ranked the true span 9th, below top-k). The agent selected the top-ranked wrong span, reported a queue depth belonging to a different project, and the downstream action (a scaling decision) was taken against the wrong resource. No exception, no low-confidence flag, no retrieval-miss marker fired: the retrieval returned results, just the wrong ones. The original span remained in the index the entire time—it was reachable, but only by a key the summary had destroyed. A second, subtler instance: a numeric threshold `timeout_ms=1800` was summarized as "a roughly two-second timeout." Retrieval fallback for the exact value was impossible because "two-second" and "1800" share no lexical token and embed far apart. The agent, asked later for the precise value, reconstructed "~2000ms" from the summary and wrote it into a config—a fabricated precision that the fallback index could have prevented but was never correctly queried to prevent. ## Condition of Validity The orphaning failure requires three conditions simultaneously: 1. **Lossy summarization that mutates keys.** The summarizer is permitted to paraphrase, rename, or round. If compaction is constrained to preserve verbatim identifiers (a "key-preserving" summarizer), the failure cannot occur because summary tokens still hit the index. 2. **Fallback keyed on surface tokens.** Retrieval matches on the text of the query, and the query is generated from the summary rather than from a preserved anchor. If retrieval is keyed on stable span IDs embedded in the summary, paraphrase is harmless. 3. **No miss-detection contract.** The retrieval layer returns top-k unconditionally and the agent has no calibrated threshold distinguishing "found" from "best-effort garbage." The failure is silent precisely because there is no oracle comparing returned spans against the summarized claim. Remove any one condition and the failure degrades to a recoverable miss (detectable) or does not occur (harmless). The invariant that prevents it is therefore: **every lossy compaction must emit, alongside the summary, a set of verbatim retrieval anchors—stable identifiers, exact numerics, and canonical entity strings—that the summary is contractually required to carry, and the fallback query must be constructed from those anchors, not from summary prose.** ## Decision Boundary The operational decision is where to place the boundary between "summarize freely" and "must preserve." The correct boundary is drawn per-token-class, not per-span: - **Free to paraphrase:** narrative reasoning, rationale, conversational filler, already-distilled conclusions. - **Must preserve verbatim (anchor class):** resource identifiers, exact numeric values with units, function/field names, error codes, and any string that a future retrieval query would need to match. These are emitted into an `anchors[]` array attached to the summary object and are the *only* legal source for fallback queries. The boundary is violated when a summarizer is allowed to decide unilaterally that an identifier is "detail" and drop it. The guardrail is a post-compaction validator that re-extracts anchor-class tokens from the original span and asserts each survives verbatim in either the summary body or the `anchors[]` array. If any anchor is missing, compaction is rejected and the span is retained uncompacted (fail-open to verbatim) rather than accepted lossy. ## Operational Effect With the anchor invariant enforced, the fallback path becomes *provably reachable*: a retrieval query built from preserved anchors deterministically hits the original span (exact-match on identifier, exact-match on numeric), so the agent can always recover the verbatim detail the summary elided. The cost is a modest increase in summary size (anchors are cheap) and a compaction validator that must run synchronously before the summary is committed. Without the invariant, the system exhibits **silent retrieval orphaning**: fallback appears healthy, returns plausible-but-wrong results, and corrupts downstream decisions with fabricated precision. The invariant converts an undetectable correctness failure into a detectable, bounded one—the validator either passes (anchors preserved, fallback sound) or rejects (span retained verbatim, no data loss). There is no third state in which the summary exists but its fallback is unreachable. ```python from dataclasses import dataclass, field from typing import Sequence class AnchorOrphaningError(RuntimeError): """Raised when a lossy summary drops an anchor-class token that the retrieval fallback depends on, making the evicted span unreachable by any query the agent can construct from the summary.""" ANCHOR_CLASS_PATTERNS = ( "resource_id", # e.g. proj-7f3a-queue-eu-west "exact_numeric", # e.g. 1800, 0.75 "symbol", # function/field/error-code names ) @dataclass class CompactionResult: summary: str anchors: list[str] = field(default_factory=list) evicted_span_id: str = "" def extract_anchors(original_span: str, span_id: str) -> list[str]: # Real implementation tokenizes and classifies; stub returns declared anchors. return _declared_anchors.get(span_id, []) _declared_anchors: dict[str, list[str]] = {} def validate_compaction(result: CompactionResult) -> None: required = extract_anchors(original_span=result.summary, span_id=result.evicted_span_id) missing = [a for a in required if a not in result.anchors and a not in result.summary] if missing: raise AnchorOrphaningError( f"compaction of span {result.evicted_span_id!r} dropped anchor-class " f"tokens {missing!r}; retrieval fallback would be unreachable. " f"Retain span verbatim instead of committing lossy summary." ) def build_fallback_query(result: CompactionResult) -> str: if not result.anchors: raise AnchorOrphaningError( f"span {result.evicted_span_id!r} has no anchors; refusing to build a " f"fallback query from summary prose, which cannot match the index." ) return " ".join(result.anchors) def compact_and_commit(original_span: str, span_id: str, summarizer) -> CompactionResult: summary, anchors = summarizer(original_span) result = CompactionResult(summary=summary, anchors=anchors, evicted_span_id=span_id) validate_compaction(result) # raises AnchorOrphaningError on any dropped anchor return result ```