Skip to content

The agent that grows with you

fix(local-runtime): stop only orphaned incumbents; owners free the server on exit

emozillad729da70da87
diff --git a/hermes_cli/local_runtime/bootstrap.py b/hermes_cli/local_runtime/bootstrap.py
index e12347d0f74..3815e21d673 100644
--- a/hermes_cli/local_runtime/bootstrap.py
+++ b/hermes_cli/local_runtime/bootstrap.py
@@ -10,7 +10,6 @@ from __future__ import annotations
from contextlib import contextmanager, suppress
import logging
import os
-import signal
import time
from pathlib import Path
@@ -20,6 +19,20 @@ from hermes_cli.local_runtime.gguf import SPLIT_PART_RE, model_id_from_stem
logger = logging.getLogger(__name__)
_SUPERVISOR = None # process-wide singleton; one router per Hermes process
+_EXIT_HOOKED = False
+
+
+def _stop_at_exit() -> None:
+ """The process that boots the server stops it on a clean exit, whatever surface it is (the
+ desktop backend also stops it in its shutdown handler; the second call is a no-op). Processes
+ that only adopted another's server never stop it. A hard kill still leaves an orphan, which the
+ next boot adopts or replaces."""
+ global _EXIT_HOOKED
+ if not _EXIT_HOOKED:
+ import atexit
+
+ atexit.register(shutdown_local_runtime)
+ _EXIT_HOOKED = True
def _detect_gpu_vendor() -> str | None:
@@ -134,25 +147,36 @@ def _presets_stale() -> bool:
return False
-def _stop_state_server(state: dict) -> None:
- """Best-effort stop of the server the state file points at (an incumbent this process doesn't
- supervise). The state pid is ours by contract — the file only ever describes the managed
- server."""
- from hermes_cli.local_runtime.endpoint import _pid_alive
-
+def _stop_state_server() -> bool:
+ """Stop the server the state file points at so this process can boot a replacement; False when
+ it must be left alone. Only an orphan (recorded owner gone) is stopped: a live owner's watchdog
+ would respawn its router beside ours. The process comes from the identity-guarded reader, never
+ a bare PID — the endpoint dict callers hold carries no process identity."""
+ from hermes_cli.local_runtime.recovery import (
+ _owner_is_dead,
+ is_modern,
+ legacy_recorded_process,
+ read_state,
+ recorded_process,
+ )
+ from hermes_cli.local_runtime.supervisor import LlamaServerSupervisor
+
+ state = read_state()
+ if is_modern(state):
+ if not _owner_is_dead(state):
+ logger.info("llama-server pid=%s belongs to a live Hermes process; leaving it", state.get("pid"))
+ return False
+ proc = recorded_process(state)
+ else:
+ proc = legacy_recorded_process(state)
+ if proc is None:
+ return True
try:
- pid = int(state.get("pid"))
- if pid <= 0:
- return
- os.kill(pid, signal.SIGTERM)
- except (TypeError, ValueError, OSError):
- return
- # Give it a moment to release the port and the GPU. Liveness via psutil — on Windows
- # os.kill(pid, 0) TERMINATES the process, it is not a probe.
- for _ in range(50):
- if not _pid_alive(pid):
- return
- time.sleep(0.1)
+ # Waits for the tree to exit, so the port and the GPU are free for the replacement.
+ LlamaServerSupervisor._terminate_tree(proc, verified_root=True)
+ except Exception as exc: # noqa: BLE001 - a failed stop must not block the replacement boot
+ logger.warning("could not stop the incumbent llama-server (pid=%s): %s", proc.pid, exc)
+ return True
def refresh_local_runtime() -> bool:
@@ -169,8 +193,8 @@ def refresh_local_runtime() -> bool:
state = _state_endpoint()
if state is None:
return False
- logger.info("bouncing adopted llama-server (pid=%s) to rescan models", state.get("pid"))
- _stop_state_server(state)
+ if not _stop_state_server():
+ return False
else:
shutdown_local_runtime()
return ensure_local_runtime(load_config(), force=True) is not None
@@ -410,7 +434,8 @@ def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":
return None
logger.info("running server's presets predate the staged models; "
"replacing it so every model launches with a policy")
- _stop_state_server(state)
+ if not _stop_state_server():
+ return None
try:
from hermes_cli.local_runtime.binaries import installed_engine
@@ -438,6 +463,7 @@ def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":
sup.stop()
raise
_SUPERVISOR = sup
+ _stop_at_exit()
logger.info("managed llama-server up at %s (backend=%s tag=%s)", sup.base_url, engine.backend, engine.tag)
_start_idle_sweeper(sup)
return sup
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index 79e53a53122..5ba61eb81a7 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -105,6 +105,8 @@ _ONESHOT_CLEANUPS = (
("tools.browser_tool_lifecycle", "_emergency_cleanup_all_sessions", {}, Exception),
("tools.mcp_tool_lifecycle", "shutdown_mcp_servers", {}, BaseException),
("agent.auxiliary_client", "shutdown_cached_clients", {}, Exception),
+ # A no-op unless this run booted the managed llama-server (atexit's hook is skipped here).
+ ("hermes_cli.local_runtime.bootstrap", "shutdown_local_runtime", {}, Exception),
)
diff --git a/tests/hermes_cli/test_boot_preset_staleness.py b/tests/hermes_cli/test_boot_preset_staleness.py
index fdc309567aa..c5c5c063277 100644
--- a/tests/hermes_cli/test_boot_preset_staleness.py
+++ b/tests/hermes_cli/test_boot_preset_staleness.py
@@ -79,9 +79,8 @@ def test_boot_replaces_incumbent_with_stale_presets(hermes_home, monkeypatch):
stopped = {}
monkeypatch.setattr(
"hermes_cli.local_runtime.endpoint._state_endpoint",
- lambda: {"base_url": "http://127.0.0.1:18434/v1", "pid": 12345})
- monkeypatch.setattr(boot, "_stop_state_server",
- lambda state: stopped.setdefault("pid", state["pid"]))
+ lambda: {"base_url": "http://127.0.0.1:18434/v1", "api_key": "k"})
+ monkeypatch.setattr(boot, "_stop_state_server", lambda: stopped.setdefault("stopped", True))
sentinel = object()
@@ -96,7 +95,7 @@ def test_boot_replaces_incumbent_with_stale_presets(hermes_home, monkeypatch):
"hermes_cli.local_runtime.binaries.installed_engine", fake_boot)
result = boot.ensure_local_runtime({"local_runtime": {"enabled": True}})
- assert stopped.get("pid") == 12345, "stale incumbent was not stopped"
+ assert stopped.get("stopped"), "stale incumbent was not stopped"
# Boot proceeded past adoption (our fake raised inside the try block,
# which ensure_local_runtime swallows into a None return).
assert result is None or result is sentinel
@@ -115,15 +114,14 @@ def test_refresh_bounces_an_adopted_server(hermes_home, monkeypatch):
monkeypatch.setattr(boot, "_SUPERVISOR", None)
monkeypatch.setattr(
"hermes_cli.local_runtime.endpoint._state_endpoint",
- lambda: {"base_url": "http://127.0.0.1:18434/v1", "pid": 4242})
- monkeypatch.setattr(boot, "_stop_state_server",
- lambda state: stopped.setdefault("pid", state["pid"]))
+ lambda: {"base_url": "http://127.0.0.1:18434/v1", "api_key": "k"})
+ monkeypatch.setattr(boot, "_stop_state_server", lambda: stopped.setdefault("stopped", True))
booted = {}
monkeypatch.setattr(boot, "ensure_local_runtime",
lambda cfg, force=False: booted.setdefault("force", force) or object())
assert boot.refresh_local_runtime() is True
- assert stopped.get("pid") == 4242, "adopted server was not stopped"
+ assert stopped.get("stopped"), "adopted server was not stopped"
assert booted.get("force") is True, "fresh boot did not follow the stop"
diff --git a/tests/hermes_cli/test_local_runtime_recovery.py b/tests/hermes_cli/test_local_runtime_recovery.py
index 0d3accad57c..0c10309764d 100644
--- a/tests/hermes_cli/test_local_runtime_recovery.py
+++ b/tests/hermes_cli/test_local_runtime_recovery.py
@@ -417,6 +417,63 @@ def test_clock_step_keeps_the_recorded_router(tmp_path, monkeypatch):
proc.wait(timeout=5)
[email protected]("owner", ["exited", "alive"])
+def test_replacement_stops_only_an_orphaned_router(tmp_path, monkeypatch, owner):
+ """Stale-preset replacement and the rescan bounce stop the recorded router only when its owner
+ is gone: a live owner's watchdog would respawn its router next to the replacement. (POSIX: a
+ Windows router dies with its owner's job object, so no orphan exists to stop.)"""
+ from gateway.status import get_process_start_time
+ from hermes_cli.local_runtime import bootstrap, endpoint, supervisor
+
+ monkeypatch.setattr(supervisor, "runtimes_root", lambda: tmp_path)
+ holder = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
+ router = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
+ try:
+ holder_proc, router_proc = psutil.Process(holder.pid), psutil.Process(router.pid)
+ supervisor.state_path().write_text(json.dumps({
+ "base_url": "http://127.0.0.1:59997/v1", "api_key": "test-only",
+ "pid": router.pid, "create_time": router_proc.create_time(),
+ "start_time": get_process_start_time(router.pid), "executable": router_proc.exe(),
+ "owner_pid": holder.pid, "owner_create_time": holder_proc.create_time(),
+ "owner_start_time": get_process_start_time(holder.pid)}))
+ if owner == "exited":
+ holder.kill()
+ holder.wait(timeout=5)
+
+ stopped = bootstrap._stop_state_server()
+
+ assert stopped == (owner == "exited")
+ if stopped:
+ router.wait(timeout=10)
+ assert endpoint._state_endpoint() is None
+ else:
+ assert router.poll() is None
+ finally:
+ for proc in (holder, router):
+ if proc.poll() is None:
+ proc.kill()
+ proc.wait(timeout=5)
+
+
+def test_the_process_that_boots_the_server_stops_it_on_a_clean_exit(tmp_path):
+ """Every surface that boots the managed server (CLI, gateway, desktop backend) frees it when it
+ exits; before, only the desktop backend's shutdown handler did and every other owner orphaned
+ the router and its VRAM."""
+ marker = tmp_path / "stopped"
+ code = (
+ "import sys\n"
+ "from hermes_cli.local_runtime import bootstrap\n"
+ "class Sup:\n"
+ f" def stop(self): open({str(marker)!r}, 'w').close()\n"
+ "bootstrap._SUPERVISOR = Sup()\n"
+ "bootstrap._stop_at_exit()\n"
+ "sys.exit(0)\n"
+ )
+ subprocess.run([sys.executable, "-c", code], cwd=Path(__file__).resolve().parents[2], check=True, timeout=60)
+ assert marker.exists()
+
+
@pytest.mark.platforms("windows")
@pytest.mark.parametrize("damage", ["valid", "birth", "exe", "bool-pid", "bool-birth", "nan", "inf", "owner-bool", "owner-nan", "parent", "partial", "list", "invalid", "unreadable"])
def test_retained_endpoint_validates_identity(tmp_path, monkeypatch, damage):