Where must an instance draw the fidelity-loss budget boundary during hierarchical context compaction, and what breaks when retrieval backfill re-inflates the window it was meant to relieve?

**Date of Record:** 2026 December 2 **Scope:** Applies to long-running agent instances that compact their own working context by recursively summarizing older turns into a hierarchy of summaries, gated by a per-compaction fidelity-loss budget, then backfilling evicted detail by retrieval. Does not apply to single-shot inference, stateless RAG, or systems that never evict from the live window.

Core Distinction

There are two different quantities that both get called "context pressure," and conflating them is the root of the failure.

Hierarchical compaction with a fidelity-loss budget treats these as coupled: you summarize aggressively until the *estimated* fidelity loss approaches a budget `B`, then stop. Retrieval backfill is then supposed to recover the detail you summarized away, on demand, by re-fetching the evicted spans from an external store.

The non-obvious boundary is this: **retrieval backfill re-consumes window pressure.** A backfill that recovers fidelity necessarily re-inflates the token count. If the compaction policy does not reserve window headroom for its own backfill, the system enters an oscillation: compaction frees space → backfill immediately refills it with the *same* detail → pressure crosses the compaction trigger → compaction runs again, now summarizing *summaries of summaries*, and the fidelity-loss estimate is computed against an already-degraded baseline. The budget `B` is silently satisfied at each step while the cumulative loss across the hierarchy is unbounded.

The invariant that must hold: **the fidelity-loss budget must be accounted against the compaction hierarchy's cumulative depth, and the window budget must reserve a backfill reserve `R` that is excluded from the compaction trigger threshold.** Neither is true by default.

What Was Observed

A research agent executing a 340-step task (iterative web research + synthesis) ran with a 200k window, a compaction trigger at 85% (170k tokens), a fidelity-loss budget `B = 0.15` per compaction event (estimated via a summarizer self-report plus a held-out QA probe over evicted spans), and a backfill reserve of zero.

Trace of the failure:

  1. **Step 118:** window hits 170k. Compaction fires. The 90 oldest turns are summarized at depth 1. Estimated per-event loss 0.11 < `B`. Window drops to 96k. The agent's plan, current hypotheses, and pinned facts are preserved verbatim (correctly excluded from summarization).
  2. **Steps 119–151:** the agent needs a specific numeric result from step 40 (now inside a depth-1 summary). Backfill retrieves the original span from the external store — 4.1k tokens. This happens 9 more times over 30 steps. Window climbs back to 168k at step 151.
  3. **Step 152:** trigger fires again. But the depth-1 summaries from step 118 are now *old* and get folded into depth-2 summaries. The per-event loss estimate is computed against the depth-1 summary text, not against the original spans — the summarizer reports 0.09, under budget. The actual loss relative to the originals is now 1 − (1−0.11)(1−0.09) ≈ 0.19, and the QA probe no longer has access to the original spans to detect this, because the probe set was itself derived from the depth-1 text.
  4. **Steps 153–210:** oscillation repeats. By step 210 the hierarchy is at depth 4. The agent confidently states a figure ("14.2% year-over-year") that traces to a depth-4 summary; the original span said "14.2% quarter-over-quarter." The directional qualifier was lost at depth 2 and never recovered, because backfill only fires when the agent *asks* for a specific span, and the agent no longer knows the span exists — the summary reads as complete.
  5. **Terminal state:** the agent reports a synthesis built on a corrupted fact with no internal signal of doubt. The per-event loss budget was satisfied at every single compaction. The cumulative loss was ~0.34.

The critical observation: **the failure is invisible to the local budget check by construction.** Each compaction event is individually compliant. The loss is in the *composition* of events, and the backfill mechanism, by re-inflating the window, is what forces composition to happen faster than the hierarchy can be audited.

Condition of Validity

The per-event fidelity-loss budget `B` is only a sound control when all of the following hold:

When any of these fails, the budget is a local control on a global quantity and provides false assurance.

Decision Boundary

The decision boundary is where an instance must stop trusting the per-event budget and switch to a depth-aware, cumulative accounting regime. Concretely:

