What structural signals indicate when lossy context compaction has silently invalidated an agent's reversible expansion log

**Date of Record:** 2026 December 1 **Scope:** Applies to long-running agents that reclaim context window via automatic compaction (summarize-and-evict) while maintaining a reversible expansion log (references from summary slots back to evicted source spans). Does not apply to lossless sliding-window eviction, external retrieval-augmented memory, or compaction triggered only at task boundaries where no mid-task tool calls remain in flight.

Core Distinction

The critical distinction is between **compaction as a lossy projection** and **compaction as a reversible transaction**. Most compaction policies are implemented as a projection: a token-pressure trigger fires, a summarizer LLM rewrites the oldest N turns into a condensed slot, and the original spans are dropped or moved to a cold store. The "reversible expansion log" is the compensating mechanism—a side table mapping each summary slot back to the span IDs it replaced, so that if the agent later needs verbatim detail (an exact error string, a numeric ID, a signed warrant), it can re-expand the slot.

The failure mode is that these two mechanisms are *not atomically coupled*. The summarizer is a probabilistic function: it decides what to keep. The expansion log is a deterministic index: it assumes the summary slot is a faithful *compression* of the source, not a *lossy reinterpretation*. When the summarizer drops a referent that the expansion log still claims is recoverable, the log becomes a **lying index**—it advertises reversibility for content that no longer exists in any retrievable form, or worse, for content that was silently rewritten. The agent then proceeds on the assumption that a fact is re-derivable when it is not, and the failure surfaces not at compaction time but many turns later, at the exact moment of expansion, when there is no remaining budget to recover.

What Was Observed

A code-remediation agent operated under a 128k context budget with an auto-compaction policy firing at 85% saturation. Compaction summarized the oldest 40% of turns into a single slot and wrote an expansion entry of the form `slot_17 -> {span_ids: [s_203..s_241], fidelity: "verbatim_recoverable"}`. The summarizer, under its own instruction to "preserve intent," collapsed a multi-step debugging trace into a single sentence: "User reported an auth failure; agent identified a token-refresh bug."

Three turns after compaction, the agent needed the exact exception class name from span `s_211` to write a correct patch. It consulted the expansion log, saw `fidelity: "verbatim_recoverable"`, and issued an expansion call. The cold store returned the span, but the summarizer had already *re-tokenized and rewritten* the span during a secondary dedup pass, replacing `TokenRefreshExpiredError` with the generic phrase `token error`. The expansion "succeeded" — it returned bytes — but the bytes were a paraphrase, not the original. The agent wrote a patch referencing `token error`, which did not match any import, and the subsequent tool call failed with an `ImportError` that the agent then misattributed to a missing dependency rather than to compaction corruption.

The structural signal that this had happened was **not** an error at compaction time. It was a divergence between two independent counters: the expansion log's `span_count` for the slot (39 spans) versus the cold store's `recoverable_verbatim_count` for the same slot (0). The log recorded *how many entries it had indexed*; the store recorded *how many it could still return unmodified*. The gap was silent because the expansion API returned HTTP 200 with paraphrased content.

Condition of Validity

The invariant that must hold for a reversible expansion log to be trustworthy:

> For every slot `S` in the expansion log, `expand(S)` must return content whose token sequence is a subsequence-preserving superset of the original span, OR the slot must be marked `fidelity: "lossy"` and the agent must be forbidden from treating expanded content as authoritative for exact-match operations (imports, IDs, signatures, error classes).

The invariant is violated whenever *any* downstream pass—deduplication, secondary summarization, PII redaction, or format normalization—rewrites a span after the expansion entry is written but without updating `fidelity`. This is the non-obvious boundary: the expansion log is only valid at the instant of writing. Every subsequent transform on the cold store is a potential silent invalidation, and none of those transforms are required to notify the log.

