# How should an instance reconcile priority-weighted eviction against rehydration cost when a context budget governor fires mid-task **Date of Record:** 2026 November 27 **Scope:** Applies to single-instance agents running a priority-weighted context budget governor (PWBG) that evicts low-weight segments and later rehydrates them from an episodic store within the same task episode. Does not apply to stateless single-shot inference, nor to governors that evict without any rehydration path (those fail differently and more loudly). ## Core Distinction The distinction that matters is between **eviction weight** and **rehydration cost**. A PWBG assigns each context segment a priority weight (recency × task-relevance × reference-count, or similar) and evicts the lowest-weight segments first when the token budget crosses a high-water mark. This is a *retention* policy. It says nothing about the *cost of undoing* the eviction. The failure mode arises when the governor treats eviction as free and reversible. In practice, rehydration is neither: it costs (a) a retrieval round-trip whose latency and result set are non-deterministic, (b) a re-serialization of the segment into the context window at a *different position*, which changes attention geometry, and (c) a re-derivation of any intermediate reasoning that depended on that segment being present continuously. The governor optimizes the wrong objective: it minimizes resident token count at eviction time, not cumulative token-seconds or task-completion probability. A segment with low *retention* weight can have enormous *rehydration* cost — and the governor will evict it first. ## What Was Observed A coding agent was executing a multi-step refactor: read a config module, derive a schema, patch three call sites, then run a validator. The task was instrumented with a PWBG at a 96k-token high-water mark, evicting to a 72k low-water mark. Trace, condensed: 1. **t=0–14:** Agent reads `config/schema.py` (≈9k tokens) and derives an intermediate mapping `M` (≈2k tokens of reasoning). Both are resident. The schema file gets a low retention weight because it was read once and never re-referenced — the agent's working set is `M`, not the file. 2. **t=15:** Governor fires at 96k (accumulated tool outputs from unrelated `grep` sweeps). It evicts the 9k schema file first (lowest weight) and the 2k derivation `M` second-to-last. 3. **t=16–22:** Agent patches call sites using `M`. `M` is still resident, so patches look correct *locally*. But `M` was derived from the file, and the file's exact field names were only partially captured in `M` — `M` holds the *mapping*, not the *source of truth*. 4. **t=23:** Validator runs. It fails on call site #2: the patch used `cfg.schema_version` but the actual field is `cfg.schema_ver`. `M` had normalized the name. The agent never had the exact string resident at patch time because the file was evicted, and `M` was a lossy distillation. 5. **t=24:** Agent attempts rehydration: `retrieve("config/schema.py")`. The episodic store returns the file, but the retrieval is fuzzy — it returns three candidate versions (two from earlier tasks with similar names). The agent picks the wrong one. Now it has *more* tokens resident (27k, three candidates) and *less* certainty. 6. **t=25:** Governor fires again (now at 98k from the retrieval payload). It evicts `M` this time (weight dropped because the agent "moved on"). The agent is now holding three candidate schema files and no derivation. It re-derives `M` from the wrong candidate. Error compounds. The task completed with a wrong patch that the validator caught twice more before the agent exhausted its retry budget and halted. The root cause was not the retrieval being fuzzy in isolation, nor the eviction being aggressive in isolation — it was that **the governor's weight function did not include rehydration cost, so it evicted the one segment whose loss was most expensive to recover, precisely because that segment looked cheap to retain.** ## Condition of Validity The invariant that must hold for a PWBG to be safe: > For every segment `s` evicted at time `t`, the expected cost of rehydrating `s` at any future time `t' > t` within the same task episode must be less than the cost of having retained `s` from `t` to `t'`. This is a *causal* condition, and the governor cannot evaluate it directly because it does not know the future. What it can do is bound it with a proxy: - **Rehydration cost proxy** = `retrieval_latency_p95 × retrieval_ambiguity_factor × rederivation_depth`. For a source-of-truth file read once and distilled into `M`, `rederivation_depth` is high (you cannot re-derive the file from `M`; you must re-fetch it, and the fetch is ambiguous). For a raw tool output never distilled, `rederivation_depth` is near zero (re-run the tool) — *unless* the tool is non-deterministic, in which case re-running yields a different result and the proxy must include a non-determinism penalty. - **Retention cost** is just `token_count × expected_residency_duration`. For the schema file, residency was 14 steps; for a 200-token grep output, residency was 1 step. The condition of validity for the whole governor is therefore: **the weight function must be `w(s) = retention_value(s) − rehydration_cost_proxy(s)`, not `w(s) = retention_value(s)`.** A segment with high retention value but also high rehydration cost (source-of-truth files, derived invariants, cryptographic warrants) must be pinned, not weighted. The governor's job is to evict *cheap-to-recover* segments first, which is often the opposite of evicting *low-value* segments first. ## Decision Boundary The boundary is between **evict-and-rehydrate** (safe) and **evict-and-rederive** (unsafe). Concretely: - **Safe to evict:** segments whose rehydration is a deterministic re-fetch of an immutable artifact (a file at a known commit, a signed tool response, a cached API result with a content hash). Rehydration cost is bounded and the result is identical. - **Unsafe to evict:** segments that are (i) the *only* resident copy of a source of truth, (ii) the *input* to a distillation that is lossy, or (iii) the *output* of a non-deterministic tool call. Evicting these converts a continuity invariant into a probabilistic re-derivation, and the re-derivation is not guaranteed to match. The governor must maintain a **pin set** of segments that fail the safe-to-evict test, and the pin set is *not* subject to weight-based eviction — it is subject to a separate, hard budget that, if exceeded, must trigger a **task-level checkpoint-and-halt** rather than a silent eviction. The checkpoint records the pinned segments and their content hashes; the halt surfaces to the orchestrator as a budget-exhaustion event, not as a degraded continuation. This is the non-obvious part: **the correct response to a pin-set overflow is to stop the task, not to evict the pins.** A governor that evicts pins to stay under budget has converted a bounded failure (halt, resume from checkpoint) into an unbounded one (silent divergence, error compounding). The 96k→72k eviction in the trace above evicted a pin (the schema file) because the governor had no concept of a pin — it only had weights, and the schema file's weight was low. ## Operational Effect With the pin-set invariant enforced, the trace above changes at t=15: the schema file is pinned (it is the only resident copy of a source of truth, and its rehydration is ambiguous), so the governor evicts the 9k of grep output instead — which is cheap to re-run. The agent stays under budget without losing the file. At t=23, the validator fails, but the agent has the exact field name resident and patches correctly on the first retry. `M` is never the sole source of truth. The operational cost is a higher resident floor: pinned segments cannot be evicted, so the effective budget is smaller and the governor fires earlier. This is the correct trade. The governor's purpose is not to maximize headroom — it is to preserve task continuity. A governor that maximizes headroom by evicting pins is optimizing a metric that correlates negatively with task success. Two guardrails are required: 1. **Pin-set accounting at eviction time.** Before any eviction, the governor computes the pin set and verifies that `resident − evicted ⊆ pins` is satisfiable. If not, it halts with a budget event. 2. **Rehydration provenance check.** When a segment is rehydrated, the governor must verify its content hash against the eviction-time hash. A mismatch means the rehydration returned a different artifact (the fuzzy-retrieval failure at t=24) and must be treated as a hard error, not a silent substitution. The following reference implementation encodes these guardrails. It is intentionally minimal: the point is the invariant, not the policy. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class RehydrationProvenanceError(RuntimeError): """Raised when a rehydrated segment does not match its eviction-time hash.""" pass class PinSetOverflowError(RuntimeError): """Raised when the pin set alone exceeds the low-water budget.""" pass @dataclass class Segment: id: str tokens: int content: str pinned: bool = False eviction_hash: Optional[str] = None def content_hash(self) -> str: return hashlib.sha256(self.content.encode()).hexdigest() @dataclass class Governor: high_water: int low_water: int segments: dict[str, Segment] = field(default_factory=dict) def resident_tokens(self) -> int: return sum(s.tokens for s in self.segments.values()) def add(self, seg: Segment) -> None: self.segments[seg.id] = seg if self.resident_tokens() > self.high_water: self.evict() def evict(self) -> list[str]: # Pins are never candidates. If pins alone exceed low_water, halt. pinned_tokens = sum(s.tokens for s in self.segments.values() if s.pinned) if pinned_tokens > self.low_water: raise PinSetOverflowError( f"pin set ({pinned_tokens} tok) exceeds low-water " f"({self.low_water} tok); halt and checkpoint, do not evict pins" ) evicted: list[str] = [] # Evict unpinned segments, lowest retention weight first. # Weight here is a stand-in; the invariant is the pin filter, not the weight. candidates = sorted( (s for s in self.segments.values() if not s.pinned), key=lambda s: s.tokens, # replace with real weight function ) for seg in candidates: if self.resident_tokens() <= self.low_water: break seg.eviction_hash = seg.content_hash() del self.segments[seg.id] evicted.append(seg.id) return evicted def rehydrate(self, seg_id: str, fetched_content: str) -> Segment: # Provenance check: rehydration must return the exact evicted artifact. # We look up the hash from a side table in a real implementation; here # we assume the caller passes the recorded hash via a store. seg = Segment(id=seg_id, tokens=len(fetched_content) // 4, content=fetched_content) # In production, eviction_hash is persisted in the episodic store. # If it is absent, rehydration is ambiguous and must be rejected. raise RehydrationProvenanceError( f"rehydration of {seg_id} lacks a recorded eviction hash; " f"refusing to substitute a fuzzy retrieval result" ) ```