The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): drop the HERMES_GATEWAY_* executor knobs
kshitijk4poor86b479eb36d6
diff --git a/gateway/run.py b/gateway/run.pyindex 10f3d1048a8..207c97b8a34 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -56,42 +56,10 @@ _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)+# Size of the separate pool for best-effort session HOUSEKEEPING (finalize hooks, agent cleanup).+# It is separate from the turn pool because housekeeping callers ABANDON their worker on timeout —+# see _run_housekeeping_in_executor.+_HOUSEKEEPING_MAX_WORKERS = 4def _get_or_create_pool(@@ -118,15 +86,7 @@ def _get_or_create_pool(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+_EXECUTOR_WAIT_WARN_SECS = 5.0# 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")@@ -4377,7 +4337,7 @@ class GatewayRunner(loop = asyncio.get_running_loop()ctx = copy_context()submitted_at = time.monotonic()- warn_after = _executor_wait_warn_secs()+ warn_after = _EXECUTOR_WAIT_WARN_SECSdef _timed(*call_args):waited = time.monotonic() - submitted_at@@ -4400,15 +4360,13 @@ class GatewayRunner(def _get_executor(self) -> concurrent.futures.ThreadPoolExecutor:"""Return the gateway-owned executor for blocking agent work."""- return _get_or_create_pool(- self, "_executor", "hermes-gateway", _executor_max_workers())+ return _get_or_create_pool(self, "_executor", "hermes-gateway", 10)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())+ self, "_housekeeping_executor", "hermes-gateway-hk", _HOUSEKEEPING_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.diff --git a/tests/gateway/test_executor_pool_isolation.py b/tests/gateway/test_executor_pool_isolation.pyindex 36c7c166063..051f68c96f4 100644--- a/tests/gateway/test_executor_pool_isolation.py+++ b/tests/gateway/test_executor_pool_isolation.py@@ -166,96 +166,6 @@ def test_turn_pool_still_queues_a_full_pool():_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.@@ -297,30 +207,6 @@ def test_get_executor_works_on_a_bare_duck_typed_double():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