Skip to content

bug: drain_reader_threads t.join(30) deadlocks asyncio event loop permanently when reader thread is stuck #657

Closed

Description

@vybe

Summary

When drain_reader_threads() is called after a claude process exits and the reader thread is permanently stuck (pipe held open by an orphan MCP subprocess), t.join(timeout=30) blocks the asyncio event loop thread indefinitely. The 30-second timeout is never enforced because Thread.join() is a synchronous blocking call — it does not yield control back to the event loop. The agent-server becomes completely unresponsive: all HTTP requests time out, health checks fail, the circuit breaker opens, and recovery requires a manual container restart.

Component

Agent Runtime — docker/base-image/agent_server/utils/subprocess_pgroup.py

Priority

P1 — agent-server completely down; workaround is manual docker restart, ~20–25 min downtime per incident

Evidence (from agent-server logs)

# Drain warning fires — process group killed, 30s wait begins:
WARNING: [Subprocess] Reader thread(s) still busy after process exit
         (pid=XXXX, stuck_count=1) — killing process group, then waiting 30s for natural drain

# [NO FURTHER LOG OUTPUT — force-close message never fires]
# [Agent-server HTTP endpoint becomes unresponsive within seconds]
# [Circuit breaker accumulates 40+ failures over 20+ minutes]
# [Container CPU stays at 140–180% from stuck reader thread]

When the asyncio event loop is NOT blocked (clean path):

WARNING: [Subprocess] Reader thread(s) still busy after process exit (pid=XXXX) — killing...
ERROR:   [Subprocess] Reader thread(s) still stuck after 30s post-kill grace — force-closing pipes
ERROR:   [Subprocess] 1 reader thread(s) leaked for pid=XXXX after force-close; continuing anyway
INFO:    [ProcessRegistry] Unregistered execution XXXX

The second sequence takes ~41 seconds. The deadlock variant produces only the WARNING line, then silence indefinitely.

Location

  • File: docker/base-image/agent_server/utils/subprocess_pgroup.py
  • Function: drain_reader_threads (or caller that invokes t.join(timeout=30))
  • Trigger: called from async context after process group kill when MCP subprocess survives kill

Root Cause

Thread.join(timeout=30) is a synchronous blocking call. When invoked directly from the asyncio event loop thread (inside a coroutine or async function), it blocks the event loop for the full timeout duration — or permanently if the thread never exits. An orphan MCP subprocess that called setsid() (creating a new process group) survives terminate_process_group() and continues holding the write end of the stdout pipe open. The reader thread spinning on that pipe never sees EOF. The t.join(timeout=30) call therefore blocks the asyncio event loop thread forever, preventing all other async work including HTTP request handling, health checks, and cleanup.

This bug is conditional: it fires when the orphan subprocess is CPU-heavy enough that the asyncio event loop doesn't get scheduled to even reach the t.join timeout check. In practice it fires reliably when the orphan is running at 140%+ CPU.

Reproduction Steps

  1. Configure an agent that uses an MCP server which calls setsid() on startup (e.g. any Node.js-based MCP server — node's child_process typically calls setsid)
  2. Run an execution that causes the MCP server to spawn child processes or hold the stdout pipe write-end open
  3. Let the claude process exit
  4. Observe agent-server logs: the drain WARNING fires once, then silence
  5. Attempt curl -m 5 http://localhost:8000/health on the agent container — times out
  6. Observe container CPU at 140–180% from the stuck reader thread spinning in agent-server.py

Suggested Fix

Replace the synchronous t.join() call with one that runs off the event loop thread:

# CURRENT — blocks event loop thread permanently if reader thread is stuck:
t.join(timeout=30)
if t.is_alive():
    # force-close — never reached when deadlocked

# FIX A — run_in_executor (Python 3.7+):
import asyncio
loop = asyncio.get_event_loop()
await loop.run_in_executor(None, lambda: t.join(timeout=30))
if t.is_alive():
    # force-close pipes here

# FIX B — asyncio.to_thread (Python 3.9+, cleaner):
await asyncio.to_thread(t.join, 30)
if t.is_alive():
    # force-close pipes here

Either fix ensures the 30-second timeout enforces regardless of what the reader thread or orphan subprocesses are doing, and the event loop remains responsive throughout.

Environment

  • Trinity version: 64e19aa (fix(agent-runtime): bound _kill_orphan_pipe_writers to 10s)
  • Agent runtime: Claude Code (headless --print mode)
  • OS: Ubuntu 22.04 (agent base image)

Related

Activity

  1. vybe commented on May 5, 2026

    @vybe
    ContributorAuthor

    /claim

  2. added
    status-in-progress
    on May 5, 2026
  3. github-actions commented on May 5, 2026

    @github-actions

    Claimed by @vybe. Label status-in-progress added.

    Next steps:

    1. Create branch: feature/657-<short-slug>
    2. Implement the feature
    3. Open a PR with Fixes #657
  4. added
    status-in-dev
    and removed
    status-in-progress
    on May 5, 2026
  5. removed
    status-in-dev
    on May 5, 2026
  6. added
    status-in-progress
    on May 14, 2026
  7. self-assigned this
    on May 14, 2026
  8. dolho commented on May 14, 2026

    @dolho
    Contributor

    Picked this up — turns out the fix is already in dev. Commit d7cc9580 ("fix(agent-server): make drain_reader_threads async to prevent event-loop deadlock (#657)") landed 2026-05-05 and exactly matches the suggested-fix from the issue body: drain_reader_threads() is async, every t.join() is wrapped in await asyncio.wait_for(asyncio.to_thread(t.join, …), timeout=…+1) so the deadline is enforced at the event-loop level even under CPU pressure from orphan subprocesses. Docstring at lines 510–516 explicitly references this issue.

    Closing as done. Reopen if there's a remaining edge case I missed.

  9. added
    status-in-dev
    and removed
    status-in-progress
    on May 14, 2026
  10. removed their assignment
    on May 14, 2026
  11. reopened this on May 14, 2026
  12. dolho commented on May 14, 2026

    @dolho
    Contributor

    Correction on the earlier comment — premature close. Fix d7cc9580 is merged to dev only, not yet to main. Reopening + relabeling status-in-dev per the team rule that issues close only on main merge (i.e. at release cut).

  13. vybe commented on Jun 1, 2026

    @vybe
    ContributorAuthor

    Shipped in v0.6.0 (released via #998).

  14. added
    complexity-low
    theme-reliability
    and removed
    status-in-dev
    on Jun 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

complexity-lowpriority-p1theme-reliabilitytype-bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions