fix(web): cap web_extract provider dispatch with a wall-clock timeout (salvage #57180)

A provider whose backend keeps the response open without finishing (hanging
HTTP server, stuck SDK call) stalled the web_extract tool call — and with a
sync provider, the borrowed thread — indefinitely. The dispatch in
tools/web_tools_extract._dispatch_extract now runs under asyncio.wait_for with
web.extract_timeout (config.yaml, default 120s; 0 disables). On timeout the
tool returns structured per-URL error entries, and the one-shot keyless rescue
still gets its chance when eligible.

Salvaged from PR #57180 by @liuhao1024 (base predated the web_tools
decomposition; re-applied at the _dispatch_extract seam, env-var timeout
replaced with the web.* config section per the .env-is-for-secrets rule, and
the timeout path made rescue-aware).

Inspired by Claude Code 2.1.268: "Fixed WebFetch hanging indefinitely on a
server that keeps the response open without finishing; a fetch now fails
after 300 seconds."

Fixes #57155

Co-authored-by: liuhao1024 <sunsky.lau@gmail.com>
This commit is contained in:
liuhao1024
2026-09-11 17:28:12 -07:00
committed by Teknium
parent f41b2c615d
commit 0e13fa98ec
3 changed files with 89 additions and 4 deletions
+56
View File
@@ -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)
@pytest.mark.parametrize("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"
+31 -4
View File
@@ -18,6 +18,7 @@ from tools.web_tools_rescue import _rescue_eligible, _rescue_extract
logger = 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 inspect
from 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 rescue
if not _rescue_eligible(provider):
raise
@@ -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 way
If 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).