Skip to content

bug: headless_executor reader thread leak causes 2h execution hangs #970

Closed

Description

@vybe

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:

  1. Pipe-holder grandchild not in scope of the cgroup sweep. Some stdio-launched MCP server (or a claude tool subagent that spawned its own process in a new session) holds the write-end of the pipe and is not caught by kill_cgroup_orphans(). safe_close_pipes only closes the parent's FD; the grandchild's FD keeps the write-end live, so the read end never sees EOF.
  2. readline() wedged in an uninterruptible syscall. Even after FDs are closed parent-side, the thread is stuck in read() 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

  1. Deploy an agent that uses stdio-based MCP servers and/or skills that fork subagents/tool processes.
  2. Configure scheduled tasks with timeout_seconds=7200.
  3. Run the schedules repeatedly for several hours.
  4. Observe in the agent container's logs: Reader thread(s) still busy after process exit, then Reader thread(s) still stuck … force-closing pipes, then outcome=leaked.
  5. Observe the corresponding executions in the platform marked failed: Task execution timed out after 7200 seconds, with duration_ms ≈ 7,215,000.
  6. 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:

  1. Decouple the orchestrator from the leaked reader thread (high-impact). When _drain_bounded returns with outcome=leaked, _run_headless_subprocess should still return to _finalize_headless_result promptly — 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).
  2. Wider pipe-holder discovery (root cause). When force-close still leaves a stuck reader, fall back to lsof / /proc/*/fd enumeration 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_seconds from 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

Activity

  1. added a commit that references this issue on May 29, 2026
  2. vybe commented on Jun 2, 2026

    @vybe
    ContributorAuthor

    Fixed by #973 (squash-merged to dev as 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 MCP tools/call kept 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-/proc directions wouldn't have helped.

    #973 replaces the blocking wait with a poll loop: early-completion on the result message (force return_code=0; genuine errors still surface via metadata.error_type ahead 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 to main on next release.

  3. added a commit that references this issue on Jun 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

priority-p1type-bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions