Repository navigation
Description
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:
-
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_writersmay not reach it if it is not in/procunder the expected pgid.read_stdoutthen blocks onreadline()indefinitely, preventing the reader thread from joining. -
asyncio.run()in executor blocksshutdown_default_executor(): Python 3.11'sasyncio.run()callsloop.shutdown_default_executor()after the coroutine completes, waiting for all threads submitted viaasyncio.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
- Assign an agent a Claude Max subscription token that is expired or invalid.
- Trigger a scheduled execution on that agent.
- Observe
agent-server.pyCPU viadocker exec <agent-container> ps aux. - Confirm no
claudechild process is present. - Observe backend logs:
Circuit OPENED for agent <name>fires every ~18 s indefinitely. - Observe cleanup logs:
agent unreachable during re-verify— execution staysrunning.
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 handlingA 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
83dc5e2(bug: circuit breaker has no half-open recovery — stays open permanently after agent probe timeouts under load #687) — CB cooldown clock fix; partially mitigates by allowing half-open retries, but container is unresponsive so retries still faild7cc958(bug: drain_reader_threads t.join(30) deadlocks asyncio event loop permanently when reader thread is stuck #657) — drain_reader_threads async fix; covers normal exit path but not this auth-failure spin569540b(fix(agent-server): recover lost result metadata + harden per-line reader (#630) #639) — harden per-line readerdocker/base-image/agent_server/services/claude_code.py—execute_headless_taskdocker/base-image/agent_server/utils/subprocess_pgroup.py—drain_reader_threads
Activity
vybe commentedon May 8, 2026
/claim
github-actions commentedon May 8, 2026
Claimed by @vybe. Label
status-in-progressadded.Next steps:
feature/728-<short-slug>Fixes #728fix(agent-server): cap drain executor thread at 90 s to fix #728 CPU …
vybe commentedon May 9, 2026
Field ops report — construct instance, 2026-05-09
PR #730 / commit
18f259fwas 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 = 90swarning 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:The
1821.9s post-kill gracemeans the reader thread was still alive and blocking 30 minutes after the 90s budget fired. The completion handler never ran → DB staysrunning→ 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-stateline is the keyThis fires before the 90s budget even starts.
_kill_orphan_pipe_writersscans/procto 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]/fdreadlink call itself blocks. The kill function never returns, the write-FD stays open, the reader thread'sTextIOWrapper.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_writersbeforesafe_close_pipeseven runs.Observed timing patterns (drain grace periods logged today)
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)
The 05:59 run held the DB slot as
runningfor 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_writersThe function needs a hard timeout on the
/procscan itself — not just on the outer drain budget. If scanning/proc/[pid]/fdblocks 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_BUDGETis exceeded, the scheduler HTTP response should be sent immediately as a soft-success (theresponse_partsrecovery 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
18f259fdeployedWorkaround each time:
docker stop agent-cornelius-m && docker start agent-cornelius-m(MTTR 2–5 min).fix(subprocess): replace os.stat() with os.readlink() in orphan pipe …
refactor(agent-server): split claude_code.py into focused modules (#122…
fix(agent-server): bound accumulators + /health diagnostics (#333 har…
fix(agent-server): bound accumulators + /health diagnostics (#333 har…
test: remove unit tests for cleanup symbols deleted in #817 follow-up
fix(agent-runtime): cgroup-walk sweep catches env-stripped orphans (#817
vybe commentedon Jun 1, 2026
Shipped in v0.6.0 (released via #998).
Release: v0.6.1 (#1171)
fix(agent-server): kill the process group on a budget-exceeded drain (#…
fix(sanitizer): linear KEY=value redaction — the #1661 CPU spin is th…
fix(agent): record WHERE a wedged reader thread is, instead of guessi…
fix(tests): stop a unit test from SIGKILLing the CI runner and the de…
fix(tests): stop a unit test from SIGKILLing the CI runner and the de…
feat(workspace): the Work card says what the agent is doing — one lin…