Skip to content

The agent that grows with you

perf(local-endpoints): disk L2 for server-type + ollama ctx probes, faster timeouts

teknium1d7a4065568b8
diff --git a/agent/model_metadata.py b/agent/model_metadata.py
index 757a306cde7..7794a6caa0c 100644
--- a/agent/model_metadata.py
+++ b/agent/model_metadata.py
@@ -123,6 +123,67 @@ _ENDPOINT_MODEL_CACHE_TTL = 300
_ENDPOINT_PROBE_TTL_SECONDS = 3600.0
_endpoint_probe_path_cache: Dict[str, tuple] = {}
+# ── Disk L2 for local-endpoint probe results ────────────────────────────────
+# The in-process caches above die with the process, so every CLI cold start
+# with a local model re-paid the probe waterfall in AIAgent.__init__:
+# detect_local_server_type (up to 4 HTTP GETs, ≤2 s each on a hung server)
+# + /api/show (≤3 s). A short-TTL disk cache makes back-to-back CLI
+# invocations hit disk instead of the network. Only SUCCESSFUL probes are
+# persisted (a down server must not pin a negative verdict), and the TTL is
+# short enough that swapping the server on a port (stop Ollama, start
+# LM Studio) is picked up within minutes — strictly fresher than the 1 h
+# in-process TTL that already accepts that staleness.
+_LOCAL_PROBE_DISK_TTL_SECONDS = 300.0
+
+
+def _local_probe_disk_cache_path() -> Path:
+ from hermes_constants import get_hermes_home
+ return get_hermes_home() / "cache" / "local_endpoint_probes.json"
+
+
+def _load_local_probe_disk_cache() -> Dict[str, Any]:
+ try:
+ with _local_probe_disk_cache_path().open("r", encoding="utf-8") as f:
+ data = json.load(f)
+ return data if isinstance(data, dict) else {}
+ except Exception:
+ return {}
+
+
+def _local_probe_disk_get(kind: str, key: str) -> Optional[Any]:
+ """Return a fresh cached value for ``kind:key``, else None."""
+ entry = _load_local_probe_disk_cache().get(f"{kind}:{key}")
+ if not isinstance(entry, dict):
+ return None
+ try:
+ if (time.time() - float(entry["ts"])) >= _LOCAL_PROBE_DISK_TTL_SECONDS:
+ return None
+ return entry["value"]
+ except Exception:
+ return None
+
+
+def _local_probe_disk_put(kind: str, key: str, value: Any) -> None:
+ """Persist a successful probe result. Best-effort; prunes stale entries."""
+ try:
+ now = time.time()
+ data = _load_local_probe_disk_cache()
+ data = {
+ k: v
+ for k, v in data.items()
+ if isinstance(v, dict)
+ and (now - float(v.get("ts", 0))) < _LOCAL_PROBE_DISK_TTL_SECONDS
+ }
+ data[f"{kind}:{key}"] = {"value": value, "ts": now}
+ atomic_json_write(
+ _local_probe_disk_cache_path(),
+ data,
+ indent=0,
+ separators=(",", ":"),
+ )
+ except Exception as e:
+ logger.debug("Failed to save local probe disk cache: %s", e)
+
def _get_model_metadata_cache_path() -> Path:
"""Return path to the OpenRouter model metadata disk cache."""
@@ -752,6 +813,13 @@ def detect_local_server_type(base_url: str, api_key: str = "") -> Optional[str]:
if cached is not None and (time.monotonic() - cached[1]) < _ENDPOINT_PROBE_TTL_SECONDS:
return cached[0]
+ # Disk L2: a fresh cross-process verdict skips the HTTP waterfall
+ # entirely (back-to-back CLI invocations, cron ticks).
+ disk_hit = _local_probe_disk_get("server_type", server_url)
+ if isinstance(disk_hit, str):
+ _endpoint_probe_path_cache[server_url] = (disk_hit, time.monotonic())
+ return disk_hit
+
headers = _auth_headers(api_key)
result: Optional[str] = None
@@ -804,6 +872,7 @@ def detect_local_server_type(base_url: str, api_key: str = "") -> Optional[str]:
if result is not None:
_endpoint_probe_path_cache[server_url] = (result, time.monotonic())
+ _local_probe_disk_put("server_type", server_url, result)
return result
@@ -1523,6 +1592,13 @@ def query_ollama_num_ctx(model: str, base_url: str, api_key: str = "") -> Option
if server_type != "ollama":
return None
+ # Disk L2: /api/show results are stable for a given (model, server) on
+ # human timescales — skip the HTTP roundtrip on fresh cross-process hits.
+ _disk_key = f"{server_url}|{bare_model}"
+ disk_hit = _local_probe_disk_get("ollama_num_ctx", _disk_key)
+ if isinstance(disk_hit, int) and disk_hit > 0:
+ return disk_hit
+
headers = _auth_headers(api_key)
try:
@@ -1540,7 +1616,9 @@ def query_ollama_num_ctx(model: str, base_url: str, api_key: str = "") -> Option
parts = line.strip().split()
if len(parts) >= 2:
try:
- return int(parts[-1])
+ _ctx = int(parts[-1])
+ _local_probe_disk_put("ollama_num_ctx", _disk_key, _ctx)
+ return _ctx
except ValueError:
pass
@@ -1548,7 +1626,9 @@ def query_ollama_num_ctx(model: str, base_url: str, api_key: str = "") -> Option
model_info = data.get("model_info", {})
for key, value in model_info.items():
if "context_length" in key and isinstance(value, (int, float)):
- return int(value)
+ _ctx = int(value)
+ _local_probe_disk_put("ollama_num_ctx", _disk_key, _ctx)
+ return _ctx
except Exception:
pass
return None
diff --git a/agent/models_dev.py b/agent/models_dev.py
index 54030c0965c..aed49b0d1d5 100644
--- a/agent/models_dev.py
+++ b/agent/models_dev.py
@@ -252,7 +252,12 @@ def _fetch_models_dev_from_network() -> Dict[str, Any]:
Raises on network errors and on an empty/invalid registry payload.
"""
- response = requests.get(MODELS_DEV_URL, timeout=15)
+ # Tuple (connect, read): a flat timeout=15 let a blackholed connect
+ # stall the first-turn critical path for the full 15 s. 5 s connect
+ # fails fast on unreachable hosts; 10 s read still tolerates a slow
+ # registry response (matches the OpenRouter fetch convention in
+ # agent/model_metadata.py).
+ response = requests.get(MODELS_DEV_URL, timeout=(5, 10))
response.raise_for_status()
data = response.json()
if not isinstance(data, dict) or not data:
diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.py
index 3b3d0eafb8e..c140ee02b4c 100644
--- a/hermes_cli/runtime_provider.py
+++ b/hermes_cli/runtime_provider.py
@@ -264,7 +264,7 @@ def _auto_detect_local_model(base_url: str) -> str:
url = base_url.rstrip("/")
if not url.endswith("/v1"):
url += "/v1"
- resp = requests.get(url + "/models", timeout=5)
+ resp = requests.get(url + "/models", timeout=(2, 3))
if resp.ok:
models = resp.json().get("data", [])
if len(models) == 1:
diff --git a/tests/agent/test_local_probe_disk_cache.py b/tests/agent/test_local_probe_disk_cache.py
new file mode 100644
index 00000000000..5bce7cf19a8
--- /dev/null
+++ b/tests/agent/test_local_probe_disk_cache.py
@@ -0,0 +1,132 @@
+"""Tests for the local-endpoint probe disk L2 cache in agent/model_metadata.
+
+Contract:
+- only SUCCESSFUL probes are persisted (failures never pin a verdict);
+- fresh disk entries serve cross-process (in-proc caches cleared);
+- entries expire after _LOCAL_PROBE_DISK_TTL_SECONDS;
+- corrupted cache files degrade to a miss;
+- detect_local_server_type and query_ollama_num_ctx both use it.
+"""
+
+import json
+import time
+from unittest.mock import MagicMock, patch
+
+import agent.model_metadata as MM
+
+
+def _clear_in_proc():
+ MM._endpoint_probe_path_cache.clear()
+ MM._LOCAL_CTX_PROBE_CACHE.clear()
+
+
+def _cache_file():
+ return MM._local_probe_disk_cache_path()
+
+
+class TestDiskHelpers:
+ def test_put_get_roundtrip(self):
+ MM._local_probe_disk_put("server_type", "http://127.0.0.1:11434", "ollama")
+ assert MM._local_probe_disk_get("server_type", "http://127.0.0.1:11434") == "ollama"
+
+ def test_expired_entry_is_miss(self):
+ MM._local_probe_disk_put("server_type", "http://127.0.0.1:11434", "ollama")
+ path = _cache_file()
+ data = json.loads(path.read_text(encoding="utf-8"))
+ for entry in data.values():
+ entry["ts"] = time.time() - MM._LOCAL_PROBE_DISK_TTL_SECONDS - 1
+ path.write_text(json.dumps(data), encoding="utf-8")
+ assert MM._local_probe_disk_get("server_type", "http://127.0.0.1:11434") is None
+
+ def test_corrupted_file_is_miss(self):
+ path = _cache_file()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("not json{{{", encoding="utf-8")
+ assert MM._local_probe_disk_get("server_type", "anything") is None
+ # And put() recovers by rewriting cleanly
+ MM._local_probe_disk_put("server_type", "k", "vllm")
+ assert MM._local_probe_disk_get("server_type", "k") == "vllm"
+
+ def test_stale_entries_pruned_on_put(self):
+ MM._local_probe_disk_put("server_type", "old", "ollama")
+ path = _cache_file()
+ data = json.loads(path.read_text(encoding="utf-8"))
+ for entry in data.values():
+ entry["ts"] = time.time() - MM._LOCAL_PROBE_DISK_TTL_SECONDS - 1
+ path.write_text(json.dumps(data), encoding="utf-8")
+ MM._local_probe_disk_put("server_type", "new", "vllm")
+ data = json.loads(path.read_text(encoding="utf-8"))
+ assert "server_type:old" not in data
+ assert "server_type:new" in data
+
+
+class TestDetectLocalServerTypeDiskL2:
+ def test_disk_hit_skips_http_entirely(self):
+ _clear_in_proc()
+ MM._local_probe_disk_put("server_type", "http://127.0.0.1:9999", "ollama")
+ with patch("httpx.Client") as mock_client:
+ result = MM.detect_local_server_type("http://127.0.0.1:9999/v1")
+ assert result == "ollama"
+ mock_client.assert_not_called()
+
+ def test_successful_probe_persists_to_disk(self):
+ _clear_in_proc()
+ ok = MagicMock(status_code=200)
+ ok.json.return_value = {"models": []}
+ notfound = MagicMock(status_code=404, text="")
+
+ def route(url, *a, **k):
+ return ok if url.endswith("/api/tags") else notfound
+
+ client = MagicMock()
+ client.get.side_effect = route
+ client.__enter__ = lambda s: client
+ client.__exit__ = lambda s, *a: False
+ with patch("httpx.Client", return_value=client):
+ result = MM.detect_local_server_type("http://127.0.0.1:8888/v1")
+ assert result == "ollama"
+ assert MM._local_probe_disk_get("server_type", "http://127.0.0.1:8888") == "ollama"
+
+ def test_failed_probe_not_persisted(self):
+ _clear_in_proc()
+ client = MagicMock()
+ client.get.side_effect = Exception("connection refused")
+ client.__enter__ = lambda s: client
+ client.__exit__ = lambda s, *a: False
+ with patch("httpx.Client", return_value=client):
+ result = MM.detect_local_server_type("http://127.0.0.1:7777/v1")
+ assert result is None
+ assert MM._local_probe_disk_get("server_type", "http://127.0.0.1:7777") is None
+
+
+class TestOllamaNumCtxDiskL2:
+ def test_disk_hit_skips_api_show(self):
+ _clear_in_proc()
+ MM._local_probe_disk_put("server_type", "http://127.0.0.1:11434", "ollama")
+ MM._local_probe_disk_put(
+ "ollama_num_ctx", "http://127.0.0.1:11434|llama3", 131072
+ )
+ with patch("httpx.Client") as mock_client:
+ ctx = MM.query_ollama_num_ctx("llama3", "http://127.0.0.1:11434/v1")
+ assert ctx == 131072
+ mock_client.assert_not_called()
+
+ def test_successful_show_persists(self):
+ _clear_in_proc()
+ MM._local_probe_disk_put("server_type", "http://127.0.0.1:11434", "ollama")
+ resp = MagicMock(status_code=200)
+ resp.json.return_value = {
+ "parameters": "",
+ "model_info": {"llama.context_length": 8192},
+ }
+ client = MagicMock()
+ client.post.return_value = resp
+ client.__enter__ = lambda s: client
+ client.__exit__ = lambda s, *a: False
+ with patch("httpx.Client", return_value=client):
+ ctx = MM.query_ollama_num_ctx("llama3", "http://127.0.0.1:11434/v1")
+ assert ctx == 8192
+ assert (
+ MM._local_probe_disk_get("ollama_num_ctx", "http://127.0.0.1:11434|llama3")
+ == 8192
+ )