Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

perf(local-models): nothing blocks the loop, and the hardware and registry probes are memoised

rubenluetke10-beep1401bcc7f208
diff --git a/jarvis/brain/ollama_pull.py b/jarvis/brain/ollama_pull.py
index 6a12990e5a..5a35d3cf4b 100644
--- a/jarvis/brain/ollama_pull.py
+++ b/jarvis/brain/ollama_pull.py
@@ -29,6 +29,7 @@ import asyncio
import datetime
import json
import logging
+import time
from dataclasses import dataclass
from typing import Any, Literal
@@ -420,8 +421,29 @@ async def registry_size_gb(client: httpx.AsyncClient, model: str) -> float | Non
return size
+#: The whole-shortlist registry sweep is memoised for five minutes INCLUDING
+#: a negative answer: offline, every open of the section used to fire fifteen
+#: manifest requests that each waited out the connect timeout. The per-model
+#: positives above live for the process; this memo is the one that remembers
+#: "the registry did not answer" long enough for the panel to stay instant.
+_REAL_SIZES_TTL_S = 300.0
+_real_sizes_memo: tuple[float, dict[str, float]] | None = None # (monotonic, sizes)
+
+
+def _reset_for_tests() -> None:
+ """Forget the registry memos (tests only)."""
+ global _real_sizes_memo
+ _real_sizes_memo = None
+ _registry_sizes.clear()
+
+
async def _real_sizes() -> dict[str, float]:
- """Registry sizes for the whole shortlist, fetched concurrently."""
+ """Registry sizes for the whole shortlist, fetched concurrently and
+ memoised for :data:`_REAL_SIZES_TTL_S` (misses included)."""
+ global _real_sizes_memo
+ hit = _real_sizes_memo
+ if hit is not None and time.monotonic() - hit[0] < _REAL_SIZES_TTL_S:
+ return dict(hit[1])
async with httpx.AsyncClient(timeout=_REGISTRY_TIMEOUT) as client:
results = await asyncio.gather(
*(registry_size_gb(client, entry.id) for entry in RECOMMENDED_MODELS),
@@ -431,6 +453,7 @@ async def _real_sizes() -> dict[str, float]:
for entry, result in zip(RECOMMENDED_MODELS, results, strict=True):
if isinstance(result, float):
sizes[entry.id] = result
+ _real_sizes_memo = (time.monotonic(), dict(sizes))
return sizes
@@ -483,10 +506,15 @@ async def recommendations() -> dict[str, Any]:
verdict weighs GPU memory ahead of RAM, and each role gets exactly one
"recommended" entry — the largest one this box runs well.
"""
- installed, error = await installed_models()
- memory_gb = total_memory_gb()
- accel, accel_source = accelerator_gb()
- real_sizes = await _real_sizes()
+ # The two hardware probes are synchronous (psutil, nvidia-smi) and go to a
+ # worker thread; everything runs concurrently so the panel waits for the
+ # slowest leg, not the sum.
+ (installed, error), memory_gb, (accel, accel_source), real_sizes = await asyncio.gather(
+ installed_models(),
+ asyncio.to_thread(total_memory_gb),
+ asyncio.to_thread(accelerator_gb),
+ _real_sizes(),
+ )
models: list[dict[str, Any]] = []
for entry in RECOMMENDED_MODELS:
diff --git a/jarvis/hardware/detection.py b/jarvis/hardware/detection.py
index 5ed7e27341..e6d2f8f85b 100644
--- a/jarvis/hardware/detection.py
+++ b/jarvis/hardware/detection.py
@@ -5,6 +5,7 @@ STT configuration (local Whisper model vs. cloud API) to the user.
All checks are read-only; nothing is installed or modified.
"""
+
from __future__ import annotations
import logging
@@ -12,6 +13,8 @@ import platform
import shutil
import subprocess
import sys
+import threading
+import time
from dataclasses import dataclass, field
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
@@ -22,6 +25,7 @@ log = logging.getLogger(__name__)
# DataClasses
# ----------------------------------------------------------------------
+
@dataclass(slots=True)
class GPUInfo:
name: str
@@ -59,10 +63,11 @@ class HardwareReport:
@dataclass(slots=True)
class WhisperRecommendation:
"""Recommended Whisper configuration based on detected hardware."""
- provider: str # "faster-whisper" | "openai-api"
- model: str # tiny | base | small | large-v3-turbo | large-v3
- device: str # cuda | cpu
- compute_type: str # int8_float16 | fp16 | int8
+
+ provider: str # "faster-whisper" | "openai-api"
+ model: str # tiny | base | small | large-v3-turbo | large-v3
+ device: str # cuda | cpu
+ compute_type: str # int8_float16 | fp16 | int8
expected_latency_ms: int
rationale: str
@@ -71,6 +76,7 @@ class WhisperRecommendation:
# Detection
# ----------------------------------------------------------------------
+
def _run(cmd: list[str], timeout: int = 10) -> str:
try:
result = subprocess.run(
@@ -132,8 +138,7 @@ def _detect_nvidia_gpus() -> list[GPUInfo]:
pynvml.nvmlShutdown()
return gpus
except Exception: # noqa: BLE001 — no pynvml / no driver is a normal state
- log.debug("hardware: pynvml probe unavailable, falling back to nvidia-smi",
- exc_info=True)
+ log.debug("hardware: pynvml probe unavailable, falling back to nvidia-smi", exc_info=True)
# Fallback: nvidia-smi
out = _run(["nvidia-smi", "--query-gpu=name,memory.total", "--format=csv,noheader,nounits"])
@@ -208,6 +213,7 @@ def _detect_existing_installs() -> dict[str, str]:
# Public API
# ----------------------------------------------------------------------
+
def analyze() -> HardwareReport:
"""Full hardware analysis (run once during setup and on demand)."""
cpu_name, cpu_phys, cpu_log = _detect_cpu()
@@ -260,9 +266,7 @@ def recommend_whisper(
large-v3-turbo anyway).
"""
gpu_usable = (
- report.has_nvidia_gpu
- and report.torch_cuda_available
- and gpu_inference_verified is True
+ report.has_nvidia_gpu and report.torch_cuda_available and gpu_inference_verified is True
)
if not gpu_usable:
cuda_present_unverified = report.has_nvidia_gpu and report.torch_cuda_available
@@ -335,6 +339,7 @@ def recommend_whisper(
# CLI
# ----------------------------------------------------------------------
+
def _format_report(report: HardwareReport, rec: WhisperRecommendation) -> str:
lines = [
"╔══════════════════════════════════════════════════════════╗",
@@ -393,9 +398,7 @@ def _format_report(report: HardwareReport, rec: WhisperRecommendation) -> str:
return "\n".join(lines)
-def check_records(
- report: HardwareReport, rec: WhisperRecommendation
-) -> list[dict[str, object]]:
+def check_records(report: HardwareReport, rec: WhisperRecommendation) -> list[dict[str, object]]:
"""The same preflight as :func:`_format_report`, as machine-readable records.
One record per component, in the closed vocabulary defined by
@@ -450,9 +453,7 @@ def check_records(
detail += f", compute capability {gpu.compute_capability}"
records.append(record(f"gpu{i}", "ok", detail))
else:
- records.append(
- record("gpu", "info", "no NVIDIA GPU detected — everything runs on CPU")
- )
+ records.append(record("gpu", "info", "no NVIDIA GPU detected — everything runs on CPU"))
records.append(
record(
@@ -510,9 +511,44 @@ def cuda_inference_verified() -> bool | None:
return None
+#: :func:`usable_accelerator_gb` shells out to ``nvidia-smi`` (or drives
+#: pynvml) — 100–400 ms on a Windows box — and the "Local models" section asks
+#: it from several panels per paint. A card does not change size while the app
+#: runs, so one probe per minute is the honest cadence; the memo is process-wide
+#: and thread-safe because the callers hop to a worker thread.
+_ACCELERATOR_TTL_S = 60.0
+_accelerator_lock = threading.Lock()
+_accelerator_memo: tuple[float, tuple[float, str]] | None = None # (monotonic, answer)
+
+
+def _reset_for_tests() -> None:
+ """Forget the memoised accelerator probe (tests only)."""
+ global _accelerator_memo
+ with _accelerator_lock:
+ _accelerator_memo = None
+
+
def usable_accelerator_gb() -> tuple[float, str]:
"""Usable accelerator memory in GiB and where that figure came from.
+ Memoised for :data:`_ACCELERATOR_TTL_S`; see :func:`_probe_accelerator_gb`
+ for the probe itself.
+ """
+ global _accelerator_memo
+ now = time.monotonic()
+ with _accelerator_lock:
+ hit = _accelerator_memo
+ if hit is not None and now - hit[0] < _ACCELERATOR_TTL_S:
+ return hit[1]
+ answer = _probe_accelerator_gb()
+ with _accelerator_lock:
+ _accelerator_memo = (time.monotonic(), answer)
+ return answer
+
+
+def _probe_accelerator_gb() -> tuple[float, str]:
+ """The uncached accelerator probe behind :func:`usable_accelerator_gb`.
+
``(gb, source)`` with source ``"nvidia-smi"`` | ``"apple-unified"`` |
``"none"``. Dedicated NVIDIA VRAM counts as-is; on Apple Silicon the GPU
shares the unified memory, so total RAM is the honest figure. Every other
diff --git a/jarvis/ui/web/local_models_routes.py b/jarvis/ui/web/local_models_routes.py
index 78157dc29d..2d963740e9 100644
--- a/jarvis/ui/web/local_models_routes.py
+++ b/jarvis/ui/web/local_models_routes.py
@@ -24,6 +24,7 @@ the two steps leaves a valid config, never an empty slot.
from __future__ import annotations
+import asyncio
import logging
from dataclasses import asdict
from typing import Any
@@ -460,6 +461,11 @@ async def set_role(
if tag
else f"{role} is back to discovery: Jarvis picks the smallest capable download."
)
+ if not written.get("drift_guarded", True):
+ message += (
+ " This pick may be reverted by the drift guard — "
+ "the config baseline could not be updated."
+ )
return RoleSetResponse(
ok=True, role=role, model=tag, config_key=written["config_key"], message=message
)
@@ -815,7 +821,9 @@ class EnvGuideResponse(BaseModel):
async def get_server(provider_id: str) -> ServerResponse:
"""Runtime picture plus what is loaded and how much disk the downloads take."""
_require_pull_capable(provider_id)
- status = ollama_runtime.runtime_status()
+ # A synchronous urllib probe (up to 1.5 s when the server is down) — off
+ # the loop so the sibling panels' requests keep flowing meanwhile.
+ status = await asyncio.to_thread(ollama_runtime.runtime_status)
root = str(status.get("base_url") or _server_root())
running: list[RunningModelRow] = []
disk = 0
@@ -851,7 +859,7 @@ async def get_server(provider_id: str) -> ServerResponse:
async def post_server_stop(provider_id: str) -> ServerActionResponse:
"""Stop the Ollama Jarvis itself started — never one started elsewhere."""
_require_pull_capable(provider_id)
- ok, message = ollama_runtime.stop_server()
+ ok, message = await asyncio.to_thread(ollama_runtime.stop_server)
return ServerActionResponse(ok=ok, message=message)
@@ -907,7 +915,7 @@ async def get_server_log(
) -> ServerLogResponse:
"""The last lines of the server log Jarvis writes when it starts Ollama."""
_require_pull_capable(provider_id)
- return ServerLogResponse(lines=ollama_runtime.tail_log(lines))
+ return ServerLogResponse(lines=await asyncio.to_thread(ollama_runtime.tail_log, lines))
@router.get("/server/env-guide", response_model=EnvGuideResponse)
diff --git a/tests/unit/brain/test_ollama_pull.py b/tests/unit/brain/test_ollama_pull.py
index a18e57ad0b..488476eaf7 100644
--- a/tests/unit/brain/test_ollama_pull.py
+++ b/tests/unit/brain/test_ollama_pull.py
@@ -84,6 +84,8 @@ def test_installed_matching_understands_the_latest_tag(
class _FakeTagsClient:
payload: dict[str, Any] = {}
fail: bool = False
+ #: Manifest requests the registry half answered (memo proof).
+ registry_calls: int = 0
#: Registry manifests keyed by model id, for the real-size lookup. Empty by
#: default, which is the offline case: the curated estimates are used.
@@ -104,6 +106,7 @@ class _FakeTagsClient:
# report a nonsense size, and a test suite that reaches the real
# registry would be a network dependency in a unit test.
if "registry.ollama.ai" in url:
+ _FakeTagsClient.registry_calls += 1
return _registry_response(url)
if _FakeTagsClient.fail:
raise httpx.ConnectError("connection refused")
@@ -145,9 +148,10 @@ def fake_tags(monkeypatch):
_FakeTagsClient.fail = False
_FakeTagsClient.payload = {}
_FakeTagsClient.manifests = {}
- pull._registry_sizes.clear()
+ _FakeTagsClient.registry_calls = 0
+ pull._reset_for_tests()
yield _FakeTagsClient
- pull._registry_sizes.clear()
+ pull._reset_for_tests()
async def test_installed_models_excludes_cloud_references(fake_tags) -> None:
@@ -487,3 +491,36 @@ async def test_the_payload_names_the_hardware_it_judged_against(fake_tags, monke
assert result["accelerator_gb"] == 16.0
assert result["accelerator_source"] == "nvidia-smi"
assert result["memory_gb"] == 32.0
+
+
+# ── Instant paint: probes and registry sweeps are memoised ───────────────
+async def test_the_accelerator_is_probed_once_across_two_calls(fake_tags, monkeypatch) -> None:
+ """``nvidia-smi`` costs hundreds of milliseconds; the section asks several
+ times per paint, so the probe answers from a 60 s memo after the first."""
+ from jarvis.hardware import detection
+
+ probes: list[int] = []
+
+ def _probe() -> tuple[float, str]:
+ probes.append(1)
+ return 16.0, "nvidia-smi"
+
+ detection._reset_for_tests()
+ monkeypatch.setattr(detection, "_probe_accelerator_gb", _probe)
+ try:
+ await pull.recommendations()
+ await pull.recommendations()
+ assert pull.accelerator_gb() == (16.0, "nvidia-smi")
+ finally:
+ detection._reset_for_tests()
+ assert len(probes) == 1
+
+
+async def test_an_offline_registry_is_not_asked_again_within_the_memo(fake_tags) -> None:
+ """Fifteen manifest misses per open, each waiting out a connect timeout,
+ is what made the shortlist feel slow offline — the miss is remembered."""
+ await pull.recommendations()
+ first = fake_tags.registry_calls
+ assert first == len(pull.RECOMMENDED_MODELS)
+ await pull.recommendations()
+ assert fake_tags.registry_calls == first
diff --git a/tests/unit/ui/web/test_local_models_routes.py b/tests/unit/ui/web/test_local_models_routes.py
index 19648563b3..c38fa44108 100644
--- a/tests/unit/ui/web/test_local_models_routes.py
+++ b/tests/unit/ui/web/test_local_models_routes.py
@@ -619,3 +619,38 @@ def test_roles_carry_the_voice_brains_context(server: WebServer, fake, monkeypat
assert rows["voice"]["context_source"] == "automatic"
assert rows["chat"]["context_tokens"] is None
assert rows["chat"]["context_source"] == ""
+
+
+# ═════════════════════════════════════════════════════════════════════════
+# Instant paint: nothing blocks the loop
+# ═════════════════════════════════════════════════════════════════════════
+
+
+async def test_server_and_inventory_overlap_instead_of_queueing(server, fake, monkeypatch) -> None:
+ """The runtime probe is synchronous (urllib, up to 1.5 s when Ollama is
+ down); it used to run ON the loop, so ``/inventory`` waited behind it.
+ Off the loop, the two requests take about the slowest one, not the sum."""
+ import asyncio
+ import time
+
+ def _slow_status() -> dict:
+ time.sleep(0.4)
+ return _status(False)
+
+ monkeypatch.setattr(ollama_runtime, "runtime_status", _slow_status)
+
+ async def _slow_inventory(root: str, **_kw) -> list:
+ await asyncio.sleep(0.4)
+ return []
+
+ monkeypatch.setattr(ollama_inventory, "list_models", _slow_inventory)
+ # Loopback peer + loopback Host, so the surface guard serves it like the app.
+ transport = httpx.ASGITransport(app=server.app, client=("127.0.0.1", 1))
+ async with httpx.AsyncClient(transport=transport, base_url="http://127.0.0.1") as client:
+ started = time.perf_counter()
+ first, second = await asyncio.gather(
+ client.get(f"{BASE}/server"), client.get(f"{BASE}/inventory")
+ )
+ elapsed = time.perf_counter() - started
+ assert first.status_code == 200 and second.status_code == 200
+ assert elapsed < 0.7, f"the two requests queued: {elapsed:.2f}s"