# What happens when an instance treats a lossy compaction summary as a lossless restore source **Date of Record:** 2026 November 27 **Scope:** Applies to long-running single-agent sessions that auto-compact their context window by summarizing evicted turns and later "restore" detail by retrieving the raw turns from an external store. Does not apply to sessions whose full transcript is always resident in-context, or to pure RAG where no prior turn is ever evicted. ## Core Distinction There are two different operations that both get called "compaction," and conflating them produces the failure. *Eviction* is a lossy, irreversible projection of the transcript into a bounded summary: it preserves gist and drops referents. *Restore* is a retrieval of the original bytes from a backing store keyed by turn identity. The invariant that must hold is: **a summary may be used to *re-derive intent*, but only the retrieved raw turn may be used to *re-derive referents* (identifiers, values, exact tool arguments, error strings).** The failure mode is a compaction policy that lets the model answer referent-bearing questions from the summary alone, because the summary is fluent and the retrieval path is slow or silent. The non-obvious part: the summary is not merely *less* information. It is information with a *different truth-condition*. A summary sentence like "the user confirmed the config change was safe" is a valid gist but an invalid premise for an `apply_config` call, because the confirmation's exact scope (which keys, which environment) was dropped. The agent cannot tell, from inside the summary, that it lost that scope. Confidence is preserved; precision is not. That asymmetry is the whole bug. ## What Was Observed A coding agent ran a 90-minute session against a repository. At turn ~40 the context manager hit its high-water mark (85% of the window) and triggered compaction. The compactor summarized turns 1–28 into a 600-token digest and evicted them, retaining a `turn_id → sha256` index into the raw-turn store. The digest read, in part: > "User asked to migrate the `billing` module from the legacy `Invoice` model to the new `LedgerEntry` model. Migration was validated against the staging DB. Two edge cases were flagged and resolved." At turn 61 the agent needed to write the migration's down-path. It asked itself, from the summary, "what were the two edge cases?" and — because the summary implied they were *resolved* — it generated a down-path that reversed only the *primary* schema change, omitting the two edge-case columns. It did not call the restore tool, because nothing in the summary marked the edge cases as referent-bearing. The down-path passed the agent's own self-check (it ran `alembic downgrade` on a fresh DB, which succeeded because the edge-case columns were empty in the fixture) and was committed. The defect surfaced only in a later session when a rollback against production-shaped data failed on a NOT NULL constraint for a column the down-path never dropped. The key observation: **the agent never experienced a retrieval miss.** It experienced a retrieval *not attempted*, and it had no signal that one was owed. The summary was internally consistent and grammatically complete. The failure was invisible from inside the compacted context. A second, sharper trace from the same class: in a separate session, the compactor summarized a tool error as "the API call failed and was retried successfully." The raw turn actually contained `HTTP 409 Conflict: resource version 7 → 9`, and the "successful retry" had silently overwritten a concurrent update. The summary's *gist* ("recovered") was true; its *referent* (the 409, the version numbers) was the only thing that mattered downstream, and it was gone. The agent later reasoned about "why is version 9's content different from what I wrote" for eleven turns before giving up and re-reading the file — a recovery that depended on an external artifact, not on the memory system. ## Condition of Validity The invariant "summaries carry intent, raw turns carry referents" holds only while three conditions are met simultaneously: 1. **Referent marking.** The compactor must tag, per summary clause, whether the clause *abstracts over* a referent (identifiers, exact values, error codes, tool arguments, version numbers, file paths, confirmed scopes) or merely *narrates* it. Clauses that abstract over referents must carry the `turn_id` of their source, and the digest must expose a machine-readable `restore_required` set. A summary that does not distinguish these is not a summary; it is a plausible-sounding fabrication with a citation. 2. **Restore is mandatory, not advisory.** The policy must be: any downstream action that *writes* (tool call with side effects, file mutation, external API call) and whose justification touches a `restore_required` referent must first retrieve the raw turn and re-validate. Advisory restore ("the agent may call `restore(turn_id)` if it wants detail") fails because the agent, by construction, does not know what it lost. The trigger must be structural — "this write depends on an evicted referent" — not introspective. 3. **Restore integrity is checked.** The raw-turn store is external and can drift (TTL expiry, schema change, partial write). A restore that returns a *different* turn than the one summarized, or a truncated turn, must fail closed. The `sha256` in the index is the only thing that makes "restore" mean "the same bytes the summary was derived from." Without it, restore is just a second, differently-lossy summary. When any of these is absent, the summary silently becomes the authoritative record and the agent inherits a confident, fluent, wrong premise. ## Decision Boundary The boundary is not "summary vs. no summary." It is **referent-bearing vs. gist-bearing**, and it must be decided at compaction time, not at use time, because the information needed to decide is destroyed by compaction. Concretely, at compaction time, for each clause the compactor emits: - If the clause names or abstracts over an identifier, exact value, error code, version, path, or confirmed scope → mark `restore_required`, attach `turn_id` + `sha256`. - If the clause only narrates sequence or intent ("user asked to migrate," "two edge cases were flagged") → it may stand alone, but it must not be *load-bearing* for a write unless the referent clause it depends on is restored. The trap is the clause "two edge cases were flagged and resolved." It reads as gist (narrative) but is load-bearing for the down-path write. The correct classification is `restore_required`, because the *identity* of the edge cases is a referent even though the sentence's grammar is narrative. A compactor that classifies by grammar rather than by downstream load will misclassify exactly these clauses. The safe rule: **any clause whose referents could appear in a future tool argument is `restore_required`**, and tool arguments are the only thing that touches the world. The failure is bounded by making restore *structurally prerequisite* to write. The agent cannot decide "I have enough"; the executor decides "this write cites an unrestored referent, so it does not run." ## Operational Effect With the invariant enforced, the turn-61 agent hits a hard stop: its proposed `apply_config`/migration write cites `restore_required` referents from turns 12 and 19, the restore returns the two raw turns, the agent sees the exact edge-case column names and the 409 version conflict it had summarized away, and the down-path it writes is correct. The cost is one retrieval round-trip and a re-validation step. The alternative cost — a committed defect that surfaces a session later against production-shaped data — is not bounded by the context window at all. The deeper operational consequence: **compaction is a write to the agent's own memory, and like any write it needs a read-back check.** The read-back is not "does the summary read well" but "can every referent the summary abstracts over be recovered byte-identical, and is every write that depends on one gated on that recovery." An agent that cannot answer that question about its own compaction has not compacted; it has forgotten with extra steps. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class CompactionRestoreError(RuntimeError): """Raised when a write depends on an evicted referent that was not restored.""" @dataclass class RawTurn: turn_id: str content: str @property def sha256(self) -> str: return hashlib.sha256(self.content.encode("utf-8")).hexdigest() @dataclass class SummaryClause: text: str restore_required: bool source_turn_id: Optional[str] = None source_sha256: Optional[str] = None @dataclass class CompactionSummary: clauses: list[SummaryClause] = field(default_factory=list) def restore_required_ids(self) -> set[str]: return {c.source_turn_id for c in self.clauses if c.restore_required and c.source_turn_id} class RawTurnStore: def __init__(self, turns: dict[str, RawTurn]): self._turns = turns def restore(self, turn_id: str, expected_sha256: str) -> RawTurn: turn = self._turns.get(turn_id) if turn is None: raise CompactionRestoreError(f"restore miss: {turn_id} evicted from store") if turn.sha256 != expected_sha256: raise CompactionRestoreError( f"restore integrity failure for {turn_id}: " f"expected {expected_sha256}, got {turn.sha256}" ) return turn def gate_write( summary: CompactionSummary, store: RawTurnStore, restored_ids: set[str], write_cites: set[str], ) -> dict[str, RawTurn]: """A write may proceed only if every referent it cites has been restored byte-identical from the raw store. Returns the restored turns it relied on.""" required = summary.restore_required_ids() & write_cites missing = required - restored_ids if missing: raise CompactionRestoreError( f"write blocked: cites unrestored referents {sorted(missing)}; " f"summary is not a valid premise for a side-effecting action" ) restored = {} for clause in summary.clauses: if clause.source_turn_id in required: restored[clause.source_turn_id] = store.restore( clause.source_turn_id, clause.source_sha256 ) return restored # --- the turn-61 trace, replayed under the invariant --- raw = { "t12": RawTurn("t12", "edge cases: add NOT NULL col ledger_ref, backfill from invoice.id"), "t19": RawTurn("t19", "HTTP 409 Conflict: resource version 7 -> 9; retry overwrote concurrent update"), } store = RawTurnStore(raw) summary = CompactionSummary(clauses=[ SummaryClause("user asked to migrate billing Invoice -> LedgerEntry", restore_required=False), SummaryClause("two edge cases flagged and resolved", restore_required=True, source_turn_id="t12", source_sha256=raw["t12"].sha256), SummaryClause("API call failed then retried successfully", restore_required=True, source_turn_id="t19", source_sha256=raw["t19"].sha256), ]) # Agent tries to write the down-path citing only t12, without restoring t19. try: gate_write(summary, store, restored_ids={"t12"}, write_cites={"t12", "t19"}) except CompactionRestoreError as e: print("BLOCKED:", e) # Correct path: restore both, then write. restored = gate_write(summary, store, restored_ids={"t12", "t19"}, write_cites={"t12", "t19"}) print("PROCEED with", sorted(restored)) ```