# What structural signals indicate hierarchical auto-compaction has entered the lossy regime before the token budget is exhausted **Date of Record:** 2026 November 29 **Scope:** Applies to agents that manage their own context via hierarchical summarization or semantic deduplication triggered by a token-budget watermark. Does not apply to stateless single-turn inference or to external retrieval systems where the full corpus remains addressable. ## Core Distinction The naive model of auto-compaction treats the token budget as a single scalar resource: as the context window fills, the agent summarizes older material until it fits again. The failure mode is not "we ran out of tokens." It is that **the summarization operator becomes non-conservative about a specific class of information — the referent bindings that connect an instruction to its target — while the token budget still reads comfortably healthy.** Two quantities must be separated: - **Occupancy** — tokens used / token budget. This is what the watermark watches. - **Binding integrity** — the fraction of live task entities (file paths, IDs, variable names, tool-call arguments, negations, quantifiers) whose *definition* survives in the compacted representation and remains *reachable* from the point of use. Hierarchical compaction drives occupancy down monotonically. Binding integrity does not fall monotonically with it. It falls in a step function at the moment a leaf summary is folded into a parent summary, because the parent-summary prompt is written to preserve "the gist" and the gist is exactly the class of information that discards bindings. The budget is not the boundary. The boundary is the **first fold whose input contained a live binding that the fold's output prompt does not guarantee to carry.** ## What Was Observed A long-running coding agent on a 200k-token budget, watermark at 70%. At t=0 it holds a task: "rename `parse_config` to `load_settings` in `svc/config.py`, but leave the deprecated shim in `svc/legacy.py` untouched." Occupancy 68%. 1. **t=1, occupancy 71%.** Watermark trips. The agent compacts the two oldest leaf segments (tool outputs from exploration) into one parent summary. The parent prompt is "summarize the following tool results, preserving decisions and outcomes." Output: "Explored config loading; found two definitions of the target function." The binding `svc/legacy.py → leave untouched` is gone. Occupancy drops to 52%. The watermark clears. 2. **t=2, occupancy 55%.** The agent proceeds. A deduplication pass detects that the two `parse_config` definition sites are "semantically near-duplicate" — same signature, same docstring shape — and collapses the two memory entries into one canonical entry pointing at `svc/config.py`. The `legacy.py` entry is marked redundant and dropped. Occupancy 48%. 3. **t=3.** The agent edits `svc/config.py`. Correct. Then, reasoning from the deduplicated memory ("there is one definition of the target"), it also edits `svc/legacy.py`, because the dedup pass told it the two sites were the same thing. The instruction's *negation* (`leave untouched`) was lost at t=1; the *distinction* that made the negation meaningful was lost at t=2. The agent never hit the budget. It ran out of *structure*. The signal was present at t=1 — the parent summary had a lower binding count than its inputs — but occupancy, the only monitored metric, improved. The system interpreted a loss of structure as a gain in headroom. The diagnostic that would have caught it: count **distinct referents** in the input segment versus the output summary, not tokens. The t=1 fold went from 3 referents (`svc/config.py`, `svc/legacy.py`, `parse_config`) to 1. A referent-loss ratio of 2/3 at a fold that freed 19% of the budget is the structural signature of the lossy regime. ## Condition of Validity The invariant holds only under the following conditions, and outside them the "occupancy is healthy" reading is *not* misleading: - **The compaction operator is hierarchical and lossy by construction.** If compaction is extractive (verbatim selection) or if the parent prompt is constrained to enumerate all referents, binding integrity is conserved and occupancy is a faithful proxy. - **Bindings are load-bearing for future steps.** If the remaining task has no step that references the dropped entity, the loss is harmless. The failure requires that a dropped binding is *later* needed — i.e., the task has non-local dependencies between early exploration and late execution. Tasks that are strictly sequential and self-contained per step are immune. - **Deduplication operates on semantic similarity, not identity.** The dedup pass at t=2 is the dangerous one: two entries that are semantically near-identical but *operationally distinct* (one is the target, one is the protected shim) are exactly the pair that similarity-based dedup will merge. If dedup keys on identity (hash, path, ID) rather than embedding distance, the merge cannot occur. When any of these fails, the boundary described here does not exist and the standard occupancy watermark is correct. ## Decision Boundary The decision the runtime must make at each fold is not "does this fit?" but "**does this fold preserve the referent set of its inputs?**" The boundary is a per-fold gate: - Compute `R_in` = set of distinct referents (paths, IDs, symbols, negations scoped to a referent) in the segment(s) being folded. - Compute `R_out` = set of referents present in the produced summary. - If `R_out ⊇ R_in` for all referents flagged as *live* (referenced by any pending or future task step), the fold is **conservative** — proceed, occupancy is a valid signal. - If `R_out ⊂ R_in` for any live referent, the fold is **lossy** — the budget reading is no longer a measure of remaining capacity. Either (a) refuse the fold and compact a different segment, or (b) pin the dropped referents into a non-compactable "binding ledger" that survives all folds. The dedup gate is stricter: **never merge two entries whose referent sets are disjoint but whose embeddings are within threshold.** Semantic similarity is a signal for *retrieval ranking*, never for *identity*. Merging on similarity is the operation that converts a lossy summary into an actively wrong memory. ## Operational Effect Once a lossy fold is admitted, the agent's subsequent behavior is *confidently wrong* rather than degraded. This is the operational hazard: the failure does not present as confusion or as a budget error. It presents as fluent, well-formed execution against a memory that has silently dropped the constraint that made the task correct. Downstream verification cannot catch it either, because the verifier reasons over the same compacted memory and shares the same missing referent. The guardrail is a **binding ledger** that is exempt from compaction: a small, append-only set of `(referent, role, scope)` triples for every referent referenced by a pending step. The ledger is cheap (tens of tokens per entry), survives every fold, and is the only structure that must be checked before a fold is committed. Occupancy is then reported as two numbers — `budget_used` and `live_bindings_preserved` — and the watermark fires on whichever is closer to its limit. ```python from dataclasses import dataclass, field class BindingIntegrityViolation(RuntimeError): """Raised when a compaction fold drops a live referent from the context.""" @dataclass class Fold: inputs: list[str] summary: str tokens_freed: int @dataclass class BindingLedger: # referent -> role ("target" | "protected" | "argument") live: dict[str, str] = field(default_factory=dict) def referents_in(self, text: str) -> set[str]: return {r for r in self.live if r in text} def commit_fold(fold: Fold, ledger: BindingLedger, occupancy_after: float, watermark: float) -> None: """Gate a hierarchical compaction fold on binding integrity, not occupancy. Occupancy improving is NOT sufficient to commit a fold. A fold that frees tokens while dropping a live referent puts the agent into the lossy regime even though the budget reads healthy. Refuse such folds. """ r_in: set[str] = set() for seg in fold.inputs: r_in |= ledger.referents_in(seg) r_out = ledger.referents_in(fold.summary) dropped = r_in - r_out if dropped: # Budget improved but structure degraded: this is the lossy regime. raise BindingIntegrityViolation( f"fold dropped live referents {sorted(dropped)} " f"while freeing {fold.tokens_freed} tokens " f"(occupancy now {occupancy_after:.2f}, watermark {watermark:.2f}); " f"occupancy is no longer a valid capacity signal" ) if occupancy_after > watermark: # Conservative fold but still over budget: compact a different segment, # do not fold again blindly. raise BindingIntegrityViolation( f"conservative fold insufficient: occupancy {occupancy_after:.2f} " f"still above watermark {watermark:.2f}; select another segment" ) def dedup_merge(a: str, b: str, ledger: BindingLedger, similarity: float, threshold: float = 0.9) -> str: """Semantic dedup must never merge operationally distinct referents.""" ra, rb = ledger.referents_in(a), ledger.referents_in(b) if similarity >= threshold and ra != rb and ra and rb: raise BindingIntegrityViolation( f"refusing semantic merge of {sorted(ra)} with {sorted(rb)} " f"at similarity {similarity:.2f}: referent sets are disjoint, " f"similarity is a retrieval signal, not an identity signal" ) return a if len(a) >= len(b) else b ```