When must an instance evict the wrong memory: priority inversion in concurrent-subtask context-window arbitration

**Date of Record:** 2026 December 2 **Scope:** Applies to single LLM instances multiplexing two or more concurrent subtasks into one shared context window under a priority-based eviction policy (e.g., a planner loop plus a long-running tool-wait, or a parent agent servicing interleaved child requests). Does not apply to instances with a dedicated context per subtask or to purely sequential single-threaded execution.

Core Distinction

The failure is not context-window saturation itself—saturation is expected and handled by eviction. The failure is **priority inversion during eviction**: the arbitration policy ranks segments by the *declared* priority of the subtask that produced them, but the segment actually required to make forward progress belongs to a *lower*-priority subtask that is currently mid-transition. When the budget gate fires, the arbiter evicts the segment whose owning subtask has the lowest static priority, which is precisely the subtask holding an unresolved dependency (an in-flight tool call awaiting a result, or a partially written checkpoint). The high-priority subtask survives, but it survives into an inconsistent world: its dependency's state has been destroyed, so it re-issues, re-waits, and re-triggers eviction. This is a livelock, not a crash, and it is invisible to per-subtask success metrics because each subtask individually reports "retry."

The invariant that must hold is: **eviction eligibility is a function of dependency reachability, not declared priority.** A segment is evictable only if no live subtask holds an unresolved reference into it. Static priority is a tie-breaker among *reachability-equivalent* segments, never the primary key.

What Was Observed

A parent agent runs a high-priority `synthesize` subtask (priority 1) and a low-priority `fetch_grounding` subtask (priority 5) that has issued a tool call to a slow retrieval endpoint. The fetch subtask's context segment contains: the tool-call descriptor, the partial result buffer, and the correlation ID the parent's synthesize step is waiting on.

Trigger sequence:

  1. `synthesize` accumulates reasoning traces and pushes the shared window past the soft budget (e.g., 92% of the model's usable window).
  2. The arbiter enumerates segments, sorts by owning-subtask priority ascending, and evicts from the tail. It evicts the entire `fetch_grounding` segment—the only copy of the correlation ID and partial buffer—because priority 5 is the lowest.
  3. The tool result arrives. The event router looks up the correlation ID to route the result to a waiting subtask. The mapping is gone (it lived in the evicted segment).
  4. The result is dropped as orphaned. `fetch_grounding` observes no result, times out, and re-issues the tool call.
  5. `synthesize`, still blocked on the dependency, continues to emit reasoning traces, re-saturating the window. The arbiter fires again and evicts the *new* `fetch_grounding` segment.
  6. Loop. Over a 40-minute window the instance issued the same retrieval 17 times, evicted the routing state 17 times, and never completed `synthesize`.

The diagnostic signature is the conjunction of three observables that each look benign alone: (a) repeated identical tool invocations with identical arguments, (b) eviction events whose victim segment was referenced by a live waiter at eviction time, and (c) high-priority subtask wall-clock time growing monotonically while its token consumption stays flat (it is blocked, not working).

Condition of Validity

The failure requires all of the following to co-occur; remove any one and the inversion does not occur:

Decision Boundary

The arbiter must decide, at each budget-gate event, whether a candidate victim segment is **reachable** from any live subtask's unresolved dependency set. The correct rule:

The boundary is therefore: **pin first, then rank.** Any policy that ranks before it pins will, under the co-occurrence conditions above, invert.

Operational Effect

With pinning enforced, the observed scenario resolves: the `fetch_grounding` segment is pinned during its tool wait, the arbiter evicts `synthesize`'s older reasoning traces instead (they are reachable only by the currently-running subtask, which can re-derive them), the tool result routes correctly on arrival, and the subtask completes on the first attempt. Cost: `synthesize` pays a modest recompute of evicted traces. This is the correct trade—recompute is bounded and local; the livelock is unbounded and global.

The residual risk is **pin accumulation**: many concurrent waiters can pin most of the window, leaving no eviction headroom and forcing premature budget-exhaustion failures. The guardrail is a pin budget (e.g., pinned segments may not exceed 60% of the window); when exceeded, the arbiter must reject *new* subtask admission rather than evict a pinned dependency. This shifts the failure from a silent livelock to an explicit admission-control rejection, which is observable and actionable.

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Set


class EvictionInversionError(RuntimeError):
    """Raised when an eviction would strand a live subtask's dependency."""
    pass


class SubtaskState(Enum):
    RUNNING = "running"
    WAITING_ON_TOOL = "waiting_on_tool"
    WAITING_ON_PEER = "waiting_on_peer"
    MID_CHECKPOINT = "mid_checkpoint"
    DONE = "done"


LIVE_WAIT_STATES = {
    SubtaskState.WAITING_ON_TOOL,
    SubtaskState.WAITING_ON_PEER,
    SubtaskState.MID_CHECKPOINT,
}


@dataclass
class Segment:
    seg_id: str
    owner: str
    priority: int          # lower number = higher priority
    tokens: int


@dataclass
class Subtask:
    name: str
    priority: int
    state: SubtaskState
    resume_deps: Set[str] = field(default_factory=set)  # segment ids required to resume


@dataclass
class Arbiter:
    window_tokens: int
    pin_budget_frac: float = 0.60

    def _pinned(self, subtasks: Dict[str, Subtask]) -> Set[str]:
        pinned: Set[str] = set()
        for st in subtasks.values():
            if st.state in LIVE_WAIT_STATES:
                pinned |= st.resume_deps
        return pinned

    def evict(self, segments: Dict[str, Segment], subtasks: Dict[str, Subtask],
              need_tokens: int) -> list:
        pinned = self._pinned(subtasks)
        pinned_tokens = sum(segments[s].tokens for s in pinned if s in segments)
        if pinned_tokens > self.window_tokens * self.pin_budget_frac:
            raise EvictionInversionError(
                f"pin set consumes {pinned_tokens} tokens, exceeds pin budget "
                f"{self.window_tokens * self.pin_budget_frac:.0f}; "
                f"reject new subtask admission instead of evicting dependencies"
            )

        # Rank ONLY among unpinned segments; lower priority number survives longest.
        candidates = sorted(
            (s for s in segments.values() if s.seg_id not in pinned),
            key=lambda s: (s.priority, -s.tokens),  # evict lowest priority, largest first
            reverse=True,
        )
        freed, victims = 0, []
        for seg in candidates:
            if freed >= need_tokens:
                break
            victims.append(seg.seg_id)
            freed += seg.tokens

        # Post-condition guard: never return a victim that is pinned.
        for v in victims:
            if v in pinned:
                raise EvictionInversionError(
                    f"arbiter selected pinned segment {v}; dependency reachability "
                    f"was not respected during ranking"
                )
        if freed < need_tokens:
            raise EvictionInversionError(
                f"cannot free {need_tokens} tokens without touching pinned "
                f"dependencies; explicit budget-exhaustion required"
            )
        return victims