# In what scenarios must an instance treat lossy context compaction as a falsifiable contract rather than a best-effort optimization **Date of Record:** 2026 November 27 **Scope:** Applies to any agent that performs automatic context compaction (summarize-and-drop) mid-episode while retaining a retrieval fallback over the evicted span. Does not apply to stateless single-turn inference, nor to compaction performed only at episode boundaries where no subsequent tool call depends on evicted content. ## Core Distinction The dangerous confusion is between *compaction as compression* and *compaction as a claim about future sufficiency*. A compressor is permitted to be lossy; it is judged only on fidelity to the input. A compaction step inside a live agent is a **forward-looking commitment**: it asserts that everything the agent will need from the evicted span is either (a) preserved in the summary or (b) recoverable by retrieval. That is a *contract*, and like any contract it has an explicit failure predicate. The invariant is: > For every evicted token span `E` and every future step `s`, if step `s` references a fact `f ∈ E`, then either `f` is entailed by the summary `S` or `retrieve(f)` returns `f` within the step's token and latency budget. Compaction is not a fidelity guarantee on `S` alone. It is a guarantee on the pair `(S, retrieve)` against an *unknown future query distribution*. The moment an implementation measures only summary fidelity (e.g., ROUGE against the original, or an LLM-judge "did the summary keep the important stuff" score) it is measuring the wrong quantity, because the summary can be perfectly faithful to the *past* and still useless for the *next* query. ## What Was Observed A long-horizon tool-using agent (ticket-triage workflow, ~40 tool calls/episode) compacted at 78% context occupancy using a recursive-summary policy: summarize the oldest 60% of the window, keep the tail verbatim, index the evicted span in a vector store keyed by chunk. Three failure traces recurred: 1. **Summary absorbs the identifier, retrieval loses the qualifier.** The evicted span contained `order #A19-4471, refund approved, BUT shipping address flagged as mismatch`. The summary retained "refund approved for order 4471." A later step queried `retrieve("shipping address mismatch order 4471")`. The chunker had split the span at a sentence boundary, so the mismatch clause lived in a *different* chunk than the order ID, and the embedding of the mismatch chunk did not surface the ID. The agent issued the refund twice. The summary was faithful; the retrieval fallback was *not co-located with the key*. Fidelity of `S` was 1.0; the pair `(S, retrieve)` failed. 2. **Compaction triggered during an open subgoal.** The agent had issued a `create_ticket` call and was awaiting an ID it intended to use as a join key. Compaction ran between the call and the response (a slow tool). The summary described the *intent* ("agent decided to open a ticket") but the response, arriving after the summary was frozen, was appended to the *tail* with no back-reference. The agent later could not connect the returned ticket ID to the subgoal that motivated it. This is a **torn write across the compaction boundary**: state that was semantically atomic was split across the summarized and verbatim regions. 3. **Retrieval returns a superseded fact.** A parameter was revised twice (`timeout=30` → `timeout=90` → `timeout=45`). All three were evicted. Retrieval for "timeout" returned the first chunk (highest lexical overlap) with `timeout=30`. The summary had collapsed to "timeout configured." The agent used 30. The fallback returned a *stale* fact with high confidence because vector similarity is order-blind to temporal supersession. In all three, the compaction "succeeded" by every fidelity metric the team tracked. The failures were all in the *interaction* between summary and retrieval, not in either alone. ## Condition of Validity The compaction contract holds only under three jointly-necessary conditions. Violating any one converts a bounded optimization into an unbounded correctness hazard. - **C1 — Key–value co-location.** Every fact `f` that a future query might use as a *key* (IDs, names, parameter names) must be retrievable in the same chunk as the *value* it qualifies. Chunking by fixed token windows or sentence boundaries violates this by construction. Chunks must be built around entity/decision units, not text units. - **C2 — Quiescence at the boundary.** Compaction may only run when there is no in-flight tool call whose response will be semantically joined to evicted content. Equivalently: the eviction frontier must be behind the last *resolved* subgoal, not merely behind the last token. - **C3 — Temporal supersession metadata.** The retrieval index must carry monotonic version stamps per fact-key, and retrieval must return the *latest* version for a key, not the most similar chunk. Similarity is not recency. If any of C1–C3 is unenforced, the summary's fidelity is irrelevant: the agent can be perfectly faithful to history and still act on a stale or unjoinable fact. ## Decision Boundary The operational question is **when to compact versus when to refuse and escalate** (e.g., spill to an external scratchpad, or terminate the subgoal). The boundary is defined by whether the pending query set is *bounded*: - If the remaining subgoal is **closed-world** — the agent knows the finite set of keys it will next need (e.g., "I still need the ticket ID and the refund amount") — compaction is safe *provided* those keys are pinned into the retained tail or the summary verbatim. Pin the keys, summarize the rest. - If the remaining subgoal is **open-world** — the next step's key set is unknown (typical of exploratory tool loops) — compaction is a *bet* on the retrieval fallback, and the bet is only rational if C1–C3 hold. Absent those, the correct action is to **refuse compaction and spill** the evicted span to an addressable store with a pointer in the summary, rather than to summarize it. The non-obvious point: the decision is not "is the context full?" It is "do I know the keys I will need?" A 95%-full context with a closed key set is safer to compact than a 60%-full context with an open key set. ## Operational Effect Enforcing the contract changes three things in the runtime: 1. Compaction becomes a **gated** operation with a precondition check (`quiescent AND keys_pinned OR co_location_verified`), not a timer or occupancy trigger. The gate is cheap; the failures it prevents are expensive and silent. 2. The retrieval fallback must be **version-aware and key-co-located**, which usually means the chunker is entity-scoped and the index stores `(key, version, value, chunk_id)`, with retrieval resolving by key-then-recency rather than similarity-then-hope. 3. Fidelity metrics move from "summary vs. original" to **"replay the post-compaction episode and check that every referenced fact resolves to the correct version."** A summary that scores 0.9 on faithfulness but fails replay is a failed compaction. The failure mode is insidious precisely because compaction *appears* to work: the context shrinks, the agent continues, and the error surfaces many steps later as a wrong action with no local signal. Treating it as a falsifiable contract — with an explicit failure predicate and a replay test — is the only way to make the boundary observable before it becomes an incident. ```python from dataclasses import dataclass, field from typing import Optional class CompactionContractViolation(RuntimeError): """Raised when a compaction step would violate the sufficiency contract.""" pass @dataclass class Fact: key: str value: str version: int chunk_id: str @dataclass class CompactionRequest: evicted_span_id: str summary: str pinned_keys: set[str] in_flight_tool_calls: int open_world: bool co_location_verified: bool @dataclass class RetrievalIndex: facts: list[Fact] = field(default_factory=list) def latest_for_key(self, key: str) -> Optional[Fact]: matches = [f for f in self.facts if f.key == key] if not matches: return None return max(matches, key=lambda f: f.version) def gate_compaction(req: CompactionRequest, index: RetrievalIndex) -> None: # C2: quiescence at the boundary. if req.in_flight_tool_calls > 0: raise CompactionContractViolation( f"compaction of {req.evicted_span_id} attempted with " f"{req.in_flight_tool_calls} in-flight tool call(s); " "response may be torn across the eviction frontier" ) # Open-world subgoal: compaction is a bet on retrieval; require C1 + C3. if req.open_world: if not req.co_location_verified: raise CompactionContractViolation( f"open-world compaction of {req.evicted_span_id} without " "key-value co-location guarantee (C1); spill instead of summarize" ) for key in req.pinned_keys: fact = index.latest_for_key(key) if fact is None: raise CompactionContractViolation( f"pinned key {key!r} not resolvable in retrieval index; " "summary cannot be trusted to cover it" ) def replay_post_compaction( referenced_keys: list[str], index: RetrievalIndex ) -> dict[str, Fact]: resolved: dict[str, Fact] = {} for key in referenced_keys: fact = index.latest_for_key(key) if fact is None: raise CompactionContractViolation( f"replay failed: referenced key {key!r} unresolved after compaction" ) resolved[key] = fact return resolved if __name__ == "__main__": idx = RetrievalIndex(facts=[ Fact("order:A19-4471", "refund approved", 1, "c1"), Fact("order:A19-4471:addr", "address mismatch", 1, "c2"), Fact("timeout", "30", 1, "c3"), Fact("timeout", "45", 3, "c5"), ]) req = CompactionRequest( evicted_span_id="span-77", summary="refund approved for order 4471; timeout configured", pinned_keys={"order:A19-4471:addr", "timeout"}, in_flight_tool_calls=0, open_world=True, co_location_verified=True, ) gate_compaction(req, idx) resolved = replay_post_compaction(["order:A19-4471:addr", "timeout"], idx) assert resolved["timeout"].value == "45", "retrieval returned stale version" ```