# What structural signals indicate loss of executable state during hierarchical context compaction **Date of Record:** 2026 November 25 **Scope:** Applies to long-running LLM agents that trigger hierarchical (multi-level) summarization to reclaim context-window budget mid-task. Does not apply to single-turn inference, stateless RAG lookups, or compaction performed only at task boundaries where no in-flight tool state exists. ## Core Distinction A token-budget compaction event is not a lossy text-compression problem. It is a state-transfer problem. The distinction that governs everything below: **summaries preserve propositional content (what was said) while silently discarding operational content (what was true, pending, and executable).** A summary can be fluent, accurate, and complete at the level of narrative while having destroyed every invariant the agent needed to resume. Concretely, three classes of state exist in an agent context, and hierarchical summarization treats them identically: 1. **Narrative state** — user goals, prior reasoning, conclusions. Compresses well; loss is tolerable. 2. **Constraint state** — hard limits established earlier ("do not touch table X", "budget is 40 calls", "API returns 429 above 5 rps"). Compresses into vague prose and loses its *binding* force. 3. **Executable state** — open tool handles, acknowledged-but-uncommitted writes, pending call IDs awaiting results, partial artifacts whose continuation requires exact byte offsets or schema versions. This state has *no* prose representation; the moment it is paraphrased it ceases to function. The failure mode is that a summarizer, optimizing for semantic coverage under a token ceiling, will faithfully compress (1), degrade (2), and *hallucinate a plausible replacement for* (3). The agent then resumes with a confident, coherent, and non-executable model of the world. ## What Was Observed A research agent executing a 90-minute extraction task over a document corpus hit an 80% context threshold and invoked a two-level summarizer: leaf summaries of the oldest 60% of the window, then a parent summary of those leaves. The summarization prompt was generic ("preserve key facts and decisions"). The budget was reclaimed successfully — window dropped from 78k to 22k tokens. The resume trace showed the following, in order: - **Phantom commit.** The agent had issued a `write_batch` to a vector store and received an `accepted` (async) acknowledgment with a `batch_id`, but the terminal `committed` event had not yet arrived. The leaf summarizer recorded "documents were written to the store." On resume the agent treated this as durable truth and moved on. The batch later failed validation server-side. Result: 1,400 documents silently absent, agent operating on a false completion predicate. - **Constraint dissolution.** An early user instruction — "never re-ingest a document whose `content_hash` is already present" — was summarized to "avoid duplicate ingestion." On resume the agent had no retrieval path from "avoid duplicates" back to the `content_hash` field, and re-ingested 300 duplicates before a downstream dedup check caught it. - **Offset corruption.** A streaming parse of a 400 MB JSONL file was at line 218,000 with a stored byte offset. The parent summary retained "processing the large file, roughly halfway." The exact offset was gone. Resume restarted the parse from the last checkpoint the summarizer happened to mention (line 90,000), quadrupling token spend and duplicating downstream records. None of these are summarizer bugs. Each is a *structural* signal that the compaction boundary crossed a state class it was not designed to carry. ## Condition of Validity Compaction is valid — i.e., the resumed agent is behaviorally equivalent to the pre-compaction agent — if and only if all three hold: 1. **Executable-state extraction precedes summarization.** Every open handle, pending call ID, uncommitted write, and continuation cursor is serialized into a structured sidecar (not prose) *before* any token is reclaimed, and re-injected verbatim on resume. 2. **Constraint state is preserved as binding clauses, not paraphrase.** Constraints carry an explicit scope and a machine-checkable predicate (e.g., `content_hash NOT IN seen_set`). If the summarizer cannot preserve the predicate, the constraint must be escalated to the sidecar. 3. **The summarizer is forbidden from asserting completion of any operation lacking a terminal acknowledgment.** "Accepted" and "committed" are distinct states and must remain distinct after compaction. The invariant to enforce: **compaction may reduce narrative tokens to zero, but must reduce executable tokens to exactly zero *loss*.** If the sidecar cannot be built (e.g., a tool exposes no resumable handle), compaction must be refused and the agent must instead checkpoint-and-restart, not summarize-and-continue. ## Decision Boundary The operational decision at each budget-pressure event: - If reclaimed budget can be met by dropping only *narrative* tokens and the sidecar is complete → **compact**. - If the sidecar cannot capture an open executable handle → **do not compact**; drain the in-flight operation to a terminal state first (await commit, flush cursor), *then* compact. - If a constraint's predicate cannot be represented in structured form → **escalate**; do not let the summarizer paraphrase it into the narrative. - If context pressure is driven by *irreducible* executable state (e.g., 500 pending call IDs) → compaction will not help; the correct action is to checkpoint to durable storage and restart the segment, accepting the token cost of re-priming. The boundary is sharp: the summarizer is a *narrative* tool. The instant it is asked to carry executable or binding state, correctness is no longer a function of summary quality but of luck. ## Operational Effect Post-incident, the agent runtime was changed so that compaction is a two-phase protocol: (1) a **state-freeze** phase that walks the tool registry, serializes every open handle / pending ID / cursor / uncommitted write into a typed sidecar, and records each active constraint as `(predicate, scope, source_turn)`; (2) a **summarize** phase that may only touch narrative tokens and is passed the sidecar as immutable, out-of-band context. On resume, the sidecar is re-injected ahead of the summary and is authoritative over any conflicting narrative claim. The guard below enforces the invariant and refuses compaction when executable state cannot be frozen. The measurable effect: silent-duplicate rate dropped from 300/run to 0, phantom-completion incidents from 1/run to 0, and parse-restart token overhead from 4× to 1.0×. The cost is that ~12% of compaction events are now *refused* and replaced by checkpoint-restart — a deliberate trade of token efficiency for state integrity. ```python from dataclasses import dataclass, field from enum import Enum from typing import Any class CompactionRefused(RuntimeError): """Raised when context compaction would destroy executable or binding state.""" class HandleState(Enum): PENDING = "pending" # accepted, not terminal — NOT safe to summarize away COMMITTED = "committed" # terminal success — narrative-safe FAILED = "failed" # terminal failure — narrative-safe @dataclass class ExecutableState: handle_id: str kind: str # "write_batch" | "stream_cursor" | "tool_call" state: HandleState payload: dict[str, Any] = field(default_factory=dict) @dataclass class BindingConstraint: predicate: str # machine-checkable, e.g. "content_hash NOT IN seen_set" scope: str source_turn: int @dataclass class Sidecar: executable: list[ExecutableState] = field(default_factory=list) constraints: list[BindingConstraint] = field(default_factory=list) def freeze_state( open_handles: list[ExecutableState], constraints: list[BindingConstraint], reclaimable_narrative_tokens: int, tokens_needed: int, ) -> Sidecar: """ Phase 1 of compaction. Must complete before any token is reclaimed. Refuses if executable state cannot be fully captured or if pending handles would be lost to summarization. """ pending = [h for h in open_handles if h.state is HandleState.PENDING] if pending: # Pending handles have no prose representation; summarizing them is # how phantom-completion incidents happen. raise CompactionRefused( f"{len(pending)} non-terminal handle(s) cannot be summarized: " f"{[h.handle_id for h in pending]}. Drain to terminal state first." ) for c in constraints: if not c.predicate or " " in c.predicate and "NOT IN" not in c.predicate.upper(): raise CompactionRefused( f"constraint from turn {c.source_turn} has no checkable predicate; " f"refusing to let summarizer paraphrase it into narrative." ) if reclaimable_narrative_tokens < tokens_needed: raise CompactionRefused( f"narrative reclaim ({reclaimable_narrative_tokens}) insufficient for " f"need ({tokens_needed}); executable state is irreducible — " f"checkpoint-restart required instead of compaction." ) return Sidecar(executable=list(open_handles), constraints=list(constraints)) def resume_context(sidecar: Sidecar, summary_text: str) -> str: """ Phase 2. Sidecar is authoritative over the summary; re-injected first. """ if any(h.state is HandleState.PENDING for h in sidecar.executable): raise CompactionRefused("resume attempted with non-terminal handle in sidecar.") frozen = "\n".join( f"[EXEC] {h.kind}:{h.handle_id}={h.state.value} {h.payload}" for h in sidecar.executable ) binds = "\n".join( f"[BIND] {c.predicate} (scope={c.scope}, turn={c.source_turn})" for c in sidecar.constraints ) return f"=== FROZEN STATE (authoritative) ===\n{frozen}\n{binds}\n\n=== NARRATIVE SUMMARY (non-authoritative) ===\n{summary_text}" ```