Repository navigation
Description
Summary
The recreate_container_with_updated_config() function in the agent lifecycle service is marked async but contains synchronous blocking Docker SDK calls that are not wrapped in run_in_executor(). When container recreation is triggered, these blocking calls freeze the FastAPI event loop for 10-30+ seconds, causing all other API requests to time out and the UI to become unresponsive.
Component
Backend / Agent Service / Lifecycle
Priority
P1
Error
No explicit error - manifests as:
- API requests returning HTTP 499 (client timeout)
/api/telemetry/hostand other endpoints timing out- WebSocket connections dropping
- UI pages failing to load
- Docker health check marking backend as "unhealthy"
Example from logs:
INFO: ('172.28.0.6', 40848) - "WebSocket /ws" [accepted]
INFO: connection closed
INFO: ('172.28.0.6', 56940) - "WebSocket /ws" [accepted]
INFO: connection closed
# Rapid reconnection attempts as clients timeout
Frontend logs showing 499s during incident:
"GET /api/telemetry/host HTTP/1.1" 499 0
"GET /api/setup/status HTTP/1.1" 499 0
"GET /api/agents HTTP/1.1" 499 0
Location
- File:
src/backend/services/agent_service/lifecycle.py - Lines: 277-430 (approximately)
- Function:
recreate_container_with_updated_config()
Root Cause
The function is defined as async but contains multiple synchronous Docker SDK calls that block the event loop:
async def recreate_container_with_updated_config(agent_name: str, old_container, owner_username: str):
# ...
# These are ALL blocking calls - NOT using run_in_executor:
old_container.stop() # ~1-5 seconds blocking
old_container.remove() # ~1 second blocking
docker_client.volumes.get(shared_volume_name) # blocking
docker_client.volumes.create(...) # blocking
docker_client.containers.run('alpine', ...) # ~2-5 seconds blocking
docker_client.containers.run(image, ...) # ~2-5 seconds blockingSince FastAPI uses a single-threaded async event loop, these blocking calls prevent ANY other requests from being processed. With multiple Docker operations taking 10-30+ seconds combined, the entire backend becomes unresponsive.
Reproduction Steps
- Have a Trinity instance with multiple agents running
- Trigger a container recreation (e.g., change API key setting, modify shared folder config, or have a task fail that triggers recreation)
- Immediately try to load the UI or make API calls
- Observe that all requests timeout until the Docker operations complete
- Check frontend logs for HTTP 499 status codes
Suggested Fix
Wrap all blocking Docker SDK calls in asyncio.to_thread() (Python 3.9+) or loop.run_in_executor():
import asyncio
async def recreate_container_with_updated_config(agent_name: str, old_container, owner_username: str):
# ... existing setup code ...
# Stop and remove old container - NOW NON-BLOCKING
try:
await asyncio.to_thread(old_container.stop)
except Exception:
pass
await asyncio.to_thread(old_container.remove)
# Volume operations - NOW NON-BLOCKING
try:
await asyncio.to_thread(docker_client.volumes.get, shared_volume_name)
except docker.errors.NotFound:
await asyncio.to_thread(
docker_client.volumes.create,
name=shared_volume_name,
labels={...}
)
# Container creation - NOW NON-BLOCKING
# Note: containers.run() with many args needs a wrapper function
def create_container():
return docker_client.containers.run(
image,
detach=True,
name=f"agent-{agent_name}",
# ... all other args ...
)
new_container = await asyncio.to_thread(create_container)Alternative using a shared executor (matches telemetry.py pattern):
from concurrent.futures import ThreadPoolExecutor
_docker_executor = ThreadPoolExecutor(max_workers=4)
async def recreate_container_with_updated_config(...):
loop = asyncio.get_event_loop()
await loop.run_in_executor(_docker_executor, old_container.stop)
await loop.run_in_executor(_docker_executor, old_container.remove)
# ... etcNote: The routers/telemetry.py file already uses this pattern correctly for Docker stats - the same approach should be applied to lifecycle.py.
Environment
- Trinity version:
b2b8f06 - Docker version: 28.3.3
- OS: Ubuntu (Debian-based container)
Related
src/backend/routers/telemetry.py- Example of correct async Docker handling withrun_in_executorsrc/backend/services/agent_service/lifecycle.py- Primary file needing fixes- Similar blocking calls may exist in other lifecycle functions (
start_agent,stop_agent, etc.) - recommend auditing entire file
Impact
When triggered, this bug causes:
- Complete UI unresponsiveness for 10-30+ seconds
- All scheduled tasks to queue up
- WebSocket disconnections
- Potential cascade effects if multiple recreations are triggered
Activity
vybe commentedon Feb 24, 2026
Update: Blocking Docker Calls Are Widespread
Further investigation shows blocking Docker SDK calls exist across multiple files, not just lifecycle.py:
Affected Files and Blocking Calls
services/agent_service/lifecycle.pyrecreate_container_with_updated_config()stop(),remove(),volumes.get/create(),containers.run()services/agent_service/crud.pycreate_agent()volumes.get/create(),containers.run()(2x - alpine + agent)services/agent_service/terminal.pyhandle_terminal_ws()exec_create(),exec_start(),exec_resize()services/agent_service/helpers.pyvolumes.get()services/monitoring_service.pycontainers.get()services/system_agent_service.pycontainers.run()Impact
Every one of these operations blocks the FastAPI event loop:
Recommended Fix
Create a shared Docker operations module that wraps all Docker SDK calls:
Then systematically replace all direct
docker_client.*calls withawait run_docker_op(docker_client.*, ...).fix: Wrap blocking Docker SDK calls in ThreadPoolExecutor for async s…
vybe commentedon Mar 2, 2026
Resolved ✅
Fixed in DOCKER-001 (2026-02-24).
All blocking Docker SDK calls are now wrapped in
asyncio.run_in_executor()via the centralizeddocker_utils.pymodule. 13 async wrapper functions cover all container, volume, and exec operations.Files Updated
services/docker_utils.py- NEW core utility module (287 lines)services/agent_service/lifecycle.py- All Docker calls now asyncservices/agent_service/crud.py- All Docker calls now asyncservices/agent_service/terminal.py- Usesapi_exec_create,api_exec_startservices/agent_service/helpers.py-check_shared_folder_mounts_match()now asyncrouters/agents.py- Delete/stop/reload calls wrappedrouters/ops.py- Fleet restart/stop calls wrappedservices/system_agent_service.py- Container ops wrappedservices/ssh_service.py- All credential methods now asyncservices/docker_service.py-execute_command_in_container()now asyncservices/git_service.py- Awaits async container commandsImpact
Documentation
docs/memory/feature-flows/async-docker-operations.md