Repository navigation
Description
Summary
When an agent container exhausts its memory limit and the kernel OOM-kills processes inside it, the failure does not stay contained — it cascades into backend worker starvation and ultimately freezes the entire admin UI. Agent containers run with hard memory limits precisely so they can be isolated, but the current execution path makes the backend's two uvicorn workers vulnerable to slow / hung agent responses with multi-minute HTTP timeouts. The user-visible symptom is "UI is frozen"; the real cause is a single misbehaving agent.
Component
Backend / Task Execution Service + Agent Runtime + Claude Code SDK error classification
Priority
P1 — major feature (admin UI) broken with no in-UI workaround. Operator must SSH and restart the offending agent container to recover. No data loss, but the platform appears down to the operator.
Observed Behavior
Reproducible cascade observed in production:
-
Agent OOM: an agent container with a 4 GB hard memory limit runs an internal
gitoperation (the agent's workspace was itself a sizeable git repo). The kernel cgroup OOM-killer terminates thegitprocess at ~4.1 GB anon-rss. Confirmed viadmesg:Memory cgroup out of memory: Killed process N (git) total-vm:5468752kB, anon-rss:4097292kB ... oom_memcg=/system.slice/docker-<container-id>.scope -
Claude subprocess dies at 0 turns: the
claudeCLI subprocess (spawned byagent_server.services.headless_executor) dies with exit code-9before the first agentic turn completes. Stored inschedule_executions.erroras:Execution terminated by SIGKILL after 0 tool calls / 0 turns (exit code -9). Likely cause: schedule/agent timeout exceeded, OOM kill, or operator cancel. -
Claude Code SDK misclassifies as auth failure: in some fraction of cases, the SDK can't determine why its child died and reports:
Claude Code execution failed (exit code -9): Subscription token may be expired or revoked. Generate a new one with 'claude setup-token'.This is a false signal — the token is fine. Verified by hashing
CLAUDE_CODE_OAUTH_TOKENacross two agents sharing the same subscription: hashes matched, the other agent worked normally. -
SUB-003 auto-switch fires incorrectly: backend's pattern matcher treats the "Subscription token may be expired or revoked" string as an auth-class failure and triggers auto-switch. A row is written to
subscription_rate_limit_events. The switch is futile (the new subscription has the same memory limit) and consumes the 2-hour skip-list slot, blocking auto-switch from helping when it's actually needed later. -
Backend worker saturation:
services.task_execution_servicecalls agents over HTTP with very long per-call timeouts (observed: 610s, 1210s, 2710s). With the defaultuvicorn --workers 2, two slow agent calls saturate the worker pool. Concrete measurement: a single an agent call returned HTTP 200 after 692 440 ms (11.5 min) before completion. While workers are held, all other HTTP traffic — including the dashboard's parallel API fan-out (/api/agents,/api/ops/fleet/health,/api/operator-queue?status=pending,/api/agents/execution-stats) — queues. -
Docker healthcheck flips to unhealthy: container
/healthcurl exceeds its 10s timeout,FailingStreakclimbs (observed: 8 consecutive failures). From inside the container,/healthis fast (7–16 ms) when a worker is free, ~1000+ ms when both are busy — perfectly consistent with worker starvation, not a stuck process. -
UI appears frozen to the operator: HTML loads (
http://[INSTANCE_HOST]:[FRONTEND_PORT]/returns 200 in ~240ms) but the dashboard never finishes loading because at least one of the parallel API calls is gated behind a multi-minute task call.
Reproduction
Synthetic repro outline:
- Deploy a Trinity instance with default backend config (
uvicorn --workers 2). - Create an agent with the default 4 GB memory limit and a workspace large enough that a
git status/git log --allallocates >4 GB of resident memory (or simulate with a memory-hog script triggered by a skill). - Configure a second agent to call the first via
chat_with_agentor/adviseMCP tool with high frequency, so the backend has multiple synchronoustask_execution_servicecalls in flight to the same target. - Observe:
- Failing executions on the OOM'd agent with mixed error strings: some
SIGKILL exit -9 / 0 turns / 0 tool calls, someSubscription token may be expired or revoked - A
subscription_rate_limit_eventsrow is created even though the token is valid (verifiable by hashing the OAuth token env var across two agents on the same subscription) docker inspect <backend> --format '{{.State.Health.Status}}'reportsunhealthy/api/ops/fleet/healthlatency climbs from sub-second to 5–10+ seconds- The admin UI dashboard fails to load (or loads partially) until the offending agent is restarted
- Failing executions on the OOM'd agent with mixed error strings: some
Root Causes (multiple, layered)
There are at least four independent contributing factors. Fixing any one of them reduces blast radius; fixing them together is the right answer.
RC-1: Agent failure isolation is incomplete
A single agent's resource exhaustion can saturate the backend's HTTP worker pool. Agent containers exist specifically to isolate per-agent failure — but the platform's call path negates the isolation by holding a worker for the entire duration of a remote agent task.
Where: services/task_execution_service.py — synchronous httpx calls with multi-minute timeouts. Even though the HTTP client is async, the surrounding execution context (DB writes, retries, slot reconciliation) holds the worker.
Fix candidates:
- Add a per-agent in-flight call limit at the backend (independent of agent-side
max_parallel_tasks) so one misbehaving agent cannot consume both/all workers. - Add an outer call-budget timeout that is independent of the agent's
timeout_seconds(e.g. 60s to establish + heartbeat, with the long body running on a detached background task pulling status from the agent's/api/executions/{id}). - Increase default
--workerscount, but this is a mitigation, not a fix.
RC-2: Claude Code SDK exit-code -9 is mis-mapped to "token expired"
When the child claude process dies with SIGKILL before any API interaction, the SDK has no signal about why — it cannot distinguish OOM from operator cancel from timeout from real token revocation. Defaulting to "Subscription token may be expired or revoked" is a guess that contaminates downstream observability and auto-switch logic.
Where: error message construction inside agent_server/services/headless_executor.py (or the underlying Claude Code SDK). Need to distinguish:
- Exit code -9 with no SDK API activity → "Process killed externally (likely OOM or watchdog); cause unknown"
- Exit code -9 after a 401/403/429 was actually observed on the wire → "Token likely revoked"
Fix: emit a generic "subprocess terminated by signal N before any agent activity" classification for SIGKILL-at-0-turns. Reserve the "token expired" string for cases where an actual auth-class HTTP response has been seen.
RC-3: SUB-003 auto-switch trusts the string match too eagerly
Auto-switch (SUB-003) treats the literal "Subscription token may be expired or revoked" string as a trigger. With RC-2 generating false positives, auto-switch flaps subscriptions for what is actually a memory issue, and burns the 2-hour skip-list slot. When a real token expiry happens after this, the cooldown can prevent the legitimate switch.
Where: error pattern matching in subscription auto-switch logic (search for "may be expired" / "revoked").
Fix: gate the auto-switch trigger on an actual HTTP 401/403/429 having been observed on the wire (Claude SDK exposes this), not on a string in a generic error message. As a partial improvement, require at least one successful turn before counting a subsequent failure as an auth signal (rules out 0-turn SIGKILLs).
RC-4: Container OOMs are silent at the platform layer
The platform has no signal that an agent's cgroup OOM-killer fired. Operators currently have to SSH to the host and dmesg | grep oom to find it. This information is exactly what we need to (a) auto-classify the SIGKILL correctly, (b) surface in /api/agents/{name}/diagnostics, and (c) generate an operator queue alert.
Fix candidates:
- After a SIGKILL-at-0-turns, the backend reads
/sys/fs/cgroup/memory.events(or equivalent) for the agent's container and looks for an OOMoom_killcounter increment. If present, classify as OOM and emit a structured event. - Surface OOM count in
/api/agents/{name}/statsand the agent dashboard. - Generate an operator queue alert (existing OPS-001) when an agent OOMs N times in M minutes.
Suggested Fix Order
- RC-2 + RC-4 first (cheapest, biggest debugging win): correctly classify SIGKILL exits and surface cgroup OOM events. Solves the false "token expired" story everywhere.
- RC-3: tighten auto-switch trigger so it requires an actual HTTP auth-class response. Once RC-2 is fixed, this becomes almost automatic.
- RC-1: add per-agent backend worker budget. Real architectural change but the only thing that prevents the UI-freeze from any future class of slow/hung-agent bug, not just OOM.
Environment
- Trinity version:
98574f37(fix(cleanup): per-slot TTL prevents false-kill of long-running executions (#869) (#871)) - Backend:
uvicorn 0.37.0 --workers 2 --timeout-worker-healthcheck 120 - Agent container memory limit: 4 GB (default)
- Agent runtime: Claude Code SDK via
agent_server.services.headless_executor
Evidence (sanitized excerpts)
Kernel cgroup OOM (host dmesg):
git invoked oom-killer: gfp_mask=0xcc0(GFP_KERNEL), order=0, oom_score_adj=0
Memory cgroup out of memory: Killed process N (git)
total-vm:5468752kB, anon-rss:4097292kB, file-rss:4412kB
oom_memcg=/system.slice/docker-<container-id>.scope
Backend log during incident:
[TaskExecService] Agent [AGENT] responded: HTTP 200 (692440ms)
DB execution-error mix on the same agent within ~10 min window:
exit code -9: Subscription token may be expired or revoked. <-- false signal
Execution terminated by SIGKILL after 0 tool calls / 0 turns (exit code -9).
Execution terminated by SIGKILL after 0 tool calls / 0 turns (exit code -9).
exit code -9: Subscription token may be expired or revoked. <-- false signal
Task execution error: [Errno 32] Broken pipe
Auto-switch false trigger:
subscription_rate_limit_events row created for an agent whose token
hash matched a sibling agent's token (verified working in parallel).
Backend healthcheck failure during incident:
docker inspect trinity-backend --format '{{.State.Health.Status}} {{.State.Health.FailingStreak}}'
unhealthy 8
But /health from inside the backend container responded in 7–16 ms when a worker was free (re-tested across 5 calls). Classic worker-pool exhaustion, not a stuck process.
Workaround (today)
Operator restarts the offending agent container:
docker restart agent-[NAME]
This drops the in-flight HTTP calls, frees the backend workers, and the UI recovers within ~30 seconds. The underlying OOM will recur on the next heavy workspace operation unless the agent's memory limit is raised.
Related
- SUB-003 (auto-switch)
- OPS-001 (operator queue — natural surface for OOM alerts)
- Per-agent execution timeout (TIMEOUT-001)
- Per-agent resource limits API:
PUT /api/agents/{name}/resources - Cleanup Service + active watchdog (currently catches the dead exec rows, but doesn't prevent the worker saturation)
Activity
fix(tests): adopt _STUBBED_MODULE_NAMES pattern for #904 test file
fix(#904): per-agent + global semaphore on backend agent HTTP calls (…
fix(#904 RC-1): default queue timeout 3600s — preserve "eventually su…
fix(#904): SIGKILL/OOM no longer misclassified as auth failure
fix(tests): adopt _STUBBED_MODULE_NAMES pattern for #904 test file
fix(#904): per-agent + global semaphore on backend agent HTTP calls (…
fix(#904 RC-1): default queue timeout 3600s — preserve "eventually su…
fix(#904): no false 'token expired' on SIGKILL/OOM + backend call bud…
vybe commentedon Jun 1, 2026
Shipped in v0.6.0 (released via #998).
refactor(reliability): unify the SUB-003 auth-class failure classifie…
Release: v0.8.0 (#1529)