Skip to content

The agent that grows with you

fix(local-runtime): serialize managed runtime boot across processes

chelsealong4352a7d05346
diff --git a/hermes_cli/local_runtime/bootstrap.py b/hermes_cli/local_runtime/bootstrap.py
index 4d9ef0841dd..a67b062ed96 100644
--- a/hermes_cli/local_runtime/bootstrap.py
+++ b/hermes_cli/local_runtime/bootstrap.py
@@ -7,7 +7,7 @@ import-light: callers gate on config before importing so disabled sessions never
from __future__ import annotations
-from contextlib import suppress
+from contextlib import contextmanager, suppress
import logging
import os
import signal
@@ -173,6 +173,68 @@ def _generate_presets(mdir: Path, preset_path: Path) -> Path | None:
return None
+def _try_lock_boot_fd(fd: int) -> bool:
+ """Non-blocking exclusive attempt; portable across fcntl/msvcrt."""
+ if os.name == "nt":
+ import msvcrt
+
+ if os.fstat(fd).st_size == 0:
+ os.write(fd, b"\0")
+ os.lseek(fd, 0, os.SEEK_SET)
+ try:
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
+ return True
+ except OSError:
+ return False
+ else:
+ import fcntl
+
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ return True
+ except OSError:
+ return False
+
+
+def _unlock_boot_fd(fd: int) -> None:
+ if os.name == "nt":
+ import msvcrt
+
+ os.lseek(fd, 0, os.SEEK_SET)
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
+ else:
+ import fcntl
+
+ fcntl.flock(fd, fcntl.LOCK_UN)
+
+
+@contextmanager
+def _cross_process_boot_lock(timeout_s: float = 130.0):
+ """Serialize the state-check-then-spawn sequence across every Hermes process on this
+ machine — the ``_SUPERVISOR`` singleton above only rules out a race within ONE process.
+ Two profiles booting in the same second each see no ``server.json`` yet and each spawn a
+ router on the stable port (#116682); an OS-held lock makes the second caller wait for the
+ first to publish its state file, so it re-checks and adopts instead of spawning a duplicate.
+ Bounded, not indefinite: never hang session start dead if the lock is somehow stuck."""
+ path = runtimes_root() / "boot.lock"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd = os.open(path, os.O_CREAT | os.O_RDWR, 0o600)
+ try:
+ deadline = time.monotonic() + timeout_s
+ while not _try_lock_boot_fd(fd):
+ if time.monotonic() >= deadline:
+ logger.warning("boot lock contended past %.0fs; proceeding without it", timeout_s)
+ break
+ time.sleep(0.2)
+ try:
+ yield
+ finally:
+ with suppress(OSError):
+ _unlock_boot_fd(fd)
+ finally:
+ os.close(fd)
+
+
def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":
"""Idempotent boot of the managed runtime. Returns the supervisor (or None when
disabled/unavailable). Never raises into a session start — failures log and return None; chat
@@ -195,64 +257,69 @@ def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":
# download serves the new model with no policy at all (--models-autoload + stock fit). A stale
# incumbent gets stopped and replaced by a fresh boot with regenerated presets; sessions ride
# through like any other supervised restart (stable port + persisted key).
+ #
+ # The state check and the spawn below run under a cross-process lock: two backends racing
+ # to boot (#116682) must not both find no state file and both spawn a router on the stable
+ # port — the loser waits here, then re-checks state and adopts the winner's server instead.
from hermes_cli.local_runtime.endpoint import _state_endpoint
- 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 (
- default_tag, ensure_runtime_installed, installed_tags, select_backend)
- from hermes_cli.local_runtime.supervisor import LlamaServerSupervisor
-
- backend = section.get("backend", "auto")
- if backend == "auto":
- backend = select_backend(_detect_gpu_vendor())
- # Boot ladder: serve what is INSTALLED, never download here. The configured tag is
- # preferred; when it isn't installed yet, the newest installed tag serves and the status
- # endpoint reports the pending update — the download is a deliberate click in the pane,
- # not a boot-path surprise (a multi-minute inline download here is exactly how the
- # onboarding bounce returns).
- tag = section.get("tag") or default_tag()
- have = installed_tags()
- if tag not in have:
- if not have:
- logger.info("local runtime enabled but no build installed; "
- "install happens in the Local Models pane")
+ with _cross_process_boot_lock():
+ 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("configured tag %s not installed; serving %s "
- "(update is a click in Local Models)", tag, have[0])
- tag = have[0]
- install_dir = ensure_runtime_installed(tag, backend)
-
- mdir = models_dir()
- mdir.mkdir(parents=True, exist_ok=True)
- preset_path = _generate_presets(mdir, runtimes_root() / "presets.ini")
-
- sup = LlamaServerSupervisor(install_dir, mdir, preset_path=preset_path,
- models_max=int(section.get("models_max", 4)),
- port=int(section.get("port", 0)) or 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:
- sup.start()
- except Exception:
- # start() can fail after the router process exists (health timeout): leaving it
- # running unsupervised strands its VRAM behind a port nothing will clean up.
- with suppress(Exception):
- sup.stop()
- raise
- _SUPERVISOR = sup
- logger.info("managed llama-server up at %s (backend=%s tag=%s)", sup.base_url, backend, tag)
- _start_idle_sweeper(sup)
- return sup
- except Exception as exc: # noqa: BLE001 — never break session start
- logger.warning("managed local runtime unavailable: %s", exc)
- return None
+ from hermes_cli.local_runtime.binaries import (
+ default_tag, ensure_runtime_installed, installed_tags, select_backend)
+ from hermes_cli.local_runtime.supervisor import LlamaServerSupervisor
+
+ backend = section.get("backend", "auto")
+ if backend == "auto":
+ backend = select_backend(_detect_gpu_vendor())
+ # Boot ladder: serve what is INSTALLED, never download here. The configured tag is
+ # preferred; when it isn't installed yet, the newest installed tag serves and the
+ # status endpoint reports the pending update — the download is a deliberate click in
+ # the pane, not a boot-path surprise (a multi-minute inline download here is exactly
+ # how the onboarding bounce returns).
+ tag = section.get("tag") or default_tag()
+ have = installed_tags()
+ if tag not in have:
+ if not have:
+ logger.info("local runtime enabled but no build installed; "
+ "install happens in the Local Models pane")
+ return None
+ logger.info("configured tag %s not installed; serving %s "
+ "(update is a click in Local Models)", tag, have[0])
+ tag = have[0]
+ install_dir = ensure_runtime_installed(tag, backend)
+
+ mdir = models_dir()
+ mdir.mkdir(parents=True, exist_ok=True)
+ preset_path = _generate_presets(mdir, runtimes_root() / "presets.ini")
+
+ sup = LlamaServerSupervisor(install_dir, mdir, preset_path=preset_path,
+ models_max=int(section.get("models_max", 4)),
+ port=int(section.get("port", 0)) or None)
+ try:
+ sup.start()
+ except Exception:
+ # start() can fail after the router process exists (health timeout): leaving it
+ # running unsupervised strands its VRAM behind a port nothing will clean up.
+ with suppress(Exception):
+ sup.stop()
+ raise
+ _SUPERVISOR = sup
+ logger.info("managed llama-server up at %s (backend=%s tag=%s)", sup.base_url, backend, tag)
+ _start_idle_sweeper(sup)
+ return sup
+ except Exception as exc: # noqa: BLE001 — never break session start
+ logger.warning("managed local runtime unavailable: %s", exc)
+ return None
def shutdown_local_runtime() -> None:
diff --git a/tests/hermes_cli/test_local_runtime.py b/tests/hermes_cli/test_local_runtime.py
index 9448ea5da30..46f06b488ff 100644
--- a/tests/hermes_cli/test_local_runtime.py
+++ b/tests/hermes_cli/test_local_runtime.py
@@ -959,6 +959,71 @@ def test_bootstrap_failure_never_raises(tmp_path, monkeypatch):
assert result is None # no exception escaped
+def test_ensure_local_runtime_serializes_racing_callers(tmp_path, monkeypatch):
+ """Cross-process boot race (#116682): two backends starting in the same second must not
+ both spawn a router on the stable port. Neither caller here ever sees the other's
+ in-process ``_SUPERVISOR`` (each opens its own fd for the boot lock, exactly like two
+ separate OS processes would) — only the cross-process file lock can serialize them."""
+ import time as _time
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ from hermes_cli.local_runtime import bootstrap
+ from hermes_cli.local_runtime import supervisor as sup_mod
+
+ monkeypatch.setattr(bootstrap, "_SUPERVISOR", None)
+ mdir = bootstrap.models_dir()
+ mdir.mkdir(parents=True, exist_ok=True)
+ (mdir / "stub-Q4_K_M.gguf").touch()
+
+ monkeypatch.setattr(bootstrap, "_generate_presets", lambda *a, **k: None)
+ monkeypatch.setattr(bootstrap, "_presets_stale", lambda: False)
+ monkeypatch.setattr(bootstrap, "_detect_gpu_vendor", lambda: None)
+ monkeypatch.setattr("hermes_cli.local_runtime.binaries.installed_tags", lambda: ["b1"])
+ monkeypatch.setattr("hermes_cli.local_runtime.binaries.default_tag", lambda: "b1")
+ monkeypatch.setattr("hermes_cli.local_runtime.binaries.ensure_runtime_installed",
+ lambda tag, backend: tmp_path / "install")
+
+ spawns = []
+
+ class _FakeSupervisor:
+ def __init__(self, *a, **k):
+ self.port = 18434
+ self.api_key = "k"
+ self.proc = None
+
+ @property
+ def base_url(self):
+ return f"http://127.0.0.1:{self.port}/v1"
+
+ def start(self, timeout_s=120):
+ spawns.append(1)
+ _time.sleep(0.3) # widen the window the other caller races into
+ path = sup_mod.state_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps({
+ "base_url": self.base_url, "api_key": self.api_key, "pid": os.getpid(),
+ }), encoding="utf-8")
+
+ monkeypatch.setattr(sup_mod, "LlamaServerSupervisor", _FakeSupervisor)
+
+ barrier = threading.Barrier(2)
+ results = []
+
+ def _boot():
+ barrier.wait()
+ results.append(bootstrap.ensure_local_runtime({"local_runtime": {"enabled": True}}))
+
+ threads = [threading.Thread(target=_boot) for _ in range(2)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout=10)
+
+ assert len(spawns) == 1, (
+ "both racing callers spawned a router instead of the second adopting the "
+ "first's published state (#116682)")
+
+
def test_manifest_verified_tolerates_non_dict_manifest(tmp_path):
"""A parseable-but-non-object manifest used to raise AttributeError out of
manifest_verified (the .get ran inside a try that only caught decode/OSError),