Skip to content

The agent that grows with you

fix(local-runtime): never adopt a running server whose presets predate the staged models

emozilla55e69e2b05b5
diff --git a/hermes_cli/local_runtime/bootstrap.py b/hermes_cli/local_runtime/bootstrap.py
index 802621f7805..bd0a0f5e36b 100644
--- a/hermes_cli/local_runtime/bootstrap.py
+++ b/hermes_cli/local_runtime/bootstrap.py
@@ -13,6 +13,7 @@ sessions with local_runtime disabled never pay the import.
from __future__ import annotations
import logging
+import os
import subprocess
import time
from pathlib import Path
@@ -70,6 +71,40 @@ def staged_model_ids() -> "list[str]":
return [re.sub(r"-\d{5}-of-\d{5}$", "", p.stem) for p in staged_models()]
+def _presets_stale() -> bool:
+ """True when a staged model has no section in the preset INI — it
+ would autoload with stock fit instead of a policy decision."""
+ try:
+ from hermes_cli.local_runtime.presets import read_preset_decisions
+
+ known = set(read_preset_decisions())
+ return any(mid not in known for mid in staged_model_ids())
+ except Exception: # noqa: BLE001
+ 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."""
+ pid = state.get("pid")
+ if not pid:
+ return
+ try:
+ import signal
+
+ os.kill(int(pid), signal.SIGTERM)
+ except (OSError, ValueError):
+ return
+ # Give it a moment to release the port and the GPU.
+ for _ in range(50):
+ try:
+ os.kill(int(pid), 0)
+ except OSError:
+ return
+ time.sleep(0.1)
+
+
def refresh_local_runtime() -> bool:
"""Restart the managed server so it rescans the models directory.
@@ -114,12 +149,24 @@ def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":
logger.info("local runtime enabled but no models staged; not booting")
return None
- # Another Hermes process may already be supervising — reuse via state.
+ # Another Hermes process may already be supervising — reuse via state,
+ # but ONLY while its launch policy still covers every staged model. A
+ # server whose preset file predates a download serves the new model
+ # with no policy at all (--models-autoload + stock fit: f16 KV at max
+ # context, no placement — the silent-demotion busy-wait on WDDM). A
+ # stale incumbent gets stopped and replaced by a fresh boot with
+ # regenerated presets; sessions ride through exactly like any other
+ # supervised restart (stable port + persisted key).
from hermes_cli.local_runtime.endpoint import _state_endpoint
- if _state_endpoint() is not None:
- logger.info("managed llama-server already running (another process)")
- return None
+ state = _state_endpoint()
+ if state is not None:
+ if not _presets_stale():
+ logger.info("managed llama-server already running (another process)")
+ 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)
try:
from hermes_cli.local_runtime.binaries import (
diff --git a/tests/hermes_cli/test_boot_preset_staleness.py b/tests/hermes_cli/test_boot_preset_staleness.py
new file mode 100644
index 00000000000..1ed7ee27756
--- /dev/null
+++ b/tests/hermes_cli/test_boot_preset_staleness.py
@@ -0,0 +1,92 @@
+"""Every staged model must launch with a policy decision, never stock fit.
+
+The managed server autoloads any GGUF in its models dir; a model missing
+from the preset INI loads with llama-server defaults (f16 KV at max
+context, no placement) — on Windows/WDDM that silently demotes VRAM and
+decodes at a crawl. Boot must therefore refuse to adopt a running server
+whose presets predate the staged set."""
+
+from __future__ import annotations
+
+import pytest
+
+
+def hermes_home(tmp_path, monkeypatch):
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ return home
+
+
+def _stage(home, name):
+ mdir = home / "models"
+ mdir.mkdir(parents=True, exist_ok=True)
+ (mdir / f"{name}.gguf").write_bytes(b"GGUF" + b"\x00" * 32)
+
+
+def _write_presets(home, *model_ids):
+ pdir = home / "runtimes" / "llamacpp"
+ pdir.mkdir(parents=True, exist_ok=True)
+ body = "\n".join(f"[{m}]\nctx-size = 65536\n" for m in model_ids)
+ (pdir / "presets.ini").write_text(body, encoding="utf-8")
+
+
+def test_presets_stale_when_a_staged_model_has_no_section(hermes_home):
+ from hermes_cli.local_runtime.bootstrap import _presets_stale
+
+ _stage(hermes_home, "model-a")
+ _stage(hermes_home, "model-b")
+ _write_presets(hermes_home, "model-a")
+ assert _presets_stale() is True
+
+
+def test_presets_current_when_every_staged_model_is_covered(hermes_home):
+ from hermes_cli.local_runtime.bootstrap import _presets_stale
+
+ _stage(hermes_home, "model-a")
+ _write_presets(hermes_home, "model-a")
+ assert _presets_stale() is False
+
+
+def test_no_models_is_never_stale(hermes_home):
+ from hermes_cli.local_runtime.bootstrap import _presets_stale
+
+ _write_presets(hermes_home, "model-a")
+ assert _presets_stale() is False
+
+
+def test_boot_replaces_incumbent_with_stale_presets(hermes_home, monkeypatch):
+ """ensure_local_runtime must not adopt a running server whose presets
+ miss a staged model — it stops it and boots fresh (boot itself is
+ stubbed; the contract under test is the adopt/replace decision)."""
+ import hermes_cli.local_runtime.bootstrap as boot
+
+ _stage(hermes_home, "model-a")
+ _stage(hermes_home, "model-b")
+ _write_presets(hermes_home, "model-a")
+
+ 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"]))
+
+ sentinel = object()
+
+ def fake_boot(*a, **k):
+ raise _BootReached()
+
+ class _BootReached(Exception):
+ pass
+
+ # Fail fast once boot proper begins — reaching it IS the assertion.
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.binaries.ensure_runtime_installed", fake_boot)
+
+ result = boot.ensure_local_runtime({"local_runtime": {"enabled": True}})
+ assert stopped.get("pid") == 12345, "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