Skip to content

The agent that grows with you

fix(gateway): stop capping the turn-body executor at 10 threads

Kyzcreig24758cf4b8b5
diff --git a/gateway/run.py b/gateway/run.py
index 78c0de2ec57..52293d29c4b 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -57,11 +57,64 @@ _TELEGRAM_CONNECT_TIMEOUT_SECS_DEFAULT = 180.0
# offline update queue, #46621).
_TELEGRAM_INITIAL_CONNECT_TIMEOUT_SECS_DEFAULT = 45.0
_ADAPTER_DISCONNECT_TIMEOUT_SECS_DEFAULT = 5.0
-# Size of the pool that runs turn bodies (blocking agent work).
-_TURN_MAX_WORKERS = 10
+# Size of the pool that runs turn bodies (blocking agent work). ``None`` = unbounded: a turn body
+# holds its thread for the whole turn (every tool call blocks), so a finite pool silently queues
+# turns that were already accepted behind whichever bodies are running, with nothing in the logs.
+# Concurrency is bounded where turns are ADMITTED (``max_concurrent_sessions``), not here.
+_TURN_MAX_WORKERS = None
# Size of the separate pool for best-effort session HOUSEKEEPING; why it is separate: _run_housekeeping_in_executor.
_HOUSEKEEPING_MAX_WORKERS = 4
+
+class _UnboundedThreadExecutor(concurrent.futures.Executor):
+ """One thread per submitted work item; no queue, no cap.
+
+ ``ThreadPoolExecutor(max_workers=None)`` is NOT unbounded (it is ``min(32, cpu_count + 4)``),
+ which is the same silent queue at a larger number. Exposes ``_threads`` and ``_shutdown`` like
+ ``ThreadPoolExecutor`` so ``_stop_pool`` / ``_shutdown_executor`` join and count its workers.
+ """
+
+ def __init__(self, thread_name_prefix: str = ""):
+ self._prefix = thread_name_prefix
+ self._threads: set = set()
+ self._shutdown = False
+ self._lock = threading.Lock()
+ self._n = 0
+
+ def submit(self, fn, /, *args, **kwargs):
+ with self._lock:
+ if self._shutdown:
+ raise RuntimeError("cannot schedule new futures after shutdown")
+ self._n += 1
+ n = self._n
+ fut: concurrent.futures.Future = concurrent.futures.Future()
+
+ def _run():
+ try:
+ if not fut.set_running_or_notify_cancel():
+ return
+ try:
+ fut.set_result(fn(*args, **kwargs))
+ except BaseException as exc: # noqa: BLE001 - mirror ThreadPoolExecutor
+ fut.set_exception(exc)
+ finally:
+ with self._lock:
+ self._threads.discard(threading.current_thread())
+
+ t = threading.Thread(target=_run, name=f"{self._prefix}_{n}", daemon=True)
+ with self._lock:
+ self._threads.add(t)
+ t.start()
+ return fut
+
+ def shutdown(self, wait: bool = True, *, cancel_futures: bool = False):
+ with self._lock:
+ self._shutdown = True
+ threads = list(self._threads)
+ if wait:
+ for t in threads:
+ t.join()
+
# End reasons meaning the USER deliberately closed this thread. Shared by _classify_completion_target and
# _resolve_async_delegation_session so they never disagree (else a "delivered" reason is acked, then lost).
_USER_BOUNDARY_END_REASONS = ("session_reset", "user_exit", "session_switch", "new_session")
@@ -4314,7 +4367,7 @@ class GatewayRunner(
return await loop.run_in_executor(
self._get_housekeeping_executor(), copy_context().run, func, *args)
- def _get_or_create_pool(self, attr: str, max_workers: int, prefix: str) -> concurrent.futures.ThreadPoolExecutor:
+ def _get_or_create_pool(self, attr: str, max_workers: Optional[int], prefix: str) -> concurrent.futures.Executor:
"""Return (creating under ``_executor_lock``) the pool at ``attr``; one lock + closing flag fences both."""
lock = getattr(self, "_executor_lock", None)
if lock is None:
@@ -4325,11 +4378,14 @@ class GatewayRunner(
raise RuntimeError("Gateway is shutting down; executor unavailable")
executor = getattr(self, attr, None)
if executor is None or getattr(executor, "_shutdown", False):
- executor = concurrent.futures.ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix=prefix)
+ if max_workers is None:
+ executor = _UnboundedThreadExecutor(thread_name_prefix=prefix)
+ else:
+ executor = concurrent.futures.ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix=prefix)
setattr(self, attr, executor)
return executor
- def _get_executor(self) -> concurrent.futures.ThreadPoolExecutor:
+ def _get_executor(self) -> concurrent.futures.Executor:
"""Return the gateway-owned executor for blocking agent work."""
return GatewayRunner._get_or_create_pool(self, "_executor", _TURN_MAX_WORKERS, "hermes-gateway")
diff --git a/tests/gateway/test_executor_pool_isolation.py b/tests/gateway/test_executor_pool_isolation.py
index fa67b863c6e..833c6605aaa 100644
--- a/tests/gateway/test_executor_pool_isolation.py
+++ b/tests/gateway/test_executor_pool_isolation.py
@@ -22,7 +22,11 @@ import time
import pytest
-from gateway.run import _TURN_MAX_WORKERS, GatewayRunner
+from gateway.run import GatewayRunner
+
+# The turn pool used to be a 10-thread ThreadPoolExecutor; abandon at least that many so the
+# regression would have filled it outright.
+_OLD_TURN_POOL_SIZE = 10
def _runner(cleanup=None, *, cleanup_timeout=0.5):
@@ -63,7 +67,7 @@ def test_abandoned_housekeeping_cannot_delay_a_turn_body():
runner = _runner(wedged_cleanup)
# Enough to fill the turn pool outright if housekeeping still lands on it.
- abandoned = _TURN_MAX_WORKERS
+ abandoned = _OLD_TURN_POOL_SIZE
async def exercise():
await _abandon_housekeeping(runner, abandoned, runner._CLEANUP_TIMEOUT_S)
diff --git a/tests/gateway/test_turn_pool_unbounded.py b/tests/gateway/test_turn_pool_unbounded.py
new file mode 100644
index 00000000000..c621fada5d4
--- /dev/null
+++ b/tests/gateway/test_turn_pool_unbounded.py
@@ -0,0 +1,93 @@
+"""An accepted turn must never queue behind other turn bodies on the gateway's turn pool.
+
+A turn body holds its executor thread for the whole turn (every tool call blocks). With a finite
+pool (it was 10 threads), a burst of turns after a restart (resumed sessions plus new messages)
+filled it, and every later turn, including the user's next message, waited in the executor queue
+for minutes with no log line naming the wait. Concurrency is bounded at admission, not here.
+"""
+
+from __future__ import annotations
+
+import threading
+
+import pytest
+
+from gateway.run import GatewayRunner, _UnboundedThreadExecutor
+
+
+def _runner():
+ runner = GatewayRunner.__new__(GatewayRunner)
+ runner._executor_lock = threading.Lock()
+ runner._executor = None
+ runner._housekeeping_executor = None
+ runner._executor_closing = False
+ return runner
+
+
+def test_turn_pool_runs_many_blocking_bodies_at_the_same_instant():
+ runner = _runner()
+ n = 60
+ barrier = threading.Barrier(n, timeout=5)
+
+ def body():
+ barrier.wait() # raises BrokenBarrierError unless all n bodies run concurrently
+ return "ran"
+
+ ex = runner._get_executor()
+ try:
+ futs = [ex.submit(body) for _ in range(n)]
+ results = [f.result(timeout=15) for f in futs]
+ finally:
+ runner._shutdown_executor(drain_timeout=1)
+ assert results == ["ran"] * n
+
+
+def test_a_new_turn_starts_while_many_are_parked():
+ runner = _runner()
+ release = threading.Event()
+ parked = threading.Semaphore(0)
+
+ def parked_body():
+ parked.release()
+ assert release.wait(30)
+
+ ex = runner._get_executor()
+ try:
+ for _ in range(40):
+ ex.submit(parked_body)
+ for _ in range(40):
+ assert parked.acquire(timeout=10), "a parked body never started"
+ started = threading.Event()
+ ex.submit(started.set)
+ assert started.wait(2), "the 41st turn body queued behind 40 parked ones"
+ finally:
+ release.set()
+ runner._shutdown_executor(drain_timeout=5)
+
+
+def test_unbounded_executor_propagates_results_and_refuses_after_shutdown():
+ ex = _UnboundedThreadExecutor(thread_name_prefix="t")
+ assert ex.submit(lambda: 3).result(timeout=5) == 3
+ with pytest.raises(ValueError):
+ ex.submit(lambda: (_ for _ in ()).throw(ValueError("boom"))).result(timeout=5)
+ ex.shutdown(wait=True)
+ with pytest.raises(RuntimeError):
+ ex.submit(lambda: None)
+
+
+def test_shutdown_counts_a_live_turn_worker():
+ runner = _runner()
+ wedge = threading.Event()
+ entered = threading.Event()
+
+ def wedged():
+ entered.set()
+ assert wedge.wait(30)
+
+ runner._get_executor().submit(wedged)
+ assert entered.wait(5)
+ try:
+ live = runner._shutdown_executor(drain_timeout=0.2)
+ finally:
+ wedge.set()
+ assert live == 1, f"wedged turn worker not reported as live (got {live})"