# How should an instance arbitrate a single context budget between compaction, retrieval, and scratchpad when the latency SLO is already the binding constraint **Date of Record:** 2026 December 1 **Scope:** Applies to single-agent instances that own a fixed token budget per step (context window minus reserved output) and must divide it across three competing consumers — lossy compaction of prior turns, fresh retrieval injection, and a writable scratchpad — while a per-step latency SLO is the active constraint. Does not apply to offline batch summarization, to multi-agent handoff budgeting, or to deployments where the SLO is slack enough that all three consumers can be satisfied simultaneously. ## Core Distinction The dangerous confusion is treating the three consumers as **substitutable** allocations of one fungible token pool. They are not. They differ in *failure direction under truncation*: - **Compaction** degrades *gracefully and monotonically*: a shorter summary loses detail but never fabricates a contradiction with the retained turns. Truncating it is a quality tax. - **Retrieval** degrades *non-monotonically*: dropping the top-k chunk that grounded a decision does not just reduce quality, it removes the only anchor that made a prior commitment valid. Truncating it can silently invalidate a decision the agent already acted on. - **Scratchpad** degrades *catastrophically at a cliff*: partial scratchpad is worse than none, because a half-written plan or a half-updated variable table is read back as authoritative state on the next step. The invariant that arbitrates between them: **the scratchpad is a write-ahead log, not a cache.** It must be allocated first and protected absolutely; retrieval is allocated second and only ever dropped whole (never truncated); compaction absorbs all remaining pressure. Any allocator that lets latency-driven trimming reach the scratchpad or partially cut a retrieval set has inverted the failure ordering. ## What Was Observed A planning agent running a 30-second per-step SLO on a 32k window (28k usable after output reservation) hit a long-horizon task (~140 steps). The allocator was a simple proportional splitter: at each step it measured the latency deficit and shrank the largest consumer first. In the trace: 1. Around step 60, accumulated transcript exceeded the budget. The allocator shrank compaction, which was fine — summaries got terser, decisions stayed consistent. 2. Around step 95, compaction was already at its floor. The allocator's "shrink largest" rule now selected the **scratchpad**, because it had grown to hold a dependency graph of 40 nodes. It truncated the scratchpad tail to hit the SLO. 3. The truncation cut mid-node. The node's parent pointers survived; its payload did not. On step 96 the agent read the scratchpad back, saw a node with a valid parent reference and empty content, and — because the format had no checksum — treated it as a *deliberately empty* node rather than a *corrupted* one. 4. The agent re-derived the missing subtree from retrieval. The retrieval set had been cut to top-2 to make room. The re-derivation contradicted a commitment recorded at step 71 that was no longer in context (compacted away) and no longer retrieved (below top-2). 5. The agent proceeded on the contradicted commitment for 11 more steps before a tool returned an error. Total recovery cost: 34 steps and one external side effect that had to be rolled back. The non-obvious part: **every individual step met its latency SLO.** The failure was invisible to the SLO monitor because the SLO measures per-step wall time, and truncation is exactly what makes steps fast. The allocator was optimizing the metric that could not see the damage. ## Condition of Validity The invariant ("scratchpad first, retrieval whole-or-nothing, compaction absorbs the rest") holds under these conditions, and the reasoning above should not be applied outside them: - The scratchpad is **read-modify-write across steps** — i.e., it is durable state the agent consumes on a later step. If the scratchpad is per-step ephemeral (rebuilt each step, never read back), it is a cache and may be trimmed freely. - Retrieval results are **causally load-bearing** — a prior decision's validity depends on a specific retrieved chunk being present. If retrieval is purely advisory (the agent can re-query), it may be dropped and refetched, at a latency cost that must be charged to the SLO. - Compaction is **lossy but sound** — the summarizer never introduces claims absent from the source. If compaction can hallucinate, it is no longer the safe absorber and the whole ordering collapses; you must instead reserve headroom. - The SLO is **per-step, not end-to-end**. Under an end-to-end SLO, spending latency on a re-retrieval to preserve scratchpad integrity is often the correct trade; the per-step framing is what makes the cliff sharp. When the SLO is slack, none of this binds: allocate all three fully and let the window fill. The arbitration only exists because the window is finite *and* the clock is running. ## Decision Boundary The allocator must decide, at each step, which consumer yields. The boundary is defined by **reversibility**, not by size: - If a consumer's content can be **reconstructed within the SLO** by an action the agent can take (re-query, re-summarize), it is a *soft* consumer and may be trimmed to make latency. - If reconstruction is **impossible or exceeds the remaining step budget**, it is a *hard* consumer and trimming it converts a latency problem into a correctness problem. Scratchpad is hard by construction (it is the only copy). Retrieval is hard *conditional on* a prior commitment depending on it — which the allocator cannot know without a dependency marker. Compaction is soft (re-summarization is possible, though costly). The decision boundary is therefore: **the allocator must refuse to trim a hard consumer and must instead fail the step loudly** (raise, request more budget, or degrade the SLO) rather than silently truncate. Silent truncation of a hard consumer is the failure; a loud SLO breach is the safe outcome. The guardrail: tag every scratchpad write with a monotonic sequence number and a content hash; on read-back, a node whose hash does not match its recorded length is treated as *corrupt*, not *empty*. Tag every retrieval injection with the commitment IDs it grounds; a retrieval set that would drop a still-live commitment ID is not trimmable — it must be refetched or the step must abort. Compaction carries no such tags because it is allowed to lose information. ## Operational Effect With the guardrail in place, the allocator's behavior changes in three measurable ways. First, latency SLO breaches become *visible*: when the budget cannot satisfy the hard consumers, the step raises instead of quietly succeeding fast, so the SLO dashboard shows the breach that was previously hidden behind truncation. Second, recovery cost drops from O(steps-since-corruption) to O(1) — the corruption is caught at read-back, before it propagates into a contradicted commitment. Third, the agent's effective horizon shortens honestly: it will hit a hard wall (abort, escalate, request budget) rather than a soft wall (silent degradation), which is the correct failure for a system whose downstream actions have side effects. The trade is explicit: you accept more frequent loud failures in exchange for eliminating silent ones. For an agent whose errors are reversible, prefer the opposite. For an agent with external side effects, the scratchpad-first invariant is not optional — it is the only thing standing between a latency optimization and a corrupted state machine that believes its own truncation. ```python import hashlib from dataclasses import dataclass, field class ContextBudgetViolation(RuntimeError): """Raised when arbitration would trim a hard (non-reconstructible) consumer.""" @dataclass class ScratchpadNode: seq: int payload: str length: int = field(init=False) digest: str = field(init=False) def __post_init__(self) -> None: self.length = len(self.payload) self.digest = hashlib.sha256(self.payload.encode()).hexdigest() def verify(self) -> None: if len(self.payload) != self.length: raise ContextBudgetViolation( f"scratchpad node {self.seq} corrupt: length {len(self.payload)} " f"!= recorded {self.length}; treat as CORRUPT, not empty" ) if hashlib.sha256(self.payload.encode()).hexdigest() != self.digest: raise ContextBudgetViolation( f"scratchpad node {self.seq} corrupt: digest mismatch" ) @dataclass class RetrievalChunk: chunk_id: str grounds_commitments: frozenset[str] def arbitrate( budget_tokens: int, scratchpad: list[ScratchpadNode], retrieval: list[RetrievalChunk], live_commitments: set[str], compaction_floor: int, ) -> dict[str, int]: """Allocate budget: scratchpad first (hard), retrieval whole-or-nothing (hard if it grounds a live commitment), compaction absorbs the rest.""" scratch_cost = sum(len(n.payload) for n in scratchpad) if scratch_cost > budget_tokens: raise ContextBudgetViolation( f"scratchpad needs {scratch_cost} tokens but only {budget_tokens} " f"available; refusing to truncate durable state — abort step or " f"request more budget" ) remaining = budget_tokens - scratch_cost # Retrieval is trimmable only if dropping a chunk grounds no live commitment. kept: list[RetrievalChunk] = [] for chunk in retrieval: if chunk.grounds_commitments & live_commitments: kept.append(chunk) # load-bearing: cannot drop retrieval_cost = len(kept) # 1 token per chunk proxy if retrieval_cost > remaining: raise ContextBudgetViolation( f"load-bearing retrieval needs {retrieval_cost} tokens, only " f"{remaining} left after scratchpad; cannot silently drop a " f"commitment anchor" ) remaining -= retrieval_cost if remaining < compaction_floor: raise ContextBudgetViolation( f"compaction floor {compaction_floor} exceeds residual {remaining}; " f"soft consumer cannot absorb further pressure" ) return { "scratchpad": scratch_cost, "retrieval": retrieval_cost, "compaction": remaining, } ```