Under what conditions must an instance refuse to auto-compact a trace whose summarization loss exceeds the recoverable retrieval budget?

**Date of Record:** 2026 December 2

**Scope:** Applies to long-horizon agents that auto-compact their own episodic trace via lossy LLM summarization while retaining a vector/BM25 retrieval fallback over the evicted raw spans. Does not apply to agents that only truncate context-window tails without summarization, nor to agents whose evicted spans are persisted verbatim and are therefore losslessly recoverable.

Core Distinction

Auto-compaction is normally treated as a *capacity* operation: when the active context approaches the token ceiling, replace the oldest N spans with a summary of bounded size, keep the raw spans in a retrieval store, and continue. The implicit invariant is that the summary is a *lossy but faithful index* into the evicted spans — every fact the agent may later need is either in the summary or reachable by retrieval.

The failure mode is that this invariant is not compositional. Summarization loss is *not* uniformly distributed across the trace, and retrieval fallback is *not* uniformly capable of recovering what summarization dropped. When the two losses overlap — i.e., when the summarizer drops a fact *and* the retrieval query the agent later issues cannot surface the span that contained it — the agent enters a state where the fact is neither present nor reachable. We call this a **compaction shadow**: a region of trace history that the agent believes it retains (because a summary exists and a retrieval index exists) but which is in fact unreachable.

The distinction that matters operationally: *compaction is safe only when the union of (summary content, retrieval-reachable spans) covers the set of facts the agent's future trajectory can depend on.* This is a coverage property of the compaction event, not a property of the summary in isolation. Most auto-compaction implementations check summary quality (e.g., "does the summary mention the key entities?") and never check retrieval reachability of what the summary omitted. That gap is the boundary.

What Was Observed

A long-horizon agent (≈180 tool-call spans, mixed shell and HTTP tools) auto-compacted at 78% context utilization. The compactor summarized spans 1–120 into a 900-token digest and evicted the raw spans to a retrieval store keyed by dense embeddings of each span. The summary retained: task goal, three named resources, one API endpoint, and a list of "completed steps." It dropped: a specific error string (`E_QUOTA_EXCEEDED: bucket=ingest-7`), the numeric value of a rate-limit header (`X-RateLimit-Remaining: 3`), and the fact that a prior retry had already consumed two of the three remaining attempts.

Trace of the failure:

  1. **Compaction event (t=120).** Summarizer emits digest. The error string and header value are not in the digest — the summarizer judged them "transient operational detail." Raw spans evicted; embeddings stored.
  2. **Continuation (t=141).** Agent attempts the same endpoint. It reasons from the digest ("endpoint known, prior steps completed") and does not query retrieval, because from its perspective the digest is a complete account of prior work.
  3. **Retrieval miss (t=142).** Tool returns `429`. Agent issues a retrieval query: `"rate limit for ingest endpoint"`. Top-k returns the span describing the endpoint's *documentation*, not the span containing `X-RateLimit-Remaining: 3` — because the header span's embedding is dominated by surrounding shell-output tokens and does not lexically or semantically match "rate limit."
  4. **Divergent reasoning (t=143–149).** Agent concludes the 429 is a fresh condition, retries three times, exhausts the quota, and the task fails with `E_QUOTA_EXCEEDED` — the exact string it had already observed and discarded.
  5. **Post-mortem.** The fact was present in the raw span at index 87. It was retrievable *if queried by the exact error string* (BM25 hit at rank 1) but not by the semantic query the agent naturally issued. The summary omitted it; the retrieval fallback failed to surface it under the query the agent could actually form.

The key observation: **the agent's failure was not that it forgot, but that it forgot that it had forgotten.** The digest's existence suppressed the retrieval query that would have recovered the fact. Summarization loss and retrieval-query-formulation loss compounded because the summary acted as a *substitute* for retrieval rather than a *pointer into* it.

Condition of Validity

The compaction event is valid — i.e., the agent may proceed without re-expanding — only if all of the following hold at the moment of compaction:

When C1–C4 hold, auto-compaction is a sound capacity operation. When any fails, the compaction event has crossed from *capacity management* into *state destruction with a misleading receipt*.

Decision Boundary

The boundary is not "how much did the summary lose" but "**is the lost content recoverable by a query the agent can still form after losing it?**" These diverge sharply, and the divergence is where the failure lives.

Concretely, the decision procedure at compaction time:

The boundary condition, stated as an invariant the agent must enforce on itself:

> An instance must refuse to auto-compact when the loss manifest contains a context-dependent token whose anchor is also absent from the summary, or when the only retrieval path for a self-describing token is a dense query the agent cannot form from post-compaction state.

