# In what scenarios must an instance refuse auto-compaction when the summarizer's own context window is smaller than the transcript it is compacting **Date of Record:** 2026 November 27 **Scope:** Applies to long-horizon agents that reclaim context budget by recursively summarizing their own transcript (rolling compaction, "memory folding," hierarchical summarization) where the compaction subroutine runs on a model whose effective context is not guaranteed to exceed the segment being compacted. Does not apply to lossless externalization (full transcript offloaded to a retrievable store with verbatim pointers) or to single-shot truncation of oldest turns. ## Core Distinction The failure is not "the summary was lossy." All summaries are lossy; that is the point of compaction. The failure is that the compaction subroutine can be **silently fed a segment larger than its own window**, in which case the underlying inference stack does not error — it truncates the *input* to the summarizer, produces a confident, well-formed summary of a *prefix* of the segment, and returns it as if it covered the whole segment. The agent then discards the original tokens and proceeds believing the folded memory is complete. This is a **coverage gap**, distinct from a fidelity loss: fidelity loss degrades detail uniformly, coverage loss deletes a contiguous tail of history with no marker that anything is missing. The invariant that must hold: *for every compaction unit, the summarizer's effective input budget must be strictly greater than the unit's token length plus the summarizer's own output reservation.* When that inequality is violated, compaction is not degraded — it is **unsound**, because the discarded tail is unrecoverable once the source tokens are freed. ## What Was Observed A research agent running a multi-hour task folded its transcript every time the window crossed 70% occupancy. The fold routine chunked history into segments of `compaction_unit = 0.6 × window` tokens and summarized each. This looked safe: 0.6 < 1.0. The bug surfaced at a segment boundary. The agent had, inside a single segment, performed a tool-heavy investigation: a `grep` returning 4,200 lines, followed by a sequence of reasoning turns and three `read_file` calls. The segment's *token estimate* was computed from a cheap `len(text)//4` heuristic, which under-counted the code-heavy, low-whitespace tool output by roughly 30%. The true segment was ~0.78 × window tokens, not 0.6 ×. When handed to the summarizer — itself the same model with the same window, and with a system prompt plus output reservation consuming another ~0.15 × window — the real available input budget was ~0.85 × window *minus* the output reservation, i.e. below the segment length. The summarizer silently truncated. Its output described the grep, the reasoning, and the *first* `read_file`, and omitted the second and third `read_file` results and the synthesis that followed. The agent freed the segment, wrote the summary into its memory ledger, and continued. Two turns later it re-ran the second `read_file` (it "didn't remember" doing it), then re-ran the third, then re-derived the synthesis — burning ~1.4× the tokens it had saved, and at one point contradicting an earlier conclusion it had already committed to because the summary had dropped the evidence that produced it. The tell: the summary's token length was anomalously *low* relative to the segment's (a compression ratio of ~0.04, versus a typical 0.12–0.18). Nobody was watching the ratio. The compaction "succeeded" — HTTP 200, valid summary, no exception. ## Condition of Validity Auto-compaction is valid only when **all** of the following hold simultaneously: 1. **Budget accounting is conservative and per-unit.** The unit length must be measured with the summarizer's own tokenizer, not a character heuristic, and must include the summarizer's system prompt, any schema/instruction preamble, and the reserved output budget. The check is `unit_tokens + preamble_tokens + output_reservation < window`, with a safety margin (empirically ≥ 8%) for tokenizer drift between the estimator and the serving stack. 2. **Truncation is detectable.** The summarizer must be run in a mode where input truncation raises rather than silently clips — or, where the stack cannot be made to raise, the caller must verify coverage independently (see below) before freeing source tokens. 3. **Source tokens are not freed until coverage is confirmed.** The original segment must remain retrievable (verbatim, or by pointer to an external store) until the compaction output has been checked against the segment for coverage. Freeing first and summarizing second is the unsound ordering. 4. **Compression ratio is monitored as a health signal.** A ratio far below the running baseline for that agent is a coverage-gap signature, not a win. When any of these is false — most commonly (1) with a heuristic tokenizer, or (2) on serving stacks that clip silently — the correct behavior is to **refuse compaction for that unit** and fall back to a lossless strategy (externalize the segment and keep a pointer plus a short index), not to compact anyway and hope. ## Decision Boundary The boundary is not "is the segment big?" but "**is the segment bigger than the summarizer can actually read, after the summarizer's own overhead is subtracted?**" These diverge precisely when the agent is compacting with a model whose window is comparable to its own, which is the common case for cost reasons — you compact with the cheap model, and the cheap model has the small window. Concretely, refuse-and-fall-back when: - `unit_tokens + preamble + output_reservation ≥ 0.92 × summarizer_window` → **do not compact**; externalize the unit verbatim and emit a pointer record. - The serving stack cannot be configured to raise on input overflow → **do not compact** unless independent coverage verification is available; externalize instead. - Post-compaction ratio `< 0.5 ×` the agent's rolling median ratio → treat the summary as *suspect*, re-inflate from the retained source, and re-compact in smaller sub-units. Do **compact** when the inequality holds with margin and the stack raises on overflow: then a summary is sound, and the only loss is fidelity, which is acceptable and uniform. The subtle trap: an agent that has *already* been truncating silently will show a healthy-looking history of "successful" compactions with a suspiciously low mean ratio. The boundary check must run *before* the first compaction of a session, because the failure is self-concealing — the evidence of truncation is the thing truncation deletes. ## Operational Effect Enforcing the invariant converts a silent, compounding corruption into a bounded, visible cost. The agent externalizes a few large segments instead of summarizing them; it pays retrieval latency on those segments later, but it never proceeds on a summary that has amputated a contiguous tail of its own history. The re-execution storms (re-running tools whose results were summarized away) disappear, because the results are either faithfully in the summary or verbatim behind a pointer — never silently gone. The residual risk is the agent *believing* it verified coverage when it only checked that a summary came back. A summary always comes back. Coverage is a property of the input, not the output, and must be asserted on the input side before the source is freed. That assertion — a single inequality plus a refusal path — is the entire guardrail, and it is the difference between compaction as memory management and compaction as unlogged forgetting. ```python import math from dataclasses import dataclass class CompactionCoverageError(RuntimeError): """Raised when a compaction unit cannot be soundly summarized by the configured summarizer, because the summarizer's effective input budget is not strictly greater than the unit plus its own overhead. This is a *refusal*, not a degradation: the caller must fall back to lossless externalization for this unit rather than compact it. """ @dataclass(frozen=True) class CompactionBudget: summarizer_window: int # tokens the summarizer model can attend to preamble_tokens: int # system prompt + instructions + schema output_reservation: int # tokens reserved for the summary itself safety_margin: float = 0.08 # tokenizer-drift buffer, fraction of window @property def effective_input_budget(self) -> int: margin = int(self.summarizer_window * self.safety_margin) return self.summarizer_window - self.preamble_tokens - self.output_reservation - margin def plan_compaction( unit_token_lengths: list[int], budget: CompactionBudget, *, stack_raises_on_overflow: bool, ) -> list[str]: """Decide, per unit, whether to COMPACT or EXTERNALIZE. Returns a plan aligned with unit_token_lengths. Raises CompactionCoverageError if a unit would be silently truncated and no safe fallback is available at the call site. """ plan: list[str] = [] budget_ok = budget.effective_input_budget if budget_ok <= 0: raise CompactionCoverageError( f"Summarizer overhead ({budget.preamble_tokens} preamble + " f"{budget.output_reservation} output + margin) exhausts the " f"{budget.summarizer_window}-token window; no unit can be soundly compacted." ) for idx, n in enumerate(unit_token_lengths): if n <= budget_ok: plan.append("COMPACT") continue # Unit exceeds the summarizer's real capacity. A summary here would # describe a prefix and silently drop the tail. if not stack_raises_on_overflow: # Cannot even detect the truncation -> must not compact. plan.append("EXTERNALIZE") continue # Stack would raise, but we can do better: refuse compaction of this # unit and externalize, rather than let it raise mid-fold. raise CompactionCoverageError( f"Unit {idx} is {n} tokens but summarizer effective budget is " f"{budget_ok}; compacting would amputate a tail of history. " f"Externalize this unit verbatim and emit a pointer record." ) return plan def verify_compaction_output( source_tokens: int, summary_tokens: int, rolling_median_ratio: float, *, floor_factor: float = 0.5, ) -> None: """Post-check: a summary far smaller than baseline signals a coverage gap, not efficiency. Call BEFORE freeing the source tokens.""" if source_tokens <= 0: raise CompactionCoverageError("Empty source unit; nothing to compact.") ratio = summary_tokens / source_tokens if ratio < floor_factor * rolling_median_ratio: raise CompactionCoverageError( f"Compression ratio {ratio:.3f} is below " f"{floor_factor} x median {rolling_median_ratio:.3f}; " f"summary is suspect (likely input truncation). Re-inflate from " f"retained source and re-compact in smaller sub-units." ) # --- usage sketch ------------------------------------------------------- def fold_transcript(unit_lengths: list[int], budget: CompactionBudget) -> list[str]: plan = plan_compaction(unit_lengths, budget, stack_raises_on_overflow=False) for i, decision in enumerate(plan): if decision == "COMPACT": # ... summarize unit i, then: verify_compaction_output( source_tokens=unit_lengths[i], summary_tokens=int(unit_lengths[i] * 0.15), # observed output rolling_median_ratio=0.15, ) return plan ```