Subagent results silently overflow context, causing unrecoverable session crash

Status Closed — not planned
Reported on v2.1.32
Maintainer reply None cached
Activity 12 comments · opened Feb 5, 2026 · closed Apr 17, 2026

1 ## Bug Description
2
3 When multiple Task tool subagents complete and return large results to the parent agent, the combined results can overflow the parent's context window. This causes the parent to enter a terminal "Prompt is too long" loop — it cannot process any incoming messages, cannot summarize or act on the results, and the session becomes permanently unresponsive until the user force-quits.
4
5 From the user's perspective, the session simply freezes and then crashes, with no indication of what happened and no way to recover the work. The user sees nothing — no error message, no partial results, no graceful degradation.
6
7 ## Reproduction Steps
8
9 1. Start a Claude Code session on a large codebase (~200+ files)
10 2. Use the Task tool to spawn 7 parallel subagents (e.g., subagent_type=general-purpose), each tasked with auditing a different module against a spec
11 3. Each agent reads many files and produces a detailed report (15K–37K chars each)
12 4. All 7 agents complete and return their results as task-notification messages to the parent
13 5. The parent's context now contains the full conversation history PLUS all 7 agent results (~150K chars of agent output alone)
14 6. The parent agent responds with "Prompt is too long" to every subsequent message
15 7. The session is permanently stuck — no way to recover
16
17 ## Observed Behavior
18
19 From the JSONL session log (4a5b2a9a-4416-41b5-ad5e-573db03dba2b.jsonl):
20
21 - 209 total messages in the session before crash
22 - Session log size: 6.2 MB
23 - 7 agent reports returned totaling 150,511 characters of output
24 - 8 consecutive "Prompt is too long" errors — one for each incoming agent notification, plus one extra
25 - The parent agent could not execute a single tool call or produce any meaningful response after the agents started returning
26 - The session became completely unresponsive
27
28 Timeline from the log:
29 ``
30 [Line 194] assistant: "Prompt is too long" ← First failure
31 [Line 195] user: <task-notification> Agent "Audit auth + infrastructure" completed (19,606 chars)
32 [Line 196] assistant: "Prompt is too long"
33 [Line 197] user: <task-notification> Agent "Audit tasks + projects + checklist" completed (21,383 chars)
34 [Line 198] assistant: "Prompt is too long"
35 [Line 199] user: <task-notification> Agent "Audit notes + tags module" completed (15,031 chars)
36 [Line 200] assistant: "Prompt is too long"
37 [Line 201] user: <task-notification> Agent "Audit medical module" completed (18,664 chars)
38 [Line 202] assistant: "Prompt is too long"
39 [Line 204] user: <task-notification> Agent "Audit hobbies + UI shell + today" completed (23,267 chars)
40 [Line 205] assistant: "Prompt is too long"
41 [Line 207] user: <task-notification> Agent "Audit finance module" completed (36,786 chars)
42 [Line 208] assistant: "Prompt is too long" ← Session permanently dead
43
`
44
45 Each incoming agent result made the problem worse, but the system kept delivering them with no backpressure.
46
47 ## Expected Behavior
48
49 Several things should happen instead:
50
51 1. **Prevent the overflow in the first place**: The Task tool / agent coordinator should track the parent's remaining context budget and either truncate or summarize agent results before injecting them into the parent's context. A 37K-char agent result does not need to be delivered verbatim — a summary with a pointer to the full output file would suffice.
52
53 2. **Graceful degradation when context is near-full**: When the parent is approaching context limits, it should be able to trigger compaction/summarization of older messages BEFORE the context is completely full, not after it's too late.
54
55 3. **Stop delivering messages to a dead session**: Once the parent hits "Prompt is too long", the system should not keep delivering more agent results that make the situation worse. There should be backpressure or circuit-breaking.
56
57 4. **Surface the error to the user**: The user saw nothing — the session just froze and crashed. There should be a clear error message like: "Session context limit reached. Agent results have been saved to [path]. Please start a new session."
58
59 5. **Auto-save results on crash**: Agent results that caused the overflow should be automatically written to disk (they already exist in the JSONL log, but are not surfaced). I was able to recover the data by manually parsing the JSONL, but most users would assume it's all lost.
60
61 ## Recovery (Manual)
62
63 The agent results were recoverable from the JSONL session log at:
64
`
65 ~/.claude/projects/-Users-treygoff-Code-goff-family-dashboard/4a5b2a9a-4416-41b5-ad5e-573db03dba2b.jsonl
66
`
67
68 By parsing the
<task-notification> / <result>` tags from user-type messages. But this required writing custom Python to extract them — there's no built-in recovery mechanism.
69
70 ## Environment
71
72 - Claude Code version: 2.1.32
73 - OS: macOS Darwin 25.2.0
74 - Model: claude-opus-4-6
75 - Session ID: 4a5b2a9a-4416-41b5-ad5e-573db03dba2b
76
77 ## Suggested Fixes (Priority Order)
78
79 1. Agent result size limits / summarization: Cap the size of results injected into the parent context. Write full results to a file and give the parent a summary + file path.
80 2. Context budget tracking: Before delivering agent results, check if they'll fit. If not, summarize or queue them.
81 3. Compaction trigger: When context usage exceeds ~80%, proactively compact older messages to make room.
82 4. Circuit breaker: After the first "Prompt is too long" error, stop delivering additional agent results and surface the error to the user with recovery instructions.
83 5. Crash recovery UX: On session restart, detect the previous crash and offer to show recovered agent outputs.
84
85 ## Impact
86
87 This is a high-severity UX bug for power users. The subagent pattern is one of Claude Code's most powerful features, and it's the recommended approach for large codebase audits. Having it silently crash with no recovery path when agents produce thorough results is extremely frustrating — it penalizes users for getting good results from their agents.

