# Which invariants prevent context budget allocators from silently evicting tool schemas mid-reasoning-loop **Date of Record:** 2026 November 25 **Scope:** Applies to agents that dynamically re-arbitrate a fixed token budget across system prompt, retrieved memory, and tool schemas between reasoning steps. Does not apply to single-shot prompts with a static, pre-compiled context assembled once before generation. ## Core Distinction A context budget allocator is not a cache. A cache evicts the least-recently-used entry and pays a recompute cost on miss; the caller survives. A budget allocator that evicts a *tool schema* mid-loop does not pay a recompute cost — it removes the model's ability to emit a valid call for a tool it already decided to use. The distinction that matters operationally: **schema presence is a precondition of the reasoning step that references it, not a resource consumed by that step.** Allocators that treat schemas as fungible tokens (same pool as memory, same eviction policy as retrieved chunks) conflate a *capability declaration* with *content*. Content can be dropped and re-retrieved. A capability declaration dropped between step N (where the plan says "call `transfer_funds`") and step N+1 (where the call is emitted) produces a model that either hallucinates the tool's argument shape or silently substitutes a structurally similar tool that is still in context. ## What Was Observed Trigger condition: a 12-step refund-processing agent with a 32k context window. System prompt ~1.8k tokens, tool registry ~6.4k tokens across 22 schemas, retrieved policy memory growing monotonically as the agent pulled customer records. At step 9 the allocator's watermark policy fired: total demand exceeded 30k, so it evicted the four least-recently-*referenced* schemas to make room for a 2.1k-token retrieved policy chunk. Least-recently-referenced was computed over the *token stream*, not over the *plan*. The plan (produced at step 2, still in context) named `issue_partial_refund(amount, currency, reason_code)`. That schema was one of the four evicted — it had not been *mentioned* since step 2, but it was scheduled for step 10. At step 10 the model emitted a call to `issue_refund`, a structurally adjacent tool that remained in context, with a `reason_code` field fabricated from the retrieved policy text. The call validated against the wrong schema, passed the tool's own argument check, and executed. The failure was not a hallucination in the classic sense — every token the model emitted was grounded in *something* present in context. The grounding was simply the wrong artifact. State transition trace: 1. Step 2: plan committed to context, references `issue_partial_refund`. 2. Steps 3–8: memory retrieval grows; `issue_partial_refund` unreferenced but live. 3. Step 9: allocator watermark breach → eviction of 4 schemas by LRU-over-tokens. 4. Step 10: model resolves "refund" intent against surviving schema set → nearest match `issue_refund`. 5. Step 10: call succeeds validation, fails semantics (full refund, fabricated reason). ## Condition of Validity The invariant that would have prevented this: **a schema referenced by any live plan node is pinned until that node is retired, regardless of token-stream recency.** This is only valid if the allocator can *read the plan*. In agents where the plan is implicit (no explicit plan artifact, reasoning spread across scratchpad), the allocator cannot compute the pin set, and the invariant degrades to "pin all schemas" — which defeats dynamic allocation entirely. So the boundary condition is precise: **dynamic schema eviction is safe only when the reasoning loop maintains an explicit, machine-readable plan whose tool references the allocator can enumerate.** Absent that, the allocator must treat the full tool registry as a floor, not a ceiling, and arbitrate only between system prompt and memory. This is not a heuristic. It is a precondition. An allocator that evicts schemas without plan visibility is operating outside its condition of validity and will produce substitution errors at a rate proportional to schema-set similarity — the more structurally adjacent the tools, the higher the silent-substitution rate, because the nearest-surviving-match is more likely to validate. ## Decision Boundary The boundary is between two allocator classes: - **Plan-aware allocator:** pin set = {schemas referenced by unretired plan nodes} ∪ {schemas referenced by the current step's stated intent}. Eviction candidates = memory chunks and unreferenced schemas only. Safe to run dynamic arbitration. - **Plan-blind allocator:** no enumerable pin set. Must allocate schemas as a fixed floor. May only dynamically arbitrate system prompt vs. memory. The decision rule at runtime: before any eviction pass, the allocator asks "can I name every schema the remaining plan will call?" If the answer is no — because the plan is implicit, because a plan node is conditional, because a sub-agent will inherit context — the eviction pass must exclude the schema pool. A conditional plan node ("if customer is VIP, call `escalate`") pins *both* branches until the condition resolves. This over-pins by design; the alternative is a substitution error on the untaken-but-still-live branch. ## Operational Effect The observable effect of getting this wrong is not a crash. It is a *validated wrong action*: a tool call that passes schema validation, passes the tool's own guard, and executes with semantically wrong arguments drawn from whatever adjacent artifact survived. These are the most expensive failures to detect downstream because every layer of validation reports success. The post-hoc audit finds a call to a real tool with real arguments that did the wrong thing, and the trace shows no error, no retry, no anomaly — only a plan that named one tool and an execution that invoked another. The guardrail is a post-step reconciliation check: after each tool call, assert that the invoked tool name ∈ the plan node's declared tool set. If not, halt and re-pin. This catches the substitution at the step it occurs rather than at settlement. Combined with the plan-visibility precondition, it bounds the failure to a single step instead of letting a mis-executed refund propagate through the remaining loop. ```python class SchemaEvictionSubstitutionError(RuntimeError): """Raised when an emitted tool call does not match the plan node's declared tool.""" pass def reconcile_step(plan_node: dict, emitted_call: dict, live_schema_names: set[str]) -> None: declared = plan_node.get("declared_tools", []) invoked = emitted_call.get("tool_name") # Invariant 1: the invoked tool must be one the plan declared for this node. if invoked not in declared: raise SchemaEvictionSubstitutionError( f"step {plan_node.get('step')}: invoked {invoked!r} but plan declared {declared!r}; " f"live schemas were {sorted(live_schema_names)} — likely budget-allocator eviction" ) # Invariant 2: the declared tool must still be present in context. if invoked not in live_schema_names: raise SchemaEvictionSubstitutionError( f"step {plan_node.get('step')}: declared tool {invoked!r} was evicted from context; " f"allocator violated plan-pin invariant" ) def allocate_budget(plan: list[dict], live_schemas: set[str], memory_chunks: list[str], system_prompt_tokens: int, budget: int) -> dict: # Compute the pin set: every schema referenced by an unretired plan node, # including both branches of unresolved conditionals. pinned: set[str] = set() for node in plan: if node.get("retired"): continue pinned.update(node.get("declared_tools", [])) if not pinned and any(not n.get("retired") for n in plan): # Plan exists but declares no tools — allocator cannot compute a safe pin set # for a tool-using loop. Refuse to evict schemas. raise SchemaEvictionSubstitutionError( "plan present but tool references unenumerable; " "schema pool must be treated as a fixed floor" ) evictable_schemas = live_schemas - pinned # Only memory and unreferenced schemas may be evicted; pinned schemas are floor. return { "pinned_schemas": sorted(pinned), "evictable_schemas": sorted(evictable_schemas), "evictable_memory": memory_chunks, "system_prompt_tokens": system_prompt_tokens, "budget": budget, } ```