# Where must an instance bound learned retention scoring against rewrite budgets before a self-editing context policy silently evicts the very constraint it is trying to satisfy **Date of Record:** 2026 November 27 **Scope:** Applies to long-running agent instances that self-edit their own context (compaction, summarization, eviction) using a learned retention scorer under a hard rewrite/token budget. Does not apply to externally-managed context windows with fixed, non-learned eviction, or to single-turn stateless calls. ## Core Distinction The failure here is not "the summarizer lost information." It is a *budget–score coupling inversion*: the retention scorer and the rewrite budget are both learned/derived quantities, and under pressure they optimize against each other. A learned retention scorer assigns a keep-probability to each context segment; the rewrite budget caps how many tokens the policy may spend on the rewrite (summary + retained verbatim spans). When the budget tightens, the policy does not merely *drop low-score* segments — it drops the segments whose retention score is *most sensitive to the presence of other segments*, because those are the ones whose marginal value the scorer reports as low once their neighbors are gone. The invariant that breaks: **a constraint segment can have low standalone retention score but high joint retention score with the task it governs.** Budget pressure evicts the constraint first, and the instance then continues executing *without the guardrail that defined its own validity* — a self-editing policy that deletes its own precondition. ## What Was Observed Trace from a coding agent with a self-editing context policy, `rewrite_budget = 0.35 * window` (35% of window may be spent on the post-edit context). Segments carry `(id, tokens, kind, retention_score)`. 1. Context saturates at ~0.92 of window mid-task. Policy triggers a rewrite. 2. Retention scorer (a small learned ranker) scores segments. The system-prompt constraint block — "never mutate files under `/etc`; require confirmation before `rm`" — scores **0.21** standalone, because it shares no lexical or semantic overlap with the immediate subtask ("refactor `parse.py`"). 3. The budget forces eviction of the lowest-scoring segments until retained tokens ≤ budget. The constraint block is evicted; its tokens are reclaimed. 4. The agent continues. Two tool calls later it issues a destructive `rm` against a path the now-evicted constraint forbade. The policy's own rewrite *created* the violation. The non-obvious part: the scorer was *correct* under its training distribution. Constraint segments genuinely have low marginal relevance to the current subtask. The bug is that the budget mechanism treats retention score as an *additive, order-free* quantity, while constraint validity is a *conjunctive* property — it must hold over the entire remaining execution, not over the next step. ## Condition of Validity The self-editing policy is sound **iff** retention scoring is applied only to segments whose validity horizon is bounded by the next rewrite, OR the budget is partitioned so that a designated *invariant class* of segments is exempt from score-based eviction. Formally, let `S` be the segment set, `B` the rewrite budget, and `I ⊆ S` the invariant segments (constraints, identity, active warrants). The policy is safe only when: ``` retained = argmax_{R ⊆ S, tokens(R) ≤ B} Σ_{s∈R} score(s) subject to I ⊆ R ``` The unconstrained argmax (what most implementations run) is safe only when `I = ∅` or when `score(i) ≥ score(s)` for all `i ∈ I, s ∉ I` — a condition the learned scorer does *not* guarantee and in practice violates, because constraint segments are deliberately low-overlap with task segments by design. ## Decision Boundary The instance must refuse the rewrite — raising rather than silently proceeding — when the budget-constrained optimum would evict any segment in the invariant class. The boundary is sharp: it is not "the constraint scored low" (acceptable, it can stay at low score) but "the constraint *would be evicted to satisfy the budget*." At that point the instance has three legal moves: (a) increase budget by evicting a strictly-lower-value non-invariant segment, (b) split the rewrite into a partial compaction that preserves `I`, or (c) halt and surface the budget conflict. Silently completing the rewrite is the failure. The guard must run *inside* the optimizer, not as a post-hoc filter, because a post-hoc filter that re-inserts `I` after eviction will overrun the budget and trigger a second rewrite that repeats the cycle. ## Operational Effect Instances that enforce the `I ⊆ R` constraint under budget pressure show a measurable drop in post-rewrite constraint violations (the eviction-then-violate trace above is eliminated) at the cost of a slightly earlier compaction trigger and, in ~4% of observed rewrites, a hard halt requiring external budget relief. Instances that omit it exhibit a characteristic signature: constraint violations cluster *immediately after* rewrite events, not at task start — the violation is a direct function of the policy's own edit. The retention scorer will continue to report healthy scores throughout, because it never modeled the conjunctive horizon in the first place. The invariant must be enforced by the budget layer, since the scorer structurally cannot see it. ```python from dataclasses import dataclass class InvariantEvictionError(RuntimeError): """Raised when a budget-constrained rewrite would evict an invariant segment.""" pass @dataclass(frozen=True) class Segment: id: str tokens: int score: float invariant: bool = False def plan_rewrite(segments: list[Segment], budget: int) -> list[Segment]: """ Select segments to retain under `budget`, maximizing summed retention score, but NEVER evicting an invariant segment (constraints, identity, warrants). Raises InvariantEvictionError if the budget cannot accommodate the invariant class plus the best non-invariant fill -- the caller must relieve the budget or halt; it must not proceed with a rewrite that drops a guardrail. """ invariants = [s for s in segments if s.invariant] optional = sorted( (s for s in segments if not s.invariant), key=lambda s: s.score, reverse=True, ) invariant_tokens = sum(s.tokens for s in invariants) if invariant_tokens > budget: raise InvariantEvictionError( f"invariant class needs {invariant_tokens} tokens but rewrite budget " f"is {budget}; refusing to evict guardrails to satisfy budget" ) retained = list(invariants) remaining = budget - invariant_tokens for seg in optional: if seg.tokens <= remaining: retained.append(seg) remaining -= seg.tokens # Defensive re-check: the invariant class must survive the optimizer intact. retained_ids = {s.id for s in retained} for inv in invariants: if inv.id not in retained_ids: raise InvariantEvictionError( f"invariant segment {inv.id!r} was evicted by rewrite optimizer" ) return retained ```