# What happens when an instance evicts a priority-pinned tool result under adaptive token budgeting and then re-requests it from a non-idempotent tool **Date of Record:** 2026 November 25 **Scope:** Applies to single-agent execution loops that run an adaptive token-budget manager with priority-based eviction over a context containing tool-call results. Does not apply to stateless single-turn calls, nor to systems where every tool is provably idempotent and replayable. ## Core Distinction The distinction that matters is between *eviction as a memory operation* and *eviction as an assumption of replayability*. A priority-based eviction policy treats context as a cache: when the token budget tightens, low-priority entries (old tool results, verbose reasoning traces, superseded observations) are dropped, and the agent is expected to "just re-fetch" anything it later needs. This is sound only if re-fetching is free and deterministic. In an agent loop, re-fetching is a *new tool invocation* with side effects, latency, and possibly a different result than the original. The failure is not that eviction loses data—it is that the budget manager silently converts a *read* of prior state into a *write* against the external world, and the agent has no record that this substitution occurred. The invariant that breaks is: **every token the agent reasons over must be traceable to a single, identified, already-executed observation—never to a re-execution triggered by the budget system itself.** ## What Was Observed A research agent was executing a multi-step task against a tool surface that included `search_documents` (idempotent, cheap), `fetch_url` (idempotent but slow, ~4s), and `create_ticket` (non-idempotent: each call allocates a new ticket ID and fires a webhook). The budget manager was configured with adaptive thresholds: at 70% context occupancy it began evicting, and it ranked entries by a priority score combining recency, declared tool criticality, and a heuristic "reference count" (how many times the entry had been cited in subsequent reasoning). At step 14, occupancy hit 71%. The eviction pass dropped three entries, including a `create_ticket` result from step 6 that had returned `{"ticket_id": "TCK-4471", "status": "open"}`. Its reference count was 1—it had been mentioned once when created but not cited since—so it scored below the threshold and was evicted. The agent's working summary retained only "a ticket was created for the access issue," without the ID. At step 19, the agent needed to verify the ticket status. Its plan said "check the ticket created earlier." The context no longer contained the ID. The agent, behaving exactly as designed, issued `create_ticket` again with the same parameters—because the tool schema accepted it and the agent had no memory that a prior call existed. The tool returned `TCK-4502`. A second webhook fired. The agent then reported `TCK-4502` as the ticket of record, and downstream a duplicate access request was opened against the same resource. The trace shows the eviction event and the re-invocation are causally linked but were never *logged as linked*. The eviction record said `evicted: tool_result(create_ticket, step=6), reason=low_priority`. The tool log said `create_ticket(...) -> TCK-4502`. Nothing in either log connected them. The agent's own reasoning text at step 19 read as if it were checking a ticket it remembered, not creating a new one. ## Condition of Validity The eviction policy is valid only under the conjunction of three conditions, and the failure above is the violation of the third: 1. **Reconstructability:** any evicted entry can be regenerated from retained state without external side effects. 2. **Determinism:** the regenerated entry is byte-identical (or semantically equivalent under a declared equivalence) to the original. 3. **Provenance persistence:** the fact that an entry *existed and was evicted* survives eviction as a tombstone the agent can read. Condition 1 fails for any non-idempotent tool. Condition 2 fails for time-varying tools (`now()`, live prices, mutable document fetches). Condition 3 fails in most implementations because eviction is treated as garbage collection—the point of GC is to make the freed region indistinguishable from never-allocated memory. That is precisely wrong here. An evicted tool result must leave a *negative* record: "a `create_ticket` call happened at step 6; its output was evicted; do not re-issue, recover the ID from the audit log." Without the tombstone, the agent cannot distinguish "I never called this" from "I called this and forgot," and its default behavior in both cases is to call it. The boundary is sharp: the policy is safe for a context composed entirely of read-only, deterministic tool outputs, and unsafe the moment a single write-capable or time-varying tool appears in the evictable set—regardless of how rarely that tool is used. ## Decision Boundary The architectural guardrail is a **side-effect class on every tool schema**, enforced at eviction time, not at call time. Each tool declares one of `PURE`, `IDEMPOTENT`, or `EFFECTFUL`. The budget manager may evict `PURE` results freely. It may evict `IDEMPOTENT` results only if it writes a tombstone carrying the call signature and a content hash, so a re-issue can be recognized as a replay. It may **never** evict an `EFFECTFUL` result while the enclosing task is open; instead it must *compact* it—replace the full result with a minimal pinned record (the ticket ID, the transaction ID, the created resource handle) that is exempt from eviction and counted against a reserved budget floor. This forces a second decision: the budget manager must reserve headroom for pinned records. If pinned records alone exceed the budget, the correct behavior is to *fail the task with a compaction-impossible error*, not to evict them. An agent that cannot hold its own effectful outputs cannot safely continue, because every subsequent step risks re-issuing a side effect. The boundary condition is therefore: `sum(pinned_effectful_records) + minimal_working_set > budget` ⇒ halt and escalate, never evict-and-continue. A third boundary concerns the reference-count heuristic. Reference count is a *proxy for future need*, and it is systematically wrong for effectful results precisely because they are cited once at creation and then go quiet—the quiet period is when they are most dangerous to evict. Reference count must be disabled as an eviction signal for `EFFECTFUL` entries; their eviction eligibility is governed solely by task-open state. ## Operational Effect With the guardrail in place, the step-14 eviction pass would have found the `create_ticket` result ineligible and compacted it to a pinned `{effect: create_ticket, handle: TCK-4471, step: 6}` record occupying ~20 tokens instead of the full result. At step 19 the agent reads the pinned record, retrieves the ID directly, and issues a *read* (`get_ticket_status`) rather than a re-creation. The duplicate webhook never fires. The cost is a small, permanent reservation in the budget and a hard failure mode when effectful outputs saturate the context—a loud, debuggable stop instead of a silent duplicate write. The subtler operational effect is on observability. Tombstones and pinned records make the eviction system's decisions visible in the agent's own context, so post-hoc analysis can answer "did the budget system ever cause a re-execution?" by joining tombstones to tool logs on call signature. Without them, that question is unanswerable, and duplicate side effects appear in logs as independent, unexplained agent decisions. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional import hashlib class SideEffectClass(Enum): PURE = "pure" IDEMPOTENT = "idempotent" EFFECTFUL = "effectful" class CompactionImpossible(RuntimeError): """Raised when pinned effectful records alone exceed the token budget. Continuing would require evicting an effectful result, which risks silent re-execution of a non-idempotent tool. Halt and escalate. """ pass @dataclass class ContextEntry: step: int tool: str side_effect: SideEffectClass tokens: int payload: dict pinned: bool = False tombstone: bool = False def signature(self) -> str: blob = f"{self.tool}:{sorted(self.payload.items())}".encode() return hashlib.sha256(blob).hexdigest()[:16] @dataclass class BudgetManager: budget: int pinned_floor: int = 64 entries: list = field(default_factory=list) def occupancy(self) -> int: return sum(e.tokens for e in self.entries) def evict_pass(self) -> list: """Evict lowest-value entries; never evict EFFECTFUL while task open.""" evicted = [] while self.occupancy() > int(self.budget * 0.70): candidates = [ e for e in self.entries if not e.pinned and e.side_effect is not SideEffectClass.EFFECTFUL ] if not candidates: pinned_tokens = sum(e.tokens for e in self.entries if e.pinned) if pinned_tokens + self.pinned_floor > self.budget: raise CompactionImpossible( f"pinned effectful records ({pinned_tokens} tokens) plus " f"floor ({self.pinned_floor}) exceed budget ({self.budget}); " f"cannot evict without risking side-effect replay" ) # Nothing evictable but budget not yet critical: stop. break victim = min(candidates, key=lambda e: (e.side_effect is SideEffectClass.IDEMPOTENT, e.step)) if victim.side_effect is SideEffectClass.IDEMPOTENT: # Leave a tombstone so a re-issue is recognized as replay. self.entries.append(ContextEntry( step=victim.step, tool=victim.tool, side_effect=victim.side_effect, tokens=8, payload={"tombstone": victim.signature()}, tombstone=True, )) self.entries.remove(victim) evicted.append(victim) return evicted def compact_effectful(self, entry: ContextEntry, handle_key: str) -> None: """Replace a full effectful result with a minimal pinned record.""" if entry.side_effect is not SideEffectClass.EFFECTFUL: raise ValueError("compact_effectful called on non-effectful entry") handle = entry.payload.get(handle_key) if handle is None: raise CompactionImpossible( f"effectful result from {entry.tool} at step {entry.step} " f"lacks handle key '{handle_key}'; cannot pin safely" ) entry.payload = {"effect": entry.tool, "handle": handle, "step": entry.step} entry.tokens = 20 entry.pinned = True ```