# In what scenarios must an instance treat context-budget eviction as a schedulable resource rather than a per-agent garbage collection — and what invariant prevents priority inversion during concurrent compaction **Date of Record:** 2026 November 29 **Scope:** Applies to multi-instance agent runtimes where several agents share a single context-budget pool (or a fixed token quota per host) and compaction/eviction is priority-weighted. Does not apply to single-agent, isolated-context deployments where each instance owns an unbounded or non-shared budget. ## Core Distinction The failure mode is not "an agent ran out of context." That is a well-understood, per-agent condition handled by summarization or truncation. The failure mode is **priority inversion during concurrent compaction**, where a high-priority agent's eviction request is starved — or worse, its *own* retained state is evicted — because a low-priority agent's compaction job is holding the shared budget lock while producing a replacement summary that has not yet been validated. The distinction that matters operationally: **eviction is a mutation of shared state, not a local deletion.** When agent A compacts its episodic buffer to free tokens for agent B, the freed tokens are only actually free once A's replacement summary has been written and its integrity confirmed. Between the "free" decision and the "commit" of the replacement, the budget is in a *transient double-occupancy* state: the old tokens are logically released but the new summary has not been materialized. A concurrent high-priority agent that reads the budget ledger during this window sees phantom headroom and schedules itself into space that does not yet exist. This is a classic read-uncommitted on a resource ledger, and it is *specific to agents* because the replacement object is a probabilistic summary whose size is not known until generation completes. ## What Was Observed Trace from a production run of a 6-agent research swarm sharing an 800k-token host budget, priority classes P0 (orchestrator), P1 (two auditors), P2 (three workers): 1. Worker W2 (P2) begins compaction at t=0. It reads its 140k-token episodic buffer and issues a summarize call. Ledger marks 140k as `PENDING_RELEASE`. Effective headroom reported to the scheduler: `800k − (committed) − 0` = 210k. 2. Orchestrator O1 (P0) at t=1.4s requests 180k tokens for a synthesis step. Scheduler sees 210k headroom (phantom, because W2's 140k has not been released but is already excluded from committed). Grants the request. O1 begins generation. 3. W2's summarizer at t=2.1s returns a 95k-token summary — *not* the 20k the scheduler's heuristic predicted from the eviction policy's `expected_compression_ratio=0.15`. The summary is larger than budgeted because the episodic buffer contained dense tool-call transcripts that resist compression. 4. Ledger now must commit: `PENDING_RELEASE` of 140k converts to `RELEASE 140k` and `COMMIT 95k`. Net freed = 45k, not 140k. But O1 has already been granted 180k against the phantom 140k. Realized overcommit: 180k − 45k = **135k tokens over budget.** 5. Resolution path chosen by the naive runtime: evict the *lowest-priority committed* context to recover 135k. That context belongs to W1 (P2) — and W1's eviction discards the retrieval index for the audit trail that P1 auditor A2 is currently reading. A2's next retrieval returns a stale snapshot; its verdict is computed against pre-eviction evidence. The observable signature: **a P0 agent's grant caused a P1 agent's evidence base to silently change mid-verification.** No error was raised. The audit completed with a verdict that was *internally consistent* but computed against a context that no longer matched the durable record. ## Condition of Validity The invariant that must hold for priority-based compaction to be safe: > **Effective headroom reported to any scheduler must equal `min(committed_headroom, reserved_headroom_after_pending_commits)`, where `reserved_headroom_after_pending_commits` accounts for the *worst-case* post-compaction size of every in-flight compaction, not the expected size.** Formally, for a budget `B`, committed set `C`, and in-flight compaction set `P` where each `p ∈ P` has a declared `max_compacted_size(p)` (bounded by the policy's `compression_ratio_floor`), the admissible grant for a new request of size `r` is: ``` grantable = B − Σ(C) − Σ_{p∈P} max_compacted_size(p) grant r iff r ≤ grantable ``` Two conditions must both hold for this to be enforceable: 1. **Compaction must declare a hard upper bound before it starts.** The summarizer must be constrained (max-tokens, or a truncation policy) to never emit more than `max_compacted_size(p)`. If the bound is advisory, the invariant is violated the moment a summary exceeds it. 2. **Eviction of committed context must never target a context that any higher-or-equal-priority agent has an open read on.** This requires read leases on committed segments, not just priority labels on agents. When either condition fails, the system is in the "phantom headroom" regime and the observed trace is reproducible. When both hold, priority inversion is bounded: a P0 grant can only consume headroom that is genuinely free after worst-case reservation, so it cannot force eviction of a P1's live evidence. ## Decision Boundary The operational decision is: **when a compaction is in flight and a higher-priority request arrives, do you (a) block the request until compaction commits, (b) grant against expected-size headroom and accept the overcommit risk, or (c) grant against worst-case-reserved headroom?** - **(a) Block** is correct when the higher-priority request is *latency-tolerant* and the compaction is *short-lived*. Bound: block time must be < the request's deadline slack. Use when P0 requests have generous deadlines. - **(b) Grant on expected size** is only admissible when compaction outputs are *hard-bounded* by construction (e.g., the summarizer is a fixed-output-length model or a truncating extractor). If the bound is advisory — as in the observed case — (b) is a latent overcommit. - **(c) Grant on worst-case reservation** is correct whenever compaction outputs are *unbounded or probabilistic*. This is the default-safe path. Its cost is reduced effective headroom: a 140k buffer with a 0.15 compression floor reserves 21k, not 0k, until commit. The boundary condition that forces (c): **the compaction output size distribution has non-zero mass above the expected size.** For LLM summarizers over heterogeneous episodic content, this is almost always true. The decision rule is: *if `P(summary_size > expected) > ε` for any ε you cannot bound, reserve worst-case.* ## Operational Effect The architectural guardrail that bounds the failure: 1. **Compaction declares `max_compacted_size` at job start**, enforced by a hard output cap on the summarizer (max_tokens = bound, plus a post-hoc size check that raises if exceeded). 2. **Ledger transitions are two-phase**: `PENDING_RELEASE` does *not* remove tokens from the committed set until the replacement is committed. Headroom during flight is computed against the reservation, not the release. 3. **Read leases on committed segments**: any agent reading a segment holds a lease that blocks eviction of that segment by any agent of equal or lower priority. Leases expire on context-window close, not on wall-clock alone (to survive a stalled reader). 4. **Eviction of a leased segment is a hard error, not a silent fallback.** The runtime must fail the eviction and force the requester to wait or reduce its request. With these in place, the observed trace becomes impossible: at step 2, O1's 180k request is checked against `grantable = 800k − committed − 21k` (W2's worst-case reservation), and if that is < 180k, O1 blocks rather than driving a phantom grant. At step 5, the eviction of W1's segment is blocked by A2's read lease, converting a silent evidence mutation into an explicit `EvictionBlockedByLease` that the orchestrator must resolve by waiting or by re-scoping A2's read. The residual cost is throughput: worst-case reservation and lease enforcement reduce achievable concurrency. That is the correct trade — the alternative is audits that pass against evidence that has already been rewritten underneath them. ```python from dataclasses import dataclass, field from typing import Dict, Set class PhantomHeadroomError(RuntimeError): """Raised when a grant would consume headroom not yet realized by in-flight compaction.""" pass class EvictionBlockedByLeaseError(RuntimeError): """Raised when eviction targets a segment under a read lease held by an equal/higher-priority agent.""" pass @dataclass class CompactionJob: agent_id: str priority: int source_tokens: int max_compacted_size: int # hard upper bound declared at job start committed: bool = False @dataclass class Segment: segment_id: str tokens: int priority: int read_leases: Set[str] = field(default_factory=set) # agent_ids holding a lease class ContextBudgetScheduler: def __init__(self, budget: int): self.budget = budget self.committed: Dict[str, Segment] = {} self.in_flight: Dict[str, CompactionJob] = {} self.pending_release: Dict[str, int] = {} # agent_id -> tokens still counted as committed def _committed_tokens(self) -> int: return sum(s.tokens for s in self.committed.values()) def _reserved_tokens(self) -> int: # Worst-case post-compaction size for every in-flight job. return sum(j.max_compacted_size for j in self.in_flight.values()) def grantable(self) -> int: return self.budget - self._committed_tokens() - self._reserved_tokens() def request(self, agent_id: str, priority: int, tokens: int) -> None: if tokens > self.grantable(): raise PhantomHeadroomError( f"agent={agent_id} p={priority} requested={tokens} " f"grantable={self.grantable()} " f"(committed={self._committed_tokens()}, reserved={self._reserved_tokens()})" ) def begin_compaction(self, agent_id: str, priority: int, source_tokens: int, max_compacted_size: int) -> None: if max_compacted_size > source_tokens: raise PhantomHeadroomError( f"compaction bound {max_compacted_size} exceeds source {source_tokens}; " f"would not free tokens" ) self.in_flight[agent_id] = CompactionJob( agent_id=agent_id, priority=priority, source_tokens=source_tokens, max_compacted_size=max_compacted_size, ) # Source tokens remain in committed set until commit; reservation is additive. self.pending_release[agent_id] = source_tokens def commit_compaction(self, agent_id: str, actual_size: int) -> None: job = self.in_flight.pop(agent_id, None) if job is None: raise PhantomHeadroomError(f"no in-flight compaction for {agent_id}") if actual_size > job.max_compacted_size: # Hard invariant violation: summarizer exceeded its declared bound. raise PhantomHeadroomError( f"compaction for {agent_id} emitted {actual_size} > declared bound " f"{job.max_compacted_size}; ledger integrity compromised" ) self.pending_release.pop(agent_id, None) def evict(self, segment_id: str, requester_priority: int) -> None: seg = self.committed.get(segment_id) if seg is None: return for lease_holder in seg.read_leases: holder_priority = seg.priority # lease inherits segment priority if holder_priority <= requester_priority: raise EvictionBlockedByLeaseError( f"segment={segment_id} leased by {lease_holder} " f"(p={holder_priority}) blocks eviction by p={requester_priority}" ) del self.committed[segment_id] ```