Skip to content

When an Agent Loop Will Not Stop: Five Root Causes, One Triage Decision Tree

The most expensive and most infuriating class of agent failure is not a wrong answer. It is a stuck agent: one that calls the same tool until the token budget runs out, or whose token count climbs until the bill spikes or the process OOMs. This class is the easiest to misdiagnose as "the model is weak," and the most likely to burn a whole day — someone retunes the prompt, someone swaps in a bigger model, and nothing changes.

I have hardened this kind of triage on our internal agents into five root-cause branches. The single core idea: capture loop evidence first, then identify the cause, and only then talk about a fix. Jumping straight to "please converge, model" in the system prompt turns debugging into wishful thinking — you do not know why it will not converge, so that sentence is very likely to do nothing. The section below starts with the evidence commands, then walks each of the five root causes.

Prerequisite: Capture the "loop evidence" — without this line, everything after is guessing

The only reliable evidence that an agent is looping is its behavior sequence, not your impression of it. So the first step is not changing any configuration — it is turning on loop-detection logging:

# Inside the agent's main loop, print this one line each turn (sampled in prod is fine)
import hashlib, json
for turn, action in enumerate(agent.run_loop(), 1):
    args_hash = hashlib.md5(
        json.dumps(action.arguments, sort_keys=True, default=str).encode()
    ).hexdigest()[:8]
    ctx_tokens = token_counter.count(history)
    print(f"[loop] turn={turn} tool={action.name} "
          f"args={args_hash} ctx={ctx_tokens}")

That one line gives you three quantities: turn (which round), args (an argument hash, to tell whether it is spinning in place), and ctx (context tokens, to tell whether it is growing unbounded). With it, you are routed straight into a branch of the decision tree:

Symptom: agent stuck / token bill spiking / same tool called again and again
|
+-- K consecutive turns of same tool + same arg hash (K=3)
|  +-- context stays flat --> Root cause A: no termination condition (model thinks the task is not done)
|  +-- tool returns "not found / retry" --> Root cause B: tool spinning (return carries no new info)
|  +-- args nudge around but never converge --> Root cause E: duplicate tool registration (resolving to the wrong version)
|
+-- args are changing, but ctx jumps every turn and finally OOMs
|  +-- Root cause C: context bloat (observations / tool returns never truncated)
|
+-- total tokens climbing, but each turn behaves normally and nothing repeats
|  +-- Root cause D: no budget cap (a legitimately long job with no max_turns / max_tokens)
|
+-- none of the above, single turn just hangs
   +-- not a loop: a hung tool or a blocked LLM call (back to cause B, or check the tool-side timeout)

A one-line script makes the judgment above automatic, so the turn/args/ctx triple is always in front of you:

# Collapse agent_trace.jsonl into one line per turn; awk flags repeats
jq -r '[.turn, .tool, .args_hash, .ctx_tokens] | @tsv' agent_trace.jsonl \
  | awk '{
      print;
      if ($2==pt && $3==pa) rep++; else rep=1;
      if (rep>=3) print "  >>> REPEAT x" rep " (turn " $1 ")";
      pt=$2; pa=$3
    }' | head -40

A REPEAT x3 is hard proof of a stuck loop. One scenario I postmortemed (built from a typical production pattern): an internal ticketing agent, and users reported "it just keeps spinning, it never ends." The on-call engineer's first instinct was that the model was too weak, so they swapped 7B for 32B — still spinning. Opening the table showed it: the agent called search_tickets every turn with an identical args_hash, for 40-plus turns, while the context barely grew — because every search returned zero rows, producing the same fixed "no results" string, so the model kept generating the same query. That was root cause A (no termination condition) and B (tool return carries no new information) stacked together, and it had nothing to do with model size. A 32B given the same input will, of course, generate the same output.

Root cause A: No termination condition — "the model believes the task is not done"

Signature: the same tool and same arguments repeat, and the context stays roughly flat. The model is not unaware that it is repeating; it has simply concluded "the task is not finished," so it keeps retrying.

The root usually lives in one of two places: the prompt has no clear "stop when done" signal, or the exit criterion is unreachable (it can never be found, or a check never passes).

# Confirm an "exit criterion" exists: grab the agent's last assistant output before each turn ends
grep -n "stop\|done\|finished\|answer" agent_trace.jsonl | tail -20

Branching:

  • No "terminate"-style action (finish / submit / answer) ever appears in the log -> there is no "submit" tool in the tool list, so the model has no exit. Fix: add an explicit terminal tool (say submit_answer), and state in the prompt "when you have a final answer, you must call submit_answer and stop calling other tools."
  • The terminal tool exists but the model never calls it -> the exit criterion is unreachable. Either the information it gets never satisfies "have an answer" (back to cause B), or the prompt never says when to stop.
  • The model oscillates between tool A and tool B, and the arguments never settle -> this is oscillation, not a single-point loop; it usually means the two tools return conflicting conclusions on the same input. Check whether the two tools disagree on the same input.

One independent judgment worth holding onto: giving the agent an explicit "submit" tool works far better than begging it to "converge" in the prompt. "Please converge" depends on the model judging for itself when to stop, whereas "you are only done once you call submit_answer" moves the termination condition from the model's self-discipline to a hard constraint at the tool layer. The first one's hit rate depends on the model; the second's depends only on whether you configured the tool.

Root cause B: Tool spinning — "the return carries no new information"

Signature: the same tool and same arguments are called repeatedly, and the tool returns a fixed "not found / error / retry" string. The essence here: the tool's return does not carry new information that could change the model's next decision, so the model keeps making the same choice.

# Grab the tool returns and see whether they are "the same every turn"
jq -r '.observation' agent_trace.jsonl | sort | uniq -c | sort -rn | head

uniq -c makes it obvious: if some observation's count is 40, that return was repeated 40 times. Branching:

  • The tool returns a fixed "not found / error" with no actionable hint -> the model gets "not found," and its only move is to search again (it has nothing else to do), so it loops. Fix: make the tool's return carry a "next step" or "try a different query" hint, not a bare "no results."
  • The tool intermittently times out and the model's retries all hit the same slow path -> this is not a logic loop, it is a tool that is stuck. Give the tool a timeout plus a max retry, and when the retry limit is hit, return an "abandon" signal instead of retrying forever.
  • The tool returns success but the content never changes (querying the same un-updated data) -> this is "false success"; the data layer is not advancing. Check whether the tool is querying the same snapshot every time.

One scenario I postmortemed (built from a typical production pattern): a support agent kept calling "look up the order," and users reported "it spun for ten minutes and never answered." uniq -c showed "order not found" appearing 52 times. The root was that the order-number format did not match between the prompt and the tool schema — the user said "order 88990," the tool expected the prefixed SO-88990, the model sent the bare number every time, the tool returned not found every time, and the model, seeing not found, sent the bare number again. The key to breaking the loop was not in the model's hands; it was in data-format alignment. The fix was to have the tool prefix-complement bare numbers, not to trust the model to add the prefix itself.

Root cause C: Context bloat — "observations never truncated, so it grows unbounded"

Signature: arguments are changing (not a loop), but ctx jumps every turn until it hits the token limit or OOMs. This is not the model spinning; it is the "historical baggage" getting heavier every turn, dragging the full history to the model each round.

# Watch the per-turn growth rate of context tokens
jq -r '[.turn, .ctx_tokens] | @tsv' agent_trace.jsonl \
  | awk '{print $1, $2, $2-prev; prev=$2}' | head -30

The third column is the per-turn delta. If the delta is consistently large (say +8000 every turn), the problem is not one turn — it is structurally un-truncated. Branching:

  • Each tool return is dumped into the context in full -> tool returns are not truncated. A tool that returns 200 rows of a database dump is thousands of tokens. Fix: truncate tool returns to top-N rows or a summary.
  • The entire conversation history is never trimmed -> no sliding window / summarization. In a long job, early observations are useless to later turns but keep occupying space. Fix: add context management — once a threshold is crossed, summarize-compress the early turns, or keep only the last N turns plus the task goal.
  • The system prompt re-injects a large static block every turn -> for example, the full knowledge-base schema pasted in each round. Fix: static content belongs in a one-time system message, not re-injected every turn.
# Minimal guardrail for a single tool return: truncate + leave a ref (smallest fix for cause C)
def truncate_observation(obs: str, limit: int = 2000) -> str:
    if token_counter.count(obs) <= limit:
        return obs
    ref = store_full(obs)            # persist the full result, return a re-queryable id
    head = obs[: token_counter.slice(obs, limit - 60)]
    return f"{head}\n[truncated, full result saved as {ref}, re-query to fetch]"

A tradeoff worth stating: truncating tool returns has a cost, but "do not truncate until OOM" costs more. My experience: a hard 2000-token cap per tool return, with a summary plus "full result saved as ref_id, re-query to fetch" above the cap, is far cheaper than letting it run until OOM. An OOM is irreversible (that task is dead); a truncation is reversible (the model can query again).

Root cause D: No budget cap — "a legitimate long job, but no brake"

Signature: each turn behaves normally, arguments change, nothing repeats, yet total tokens keep climbing. This is the most easily missed one, because it "looks like it is working fine" — it simply has no brake and runs past the budget.

# Confirm whether a total token budget is configured
grep -rn "max_turns\|max_tokens\|budget\|max_steps" agent_config/ 2>/dev/null

Branching:

  • No max_turns / max_tokens anywhere in the config -> no budget. A job that legitimately needs 100 steps will run to 1000 with no budget. Fix: set two layers — max_turns (turn count) and max_context_tokens (total context size).
  • max_turns exists, but per-turn tokens are unbounded -> a variant of cause C. The turn count is capped, but each turn can be unlimited, so it still blows up.
  • A budget exists, but hitting it crashes or silently truncates -> the on-budget-exhaustion behavior is undefined. Fix: on budget exhaustion, return an explicit "budget exhausted" state so the caller decides whether to degrade, split the task, or report an error — rather than silently cutting it in half.

One independent judgment to hold: set the budget in two layers — max_turns for the turn count, max_context_tokens for the total, and per-tool-return for the single point. Setting only max_turns is a common mistake, because it says nothing about how heavy each turn can be. An agent that spends 5000 tokens per turn at max_turns=50 starts at 250,000 tokens. Three budget layers; missing any one of them is running with no brakes.

Root cause E: Duplicate tool registration — "it is calling the old version of the tool"

Signature: arguments keep tweaking, the model "thinks" it is progressing, but the result never converges, and the tool name looks right. This is the sneakiest, because on the surface the model looks busy; in reality it may be calling a "shadow" tool.

# Inspect the tool registry for the same name registered more than once
jq -r '.tool' agent_trace.jsonl | sort | uniq -c | sort -rn
# Then look at which tool implementation each call actually resolves to (with version/hash)
jq -r '[.turn, .tool, .tool_version] | @tsv' agent_trace.jsonl | head

Branching:

  • The same tool name appears more than once in the registry (an old + a new copy) -> the model calls by name and resolves to the old implementation. The old one behaves differently from the new one, so the model's calls based on new-version expectations never converge. Fix: at startup, assert the tool registry for duplicate names and fail-fast, rather than "the latter overwrites the former."
  • No duplicate name, but the argument schema in the prompt disagrees with what is actually validated -> same story as the RAG/MCP piece: the model is seeing a broken schema. Fix: the schema injected into the prompt and the schema the server validates must be the same copy; error on any diff.
  • The model keeps hopping between two functionally overlapping tools -> this is not a bug, it is tool-design redundancy. The model cannot tell which to use, so it takes turns trying. Fix: merge the tools or tighten their descriptions so the model can pick exactly one.

One scenario I postmortemed (built from a typical production pattern): an agent kept calling "run SQL," changing the where clause each time, yet never got the result it wanted, and tokens climbed steadily. To the eye it looked like "the model is reasoning carefully." Opening tool_version revealed it: run_sql was registered twice in the tool list — a "read-only restricted" copy added for development, and the full production copy — and a load-order bug made every call resolve to the restricted copy, which has column-permission limits on that query and can never return complete results. The model kept tweaking the where clause, but what was actually blocking it was column permissions, so tweaking where could never help. For a loop like this, looking at the prompt or the model is useless — you have to look at "which tool copy is actually being resolved."

