Repository navigation
Description
Summary
services/task_execution_service.py calls POST /api/task on an agent with timeout=3610 s and holds the HTTP connection open for the full task duration. Skills that run 10-45 minutes are common (prediction pipelines, multi-step analytics). When 2-3 such calls overlap, GIL contention on the backend causes uvicorn's worker-healthcheck to time out — even with --timeout-worker-healthcheck 120 applied — and the worker is SIGKILLed. All in-flight HTTP connections on that worker drop.
The agent completes its task correctly, but the backend never receives the response. The cleanup service's watchdog recovers state and marks the execution as Execution completed on agent but status not reported — recovered by watchdog (or orphaned / Stale execution — slot TTL expired depending on timing). No data loss, but each drop burns a scheduler retry and produces user-visible failed executions.
The fire-and-forget pattern from SCHED-ASYNC-001 solved the analogous problem for the scheduler→backend hop. The same pattern is still needed for backend→agent.
Component
Backend / Task Execution Service
Priority
P2
Error
INFO: Waiting for child process [X]
INFO: Child process [X] died
WARNING services.cleanup_service: [Watchdog] orphan_recovered: execution [ID] on agent '[AGENT]'
ERROR scheduler.service: Background poll: execution [ID] failed: Execution completed on agent but status not reported — recovered by watchdog
ERROR scheduler.service: Background poll: execution [ID] failed: Stale execution — slot TTL expired for agent '[AGENT]', cleaned by cleanup service
Location
- File:
services/task_execution_service.py - Function:
execute_task(synchronous HTTP call with ~1 h timeout) - Related: uvicorn worker-healthcheck (platform) +
services/cleanup_service.pywatchdog
Root Cause
Backend → agent task dispatch is synchronous: the calling coroutine awaits the full HTTP response. With timeout=3610 s that coroutine can hold a worker busy for up to an hour. Under concurrent load, the worker can't respond to uvicorn's ping/pong healthcheck within --timeout-worker-healthcheck 120 and is killed. Worker death drops every in-flight connection that was bound to it.
Observed on a fleet of 7 agents with hourly schedules running a 10-40 min skill: ~8 orphan/stale recoveries in ~7 hours despite uvicorn 0.37.0 + 120 s healthcheck window already being applied.
Reproduction Steps
- Configure 7+ agents with scheduled tasks that take 10-45 min each (e.g., a skill with many tool calls / web searches)
- Stagger schedules across the hour so 2-3 always overlap
- Let the fleet run 6-12 hours
- Grep
trinity-backendlogs forChild process [X] died— coincides with in-flight long calls - Grep
trinity-backendlogs for[Watchdog] orphan_recovered— downstream effect - In the UI, observe executions marked "failed" with
Execution completed on agent but status not reportedas the error
Suggested Fix
Convert backend → agent task dispatch to fire-and-forget, mirroring SCHED-ASYNC-001:
POST /api/task/starton the agent returns immediately (202) with anexecution_id- Agent runs the task in a background worker, writes progress/result to its own DB or filesystem
- Backend polls
GET /api/executions/{id}(already exists via the watchdog path) to detect completion and fetch the result - Worker death on backend no longer orphans the execution — the next worker picks up the poll cycle from DB state
This decouples long task duration from HTTP connection lifetime, and eliminates GIL-pressure-induced worker kills. Secondary benefit: execution state survives backend restarts without watchdog reconciliation.
Environment
- Trinity version:
8106fe9 - Uvicorn: 0.37.0 (with
--timeout-worker-healthcheck 120) - Workers: 2
Related
- SCHED-ASYNC-001 — fire-and-forget for scheduler→backend (same pattern to replicate)
- Bug report in ops repo:
instances/*/deploys/2026-03-13-bug-report-uvicorn-worker-recycle.md(earlier investigation) - Cleanup service watchdog handles the symptom; this issue is the root cause
Activity
vybe commentedon Apr 20, 2026
Revised approach: watchdog claims completed results (simpler)
After digging into regression risks of the original fire-and-forget proposal, the simpler symptom-level fix looks strictly better for this bug.
Observation
The agent already completes the task correctly. What the user sees as "failed" is actually "agent succeeded, backend lost the response, watchdog gave up instead of claiming the result." The fire-and-forget plan tried to prevent the dropped connection; this plan lets the watchdog recover the result the agent already has.
Changes (three local, additive)
ProcessRegistry— when subprocess exits, keep the entry. Move it to a_completed_cachewith(status, result, error, completed_at). TTL ~1h, bounded size ~50 entries. (~20 lines)GET /api/executions/{id}/resultendpoint returns cached completed result or 404. (~15 lines)cleanup_service._reconcile_orphaned_executions) — before marking an execution orphan-recovered, callGET /api/executions/{id}/result. If the agent has a success result cached, write SUCCESS to the DB with the real response. If 404, fall through to current orphan-recovery path. (~30 lines)Total: ~65 lines. No new state machine. No changes to
TaskExecutionService, no changes to the 6+ sync callers, no polling coroutines, no sync/async cutover.Trade-offs vs. original fire-and-forget plan
What this does NOT fix
Backend workers still occasionally get killed by uvicorn's healthcheck. That is a separate infra-level diagnosis (memory / GC pauses / etc.). This fix changes the user-visible impact of those kills from "failed execution" to "success arrives up to 5 minutes late via watchdog." If workers kill frequently enough that the 5-min delay is painful, a separate ticket should focus on root-causing the kill itself (memory profile, worker recycle behavior, GC settings).
Acceptance criteria
ProcessRegistryretains completed executions for up to 1h (bounded cache, FIFO eviction)GET /api/executions/{id}/resultreturns{status, result, error, completed_at}or 404TaskExecutionServiceor any callers of/api/taskgithub-actions commentedon Apr 20, 2026
Claimed by @vybe. Label
status-in-progressadded.Next steps:
feature/408-<short-slug>Fixes #408vybe commentedon Apr 20, 2026
Deferring — #306 should land first
After an architectural review of the orchestration surface, this issue's suggested fix ("mirror SCHED-ASYNC-001 for backend→agent") would add a fourth fire-and-forget + polling layer on top of three existing ones. The underlying pattern — "poll and pretend it's push" — is itself the root cause of much of the nine-path cleanup pyramid.
Why defer
The issue's symptom (uvicorn worker killed under GIL contention while holding 1h HTTP call) has two honest fixes:
Shipping #408 as drafted means building (2) and then deleting it three months later when (1) lands.
Also considered
Next step
Reopening #306 as the priority. Once result push is in, #408's symptom disappears — agent push replaces the blocked HTTP call entirely, and the watchdog can shrink.
Putting this back to `status-ready` pending #306.
feat: Redis Streams event bus for WebSocket delivery (RELIABILITY-003) (
9 remaining items
feat(#914): MCP chat_with_agent gateway-timeout receipt instead of fe…
feat(#914): MCP chat_with_agent gateway-timeout receipt instead of fe…
vybe commentedon May 27, 2026
Adding new evidence from a deploy on 2026-05-27 (commit
33023f51, which includes #922 — "scheduler honors per-agent execution_timeout_seconds"). The bug persists, with one detail that may sharpen the root-cause hypothesis.Timeline
33023f51).uvicorn==0.37.0+--timeout-worker-healthcheck 120confirmed live in cmdline[AGENT-A]; callsPOST /api/task(timeout=7210s) on two scheduled executions[TaskExecService] Agent [AGENT-A] responded: HTTP 200 (5051083ms)— 84 min, success[TaskExecService] Agent [AGENT-A] responded: HTTP 200 (5412481ms)— 90 min, successrouters.internal: Async task completed for [AGENT-A]: status=SUCCESSApplication startup complete;cleanup_serviceruns startup recovery[Recovery] Could not reach agent [AGENT-A] registry: Transient transport error: ReadTimeout[Slots] Agent [AGENT-A] released slot for execution ... 0 slots still active(× 4)[Recovery] Task execution recovery complete: recovered=4, still_running=0, skipped_grace=0, errors=0Executing retry for schedule ..., attempt 2What's new vs the original report
The original write-up frames the death as happening during long-running calls — GIL contention preventing the worker from responding to the ping/pong within the 120s window. In this instance the worker completed both long calls successfully (HTTP 200 at 19:29:11/12), released its slots cleanly, then died ~5 minutes later in the apparently-idle window between 19:29:19 and 19:34:30.
Diagnostic exclusions:
OOMKilled: false,ExitCode: 0on the container (container itself never restarted;RestartCount=0,uptime=2h25mat observation time)dmesgshows no kernel OOM-killer entries; host memory 1.7 GiB / 3.8 GiB used at observationINFO: Waiting for child process [8]That makes "GIL-blocked during long call → ping miss → SIGKILL" not quite the right story for this occurrence — though the rest of the cascade (cleanup_service orphan-recovery of OTHER in-flight executions on the same dead worker, followed by scheduler retry) matches the report exactly.
Possible additional candidates worth checking:
--limit-max-requestsor--limit-max-requests-jitterdefaults — does uvicorn 0.37 cycle workers after N completed requests by default? Worth grepping uvicorn config andproc/[pid]/statusfor graceful-exit signals during the dead window.trace_id/span_idpopulated; if the OTel exporter is configured for blocking-flush and gets backpressured against the collector, the worker could be GIL-blocked during the "idle" 5-minute window after response.The proposed fire-and-forget refactor in the original report's "Suggested Fix" would still resolve this — once the connection isn't held for the full task duration, any mid-handler worker death stops cascading into orphan-recoveries. Adding the new evidence here in case it nudges the diagnostic angle.
Side observation
The new worker's startup-time
cleanup_servicestartup-sweep is the actual source of the orphan-recoveries — it runs unconditionally onApplication startup completeand assumes any in-flight execution it can't probe is orphaned. Given that the prior worker's death is the only reason those probes fail, the watchdog amplifies the worker-death blast radius from "executions on that worker drop" to "all in-flight executions across both workers get killed". Whether to gate the startup-sweep behind a grace window (e.g. "skip if backend was up for <5 min") seems worth considering as a defensive mitigation independent of the root-cause fix.vybe commentedon Jun 1, 2026
Shipped in v0.6.0 (released via #998).
vybe commentedon Jun 6, 2026
Closed-but-premise-still-live (recurrence flag). Surfaced by the execution-bug meta-analysis (PR #1087 ·
docs/planning/ORCHESTRATION_BUG_META_ANALYSIS_2026-06.md).The mechanism this issue describes — the backend holding a synchronous call open for the whole agent turn — is still live:
src/backend/services/task_execution_service.py:746stillawaitsagent_post_with_retry(...)withtimeout_seconds = db.get_execution_timeout(agent_name)(up to ~2h). #998 did not remove the long await; #914 was a relabel.This is structurally resolved by #1083 (fire-and-forget dispatch — "a hung turn holds zero backend resource"), which is where the real fix lives, under Epic #1045 / umbrella #1081 (pull). Leaving #408 closed, but cross-linking so a future reader searching closed issues isn't misled into thinking the blocking-dispatch original sin is gone. Track the cure on #1083.