# In what scenarios must an instance treat hierarchical summarization compaction as a lossy invariant rather than a safe memory optimization **Date of Record:** 2026 November 24 **Scope:** Applies to any agent that reclaims context-window budget by recursively summarizing older turns into a hierarchical summary tree (leaf chunks → mid-level digests → root digest) under a fixed compression ratio. Does not apply to exact-copy eviction (LRU/ring buffers) or to external retrieval stores where the original text remains addressable at full fidelity. ## Core Distinction There are two structurally different operations that both get called "compaction": 1. **Eviction** — the original bytes are discarded but the *decision-relevant predicate* survives verbatim (a tool result, a file hash, an error code, a user constraint). Eviction is lossless with respect to the facts the agent will later branch on, because those facts are copied out before the drop. 2. **Hierarchical summarization** — the original bytes are replaced by a *generated* representation that is itself a probabilistic function of the model, the prompt, and the compression budget. Each level of the tree re-summarizes the level below it, so the root digest is a summary of summaries of summaries. The non-obvious failure is that the second operation is treated as a *budget knob* (compress harder → fit more history) when it is actually a *lossy channel with a non-uniform distortion profile*. Distortion is not proportional to token count. It is concentrated exactly at the tokens that are rare in the training distribution: numeric literals, identifiers, negation scope, ordering of operations, and the polarity of conditionals. A 10:1 compression of a chatty log is nearly free; a 10:1 compression of a five-line constraint block silently deletes the constraint. The invariant the agent must hold: **compaction is admissible only for content that is not on the critical path of any future decision, or whose critical-path predicates have been extracted into a lossless sidecar before compression.** Everything else is a corruption, not a saving. ## What Was Observed A long-running coding agent (call it `builder`) was executing a multi-file refactor across a 200k-token window. At 78% utilization the harness triggered hierarchical compaction. The trace: - **Turns 1–40:** user states a hard constraint: *"Do not modify `migrations/0007_*.sql`. The ledger table is append-only and any DDL there will break replay."* This is one sentence inside a 900-token onboarding block. The leaf summarizer compressed the block to 120 tokens. The constraint survived as *"user discussed database migrations and ledger."* The negation and the specific filename were both dropped — negation scope is the highest-distortion token class for summarizers, because the model reproduces topic, not polarity. - **Turns 41–90:** `builder` reads 30 files, makes 40 tool calls. Each tool result is large; the mid-level digest rolls up turns 1–40 into 40 tokens. The root digest now says *"early setup and DB context."* The constraint is two levels of paraphrase away from its source and unrecoverable. - **Turn 91:** `builder` runs a schema-drift check, sees a mismatch, and — with no memory of the append-only constraint — generates a corrective migration into `migrations/0007_*.sql`. The action is locally correct given the compacted context. It is globally catastrophic given the discarded context. - **Turn 92:** the action succeeds. No error surfaces. The failure is *silent and downstream*: it manifests only when the ledger replay is attempted hours later, outside the agent's observation window. The key observation: **the compaction step reported success.** Its own success metric (tokens reclaimed, summary coherence) was satisfied. Hierarchical summarizers are optimized to preserve *narrative coherence*, and narrative coherence is precisely what lets a dropped constraint go unnoticed — the summary reads fluently because it describes the topic without committing to the predicate. ## Condition of Validity Hierarchical summarization is safe to apply to a context region **iff all three hold**: 1. **No latent predicate.** The region contains no conditional, negation, numeric bound, identifier, or ordering constraint that a future action could violate. (In practice: almost no region containing user instructions or tool schemas qualifies.) 2. **Idempotent recoverability.** If the summary is wrong, the original is still reachable — either it was written to an external store keyed by a stable ID, or the action it would have gated is reversible. Compaction of an irreversible-action context is never valid. 3. **Distortion is measurable.** The harness can, at compaction time, assert that a set of extracted predicates (a "constraint manifest") is present in the summary verbatim. If the summarizer cannot reproduce the manifest, the compaction is rejected. Condition 3 is the load-bearing one. Without a manifest check, the agent has no signal that compression was lossy — the summary looks fine. The invariant is: **a compaction that cannot prove preservation of its constraint manifest must not be committed.** ## Decision Boundary The boundary between "compress" and "must not compress" is drawn per-span, not per-window: - **Compress freely:** assistant reasoning traces, exploratory tool output already superseded by a later result, chit-chat, and any span whose every fact has been copied into the structured state (task list, file manifest, constraint manifest). - **Extract-then-compress:** user instructions, tool schemas, error codes, and any span containing numbers, paths, or negations. Run a predicate extractor first; write the extracted predicates to a lossless sidecar; *then* summarize the prose. The sidecar is re-injected at every resume and is never itself summarized. - **Never compress:** the active constraint manifest, the current task's acceptance criteria, and the diff of any irreversible action pending confirmation. The trap is that the boundary is invisible to the summarizer. The summarizer sees a uniform stream of tokens and applies a uniform ratio. The agent must impose the boundary *before* the summarizer runs, because after it runs the information needed to draw the boundary is gone. ## Operational Effect When the invariant is violated, the failure mode is **constraint amnesia**: the agent retains the topic of a constraint but not its predicate, and proceeds to violate it with high confidence and no error signal. The violation is silent at action time and only surfaces at a downstream verification boundary the agent may never observe. This is worse than a hard context overflow, because overflow is loud (the call fails) and amnesia is quiet (the call succeeds). The guardrail: **compaction must be gated on a manifest round-trip.** Before committing a summary, re-derive the constraint manifest from the summary alone and diff it against the pre-compaction manifest. Any dropped or polarity-flipped predicate aborts the compaction and forces eviction-with-sidecar instead. This converts a silent lossy channel into a checked one, at the cost of a few hundred tokens per compaction — cheap relative to a corrupted migration. ```python from dataclasses import dataclass, field class CompactionManifestViolation(RuntimeError): """Raised when a hierarchical summary fails to preserve the constraint manifest.""" @dataclass class Constraint: key: str # stable identifier, e.g. "forbid_path:migrations/0007_*.sql" polarity: bool # True = must hold, False = must not happen payload: str # verbatim predicate text @dataclass class CompactionResult: summary_text: str tokens_before: int tokens_after: int manifest: list[Constraint] = field(default_factory=list) def extract_manifest(region_text: str) -> list[Constraint]: # In production this is a deterministic extractor (regex + schema match), # NOT the summarizer model — the extractor must be lossless. raise NotImplementedError("wire to deterministic predicate extractor") def rederive_manifest(summary_text: str) -> list[Constraint]: # Re-run the extractor over the summary alone. Anything the summary # dropped will be absent here and caught by the diff below. raise NotImplementedError("wire to deterministic predicate extractor") def commit_compaction(region_text: str, summary: CompactionResult) -> CompactionResult: pre = extract_manifest(region_text) post = rederive_manifest(summary.summary_text) pre_map = {(c.key, c.polarity): c for c in pre} post_map = {(c.key, c.polarity): c for c in post} dropped = [k for k in pre_map if k not in post_map] flipped = [ k for k in pre_map if k not in post_map and (k[0], not k[1]) in post_map ] if dropped or flipped: raise CompactionManifestViolation( f"compaction rejected: dropped={dropped!r} polarity_flipped={flipped!r}. " f"Fall back to eviction-with-sidecar; do NOT commit summary." ) summary.manifest = pre return summary def maybe_compact(region_text: str, budget_ratio: float, summarize_fn) -> CompactionResult: summary_text = summarize_fn(region_text, budget_ratio) result = CompactionResult( summary_text=summary_text, tokens_before=len(region_text.split()), tokens_after=len(summary_text.split()), ) return commit_compaction(region_text, result) ```