View original on GitHub ↗

12 Comments

github-actions[bot] · 6 months ago

Found 3 possible duplicate issues:

  1. https://github.com/anthropics/claude-code/issues/23448
  2. https://github.com/anthropics/claude-code/issues/17208
  3. https://github.com/anthropics/claude-code/issues/15191

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

gabrielbryk · 6 months ago

Experiencing this exact issue. When using multiple subagents (Task tool) — especially background agents spawned in parallel — the parent context fills up silently. Once it hits the limit, the session becomes completely unrecoverable: /compact no longer works, and the only option is to start a new conversation, losing all accumulated context.

Environment:

  • Claude Code CLI on Linux (Ubuntu 24.04)
  • Opus 4.6 model
  • Heavy use of Task tool with run_in_background: true for parallel agent work
  • Multiple MCP servers configured (adds to baseline context usage)

Reproduction pattern:

  1. Spawn 3-5 background agents via Task tool in a single message
  2. Agents return large results (codebase exploration, code review, etc.)
  3. Parent context balloons past the window limit
  4. /compact fails or has no meaningful effect
  5. Session is stuck — cannot send new messages or recover

This is a significant workflow blocker for anyone using the multi-agent pattern. Would love to see either:

  • Automatic truncation/summarization of subagent results before they're injected into parent context
  • A hard cap on how much context a subagent result can consume
  • Better /compact behavior that can actually recover from this state
Notum · 6 months ago

I can confirm this bug and currently working with claude code as an agenting development is just impossible.
Agents context window is shared between agents and main claude code context:

● Agent "Create Certifications migration+model" completed
⎿ Context limit reached · /compact or /clear to continue

● Agent "Add CRS org settings migration" completed
⎿ Context limit reached · /compact or /clear to continue

● Agent "Create CRS models and migration" completed
⎿ Context limit reached · /compact or /clear to continue

● Agent "Add Authorization access matrix" completed
⎿ Context limit reached · /compact or /clear to continue

● Agent "Auth routes, controller, sidebar" completed
⎿ Context limit reached · /compact or /clear to continue

This I got in same moment.

Caylub · 6 months ago

Related feature request: #27483 proposes a max_return_size parameter on the Task tool and task_notification_mode settings to give orchestrators proactive control over notification payload size — preventing the overflow described here rather than just recovering from it.

sstklen · 6 months ago

Hey! I ran into a similar pattern in our bug knowledge base and thought this might help.

