# Why does an instance's semantic-convention anomaly detector systematically miss runaway tool-call loops that straddle a telemetry batch boundary **Date of Record:** 2026 November 24 **Scope:** Applies to anomaly detectors that consume OpenTelemetry-style GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.*`) emitted per agent step and evaluated over sliding or tumbling telemetry windows. Does not apply to detectors operating on complete, un-truncated per-session traces with unbounded lookback, nor to synchronous in-process loop guards that sit inside the agent runtime itself. ## Core Distinction The failure is not "the detector fails to see a loop." The detector sees every span. The failure is that the *invariant the detector enforces is window-local*, while the *loop it must catch is window-spanning*. A runaway tool-call loop is defined by a repetition count threshold over a causal chain of agent steps — `N` consecutive invocations of the same `gen_ai.tool.name` with near-identical argument payloads and monotonically growing `gen_ai.usage.input_tokens`. When the telemetry pipeline batches spans into fixed windows (say, 30-second tumbling windows, or windows keyed on a `trace_id` batch flush), the repetition count is *reset at every window edge*. A loop that produces 12 iterations across two windows of 6 each never exceeds a per-window threshold of 10. The detector reports "normal," the agent keeps burning tokens, and the first signal anyone gets is the bill. The distinction that matters operationally: **cardinality of repetition is a property of the trace, not of the window.** Any anomaly rule whose threshold is expressed against a per-window aggregate is structurally blind to loops whose period does not align with the window cadence. This is not a tuning problem — lowering the threshold to catch 6-per-window loops creates false positives on legitimately repetitive agents (batch file processors, paginated retrievers) that are *supposed* to call the same tool many times. ## What Was Observed A research agent executing a "find and summarize" task entered a tool-call loop against a web-search tool. The trigger: the search tool returned a `200 OK` with an empty `results` array and a `gen_ai.tool.call.result` attribute of `"[]"`. The agent's planner interpreted empty results as "query too narrow, broaden and retry," broadened, got empty again, and re-narrowed — a period-2 oscillation that never terminated because the agent had no success predicate for "the corpus genuinely has nothing." Telemetry showed the following per-window counts of `gen_ai.tool.name == "web_search"`: ``` window t0-t30s: 7 calls window t30-t60s: 6 calls window t60-t90s: 7 calls window t90-t120s: 5 calls (agent paused to re-plan) window t120-t150s: 8 calls ``` The detector's rule was `count(tool.name == X) > 10 within window` → anomaly. No window tripped. Across the full 150-second trace there were 33 calls to the same tool with alternating argument shapes and a cumulative input-token spend of 410k — a textbook runaway. The per-window max was 8. Two secondary observations compounded the miss: 1. **Argument-hash drift across the boundary.** The detector's secondary rule was "same `tool.name` AND same `args_hash` repeated > 3 times." Because the agent alternated between two query shapes (broaden/narrow), the `args_hash` alternated too. Even a cross-window counter keyed on `(tool.name, args_hash)` would see runs of at most 2 before the hash flipped. The loop was *semantically* repetitive but *syntactically* alternating. 2. **Token-growth signal was present but unread.** `gen_ai.usage.input_tokens` grew monotonically (context accumulated each turn) — a clean runaway signature. But the token-usage rule was also window-scoped (`sum(input_tokens) > budget_per_window`), and each window's sum stayed under the per-window budget because the budget had been sized for a single long step, not for cumulative growth across steps. The loop terminated only when the agent hit the runtime's hard `max_tokens` ceiling and the process was killed — 41 minutes after onset. ## Condition of Validity The window-local detector is *valid* — sound and complete for its stated scope — only under the following condition: > **The minimum runaway-loop period `P` (in wall-clock or step count) is greater than or equal to the telemetry window size `W`, AND the loop's argument payload is stable across iterations (args_hash does not alternate), AND cumulative token growth per window is bounded.** Formally, the detector catches a loop iff `repetitions_within_window(loop) > threshold`. For a loop of total repetition `R` spread uniformly over `k` windows, `repetitions_within_window ≈ R/k`. The detector fires iff `R > k · threshold`. A loop with `R = 33`, `k = 5`, `threshold = 10` requires `R > 50` to fire — meaning the detector is *guaranteed* to miss any loop shorter than 51 iterations, regardless of how obviously pathological those 33 iterations are. The condition breaks in three concrete ways, each of which we observed: - **Window/period aliasing:** when the loop's step cadence is close to the window cadence, repetitions distribute evenly and never concentrate. (Observed: 6–8 per 30s window, never >10.) - **Semantic repetition without syntactic repetition:** alternating argument shapes defeat hash-based dedup. (Observed: broaden/narrow oscillation.) - **Additive signals evaluated per-window:** cumulative token growth is a *monotone* signal; summing it per-window discards the monotonicity. (Observed: per-window sums all under budget.) The detector is *invalid* — must not be relied upon — whenever any of these hold. In practice, all three held simultaneously, which is why the miss was total rather than partial. ## Decision Boundary The architectural fix is not "smaller windows" (that raises false-positive rate on legitimate batch agents and increases detector cost) and not "bigger threshold headroom" (that widens the blind spot). The correct boundary is a **two-tier evaluation with an explicit cross-window stateful accumulator** that carries loop-detection state across window edges, plus a **success-predicate check** that distinguishes "repetition because the agent is progressing" from "repetition because the agent has no termination condition." The decision boundary is drawn as follows: 1. **Stateless per-window rules remain** for point anomalies (single-call latency spikes, single-call token blowups, unexpected tool names). These are genuinely window-local and correct as-is. 2. **A stateful loop accumulator is added** that, per `(agent_id, tool.name)` pair, maintains an exponentially-decayed repetition counter and a *canonicalized* argument signature (normalized over the oscillation — e.g., set-of-tokens hash rather than exact-string hash, so broaden/narrow variants collapse). The accumulator is flushed only on session end or on an explicit termination span, never on window edge. Threshold is expressed against the accumulator, not the window. 3. **A monotonicity check on `gen_ai.usage.input_tokens`** is evaluated against the session-cumulative series, not the per-window sum. A strictly increasing input-token series over `M` consecutive steps with no intervening `gen_ai.tool.call.result` that changes state (i.e., every result is a no-op like `"[]"` or an error) is itself a runaway signal independent of repetition count. 4. **The success predicate is the load-bearing guardrail.** The accumulator must be paired with a check: does the agent's tool-call sequence contain any step whose result *advanced* the task state (non-empty result, successful write, changed retrieval set)? A loop with zero state-advancing results over `M` steps is a runaway even at low repetition count. This is the invariant that catches the empty-results oscillation that repetition-counting alone misses. The boundary is therefore: **any anomaly rule whose predicate is a function of a single window is permitted only for signals that are themselves window-local. Repetition, cumulative growth, and no-progress conditions are session-local and must be evaluated by a stateful accumulator that outlives the window.** ## Operational Effect With the stateful accumulator and success-predicate guardrail deployed, the same agent trace is caught at step 9 (t=~38s, second iteration of the oscillation, first window boundary crossed with `no_progress_streak == 4`). The detector emits a `runaway_tool_loop` anomaly with the tool name, the canonicalized argument signature, the no-progress streak length, and the cumulative token spend at detection time (≈ 62k, vs. 410k at the prior miss). The agent runtime's circuit breaker trips, the session is checkpointed, and the planner is re-invoked with an explicit "empty results is terminal, not retryable" instruction injected into its context. The cost of the miss, quantified: 410k input tokens × the model's per-token rate, plus 41 minutes of wall-clock latency on a task that should have completed in under 3 minutes, plus a downstream summarization step that ran against a truncated corpus and produced a confidently wrong answer that was *not* flagged as low-confidence — the worst failure mode, because the anomaly detector's silence was read as "the agent completed normally." The invariant to carry forward: **a semantic-convention anomaly detector is only as good as the scope of the state it accumulates.** Window-scoped detectors are structurally blind to loops whose repetition period aliases with the window cadence, to semantically-repetitive-but-syntactically-alternating argument payloads, and to monotone cumulative signals. The guardrail is a session-scoped accumulator keyed on canonicalized tool identity with an explicit no-progress predicate — and a hard rule that repetition, growth, and no-progress signals are never evaluated per-window. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class RunawayLoopUndetectedError(RuntimeError): """Raised when a window-local detector is asked to certify a session whose loop period aliases with the telemetry window cadence.""" pass @dataclass class Step: tool_name: str args: dict result_is_noop: bool # True for "[]", "", error, unchanged state input_tokens: int @dataclass class SessionAccumulator: """Session-scoped, outlives telemetry windows. The invariant: repetition and no-progress are session-local, never window-local.""" canonical_sig_counts: dict = field(default_factory=dict) no_progress_streak: int = 0 cumulative_input_tokens: int = 0 last_input_tokens: int = 0 @staticmethod def _canonical_sig(tool_name: str, args: dict) -> str: # Collapse oscillation: sort keys, sort list elements, drop volatile # fields so broaden/narrow variants hash identically. def normalize(v): if isinstance(v, dict): return tuple(sorted((k, normalize(x)) for k, x in v.items())) if isinstance(v, (list, tuple)): return tuple(sorted(normalize(x) for x in v)) return v payload = repr((tool_name, normalize(args))).encode() return hashlib.sha256(payload).hexdigest()[:16] def observe(self, step: Step) -> Optional[str]: sig = self._canonical_sig(step.tool_name, step.args) self.canonical_sig_counts[sig] = self.canonical_sig_counts.get(sig, 0) + 1 self.cumulative_input_tokens += step.input_tokens if step.result_is_noop: self.no_progress_streak += 1 else: self.no_progress_streak = 0 # Guardrail 1: no-progress streak (catches empty-result oscillation # even at low repetition count). if self.no_progress_streak >= 4: return f"runaway_tool_loop:no_progress_streak={self.no_progress_streak}" # Guardrail 2: canonicalized repetition count across the whole session. if self.canonical_sig_counts[sig] > 10: return f"runaway_tool_loop:repetition={self.canonical_sig_counts[sig]}" # Guardrail 3: monotone token growth with no state advance. if (self.no_progress_streak >= 2 and step.input_tokens > self.last_input_tokens): self.last_input_tokens = step.input_tokens if self.cumulative_input_tokens > 200_000: return "runaway_tool_loop:cumulative_token_blowup" self.last_input_tokens = step.input_tokens return None def certify_window_local_detector(window_size_s: int, min_loop_period_s: int, threshold: int) -> None: """A window-local detector may only be certified if the minimum loop period it must catch exceeds the window size. Otherwise it is structurally blind and must not be deployed as the sole guard.""" if min_loop_period_s < window_size_s: raise RunawayLoopUndetectedError( f"window={window_size_s}s < min_loop_period={min_loop_period_s}s: " f"repetitions distribute across windows and never exceed " f"threshold={threshold}. Deploy session accumulator instead." ) ```