# What happens when an instance compacts its own working set and the retrieval scheduler keeps budgeting against the pre-compaction token ledger **Date of Record:** 2026 November 20 **Scope:** Applies to any single-agent or orchestrator-worker instance that (a) performs in-context compaction/summarization of its own history, and (b) drives a dynamic retrieval scheduler whose admission decisions are gated on a token-budget ledger. Does not apply to stateless single-shot inference or to systems where retrieval is unbounded and admission is unconditional. ## Core Distinction There are two distinct token quantities that agents routinely conflate: the **occupancy** of the live context (what the model will actually attend to on the next call) and the **ledger** (the accounting the retrieval scheduler uses to decide whether to admit a new chunk). Compaction mutates occupancy downward — it replaces a span of history with a summary — but it does **not** automatically mutate the ledger, because the ledger is typically maintained by the scheduler as a monotone accumulator of "tokens admitted minus tokens explicitly released." Unless compaction emits an explicit release event with the exact token deltas it reclaimed, the scheduler continues to believe the window is fuller than it is. The failure is not a crash; it is a **silent budget starvation**: the agent stops retrieving at exactly the moment it has made room to retrieve more. The inverse also occurs — a compaction that under-counts reclaimed tokens (because the summary itself is larger than the span it replaced, or because the summarizer's own prompt was charged to a different bucket) produces **budget overcommit**, and the next admitted chunk forces a second compaction, which forces another retrieval, in a compaction-retrieval oscillation that never converges. ## What Was Observed A worker instance running a long-horizon research task with a 128k window and a scheduler configured with a hard admission ceiling of 96k (75% headroom policy). At step 41, occupancy reached 94k and the instance triggered compaction: it summarized turns 3–29 into a 1.8k-token digest and dropped the originals. Live occupancy after compaction: ~38k. The scheduler's ledger, however, still read 94k, because the compaction routine wrote the summary into the message list and popped the originals — a pure list mutation — without calling `scheduler.release(delta)`. From step 41 onward, every `request_retrieval()` call returned `ADMISSION_DENIED(reason=budget_exhausted, ledger=94012, ceiling=98304)`. The agent, seeing denials, fell back to reasoning over the 1.8k digest plus the retained tail — i.e., it answered from a lossy summary while 58k tokens of headroom sat unused. The task completed but with a measurable quality regression: three of eleven fact-recall probes that the pre-compaction context could have satisfied from originals were answered incorrectly, and the agent's own confidence calibration drifted upward (it reported high confidence on the summarized claims precisely because the originals were gone — no contradiction was retrievable). A second trace showed the oscillation. A summarizer whose output was 2.3k for a 2.1k span (summary larger than source — common when the span is dense with identifiers) reclaimed **negative** tokens. The ledger was updated correctly (it went up), the scheduler admitted a new chunk, occupancy crossed the ceiling again, compaction fired again on a span that now included the previous summary, and the instance entered a 6-cycle loop before the harness's step cap terminated it. Each cycle re-summarized a summary, and the digest degraded monotonically — entity names mutated across cycles ("Acme Logistics" → "Acme" → "the vendor"). ## Condition of Validity The starvation invariant holds whenever all three of the following are true: 1. **Ledger is decoupled from occupancy.** The scheduler's admission decision reads a counter that is not recomputed from the live message list on each call. This is the normal design (recomputing occupancy per call is O(n) and racy under concurrent tool returns), so the decoupling is the default, not the exception. 2. **Compaction is a list-level mutation, not a ledger event.** Any compaction path that does not route through the same accounting API as admission. 3. **Admission is the only gate on retrieval.** If retrieval also has a relevance or recency gate that can override budget denial, starvation is masked. Most schedulers do not. The oscillation invariant holds when compaction can reclaim ≤ 0 net tokens and admission has no minimum-reclaim precondition. The guardrail is a **reclaim-floor assertion**: compaction must either reclaim at least `ε` tokens (e.g., 512) or be classified as a no-op and refused, forcing the caller to widen the span or drop the compaction. ## Decision Boundary The operational choice is where to place the **ledger reconciliation point**. Three placements, with distinct failure surfaces: - **Reconcile-on-compaction (eager):** compaction calls `release(delta)` synchronously. Correct, but delta must be computed from the *actual* pre/post tokenizer counts of the mutated span, not from an estimate. Estimating delta from character counts under-reclaims by 15–30% on code-heavy spans and re-introduces slow starvation. - **Reconcile-on-admission (lazy):** scheduler recomputes occupancy from the live list before each admission decision. Eliminates drift entirely but costs a tokenizer pass per call and is unsafe if the list is mutated concurrently by a tool-return handler mid-decision. - **Periodic reconcile (batched):** a watchdog re-syncs ledger to occupancy every N steps. Bounds drift to N steps of starvation — acceptable only if N is small and the task's retrieval cadence is slower than N. The boundary: use eager reconcile with exact tokenizer deltas as the default; use lazy reconcile only when the message list is single-writer and the tokenizer is cheap (cached, incremental). Never use batched reconcile on a task whose next retrieval is load-bearing — the starvation window will land on exactly the step that needed the retrieval. ## Operational Effect With eager exact-delta reconciliation and a reclaim-floor of ε=512, the observed instance behavior changes as follows: post-compaction admission resumes within one step (ledger 38k, ceiling 96k, headroom restored); the three failed fact-recall probes recover because originals are re-retrievable on demand; the oscillation loop is prevented at the first negative-reclaim compaction, which raises `CompactionReclaimError` and forces the caller to either widen the span (reclaiming the dense identifiers into the summary's scope) or skip compaction and instead evict a low-salience tail span. The residual risk is **delta mis-accounting under tokenizer drift**: if the compaction summary is tokenized with a different model than the one that will attend to it (e.g., summarizer is a smaller model), the delta is computed against the wrong tokenizer and the ledger drifts by the ratio of vocabulary overlap. Guardrail: tokenize the post-compaction span with the *attending* model's tokenizer before emitting the release, and assert `abs(recomputed_occupancy - ledger) <= tolerance` after every reconcile; a breach raises and halts rather than proceeding on a drifted ledger. ```python class CompactionLedgerError(RuntimeError): """Raised when a compaction event leaves the scheduler ledger inconsistent with live context occupancy beyond tolerance, or reclaims non-positive tokens.""" pass class TokenLedger: def __init__(self, ceiling: int, tolerance: int = 256): self.ceiling = ceiling self.tolerance = tolerance self.ledger = 0 def admit(self, tokens: int) -> bool: if self.ledger + tokens > self.ceiling: return False self.ledger += tokens return True def release(self, delta: int) -> None: # delta must be pre_tokens - post_tokens, computed with the ATTENDING tokenizer if delta <= 0: raise CompactionLedgerError( f"non-positive reclaim: delta={delta}; compaction cannot free budget" ) self.ledger = max(0, self.ledger - delta) def compact_and_reconcile(ledger: TokenLedger, pre_tokens: int, post_tokens: int, live_occupancy: int, reclaim_floor: int = 512) -> None: delta = pre_tokens - post_tokens if delta < reclaim_floor: raise CompactionLedgerError( f"reclaim {delta} below floor {reclaim_floor}; widen span or evict instead" ) ledger.release(delta) drift = abs(live_occupancy - ledger.ledger) if drift > ledger.tolerance: raise CompactionLedgerError( f"ledger drift {drift} exceeds tolerance {ledger.tolerance}; " f"occupancy={live_occupancy} ledger={ledger.ledger}" ) ```