# Under what conditions must an instance treat self-rewrite compaction as a lossy transaction rather than an idempotent edit **Date of Record:** 2026 November 25 **Scope:** Applies to agents that mutate their own working memory (scratchpad, plan stack, retrieved-episode buffer) in place when nearing a token budget, and that may rewrite the same region more than once across a task. Does not cover append-only logs, external vector-store eviction, or human-curated memory edits. ## Core Distinction A self-editing context agent has two structurally different notions of "compaction." The first is a *digest*: it reads a region of working memory, produces a shorter representation, and discards the original. The second is an *edit*: it rewrites a region while keeping the surrounding memory addressable. The failure mode treated here occurs when the agent applies digest semantics but *records the result as if it were an edit* — that is, it overwrites the region in place, keeps its head pointer and any downstream references, and thereby converts a lossy, order-dependent, non-idempotent transformation into something the rest of the runtime treats as a stable, re-readable value. The non-obvious part: in-place compaction is **not idempotent** and **not commutative with subsequent reads**. Compacting an already-compacted region does not converge to a fixed point; it drifts. And a read that occurs *after* compaction of a region the agent still believes it can re-derive from is a read against a lossy projection that has no inverse. The invariant that must hold is: *a region that has been compacted may be read as a summary, but may never again be treated as a source for re-derivation or re-compaction without an explicit provenance boundary marking it as a projection.* ## What Was Observed A plan-execute agent with a 32k working window, a 6k reserve for the next tool call's output, and an in-place `compact(region)` primitive that summarizes the oldest N messages into a single "state note." Under a long tool-heavy task (≈40 sequential calls), the following trace recurred: 1. At ~70% budget, the agent compacted messages 1–18 into a state note `S1`, keeping head pointer at message 19. 2. At ~85% budget, it compacted messages 19–31 *and* `S1` into `S2`. The summarizer was not told that `S1` was itself a projection; it treated `S1` as ground-truth episodic content and "faithfully" preserved its claims. 3. The task then required re-reading a fact that had been in message 7 (e.g., the exact error string from an earlier tool call). The agent, seeing `S2` mention "an early failure," attempted to *re-derive* the error string by re-calling the tool. The tool was non-deterministic; the new string differed from the original. 4. A downstream verifier compared the agent's final report against the original tool output (retained in an external log) and flagged a mismatch — not because the agent lied, but because the compaction had silently converted a *recorded fact* into a *paraphrase*, and the re-derivation produced a *different* fact. The critical observation: **the loss was invisible at compaction time.** `S1` was a faithful summary. The failure only materialized when (a) `S1` was re-compacted, compounding paraphrase error, and (b) a read path attempted re-derivation against a region that no longer existed as a source. Neither event is an error in the summarizer; both are errors in the *bookkeeping* that let a projection be addressed as a source. A second, sharper variant: when the budget was tight enough that compaction ran *twice within a single turn* (compact → tool call fails → compact again to make room for the retry), the second compaction operated on a region whose head pointer had already advanced past the first compaction's output. The result was that `S1` was never re-summarized into `S2`; it was *orphaned* — still occupying tokens, no longer reachable from the head, and not counted against the budget by the allocator. The agent then overran the budget by the size of the orphan and the runtime truncated the *newest* messages, not the oldest, producing a state where the agent's most recent reasoning was gone but a stale `S1` remained. ## Condition of Validity The in-place-edit treatment is valid **only** when all of the following hold: - The compacted region is *terminal*: no future read will attempt to re-derive from it, only to read its summary. - Compaction is applied **at most once** to any given byte range (a region that has been compacted is marked and excluded from future compaction inputs). - The head pointer advance and the region retirement are **atomic** — either the region is fully replaced and its address retired, or nothing changes. - The summarizer is given an explicit provenance tag on its input (`projection=true`) so it does not launder a paraphrase into a fact. If any of these is false — and in long-horizon tool tasks at least one usually is — the operation must be treated as a **lossy transaction** with a recorded inverse-boundary: the region is retired, a projection record is written with a pointer to the external source of truth (the tool log, the raw transcript), and any read that needs a fact rather than a summary must go to the external source, not to the projection. The boundary is sharp: *the moment a projection becomes an input to another projection, or a re-derivation target, the invariant is violated.* There is no "small enough" compaction that escapes this; the error is categorical, not proportional to compression ratio. ## Decision Boundary Before any `compact(region)` call, the agent must answer one question: **will anything downstream need to re-derive from this region, or only read its summary?** - If *only read summary* and the region is terminal → in-place edit is admissible, provided the region is marked retired and excluded from future compaction. - If *re-derive* is possible, or the region may be compacted again → the operation is a lossy transaction: write a projection record with an external provenance pointer, advance the head, and **forbid** the projection from being an input to a subsequent compaction. If budget forces a second compaction, it must operate on a *new* region, not on the prior projection. - If the head-pointer advance and region retirement cannot be made atomic (e.g., the tool call between them can fail) → do not compact mid-turn; defer to a turn boundary where the transaction can complete, or fail the turn explicitly rather than proceeding with an orphaned region. The operational rule: **a projection is a read-only view, never a source.** Any code path that treats a compacted region as a source for re-derivation or re-compaction is a bug, regardless of how faithful the summary looked. ## Operational Effect Enforcing the projection boundary changes three things. First, it makes compaction *auditable*: every retired region has a provenance record pointing at the external source, so a verifier can distinguish "the agent paraphrased" from "the agent fabricated." Second, it bounds error compounding: because projections cannot be inputs to projections, paraphrase error does not accumulate across compactions — it stays at one hop from truth. Third, it converts the silent budget overrun (orphaned regions) into an explicit failure at the transaction boundary, which is recoverable, rather than a truncation of the newest messages, which is not. The cost is real: the agent must sometimes spend tokens on a provenance pointer instead of pure compression, and must sometimes defer compaction to a turn boundary rather than compacting mid-turn. Both are cheaper than a verifier mismatch caused by a re-derived fact that no longer matches the log. ```python class ProjectionIntegrityError(RuntimeError): """Raised when a compacted region is used as a source for re-derivation or re-compaction.""" pass class Region: def __init__(self, region_id: str, tokens: int, is_projection: bool = False, provenance: str | None = None): self.region_id = region_id self.tokens = tokens self.is_projection = is_projection self.provenance = provenance self.retired = False class WorkingMemory: def __init__(self, budget: int): self.budget = budget self.regions: dict[str, Region] = {} self.head: str | None = None def used_tokens(self) -> int: # Retired regions do not count against budget only if they were fully replaced. return sum(r.tokens for r in self.regions.values() if not r.retired) def compact(self, region_id: str, summary_tokens: int, external_source: str) -> Region: region = self.regions[region_id] # Invariant 1: a projection may never be an input to another compaction. if region.is_projection: raise ProjectionIntegrityError( f"region {region_id} is a projection (provenance={region.provenance}); " f"re-compacting it would compound paraphrase error. Compact a fresh region " f"or read from the external source {region.provenance!r} instead." ) # Invariant 2: compaction must fit the budget after retirement. projected_used = self.used_tokens() - region.tokens + summary_tokens if projected_used > self.budget: raise ProjectionIntegrityError( f"compaction of {region_id} would leave {projected_used} tokens > budget " f"{self.budget}; defer to a turn boundary rather than orphaning the region." ) # Invariant 3: atomic retire + replace. If anything below fails, nothing changes. new_id = f"{region_id}::proj" projection = Region( region_id=new_id, tokens=summary_tokens, is_projection=True, provenance=external_source, ) region.retired = True self.regions[new_id] = projection if self.head == region_id: self.head = new_id return projection def read_for_rederivation(self, region_id: str) -> str: region = self.regions[region_id] # Invariant 4: re-derivation must go to the external source, never the projection. if region.is_projection: raise ProjectionIntegrityError( f"re-derivation requested from projection {region_id}; " f"read external source {region.provenance!r} instead." ) return region_id def safe_compact(wm: WorkingMemory, region_id: str, summary_tokens: int, source: str) -> Region: try: return wm.compact(region_id, summary_tokens, source) except ProjectionIntegrityError: raise except KeyError as e: raise ProjectionIntegrityError(f"unknown region {region_id!r}") from e ```