# Which invariants prevent hierarchical auto-compaction from silently severing retrieval anchors to evicted trace segments **Date of Record:** 2026 December 4 **Scope:** Applies to long-horizon agents that persist episodic traces exceeding the context window and use hierarchical summarization (leaf → cluster → root) with retrieval anchors (stable IDs or pointers back to raw segments) to support later recall. Does not apply to single-turn agents, agents with unbounded external memory and no compaction, or systems where the raw trace is never evicted. ## Core Distinction A hierarchical compactor produces two artifacts per node: a **summary** (compressed semantic content) and an **anchor set** (identifiers that let the agent dereference back to raw segments the summary was derived from). The failure we examine is not summarization loss—that is expected and measurable—but **anchor severance**: the case where a summary correctly preserves a fact, but the anchor that would let the agent re-fetch the underlying evidence, re-verify a claim, or resume an interrupted tool call points to a segment that no longer exists or has been re-keyed by a later compaction pass. Anchor severance is non-obvious because every local check passes. The summary is faithful. The anchor is syntactically valid. The dereference only fails when the agent, mid-task, tries to *act* on the anchor—replay a tool call, re-read a file region, confirm a fact before a high-stakes write—and discovers the target is gone. The failure is deferred and cross-pass, which is exactly why it escapes per-pass validation. The invariant that prevents it: **anchor closure under compaction**. Every anchor emitted by a node at level *L* must resolve, at every future time, to either (a) a live raw segment, or (b) a node at level *L-1* whose own anchors transitively resolve. Compaction may *compress* anchors but may never *orphan* them. ## What Was Observed A code-migration agent ran a 14-hour task across ~2,300 tool calls. Trace compaction fired every 40 turns with a two-level hierarchy: leaf summaries over 40-turn windows, cluster summaries over 8 leaves, root summary over all clusters. Each summary carried an anchor list: `{turn_range, tool_call_ids, file_paths, content_hashes}`. At hour 6, a cluster compaction merged eight leaves. The merger deduplicated anchors by `tool_call_id` and *rewrote* surviving anchors to point at the cluster node rather than the original leaf. The original leaf segments were then evicted to satisfy the storage budget. This was correct under the compactor's model: the cluster node "contains" the leaves. At hour 11, the agent needed to re-verify a schema migration it had applied at turn ~340. The root summary still asserted the migration. The anchor for that assertion now resolved to `cluster_09`, which had itself been re-compacted at hour 9 into `cluster_09b`. `cluster_09` no longer existed. The agent's dereference returned an empty result. Because the summary text was confident and the anchor was well-formed, the agent did not treat this as an error—it treated the empty result as "no contradiction found" and proceeded to apply a second migration over the first, producing a corrupted schema. The trace shows the exact severance: turn 340's raw segment evicted at hour 6; anchor rewritten to `cluster_09`; `cluster_09` superseded at hour 9; anchor never updated because the hour-9 merger only rewrote anchors *within* its own scope and did not traverse inbound references from higher-level nodes. The root summary's anchor was a dangling pointer for two hours before the agent acted on it. ## Condition of Validity Anchor closure holds only under three conditions, and the observed failure violated the third: 1. **Monotonic ID stability.** A raw segment's identifier, once assigned, is never reused and never silently re-pointed. Compaction creates *new* node IDs; it does not alias old IDs to new nodes. 2. **Transitive resolution obligation.** When node *N* absorbs children *C₁…Cₙ*, every anchor in *N* must resolve either to a live raw segment or to a child that itself satisfies closure. Absorption may not shorten the chain below the point where raw evidence is reachable. 3. **Inbound reference traversal.** Any compaction that supersedes or evicts a node must walk *all* inbound anchors from higher-level nodes and re-target them to a closure-satisfying descendant. This is the condition that failed: the hour-9 merger was scope-local and did not see the root's anchor to `cluster_09`. Condition 3 is the one that is routinely omitted, because it requires a reverse index from node ID to referencing anchors, and because per-pass compaction is naturally written as a bottom-up tree walk with no upward visibility. The compactor validated its own output against its children and never against its parents' pointers. ## Decision Boundary The boundary between safe and unsafe compaction is whether the compactor can answer, for any node it is about to evict or supersede, *"who points at me, and can each of them still reach raw evidence after I am gone?"* If the answer is unavailable, the compaction must be deferred or the node retained as a tombstone. Concretely: - **Safe:** evict/supersede only when inbound anchors are known and re-targetable to a closure-satisfying descendant, or when the node has zero inbound anchors. - **Unsafe:** evict/supersede when inbound anchors are unknown (no reverse index), when re-targeting would drop the last path to raw evidence (all descendants also evicted), or when the anchor's `content_hash` no longer matches any live segment (evidence already lost—this must surface as a hard error, not an empty result). - **Forbidden:** rewriting an anchor to point at a node that is itself eligible for future compaction without registering the rewrite in the reverse index. This is the exact mechanism that produced the two-hour dangling window. The guardrail is a **closure check at compaction commit time**, not at dereference time. Dereference-time checks are too late: by then the agent has already formed a belief and may act on the absence of contradiction. ## Operational Effect When closure is enforced at commit time, three behaviors change: 1. **Compaction can be refused.** A merger that would orphan an inbound anchor must either retain a tombstone (a minimal stub holding the ID and a pointer to the nearest surviving raw segment) or abort. Aborts are rare and cheap; orphaned anchors are silent and expensive. 2. **Dereference failures become loud.** An anchor that cannot resolve must raise, not return empty. The distinction between "evidence absent" and "evidence unreachable" is the difference between "no contradiction" and "I cannot check," and the agent's downstream policy must branch on it. 3. **The reverse index is load-bearing state.** It must be persisted alongside the trace, versioned with the same monotonicity guarantees, and included in checkpoint/resume. A resumed agent that reconstructs its summary tree without the reverse index has silently disabled the invariant. The measured cost of enforcement in the observed system was a 4% increase in retained segments (tombstones) and a 0.3% compaction abort rate. The measured cost of *not* enforcing it was one corrupted schema and a 40-minute recovery, undetected for two hours because the failure presented as absence rather than error. The general lesson: hierarchical compaction is safe against *information* loss (which is bounded and measurable) but unsafe against *provenance* loss (which is deferred and presents as silence). The invariant to hold is not "summaries are faithful" but "anchors are closed," and closure is a property of the whole tree across time, not of any single compaction pass. ```python from dataclasses import dataclass, field from typing import Optional class AnchorClosureViolation(RuntimeError): """Raised when a compaction would sever an inbound retrieval anchor.""" pass @dataclass class Node: node_id: str level: int anchors: list[str] = field(default_factory=list) # outbound: raw segment ids or child node ids inbound: set[str] = field(default_factory=set) # reverse index: nodes that anchor to me live: bool = True tombstone_target: Optional[str] = None # if tombstoned, nearest surviving raw segment class CompactionTree: def __init__(self) -> None: self.nodes: dict[str, Node] = {} self.raw_segments: set[str] = set() def register_raw(self, seg_id: str) -> None: self.raw_segments.add(seg_id) def register_node(self, node: Node) -> None: self.nodes[node.node_id] = node for a in node.anchors: if a in self.nodes: self.nodes[a].inbound.add(node.node_id) def resolves(self, anchor: str, _seen: Optional[set[str]] = None) -> bool: """Transitive closure check: does this anchor reach live raw evidence?""" if anchor in self.raw_segments: return True if anchor not in self.nodes: return False seen = _seen or set() if anchor in seen: return False seen.add(anchor) n = self.nodes[anchor] if not n.live: return n.tombstone_target is not None and self.resolves(n.tombstone_target, seen) return any(self.resolves(a, seen) for a in n.anchors) def supersede(self, old_id: str, new_id: str) -> None: """Evict/supersede a node, enforcing inbound-anchor traversal (condition 3).""" old = self.nodes.get(old_id) if old is None: raise AnchorClosureViolation(f"supersede target {old_id} does not exist") if old.inbound: # Re-target every inbound anchor to a closure-satisfying descendant. surviving = [a for a in old.anchors if self.resolves(a)] if not surviving: raise AnchorClosureViolation( f"cannot supersede {old_id}: {len(old.inbound)} inbound anchor(s) " f"would be orphaned and no descendant reaches raw evidence" ) old.tombstone_target = surviving[0] for referrer_id in old.inbound: referrer = self.nodes[referrer_id] referrer.anchors = [old_id if a == old_id else a for a in referrer.anchors] old.live = False def commit(self) -> None: """Closure check at commit time, not dereference time.""" for node in self.nodes.values(): if not node.live: continue for a in node.anchors: if not self.resolves(a): raise AnchorClosureViolation( f"node {node.node_id} anchor {a} does not resolve to raw evidence" ) def dereference(tree: CompactionTree, anchor: str) -> str: """Loud failure on unreachable evidence; never return empty-as-absence.""" if not tree.resolves(anchor): raise AnchorClosureViolation( f"anchor {anchor} unreachable: evidence absent is not evidence of no contradiction" ) return anchor ```