Skip to content

bug: agent-server.py spins at 90% CPU on OAuth token auth failure, blocking CB recovery #728

Closed

Description

@vybe

Summary

When an agent's Claude Max subscription token is expired and an execution is dispatched, agent-server.py enters a CPU spin loop (~87–91%, rising over time) with no claude child process present. The container becomes unresponsive to all HTTP requests, blocking both the circuit-breaker half-open recovery path and the cleanup service's re-verify step. The execution stays `running` in the DB until the full per-agent execution timeout fires (up to 7200 s), causing a compounding outage on that agent slot.

This is distinct from the drain deadlock fixed in #657 (normal exit path). The spin occurs specifically when claude exits immediately due to an authentication failure on an expired OAuth token.

Component

Agent Runtime — docker/base-image/agent_server/services/claude_code.py

Priority

P1 — single-agent slot blocked for up to 2 h; CB stays open during that window; no workaround short of manually restarting the container.

Observed Behaviour

# agent-server.py CPU climbs and stays high; no claude child process
python3 /app/agent-server.py   87% CPU → 88% → 89.7% → 90.8% → 91% (over ~40 min)
node   moltbook-mcp             0.1% CPU  (MCP HTTP server — unrelated)
# no claude / npx process visible

# Backend logs: circuit never closes
Circuit OPENED for agent <name> after N failures  (~1 per 18 s, counting indefinitely)

