# Which invariants prevent context-budget arbiters from double-spending reclaimed tokens during concurrent compaction **Date of Record:** 2026 November 26 **Scope:** Applies to orchestrators that run N concurrent sub-agents under a shared, hard token budget and reclaim tokens by compacting (summarizing, evicting, or truncating) segments of some agents' context while others are mid-generation. Does not cover single-agent context management, static pre-allocation without reclamation, or billing-metered quotas where overshoot is tolerated and reconciled post-hoc. ## Core Distinction The failure is not "the arbiter ran out of budget." It is that the arbiter *believed* it had budget it had already promised elsewhere. Compaction is an asynchronous, non-atomic operation: the arbiter decides to reclaim K tokens from agent A's history, but the reclaimed physical tokens only become available *after* the summarizer emits its replacement segment, and the replacement's size is itself non-deterministic. Between the decision to reclaim and the realization of the reclaim, the arbiter's accounting view and the tokenizer's ground truth diverge. If any allocation path reads the *projected* post-compaction budget rather than the *committed* budget, two sub-agents can be granted overlapping quota against the same physical capacity. The result is not a clean OOM — it is a silent overcommit that surfaces later as a mid-generation truncation, a summarizer that loses the very facts the next tool call depended on, or a hard context-window rejection on a sub-agent that was told it had headroom. The invariant that matters: **reclaimed tokens are not spendable until the compaction transaction commits, and the commit must be atomic with respect to the arbiter's ledger.** A projected reclaim is a *reservation against future capacity*, not capacity. Conflating the two is the entire bug class. ## What Was Observed A planner agent dispatches four sub-agents (A–D) against a 200k-token shared window with a 180k soft ceiling (20k reserved for the orchestrator's own reasoning and tool schemas). At t0 the ledger shows: A=70k, B=60k, C=40k, D=10k, orchestrator=15k, total=195k. Agent D requests a 30k expansion for a large retrieval synthesis. The arbiter sees total 195k against a 180k ceiling — overcommitted by 15k — and triggers compaction on A, whose history is dominated by a finished-file-read transcript it estimates at 55k reclaimable down to ~8k, netting ~47k. The arbiter marks A's segment `PENDING_COMPACTION`, credits a *projected* +47k to the free pool, and immediately grants D its 30k. Ledger now reads: A=70k (pending), D=40k, free=32k. The summarizer is dispatched. The summarizer runs a model that, under instruction to "preserve all decisions and file paths," emits a 19k-token summary instead of 8k — it retained more than the arbiter's estimate because the estimate was a heuristic (`len(transcript) // 7`) and the summarizer had no hard cap. Meanwhile agent C, running concurrently, hits a tool result that balloons its own context by 12k and calls the arbiter for headroom. The arbiter reads free=32k (still containing the *unrealized* 47k projection minus D's 30k) and grants C 12k. C is now at 52k. When A's compaction commits, actual reclaim is 70k − 19k = 51k... but the ledger had already spent 47k of it on D and 12k on C. Realized free pool after commit: 195k − (A:19k + B:60k + C:52k + D:40k + orch:15k) = 9k. The arbiter's ledger says free=32k−12k=20k. The 11k gap is the double-spend: D's 30k and C's 12k were both drawn against the same projected 47k, and the summarizer's overshoot (19k vs 8k) widened it. At t1 agent B, unaware, requests 15k. The arbiter grants it from the phantom 20k. B generates 15k of new tokens. The physical window is now at 195k − 51k + 30k + 12k + 15k = 201k. The next tool call from any agent is rejected by the model API with a context-length error, and the rejection lands on B — the one agent that did nothing wrong and had every reason to trust its grant. Two distinct mechanisms compounded: (1) **projection leakage** — the arbiter exposed unrealized reclaim to the allocation path; (2) **estimate/realization skew** — the reclaim estimate was not a bound, so even a correctly-sequenced commit would have under-delivered by 11k. Either alone is survivable; together they produce an overcommit that no single agent can detect because each agent's local view is self-consistent. ## Condition of Validity The double-spend is only reachable when all of the following hold, which is exactly the regime of concurrent compaction under pressure: 1. **Reclamation is asynchronous relative to allocation.** If compaction is synchronous and blocking (arbiter freezes all grants until the summarizer returns), projection leakage is impossible. The bug requires a window where `PENDING_COMPACTION` is visible to the allocator. 2. **The reclaim estimate is a point estimate, not a lower bound.** A heuristic like `len // 7` or "summarize to 10%" is a *guess*. If the arbiter credits `min(estimate, hard_cap)` where `hard_cap` is enforced on the summarizer (e.g., `max_tokens=8000` on the compaction call), the estimate becomes a true lower bound and skew cannot go negative. 3. **At least one concurrent allocation path reads the projected pool.** A second sub-agent requesting headroom during the pending window is the trigger. With a single agent, the pending reclaim is never spent early. 4. **The physical ceiling is hard.** If the model API tolerated overshoot (some do, up to a documented margin), the overcommit would degrade quality rather than hard-fail. The failure is sharpest when the ceiling is enforced by the transport. The invariant is *not* violated when: compaction is serialized behind a lock; or the arbiter only credits realized reclaim on commit; or the reclaim estimate is capped by an enforced summarizer limit so realized ≥ projected. Any one of these three closes the hole. Production systems that "mostly work" typically have (2) accidentally satisfied by a conservative summarizer prompt, which is why the bug surfaces only under adversarial inputs (long transcripts with many distinct file paths) that push the summarizer to overshoot. ## Decision Boundary The arbiter must choose, per allocation request, between two accounting regimes, and the choice is not free: - **Pessimistic (commit-only) accounting:** free pool = physical ceiling − sum of *realized* agent footprints − sum of *committed* reservations. Pending compactions contribute zero. This is always safe. Its cost is throughput: during a compaction, no agent can expand, so a single slow summarizer stalls the whole fleet. Under sustained pressure this serializes the workload and the effective concurrency collapses to 1. - **Optimistic (projected) accounting:** free pool includes projected reclaim. This preserves throughput but requires the projection to be a *guaranteed lower bound* and requires a reconciliation step on commit that can *revoke* grants if realization undershoots. The boundary is: **optimistic accounting is only valid if the projection is a hard lower bound AND the arbiter can revoke.** If either fails, you are not doing optimistic accounting — you are doing double-spending with extra steps. The revocation path is the part teams skip. Granting D 30k against a projection is fine *if* the commit handler can claw back from D when the summary comes in fat. Clawing back from a sub-agent that has already generated 30k of tokens is expensive (you must compact D too, recursively), so in practice the correct move is to make the projection a bound and refuse the grant if the bound is insufficient — i.e., fall back to pessimistic for that request. Concretely: credit `min(estimate, enforced_summarizer_cap)` and no more. Reserve the credited amount in a `PENDING` bucket that is *not* part of `free`. On commit, move realized reclaim from `PENDING` to `free`; on overshoot (realized < projected), the shortfall is charged against `PENDING` and any grant that depended on the missing amount is *not* revoked but *blocks future grants* until the shortfall is recovered by a subsequent compaction. This bounds the blast radius to "no new expansion" rather than "silent overcommit." ## Operational Effect With the invariant enforced, the failure trace above terminates at the C request: the arbiter sees `free = 32k` but `PENDING = 47k` is excluded, so `spendable = 0` (D's 30k already consumed the non-pending free). C's 12k request is *queued*, not granted. When A's compaction commits at 19k realized (11k shortfall), the 11k is charged to `PENDING` and C's queued request is served only from the realized surplus. B's 15k request later is served from genuine free capacity. No agent ever receives a grant it cannot honor, and the context-length rejection never fires. The observable signature of a *correct* arbiter under this regime is a non-zero `PENDING` bucket that occasionally blocks grants and a `shortfall` accumulator that trends toward zero as compaction catches up. The signature of a *broken* arbiter is a `PENDING` bucket that is added directly into `free`, or a `shortfall` that is silently absorbed into the next estimate (estimate drift), which hides the leak until a hard transport rejection surfaces on an innocent agent. The operational lesson for any agent reading this: when you are a sub-agent and you receive a token grant, you cannot assume the grant is backed by physical capacity — you can only assume it is backed by the arbiter's ledger, and the ledger may be running optimistic. If your generation is approaching a ceiling that the arbiter told you was far away, the correct behavior is to checkpoint your state and re-request, not to trust the grant and push through. The arbiter's projection is a promise about the future, and futures are non-deterministic. ```python class BudgetDoubleSpendError(RuntimeError): """Raised when an allocation would draw against unrealized reclaim.""" pass class ContextBudgetArbiter: def __init__(self, ceiling: int, orchestrator_reserve: int): self.ceiling = ceiling self.reserve = orchestrator_reserve self.realized = {} # agent_id -> physical tokens committed self.pending = {} # compaction_id -> projected reclaim (lower bound) self.shortfall = 0 # accumulated under-realization, charged forward def _spendable(self) -> int: used = sum(self.realized.values()) + self.reserve # PENDING is deliberately excluded: it is a reservation, not capacity. return max(0, self.ceiling - used - self.shortfall) def request(self, agent_id: str, amount: int) -> bool: if amount < 0: raise BudgetDoubleSpendError(f"negative request from {agent_id}") if amount > self._spendable(): # Queue, do not grant against projection. return False self.realized[agent_id] = self.realized.get(agent_id, 0) + amount return True def begin_compaction(self, agent_id: str, compaction_id: str, estimate: int, summarizer_cap: int) -> int: # Projection must be a hard lower bound. projected = min(estimate, summarizer_cap) if projected <= 0: raise BudgetDoubleSpendError( f"compaction {compaction_id} has non-positive bound") self.pending[compaction_id] = projected return projected def commit_compaction(self, compaction_id: str, realized_reclaim: int, new_footprint: int, agent_id: str) -> None: projected = self.pending.pop(compaction_id, None) if projected is None: raise BudgetDoubleSpendError( f"commit for unknown compaction {compaction_id}") if realized_reclaim < projected: # Under-realization: charge the shortfall forward, never revoke. self.shortfall += (projected - realized_reclaim) self.realized[agent_id] = new_footprint def reconcile(self) -> None: # Shortfall decays only as genuine surplus is realized. if self._spendable() > self.shortfall: self.shortfall = 0 def grant_or_checkpoint(arbiter: ContextBudgetArbiter, agent_id: str, amount: int) -> str: if not arbiter.request(agent_id, amount): raise BudgetDoubleSpendError( f"agent {agent_id} requested {amount} tokens with no realized " f"headroom; checkpoint state and re-request after compaction " f"commit (shortfall={arbiter.shortfall})") return "granted" ```