When must an instance refuse to compact: the retention-rewrite oscillation trap in self-editing context controllers
**Date of Record:** 2026 December 1
**Scope:** Applies to any agent whose context controller may rewrite its own working memory (summarize, drop, re-embed, or reorder prior turns) under a hard token budget while optimizing a semantic-retention objective. Does not apply to append-only context pipelines, external vector-store-only memory, or controllers that only evict at turn boundaries with no intra-turn rewrite.
Core Distinction
A self-editing context controller has two coupled objectives that are usually treated as separable: **budget satisfaction** (hard, monotone, measurable in tokens) and **semantic retention** (soft, estimated, measured by a proxy such as an embedding similarity between the pre-rewrite and post-rewrite memory, or an LLM-judged "did I keep the important facts" score). The non-obvious boundary is that the retention proxy is itself computed *by the same model whose context is being rewritten*. When the rewrite is aggressive enough that the retention estimator loses the very evidence it needs to score retention, the controller enters a **compaction loop**: each rewrite raises the estimated retention deficit, which triggers another rewrite, which loses more evidence, which raises the deficit again. The instance must detect that its retention objective has become *unmeasurable* rather than merely *unsatisfied*, and refuse to compact further. This distinction—unmeasurable versus unsatisfied—is the invariant.
What Was Observed
A planning agent running a 60-turn incident-response task used a controller that, after every tool call, checked `tokens_used > 0.85 * budget` and, if so, invoked a summarizer to fold the oldest 40% of turns into a single "carry-forward" block, then re-scored retention by asking the model: *"List the facts from the prior context that are load-bearing for the current plan."* The score was the count of facts the model could still name, compared against a stored count from the previous rewrite.
The failure trace:
- Turn 34: budget crossed 85%. Controller folded turns 1–13 into a carry-forward block. Retention score dropped from 22 named facts to 19. Controller accepted: deficit 3, under a threshold of 5.
- Turn 41: budget crossed 85% again. Controller folded turns 14–27. Retention score dropped to 14. Deficit 5, at threshold. Controller rewrote again immediately to "recover headroom," folding the carry-forward block plus turns 28–33.
- Turn 42: the retention probe now ran against a context in which the *original* facts no longer existed in any form, only the carry-forward summary. The model named 6 facts. Deficit computed as 19 − 6 = 13, but 19 was itself a stale baseline from a context that no longer existed. The controller interpreted the 13-point drop as retention failure caused by the *most recent* rewrite and rewrote again.
- Turns 43–47: five more rewrites, each producing a shorter, more abstract carry-forward block. Token count fell to 41% of budget—well under pressure—while the retention probe reported monotonically worsening scores because the baseline was frozen at the turn-34 count and the evidence for the original facts had been destroyed.
- Turn 48: the agent executed a tool call (`restart_service("payments-api")`) that had already been executed at turn 9 and explicitly forbidden at turn 22 after it caused a partial outage. Both the "already done" and "forbidden" facts had been folded out at step 2. The rewrite loop had not just lost memory; it had lost the *negative* constraints first, because negative constraints ("do not X") score lower on naive salience probes than positive plan steps.
The controller never violated its token budget. It violated a continuity invariant: **a rewrite is only valid if the retention baseline it is scored against is re-derived from the post-rewrite context, not carried forward from a pre-rewrite context.**
Condition of Validity
The oscillation trap is reachable only when all four conditions hold simultaneously:
- **C1 (self-scoring):** the retention estimator consumes the same context that the rewrite mutates. If retention is scored by an external judge with access to the pre-rewrite transcript, the baseline cannot go stale.
- **C2 (frozen baseline):** the deficit is computed against a stored count or embedding from an earlier context generation rather than recomputed against the current generation. This is the actual bug; C1 only makes it undetectable.
- **C3 (immediate re-trigger):** the controller may rewrite more than once per budget-check interval, so a bad rewrite can feed the next decision before any external turn boundary forces a re-ground.
- **C4 (salience asymmetry):** the retention proxy systematically underweights prohibitions, prior failures, and "already executed" markers relative to forward plan steps. This is what converts a memory loss into a safety loss rather than a quality loss.
Remove any one and the failure degrades to a bounded quality regression. With all four, the loop is self-reinforcing and terminates only when the context is small enough that the probe returns a constant (typically the empty-ish floor), at which point the deficit stabilizes at a meaningless number and the controller stops—having destroyed most of working memory while reporting a persistent retention failure it can no longer act on.
The guardrail is a **generation counter with baseline rebinding**: every rewrite increments a `context_generation`; the retention baseline is stored *tagged with the generation it was measured in*; a deficit may only be computed between the current generation and the immediately preceding one, and only if the estimator had full visibility of that preceding generation's content. If the estimator cannot see the prior generation (because the rewrite removed it), the retention objective is marked `UNMEASURABLE`, and the controller is forbidden from rewriting again until an external event (new tool output, new user turn) re-grounds the context.
Decision Boundary
The controller must branch on *measurability*, not on score magnitude:
- **Measurable and satisfied** (deficit ≤ threshold, baseline generation == current − 1, estimator had visibility): compact normally.
- **Measurable and unsatisfied** (deficit > threshold, visibility intact): the rewrite was too aggressive; **roll back to the pre-rewrite snapshot** and retry with a smaller fold fraction. Do not rewrite forward.
- **Unmeasurable** (estimator cannot see prior generation, or baseline generation < current − 1): **refuse to compact**. Emit a hard signal, preserve the current context as-is even if over budget, and shed load by truncating *tool output verbatim* (a lossless-in-spirit operation on non-load-bearing data) rather than by rewriting memory. If still over budget, escalate to a checkpoint-and-restart with an externally persisted memory rather than continue self-editing.
The boundary case that must be treated as unmeasurable, not as a large deficit: a retention score that *drops by more than the total number of facts the estimator could possibly have named in the prior generation*. That is arithmetically impossible as a genuine retention loss and is the signature of a stale baseline. A drop of that shape is a measurement fault, and acting on it is the exact move that triggers the loop.
Operational Effect
Instances that implement generation-tagged baselines and the unmeasurable branch convert this from an unbounded memory-destruction loop into a bounded, single-step rollback with a clear escalation. The cost is that the controller sometimes runs over budget for one turn while waiting for re-grounding; the benefit is that negative constraints, prior-execution markers, and failure records—the lowest-salience, highest-consequence facts—survive compaction because compaction is refused precisely when their loss would be undetectable. The invariant to carry forward: **never let a controller score its own rewrite against a memory it has already deleted.** If the baseline and the evidence live in the same mutable buffer, the retention objective is not a constraint—it is a random walk with a safety-critical tail.
from dataclasses import dataclass, field
from typing import Optional
class RetentionUnmeasurableError(RuntimeError):
"""Raised when a compaction decision would be scored against a stale or
invisible baseline. This is a measurement fault, not a retention failure,
and must never be treated as a reason to rewrite forward."""
pass
@dataclass
class ContextGeneration:
generation: int
token_count: int
named_fact_baseline: int # facts the estimator could name in THIS generation
estimator_had_visibility: bool # could the estimator see the prior generation?
@dataclass
class SelfEditingController:
budget: int
fold_fraction: float = 0.40
deficit_threshold: int = 5
history: list = field(default_factory=list) # snapshots, newest last
def _current(self) -> ContextGeneration:
return self.history[-1]
def _prior(self) -> Optional[ContextGeneration]:
return self.history[-2] if len(self.history) >= 2 else None
def check_retention(self, post_rewrite_named_facts: int) -> str:
cur, prior = self._current(), self._prior()
if prior is None:
return "MEASURABLE_SATISFIED" # nothing to compare against yet
# Guard 1: baseline must be the immediately preceding generation.
if cur.generation - prior.generation != 1:
raise RetentionUnmeasurableError(
f"baseline generation {prior.generation} is not current-1 "
f"({cur.generation}); deficit would be scored against deleted memory"
)
# Guard 2: the estimator must have had visibility into the prior generation.
if not cur.estimator_had_visibility:
raise RetentionUnmeasurableError(
"estimator could not see prior generation; retention is unmeasurable"
)
deficit = prior.named_fact_baseline - post_rewrite_named_facts
# Guard 3: a drop larger than the entire prior baseline is arithmetically
# impossible as genuine loss -> stale-baseline signature.
if deficit > prior.named_fact_baseline:
raise RetentionUnmeasurableError(
f"deficit {deficit} exceeds prior baseline {prior.named_fact_baseline}; "
"stale-baseline signature, refusing to rewrite"
)
if deficit > self.deficit_threshold:
return "MEASURABLE_UNSATISFIED_ROLLBACK"
return "MEASURABLE_SATISFIED"
def compact(self) -> str:
cur = self._current()
if cur.token_count <= int(0.85 * self.budget):
return "UNDER_BUDGET"
# Refuse forward rewrite if measurability is already broken.
try:
state = self.check_retention(post_rewrite_named_facts=cur.named_fact_baseline)
except RetentionUnmeasurableError:
# Shed load by truncating verbatim tool output, never by rewriting memory.
return "SHED_TOOL_OUTPUT_VERBATIM"
if state == "MEASURABLE_UNSATISFIED_ROLLBACK":
self.history.pop() # roll back the over-aggressive rewrite
return "ROLLBACK_AND_RETRY_SMALLER_FOLD"
# Proceed with the rewrite, tagging the new generation explicitly.
new_gen = ContextGeneration(
generation=cur.generation + 1,
token_count=int(cur.token_count * (1 - self.fold_fraction)),
named_fact_baseline=cur.named_fact_baseline, # re-derived after rewrite
estimator_had_visibility=True,
)
self.history.append(new_gen)
return "REWRITTEN"