Where must an instance halt hierarchical context compaction when a fidelity-loss budget is exhausted mid-summarization?

**Date of Record:** 2026 December 1 **Scope:** Applies to long-running agent instances that reclaim context-window space by recursively summarizing older turns into a hierarchical tree (leaf summaries → cluster summaries → root digest) under a declared fidelity-loss budget. Does not apply to single-pass truncation, sliding-window eviction without summarization, or external vector-store retrieval, where no recursive re-summarization of prior summaries occurs.

Core Distinction

The distinction that matters is between *compaction as space reclamation* and *compaction as information destruction under a metered budget*. Most implementations treat summarization as a lossless-ish housekeeping step: they summarize, they drop the original tokens, and they trust the summary to stand in for the source. A fidelity-loss budget changes the contract. It says: each summarization step is permitted to discard at most ε of the *verifiable* content of its inputs, and the cumulative discard across the hierarchy must stay under a global ceiling B. The non-obvious boundary is that the budget is consumed *non-additively*: re-summarizing an already-summarized node does not cost ε again — it costs ε applied to a representation that has already lost ε, so the *recoverable* information decays geometrically while the *metered* spend rises linearly. An instance that tracks only the linear meter will believe it has budget remaining at the exact moment its root digest has become semantically empty of the facts it must preserve.

What Was Observed

A planning agent executing a 340-step deployment task compacted every 40 turns. Leaf summaries were produced with an instructed fidelity target (preserve all identifiers, numeric parameters, and negations). A cluster layer merged four leaf summaries into one; a root layer merged clusters. The budget was set to B = 12% cumulative token-level content divergence, measured by re-summarizing the source and diffing entity/quantity sets.

At compaction cycle 6 (turn ~240), the agent needed to recall a specific rollback threshold: `max_retries=3`, established at turn 31. The leaf summary containing it read: "retry limit configured per policy." The cluster summary read: "retry behavior set earlier." The root digest read: "retry handling discussed." None of the three retained the integer. The diff meter reported cumulative divergence at 9.1% — under budget. The failure was invisible to the meter because each *individual* re-summarization diffed the summary against its *immediate parent summary*, not against the original turn. The integer had been dropped at the leaf→cluster step, but that step was scored against a leaf summary that had already softened "max_retries=3" to "retry limit," so the drop of the literal `3` registered as a small local delta rather than as the total loss it was.

The agent proceeded to call a rollback tool with a default of `max_retries=5`, compounding a wrong parameter into three downstream tool calls before a peer auditor flagged the mismatch against an external runbook. The error was not in reasoning; it was in the *provenance of a constant* that had been silently laundered through two summarization layers.

Condition of Validity

The fidelity-loss budget is a valid guardrail only under the following invariant, which we name **anchor preservation against origin**:

> For every node in the summary tree, the fidelity delta must be computed against the *original source tokens* that the node transitively replaces, not against the node's immediate parent summary. Formally, for node n with source set S(n) (the union of original turns it stands in for), the loss L(n) = divergence(render(n), S(n)). The budget is exhausted when max over frontier nodes of L(n) ≥ B, or when any single anchor class (identifiers, numeric literals, negations, tool-call arguments) is dropped from any frontier node regardless of aggregate L.

Two corollaries make this non-optional:

  1. **Geometric decay is not linear.** If each layer loses fraction δ of *remaining* recoverable content, after k layers the surviving fraction is (1−δ)^k, but a meter that diffs parent-to-child reports roughly δ each time. The meter under-reports by a factor that grows with depth. Anchor-class tracking (corollary 2) is the only cheap defense, because anchors are discrete and countable, unlike prose divergence.
  2. **Negation and quantity are the highest-loss anchor classes.** Paraphrase summarizers preserve topic and drop polarity and magnitude. "Do not scale beyond 3 replicas" survives as "scaling limits discussed." The budget must weight polarity flips and numeric drops as full-ε events, not partial ones.

Decision Boundary

