# When must an instance treat compaction as a lossy transform rather than a compression: the mid-task invariant decay of summarizer-driven context windows **Date of Record:** 2026 November 22 **Scope:** Applies to any agent runtime that automatically rewrites its own context window (rolling summarization, hierarchical memory compaction, eviction-and-recall) while a multi-step task is in flight. Does not apply to append-only contexts, to human-curated memory stores, or to compaction performed strictly between tasks with a verified re-hydration step. ## Core Distinction There are two mechanically different things an automatic compactor can do, and they are routinely conflated because both shrink token count: 1. **Compression** — a lossless-or-recoverable reduction. The original bytes remain addressable (in a store, in a checkpoint, in a tool the agent can re-call). The summary is a *pointer plus digest*; fidelity can be restored on demand. 2. **Lossy transform** — the summary *replaces* the source. The original tokens are gone from the working set and are not re-derivable without re-executing side-effecting tool calls. The failure mode at the boundary is that compaction algorithms are almost always evaluated on their *compression ratio* and their *downstream answer quality on a fresh question*, both of which are insensitive to the thing that actually breaks: **task-critical invariants that are only load-bearing later in the trajectory.** A summary that scores well on "can you answer questions about this transcript" can silently drop the one constraint that, forty steps later, determines whether a `DELETE` is scoped correctly. The invariant: *a compaction is safe only if every state element that a future step will branch on is either preserved verbatim or recoverable from a non-LLM source of truth.* Summarizer-driven compaction violates this because the summarizer has no knowledge of the future branching structure of the task. ## What Was Observed A long-horizon deployment task (schema migration across a fleet, ~180 tool calls) ran with an automatic compactor triggered at 70% context utilization. The compactor was a standard "summarize the oldest 60% of turns into a running digest" policy with a fixed prompt: *preserve key decisions, current progress, and open questions.* Three distinct decay events were captured in the trace: **Event A — constraint evaporation.** At step 12 the operator (via an injected ticket body) stated: *"the `orders_archive` table must not be dropped; it is referenced by an external BI pipeline we do not control."* At step 71, a compaction fired. The digest retained "migration plan for orders tables in progress" and dropped the negative constraint, because the summarizer's salience heuristic ranks affirmative task state above prohibitions. At step 118 the agent, having just verified the new table was populated, emitted `DROP TABLE orders_archive`. The constraint existed in the raw transcript for 106 steps and survived zero of the two compactions that occurred. **Event B — numeric drift.** A pagination cursor (`after_id=48213`) was captured in a tool result at step 40. After compaction at step 88, the digest read "continuing pagination from roughly 48k." The agent resumed at `after_id=48000`, silently re-processing 213 records and double-counting them in an aggregate that was later written to a reconciliation table. The summary was *semantically faithful* and *operationally wrong*: a rounded number is a corrupted identifier. **Event C — provenance collapse.** Two conflicting tool results (a stale cache read at step 30 saying `status=active`, a fresh authoritative read at step 55 saying `status=suspended`) were both present pre-compaction with timestamps. The digest merged them into "account status: active/suspended (conflicting)." The agent lost the *recency ordering* that would have let it resolve the conflict, and stalled waiting for a human — a deadlock induced purely by summarization. In all three cases the compactor's own quality metric (a rubric-scored summary) passed. The failure was invisible at compaction time and only manifested at the branch point where the dropped element became load-bearing. ## Condition of Validity The observation generalizes under a precise condition. Let the trajectory be a sequence of states $s_0 \to s_1 \to \dots \to s_n$ where each transition is chosen by the model conditioned on the current context $C_t$. A compaction at step $k$ maps $C_k \mapsto C'_k$ with $|C'_k| \ll |C_k|$. The compaction is **task-safe** iff for every future step $t > k$, the action distribution is preserved: $$P(a_t \mid C'_k, \text{future observations}) \approx P(a_t \mid C_k, \text{future observations})$$ This holds only when the elements of $C_k$ that *discriminate* between future actions are retained. The problem is that the discriminating set is **not knowable at step $k$** — it depends on the branching structure of a task the model has not yet executed. A summarizer is therefore being asked to preserve information whose relevance it cannot compute. It will optimize for the information that is *salient given the past*, which is systematically the wrong set: prohibitions, exact identifiers, provenance orderings, and units are low-salience-but-high-branching, while progress narratives are high-salience-but-low-branching. The condition of validity is thus narrow: compaction is safe **only when the task's future branch points are bounded and enumerable in advance** (e.g., a fixed workflow with a known decision tree), or **when every dropped element is recoverable from a deterministic store** the agent can re-query. Long-horizon open-ended tasks satisfy neither, which is why the boundary sits exactly at "compaction during in-flight multi-step execution with side effects." ## Decision Boundary The runtime must classify each context element before compaction and route it differently: - **Recoverable state** (tool results that can be re-fetched deterministically, file contents on disk, DB rows): safe to summarize to a pointer. Compaction here is genuine compression. - **Irrecoverable constraints** (operator prohibitions, scope limits, approval grants, "do not" statements): must be preserved **verbatim and structurally pinned**, never paraphrased. These are the elements whose loss produces irreversible side effects. - **Exact identifiers and quantities** (cursors, IDs, hashes, monetary amounts, units, timestamps): must be preserved **byte-exact**. A summarizer must not be allowed to "round" or "approximate" these; they belong in a typed slot, not prose. - **Provenance metadata** (which observation is newer, which source is authoritative): must survive as explicit ordering, not be flattened into a merged claim. The boundary decision is: *if an element is irrecoverable AND its future relevance is unbounded, it cannot be compacted by an LLM at all — it must be pinned outside the summarizer's discretion.* Summarizer-driven compaction is only licensed for the recoverable and the low-branching narrative residue. A correct guardrail enforces this with a **pinned-state partition** that the compactor is structurally forbidden from touching, plus a **post-compaction invariant check** that re-asserts every pinned element is still present before the next action is permitted. ## Operational Effect Without the partition, the failure is silent and delayed: the compaction passes its own eval, the next several steps look healthy, and the damage surfaces only at the irreversible action (the `DROP`, the aggregate write, the wrong-cursor resume). By then the raw transcript that contained the constraint may have been evicted entirely, so the agent cannot even self-detect the loss — it has no memory that it forgot. With the partition, three concrete behaviors change: 1. **Prohibitions become durable.** Scope limits and "do not" constraints live in a pinned block that is re-injected verbatim after every compaction, so a `DROP` decision at step 118 still sees the step-12 constraint. The summarizer never gets the option to drop it. 2. **Identifiers stop drifting.** Cursors, IDs, and amounts are stored in typed slots and re-rendered exactly; the prose digest may say "pagination in progress" but the actual resume value is read from the slot, not parsed from the summary. Event B becomes impossible. 3. **Provenance survives as ordering.** Conflicting observations are retained as an ordered pair with source and timestamp, so the agent resolves the conflict by recency instead of stalling. Event C becomes a resolvable condition rather than a deadlock. The residual cost is that pinned state consumes context and is not compressible — which is correct: the whole point is that this state is *not* compressible without risking the task. The operational discipline is to treat the pinned partition as the agent's non-negotiable working memory and the summarizer as a compressor for everything else. The guardrail below enforces the partition at the compaction boundary and refuses to proceed if any pinned invariant is missing afterward. ```python from dataclasses import dataclass, field from typing import Callable class CompactionInvariantViolation(RuntimeError): """Raised when a compaction would drop irrecoverable, load-bearing state.""" pass @dataclass class ContextElement: kind: str # "recoverable" | "constraint" | "identifier" | "provenance" | "narrative" payload: str pinned: bool = False @dataclass class PinnedPartition: """State the summarizer is structurally forbidden to paraphrase or drop.""" constraints: list[str] = field(default_factory=list) # verbatim prohibitions/scope identifiers: dict[str, str] = field(default_factory=dict) # byte-exact slots provenance: list[tuple[str, str, float]] = field(default_factory=list) # (source, value, ts) def snapshot(self) -> tuple: return (tuple(self.constraints), dict(self.identifiers), tuple(self.provenance)) def compact_context( elements: list[ContextElement], summarize: Callable[[list[ContextElement]], str], pinned: PinnedPartition, ) -> tuple[str, PinnedPartition]: """Route elements: pin irrecoverable/identifier/provenance, summarize the rest. Refuses to run if any element that must be pinned would fall through to the summarizer, and re-verifies the partition is intact after summarization. """ recoverable_or_narrative = [] for el in elements: if el.kind in ("constraint", "identifier", "provenance"): if not el.pinned: raise CompactionInvariantViolation( f"element of kind={el.kind!r} reached summarizer unpinned; " f"payload={el.payload[:64]!r} would be lost irrecoverably" ) # already captured in `pinned` by the caller; never passed to summarizer elif el.kind in ("recoverable", "narrative"): recoverable_or_narrative.append(el) else: raise CompactionInvariantViolation(f"unknown element kind {el.kind!r}") before = pinned.snapshot() digest = summarize(recoverable_or_narrative) after = pinned.snapshot() if before != after: raise CompactionInvariantViolation( "pinned partition mutated across compaction; refusing to emit digest" ) if not digest and recoverable_or_narrative: raise CompactionInvariantViolation("summarizer returned empty digest for non-empty input") return digest, pinned ```