The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): keep slow hosted plugin requests off the gateway's shared threads
unsupportedpastels358ed4c3055d
diff --git a/hermes_cli/plugin_host.py b/hermes_cli/plugin_host.pyindex b0cd37ee545..e36c22ef59d 100644--- a/hermes_cli/plugin_host.py+++ b/hermes_cli/plugin_host.py@@ -78,6 +78,10 @@ class PluginHost:def pid(self) -> Optional[int]:return self._proc.pid if self._proc is not None else None+ @property+ def home(self) -> Path:+ return self._home+@propertydef alive(self) -> bool:return (self._channel is not None and self._channel.closed_reason is None@@ -287,12 +291,14 @@ class PluginHost:"attr": attr, "args": encode(list(args)), "kwargs": encode(kwargs)})def asgi_request(self, plugin_name: str, dashboard_dir: str, api_file: str, method: str, path: str,- query: str, headers: list, body: bytes) -> dict[str, Any]:- """One dashboard ``/api/plugins/<name>/`` request, served by the plugin's router in the host."""+ query: str, headers: list, body: bytes, *, timeout: Optional[float] = None) -> dict[str, Any]:+ """One dashboard ``/api/plugins/<name>/`` request, served by the plugin's router in the host;+ ``TimeoutError`` when no answer comes within ``timeout`` seconds (the host is left running)."""self.ensure_started()return self._call("asgi", {"plugin": plugin_name, "dashboard_dir": dashboard_dir, "api_file": api_file,"method": method, "path": path, "query": query,- "headers": [list(h) for h in headers], "body": encode(body)})+ "headers": [list(h) for h in headers], "body": encode(body)},+ timeout=timeout)def _unload(self, plugin_key: str) -> None:self._contexts.pop(plugin_key, None)@@ -304,7 +310,8 @@ class PluginHost:logger.warning("Plugin '%s' on_unload callback failed in the plugin host: %s", plugin_key, error)# -- parent -> host ------------------------------------------------------------------------------ def _call(self, method: str, params: dict[str, Any], *, generation: Optional[int] = None) -> Any:+ def _call(self, method: str, params: dict[str, Any], *, generation: Optional[int] = None,+ timeout: Optional[float] = None) -> Any:channel = self._channeltry:if channel is None:@@ -314,7 +321,7 @@ class PluginHost:if self._releases:released, self._releases = self._releases, []channel.call("release", {"refs": released})- return decode(channel.call(method, params), self._resolve_ref)+ return decode(channel.call(method, params, timeout=timeout), self._resolve_ref)except PluginHostUnavailable as exc:raise PluginHostUnavailable(self._exit_reason()) from excdiff --git a/hermes_cli/web_server_dashboard.py b/hermes_cli/web_server_dashboard.pyindex f8963cf19b9..d1321d29ad2 100644--- a/hermes_cli/web_server_dashboard.py+++ b/hermes_cli/web_server_dashboard.py@@ -969,11 +969,11 @@ def _mount_hosted_plugin_api(app, plugin: dict, api_file_name: str) -> None:if target is None:return JSONResponse({"detail": f"plugin {name!r} is not enabled in this profile"}, status_code=404)host, dashboard_dir, api_file = target- from hermes_cli.web_server_plugin_profiles import hosted_response- return hosted_response(await asyncio.to_thread(- host.asgi_request, name, dashboard_dir, api_file, request.method, "/" + path,- request.url.query, [(k, v) for k, v in request.headers.items() if k.lower() != "host"],- await request.body()))+ from hermes_cli.web_server_plugin_profiles import run_hosted_request+ query, headers = request.url.query, [(k, v) for k, v in request.headers.items() if k.lower() != "host"]+ body = await request.body()+ return await run_hosted_request(host.home, name, lambda timeout: host.asgi_request(+ name, dashboard_dir, api_file, request.method, "/" + path, query, headers, body, timeout=timeout))app.add_api_route(f"/api/plugins/{name}/{{path:path}}", forward, include_in_schema=False,methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"],diff --git a/hermes_cli/web_server_plugin_profiles.py b/hermes_cli/web_server_plugin_profiles.pyindex e8650a45d45..2c6c497e1f9 100644--- a/hermes_cli/web_server_plugin_profiles.py+++ b/hermes_cli/web_server_plugin_profiles.py@@ -12,11 +12,14 @@ profile's plugin websockets are refused by name until it carries them.from __future__ import annotationsimport asyncio+import contextvarsimport loggingimport threading+import time+from concurrent.futures import ThreadPoolExecutorfrom contextlib import ExitStack, contextmanagerfrom pathlib import Path-from typing import Any, Iterator, Optional+from typing import Any, Callable, Iterator, Optionalfrom urllib.parse import parse_qsl, urlencodefrom fastapi.responses import JSONResponse, Response@@ -38,6 +41,15 @@ _GATEWAY_QUERY_KEYS = frozenset({"token", "ticket", "internal", "display_ticket"_profile_plugins: dict[str, list] = {}_profile_plugins_lock = threading.Lock()+# Requests forwarded to a profile's plugin host wait on that profile's own threads, not the gateway's+# shared ``asyncio.to_thread`` pool: a slow plugin queues behind its own profile's plugin requests+# instead of stalling every route that offloads blocking work.+_HOSTED_REQUEST_THREADS = 4+# How long a forwarded request may take, queueing included, before it answers 504. The host protocol+# has no cancel, so the host may still finish the abandoned handler; the gateway's thread is freed.+HOSTED_REQUEST_TIMEOUT_SECS = 60.0+_hosted_executors: dict[str, ThreadPoolExecutor] = {}+def secondary_profile_home() -> Optional[Path]:"""The active scope's home when it is a profile other than the launch profile, else None."""@@ -144,12 +156,38 @@ def hosted_response(result: dict[str, Any]) -> Response:return response+def _hosted_executor(home: Path) -> ThreadPoolExecutor:+ from hermes_constants import hermes_home_key+ key = hermes_home_key(home)+ with _profile_plugins_lock:+ executor = _hosted_executors.get(key)+ if executor is None:+ executor = _hosted_executors[key] = ThreadPoolExecutor(+ _HOSTED_REQUEST_THREADS, thread_name_prefix=f"plugin-host-requests-{Path(home).name}")+ return executor+++async def run_hosted_request(home: Path, name: str, call: Callable[[float], dict[str, Any]]) -> Response:+ """Run ``call(timeout)``, one plugin host ``asgi`` round trip for plugin ``name`` of the profile at+ ``home``, on that profile's own threads in this request's context; its answer, or 504 after+ :data:`HOSTED_REQUEST_TIMEOUT_SECS`. Other failures propagate."""+ timeout = HOSTED_REQUEST_TIMEOUT_SECS+ deadline, context = time.monotonic() + timeout, contextvars.copy_context()+ job = asyncio.get_running_loop().run_in_executor(+ _hosted_executor(home), context.run, lambda: call(max(deadline - time.monotonic(), 0.01)))+ try:+ return hosted_response(await asyncio.wait_for(job, timeout))+ except TimeoutError:+ _log.warning("Plugin %s: its plugin host did not answer within %gs", name, timeout)+ return JSONResponse({"detail": f"plugin {name!r} did not answer within {timeout:g}s"}, status_code=504)++async def forward_secondary_plugin_request(request, name: str) -> Optional[Response]:"""Serve ``/api/plugins/<name>/`` for a secondary profile through its own plugin host, or Nonewhen the in-process router answers (the launch profile, or a bundled plugin). Consent has beenchecked in the request's scope already."""- plugin = _secondary_hosted_plugin(name)- if plugin is None:+ plugin, home = _secondary_hosted_plugin(name), secondary_profile_home()+ if plugin is None or home is None:return Noneif not plugin.get("_api_file"):return JSONResponse({"detail": "Not Found"}, status_code=404)@@ -160,14 +198,14 @@ async def forward_secondary_plugin_request(request, name: str) -> Optional[Respoheaders = [(k, v) for k, v in request.headers.items() if k.lower() not in _GATEWAY_CREDENTIAL_HEADERS]body = await request.body()- def call() -> dict[str, Any]:+ def call(timeout: float) -> dict[str, Any]:from hermes_cli.plugins import get_plugin_managerhost = get_plugin_manager()._plugin_host() # the active (secondary) profile's own hostreturn host.asgi_request(name, str(plugin["_dir"]), str(plugin["_api_file"]), request.method, path,- query, headers, body)+ query, headers, body, timeout=timeout)try:- return hosted_response(await asyncio.to_thread(call))+ return await run_hosted_request(home, name, call)except Exception as exc: # health: allow BLE001 -- the host runs third-party code; any failure is this request's 502_log.warning("Plugin %s: its profile's plugin host could not serve %s: %s", name, path, exc)return JSONResponse({"detail": f"plugin {name!r} could not run in this profile's plugin host"},diff --git a/tests/hermes_cli/test_plugin_api_consent_gate.py b/tests/hermes_cli/test_plugin_api_consent_gate.pyindex 0f225af30cd..113c805fcc8 100644--- a/tests/hermes_cli/test_plugin_api_consent_gate.py+++ b/tests/hermes_cli/test_plugin_api_consent_gate.py@@ -100,7 +100,7 @@ def daemon(_isolate_hermes_home, monkeypatch):monkeypatch.setattr(profiles, "_get_profiles_root", lambda: launch / "profiles")hosted, calls = [], []- def asgi_request(host, plugin, dashboard_dir, api_file, method, path, query, headers, body):+ def asgi_request(host, plugin, dashboard_dir, api_file, method, path, query, headers, body, **_):hosted.append(plugin)calls.append(SimpleNamespace(home=host._home, dir=dashboard_dir, path=path, query=query,headers={str(k).lower() for k, _ in headers}))diff --git a/tests/hermes_cli/test_plugin_secondary_profile_host.py b/tests/hermes_cli/test_plugin_secondary_profile_host.pyindex 4e982fede1c..b3b38655f75 100644--- a/tests/hermes_cli/test_plugin_secondary_profile_host.py+++ b/tests/hermes_cli/test_plugin_secondary_profile_host.py@@ -12,9 +12,12 @@ a recorder there; the last test runs a real one."""from __future__ import annotations+import asyncioimport jsonimport osimport sys+import threading+from concurrent.futures import ThreadPoolExecutorfrom pathlib import Pathfrom urllib.parse import parse_qsl, urljoin@@ -418,7 +421,120 @@ def test_secondary_plugin_runs_in_a_real_host_bound_to_its_home(daemon, monkeypaassert Path(body["home"]).resolve() == daemon.beta.resolve()assert _never_imported(imported)finally:- for manager in list(plugins_mod._plugin_managers_by_home.values()):- host = getattr(manager, "_plugin_host_instance", None)- if host is not None:- host.shutdown()+ _shutdown_hosts()+++def _shutdown_hosts():+ for manager in list(plugins_mod._plugin_managers_by_home.values()):+ host = getattr(manager, "_plugin_host_instance", None)+ if host is not None:+ host.shutdown()+++def _asgi_client():+ """An async client on the real app, so one test can hold requests in flight side by side."""+ import httpx++ async def loopback_peer(scope, receive, send):+ scope["hermes.gateway_socket_peer"] = ("127.0.0.1", 50000)+ await web_server.app(scope, receive, send)++ return httpx.AsyncClient(transport=httpx.ASGITransport(app=loopback_peer), base_url="http://testserver")+++def test_slow_hosted_requests_do_not_starve_the_gateways_shared_threads(daemon, monkeypatch):+ """A slow secondary-profile plugin ties up threads of its own host's forwarding only: with every+ hosted request still in flight, a ``to_thread`` route (the plugin list) answers."""+ _beta_plugin(daemon)+ release, selected = threading.Event(), {"params": {"profile": "beta"}, "headers": daemon.owner}++ async def scenario():+ loop = asyncio.get_running_loop()+ loop.set_default_executor(ThreadPoolExecutor(2)) # the gateway's shared pool, kept small+ started, two_started = [], asyncio.Event()++ def slow(host, *args, **kwargs):+ loop.call_soon_threadsafe(lambda: started.append(1) or (len(started) >= 2 and two_started.set()))+ release.wait(30)+ return {"status": 200, "headers": [], "body": b'{"hosted": true}'}++ monkeypatch.setattr(PluginHost, "asgi_request", slow)+ async with _asgi_client() as client:+ hosted = [asyncio.ensure_future(client.get(PING, **selected)) for _ in range(4)]+ try:+ await asyncio.wait_for(two_started.wait(), 30)+ try:+ listed = await asyncio.wait_for(client.get("/api/dashboard/plugins", **selected), 10)+ except TimeoutError:+ listed = None+ in_flight = not any(t.done() for t in hosted)+ finally:+ release.set()+ answers = await asyncio.gather(*hosted)+ return listed, in_flight, [a.status_code for a in answers]++ listed, in_flight, answers = asyncio.run(scenario())+ assert listed is not None, "the plugin list waited behind slow hosted plugin requests"+ assert listed.status_code == 200 and NAME in {p["name"] for p in listed.json()}+ assert in_flight and answers == [200] * 4+++_HANG_API = _HOME_API + '''+[email protected]("/hang")+async def hang():+ import asyncio+ await asyncio.Event().wait()+'''++[email protected]("posix") # the host is a real child process+def test_hung_hosted_request_answers_504_and_the_host_serves_the_next(daemon, monkeypatch):+ from hermes_cli import web_server_plugin_profiles+ monkeypatch.setattr(PluginHost, "asgi_request", _REAL_ASGI_REQUEST)+ monkeypatch.setattr(web_server_plugin_profiles, "HOSTED_REQUEST_TIMEOUT_SECS", 1.0, raising=False)+ _beta_plugin(daemon)+ (daemon.beta / "plugins" / NAME / "dashboard" / "plugin_api.py").write_text(_HANG_API)+ selected = {"params": {"profile": "beta"}, "headers": daemon.owner}+ whoami, hang = f"/api/plugins/{NAME}/whoami", f"/api/plugins/{NAME}/hang"++ async def scenario():+ async with _asgi_client() as client:+ try:+ before = await client.get(whoami, **selected)+ try:+ hung = await asyncio.wait_for(client.get(hang, **selected), 20)+ except TimeoutError:+ hung = None+ after = await client.get(whoami, **selected)+ finally:+ _shutdown_hosts() # also frees a request still parked on the host+ return before, hung, after++ before, hung, after = asyncio.run(scenario())+ assert hung is not None, "a hung plugin request never answered"+ assert hung.status_code == 504 and NAME in hung.json()["detail"]+ assert (before.status_code, after.status_code) == (200, 200)+ assert after.json()["pid"] == before.json()["pid"] # the same host, not a restarted one+++def test_launch_profiles_hosted_mount_answers_504_too(daemon, monkeypatch):+ """``plugins.isolation: host`` for the launch profile forwards through the same path."""+ from hermes_cli import web_server_plugin_profiles+ monkeypatch.setattr(web_server_plugin_profiles, "HOSTED_REQUEST_TIMEOUT_SECS", 0.2, raising=False)+ _install(daemon.launch, "launch-hosted")+ _plugins(daemon.launch, enabled=["launch-hosted"], isolation="host")+ homes = []++ def slow(host, *args, timeout=None, **kwargs):+ homes.append(host._home)+ threading.Event().wait(timeout or 3) # the channel's wait for a reply that never comes+ if timeout:+ raise TimeoutError+ return {"status": 200, "headers": [], "body": b"{}"}++ monkeypatch.setattr(PluginHost, "asgi_request", slow)+ response = daemon.client.get("/api/plugins/launch-hosted/ping", headers=daemon.owner)++ assert response.status_code == 504 and homes == [daemon.launch]+diff --git a/website/docs/user-guide/features/extending-the-dashboard.md b/website/docs/user-guide/features/extending-the-dashboard.mdindex 9be238716e1..1fafafd4e9d 100644--- a/website/docs/user-guide/features/extending-the-dashboard.md+++ b/website/docs/user-guide/features/extending-the-dashboard.md@@ -757,7 +757,8 @@ synchronous HTTP client, a long file scan) holds all of them until it returns: adelays an unrelated `/api/status` by seconds and can time out Desktop's connection. Use `async def` withasync I/O, or move blocking work off the loop with `await asyncio.to_thread(...)` (a plain `def` handleralso runs in a worker thread). `plugins.isolation: host` runs the handlers in a separate process-([plugin host](plugins.md#running-plugins-out-of-process-pluginsisolation)).+([plugin host](plugins.md#running-plugins-out-of-process-pluginsisolation)): a slow handler there+delays only that profile's hosted plugin requests, and one with no answer after 60 s gets HTTP 504.#### Accessing Hermes internalsdiff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex 397ee25b933..5b4bbcadf3d 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -842,7 +842,8 @@ its own dashboard plugins (installed under its own `plugins/` folder or the rootthe profile's own copy winning a same-name conflict, and enabled in its own config) in its own pluginhost, whatever its `plugins.isolation` says: another profile's plugin code never runs inside thegateway. The host does not carry websockets yet, so such a plugin's websocket routes are refused-(HTTP 501) for that profile; its HTTP routes work.+(HTTP 501) for that profile; its HTTP routes work. A slow hosted handler holds only its own profile's+plugin requests, and a request the host has not answered after 60 s gets HTTP 504.What changes in `host` mode: