The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): isolate control routes from default executor
fangliquanflqcb54576b1ae0
diff --git a/hermes_cli/web_routers/profiles.py b/hermes_cli/web_routers/profiles.pyindex 77ff1ad50aa..c0669510a49 100644--- a/hermes_cli/web_routers/profiles.py+++ b/hermes_cli/web_routers/profiles.py@@ -79,6 +79,7 @@ _profile_setup_command = late("_profile_setup_command")_profile_to_dict = late("_profile_to_dict")_resolve_profile_dir = late("_resolve_profile_dir")_spawn_hermes_action = late("_spawn_hermes_action")+run_in_threadpool = late("run_in_threadpool")_strip_session_list_rows = late("_strip_session_list_rows")_write_profile_mcp_servers = late("_write_profile_mcp_servers")_write_profile_model = late("_write_profile_model")@@ -777,8 +778,7 @@ def post_profiles_sessions_pull_requests(body: SessionPrScanBody):async def list_profiles_endpoint():from hermes_cli import profiles as profiles_modtry:- loop = asyncio.get_running_loop()- profiles = await loop.run_in_executor(None, profiles_mod.list_profiles)+ profiles = await run_in_threadpool(profiles_mod.list_profiles)return {"profiles": [_profile_to_dict(p) for p in profiles]}except Exception:_log.exception("GET /api/profiles failed; falling back to profile directory scan")diff --git a/hermes_cli/web_routers/tools.py b/hermes_cli/web_routers/tools.pyindex 7cd5099e235..f6ebace20c9 100644--- a/hermes_cli/web_routers/tools.py+++ b/hermes_cli/web_routers/tools.py@@ -43,6 +43,7 @@ _spawn_hermes_action = late("_spawn_hermes_action")_toolset_model_catalog = late("_toolset_model_catalog")load_config = late("load_config")save_config = late("save_config")+run_in_threadpool = late("run_in_threadpool")# Live proxies for web_server-owned module state (mutations/monkeypatches# on web_server remain authoritative; resolved at operation time).@@ -90,7 +91,7 @@ async def get_toolsets(profile: Optional[str] = None):features = get_nous_subscription_features(config)return config, toolset_rows, enabled_by_platform, features- config, toolset_rows, enabled_by_platform, features = await asyncio.to_thread(_read)+ config, toolset_rows, enabled_by_platform, features = await run_in_threadpool(_read)result = []for name, label, desc in toolset_rows:try:diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 419a4bb00c4..09b98ea97e4 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -2061,10 +2061,9 @@ def _count_status_active_sessions() -> int:async def _status_active_sessions() -> int:- loop = asyncio.get_running_loop()try:return await asyncio.wait_for(- loop.run_in_executor(None, _count_status_active_sessions),+ run_in_threadpool(_count_status_active_sessions),timeout=_STATUS_ACTIVE_SESSIONS_TIMEOUT,)except asyncio.TimeoutError:@@ -3880,9 +3879,7 @@ async def get_status(profile: Optional[str] = None):# ``<profile>:<platform>`` grammar so fleet health sees them (OOF-3).# A ``?profile=`` request targets one profile's view and is left# unmerged.- topology = await asyncio.get_running_loop().run_in_executor(- None, _collect_profile_gateway_topology_cached- )+ topology = await run_in_threadpool(_collect_profile_gateway_topology_cached)if not requested_profile:gateway_platforms = _merge_profile_gateway_platforms(gateway_platforms, topology.get("profile_platforms") or {}@@ -3911,11 +3908,9 @@ async def get_status(profile: Optional[str] = None):# Windows install the first import of hermes_cli.gateway blocks the# asyncio event loop for 15-30s (.pyc compilation + Defender scans),# exceeding the desktop handshake's 15s socket timeout. After the- # first call the module is in sys.modules and run_in_executor returns+ # first call the module is in sys.modules and the worker call returns# in microseconds.- restart_drain_timeout = await asyncio.get_running_loop().run_in_executor(- None, _resolve_restart_drain_timeout- )+ restart_drain_timeout = await run_in_threadpool(_resolve_restart_drain_timeout)# Dashboard auth gate (Phase 7): surface whether the gate is engaged# and which providers are registered so ``hermes status`` and the@@ -3994,9 +3989,7 @@ async def get_status(profile: Optional[str] = None):# may touch disk, so keep it off the event loop; afterwards it is a# process-global cache hit. Omitted (not null) when unpersistable so# older-client behavior and the no-identity fallback stay identical.- install_id = await asyncio.get_running_loop().run_in_executor(- None, get_install_id- )+ install_id = await run_in_threadpool(get_install_id)if install_id:status["install_id"] = install_id@@ -4015,9 +4008,7 @@ async def get_status(profile: Optional[str] = None):try:from gateway.readiness import _probe_state_db- storage_check = await asyncio.get_running_loop().run_in_executor(- None, functools.partial(_probe_state_db, get_hermes_home())- )+ storage_check = await run_in_threadpool(_probe_state_db, get_hermes_home())components["storage"] = {"status": storage_check.get("status", "degraded")}except Exception:components["storage"] = {"status": "degraded"}@@ -4055,12 +4046,9 @@ async def get_status(profile: Optional[str] = None):try:from gateway.memory_status import collect_memory_status- status["memory"] = await asyncio.get_running_loop().run_in_executor(- None,- functools.partial(- collect_memory_status,- profile_dir if profile_dir else get_hermes_home(),- ),+ status["memory"] = await run_in_threadpool(+ collect_memory_status,+ profile_dir if profile_dir else get_hermes_home(),)except Exception:status["memory"] = {"pressure": "unknown"}@@ -4073,12 +4061,9 @@ async def get_status(profile: Optional[str] = None):try:from gateway.disk_status import collect_disk_status- status["disk"] = await asyncio.get_running_loop().run_in_executor(- None,- functools.partial(- collect_disk_status,- profile_dir if profile_dir else get_hermes_home(),- ),+ status["disk"] = await run_in_threadpool(+ collect_disk_status,+ profile_dir if profile_dir else get_hermes_home(),)except Exception:status["disk"] = {"pressure": "unknown"}diff --git a/tests/hermes_cli/test_web_server_executor_isolation.py b/tests/hermes_cli/test_web_server_executor_isolation.pynew file mode 100644index 00000000000..0fe98cbadc2--- /dev/null+++ b/tests/hermes_cli/test_web_server_executor_isolation.py@@ -0,0 +1,128 @@+"""Control-plane routes stay available when asyncio's default pool is wedged.++Regression for #95559: the event loop and lightweight async routes remained+healthy, but management routes queued blocking work behind an unavailable+default executor and timed out until the Desktop backend was restarted.+"""++from __future__ import annotations++import asyncio+import concurrent.futures+import threading++import pytest+++def _occupy_default_executor(loop: asyncio.AbstractEventLoop):+ release = threading.Event()+ started = threading.Event()+ pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)+ loop.set_default_executor(pool)++ def _block() -> None:+ started.set()+ release.wait()++ future = loop.run_in_executor(None, _block)+ return pool, future, started, release+++async def _request_with_wedged_default_executor(path: str, *, warm: bool = False):+ try:+ import httpx+ except ImportError:+ pytest.skip("httpx not installed")++ from hermes_cli import web_server++ if warm:+ warm_transport = httpx.ASGITransport(app=web_server.app)+ async with httpx.AsyncClient(+ transport=warm_transport,+ base_url="http://testserver",+ headers={web_server._SESSION_HEADER_NAME: web_server._SESSION_TOKEN},+ ) as client:+ warm_response = await client.get(path)+ assert warm_response.status_code == 200++ loop = asyncio.get_running_loop()+ pool, blocker, started, release = _occupy_default_executor(loop)+ try:+ for _ in range(100):+ if started.is_set():+ break+ await asyncio.sleep(0.01)+ assert started.is_set(), "default-executor blocker did not start"++ transport = httpx.ASGITransport(app=web_server.app)+ async with httpx.AsyncClient(+ transport=transport,+ base_url="http://testserver",+ headers={web_server._SESSION_HEADER_NAME: web_server._SESSION_TOKEN},+ ) as client:+ return await asyncio.wait_for(client.get(path), timeout=2.0)+ finally:+ release.set()+ await blocker+ pool.shutdown(wait=True, cancel_futures=True)+++def test_profiles_route_survives_default_executor_starvation(monkeypatch):+ from hermes_cli import profiles++ monkeypatch.setattr(profiles, "list_profiles", lambda: [])++ response = asyncio.run(_request_with_wedged_default_executor("/api/profiles"))++ assert response.status_code == 200+ assert response.json() == {"profiles": []}+++def test_toolsets_route_survives_default_executor_starvation(monkeypatch):+ from hermes_cli import platforms, tools_config+ import toolsets++ monkeypatch.setattr(+ tools_config,+ "_get_effective_configurable_toolsets",+ lambda: [("test", "Test", "Test toolset")],+ )+ monkeypatch.setattr(tools_config, "_toolset_configuration_platform", lambda _name: "cli")+ monkeypatch.setattr(tools_config, "_get_platform_tools", lambda *_args, **_kwargs: [])+ monkeypatch.setattr(tools_config, "get_nous_subscription_features", lambda _cfg: {})+ monkeypatch.setattr(tools_config, "_toolset_has_keys", lambda *_args, **_kwargs: False)+ monkeypatch.setattr(tools_config, "gui_toolset_label", lambda label: label)+ monkeypatch.setattr(platforms, "platform_label", lambda _key, fallback: fallback)+ monkeypatch.setattr(toolsets, "resolve_toolset", lambda _name: [])++ response = asyncio.run(+ _request_with_wedged_default_executor("/api/tools/toolsets")+ )++ assert response.status_code == 200+ assert isinstance(response.json(), list)+++def test_status_route_survives_default_executor_starvation(monkeypatch):+ from hermes_cli import web_server++ monkeypatch.setattr(+ web_server,+ "_collect_profile_gateway_topology_cached",+ lambda: {+ "profiles": ["default"],+ "gateway_mode": "none",+ "gateways": [],+ "profile_platforms": {},+ },+ )+ monkeypatch.setattr(web_server, "_resolve_restart_drain_timeout", lambda: 30.0)+ monkeypatch.setattr(web_server, "get_install_id", lambda: None)++ response = asyncio.run(+ _request_with_wedged_default_executor("/api/status", warm=True)+ )++ assert response.status_code == 200+ assert response.json()["version"]