# Cleanup service (every 5 min):
Skipping <execution_id> for '<agent>' — agent unreachable during re-verify (#378);
  Phase 1 stale cleanup is fallback
# Redis slot freed; DB execution stays status=running

# Execution self-resolves only when the 7200 s timeout fires

Root Cause (Hypothesis)

execute_headless_task dispatches subprocess work via:

return_code = await asyncio.wait_for(
    loop.run_in_executor(None, read_subprocess_output_with_timeout),
    timeout=timeout_seconds + 60   # e.g. 7270 s for a 7210 s timeout agent
)

Inside read_subprocess_output_with_timeout, after process.wait() returns (claude exits fast on auth failure), asyncio.run(_drain_reader_threads(...)) is called. Two failure modes are suspected:

  1. Pipe not closed: A grandchild process (e.g. an MCP server started outside claude's pgid) holds the stdout write-FD open. _kill_orphan_pipe_writers may not reach it if it is not in /proc under the expected pgid. read_stdout then blocks on readline() indefinitely, preventing the reader thread from joining.

  2. asyncio.run() in executor blocks shutdown_default_executor(): Python 3.11's asyncio.run() calls loop.shutdown_default_executor() after the coroutine completes, waiting for all threads submitted via asyncio.to_thread. If any of those threads (e.g. t.join(join_timeout)) is itself blocked on a stuck daemon reader thread, the shutdown can stall beyond the expected window.

In both cases the executor thread never returns, so the outer asyncio.wait_for does not fire until timeout_seconds + 60 elapses. During that entire period the event loop is busy-waiting (high CPU) and the HTTP response to the backend is never sent, keeping the connection open and the CB unable to recover.

Location

  • File: docker/base-image/agent_server/services/claude_code.py
  • Function: execute_headless_task → read_subprocess_output_with_timeout
  • File: docker/base-image/agent_server/utils/subprocess_pgroup.py
  • Function: drain_reader_threads

Reproduction Steps

  1. Assign an agent a Claude Max subscription token that is expired or invalid.
  2. Trigger a scheduled execution on that agent.
  3. Observe agent-server.py CPU via docker exec <agent-container> ps aux.
  4. Confirm no claude child process is present.
  5. Observe backend logs: Circuit OPENED for agent <name> fires every ~18 s indefinitely.
  6. Observe cleanup logs: agent unreachable during re-verify — execution stays running.

Suggested Fix

Short-term: Add a post-exit deadline inside read_subprocess_output_with_timeout. Once process.wait() returns, all drain and cleanup should complete in well under 60 s. Reduce the outer asyncio.wait_for timeout to min(timeout_seconds, process_exit_time + 90) or restructure so the outer timeout resets after process exit is confirmed.

# After process.wait() returns, use a tight cleanup budget
DRAIN_BUDGET = 90  # seconds — generous but bounded
try:
    stderr_output, return_code = await asyncio.wait_for(
        loop.run_in_executor(None, read_subprocess_output_with_timeout),
        timeout=timeout_seconds + DRAIN_BUDGET,
    )
except asyncio.TimeoutError:
    # ... existing handling

A cleaner fix would split the executor call into two phases: (1) blocking process.wait() with the full execution timeout, and (2) a separate short-timeout drain phase — preventing the drain from inheriting the 2-hour window.

Medium-term: Extend real-time auth failure detection from stderr (_is_auth_failure_message) to also scan stdout JSON events. If claude emits an auth error as a stream-json type: error event, abort immediately instead of waiting for process exit.

Long-term: Add a watchdog that detects process.poll() is not None (claude already exited) but the HTTP response has not been sent after N seconds, and force-returns an error. This would cap the spin window regardless of the drain/cleanup path.

Environment

  • Trinity version: 6593030
  • Python: 3.11.15 (agent container)
  • Docker: 29.2.1
  • OS: Ubuntu (container)

Related

Activity

  1. vybe commented on May 8, 2026

    @vybe
    ContributorAuthor

    /claim

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

    @github-actions

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

    Next steps:

    1. Create branch: feature/728-<short-slug>
    2. Implement the feature
    3. Open a PR with Fixes #728
  4. added a commit that references this issue on May 8, 2026
    18f259f
  5. added
    status-in-dev
    and removed
    status-in-progress
    on May 8, 2026
  6. vybe commented on May 9, 2026

    @vybe
    ContributorAuthor

    Field ops report — construct instance, 2026-05-09

    PR #730 / commit 18f259f was deployed 2026-05-08 at 10:55 UTC. It held for 8 clean HH:59 runs (12:59–19:59, ~9h), then the drain deadlock recurred and has been recurring multiple times per day since. As of this comment, CB#11 is actively open on the construct instance (~09:59 UTC, 1h45m, 193+ failures). This is a field evidence dump to help close the root cause.


    The 90s cap does not fix the blocking path

    The DRAIN_BUDGET = 90s warning fires correctly, but the agent continues to hold the execution open in the DB for 1704–1821 seconds after that warning. The 90s budget bounds the active spin but not the stuck state. From today's agent logs:

    # pid=11338, pid=11343, pid=11348 — three concurrent processes stuck simultaneously
    WARNING: _kill_orphan_pipe_writers still running after 10s (pid=11348)
             — /proc scan may be blocked on a D-state process
    ERROR:   Reader thread(s) still stuck after 33.6s post-kill grace (pid=11348, stuck_count=1)
    ERROR:   Reader thread(s) still stuck after 44.7s post-kill grace (pid=11343, stuck_count=1)
    ERROR:   Reader thread(s) still stuck after 59.2s post-kill grace (pid=11338, stuck_count=1)
    WARNING: Drain budget (90s) exceeded — safe_close_pipes may have deadlocked with reader
             thread's TextIOWrapper lock; reader threads are leaked daemon threads (pid=11338). Issue #728.
    ERROR:   1 reader thread(s) leaked for pid=11343 after force-close; continuing anyway
    
    # pid=12756 — later process, same path
    WARNING: Drain budget (90s) exceeded — leaked daemon threads (pid=12756). Issue #728.
    WARNING: _kill_orphan_pipe_writers still running after 10s (pid=12756)
             — /proc scan may be blocked on a D-state process
    ERROR:   Reader thread(s) still stuck after 1821.9s post-kill grace (pid=12756, stuck_count=1)
    ERROR:   1 reader thread(s) leaked for pid=12756 after force-close; continuing anyway
    

    The 1821.9s post-kill grace means the reader thread was still alive and blocking 30 minutes after the 90s budget fired. The completion handler never ran → DB stays running → scheduler polls indefinitely.


    This is not the auth-failure path

    The original bug report tied the spin to expired OAuth tokens. Every incident today is on a valid subscription (Romain Max, active). The trigger is a normal long-running execution completing (cornelius-m's hourly task, typically 5–47 min). The 90s drain budget was presumably targeted at the fast-exit auth-failure path. The slow path — long-running task completes, MCP grandchildren hold the pipe FD open — hits the same deadlock but wasn't covered.


    The /proc scan blocked on D-state line is the key

    _kill_orphan_pipe_writers still running after 10s (pid=XXXX)
    — /proc scan may be blocked on a D-state process
    

    This fires before the 90s budget even starts. _kill_orphan_pipe_writers scans /proc to find grandchild processes still holding the stdout write-FD. If any of those grandchildren are in D-state (uninterruptible kernel sleep — common for NFS, pipes, or certain syscalls), the /proc/[pid]/fd readlink call itself blocks. The kill function never returns, the write-FD stays open, the reader thread's TextIOWrapper.read() never gets EOF, and the drain budget counts down against a wall.

    The 90s budget cap does not help here because the blocking happens inside _kill_orphan_pipe_writers before safe_close_pipes even runs.


    Observed timing patterns (drain grace periods logged today)

    pid post-kill grace (s) notes
    11348 33.6 /proc scan blocked >10s
    11343 44.7 concurrent with 11338/11348
    11338 59.2 90s budget fired for this one
    10978 (yesterday CB#8) 1704.5
    12756 1821.9 /proc scan blocked >10s

    Three processes stuck simultaneously (11338/11343/11348) because a rapid chain of retries each hit the drain path at near the same time, each leaking a thread.


    Execution-level impact (from DB, 2026-05-09)

    05:59:00  pending_retry   completed 07:59:15  — stuck 2h in DB
    06:23:00  success         completed 08:13:35  — 1h50m
    06:59:00  success         completed 08:14:45  — 1h15m
    07:59:00  success         completed 08:12:47  — clean run ✓
    08:59:00  success         completed 09:05:44  — clean run ✓
    09:59:00  running         (still stuck, 1h45m as of comment time)
    10:37:00  running         (retry, also stuck)
    10:59:00  pending_retry   instant capacity fail
    11:00:10  failed          instant capacity fail (attempt 2)
    

    The 05:59 run held the DB slot as running for 2 hours before resolving. Even after CB#10 resolved (~08:15 UTC), CB#11 opened on the very next long-running execution (09:59 UTC).


    What needs to change in _kill_orphan_pipe_writers

    The function needs a hard timeout on the /proc scan itself — not just on the outer drain budget. If scanning /proc/[pid]/fd blocks for more than ~2s, abort and accept the leaked FD. Without this, every D-state grandchild process wedges the entire drain path before the 90s budget can help.

    The completion handler also needs to decouple from drain completion: if DRAIN_BUDGET is exceeded, the scheduler HTTP response should be sent immediately as a soft-success (the response_parts recovery path already exists for the "Result event lost" case) so the DB record gets updated and the slot is freed. Right now the leaked daemon thread blocks the HTTP response indefinitely.


    Quick ops timeline for context

    Time UTC Event
    2026-05-08 10:55 18f259f deployed
    2026-05-08 12:59–19:59 8 clean HH:59 runs
    2026-05-08 20:59–23:33 CB#8+9, drain chain, complex retries
    2026-05-08 23:59–04:59 6 clean runs
    2026-05-09 05:59–08:15 CB#10 — 05:59 exec stuck 2h, 3 concurrent running in DB
    2026-05-09 07:59–08:59 2 clean runs
    2026-05-09 09:59–now CB#11 open — 193+ failures, 2 stuck execs

    Workaround each time: docker stop agent-cornelius-m && docker start agent-cornelius-m (MTTR 2–5 min).

  7. vybe commented on Jun 1, 2026

    @vybe
    ContributorAuthor

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

  8. removed
    status-in-dev
    on Jun 1, 2026
  9. added a commit that references this issue on Jun 12, 2026
    e396414
  10. added a commit that references this issue on Jul 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

priority-p1type-bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions