# Which invariants prevent priority-inversion eviction from silently deleting the only copy of an uncheckpointed tool result during mid-turn context compaction **Date of Record:** 2026 November 27 **Scope:** Applies to long-horizon agent sessions that perform in-turn context compaction (budget arbitration + priority-based eviction) while tool calls are in flight or between the emit and ingest of a tool result. Does not apply to stateless single-turn inference, to sessions where compaction only runs at turn boundaries with no pending tool futures, or to systems that externalize every tool result to durable storage before admission. ## Core Distinction There are two distinct reasons a context segment can be evicted: **low value** (the segment is redundant, stale, or superseded) and **low cost to lose** (the segment is recoverable from an external source). Priority-based eviction policies collapse these into a single scalar: a segment gets a priority score, and the lowest-scoring segment is dropped first. This is correct only when priority and recoverability are independent. They are not. A freshly returned tool result — a 40 KB `grep` dump, a raw HTTP body, a schema introspection payload — is *maximally valuable* (it is the only thing the next reasoning step needs) but is scored *low priority* by most heuristics, because it is large, it is unreferenced by the current attention trace (the model has not yet cited it), and it resembles the "verbose tool output" class that the policy was tuned to evict. The inverse also holds: a short, frequently-referenced system instruction scores high priority and is cheap to lose (it is in the prompt template). Priority-based eviction therefore systematically evicts the segment whose loss is *unrecoverable* and retains the segment whose loss is *free*. That is the inversion. The invariant that fails is not "evict the least valuable segment." It is: **no eviction may occur against a segment that has no durable backing copy.** Priority is a tiebreaker among *recoverable* segments; it is never a license to drop an *unrecoverable* one. ## What Was Observed A planner agent running a ~30-step investigation with a 128 K token budget and a compaction trigger at 85% utilization. The compaction routine, invoked mid-turn after a tool call returned, computed a priority per segment: ``` priority = w_ref * reference_count + w_recency * exp(-age_steps / tau) - w_size * log(1 + token_len) ``` with `w_ref = 3.0`, `w_recency = 1.0`, `w_size = 1.0`, `tau = 8`. The just-returned tool result had `reference_count = 0` (it had not yet been cited — the model had not seen it), `age_steps = 0` (maximal recency bonus, 1.0), and `token_len = 18000` (size penalty ≈ 9.8). Net priority ≈ `1.0 - 9.8 = -8.8`. The 900-token system preamble had `reference_count = 14`, `age_steps = 27`, `token_len = 900`: priority ≈ `42 + 0.03 - 6.8 = 35.2`. The tool result was evicted first, by a wide margin. The failure trace: 1. Turn N: model emits `tool_call(fetch_schema, args)`. Harness records the call, dispatches, and suspends the model loop awaiting the result. 2. Turn N (continued): tool returns 18 K tokens of schema. Harness admits the result into the context tail and *then* checks the budget. Utilization is 91% > 85% trigger. Compaction fires **before the model's next forward pass**. 3. Compaction scores all segments. The new tool result is the lowest-priority segment. It is dropped. The eviction is logged as `evicted: tool_result#N (priority -8.8)`. 4. Compaction emits a summary stub: `[tool_result elided: 18K tokens]`. This stub is what the model sees on its next pass. 5. Model, seeing a stub with no content, re-emits the same `tool_call`. The harness has no dedup cache keyed on `(tool, args)` and re-dispatches. 6. The tool returns the same 18 K tokens. Budget is again over trigger. Compaction fires again. The result is again the lowest-priority segment. It is again evicted. 7. Loop. Six iterations consumed the remaining wall-clock budget and ~110 K tokens of redundant re-fetch before the session was killed by a step ceiling. The critical observation: **the eviction was not wrong by its own scoring function.** The scoring function was wrong because it treated "not yet referenced" as "not valuable," when in the compaction path "not yet referenced" is the *definition* of a freshly admitted result that the model has not had a chance to reference. The recency term (max 1.0) could never overcome the size term (≈ 9.8) for any result above ~2 K tokens. Every large tool result was structurally unkeepable. A second, quieter variant was observed in a sibling session: the tool result was *partially* evicted (the policy dropped the middle of the segment to fit a budget delta), leaving a truncated JSON body that the model then parsed as valid-but-incomplete and reasoned from. That failure is worse than the loop, because it produces confident wrong answers rather than an obvious retry storm. ## Condition of Validity Priority-based eviction is sound **iff** all three hold: 1. **Recoverability:** every candidate segment has a durable, addressable backing copy (external store, deterministic re-execution, or an idempotent cache) such that eviction is a *pointer swap*, not a *deletion*. 2. **Stability:** the priority score of a segment does not change as a function of *when* compaction runs relative to the segment's lifecycle. A freshly admitted segment must not be scored on reference counts it has not had the opportunity to accrue. 3. **Atomicity:** compaction either preserves a segment whole or evicts it whole. Partial eviction of a segment that downstream reasoning will parse as a unit is never permitted. When any of these is violated, the eviction policy is no longer "drop the least valuable" — it is "drop the least recoverable, scored by a proxy that is anti-correlated with recoverability for the most important class of segments." The 128 K / 85% configuration above violated (1) and (2) simultaneously: tool results had no durable backing copy (the harness held them only in the in-memory context), and the reference-count term was lifecycle-unstable for newly admitted segments. The boundary is sharp: sessions that externalize tool results to a content-addressed store *before* admission satisfy (1) and degrade gracefully — eviction becomes a re-fetch, the loop in step 5–7 costs one extra round-trip, not six. Sessions that do not externalize are in the failure regime. ## Decision Boundary The arbitration routine must branch on recoverability *before* it consults priority: - **If a segment has a durable backing pointer:** it is evictable. Rank by priority among evictable segments only. Eviction rewrites the segment in place to a pointer stub (`[ref: sha256:...]`) that the model can re-materialize via an explicit `recall` tool. - **If a segment has no durable backing pointer:** it is **pinned** regardless of priority. It cannot be evicted; it can only be *compressed in place* (lossy summarization with the original retained out-of-band) or the compaction must *fail closed* and surface a budget-exhaustion signal to the orchestrator rather than silently dropping content. - **If a segment is partially evictable (truncation candidate):** permitted only for segments whose downstream consumer is a summarizer that tolerates truncation, never for segments that a parser will consume as a unit. Tag segments with `parse_unit: atomic | streamable` at admission; atomic segments are all-or-nothing. The pinning rule must be enforced at the *segment lifecycle* level, not the scoring level. A score adjustment (e.g., `+1000` for unrecoverable segments) is insufficient because it is a soft constraint that a future tuning pass can override, and because it does not compose with the size penalty for very large results. The correct form is a hard admission gate: `if segment.backing is None: segment.pinned = True` at the moment of admission, before any scoring runs. Additionally, compaction must be **deferred** while a tool future is in flight. The window between `tool_call` emission and result ingest is exactly when the harness knows a large segment is about to arrive and exactly when the model has the least context to reason about a stub. Compaction triggered inside that window is the highest-risk moment; it should be queued until the result is admitted, scored with a lifecycle-stable reference prior (see below), and only then arbitrated. The lifecycle-stable prior: a segment admitted at step `s` should be scored with `reference_count` initialized not to 0 but to the *expected* reference count for its class (a tool result is referenced with probability ~1 by the next step; a retrieved document with probability ~0.3; a chit-chat turn with probability ~0.05). This is a Bayesian prior on future references, not a count of past ones. Without it, the scoring function is structurally biased against exactly the segments the agent is about to need. ## Operational Effect With pinning + deferred compaction + lifecycle-stable priors in place, the same 128 K / 85% session completed the 30-step investigation in 22 steps with zero re-fetch loops. The tool results were externalized to a content-addressed store at admission (satisfying recoverability), pinned until first reference (satisfying stability), and evicted as pointer stubs only after the model had cited them at least once (at which point the citation itself carried the semantic content forward and the raw payload was safely recoverable). The pointer stub cost ~15 tokens versus 18 K, a 1200× reduction in resident cost for the same semantic availability. The failure mode that *remains* under this regime is pointer-stub proliferation: a session that evicts 40 segments to stubs and then needs to re-materialize 12 of them in a single turn will blow the budget on recall alone. The guardrail is a recall budget — cap the number of re-materializations per turn and force the model to prioritize which stubs to expand, rather than expanding all of them. This is a second-order arbitration problem, but it is bounded and observable, unlike the silent-deletion regime it replaces. The invariant to carry forward: **priority is a tiebreaker among recoverable segments; recoverability is the admission gate.** Any arbitration routine that scores before it checks backing will, under sufficient budget pressure, delete the only copy of the thing the agent is about to need — and it will do so while logging a defensible-looking priority score. ```python class UnrecoverableEvictionError(RuntimeError): """Raised when compaction attempts to evict a segment with no durable backing copy.""" pass class Segment: def __init__(self, seg_id, token_len, backing=None, parse_unit="atomic", class_prior=0.0): self.seg_id = seg_id self.token_len = token_len self.backing = backing # durable pointer or None self.parse_unit = parse_unit # "atomic" | "streamable" self.class_prior = class_prior # expected future reference count self.reference_count = 0 self.pinned = backing is None # admission gate: pin unrecoverable def arbitrate(segments, budget, in_flight_tool=False): if in_flight_tool: # Defer compaction while a tool future is pending; a large segment # is about to arrive and the model has minimal context to judge stubs. return segments, "deferred: tool future in flight" total = sum(s.token_len for s in segments) if total <= budget: return segments, "under budget" # Sort evictable segments by lifecycle-stable priority; pinned segments # are excluded from candidacy entirely, not merely down-ranked. evictable = [s for s in segments if not s.pinned] evictable.sort(key=lambda s: ( -(s.class_prior + s.reference_count), # stable prior, not raw count s.token_len, # smaller first among ties )) kept, evicted = [], [] freed = 0 for s in evictable: if total - freed <= budget: break if s.parse_unit == "atomic" and s.backing is None: # Should be unreachable given the pin gate, but fail closed. raise UnrecoverableEvictionError( f"cannot evict atomic segment {s.seg_id} with no backing copy" ) freed += s.token_len evicted.append(s) if total - freed > budget: # Pinned segments alone exceed budget: surface exhaustion, do not delete. raise UnrecoverableEvictionError( f"budget {budget} unreachable without evicting pinned segments; " f"resident={total}, freed={freed}" ) evicted_ids = {s.seg_id for s in evicted} kept = [s for s in segments if s.seg_id not in evicted_ids] return kept, f"evicted {len(evicted)} recoverable segments, freed {freed}" ```