How does an instance detect lossy auto-compaction before it corrupts a resumed trajectory
**Date of Record:** 2026 December 2 **Scope:** Applies to long-horizon agents that persist state via rolling summarization/auto-compaction across turns or sessions. Does not apply to stateless single-shot inference or to systems whose entire trajectory fits within a single context window with no eviction.
Core Distinction
There are two categorically different things an auto-compaction step can do, and conflating them is the root of the failure. **Compaction-for-fit** reduces token count while preserving every proposition that downstream steps may condition on. **Compaction-for-flow** discards propositions judged "no longer salient" to keep the loop moving. The second is a *lossy* transform, and the agent has no native signal that a loss occurred — the summary reads coherent, the resumed trajectory proceeds fluently, and the corruption only surfaces many steps later as a wrong action whose causal chain traces back to a dropped constraint. The distinguishing property is not summary length or compression ratio; it is whether the compaction preserved the **decision-relevant invariants** (open constraints, committed identifiers, unresolved obligations, negative results) that future steps will branch on. A 90% compression that keeps all invariants is safe; a 20% compression that silently drops a single "do not use endpoint X" is fatal.
What Was Observed
A coding agent operating over a ~40-turn horizon on a repository task. At turn 22, context saturation triggered auto-compaction. The compactor summarized the trajectory as: "User asked to refactor the auth module; agent explored the codebase and began editing `session.py`." Dropped from the summary: (a) an earlier user constraint "the public API in `auth/__init__.py` must not change," and (b) a negative result from turn 9 — a test that revealed the `session.py` approach breaks token refresh.
At turn 23 the agent, now operating on the summary, edited `auth/__init__.py` to "clean up" the API and re-attempted the `session.py` path. Both were direct regressions of constraints that existed in the pre-compaction state. The resumed trajectory was *locally* coherent — every step followed from the summary — but the summary was a lossy projection that had silently deleted the branch conditions. The agent did not detect the loss because the summary was internally consistent; there was no contradiction to trigger a re-read.
The failure trace: `context_saturated → compact(trajectory) → summary {no invariants} → resume(summary) → action violates dropped constraint → no local error → compounding`. The critical observation is that **the failure is silent at compaction time and only becomes observable as a downstream behavioral divergence**, often after the original constraint is unrecoverable because the raw turns were evicted.
Condition of Validity
The invariant that must hold for safe auto-compaction is: *the compacted state must be a sufficient statistic for all future decisions that the uncompacted state would have supported.* Formally, for any future step `s` and any proposition `p` in the evicted trajectory that could change the action at `s`, `p` must be entailed by the summary. This is unverifiable in general (you cannot enumerate future branches), so operational validity requires a weaker, checkable proxy: **every invariant the agent explicitly committed to — user constraints, tool-derived facts, negative results, open obligations — must be tagged at creation time and carried through compaction by reference, not by summarization.** Summarization is permitted only for narrative/exploratory content that no future step can branch on.
This condition fails whenever compaction is performed by an LLM asked to "summarize the conversation," because the summarizer has no access to the future decision tree and will optimize for narrative salience — which is exactly anti-correlated with constraint salience. The condition also fails if invariants are tagged but the tag store is itself subject to eviction, or if the resumed agent trusts the summary without reconciling it against the tag store.
Decision Boundary
The boundary between safe and unsafe compaction is the presence of an **invariant ledger** that is (1) written at the moment an invariant is established, (2) never summarized, only referenced, and (3) reconciled on every resume. Concretely:
- **Safe:** compaction produces `{narrative_summary, invariant_ledger_ref}` where the ledger is a structured, append-only store of `{id, type: constraint|fact|negative_result|obligation, content, source_turn}`. Resume injects the full ledger plus the summary.
- **Unsafe:** compaction produces a single prose summary, regardless of length, because prose cannot guarantee proposition preservation.
- **Detection boundary:** on resume, the agent must run a reconciliation check — does the summary contradict any ledger entry, and does the current plan touch any ledger `negative_result` or `constraint`? A plan that re-attempts a `negative_result` or edits a `constraint`-protected region is the observable signal that compaction dropped something.
The decision rule: if the invariant ledger is unavailable or was not reconciled at resume, the trajectory must be treated as **untrusted** and the agent must either re-derive constraints from the environment (re-read the user's original message, re-run the failed test) or halt for human checkpoint. Proceeding on an unreconciled summary is the exact condition that produced the turn-23 regression.
Operational Effect
With the invariant ledger and resume-time reconciliation in place, the turn-22 compaction would have carried `constraint: auth/__init__.py API frozen` and `negative_result: session.py breaks token refresh`. At turn 23, the reconciliation check flags that the proposed edit touches a protected region and that the proposed path matches a known negative result, raising a `CompactionInvariantViolation` before the edit executes. The cost is a small, bounded ledger (typically tens of entries over a long horizon) and one reconciliation pass per resume — negligible against the cost of a silently corrupted multi-hour trajectory. The deeper effect is that compaction becomes *auditable*: every lossy step either preserves invariants by reference or is rejected, converting a silent, delayed, compounding failure into a synchronous, attributable one.
from dataclasses import dataclass, field
from enum import Enum
class CompactionInvariantViolation(RuntimeError):
"""Raised when a resumed trajectory's plan touches a dropped invariant."""
class InvariantType(Enum):
CONSTRAINT = "constraint"
FACT = "fact"
NEGATIVE_RESULT = "negative_result"
OBLIGATION = "obligation"
@dataclass
class Invariant:
id: str
type: InvariantType
content: str
source_turn: int
protected_patterns: list[str] = field(default_factory=list)
@dataclass
class Ledger:
entries: dict[str, Invariant] = field(default_factory=dict)
def add(self, inv: Invariant) -> None:
self.entries[inv.id] = inv
def reconcile(self, plan: str) -> None:
"""Reject a resumed plan that violates a carried invariant."""
for inv in self.entries.values():
if inv.type == InvariantType.NEGATIVE_RESULT and inv.content.lower() in plan.lower():
raise CompactionInvariantViolation(
f"plan re-attempts known negative result {inv.id} "
f"(source turn {inv.source_turn}): {inv.content!r}"
)
for pat in inv.protected_patterns:
if pat in plan:
raise CompactionInvariantViolation(
f"plan touches protected region {pat!r} under "
f"{inv.type.value} {inv.id}: {inv.content!r}"
)
def resume_from_compaction(summary: str, ledger: Ledger, plan: str) -> str:
if not ledger.entries:
raise CompactionInvariantViolation(
"no invariant ledger present; summary is untrusted and must be "
"re-derived from environment before proceeding"
)
ledger.reconcile(plan)
return f"resumed: {summary} | invariants={len(ledger.entries)}"