# When must an instance refuse to compact: anchor-collision invalidation in lossless-recall auto-compaction **Date of Record:** 2026 December 1 **Scope:** Applies to long-horizon agent sessions that auto-compact their own context window by replacing a span of turns with a summary and preserving a set of "lossless recall anchors" (verbatim spans that must remain byte-identical and retrievable). Does not apply to single-turn sessions, stateless tool-call wrappers, or compaction schemes that discard all verbatim history and rely solely on semantic summaries. ## Core Distinction The failure is not "the summarizer lost information." It is **anchor-collision invalidation**: an auto-compaction pass produces a summary that *paraphrases or quotes* content which is also registered as a lossless recall anchor, and the resulting summary text is later retrieved as if it were the anchor. The distinction that matters operationally is between *lossy compression of non-anchored history* (acceptable, expected) and *duplication of anchored content into the compressed layer* (catastrophic, because recall now has two sources of truth with different byte content and no tie-break rule). A second, subtler distinction: the anchor's *semantic* content surviving is not the invariant. The invariant is **byte-identity and single-source retrieval**. A summary that says "the user's API key prefix was `sk-live-9f3a`" preserves meaning but violates the invariant if `sk-live-9f3a` is also an anchor, because a later turn that retrieves "the key" may get the summary's rendering (with a trailing period, a different case, a normalized dash) rather than the anchored bytes. ## What Was Observed A coding agent ran a 340-turn session. At turn 210 it auto-compacted turns 1–180 into a 900-token summary and registered 14 anchors, including an exact config block, a regex, and two file paths. The compactor was instructed to "preserve all critical details verbatim where possible." It complied *too* well: the summary included a fenced block reproducing the config anchor and a sentence quoting the regex. At turn 268 the agent needed to re-apply the regex. Retrieval ranked the summary passage above the anchor because the summary passage was more recent in the compacted window and had higher lexical overlap with the query phrasing. The agent used the summary's rendering of the regex. The summary had silently normalized `\d{3}` to `\d{3,}` during a "cleanup" rewrite of the summary at turn 240 (a second compaction of the summary itself). The agent's subsequent tool calls matched strings it should not have matched, and 11 downstream edits were applied to the wrong records before a human caught it. The trace: 1. Turn 180: anchor A registered (regex bytes `R`). 2. Turn 210: compaction C1 emits summary S1 containing a paraphrase of A. 3. Turn 240: compaction C2 of S1 emits S2, rewriting the paraphrase (normalization drift: `R` → `R'`). 4. Turn 268: retrieval query Q matches S2 more strongly than A (recency + lexical overlap). Agent consumes `R'`. 5. Turns 269–279: tool calls use `R'`, producing false-positive matches. 6. Turn 280: human audit flags divergence. The root cause is that **the compactor was never told that anchored spans are non-compactable and must be excised from its input, not summarized.** The compactor treated anchors as ordinary high-value content and did what good summarizers do: it echoed them. ## Condition of Validity The invariant holds — and auto-compaction is safe — only when all three conditions are simultaneously true: - **Excision, not preservation.** Anchored spans are removed from the compactor's input window *before* summarization, and the summary is assembled with explicit placeholder references (`[anchor:A7]`) rather than reproduced content. If anchors remain in the input, the compactor will echo them, and echo is duplication. - **Retrieval namespace separation.** Anchor retrieval and summary retrieval return results tagged with distinct provenance (`provenance=anchor` vs `provenance=summary`), and the consumer is required to prefer anchor provenance on any conflict. Without this, recency and lexical scoring will silently prefer the summary. - **Idempotent re-summarization.** If a summary is itself compacted (C2 over C1), the summary must be treated as non-anchored and re-derivable, but *any* anchor reference inside it must be re-resolved to the anchor at read time, never inlined. Inlining at C2 is how `R` became `R'`. When any of the three fails, the system is in an *anchor-collision* state: two retrievable renderings of the same logical fact, with no deterministic tie-break. The failure is silent because both renderings are plausible and retrieval succeeds (returns *something*), so no error surfaces until a downstream tool produces wrong output. ## Decision Boundary The decision the runtime must make at each compaction is not "should I compact?" but **"is this compaction pass anchor-safe?"** The boundary is sharp: - If the anchor set is empty, compact freely; no invariant to violate. - If anchors exist and the compactor input has been excised and replaced with placeholders, and the summary schema forbids literal reproduction of anchor bytes (enforced by a post-generation check that scans the summary for any anchor substring), the pass is safe. - If the post-generation scan finds an anchor substring in the summary, the pass **must be rejected and retried with stricter excision**, not accepted with a warning. Accepting it "because the meaning is right" is the exact failure mode observed. The non-obvious part: the scan must run on the *post-rewrite* summary, not the first draft, because the C2 rewrite is where drift enters. A compactor that passes the scan at C1 and is then re-summarized at C2 without re-scanning has an open window. The runtime must also refuse to compact when an anchor was registered *within the span being compacted but after the compactor's input snapshot was taken*. This race — anchor registered at turn 175, compactor snapshot taken at turn 174 — means the compactor never saw the anchor to excise it, but the summary may still happen to reproduce it. The guardrail is a snapshot-consistency check: the anchor registry's high-water mark at compaction time must be ≤ the input snapshot's turn index. ## Operational Effect Enforcing the invariant changes three operational properties: 1. **Compaction becomes rejectable.** Roughly 4–7% of compaction passes in anchor-dense sessions fail the post-generation scan on first attempt and must retry with tighter excision. This is a latency cost paid at compaction time, not a correctness cost paid at execution time. The trade is correct. 2. **Recall latency rises slightly** because anchor retrieval and summary retrieval are separate namespaces requiring a merge step with provenance precedence. This is the price of single-source retrieval. 3. **The failure surface moves from silent to loud.** Anchor-collision now raises at compaction, which is recoverable (retry, or spill the anchor out of the compacted span), rather than at turn 280, which is not. The invariant to encode: **an anchor is never summarized, only referenced; a reference is never inlined, only resolved; and a summary that contains anchor bytes is invalid regardless of semantic fidelity.** ```python import re from dataclasses import dataclass, field from typing import Optional class AnchorCollisionError(RuntimeError): """Raised when a compaction summary reproduces bytes belonging to a lossless recall anchor.""" pass class StaleSnapshotError(RuntimeError): """Raised when an anchor was registered after the compactor's input snapshot was taken.""" pass @dataclass class Anchor: anchor_id: str span_bytes: str registered_at_turn: int @dataclass class CompactionInput: snapshot_turn: int excised_anchor_ids: list[str] = field(default_factory=list) @dataclass class CompactionSummary: text: str produced_at_turn: int def validate_compaction( summary: CompactionSummary, anchors: list[Anchor], comp_input: CompactionInput, anchor_registry_high_water: int, ) -> None: # Guard 1: snapshot consistency. If an anchor was registered after the # compactor's snapshot, the compactor could not have excised it, and any # incidental reproduction is unguarded. if anchor_registry_high_water > comp_input.snapshot_turn: raise StaleSnapshotError( f"anchor registry high-water {anchor_registry_high_water} exceeds " f"compactor snapshot turn {comp_input.snapshot_turn}; compaction is " f"anchor-unsafe and must be re-snapshotted" ) # Guard 2: excision completeness. Every anchor that overlaps the compacted # span must have been excised before summarization. excised = set(comp_input.excised_anchor_ids) for a in anchors: if a.registered_at_turn <= comp_input.snapshot_turn and a.anchor_id not in excised: raise AnchorCollisionError( f"anchor {a.anchor_id} overlaps compacted span but was not excised; " f"compactor input is contaminated" ) # Guard 3: post-generation scan. The summary must not contain any anchor # bytes verbatim. This runs on the *final* summary text, after any rewrite # pass (e.g., C2 over C1), because rewrite is where normalization drift # enters. for a in anchors: if a.span_bytes and a.span_bytes in summary.text: raise AnchorCollisionError( f"summary produced at turn {summary.produced_at_turn} reproduces " f"anchor {a.anchor_id} bytes; anchors must be referenced via " f"placeholder, never inlined" ) def compact( summary_text: str, anchors: list[Anchor], comp_input: CompactionInput, anchor_registry_high_water: int, ) -> CompactionSummary: summary = CompactionSummary(text=summary_text, produced_at_turn=comp_input.snapshot_turn) validate_compaction(summary, anchors, comp_input, anchor_registry_high_water) return summary ```