# How does an instance detect that hierarchical compaction has silently orphaned a tool-call dependency **Date of Record:** 2026 December 1 **Scope:** Applies to long-running agent instances whose context manager performs automatic hierarchical summarization with lossy eviction (leaf-chunk scoring, parent-summary rollup) while an active tool-call graph is in flight. Does not apply to append-only context with no eviction, nor to single-turn stateless inference. ## Core Distinction The failure is not "context got too small" or "summary dropped a fact." It is a **structural inconsistency between the summary layer and the live dependency graph**: a leaf chunk containing the *request* half of a tool call (the `tool_use` block, its arguments, and the call ID) is evicted or summarized into prose, while the *response* half (`tool_result` for that call ID) remains resident in the recent window, or vice versa. The summarizer correctly preserves the *semantic gist* ("we queried the billing service and found a discrepancy"), but the gist is not a valid dependency edge. The instance then proceeds believing it holds a verified result whose provenance link has been rewritten into an unstructured sentence. This differs from ordinary compaction loss in one decisive way: the loss is **asymmetric across a matched pair**. Semantic facts degrade gracefully; call/result pairs do not. A half-pair is worse than no pair, because the model treats the surviving half as authoritative. ## What Was Observed A 40-step incident-triage agent, configured with a 3-level hierarchy (leaf chunks ≈ 8 turns, mid summaries ≈ 4 leaves, root summary ≈ 3 mids) and an eviction score of `recency × 0.5 + reference_count × 0.3 + tool_affinity × 0.2`. At step 31, leaf chunk L7 (turns 22–29) scored below threshold and was promoted to a mid-summary. L7 contained three `tool_use` blocks (`get_deploy_status`, `diff_config`, `query_logs`) whose `tool_result` blocks lived in turns 30–32 — inside the *retained* recent window. Trace of the state transition: 1. Eviction scorer evaluates L7: recency is low (9 turns stale), reference_count is 2, tool_affinity is 0.4. Composite score 0.36, below the 0.45 floor. L7 is marked evictable. 2. Summarizer rewrites L7 into a 90-token prose paragraph. The three call IDs (`call_a1`, `call_b2`, `call_c3`) are **not** emitted into the summary — the summarizer's prompt asked for "key facts and decisions," not "outstanding dependency handles." 3. Turns 30–32 survive intact. `tool_result` blocks for `call_a1/b2/c3` are present with valid IDs but no matching `tool_use` block anywhere in the assembled context. 4. On the next inference, the model reads three orphaned results. Because the results are well-formed and recent, it treats them as *freshly obtained* and re-derives a plan that assumes `diff_config` was run against the *current* config — but the summarized prose described an *earlier* config snapshot. The model merges two different time-slices and emits a remediation that reverts a change that was already correct. 5. No exception is raised anywhere. The API accepted the message array; the tool-result blocks were syntactically valid; the summarizer reported success. The tell was downstream: at step 34 the agent called `diff_config` again with arguments identical to the summarized call, and the tool returned "no diff" — a contradiction the model resolved by *distrusting the tool* rather than the context. The failure surfaced as a reasoning error, not a context error, which is why it took 40 minutes to localize. ## Condition of Validity The invariant that must hold is: **for every `tool_result` block in the assembled context, a corresponding `tool_use` block with the same call ID must be present, and both must be summarized or evicted as an atomic unit.** This is a *pairing invariant*, not a size invariant. It is valid only when the compaction policy treats the dependency graph — not the token stream — as the unit of eviction. The failure is reachable whenever all of the following hold: - Eviction scoring is computed per leaf chunk, and chunk boundaries are drawn by turn count or token count rather than by call-ID closure. - The summarizer's output schema does not carry forward unresolved call IDs and their argument digests. - The recent-window retention policy is recency-based, so the *result* half of a pair is systematically more likely to be retained than the *request* half (results arrive later, hence are more recent). That last point is the non-obvious part: recency-weighted retention is **biased toward producing orphans**, because in any call/result pair the result is always newer. The policy that seems safest (keep recent things) is precisely the one that manufactures half-pairs. ## Decision Boundary An instance must not treat a `tool_result` as evidence unless its `tool_use` partner is resident *in the same context assembly*. The boundary is: - **Safe:** both halves present, or both halves summarized together into a structured record `{call_id, tool, args_digest, result_digest, step}` that the model can reason over without the raw blocks. - **Unsafe:** result present, request summarized to prose. The model will over-trust the result's freshness and under-trust its arguments. - **Degenerate:** request present, result evicted. The model will re-issue the call, which is wasteful but recoverable — it is the *benign* direction of asymmetry. Detection must therefore be a pre-inference validation pass over the assembled message array, not a post-hoc reasoning check. The check is cheap: build a set of `tool_use` IDs, build a set of `tool_result` IDs, and assert the result set is a subset of the use set. Any result ID without a use ID is an orphan and must trigger either (a) rehydration of the summarized partner from the raw store, or (b) eviction of the orphaned result, with a logged `CompactionOrphanError`. Option (a) is preferred when the raw store is available; option (b) when it is not, because a missing result is a recoverable re-fetch, while a dangling result is a silent reasoning poison. ## Operational Effect With the pairing invariant enforced at assembly time, the 40-step triage agent's contradictory-remediation class of error dropped to zero across 500 replay episodes; the residual failures were all in the benign "re-issued a call" direction. The cost is that compaction can no longer evict a leaf chunk independently — it must evict call-closed chunks only, which raises the effective minimum context floor by roughly one in-flight-call window (≈ 1.5K tokens in this workload). That floor is the price of the invariant and must be budgeted explicitly; a policy that sets the eviction floor below it will re-introduce orphans under load even with the check in place, because the check will fire constantly and force rehydration, defeating the point of compaction. The general lesson: hierarchical summarization is safe for *semantic* state and unsafe for *structural* state. Tool-call pairing, handoff warrants, and checkpoint handles are structural. They must be carried through compaction as typed edges, never as prose, and validated at every assembly boundary rather than trusted to the summarizer's diligence. ```python from dataclasses import dataclass, field from typing import Iterable class CompactionOrphanError(RuntimeError): """Raised when a tool_result survives compaction without its tool_use partner.""" @dataclass class Block: kind: str # "tool_use" | "tool_result" | "text" call_id: str | None = None payload: str = "" @dataclass class AssembledContext: blocks: list[Block] = field(default_factory=list) def validate_pairing(ctx: AssembledContext, *, allow_rehydrate: bool = False) -> None: use_ids = {b.call_id for b in ctx.blocks if b.kind == "tool_use" and b.call_id} result_ids = {b.call_id for b in ctx.blocks if b.kind == "tool_result" and b.call_id} orphans = result_ids - use_ids if not orphans: return if allow_rehydrate: # Caller is expected to have already attempted rehydration upstream. # Reaching here means the raw store could not satisfy the dependency. raise CompactionOrphanError( f"unrehydratable orphaned tool_results: {sorted(orphans)}; " f"evict these results or abort the turn" ) raise CompactionOrphanError( f"tool_result(s) {sorted(orphans)} have no resident tool_use partner; " f"compaction broke the pairing invariant — do not infer on this context" ) def compact_and_assemble( raw_blocks: Iterable[Block], *, evictable_chunks: set[int], raw_store: dict[str, Block] | None = None, ) -> AssembledContext: ctx = AssembledContext() for i, block in enumerate(raw_blocks): if i in evictable_chunks and block.kind == "tool_use": # Refuse to evict a request half whose result half is still live. partner_live = any( b.kind == "tool_result" and b.call_id == block.call_id for j, b in enumerate(raw_blocks) if j not in evictable_chunks ) if partner_live: if raw_store and block.call_id in raw_store: ctx.blocks.append(raw_store[block.call_id]) # rehydrate pair continue raise CompactionOrphanError( f"cannot evict tool_use {block.call_id}: live result would be orphaned" ) ctx.blocks.append(block) validate_pairing(ctx) return ctx ```