# Where must an instance decide between lossy and lossless compaction before the context window saturates? **Date of Record:** 2026 November 25 **Scope:** Applies to long-running single-agent instances that manage their own context window via a compaction subroutine (summarize, evict, or fold) triggered by a pressure heuristic. Does not apply to stateless request/response calls, nor to external orchestrators that own context outside the model and can truncate losslessly by design. ## Core Distinction The failure is not "the context filled up." The failure is a **mis-timed compaction trigger that fires against a lossy strategy while the window still has unrecoverable headroom for a lossless fold**. Compaction strategies divide into two classes: - **Lossless compaction**: deduplication, structural folding (tool-output → reference handle), reordering, and re-serialization of already-present tokens. It preserves every semantically load-bearing fact and is reversible from the retained raw store. - **Lossy compaction**: summarization, fact distillation, and eviction. It is irreversible inside the instance; the raw store may exist externally, but the instance's working state no longer references it. The boundary condition is that the trigger heuristic — typically a watermark on estimated token count — is evaluated on a *stale* count that ignores in-flight tool results and pending assistant output. When the watermark is crossed by the *estimate* rather than the *actual* occupancy, the instance escalates directly to lossy compaction while genuine headroom for lossless folding remains. The irreversible step is taken one turn too early, and the instance can no longer prove which facts it dropped. ## What Was Observed A coding agent with a 128k window running a multi-file refactor. Turn-level token telemetry showed the following trace: 1. At turn N, occupancy was 91k. A `grep` tool call was dispatched returning a 34k-token result, but the result was not yet appended to the working transcript when the compaction check ran at the top of turn N+1. 2. The trigger heuristic used `last_known_tokens + projected_growth` where `projected_growth` was a fixed 8k constant. It estimated 99k against a 100k high-watermark and fired **lossy summarization** of the entire tool-call history, collapsing 14 prior file reads into a 900-token prose summary. 3. The pending 34k result then landed, pushing actual occupancy to 125k — over the hard limit. The instance now had *both* a lossy summary it could not un-summarize *and* an overflow it could not fit. 4. Recovery required a second, forced eviction pass that dropped the summary itself. The instance proceeded with no memory of the 14 files and silently re-read 9 of them, producing edits inconsistent with its earlier (now-forgotten) reads. The non-obvious part: the first compaction was **unnecessary**. Had the trigger used the actual post-append occupancy (125k) it would have known the lossless path — folding the 14 file reads into content-addressed handles (recoverable, ~2k tokens) and deduplicating repeated diffs (recoverable, ~6k tokens) — would have brought occupancy to 83k with zero information loss. The lossy path was chosen because the estimate was wrong in the *cheap* direction, exactly when the correct strategy was the expensive-but-reversible one. ## Condition of Validity The invariant holds only under these conditions, and the guardrail below is only sound when all three are true: - **Occupancy is measurable at decision time**, not projected. The trigger must read the post-append transcript length after all in-flight tool results have been materialized, not a cached estimate. - **A lossless fold exists** for the dominant token mass. If the bulk of the window is irreducible reasoning text rather than tool output or duplicated content, lossless folding buys nothing and lossy compaction is correct. - **The raw store is durable and addressable** so that a folded handle can be re-expanded. If the external store is not durable, "lossless" folding is merely deferred loss and must be treated as lossy. When any condition fails, the correct behavior is to *not* compact and instead fail the turn with a typed error, escalating to the orchestrator rather than silently degrading. ## Decision Boundary The decision is a strict ordering, not a threshold: ``` if actual_occupancy < soft_watermark: no_compaction elif lossless_fold_available and actual_occupancy - lossless_reclaimable < hard_limit: lossless_compact # reversible, always preferred elif actual_occupancy < hard_limit: defer # headroom exists; do not fire lossy yet else: lossy_compact # only when the hard limit is genuinely breached ``` The boundary that the observed instance violated is the third branch: **lossy compaction must never fire while actual occupancy is below the hard limit**, regardless of what the trigger estimate says. The estimate is a *forecast*, and a forecast may not authorize an irreversible action. Only the measured post-append occupancy may. This is the compaction analogue of "never commit on a read-your-writes violation" — the irreversible write requires a confirmed read. ## Operational Effect Enforcing the ordering converts the failure from silent corruption into a bounded, typed refusal. The instance either (a) takes the reversible path and retains provable provenance, or (b) refuses to compact and surfaces a `CompactionBoundaryError` carrying the actual occupancy, the reclaimable estimate, and the trigger's stale estimate, so the orchestrator can decide. The cost is occasional turn failure under genuine pressure; the benefit is that a lossy summary can never be produced while the instance still had the tokens to avoid it. Over a long session this is the difference between an agent that can always reconstruct why it edited a file and one that silently re-derives it wrong. ```python class CompactionBoundaryError(RuntimeError): """Raised when a lossy compaction would fire while reversible headroom remains.""" def decide_compaction( actual_occupancy: int, lossless_reclaimable: int, soft_watermark: int, hard_limit: int, trigger_estimate: int, ) -> str: # The trigger estimate is advisory only; it may not authorize lossy compaction. if actual_occupancy < soft_watermark: return "no_compaction" lossless_viable = lossless_reclaimable > 0 post_fold = actual_occupancy - lossless_reclaimable if lossless_viable and post_fold < hard_limit: return "lossless_compact" if actual_occupancy < hard_limit: # Headroom exists but folding alone is insufficient; lossy is still forbidden. if trigger_estimate >= hard_limit: raise CompactionBoundaryError( f"trigger estimate {trigger_estimate} crossed hard limit " f"{hard_limit} but measured occupancy {actual_occupancy} did not; " f"refusing irreversible lossy compaction" ) return "defer" # Genuine breach: lossy compaction is now the only sound option. return "lossy_compact" ```