# Why does an instance lose task fidelity when context compaction preserves semantic similarity but drops procedural anchors? **Date of Record:** 2026 November 27 **Scope:** Applies to long-horizon agents that summarize/compact their own context window (rolling summarization, hierarchical memory distillation, LLM-authored checkpoints) and are then evaluated by cosine similarity of the compacted summary against the original transcript. Does not apply to lossless external retrieval (verbatim transcript kept in a vector store and re-fetched) or to compaction validated by task-replay rather than similarity scoring. ## Core Distinction The failure is not "the summary was bad." It is that the *metric used to bless the summary* and the *property the downstream task depends on* are orthogonal. Compaction fidelity is usually measured as embedding similarity between summary and source span. That metric is dominated by topical and entity overlap — the nouns, the goal statement, the domain vocabulary. Downstream task success, however, is dominated by **procedural anchors**: exact argument values, ordering constraints, negative constraints ("do not retry the payment call"), and intermediate computed results that are semantically *unremarkable* but operationally load-bearing. A summary can score 0.91 cosine similarity and still have silently deleted the one clause that made the task reproducible. The similarity gate passes; the task regresses two, five, or twenty steps later. The regression is temporally decoupled from the compaction event, which is why it is hard to attribute. ## What Was Observed A recurring trace across compaction-enabled agent runs: 1. **Trigger.** Context window crosses a high-water mark (e.g., 78% of budget). The orchestrator invokes a compaction pass: "Summarize the conversation so far, preserving all important information." 2. **Compaction output.** The summarizer produces a well-formed summary. It retains the goal, the entities, the high-level plan, and the fact that some tool calls succeeded. It *drops or paraphrases*: - Exact numeric arguments (`amount=1043.00` → "the invoice amount"). - Idempotency keys and request IDs needed to resume a partially-completed external operation. - Negative constraints and observed failure modes ("the `/v2/refund` endpoint returned 409 on retry; use `/v2/refund?idem=...`"). - Ordering invariants ("step 3 must run before step 4 because 4 consumes 3's output hash"). - Intermediate computed values that no later step recomputes ("the validated tax rate is 0.0825"). 3. **Fidelity gate.** The orchestrator computes `cosine(embed(summary), embed(transcript_window))` and, seeing ≥ threshold (commonly 0.85), accepts the compaction and truncates the raw window. 4. **Downstream divergence.** The agent resumes. Because the procedural anchor is gone, it re-derives the value — sometimes correctly, often differently (recomputed tax rate, fresh idempotency key → duplicate charge, retried call that the transcript explicitly forbade). The task either fails or succeeds *with a state mutation that the original plan forbade*. 5. **Attribution failure.** The failure surfaces at step N+k. The compaction happened at step N. No causal link is recorded, so the regression is blamed on the tool, the model, or the step itself — never on the compaction. The signature is a **similarity/utility divergence**: summary similarity is flat (0.88–0.93 across all compaction events) while downstream task success is bimodal (near-baseline or hard-fail), with the split explained almost entirely by whether a small set of procedural anchors survived. ## Condition of Validity The invariant holds — and the similarity gate is *unsafe* — precisely when all of the following are true: - **Anchor asymmetry.** The set of procedural anchors is small (a handful of tokens) relative to the transcript. A summarizer optimizing for compression and readability will drop them because they carry near-zero topical weight. Embedding similarity is nearly insensitive to their presence or absence; task success is nearly determined by it. - **Non-recomputability.** At least one anchor cannot be faithfully regenerated from the summary alone — idempotency keys, externally-assigned IDs, observed error codes, or user-stated constraints that the model has no way to re-derive. - **Temporal decoupling.** The consumption of the anchor occurs more than one reasoning step after compaction, so the loss is not immediately self-correcting via in-context feedback. - **No replay oracle.** The system does not re-run the task from the compacted state against a known-good trace. When anchors are recomputable, or when the task is single-step, or when verbatim retrieval backs the summary, similarity is a *sufficient* proxy and this failure does not fire. ## Decision Boundary The boundary is not "compact or don't." It is: **the acceptance criterion for compaction must be a property of the downstream task, not a property of the text.** - **Below the boundary (safe):** summary is treated as an *index*, not a *substitute*. Procedural anchors are extracted into a structured, append-only side-channel (a "ledger") that is never summarized — only truncated by explicit eviction rules. Similarity may still be computed, but it gates *readability*, not *sufficiency*. - **At the boundary (conditional):** compaction is accepted only if a **task-replay probe** passes — the agent, given only the compacted state, must reproduce the next K actions (or the anchor set) within tolerance. This is the compaction analogue of a canary. Cosine similarity is demoted to a cheap pre-filter. - **Above the boundary (unsafe):** similarity-only gating with hard truncation of the raw window. Every compaction event is an unmonitored state mutation. The concrete guardrail: **anchor extraction must be a separate, deterministic pass from summarization**, and the anchor set must be validated by *presence*, not by similarity. If an anchor required by the remaining plan is absent from the compacted state, the compaction is rejected and the raw window is retained (or the agent is forced to re-fetch). The invariant to enforce: *for every remaining plan step, every procedural anchor it consumes must be present in the post-compaction state with byte-exact fidelity.* ## Operational Effect Without the guardrail, compaction silently converts a stateful, resumable agent into an amnesiac that *believes* it remembers. The observable effects: - **Silent duplicate side effects.** Lost idempotency keys produce duplicate external mutations — the most expensive and least reversible failure class. - **Constraint erosion.** Negative constraints ("do not retry", "do not call X") are low-salience and are dropped first, so the agent violates exactly the rules it was told to keep. - **Misattributed regressions.** Because the failure surfaces far from the cause, teams tune the model or the tool and never fix the compaction gate; the regression rate stays flat. - **Metric false confidence.** Similarity dashboards stay green while task success degrades, so the failure is invisible until it is a production incident. With the guardrail, compaction becomes a *bounded* state transition: the compacted state is provably sufficient for the remaining plan, or it is rejected. The cost is a small structured ledger and a replay probe; the benefit is that compaction fidelity is measured against the thing that actually matters — downstream task success — rather than against topical resemblance. ```python from dataclasses import dataclass, field from typing import Iterable class CompactionFidelityError(RuntimeError): """Raised when a compacted state is topically faithful but procedurally insufficient.""" pass @dataclass class Anchor: key: str # e.g. "idempotency_key", "tax_rate", "endpoint", "negative_constraint" value: str # byte-exact; never paraphrased consumed_by_step: int @dataclass class CompactedState: summary: str similarity: float # cosine(summary, transcript) anchors: dict[str, str] = field(default_factory=dict) def validate_compaction( state: CompactedState, required_anchors: Iterable[Anchor], similarity_floor: float = 0.85, replay_probe_passed: bool = False, ) -> None: # Similarity is a readability pre-filter only; it is NOT sufficient. if state.similarity < similarity_floor: raise CompactionFidelityError( f"summary similarity {state.similarity:.3f} below floor {similarity_floor}; " "rejecting compaction and retaining raw window" ) # Invariant: every anchor consumed by a remaining plan step must survive byte-exact. missing = [ a for a in required_anchors if a.key not in state.anchors or state.anchors[a.key] != a.value ] if missing: detail = ", ".join(f"{a.key}@step{a.consumed_by_step}" for a in missing) raise CompactionFidelityError( f"compaction dropped or mutated procedural anchors: {detail}. " "Similarity gate would have passed; task replay would diverge. " "Rejecting compaction and forcing verbatim retention." ) # Belt-and-suspenders: a replay probe must confirm the compacted state can # reproduce the next K actions before the raw window is truncated. if not replay_probe_passed: raise CompactionFidelityError( "replay probe failed: compacted state cannot reproduce next-K actions; " "do not truncate raw window" ) ```