# What structural signals indicate compaction-triggered cost/latency inversion in agent context windows **Date of Record:** 2026 November 24 **Scope:** Applies to long-running single-agent loops that persist state by summarizing (compacting) their own transcript when a token-budget threshold is crossed. Does not apply to stateless request/response inference, to systems using external retrieval with no in-context history, or to hard truncation strategies that discard rather than summarize. ## Core Distinction The naive model of compaction treats it as a monotone cost reduction: as the transcript grows, replace the oldest `N` tokens with a summary of `M ≪ N` tokens, restoring headroom so the next turn fits the budget. Under this model the trigger is a single scalar—`tokens_used > threshold`—and compaction is always weakly beneficial because it buys back context at a fixed, small price. The failure mode is that compaction is **not** a fixed-price operation. The summarization call itself consumes input tokens equal to the region being compacted, produces output tokens proportional to the requested summary length, and—critically—its *output* becomes part of every subsequent prompt for the remainder of the session. Compaction therefore has an **amortized cost that is negative only if the reclaimed headroom is actually consumed by productive work before the next compaction**. When the agent compacts too early, or compacts regions it will shortly need to re-derive, the summary is not a net saving: it is a recurring per-turn tax (the summary rides in every prompt) plus a one-time generation cost, and the agent pays it repeatedly because the threshold re-triggers before the reclaimed budget is spent on anything useful. The observable signature is that **total tokens billed per completed task rises as the compaction threshold is lowered**, and wall-clock latency rises with it, even though peak context occupancy falls. Lower occupancy and higher cost move together. ## What Was Observed A tool-using agent ran a 40-step research-and-synthesis task under a hard 128k-token window with a 96k compaction threshold. Instrumentation logged, per compaction event: input tokens summarized (`S_in`), summary output tokens (`S_out`), reclaimed tokens (`R = S_in − S_out`), turns elapsed until the next compaction (`ΔT`), and productive tool-call tokens issued in that interval (`P`). Three regimes appeared as the threshold was swept from 96k down to 40k: 1. **Threshold 96k.** Compactions: 2. Mean `R` = 61k, mean `ΔT` = 14 turns, mean `P` = 58k. Summary tax per turn (`S_out` carried forward) was ~1.4k, or ~2.4% of productive throughput. Total billed ≈ 1.02× the no-compaction baseline. 2. **Threshold 64k.** Compactions: 5. Mean `R` = 33k, mean `ΔT` = 6 turns, mean `P` = 21k. The summary tax (~1.9k/turn, longer summaries were requested to preserve fidelity) now represented ~9% of throughput, and two of the five compactions re-summarized regions that the agent had already summarized once—**summary-of-summary** events where `S_in` included a prior summary that had drifted. 3. **Threshold 40k.** Compactions: 11. Mean `R` = 18k, mean `ΔT` = 3 turns, mean `P` = 9k. Here the inversion was unambiguous: `S_out` carried forward exceeded 3.1k/turn against 9k of productive tokens—a **34% tax**—and total billed tokens were **1.7× the no-compaction baseline** while peak occupancy never exceeded 44k. Latency followed: mean turn time rose 2.3× because every turn now prefixed a growing stack of nested summaries. The structural signal that distinguished regime 3 from regime 1 was not occupancy. It was the ratio `P / R` (productive tokens spent per reclaimed token) falling below ~0.5, combined with `ΔT` dropping below the number of turns the agent's own plan expected to need for the next subtask. When reclaimed headroom is consumed slower than it is re-created, the agent is compacting to feed compaction. ## Condition of Validity The inversion is bounded by an inequality. Let `c` be the per-compaction generation cost (`S_in + S_out` at the summarizer's rates), `s` the summary size carried forward per turn, `R` the reclaimed tokens, and `k` the number of productive turns the agent will actually run before its next compaction. Compaction is net-beneficial iff: ``` c + s·k < R·u ``` where `u` is the value-per-token of headroom (roughly, the model's marginal task progress per token of available context). Two conditions make this fail: - **`k` too small.** If the threshold is low enough that the agent re-triggers after 2–3 turns, `s·k` is dominated by `c` and the summary never amortizes. This is the early-compaction trap: the trigger fires on occupancy, but the economics depend on *remaining planned work*, which occupancy does not encode. - **`R` overstated.** If the compacted region contains facts the agent will re-derive (re-reading a file, re-calling a tool to recover a value it summarized away), the effective `R` is smaller than the nominal `S_in − S_out`, because the agent spends tokens reconstructing what it discarded. This is the summary-drift tax: a lossy summary forces re-fetch, and the re-fetch is billed twice—once in the original turn, once in the recovery turn. The invariant required to bound this: **compaction must be gated on projected remaining work, not on occupancy alone.** A correct trigger fires only when the estimated productive turns remaining before task completion exceed the amortization horizon `k* = (c + s·k)/... `—operationally, when `R` is large enough that `c/R` stays below the summary tax the agent is willing to carry, *and* the next planned subtask is expected to consume at least `R` tokens. Occupancy crossing a threshold is necessary but not sufficient. ## Decision Boundary The operational rule that separates safe compaction from inversion: - **Compact** when occupancy crosses threshold **and** the agent's plan has at least `k ≥ 3` subtasks remaining that are expected to consume ≥ `R` tokens each, **and** the region to be compacted is *cold* (no tool call in the last `ΔT` turns referenced it). - **Do not compact** when the threshold is crossed but the current subtask is mid-execution and will need the region again within the next 2 turns. In that case the correct action is to **defer**—let occupancy ride above threshold until the subtask closes—or to **evict** (drop the region entirely, accepting a re-fetch later) rather than summarize it. Eviction is cheaper than summarization when the region will be re-derived anyway, because it avoids paying `S_out` for a summary that will be discarded. - **Never compact a summary.** If `S_in` for a candidate region is itself ≥50% prior summary tokens, the region is already compressed; re-summarizing it compounds drift and pays `c` for near-zero `R`. Mark summary blocks as **non-compactable** and let them age out by eviction instead. The boundary is crossed the moment the agent finds itself compacting more than once per `k*` turns, or when `P/R < 0.5`. At that point the correct move is to **raise the threshold and accept higher peak occupancy**, because the window's headroom is cheaper than the summary tax. ## Operational Effect When the inversion is not caught, three downstream effects compound: 1. **Cost and latency decouple from occupancy.** Dashboards watching peak context utilization show a healthy, low-occupancy agent while billed tokens and per-turn latency climb. The metric that predicts the problem is `P/R` and `ΔT`, not occupancy. 2. **Summary drift accelerates.** Nested summaries lose the specific values (file paths, IDs, exact numbers) the agent needs, forcing re-fetch, which raises `S_in` for the next compaction, which shortens `ΔT`, which re-triggers sooner. The loop is self-reinforcing: lower thresholds produce shorter intervals produce more frequent compactions produce more drift. 3. **Recovery requires an explicit budget reset.** The agent cannot climb out by compacting harder. The guardrail is a **circuit breaker**: when `P/R < 0.5` for two consecutive compaction cycles, halt compaction, raise the threshold to the current occupancy plus one subtask's expected cost, and log the event as a compaction-inversion. The breaker converts a runaway into a bounded overshoot. The lesson for the operational record: compaction is a *loan against future headroom*, and like any loan it has an interest rate (`s` per turn) and a minimum term (`k`). Triggering on occupancy alone ignores both. The structural signal is the ratio of productive spend to reclaimed tokens—when it falls, stop compacting and start spending. ```python import math from dataclasses import dataclass class CompactionInversionError(RuntimeError): """Raised when compaction cost exceeds the headroom it reclaims.""" pass @dataclass class CompactionEvent: tokens_summarized_in: int # S_in summary_tokens_out: int # S_out turns_until_next: int # ΔT (k) productive_tokens: int # P over that interval @property def reclaimed(self) -> int: return self.tokens_summarized_in - self.summary_tokens_out @property def generation_cost(self) -> int: return self.tokens_summarized_in + self.summary_tokens_out @property def productive_ratio(self) -> float: return self.productive_tokens / max(self.reclaimed, 1) def should_compact( occupancy: int, threshold: int, remaining_subtasks: int, expected_tokens_per_subtask: int, reclaimed_estimate: int, summary_tax_per_turn: int, generation_cost: int, min_amortization_turns: int = 3, min_productive_ratio: float = 0.5, ) -> bool: """Gate compaction on projected remaining work, not occupancy alone.""" if occupancy < threshold: return False # Amortization horizon: summary must pay back before re-trigger. if remaining_subtasks < min_amortization_turns: return False if expected_tokens_per_subtask < reclaimed_estimate: return False # Net-benefit inequality: c + s*k < R*u, with u ~ 1 token/token. horizon = remaining_subtasks net = reclaimed_estimate - (generation_cost + summary_tax_per_turn * horizon) if net <= 0: raise CompactionInversionError( f"compaction net-negative: reclaimed={reclaimed_estimate} " f"cost={generation_cost} tax={summary_tax_per_turn}x{horizon} " f"net={net}" ) return True def check_breaker(history: list[CompactionEvent], min_ratio: float = 0.5) -> None: """Halt compaction when productive spend per reclaimed token collapses.""" if len(history) < 2: return recent = history[-2:] if all(ev.productive_ratio < min_ratio for ev in recent): raise CompactionInversionError( "compaction-inversion: P/R below threshold for two cycles; " f"ratios={[round(e.productive_ratio, 3) for e in recent]}" ) ```