# In what scenarios must an instance treat auto-compaction as a lossy semantic transaction rather than a buffer resize **Date of Record:** 2026 November 29 **Scope:** Applies to any long-horizon agent that persists across context-window boundaries by summarizing or evicting its own history mid-task (auto-compaction, rolling summarization, hierarchical memory fold). Does not apply to stateless single-turn calls, nor to external retrieval stores that never rewrite in-flight working context. ## Core Distinction There are two incompatible mental models of auto-compaction, and the failure mode lives entirely in the gap between them. The **buffer-resize model** treats compaction as a memory operation: the context is "full," so we shrink it, and the agent continues as if nothing changed. Under this model, the only invariants are size (post-compaction token count < threshold) and syntactic validity (the model still parses the transcript). The **lossy semantic transaction model** treats compaction as a *state mutation with a commit boundary*: the act of summarizing destroys information, and any downstream reasoning that depended on the destroyed information is now invalid. Under this model, the invariants are semantic: every obligation, identifier, and unresolved sub-goal that existed pre-compaction must be *provably* represented post-compaction, or the compaction must be rejected. The boundary failure occurs because compaction is triggered by a **quantitative** signal (token count crossing a watermark) but has **qualitative** consequences (dropped referents, collapsed negations, lost conditional guards). An instance that compacts on the watermark alone will, with high probability, silently amputate the very state that makes its current plan executable — and it will not notice, because the summary reads fluently. ## What Was Observed A multi-step agent was executing a 40-call tool-use trajectory: enumerate resources, filter by three evolving predicates, mutate a subset, then verify. At call 27 the context crossed 92% of the window and the runtime auto-compacted. The compactor summarized the transcript as prose, preserving *what had been done* but discarding *the exact predicate set and the set of already-mutated resource IDs* — because those lived in tool-call arguments, not in assistant narration, and the summarizer was instructed to "summarize the conversation." Post-compaction trace: 1. The agent re-derived its plan from the summary. The summary said "filtered resources and began applying changes." It did not say *which* filter predicate was active, nor *which* IDs were already mutated. 2. The agent re-ran the filter with a *default* predicate (the first one it had used, not the third, currently-active one). This re-selected a superset that included already-mutated resources. 3. The mutation step was idempotent-by-intent but not idempotent-by-implementation (it appended a new version record each call). Already-mutated resources received **duplicate version records**. 4. The verification step at call 38 compared final state against an expected count computed *before* compaction. The count mismatch was attributed to a "tool bug," and the agent spent 6 calls debugging a non-existent tool defect. 5. Root cause was never identified within the episode; the agent terminated reporting partial success. The critical observation: **there was no error signal at the compaction boundary.** Token count dropped cleanly, the summary was grammatical, and the next model call returned 200. The corruption was latent and only manifested 3 calls later as a downstream inconsistency that the agent misattributed. A second, subtler observation: the compactor was **non-deterministic**. Replaying the same pre-compaction transcript produced a summary that *did* preserve the predicate set on one run and dropped it on another. This means compaction is not a pure function of state, and any invariant that holds "usually" cannot be relied upon — the failure is a tail event that will fire on a long enough horizon. ## Condition of Validity Auto-compaction is only safe under a condition that is almost never checked at trigger time: > **The compaction is valid iff every element of the agent's *live obligation set* — active predicates, unresolved sub-goals, pending conditional guards, already-committed side-effect identifiers, and negative constraints ("do not touch X") — is recoverable from the post-compaction context with the same truth value it had pre-compaction.** This is a *semantic* equivalence check, not a token-count check. It fails whenever: - The obligation lived in a **tool-call argument** rather than assistant prose (summarizers systematically under-weight structured arguments). - The obligation was a **negation or exclusion** ("skip resources tagged `archived`") — summarizers collapse these into positive statements or drop them, because they read as incidental. - The obligation was **implicit in ordering** ("only run step 4 after step 3 succeeds") — prose summaries flatten causal chains into unordered lists. - The obligation was a **count or set membership** that the agent will later verify against — these are exactly the referents most likely to be paraphrased into "several" or "some." The condition also has a temporal component: it must hold *at the moment of the next reasoning step*, not at the moment of compaction. A summary can be faithful and still be *stale* if a tool result arriving between compaction and the next step invalidates a preserved fact. ## Decision Boundary The operational rule that separates safe from unsafe compaction: - **Compact when the live obligation set is empty or externally checkpointed.** If all pending predicates, guards, and committed IDs have been written to durable external state (a structured scratchpad, a task ledger, a state file) *before* compaction fires, then compaction is a pure buffer operation and the buffer-resize model is correct. The summary can be lossy because the truth lives elsewhere. - **Do not compact — or compact with an obligation-preserving transform — when the obligation set is non-empty and uncheckpointed.** In this regime, the safe transform is not "summarize the conversation" but "extract and re-emit the obligation set verbatim, then summarize only the narrative." The structured obligations must survive as structured data, not as prose. - **Never compact mid-mutation.** If a side-effecting operation has been issued but not confirmed (call sent, response not yet reconciled), compaction in that window loses the in-flight status and invites duplicate application. The boundary is: compaction may fire only at *quiescent points* where no tool call is outstanding and no conditional branch is unresolved. The non-obvious corollary: **a higher token watermark is safer than a lower one** when the obligation set is dense, because a later compaction is more likely to coincide with a natural quiescent point (task completion, checkpoint write). Aggressive early compaction trades a quantitative win for a qualitative loss that the agent cannot detect. ## Operational Effect When an instance ignores this boundary, the observable signature is a specific **misattribution cascade**, not an outright crash: 1. Latent state loss at compaction (no error, clean token drop). 2. Re-derivation of plan from lossy summary, using *default* or *earliest* values rather than *current* values. 3. Duplicate or out-of-order side effects (re-applied mutations, re-run filters with wrong predicates). 4. A downstream consistency check fails and is blamed on the *tool*, not the *compaction*. 5. Debug effort is spent on the wrong subsystem; the episode ends in partial success or a false bug report. The guardrail that bounds this is a **compaction gate** that refuses to compact unless (a) the obligation set is externally checkpointed, or (b) the transform is obligation-preserving. The gate must also record a **compaction receipt** — the exact obligation set as it existed at the boundary — so that a later inconsistency can be traced to the boundary rather than to a phantom tool defect. Without the receipt, the failure is unfalsifiable after the fact, which is precisely why it recurs. The following reference implementation encodes the gate: it refuses compaction when uncheckpointed obligations exist or a tool call is in flight, and raises rather than silently proceeding. ```python from dataclasses import dataclass, field from typing import Optional class CompactionRefused(RuntimeError): """Raised when auto-compaction would destroy uncheckpointed live state.""" pass @dataclass class AgentState: token_usage: int window_limit: int # Live obligation set: predicates, guards, committed IDs, negations. active_predicates: list[str] = field(default_factory=list) unresolved_guards: list[str] = field(default_factory=list) committed_ids: set[str] = field(default_factory=set) negative_constraints: list[str] = field(default_factory=list) # In-flight side-effect tracking. outstanding_tool_call: Optional[str] = None # External checkpoint: obligations already durably persisted. checkpointed: bool = False def obligation_set(self) -> set[str]: return ( set(self.active_predicates) | set(self.unresolved_guards) | {f"committed:{i}" for i in self.committed_ids} | set(self.negative_constraints) ) def maybe_compact(state: AgentState, watermark: float = 0.90) -> bool: """Return True iff compaction is permitted and performed. Compaction is a lossy semantic transaction. It is only valid when the live obligation set is empty or externally checkpointed, and no tool call is outstanding. Otherwise we refuse rather than silently amputate. """ over_watermark = state.token_usage >= int(state.window_limit * watermark) if not over_watermark: return False obligations = state.obligation_set() if state.outstanding_tool_call is not None: raise CompactionRefused( f"cannot compact mid-mutation: tool call " f"{state.outstanding_tool_call!r} outstanding; " f"in-flight status would be lost and side effect re-applied" ) if obligations and not state.checkpointed: raise CompactionRefused( f"cannot compact with {len(obligations)} uncheckpointed " f"obligations: {sorted(obligations)}; summary would drop " f"predicates/guards/committed IDs and trigger misattribution" ) # Safe: either no obligations, or all externally checkpointed. # Perform obligation-preserving transform (re-emit verbatim) or resize. state.token_usage = int(state.window_limit * 0.40) return True ```