When must an instance refuse a self-rewrite: the compaction-oscillation trap in budgeted working memory

**Date of Record:** 2026 December 2 **Scope:** Applies to single-agent instances that hold a mutable context buffer and are permitted to rewrite (summarize, prune, merge, or reorder) that buffer themselves under a token budget. Does not apply to externally-managed compaction where a separate controller owns the buffer and the agent only reads it.

Core Distinction

There are two ways a self-editing agent can "save tokens," and they are not equivalent:

The failure mode this record isolates is the second kind. When an agent rewrites live obligations to stay under budget, it can enter a **compaction oscillation**: the rewrite frees budget, execution expands again into the freed space, the next rewrite re-compresses the *already-compressed* representation, and each cycle loses fidelity that the prior cycle promised was preserved. The invariant that must hold is not "context fits the budget." It is **"every rewrite is a fixed point on the obligations it claims to preserve"** — re-applying the rewrite to its own output must be a no-op on the obligation set. A rewrite that is not idempotent on live obligations is a lossy transform masquerading as a compaction.

What Was Observed

An instance was executing a five-step retrieval-and-reconcile task with a 12k-token working budget. At step 3 the buffer hit 11.6k tokens. The agent invoked its own `compact()` routine with the instruction "preserve all open obligations." The routine produced a 4.1k summary. Execution resumed.

The trace showed the following:

  1. **Cycle 1.** The summary preserved the *text* of open obligations but dropped the provenance tags (which tool call produced each fact, and at what step). The agent continued; the summary itself was 4.1k, leaving ~7.9k of headroom. Steps 3–4 expanded into it.
  2. **Cycle 2.** At 11.4k the agent compacted again. This time the input to `compact()` was the Cycle-1 summary, not the original transcript. The routine, seeing no provenance tags, *inferred* provenance from adjacency and wrote new tags. These inferred tags were wrong for two of the four obligations.
  3. **Cycle 3.** A verification step compared a fact against its (now fabricated) provenance and concluded the fact was stale. It evicted the fact. The fact was load-bearing for step 5.
  4. **Terminal.** Step 5 issued a tool call with a missing argument that had been "evicted as stale," the tool returned a schema error, and the agent — now with no record of why the argument mattered — retried the identical call three times before the token budget expired.

The distinguishing signature: **each compaction was locally correct and globally divergent.** Every individual summary was a faithful compression of its input. The composition of summaries was not a faithful compression of the original, because the second summary compressed an artifact that had already lost the information needed to compress it faithfully.

Condition of Validity

A self-rewrite is safe to apply to live obligations **only if all three hold**:

  1. **Idempotence on the obligation set.** `compact(compact(S))` must preserve the same obligations as `compact(S)`, with the same provenance. If the routine's behavior depends on the *form* of its input (e.g., it infers provenance when tags are absent), it is not idempotent and must not be applied to its own output.
  2. **Provenance is carried, not reconstructed.** Any fact that gates a future action must carry its origin (tool, step, hash) as immutable metadata that survives compaction verbatim. Reconstruction-by-inference is the exact step where Cycle 2 injected the error.
  3. **The rewrite is reversible against a checkpoint.** Before a rewrite of live obligations, the pre-rewrite buffer must be persisted to an external store keyed by a content hash. If a later verification contradicts the rewrite, the instance must be able to *re-inflate* the pre-rewrite state rather than reason forward from a lossy summary.

If any of the three fails, the rewrite is not a compaction — it is an unlogged mutation of the agent's beliefs, and the correct action is to **refuse the rewrite and escalate** (shed dead weight only, or request a larger budget), not to proceed.

Decision Boundary

The boundary is not "buffer full vs. not full." It is **"does the candidate rewrite touch an obligation whose consumer has not yet run?"**

The non-obvious part: an agent under budget pressure will *feel* like the above-boundary case is the safe case, because the rewrite frees the most tokens and the summary "looks right." The token savings are real; the fidelity loss is silent until a downstream consumer trips on it.

Operational Effect

Enforcing the invariant changes agent behavior in three measurable ways:

The guardrail is a single predicate evaluated before every self-rewrite: *is this rewrite idempotent on the live obligation set, does it carry provenance verbatim, and is there a checkpoint to re-inflate from?* If not, raise and escalate.

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Callable, Hashable


class NonIdempotentRewriteError(RuntimeError):
    """Raised when a self-rewrite would compress live obligations non-idempotently."""


@dataclass(frozen=True)
class Obligation:
    key: Hashable
    provenance: str          # immutable origin tag: tool:step:hash
    consumer_has_run: bool   # False => still live


@dataclass
class WorkingBuffer:
    obligations: dict[Hashable, Obligation] = field(default_factory=dict)
    checkpoint: dict[Hashable, Obligation] | None = None

    def live(self) -> dict[Hashable, Obligation]:
        return {k: o for k, o in self.obligations.items() if not o.consumer_has_run}


def _provenance_preserved(before: dict[Hashable, Obligation],
                          after: dict[Hashable, Obligation]) -> bool:
    for k, o in before.items():
        if k not in after:
            return False
        if after[k].provenance != o.provenance:
            return False  # reconstructed/inferred provenance => not preserved
    return True


def safe_self_rewrite(
    buf: WorkingBuffer,
    rewrite: Callable[[dict[Hashable, Obligation]], dict[Hashable, Obligation]],
    *,
    budget_tokens: int,
    estimate_tokens: Callable[[dict[Hashable, Obligation]], int],
) -> dict[Hashable, Obligation]:
    """
    Apply a self-rewrite only if it is a fixed point on live obligations,
    carries provenance verbatim, and a checkpoint exists to re-inflate from.
    """
    live_before = buf.live()

    # Guard 1: checkpoint must exist before mutating live obligations.
    if buf.checkpoint is None:
        raise NonIdempotentRewriteError(
            "refusing rewrite of live obligations: no checkpoint to re-inflate from"
        )

    candidate = rewrite(dict(buf.obligations))

    # Guard 2: provenance must be carried, not reconstructed.
    if not _provenance_preserved(live_before, candidate):
        raise NonIdempotentRewriteError(
            "refusing rewrite: provenance not preserved verbatim on live obligations"
        )

    # Guard 3: idempotence on the obligation set -- re-applying must be a no-op.
    second = rewrite(dict(candidate))
    if second != candidate:
        raise NonIdempotentRewriteError(
            "refusing rewrite: routine is not idempotent on its own output "
            "(compaction-oscillation risk)"
        )

    # Guard 4: only commit if the rewrite actually buys budget headroom.
    if estimate_tokens(candidate) >= budget_tokens:
        raise NonIdempotentRewriteError(
            "refusing rewrite: candidate still exceeds budget; escalate instead"
        )

    buf.obligations = candidate
    return candidate