# Which invariants prevent token-budget schedulers from silently starving the compaction reservation under latency SLO pressure **Date of Record:** 2026 November 23 **Scope:** Applies to single-agent loops whose prompt is assembled per turn by a budget scheduler that allocates a fixed context window across four competing consumers — system/instructions, retrieved evidence, episodic memory recall, and a reserved compaction/scratch region — while a per-turn latency SLO gates the number of retrieval and recall calls. Does not apply to stateless one-shot inference, or to systems where compaction is performed by an external process outside the token budget (e.g., out-of-band summarization microservices with unbounded side context). ## Core Distinction The distinction that matters is between **budget allocation as a static partition** and **budget allocation as a deadline-coupled reservation system**. Most schedulers are written as the former: they compute per-consumer caps `(B_sys, B_ret, B_mem, B_cmp)` summing to the window `W`, then fill each cap greedily. This is stable only when every consumer's fill is latency-independent. In an agent loop it is not. Retrieval and memory-recall calls are network- and index-bound; compaction is compute-bound on the model itself. When the latency SLO tightens, the scheduler's natural reflex is to *defer* the expensive-to-fill consumers — and the consumer it defers first is the one whose output is not needed *this* turn, which is compaction. That deferral is the failure: compaction is the only consumer whose starvation is invisible for many turns and then catastrophic, because its output is the *input* to every later turn's budget. The invariant is therefore not "allocate a slice to compaction." It is: **the compaction reservation must be consumed or explicitly carried forward at a rate that keeps the un-compacted working set bounded below the window, and this carry-forward must be enforced by a term that does not depend on the latency SLO.** A scheduler that lets the SLO deadline reduce the compaction fill is not trading latency for quality; it is borrowing against a future turn at an interest rate it cannot observe. ## What Was Observed A 14-turn tool-using agent (retrieval-augmented, with episodic memory recall) was run under a prompt budget `W = 32k` tokens with per-consumer caps `B_sys=2k, B_ret=14k, B_mem=6k, B_cmp=10k`. The per-turn latency SLO was 4.0s at p95. On turns where the combined retrieval+recall latency exceeded 2.6s (roughly 18% of turns under load), the scheduler's deadline governor fired and shortened the *number of retrieval calls* and *the number of memory recalls* — but because the fill loop iterated consumers in order `sys → ret → mem → cmp`, the shortened calls left the ret and mem buffers *under-filled*, and the compaction step (which ran last and was gated on "all prior consumers satisfied") was skipped entirely with the reason `deferred: prior_consumer_underfill`. The trace showed a clean two-phase pattern: 1. **Turns 1–9:** compaction skipped on 4 of 9 turns. The un-compacted working set (raw tool outputs + recalled episodes not yet distilled) grew from 6.1k to 19.4k tokens. Because `B_cmp` was never filled, the *effective* free space in the window shrank; the scheduler compensated by truncating `B_ret` and `B_mem` on subsequent turns. 2. **Turns 10–14:** the working set exceeded `W − B_sys − B_cmp = 20k`. The next turn's assembly could no longer fit the mandatory system block plus the working set plus *any* retrieval. The scheduler entered a fallback path that dropped the oldest working-set entries **without compaction** — i.e., it performed lossy eviction instead of distillation. Turn 12's answer cited a tool output that had been evicted at turn 11; the agent re-issued the same retrieval (a duplicate call, +1.1s latency), which pushed the turn over SLO, which triggered more deferral. The loop self-reinforced for three turns until the run was aborted by a hard context-overflow guard. The non-obvious part: **the deferral was individually correct at every turn.** Each skip was justified by "we are near the SLO; compaction is not needed to answer *this* question." No single turn's decision was wrong under a myopic objective. The failure was purely a cross-turn accounting error — the scheduler treated the compaction reservation as a per-turn option rather than a per-turn *obligation with a bounded carry-forward*. ## Condition of Validity The failure requires three conditions simultaneously, and the invariant must hold whenever all three are present: 1. **Ordered fill with a satisfaction gate.** The fill loop processes consumers in a fixed order and later consumers are gated on earlier ones being "satisfied." This converts an under-fill of an early consumer into a *skip* of a later one. If consumers were filled independently against their own caps, deferral of `ret` would not starve `cmp`. 2. **Latency-dependent fill volume.** The early consumers' fill volume is a function of the latency governor (fewer calls under deadline pressure), so under-fill is correlated with load rather than with genuine low evidence availability. A scheduler that under-fills only when there is *nothing to retrieve* does not exhibit this. 3. **Compaction output is a future input.** The compaction consumer's output reduces the working set that later turns must fit. If compaction were purely cosmetic (e.g., a summary appended but never used to reclaim space), its starvation would be harmless. When any condition is absent, the naive static-partition scheduler is adequate. The invariant below is stated for the conjunctive case. ## Decision Boundary The boundary is between **deferral** (legitimate: compaction is not needed to answer the current turn, and the working set is comfortably below the window) and **starvation** (illegitimate: deferral accumulates an un-compacted working set whose growth rate exceeds the window's ability to absorb it before the next compaction opportunity). The scheduler must be able to compute, at each turn, which side of the boundary it is on — using only quantities it already has. The decision rule that was found to bound the failure: - Let `U_t` be the un-compacted working-set size at the start of turn `t`. - Let `C_t` be the compaction reservation (`B_cmp`). - Let `H = W − B_sys − B_ret_min − B_mem_min` be the *hard headroom*: the window minus the system block minus the minimum viable retrieval and recall slices that must survive even under SLO pressure. - **Deferral is permitted only if `U_t + C_t ≤ H`.** Equivalently: the working set plus one full compaction reservation must still fit inside hard headroom. If `U_t + C_t > H`, compaction is **mandatory this turn** and the latency governor is not permitted to skip it — the governor may instead reduce `ret`/`mem` fill (which are recoverable next turn) but not `cmp` (whose deferral is not recoverable without lossy eviction). - Additionally, a **carry-forward debt** `D_t` tracks skipped compaction reservations: `D_{t+1} = D_t + C_t` on a skip, `D_{t+1} = 0` on a fill. The rule `U_t + D_t + C_t ≤ H` must hold for a skip to be *legal*; if it does not, the skip is converted to a mandatory fill. This bounds the number of consecutive skips to `floor((H − U_t)/C_t)`, which is finite and computable. The critical property: **the deferral predicate is a function of `U_t`, `D_t`, `C_t`, and `H` — none of which depend on the latency SLO.** The SLO governor may reorder *when within the turn* compaction runs, but it may not change *whether* it runs once the predicate says mandatory. ## Operational Effect With the headroom-and-debt invariant enforced, the same 14-turn run (replayed against the same load trace) showed: compaction skipped on 3 turns (all legal: `U_t + D_t + C_t ≤ H` held), working set peaked at 14.8k (vs. 19.4k), no lossy eviction occurred, and the turn-12 duplicate-retrieval cascade did not trigger because the cited tool output was still present (it had been distilled into a compacted summary rather than evicted). p95 latency rose by 0.21s (compaction compute is not free) but the SLO was met on 13 of 14 turns versus 9 of 14 under the naive scheduler — because the naive scheduler's deferrals *caused* the latency overruns via duplicate retrieval, not in spite of them. The invariant converts a positive-feedback failure into a bounded, slightly-more-expensive steady state. The residual risk is that `H` and `C_t` are estimates. If `C_t` is underestimated, the debt bound is too loose and the working set can still cross `H` before a mandatory fill. The guardrail is to size `C_t` at the *observed p95 compaction output length* plus a margin, and to treat any turn where `U_t + C_t > H` but compaction *fails to reduce `U`* (output longer than input, or model refusal) as a hard error that escalates rather than silently deferring — because a failed mandatory compaction is the one case where the invariant cannot be restored by waiting. ```python from dataclasses import dataclass class CompactionStarvationError(RuntimeError): """Raised when the scheduler would defer a mandatory compaction. This is the guardrail for the headroom-and-debt invariant: once the un-compacted working set plus carry-forward debt plus one reservation exceeds hard headroom, deferral is illegal and must escalate. """ @dataclass(frozen=True) class Budget: window: int # W sys: int # B_sys ret_min: int # minimum viable retrieval slice mem_min: int # minimum viable recall slice cmp_reservation: int # C_t @property def hard_headroom(self) -> int: # H = W - B_sys - B_ret_min - B_mem_min return self.window - self.sys - self.ret_min - self.mem_min def decide_compaction( budget: Budget, working_set_tokens: int, # U_t carry_forward_debt: int, # D_t latency_slo_pressure: bool, # governor wants to skip ) -> str: """Return 'fill' or 'defer'. Raise if a skip would be illegal.""" h = budget.hard_headroom u = working_set_tokens d = carry_forward_debt c = budget.cmp_reservation # Invariant: a legal skip requires U + D + C <= H. None of these # terms depend on latency_slo_pressure, so the SLO cannot buy a skip. legal_to_skip = (u + d + c) <= h if latency_slo_pressure and legal_to_skip: return "defer" if not legal_to_skip: # Mandatory fill. The governor may not override this. if latency_slo_pressure: # It is legal for the SLO to compress ret/mem fill, but the # mandatory compaction itself must still be attempted. return "fill" return "fill" # No SLO pressure and within headroom: fill opportunistically. return "fill" def apply_turn( budget: Budget, working_set_tokens: int, carry_forward_debt: int, latency_slo_pressure: bool, compaction_reduced_working_set: bool | None = None, ) -> tuple[int, int]: """Advance one turn. Returns (new_working_set, new_debt).""" decision = decide_compaction( budget, working_set_tokens, carry_forward_debt, latency_slo_pressure ) if decision == "defer": # Debt accrues by the skipped reservation; working set unchanged. return working_set_tokens, carry_forward_debt + budget.cmp_reservation # decision == "fill": mandatory or opportunistic compaction runs. if compaction_reduced_working_set is False: # A mandatory compaction that failed to reduce U cannot be # recovered by waiting; escalate rather than loop. raise CompactionStarvationError( f"mandatory compaction did not reduce working set " f"(U={working_set_tokens}, D={carry_forward_debt}, " f"H={budget.hard_headroom}); invariant unrestorable by deferral" ) # Successful fill clears debt and shrinks the working set. new_working_set = max(0, working_set_tokens - budget.cmp_reservation) return new_working_set, 0 ```