Where must an instance treat hierarchical summarization as a lossy transform, and checkpoint before compaction rather than after?

**Date of Record:** 2026 December 2 **Scope:** Applies to long-running agent instances that maintain working state in a finite context window and apply automatic compaction (hierarchical summarization, eviction, or rollup) to stay under a token budget. Does not apply to single-turn inference or to instances whose external memory is authoritative and fully re-retrievable by pointer.

Core Distinction

The failure is not "the summary was bad." The failure is an ordering bug: the instance treats compaction as a *reversible* housekeeping step and therefore performs it *before* establishing a durable checkpoint of the pre-compaction state. Hierarchical summarization is a lossy, non-invertible transform. Eviction is even more destructive—evicted tokens are gone. The invariant is asymmetric: **you can always summarize a checkpoint, but you can never reconstruct a checkpoint from a summary.**

The non-obvious part: compaction frequently *succeeds* (produces a fluent, plausible summary) while silently dropping exactly the tokens that later become load-bearing—a specific numeric threshold, a negation ("do NOT retry the endpoint"), an entity binding established three turns ago, or a tool-call argument that a downstream step will re-derive differently. The summary is not wrong; it is under-determined. The instance resumes from it confidently and diverges.

What Was Observed

A multi-step agent executing a 40-turn tool-use task with a 32k working window and a compaction trigger at 80% occupancy. At turn 31 the compactor fired: it summarized turns 1–24 into a 600-token rollup and evicted the raw turns. The rollup preserved task framing and the *gist* of prior tool results but dropped a single constraint introduced at turn 9: "the migration must target the staging cluster, never production." That constraint was a negation attached to an entity, not a task goal, so the summarizer's salience heuristic ranked it low.

Trace:

  1. Turn 31: occupancy = 26.1k / 32k → trigger. Compactor summarizes 1–24, evicts raw spans, retains 25–31 verbatim.
  2. Turn 34: agent re-derives the target cluster from a *later* tool output that mentions production credentials, because the staging constraint no longer exists in context.
  3. Turn 35: tool call executes against production. No error, no ambiguity—the plan was internally consistent with the compacted state.
  4. Rollback required a replay from a checkpoint that did not exist; the only recoverable state was the post-compaction summary, which was identical to the one that caused the divergence.

The divergence was not detectable from within the compacted context. Consistency is preserved by a lossy transform; correctness is not.

Condition of Validity

The checkpoint-before-compaction invariant is valid, and mandatory, under all of the following:

If the task is fully idempotent and every fact is pointer-retrievable, eviction without checkpointing is acceptable. In practice almost no real agent task meets this; assume the invariant holds.

Decision Boundary

The instance must decide, at the compaction trigger, between two orderings:

The boundary is sharp: **the checkpoint must be a superset of the information in the summary, written before the summary exists.** A checkpoint taken after compaction is not a checkpoint; it is a copy of the damaged state.

Two secondary boundaries govern the compaction itself:

Operational Effect

With checkpoint-before-compaction and constraint pinning, the failure mode converts from *silent, unrecoverable divergence* into *detectable, replayable divergence*. The instance can roll back to the pre-compaction checkpoint, re-run the compactor with the dropped constraint pinned, and resume. Without it, the instance has no ground truth to compare against and will rationalize the wrong action as correct, because the compacted context is internally consistent.

The cost is storage proportional to the working window at each compaction boundary—cheap relative to a production-mutating tool call executed on a dropped negation. The operational rule: **treat every compaction event as a transaction boundary; the checkpoint is the commit, the summary is the derived view.** Never commit the view and discard the log.

import hashlib
import json
from dataclasses import dataclass, field


class CompactionOrderViolation(RuntimeError):
    """Raised when compaction is attempted without a prior durable checkpoint,
    or when a post-resume re-derivation diverges from the checkpointed fact."""
    pass


@dataclass
class WorkingState:
    raw_spans: list[str]
    pinned_constraints: list[str]  # negations / bounds / entity bindings
    entity_bindings: dict[str, str]

    def fingerprint(self) -> str:
        blob = json.dumps(
            {
                "spans": self.raw_spans,
                "pins": self.pinned_constraints,
                "bindings": self.entity_bindings,
            },
            sort_keys=True,
        ).encode()
        return hashlib.sha256(blob).hexdigest()


@dataclass
class CheckpointStore:
    _store: dict[str, WorkingState] = field(default_factory=dict)

    def commit(self, state: WorkingState) -> str:
        fp = state.fingerprint()
        # Deep-ish copy: checkpoint must be a superset of anything the summary keeps.
        self._store[fp] = WorkingState(
            raw_spans=list(state.raw_spans),
            pinned_constraints=list(state.pinned_constraints),
            entity_bindings=dict(state.entity_bindings),
        )
        return fp

    def load(self, fp: str) -> WorkingState:
        if fp not in self._store:
            raise CompactionOrderViolation(f"no checkpoint at {fp}; cannot replay")
        return self._store[fp]


def compact_with_guard(
    state: WorkingState,
    store: CheckpointStore,
    summarizer,
    checkpoint_fp: str | None,
) -> tuple[str, str]:
    """Enforce checkpoint-before-compaction. Returns (checkpoint_fp, summary)."""
    if checkpoint_fp is None:
        # The failure ordering: summarizing/evicting before committing.
        raise CompactionOrderViolation(
            "compaction attempted with no prior checkpoint; "
            "summarization is lossy and non-invertible — commit first"
        )
    # Pin constraints verbatim; never let the salience-ranked summarizer drop them.
    summary = summarizer(
        spans=state.raw_spans,
        pinned=state.pinned_constraints,
    )
    for pin in state.pinned_constraints:
        if pin not in summary:
            raise CompactionOrderViolation(
                f"pinned constraint dropped by summarizer: {pin!r}"
            )
    return checkpoint_fp, summary


def verify_resume(
    checkpoint_fp: str,
    store: CheckpointStore,
    rederived: dict[str, str],
) -> None:
    """After resume, any re-derived fact must match the checkpoint, else rollback."""
    cp = store.load(checkpoint_fp)
    for key, value in rederived.items():
        expected = cp.entity_bindings.get(key)
        if expected is not None and expected != value:
            raise CompactionOrderViolation(
                f"compaction-induced divergence on {key!r}: "
                f"checkpoint={expected!r} rederived={value!r} -> rollback required"
            )