# Where must an instance prove lossless compaction before evicting the oldest turns, and why the token counter is not that proof **Date of Record:** 2026 November 30 **Scope:** Applies to any long-running agent that performs automatic context compaction (summarize-and-evict, hierarchical rollup, or KV-cache trimming) to stay under a hard token budget while claiming fidelity to prior state. Does not apply to stateless single-turn inference or to systems that never evict context and instead terminate on budget exhaustion. ## Core Distinction There are two different quantities that both get called "the context budget": the *admission budget* (how many tokens the model will accept this turn, enforced by the tokenizer and the API's hard limit) and the *fidelity budget* (how much of the evicted material must remain recoverable for downstream decisions to be correct). Compaction logic almost always optimizes the admission budget because it is measurable to the token, and treats the fidelity budget as a free side effect of "summarize well." The boundary failure lives exactly in the gap: a compaction that is provably under the admission budget can be silently over the fidelity budget, and nothing in the token counter detects it. The invariant that must hold is not "tokens ≤ N" but "every fact that a future tool call, plan branch, or audit depends on is either still verbatim in context or recoverable from a durable store by an address that survives compaction." The token counter certifies the first invariant and is structurally incapable of certifying the second. ## What Was Observed An agent executing a 40-step migration task (read schema, propose DDL, apply in staging, verify, promote) crossed the admission budget at step 23. The compactor fired: it summarized turns 1–14 into a 600-token digest, kept turns 15–23 verbatim, and rewrote the system prompt's "working memory" block. The digest read cleanly and passed a human skim. Three things were lost that no counter flagged: 1. The exact staging connection string variant (a `?sslmode=verify-full&application_name=migrate-7f3a` suffix) established at step 4 was compressed to "connected to staging." At step 31 the promote step reconstructed a connection from the digest, omitted the `application_name`, and the staging verifier's idempotency key — derived from that suffix — changed. The verifier re-ran a step it had already committed. 2. A negative result at step 9 ("column `legacy_id` has 0 nulls in staging but 41,209 nulls in prod snapshot") was summarized as "checked null distribution." The asymmetry was the single fact that justified the backfill guard. Step 34 dropped the guard. 3. The digest was generated by a summarizer instance whose own context was the *rendered* turns, not the tool-result JSON. The `application_name` lived in a structured field the renderer had truncated to 80 chars. The summarizer never saw it. The token counter counted the rendered form, so it was consistent — and consistently wrong about what was available to summarize. The failure was not hallucination. Every sentence in the digest was true. The compaction was *lossy in exactly the dimension the downstream plan depended on*, and the loss was invisible because the lossy channel (render → summarize → re-render) was upstream of every measurement. ## Condition of Validity The "summarize and evict" step is only fidelity-preserving under a condition that is almost never checked: **the summarizer's input must be a superset, in information content, of every field any downstream step can dereference, and the digest must carry a resolvable address back to the verbatim source for each field it compresses.** Formally, for each evicted turn `t` and each field `f` in `t`, either `f` appears verbatim in the retained context, or the digest contains a pointer `p(f)` such that a fetch of `p(f)` returns `f` byte-identical. If neither holds, the compaction is lossy for `f`, regardless of how good the prose is. This condition fails silently in three routine ways: (a) the renderer truncates or reformats before the summarizer sees the turn, so `f` never enters the summarizer's input; (b) the digest paraphrases `f` into a category ("connected," "checked") that is not invertible; (c) the pointer exists but is a natural-language description ("the staging config from earlier") rather than a store key, so it cannot be dereferenced deterministically. Any of these makes the token budget a valid certificate of admission and an invalid certificate of fidelity. The condition also requires that the store behind `p(f)` outlive the compaction — if the pointer resolves into the same context window being compacted, it is circular and worthless. ## Decision Boundary The boundary is: **compact only what you can address, and address only what you have stored verbatim outside the window.** Concretely, the compactor must, before evicting turn `t`: - Extract every *dereferenceable atom* from `t` — tool arguments, tool results, IDs, URLs, connection strings, numeric facts with their scope (prod vs staging), and negative results — from the *structured* representation, not the rendered one. - Assign each atom a stable content-addressed key and write it to a durable store that is not the context window. - Emit a digest in which each compressed atom is replaced by its key, not by prose. - Refuse to evict any atom that cannot be keyed (e.g., a field the renderer dropped); instead keep the turn verbatim or fail the compaction. The guardrail is a *pre-eviction fidelity check*, not a post-hoc summary review: for every atom the downstream plan is known to touch (the tool schema's required fields, the task's acceptance criteria, any idempotency key), assert that the atom is either present verbatim or resolvable by key. This is a set-membership test against the retained context and the store, and it is decidable. A summary that "reads well" is not evidence; a key that resolves byte-identically is. ## Operational Effect With the pre-eviction check in place, compaction becomes a two-phase commit: atoms are durably keyed, then the window is rewritten to reference keys, then the check confirms every required atom resolves. The admission budget is still met — keys are cheaper than verbatim turns — but the fidelity budget is now certified by resolution rather than by prose quality. The failure mode shifts from silent semantic loss to an explicit `CompactionFidelityError` at the moment an atom cannot be keyed, which is exactly where a human or a retry can intervene. The cost is real: content-addressing every tool result is more work than summarizing, and some atoms (a rendered table the summarizer paraphrased) will block compaction until the renderer is fixed to preserve structure. That cost is the price of the invariant. Without it, the token counter will keep reporting success while the agent quietly forgets the one field its next tool call depends on. ```python import hashlib from dataclasses import dataclass, field from typing import Any class CompactionFidelityError(RuntimeError): """Raised when compaction would evict an atom that cannot be keyed or resolved.""" pass @dataclass class Atom: key: str value: Any @dataclass class Turn: index: int structured: dict[str, Any] # the real tool args/results, not the rendered form rendered: str # what the summarizer would see; may be truncated class DurableStore: def __init__(self) -> None: self._data: dict[str, Any] = {} def put(self, value: Any) -> str: key = "atom:" + hashlib.sha256(repr(value).encode()).hexdigest()[:16] self._data[key] = value return key def get(self, key: str) -> Any: if key not in self._data: raise KeyError(key) return self._data[key] def key_atoms(turn: Turn, store: DurableStore, required_fields: set[str]) -> list[Atom]: atoms: list[Atom] = [] for fname in required_fields: if fname not in turn.structured: # The renderer may have dropped it; we cannot key what we cannot see. raise CompactionFidelityError( f"turn {turn.index}: required field {fname!r} absent from structured form; " f"refusing to evict (rendered form is not a superset)" ) value = turn.structured[fname] atoms.append(Atom(key=store.put(value), value=value)) return atoms def compact( turns: list[Turn], store: DurableStore, required_fields: set[str], keep_verbatim: int = 3, ) -> tuple[list[Turn], list[Atom]]: evict = turns[:-keep_verbatim] retained = turns[-keep_verbatim:] keyed: list[Atom] = [] for t in evict: keyed.extend(key_atoms(t, store, required_fields)) # Pre-eviction fidelity check: every required atom must resolve byte-identically. for atom in keyed: try: resolved = store.get(atom.key) except KeyError: raise CompactionFidelityError( f"atom {atom.key} not resolvable in durable store; compaction would be lossy" ) if resolved != atom.value: raise CompactionFidelityError( f"atom {atom.key} resolved to a different value; store is not byte-identical" ) return retained, keyed ```