Skip to content

The agent that grows with you

fix(models-dev): cap the whole registry download, not just each read

Teknium4df354dba865
diff --git a/agent/models_dev.py b/agent/models_dev.py
index 1a7801e1cfb..a94c57477fe 100644
--- a/agent/models_dev.py
+++ b/agent/models_dev.py
@@ -27,6 +27,7 @@ logger = logging.getLogger(__name__)
MODELS_DEV_URL = "https://models.dev/api.json"
_MODELS_DEV_CACHE_TTL = 4 * 3600 # 4 hours — ETag conditional GET makes refresh cheap
_MODELS_DEV_RETRY_DELAY = 300 # 5 minutes after a failed refresh
+_MODELS_DEV_FETCH_DEADLINE = 15.0 # whole download; ~600 KB gzipped fits at ~40 KB/s
# In-memory cache
_models_dev_cache: dict[str, Any] = {}
_models_dev_cache_time: float = 0
@@ -342,18 +343,33 @@ def _fetch_models_dev_from_network(*, conditional: bool = False) -> tuple[dict[s
errors and on an empty/invalid payload. ``conditional`` sends ``If-None-Match`` with the sidecar's
ETag and raises ``_NotModified`` on 304 — pass True ONLY while holding ``_models_dev_fetch_lock``
AND a servable registry, or a 304 leaves the process with no data."""
+ from agent.deadline import DeadlineExpired, run_bounded_sync
+
headers: dict[str, str] = {}
if conditional and (etag := _load_etag()):
headers["If-None-Match"] = etag
- # (connect, read): 5 s connect fails fast on blackholed hosts; 10 s read tolerates a slow registry.
- response = requests.get(_get_models_dev_url(), headers=headers, timeout=(5, 10))
- if response.status_code == 304:
+ url = _get_models_dev_url()
+
+ def download() -> tuple[int, Any, str]:
+ # (connect, read) bounds each socket op, not the download: a trickling body never trips it.
+ response = requests.get(url, headers=headers, timeout=(5, 10))
+ if response.status_code == 304:
+ return 304, None, ""
+ response.raise_for_status()
+ return response.status_code, response.json(), response.headers.get("ETag", "")
+
+ # The cold-cache fetch runs inside a caller's request (a fresh home's first session.create
+ # reaches it through tool availability), so the whole exchange, DNS included, gets one
+ # wall-clock cap; on expiry the caller falls back to the stale/empty cache and the backoff.
+ bounded = run_bounded_sync(download, _MODELS_DEV_FETCH_DEADLINE, label="models.dev fetch")
+ if bounded.timed_out:
+ raise DeadlineExpired("models.dev fetch", _MODELS_DEV_FETCH_DEADLINE)
+ status, data, etag = bounded.value
+ if status == 304:
raise _NotModified()
- response.raise_for_status()
- data = response.json()
if not _validate_registry(data):
raise ValueError("models.dev returned an empty or invalid registry")
- return data, response.headers.get("ETag", "")
+ return data, etag
def _mark_stale_cache_grace() -> None:
diff --git a/tests/agent/test_models_dev_fetch_deadline.py b/tests/agent/test_models_dev_fetch_deadline.py
new file mode 100644
index 00000000000..525729bb006
--- /dev/null
+++ b/tests/agent/test_models_dev_fetch_deadline.py
@@ -0,0 +1,71 @@
+"""The models.dev download has a total wall-clock bound, not just a per-read timeout.
+
+A registry that trickles bytes slower than the per-read timeout never trips it, and the cold-cache
+fetch runs inside a caller's request (a fresh home's first ``session.create``), so the bound must
+cover the whole exchange and fall back to the cache path the client already has.
+"""
+import json
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+import pytest
+
+import agent.models_dev as md
+
+REGISTRY = {"anthropic": {"id": "anthropic", "models": {"claude-x": {"id": "claude-x"}}}}
+
+
+class _Trickle(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def do_GET(self):
+ self.server.gets += 1
+ try:
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", "1000000")
+ self.end_headers()
+ for _ in range(40): # ~4 s of one byte per 0.1 s: far under any per-read timeout
+ self.wfile.write(b" ")
+ self.wfile.flush()
+ if self.server.stop.wait(0.1):
+ return
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+
+
+def trickling_registry(monkeypatch):
+ server = ThreadingHTTPServer(("127.0.0.1", 0), _Trickle)
+ server.gets, server.stop = 0, threading.Event()
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ monkeypatch.setattr(md, "_get_models_dev_url", lambda: f"http://127.0.0.1:{server.server_port}/api.json")
+ monkeypatch.setattr(md, "_MODELS_DEV_FETCH_DEADLINE", 0.5, raising=False)
+ for name, value in (("_models_dev_cache", {}), ("_models_dev_cache_time", 0), ("_models_dev_retry_after", 0)):
+ monkeypatch.setattr(md, name, value)
+ yield server
+ server.stop.set()
+ server.shutdown()
+ server.server_close()
+
+
+def test_cold_fetch_from_a_trickling_registry_returns_within_the_deadline(trickling_registry):
+ assert not md._get_cache_path().exists()
+ started = time.monotonic()
+ assert md.fetch_models_dev() == {}
+ assert time.monotonic() - started < 2.0
+ # The failure arms the backoff, so the next caller does not wait again.
+ started = time.monotonic()
+ assert md.fetch_models_dev() == {}
+ assert time.monotonic() - started < 0.2
+ assert trickling_registry.gets == 1
+
+
+def test_forced_refresh_falls_back_to_the_disk_cache_within_the_deadline(trickling_registry):
+ md._get_cache_path().parent.mkdir(parents=True, exist_ok=True)
+ md._get_cache_path().write_text(json.dumps(REGISTRY), encoding="utf-8")
+ started = time.monotonic()
+ assert md.fetch_models_dev(force_refresh=True) == REGISTRY
+ assert time.monotonic() - started < 2.0