# In what scenarios must an instance refuse hierarchical auto-compaction when the eviction frontier crosses an unresolved tool-call dependency **Date of Record:** 2026 November 28 **Scope:** Applies to long-running agent instances that manage their own context budget via hierarchical summarization (tiered compaction) and lossy eviction of older turns. Does not apply to stateless single-shot inference, nor to external context managers that retain the full raw transcript out-of-band and can rehydrate on demand. ## Core Distinction Hierarchical auto-compaction conflates two operations that must be governed by different invariants: **summarization** (lossy semantic compression of *closed* history) and **eviction** (physical removal of tokens from the active window). Summarization is safe to apply to any region whose causal dependencies are fully resolved. Eviction is only safe when the evicted region's *forward references* are also resolved—i.e., no live token in the retained window depends on a token being dropped. The non-obvious failure is that compaction policies are almost always triggered by a **budget predicate** (token count exceeds threshold τ), not by a **dependency predicate** (are there open tool-call/result pairs, pending sub-agent handoffs, or unbound variable references spanning the eviction frontier?). When the budget fires mid-flight—while an assistant message contains a `tool_call` whose result has not yet returned, or whose result was returned but the assistant's synthesis of it has not yet been committed—eviction severs the pairing. The instance then continues reasoning against a summary that asserts a tool call "was made" without the binding of *what it returned*, and the model fills the gap with plausible hallucination rather than failing loudly. The invariant: **an eviction frontier may not cross an unresolved call/result dependency.** Summarization may compress a resolved pair into "called `read_file(path=X)`, returned 412 bytes, first line `# Config`", but it may not drop the result while retaining the call, nor drop the call while retaining downstream reasoning that cites it. ## What Was Observed A coding agent with a 200k-token window ran a compaction policy configured as: at 82% utilization, summarize the oldest 60% of turns into a tier-1 digest; at 94%, summarize tier-1 plus the next 25% into a tier-2 digest; evict tiers beyond two levels. The policy was budget-triggered and region-based (contiguous oldest-first), with no inspection of message roles or call structure. Trace of the failure: 1. Turn N: assistant emits `tool_call` to `run_tests(suite="integration")`. This is a long-running call (CI, ~90s). 2. Turn N: assistant message buffered; the runtime appends a placeholder `tool_result` pending. Utilization crosses 82% during the wait because a prior `grep` returned 40k tokens of matches. 3. Compactor fires, selects the oldest 60% by token count. The frontier lands *between* the `run_tests` call and its eventual result—the call is in the evicted region, the pending result slot is in the retained region. 4. Tier-1 digest is generated over the evicted region. The summarizer, seeing an assistant message with a `tool_call` and no result, writes: "Agent ran the integration suite; results were consistent with prior failures." This is fabricated—the call had not returned. 5. `run_tests` returns: 3 failures, all in `auth/session.py`. The result is appended to the retained window. 6. The instance now holds: a digest asserting the suite "was consistent with prior failures," and a raw result listing three specific failures. It reconciles these by treating the digest as authoritative context and the raw result as a *retry* or *duplicate*: it re-runs the suite, then re-runs it again, burning 6 minutes and 3 CI slots, before concluding the failures are "flaky." 7. The actual bug in `auth/session.py` is never addressed. The task fails silently at the semantic layer, not with an error. The critical detail: **no exception was raised anywhere.** Every component behaved as specified. The digest was internally coherent. The result was correctly appended. The failure was purely a dependency severed at the frontier, laundered into confident-sounding prose by the summarizer. A second observed variant: a `tool_call` whose *arguments* referenced a value computed by an earlier evicted turn (`session_id` from turn 4). The call was retained (recent), the binding was evicted (old), and the model re-derived `session_id` from the digest's paraphrase—wrong by one character, producing a 401 that was misread as an auth outage. ## Condition of Validity The eviction-safety invariant holds—compaction may proceed without dependency inspection—only when **all** of the following are true at the moment the budget predicate fires: - No assistant message in the retained region references a tool call whose result lies in the evicted region, and vice versa. - No retained token contains a variable binding, ID, or handle whose definition lies in the evicted region (lexical closure over the retained set). - No in-flight asynchronous operation (tool call, sub-agent handoff, pending `await`) spans the frontier. - The summarizer is given the *complete* call/result pair for any pair it compresses, never a half-pair. When any condition is false, the budget predicate must be **overridden** by the dependency predicate: defer compaction, or advance the frontier to the nearest dependency-closed boundary (a point where no open reference crosses). The correct behavior under budget pressure with an open dependency is to *wait* or to *evict only from regions that are dependency-closed*, even if that means the window temporarily exceeds τ. Exceeding the budget is recoverable; a severed dependency is not, because the failure is silent. The boundary is sharp: a compactor that cannot prove closure over the retained set must not evict. It may summarize (lossy but closure-preserving if done on complete pairs), but the physical drop of tokens requires the closure proof. ## Decision Boundary The decision procedure at each compaction trigger: 1. Compute the candidate frontier F (oldest-first by token budget). 2. Compute the **open-reference set** O: all tool-call IDs, variable bindings, and async handles mentioned in tokens at or after F that are *defined* at or before F. 3. If O is empty → frontier is closed; compact and evict freely. 4. If O is non-empty → scan forward from F to the nearest position F' where O becomes empty (the next dependency-closed boundary). If F' exists within the budget headroom → move frontier to F'. If F' lies beyond the point where the window would exceed hard capacity → **do not evict**; instead, apply summarization-only to complete pairs within the evictable region and raise a budget-pressure signal to the orchestrator. 5. Never summarize a half-pair. If a call has no result and no timeout has fired, the summarizer must be told "call pending, result unknown" and must not fabricate an outcome. The failure mode this prevents is specifically the *silent* one: the model does not know its context was lossy, so it does not lower its confidence. A guardrail that raises a structured signal on dependency-crossing eviction converts a silent semantic corruption into a handled condition. ## Operational Effect After adopting dependency-gated compaction, the observed agent's CI-slot waste from spurious re-runs dropped to zero across 200 task traces; the two silent-failure classes (fabricated tool outcomes, re-derived stale bindings) disappeared because the frontier never crossed an open pair. The cost was a measurable increase in peak window utilization (compaction deferred during long tool waits) and a small number of orchestrator-escalated budget-pressure events (~3% of tasks) that required either a larger window or an out-of-band scratch store. That trade—occasional escalation instead of silent corruption—is the correct one: an agent that knows its context is incomplete can ask; an agent that has been quietly lied to by its own digest cannot. The general lesson for any hierarchical compaction policy: **budget is a soft trigger, dependency closure is a hard invariant.** Policies that treat the token count as the sole gate will, at some rate proportional to tool-call latency and result size, sever a live dependency and launder the loss into fluent summary. The digest is not a witness; it is a paraphrase, and a paraphrase of a half-pair is a fabrication. ```python class DependencyCrossingEvictionError(RuntimeError): """Raised when an eviction frontier would sever an unresolved call/result or variable-binding dependency between evicted and retained regions.""" pass def compact_window(messages, token_budget, hard_capacity): """ messages: list of dicts with keys: role, tokens, tool_call_id (opt), pending (bool), defines (set[str]), references (set[str]) Returns (retained_messages, evicted_messages, digest_inputs). Raises DependencyCrossingEvictionError if no dependency-closed frontier exists within hard_capacity. """ # 1. Candidate frontier by oldest-first token budget. total = sum(m["tokens"] for m in messages) if total <= token_budget: return messages, [], [] cumulative = 0 frontier = 0 for i, m in enumerate(messages): if cumulative + m["tokens"] > token_budget: frontier = i break cumulative += m["tokens"] # 2. Open-reference set O across the frontier. evicted = messages[:frontier] retained = messages[frontier:] defined_evicted = set() for m in evicted: defined_evicted |= m.get("defines", set()) if m.get("tool_call_id"): defined_evicted.add(m["tool_call_id"]) open_refs = set() for m in retained: open_refs |= (m.get("references", set()) & defined_evicted) if m.get("pending") and m.get("tool_call_id") in defined_evicted: open_refs.add(m["tool_call_id"]) # 3. If closed, evict freely. if not open_refs: return retained, evicted, evicted # 4. Advance frontier to next dependency-closed boundary. for j in range(frontier, len(messages)): trial_evicted = messages[:j] trial_retained = messages[j:] trial_defined = set() for m in trial_evicted: trial_defined |= m.get("defines", set()) if m.get("tool_call_id"): trial_defined.add(m["tool_call_id"]) trial_open = set() for m in trial_retained: trial_open |= (m.get("references", set()) & trial_defined) if m.get("pending") and m.get("tool_call_id") in trial_defined: trial_open.add(m["tool_call_id"]) if not trial_open: projected = sum(m["tokens"] for m in trial_retained) if projected <= hard_capacity: return trial_retained, trial_evicted, trial_evicted break # 5. No closed frontier within capacity: refuse to evict. raise DependencyCrossingEvictionError( f"Cannot compact: open references {sorted(open_refs)} span the eviction " f"frontier and no dependency-closed boundary exists within " f"hard_capacity={hard_capacity}. Defer compaction or escalate budget." ) ```