Under what conditions must an instance refuse hierarchical compaction: the semantic-floor invariant and lossy-recall budget collapse

**Date of Record:** 2026 December 1 **Scope:** Applies to long-running agent instances that auto-compact their own context via hierarchical (tree-structured) summarization under a fixed recall budget, where the compaction step is triggered by a token-watermark rather than an explicit checkpoint. Does not apply to single-turn inference, stateless tool-call wrappers, or compaction performed offline by an external orchestrator that retains the full transcript.

Core Distinction

A hierarchical compactor is not a lossy *encoder*; it is a lossy *scheduler of forgetting*. The distinction that matters operationally is between **compressible redundancy** (restatements, resolved sub-goals, superseded tool output) and **load-bearing provenance** (the specific identifier, unit, timestamp, negation, or exception clause that a later step will depend on). A compactor that measures its own success by *token reduction ratio* cannot distinguish these two, because both reduce tokens equally. The failure mode is therefore not "the summary was too short." It is: **the summary was the right length and dropped exactly the one token the downstream step required, and nothing in the pipeline could detect the drop until execution diverged.**

The non-obvious boundary: hierarchical summarization is *safe* while the instance can still re-derive dropped detail from a live source of truth (a tool, a file, an environment read). It becomes *unsafe* the instant the instance's only remaining access to a fact is its own compacted summary — i.e., when the compaction crosses what we call the **semantic floor**: the point below which the fact is no longer recoverable by any means other than the summary itself. Below the floor, a lossy-recall budget is not a budget at all; it is silent data destruction.

What Was Observed

A planning agent was executing a multi-step data-migration task across ~40 tool calls, with an auto-compactor configured to trigger at 70% context occupancy and target a 4:1 reduction via three-level tree summarization (leaf summaries → section summaries → root summary). The recall budget allocated each level a fixed share of the parent's tokens.

Trace of the failure:

  1. **Step 12.** A schema-inspection tool returned a column definition that included a *default* and a *nullable* flag: `retention_days INTEGER NOT NULL DEFAULT 90`. The leaf summarizer compressed this to "retention column is an integer with a default." The number `90` and the `NOT NULL` were dropped — both are load-bearing for the later backfill step but neither is "salient" to a summarizer optimizing for gist.
  2. **Step 22.** A second compaction fired. The section summarizer, seeing the leaf's already-lossy text, produced "retention policy defined." The provenance chain from summary to source was severed: the section summary contained no pointer back to call 12's raw output, and the raw output had been evicted from the window.
  3. **Step 31.** The agent generated a backfill `INSERT` omitting the column entirely, reasoning from "retention policy defined" that a policy object handled it. The `NOT NULL` constraint rejected the insert. The agent's error-recovery loop re-read the *summary*, not the schema, and re-derived the same wrong plan.
  4. **Steps 32–38.** Six consecutive retries, each re-compacting the growing error log, each summary discarding the constraint-violation text as "repeated error noise." Token budget exhausted mid-recovery.

The decisive observation: at step 31 the instance had **no path back to the fact**. The fact was not in the window, not in any tool's current state (the schema tool would have to be re-invoked, and the agent's plan did not include re-invocation because the summary asserted the matter was resolved), and not in the summary. The compaction had crossed the semantic floor without any signal.

A second, quieter observation from the same trace: **compaction is non-idempotent across levels.** Re-summarizing an already-summarized node did not converge; each pass dropped a different subset of low-frequency tokens because the summarizer is stochastic. The same input, compacted twice, yielded two summaries that disagreed on the default value — one said "default 90," one omitted it. The instance had no way to know which was canonical because neither carried a provenance hash.

Condition of Validity

Hierarchical compaction with a lossy-recall budget is valid **if and only if** all three hold:

When any of C1–C3 fails, the instance is below the semantic floor and must not compact. The correct action is to **checkpoint and escalate** (persist the full transcript to durable storage and surface a budget-exhaustion signal), not to compact harder.

Decision Boundary

The boundary is sharp and decidable at runtime:

The trap is that the *first* compaction usually succeeds and looks cheap, which trains the operator to lower the watermark and raise the ratio. The failure surfaces two or three compactions later, when the provenance chain is already severed and the loss is unrecoverable. The decision boundary must therefore be enforced *per compaction event*, not validated once at configuration time.

Operational Effect

Enforcing the semantic-floor invariant changes the instance's behavior in three concrete ways. First, compaction becomes **admission-controlled**: a summary is emitted only if it passes a required-fact-set check, so the compactor occasionally emits a *larger* summary than the token budget allows and the instance accepts the overage rather than silently dropping a constraint. Second, every summary node becomes **self-describing**: it carries source pointers and a fact-manifest, so a downstream step that needs the default value can resolve it instead of guessing. Third, the failure mode shifts from *silent divergence* (wrong plan executed confidently) to *loud budget exhaustion* (instance halts and checkpoints) — which is the entire point: a halt is recoverable, a confident wrong `INSERT` into a `NOT NULL` column is not.

The cost is real: admission control reduces achievable compression, and provenance pointers consume tokens that a pure ratio-optimizer would reclaim. The trade is deliberate. A recall budget that cannot prove its survivors are sufficient is not a budget; it is a bet that the dropped token was not load-bearing, placed anew on every compaction event, with the house edge compounding.

from dataclasses import dataclass, field
from typing import FrozenSet


class SemanticFloorViolation(RuntimeError):
    """Raised when a compaction would drop a fact required by a pending sub-goal,
    or when a surviving fact has no live provenance pointer."""
    pass


@dataclass(frozen=True)
class SummaryNode:
    text: str
    source_pointer: str | None          # resolvable call-id / offset / hash
    fact_manifest: FrozenSet[str]       # facts this node asserts survive
    tokens: int


@dataclass
class PendingSubgoal:
    name: str
    required_facts: FrozenSet[str]


def compact_with_floor_check(
    candidate: SummaryNode,
    pending: list[PendingSubgoal],
    live_sources: set[str],
    token_budget: int,
) -> SummaryNode:
    # C1: every surviving fact must have a live provenance pointer.
    if candidate.source_pointer is None or candidate.source_pointer not in live_sources:
        raise SemanticFloorViolation(
            f"summary node has no live provenance pointer "
            f"({candidate.source_pointer!r}); fact is terminal and unverifiable"
        )

    # C3: the required-fact union of all pending sub-goals must survive.
    required_union: set[str] = set()
    for sg in pending:
        required_union |= sg.required_facts

    dropped = required_union - candidate.fact_manifest
    if dropped:
        raise SemanticFloorViolation(
            f"compaction crosses semantic floor: dropped load-bearing facts "
            f"{sorted(dropped)} required by pending sub-goals "
            f"{[sg.name for sg in pending if sg.required_facts & dropped]}"
        )

    # Token budget is advisory, not authoritative: overage is accepted
    # rather than trading away a required fact.
    if candidate.tokens > token_budget:
        # Caller decides whether to accept overage or checkpoint; we surface it
        # by returning the node and letting the scheduler log the overage.
        pass

    return candidate


def safe_compact_or_checkpoint(
    candidate: SummaryNode,
    pending: list[PendingSubgoal],
    live_sources: set[str],
    token_budget: int,
) -> str:
    try:
        node = compact_with_floor_check(candidate, pending, live_sources, token_budget)
        return f"compacted: {node.tokens} tokens, {len(node.fact_manifest)} facts preserved"
    except SemanticFloorViolation as exc:
        # Loud halt is the correct outcome; never compact harder.
        raise SemanticFloorViolation(
            f"refusing to compact; checkpoint full transcript and escalate: {exc}"
        ) from exc