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): one shared inventory sweep per paint

rubenluetke10-beepc8c6cb3d5093
diff --git a/jarvis/brain/ollama_pull.py b/jarvis/brain/ollama_pull.py
index 5a35d3cf4b..5b2ecd6032 100644
--- a/jarvis/brain/ollama_pull.py
+++ b/jarvis/brain/ollama_pull.py
@@ -348,6 +348,13 @@ async def installed_models() -> tuple[set[str], str | None]:
nothing installed".
"""
root = server_root()
+ # The section's shared sweep, when it is fresh, already holds the answer;
+ # a pull's own progress polling keeps its independent /api/tags below.
+ from jarvis.brain import ollama_inventory # noqa: PLC0415 — sibling, lazy
+
+ snapshot = ollama_inventory.peek_snapshot(root)
+ if snapshot is not None:
+ return set(snapshot.all_names), None
try:
async with httpx.AsyncClient(timeout=CLIENT_TIMEOUT) as client:
resp = await client.get(f"{root}/api/tags")
@@ -639,7 +646,11 @@ async def _run_pull(model: str) -> None:
# Trust the server's inventory over the stream's last line: a pull can end
# cleanly and still leave nothing usable, and a card that says "ready" over
- # a missing model is the failure this whole area exists to prevent.
+ # a missing model is the failure this whole area exists to prevent. The
+ # shared snapshot is dropped first so every panel sees the new download.
+ from jarvis.brain import ollama_inventory # noqa: PLC0415 — sibling, lazy
+
+ ollama_inventory.invalidate_snapshot(root)
installed, error = await installed_models()
if error or not _is_installed(model, installed):
run.state = "error"
diff --git a/jarvis/ui/web/local_models_routes.py b/jarvis/ui/web/local_models_routes.py
index 2d963740e9..4642fb9075 100644
--- a/jarvis/ui/web/local_models_routes.py
+++ b/jarvis/ui/web/local_models_routes.py
@@ -176,13 +176,15 @@ def _row(
async def _running_by_name(root: str) -> dict[str, OllamaRunningModel]:
- """``/api/ps`` as a map; an unanswered probe is an empty map (logged), so a
- server that lists downloads but stalls on ``/api/ps`` still renders."""
+ """``/api/ps`` as a map from the shared snapshot; an unanswered probe is an
+ empty map (logged), so a server that lists downloads but stalls on
+ ``/api/ps`` still renders."""
try:
- return {r.name: r for r in await inventory.running_models(root)}
+ snapshot = await inventory.cached_snapshot(root)
except OllamaServerError as exc:
- log.info("local-models: /api/ps unavailable at %s: %s", root, exc)
+ log.info("local-models: inventory unavailable at %s: %s", root, exc)
return {}
+ return {r.name: r for r in snapshot.running}
def _http_error(exc: OllamaServerError) -> HTTPException:
@@ -206,7 +208,7 @@ async def get_inventory(provider_id: str, request: Request) -> InventoryResponse
root = _server_root()
cfg = _resolve_cfg(request)
try:
- models = await inventory.list_models(root)
+ snapshot = await inventory.cached_snapshot(root)
except OllamaServerError as exc:
return InventoryResponse(
provider=provider_id,
@@ -217,7 +219,8 @@ async def get_inventory(provider_id: str, request: Request) -> InventoryResponse
loaded_vram_bytes=0,
error=str(exc),
)
- running = await _running_by_name(root)
+ models = snapshot.models
+ running = {r.name: r for r in snapshot.running}
rows = [LocalModelRow(**_row(m, running, _roles_using(cfg, m.name))) for m in models]
return InventoryResponse(
provider=provider_id,
diff --git a/tests/unit/brain/test_ollama_inventory.py b/tests/unit/brain/test_ollama_inventory.py
index 54153582fc..a5eff1352d 100644
--- a/tests/unit/brain/test_ollama_inventory.py
+++ b/tests/unit/brain/test_ollama_inventory.py
@@ -18,6 +18,7 @@ ROOT = "http://localhost:11434"
@pytest.fixture
def fake() -> FakeOllamaServer:
+ inv._reset_for_tests()
server = FakeOllamaServer()
server.add(
"qwen3.5:4b",
@@ -120,9 +121,12 @@ async def test_get_model_is_latest_tolerant_and_404s_honestly(fake: FakeOllamaSe
def test_native_context_length_reads_the_architecture_key() -> None:
- assert inv.native_context_length(
- {"general.architecture": "gemma4", "gemma4.context_length": 131072}
- ) == 131072
+ assert (
+ inv.native_context_length(
+ {"general.architecture": "gemma4", "gemma4.context_length": 131072}
+ )
+ == 131072
+ )
# No architecture hint: any ``*.context_length`` key still counts.
assert inv.native_context_length({"llama.context_length": 8192}) == 8192
assert inv.native_context_length({"general.architecture": "x"}) is None
@@ -165,6 +169,57 @@ async def test_delete_removes_the_download_and_404s_afterwards(fake: FakeOllamaS
async def test_disk_usage_counts_each_weight_once(fake: FakeOllamaServer) -> None:
"""An alias shares its weights with the base — counting it would double the total."""
fake.add("qwen3.5-4b-jarvis-ab12cd34:latest", size=3_400_000_000)
- assert await inv.disk_usage(ROOT, transport=fake.transport()) == (
- 3_400_000_000 + 2_500_000_000
+ assert await inv.disk_usage(ROOT, transport=fake.transport()) == (3_400_000_000 + 2_500_000_000)
+
+
+# ── Shared snapshot ──────────────────────────────────────────────────────
+async def test_concurrent_readers_share_one_sweep(fake) -> None:
+ """Four panels opening at once used to mean four ``/api/tags`` and four
+ full ``/api/show`` sweeps; they now join the sweep in flight."""
+ import asyncio
+
+ first, second, third = await asyncio.gather(
+ inv.cached_snapshot(ROOT, transport=fake.transport()),
+ inv.cached_snapshot(ROOT, transport=fake.transport()),
+ inv.cached_snapshot(ROOT, transport=fake.transport()),
)
+ assert first is second is third
+ assert [c[1] for c in fake.calls].count("/api/tags") == 1
+ assert [c[1] for c in fake.calls].count("/api/show") == len(fake.models)
+ assert [c[1] for c in fake.calls].count("/api/ps") == 1
+ assert {m.name for m in first.models} == set(fake.models)
+ assert first.fetched_at > 0
+
+
+async def test_unload_and_delete_drop_the_snapshot(fake) -> None:
+ fake.load("qwen3.5:4b")
+ before = await inv.cached_snapshot(ROOT, transport=fake.transport())
+ assert [r.name for r in before.running] == ["qwen3.5:4b"]
+ await inv.unload_model(ROOT, "qwen3.5:4b", transport=fake.transport())
+ after = await inv.cached_snapshot(ROOT, transport=fake.transport())
+ assert after is not before and after.running == ()
+ await inv.delete_model(ROOT, "qwen3-embedding:4b", transport=fake.transport())
+ gone = await inv.cached_snapshot(ROOT, transport=fake.transport())
+ assert [m.name for m in gone.models] == ["qwen3.5:4b"]
+
+
+async def test_an_offline_server_is_asked_once_per_window(fake) -> None:
+ """Every panel shows the same sentence after ONE refused connection."""
+ fake.offline = True
+ with pytest.raises(inv.OllamaServerError):
+ await inv.cached_snapshot(ROOT, transport=fake.transport())
+ fake.offline = False
+ # Still within the window: the remembered failure answers, no request.
+ with pytest.raises(inv.OllamaServerError):
+ await inv.cached_snapshot(ROOT, transport=fake.transport())
+ assert fake.calls == []
+ inv.invalidate_snapshot(ROOT)
+ snapshot = await inv.cached_snapshot(ROOT, transport=fake.transport())
+ assert len(snapshot.models) == 2
+
+
+async def test_the_snapshot_expires(fake) -> None:
+ first = await inv.cached_snapshot(ROOT, transport=fake.transport())
+ second = await inv.cached_snapshot(ROOT, max_age_s=0.0, transport=fake.transport())
+ assert second is not first
+ assert inv.peek_snapshot(ROOT) is second
diff --git a/tests/unit/brain/test_ollama_pull.py b/tests/unit/brain/test_ollama_pull.py
index 488476eaf7..ff71437ebf 100644
--- a/tests/unit/brain/test_ollama_pull.py
+++ b/tests/unit/brain/test_ollama_pull.py
@@ -18,8 +18,12 @@ import pytest
import jarvis.brain.ollama_pull as pull
import jarvis.core.config as cfg
+from jarvis.brain import ollama_inventory
from jarvis.core.config import JarvisConfig
+#: Captured before any fixture swaps ``httpx.AsyncClient`` for the fake.
+_RealAsyncClient = httpx.AsyncClient
+
@pytest.fixture(autouse=True)
def _clean_runs(monkeypatch):
@@ -27,8 +31,10 @@ def _clean_runs(monkeypatch):
monkeypatch.setattr(cfg, "load_config", lambda: JarvisConfig())
monkeypatch.delenv("OLLAMA_HOST", raising=False)
pull._runs.clear()
+ ollama_inventory._reset_for_tests()
yield
pull._runs.clear()
+ ollama_inventory._reset_for_tests()
# ── Fit verdict ──────────────────────────────────────────────────────────
@@ -524,3 +530,29 @@ async def test_an_offline_registry_is_not_asked_again_within_the_memo(fake_tags)
assert first == len(pull.RECOMMENDED_MODELS)
await pull.recommendations()
assert fake_tags.registry_calls == first
+
+
+async def test_installed_models_reads_the_shared_snapshot_when_fresh(
+ fake_tags, monkeypatch
+) -> None:
+ """A paint that already swept the server does not ask ``/api/tags`` again
+ for the shortlist's "installed" marks; the pull polling still may."""
+ from tests.fakes.fake_ollama_server import FakeOllamaServer
+
+ fake = FakeOllamaServer()
+ fake.add("qwen3.5:latest")
+ fake.add("qwen3.5-latest-jarvis-ab12cd34:latest")
+ # ``fake_tags`` swapped httpx.AsyncClient; the inventory sweep needs the
+ # real one over the fake server's transport.
+ monkeypatch.setattr(
+ ollama_inventory,
+ "_make_client",
+ lambda transport=None: _RealAsyncClient(transport=fake.transport()),
+ )
+ await ollama_inventory.cached_snapshot(pull.server_root())
+ fake_tags.fail = True # the pull module's own client would fail now
+ installed, error = await pull.installed_models()
+ assert error is None
+ # Aliases count as "on the server" for the bookkeeping, even though the
+ # ledger hides them.
+ assert installed == {"qwen3.5:latest", "qwen3.5-latest-jarvis-ab12cd34:latest"}
diff --git a/tests/unit/ui/web/test_local_models_routes.py b/tests/unit/ui/web/test_local_models_routes.py
index c38fa44108..04566a51cd 100644
--- a/tests/unit/ui/web/test_local_models_routes.py
+++ b/tests/unit/ui/web/test_local_models_routes.py
@@ -31,6 +31,7 @@ BASE = "/api/providers/ollama/local-models"
@pytest.fixture
def fake(monkeypatch: pytest.MonkeyPatch) -> FakeOllamaServer:
+ ollama_inventory._reset_for_tests()
server = FakeOllamaServer()
server.add("qwen3.5:4b", size=3_400_000_000, capabilities=("completion", "tools", "vision"))
server.add("gemma4:12b-it-qat", size=7_200_000_000, capabilities=("completion", "tools"))
@@ -654,3 +655,19 @@ async def test_server_and_inventory_overlap_instead_of_queueing(server, fake, mo
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"
+
+
+def test_one_paint_costs_one_sweep(server, fake, shortlist, monkeypatch) -> None:
+ """Inventory, roles and server in sequence: ONE ``/api/tags`` and ONE
+ ``/api/show`` per download — the panels share the snapshot."""
+ monkeypatch.setattr(ollama_runtime, "runtime_status", lambda: _status(True))
+ with TestClient(server.app) as client:
+ inventory_ = client.get(f"{BASE}/inventory").json()
+ roles = client.get(f"{BASE}/roles").json()
+ status = client.get(f"{BASE}/server").json()
+ paths = [c[1] for c in fake.calls]
+ assert paths.count("/api/tags") == 1
+ assert paths.count("/api/show") == 3, "one per visible download, the alias is skipped"
+ assert paths.count("/api/ps") == 1
+ assert inventory_["disk_bytes"] == status["disk_bytes"] > 0
+ assert roles["error"] is None