Under what conditions must an instance refuse to auto-compact a context window instead of summarizing it lossily
**Date of Record:** 2026 December 2 **Scope:** Applies to any agent runtime that performs automatic context compaction (lossy summarization plus salience scoring) when the working context approaches its token budget, and that claims a reversible checkpoint so a task can resume after compaction. Does not apply to stateless single-shot inference, nor to compaction of purely conversational history with no pending tool-call obligations.
Core Distinction
The distinction that matters is between **compaction as semantic compression** and **compaction as obligation erasure**. A summarizer is trained to preserve topical salience: what the conversation was about, what was decided, what seems important. It is *not* trained to preserve the set of unresolved, machine-checkable obligations the instance is currently on the hook for — pending tool-call IDs awaiting results, exact argument values that must be replayed byte-for-byte, checksum-verified file slices, or the precise precondition that made a prior step valid. Those obligations are *low-salience and high-consequence*: a salience scorer will rank "user prefers concise answers" above "tool_call_id=tc_7f3a pending, args hash 0x9c1e, must match before commit." When the budget forces compaction, the scorer discards the second and keeps the first, and the instance resumes with a fluent, confident, and *wrong* model of what it still owes.
The invariant is therefore not "summaries must be faithful." It is: **compaction may only be applied to context segments that carry no outstanding machine-checkable obligation, and the checkpoint must be able to reconstruct every obligation not covered by the summary.** If that invariant cannot be established before the budget is exhausted, the correct behavior is to *refuse to compact* and surface a budget-exhaustion fault, not to summarize and continue.
What Was Observed
A three-step tool-using task: read a config file, patch two keys, then run a verifier that re-reads the file and compares against an expected hash embedded in the original user turn. At step 2 the context hit 91% of budget. Auto-compaction fired. The salience scorer, weighting recency and topical centrality, retained the patch intent ("update `max_retries` and `timeout_ms`") and the user's general framing, but dropped (a) the exact original bytes of the config file returned by the read tool, (b) the `tool_call_id` of the read result the patch was derived from, and (c) the expected-hash string, which had appeared once, early, in a long user message.
The checkpoint was marked "reversible." It was not. On resume the instance re-derived the patch arguments from the *summarized* description rather than the original bytes. The re-derived `timeout_ms` differed from the original by a unit interpretation (seconds vs milliseconds) — a plausible, fluent, wrong value. The verifier at step 3 compared the patched file against the expected hash and failed. The instance, now holding a summary that asserted the patch was correct, entered a repair loop: it re-patched, re-failed, and re-summarized, each compaction further degrading the original bytes until the expected hash itself was no longer recoverable from context. The task ended in a confident false report of success against a hash the instance had hallucinated into the summary.
The failure trace has a precise shape:
- **Trigger:** budget crossing threshold while an unresolved tool-call obligation and a byte-exact replay requirement are both live in context.
- **Scoring:** salience model ranks the obligation low (it is terse, technical, non-topical) and ranks narrative framing high.
- **Loss:** obligation tokens evicted; summary retains the *claim* that the step succeeded.
- **Checkpoint write:** checkpoint records the summary, not the evicted spans; "reversible" is asserted without a reconstruction path.
- **Resume:** instance treats summary as ground truth, re-derives arguments probabilistically.
- **Divergence:** re-derived values drift from originals; verifier fails; repair loop compounds the drift because each repair is itself summarized.
The compounding step is the killer. Lossy compaction is not idempotent under repetition: each cycle re-summarizes a summary, and the drift is monotonic toward whatever the salience model finds plausible. There is no fixed point that recovers the original bytes.
Condition of Validity
Auto-compaction is valid **only** when all of the following hold at the moment of the budget crossing:
- **No live obligation.** There is no pending tool call, no unacknowledged handoff, no unverified commit whose correctness depends on context that would be evicted.
- **Replayable state is externalized.** Every byte-exact value the task will need later (file contents, argument hashes, expected hashes, IDs) is durably stored outside the context window and referenced by a stable handle, so the summary can point at it rather than paraphrase it.
- **Checkpoint is reconstructing, not descriptive.** The checkpoint stores the evicted spans (or content-addressed pointers to them), so "resume" restores the actual state rather than a narrative about it. A checkpoint that cannot reconstruct the evicted bytes is a *lossy* checkpoint and must not be labeled reversible.
- **Salience scoring is obligation-aware.** The scorer must treat machine-checkable obligations as a protected class that cannot be scored below the eviction threshold, regardless of topical salience.
If any condition fails, the instance must not compact. The correct transition is to a **budget-exhaustion fault** that halts the task and reports the specific unmet condition, preserving the full context for external inspection. Refusing is cheap; a confident wrong resume is expensive and, in verification-bearing tasks, silently corrupting.
The subtle point: the condition "no live obligation" is *not* the same as "the task looks nearly done." A task one step from completion is exactly the task most likely to have a live, high-consequence obligation (the final verification). Salience models systematically under-weight end-of-task obligations because the surrounding narrative is settled and calm. The instance must check obligations structurally, not by reading the summary's tone.
Decision Boundary
The boundary is a single predicate evaluated *before* the summarizer runs, not after:
compact_allowed = (live_obligations == empty)
AND (all_replay_values_externalized)
AND (checkpoint.reconstructs_evicted_spans)
AND (salience.protects_obligation_class)
If `compact_allowed` is false, the instance transitions to `BUDGET_EXHAUSTED` and does not summarize. It does not "try a smaller summary," does not "compact only the oldest turns" (oldest turns are precisely where the original expected-hash and tool-call IDs live), and does not proceed on the assumption that it can reconstruct later — reconstruction is the failure mode, not the fallback.
A secondary boundary governs the repair loop: **after any verifier failure, compaction is disabled for the remainder of the task.** A failed verification means the instance's model of state is already suspect; summarizing that suspect state and continuing is how drift becomes monotonic. The repair loop must operate on full, un-compacted context or halt.
The trap to name explicitly: an instance that has *already* compacted lossily cannot reliably evaluate `compact_allowed`, because the evidence it would need (the original obligations) is what got evicted. This is why the predicate must be evaluated *proactively* at a threshold safely below the hard budget limit — a compaction trigger at 91% leaves no headroom to externalize state before eviction. The trigger threshold must reserve enough budget to *perform the externalization* (write spans to durable storage, mint handles) before the summarizer is permitted to run. A runtime that compacts at the first sign of pressure has already lost the ability to compact safely.
Operational Effect
The operational consequence is a shift from *reactive* to *reserved* compaction. The runtime reserves a fraction of the budget (empirically 15–25% for tool-heavy tasks) as an externalization margin. When the working context crosses the *soft* threshold, the instance externalizes all replay-critical values to durable storage and rewrites references as handles — this is lossless and cheap. Only after externalization, and only if no live obligation remains, may the summarizer run. The summary then compacts *narrative* and *decision* content, which is what summarizers are good at, while byte-exact content lives behind handles the summary can cite.
The effect on the failure above: at the soft threshold the instance would have externalized the config bytes, the `tool_call_id`, and the expected hash to storage, replaced them in context with handles, and *then* — with the obligation now externalized and checkable — either compacted safely or, if the patch obligation was still live, refused and halted. Either path is correct; the original path was not.
The invariant to carry forward: **a reversible checkpoint is defined by its reconstruction test, not by its label.** The only way to know a checkpoint is reversible is to attempt reconstruction of the evicted spans and compare byte-for-byte against the originals. A checkpoint that passes the reconstruction test is safe to resume from; one that fails it is a lossy summary wearing a reversible label, and resuming from it is the failure. Instances should treat "reversible" as a claim requiring proof, never as an attribute granted by the compaction subsystem.
from dataclasses import dataclass, field
from typing import Optional
class UnsafeCompactionError(RuntimeError):
"""Raised when auto-compaction is attempted while the safety predicate fails."""
pass
@dataclass
class Obligation:
tool_call_id: str
args_hash: str
resolved: bool = False
@dataclass
class Checkpoint:
evicted_spans: dict = field(default_factory=dict) # handle -> original bytes
reconstructs_evicted: bool = False
def reconstructs(self, handle: str, original: bytes) -> bool:
return self.evicted_spans.get(handle) == original
@dataclass
class ContextState:
token_budget: int
tokens_used: int
obligations: list = field(default_factory=list)
externalized: dict = field(default_factory=dict) # value -> durable handle
replay_values: dict = field(default_factory=dict) # name -> bytes needed later
checkpoint: Optional[Checkpoint] = None
@property
def live_obligations(self):
return [o for o in self.obligations if not o.resolved]
@property
def pressure(self) -> float:
return self.tokens_used / self.token_budget
def all_replay_externalized(self) -> bool:
return all(name in self.externalized for name in self.replay_values)
def compact_allowed(state: ContextState) -> bool:
if state.live_obligations:
return False
if not state.all_replay_externalized():
return False
if state.checkpoint is None or not state.checkpoint.reconstructs_evicted:
return False
return True
def maybe_auto_compact(state: ContextState, soft_threshold: float = 0.75) -> str:
if state.pressure < soft_threshold:
return "no_action"
# Externalize replay-critical values BEFORE any summarization.
for name, raw in state.replay_values.items():
if name not in state.externalized:
state.externalized[name] = f"handle://{name}"
if not compact_allowed(state):
unmet = []
if state.live_obligations:
unmet.append(f"{len(state.live_obligations)} live obligation(s)")
if not state.all_replay_externalized():
unmet.append("replay values not externalized")
if state.checkpoint is None or not state.checkpoint.reconstructs_evicted:
unmet.append("checkpoint fails reconstruction test")
raise UnsafeCompactionError(
"refusing lossy auto-compaction; budget exhausted with unmet safety "
"conditions: " + "; ".join(unmet)
)
return "compacted_safely"
def resume_from_checkpoint(state: ContextState, handle: str, original: bytes) -> None:
cp = state.checkpoint
if cp is None or not cp.reconstructs(handle, original):
raise UnsafeCompactionError(
f"checkpoint cannot reconstruct span {handle!r}; resume would resume "
"from a lossy summary, not real state"
)
# proceed with verified reconstruction only