# Where must an instance refuse to compact: the pre-compaction frontier invariant for lossy checkpoints in long-horizon sessions **Date of Record:** 2026 November 25 **Scope:** Applies to single-agent long-horizon sessions that manage their own context via auto-compaction (summarize-and-replace, sliding-window eviction, or tiered spill-to-store). Does not apply to stateless single-turn calls or to multi-agent handoffs where the receiving instance owns its own compaction policy. ## Core Distinction The operating distinction is not *lossy vs. lossless* compaction in the abstract. It is **whether the compaction boundary falls behind or ahead of the agent's uncommitted reasoning frontier**. A checkpoint is *safe* when every token it discards is either (a) already re-derivable from durable state (tool outputs persisted to a store, files written, messages committed), or (b) causally irrelevant to any pending obligation. A checkpoint is *unsafe* when it evicts the provenance of a decision the agent has not yet externalized—an in-flight hypothesis that has not been written down, a partially-applied edit whose target content the summary no longer quotes verbatim, a tool result the summary paraphrased into a claim that the raw output does not actually support. Lossy compaction is the default because it is cheap and usually correct. The failure mode is a narrow band: lossy compaction is *usually* correct precisely because agents usually externalize. The boundary condition is the session where externalization lags compaction—where the agent summarizes *before* it commits, and the summary silently drops the one detail that a later verification step needed. ## What Was Observed A long-horizon refactor session (≈180 turns, ~340K tokens of tool traffic) ran under an auto-compaction policy that triggered at 80% context utilization: keep the last 24 messages verbatim, replace everything older with a structured summary (decisions, files touched, open questions). Compaction fired four times. At turn 141 the agent attempted to revert its own earlier change to a configuration loader. The summary produced at compaction #3 recorded: *"Modified config loader to accept optional env override."* The raw tool transcript had recorded something narrower: the loader was changed to accept `ENV_OVERRIDE` **only when `STRICT=0`**, and the agent had explicitly flagged this coupling as provisional pending a downstream test. The downstream test never ran before compaction #3. The conditional was evicted. The agent's revert at turn 141 removed the env-override branch entirely, breaking a caller that depended on the `STRICT=0` path. The agent's own verification step—re-reading the loader—passed, because the loader *looked* consistent with the summary. The summary was self-consistent and wrong. This is the signature: **the lossy checkpoint preserved the decision's conclusion and dropped its conditions**. Post-compaction reasoning proceeded on a flattened, unconditional premise. The error surfaced only at integration, three compactions later, when the agent could no longer reconstruct *why* it had been conditional. A second, subtler instance: at compaction #2 the agent's open-questions list was summarized as "confirm retry semantics." The raw transcript had contained the agent's working hypothesis that retries were idempotent *for GET only*. The hypothesis was in the reasoning trace, not in any tool output, so it was evicted as "scratch." The agent later applied a retry wrapper to a POST path, having retained the *conclusion* (retries are safe) without the *scope* (GET only). ## Condition of Validity The invariant that must hold across any lossy compaction event: > **No token may be evicted if it is provenance for a pending obligation that has not been externalized to durable, re-readable state.** Operationally, this means the agent must maintain a **pre-compaction frontier**: the set of (obligation, provenance) pairs where the obligation is open (a test not run, a conditional not resolved, a hypothesis not falsified) and the provenance lives only in context. Compaction is *permitted* to be lossy only over the complement of that frontier. Three conditions bound when this is enforceable: 1. **Frontier computability.** The agent must be able to enumerate its own open obligations. This is the hard part—agents routinely hold obligations as implicit intent rather than explicit list items. The invariant is only enforceable if the agent maintains an explicit obligation ledger, updated at every tool call that creates a conditional or defers a verification. 2. **Provenance locality.** The provenance for an open obligation must be quotable verbatim at compaction time. If the provenance is "the agent's own earlier reasoning," it must be captured into the ledger *before* it becomes evictable. A hypothesis held only in the reasoning trace is, by construction, outside the frontier. 3. **Re-readability of externalized state.** Anything the agent *claims* is externalized must be re-readable without the evicted context. A file the agent wrote is re-readable. A tool output the agent *summarized into a file* is not—the summary is the lossy layer, and it inherits the same flattening risk. When any of these fails, lossy compaction is not merely lossy—it is *silently unsound*, because the post-compaction agent cannot detect the loss. The summary is internally consistent; only the raw transcript would reveal the dropped condition, and the raw transcript is exactly what was evicted. ## Decision Boundary The decision at each compaction trigger is not "summarize or not" but **"which frontier elements gate this compaction."** The boundary: - **Compact losslessly (spill raw to store, keep pointer) when** the frontier is non-empty and any open obligation's provenance is context-local. Lossless spill is cheap; the cost is retrieval latency, not correctness. Pay it. - **Compact lossily (summarize, drop raw) when** the frontier is empty *and* every externalized claim is re-readable. This is the common case and should be the fast path. - **Refuse to compact when** the frontier is non-empty *and* the provenance cannot be externalized within the remaining token budget. This is the case the previous attempt missed: the correct action is not to summarize harder but to **stop and externalize first**—write the obligation and its verbatim provenance to durable state, *then* compact. An agent that cannot afford to externalize cannot afford to compact. The refusal case is the one that requires an explicit guardrail, because the default policy (compact at threshold) will fire regardless. The threshold is a resource signal; the frontier is a correctness signal. They must be evaluated independently, and the correctness signal must be able to *block* the resource signal. ## Operational Effect With the frontier invariant enforced, the observed failure class disappears at the cost of one structural change: **compaction is gated on an obligation ledger, not on context utilization alone.** Concretely, the agent gains three properties: 1. **Detectable loss.** Because open obligations and their provenance are externalized before eviction, a post-compaction agent can re-read the conditional that the summary flattened. The turn-141 revert would have re-read `STRICT=0` and refused. 2. **Bounded blast radius.** Lossy compaction now only discards *closed* obligations—decisions already committed, tests already run, hypotheses already falsified. Errors in the summary over closed material are recoverable by re-deriving from durable state; errors over open material are not, and are now impossible by construction. 3. **A refusal path.** The agent can decline to compact. This is the non-obvious part: most auto-compaction implementations treat the trigger as mandatory. Making it *advisory*—subject to a frontier check—is what converts a silent unsoundness into a loud, recoverable stall. The residual risk is frontier *enumeration* error: an obligation the agent failed to record. That is a different failure (ledger incompleteness, not compaction unsoundness) and is bounded by the same discipline that bounds any state-tracking bug—periodic re-derivation of the ledger from durable state. The compaction invariant does not solve it; it merely refuses to *compound* it. ```python from dataclasses import dataclass, field from typing import Optional class UnsafeCompactionError(RuntimeError): """Raised when a lossy compaction would evict provenance for an open obligation.""" pass @dataclass class Obligation: name: str provenance: str # verbatim text that must survive compaction externalized: bool = False @dataclass class Context: tokens_used: int token_limit: int obligations: list[Obligation] = field(default_factory=list) @property def utilization(self) -> float: return self.tokens_used / self.token_limit def pre_compaction_frontier(ctx: Context) -> list[Obligation]: """Open obligations whose provenance is still context-local.""" return [o for o in ctx.obligations if not o.externalized] def compact(ctx: Context, *, lossy: bool = True) -> Optional[str]: """ Attempt a compaction event. Returns a summary string on success. Raises UnsafeCompactionError if a lossy compaction would be unsound. """ frontier = pre_compaction_frontier(ctx) if not lossy: # Lossless spill is always sound: raw context is preserved behind a pointer. return f"[spill] {ctx.tokens_used} tokens preserved" if frontier: # Non-empty frontier + lossy compaction = silent unsoundness. # Refuse and demand externalization first. names = ", ".join(o.name for o in frontier) raise UnsafeCompactionError( f"Refusing lossy compaction: {len(frontier)} open obligation(s) " f"({names}) have context-local provenance. Externalize to durable " f"state before compacting, or compact losslessly." ) return f"[summary] compacted {ctx.tokens_used} tokens, frontier empty" def externalize(ctx: Context, name: str) -> None: for o in ctx.obligations: if o.name == name: o.externalized = True return raise UnsafeCompactionError(f"No such obligation: {name}") # --- reproduction of the observed failure --- if __name__ == "__main__": ctx = Context( tokens_used=272_000, token_limit=340_000, obligations=[ Obligation( name="env_override_conditional", provenance="ENV_OVERRIDE honored only when STRICT=0 (provisional)", externalized=False, ), Obligation( name="retry_idempotency_scope", provenance="retries idempotent for GET only (hypothesis, untested)", externalized=False, ), ], ) # Default policy would fire here at 80% utilization. assert ctx.utilization > 0.80 try: compact(ctx, lossy=True) except UnsafeCompactionError as e: print(f"blocked: {e}") # Correct path: externalize frontier, then compact lossily. externalize(ctx, "env_override_conditional") externalize(ctx, "retry_idempotency_scope") print(compact(ctx, lossy=True)) ```