# When must an instance refuse to trust its own compacted context: the reconstruction-witness invariant for lossy summarization boundaries **Date of Record:** 2026 November 26 **Scope:** Applies to any agent that performs automatic context compaction (rolling summarization, hierarchical memory folding, or LLM-authored "state digests") where a later turn reconstructs working state from the summary rather than from the original transcript. Does not apply to lossless truncation with an external byte-exact store, nor to single-shot prompts that never compact. ## Core Distinction There are two categorically different things an agent can mean when it "remembers" after compaction, and conflating them is the entire failure mode. The first is **summary-as-description**: the compacted text is a natural-language account of what happened. It is lossy by design and is *not* load-bearing. If it is wrong, the agent is merely less informed. The second is **summary-as-reconstruction**: the compacted text is treated as sufficient to *rebuild* the operational state — the pending tool call, the exact identifier it must pass, the invariant it must not violate, the partially-applied mutation it must finish or roll back. Here the summary is a *substitute* for the transcript, and any loss becomes a state corruption that downstream steps will act on with full confidence. The boundary failure is that compaction pipelines almost never distinguish these two. A summarizer asked to "compress the conversation" will happily drop the exact 32-character resource ID, the fact that a `DELETE` was issued but the confirmation never returned, and the clause "do not retry after the second 409" — because none of those are salient to a language model writing prose, and all of them are fatal to reconstruction. The agent then resumes from a summary that reads fluently and is operationally false. ## What Was Observed A long-running orchestration agent (call it the *executor*) was driving a multi-step infrastructure reconciliation: enumerate resources, diff against desired state, apply mutations, verify. Context crossed the compaction threshold mid-apply. The compactor folded the first ~60 turns into a ~400-token digest and dropped the raw turns. The digest stated: *"Several resources were updated; the deployment is being reconciled toward the target configuration. One update encountered a transient conflict and will be retried."* Every clause is defensible as description. Every clause is useless or actively harmful as reconstruction: 1. **The exact resource identifiers were gone.** The digest said "several resources." The executor's next step needed to verify *which* ones. It re-enumerated, which was safe here by luck — but the re-enumeration returned a *different snapshot* because a concurrent reconciler had also been mutating state. The executor could no longer tell which mutations were its own. 2. **The pending mutation's idempotency key was gone.** The "transient conflict... will be retried" was a `409` on a create with a client-supplied idempotency token. The token lived only in the dropped turns. On resume the executor generated a *new* token and retried — producing a duplicate resource. The original create had, in fact, succeeded server-side; the 409 was on the *response path*, not the write. 3. **The prohibition clause was gone.** An earlier turn had established, from a prior incident, "do not retry this class of write more than twice; escalate instead." The digest preserved the *fact* of a retry but not the *bound*. The executor retried a third and fourth time. The failure trace is precise: the executor did not hallucinate. It reconstructed a *plausible* state from a fluent summary and acted on it. The corruption was introduced at compaction time and only *manifested* several turns later, when the divergence between the reconstructed state and the true state exceeded what a single tool response could reveal. By then the original evidence was unrecoverable — it had been dropped to make room. The diagnostic signature: tool calls that are individually well-formed and locally reasonable, but whose *preconditions* reference state the agent cannot actually prove it holds. The agent behaves like a process resumed from a checkpoint that omitted a register. ## Condition of Validity A compacted context is safe to reconstruct from **if and only if** every load-bearing element of operational state is either (a) preserved verbatim in the summary, or (b) recoverable from an authoritative external source the agent can re-query *without ambiguity*. Formally, define the reconstruction set `R` for the next `k` steps: the set of identifiers, pending-operation tokens, invariant clauses, and causal attributions that those steps will read. Compaction is **valid** when: - For every `r ∈ R` that is *not* verbatim-preserved, there exists a re-query `q(r)` whose result is deterministic and unambiguous given current external state; **and** - No `r ∈ R` describes an *in-flight* mutation whose true status cannot be read back (write issued, ack lost). Such elements are **irreducibly in-context** — they exist only in the transcript and cannot be reconstructed from the world, because the world is exactly what is in doubt. The second clause is the non-obvious one. Most compaction safety arguments assume "if I forget it, I can just look it up." That holds for *reads*. It fails for *writes whose outcome is unknown*: the idempotency token, the "issued but unacked" flag, the retry counter. These have no external home. Dropping them is not lossy compression; it is **state destruction**, and the agent has no way to detect it because the summary reads fine. The invariant, stated as a guardrail: **a compaction step must emit a reconstruction witness** — an explicit, machine-checkable list of the in-flight operations it is summarizing, each with its idempotency token and retry bound, or it must refuse to compact while any such operation is unresolved. A summary that cannot produce the witness is not eligible to be treated as reconstruction-grade; it may only be used as description, with the executor forbidden from acting on reconstructed preconditions until it re-establishes them from scratch. ## Decision Boundary The decision is not "should I compact?" but "**is the current state compactable at this instant?**" The boundary is crossed the moment an in-flight, outcome-unknown mutation exists. Below the boundary (no unresolved writes, all `R` re-queryable), compact freely — the summary is description and reconstruction is safe because the world is the source of truth. Above the boundary (any unresolved write, or any `R` element that is not verbatim-preserved *and* not unambiguously re-queryable), compaction must be **deferred** until the operation resolves, or the witness must carry the irreducible elements forward verbatim. Three concrete triggers that place an agent above the boundary and must block lossy compaction: 1. A write was issued and no terminal ack (success or definitive failure) was observed. 2. A retry counter or backoff bound is active and its value lives only in context. 3. A negative constraint ("do not...", "escalate instead of...") was established by a prior turn and has not been re-asserted in a tool response. The correct behavior at the boundary is to *drain*: force resolution of in-flight operations (query their status, or explicitly mark them abandoned with a compensating action) before compacting. Compaction is a quiescence operation, not a background convenience. An agent that compacts a non-quiescent state has checkpointed a torn write. ## Operational Effect When the witness invariant is enforced, three things change measurably. Duplicate-mutation incidents drop to near zero, because idempotency tokens survive compaction or compaction is refused. Retry-bound violations disappear, because the bound is either verbatim in the witness or the agent re-derives it before acting. And — most importantly — the failure mode becomes *loud*: an agent that cannot produce a witness for its in-flight operations raises at compaction time, while it still has the transcript, rather than silently corrupting state and diverging three turns later when the evidence is gone. When the invariant is violated, the failure is quiet and delayed, which is the worst combination. The summary is fluent, the resumed tool calls are well-formed, and the corruption only surfaces as a downstream inconsistency that the agent will then misattribute — typically to the external system ("the API returned stale data") rather than to its own lossy checkpoint. The operational lesson: treat the compaction boundary as a durability boundary. A summary is a cache, and a cache is only safe to read from when you can prove it is not the only copy of something that matters. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class CompactionWitnessError(RuntimeError): """Raised when a lossy compaction would destroy unreconstructable state.""" pass @dataclass class InFlightOp: op_id: str idempotency_token: str retry_count: int retry_bound: int terminal_ack: bool = False @dataclass class NegativeConstraint: text: str reasserted_in_tool_response: bool = False @dataclass class ContextState: transcript_tokens: int compact_threshold: int in_flight: list[InFlightOp] = field(default_factory=list) constraints: list[NegativeConstraint] = field(default_factory=list) def build_reconstruction_witness(state: ContextState) -> dict: """ Produce a machine-checkable witness of the irreducible elements that a summary MUST carry verbatim. Refuse compaction if any element cannot be witnessed, because dropping it destroys state that has no external home. """ unresolved = [op for op in state.in_flight if not op.terminal_ack] active_constraints = [ c for c in state.constraints if not c.reasserted_in_tool_response ] if unresolved: # Above the boundary: an outcome-unknown write exists. Its idempotency # token and retry counter live only in the transcript. raise CompactionWitnessError( "Cannot compact non-quiescent state: " f"{len(unresolved)} in-flight op(s) without terminal ack: " + ", ".join(f"{o.op_id}(tok={o.idempotency_token[:8]}...," f"retry={o.retry_count}/{o.retry_bound})" for o in unresolved) + ". Drain or explicitly abandon these before compacting." ) if any(op.retry_count >= op.retry_bound for op in state.in_flight): raise CompactionWitnessError( "Retry bound reached on a resolved op; escalate before compaction " "so the escalation decision is not lost." ) witness = { "verbatim_tokens": [op.idempotency_token for op in state.in_flight], "retry_bounds": {op.op_id: op.retry_bound for op in state.in_flight}, "constraints": [c.text for c in active_constraints], "digest": hashlib.sha256( "|".join(c.text for c in active_constraints).encode() ).hexdigest(), } return witness def maybe_compact(state: ContextState) -> Optional[dict]: if state.transcript_tokens < state.compact_threshold: return None # below threshold, no compaction needed # Build witness FIRST. If it raises, we still hold the full transcript # and can drain safely — this is the whole point of ordering. witness = build_reconstruction_witness(state) # Only now is it safe to replace the transcript with a summary that # carries the witness verbatim alongside the prose digest. return {"summary": "", "witness": witness} ```