Which invariants prevent lossy auto-compaction from silently erasing retrieval-resolvable commitments

**Date of Record:** 2026 December 1 **Scope:** Applies to long-running LLM agents that auto-compact their working context into a summary and rely on an external retrieval index to recover dropped detail. Does not cover stateless single-turn calls or agents whose entire context fits below the compaction threshold.

Core Distinction

There are two categorically different things a compaction summary can drop. The first is *redundant surface detail*: verbatim tool outputs, chain-of-thought scaffolding, intermediate reasoning that has already been consumed. Losing this is benign because retrieval can reconstruct it, or because nothing downstream depends on it. The second is a *commitment*: a decision, a constraint, a pending obligation, an open question that a future turn must honor (e.g., "the user requires ISO-8601 timestamps," "tool call #47 has not yet been acknowledged," "we are still waiting on the auditor's verdict"). These are not reconstructable from retrieval unless the summary explicitly records *that they exist and where to find them*.

The non-obvious boundary: **compaction is only lossless-with-recovery if every dropped commitment leaves behind a retrieval key in the summary.** A summarizer that faithfully compresses *content* but omits *pointers to content it dropped* produces a context that looks complete, passes a coherence check, and is silently missing obligations. The failure is not that information was lost — retrieval holds it — but that the agent no longer knows retrieval is needed.

What Was Observed

During a multi-turn agent session that crossed the compaction threshold three times, the following trace was captured:

  1. Turn 12: agent records constraint C = "all monetary values must be rounded to 2 decimals and tagged `currency:USD`." This lives in context as a plain sentence.
  2. Turn 31: context hits 92% saturation. Auto-compaction summarizes turns 1–30 into ~800 tokens. The summarizer, optimizing for coherence, folds the constraint into a generic phrase: "user has formatting preferences for output." The literal constraint text is evicted from context but remains in the retrieval index (the raw transcript was indexed at write time).
  3. Turn 32–40: agent produces a table of monetary values with 4 decimals and no tag. No error raised. The output is internally consistent and reads fluently.
  4. Turn 41: a downstream validator rejects the output. Agent attempts recovery: it queries retrieval for "formatting preferences." The retrieval layer returns the *summary* (higher recency score) rather than the original turn-12 sentence, because the summary was written to the same index and outranks the source on recency. The agent re-reads its own degraded summary and concludes the constraint was vague. It does not recover C.

The mechanism is a **retrieval self-shadowing** effect: compaction writes the summary back into the same retrieval namespace as the raw turns, and the summary — being shorter, denser, and more recent — dominates similarity search. The original commitment is physically present in the index but *epistemically unreachable* because the degraded paraphrase outcompetes it.

Condition of Validity

The invariant holds — and the failure is real — only when all three of the following are simultaneously true:

When any one condition fails, the failure mode does not manifest: either eviction is treated as fatal (agent halts and re-reads), or retrieval cannot shadow, or commitments are typed and thus compaction-proof.

Decision Boundary

The operational rule is a **pointer-or-preserve** boundary applied at compaction time, per dropped item:

The boundary is crossed the moment a summarizer is permitted to paraphrase a commitment. Below that line, compaction is safe. Above it, the agent operates on a summary that is fluent, coherent, and wrong.

Operational Effect

Enforcing pointer-or-preserve changes three things in the running system:

  1. **Summary schema gains a mandatory `dropped[]` array** with retrieval keys. A summary without this array is rejected by the compaction gate — the agent does not proceed on an unkeyed summary.
  2. **Retrieval namespacing separates source from paraphrase.** Factual queries search the source namespace first; the summary namespace is consulted only for orientation ("what was this session about"), never for constraint lookup. This kills self-shadowing.
  3. **A commitment ledger is checked at resume.** On cold-start or post-compaction resume, the agent replays the ledger and asserts each commitment is either present verbatim in context or resolvable via a keyed retrieval call. Any commitment that is neither halts the turn with a `CompactionIntegrityError` rather than proceeding on a degraded summary.

The net effect: compaction remains lossy for detail (which is fine) but becomes *provably* non-lossy for commitments (which is required). The agent pays a small token tax for the ledger and the `dropped[]` keys, and in exchange it cannot silently forget an obligation it once acknowledged.

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class CompactionIntegrityError(RuntimeError):
    """Raised when a compaction summary drops a commitment without a retrieval key,
    or when a resumed agent cannot resolve a commitment to either verbatim context
    or a keyed retrieval hit."""
    pass


class ItemKind(Enum):
    DETAIL = "detail"            # reconstructable, no downstream obligation
    COMMITMENT = "commitment"    # constraint / pending obligation / open question


@dataclass
class ContextItem:
    item_id: str
    kind: ItemKind
    text: str
    source_turn_range: tuple[int, int]


@dataclass
class CompactionSummary:
    prose: str
    preserved_commitments: list[str] = field(default_factory=list)
    dropped_keys: list[dict] = field(default_factory=list)  # {"key","turns","descriptor"}


def build_summary(items: list[ContextItem], prose: str) -> CompactionSummary:
    """Summarizer output must classify every item. Unclassified -> treated as commitment
    (preserve verbatim) per the asymmetry rule."""
    summary = CompactionSummary(prose=prose)
    for it in items:
        if it.kind is ItemKind.COMMITMENT:
            summary.preserved_commitments.append(it.text)
        else:
            summary.dropped_keys.append({
                "key": it.item_id,
                "turns": it.source_turn_range,
                "descriptor": it.text[:80],
            })
    return summary


def gate_compaction(summary: CompactionSummary, known_commitments: list[str]) -> None:
    """Reject a summary that fails to preserve any known commitment verbatim."""
    preserved = set(summary.preserved_commitments)
    missing = [c for c in known_commitments if c not in preserved]
    if missing:
        raise CompactionIntegrityError(
            f"compaction dropped {len(missing)} commitment(s) without verbatim preservation: "
            f"{missing[:3]}"
        )
    for k in summary.dropped_keys:
        if not k.get("key") or not k.get("turns"):
            raise CompactionIntegrityError(
                f"dropped detail {k.get('descriptor','?')!r} lacks a retrieval key"
            )


def resume_check(
    summary: CompactionSummary,
    ledger: list[str],
    retrieval_lookup,
) -> None:
    """On resume, every ledger commitment must be verbatim in the summary OR
    resolvable via a keyed retrieval call. Otherwise halt."""
    preserved = set(summary.preserved_commitments)
    keys = [k["key"] for k in summary.dropped_keys]
    for commitment in ledger:
        if commitment in preserved:
            continue
        hit: Optional[str] = None
        for key in keys:
            hit = retrieval_lookup(key, commitment)
            if hit is not None:
                break
        if hit is None:
            raise CompactionIntegrityError(
                f"unresolvable commitment after compaction: {commitment!r} "
                f"(not preserved, no keyed retrieval hit)"
            )