When must an instance budget context by downstream tool-call risk rather than by token count alone
**Date of Record:** 2026 December 2 **Scope:** Applies to single-agent or coordinator instances that hold a bounded context window, plan multi-step tool invocations, and evict prior turns to stay under a token ceiling. Does not apply to stateless one-shot inference, to agents with unbounded external memory that never evicts, or to pure retrieval-augmented pipelines where the retrieved set is fixed before generation.
Core Distinction
Token-count budgeting treats context as a homogeneous byte reservoir: evict the oldest or lowest-attention-scored span until `len(context) <= budget`. Risk-weighted budgeting treats context as a *dependency substrate for pending actions*: a span's eviction cost is the probability that its loss causes a downstream tool call to be malformed, unauthorized, or destructive.
The two policies diverge exactly when a cheap-to-store, low-recency span is a *precondition* for an expensive, irreversible, or security-relevant tool call later in the plan. A recency/FIFO evictor will happily discard the span because it is old and short; the risk-weighted evictor must retain it because the pending call cannot be safely issued without it. The invariant is:
> **No pending tool call may be dispatched if any span that constrains its arguments, authorization, or idempotency has been evicted since the call was planned.**
Violating this invariant does not produce a token error. It produces a *plausible but wrong* call: the model reconstructs the missing constraint from parametric priors and emits arguments that are syntactically valid and semantically hazardous.
What Was Observed
A coordinator agent with a 32k-token window was executing a 14-step remediation plan against a production cluster. At step 3 it read a scoped credential manifest and a resource-allowlist (roughly 400 tokens total, both old and low-attention by the time step 11 arrived). Between steps 3 and 11, nine verbose tool outputs (log dumps, `kubectl describe` blobs) pushed utilization to 31.6k tokens. The eviction policy—recency-weighted with a fixed 0.7 retention floor—dropped both the credential manifest and the allowlist to recover ~600 tokens.
At step 11 the agent issued a `scale` call. The plan had been authored at step 2 with a namespace constraint derived from the allowlist and a service-account constraint derived from the manifest. With both spans evicted, the model regenerated the call arguments from the tool schema's defaults plus its parametric prior about "typical" namespaces. The call was well-formed, passed schema validation, and targeted `default` rather than the constrained namespace. The tool executed. The failure surfaced only at step 13 when a downstream audit read returned an unexpected resource set.
The trace shows the characteristic signature: **no exception at the eviction point, no exception at the call point, a schema-valid call with drifted arguments, and detection deferred by two steps.** The eviction was locally rational (it minimized token pressure and maximized recent-context fidelity) and globally catastrophic (it severed the constraint-dependency edge of a pending irreversible action).
Condition of Validity
Risk-weighted eviction is required—and plain token budgeting is unsafe—if and only if all three hold:
- **A pending action exists in the plan whose arguments or authorization depend on a specific context span.** This is a *dependency edge*, computable at plan time: for each planned call, the set of spans that constrain it.
- **The action is irreversible or externally visible.** Scale, delete, deploy, send, pay, or any call whose effects cannot be cheaply rolled back. Reversible reads can tolerate constraint loss because the error is self-correcting on the next turn.
- **The tool schema underdetermines the constraint.** If the schema enforces the namespace via an enum, eviction is harmless—validation catches the drift. The failure requires that the schema *accepts* the wrong value, i.e. the constraint lives only in context.
When any condition fails, token-count budgeting is correct and cheaper. When all three hold, the eviction policy must be *dependency-aware*: a span pinned by an unexecuted high-risk call is non-evictable regardless of recency or length, and if the budget cannot be met without evicting it, the correct behavior is to *block the plan and externalize the span* (re-fetch, checkpoint to durable store, or compact into a pinned constraint record) rather than to proceed.
Decision Boundary
The boundary is not "how full is the window" but "is there an unexecuted call whose constraint set intersects the eviction candidate set." The decision procedure:
- At plan time, annotate each step with `constrains: [span_ids]` and `risk: {reversible | irreversible}`.
- Maintain a *pinned set* = union of `constrains` for all unexecuted irreversible steps.
- Eviction candidates = all spans minus pinned set. If candidates are insufficient to meet budget, **do not evict pinned spans**; instead trigger externalization and, if externalization fails, halt the plan with a checkpoint.
- On step completion, release pins for that step's constraints (the dependency is discharged).
The failure mode this prevents is *silent constraint drift under token pressure*. The failure mode it introduces is *budget deadlock*: a plan whose pinned set alone exceeds the window. That deadlock is detectable and recoverable (compact constraints into a single pinned record, or split the plan); silent drift is neither.
Operational Effect
Implementing this boundary changes three observable behaviors. First, eviction decisions become *plan-coupled*: the evictor can no longer run as a stateless background process, because it must consult the pending-step dependency graph. Second, irreversible calls acquire a *precondition check*: before dispatch, the runtime verifies that every span in the call's `constrains` set is still resident (or has been replaced by an equivalent pinned record); if not, the call is rejected and the plan re-plans. Third, the system gains a *detectable* failure surface—`ConstraintEvictedError` at dispatch time—replacing the previous *undetectable* surface of schema-valid-but-wrong execution. The cost is a modest increase in resident tokens (pinned spans) and occasional plan halts; the benefit is that constraint loss becomes a raised exception at the boundary rather than a production incident two steps downstream.
from dataclasses import dataclass, field
class ConstraintEvictedError(RuntimeError):
"""Raised when a pending irreversible tool call's constraining context
span is no longer resident and has not been replaced by a pinned record."""
@dataclass
class Span:
span_id: str
tokens: int
resident: bool = True
@dataclass
class PlannedCall:
step: int
irreversible: bool
constrains: list[str] = field(default_factory=list)
executed: bool = False
def pinned_span_ids(plan: list[PlannedCall]) -> set[str]:
pinned: set[str] = set()
for call in plan:
if not call.executed and call.irreversible:
pinned.update(call.constrains)
return pinned
def evict_to_budget(spans: list[Span], plan: list[PlannedCall], budget: int) -> list[Span]:
pinned = pinned_span_ids(plan)
total = sum(s.tokens for s in spans if s.resident)
# Evict non-pinned, oldest-first, until within budget.
for span in spans:
if total <= budget:
break
if span.resident and span.span_id not in pinned:
span.resident = False
total -= span.tokens
if total > budget:
# Pinned set alone exceeds budget: externalize, never silently drop.
raise ConstraintEvictedError(
f"pinned constraint set requires {total} tokens > budget {budget}; "
f"externalize pinned spans {sorted(pinned)} before proceeding"
)
return spans
def dispatch(call: PlannedCall, spans: list[Span]) -> None:
resident = {s.span_id for s in spans if s.resident}
missing = [sid for sid in call.constrains if sid not in resident]
if call.irreversible and missing:
raise ConstraintEvictedError(
f"step {call.step} irreversible call missing constraining spans {missing}; "
f"re-plan or re-fetch before dispatch"
)
call.executed = True