The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(local-runtime): size launch windows beside other programs' GPU memory
emozilla20700f298ac6
diff --git a/hermes_cli/local_runtime/bootstrap.py b/hermes_cli/local_runtime/bootstrap.pyindex 9b78b7a073a..d4894239c36 100644--- a/hermes_cli/local_runtime/bootstrap.py+++ b/hermes_cli/local_runtime/bootstrap.py@@ -215,6 +215,9 @@ def _generate_presets(mdir: Path, preset_path: Path) -> Path | None:still hold the card (restart, refresh after a download), and its memory is freed before the newinstance loads anything. Pricing against live-free once pinned a fitting model's weights to CPU.+ The window is then narrowed to what fits beside other programs' GPU memory+ (``hardware.launch_budget``), which never moves weights to the CPU.+Degradation ladder on failure: a STALE policy still beats no policy — stock fit (f16 KV at maxcontext, no placement) is the silent-busy-wait failure on Windows. Keep serving with theprevious INI when one exists; only a first boot with no INI at all falls to stock fit.@@ -223,7 +226,8 @@ def _generate_presets(mdir: Path, preset_path: Path) -> Path | None:from hermes_cli.local_runtime.presets import generate_presetstry:- for entry in generate_presets(mdir, probe_budget(planning=True), preset_path):+ capacity = probe_budget(planning=True)+ for entry in generate_presets(mdir, capacity, preset_path, live=_launch_budget(capacity)):if entry.refusal:logger.warning("model refused by physics check: %s", entry.refusal)return preset_path@@ -239,6 +243,71 @@ def _generate_presets(mdir: Path, preset_path: Path) -> Path | None:return None+def _launch_budget(capacity, own_bytes: int = 0):+ """``hardware.launch_budget``, or None when the probe fails: a boot never waits on it."""+ from hermes_cli.local_runtime.hardware import launch_budget++ try:+ return launch_budget(capacity, own_bytes=own_bytes)+ except Exception as exc: # noqa: BLE001+ logger.warning("free GPU memory probe failed (%s); launch windows use capacity", exc)+ return None+++# Router statuses that hold GPU memory. The preset file changes only while every model is out of+# them: the router unloads a loaded model whose launch flags change on reload.+_HOLDS_MEMORY = frozenset({"loaded", "loading", "sleeping", "ready"})+++def refit_idle_presets(sup) -> bool:+ """Re-plan launch windows against free GPU memory while no model is loaded.++ Boot plans every window once, but models load later (on demand, after an idle unload), and by+ then other programs may hold more or less of the card. Returns True when the router was given+ new presets. A request that starts a load between the last status check and the reload is+ unloaded by the router and fails once; that gap is a few milliseconds, and only when a window+ changes.+ """+ from hermes_cli.local_runtime.hardware import probe_budget+ from hermes_cli.local_runtime.presets import plan_presets, render_presets++ path = sup.preset_path+ if path is None or not path.exists() or _any_holds_memory(sup):+ return False+ capacity = probe_budget(planning=True)+ live = _launch_budget(capacity)+ if live is None:+ return False+ last = sup._refit_usable+ if last is not None and abs(live.usable_vram_bytes - last) < _REFIT_STEP_BYTES:+ return False+ text = render_presets(plan_presets(models_dir(), capacity, live=live))+ # Held across the write and the reload so a restart can't spawn between them; everything+ # slow ran above.+ with sup._lifecycle_lock:+ if sup.proc is None or sup.proc.poll() is not None or _any_holds_memory(sup):+ return False+ sup._refit_usable = live.usable_vram_bytes+ if text == path.read_text(encoding="utf-8-sig"):+ return False+ from utils import atomic_write_text++ atomic_write_text(path, text, tmp_prefix=f".{path.name}_", mode=0o600)+ sup.reload_presets()+ logger.info("launch windows re-planned for %.1f GiB of free GPU memory",+ live.usable_vram_bytes / (1 << 30))+ return True+++# Smaller changes in free memory don't move a window by a ladder rung; skipping them keeps the+# idle loop from re-reading every model header each pass.+_REFIT_STEP_BYTES = 256 << 20+++def _any_holds_memory(sup) -> bool:+ return any(status in _HOLDS_MEMORY for status in sup.models(timeout_s=5).values())++def _try_lock_boot_fd(fd: int) -> bool:"""Non-blocking exclusive attempt; portable across fcntl/msvcrt."""if os.name == "nt":@@ -397,18 +466,30 @@ def get_supervisor():return _SUPERVISOR+_SWEEP_EVERY_S = 120+_REFIT_EVERY_S = 30++def _start_idle_sweeper(sup) -> None:"""Idle-residency loop: every couple of minutes, unload models idle past the supervisor's- threshold. Daemon thread tied to the supervisor's lifetime — exits when the server stops."""+ threshold; every 30 s with nothing loaded, re-plan launch windows against free GPU memory.+ Daemon thread tied to the supervisor's lifetime — exits when the server stops."""import threadingdef _loop():+ last_sweep = time.monotonic()while sup.proc is not None and sup.proc.poll() is None:- time.sleep(120)+ time.sleep(_REFIT_EVERY_S)+ if time.monotonic() - last_sweep >= _SWEEP_EVERY_S:+ last_sweep = time.monotonic()+ try:+ sup.sweep_idle()+ except Exception as exc: # noqa: BLE001+ logger.debug("idle sweep skipped: %s", exc)try:- sup.sweep_idle()+ refit_idle_presets(sup)except Exception as exc: # noqa: BLE001- logger.debug("idle sweep skipped: %s", exc)+ logger.debug("launch window re-plan skipped: %s", exc)threading.Thread(target=_loop, daemon=True, name="local-runtime-idle-sweep").start()diff --git a/hermes_cli/local_runtime/context_policy.py b/hermes_cli/local_runtime/context_policy.pyindex 11356fdc19e..778723724cb 100644--- a/hermes_cli/local_runtime/context_policy.py+++ b/hermes_cli/local_runtime/context_policy.py@@ -166,6 +166,34 @@ def plan_launch(profile: ModelProfile, budget: HardwareBudget, *, mtp_capable: breturn lean+def fit_to_free_memory(plan: LaunchPlan, profile: ModelProfile, live: HardwareBudget, *,+ mtp_capable: bool = False,+ fixed_overhead: int = RUNTIME_OVERHEAD_BYTES) -> LaunchPlan:+ """Narrow a resident capacity plan to the window the card's free memory holds now.++ Only the window moves, and only down to the floor. A plan that already spills keeps its+ placement, and so does a card too busy to hold even the floor: moving weights to the CPU on a+ live reading is how a launch once pinned a fitting model to the CPU, because the reading still+ counted memory the outgoing server was about to free.+ """+ decision = plan.decision+ if not isinstance(decision, WindowDecision) or decision.spilled:+ return plan+ now = plan_launch(profile, live, mtp_capable=mtp_capable, fixed_overhead=fixed_overhead)+ if isinstance(now.decision, WindowDecision) and not now.decision.spilled:+ if now.decision.window >= decision.window:+ return plan+ return LaunchPlan(replace(now.decision, reasons=[+ f"{now.decision.window // 1024}K fits beside other programs' GPU memory "+ f"({decision.window // 1024}K would not)"]), now.mtp_prefill, now.overhead_bytes)+ floor = min(FLOOR, profile.n_ctx_train or FLOOR)+ if decision.window <= floor:+ return plan+ return LaunchPlan(WindowDecision(window=floor, spill_bytes=0, kv_on_gpu=True, reasons=[+ f"floor held at {floor // 1024}K; other programs hold most of the GPU memory"]),+ plan.mtp_prefill, plan.overhead_bytes)++@dataclassclass GrowthDecision:action: str # "grow" | "hold" | "compress-default"diff --git a/hermes_cli/local_runtime/growth.py b/hermes_cli/local_runtime/growth.pyindex 631f05fcda6..572e57738d2 100644--- a/hermes_cli/local_runtime/growth.py+++ b/hermes_cli/local_runtime/growth.py@@ -71,12 +71,13 @@ def maybe_grow_window(model_id: str, *, base_url: str, session_tokens: int,window — nothing rewinds."""from hermes_cli.local_runtime.bootstrap import (- get_supervisor, refresh_local_runtime, staged_models)+ _launch_budget, get_supervisor, refresh_local_runtime, staged_models)from hermes_cli.local_runtime.context_policy import growth_decisionfrom hermes_cli.local_runtime.estimator import profile_from_gguffrom hermes_cli.local_runtime.gguf import model_id_from_stem, read_gguf_headerfrom hermes_cli.local_runtime.hardware import probe_budget- from hermes_cli.local_runtime.presets import preset_for_model, read_preset_decisions+ from hermes_cli.local_runtime.presets import (+ preset_for_model, read_preset_decisions, resident_footprint)sup = get_supervisor()if sup is None or not is_managed_endpoint(base_url):@@ -116,9 +117,13 @@ def maybe_grow_window(model_id: str, *, base_url: str, session_tokens: int,logger.debug("growth %s: %s (%s)", model_id, decision.action, decision.reason)return None- plan = preset_for_model(gguf, budget, set(), requested_window=decision.next_window)+ # The grown instance loads after this one exits, so the model's own memory counts as free.+ # Other loaded models still count as held, which errs toward a smaller window.+ live = _launch_budget(budget, own_bytes=resident_footprint(gguf, budget, current_window) or 0)+ plan = preset_for_model(gguf, budget, set(), requested_window=decision.next_window, live=live)if plan is None or plan.refusal or plan.window < decision.next_window:- logger.debug("growth %s: complete launch footprint does not admit the next rung", model_id)+ logger.debug("growth %s: the next rung does not fit beside other programs' GPU memory",+ model_id)return Nonelogger.info("context growth %s: %s", model_id, decision.reason)diff --git a/hermes_cli/local_runtime/hardware.py b/hermes_cli/local_runtime/hardware.pyindex 29072a60c2a..a3b09e5bc0f 100644--- a/hermes_cli/local_runtime/hardware.py+++ b/hermes_cli/local_runtime/hardware.py@@ -17,6 +17,7 @@ import shutilimport subprocessimport sysimport time+from dataclasses import replacefrom pathlib import Pathfrom hermes_cli.local_runtime.estimator import HardwareBudget@@ -31,6 +32,9 @@ _GIB = 1 << 30# reality). Small cards give up window to this; spill mode is their path to big models._MARGIN_FLOOR = 2 << 30_MARGIN_FRACTION = 0.09+# Room left on top of what other programs hold when a model launches: a browser tab or a chat app+# can take another GiB between launch and the next request.+_LAUNCH_HEADROOM = 1 << 30# UMA headroom: on unified-memory machines the model shares physical memory with the OS and every# app, so budget from RAM minus this fraction._UMA_HEADROOM_FRACTION = 0.20@@ -351,3 +355,28 @@ def probe_budget(*, planning: bool = False) -> HardwareBudget:total_device_bytes=total,ram_available_bytes=ram_total if planning else ram_avail,uma=False, gpu_name=gpu_name, platform=sys.platform)+++def launch_budget(capacity: HardwareBudget, *, own_bytes: int = 0) -> HardwareBudget | None:+ """Capacity less what other programs hold on the card right now, or None when that can't apply.++ Capacity assumes other programs hold no more than the fixed margin. Beside a heavier desktop the+ capacity-sized window doesn't fit, and Windows pages part of the model to host memory without+ an error: a 32 GiB card with 4.5-6.3 GiB held by other apps decoded at ~24 tok/s at the+ capacity window, and at ~90 tok/s at a window sized from free memory.++ ``own_bytes`` is what the managed server holds now and frees before the new instance loads.+ A stopped server's memory reads as free by the time its process has exited (measured on+ Windows: free memory was fully back at the first reading after exit). None for unified memory+ (its live budget is already free memory) and when the device query fails, so callers keep the+ capacity plan.+ """+ if capacity.uma:+ return None+ vram = _nvidia_vram()+ if vram is None:+ return None+ total, free, _name = vram+ others = max(0, total - free - max(0, own_bytes))+ usable = min(capacity.usable_vram_bytes, max(0, total - others - _LAUNCH_HEADROOM))+ return replace(capacity, usable_vram_bytes=usable)diff --git a/hermes_cli/local_runtime/presets.py b/hermes_cli/local_runtime/presets.pyindex 66e02a9de1b..445531fb014 100644--- a/hermes_cli/local_runtime/presets.py+++ b/hermes_cli/local_runtime/presets.py@@ -6,11 +6,11 @@ from __future__ import annotationsimport jsonimport logging-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom pathlib import Pathfrom hermes_cli.local_runtime.context_policy import (- RUNTIME_OVERHEAD_BYTES, launch_args, plan_launch, ub_logits_bytes)+ RUNTIME_OVERHEAD_BYTES, fit_to_free_memory, launch_args, plan_launch, ub_logits_bytes)from hermes_cli.local_runtime.estimator import (HardwareBudget, PhysicsRefusal, ctx_bytes, footprint_bytes, profile_from_gguf)from hermes_cli.local_runtime.gguf import model_id_from_stem, read_gguf_header@@ -77,8 +77,13 @@ def _draft_fits(path: Path, profile, budget: HardwareBudget, window: int, overhedef preset_for_model(gguf: Path, budget: HardwareBudget,- mtp_capable: set[str], *, requested_window: int | None = None) -> PresetEntry | None:- """The launch decision for one staged model, or None when its header is unreadable."""+ mtp_capable: set[str], *, requested_window: int | None = None,+ live: HardwareBudget | None = None) -> PresetEntry | None:+ """The launch decision for one staged model, or None when its header is unreadable.++ ``budget`` is the card's capacity; ``live`` (from ``hardware.launch_budget``) narrows the+ window to what fits beside other programs now.+ """from hermes_cli.local_runtime.catalog import entry_for_modelfrom hermes_cli.local_runtime.growth import load_window_overrides@@ -98,6 +103,9 @@ def preset_for_model(gguf: Path, budget: HardwareBudget,plan = plan_launch(profile, budget, mtp_capable=is_mtp, fixed_overhead=fixed_overhead,requested_window=(load_window_overrides().get(model_id)if requested_window is None else requested_window))+ if live is not None:+ plan = fit_to_free_memory(plan, profile, live, mtp_capable=is_mtp,+ fixed_overhead=fixed_overhead)decision = plan.decisionif isinstance(decision, PhysicsRefusal):return PresetEntry(model_id=model_id, window=0, spilled=False, refusal=decision.message)@@ -134,6 +142,26 @@ def preset_for_model(gguf: Path, budget: HardwareBudget,spilled=decision.spilled, keys=keys)+def resident_footprint(gguf: Path, budget: HardwareBudget, window: int) -> int | None:+ """Estimated bytes one staged model holds while loaded at ``window``, or None when unreadable."""+ from hermes_cli.local_runtime.catalog import entry_for_model++ model_id = model_id_from_stem(gguf.stem)+ try:+ profile = profile_from_gguf(read_gguf_header(gguf))+ except (ValueError, OSError) as exc:+ logger.debug("footprint skip %s: %s", gguf.name, exc)+ return None+ entry = entry_for_model(model_id)+ is_mtp = entry.mtp if entry is not None else False+ mmproj = entry.mmproj.size_bytes if entry is not None and _asset_path(entry.mmproj) else 0+ plan = plan_launch(profile, budget, mtp_capable=is_mtp,+ fixed_overhead=RUNTIME_OVERHEAD_BYTES + mmproj, requested_window=window)+ if is_mtp and profile.kv_scale == 1.0:+ profile = replace(profile, kv_scale=1.2)+ return footprint_bytes(profile, window, overhead_bytes=plan.overhead_bytes)++def _launch_footprint(gguf: Path, budget: HardwareBudget) -> int | None:"""Estimated resident bytes for one staged model at the window this policy grants it, or Nonewhen it cannot be priced: an unreadable header, or a model the physics check refuses outright@@ -189,19 +217,36 @@ def admitted_residency_count(models_dir: Path, budget: HardwareBudget, configurereturn max(1, min(configured, budget.usable_vram_bytes // largest))-def generate_presets(models_dir: Path, budget: HardwareBudget, preset_path: Path,- mtp_capable: set[str] | None = None) -> list[PresetEntry]:- """Walk the staged models, run the launch decision per model, and write one INI. Refused- models get no section (the picker surfaces the refusal from the returned entries)."""+def plan_presets(models_dir: Path, budget: HardwareBudget, mtp_capable: set[str] | None = None,+ *, live: HardwareBudget | None = None) -> list[PresetEntry]:+ """The launch decision for every staged model; unreadable headers are skipped."""from hermes_cli.local_runtime.bootstrap import staged_in- entries: list[PresetEntry] = []+ entries = (preset_for_model(gguf, budget, mtp_capable or set(), live=live)+ for gguf in staged_in(models_dir))+ return [entry for entry in entries if entry is not None]+++def generate_presets(models_dir: Path, budget: HardwareBudget, preset_path: Path,+ mtp_capable: set[str] | None = None, *,+ live: HardwareBudget | None = None) -> list[PresetEntry]:+ """Plan every staged model and write one INI. Refused models get no section (the picker+ surfaces the refusal from the returned entries)."""+ entries = plan_presets(models_dir, budget, mtp_capable, live=live)+ write_presets(entries, preset_path)+ return entries+++def write_presets(entries: list[PresetEntry], preset_path: Path) -> None:+ from utils import atomic_write_text++ atomic_write_text(preset_path, render_presets(entries), tmp_prefix=f".{preset_path.name}_", mode=0o600)+ logger.info("wrote %d preset sections to %s", sum(e.keys is not None for e in entries), preset_path)+++def render_presets(entries: list[PresetEntry]) -> str:sections: list[str] = []- for gguf in staged_in(models_dir):- entry = preset_for_model(gguf, budget, mtp_capable or set())- if entry is None:- continue- entries.append(entry)+ for entry in entries:# INI comments preserve non-flag facts atomically with the launch policy.sections.append("# hermes-decision: " + json.dumps({"model_id": entry.model_id, "window": entry.window,@@ -209,11 +254,7 @@ def generate_presets(models_dir: Path, budget: HardwareBudget, preset_path: Pathif entry.keys is not None:body = "\n".join(f"{k} = {v}" for k, v in entry.keys.items())sections.append(f"[{entry.model_id}]\n{body}\n")-- from utils import atomic_write_text- atomic_write_text(preset_path, "\n".join(sections), tmp_prefix=f".{preset_path.name}_", mode=0o600)- logger.info("wrote %d preset sections to %s", sum(e.keys is not None for e in entries), preset_path)- return entries+ return "\n".join(sections)def read_preset_decisions(preset_path: Path | None = None) -> dict[str, PresetEntry]:diff --git a/hermes_cli/local_runtime/supervisor.py b/hermes_cli/local_runtime/supervisor.pyindex a95daeb5879..e95839ec552 100644--- a/hermes_cli/local_runtime/supervisor.py+++ b/hermes_cli/local_runtime/supervisor.py@@ -143,6 +143,8 @@ class LlamaServerSupervisor:self._watchdog: threading.Thread | None = Noneself._log_handle = Noneself._idle_since: dict[str, float] = {}+ # Launch budget the preset file was last planned against (bootstrap.refit_idle_presets).+ self._refit_usable: int | None = None# ── endpoints ────────────────────────────────────────────@@ -358,14 +360,20 @@ class LlamaServerSupervisor:# ── model management (router endpoints) ──────────────────- def models(self) -> dict:+ def models(self, timeout_s: int = 30) -> dict:"""{model_id: status_value} from GET /models."""return {m["id"]: m.get("status", {}).get("value", "unknown")- for m in self._request("/models").get("data", [])}+ for m in self._request("/models", timeout_s=timeout_s).get("data", [])}def load_model(self, model_id: str, timeout_s: int = 600) -> None:self._request("/models/load", {"model": model_id}, timeout_s=timeout_s)+ def reload_presets(self) -> None:+ """Have the router re-read the preset file (GET /models?reload=1). It applies new launch+ flags to models that aren't loaded and unloads any loaded model whose flags changed, so+ callers rewrite the file only while nothing is loaded."""+ self._request("/models?reload=1", timeout_s=10)+def unload_model(self, model_id: str) -> None:"""Free the child's VRAM now (POST /models/unload; bogus name -> 400). Momentary: nevertouches primary_model — the declaration is durable, an eject is not."""diff --git a/tests/hermes_cli/test_local_launch_budget.py b/tests/hermes_cli/test_local_launch_budget.pynew file mode 100644index 00000000000..30bb3a59e5e--- /dev/null+++ b/tests/hermes_cli/test_local_launch_budget.py@@ -0,0 +1,327 @@+"""Launch windows are sized beside what other programs hold on the card, not from capacity alone.++On a 32 GiB card, the capacity plan booted Qwen3.8 27B at 216K. That fit only while other+programs held about 3.4 GiB or less. With 4.5-6.3 GiB held, Windows paged part of the model to+host memory without an error, and decode fell from ~90 to ~24 tok/s. The window must shrink to+what fits now, and the weights must stay on the GPU.+"""+from __future__ import annotations++from dataclasses import replace+from types import SimpleNamespace++import pytest++from hermes_cli.local_runtime import hardware+from hermes_cli.local_runtime.estimator import HardwareBudget++GIB = 1 << 30+# The measured card: RTX 5090, 31.84 GiB total, capacity = total minus the 9% margin.+CARD_TOTAL = int(31.84 * GIB)+CARD_CAPACITY = HardwareBudget(+ usable_vram_bytes=CARD_TOTAL - max(hardware._MARGIN_FLOOR, int(CARD_TOTAL * hardware._MARGIN_FRACTION)),+ total_device_bytes=CARD_TOTAL, ram_available_bytes=256 * GIB, uma=False)+MODEL_ID = "Qwen3.8-27B-UD-Q4_K_M"+++def hermes_home(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ return tmp_path+++def _card(monkeypatch, others_gib: float, *, total: int = CARD_TOTAL):+ monkeypatch.setattr(hardware, "_nvidia_vram",+ lambda: (total, total - int(others_gib * GIB), "NVIDIA GeForce RTX 5090"))+++def capacity_probe(monkeypatch):+ """Launch decisions run through a server bounce, so they price the card's capacity+ (``planning=True``), never raw free memory, which still counts the outgoing server. Free+ memory enters only through ``launch_budget``. Every call is recorded, so a probe inside a+ path that swallows exceptions still fails the test."""+ calls = []++ def probe(**kwargs):+ calls.append(kwargs)+ return CARD_CAPACITY++ monkeypatch.setattr(hardware, "probe_budget", probe)+ yield calls+ assert all(call == {"planning": True} for call in calls), calls+++# ── launch_budget ────────────────────────────────────────────+++def test_launch_budget_subtracts_other_programs_plus_headroom(monkeypatch):+ _card(monkeypatch, 5.4)+ budget = hardware.launch_budget(CARD_CAPACITY)+ assert budget.usable_vram_bytes == CARD_TOTAL - int(5.4 * GIB) - hardware._LAUNCH_HEADROOM+ assert budget.total_device_bytes == CARD_TOTAL and budget.uma is False+++def test_launch_budget_never_exceeds_capacity(monkeypatch):+ _card(monkeypatch, 0.0)+ assert hardware.launch_budget(CARD_CAPACITY).usable_vram_bytes == CARD_CAPACITY.usable_vram_bytes+++def test_launch_budget_counts_own_server_as_free(monkeypatch):+ """The managed server exits before the next instance loads; counting it as another program+ once pinned a fitting model's weights to the CPU."""+ _card(monkeypatch, 5.0 + 24.6) # 5 GiB of other programs plus our own 24.6 GiB model+ budget = hardware.launch_budget(CARD_CAPACITY, own_bytes=int(24.6 * GIB))+ assert budget.usable_vram_bytes == pytest.approx(+ CARD_TOTAL - 5 * GIB - hardware._LAUNCH_HEADROOM, abs=1 << 20)+++def test_launch_budget_skips_unified_memory_and_failed_probes(monkeypatch):+ uma = replace(CARD_CAPACITY, uma=True)+ monkeypatch.setattr(hardware, "_nvidia_vram", lambda: pytest.fail("UMA must not probe"))+ assert hardware.launch_budget(uma) is None+ monkeypatch.setattr(hardware, "_nvidia_vram", lambda: None)+ assert hardware.launch_budget(CARD_CAPACITY) is None+++# ── launch windows for the real catalog 27B ─────────────────+++def _stage_27b(hermes_home, monkeypatch):+ """The real catalog entry (mmproj staged), priced from its catalog profile."""+ from hermes_cli.local_runtime import bootstrap, catalog, presets++ entry = catalog.catalog_by_id()["qwen3.8-27b"]+ variant = next(v for v in entry.variants if v.model_id == MODEL_ID)+ mdir = hermes_home / "models"+ mdir.mkdir(parents=True, exist_ok=True)+ # First: assets_dir() resolves under models_dir(), so the projector lands in this test's tree.+ monkeypatch.setattr(bootstrap, "models_dir", lambda: mdir)+ gguf = mdir / f"{MODEL_ID}.gguf"+ gguf.write_bytes(b"GGUF" + b"\x00" * 64)+ asset = bootstrap.assets_dir() / entry.mmproj.local_name+ asset.parent.mkdir(parents=True, exist_ok=True)+ asset.touch()+ profile = entry.profile(variant)+ monkeypatch.setattr(presets, "read_gguf_header", lambda p: SimpleNamespace(sampling_defaults={}))+ monkeypatch.setattr(presets, "profile_from_gguf", lambda h: profile)+ monkeypatch.setattr(bootstrap, "staged_models", lambda: [gguf])+ monkeypatch.setattr(bootstrap, "staged_in", lambda d: [gguf])+ return mdir, gguf++[email protected]("others_gib,window_k", [+ (0.0, 216), # quiet card: capacity plan unchanged+ (3.0, 216),+ (3.6, 144), # measured: 216K ran with 0.7 GiB spare here — too close to keep+ (4.5, 144), # measured: 216K demoted to ~24 tok/s here+ (5.4, 144),+ (6.5, 96), # measured smoke run held 6.3 GiB at peak+ (8.5, 64),+])+def test_27b_window_follows_other_programs(hermes_home, monkeypatch, others_gib, window_k):+ from hermes_cli.local_runtime import presets++ _mdir, gguf = _stage_27b(hermes_home, monkeypatch)+ _card(monkeypatch, others_gib)+ entry = presets.preset_for_model(gguf, CARD_CAPACITY, set(), requested_window=0,+ live=hardware.launch_budget(CARD_CAPACITY))+ assert entry.window == window_k * 1024+ assert entry.spilled is False and "override-tensor" not in entry.keys+ assert entry.keys["ctx-size"] == str(window_k * 1024)+ assert entry.keys["mmproj"].endswith("mmproj-Qwen3.8-27B-BF16.gguf")+++def test_busy_card_holds_the_floor_and_keeps_weights_on_the_gpu(hermes_home, monkeypatch):+ """A live reading may still include memory about to be freed; it never moves weights."""+ from hermes_cli.local_runtime import presets++ _mdir, gguf = _stage_27b(hermes_home, monkeypatch)+ _card(monkeypatch, 14.0)+ entry = presets.preset_for_model(gguf, CARD_CAPACITY, set(), requested_window=0,+ live=hardware.launch_budget(CARD_CAPACITY))+ assert entry.window == 64 * 1024+ assert entry.spilled is False and "override-tensor" not in entry.keys+++def test_a_capacity_plan_that_spills_is_left_alone(hermes_home, monkeypatch):+ """Small cards spill by design; a live reading must not rearrange that placement."""+ from hermes_cli.local_runtime import presets++ _mdir, gguf = _stage_27b(hermes_home, monkeypatch)+ small = HardwareBudget(usable_vram_bytes=10 * GIB, total_device_bytes=12 * GIB,+ ram_available_bytes=64 * GIB)+ _card(monkeypatch, 3.0, total=12 * GIB)+ capacity_only = presets.preset_for_model(gguf, small, set(), requested_window=0)+ with_live = presets.preset_for_model(gguf, small, set(), requested_window=0,+ live=hardware.launch_budget(small))+ assert capacity_only.spilled and with_live == capacity_only+++def test_recommendations_still_price_against_capacity(hermes_home, monkeypatch):+ """The catalog and picker describe the card, not this minute's desktop."""+ from hermes_cli.local_runtime import catalog++ _card(monkeypatch, 8.5)+ entry = catalog.catalog_by_id()["qwen3.8-27b"]+ variant = next(v for v in entry.variants if v.model_id == MODEL_ID)+ assert entry.launch_plan(variant, CARD_CAPACITY).decision.window == 216 * 1024+++# ── boot wiring ──────────────────────────────────────────────+++def test_boot_writes_the_launch_window(hermes_home, monkeypatch, capacity_probe):+ from hermes_cli.local_runtime import bootstrap, presets++ mdir, _gguf = _stage_27b(hermes_home, monkeypatch)+ _card(monkeypatch, 5.4)+ path = hermes_home / "presets.ini"+ assert bootstrap._generate_presets(mdir, path) == path+ assert presets.read_preset_decisions(path)[MODEL_ID].window == 144 * 1024+++def test_boot_keeps_capacity_when_the_probe_fails(hermes_home, monkeypatch, capacity_probe):+ """The probe is policy, not a prerequisite: a failure must never block a boot."""+ from hermes_cli.local_runtime import bootstrap, presets++ mdir, _gguf = _stage_27b(hermes_home, monkeypatch)++ def boom():+ raise OSError("nvidia-smi vanished")++ monkeypatch.setattr(hardware, "_nvidia_vram", boom)+ path = hermes_home / "presets.ini"+ assert bootstrap._generate_presets(mdir, path) == path+ assert presets.read_preset_decisions(path)[MODEL_ID].window == 216 * 1024+++# ── re-planning while nothing is loaded ──────────────────────+++class _Router:+ def __init__(self, preset_path, statuses):+ self.preset_path = preset_path+ self.statuses = statuses+ self.reloads = 0+ self.proc = SimpleNamespace(poll=lambda: None)+ self._refit_usable = None+ import threading++ self._lifecycle_lock = threading.RLock()++ def models(self, timeout_s=30):+ return dict(self.statuses)++ def reload_presets(self):+ self.reloads += 1+++def _booted(hermes_home, monkeypatch, others_gib):+ from hermes_cli.local_runtime import bootstrap++ mdir, _gguf = _stage_27b(hermes_home, monkeypatch)+ _card(monkeypatch, others_gib)+ path = hermes_home / "presets.ini"+ bootstrap._generate_presets(mdir, path)+ return path+++def test_idle_router_gets_windows_for_the_current_desktop(hermes_home, monkeypatch, capacity_probe):+ from hermes_cli.local_runtime import bootstrap, presets++ path = _booted(hermes_home, monkeypatch, 6.5)+ assert presets.read_preset_decisions(path)[MODEL_ID].window == 96 * 1024+ router = _Router(path, {MODEL_ID: "unloaded"})+ _card(monkeypatch, 2.0) # the user closed the heavy apps+ assert bootstrap.refit_idle_presets(router) is True+ assert router.reloads == 1+ assert presets.read_preset_decisions(path)[MODEL_ID].window == 216 * 1024+ # Nothing changed since: no rewrite, no reload.+ assert bootstrap.refit_idle_presets(router) is False and router.reloads == 1++[email protected]("status", ["loaded", "loading", "sleeping"])+def test_never_rewrites_while_a_model_holds_memory(hermes_home, monkeypatch, capacity_probe, status):+ """The router unloads a loaded model whose launch flags change on reload."""+ from hermes_cli.local_runtime import bootstrap++ path = _booted(hermes_home, monkeypatch, 6.5)+ before = path.read_text(encoding="utf-8-sig")+ router = _Router(path, {MODEL_ID: status})+ _card(monkeypatch, 2.0)+ assert bootstrap.refit_idle_presets(router) is False+ assert router.reloads == 0 and path.read_text(encoding="utf-8-sig") == before+++def test_small_changes_in_free_memory_do_not_replan(hermes_home, monkeypatch, capacity_probe):+ from hermes_cli.local_runtime import bootstrap, presets++ path = _booted(hermes_home, monkeypatch, 5.4)+ router = _Router(path, {MODEL_ID: "unloaded"})+ assert bootstrap.refit_idle_presets(router) is False # same reading as boot: same file+ monkeypatch.setattr(presets, "plan_presets", lambda *a, **k: pytest.fail("re-planned"))+ _card(monkeypatch, 5.5)+ assert bootstrap.refit_idle_presets(router) is False+++# ── growth ───────────────────────────────────────────────────+++def test_growth_counts_the_growing_model_as_free(hermes_home, monkeypatch, capacity_probe):+ """The grown instance loads after the current one exits. Counting the model's own memory as+ held would veto every rung."""+ from hermes_cli.local_runtime import bootstrap, growth, presets++ mdir, gguf = _stage_27b(hermes_home, monkeypatch)+ monkeypatch.setattr(bootstrap, "get_supervisor", lambda: SimpleNamespace(is_idle=lambda m: True))+ monkeypatch.setattr(growth, "is_managed_endpoint", lambda url: True)+ from hermes_cli.local_runtime import estimator, gguf as gguf_mod++ monkeypatch.setattr(gguf_mod, "read_gguf_header", presets.read_gguf_header)+ monkeypatch.setattr(estimator, "profile_from_gguf", presets.profile_from_gguf)+ own = presets.resident_footprint(gguf, CARD_CAPACITY, 144 * 1024)+ _card(monkeypatch, 2.0 + own / GIB) # 2 GiB of other programs plus our loaded 144K model+ path = hermes_home / "presets.ini"++ def refresh():+ presets.generate_presets(mdir, CARD_CAPACITY, path)+ return True++ monkeypatch.setattr(bootstrap, "refresh_local_runtime", refresh)+ real_read = presets.read_preset_decisions+ monkeypatch.setattr(presets, "read_preset_decisions", lambda p=None: real_read(path))+ grown = growth.maybe_grow_window(MODEL_ID, base_url="http://127.0.0.1:1/v1",+ session_tokens=140 * 1024, current_window=144 * 1024)+ assert grown == 216 * 1024+++def test_growth_refuses_a_rung_other_programs_leave_no_room_for(hermes_home, monkeypatch, capacity_probe):+ from hermes_cli.local_runtime import bootstrap, growth, presets++ _mdir, gguf = _stage_27b(hermes_home, monkeypatch)+ monkeypatch.setattr(bootstrap, "get_supervisor", lambda: SimpleNamespace(is_idle=lambda m: True))+ monkeypatch.setattr(growth, "is_managed_endpoint", lambda url: True)+ from hermes_cli.local_runtime import estimator, gguf as gguf_mod++ monkeypatch.setattr(gguf_mod, "read_gguf_header", presets.read_gguf_header)+ monkeypatch.setattr(estimator, "profile_from_gguf", presets.profile_from_gguf)+ own = presets.resident_footprint(gguf, CARD_CAPACITY, 144 * 1024)+ _card(monkeypatch, 5.4 + own / GIB)+ monkeypatch.setattr(bootstrap, "refresh_local_runtime", lambda: pytest.fail("bounced"))+ assert growth.maybe_grow_window(MODEL_ID, base_url="http://127.0.0.1:1/v1",+ session_tokens=140 * 1024, current_window=144 * 1024) is None+ assert not growth.load_window_overrides()+++# ── budget source ────────────────────────────────────────────+++def test_residency_cap_prices_capacity(hermes_home, monkeypatch, capacity_probe):+ """The residency cap is also decided before a server bounce. It swallows probe errors to keep+ boots unblocked, so the recorded call is the proof it priced capacity."""+ from hermes_cli.local_runtime import bootstrap++ mdir, _gguf = _stage_27b(hermes_home, monkeypatch)+ bootstrap._admitted_models_max(mdir, 4)+ assert capacity_probe == [{"planning": True}]