[BUG] Agent processes only first notification when multiple background tasks complete in parallel, remaining notifications queued indefinitely
Preflight Checklist
- [x] I have searched existing issues and this hasn't been reported yet
- [x] This is a single bug report (please file separate reports for different bugs)
- [x] I am using the latest version of Claude Code
What's Wrong?
Environment
- Platform: Windows (WSL2)
- Claude Code Version: v2.1.20
- Model: Claude Sonnet 4.5
- Terminal: [Your terminal]
- Task Tool:
Taskwithrun_in_background=true - Context: Multi-round batch processing workflow
---
Summary
When multiple background tasks (launched with run_in_background=true) complete within a short time window (~3 minutes), the main agent only processes the first completion notification. Subsequent notifications are delivered to the UI (visible in logs) but remain unprocessed by the agent, causing the session to hang at "0 tokens" until manual interrupt (ESC).
Critical Pattern: This issue occurs specifically when tasks complete in parallel/near-simultaneously, not when they complete sequentially with longer intervals.
---
Steps to Reproduce
Scenario: Multi-Agent Batch Processing
- Launch multiple background tasks in parallel (5 tasks):
```python
task_ids = []
for i in range(1, 6): # Tasks 1-5
task = Task(
description=f"Background Task {i}",
subagent_type="general-purpose",
run_in_background=True,
prompt=f"""Process data batch {i}..."""
)
task_ids.append(task.agent_id)
print("✅ Batch launched (5 background tasks)")
print("Waiting for completion...")
```
- Wait for tasks to complete:
- All 5 tasks complete within 3 minutes
- Completion order: Task 3 → 2 → 5 → 4 → 1
- Observe notification processing:
- ✅ First notification (Task 3): Processed successfully
- ❌ Remaining notifications (2, 5, 4, 1): Displayed but NOT processed
- Agent shows:
✻ Processing... (esc to interrupt · 2m 5s · ↓ 0 tokens) - Session hangs with "0 tokens" for 2+ minutes
- User presses ESC:
- Notification queue releases, showing:
````
● Agent "Background Task 2" completed
● Agent "Background Task 4" completed
● Agent "Background Task 1" completed
- Task 5 notification missing entirely
---
Expected Behavior
- All 5 background tasks complete
- Agent receives 5 completion notifications
- Agent processes each notification sequentially or in batch
- Agent acknowledges all 5 completions:
````
✅ Task 3 completed successfully
✅ Task 2 completed successfully
✅ Task 5 completed successfully
✅ Task 4 completed successfully
✅ Task 1 completed successfully
- Agent continues to next phase automatically
---
Actual Behavior
- All 5 background tasks complete ✅
- Agent receives 5 completion notifications ✅
- Agent processes ONLY first notification ❌
- Agent acknowledges Task 3 only:
````
✅ Task 3 completed successfully
Progress: 1/5 completed, waiting for others...
- Agent hangs with "↓ 0 tokens" ❌
- Remaining notifications (2, 4, 1) visible in UI but unprocessed ❌
- Task 5 notification completely missing ❌
- Requires manual ESC interrupt to continue ❌
---
Log Evidence
Initial Task Launch
● 5 Task agents launched (ctrl+o to expand)
├─ Background Task 1
│ ⎿ Running in the background (↓ to manage)
├─ Background Task 2
│ ⎿ Running in the background (↓ to manage)
├─ Background Task 3
│ ⎿ Running in the background (↓ to manage)
├─ Background Task 4
│ ⎿ Running in the background (↓ to manage)
└─ Background Task 5
⎿ Running in the background (↓ to manage)
● ✅ Batch launched (5 background tasks)
Waiting for completion...
First Notification Processed (Task 3)
✻ Baked for 43s
● Agent "Background Task 3" completed
● ✅ Task 3 completed successfully
Progress: 1/5 completed, waiting for others...
Agent Hangs (No Further Processing)
✶ Processing batch... (esc to interrupt · ctrl+t to show todos · 2m 5s · ↓ 0 tokens)
⎿ Next: Validation phase
Key Observation: "↓ 0 tokens" indicates agent is not reasoning/processing
After ESC Interrupt (Notification Queue Released)
● Agent "Background Task 2" completed
● Agent "Background Task 4" completed
● Agent "Background Task 1" completed
Missing: Task 5 notification never appeared, even after ESC
---
Verification: All Tasks Actually Completed
Verified by checking output files:
| Task | Completion Time (UTC) | File Modified | Status |
|------|----------------------|---------------|--------|
| 3 | 2026-01-27 09:31:01 | 09:31:01 | ✅ Completed |
| 2 | 2026-01-27 09:31:19 | 09:31:19 | ✅ Completed |
| 5 | 2026-01-27 09:31:21 | 09:31:08 | ✅ Completed |
| 4 | 2026-01-27 09:32:27 | 09:32:27 | ✅ Completed |
| 1 | 2026-01-27 09:33:17 | 09:33:17 | ✅ Completed |
Actual completion order: 3 → 2 → 5 → 4 → 1 (all within 2 minutes 16 seconds)
Conclusion: All 5 tasks completed successfully and generated valid outputs, proving the issue is purely notification processing failure, not task execution failure.
---
Comparison: Successful Batch 1 vs Failed Batch 2
Batch 1 (Tasks A-E): ✅ Success
- All 5 agents launched
- All 5 completion notifications processed sequentially
- No hang, no manual intervention required
- Total time: ~6 minutes
Batch 2 (Tasks 1-5): ❌ Failed
- All 5 agents launched
- Only 1st completion notification (Task 3) processed
- 4 notifications queued/lost (2, 5, 4, 1)
- Session hung at "0 tokens" for 2+ minutes
- Required ESC to continue
Critical Difference: Both batches used identical code pattern, but Batch 2 tasks completed within a much shorter time window (2m 16s vs likely longer in Batch 1), suggesting parallel/rapid completion triggers the bug.
---
Related Issues
This bug shares symptoms with but differs from:
- Similar: #20336 - Claude hangs in "Caramelizing" state after background task completion
- Difference: #20336 shows "0 tokens" with NO notifications processed; this issue processes first notification then hangs
- Similar: #19195 - Background task queue operations cause session hang
- Difference: #19195 is about dequeue race condition after timeout; this is about notification processing during normal completion
- Related: #17157 - Background process completion causes UI state corruption
- Status: Fixed in v2.1.4 (ESC key issue)
- Difference: This issue occurs even when ESC is not pressed initially; ESC is needed as workaround
- Related: #6854 - Feature request for background task completion notifications
- Status: Closed (Not Planned)
- Note: Notifications ARE being delivered (visible in UI), but not processed by agent
---
Root Cause Hypothesis
Based on the pattern, possible causes include:
Hypothesis 1: Notification Queue Overflow
- When multiple notifications arrive within a short window, queue may have capacity limits
- First notification processed, subsequent ones overflow or are dropped
- Explains Task 5 being completely missing
Hypothesis 2: Agent State Machine Issue
- Processing first notification transitions agent to a state incompatible with receiving more notifications
- Agent expects only one completion event per waiting cycle
- Subsequent notifications delivered to UI but not to agent's processing queue
Hypothesis 3: Race Condition in Event Handling
- Multiple near-simultaneous completion events create race condition
- Event handler processes first event, locks/blocks subsequent events
- ESC interrupt resets the handler, releasing queued events
---
Impact Assessment
Severity: High
Affected Use Cases:
- ✅ Multi-agent parallel processing (primary use case)
- ✅ Batch operations with >1 background task
- ✅ Any workflow where task completion order is non-deterministic
- ✅ Large-scale processing pipelines requiring parallel execution
User Impact:
- 🔴 Productivity Loss: Manual polling instead of automatic processing
- 🔴 Unreliable Execution: Cannot trust agent to handle parallel tasks
- 🔴 Data Loss Risk: Some notifications completely missing
- 🔴 Manual Intervention Required: Must press ESC to unstick agent
- 🔴 Scalability Blocker: Cannot scale to larger batch sizes reliably
Business Impact:
- Undermines Claude Code's multi-agent architecture value proposition
- Forces workarounds like serial execution (defeats parallelism purpose)
- Reduces user confidence in background task reliability
---
Current Workarounds
Workaround 1: Serial Execution (Defeats Purpose)
for i in range(1, 6):
# Don't use run_in_background - wait for each task
task = Task(description=f"Task {i}", run_in_background=False)
result = task.wait()
print(f"✅ Task {i} completed")
Limitation: Loses all parallelism, 5x slower execution time
Workaround 2: Manual Polling with File System Checks
task_ids = [launch 5 tasks...]
completed = []
while len(completed) < 5:
for i in range(1, 6):
if i not in completed and check_output_file_exists(i):
completed.append(i)
print(f"✅ Task {i} completed")
time.sleep(180) # Poll every 3 minutes
Limitation: Wastes tokens, requires manual ESC when hung
Workaround 3: Small Batch Sizes with Delays
# Launch only 2-3 tasks per batch
# Add artificial delays between launches
Limitation: Reduces parallelism benefits, increases total execution time
---
Suggested Investigation Areas
For Claude Code developers to investigate:
- Notification Queue Implementation:
- Check for capacity limits (seems to be ~4 notifications?)
- Add logging for enqueue/dequeue operations
- Verify queue behavior under rapid concurrent events
- Agent State Transitions:
- Log agent state after processing first notification
- Verify whether agent remains in "notification-aware" state
- Check if response without tool calls affects state
- Event Handler Locking:
- Check for mutex/lock contention in notification handler
- Verify event handler can process multiple events consecutively
- Test with rapid-fire notifications (< 1s apart)
- TaskOutput Behavior:
- Verify behavior when NOT using explicit TaskOutput calls
- Test implicit notification delivery vs explicit polling
- Document expected pattern for multi-task scenarios
---
Minimal Reproduction Example
# Simple reproduction case
from anthropic import Task
import time
def reproduce_bug():
"""
Launches 5 fast-completing background tasks.
Expected: All 5 notifications processed
Actual: Only first notification processed, others queued
"""
task_ids = []
# Launch 5 background tasks
for i in range(1, 6):
task = Task(
description=f"Quick Task {i}",
subagent_type="general-purpose",
run_in_background=True,
prompt=f"""
Execute a simple task that completes in ~30 seconds.
Task ID: {i}
Just create a small output file and exit.
"""
)
task_ids.append(task.agent_id)
print(f"✅ Launched {len(task_ids)} background tasks")
print("Waiting for completions...")
# Expected: Agent automatically processes all 5 completion notifications
# Actual: Agent processes only first, hangs at "0 tokens"
# User must press ESC to see queued notifications
if __name__ == "__main__":
reproduce_bug()
---
Additional Context
Production Context: This issue was discovered during execution of a large-scale batch processing pipeline, handling multiple independent tasks across multiple rounds (5 tasks per round). The issue occurred consistently when tasks completed within a short time window, blocking the entire pipeline.
User Expectation: The multi-agent parallel execution is a core feature of Claude Code. Users expect that launching N background tasks should result in N completion notifications being processed automatically, without manual intervention.
---
System Information
OS: Linux 5.10.16.3-microsoft-standard-WSL2 (WSL2)
Claude Code Version: [run: claude --version]
Python Version: [if applicable]
Node Version: [if applicable]
Terminal: [your terminal]
---
Labels Suggested
bugarea:corearea:toolshas reproseverity:highplatform:windowsplatform:linux(WSL2)
---
Reporter: [Your GitHub username]
Date: 2026-01-27
---
Questions for Maintainers
- Is there a documented pattern for waiting on multiple background tasks?
- Are there known limits on notification queue capacity?
- Should users explicitly call
TaskOutputfor each task, or rely on automatic notification delivery? - Is the behavior (processing only first notification) intentional as a rate-limiting mechanism?
---
Thank you for your attention to this issue. Happy to provide additional information or testing as needed.
What Should Happen?
- All 5 background tasks complete
- Agent receives 5 completion notifications
- Agent processes each notification sequentially or in batch
- Agent acknowledges all 5 completions:
````
✅ Task 3 completed successfully
✅ Task 2 completed successfully
✅ Task 5 completed successfully
✅ Task 4 completed successfully
✅ Task 1 completed successfully
- Agent continues to next phase automatically
Error Messages/Logs
## Log Evidence
### Initial Task Launch
● 5 Task agents launched (ctrl+o to expand)
├─ Background Task 1
│ ⎿ Running in the background (↓ to manage)
├─ Background Task 2
│ ⎿ Running in the background (↓ to manage)
├─ Background Task 3
│ ⎿ Running in the background (↓ to manage)
├─ Background Task 4
│ ⎿ Running in the background (↓ to manage)
└─ Background Task 5
⎿ Running in the background (↓ to manage)
● ✅ Batch launched (5 background tasks)
Waiting for completion...
### First Notification Processed (Task 3)
✻ Baked for 43s
● Agent "Background Task 3" completed
● ✅ Task 3 completed successfully
Progress: 1/5 completed, waiting for others...
### Agent Hangs (No Further Processing)
✶ Processing batch... (esc to interrupt · ctrl+t to show todos · 2m 5s · ↓ 0 tokens)
⎿ Next: Validation phase
**Key Observation**: "↓ 0 tokens" indicates agent is not reasoning/processing
### After ESC Interrupt (Notification Queue Released)
● Agent "Background Task 2" completed
● Agent "Background Task 4" completed
● Agent "Background Task 1" completed
**Missing**: Task 5 notification never appeared, even after ESC
Steps to Reproduce
Scenario: Multi-Agent Batch Processing
- Launch multiple background tasks in parallel (5 tasks):
```python
task_ids = []
for i in range(1, 6): # Tasks 1-5
task = Task(
description=f"Background Task {i}",
subagent_type="general-purpose",
run_in_background=True,
prompt=f"""Process data batch {i}..."""
)
task_ids.append(task.agent_id)
print("✅ Batch launched (5 background tasks)")
print("Waiting for completion...")
```
- Wait for tasks to complete:
- All 5 tasks complete within 3 minutes
- Completion order: Task 3 → 2 → 5 → 4 → 1
- Observe notification processing:
- ✅ First notification (Task 3): Processed successfully
- ❌ Remaining notifications (2, 5, 4, 1): Displayed but NOT processed
- Agent shows:
✻ Processing... (esc to interrupt · 2m 5s · ↓ 0 tokens) - Session hangs with "0 tokens" for 2+ minutes
- User presses ESC:
- Notification queue releases, showing:
````
● Agent "Background Task 2" completed
● Agent "Background Task 4" completed
● Agent "Background Task 1" completed
- Task 5 notification missing entirely
Claude Model
Sonnet (default)
Is this a regression?
Yes, this worked in a previous version
Last Working Version
_No response_
Claude Code Version
2.1.20
Platform
AWS Bedrock
Operating System
Ubuntu/Debian Linux
Terminal/Shell
Terminal.app (macOS)
Additional Information
_No response_
This issue has 3 comments on GitHub. Read the full discussion on GitHub ↗