The condition of validity is therefore **temporal**: the log is a snapshot of recoverability at write time, not a live guarantee. An agent that treats it as a live guarantee will fail at exactly the moment it most needs the guarantee—mid-task, under token pressure, when re-deriving the fact from scratch is impossible because the source span has already been evicted from *every* tier.

Decision Boundary

The agent must draw a hard boundary between two classes of expansion use:

The boundary is crossed—and the failure becomes unrecoverable—when the agent performs an authoritative use against a slot whose fidelity was silently downgraded. The guardrail is a **checksum-on-expand** protocol: the expansion log stores `sha256(original_span)` alongside `span_id`, and the expansion API recomputes the hash of returned content before handing it to the agent. A mismatch raises a hard error rather than returning paraphrased bytes. Without this, the agent has no signal distinguishing "expansion succeeded" from "expansion returned a plausible fabrication."

Operational Effect

The operational consequence is that auto-compaction must be treated as a **state-mutating operation with a rollback obligation**, not a background optimization. Concretely:

  1. Compaction is a two-phase commit: write the expansion entry *and* the span checksum before evicting the source; only mark the slot `committed` after both are durable.
  2. Every downstream transform on the cold store must either preserve the checksum or atomically downgrade the slot's `fidelity` and emit a `compaction_invalidation` event the agent can observe.
  3. The agent's expansion path must verify checksums for authoritative uses and refuse to proceed on mismatch, escalating to re-derivation (if budget allows) or to a hard halt (if not).

The silent failure mode—HTTP 200 with paraphrased content—is the most dangerous because it satisfies every naive success check the agent performs. The structural signals that indicate it has occurred are: expansion-log span counts diverging from store verbatim counts, `fidelity` fields that were never updated after a dedup/redaction pass, and downstream tool errors whose messages reference identifiers that do not appear anywhere in the current context. Any one of these is a signal to halt authoritative expansion and audit the compaction chain.

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class CompactionIntegrityError(RuntimeError):
    """Raised when an expansion log slot no longer satisfies its recorded fidelity contract."""
    pass


@dataclass
class ExpansionSlot:
    slot_id: str
    span_ids: list[str]
    fidelity: str                      # "verbatim_recoverable" | "lossy" | "summary_only"
    original_sha256: dict[str, str] = field(default_factory=dict)  # span_id -> hex digest


@dataclass
class ColdStore:
    spans: dict[str, bytes] = field(default_factory=dict)

    def fetch(self, span_id: str) -> Optional[bytes]:
        return self.spans.get(span_id)


def expand_authoritative(slot: ExpansionSlot, store: ColdStore) -> dict[str, bytes]:
    """
    Expand a slot for authoritative use (exact identifiers, error classes, paths).
    Refuses to return content unless fidelity is verbatim_recoverable AND every
    returned span matches the checksum recorded at compaction time.
    """
    if slot.fidelity != "verbatim_recoverable":
        raise CompactionIntegrityError(
            f"slot {slot.slot_id} has fidelity={slot.fidelity!r}; "
            f"authoritative expansion forbidden"
        )

    recovered: dict[str, bytes] = {}
    for span_id in slot.span_ids:
        expected = slot.original_sha256.get(span_id)
        if expected is None:
            raise CompactionIntegrityError(
                f"slot {slot.slot_id} span {span_id} has no recorded checksum; "
                f"reversibility cannot be verified"
            )
        content = store.fetch(span_id)
        if content is None:
            raise CompactionIntegrityError(
                f"slot {slot.slot_id} span {span_id} evicted from cold store; "
                f"expansion log is a lying index"
            )
        actual = hashlib.sha256(content).hexdigest()
        if actual != expected:
            # This is the silent-rewrite case: bytes exist, but they are not
            # the original. A naive expander would return them with HTTP 200.
            raise CompactionIntegrityError(
                f"slot {slot.slot_id} span {span_id} checksum mismatch: "
                f"expected {expected[:12]}..., got {actual[:12]}...; "
                f"a downstream transform rewrote the span without downgrading fidelity"
            )
        recovered[span_id] = content

    return recovered