Repository navigation
Description
Summary
The scheduler's HTTP connection to the backend drops during long-running agent executions (10-20+ minutes), causing Server disconnected without sending a response errors. The agent tasks actually complete successfully on the container side, but the scheduler never receives the response. This results in zero execution records for affected agents and misleading error logs.
Component
Scheduler / Backend (TaskExecutionService)
Priority
P2
Error
[ERROR] scheduler.service: Schedule Heartbeat execution failed: Server disconnected without sending a response.
This is an httpx RemoteProtocolError — the TCP connection from the scheduler to the backend is reset by the server before a response is returned.
Location
- File:
src/scheduler/service.py(line ~713,_call_backend_execute_task) - File:
src/backend/routers/internal.py(line ~185,execute_task_internal) - Function:
_call_backend_execute_task→POST /api/internal/execute-task
Root Cause
The scheduler calls POST /api/internal/execute-task with httpx and waits for the backend to return. The backend's endpoint is a synchronous HTTP request that blocks until the agent finishes (via agent_post_with_retry → agent container's /api/task). For long-running tasks (10-20+ minutes), the underlying TCP connection between scheduler and backend is reset.
Possible causes:
- Uvicorn worker recycling — Multiple uvicorn workers (5 observed) may recycle during long requests
- TCP keepalive defaults — The httpx client in the scheduler creates a new
AsyncClientper request (no connection pooling or keepalive configuration) - Docker network timeouts — The trinity-network bridge may have default TCP timeout settings that close idle-appearing connections
The key issue is the architecture: the scheduler makes a blocking HTTP request that must stay open for the entire duration of the agent's execution (potentially 30-60 minutes). Any connection instability causes a false failure.
Observed Impact
- False failure logging: Scheduler logs errors even though agent work completes successfully
- Zero execution records:
schedule_executionstable has 0 rows for affected agents — the scheduler can't record results it never receives - Stale slot cleanups: Every execution cycle triggers a stale slot cleanup warning because the previous slot wasn't released cleanly
- No actual data loss: Agent work (predictions, commits, dashboard updates) completes normally on the container side
Reproduction Steps
- Create an agent with a scheduled task that takes >10 minutes to complete
- Configure the schedule with
timeout_seconds: 3600(1 hour) - Wait for the schedule to trigger
- Observe scheduler logs:
Server disconnected without sending a response - Verify the agent actually completed the work (check session logs in the agent container)
- Check
schedule_executionstable — no records for the agent
Suggested Fix
Option A (Recommended): Fire-and-forget with polling
Instead of blocking on the HTTP response, the scheduler should:
- POST to
/api/internal/execute-taskwhich returns immediately with anexecution_id - Poll
GET /api/internal/execution/{id}/statusperiodically until completion - This eliminates the long-lived HTTP connection entirely
# In scheduler/service.py _call_backend_execute_task:
async with httpx.AsyncClient() as client:
# Step 1: Start execution (returns immediately)
response = await client.post(
f"{config.backend_url}/api/internal/execute-task",
headers=headers,
json={**payload, "async": True},
timeout=30.0, # Short timeout for dispatch
)
execution_id = response.json()["execution_id"]
# Step 2: Poll for completion
deadline = time.monotonic() + request_timeout
while time.monotonic() < deadline:
await asyncio.sleep(10)
status_resp = await client.get(
f"{config.backend_url}/api/internal/execution/{execution_id}/status",
headers=headers,
timeout=10.0,
)
result = status_resp.json()
if result["status"] in ("completed", "failed"):
return resultOption B (Quick fix): Increase TCP keepalive and connection resilience
# In scheduler/service.py _call_backend_execute_task:
transport = httpx.AsyncHTTPTransport(
retries=1,
keepalive_expiry=30.0,
)
async with httpx.AsyncClient(
transport=transport,
timeout=httpx.Timeout(request_timeout, connect=10.0, pool=10.0),
) as client:
...Environment
- Trinity version:
d46281f - Scheduler: Python/APScheduler with httpx client
- Backend: FastAPI/Uvicorn (multiple workers)
- Affected agents: Any agent with scheduled tasks running >10 minutes
Related
src/scheduler/service.py—_call_backend_execute_taskmethodsrc/scheduler/agent_client.py—execute_taskmethodsrc/backend/routers/internal.py—/execute-taskendpointsrc/backend/services/task_execution_service.py—execute_taskmethod
Activity
vybe commentedon Mar 11, 2026
Implementation Plan: Issue #101 — Scheduler Async Fire-and-Forget with DB Polling
Problem
The scheduler makes a blocking HTTP call to
POST /api/internal/execute-taskthat holds a TCP connection open for the entire task duration (10-60+ minutes). The connection drops due to TCP idle timeouts, Docker bridge networking, or uvicorn worker recycling, causingRemoteProtocolError: Server disconnected without sending a response. The agent completes its work, but the scheduler never receives the response.Three interrelated bugs:
failed, even ifTaskExecutionServicealready updated it tosuccessin the shared DBCleanupServicemarks any execution stillrunningafter 30 min asfailed, hitting legitimate long tasksSolution
Replace the blocking HTTP call with fire-and-forget dispatch + DB polling, mirroring the existing
async_modepattern in the/taskendpoint.Changes
1. Backend: Add async mode to internal endpoint
File:
src/backend/routers/internal.pyasync_mode: bool = FalsetoInternalTaskExecutionRequestmodel (line 174-182)async_mode=Trueinexecute_task_internal()(line 186-223):asyncio.create_task(_execute_task_internal_background(task_service, request)){"status": "accepted", "execution_id": request.execution_id, "async_mode": True}_execute_task_internal_background()function:task_service.execute_task()(same as sync path)import asyncioat top of file2. Scheduler: Switch to async dispatch + DB polling
File:
src/scheduler/service.pyRewrite
_call_backend_execute_task()(lines 664-720):async_mode: Trueand a 30-second timeout (dispatch only){"status": "accepted"}, enter polling loop:self.db.get_execution(execution_id)every 10 secondstimeout_seconds + 60(buffer beyond task timeout)execution.status != "running"→ return result dictacceptedresponse (old backend), treat it as a sync result and return directly3. Scheduler: Guard against status overwrite
File:
src/scheduler/service.pyModify the
exceptblock in_execute_schedule_with_lock()(lines 645-662):self.db.update_execution_status(failed), check current status:4. Cleanup service: Increase stale timeout
File:
src/backend/services/cleanup_service.pyEXECUTION_STALE_TIMEOUT_MINUTESfrom30to120(line 24)ACTIVITY_STALE_TIMEOUT_MINUTESfrom30to120(line 25)5. Scheduler config: Add poll_interval setting
File:
src/scheduler/config.pypoll_interval: intfield (default 10, fromPOLL_INTERVALenv var)_call_backend_execute_task()polling loopFiles Changed
src/backend/routers/internal.pyasync_modefield, async dispatch, background functionsrc/scheduler/service.py_call_backend_execute_task(), add status overwrite guardsrc/backend/services/cleanup_service.pysrc/scheduler/config.pypoll_intervalconfigdocs/memory/requirements.mddocs/memory/changelog.mdEdge Cases
successon first pollrunning, cleanup marks failed at 120 minasync_mode=False, sync behavior unchangedDeploy Order
async_mode=False)Verification
POST /api/internal/execute-taskaccepted in < 1sschedule_executionstable — verify record showssuccesswith response, cost, durationfailedstatusGitHub Issue Update
Attach this plan as a comment on issue #101 with implementation steps and file list.
vybe commentedon Mar 11, 2026
Implementation Complete
All changes from the approved plan have been implemented:
Changes Made
src/backend/routers/internal.pyasync_modefield; whenTrue, spawns background task and returns immediatelysrc/scheduler/service.py_call_backend_execute_task()with async dispatch + DB polling; added status overwrite guardsrc/scheduler/config.pypoll_intervalconfig (default 10s,POLL_INTERVALenv var)src/backend/services/cleanup_service.pydocs/memory/requirements.mdTests
tests/scheduler_tests/test_async_dispatch.py— 11 tests, all passing:async_mode=Truewith 30s timeoutDeploy Order
False, fully backward compatiblefix: Scheduler async fire-and-forget with DB polling (#101)
vybe commentedon Mar 21, 2026
Closing — fixed by SCHED-ASYNC-001 (commit 747ec4a). Scheduler now uses async fire-and-forget dispatch + DB polling, eliminating TCP connection drops on long-running tasks.
feat(executions): GET /api/executions/timeline — bucketed fleet rollu…
feat(executions): GET /api/executions/timeline — bucketed fleet rollu…
feat(grid): widget chassis — InfoTile, GRID_WIDGETS registry, layout …
fix(grid): point tile components at tokens that exist, in both themes…
feat(grid): widget chassis — InfoTile, GRID_WIDGETS registry, layout …
fix(grid): point tile components at tokens that exist, in both themes…
fix(grid): the fleet tile linked to a route that does not exist (ent#…
feat(grid): widget chassis — InfoTile, GRID_WIDGETS registry, layout …