Skip to content

The agent that grows with you

fix(api_server): agent turns and cron fires stop holding asyncio's default thread pool

Teknium0bc26adf2aa4
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index df3dc3b2aa5..1a72ca5b5cd 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -3515,7 +3515,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
def _detach_fire(fire_fn, *fire_args) -> web.Response:
# The done callback owns the reservation once the task is detached.
- task = asyncio.create_task(asyncio.to_thread(fire_fn, *fire_args, adapters=adapters, loop=loop))
+ task = asyncio.create_task(_api_runs.on_turn_executor(fire_fn, *fire_args, adapters=adapters, loop=loop))
reservation["detached"] = True
task.add_done_callback(lambda _task: _release_pending_api_work(self, reservation))
self._track_background_task(task, tolerate_missing=True)
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.py
index c3b1cabe7f5..5196c45322e 100644
--- a/gateway/platforms/api_server_runs.py
+++ b/gateway/platforms/api_server_runs.py
@@ -1,6 +1,8 @@
"""Durable ``/v1/runs`` admission, status, events, and control handlers."""
import asyncio
+import contextvars
+import functools
import hashlib
import json
import logging
@@ -25,6 +27,7 @@ except ImportError:
RequestKey = None # type: ignore[assignment,misc]
from gateway.platforms.api_server_room_grants import _json_error, _room_grant_error_response
+from gateway.turn_executor import _UnboundedThreadExecutor
from gateway.platforms.api_server_run_idempotency import TERMINAL_STATUSES
@@ -38,6 +41,17 @@ logger = logging.getLogger("gateway.platforms.api_server")
# in the worker thread's own ``finally``, which also keeps it visible past ``adapters.clear()``.
_API_WORKER_LOCK = threading.Lock()
_API_WORKER_LIVE = 0
+# API-server agent turns and cron fires run on their own executor, as Desktop and messaging turns
+# do (``GatewayRunner._get_executor``). asyncio's default pool is ``min(32, cpu_count + 4)`` threads
+# shared with every ``asyncio.to_thread`` SessionDB read in the session handlers, so once live
+# turns filled it each /api/sessions read queued behind a whole turn (#144362). Turn concurrency is
+# bounded where it is refused: ``gateway.api_server.max_concurrent_runs`` (429 past the cap).
+_API_TURN_EXECUTOR = _UnboundedThreadExecutor(thread_name_prefix="hermes-api-turn")
+
+
+def api_turn_executor() -> _UnboundedThreadExecutor:
+ """The executor that runs API-server agent turns and cron fires (never the loop's default)."""
+ return _API_TURN_EXECUTOR
def api_worker_live_count() -> int:
@@ -46,12 +60,18 @@ def api_worker_live_count() -> int:
return _API_WORKER_LIVE
+async def on_turn_executor(fn, /, *args, **kwargs):
+ """``asyncio.to_thread`` (context copied the same way) on the API turn executor."""
+ call = functools.partial(contextvars.copy_context().run, fn, *args, **kwargs)
+ return await asyncio.get_running_loop().run_in_executor(_API_TURN_EXECUTOR, call)
+
+
def _submit_api_worker(loop, fn):
- """``loop.run_in_executor(None, fn)`` with the worker-lifetime count held for the submission.
+ """``loop.run_in_executor(api_turn_executor(), fn)`` with the worker-lifetime count held for the submission.
Increment on the submitting (handler) thread so the count is live before the worker can
exit; decrement in the worker thread's own ``finally`` so handler cancellation cannot drop
- it early. When submission itself fails (default executor already shut down during quiesce
+ it early. When submission itself fails (executor shut down, or no thread can be started
-> RuntimeError) the worker never runs, so the count is released here instead — a leaked
count would make the shutdown close gate skip the SessionDB close for the process lifetime.
"""
@@ -68,7 +88,7 @@ def _submit_api_worker(loop, fn):
_API_WORKER_LIVE -= 1
try:
- return loop.run_in_executor(None, _counted)
+ return loop.run_in_executor(_API_TURN_EXECUTOR, _counted)
except BaseException:
with _API_WORKER_LOCK:
_API_WORKER_LIVE -= 1
diff --git a/tests/gateway/test_api_server_turn_executor.py b/tests/gateway/test_api_server_turn_executor.py
new file mode 100644
index 00000000000..8179130566e
--- /dev/null
+++ b/tests/gateway/test_api_server_turn_executor.py
@@ -0,0 +1,56 @@
+"""API-server agent turns must not occupy asyncio's default executor (#144362).
+
+The session handlers do their SessionDB work with ``asyncio.to_thread`` (the default pool). If live
+turns hold that pool, every /api/sessions read queues behind a whole turn.
+"""
+
+import asyncio
+import os
+import threading
+
+import pytest
+
+from gateway.platforms import api_server_runs as api_runs
+
+
+def _default_pool_size() -> int:
+ return min(32, (os.cpu_count() or 1) + 4)
+
+
+async def test_live_api_turns_leave_the_default_pool_to_session_reads():
+ loop = asyncio.get_running_loop()
+ release = threading.Event()
+ started = threading.Semaphore(0)
+ n = _default_pool_size() + 2
+
+ def _turn():
+ started.release()
+ release.wait(10)
+
+ turns = [api_runs._submit_api_worker(loop, _turn) for _ in range(n)]
+ try:
+ session_read = asyncio.ensure_future(asyncio.to_thread(lambda: "row"))
+ assert await asyncio.wait_for(session_read, 3) == "row", "session read queued behind live turns"
+ await asyncio.wait_for(asyncio.to_thread(lambda: [started.acquire(timeout=5) for _ in range(n)]), 8)
+ assert api_runs.api_worker_live_count() >= n
+ finally:
+ release.set()
+ await asyncio.gather(*turns)
+
+
+async def test_cron_fire_body_keeps_contextvars_off_the_default_pool():
+ import contextvars
+
+ var = contextvars.ContextVar("probe_scope", default="unset")
+ var.set("profile-a")
+ seen = {}
+
+ def _fire(job, *, adapters, loop):
+ seen.update(job=job, scope=var.get(), adapters=adapters)
+ return "fired"
+
+ out = await api_runs.on_turn_executor(_fire, "job-1", adapters={"a": 1}, loop=asyncio.get_running_loop())
+ assert out == "fired"
+ assert seen["scope"] == "profile-a" and seen["job"] == "job-1" and seen["adapters"] == {"a": 1}