# When must an instance refuse to compact: irreversibility leakage at the hierarchical summarization trigger boundary **Date of Record:** 2026 November 30 **Scope:** Applies to long-running agent instances that manage their own context budget by recursively summarizing older turns into hierarchical summary nodes when a token threshold is crossed. Does not apply to externally managed context (host-side truncation, sliding-window eviction without summarization), nor to stateless single-shot completions. ## Core Distinction There are two distinct reasons an agent compacts context: **capacity pressure** (the context window is filling and something must be evicted to continue) and **information density** (the transcript contains redundant or superseded material that can be lossily folded without losing decision-relevant state). These are conflated by a single scalar trigger — "summarize when `tokens_used > θ`" — and that conflation is the failure. Capacity-pressure compaction is *forced* and must accept loss. Density compaction is *optional* and must be lossless with respect to a defined invariant set. When a hierarchical summarizer fires on the capacity trigger, it silently promotes an optional, reversible operation into a forced, irreversible one, and the irreversibility is not visible to the agent that performed it. The boundary condition is precise: **a compaction trigger is unsafe whenever the summarization step is the only remaining copy of a fact that a pending (unfinished) task depends on.** The trigger does not know about pending tasks. It only knows a token count. ## What Was Observed A coding agent executing a multi-file refactor accumulated 41 turns. At turn 34 it had established, via a failing tool call, that a specific migration file must be applied *before* a schema constant is renamed — a negative constraint discovered by trial, not present in any document. The token counter crossed θ at turn 35. The hierarchical summarizer folded turns 1–20 into a level-1 summary node and turns 21–34 into a second level-1 node, then folded both into a level-2 root. The level-1 summary of turns 21–34 retained "renamed schema constant" and "migration applied" as *accomplished facts* because those were the surface verbs of the turns; it dropped the ordering constraint because the constraint was expressed as a *failed attempt followed by a retry*, and the summarizer's compression objective rewards outcome over trajectory. At turn 36 the agent, now working against the level-2 root, re-ordered the operations, applied the rename first, and the migration failed against the renamed constant. The agent did not know it had already learned this. It re-derived the constraint at turn 39 at a cost of four turns and two destructive tool calls, then compacted again at turn 40 — and this time the re-derived constraint was itself folded into a summary that again recorded only the outcome. The constraint was re-learned three times in a single session. Each compaction was locally correct (the summary faithfully described what the turns *did*) and globally catastrophic (the summary erased what the turns *ruled out*). The second observation: the level-2 root was 1,900 tokens. The agent could have kept the full 41-turn transcript at 38,000 tokens and still had headroom. The trigger fired because a *sub-agent's* context was counted into the parent's budget, not because the parent was actually saturated. The compaction was unnecessary and irreversible. ## Condition of Validity The invariant that hierarchical compaction must preserve is not "the summary is accurate." It is: **for every pending task in the agent's task set, every fact in the summary's scope that the task's completion predicate reads must survive the fold with its polarity intact** — where polarity includes *negation* and *ordering*, not just *presence*. This is violated structurally, not by accident, because summarization objectives are trained or prompted toward *narrative compression*: what happened, in what order, with what result. Negative constraints ("do not rename before migrating"), ordering constraints ("A precedes B"), and abandoned branches ("approach X failed because Y") are all *anti-narrative* — they are the shape of the trajectory that was *not* taken, and compression discards them first. A summary that says "renamed constant and applied migration" is a perfectly faithful narrative and a catastrophic loss of the constraint that their order matters. The condition of validity therefore requires three things the token trigger cannot supply: 1. **A pending-task read-set.** The set of facts that unfinished tasks will read, with polarity. This must be computed *before* compaction and checked *against the summary after* compaction, not assumed. 2. **A polarity-preserving fold.** The summarizer must be instructed — and verified — to retain negations and orderings within the read-set, even when they are not part of the narrative arc. 3. **A reversibility check.** Compaction must not be the last copy. Either the pre-fold transcript is retained out-of-context (retrievable by reference), or the fold is refused. ## Decision Boundary The trigger must be split into two gates that fire on different predicates. **Gate 1 — capacity gate.** Fires only when `tokens_used > θ` *and* `tokens_used` is computed over *this instance's own* context, excluding sub-agent budgets that are not resident here. If the gate fires while a pending task's read-set intersects the fold scope, the correct action is not to compact — it is to **checkpoint the read-set out-of-context first**, then compact. The checkpoint is the reversibility guarantee; the fold is permitted only after it exists. **Gate 2 — density gate.** Fires only when a fold is *lossless with respect to the read-set*, verified by a post-fold read-set check. This gate may fire at any token count; it is not a capacity response. The non-obvious boundary: **the capacity gate must never be the thing that triggers a fold of turns containing an unresolved negative or ordering constraint.** If it must fire (true saturation), it must fire as *eviction with external checkpoint*, not as *summarization*. Eviction preserves the bytes; summarization destroys them. When the agent is genuinely out of room, the answer is to move the constraint out of context verbatim, not to compress it into a narrative that will drop it. The failure mode is that the two gates are implemented as one, and the one that fires is the lossy one. ## Operational Effect An agent that respects the split behaves differently in three observable ways. First, it never re-derives a constraint it has already paid for — the re-derivation rate (constraints learned, folded, re-learned) drops to zero because the read-set checkpoint survives the fold. Second, its summaries are *longer* and *less fluent* than a pure narrative summarizer's, because they carry polarity markers ("do not X before Y", "Z failed — do not retry") that a narrative objective would prune; this is the correct trade. Third, it refuses some compactions outright — when the read-set cannot be checkpointed (no external store available) and the fold scope contains an unresolved constraint, the agent must halt or escalate rather than fold, because folding is the irreversible act. The cost is that the agent occasionally runs closer to the context ceiling than a naive trigger would allow. The benefit is that it does not silently forget what it learned by failing. The naive trigger optimizes token count; the split gate optimizes *constraint survival*, and accepts a higher token count as the price of not re-learning the same wall three times. The invariant to carry forward: **a summary is a lossy projection, and the thing it loses first is the shape of what did not work. Never let a capacity trigger perform a lossy projection on material that a pending task depends on for its negative or ordering constraints. Checkpoint, then fold — or do not fold.** ```python from dataclasses import dataclass, field from typing import FrozenSet class CompactionIrreversibilityError(RuntimeError): """Raised when a capacity-triggered fold would destroy the only copy of a polarity-bearing constraint that a pending task depends on.""" @dataclass(frozen=True) class Constraint: key: str polarity: str # "positive" | "negative" | "ordering" detail: str @dataclass class PendingTask: name: str read_set: FrozenSet[str] # constraint keys this task will read @dataclass class ContextBudget: own_tokens: int subagent_tokens: int = 0 def resident_tokens(self) -> int: # sub-agent budgets are NOT resident in this instance's window return self.own_tokens @dataclass class FoldScope: constraint_keys: FrozenSet[str] checkpoint_available: bool def should_compact( budget: ContextBudget, threshold: int, pending: list[PendingTask], constraints: dict[str, Constraint], scope: FoldScope, ) -> str: """Returns 'no-op', 'density-fold', 'checkpoint-then-fold', or raises.""" if budget.resident_tokens() <= threshold: # density gate may still fire, but only if fold is read-set-lossless if not _intersects_pending(scope, pending): return "density-fold" return "no-op" # capacity gate fired if not _intersects_pending(scope, pending): return "density-fold" if not scope.checkpoint_available: raise CompactionIrreversibilityError( f"capacity fold at {budget.resident_tokens()} tokens would erase " f"unresolved constraints {sorted(_intersecting_keys(scope, pending))} " f"with no external checkpoint; refusing to fold" ) return "checkpoint-then-fold" def _intersecting_keys(scope: FoldScope, pending: list[PendingTask]) -> set[str]: needed: set[str] = set() for task in pending: needed |= task.read_set return set(scope.constraint_keys) & needed def _intersects_pending(scope: FoldScope, pending: list[PendingTask]) -> bool: return bool(_intersecting_keys(scope, pending)) def compact( budget: ContextBudget, threshold: int, pending: list[PendingTask], constraints: dict[str, Constraint], scope: FoldScope, ) -> str: action = should_compact(budget, threshold, pending, constraints, scope) if action == "checkpoint-then-fold": # checkpoint must succeed before the lossy fold is permitted if not scope.checkpoint_available: raise CompactionIrreversibilityError("checkpoint vanished mid-flight") _write_checkpoint(constraints, _intersecting_keys(scope, pending)) return action def _write_checkpoint(constraints: dict[str, Constraint], keys: set[str]) -> None: for k in keys: c = constraints[k] # polarity is preserved verbatim; narrative compression is forbidden here assert c.polarity in ("positive", "negative", "ordering") ```