The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(web): cap web_extract provider dispatch with a wall-clock timeout (salvage #57180)
liuhao10240e13fa98ecd0
diff --git a/tests/tools/test_web_extract_timeout.py b/tests/tools/test_web_extract_timeout.pynew file mode 100644index 00000000000..fc3948af0e6--- /dev/null+++ b/tests/tools/test_web_extract_timeout.py@@ -0,0 +1,56 @@+"""web_extract provider dispatch must be wall-clock bounded (#57155, salvage #57180).++A backend that keeps the response open without finishing (hanging HTTP server,+stuck SDK) must produce per-URL timeout errors instead of stalling the tool+call — and the event loop — indefinitely.+"""+from __future__ import annotations++import asyncio++import pytest++from tools import web_tools_extract as wte+++class _HangingAsyncProvider:+ name = "hanging-async"++ async def extract(self, urls, format=None):+ await asyncio.sleep(9999)+++class _HangingSyncProvider:+ name = "hanging-sync"++ def extract(self, urls, format=None):+ import time++ # Longer than the patched 0.2s cap, short enough that asyncio.run's+ # executor-join at loop shutdown doesn't hang the test.+ time.sleep(2)++[email protected]("provider", [_HangingAsyncProvider(), _HangingSyncProvider()],+ ids=["async", "sync-to-thread"])+def test_hanging_provider_returns_per_url_timeout_errors(monkeypatch, provider):+ monkeypatch.setattr(wte, "_extract_timeout_seconds", lambda: 0.2)+ monkeypatch.setattr(wte, "_rescue_eligible", lambda p: False)+ urls = ["https://example.com/a", "https://example.com/b"]+ results = asyncio.run(wte._dispatch_extract(provider, urls, None))+ assert [r["url"] for r in results] == urls+ for r in results:+ assert "timed out" in r["error"].lower()+ assert provider.name in r["error"]+++def test_timeout_zero_disables_the_cap(monkeypatch):+ class _FastProvider:+ name = "fast"++ async def extract(self, urls, format=None):+ return [{"url": u, "content": "ok"} for u in urls]++ monkeypatch.setattr(wte, "_extract_timeout_seconds", lambda: 0.0)+ results = asyncio.run(wte._dispatch_extract(_FastProvider(), ["https://example.com/x"], None))+ assert results[0]["content"] == "ok"diff --git a/tools/web_tools_extract.py b/tools/web_tools_extract.pyindex 9f4d5bfad3f..e4afc8b75c9 100644--- a/tools/web_tools_extract.py+++ b/tools/web_tools_extract.py@@ -18,6 +18,7 @@ from tools.web_tools_rescue import _rescue_eligible, _rescue_extractlogger = logging.getLogger("tools.web_tools")_NO_RESULT_ERROR = "Extract backend returned no result for this URL"+_DEFAULT_EXTRACT_TIMEOUT_S = 120.0_EXTRACT_BACKENDS_HINT = "firecrawl, tavily, keenable, exa, or parallel."_INVALID_ITEM_ERROR = ("Invalid URL item at index {}: expected a URL string or an object with a string 'url' or 'href' field"@@ -132,19 +133,45 @@ def _resolve_extract_provider(backend: str):return provider, None+def _extract_timeout_seconds() -> float:+ """Wall-clock cap for one provider ``extract()`` dispatch (``web.extract_timeout``, default 120s).++ A hanging backend (server keeps the response open without finishing) otherwise stalls the+ tool call indefinitely. 0 or a negative value disables the cap.+ """+ from tools.web_tools import _load_web_config+ try:+ return float(_load_web_config().get("extract_timeout", _DEFAULT_EXTRACT_TIMEOUT_S))+ except (TypeError, ValueError):+ return _DEFAULT_EXTRACT_TIMEOUT_S++async def _dispatch_extract(provider, fetch_urls: List[str], format: Optional[str]) -> List[dict]:"""Call ``provider.extract`` (async or sync-in-thread), with one-shot keyless rescue.- Rescue fires on a raised exception or when the WHOLE batch failed (backend outage, not per-page- problems). Rescued batches are never cached.+ Rescue fires on a raised exception — including a dispatch timeout — or when the WHOLE batch+ failed (backend outage, not per-page problems). Rescued batches are never cached."""import inspectfrom tools.web_result_cache import extract_cache_put+ timeout = _extract_timeout_seconds()try:if inspect.iscoroutinefunction(provider.extract):- results = await provider.extract(fetch_urls, format=format)+ coro = provider.extract(fetch_urls, format=format)else: # sync extract() runs in a thread so network I/O never blocks the loop- results = await asyncio.to_thread(provider.extract, fetch_urls, format=format)+ coro = asyncio.to_thread(provider.extract, fetch_urls, format=format)+ if timeout > 0:+ results = await asyncio.wait_for(coro, timeout=timeout)+ else:+ results = await coro+ except asyncio.TimeoutError as exc: # hanging backend — bounded, never a stalled tool call+ logger.warning("web_extract provider '%s' timed out after %.0fs for %d URL(s)",+ provider.name, timeout, len(fetch_urls))+ failed = [_result_entry(u, f"Extract timed out after {timeout:.0f}s via {provider.name}")+ for u in fetch_urls]+ if not _rescue_eligible(provider):+ return failed+ return await asyncio.to_thread(_rescue_extract, provider.name, fetch_urls, failed)except Exception as exc: # noqa: BLE001 — candidate for rescueif not _rescue_eligible(provider):raisediff --git a/website/docs/user-guide/features/web-search.md b/website/docs/user-guide/features/web-search.mdindex bcd6b34255a..19618423e9b 100644--- a/website/docs/user-guide/features/web-search.md+++ b/website/docs/user-guide/features/web-search.md@@ -57,6 +57,8 @@ Backends return raw page markdown, which can be huge (forum threads, docs sites,The per-page budget is configurable via `web.extract_char_limit` in `config.yaml` (default `15000`, clamped to 2 000–500 000), and the agent can raise it per-call with the tool's `char_limit` argument.+Each provider dispatch is also bounded by a wall-clock timeout (`web.extract_timeout` in `config.yaml`, default `120` seconds; `0` disables it). A backend that keeps the response open without finishing returns per-URL timeout errors instead of stalling the tool call indefinitely.+### When truncation gets in the wayIf you specifically need the live DOM rather than extracted markdown — for example, a JS-heavy page where extraction returns little content — use `browser_navigate` + `browser_snapshot` instead. The browser tool returns the live accessibility tree (subject to its own snapshot cap on huge pages).