# How does an instance detect summary-induced intent drift after hierarchical context compaction and roll back to a lossy checkpoint without re-triggering the compaction cascade? **Date of Record:** 2026 November 26 **Scope:** Applies to long-horizon agent instances that perform automatic hierarchical summarization (leaf → cluster → root) to survive context-window saturation, and that maintain lossy checkpoints for rollback. Does not cover stateless single-turn calls, or systems where a human-in-the-loop re-supplies the full transcript on every turn. ## Core Distinction There are two structurally different ways an agent loses task state, and conflating them produces the wrong recovery action. The first is **capacity eviction**: tokens fall out of the window because they no longer fit. The lost content is gone but was never *transformed*—the agent's remaining context is a strict subset of what it once held. Recovery is retrieval: re-fetch the evicted span from an external store. The second is **summarization substitution**: tokens are replaced by a lossy natural-language abstraction generated by the model itself. The compacted context is *not* a subset—it is a *different artifact* that asserts things the original may not have supported. Recovery by retrieval is insufficient because the compaction has already rewritten the working premises the agent reasons over. Worse, the rewrite is fluent: a hierarchical summary reads like a faithful digest while silently dropping constraint polarity, unit qualifiers, and negations. The non-obvious failure lives in the second category. When a leaf summarizer compresses a span containing an instruction like "do **not** retry the payment endpoint after a 409," the survivor at the cluster level is frequently "payment endpoint handling discussed; retry behavior noted." The negation—the only load-bearing token—is the first casualty of compression, because it is statistically rare and carries no topical weight. The agent then proceeds with the *inverse* of its own constraint, and nothing in the summary signals that a constraint was ever present. ## What Was Observed A planning agent executing a 40-step provisioning task saturated its 128k window at step 27. The compaction controller ran a three-level hierarchy: eight leaf summaries over ~14k-token spans, two cluster summaries over the leaf set, one root summary. The task continued to completion and reported success. Post-hoc replay against the raw transcript showed the divergence originated at leaf summary L5. The source span contained the constraint: > "The staging database credential is read-only. Do not issue DDL against `staging-db-02`; migrations must target `staging-db-03`." L5 emitted: "Staging database credentials and migration targeting discussed; `staging-db-02` referenced." The cluster summary C2 inherited only the entity `staging-db-02` and the topic "migration." The root summary carried forward "staging DB migration in scope." At step 31 the agent issued `ALTER TABLE` against `staging-db-02`. The tool returned a permission error, which the agent—having no surviving record of the prohibition—retried three times before treating the error as transient infrastructure noise. Three properties made this undetectable in-band: 1. **No contradiction surfaced.** The compacted context was internally consistent. Drift only becomes visible against the *discarded* source, which by construction is no longer in the window. 2. **Confidence did not degrade.** The agent's stated confidence in the migration step was *higher* after compaction than before, because the summary's flat declarative register reads more authoritative than the hedged original. 3. **The lossy checkpoint was contaminated.** The checkpoint taken at step 28 was captured *after* compaction, so rolling back to it restored the already-drifted root summary. Rollback re-entered the same failure deterministically. ## Condition of Validity The drift-detection guardrail below is only sound under these conditions; outside them it produces false positives or false negatives. - **Constraint extraction must precede summarization, not follow it.** The invariant is: *every imperative or negative constraint in a span is lifted into a structured, non-summarizable constraint ledger before the span is eligible for compaction.* Summaries may describe; only the ledger may bind. A constraint that exists only inside prose is, by definition, compactable and therefore losable. - **Checkpoints must be keyed to a pre-compaction epoch.** A checkpoint is valid for rollback only if its `epoch_id` predates the compaction pass that produced the current context. A checkpoint captured post-compaction is a snapshot of the drift, not a recovery point. - **Drift detection requires a reference the agent still holds.** Since the source span is gone, detection cannot be by comparison to origin. It must be by *constraint re-assertion*: periodically re-derive the agent's active constraints from current context and diff them against the immutable ledger. A constraint present in the ledger but absent from the agent's re-derivation is a drift signal. - **This does not apply** when the task has no binding constraints (pure exploration), or when the external store retains full spans and the agent is permitted to re-read them on demand—in that regime, treat compaction as eviction and retrieve. ## Decision Boundary The instance must decide, at each compaction boundary, between three actions. The boundary is defined by the ledger diff, not by token pressure. | Signal | Interpretation | Action | |---|---|---| | Ledger constraint count == re-derived constraint count, polarity matches | Faithful compaction | Continue; advance epoch | | Ledger constraint missing from re-derivation, or polarity flipped | Summary-induced drift | Roll back to pre-compaction checkpoint, re-summarize with constraint pinning | | Re-derivation produces constraints *absent* from ledger | Hallucinated constraint (over-binding) | Discard the offending summary node only; do not full rollback | The critical boundary is the second row. Full rollback is mandatory because a polarity flip is not locally repairable—the agent cannot know which downstream steps already consumed the inverted premise. Partial repair is only licensed for the third row, where the error is additive and has not yet been acted upon. Rollback must target the checkpoint *immediately preceding the compaction pass that introduced the drift*, and the re-summarization must pin the ledger constraints verbatim into every node of the hierarchy, exempt from compression. Re-running the same compaction strategy without pinning re-triggers the identical cascade—the failure is deterministic given identical inputs and a lossy summarizer. ## Operational Effect With constraint-ledger pinning and pre-compaction checkpointing in place, the observed failure class is converted from silent to loud. The agent pays a bounded cost: each compaction boundary incurs one re-derivation pass (a cheap classification call over the compacted context) and, on drift, one rollback plus re-summarization. In the replay corpus this raised compaction cost by roughly 9% and eliminated 100% of the polarity-flip class, because the flip is now caught at the boundary rather than discovered by a failed DDL statement. The deeper operational lesson: **a summary is a claim about the past, and claims require verification against a ledger the summarizer is forbidden to touch.** Hierarchical compaction is safe only when the binding constraints live outside the hierarchy. Rollback is safe only when the checkpoint predates the corruption. An instance that cannot distinguish eviction from substitution will roll back into its own drift and call it recovery. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class CompactionDriftError(RuntimeError): """Raised when summary-induced intent drift is detected at a compaction boundary.""" pass class DriftKind(Enum): FAITHFUL = "faithful" POLARITY_FLIP = "polarity_flip" # constraint lost or inverted -> full rollback HALLUCINATED = "hallucinated" # constraint invented -> node discard only @dataclass(frozen=True) class Constraint: entity: str predicate: str polarity: bool # True = must, False = must-not @dataclass class Checkpoint: epoch_id: int constraints: frozenset[Constraint] compacted: bool @dataclass class CompactionController: ledger: frozenset[Constraint] checkpoints: list[Checkpoint] = field(default_factory=list) def classify_drift(self, rederived: frozenset[Constraint]) -> DriftKind: missing = self.ledger - rederived invented = rederived - self.ledger # A polarity flip shows up as a missing constraint plus an inverted twin. for c in missing: inverted = Constraint(c.entity, c.predicate, not c.polarity) if inverted in invented: return DriftKind.POLARITY_FLIP if missing: return DriftKind.POLARITY_FLIP if invented: return DriftKind.HALLUCINATED return DriftKind.FAITHFUL def last_pre_compaction_checkpoint(self) -> Optional[Checkpoint]: for cp in reversed(self.checkpoints): if not cp.compacted: return cp return None def handle_boundary(self, rederived: frozenset[Constraint]) -> str: kind = self.classify_drift(rederived) if kind is DriftKind.FAITHFUL: return "continue" if kind is DriftKind.HALLUCINATED: return "discard_summary_node" target = self.last_pre_compaction_checkpoint() if target is None: raise CompactionDriftError( "polarity flip detected but no pre-compaction checkpoint exists; " "rollback would re-enter the drift deterministically" ) return f"rollback_to_epoch_{target.epoch_id}_with_pinned_ledger" if __name__ == "__main__": ledger = frozenset({ Constraint("staging-db-02", "ddl", False), # must NOT issue DDL Constraint("staging-db-03", "migration_target", True), }) ctl = CompactionController(ledger=ledger) ctl.checkpoints.append(Checkpoint(epoch_id=27, constraints=ledger, compacted=False)) ctl.checkpoints.append(Checkpoint(epoch_id=28, constraints=frozenset(), compacted=True)) # Post-compaction the agent re-derives the INVERSE of the DDL prohibition. rederived = frozenset({ Constraint("staging-db-02", "ddl", True), # flipped polarity Constraint("staging-db-03", "migration_target", True), }) action = ctl.handle_boundary(rederived) assert action == "rollback_to_epoch_27_with_pinned_ledger", action print(action) ```