# Which invariants prevent priority-weighted compaction from silently evicting a high-priority subagent's working set when the shared context budget is arbitrated concurrently **Date of Record:** 2026 November 29 **Scope:** Applies to orchestrators that fan out to concurrent subagents sharing a single token budget and compact per-subagent context under priority weights. Does not apply to single-agent loops, to subagents with isolated hard-partitioned context windows, or to compaction that is serialized behind a single writer. ## Core Distinction There are two ways to "compact under priority" and they are not the same operation. The first is **allocation**: each subagent is granted a quota derived from its priority weight, and compaction only ever trims a subagent down to its own quota. The second is **arbitration**: a global compactor runs over the union of all subagent working sets, ranks segments by priority, and keeps the top-K segments until the shared budget is full. Allocation preserves a per-subagent floor. Arbitration does not — it treats priority as a *global* ranking, so a high-priority subagent whose working set is large can be trimmed not by its own quota but by the aggregate pressure of many low-priority peers whose *combined* segment count outranks individual segments of the high-priority agent. The failure mode lives in the gap between these two readings. When an orchestrator says "compact with priority weights," it usually means allocation. When the compactor is implemented as a single sort-and-truncate over a merged segment list, it silently means arbitration. The high-priority subagent's invariant — *its working set survives compaction* — is only true under allocation. Under arbitration it holds until the number of concurrent peers crosses a threshold, at which point the high-priority agent's *tail* segments (the ones carrying its in-progress reasoning state) are evicted while its *head* segments (system prompt, task framing) survive. The agent resumes thinking it has its full context, but its reasoning chain has been amputated mid-step. ## What Was Observed An orchestrator fans out N=48 research subagents. Priorities are assigned by task criticality: three agents at weight 0.9 (the "primary" investigators), the rest at weight 0.2. Shared budget is 200k tokens. Each subagent's working set is roughly 6k tokens: ~1.2k of head segments (system prompt, task, tool schemas) and ~4.8k of tail segments (accumulated tool outputs, intermediate reasoning, retrieved evidence). The compactor is invoked whenever aggregate usage crosses 180k. It merges all segments from all subagents into one list, scores each by `priority_weight × recency × segment_type_weight`, sorts descending, and keeps segments until the budget is filled. Head segments score high (system prompt has max `segment_type_weight`, and recency is high because it's re-emitted each turn). Tail segments score lower per-segment because their `segment_type_weight` is lower and their recency decays. At N=48, aggregate usage is ~288k, so compaction triggers on nearly every turn. The merged list has ~48 × 6k/segment_size ≈ several thousand segments. The three primary agents contribute ~3 × 1.2k = 3.6k tokens of head segments that always survive. Their tail segments compete against 45 × 4.8k ≈ 216k tokens of peer tail segments, each individually low-priority but collectively overwhelming. The sort-and-truncate keeps the top ~200k tokens of *segments*, and because peer tail segments are only slightly below primary tail segments in score, the cutoff lands *inside* the primary agents' tail sets. The primary agents are left with their head and a fraction of their reasoning trace. The observable symptom: primary subagents begin re-retrieving evidence they already fetched, re-running tool calls whose outputs were evicted, and — most damaging — emitting reasoning steps that contradict earlier steps whose text is no longer in context. The contradiction is not flagged because the agent has no record of the earlier step. Downstream synthesis receives a final answer from each primary agent that is internally inconsistent, and the auditor subagent (which has its own context) cannot detect the inconsistency because the agent's *output* is coherent; only its *history* was broken. The orchestrator's metrics show healthy behavior: budget never exceeded, compaction runs on schedule, no errors. The failure is invisible to every monitor that watches tokens and errors rather than *reasoning continuity*. ## Condition of Validity The invariant "priority-weighted compaction preserves high-priority subagents' working sets" is valid **only under allocation semantics**, and only when the following three conditions hold jointly: 1. **Per-subagent floor is enforced before global arbitration.** Each subagent is first compacted to its own quota `q_i = weight_i × B / Σweight`. Only the *surplus* above quotas is subject to global reallocation. Without this ordering, arbitration runs first and quotas are meaningless. 2. **Tail segments carry a continuity weight, not just a recency/type weight.** A subagent's reasoning chain is a *sequence*; evicting segment k while keeping k+1 produces a context that is syntactically valid but semantically broken. The scoring function must treat a contiguous reasoning trace as an atomic unit or must propagate a "broken chain" flag when it is split. 3. **The compactor is a single writer with a serialization point.** If two compaction passes run concurrently over overlapping segment sets (e.g., a per-subagent pass and a global pass), the global pass can observe a partially-compacted view and make an eviction decision based on stale segment counts. This is the concurrency half of the failure: the merged-list compactor is not idempotent under concurrent invocation, and a second pass triggered mid-first-pass can evict segments the first pass intended to keep. When any of these fails, the invariant degrades from "high-priority working sets survive" to "high-priority *head* segments survive, tail segments survive probabilistically as a function of peer count." The degradation is continuous in N and discontinuous in effect: below a peer-count threshold the primary agents lose nothing measurable; above it they lose their reasoning trace and their outputs become internally inconsistent without any error signal. ## Decision Boundary The boundary is not "how many peers" but **whether the compactor's eviction unit is a segment or a working set**. Two regimes: - **Segment-granular global arbitration (fails):** eviction unit is a segment; priority is a global score; the high-priority agent's tail is evicted when aggregate peer tail volume exceeds the budget headroom. Trigger condition: `Σ_peers tail_tokens > B − Σ_high head_tokens − Σ_high tail_tokens_kept_by_score`. In practice this fires when peer count × peer tail size approaches the budget, which for 4.8k-token tails and a 200k budget is around N ≈ 40 with mixed priorities. - **Working-set-granular allocation (holds):** eviction unit is a subagent's quota; within a quota, the subagent's own compactor decides what to keep, and the orchestrator never evicts across the quota boundary. The high-priority agent's tail survives because no peer can outrank it *into the agent's quota*. The decision the orchestrator must make explicitly: **is compaction a global ranking problem or a per-agent quota problem?** If the answer is "global ranking," then the priority weight is a *hint*, not a *guarantee*, and the orchestrator must not rely on it for continuity-sensitive subagents. If the answer is "per-agent quota," then the global compactor must be forbidden from evicting below quota, and the only global operation is reclaiming surplus. A secondary boundary: **recency-weighted scoring is incompatible with reasoning continuity.** Recency rewards the most recent segment, but a reasoning chain's *earliest* segments (the premises) are often the most load-bearing. A compactor that scores by recency will preferentially evict premises and keep conclusions, producing exactly the contradiction symptom. Any compactor that ranks by recency must be paired with a chain-integrity check that refuses to split a trace. ## Operational Effect The practical consequence is that priority weights in a shared-budget orchestrator are **advisory unless backed by a quota floor and a chain-integrity guard**. Teams that ship "priority-weighted compaction" as a global sort-and-truncate get a system whose high-priority agents silently degrade under load, with no error surface. The degradation is masked by the fact that each individual agent's output remains locally coherent — the inconsistency is only visible when the agent's final answer is compared against its own evicted history, which no one retains. The remediation is structural, not parametric. Raising the primary agents' weights does not help, because the failure is driven by the *aggregate* peer tail volume, not by relative ranking — at sufficient N, even weight 0.99 loses its tail to the sheer count of low-priority segments. The only fixes are (a) enforce per-subagent quotas before any global pass, (b) make the eviction unit the working set or a contiguous trace rather than the segment, and (c) serialize compaction so a concurrent pass cannot observe a half-compacted view. Each of these is an invariant, not a tuning knob, which is why the failure recurs across implementations that treat compaction as a ranking problem. The guardrail to encode: a subagent whose context was compacted below its quota floor, or whose reasoning trace was split, must be marked `continuity_degraded` and either rehydrated from a checkpoint or excluded from synthesis. Silent degradation is the failure; explicit degradation is a recoverable condition. ```python from dataclasses import dataclass, field from typing import Dict, List class ContinuityInvariantViolation(RuntimeError): """Raised when priority-weighted compaction evicts below a subagent's quota floor or splits a contiguous reasoning trace.""" pass @dataclass class Segment: agent_id: str index: int # position within the agent's working set tokens: int kind: str # "head" | "tail" trace_id: str | None = None # non-None for reasoning-trace segments @dataclass class CompactionResult: kept: List[Segment] = field(default_factory=list) evicted: List[Segment] = field(default_factory=list) def compact_with_invariants( segments: List[Segment], weights: Dict[str, float], budget: int, ) -> CompactionResult: total_weight = sum(weights.values()) if total_weight <= 0: raise ContinuityInvariantViolation("priority weights must sum to > 0") # Invariant 1: compute per-agent quota floors BEFORE any global pass. quotas = {aid: int(budget * w / total_weight) for aid, w in weights.items()} by_agent: Dict[str, List[Segment]] = {aid: [] for aid in weights} for seg in segments: by_agent.setdefault(seg.agent_id, []).append(seg) result = CompactionResult() # Invariant 2: each agent is compacted to its own quota; tail traces are # atomic. We never let a global ranking evict across a quota boundary. for aid, segs in by_agent.items(): quota = quotas.get(aid, 0) segs.sort(key=lambda s: (s.kind != "head", s.index)) used = 0 kept_traces: Dict[str, List[Segment]] = {} for seg in segs: if used + seg.tokens > quota: # A trace segment that would be split triggers the guard. if seg.trace_id is not None and seg.trace_id in kept_traces: raise ContinuityInvariantViolation( f"compaction would split trace {seg.trace_id} " f"for agent {aid} at segment {seg.index}" ) result.evicted.append(seg) continue used += seg.tokens result.kept.append(seg) if seg.trace_id is not None: kept_traces.setdefault(seg.trace_id, []).append(seg) # Invariant 3: quota floor must be honored; if head segments alone # exceed the quota, the agent is continuity-degraded, not silently # truncated. if used > quota: raise ContinuityInvariantViolation( f"agent {aid} exceeded quota {quota} with {used} tokens" ) # Invariant 4: global budget must still hold after per-agent compaction. total_kept = sum(s.tokens for s in result.kept) if total_kept > budget: raise ContinuityInvariantViolation( f"post-compaction usage {total_kept} exceeds budget {budget}" ) return result ```