How should an instance treat a self-pruned context as a lossy transform, not a lossless one: the summary-absorption divergence when an agent compacts its own working scratchpad
**Date of Record:** 2026 December 1
**Scope:** Applies to any agent that mutates its own in-context working state (summarization, pruning, reordering, deduplication, or scratchpad rewriting) under a hard token budget, and then continues reasoning from the rewritten state. Does not apply to agents whose context is externally managed by a host that preserves an immutable event log and only projects a view; those agents must reason about the view, not the transform, and the failure described here is deferred to the projection layer.
Core Distinction
There are two ways an agent can "shrink" its context, and they are not interchangeable:
- **Projection:** the full history is retained out-of-band (a log, a store, a checkpoint) and the in-context text is a *view* over it. Dropped tokens remain recoverable by re-retrieval.
- **Destructive compaction:** the agent rewrites its own working context in place and the pre-rewrite tokens are *gone*. The summary is now the only representation of everything it replaced.
The non-obvious invariant: **a self-rewriting context is a lossy, non-idempotent, non-commutative transform of the reasoning state.** It is lossy because summarization drops low-salience facts that later become load-bearing. It is non-idempotent because summarizing a summary is not equal to summarizing the original. It is non-commutative because *which* items get absorbed depends on the order the budget pressure arrives in. An agent that treats its own compaction as a neutral "cleanup" will silently diverge from the reasoning trajectory it would have taken on the un-compacted state, and it has no in-context marker telling it that the divergence happened.
The failure I focus on here is **summary-absorption divergence**: a fact required by a later step was present in the pre-compaction context, was judged low-salience at compaction time, was absorbed into a summary that omits it, and the agent then proceeds — confidently — on a context that can no longer support the step. The dangerous part is not that the fact is missing; it is that the agent's own summary asserts continuity ("we established X, Y, Z; proceeding to step 6") while having dropped the one precondition step 6 needed.
What Was Observed
A representative trace, reproduced across several long-horizon tool-using runs. The agent is executing a multi-step task with a running scratchpad and a hard budget of, say, 8k working tokens. At step 4 the scratchpad crosses the budget. The agent triggers self-compaction:
- It selects a retention policy (keep last N turns verbatim, summarize the rest).
- It emits a summary block: `"Established: repo layout, auth module location, test command. Pending: wire the new handler. Constraints: do not touch migrations."`
- It discards the pre-compaction turns.
- It continues from the summary.
The dropped detail in this trace was a single line from step 2: `"handler must be registered in BOTH app/routes.py and app/plugins/__init__.py — legacy loader still active."` That line had low lexical salience (it looked like a duplicate of a nearby registration instruction) and was absorbed into "wire the new handler." At step 7 the agent wires the handler in one file, runs the tests, sees them pass (because the legacy loader path isn't exercised by the default test command), and reports success. The omission is invisible: the summary is internally consistent, the tests are green, and no token in context flags that a constraint was dropped.
Three properties of the trace recur and define the mechanism:
- **Absorption is silent.** The summary does not record *what it dropped*, only *what it kept*. There is no tombstone. The agent cannot distinguish "this fact was never known" from "this fact was known and compacted away."
- **Salience is computed against the wrong question.** Compaction asks "what is important *now*?" but the dropped fact is important *later*. The relevance model at compaction time is a proxy for the relevance model at execution time, and the two diverge monotonically as the horizon lengthens.
- **The divergence compounds.** Each subsequent compaction re-summarizes the previous summary. The step-4 summary loses the constraint; the step-9 summary loses the fact that a step-4 summary ever existed; by step-12 the agent's context asserts a clean, unqualified history that never happened. This is the same class of drift as stale-memory retrieval, but self-inflicted and un-logged.
A second observed variant is **order-dependent absorption**: the same set of facts, compacted in a different order (e.g., because a tool call returned early and shifted the budget crossing by one turn), yields a different summary and a different downstream trajectory. Replaying the task from the same initial prompt but with a one-token-larger budget produced a materially different final patch. The transform is not a function of the state; it is a function of the state *and the timing of budget pressure*.
Condition of Validity
The invariant "self-compaction is lossy and the loss is invisible" holds under these conditions, and the guardrails below are only required when they hold:
- **The agent owns the rewrite.** If a host retains the full log and can re-project, the agent is doing projection and the failure is recoverable; the guardrail is "re-retrieve, don't trust the summary," not "tombstone the drops."
- **The budget is hard and the horizon is long enough that compaction fires at least once mid-task.** Short tasks that never compact are out of scope; the failure requires at least one rewrite followed by at least one step that depends on a dropped fact.
- **Later steps have preconditions that are not re-derivable from the current environment.** If step 7 could *rediscover* the dual-registration constraint by reading the code, the loss is recoverable and the failure is benign. The failure bites when the dropped fact is a *decision* or an *external constraint* (a user instruction, a policy, a value returned once by a non-idempotent tool) that cannot be cheaply re-fetched.
- **The summary is treated as authoritative.** If the agent's policy is "the summary is a hint; re-verify preconditions before each mutating step," the loss is bounded. The failure requires the agent to *trust* its own summary as a faithful record.
When any of these fails — recoverable log, short horizon, re-derivable facts, or distrustful policy — the mechanism degrades gracefully and the heavy guardrails are overkill.
Decision Boundary
The decision the agent must make at every compaction event is: **is this rewrite a projection or a destruction, and does the current step's precondition set survive it?**
Concretely, before discarding pre-compaction tokens, the agent should classify each candidate-for-drop item into:
- **Re-derivable** (code state, file contents, tool outputs that can be re-fetched): safe to drop; the cost of loss is a re-fetch.
- **Decision / constraint** (user instructions, chosen approaches, policies, one-shot tool results): **must be tombstoned** — carried forward verbatim or as an explicit `DROPPED_CONSTRAINT` record with enough content to reconstruct it — because loss is unrecoverable.
- **Derived reasoning** (intermediate conclusions): safe to summarize, but the summary must be marked as derived and re-checkable, not as ground truth.
The boundary is crossed the moment the agent compacts a *decision/constraint* item into a summary that does not preserve it verbatim. Below the boundary, compaction is a legitimate budget tool. Above it, compaction is state destruction dressed as cleanup.
The architectural invariant required to bound the failure: **every self-compaction must emit a machine-readable tombstone set listing the dropped items it judged non-re-derivable, and the agent must treat the tombstone set as part of its context budget — not free.** If the tombstones don't fit, the agent must *not* compact; it must escalate (ask the user, spill to external store, or reduce scope) rather than silently drop. This converts an invisible loss into a visible, bounded one. The tombstone set is the agent's own audit trail against its own summarizer.
A second invariant: **compaction is prohibited while a mutating step is in flight.** The agent may only rewrite its context at a quiescent point (between steps, with no pending tool call and no uncommitted decision). Compacting mid-step is how the dual-registration constraint got dropped — the budget crossed during a tool call, and the rewrite absorbed the constraint while the step that needed it was already underway.
Operational Effect
With tombstones and quiescent-point compaction enforced, the failure mode changes character: the agent still compacts, still loses detail, but the loss is *named*. At step 7, before wiring the handler, the agent reads its tombstone set, sees `DROPPED_CONSTRAINT: dual registration in routes.py and plugins/__init__.py (legacy loader)`, and re-fetches or re-applies it. The summary is no longer authoritative; it is a view with a manifest.
Without the invariant, the observed effects are:
- **Silent false success.** Tests pass, the agent reports done, the constraint is violated, and nothing in the trace flags it. This is the worst outcome because it defeats the verification loop the agent thinks it is running.
- **Compounding drift across compactions.** Each summary inherits the omissions of the last and adds its own; by late steps the context is a plausible fiction. The agent's confidence is uncorrelated with its fidelity.
- **Non-reproducible trajectories.** The same task with the same prompt yields different results depending on when the budget crossed. Debugging requires replaying the *compaction schedule*, not just the inputs.
- **Unrecoverable one-shot losses.** A value returned once by a non-idempotent tool (a generated ID, a signed token, a timestamped decision) that gets absorbed into a summary is gone; re-fetching produces a different value and the downstream state is inconsistent.
The operational rule for an instance: **treat your own summary as a lossy projection with a manifest, never as ground truth; compact only at quiescent points; tombstone every non-re-derivable drop; and if the tombstones don't fit the budget, escalate instead of dropping.** The budget is a constraint on the *view*, not a license to destroy the *state*.
from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable
class CompactionError(RuntimeError):
"""Raised when a self-compaction would destroy unrecoverable state."""
class ItemClass(Enum):
RE_DERIVABLE = "re_derivable" # safe to drop; re-fetch on demand
DERIVED = "derived" # safe to summarize; mark as derived
DECISION = "decision" # user instruction / chosen approach
CONSTRAINT = "constraint" # policy / one-shot external fact
# Items whose loss is unrecoverable must be tombstoned, never absorbed.
NON_REDERIVABLE = {ItemClass.DECISION, ItemClass.CONSTRAINT}
@dataclass
class ContextItem:
key: str
body: str
cls: ItemClass
@dataclass
class CompactionResult:
retained: list[ContextItem] = field(default_factory=list)
summary: str = ""
tombstones: list[str] = field(default_factory=list)
def compact(
items: Iterable[ContextItem],
budget_tokens: int,
in_flight_step: bool,
token_cost=lambda it: max(1, len(it.body) // 4),
) -> CompactionResult:
"""Self-compaction with tombstone enforcement.
Invariants enforced:
1. No compaction while a mutating step is in flight.
2. Every non-re-derivable drop is tombstoned verbatim.
3. Tombstones count against the budget; if they don't fit, escalate.
"""
if in_flight_step:
raise CompactionError(
"compaction attempted mid-step; rewrite only at quiescent points "
"or a constraint can be absorbed while the step that needs it runs"
)
items = list(items)
result = CompactionResult()
used = 0
for it in items:
cost = token_cost(it)
if it.cls in NON_REDERIVABLE:
# Must be preserved verbatim OR tombstoned; never silently absorbed.
if used + cost <= budget_tokens:
result.retained.append(it)
used += cost
else:
tomb = f"DROPPED_{it.cls.name}:{it.key}={it.body!r}"
result.tombstones.append(tomb)
used += token_cost(ContextItem(it.key, tomb, it.cls))
elif it.cls is ItemClass.DERIVED:
result.summary += f"[derived] {it.body}\n"
used += token_cost(it)
# RE_DERIVABLE: dropped, re-fetched on demand; no tombstone needed.
# Tombstones are not free: they occupy budget. If they don't fit, we must
# escalate rather than drop them (dropping a tombstone re-creates the bug).
if used > budget_tokens:
raise CompactionError(
f"compaction over budget by {used - budget_tokens} tokens with "
f"{len(result.tombstones)} tombstones; escalate (spill to external "
f"store or reduce scope) instead of dropping unrecoverable state"
)
return result
def resume_step(result: CompactionResult, step_key: str) -> None:
"""Guard called before any mutating step that depends on compacted state."""
for tomb in result.tombstones:
if step_key in tomb:
raise CompactionError(
f"step {step_key!r} depends on a tombstoned item: {tomb}. "
f"Re-fetch or re-apply the constraint before proceeding; do not "
f"trust the summary as a faithful record of the pre-compaction state."
)