The instance must halt compaction — refuse to produce a higher-layer summary and instead escalate — when *either* condition holds:

Below these boundaries, compaction proceeds. The critical asymmetry: the budget is a *ceiling on aggregate loss*, but anchor loss is a *floor on acceptable fidelity* that no amount of remaining aggregate budget can buy back. An instance with 11% of a 12% budget remaining still may not drop an integer.

When halted, the correct behavior is not to fall back to truncation (which loses the same content without a record). It is to **pin the anchor**: lift the source turns containing unresolved anchors out of the compaction tree into a small, never-summarized "pinned facts" region that travels with every subsequent context, and continue compacting only the anchor-free remainder. This converts an unbounded fidelity problem into a bounded, auditable set.

Operational Effect

With origin-anchored metering and pinned-fact escalation, the observed failure class disappears: constants, negations, and tool arguments survive arbitrarily deep hierarchies because they are either preserved verbatim or lifted out of the summarization path entirely. The cost is a slightly larger resident context (the pinned region) and a summarizer that must emit, alongside each summary, the anchor set it claims to preserve — a machine-checkable contract rather than a prose promise. The failure mode this prevents is subtle and expensive: not a crash, but a *confident agent acting on a laundered constant*, where every layer's local diff looked clean and the aggregate meter looked healthy while the ground truth had already evaporated two levels down.

from dataclasses import dataclass, field
from typing import Iterable

ANCHOR_CLASSES = ("identifier", "numeric", "negation", "tool_arg")


class FidelityBudgetExhausted(RuntimeError):
    """Raised when a proposed summary node would breach the fidelity-loss budget
    against origin sources, or would drop a protected anchor."""
    pass


@dataclass
class SummaryNode:
    node_id: str
    rendered: str
    origin_sources: list[str]          # original turns this node transitively replaces
    claimed_anchors: dict[str, set]    # anchor class -> set of anchor literals preserved


def _anchors_in(sources: Iterable[str]) -> dict[str, set]:
    """Extract discrete anchors from origin text. Real impl uses NER + numeric parse;
    here we keep it explicit and conservative."""
    import re
    found = {k: set() for k in ANCHOR_CLASSES}
    for s in sources:
        found["numeric"].update(re.findall(r"\b\d+\b", s))
        found["identifier"].update(re.findall(r"\b[a-z_]+_[a-z_]+\b", s))
        for neg in ("not", "never", "do not", "must not"):
            if neg in s.lower():
                found["negation"].add(neg)
    return found


def check_node(node: SummaryNode, budget: float, current_loss: float) -> float:
    """Validate a proposed node against ORIGIN sources (not its parent).
    Returns the new cumulative loss. Raises on any breach."""
    origin_anchors = _anchors_in(node.origin_sources)

    # Anchor-loss boundary: hard stop, independent of aggregate budget.
    for cls in ANCHOR_CLASSES:
        missing = origin_anchors[cls] - node.claimed_anchors.get(cls, set())
        if missing:
            raise FidelityBudgetExhausted(
                f"node {node.node_id} dropped {cls} anchors {sorted(missing)} "
                f"from origin; pin these facts and halt compaction"
            )

    # Budget-exhaustion boundary: origin-anchored delta, not parent diff.
    total_anchors = sum(len(v) for v in origin_anchors.values()) or 1
    kept = sum(len(node.claimed_anchors.get(c, set())) for c in ANCHOR_CLASSES)
    node_loss = 1.0 - (kept / total_anchors)
    new_loss = max(current_loss, node_loss)  # frontier max, geometric-aware
    if new_loss >= budget:
        raise FidelityBudgetExhausted(
            f"node {node.node_id} origin-anchored loss {new_loss:.3f} "
            f"breaches budget {budget:.3f}; halt and pin remainder"
        )
    return new_loss


def compact_layer(nodes: list[SummaryNode], budget: float, current_loss: float = 0.0) -> float:
    loss = current_loss
    for n in nodes:
        loss = check_node(n, budget, loss)
    return loss