Skip to content

The agent that grows with you

fix(gateway): run session housekeeping on its own pool so it cannot starve turn bodies

Kyzcreig9815b4456828
diff --git a/gateway/run.py b/gateway/run.py
index 6a0c8fa2602..10f3d1048a8 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -56,6 +56,77 @@ _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 agent TURN bodies, and of the separate pool for best-effort session
+# HOUSEKEEPING (finalize hooks, agent cleanup). They are separate because housekeeping callers
+# ABANDON their worker on timeout — see _run_housekeeping_in_executor. Both are ops-tunable.
+_EXECUTOR_MAX_WORKERS_DEFAULT = 10
+_HOUSEKEEPING_EXECUTOR_MAX_WORKERS_DEFAULT = 4
+# Log PHASE=executor_wait when a submitted work item sat queued this long before its first
+# instruction. Well above scheduling jitter, well below a budget a human would notice.
+_EXECUTOR_WAIT_WARN_SECS_DEFAULT = 5.0
+
+
+def _env_positive_int(name: str, default: int) -> int:
+ """Return a positive int from ``name``, falling back to ``default``."""
+ raw = os.getenv(name, "").strip()
+ if raw:
+ try:
+ value = int(raw)
+ except ValueError:
+ logger.warning("Ignoring invalid %s=%r", name, raw)
+ else:
+ if value > 0:
+ return value
+ logger.warning("Ignoring non-positive %s=%r", name, raw)
+ return default
+
+
+def _executor_max_workers() -> int:
+ """Return the size of the turn-body executor."""
+ return _env_positive_int(
+ "HERMES_GATEWAY_EXECUTOR_MAX_WORKERS", _EXECUTOR_MAX_WORKERS_DEFAULT)
+
+
+def _housekeeping_executor_max_workers() -> int:
+ """Return the size of the best-effort housekeeping executor."""
+ return _env_positive_int(
+ "HERMES_GATEWAY_HOUSEKEEPING_MAX_WORKERS",
+ _HOUSEKEEPING_EXECUTOR_MAX_WORKERS_DEFAULT)
+
+
+def _get_or_create_pool(
+ owner: Any, attr: str, prefix: str, max_workers: int
+) -> concurrent.futures.ThreadPoolExecutor:
+ """Get-or-create one of the gateway-owned pools under the owner's shared lock.
+
+ A module-level function, not a method: ``_get_executor`` is called unbound against
+ lightweight test doubles (``GatewayRunner._get_executor(fake)``), so it must not depend on
+ any sibling method those doubles do not implement.
+ """
+ lock = getattr(owner, "_executor_lock", None)
+ if lock is None:
+ lock = threading.Lock()
+ owner._executor_lock = lock
+ with lock:
+ if getattr(owner, "_executor_closing", False):
+ raise RuntimeError("Gateway is shutting down; executor unavailable")
+ executor = getattr(owner, attr, None)
+ if executor is None or getattr(executor, "_shutdown", False):
+ executor = concurrent.futures.ThreadPoolExecutor(
+ max_workers=max_workers, thread_name_prefix=prefix)
+ setattr(owner, attr, executor)
+ return executor
+
+
+def _executor_wait_warn_secs() -> float:
+ """Return the queue-latency threshold that triggers a PHASE=executor_wait log."""
+ raw = os.getenv("HERMES_GATEWAY_EXECUTOR_WAIT_WARN", "").strip()
+ if raw:
+ try:
+ return max(0.0, float(raw))
+ except ValueError:
+ logger.warning("Ignoring invalid HERMES_GATEWAY_EXECUTOR_WAIT_WARN=%r", raw)
+ return _EXECUTOR_WAIT_WARN_SECS_DEFAULT
# 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")
@@ -3570,6 +3641,10 @@ class GatewayRunner(
self._restart_task: Optional[asyncio.Task] = None
self._executor_lock = threading.Lock()
self._executor: Optional[concurrent.futures.ThreadPoolExecutor] = None
+ # Best-effort session housekeeping runs on its OWN pool: those callers abandon their
+ # worker on timeout, and an abandoned worker holds its slot until its blocking call
+ # returns — on a shared pool that starves turn bodies. See _run_housekeeping_in_executor.
+ self._housekeeping_executor: Optional[concurrent.futures.ThreadPoolExecutor] = None
# Set on gateway stop so the recreate-on-shutdown path can't resurrect the pool.
self._executor_closing = False
# ALL per-session state lives here (gateway/session_state.py); use _session_state / _peek_session_state.
@@ -4275,25 +4350,65 @@ class GatewayRunner(
async def _run_in_executor_with_context(self, func, *args):
"""Run blocking work in the thread pool while preserving session contextvars."""
+ return await self._submit_with_context(self._get_executor(), "turn", func, *args)
+
+ async def _run_housekeeping_in_executor(self, label, func, *args):
+ """Run best-effort session housekeeping off the TURN pool.
+
+ Callers of this helper bound their await with ``asyncio.wait_for`` and, on timeout, log
+ "the worker thread is left to finish on its own" and proceed. That bounds the AWAIT but
+ NOT the OCCUPANCY: a ``concurrent.futures`` work item that has already begun executing is
+ not cancellable, so an abandoned worker keeps its pool slot until its blocking call
+ returns. On a shared pool, N abandonments retire N turn slots for ANY N — the failure is
+ scale-invariant, so raising ``max_workers`` does not fix it. Housekeeping therefore gets
+ its own bounded pool; exhausting that one delays only more housekeeping, which is
+ best-effort by construction.
+ """
+ return await self._submit_with_context(
+ self._get_housekeeping_executor(), label, func, *args
+ )
+
+ async def _submit_with_context(self, executor, pool, func, *args):
+ """Submit to ``executor`` preserving contextvars, logging excessive queue latency.
+
+ Queue latency on these pools is otherwise invisible: nothing between "inbound message"
+ and the turn body names the wait, so a saturated pool looks like a hung agent.
+ """
loop = asyncio.get_running_loop()
ctx = copy_context()
- return await loop.run_in_executor(self._get_executor(), ctx.run, func, *args)
+ submitted_at = time.monotonic()
+ warn_after = _executor_wait_warn_secs()
+
+ def _timed(*call_args):
+ waited = time.monotonic() - submitted_at
+ if waited >= warn_after:
+ try:
+ max_workers = getattr(executor, "_max_workers", -1)
+ inflight = len(getattr(executor, "_threads", ()) or ())
+ queued = executor._work_queue.qsize()
+ except Exception:
+ max_workers = inflight = queued = -1
+ logger.warning(
+ "PHASE=executor_wait pool=%s key=%s waited=%.1f inflight=%s queued=%s "
+ "max_workers=%s",
+ pool, getattr(func, "__name__", type(func).__name__), waited,
+ inflight, queued, max_workers,
+ )
+ return ctx.run(func, *call_args)
+
+ return await loop.run_in_executor(executor, _timed, *args)
def _get_executor(self) -> concurrent.futures.ThreadPoolExecutor:
"""Return the gateway-owned executor for blocking agent work."""
- lock = getattr(self, "_executor_lock", None)
- if lock is None:
- lock = threading.Lock()
- self._executor_lock = lock
- with lock:
- if getattr(self, "_executor_closing", False):
- raise RuntimeError("Gateway is shutting down; executor unavailable")
- executor = getattr(self, "_executor", None)
- if executor is None or getattr(executor, "_shutdown", False):
- executor = concurrent.futures.ThreadPoolExecutor(
- max_workers=10, thread_name_prefix="hermes-gateway")
- self._executor = executor
- return executor
+ return _get_or_create_pool(
+ self, "_executor", "hermes-gateway", _executor_max_workers())
+
+ def _get_housekeeping_executor(self) -> concurrent.futures.ThreadPoolExecutor:
+ """Return the gateway-owned executor for best-effort session housekeeping."""
+ # Prefix stays under "hermes-gateway" so existing thread-name scans keep matching.
+ return _get_or_create_pool(
+ self, "_housekeeping_executor", "hermes-gateway-hk",
+ _housekeeping_executor_max_workers())
def _shutdown_executor(self, drain_timeout: float = 0.0) -> int:
"""Stop the gateway-owned executor; returns the number of worker threads still running.
@@ -4307,6 +4422,16 @@ class GatewayRunner(
self._executor_closing = True
executor = getattr(self, "_executor", None)
self._executor = None
+ housekeeping = getattr(self, "_housekeeping_executor", None)
+ self._housekeeping_executor = None
+ # Housekeeping is best-effort and nothing awaits it by now, so it gets no drain budget —
+ # but it MUST be stopped: its workers are non-daemon and concurrent.futures' atexit hook
+ # would otherwise join them and strand the process "down but not exited".
+ if housekeeping is not None:
+ try:
+ housekeeping.shutdown(wait=False, cancel_futures=True)
+ except TypeError:
+ housekeeping.shutdown(wait=False)
if executor is None:
return 0
try:
diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.py
index c778aa10b98..5731b1e71ea 100644
--- a/gateway/run_shutdown.py
+++ b/gateway/run_shutdown.py
@@ -1221,7 +1221,8 @@ class GatewayShutdownMixin:
try:
await asyncio.wait_for(
- self._run_in_executor_with_context(self._run_release_in_profile_scope, _call, (), session_key),
+ self._run_housekeeping_in_executor(
+ "finalize", self._run_release_in_profile_scope, _call, (), session_key),
timeout=self._FINALIZE_TIMEOUT_S,
)
except asyncio.TimeoutError:
@@ -1251,8 +1252,9 @@ class GatewayShutdownMixin:
ctx_label = f" ({context})" if context else ""
try:
await asyncio.wait_for(
- self._run_in_executor_with_context(
- self._run_release_in_profile_scope, self._cleanup_agent_resources, (agent,), session_key,
+ self._run_housekeeping_in_executor(
+ "cleanup", self._run_release_in_profile_scope,
+ self._cleanup_agent_resources, (agent,), session_key,
),
timeout=self._CLEANUP_TIMEOUT_S,
)
diff --git a/gateway/slash_commands_session.py b/gateway/slash_commands_session.py
index 435f8f8b1c5..dd872896d94 100644
--- a/gateway/slash_commands_session.py
+++ b/gateway/slash_commands_session.py
@@ -127,7 +127,8 @@ class GatewaySessionCommandsMixin:
return
try:
await asyncio.wait_for(
- self._run_in_executor_with_context(self._cleanup_agent_resources, _old_agent),
+ self._run_housekeeping_in_executor(
+ "cleanup", self._cleanup_agent_resources, _old_agent),
timeout=_RESET_CLEANUP_TIMEOUT_S)
except asyncio.TimeoutError:
logger.warning(
diff --git a/tests/gateway/test_executor_pool_isolation.py b/tests/gateway/test_executor_pool_isolation.py
new file mode 100644
index 00000000000..e66f15b90cd
--- /dev/null
+++ b/tests/gateway/test_executor_pool_isolation.py
@@ -0,0 +1,357 @@
+"""Best-effort session housekeeping must not be able to starve agent turn bodies.
+
+``_finalize_session_off_loop``, ``_cleanup_agent_resources_off_loop`` and
+``_cleanup_old_agent_for_reset`` each bound their await with ``asyncio.wait_for`` and, on
+timeout, log "the worker thread is left to finish on its own" and proceed.
+
+``asyncio.wait_for`` bounds the AWAIT but not the OCCUPANCY: a ``concurrent.futures`` work item
+that has already begun executing is not cancellable, so the abandoned worker keeps its pool slot
+until its blocking call returns. While those callers shared the turn pool, N abandonments retired
+N turn slots for ANY N — the failure is scale-invariant, so raising ``max_workers`` does not fix
+it (pinned below). A saturated pool then delays the turn body of every subsequent message,
+including automatic session resumes, with nothing in the logs naming the wait.
+
+These tests bind the REAL runner methods onto a minimal object holding only the attributes they
+read, so they cannot pass by mirroring the implementation.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import concurrent.futures
+import logging
+import threading
+import time
+import types
+
+import pytest
+
+from gateway.run import GatewayRunner
+
+
+def _runner(cleanup=None, *, cleanup_timeout=1.0):
+ obj = types.SimpleNamespace()
+ obj._executor_lock = threading.Lock()
+ obj._executor = None
+ obj._housekeeping_executor = None
+ obj._executor_closing = False
+ obj._CLEANUP_TIMEOUT_S = cleanup_timeout
+ obj._FINALIZE_TIMEOUT_S = cleanup_timeout
+ if cleanup is not None:
+ obj._cleanup_agent_resources = cleanup
+ for name in (
+ "_get_executor",
+ "_get_housekeeping_executor",
+ "_submit_with_context",
+ "_run_in_executor_with_context",
+ "_run_housekeeping_in_executor",
+ "_shutdown_executor",
+ ):
+ setattr(obj, name, types.MethodType(getattr(GatewayRunner, name), obj))
+ return obj
+
+
+def _stop(runner):
+ for attr in ("_executor", "_housekeeping_executor"):
+ pool = getattr(runner, attr, None)
+ if pool is not None:
+ pool.shutdown(wait=False, cancel_futures=True)
+
+
+async def _abandon_housekeeping(runner, count, timeout):
+ """Submit ``count`` wedged housekeeping items, abandoning each like the real callers do."""
+
+ async def one():
+ try:
+ await asyncio.wait_for(
+ runner._run_housekeeping_in_executor(
+ "cleanup", runner._cleanup_agent_resources, object()
+ ),
+ timeout=timeout,
+ )
+ except asyncio.TimeoutError:
+ pass # exactly what the production callers do
+
+ await asyncio.gather(*(one() for _ in range(count)))
+
+
+def test_housekeeping_and_turns_use_separate_pools():
+ runner = _runner()
+ try:
+ assert runner._get_executor() is not runner._get_housekeeping_executor()
+ finally:
+ _stop(runner)
+
+
+def test_abandoned_housekeeping_cannot_delay_a_turn_body():
+ """The regression pin: wedged, abandoned housekeeping must leave turn slots free."""
+ wedge = threading.Event()
+ entered = threading.Semaphore(0)
+
+ def wedged_cleanup(agent):
+ entered.release()
+ assert wedge.wait(60), "wedge never released"
+
+ runner = _runner(wedged_cleanup)
+ turn_pool = runner._get_executor()
+ hk_pool = runner._get_housekeeping_executor()
+ hk_workers = hk_pool._max_workers
+ # More than the housekeeping pool holds, so it is saturated AND backlogged.
+ abandoned = turn_pool._max_workers + hk_workers
+
+ async def exercise():
+ await _abandon_housekeeping(runner, abandoned, runner._CLEANUP_TIMEOUT_S)
+ for _ in range(hk_workers):
+ assert await asyncio.to_thread(entered.acquire, True, 30)
+
+ assert len(hk_pool._threads or ()) == hk_workers
+ assert hk_pool._work_queue.qsize() > 0
+ # ...and it consumed nothing from the turn pool.
+ assert len(turn_pool._threads or ()) == 0
+
+ started: dict[str, float] = {}
+
+ def turn_body():
+ started["at"] = time.monotonic()
+
+ submitted = time.monotonic()
+ await asyncio.wait_for(
+ runner._run_in_executor_with_context(turn_body), timeout=30
+ )
+ return started["at"] - submitted
+
+ try:
+ latency = asyncio.run(exercise())
+ finally:
+ wedge.set()
+ _stop(runner)
+
+ assert latency < 5.0, f"turn body waited {latency:.2f}s behind abandoned housekeeping"
+
+
+def test_turn_pool_still_queues_a_full_pool():
+ """Turn-vs-turn concurrency is unchanged; only housekeeping was moved off."""
+ release = threading.Event()
+ occupied = threading.Semaphore(0)
+ runner = _runner()
+ max_workers = runner._get_executor()._max_workers
+
+ def long_turn():
+ occupied.release()
+ assert release.wait(60)
+
+ async def exercise():
+ turns = [
+ asyncio.ensure_future(runner._run_in_executor_with_context(long_turn))
+ for _ in range(max_workers)
+ ]
+ for _ in range(max_workers):
+ assert await asyncio.to_thread(occupied.acquire, True, 30)
+ started = threading.Event()
+ queued = asyncio.ensure_future(
+ runner._run_in_executor_with_context(started.set)
+ )
+ await asyncio.sleep(0.5)
+ was_queued = not started.is_set()
+ release.set()
+ await asyncio.gather(queued, *turns)
+ return was_queued
+
+ try:
+ assert asyncio.run(exercise()), "a full turn pool must queue the next turn"
+ finally:
+ release.set()
+ _stop(runner)
+
+
+def test_executor_wait_logs_pool_depth(caplog, monkeypatch):
+ """A queued submit must say so, naming pool, key, wait and saturation."""
+ monkeypatch.setenv("HERMES_GATEWAY_EXECUTOR_WAIT_WARN", "0.2")
+ monkeypatch.setenv("HERMES_GATEWAY_EXECUTOR_MAX_WORKERS", "1")
+ release = threading.Event()
+ occupied = threading.Semaphore(0)
+ runner = _runner()
+
+ def long_turn():
+ occupied.release()
+ assert release.wait(60)
+
+ def queued_turn():
+ return "ran"
+
+ async def exercise():
+ first = asyncio.ensure_future(runner._run_in_executor_with_context(long_turn))
+ assert await asyncio.to_thread(occupied.acquire, True, 30)
+ second = asyncio.ensure_future(
+ runner._run_in_executor_with_context(queued_turn)
+ )
+ await asyncio.sleep(0.5)
+ release.set()
+ await asyncio.gather(first, second)
+
+ with caplog.at_level(logging.WARNING, logger="gateway.run"):
+ try:
+ asyncio.run(exercise())
+ finally:
+ release.set()
+ _stop(runner)
+
+ waits = [
+ r.getMessage() for r in caplog.records if "PHASE=executor_wait" in r.getMessage()
+ ]
+ assert waits, "no executor_wait line emitted"
+ assert "pool=turn" in waits[0]
+ assert "key=queued_turn" in waits[0]
+ assert "max_workers=1" in waits[0]
+
+
+def test_fast_submit_is_not_logged(caplog, monkeypatch):
+ """The line must be a saturation signal, not per-submit noise."""
+ monkeypatch.setenv("HERMES_GATEWAY_EXECUTOR_WAIT_WARN", "5")
+ runner = _runner()
+ with caplog.at_level(logging.WARNING, logger="gateway.run"):
+ try:
+ asyncio.run(runner._run_in_executor_with_context(lambda: "quick"))
+ finally:
+ _stop(runner)
+ assert not [r for r in caplog.records if "PHASE=executor_wait" in r.getMessage()]
+
+
+def test_housekeeping_backlog_is_attributed_to_its_own_pool(caplog, monkeypatch):
+ """A housekeeping backlog must be distinguishable from a turn backlog."""
+ monkeypatch.setenv("HERMES_GATEWAY_EXECUTOR_WAIT_WARN", "0.2")
+ monkeypatch.setenv("HERMES_GATEWAY_HOUSEKEEPING_MAX_WORKERS", "1")
+ wedge = threading.Event()
+ entered = threading.Semaphore(0)
+
+ def wedged_cleanup(agent):
+ entered.release()
+ assert wedge.wait(60)
+
+ runner = _runner(wedged_cleanup, cleanup_timeout=0.3)
+
+ async def exercise():
+ await _abandon_housekeeping(runner, 1, 0.3)
+ assert await asyncio.to_thread(entered.acquire, True, 30)
+ second = asyncio.ensure_future(
+ runner._run_housekeeping_in_executor("cleanup", lambda: "hk")
+ )
+ await asyncio.sleep(0.5)
+ wedge.set()
+ await second
+
+ with caplog.at_level(logging.WARNING, logger="gateway.run"):
+ try:
+ asyncio.run(exercise())
+ finally:
+ wedge.set()
+ _stop(runner)
+
+ waits = [
+ r.getMessage() for r in caplog.records if "PHASE=executor_wait" in r.getMessage()
+ ]
+ assert waits, "housekeeping backlog emitted no executor_wait line"
+ assert any("pool=cleanup" in line for line in waits), waits
+
+
+def test_shutdown_stops_the_housekeeping_pool():
+ """Non-daemon housekeeping workers must not survive shutdown.
+
+ concurrent.futures' atexit hook joins non-daemon workers; a pool left running would strand
+ the process "down but not exited".
+ """
+ runner = _runner()
+ hk = runner._get_housekeeping_executor()
+ assert not hk._shutdown
+
+ runner._shutdown_executor()
+
+ assert hk._shutdown, "housekeeping pool was left running at shutdown"
+ assert runner._housekeeping_executor is None
+ with pytest.raises(RuntimeError):
+ runner._get_housekeeping_executor()
+
+
+def test_get_executor_works_on_a_bare_duck_typed_double():
+ """_get_executor is called UNBOUND against minimal doubles; keep it self-contained.
+
+ Existing suites do ``GatewayRunner._get_executor(fake)`` where ``fake`` implements only a
+ handful of attributes. Routing the body through a sibling METHOD broke those doubles with
+ AttributeError, so the get-or-create helper is a module-level function and this pins it.
+ """
+ double = types.SimpleNamespace(_executor=None, _executor_closing=False)
+ pool = GatewayRunner._get_executor(double)
+ try:
+ assert isinstance(pool, concurrent.futures.ThreadPoolExecutor)
+ assert double._executor is pool
+ # Same for the housekeeping pool, on a double that has never heard of it.
+ hk_double = types.SimpleNamespace(_executor_closing=False)
+ hk = GatewayRunner._get_housekeeping_executor(hk_double)
+ try:
+ assert hk is not pool
+ finally:
+ hk.shutdown(wait=False)
+ finally:
+ pool.shutdown(wait=False)
+
+
+def test_pool_sizes_are_configurable(monkeypatch):
+ monkeypatch.setenv("HERMES_GATEWAY_EXECUTOR_MAX_WORKERS", "17")
+ monkeypatch.setenv("HERMES_GATEWAY_HOUSEKEEPING_MAX_WORKERS", "3")
+ runner = _runner()
+ try:
+ assert runner._get_executor()._max_workers == 17
+ assert runner._get_housekeeping_executor()._max_workers == 3
+ finally:
+ _stop(runner)
+
+
[email protected]("bad", ["0", "-4", "not-a-number", ""])
+def test_invalid_pool_size_falls_back_to_default(monkeypatch, bad):
+ """A typo in an ops knob must not create a zero-width or crashing pool."""
+ monkeypatch.setenv("HERMES_GATEWAY_EXECUTOR_MAX_WORKERS", bad)
+ runner = _runner()
+ try:
+ pool = runner._get_executor()
+ assert isinstance(pool, concurrent.futures.ThreadPoolExecutor)
+ assert pool._max_workers == 10
+ finally:
+ _stop(runner)
+
+
+def test_contextvars_survive_both_pools():
+ """The context hop is why these helpers exist; it must not regress."""
+ from contextvars import ContextVar
+
+ probe: ContextVar[str] = ContextVar("probe", default="unset")
+ runner = _runner()
+
+ async def exercise():
+ probe.set("scoped")
+ turn = await runner._run_in_executor_with_context(probe.get)
+ hk = await runner._run_housekeeping_in_executor("cleanup", probe.get)
+ return turn, hk
+
+ try:
+ assert asyncio.run(exercise()) == ("scoped", "scoped")
+ finally:
+ _stop(runner)
+
+
+def test_args_results_and_errors_round_trip():
+ """The timing wrapper must be transparent to args, results and exceptions."""
+ runner = _runner()
+
+ async def exercise():
+ assert await runner._run_in_executor_with_context(lambda a, b: a + b, 2, 3) == 5
+ with pytest.raises(ValueError, match="boom"):
+ await runner._run_housekeeping_in_executor("cleanup", _raise_boom)
+
+ try:
+ asyncio.run(exercise())
+ finally:
+ _stop(runner)
+
+
+def _raise_boom():
+ raise ValueError("boom")