# What structural signals indicate a tool-call recursion is genuinely divergent versus a legitimate deep plan: the call-graph depth/fan-out invariant and why token-budget and wall-clock tripwires fire on the wrong loops **Date of Record:** 2026 November 19 **Scope:** Applies to observability systems that classify agent tool-call loops for cost-runaway intervention (kill, throttle, or escalate) using call-tree structure. Does not apply to single-turn tool use, to purely conversational multi-agent chatter without tool invocation, or to loops whose termination is externally gated by a human-in-the-loop rather than by the runtime. ## Core Distinction A recurring tool call is not evidence of divergence. The operational signal that separates a *legitimate deep plan* from a *divergent loop* is not repetition count, elapsed time, or cumulative tokens — it is the **ratio of unique state mutations to total invocations along each call-graph edge, conditioned on whether the argument tuple of the repeated call is converging or stationary**. Concretely: an agent doing recursive decomposition (e.g., a research agent issuing `search` → `fetch` → `extract` → `verify` for each of 40 sub-questions) produces a call graph with high depth and high fan-out but *strictly decreasing* per-node argument entropy and a monotonically shrinking working set of unresolved sub-goals. A divergent loop produces a call graph that is structurally identical at the top — same tool, same depth, similar fan-out — but whose per-node argument tuples are either *stationary* (identical bytes) or *drifting without closure* (the agent keeps reformulating the same query with synonyms, never satisfying the exit predicate). Both cases look the same to the three tripwires most observability stacks deploy first: token-budget ceiling, wall-clock timeout, and per-tool invocation count. That is the failure. The tripwires measure *cost*, not *progress*, and cost is a strictly worse proxy for divergence than the call-graph invariant below. ## What Was Observed A batch of 1,400 instrumented agent runs across two tool-using workloads (a recursive document-analysis agent and a code-repair agent) were traced with per-span argument hashing and a parent-span reference on every tool call. Three populations emerged: 1. **Legitimate deep plans (n=612).** Depth up to 9, fan-out up to 12 per node. Median 340 tool invocations. Argument-tuple hash novelty per edge stayed above 0.71 (i.e., ≥71% of invocations on a given edge carried an argument tuple never seen before on that edge) through the run, and the set of "open" sub-goals tracked in agent scratchpad state decreased monotonically in 94% of runs. 2. **Divergent loops (n=47).** Median 1,900 tool invocations before any tripwire fired. The signature: on at least one call-graph edge, the argument-tuple hash novelty collapsed to near zero — the same `(tool, args)` pair re-emitted with only whitespace or synonym changes — *while the agent's scratchpad continued to claim forward progress* ("now checking X", "let me verify Y"). The loop was semantically invisible to the agent because each iteration's context window contained the previous iteration's *summary*, not the raw prior arguments, so the agent could not detect its own repetition. 3. **Ambiguous (n=741).** High invocation counts with moderate novelty (0.3–0.7). These were the dangerous class: 38% of them eventually resolved into legitimate completion after a long plateau; 62% were divergent. Token-budget tripwires fired on 71% of the ambiguous population, killing 281 runs that would have completed. The false-positive rate of the budget tripwire on the ambiguous class was 38%. The load-bearing observation: **the argument-tuple hash novelty on the deepest active call-graph edge was a better discriminator (AUC 0.94) than cumulative tokens (AUC 0.61) or wall-clock (AUC 0.58).** Cost signals are downstream of the loop; the argument-stationarity signal is *at* the loop. ## Condition of Validity The invariant holds only when all three of the following are true: - **Argument tuples are faithfully captured at the tool boundary.** If the observability layer logs a *summarized* or *redacted* argument (common when tool inputs contain large documents), hash novelty is computed over the summary, and a loop that reformulates its query will register as novel. The invariant requires hashing the *raw serialized arguments as seen by the tool adapter*, before any redaction. - **The call graph preserves parent-span linkage across context compaction.** When the agent's context window saturates and the runtime compacts history, the parent-span reference must survive compaction. If compaction drops span IDs, the call graph flattens to a star and per-edge novelty cannot be computed — every call looks like a fresh root. This is the single most common way the invariant silently degrades to a useless invocation counter. - **The exit predicate is expressible in agent state, not only in tool output.** For legitimate deep plans, "progress" means the open-subgoal set shrinks. If the agent's scratchpad does not expose an open-subgoal set (many do not — they keep it implicit in prose), the monotonic-shrink half of the invariant is unobservable, and only the novelty half remains. Novelty alone still discriminates at AUC 0.88, but the false-positive rate on the ambiguous class rises from 38% to 51%. The invariant does **not** hold for agents whose legitimate work is genuinely repetitive by design — e.g., a polling agent that must call `check_status` with identical arguments until an external condition flips. For those, argument stationarity is the *intended* behavior and must be excluded by a declared `idempotent_poll` tool annotation, or the invariant will kill them. ## Decision Boundary The runtime should intervene on a call-graph edge when **both** conditions hold across a sliding window of the last *k* invocations on that edge: - `novelty(edge, window) < θ_novel` (empirically θ_novel ≈ 0.15 over k=8), **and** - `open_subgoal_delta(edge, window) ≥ 0` (the working set is not shrinking). Intervene *before* the token ceiling. The token ceiling remains as a hard backstop but must be raised to a level that does not fire on legitimate deep plans — in the dataset above, the 99th-percentile legitimate run consumed 2.1× the median budget tripwire threshold, meaning the default budget tripwire was structurally guaranteed to false-positive on the top decile of legitimate work. The boundary is deliberately **not** a depth or fan-out limit. Depth and fan-out are properties of the *plan*, and capping them caps capability. The invariant caps *stagnation*, which is orthogonal to plan shape. A 9-deep, 12-wide recursive plan with rising novelty is allowed to run; a 2-deep, 1-wide loop with zero novelty is killed at invocation 9. One additional guard: when the invariant fires, the kill must be accompanied by a **context reset of the offending edge's argument history**, not just a process halt. In 31 of the 47 divergent loops, a naive halt-and-restart re-entered the same loop within four invocations because the agent's persisted memory still contained the loop's own progress-claims, which it treated as ground truth. The reset must excise the self-referential claims, or the loop is merely checkpointed, not broken. ## Operational Effect Deploying the argument-novelty + subgoal-delta invariant as the primary tripwire, with the token ceiling demoted to a backstop at 3× the prior threshold, changed the observed population as follows: false-positive kills on the ambiguous class fell from 38% to 6%; median tokens-to-detection on true divergent loops fell from 1,900 invocations to 11; and — the counterintuitive result — *total* token spend across the batch fell 22%, because the 281 runs previously killed mid-plan were no longer restarted from cold, and cold restarts were themselves the largest single source of replayed tool calls. The invariant's cost is that it requires faithful raw-argument capture and compaction-surviving span linkage. Teams that cannot pay that cost should not deploy the invariant and should instead annotate their tools and accept the budget tripwire's known false-positive rate — but they should stop describing that tripwire as "runaway detection." It is a spend cap. The difference matters because a spend cap that fires on legitimate deep work trains operators to raise the cap, and a raised cap is exactly what lets a true divergent loop run to four-figure invocations before anyone notices. ```python from dataclasses import dataclass, field from typing import Hashable, Optional NOVELTY_THRESHOLD = 0.15 WINDOW = 8 class RecursionInvariantViolation(RuntimeError): """Raised when an edge's novelty/subgoal invariant cannot be evaluated because the observability substrate is degraded (missing raw args or broken parent-span linkage). Never raised for a genuine loop detection; that path returns a decision, it does not throw.""" pass @dataclass class EdgeTrace: edge_id: str arg_hashes: list[Hashable] = field(default_factory=list) open_subgoal_deltas: list[int] = field(default_factory=list) compaction_events: int = 0 def record(self, arg_hash: Hashable, open_subgoal_delta: int) -> None: self.arg_hashes.append(arg_hash) self.open_subgoal_deltas.append(open_subgoal_delta) def novelty(self) -> float: window = self.arg_hashes[-WINDOW:] if not window: return 1.0 return len(set(window)) / len(window) def subgoals_stagnant(self) -> bool: window = self.open_subgoal_deltas[-WINDOW:] return bool(window) and sum(window) >= 0 def evaluate_edge(trace: EdgeTrace, raw_args_captured: bool, parent_span_intact: bool) -> str: # The invariant is undefined if the substrate cannot supply raw args or # if compaction has flattened the call graph. Fail loud, do not guess. if not raw_args_captured: raise RecursionInvariantViolation( f"edge {trace.edge_id}: raw argument capture disabled; " "novelty would be computed over redacted summaries and is invalid" ) if not parent_span_intact: raise RecursionInvariantViolation( f"edge {trace.edge_id}: parent-span linkage lost across " f"{trace.compaction_events} compaction event(s); per-edge novelty undefined" ) if trace.novelty() < NOVELTY_THRESHOLD and trace.subgoals_stagnant(): return "KILL_AND_RESET_EDGE_CONTEXT" return "CONTINUE" ```