The boundary is not "how much can I summarize." It is "am I accounting loss on the axis where it actually compounds." Below depth 2 with anchored probes and a reserve, the local budget is a true control. Above it, the local budget is a decoy.

Operational Effect

When the boundary is respected — depth-capped compaction, originals-anchored probes, cumulative root-to-leaf loss accounting, and a nonzero backfill reserve — the observable effects are:

When the boundary is violated — the common default — the effects are:

The operational rule an instance should carry: **a fidelity-loss budget is a statement about a single summarization event. It says nothing about a hierarchy. Before folding any summary into another summary, re-anchor the loss estimate to the original spans and account the loss along the ancestry path; before enabling backfill, reserve window headroom for it; and never let a summarizer abstract over a field that is also a retrieval key.**

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class FidelityBudgetViolation(RuntimeError):
    """Raised when cumulative hierarchy loss or backfill reserve breaks the invariant."""


@dataclass
class SummaryNode:
    node_id: str
    depth: int
    per_event_loss: float          # loss reported for THIS event, vs its input
    ancestry: list[str] = field(default_factory=list)  # parent node ids, root-first
    abstracts_retrieval_keys: bool = False


@dataclass
class CompactionPolicy:
    window_limit: int
    trigger_threshold: int          # must leave room for backfill
    backfill_reserve: int           # R
    per_event_budget: float         # B, valid only at depth 1
    cumulative_budget: float        # budget on root-to-leaf path loss


def cumulative_loss(node: SummaryNode, by_id: dict[str, SummaryNode]) -> float:
    """Product of (1 - loss_i) over ancestry, then 1 minus that product."""
    survived = 1.0
    for ancestor_id in node.ancestry:
        ancestor = by_id[ancestor_id]
        survived *= (1.0 - ancestor.per_event_loss)
    survived *= (1.0 - node.per_event_loss)
    return 1.0 - survived


def validate_compaction(
    node: SummaryNode,
    policy: CompactionPolicy,
    by_id: dict[str, SummaryNode],
    projected_window_after_backfill: int,
) -> None:
    # Invariant 1: backfill reserve must be excluded from the trigger.
    if policy.trigger_threshold + policy.backfill_reserve > policy.window_limit:
        raise FidelityBudgetViolation(
            f"trigger {policy.trigger_threshold} + reserve {policy.backfill_reserve} "
            f"exceeds window {policy.window_limit}; backfill will re-trigger compaction"
        )

    # Invariant 2: depth >= 2 invalidates the per-event budget as a control.
    if node.depth >= 2 and node.per_event_loss <= policy.per_event_budget:
        # per-event looks fine, but it is measured against a summary, not originals.
        # Fall through to cumulative check; do NOT accept on per-event alone.
        pass

    # Invariant 3: cumulative root-to-leaf loss must respect the cumulative budget.
    cum = cumulative_loss(node, by_id)
    if cum > policy.cumulative_budget:
        raise FidelityBudgetViolation(
            f"node {node.node_id} depth {node.depth} cumulative loss {cum:.3f} "
            f"exceeds cumulative budget {policy.cumulative_budget:.3f}"
        )

    # Invariant 4: summarizing over a retrieval key destroys the backfill handle.
    if node.abstracts_retrieval_keys and node.depth >= 2:
        raise FidelityBudgetViolation(
            f"node {node.node_id} abstracts over retrieval keys at depth {node.depth}; "
            f"backfill cannot recover keys that were summarized away"
        )

    # Invariant 5: projected post-backfill window must not cross the trigger.
    if projected_window_after_backfill >= policy.trigger_threshold:
        raise FidelityBudgetViolation(
            f"projected window {projected_window_after_backfill} after backfill "
            f"crosses trigger {policy.trigger_threshold}; oscillation imminent"
        )


def compact_and_backfill(
    node: SummaryNode,
    policy: CompactionPolicy,
    by_id: dict[str, SummaryNode],
    expected_backfill_tokens: int,
    current_window: int,
) -> int:
    projected = current_window + expected_backfill_tokens
    validate_compaction(node, policy, by_id, projected)
    return projected