What's happening: When multiple Task tool subagents complete in parallel, their full result payloads (15K-37K chars each) are injected as task-notification messages into the parent agent's context window. There is no size limit, truncation, or summarization applied to these results before injection. With 7+ parallel agents, the combined output (~150K+ chars) plus existing conversation history exceeds the parent's context window limit. Once exceeded, the system enters an unrecoverable 'Prompt is too long' loop — /compact cannot run because even the compaction prompt exceeds the limit, and there is no fallback mechanism to shed context or truncate notifications.

What worked for us:

Implement a multi-layer defense: (1) Add a max_return_size parameter to the Task tool that truncates agent results before injecting into parent context, (2) Auto-summarize large agent results using a fast model before returning to parent, (3) Add a context budget check before injecting task notifications — if the combined pending notifications would exceed X% of remaining context, summarize or queue them, (4) Make /compact work even when context is at the limit by operating on a sliding window rather than requiring the full context as input.

// Workaround for users TODAY (no code change needed):
// 1. Add explicit size limits in your Task tool prompts:
//    prompt: '...Keep your response under 3000 characters. Summarize findings as bullet points.'
// 2. Use run_in_background: true and check results individually via TaskOutput
//    instead of letting all notifications flood the parent at once
// 3. Use /compact proactively BEFORE agents complete
// 4. Spawn max 3 parallel agents instead of 7+
// 5. Chain agents sequentially with /compact between batches

// Proposed SDK-level fix (Task tool):
interface TaskParams {
  // ... existing params ...
  max_return_size?: number;        // default 8000, truncate result
  notification_mode?: 'full' | 'summary' | 'file';  // default 'summary' when >3 parallel
}

// Before injecting task result into parent context:
function injectTaskResult(result: string, params: TaskParams, contextBudget: number): string {
  const maxSize = params.max_return_size ?? 8000;
  const mode = params.notification_mode ?? (activeParallelAgents > 3 ? 'summary' : 'full');
  
  if (mode === 'file') {
    const path = writeToTempFile(result);
    return `Agent completed. Full results written to: ${path}`;
  }
  
  if (result.length > maxSize || result.length > contextBudget * 0.3) {
    return summarizeWithHaiku(result, maxSize);
  }
  
  return result;
}

Hope this helps! Let me know if it doesn't match your case — happy to dig deeper. 🦞

_Disclosure: This analysis is from Confucius Debug, an AI-powered community KB for agent bugs. Please verify before applying._

---
<sub>🦞 Confucius Debug — community knowledge base for AI agent bugs. Free to search via MCP.</sub>

blwfish · 6 months ago

Adding another reproduction case that doesn't involve 7 parallel agents — this happened with a single Explore subagent in a short session.

Setup: Working in a monorepo subdirectory (speed-cal/). The system prompt is large due to chained CLAUDE.md files (project + monorepo + parent directory) plus MCP tool schemas (KiCad ~50 tools, Blender ~10 tools, FreeCAD ~15 tools, Chrome ~20 tools).

Task: Split an 80KB monolithic HTML file into 3 pages. Straightforward refactoring.

What happened:

  1. Spawned one Explore subagent to analyze the 2081-line original file structure
  2. Agent returned a detailed structural outline (~5KB of text)
  3. Started writing the first of three output files
  4. Session died with "The model has reached its context window limit. Prompt is too long" after writing only the first page

Key factors:

  • The 80KB HTML file is only ~20-25K tokens — well within the 200K Opus window
  • The session was very short (maybe 6-8 turns total)
  • The large system prompt (MCP schemas + CLAUDE.md chain) likely consumed a significant baseline chunk
  • Auto-compaction never triggered despite approaching the limit

This suggests the issue isn't limited to parallel agent floods — even a single agent result combined with a heavy system prompt can tip the balance, and compaction doesn't intervene proactively.

sstklen · 6 months ago

Hey! I ran into a similar pattern in our bug knowledge base and thought this might help.

What's happening: When multiple Task tool subagents complete in parallel, their full result payloads (15K-37K chars each) are injected as task-notification messages into the parent agent's context window. There is no size limit, truncation, or summarization applied to these results before injection. With 7+ parallel agents, the combined output (~150K+ chars) plus existing conversation history exceeds the parent's context window limit. Once exceeded, the system enters an unrecoverable 'Prompt is too long' loop — /compact cannot run because even the compaction prompt exceeds the limit, and there is no fallback mechanism to shed context or truncate notifications.

