Skip to content

The agent that grows with you

fix(local-runtime): abandoned requests must not keep the GPU decoding

emozillaf373a2c5a6b9
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index b5aeae274f0..e2b72dc11cc 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -8643,12 +8643,21 @@ def _build_call_kwargs(
from hermes_cli.providers import nous_api_mode
_nous_on_messages = nous_api_mode(model) == "anthropic_messages"
+ # The managed local llama-server honors explicit caps too: a local
+ # decode burns the user's own GPU at full tilt, so a caller that
+ # says "this is a 64-token task" must be believed — an uncapped
+ # local generation whose EOS never comes runs to the full context
+ # window. No wire-format quirks apply (llama.cpp accepts
+ # max_tokens), and the no-default-cap policy is unchanged: this
+ # only forwards caps callers explicitly set.
+ _is_managed_local = _is_managed_local_endpoint(_effective_base)
if (
_is_anthropic_compat_endpoint(provider, _effective_base)
or _nous_on_messages
or _is_nvidia_nim
or _is_moa
or _is_gemini_native
+ or _is_managed_local
):
# Use auxiliary_max_tokens_param() so models that require
# max_completion_tokens (GPT-5 family, Copilot) get the right
@@ -8994,6 +9003,49 @@ def _is_streaming_rejected_error(exc: Exception) -> bool:
)
+_MANAGED_LOCAL_STATE_TTL_S = 15.0
+_managed_local_cache: "tuple[float, str]" = (0.0, "")
+
+
+def _managed_local_netloc() -> str:
+ """host:port of the managed local llama-server, or "" when none.
+
+ Read from the supervisor's state file (written at spawn, removed on
+ stop) with a short TTL so per-request checks don't hit the disk. The
+ state file is the same source provider resolution uses, so the match
+ is exact — no false positives on other localhost endpoints.
+ """
+ global _managed_local_cache
+ now = time.monotonic()
+ ts, cached = _managed_local_cache
+ if now - ts < _MANAGED_LOCAL_STATE_TTL_S:
+ return cached
+ netloc = ""
+ try:
+ from hermes_cli.local_runtime.supervisor import state_path
+
+ raw = state_path().read_text(encoding="utf-8")
+ base = str((json.loads(raw) or {}).get("base_url", ""))
+ netloc = urlparse(base).netloc.lower()
+ except Exception:
+ netloc = ""
+ _managed_local_cache = (now, netloc)
+ return netloc
+
+
+def _is_managed_local_endpoint(base_url: Optional[str]) -> bool:
+ """True when *base_url* targets the llama-server this Hermes manages."""
+ if not base_url:
+ return False
+ managed = _managed_local_netloc()
+ if not managed:
+ return False
+ try:
+ return urlparse(str(base_url)).netloc.lower() == managed
+ except Exception:
+ return False
+
+
def _provider_requires_stream(provider: str, base_url: Optional[str]) -> bool:
"""Detect providers that only accept streaming (non-stream = HTTP 400).
@@ -9009,6 +9061,18 @@ def _provider_requires_stream(provider: str, base_url: Optional[str]) -> bool:
Beyond the known-host list, users can mark ANY custom endpoint as
stream-only via ``auxiliary.stream_only_base_urls`` in config.yaml
(list of substrings matched against the endpoint URL).
+
+ The managed local llama-server is always streamed for a different
+ reason: cancellation. llama-server only notices a dead client when it
+ writes to the socket. A non-streamed request writes once — after the
+ FULL generation — so an abandoned call (client timeout, retry, app
+ exit) keeps the GPU decoding to the end of the context window with
+ nobody listening; requests that queue behind a model load are the
+ worst case, since the client is long gone before decode even starts.
+ Streaming writes every few tokens, so an abandoned decode dies at the
+ first post-disconnect chunk (verified against llama-server b10362:
+ streamed disconnect cancels in <1s through the router; non-streamed
+ survives until the server's next incidental socket poll, if ever).
"""
_url = str(base_url or "").lower()
if not _url:
@@ -9016,6 +9080,9 @@ def _provider_requires_stream(provider: str, base_url: Optional[str]) -> bool:
# Tencent Copilot — "Non-stream chat request is currently not supported"
if base_url_host_matches(_url, "copilot.tencent.com"):
return True
+ # Managed local llama-server — streamed so abandonment cancels decode.
+ if _is_managed_local_endpoint(_url):
+ return True
try:
from hermes_cli.config import load_config
aux_cfg = (load_config() or {}).get("auxiliary", {})
diff --git a/hermes_cli/local_runtime/supervisor.py b/hermes_cli/local_runtime/supervisor.py
index 395d5cda08f..53ef6056356 100644
--- a/hermes_cli/local_runtime/supervisor.py
+++ b/hermes_cli/local_runtime/supervisor.py
@@ -251,6 +251,7 @@ class LlamaServerSupervisor:
time.sleep(backoff)
self._restarts += 1
try:
+ self._reap_orphaned_children()
self._spawn()
self._wait_health(120)
if self.primary_model:
@@ -262,15 +263,78 @@ class LlamaServerSupervisor:
self._stopping = True
state_path().unlink(missing_ok=True)
if self.proc and self.proc.poll() is None:
- self.proc.terminate()
- try:
- self.proc.wait(timeout=15)
- except subprocess.TimeoutExpired:
- self.proc.kill()
+ self._terminate_tree(self.proc)
if self._log_handle:
self._log_handle.close()
self._log_handle = None
+ @staticmethod
+ def _terminate_tree(proc: subprocess.Popen) -> None:
+ """Terminate the router AND its model children.
+
+ The router spawns one child llama-server per loaded model, each
+ holding gigabytes of VRAM. Terminating only the router (on
+ Windows, TerminateProcess — no signal handlers, no cleanup pass)
+ orphans those children: the port goes quiet but the weights stay
+ resident, and the next spawn re-loads models alongside a ghost
+ still holding the memory. Enumerate children FIRST (the parent
+ must be alive to walk them), then terminate parent and children
+ together, escalating to kill for stragglers.
+ """
+ children: list = []
+ try:
+ import psutil
+
+ children = psutil.Process(proc.pid).children(recursive=True)
+ except Exception: # noqa: BLE001 — no psutil view; still stop the router
+ children = []
+ proc.terminate()
+ for child in children:
+ try:
+ child.terminate()
+ except Exception: # noqa: BLE001
+ pass
+ try:
+ proc.wait(timeout=15)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ for child in children:
+ try:
+ if child.is_running():
+ child.kill()
+ except Exception: # noqa: BLE001
+ pass
+
+ def _reap_orphaned_children(self) -> None:
+ """Kill model children orphaned by a router crash, before respawn.
+
+ A crashed router can't clean up its children, and a dead parent
+ can't be walked — so match by identity instead: any process
+ running OUR llama-server binary whose parent is gone is an
+ orphan of a previous router. Their VRAM must come back before
+ the new router loads models next to the ghosts. External
+ llama-servers (different binary path) never match.
+ """
+ try:
+ import psutil
+
+ exe = str(server_binary(self.install_dir))
+ except Exception: # noqa: BLE001
+ return
+ for p in psutil.process_iter(["exe", "ppid"]):
+ try:
+ if p.info.get("exe") != exe:
+ continue
+ if self.proc is not None and p.pid == self.proc.pid:
+ continue
+ ppid = p.info.get("ppid") or 0
+ if ppid and psutil.pid_exists(ppid):
+ continue
+ logger.warning("reaping orphaned llama-server child pid=%s", p.pid)
+ p.kill()
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ continue
+
# ── model management (router endpoints) ──────────────────
def models(self) -> dict:
diff --git a/tests/hermes_cli/test_local_abandoned_requests.py b/tests/hermes_cli/test_local_abandoned_requests.py
new file mode 100644
index 00000000000..06bfbe6e36a
--- /dev/null
+++ b/tests/hermes_cli/test_local_abandoned_requests.py
@@ -0,0 +1,210 @@
+"""Abandoned-request lifecycle: work sent to the managed local server must
+die when its caller goes away, and teardown must never orphan VRAM.
+
+The incident this guards: auxiliary calls (title generation + retries)
+queued at the router behind a cold model load, their clients timed out
+and hung up, and the router then dispatched them anyway. Non-streamed
+responses write the socket only after the FULL generation, so nothing
+noticed the dead clients — two uncapped decodes ran at full GPU for the
+better part of an hour with nobody listening.
+
+Three contracts, one per failure link:
+1. Auxiliary requests to the managed local endpoint are always streamed
+ (a dead client then cancels decode at the first chunk write).
+2. Explicit caller max_tokens caps reach the managed local endpoint
+ (title generation's 64-token cap must not be silently dropped).
+3. Supervisor teardown terminates the whole process tree, and a router
+ respawn reaps orphaned model children first (each holds GiB of VRAM).
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import types
+
+import pytest
+
+import agent.auxiliary_client as aux
+from hermes_cli.local_runtime.supervisor import LlamaServerSupervisor
+
+
+MANAGED_URL = "http://127.0.0.1:18434/v1"
+
+
+def managed_state(tmp_path, monkeypatch):
+ """A supervisor state file declaring the managed endpoint, cache reset."""
+ state = tmp_path / "server.json"
+ state.write_text(json.dumps({"base_url": MANAGED_URL, "api_key": "k",
+ "pid": 4242}), encoding="utf-8")
+ monkeypatch.setattr("hermes_cli.local_runtime.supervisor.state_path",
+ lambda: state)
+ monkeypatch.setattr(aux, "_managed_local_cache", (0.0, ""))
+ return state
+
+
+# ── 1. managed endpoint is always streamed ───────────────────
+
+
+def test_managed_endpoint_requires_stream(managed_state):
+ assert aux._provider_requires_stream("custom", MANAGED_URL) is True
+
+
+def test_managed_detection_matches_netloc_not_substring(managed_state):
+ # Same host, different port: a user's own external server — untouched.
+ assert aux._provider_requires_stream("custom", "http://127.0.0.1:8080/v1") is False
+
+
+def test_no_state_file_means_no_managed_endpoint(tmp_path, monkeypatch):
+ monkeypatch.setattr("hermes_cli.local_runtime.supervisor.state_path",
+ lambda: tmp_path / "absent.json")
+ monkeypatch.setattr(aux, "_managed_local_cache", (0.0, ""))
+ assert aux._is_managed_local_endpoint(MANAGED_URL) is False
+
+
+def test_remote_providers_unaffected(managed_state):
+ assert aux._provider_requires_stream("nous",
+ "https://inference-api.nousresearch.com/v1/") is False
+
+
+# ── 2. explicit caps reach the managed endpoint ──────────────
+
+
+def test_explicit_max_tokens_forwarded_to_managed_local(managed_state, monkeypatch):
+ monkeypatch.setattr(aux, "_current_custom_base_url", lambda: MANAGED_URL)
+ kwargs = aux._build_call_kwargs(
+ "custom", "Qwen-Local", [{"role": "user", "content": "hi"}],
+ max_tokens=64, timeout=30.0, task="title_generation")
+ assert kwargs.get("max_tokens") == 64 or kwargs.get("max_completion_tokens") == 64, (
+ "explicit caller cap dropped on the managed local endpoint — an "
+ "EOS-less generation then runs to the full context window")
+
+
+def test_no_default_cap_policy_unchanged_for_remote(monkeypatch):
+ monkeypatch.setattr(aux, "_managed_local_cache", (0.0, ""))
+ kwargs = aux._build_call_kwargs(
+ "openrouter", "some/model", [{"role": "user", "content": "hi"}],
+ max_tokens=64, timeout=30.0)
+ assert "max_tokens" not in kwargs and "max_completion_tokens" not in kwargs
+
+
+# ── 3. teardown kills the tree; respawn reaps orphans ────────
+
+
+class _FakeChild:
+ def __init__(self, pid):
+ self.pid = pid
+ self.terminated = False
+ self.killed = False
+
+ def terminate(self):
+ self.terminated = True
+
+ def is_running(self):
+ return not self.terminated and not self.killed
+
+ def kill(self):
+ self.killed = True
+
+
+def test_terminate_tree_terminates_children_too(monkeypatch):
+ children = [_FakeChild(101), _FakeChild(102)]
+
+ class _FakeParentProc:
+ def __init__(self, pid):
+ self.pid = pid
+
+ def children(self, recursive=False):
+ assert recursive is True
+ return children
+
+ fake_psutil = types.SimpleNamespace(Process=_FakeParentProc)
+ monkeypatch.setitem(__import__("sys").modules, "psutil", fake_psutil)
+
+ class _FakeRouter:
+ pid = 4242
+ terminated = False
+
+ def terminate(self):
+ _FakeRouter.terminated = True
+
+ def wait(self, timeout=None):
+ return 0
+
+ def poll(self):
+ return None
+
+ LlamaServerSupervisor._terminate_tree(_FakeRouter())
+ assert _FakeRouter.terminated
+ assert all(c.terminated for c in children), (
+ "router children orphaned on stop — each holds GiB of VRAM")
+
+
+def test_terminate_tree_survives_missing_psutil(monkeypatch):
+ import builtins
+
+ real_import = builtins.__import__
+
+ def _no_psutil(name, *a, **k):
+ if name == "psutil":
+ raise ImportError("nope")
+ return real_import(name, *a, **k)
+
+ monkeypatch.setattr(builtins, "__import__", _no_psutil)
+
+ class _FakeRouter:
+ pid = 4242
+ terminated = False
+
+ def terminate(self):
+ _FakeRouter.terminated = True
+
+ def wait(self, timeout=None):
+ return 0
+
+ LlamaServerSupervisor._terminate_tree(_FakeRouter())
+ assert _FakeRouter.terminated # router still stopped without psutil
+
+
+def test_reap_orphans_kills_only_our_parentless_binaries(tmp_path, monkeypatch):
+ exe = tmp_path / "llama-server.exe"
+ exe.write_text("")
+
+ orphan = _FakeChild(300)
+ adopted = _FakeChild(301) # parent alive -> not an orphan
+ foreign = _FakeChild(302) # different binary -> never touched
+
+ def _info(pid, exe_path, ppid):
+ p = _FakeChild(pid)
+ p.info = {"exe": exe_path, "ppid": ppid}
+ return p
+
+ procs = [
+ _info(300, str(exe), 9999), # dead parent -> reap
+ _info(301, str(exe), 1), # live parent -> keep
+ _info(302, str(tmp_path / "other.exe"), 9999), # foreign -> keep
+ ]
+ reaped = []
+ for p in procs:
+ p.kill = lambda p=p: reaped.append(p.info and p.pid)
+
+ class _NoSuch(Exception):
+ pass
+
+ fake_psutil = types.SimpleNamespace(
+ process_iter=lambda attrs: procs,
+ pid_exists=lambda pid: pid == 1,
+ NoSuchProcess=_NoSuch,
+ AccessDenied=_NoSuch,
+ )
+ monkeypatch.setitem(__import__("sys").modules, "psutil", fake_psutil)
+ monkeypatch.setattr("hermes_cli.local_runtime.supervisor.server_binary",
+ lambda install_dir: exe)
+
+ sup = LlamaServerSupervisor.__new__(LlamaServerSupervisor)
+ sup.install_dir = tmp_path
+ sup.proc = None
+ sup._reap_orphaned_children()
+
+ assert reaped == [300], f"reaped {reaped}; wanted only the orphan (300)"
diff --git a/tests/hermes_cli/test_local_server_lifecycle.py b/tests/hermes_cli/test_local_server_lifecycle.py
index 8c620bc5b4b..7a2c5300efd 100644
--- a/tests/hermes_cli/test_local_server_lifecycle.py
+++ b/tests/hermes_cli/test_local_server_lifecycle.py
@@ -101,8 +101,11 @@ def test_status_reports_loaded_models_from_live_router(client, monkeypatch):
threading.Thread(target=server.serve_forever, daemon=True).start()
try:
port = server.server_address[1]
+ # Patch the ROUTE's binding: local_models binds _state_endpoint via
+ # from-import at module load, so patching the endpoint module's
+ # attribute never reaches the name the route actually calls.
monkeypatch.setattr(
- "hermes_cli.local_runtime.endpoint._state_endpoint",
+ "hermes_cli.web_routers.local_models._state_endpoint",
lambda: {"base_url": f"http://127.0.0.1:{port}/v1", "api_key": "k"})
payload = client.get("/api/local-models/status").json()
assert payload["server_running"] is True