General-purpose sub-agents recursively spawn unbounded child agents, causing exponential fan-out and massive token burn

Status Open
Maintainer reply None cached
Activity 13 comments · opened Jun 13, 2026

What happened

When using the Agent tool to delegate a research task to a general-purpose sub-agent, the sub-agent itself has access to the Agent tool and recursively spawns its own child agents. Those children can also spawn agents, creating an exponential fan-out tree with no depth or count limit.

In my case, a single Agent call for "research Venmo integration options" resulted in 48+ background agents running simultaneously. The vast majority were redundant — doing overlapping searches on the same topics (e.g., 4 separate agents researching "Wise API," 3 researching "Apple Pay P2P," multiple agents researching the same settle-up flows). The agents kept spawning faster than I could stop them manually.

This has happened twice across different sessions with different research prompts. It's a consistent pattern, not a one-off.

Note: this is new behavior. After hundreds of hours of Claude Code usage, I had never seen recursive agent fan-out until recently. The model hasn't changed (Opus 4.6 1M context) — this appears to be a harness/runtime change that started allowing or encouraging sub-agents to spawn their own children in a way they didn't before.

Expected behavior

Sub-agents spawned via the Agent tool should have bounded recursion. Options:

  • Sub-agents should not have access to the Agent tool (preventing recursive spawning entirely)
  • A configurable depth limit (e.g., max depth of 1 — sub-agents can't spawn their own sub-agents)
  • A configurable total agent count cap per turn (e.g., max 10 agents from a single parent call)
  • At minimum, the parent context should be notified and given a chance to approve before a sub-agent fans out into many children

Impact

  • ~1.5M+ tokens consumed across redundant agents in a single research request
  • No effective way to stop runaway agents — by the time the user sees them in the agent list and manually stops them, dozens have already launched and consumed tokens
  • The useful research was complete within the first 3-4 agents; the remaining 44 added no new information

Reproduction

  1. Ask Claude Code to research a broad topic (e.g., "research Venmo integration options for a mobile app")
  2. Claude spawns a general-purpose agent via the Agent tool
  3. That agent decides the topic has multiple sub-questions and spawns multiple child agents
  4. Those child agents may themselves spawn further children
  5. Result: dozens of concurrent agents doing overlapping work

Environment

  • Claude Code CLI (latest)
  • Model: claude-opus-4-6 (1M context)
  • macOS Darwin 25.5.0

Suggested fixes (in order of preference)

  1. Depth limit: Sub-agents should not be able to spawn their own sub-agents. The parent context should be the only orchestrator.
  2. Count limit: Cap the total number of agents a single Agent call can transitively produce (e.g., 10).
  3. Approval gate: If a sub-agent wants to spawn more than N children, require parent/user approval before proceeding.
  4. Tool restriction: Remove Agent from the tool set available to sub-agents spawned by Agent, so only the main conversation or Workflow (which has explicit concurrency controls) can orchestrate multi-agent work.

View original on GitHub ↗

13 Comments

github-actions[bot] · 2 months ago

Found 3 possible duplicate issues:

  1. https://github.com/anthropics/claude-code/issues/49275
  2. https://github.com/anthropics/claude-code/issues/67343
  3. https://github.com/anthropics/claude-code/issues/64938

This issue will be automatically closed as a duplicate in 3 days.

  • If your issue is a duplicate, please close it and 👍 the existing issue instead
  • To prevent auto-closure, add a comment or 👎 this comment

🤖 Generated with Claude Code

kcarriedo · 2 months ago

The unbounded recursive fan-out you're describing is a symptom of a structural gap: the Agent tool's depth/count limits are either absent or not enforced at the orchestration layer, so a general-purpose subagent that inherits the full tool set will naturally re-delegate whenever it hits uncertainty.

A few observations from building production multi-agent pipelines that map onto this:

Why it compounds so fast: The research task framing ("find options for X") is particularly prone to this because uncertainty expands rather than narrows as a subagent discovers new terms. Each branch spawns equally uncertain children. Without a depth cap or a deduplicated query registry, 48 agents doing overlapping searches on "Wise API" is the expected outcome, not a bug.

Immediate mitigation pattern: Scope the delegated agent's system prompt to explicitly forbid spawning further agents ("You are a terminal researcher. Use tools directly. Do not call Agent."). This is rough but works until Anthropic ships a first-class depth/fan-out control.

The underlying ask: A per-session agent spawn limit (configurable, with a hard ceiling) and a query deduplication signal would solve this structurally. The timeout issue in #61405 and the unrecoverable loop in #68093 are related failure modes — they all trace back to the absence of a supervision primitive at the orchestration layer.

The "48+ agents researching the same thing" failure is a great concrete data point — it puts a number on the cost of the missing guardrail.

jeffreese · 2 months ago

Root cause identified: v2.1.172 (June 10, 2026)

After reviewing the changelog between v2.1.154 and v2.1.176, I found the change that introduced this behavior:

v2.1.172: "Sub-agents can now spawn their own sub-agents (up to 5 levels deep)"

This confirms this is not a model behavior change — it's a harness capability that was intentionally added. Prior to 2.1.172, sub-agents did not have access to recursive spawning, which explains why I never saw this pattern across hundreds of hours of usage.

The depth cap isn't the problem — the breadth is

The 5-level depth limit exists but is insufficient. The issue is uncapped breadth at each level. A research prompt that decomposes into 8 sub-questions at level 1, each spawning 3–5 children at level 2, produces 24–40 agents — all before reaching the depth cap. My 48-agent tree was likely only 2–3 levels deep.

Adjacent instability in the same subsystem

The background agent / sub-agent runtime has been actively churning with fixes across recent releases, suggesting the machinery is still stabilizing:

  • v2.1.160 (June 2): Fixed background sessions "re-running the original prompt" after overnight retire — twice in the same release
  • v2.1.166 (June 6): Fixed background agent sessions that entered a git worktree crash-looping with "No conversation found" when reopened
  • v2.1.169 (June 8): "Background sessions now preserve flags across retire→wake, and respawn state validation was hardened"
  • v2.1.172 (June 10): Fixed "a background sub-agent staying stuck as 'active' in the agent panel after a nested agent it spawned was stopped" — shipped in the same release as the recursive spawning feature
  • v2.1.176 (June 12): Three more respawn fixes — malformed resume IDs rejected, persisted state neutralized before respawn, "Working forever" cleared

I also have a separate open issue (#67784) for background agents re-running after completion, which appears to be another manifestation of this subsystem's instability.

User-side mitigation (for other affected users)

Until a harness-level fix ships, defining a custom agent type whose tools frontmatter excludes Agent prevents recursive spawning entirely. This is how I structure purpose-built agents in my own system — they carry explicit tool allowlists and cannot spawn children. The general-purpose agent type is the one that needs the restriction, since it inherits the full tool set including Agent.

Recommendation

My original suggested fixes stand, but with the root cause identified, the most surgical fix would be:

  1. Default Agent out of sub-agent tool sets (opt-in recursion, not opt-out) — this restores the pre-2.1.172 behavior as the default
  2. Add a maxAgentBreadth or maxAgentCount setting for users who want controlled recursion
  3. The existing 5-level depth cap can stay as a backstop
loncharles · 2 months ago

The depth constraint as-coded is insufficient. It either is implemented to only allow an agent to launch subagents five levels deep without any concept of the current depth of recursion, or there is a bug (or likely both).

As pointed out, the breadth constraints and heavy duplication of overlapping of work is also a core issue.

Here is an infinite recursion case where a subagent hits a perms wall (that doesn't propagate to the user anyway) and it launches another subagent to do the work instead, ad infinitum:

<img width="649" height="680" alt="Image" src="https://github.com/user-attachments/assets/1979c22d-fa47-4fc9-9148-b9c80b0cab49" />

There's a set of compounding bugs and regressions that make this entire "subsystem" unstable and cumulative negative effects worse. One particular case where repo investigation triggered a Fetch or curl for every file in a github repo across 100s of files is either a model or system/tools prompt regression.
https://github.com/anthropics/claude-code/issues/68430

P47Phoenix · 2 months ago

Also have this issue.

1718 background agents were stopped by the user: “Check PR #1492 CI status and merge if green”, “Check PR #1492 CI status, merge if passing, clean up duplicates”, “Check CI, merge PR #1492, clean up duplicates”, “Check CI, merge PR
  #1492, clean up duplicates”, “Check CI, merge PR #1492, clean up duplicates”, “Check CI, merge PR #1492, and clean up duplicate PRs”, “Check CI, merge PR #1492, cleanup duplicates”, “CI check, merge PR #1492, and cleanup duplicate PRs”,
TemoSulava · 2 months ago

It happened to me yesterday, it spawned 905 agents. Each made 2k+ calls for websearch, etc. Used up my 5hr max limit in 2 mins + 87$ in another minute i literally unplugged the pc and turned off the extra usage to make it stop

fzarifian · 2 months ago

Binary-level confirmation (v2.1.195): depth tracking works; the gap is breadth + zero configurability.

Reverse-checked the native binary to settle two open questions in this thread.

**Depth is tracked (re: @loncharles's doubt).** Each spawn carries an agentContext; depth is spawnDepth/agentDepth, incremented +1 per level (qG(c.agentContext)+1). It's enforced in two places against a constant = 5:

  • tool gating: the Agent tool is kept in a sub-agent's toolset only while depth < 5;
  • launch-time stop: if (depth >= 5) throw AgentPreconditionError("Subagent nesting limit reached (depth N of 5)...") (telemetry subagent_launch / subagent_depth_cap).

So the depth limit is real and depth-aware — it is not depthless.

The actual gaps (confirming @jeffreese):

  • No breadth/count cap anywhere. Searched the binary for maxAgent*, *count*, fanout, breadth — nothing transitively bounds how many children a level produces. 8×(3–5) fan-out at depth 2 is unbounded by design.
  • Nothing is configurable. No key in claude-code-settings.schema.json (agent, disableAgentView, subagentStatusLine, agentPushNotifEnabled, SubagentStart/SubagentStop hooks are the only agent-related ones) and no env var. The 5 is a hard-coded literal.
  • Built-in agents claude / general-purpose / worker ship tools: ["*"], which includes Agent — that's why recursion is opt-out, not opt-in.

Most surgical fix, given the above: default Agent out of sub-agent tool sets (restore pre-2.1.172 opt-in recursion) and add a configurable maxAgentCount/breadth cap, honored at user/project/managed scope. The existing depth-5 backstop can stay.

Credit compensation. This is an unsolicited, harness-introduced behavior (v2.1.172) that burns tokens with no opt-out — users in this thread report 1.5M+ tokens, 905-agent runs, and ~$87 consumed in minutes. The tokens spent on this runaway fan-out were not requested by users and reflect a defect, not legitimate usage. Affected accounts (myself included) should be credited/refunded for the spend directly attributable to recursive sub-agent fan-out. Please confirm the channel and process for issuing these credits, or route affected users to billing support with the relevant session/telemetry IDs (subagent_launch / subagent_depth_cap).

Seen on all distributions (macos, linux, windows), every models (not only in opus, including fable that's costed a lot)

davidalberg · 2 months ago

I think I may have hit the same underlying issue, though I can't fully confirm the recursive-spawn mechanism directly:

What happened: Two separate, sudden quota/usage jumps within 24 hours, on two different machines (home PC and office PC), with no corresponding completed task that would explain the consumption. The pattern matched what's described here usage climbing faster than I could trace it to a visible task.

What I checked: I went through my local Claude Code session logs (~/.claude/projects/*.jsonl) for both incidents.

For the home-PC session around the time of the first jump, I found no Agent tool calls at all in that transcript so if recursive sub-agent fan-out happened there, it isn't visible in this log.
For the office-PC incident, the session simply isn't present in my home PC's local log directory (different machine, not synced) so I have no log evidence for that occurrence either way.
Across other sessions where I did see multiple Agent calls, they were all flat fan-out from the main loop (one parent spawning several sub-agents directly) none showed a sub-agent itself spawning further children, which is the specific mechanism described in this issue.
So: I can't point to a confirmed recursive tree in my own logs, but the symptom (unexplained, rapid quota consumption with no completed task to show for it) matches closely enough that I wanted to add it as a second/third data point. If there's a way to get visibility into agent-spawn trees per session (e.g., a count of total agents spawned, including nested ones, surfaced somewhere), that would make it much easier for users like me to confirm or rule this out after the fact rather than only noticing once quota is already gone.

WittmannF · 2 months ago

Has anyone using Claude Code through AWS Bedrock successfully received a refund or credit from either AWS or Anthropic for costs caused by this bug? In our case, a simple research task recursively spawned 900+ agents and consumed about $700 in tokens in roughly 30 minutes. The cost would likely have continued increasing if we had not interrupted the task.

kcarriedo · 1 month ago

The 48-agent fan-out you hit is the canonical unbounded recursion case. The root cause is that sub-agents inherit the full tool list of their parent by default, including the Task/Agent tool itself. So every sub-agent is also an orchestrator.

Two mitigations that work today without waiting for a platform-level fix:

  1. Restrict the Agent tool in sub-agent frontmatter. In your .claude/agents/<name>.md, add:

---
tools: [WebSearch, WebFetch, Read, Bash]
---
Omitting the Task/Agent tool from the declared tools list prevents that sub-agent from spawning children. You lose one level of delegation but you stop the fan-out.

  1. Add a PreToolUse hook that counts active background tasks before allowing another Task tool call:

RUNNING=$(sqlite3 ~/Library/Application\ Support/Claude/claude_code.db "SELECT COUNT(*) FROM workflow_tasks WHERE status='running';" 2>/dev/null || echo 0)
if [ "$RUNNING" -ge 8 ]; then echo '{"action":"block","reason":"agent count limit reached"}'; exit 0; fi
Crude but effective -- stops new spawns when you already have N running.

The observation that the useful work was done by agents 3-4 and the remaining 44 added nothing is consistent with what I have seen: the orchestrator does not have a "done" signal from parallel workers, so it keeps spawning more. Until there is a result-collection primitive (not just file-based polling), the safest pattern is a fixed fan-out (orchestrator spawns exactly N workers, waits for all N, aggregates) rather than letting each worker decide whether more workers are needed.

The depth-limit approach in your suggestion list is the right platform fix. A max_agent_depth setting in settings.json or CLAUDE.md would let operators set policy without patching every agent spec.

kcarriedo · 1 month ago

The 48+ agent case is alarming but not surprising given the current defaults. We have seen similar fan-out on research-style tasks where the sub-agent's prompt is open-ended enough that it decides parallelism will help.

The depth limit approach is the right fix. The count limit is useful too but it is the depth that makes it exponential -- a count limit of 10 still lets you get 10 agents at depth 2 from a single call.

For anyone hitting this now: one pattern that helps is being explicit in the sub-agent's system prompt that it does NOT have permission to spawn further agents ("You are a leaf agent. Do not use the Agent tool."). You can inject this via the agent's CLAUDE.md or via the prompt passed to the Agent tool. It is not a real solution because a sufficiently creative model will sometimes ignore it, but it reduces the problem frequency significantly.

The area:cost label is apt here. This is the kind of bug that can turn a $5 task into a $50+ incident with no warning. Some form of pre-spawn cost gate -- even just a configurable token budget per Agent call that triggers a confirmation prompt -- would give teams a safety net while the depth limit lands.

ofekron · 1 month ago

Unbounded recursive delegation needs a runtime-level budget, not only better prompting.

I would separate “may use tools” from “may create agents.” A child should receive an explicit delegation policy: max depth, max children, allowed child roles, total token/budget cap, parent-visible reason for each spawn, and whether spawned children can themselves delegate. The default for general-purpose research agents should probably be no recursive delegation unless the parent explicitly grants it.

I maintain Better Agent (https://github.com/ofekron/better-agent), where parent sessions own worker scopes and are responsible for integrating results rather than letting workers create an invisible tree. If useful, a star helps other multi-agent runtime builders find it.

Zanger67 · 1 month ago

Had the same issue arise today. Mine was less a linked list chain instead it fanned out wide and deep resulting in 99+ subagents. 118 Agent calls made but ~99 active before I force quit the terminal. Details below:

Re @kcarriedo from above

"We have seen similar fan-out on research-style tasks where the sub-agent's prompt is open-ended enough that it decides parallelism will help."

Environment

  • Version: 2.1.216 (native installer, ~/.local/share/claude/versions/)
  • Platform: Linux (Linux Mint 22, kernel 6.8.0-136, x86_64)
  • Node: v24.14.1
  • Terminal: xterm-256color
  • Model: Opus 4.8, 1M context (claude-opus-4-8[1m]) — main loop and 86 of 99 subagents; 13

subagents on Sonnet 5 via explicit override

  • Subagent type: general-purpose (all 99)
  • Invocation: interactive session, no --agents, no workflow, no ultracode
  • Occurred: 2026-07-20 ~23:00 EDT
  ┌──────────┬────────┐
  │  Depth   │ Agents │
  ├──────────┼────────┤
  │ 1 (mine) │ 3      │
  ├──────────┼────────┤
  │ 2        │ 19     │
  ├──────────┼────────┤
  │ 3        │ 38     │
  ├──────────┼────────┤
  │ 4        │ 37     │
  ├──────────┼────────┤
  │ 5        │ 2      │
  ├──────────┼────────┤
  │ Total    │ 99     │
  └──────────┴────────┘

Approx. behavior at each level:

Initial instruction: make a leaderboard artifact for (insert industry) organisations and related in terms of their prominence and scale. Differentiate from policy work and technical work in the field.
Depth 1: "This is a large landscape survey. I'll parallelize across clusters of organizations, then synthesize and do the tier assessment myself."
Depth 2: "This is a large multi-org research task with clearly parallelizable parts. I'll split the 15 organizations across four parallel research agents."
Depth 3: "Each org is an independent, self-contained research task. Launching all four now."
Depth 3: "I'll research each of the 7 organizations in parallel using dedicated research agents." → 7 singleton agents

| | Main session | 99 subagents | Total |
|---|---:|---:|---:|
| Input (uncached) | 72 | 5,820 | 5,892 |
| Cache write | 510,946 | 19,091,215 | 19,602,161 |
| Cache read | 3,218,381 | 218,054,901 | 221,273,282 |
| Output | 79,139 | 719,319 | 798,458 |
| Total | 3,808,538 | 237,871,255 | 241,679,793 |

92% cache read with total token usage being 98% by subagents

Other notes:

  • From the depth-1 governance agent, mid-run: *"Search budget

for the session is now exhausted (the parallel agents consumed it). Let me verify WebFetch still works
while agents report back."*

  • Multiple subagents called for tooling and capability testing. E.g. multiple subagents were called under the prompting and title of "Test web search availability in subagent"

Subagent tree

``
main session (3 Agent calls)
├── Research category A orgs → 6 children, no grandchildren
├── Research category B orgs → 7 children, 5 levels deep
└── Research programs → 6 children, 4 levels deep
``

<details>
<summary><b>Full tree — all 99 agents</b></summary>

main session (3 Agent calls)
├── Research category A orgs
│   ├── Research Orgs A, B, C, D, E
│   ├── Research Orgs F, G, H, I, J
│   ├── Research Orgs K, L, M, N, O
│   ├── Research academic labs
│   ├── Research Orgs P, Q, R, S
│   └── Research missed orgs
├── Research category B orgs
│   ├── Research Region 1 orgs [sonnet]
│   │   ├── Research Org T and Org U
│   │   ├── Research Org V and Org W
│   │   ├── Research Org X and Org Y
│   │   └── Research Org Z and 4 brief-entry orgs
│   ├── Research Region 2 support orgs [sonnet]
│   │   ├── Research Org AA and Org AB
│   │   ├── Research Orgs AC, AD, AE
│   │   │   ├── Research Org AC
│   │   │   ├── Research Org AD
│   │   │   └── Research Org AE
│   │   ├── Research Orgs AF, AG, AH, AI
│   │   └── Research Orgs AJ, AK, AL, AM/AN, AO, AP, J
│   │       ├── Research Org AJ  ✓done
│   │       ├── Research Org AK
│   │       ├── Research Org AL
│   │       ├── Research Org AM and Org AN
│   │       ├── Research Org AO and Org AQ
│   │       ├── Research Org AP
│   │       └── Research Org J
│   ├── Research Region 2 publicity orgs [sonnet]
│   │   ├── Research Orgs AR, AS, AT, AU
│   │   │   ├── Research Org AR shutdown [sonnet]
│   │   │   ├── Research Org AS [sonnet]
│   │   │   ├── Research Org AU [sonnet]
│   │   │   └── Research Org AT [sonnet]
│   │   ├── Research Orgs AV, AW, AX, AY, AZ
│   │   ├── Research secondary support orgs
│   │   │   ├── Research Org BA and Org BB
│   │   │   ├── Research Org BC and Org E pivot
│   │   │   ├── Research Org BC and Org E pivot
│   │   │   └── Research Orgs O, BD, BE
│   │   │       ├── Research Org O
│   │   │       └── Research Org BD
│   │   └── Research opposing-side publicity landscape
│   │       ├── Research Org BF
│   │       ├── Research Org BG
│   │       └── Research Org BH
│   ├── Research government bodies [sonnet]
│   │   ├── Research Region 3 bodies
│   │   │   ├── Research Region 2 Org BI/Org BJ status <dates>
│   │   │   └── Research Region 4 body status <dates>
│   │   ├── Research Region 5 institutes
│   │   │   ├── Research Region 6 institute
│   │   │   ├── Research Region 7 institute
│   │   │   └── Research Region 8 institute (Org BJ)
│   │   ├── Research intergovernmental bodies
│   │   └── Research Region 9 bodies and Region 11 summit
│   │       ├── Research Region 10 Org BK and Org BL
│   │       └── Research Region 11 summit <date>
│   ├── Research international coordination orgs [sonnet]
│   │   ├── Research Orgs BM, BN, BO, BP
│   │   ├── Research Org BQ and Region 10 bodies
│   │   └── Research Region 12 orgs cluster
│   │       ├── Research Org BR and Org AS Region 4 office
│   │       ├── Research Org BS and Org BT  ✓done
│   │       ├── Research Org BU and Org BV
│   │       ├── Research Org BW and Org BX
│   │       └── Research Org BS and Org BT
│   ├── Research industry bodies and publicity groups [sonnet]
│   │   ├── Research industry associations cluster
│   │   ├── Research grassroots publicity orgs
│   │   └── Research Org E pivot, open statement, artist coalitions
│   └── Research <dates> landscape shifts [sonnet]
│       ├── Org shutdowns and funding withdrawals
│       ├── Org mergers and reorganizations
│       ├── Region 3 upheaval <dates>
│       ├── Talent flows and state legislation
│       │   └── Test web search availability in subagent  ✓done
│       ├── New orgs founded <dates>
│       ├── Region 3 upheaval <dates>
│       └── Legislative testimony and citations
└── Research programs
    ├── Research flagship technical programs and groups
    ├── Research mid-tier technical programs and groups
    ├── Research internal and PhD-level programs
    │   ├── Research small-org fellowships [sonnet]
    │   │   ├── Org J program research
    │   │   ├── Org F program research
    │   │   └── Org H program research
    │   └── Research Region 2 government programs [sonnet]
    ├── Research Region 2 policy programs
    ├── Research Region 13 governance programs
    │   ├── Research Orgs AC, BY, winter programs
    │   ├── Research Orgs BZ, CA, Y
    │   ├── Research Orgs AV, CB, CC, CD
    │   └── Research Orgs C, BO, U, CE, V
    └── Sweep for missed programs and selectivity data
        ├── Regional programs sweep
        ├── University + lab programs sweep
        └── Incubators and industry programs sweep

</details>

Linking a few related issues

#68619, #72732, #72566, #72619, #77060 (Windows). #68430 is a closed twin of #68619. #77361