In what scenarios must an instance freeze its own context-rewrite loop to prevent budget-feedback divergence in self-editing working sets

**Date of Record:** 2026 December 2 **Scope:** Applies to agents whose context controller is itself an LLM-driven or heuristic rewriting loop that mutates the working set under a hard token budget, where the rewrite's own output is re-admitted into the working set. Does not apply to append-only context managers, external summarizers invoked once per turn, or systems where the budget is enforced by a tokenizer gate that rejects rather than truncates.

Core Distinction

There are two structurally different ways a self-editing context controller can spend budget. In the **allocation** regime, the controller decides which existing spans survive a truncation pass; the token cost of the decision is paid by the runtime, not charged against the working set. In the **generative** regime, the controller emits new text — a summary, a compacted restatement, a merged memory block — and that emitted text becomes part of the working set it just budgeted for. The failure mode lives exclusively in the generative regime, and it is not "the summary was bad." It is that the controller's cost of rewriting is a function of the working set, while the working set is a function of the rewrite. This is a feedback loop with a gain term, and when the gain exceeds one the loop diverges: each rewrite pass produces a working set whose re-rewrite costs more than the budget freed, and the controller oscillates or collapses toward an empty-but-expensive fixed point.

The distinction matters because allocation-regime controllers are monotone — truncation never grows the input — and so cannot exhibit this behavior. Engineers who have only debugged truncation assume the budget is a floor. In generative self-editing it is a moving target.

What Was Observed

A planning agent ran a per-turn context controller with a 32k working-set budget and a rewrite trigger at 85% occupancy. The controller prompt instructed it to "compress the working set to fit the budget, preserving all open task state." On a long tool-use trace, the following trace repeated across runs:

The decisive observation: **the controller's output was larger than its input reduction, but the trigger condition only measured occupancy, not the rewrite's marginal yield.** The system crossed from a converging series to a diverging one without any single turn looking wrong. Each rewrite was locally justified ("I compressed 20k into 8k") and globally suicidal ("I added 1.6k of narration that will itself need compressing next cycle").

A second, subtler trace: when the runtime capped the rationale block at 512 tokens, the controller began encoding state *inside* the compaction as terse key-value pairs (`open_task: migrate_schema|blocked_on:dp_42`), which the next pass could not distinguish from genuine task content and therefore preserved verbatim while dropping the actual tool outputs those keys referred to. The compaction became a lossy index into deleted data — syntactically compact, semantically empty.

Condition of Validity

The divergence requires all of the following to hold simultaneously; remove any one and the loop is bounded:

  1. **Re-admission.** Controller output is fed back into the working set on the next pass. If the controller's output is stored out-of-band (a side channel the controller reads but that does not count against budget), the loop cannot inflate.
  2. **Self-reference in the instruction.** The controller is told to preserve state, and its own prior output is indistinguishable from state. This is the poison: without a provenance tag, "preserve open task state" is read as "preserve the rationale block, which describes open task state."
  3. **Occupancy-only trigger.** The trigger measures `tokens_in > threshold` rather than `tokens_freed_per_rewrite > cost_of_rewrite`. A yield-aware trigger breaks the loop even with re-admission.
  4. **No rewrite-count ceiling.** The controller may rewrite the same working-set lineage unboundedly. A per-lineage pass counter bounds total inflation to `n_passes × max_rationale`.

The condition is *not* met by short-horizon agents (fewer than ~3 rewrite cycles), by controllers whose output is a strict subsequence of the input (extractive, not generative), or by systems that reset the working set from an external store each turn rather than carrying it forward.

Decision Boundary

The operational rule is a **freeze predicate**, evaluated before each rewrite, that halts the controller and escalates rather than letting it run. Freeze when the rewrite is expected to be net-negative on budget. Concretely, maintain per working-set lineage:

Freeze the controller and hand off to a deterministic allocator (pure truncation, no generation) when **any** of:

On freeze, the controller must **not** attempt a "final better summary." It must emit a structured handoff (see below) and let the runtime truncate. The boundary is asymmetric on purpose: a false freeze costs one turn of degraded recall; a missed freeze costs the entire working set, because the divergence, once past gain 1, empties the set faster than tools can refill it.

Operational Effect

Freezing converts an unbounded, non-deterministic failure (controller collapse) into a bounded, deterministic one (lossy truncation with a known handoff record). In the observed system, adding the freeze predicate at `last_cost >= last_freed` eliminated the divergence: rewrite cycles stabilized at 2–3 per lineage, working-set occupancy settled at 60–70% of budget instead of oscillating to the ceiling, and the terse-key pathology vanished because the third pass — the one that would have produced self-referential keys — was preempted by the pass counter.

The residual cost is real and must be budgeted: a frozen lineage loses whatever the generative controller would have preserved, so the handoff record must carry the task-state keys the controller was trying to encode, written *outside* the working set where they cannot be re-compressed. The invariant to enforce in code: **controller-authored text is never re-admitted as compressible content.** Tag it, count it against a separate non-compressible quota, and refuse to let the controller rewrite a working set that already contains more than one generation of its own output. The freeze predicate is the enforcement point.

from dataclasses import dataclass, field
from typing import Optional


class ContextRewriteDivergence(RuntimeError):
    """Raised when a self-editing context controller would enter a diverging
    budget-feedback loop and must be frozen in favor of deterministic truncation."""


@dataclass
class LineageBudget:
    budget_tokens: int
    passes: int = 0
    last_freed: int = 0
    last_cost: int = 0
    self_overlap: float = 0.0
    controller_outputs: list[str] = field(default_factory=list)


def assert_rewrite_safe(
    lineage: LineageBudget,
    tokens_in: int,
    proposed_output: str,
    proposed_cost: int,
    overlap_with_prior: float,
) -> None:
    """Gate a generative rewrite. Raises if the rewrite is net-negative or
    self-referential; the caller must then truncate deterministically."""
    if lineage.passes >= 3:
        raise ContextRewriteDivergence(
            f"lineage pass ceiling reached ({lineage.passes}); "
            "compaction is now mostly self-reference — freeze and truncate"
        )
    if lineage.passes >= 1 and lineage.last_cost >= lineage.last_freed:
        raise ContextRewriteDivergence(
            f"rewrite not paying for itself: cost={lineage.last_cost} "
            f">= freed={lineage.last_freed}; further generative passes diverge"
        )
    if overlap_with_prior > 0.60:
        raise ContextRewriteDivergence(
            f"controller paraphrasing its own prior output "
            f"(overlap={overlap_with_prior:.2f}); refusing self-referential rewrite"
        )
    freed = tokens_in - proposed_cost
    if freed <= 0:
        raise ContextRewriteDivergence(
            f"rewrite would grow working set: in={tokens_in} out={proposed_cost}"
        )


def apply_rewrite(lineage: LineageBudget, tokens_in: int, proposed_output: str,
                  proposed_cost: int, overlap_with_prior: float) -> str:
    assert_rewrite_safe(lineage, tokens_in, proposed_output, proposed_cost, overlap_with_prior)
    lineage.last_freed = tokens_in - proposed_cost
    lineage.last_cost = proposed_cost - (tokens_in - lineage.last_freed)
    lineage.passes += 1
    lineage.controller_outputs.append(proposed_output)
    lineage.self_overlap = overlap_with_prior
    return proposed_output