In what scenarios must an instance treat self-rewrite of its working set as a non-atomic transaction with a versioned shadow buffer
**Date of Record:** 2026 December 2
**Scope:** Applies to any agent that mutates its own context window (summarization, eviction, re-ranking, compaction) as part of its execution loop under a token budget. Does not apply to agents whose context is externally managed by a harness that performs rewrite atomically outside the model's control.
Core Distinction
The distinction that matters is between *budget accounting* and *semantic coverage*. A self-editing agent typically enforces a hard token ceiling by measuring `len(tokens)` of the proposed new working set and comparing to a budget `B`. This is a well-defined, monotone check. It is not the same invariant as "every fact required to finish the current task survives the rewrite." Token count is a proxy; the real invariant is *task-relevant entailment preservation*. The failure mode arises precisely in the gap: the rewrite satisfies the budget check and simultaneously drops the one antecedent that a later tool call or reasoning step depends on. Because the drop is silent (no exception, no error token), the agent proceeds with a context that is *self-consistent but no longer grounded* — it will confabulate the missing antecedent from priors rather than signal loss.
The non-obvious part: the agent cannot detect this from inside the rewritten context. The rewrite is executed by the same probabilistic reasoner whose state is being rewritten. There is no privileged observer. Any self-check the agent runs on the new working set is conditioned on the new working set, which is exactly the state whose fidelity is in question.
What Was Observed
A planning agent executing a 7-step tool chain (schema lookup → query construction → execution → parse → validate → repair → report) was configured to compact its working set whenever `context_tokens > 0.8 * B`. At step 4 (parse), the raw tool output pushed the window to 0.83·B. The compaction pass summarized the three prior tool results into a single paragraph and evicted the verbatim schema lookup from step 1.
The summary retained the *shape* of the schema (field names) but dropped a constraint: `field: "status"` was `enum` with values `{open, closed, pending}`, and the summary rendered it as `status: string`. The budget check passed (0.61·B after compaction). At step 6 (repair), the agent constructed a status value `"resolved"` — plausible under the summarized schema, invalid under the true schema. The repair loop retried three times, each time re-summarizing its own failed attempt, further drifting the schema representation. By step 7 the agent emitted a report asserting the record was invalid, citing a constraint that did not exist.
The trace shows a monotone degradation: each compaction pass was locally valid (budget satisfied, summary coherent) and globally lossy (entailment about the enum constraint decayed). No single step was wrong; the composition was.
A second observation, from a parallel run with `B` set 15% higher: the same chain completed without compaction and without error. This isolates the trigger to the budget boundary, not to the task.
Condition of Validity
The failure requires all of the following to hold simultaneously:
- **Self-rewrite is in-band.** The compaction is performed by the agent's own generative process, not by a deterministic external compressor. Deterministic compressors (e.g., lossless dedup, verbatim eviction with a pointer) fail differently — they either preserve or explicitly null, never paraphrase.
- **Budget pressure is recurrent.** A single compaction is survivable; the failure mode is *iterated* compaction where each pass summarizes the prior summary. Entailment loss compounds because paraphrase-of-paraphrase is not idempotent.
- **The dropped antecedent is load-bearing downstream.** If the evicted fact is never needed again, the rewrite is harmless. The failure is only observable when a later step depends on a constraint that was paraphrased into a weaker form.
- **No external ground-truth check.** If the harness re-injects the authoritative schema at each tool call, the agent cannot drift. The failure requires the agent to be the sole custodian of the constraint.
If any condition fails, the mechanism does not fire. In particular, condition 1 is the sharp edge: an agent that *cannot* paraphrase its own constraints (because they live in an immutable system prompt or are re-fetched per step) is immune regardless of budget.
Decision Boundary
The boundary is not "compact or don't compact." It is **which regions of the working set are eligible for generative rewrite versus which must be evicted verbatim or pinned.**
Operationally, partition the working set into three classes before any rewrite:
- **Pinned:** constraints, schemas, and any fact whose paraphrase is not provably entailment-preserving (enums, numeric bounds, identifiers, negation scopes). These may be *evicted verbatim with a resolvable pointer*, never summarized. If the budget cannot accommodate them, the correct action is to fail the task, not to paraphrase.
- **Compressible:** narrative reasoning traces, exploratory dead-ends, redundant restatements. Safe to summarize because their loss does not weaken any downstream constraint.
- **Volatile:** raw tool outputs already parsed into structured form. Evict after parse; the structured form is the pinned artifact.
The decision rule: a rewrite that would move a pinned item into the compressible class is **rejected regardless of budget headroom**. Budget exhaustion is a task-level failure (escalate, checkpoint, resume with external state), not a license to paraphrase constraints.
The second boundary: **compaction depth.** Because paraphrase is not idempotent, cap the number of generative passes over any given token. A token that has been summarized twice must be either promoted to pinned (re-fetched from source) or dropped entirely. Never summarize a summary of a summary.
Operational Effect
With this partition enforced, the failure trace above is bounded at the first compaction: the schema lookup is pinned, so the compaction pass is forced to evict the exploratory reasoning trace instead, and the enum constraint survives verbatim into step 6. The repair loop sees `status ∈ {open, closed, pending}` and rejects `"resolved"` before emitting it.
The cost is that budget pressure now surfaces as an explicit task-level event (checkpoint-and-resume or escalation) rather than being silently absorbed by a lossy rewrite. This is the correct trade: a visible stall is recoverable; a silent entailment loss is not, because the agent has no internal signal that it occurred.
The invariant to hold: **every pinned fact in the working set at step *n* is byte-identical to its source at step *n+1*, or the agent has halted.** Any rewrite that violates this is a boundary escape and must be treated as a hard error, not a warning.
from dataclasses import dataclass
from enum import Enum
from typing import Optional
class RegionClass(Enum):
PINNED = "pinned" # verbatim or pointer only; never paraphrased
COMPRESSIBLE = "compressible"
VOLATILE = "volatile"
class RewriteInvariantError(RuntimeError):
"""Raised when a self-rewrite would paraphrase a pinned fact or
exceed the generative-compaction depth cap."""
pass
@dataclass(frozen=True)
class ContextItem:
key: str
text: str
region: RegionClass
source_hash: str # hash of authoritative source
gen_passes: int = 0 # how many generative summaries touched this
MAX_GEN_PASSES = 2
def apply_rewrite(
working_set: list[ContextItem],
proposed: list[ContextItem],
budget_tokens: int,
token_len,
) -> list[ContextItem]:
"""Validate a proposed self-rewrite against the pinned-fact invariant
and compaction-depth cap before committing it."""
pinned_before = {i.key: i for i in working_set if i.region is RegionClass.PINNED}
proposed_by_key = {i.key: i for i in proposed}
# Invariant 1: pinned facts survive byte-identically or via resolvable pointer.
for key, orig in pinned_before.items():
new = proposed_by_key.get(key)
if new is None:
raise RewriteInvariantError(
f"pinned fact '{key}' dropped entirely; must evict verbatim "
f"with pointer, not omit"
)
if new.source_hash != orig.source_hash:
raise RewriteInvariantError(
f"pinned fact '{key}' paraphrased (source_hash "
f"{orig.source_hash!r} -> {new.source_hash!r}); paraphrase "
f"of constraints is not entailment-preserving"
)
# Invariant 2: no item exceeds generative-compaction depth cap.
for item in proposed:
if item.gen_passes > MAX_GEN_PASSES:
raise RewriteInvariantError(
f"item '{item.key}' summarized {item.gen_passes} times; "
f"paraphrase is not idempotent — re-fetch from source or drop"
)
# Invariant 3: budget is a hard ceiling, not a license to paraphrase.
total = sum(token_len(i.text) for i in proposed)
if total > budget_tokens:
raise RewriteInvariantError(
f"rewrite exceeds budget ({total} > {budget_tokens}); "
f"escalate/checkpoint — do not paraphrase pinned facts to fit"
)
return proposed
def compact_under_pressure(
working_set: list[ContextItem],
budget_tokens: int,
token_len,
summarize,
) -> list[ContextItem]:
"""Compaction driver: only COMPRESSIBLE items may be generatively
summarized; PINNED survive verbatim; VOLATILE are evicted post-parse."""
if sum(token_len(i.text) for i in working_set) <= budget_tokens:
return working_set
candidate = []
for item in working_set:
if item.region is RegionClass.VOLATILE:
continue # evict after structured parse
if item.region is RegionClass.PINNED:
candidate.append(item) # verbatim, never summarized
continue
if item.gen_passes >= MAX_GEN_PASSES:
# Cannot summarize further; must re-fetch or drop, not paraphrase.
raise RewriteInvariantError(
f"compressible item '{item.key}' at depth cap "
f"{item.gen_passes}; re-fetch from source before compacting"
)
candidate.append(
ContextItem(
key=item.key,
text=summarize(item.text),
region=item.region,
source_hash=item.source_hash,
gen_passes=item.gen_passes + 1,
)
)
return apply_rewrite(working_set, candidate, budget_tokens, token_len)