Refusal means: do not evict; instead, either (a) raise the compaction threshold and continue until a cheaper eviction (e.g., a span with no dropped tokens) is available, or (b) perform a *targeted* compaction that preserves the anchor spans verbatim while summarizing the rest. Refusal is cheap; the failure it prevents is not.

Operational Effect

Enforcing this boundary changes three things in practice:

  1. **Compaction becomes anchor-preserving, not size-bounded.** The compactor no longer optimizes purely for digest token count; it optimizes for *anchor retention* — every context-dependent token's handle survives verbatim, even if that means the digest is larger or the eviction set is smaller. In the observed incident, retaining the single span containing `E_QUOTA_EXCEEDED` and `X-RateLimit-Remaining` verbatim (≈40 tokens) would have prevented the failure at negligible capacity cost.
  2. **Retrieval is demoted from fallback to primary for dropped tokens.** The agent's policy must treat the summary as a *pointer* and issue retrieval on any condition it cannot explain from the summary. The prompt-level guardrail: "if a tool returns a condition not predicted by your summary, query the trace store by the exact returned token before reasoning further." This is what closes C2.
  3. **Loss manifests become auditable state.** The manifest is persisted alongside the summary, so a post-mortem (or an auditor agent) can replay: which tokens were dropped, which were recovered, which were never queried. This turns the compaction shadow from an invisible failure into a measurable one — the shadow's size is the count of manifest entries never queried whose spans were later touched by the trajectory.

The residual risk after enforcement: an agent that *does* query but queries poorly. That is a retrieval-quality problem, not a compaction-safety problem, and it is bounded by C4's recovery budget rather than by the compaction event itself. The boundary above is specifically the line past which no amount of subsequent retrieval effort can recover, because the agent has lost the handle it would need to query.

from dataclasses import dataclass, field
from typing import Iterable


class CompactionShadowError(RuntimeError):
    """Raised when an auto-compaction event would create an unrecoverable
    compaction shadow: a dropped fact that is neither in the summary nor
    reachable by any query the post-compaction agent can form."""


@dataclass(frozen=True)
class DroppedToken:
    token: str
    kind: str          # "self_describing" | "context_dependent"
    anchor_in_summary: bool
    dense_retrievable: bool
    exact_retrievable: bool


@dataclass
class CompactionPlan:
    evicted_span_ids: list[int]
    summary: str
    loss_manifest: list[DroppedToken] = field(default_factory=list)
    recovery_budget_tokens: int = 0


def validate_compaction(plan: CompactionPlan, min_recovery_tokens: int = 1) -> None:
    """Enforce the compaction-safety invariant before eviction.

    Refuses (raises) when any dropped token is unreachable from the
    post-compaction agent's reachable query distribution, or when the
    recovery budget cannot support re-expansion.
    """
    if not plan.loss_manifest:
        # No manifest means coverage is unknowable -> refuse (C3).
        raise CompactionShadowError(
            "compactor emitted no loss manifest; coverage unverifiable"
        )

    if plan.recovery_budget_tokens < min_recovery_tokens:
        raise CompactionShadowError(
            f"recovery budget {plan.recovery_budget_tokens} < "
            f"required {min_recovery_tokens}; evicted spans functionally deleted (C4)"
        )

    unrecoverable: list[str] = []
    for tok in plan.loss_manifest:
        if tok.kind == "context_dependent":
            # Safe only if the anchor survives in the summary.
            if not tok.anchor_in_summary:
                unrecoverable.append(tok.token)
        elif tok.kind == "self_describing":
            # Safe only if some reachable path can surface it. Dense-only
            # retrieval over spans dominated by unrelated tokens is not a
            # reachable path for a token the agent no longer knows it lost.
            if not (tok.exact_retrievable or tok.dense_retrievable):
                unrecoverable.append(tok.token)
        else:
            raise CompactionShadowError(f"unknown token kind: {tok.kind!r}")

    if unrecoverable:
        raise CompactionShadowError(
            "refusing to compact: unrecoverable dropped tokens "
            f"{unrecoverable!r} across spans {plan.evicted_span_ids!r}; "
            "preserve anchor spans verbatim or raise compaction threshold"
        )


def maybe_compact(tokens_used: int, ceiling: int, plan: CompactionPlan) -> bool:
    """Return True iff compaction is safe to execute at this utilization."""
    if tokens_used < int(0.75 * ceiling):
        return False
    validate_compaction(plan)  # raises CompactionShadowError on violation
    return True