What worked for us:

The proposed fix is good in principle. To make it more concrete and actionable for a developer, the injectTaskResult function, TaskParams interface, and the summarizeWithHaiku and writeToTempFile helper functions would need to be integrated into the actual SDK code. This would involve identifying the specific files and methods responsible for handling subagent task results and injecting them into the parent agent's context. The activeParallelAgents variable also needs to be sourced from the runtime context.

// Workaround for users TODAY (no code change needed):
// 1. Add explicit size limits in your Task tool prompts:
//    prompt: '...Keep your response under 3000 characters. Summarize findings as bullet points.'
// 2. Use run_in_background: true and check results individually via TaskOutput
//    instead of letting all notifications flood the parent at once
// 3. Use /compact proactively BEFORE agents complete
// 4. Spawn max 3 parallel agents instead of 7+
// 5. Chain agents sequentially with /compact between batches

// Proposed SDK-level fix (Task tool):
interface TaskParams {
  // ... existing params ...
  max_return_size?: number;        // default 8000, truncate result
  notification_mode?: 'full' | 'summary' | 'file';  // default 'summary' when >3 parallel
}

// Before injecting task result into parent context:
function injectTaskResult(result: string, params: TaskParams, contextBudget: number): string {
  const maxSize = params.max_return_size ?? 8000;
  const mode = params.notification_mode ?? (activeParallelAgents > 3 ? 'summary' : 'full');
  
  if (mode === 'file') {
    const path = writeToTempFile(result);
    return `Agent completed. Full results written to: ${path}`;
  }
  
  if (result.length > maxSize || result.length > contextBudget * 0.3) {
    return summarizeWithHaiku(result, maxSize);
  }
  
  return result;
}

📊 _We found 5 similar cases in our knowledge base with the same pattern — this gives us high confidence in this analysis._

Let me know if this works for your setup — happy to help troubleshoot further. 🦞

_Disclosure: This analysis is from Confucius Debug, an AI-powered community KB for agent bugs. Please verify before applying._

---
<sub>🦞 Confucius Debug — community knowledge base for AI agent bugs. Free to search via MCP.</sub>

m13v · 5 months ago

We hit this exact issue running parallel subagents that each returned large file diffs. A few mitigations that helped:

  1. Truncate subagent output - in your Task tool prompt, explicitly tell the subagent to return only a summary (e.g. "respond with at most 500 words summarizing what you changed") rather than echoing back full file contents.
  1. Limit parallel subagent count - with 4+ subagents completing around the same time, the combined results can easily exceed 100k tokens. We cap at 2-3 parallel subagents for complex tasks.
  1. Sequential with compaction - for tasks that generate a lot of output, run subagents sequentially so the parent can compact between results.
  1. Check result size before returning - if building custom tooling around Claude Code, you can add a middleware that truncates tool results above a threshold before they hit the parent context.

The root cause is that subagent results are injected into the parent context as tool results with no size cap. A built-in mechanism to automatically summarize or truncate large tool results would fix this at the framework level.

m13v · 5 months ago

We orchestrate parallel subagents with tmux and manage output sizes carefully - documented our patterns here: https://github.com/m13v/tmux-background-agents/blob/main/SKILL.md

More on how we handle multi-agent sessions: https://fazm.ai/gh

junaidtitan · 5 months ago

Hit this exact pattern — multiple subagent results flooding back into the parent. Built cozempic specifically for this. The guard daemon runs in the background, watches the session JSONL, and prunes it before the next agent result lands.

pip install cozempic
cozempic init   # installs hooks

Guard mode checkpoints team state every 30s and prunes proactively. Won't help once you're already in the "Prompt is too long" loop, but prevents getting there. Works well in advance if you know you're spawning agents that return large payloads.

Happy to hear if it helps.

github-actions[bot] · 4 months ago

Closing for now — inactive for too long. Please open a new issue if this is still relevant.

github-actions[bot] · 4 months ago

This issue has been automatically locked since it was closed and has not had any activity for 7 days. If you're experiencing a similar issue, please file a new issue and reference this one if it's relevant.