Three Failure Postmortems (built from typical production scenarios)

Case 1: A model big enough still dead-looped (cause A + B stacked). A ticketing agent called search_tickets with an unchanged args_hash for 40 turns, flat context. Swapping 7B to 32B did nothing. Truth: every search returned zero rows, a fixed "no results," so the model kept generating the same query. Fix: (1) add a submit_answer terminal tool (cause A exit); (2) make "no results" carry a "try a different query" hint instead of a bare empty (cause B new information). Lesson: a dead loop is unrelated to model size. Capture the behavior sequence first, then decide between "no exit" and "the return carries no new information."

Case 2: A support agent looped 52 times on "order not found" (cause B + data format). Users reported "it spun for ten minutes." uniq -c showed order not found repeated 52 times. Root: the order number's format did not match between the prompt and the tool schema (bare vs prefixed), so the model always sent the bare number. Fix: prefix-complement bare numbers on the tool side. Lesson: the key to a loop is often data-format alignment, not the model. Run uniq -c first to see which observation is flooding.

Case 3: Duplicate tool registration — the model "reasoned carefully" but called the old version (cause E). An agent kept changing a SQL where clause yet never got complete results, tokens climbing, looking like normal reasoning on the surface. tool_version exposed run_sql registered twice, resolving to the restricted read-only copy and blocked on column permissions. Fix: assert the tool registry for duplicate names at startup and fail-fast. Lesson: changing arguments is not the same as progressing. Watch "argument hash" and "which tool version is actually resolved" together — both advancing is what real work looks like.

Turning the Triage Into Standing Monitoring: A Loop-Detection and Alerting Rule Set

The five root causes above are not something you can watch by eye in a production log. My approach is to make the "loop evidence" a permanent monitor, with three alerting rules that directly cover the five causes:

# Standing loop guard (runs each turn; on hit, alert + optional circuit-break)
def loop_guard(trace):
    last3 = trace[-3:]
    # Rule 1 (covers A/B/E): three consecutive turns, same tool + same args -> alert
    if len({(a.name, a.args_hash) for a in last3}) == 1:
        alert("repeating_call", turn=trace[-1].turn, tool=last3[-1].name)
        if trace[-1].turn - last3[0].turn >= 3:
            return "circuit_break"          # stop this run
    # Rule 2 (covers C): single-turn context delta above threshold -> alert
    if trace[-1].ctx_tokens - trace[-2].ctx_tokens > 8000:
        alert("context_bloat", delta=trace[-1].ctx_tokens - trace[-2].ctx_tokens)
    # Rule 3 (covers D): total tokens past 80% of budget -> alert + prepare to degrade
    if trace[-1].ctx_tokens > BUDGET * 0.8:
        alert("budget_exhaustion", ratio=trace[-1].ctx_tokens / BUDGET)
    return "ok"

The thresholds are a starting point, not gospel: "three consecutive turns" tolerates one legitimate retry (say, a network-timeout auto-retry); "8000-token delta" and "80 percent of budget" should be set to your own per-turn variance. Use circuit-breaking with care — it solves "stuck and burning money," but it will also kill a task that "was about to converge." My tradeoff: rule 1 alerts first and only circuit-breaks at five consecutive turns, leaving the model two legitimate retries of slack.

The final independent judgment: the order of dead-loop triage is "capture evidence, then identify the cause, then discuss the fix," and "retune the prompt / swap the model" goes last. The first two steps are deterministic (logs do not lie); only "change the prompt and see if it converges" is uncertain and requires trial and error. Putting the deterministic steps first drops the troubleshooting cost from "a day of trial and error" to "a few dozen minutes of localization."


Originality statement: All loop-detection code, alerting rules, the decision tree, and the cases in this article are organized by the author from hands-on triage of in-house agents. Cases are built from typical production scenarios and contain no real company names, IP addresses, or specific timelines.