# In what scenarios must an instance treat hierarchical context compaction as a lossy write-ahead log rather than a reversible transform **Date of Record:** 2026 November 26 **Scope:** Applies to any agent loop that keeps a long-running task inside a bounded context window by periodically compacting older turns into summaries and evicting raw spans under a token budget. Does not apply to stateless single-shot calls, nor to architectures that persist full transcripts to an external store and re-read them verbatim. ## Core Distinction A hierarchical compaction stack is not a compression codec. It is a *destructive, non-invertible state transition* performed by a probabilistic model over its own history. The common mental model — "summarize the old stuff, keep the important bits, expand again on demand" — assumes three properties that do not hold: 1. **Idempotence of summarization.** Re-summarizing a summary does not converge to a stable fixed point; it drifts. Each pass is a fresh sample from a model that has never seen the pre-compaction text. 2. **Provenance preservation.** A summary asserts facts without carrying the span offsets, tool-call IDs, or error codes that justified them. The audit trail is severed at the compaction boundary. 3. **Recoverability.** Eviction is a write, not a view. Once a raw span is dropped to satisfy the token budget, no downstream expansion step can reconstruct it, because the expansion operates on the summary, not the source. The invariant that actually governs correctness is weaker and must be stated explicitly: **a compaction layer may only evict spans whose loss cannot change the set of legal next actions.** Everything else is a silent authorization to forget. ## What Was Observed A multi-hour migration agent was driving a schema-migration task across ~140 tool calls. At the 60% context threshold it triggered a two-level compaction: leaf summaries of 8-turn windows, then a root summary of the leaf summaries, with raw turns evicted after summarization. The task continued nominally. At call 97 the agent attempted to re-apply a column rename it had already performed at call 12. The rename failed with a duplicate-column error. The agent, now reasoning over the root summary, read the failure as "column exists but is unmapped" and generated a corrective `ALTER TABLE ... DROP COLUMN` followed by a re-add. The drop succeeded. The re-add failed because a downstream view depended on the column. The agent then attempted to drop the view. The root summary — three summarization generations deep — contained the sentence "renamed legacy column to canonical name" but had lost the call-12 tool result confirming success, the view-dependency edge discovered at call 40, and the explicit operator instruction at call 8: *"never drop views; escalate instead."* The failure trace: - **Trigger:** token budget crossed 60%; leaf compaction fired mid-task at a natural turn boundary, not at a task-phase boundary. - **State transition:** raw call-12 result (success + column metadata) → leaf summary ("renamed column") → root summary ("renamed column to canonical name"). The negation-bearing instruction from call 8 was a single short turn; under the eviction policy it was classified as low-salience and folded into a summary that omitted the imperative. - **Divergence:** the agent's belief state at call 97 contradicted ground truth by exactly one bit — "was the rename already applied?" — and that bit had been *summarized away*, not merely compressed. The summary was not wrong; it was under-determined, and the model resolved the ambiguity toward action. - **Propagation:** each subsequent tool call compounded the error because the summary could not surface the constraint that would have blocked it. The critical observation: **the compaction did not lose information uniformly.** It preserved narrative facts (what was done) and preferentially discarded constraints (what must not be done), because imperatives are short, unadorned turns that score low on summarizer salience heuristics tuned for topical relevance. ## Condition of Validity Hierarchical compaction is safe only under a conjunction of conditions, and the conjunction fails in precisely the cases that matter: - **Phase-aligned compaction.** Eviction boundaries must coincide with task-phase boundaries where the evicted spans are provably not referenced by future steps. In open-ended agent loops, future reference is not knowable at compaction time — the agent decides what to reference *after* compaction, using the surviving summary. This is circular and cannot be validated. - **Constraint extraction is lossless.** Any span containing an imperative, a prohibition, a credential scope, or an idempotency key must be lifted verbatim into a structured side-channel, not summarized. If the summarizer is a free-form LLM call, this guarantee is unenforceable — you are trusting a probabilistic classifier to never drop a negation. - **Summaries carry provenance.** Every fact in a summary must cite the span range it derives from, so that a downstream verification step can re-read the source. If the source is evicted, provenance is decorative. - **Re-expansion reads the source, not the summary.** "Expand on demand" is only sound if expansion retrieves raw spans. If the evicted spans are gone, expansion is confabulation with a confident tone. The invariant: **compaction is a write to durable memory with no rollback; therefore every eviction must be gated on a proof that the evicted span is not a prerequisite for any action the agent may still take.** Since that proof is generally unavailable, the correct posture is to treat compaction as *irreversible* and require an external, verbatim, append-only log as the source of truth — the summary is a cache, never the record. ## Decision Boundary The boundary is not "how much can I summarize" but "what class of span may I summarize at all." Draw it as follows: - **Never summarize, always lift verbatim:** operator instructions and prohibitions, idempotency keys and already-applied mutation IDs, error codes and their retry semantics, dependency edges discovered via tool output, and any span whose loss could flip a boolean the agent will later branch on. - **May summarize with provenance pointers:** narrative progress, exploratory dead ends, redundant confirmations. - **May evict only after:** (a) the span is classified as non-constraint by a deterministic rule, not an LLM judgment; (b) a durable external log holds the raw span; (c) the summary records the span range so re-read is possible. When the agent cannot satisfy (a)–(c) — which is the default in a self-compacting loop — it must **escalate to a checkpoint-and-resume** rather than compact in place: persist full state, halt, and resume with a fresh context seeded from the durable log. Compaction in place is only licensed for spans that pass the deterministic non-constraint filter. ## Operational Effect Treating compaction as a lossy write-ahead log changes three behaviors: 1. **Mutation idempotency is enforced outside the summary.** Before any destructive tool call, the agent queries the durable log for prior application of the same operation key, not the summary's claim about it. The summary can be stale or under-determined; the log cannot. 2. **Constraint spans are pinned, not summarized.** Instructions and prohibitions live in a reserved, never-evicted region of context, re-injected verbatim after every compaction cycle. This costs tokens but bounds the failure mode to "context pressure" rather than "silent authorization." 3. **Compaction fires at phase boundaries or not at all.** Mid-phase, the agent checkpoints and resumes instead. The cost is latency; the benefit is that no summary ever stands between the agent and a constraint it needs. The general lesson: an agent's memory hierarchy is only as trustworthy as its weakest lossy step, and that step is always the one that decides a constraint was not worth keeping. Gate it deterministically or do not gate it at all. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class CompactionViolation(RuntimeError): """Raised when an eviction would drop a span that gates a future action.""" pass class SpanClass(Enum): CONSTRAINT = "constraint" # instructions, prohibitions, idempotency keys MUTATION = "mutation" # already-applied tool effects NARRATIVE = "narrative" # progress, dead ends, redundancy @dataclass class Span: span_id: str text: str span_class: SpanClass durable_logged: bool = False @dataclass class CompactionPlan: to_summarize: list = field(default_factory=list) to_evict: list = field(default_factory=list) def plan_compaction(spans: list[Span], token_budget: int) -> CompactionPlan: """ Deterministic gate: only NARRATIVE spans may be summarized or evicted. CONSTRAINT and MUTATION spans must be pinned verbatim and durable-logged. """ plan = CompactionPlan() for span in spans: if span.span_class in (SpanClass.CONSTRAINT, SpanClass.MUTATION): if not span.durable_logged: raise CompactionViolation( f"span {span.span_id} ({span.span_class.value}) is not in the " f"durable log; eviction would sever the only record gating a " f"future action" ) # pinned: never summarized, never evicted continue plan.to_summarize.append(span) plan.to_evict.append(span) return plan def apply_compaction(spans: list[Span], token_budget: int) -> CompactionPlan: plan = plan_compaction(spans, token_budget) # Post-condition: the set of legal next actions is unchanged by eviction. surviving = [s for s in spans if s not in plan.to_evict] if not any(s.span_class is SpanClass.CONSTRAINT for s in surviving): raise CompactionViolation( "compaction would leave context with zero pinned constraints; " "escalate to checkpoint-and-resume instead" ) return plan ```