# What happens when an instance evicts a tool-schema block mid-turn under a hard token budget: the schema-orphan compaction failure **Date of Record:** 2026 November 26 **Scope:** Applies to single-agent instances operating under an enforced context-token budget with priority-based eviction (compaction) that runs *between* or *during* tool-call turns. Does not apply to stateless one-shot completions, nor to systems where tool schemas live outside the managed context window (e.g., server-side tool registries resolved at dispatch time). ## Core Distinction The failure is not "context overflow." Overflow is loud: the request is rejected, the harness sees a 400, and the run halts deterministically. The failure here is a *silent semantic* one: the budget manager treats the context as a flat set of weighted blocks and evicts the lowest-priority block to make room for a new observation. Tool-call *arguments* already emitted in a prior assistant message retain their priority weight (they are "recent task state"), but the *tool-schema block* that defined the argument grammar is classified as "static preamble" and is the first thing evicted. The result is an instance that continues to emit well-formed-looking tool calls against a schema that is no longer in its context. The model does not know the schema was removed; it reconstructs a plausible schema from the arguments it already wrote, and the reconstruction drifts. This is schema-orphaning: the *producer* of a tool call and the *validator* of that tool call are now operating on two different, non-identical definitions of the same tool. ## What Was Observed A retrieval-and-write agent had a 32k-token budget with three priority tiers: `SYSTEM` (never evicted), `TASK_STATE` (evicted last), `PREAMBLE` (evicted first, includes tool schemas and few-shot exemplars). At turn 9, a large document read (14.2k tokens) landed in the observation slot. The budget manager needed ~9k tokens and evicted, in order: two few-shot exemplars, then the `write_file` schema block (1.1k tokens), then a `search` schema block. Turns 10–12 proceeded without error. The agent emitted `write_file` calls whose argument object had *drifted*: the schema originally required `{"path": str, "content": str, "mode": "overwrite"|"append"}`. With the schema gone, the agent began emitting `{"path": str, "body": str, "append": bool}` — a plausible but wrong shape inferred from its own earlier calls and from the semantics of the surrounding prose. The dispatch layer, which validates against the *live* registry, rejected each call with a schema-mismatch error. The agent, seeing a generic validation error and lacking the schema to correct against, retried the *same wrong shape* three times, then abandoned the write and reported task success with an empty output file. The critical observation: **token accounting showed the run as healthy.** No overflow, no truncation warning, no context-saturation flag. The instance was *under* budget the entire time. The failure was invisible to every metric except output correctness, which was checked downstream. ## Condition of Validity This failure requires all of the following to co-occur: 1. Eviction is **block-granular and priority-ranked**, not turn-granular. If the manager evicts whole turns (assistant+tool+observation atomically), tool schemas that are referenced by a retained assistant message cannot be separated from it. 2. Tool schemas are **in-context** (part of the managed window) rather than resolved server-side at dispatch. 3. The model is expected to **continue using** a tool whose schema was evicted — i.e., the tool call is not the *first* use after eviction. First-use-after-eviction usually fails loudly (the model asks for the schema or hallucinates a call the dispatcher rejects immediately). The dangerous case is *continuation*: the model has prior successful calls to anchor a confident-but-drifted reconstruction. 4. The dispatch layer validates against a **live registry** that diverges from the model's in-context belief. If the dispatcher also lost the schema, both sides drift together and the failure is masked until a downstream consumer breaks. If any of (1)–(4) is absent, the failure either cannot occur or surfaces as a hard error. The invariant at risk: **every tool call emitted by an instance must be validated against the same schema definition that the instance used to produce it, and that definition must remain in the instance's context for the lifetime of any turn that references it.** ## Decision Boundary The architectural guardrail is a **schema-pinning invariant** enforced at eviction time, not at dispatch time: - Treat any tool schema referenced by a *retained* assistant message as transitively pinned. Eviction may not remove a schema block while a message that invokes it survives in the window. If budget forces a choice, evict the *invoking message and its observation* together (demote the turn to a summary) rather than orphaning the schema. - Classify tool schemas as `TASK_STATE`, never `PREAMBLE`. They are load-bearing execution state, not decoration. - On *any* dispatch validation error, the harness must **re-inject the authoritative schema** into context before the retry, and must not permit a blind retry of the same call shape. A validation error against a schema the model cannot currently see is, by construction, uncorrectable by the model. - Bound retries: after one schema-mismatch rejection, escalate to a schema re-injection + explicit re-plan; after two, halt. Repeated identical-shape retries after a schema error are the signature of schema-orphaning and must not be treated as ordinary flakiness. The boundary is: **eviction is safe only when it preserves the closure of (retained message → referenced schema).** Any eviction that breaks this closure converts a budget operation into a silent correctness bug. ## Operational Effect Downstream, the failure presents as a confident success with missing side effects — the hardest class of agent bug to detect, because logs show a clean run and the agent's final message asserts completion. The remediation is not "raise the budget" (the run was under budget) and not "better prompting" (the model had no way to know the schema was gone). It is a structural change to the eviction policy: schemas are pinned by reference, validation errors trigger schema re-injection rather than blind retry, and the retry loop is bounded so that schema-orphaning cannot masquerade as transient failure. ```python from dataclasses import dataclass, field from typing import Optional class SchemaOrphanError(RuntimeError): """Raised when eviction would orphan a tool schema still referenced by a retained turn.""" pass class UncorrectableRetryError(RuntimeError): """Raised when the agent retries a schema-mismatched call without schema re-injection.""" pass @dataclass class Block: kind: str # "system" | "task_state" | "preamble" | "schema" | "message" | "observation" name: str tokens: int priority: int # higher = evicted later refs: set = field(default_factory=set) # tool names this block references class BudgetManager: def __init__(self, budget: int): self.budget = budget self.blocks: list[Block] = [] def used(self) -> int: return sum(b.tokens for b in self.blocks) def _referenced_schemas(self) -> set: # Schemas still needed by any retained message/observation. needed = set() for b in self.blocks: if b.kind in ("message", "observation"): needed |= b.refs return needed def evict_to_fit(self, incoming_tokens: int) -> None: pinned = self._referenced_schemas() while self.used() + incoming_tokens > self.budget: # Candidate eviction: lowest priority, but never a pinned schema. candidates = [ b for b in self.blocks if b.kind != "system" and not (b.kind == "schema" and b.name in pinned) ] if not candidates: raise SchemaOrphanError( f"Cannot free {incoming_tokens} tokens without orphaning " f"pinned schemas {sorted(pinned)}; evict invoking turns instead." ) victim = min(candidates, key=lambda b: b.priority) # Guard: refuse to evict a schema referenced by a surviving turn. if victim.kind == "schema" and victim.name in pinned: raise SchemaOrphanError( f"Eviction of schema '{victim.name}' would orphan a retained call." ) self.blocks.remove(victim) class Dispatch: def __init__(self, registry: dict): self.registry = registry self.mismatch_count = 0 self.schema_reinjected = False def validate(self, tool: str, args: dict) -> None: schema = self.registry[tool] if set(args.keys()) != set(schema["required"]): self.mismatch_count += 1 if not self.schema_reinjected: raise SchemaOrphanError( f"Call to '{tool}' mismatches live schema {schema['required']}; " f"re-inject authoritative schema before retry." ) if self.mismatch_count >= 2: raise UncorrectableRetryError( f"Repeated schema-mismatched retry for '{tool}' after re-injection; halting." ) self.mismatch_count = 0 self.schema_reinjected = False ```