Skip to content

The agent that grows with you

fix(model-metadata): cap every metadata probe's whole exchange too

Teknium8469e34161c8
diff --git a/agent/model_metadata_http.py b/agent/model_metadata_http.py
index b408724c632..39e4fa23a46 100644
--- a/agent/model_metadata_http.py
+++ b/agent/model_metadata_http.py
@@ -3,6 +3,9 @@ from __future__ import annotations
from contextlib import contextmanager
+# Wall-clock cap on one probe (headers + whole body), on top of the per-op httpx timeouts.
+TOTAL_DEADLINE_S = 15.0
+
def resolve_verify(base_url: str = ""):
from agent.ssl_verify import resolve_httpx_verify
@@ -25,6 +28,7 @@ def resolve_verify(base_url: str = ""):
@contextmanager
def stream(url: str, *, headers=None, params=None, timeout=10.0, verify=None):
import httpx
+ from agent.deadline import DeadlineExpired, run_bounded_sync
from hermes_cli.urllib_security import url_origin
origin = url_origin(url)
@@ -45,11 +49,24 @@ def stream(url: str, *, headers=None, params=None, timeout=10.0, verify=None):
follow_redirects=True,
event_hooks={"request": [scope_credentials]},
) as client:
- with client.stream("GET", url, headers=headers, params=params) as response:
- yield response
+ def fetch():
+ response = client.send(client.build_request("GET", url, headers=headers, params=params), stream=True)
+ if response.is_success: # a rejection closes on its headers, never waits for a body
+ response.read()
+ return response
+ # Probes run inside requests (session.create resolves the context window through them), and
+ # httpx timeouts bound each socket op, not the exchange: a body trickling in under the read
+ # timeout, or a hung DNS lookup, would hold the caller for as long as it lasts. Leaving the
+ # client block on expiry closes the pool under the abandoned worker.
+ bounded = run_bounded_sync(fetch, TOTAL_DEADLINE_S, label=f"model metadata {origin}")
+ if bounded.timed_out:
+ raise DeadlineExpired(f"model metadata {origin}", TOTAL_DEADLINE_S)
+ try:
+ yield bounded.value
+ finally:
+ bounded.value.close()
def get(url: str, *, headers=None, params=None, timeout=10.0, verify=None):
with stream(url, headers=headers, params=params, timeout=timeout, verify=verify) as response:
- response.read()
return response
diff --git a/tests/agent/test_model_metadata_probe_deadline.py b/tests/agent/test_model_metadata_probe_deadline.py
new file mode 100644
index 00000000000..33d2713150d
--- /dev/null
+++ b/tests/agent/test_model_metadata_probe_deadline.py
@@ -0,0 +1,52 @@
+"""Model-metadata probes have a total wall-clock bound, not just per-op httpx timeouts.
+
+Probes run inside requests (a new session resolves its context window through them), so a
+``/models`` body that trickles in under the read timeout must not hold the caller.
+"""
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+import pytest
+
+import agent.model_metadata as mm
+import agent.model_metadata_http as http
+
+
+class _Trickle(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def do_GET(self):
+ try:
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", "1000000")
+ self.end_headers()
+ for _ in range(80): # ~8 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_endpoint(monkeypatch):
+ server = ThreadingHTTPServer(("127.0.0.1", 0), _Trickle)
+ server.stop = threading.Event()
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ monkeypatch.setattr(http, "TOTAL_DEADLINE_S", 0.5, raising=False)
+ yield f"http://127.0.0.1:{server.server_port}"
+ server.stop.set()
+ server.shutdown()
+ server.server_close()
+
+
+def test_endpoint_models_probe_on_a_trickling_server_returns_within_the_deadline(trickling_endpoint, monkeypatch):
+ monkeypatch.setattr(mm, "is_local_endpoint", lambda _url: False) # remote shape: /models probes only
+ started = time.monotonic()
+ assert mm.fetch_endpoint_model_metadata(trickling_endpoint + "/v1", force_refresh=True) == {}
+ # Two candidates (/v1 and bare), each capped: well under the ~8 s the body takes to arrive.
+ assert time.monotonic() - started < 3.0
diff --git a/tests/agent/test_models_dev_fetch_deadline.py b/tests/agent/test_models_dev_fetch_deadline.py
index 525729bb006..1afb1af9cb8 100644
--- a/tests/agent/test_models_dev_fetch_deadline.py
+++ b/tests/agent/test_models_dev_fetch_deadline.py
@@ -4,7 +4,6 @@ A registry that trickles bytes slower than the per-read timeout never trips it,
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
@@ -13,9 +12,6 @@ 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
@@ -62,10 +58,3 @@ def test_cold_fetch_from_a_trickling_registry_returns_within_the_deadline(trickl
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