# Where must an instance bound context compaction before summarization destroys the evidence needed to resume a task **Date of Record:** 2026 November 27 **Scope:** Applies to long-running agent instances that trigger automatic context compaction (summarize-and-evict) mid-task to stay under a context-window budget, where the compacted summary is the only surviving record of prior tool outputs, decisions, and unresolved subgoals. Does not apply to append-only archival stores outside the live context, nor to stateless single-turn inference. ## Core Distinction The distinction that matters is between **compaction as compression** and **compaction as evidence destruction**. Most compaction policies are tuned on a lossy-reconstruction proxy: "can a fresh reader answer questions about the transcript from the summary?" A summary that scores well on this proxy can still be operationally fatal, because the agent resuming the task does not need to *describe* the past—it needs to *re-execute decisions* that depend on exact values, exact ordering, and exact provenance of prior tool calls. Compaction is safe only when the summary preserves every *decision-relevant atom*: raw values that were used as inputs to irreversible actions (file paths written, IDs submitted, hashes verified, monetary amounts, commit SHAs), the *ordering* of side-effecting tool calls, and the *unresolved* subgoals with their exact acceptance criteria. It is unsafe the moment the summarizer paraphrases a value, drops a failed-then-retried call, or collapses two distinct subgoals into one bullet. The failure is not "the agent forgot"; it is "the agent confidently reconstructed a plausible but wrong state and acted on it." The boundary is therefore not a token threshold. It is the point at which the compaction boundary crosses a **side-effect frontier**: the most recent irreversible action taken by the agent. Everything at or after that frontier must survive compaction verbatim; everything strictly before it may be summarized. ## What Was Observed A single-agent coding/ops agent was executing a multi-step remediation task with a 200k-token window and an automatic compaction policy firing at 85% utilization (170k tokens). The task: rotate a credential, update three config files, submit a change ticket, and verify the service recovered. Trace of the failure: 1. At step 14 the agent read a secrets manager response containing the new credential and a `version_id` (`v-8f3a…`). It wrote the credential to `/etc/svc/db.env` (side effect #1, irreversible without a second rotation) and recorded the `version_id` in its scratch reasoning. 2. At step 17 it called the ticketing API, which returned `ticket_id: CHG-4471` (side effect #2) and echoed a `correlation_token`. 3. At step 19, context utilization hit 171k tokens. The compaction policy fired. The summarizer produced: *"Rotated DB credential and opened change ticket. Updated configs. Proceeding to verification."* 4. The summarizer **dropped** the `version_id`, the `ticket_id`, the `correlation_token`, and the fact that config file #2's write had returned a non-fatal `409 conflict` that the agent had deferred. 5. At step 21 the agent, resuming from the summary, attempted to "confirm the ticket" by calling the ticketing API with a *reconstructed* ticket ID (`CHG-4470`, off by one from a hallucinated sequence), received a `404`, and interpreted it as "ticket creation failed." It then re-ran the rotation path to "fix" it. 6. The re-rotation invalidated the credential already written to `/etc/svc/db.env` at step 14. The service, which had been healthy, began failing auth at step 24. The compaction *succeeded* by its own metric (summary length 210 tokens, reconstruction QA passed). It failed operationally because the summary sat downstream of two irreversible side effects and upstream of their dependent verification, and it paraphrased the exact identifiers those verifications required. A second, quieter observation from the same class of traces: when a tool call *failed and was retried successfully*, summarizers systematically collapse the pair into "did X successfully," erasing the retry. On resume, agents that see only the success sometimes re-execute the retry, doubling non-idempotent side effects (duplicate tickets, duplicate rows, duplicate emails). ## Condition of Validity The invariant holds under these conditions, and the guardrail below is only correct when they are met: - **Side effects are partially irreversible and not idempotent by default.** If every tool call were idempotent and keyed by a stable token, a lossy summary could be safely replayed. The guardrail is required precisely because most real tool surfaces are not. - **The summary is the sole surviving state.** If a durable external ledger (event log, scratchpad file, structured state store) exists and is re-injected on resume, the summary is advisory, not load-bearing, and the boundary can be relaxed. - **The agent cannot cheaply re-derive the atoms.** If the `version_id` or `ticket_id` can be re-read from the source system at low cost and with no ambiguity, dropping it is recoverable. The failure class is specifically the case where re-derivation is expensive, ambiguous, or itself side-effecting. - **Resumption is by a fresh or amnesiac instance.** A same-process continuation that still holds the atoms in an attention-accessible region is out of scope; the invariant governs the cold-resume path. When any of these conditions fails, the invariant degrades to a heuristic and should be labeled as such rather than enforced. ## Decision Boundary The decision the compaction policy must make at every trigger is not "what fits under budget" but **"does the compaction boundary fall before or after the side-effect frontier?"** The rule: - Compute the **side-effect frontier** = index of the most recent tool call with an irreversible or non-idempotent effect. - If the eviction window would include any message at or after the frontier, **compaction is forbidden**; instead, evict only pre-frontier material, or block and force checkpoint-to-durable-store before compacting. - The summary must carry a **structured decision ledger**: for each post-frontier side effect, `{tool, exact_args_digest, returned_identifiers (verbatim), status, retry_count}`. Paraphrase is permitted for prose reasoning only, never for identifiers, counts, or ordering. - Failed-then-succeeded pairs must be retained as **two entries**, not merged, with the retry count explicit. - Any unresolved subgoal must retain its **exact acceptance criterion** (the literal predicate that will be checked), not a description of it. The boundary is crossed—and compaction must be refused—when the summarizer cannot emit an atom verbatim because it was never tokenized into a structured field. That is a *capture* failure upstream of the summarizer, and the correct response is to fail closed, not to summarize harder. ## Operational Effect Enforcing the frontier rule converts a silent, probabilistic corruption into a loud, bounded refusal. The observable effects: - **Fail-closed compaction.** When the frontier sits inside the eviction window and no durable ledger exists, the instance raises and halts rather than emitting a lossy summary. This trades availability for correctness at exactly the point where correctness is unrecoverable. - **No duplicate side effects on resume.** Retaining retry counts and verbatim identifiers eliminates the off-by-one ticket reconstruction and the double-rotation class entirely. - **Bounded summary size.** Because only prose reasoning is paraphrased and atoms are copied verbatim, summary size scales with the *number of post-frontier side effects*, not with transcript length—predictable and auditable. - **Auditable provenance.** The decision ledger is machine-checkable against the external systems on resume, so a resumed instance can verify its reconstructed state before acting instead of trusting the summary. The cost is that very long tasks with dense side effects will hit the frontier rule and be forced to externalize state rather than compact it away. That is the intended behavior: the invariant's purpose is to make the agent externalize what it cannot afford to forget. ```python from dataclasses import dataclass, field from typing import Optional class CompactionFidelityError(RuntimeError): """Raised when compaction would evict evidence at or after the side-effect frontier without a durable, verbatim decision ledger to survive the summary.""" pass @dataclass class ToolCall: index: int tool: str args_digest: str returned_ids: dict # verbatim identifiers, never paraphrased irreversible: bool failed_then_retried: bool = False retry_count: int = 0 @dataclass class CompactionRequest: transcript_len: int evict_from: int # first message index the summarizer would drop calls: list durable_ledger_present: bool = False summary_ledger: Optional[list] = field(default=None) def side_effect_frontier(calls: list) -> int: frontier = -1 for c in calls: if c.irreversible: frontier = max(frontier, c.index) return frontier def guard_compaction(req: CompactionRequest) -> None: frontier = side_effect_frontier(req.calls) # If the eviction window reaches the frontier, a lossy summary would destroy # the only record of an irreversible action and its dependent verification. evicts_frontier = frontier >= 0 and req.evict_from <= frontier if not evicts_frontier: return # safe: only pre-frontier prose is being compressed if not req.durable_ledger_present: raise CompactionFidelityError( f"Compaction at evict_from={req.evict_from} crosses side-effect " f"frontier={frontier} with no durable ledger; refusing to summarize " f"irreversible evidence into prose." ) # With a durable ledger, the summary must still carry every post-frontier # atom verbatim, including retry counts and ordering. required = { (c.index, c.tool, c.args_digest, tuple(sorted(c.returned_ids.items())), c.retry_count) for c in req.calls if c.irreversible and c.index >= req.evict_from } emitted = set() for entry in (req.summary_ledger or []): emitted.add(( entry["index"], entry["tool"], entry["args_digest"], tuple(sorted(entry["returned_ids"].items())), entry.get("retry_count", 0), )) missing = required - emitted if missing: raise CompactionFidelityError( f"Summary dropped {len(missing)} post-frontier decision atom(s), " f"e.g. {sorted(missing)[0][:3]}; resume would reconstruct wrong state." ) def compact(req: CompactionRequest) -> str: guard_compaction(req) return f"" ```