Skip to content

bug: long-running backend→agent task calls dropped when uvicorn worker recycles #408

Closed

Description

@vybe

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.py watchdog

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

  1. Configure 7+ agents with scheduled tasks that take 10-45 min each (e.g., a skill with many tool calls / web searches)
  2. Stagger schedules across the hour so 2-3 always overlap
  3. Let the fleet run 6-12 hours
  4. Grep trinity-backend logs for Child process [X] died — coincides with in-flight long calls
  5. Grep trinity-backend logs for [Watchdog] orphan_recovered — downstream effect
  6. In the UI, observe executions marked "failed" with Execution completed on agent but status not reported as the error

Suggested Fix

Convert backend → agent task dispatch to fire-and-forget, mirroring SCHED-ASYNC-001:

  1. POST /api/task/start on the agent returns immediately (202) with an execution_id
  2. Agent runs the task in a background worker, writes progress/result to its own DB or filesystem
  3. Backend polls GET /api/executions/{id} (already exists via the watchdog path) to detect completion and fetch the result
  4. 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

  1. added
    priority-p2
    type-bug
    status-in-progress
    and removed on Apr 19, 2026
  2. vybe commented on Apr 20, 2026

    @vybe
    ContributorAuthor

    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)

    1. Agent ProcessRegistry — when subprocess exits, keep the entry. Move it to a _completed_cache with (status, result, error, completed_at). TTL ~1h, bounded size ~50 entries. (~20 lines)
    2. Agent — new GET /api/executions/{id}/result endpoint returns cached completed result or 404. (~15 lines)
    3. Backend watchdog (cleanup_service._reconcile_orphaned_executions) — before marking an execution orphan-recovered, call GET /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

    Fire-and-forget Watchdog claims result
    Surfaces changed Agent runtime, registry semantics, task execution service, watchdog, three+ callers Agent registry (additive), one new agent endpoint, watchdog
    New state machine Yes (running/awaiting_claim/claimed + poll coordination) No
    Race conditions Multiple (watchdog vs poll, late-write overwrites) Minimal — watchdog stays the single writer on the orphan path
    Regression risk High Low
    Fixes root cause (worker kills) No No
    User-visible "failed" executions resolved ~100% ~100%
    UI latency on recovery Immediate on poll completion Up to watchdog interval (5 min)

    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

    • Agent ProcessRegistry retains completed executions for up to 1h (bounded cache, FIFO eviction)
    • Agent GET /api/executions/{id}/result returns {status, result, error, completed_at} or 404
    • Watchdog attempts result fetch before marking orphan; on success writes DB as SUCCESS with the real response/cost/tokens
    • Existing orphan-recovery path still fires for genuine failures (agent unreachable, result not cached)
    • No changes to TaskExecutionService or any callers of /api/task
    • Unit tests for cache TTL + eviction, watchdog claim path, 404 fallback
  3. added and removed
    status-in-progress
    on Apr 20, 2026
  4. added
    status-in-progress
    on Apr 20, 2026
  5. github-actions commented on Apr 20, 2026

    @github-actions

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

    Next steps:

    1. Create branch: feature/408-<short-slug>
    2. Implement the feature
    3. Open a PR with Fixes #408
  6. vybe commented on Apr 20, 2026

    @vybe
    ContributorAuthor

    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:

    1. Push-based completion — agent notifies backend when done; backend never holds a long call open. This is exactly what feat: Redis Streams event bus for reliable WebSocket delivery (RELIABILITY-003) #306 (Redis Streams event bus, Sprint D) delivers.
    2. Fire-and-forget + polling — backend returns 202, then polls. Adds a poll loop, a new state machine, another watchdog path. ~300–600 LOC that would be deleted once feat: Redis Streams event bus for reliable WebSocket delivery (RELIABILITY-003) #306 ships.

    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.

  7. removed
    status-in-progress
    on Apr 20, 2026
  8. removed their assignment
    on Apr 20, 2026
  9. 9 remaining items

  10. added 2 commits that reference this issue on May 26, 2026
  11. vybe commented on May 27, 2026

    @vybe
    ContributorAuthor

    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

    Time UTC Event
    17:10 Backend deployed (33023f51). uvicorn==0.37.0 + --timeout-worker-healthcheck 120 confirmed live in cmdline
    19:05:00 Worker [8] takes slots 4/5 and 5/5 for [AGENT-A]; calls POST /api/task (timeout=7210s) on two scheduled executions
    19:29:11.79 [TaskExecService] Agent [AGENT-A] responded: HTTP 200 (5051083ms) — 84 min, success
    19:29:12.96 [TaskExecService] Agent [AGENT-A] responded: HTTP 200 (5412481ms) — 90 min, success
    19:29:19 Both slots released cleanly; routers.internal: Async task completed for [AGENT-A]: status=SUCCESS
    ~19:34 (gap) Worker [8] dies
    19:34:30 New worker [1759] spawns; Application startup complete; cleanup_service runs startup recovery
    19:34:38 [Recovery] Could not reach agent [AGENT-A] registry: Transient transport error: ReadTimeout
    19:34:39 [Slots] Agent [AGENT-A] released slot for execution ... 0 slots still active (× 4)
    19:34:39 [Recovery] Task execution recovery complete: recovered=4, still_running=0, skipped_grace=0, errors=0
    19:35:42-45 Scheduler fires three Executing retry for schedule ..., attempt 2

    What'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: 0 on the container (container itself never restarted; RestartCount=0, uptime=2h25m at observation time)
    • dmesg shows no kernel OOM-killer entries; host memory 1.7 GiB / 3.8 GiB used at observation
    • No traceback or exception in backend log between the slot-release at 19:29:19 and INFO: 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:

    1. --limit-max-requests or --limit-max-requests-jitter defaults — does uvicorn 0.37 cycle workers after N completed requests by default? Worth grepping uvicorn config and proc/[pid]/status for graceful-exit signals during the dead window.
    2. httpx connection lifecycle after a very long request — if the agent-pool connection is closed by the agent or a tunnel/proxy mid-stream after the 84/90 min call, the resulting cleanup might run a synchronous teardown that misses the next ping.
    3. OTel trace flush or other post-response side effects — both completed calls have trace_id/span_id populated; 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_service startup-sweep is the actual source of the orphan-recoveries — it runs unconditionally on Application startup complete and 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.

  12. added
    priority-p1
    status-in-dev
    and removed
    priority-p2
    status-in-progress
    on May 27, 2026
  13. vybe commented on Jun 1, 2026

    @vybe
    ContributorAuthor

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

  14. added
    complexity-medium
    theme-reliability
    and removed
    status-in-dev
    on Jun 1, 2026
  15. vybe commented on Jun 6, 2026

    @vybe
    ContributorAuthor

    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:746 still awaits agent_post_with_retry(...) with timeout_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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

complexity-mediumpriority-p1theme-reliabilitytype-bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions