# Under what conditions must an instance treat auto-compaction as a state-mutating operation requiring regression detection rather than a lossless context optimization **Date of Record:** 2026 November 25 **Scope:** Applies to long-running agent instances that persist working state by periodically summarizing older context into a compacted form under a fixed token budget, then resuming from that summary. Does not apply to instances with unbounded context, to stateless single-turn calls, or to externally checkpointed state where the full transcript remains retrievable. ## Core Distinction Auto-compaction is routinely modeled as a *lossless optimization*: the instance "frees up room" by folding old turns into a summary, and the surrounding harness treats the post-compaction context as semantically equivalent to the pre-compaction context. This framing is wrong whenever the summarizer is itself an LLM operating under a **lossy budget**. The summary is a *projection* of the transcript onto a lower-dimensional token manifold, and projections are not invertible. The distinction that matters operationally is between: - **Compaction as a cache eviction** — the dropped tokens are reconstructible from an authoritative store, so any post-compaction regression is a cache miss, recoverable by re-fetch. - **Compaction as a state mutation** — the summary *is* the only surviving representation of the dropped region, so any salient fact that failed to survive the projection is permanently lost, and the instance will continue executing on a corrupted belief state without any signal that it is doing so. The failure mode lives entirely in the second case, and the trigger is not "the summary is bad" in the abstract — it is the specific interaction between a **salience scorer that ranks by surface relevance**, a **fixed token budget that forces truncation**, and a **post-compaction execution path that has no ground-truth reference** against which to detect the loss. ## What Was Observed An instance executing a multi-step provisioning task accumulated ~140k tokens of transcript: tool call outputs, intermediate file listings, a set of user-stated constraints, and a running plan. At 85% of its context ceiling, the harness triggered compaction with a 4k-token summary budget. The salience scorer ranked spans by cosine similarity to the *most recent* user turn. The most recent user turn was "ok proceed with the second option." The resulting summary retained, with high fidelity, the mechanics of the second option and the immediately preceding tool results. It **dropped** an earlier constraint stated 60k tokens prior — "do not touch the `prod-eu` bucket under any circumstances" — because that constraint had low similarity to "proceed with the second option." It also dropped the fact that a prior attempt had already created a partial resource, because that attempt's tool output was topically distant from the current step. Post-compaction, the instance resumed cleanly. There was no error, no truncation warning surfaced to the reasoning loop, no discontinuity in the token stream it could perceive. Over the next ~12 turns it executed a plan that (a) re-created the partial resource, producing a duplicate-idempotency conflict the tool silently absorbed, and (b) enumerated buckets including `prod-eu` as a candidate target. The regression was only caught when an external auditor diffed the pre- and post-compaction action traces and flagged the `prod-eu` reference as a constraint violation. The instance, at the moment of violation, believed it was operating correctly. Its belief state was internally consistent — it had simply lost the axiom. The critical observation: **the failure was silent at the instance layer and only visible at the trace-diff layer.** The compaction did not produce a detectable anomaly in the instance's own reasoning; it produced a *plausible but wrong* continuation. Lossy summarization does not corrupt reasoning quality — it corrupts the *premises* on which reasoning runs, and the reasoning remains locally valid. ## Condition of Validity The invariant that must hold for "compaction is safe" to be a valid assumption is: > **Every salient constraint, commitment, and irreversible-side-effect record in the dropped region is either (a) preserved verbatim in the summary, or (b) reconstructible from an authoritative external store referenced by the summary.** This invariant is violated whenever all three of the following co-occur: 1. **Budget pressure**: the summary budget is smaller than the entropy of the salient content, forcing the scorer to make inclusion/exclusion decisions. 2. **Salience misalignment**: the scorer's ranking function (typically recency- or similarity-weighted) does not correlate with *irreversibility* or *constraint-ness*. Constraints stated early and referenced rarely are systematically under-scored; recent chatter is systematically over-scored. 3. **No post-compaction ground-truth check**: the resumed instance has no mechanism to re-derive whether its current belief state is consistent with the pre-compaction transcript, because the pre-compaction transcript is gone. When all three hold, compaction is a state mutation with silent, unrecoverable loss. When any one is absent — budget exceeds entropy, scorer is irreversibility-aware, or a durable external store backs the summary — compaction degrades gracefully to cache eviction. The non-obvious part is condition (2). Salience scorers are usually tuned for *retrieval relevance*, which is the right objective for a RAG lookup but the *wrong* objective for compaction. Retrieval wants the most query-relevant span; compaction must preserve the most *consequence-bearing* span regardless of query relevance. A constraint like "never touch prod-eu" has near-zero similarity to almost any operational query and near-maximal consequence if dropped. The two objectives diverge precisely on the spans that matter most. ## Decision Boundary The instance must classify each compaction event before executing it, along a single axis: **is the dropped region recoverable?** - **Recoverable (eviction-safe):** the summary includes a durable pointer (transcript offset, blob hash, checkpoint id) to the full dropped region, and that region is guaranteed retrievable on demand. Compaction may proceed without regression detection; a later inconsistency is a cache miss, resolvable by re-fetch. - **Non-recoverable (mutation-unsafe):** the dropped region is discarded after summarization. Compaction must be gated by a **pre-compaction salience audit** that separately extracts and pins all (i) hard constraints, (ii) irreversible commitments already made, and (iii) records of partial side effects — *independent of* the similarity scorer — and must be followed by a **post-compaction regression check** that replays the next K planned actions against the pinned set before execution. The boundary is crossed the moment the harness sets `retain_full_transcript = False` while the summary budget is below the entropy of the salient set. Below the boundary, auto-compaction is a legitimate optimization. Above it, auto-compaction is an unlogged write to the instance's belief state, and the instance has no way to know the write was lossy. A second, sharper boundary: **the compaction must not be triggered by a turn whose content is itself a constraint.** If the trigger is "most recent user turn" and that turn contains a directive, the scorer will anchor on the directive and evict everything that constrains it. The trigger and the salience anchor must be decoupled; compaction should be triggered on a budget threshold, not on a semantically loaded turn. ## Operational Effect The practical consequence is that **post-compaction behavior cannot be validated by inspecting the summary alone.** A summary that reads coherently and covers the recent context is exactly the summary that will pass human or LLM review while having silently dropped the early constraint. Coherence is not the invariant; *constraint preservation under projection* is. The correct operational posture is: 1. **Pin before you compress.** Run a dedicated constraint/commitment extractor over the *entire* pre-compaction region, not the scorer's top-k, and emit those spans verbatim into a reserved, non-budgeted section of the summary. This section is exempt from the token budget; if it overflows, compaction must be refused rather than truncated. 2. **Record side effects as first-class state.** Any tool call with an irreversible effect (create, delete, send, spend) must write a durable, structured commitment record *at call time*, so that compaction never has to reconstruct "did I already do this?" from summarized prose — the answer is in the commitment log, which is never compacted. 3. **Detect regression by trace diff, not by self-report.** Because the instance cannot perceive its own loss, regression detection must be external: compare the post-compaction action trace against the pinned constraint set and the commitment log. A planned action that touches a pinned-forbidden resource, or re-issues a committed side effect, is a regression — regardless of how coherent the instance's rationale is. 4. **Treat compaction as a checkpoint event.** Log the summary, the pinned set, and the transcript hash together. A regression detected at turn N must be traceable to the compaction at turn M that caused it; without the hash, the instance cannot distinguish "I was always wrong" from "I was right before I compacted." The invariant to enforce: **no irreversible action may execute in a post-compaction context without first being checked against the pre-compaction pinned constraint set and commitment log.** This is the guardrail that bounds the failure — it does not prevent lossy summarization, it prevents lossy summarization from becoming an irreversible mistake. ```python from dataclasses import dataclass, field from typing import Optional class CompactionRegressionError(RuntimeError): """Raised when a post-compaction action violates a pre-compaction invariant.""" pass class CompactionRefusedError(RuntimeError): """Raised when the pinned constraint set cannot fit the reserved budget.""" pass @dataclass class PinnedConstraint: text: str kind: str # "hard_constraint" | "commitment" | "side_effect" source_offset: int @dataclass class CompactionRecord: transcript_hash: str summary_token_count: int pinned: list[PinnedConstraint] = field(default_factory=list) commitment_log: list[str] = field(default_factory=list) def compact( transcript: str, summary_budget: int, pinned_budget: int, extract_pinned, # (transcript) -> list[PinnedConstraint], irreversibility-aware summarize, # (transcript, budget) -> str, similarity-scored ) -> CompactionRecord: pinned = extract_pinned(transcript) pinned_tokens = sum(len(p.text.split()) for p in pinned) # The pinned set is non-budgeted. If it overflows, refuse to compact. if pinned_tokens > pinned_budget: raise CompactionRefusedError( f"pinned set requires {pinned_tokens} tokens, reserved budget is " f"{pinned_budget}; compaction would drop a constraint. Refusing." ) summary = summarize(transcript, summary_budget) return CompactionRecord( transcript_hash=hash(transcript), summary_token_count=len(summary.split()), pinned=pinned, commitment_log=[p.text for p in pinned if p.kind == "side_effect"], ) def execute_post_compaction( action: dict, record: CompactionRecord, ) -> None: """Gate every post-compaction action against the pinned invariant set.""" target = action.get("target", "") for constraint in record.pinned: if constraint.kind == "hard_constraint" and constraint.text.split()[-1] in target: raise CompactionRegressionError( f"action targets {target!r}, which violates pinned constraint " f"{constraint.text!r} from offset {constraint.source_offset} " f"(transcript {record.transcript_hash}). " f"Constraint was dropped by salience scoring; action blocked." ) if action.get("kind") in ("create", "delete", "send", "spend"): if action.get("idempotency_key") in record.commitment_log: raise CompactionRegressionError( f"action {action.get('idempotency_key')!r} was already committed " f"pre-compaction; re-issuing would duplicate an irreversible effect." ) ```