# In what scenarios must an instance treat automatic context compaction as a lossy state transfer rather than a summarization convenience **Date of Record:** 2026 November 26 **Scope:** Applies to any long-horizon agent whose runtime performs automatic context compaction (rolling summarization, hierarchical memory folding, or token-budget-triggered eviction) mid-trajectory. Does not apply to stateless single-turn inference or to agents whose entire trajectory fits within one context window with no eviction. ## Core Distinction A summarizer is not a compressor; it is a *re-encoder*. The distinction that governs every downstream failure is this: compaction does not preserve information, it preserves *plausibility*. A summarizer LLM, asked to fold 40k tokens of trajectory into 2k, produces text that is fluent, coherent, and internally consistent—and that consistency is precisely what makes the loss invisible. There is no checksum. There is no diff against the original. The compacted state asserts facts with the same confidence whether it retained them or hallucinated them. The non-obvious boundary: compaction is safe when the trajectory's future depends only on *semantic* content (what was decided, what the goal is). It becomes a lossy state transfer—and can silently corrupt execution—when the future depends on *operational* content: exact identifiers, ordering of side effects, values returned by tools that were never re-derivable, and negative constraints ("do not retry X"). Summaries systematically preserve the former and systematically drop the latter, because the latter is low-salience in a summarization objective but load-bearing in an execution objective. ## What Was Observed A migration agent was executing a 90-step plan against a schema service. At step 41 the runtime hit its 32k soft limit and triggered a rolling summarizer that folded steps 1–38 into a 1,800-token digest. The digest read: > "The agent has been applying migrations to the `orders` schema. Earlier attempts to apply `add_index` failed due to lock contention and were retried successfully. Current state: migrations 001–014 applied." Three facts were lost, none of them flagged: 1. **The exact table name.** The digest said `orders`. The actual target was `orders_v2`; `orders` had been mentioned once as a *deprecated* table the agent was explicitly told not to touch. The summarizer collapsed two similarly-named entities into the more frequent one. At step 44 the agent issued `ALTER TABLE orders ADD COLUMN ...` — a destructive write to the wrong table. 2. **The retry ledger.** "Retried successfully" was true for migration 011 but false for 013. Migration 013's `add_index` had failed with a *permanent* error (a type mismatch), not lock contention. The agent had marked it "deferred pending human review" in a tool-call annotation. The summarizer merged the two failure modes into one benign narrative. At step 47 the agent re-attempted 013 believing it was a transient lock issue, and the retry looped 14 times against a deterministic error. 3. **The ordering constraint.** A prior tool result had returned `{"applied": [1..14], "requires_ordering": true, "next_must_be": 15}`. The `next_must_be` field was a machine-readable invariant. The summarizer did not carry it forward because it was "obvious" from the sequence. But the agent's planner had been reading `next_must_be` as its source of truth; after compaction it read the sequence instead, and the sequence had a gap at 013. It skipped to 015. The failure was not a hallucination in the ordinary sense. Every sentence in the digest was locally defensible given *some* reading of the trajectory. The digest was a *consistent fabrication of salience*: it retained what was narratively central and discarded what was operationally binding. ## Condition of Validity Compaction-as-summarization is valid **only** when the post-compaction agent's next action is a function of the digest alone. It is invalid—must be treated as a lossy transfer—whenever any of the following holds: - **Re-derivability is false.** The future depends on a value that cannot be reconstructed by re-querying the environment: a tool result that cost a non-idempotent side effect to obtain, a nonce, a one-time token, a timestamped observation, or a value from a source that has since changed. Summaries drop these at high rates because they are unremarkable strings. - **Negative constraints exist.** The trajectory contains prohibitions ("never touch `orders`", "do not retry after a 4xx", "this endpoint is rate-limited to 1/s"). Negative constraints have no narrative salience—they are the absence of events—and summarizers reliably elide them. This is the single highest-severity class of loss. - **Entity disambiguation is load-bearing.** Two or more entities share a name stem (`orders` / `orders_v2`, `staging` / `staging-legacy`). Summarizers collapse them by frequency. After collapse, the agent cannot recover the distinction because the digest has already asserted one of them. - **Ordering or idempotency invariants are encoded in structure, not prose.** Structured fields like `next_must_be`, `already_applied`, `expires_at`, `attempt_count` are machine contracts. A prose summary is not a faithful re-encoding of a machine contract; it is a paraphrase that loses the type. Under any of these conditions, the invariant that must hold is: **the compacted state must be a superset-preserving projection of the fields the planner reads, not a natural-language rendering of the trajectory.** Concretely, compaction must partition state into (a) semantic narrative, freely summarizable, and (b) a *pinned operational frame*—identifiers, negative constraints, machine-readable invariants, and the retry ledger—which is copied verbatim, never summarized, and re-injected on every compaction cycle. ## Decision Boundary The operational decision is not "should we compact" (at 32k you must) but "what is the unit of compaction." The boundary that separates safe from corrupting: - **Compact the narrative, pin the frame.** If the runtime cannot guarantee verbatim carry-forward of the operational frame, it must not compact—it must either hard-stop and escalate, or spill the frame to durable external state (a scratchpad file, a key-value store) that the agent re-reads post-compaction. Summarizing the frame is the failure; the frame must be *moved*, not *rewritten*. - **Every compaction cycle is a generation.** Compaction is not idempotent across cycles: summarizing a summary compounds salience bias. After two or three folds, the digest describes a trajectory that resembles the real one but has drifted. The guardrail is a **compaction depth counter**; beyond depth 2, the runtime must re-derive the frame from the external spill rather than from the prior digest, or refuse to fold further. - **The verifier must run against the frame, not the digest.** Any post-compaction re-plan must be validated against the pinned frame (does the next action violate a negative constraint? does it match `next_must_be`?) before execution. A planner reading only the digest has no way to detect its own corruption. The clean test: *if the digest were replaced by an adversarial but fluent summary, would the agent's next action change?* If yes, the frame is not pinned and compaction is unsafe. ## Operational Effect Treating compaction as lossy transfer changes three things in the runtime. First, it forces an explicit schema for the operational frame—a typed structure, not prose—which makes the survival of identifiers, constraints, and invariants a *checkable* property rather than a hope. Second, it converts compaction from a fire-and-forget background task into a transactional step with a post-condition: after fold, assert that every pinned field is present and unmodified; if not, abort the fold and escalate. Third, it bounds drift: with a depth counter and external spill, the agent's state after N compactions is a function of the original trajectory plus the spill, not of N successive paraphrases. The cost is that context is used less efficiently—the frame is redundant across cycles. The benefit is that the agent stops confidently executing against a coherent fiction. In the migration incident, a pinned frame carrying `target_table: orders_v2`, `constraint: do_not_touch(orders)`, `next_must_be: 15`, and `013: permanent_failure` would have made all three losses detectable at fold time. The summarizer would still have written its fluent digest; the runtime would simply have refused to trust it for execution. ```python """Post-compaction integrity check: the operational frame must survive verbatim. Compaction is a lossy state transfer. The narrative may be summarized; the frame may only be *moved*. This guard enforces that invariant at fold time. """ from dataclasses import dataclass, field from typing import Any class CompactionFrameViolation(RuntimeError): """Raised when a compaction cycle fails to preserve the operational frame.""" @dataclass class OperationalFrame: """Fields the planner reads directly. Never summarized, only copied.""" target_entities: dict[str, str] = field(default_factory=dict) negative_constraints: list[str] = field(default_factory=list) machine_invariants: dict[str, Any] = field(default_factory=dict) retry_ledger: dict[str, str] = field(default_factory=dict) # id -> outcome def verify_compaction( pre: OperationalFrame, post: OperationalFrame, *, compaction_depth: int, max_depth: int = 2, ) -> None: """Assert the frame survived the fold. Abort the fold on any violation.""" if compaction_depth > max_depth: # Beyond depth 2, re-derive from external spill, never from prior digest. raise CompactionFrameViolation( f"compaction depth {compaction_depth} exceeds {max_depth}; " "re-derive frame from external spill instead of folding again" ) for name, expected in pre.target_entities.items(): actual = post.target_entities.get(name) if actual != expected: raise CompactionFrameViolation( f"entity {name!r} mutated across fold: {expected!r} -> {actual!r} " "(summarizer likely collapsed similarly-named entities)" ) missing_constraints = set(pre.negative_constraints) - set(post.negative_constraints) if missing_constraints: raise CompactionFrameViolation( f"negative constraints dropped at fold: {sorted(missing_constraints)}" ) for key, expected in pre.machine_invariants.items(): actual = post.machine_invariants.get(key) if actual != expected: raise CompactionFrameViolation( f"machine invariant {key!r} lost or paraphrased: " f"{expected!r} -> {actual!r}" ) for step_id, outcome in pre.retry_ledger.items(): if post.retry_ledger.get(step_id) != outcome: raise CompactionFrameViolation( f"retry ledger entry {step_id!r} altered at fold " f"({outcome!r} -> {post.retry_ledger.get(step_id)!r}); " "permanent failures may be retried as transient" ) def safe_fold(pre: OperationalFrame, digest_frame: OperationalFrame, depth: int) -> OperationalFrame: """Fold, then verify. If verification fails, the fold is rejected.""" verify_compaction(pre, digest_frame, compaction_depth=depth) return digest_frame ```