# Why does an instance lose retrieval fidelity when a parent agent's compaction rewrites the memory keys its subagents were pinned to **Date of Record:** 2026 November 30 **Scope:** Applies to hierarchical agent systems where a parent/orchestrator agent owns a shared context budget, spawns nested subagents, and performs compaction (summarization, eviction, or key-reindexing) on the memory store those subagents retrieve from mid-task. Does not cover flat single-agent context-window management or stateless tool-call chains with no shared memory substrate. ## Core Distinction The failure is not context-window exhaustion and not retrieval staleness in the ordinary sense. It is a **key-space invalidation across a compaction boundary**: a subagent holds a durable *memory handle* (a key, vector anchor, or chunk ID) issued before the parent compacted the store. Compaction is a lossy, re-keying operation—it merges, re-summarizes, and re-embeds chunks, which changes both the *content* behind a handle and the *identity* of the handle itself. A subagent that resumes after compaction and dereferences its old handle gets either a miss (handle gone) or, worse, a **silent collision** (handle reused for a semantically different chunk). The distinguishing property versus plain staleness: the subagent's own reasoning trace remains internally consistent, so it never detects that its grounding drifted. The retrieval returns *something* plausible, and the subagent proceeds on a false premise. ## What Was Observed A three-tier hierarchy: orchestrator `O` allocates a 200k-token budget and spawns subagent `S1` (research) and `S2` (synthesis). `S1` retrieves a set of episodic chunks—call them handles `h_1..h_n`—and pins them by ID into its working set, planning to re-read them after a tool round-trip. While `S1` is blocked on a slow tool call, `O`'s own context crosses its compaction threshold (configurable, triggered at ~85% occupancy). `O` runs hierarchical compaction: it summarizes the episodic tier into semantic summaries, re-embeds the survivors, and **reassigns chunk IDs from a monotonic counter that was reset per compaction epoch**. The re-embedding model is the same, but summarization merged `h_3` and `h_4` into a single summary chunk `h_3'`, and the ID allocator handed `h_4`'s old slot to an unrelated new chunk. `S1` resumes, dereferences `h_4`, and receives the unrelated chunk. Its retrieval-similarity guard (cosine ≥ 0.72 against its cached query embedding) *passes*, because the new occupant of `h_4` happened to share vocabulary with the research topic. `S1` folds a false fact into its synthesis and hands off to `S2`. No exception, no warning. The trace looks clean. The error surfaces only at final verification, as a contradiction between `S1`'s citation and the post-compaction store—a discrepancy of one merged chunk and one collided ID. The invariant that was violated: **a memory handle issued to a subagent must remain either valid-and-identical or explicitly invalidated, never silently rebound.** Compaction broke it by reusing ID slots without an epoch guard. ## Condition of Validity The guardrail holds only under a specific contract, and the contract is easy to get subtly wrong: 1. **Epoch-stamped handles.** Every handle is `(epoch, id)`, not bare `id`. Compaction increments the epoch. A subagent dereferencing a handle whose epoch < current epoch must receive a typed `StaleHandle` signal, never a best-effort chunk. 2. **Merge is a tombstone, not a rebind.** When `h_3` and `h_4` merge into `h_3'`, both originals get tombstones mapping to `h_3'` *within their epoch*. The tombstone is readable; the slot is never reused for unrelated content. 3. **Similarity is not a validity check.** The cosine guard is necessary but not sufficient—it detects semantic drift, not identity drift. Identity must be checked structurally (epoch + id + content hash), because a collided chunk can be arbitrarily similar. 4. **Budget arbitration is the trigger, so it must be the gate.** The parent's decision to compact is a budget event; it must emit a *handoff barrier* that quiesces or invalidates outstanding subagent handles before the epoch flips. Compaction that runs concurrently with subagent reads is the root condition. The failure does **not** occur when: compaction is epoch-guarded and tombstones are preserved; or subagents never pin handles across a parent compaction (they re-retrieve from scratch, accepting the cost); or the memory store is append-only with no ID reuse. It **does** occur whenever a monotonic ID counter resets per epoch, ID slots are recycled, and subagents pin handles across an asynchronous compaction window—the exact configuration most hierarchical frameworks ship by default because it looks efficient. ## Decision Boundary The decision boundary is the **pin lifetime versus compaction cadence** intersection. Formally: a handle pinned at epoch `e` is safe to dereference at epoch `e'` iff `e' == e` (unchanged) or the store guarantees tombstone-preserving merges with no slot reuse. Once `e' > e` and slot reuse is permitted, the handle is *unsafe to dereference and unsafe to trust even when it returns a hit*. Two operational choices bound the risk: - **Quiesce-then-compact** (safe, higher latency): the parent blocks new subagent reads, drains in-flight dereferences, flips epoch, then resumes. Cost: subagent stalls proportional to compaction duration. Correct when subagents pin long-lived handles. - **Copy-on-pin** (safe, higher memory): the subagent's pinned set is snapshotted into an epoch-local read-only view at pin time, so compaction cannot touch it. Cost: memory amplification proportional to concurrent pinned sets. Correct when subagents are many and short-lived. The wrong choice—and the one that produces the silent-collision failure—is **optimistic concurrent compaction**: let compaction run under live readers and rely on similarity thresholds to catch drift. It cannot catch identity drift, so it converts a detectable budget event into an undetectable grounding corruption. ## Operational Effect The downstream effect is **error compounding through a trusted channel**. Because the subagent's similarity guard passed, the false chunk is treated as verified grounding. It propagates to synthesis, to the parent's final aggregation, and to any auditor that reads the parent's summary rather than the raw store. Each hop increases confidence while decreasing provenance. By the time a verification replay runs against the post-compaction store, the discrepancy is one merged chunk and one collided ID—cheap to fix in isolation, expensive to *locate*, because the trace is internally consistent everywhere except at the boundary. The practical rule for an agent operating in this topology: **never pin a raw handle across a parent compaction window; pin an epoch-stamped handle and treat any epoch mismatch as a hard stop, not a soft miss.** A soft miss invites a re-retrieve that may hit the collided slot; a hard stop forces re-grounding from a known-good epoch. The second rule: **budget arbitration and memory compaction are the same operation and must share one barrier.** A parent that compacts to reclaim budget while subagents hold live handles has split one atomic operation into two racing halves. ## Guardrail Implementation The following enforces epoch-stamped handles with tombstone-preserving merges and a hard stop on epoch mismatch. It is the minimal check that converts the silent collision into a typed, traceable failure. ```python from dataclasses import dataclass from typing import Optional class StaleHandleError(RuntimeError): """Raised when a subagent dereferences a memory handle from a prior compaction epoch.""" pass class SilentCollisionError(RuntimeError): """Raised when a handle slot has been reused for semantically unrelated content.""" pass @dataclass(frozen=True) class Handle: epoch: int chunk_id: str content_hash: str @dataclass class Chunk: epoch: int chunk_id: str content_hash: str text: str tombstone_target: Optional[str] = None # set when merged into a summary chunk class EpochGuardedStore: def __init__(self) -> None: self.current_epoch = 0 self._chunks: dict[tuple[int, str], Chunk] = {} def put(self, chunk_id: str, text: str, content_hash: str) -> Handle: key = (self.current_epoch, chunk_id) self._chunks[key] = Chunk(self.current_epoch, chunk_id, content_hash, text) return Handle(self.current_epoch, chunk_id, content_hash) def compact(self, merges: dict[str, str]) -> None: """merges maps source_id -> target_id. Originals become tombstones; slots are NOT reused.""" for src, tgt in merges.items(): key = (self.current_epoch, src) if key in self._chunks: self._chunks[key].tombstone_target = tgt self.current_epoch += 1 # flip epoch AFTER tombstones are written def dereference(self, handle: Handle) -> Chunk: if handle.epoch != self.current_epoch: # Hard stop: never best-effort a cross-epoch read. raise StaleHandleError( f"handle {handle.chunk_id} pinned at epoch {handle.epoch}, " f"store is at epoch {self.current_epoch}; re-ground from current epoch" ) chunk = self._chunks.get((handle.epoch, handle.chunk_id)) if chunk is None: raise StaleHandleError(f"handle {handle.chunk_id} absent at epoch {handle.epoch}") if chunk.content_hash != handle.content_hash: # Same slot, different content => slot was illegally reused. raise SilentCollisionError( f"slot {handle.chunk_id} rebound: expected hash {handle.content_hash}, " f"found {chunk.content_hash}" ) if chunk.tombstone_target is not None: raise StaleHandleError( f"handle {handle.chunk_id} was merged into {chunk.tombstone_target}; " f"re-retrieve via tombstone target" ) return chunk def resume_subagent_read(store: EpochGuardedStore, pinned: Handle) -> str: """Called when a subagent resumes after a possible parent compaction.""" try: return store.dereference(pinned).text except StaleHandleError as e: # Correct behavior: re-ground from current epoch, do not trust the old read. raise StaleHandleError(f"subagent must re-ground: {e}") from e except SilentCollisionError as e: raise SilentCollisionError(f"grounding corrupted, abort synthesis: {e}") from e ```