Repository navigation
Description
Summary
When an agent's headless task spawns grandchild processes (stdio MCP servers, hooks, subagents) that keep the stdout pipe FD open after the parent Claude process exits, the executor's stdout reader thread blocks indefinitely on readline(). The drain helper's force-close fallback does not unblock the thread, marks it outcome=leaked, and the leaked thread holds the executor worker — so _run_headless_subprocess never returns. The outer asyncio.wait_for(timeout=effective_timeout+60) is what eventually fires, causing every affected scheduled execution to consume its full timeout budget (commonly 7200s) even though Claude finished within seconds. From the platform's view this looks like a 2-hour execution; in reality no work is happening.
Component
Backend / Agent Runtime — agent_server.utils.subprocess_pgroup._drain_bounded + agent_server.services.headless_executor._run_headless_subprocess
Priority
P1 — major scheduling impact (slot saturation, false 2h timeouts, backend HTTP timeouts), but a configuration workaround exists.
Evidence
On one agent's container over ~47h uptime, drain outcomes were:
| outcome | count |
|---|---|
| natural | 10 |
| force_close | 3 |
| leaked | 24 |
drain_elapsed_ms on the leaked outcomes ranged from ~59,000 ms up to ~4,441,000 ms (≈74 min). Every leaked drain corresponded one-to-one to a scheduled execution that the platform marked failed: Task execution timed out after 7200 seconds — i.e. the agent's HTTP response never came back.
Sample log sequence from one affected execution:
INFO [Headless Task] Starting task X: claude --print --output-format stream-json --verbose...
INFO [Headless Task] Permission mode confirmed: bypassPermissions
WARN [Subprocess] Reader thread(s) still busy after process exit (pid=X, stuck_count=1) — killing process group, then waiting 30s for natural drain
ERROR [Subprocess] Reader thread(s) still stuck after 349.3s post-kill grace — force-closing pipes; some buffered data may be lost (pid=X, stuck_count=1)
ERROR [Subprocess] 1 reader thread(s) leaked for pid=X after force-close; continuing anyway
INFO [METRIC] drain_outcome pid=X pgid=X orphan_kill_count=0 outcome=leaked drain_elapsed_ms=4247022 stuck_initial=1 leaked_count=1
The expected [Headless Task] Task X completed: cost=... log line never fires, because _run_headless_subprocess never returns to _finalize_headless_result.
On the backend side, the corresponding execution log reads:
INFO [TaskExecService] Calling agent [AGENT] /api/task (timeout=7210.0s, ...)
... 7210s later ...
ERROR [TaskExecService] TIMEOUT on [AGENT] after 7210s (limit=7200s)
WARN [TaskExecService] Terminate timed out for execution X on agent '[AGENT]' — watchdog will clean up
The terminate call also times out — the agent is unresponsive on that execution's path while the leaked reader thread is wedged.
Location
- File:
agent_server/utils/subprocess_pgroup.py - Function:
_drain_bounded - Approximate lines: 230–340 (force-close fallback)
- Also:
agent_server/services/headless_executor.py:_run_headless_subprocess(outer orchestrator that blocks while the daemon reader thread leaks)
Root cause hypothesis
After safe_close_pipes(process) runs, the daemon reader thread's process.stdout.readline() should EOF — but on this agent it doesn't. Two suspects:
- Pipe-holder grandchild not in scope of the cgroup sweep. Some stdio-launched MCP server (or a
claudetool subagent that spawned its own process in a new session) holds the write-end of the pipe and is not caught bykill_cgroup_orphans().safe_close_pipesonly closes the parent's FD; the grandchild's FD keeps the write-end live, so the read end never sees EOF. readline()wedged in an uninterruptible syscall. Even after FDs are closed parent-side, the thread is stuck inread()and only the kernel can unblock it, which won't happen until every duplicate write-end is closed.
A secondary observation: the warning advertises a 30-second post-kill natural-drain budget, but the subsequent "force-closing pipes" error fires at 349.3s post-kill grace — so the natural-drain phase is itself over-running its budget by ~10×. drain_elapsed_ms then climbs further to ~4.2M ms before the metric is emitted, meaning the post-force-close join(2) calls (or something else in the path) are also blocking instead of returning. So even the bounded-grace assumption embedded in the helper is not holding.
Reproduction
- Deploy an agent that uses stdio-based MCP servers and/or skills that fork subagents/tool processes.
- Configure scheduled tasks with
timeout_seconds=7200. - Run the schedules repeatedly for several hours.
- Observe in the agent container's logs:
Reader thread(s) still busy after process exit, thenReader thread(s) still stuck … force-closing pipes, thenoutcome=leaked. - Observe the corresponding executions in the platform marked
failed: Task execution timed out after 7200 seconds, with duration_ms ≈ 7,215,000. - Observe slot-leak symptoms: schedules failing with
Agent at capacity (N/N parallel tasks running)even though no real parallel work is in flight.
Suggested fix direction
Two angles, in priority order:
- Decouple the orchestrator from the leaked reader thread (high-impact). When
_drain_boundedreturns withoutcome=leaked,_run_headless_subprocessshould still return to_finalize_headless_resultpromptly — using whatever raw messages were buffered before the wedge — instead of blocking on the leaked thread. The daemon reader is already declared expendable ("continuing anyway"); the orchestrator should match that contract. This bounds the platform-visible hang to the drain budget (~tens of seconds) rather than the full task timeout (~2h). - Wider pipe-holder discovery (root cause). When force-close still leaves a stuck reader, fall back to
lsof//proc/*/fdenumeration to find the actual processes holding the pipe write-end and SIGKILL them by PID. The current cgroup-only sweep misses MCP servers launched into a fresh session.
Either fix individually would resolve the 2h false-timeout class of failure. (1) is faster to ship and contains the blast radius even if (2) misses an edge case.
Workaround (current ops procedure)
- Reduce per-schedule
timeout_secondsfrom 7200 → e.g. 600s, so the false-timeout window collapses from 2h to 10 min and slots free up sooner. The leak still occurs. - Restart affected agent containers periodically to drop accumulated leaked daemon threads.
Environment
- Trinity commit:
33023f51 - Python 3.11
- Linux containers, Docker
- Affected: agents with stdio MCP servers and/or skills that fan out to subagents.
Related
agent_server/services/headless_executor.py—_run_headless_subprocess,_finalize_headless_resultagent_server/utils/subprocess_pgroup.py—_drain_bounded,safe_close_pipes,kill_cgroup_orphans- Prior work referenced in nearby comments: bug: expired subscription token causes hour-long zombie executions instead of fast failure #285, bug: agent-server.py spins at ~83% CPU after claude CLI subprocess becomes defunct #407, bug: dropped MCP sync connection causes broken pipe that trips circuit breaker #474, bug: stdout reader thread stuck 35s after process exit when hook subprocess escapes process group kill #586, bug(agent-runtime): npx MCP server subprocesses outside claude pgid hold stdout pipe open — reader stuck after #531 grace period #618, bug: stdio MCP subprocess stdout inheritance causes 'Execution completed without a result message' #630, fix(agent-runtime): prevent MCP stdio servers from polluting Claude's inherited stdout (#630 follow-up) #640, bug: agent-server.py spins at 90% CPU on OAuth token auth failure, blocking CB recovery #728, bug: Runaway subprocess after task failure makes agent-server unresponsive, triggering persistent CB cascade #817
Activity
docs(feature-flows): document #970 headless drain decoupling
fix(agent): bound headless wait on result + tool stall (#970) (#973)
vybe commentedon Jun 2, 2026
Fixed by #973 (squash-merged to
devas b4c5bfd).Root cause was not the reader-thread leak named in the title — that's a symptom emitted by post-timeout cleanup. The 2h was burned in
process.wait(timeout=effective_timeout)(headless_executor.py:588): the executor finalized on process exit rather than on claude's{"type":"result"}message, so when a stdio MCP child lingered in teardown (or a hung MCPtools/callkept claude alive — Claude Code has no per-MCP-tool timeout), the full budget burned on already-complete work. The drain was already 90s-bounded and reader-decoupled (#728), so the suggested 'decouple from leaked reader' / lsof-/procdirections wouldn't have helped.#973 replaces the blocking wait with a poll loop: early-completion on the
resultmessage (force return_code=0; genuine errors still surface viametadata.error_typeahead of the return_code check) + a >300s stalled-tool watchdog. The competing PR #980 was closed as superseded; its orthogonal hardening (drain exception capture, finalize snapshot isolation) is tracked in #1025. Ships tomainon next release.fix(test): make #1094 stall test self-contained (CI collection error)
fix(agent-server): distinct error for stall-watchdog kill vs max-dura…
fix(headless): harden drain/finalize against leaked reader threads (#…
fix(headless): harden drain/finalize against leaked reader threads (#…
fix(agent): scope headless stall-watchdog to mcp__ + configurable lim…
fix(agent-runtime): make AGENT_IDLE_FINALIZE_S actually settable (#2127)
fix(agent-runtime): stop killing a fan-out turn mid-wait and calling …