Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: give web search engines a connect timeout so a blocked network fails fast (#15143) (#15161)
Debojyoti Banerjeed53a09012293
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 254f9f57b23..2349bb2a0c5 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -145,6 +145,13 @@ _DDGS_RESET_MARKERS = ("forcibly closed", # Windows WSAECONNRESET (10054))_DDGS_HTTP1_RETRY_LOCK = threading.Lock()+# Connect cap per engine: a blocked tier 1 otherwise spent the whole tool budget, so tier 2 and the+# Wikipedia fallback never ran (#15143). A connected engine keeps the full budget to answer.+_SEARCH_CONNECT_TIMEOUT = 10+# primp's and httpx's wording for a connect timeout; a read timeout is "operation timed out".+_DDGS_CONNECT_TIMEOUT_MARKERS = ("connection timed out", "connecttimeout")+_DDGS_CONNECT_TIMEOUT_LOCK = threading.Lock()+_DDGS_PENDING = threading.local()# Tier 2 is only asked when tier 1 found nothing. Naming is the only way ddgs reaches an engine, so# an engine in neither tier (yandex, bing, the mullvad_* mirrors) is never contacted.@@ -18226,6 +18233,15 @@ def _search_failure_message(exc: BaseException, timeout: int) -> str:"Search failed: the search engines are rate limiting this machine. Wait a minute "'before searching again, or read a known page directly with {"url": "<URL>"}.')+ if name == "TimeoutException" and any(+ marker in str(exc).lower() for marker in _DDGS_CONNECT_TIMEOUT_MARKERS+ ):+ return (+ "Search failed: the search engines could not be reached within "+ f"{_search_connect_timeout(timeout):g}s, so they may be blocked on this network. "+ "Start Studio with HTTPS_PROXY set to a working proxy, or read a known page "+ 'directly with {"url": "<URL>"}.'+ )if name == "TimeoutException":budget = f" within {timeout}s" if timeout else ""return f"Search failed: the search engines did not respond{budget}."@@ -18235,6 +18251,111 @@ def _search_failure_message(exc: BaseException, timeout: int) -> str:return f"Search failed: {exc}"+def _search_connect_timeout(timeout) -> float:+ return min(timeout, _SEARCH_CONNECT_TIMEOUT) if timeout else _SEARCH_CONNECT_TIMEOUT+++class _PrimpWithConnectTimeout:+ """``primp`` as ddgs's ``http_client`` sees it, with a connect timeout on every ``Client``."""++ _unsloth_connect_timeout = True++ def __init__(self, module):+ self._module = module++ def __getattr__(self, name):+ return getattr(self._module, name)++ def Client(self, *args, **kwargs):+ connect = _search_connect_timeout(kwargs.get("timeout"))+ try:+ return self._module.Client(*args, **{"connect_timeout": connect, **kwargs})+ except TypeError: # primp 0.15 (ddgs 9.8.0) has no connect_timeout+ return self._module.Client(*args, **kwargs)+++def _ddgs_wait_recording(+ fs,+ timeout = None,+ return_when = "ALL_COMPLETED",+):+ """ddgs's batch ``wait``, unchanged, remembering what was still running after the last batch."""+ import concurrent.futures++ done, not_done = concurrent.futures.wait(fs, timeout = timeout, return_when = return_when)+ _DDGS_PENDING.futures = list(not_done)+ return done, not_done+++def _ddgs_text(client, query, max_results, backend) -> list:+ """``client.text`` plus answers ddgs dropped: its batch wait returns at the first failure and+ never reads engines still running after the last batch, so an engine failing its connect cap+ discarded a slower engine's results (#15143). Its executor has joined them by return."""+ _DDGS_PENDING.futures = []+ try:+ results, error = client.text(query, max_results = max_results, backend = backend), None+ except Exception as exc: # noqa: BLE001 - re-raised below unless a dropped engine answered+ results, error = [], exc+ pending, _DDGS_PENDING.futures = getattr(_DDGS_PENDING, "futures", []), []+ late = []+ if len(results) < max_results:+ for future in pending:+ if future.done() and not future.cancelled() and future.exception() is None:+ late.extend(future.result() or [])+ if late:+ from ddgs.results import ResultsAggregator++ seen = {r.get("href") for r in results if isinstance(r, dict)}+ aggregator = ResultsAggregator({"href", "image", "url", "embed_url"})+ aggregator.extend(late)+ results = list(results) + [+ r for r in aggregator.extract_dicts() if r.get("href") not in seen+ ]+ if not results and error is not None:+ raise error+ return results[:max_results]+++def _install_ddgs_connect_timeout() -> None:+ """Cap how long a ddgs engine may take to connect (#15143), leaving the read on the caller's+ timeout so a slow engine that did connect can still answer late. Applies once; never raises."""+ try:+ import concurrent.futures++ from ddgs import ddgs as ddgs_module, http_client+ with _DDGS_CONNECT_TIMEOUT_LOCK:+ if not getattr(http_client.primp, "_unsloth_connect_timeout", False):+ http_client.primp = _PrimpWithConnectTimeout(http_client.primp)+ if getattr(ddgs_module, "wait", None) is concurrent.futures.wait:+ ddgs_module.wait = _ddgs_wait_recording+ try:+ from ddgs import http_client2+ except ImportError:+ return+ cls = getattr(http_client2, "HttpClient2", None)+ if cls is None or cls.__dict__.get("_unsloth_connect_timeout"):+ return+ orig_init = cls.__init__++ @functools.wraps(orig_init)+ def __init__(self, *args, **kwargs):+ orig_init(self, *args, **kwargs)+ import httpx++ current = self.client.timeout+ self.client.timeout = httpx.Timeout(+ connect = _search_connect_timeout(current.connect),+ read = current.read,+ write = current.write,+ pool = current.pool,+ )++ cls.__init__ = __init__+ cls._unsloth_connect_timeout = True+ except Exception: # noqa: BLE001 - a hardening layer, never a reason to fail a search+ logger.debug("ddgs connect timeout not installed", exc_info = True)++def _resolve_engine_tiers(text_engines) -> list:"""``_SEARCH_ENGINE_TIERS`` reduced to the engines this ddgs actually has, in tier order.@@ -18561,6 +18682,7 @@ def _web_search(text_engines = ENGINES.get("text") or {}_install_yahoo_layout_parser(text_engines)_install_ddgs_http1_retry()+ _install_ddgs_connect_timeout()engine_tiers = _resolve_engine_tiers(text_engines)if not engine_tiers:raise RuntimeError("no approved search engine is available.")@@ -18577,7 +18699,7 @@ def _web_search(breakclient = DDGS(timeout = remaining)try:- candidates = client.text(effective_query, max_results = wanted, backend = backend)+ candidates = _ddgs_text(client, effective_query, wanted, backend)results = _usable_search_results(candidates, website_policy)rejected_results = rejected_results or bool(candidates and not results)except Exception as exc: # noqa: BLE001 - try the next tier before classifying the failure@@ -18741,6 +18863,7 @@ def _image_search(except Exception as e:return _search_failure_message(e, timeout)_install_ddgs_http1_retry()+ _install_ddgs_connect_timeout()if not callable(getattr(DDGS, "images", None)):return "Image search is unavailable in this install."diff --git a/studio/backend/tests/test_web_search_connect_timeout.py b/studio/backend/tests/test_web_search_connect_timeout.pynew file mode 100644index 00000000000..794af965d03--- /dev/null+++ b/studio/backend/tests/test_web_search_connect_timeout.py@@ -0,0 +1,154 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""ddgs engines get a short connect timeout and keep the whole budget to answer (unslothai/unsloth#15143)."""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from core.inference import tools+++def fresh_install(monkeypatch):+ """Undo the install after each test, so no test sees another's wrapped clients."""+ from ddgs import ddgs as ddgs_module, http_client, http_client2++ monkeypatch.setattr(ddgs_module, "wait", ddgs_module.wait)+ monkeypatch.setattr(http_client, "primp", http_client.primp)+ cls = http_client2.HttpClient2+ monkeypatch.setattr(cls, "__init__", cls.__init__)+ monkeypatch.setattr(cls, "_unsloth_connect_timeout", False, raising = False)+ return http_client, http_client2++[email protected](("timeout", "connect"), [(300, 10), (3, 3), (None, 10)])+def test_primp_clients_connect_fast_and_keep_the_read_budget(fresh_install, timeout, connect):+ http_client, _ = fresh_install+ tools._install_ddgs_connect_timeout()++ client = http_client.HttpClient(timeout = timeout).client++ if not hasattr(client, "connect_timeout"):+ pytest.skip("installed primp has no connect_timeout")+ assert client.connect_timeout == connect+ assert client.timeout == timeout++[email protected](("timeout", "connect"), [(300, 10), (3, 3), (None, 10)])+def test_httpx_clients_connect_fast_and_keep_the_read_budget(fresh_install, timeout, connect):+ _, http_client2 = fresh_install+ tools._install_ddgs_connect_timeout()++ budget = http_client2.HttpClient2(timeout = timeout).client.timeout++ assert budget.connect == connect+ assert (budget.read, budget.write, budget.pool) == (timeout, timeout, timeout)+++def test_installing_twice_wraps_once(fresh_install):+ http_client, http_client2 = fresh_install+ tools._install_ddgs_connect_timeout()+ primp, init = http_client.primp, http_client2.HttpClient2.__init__++ tools._install_ddgs_connect_timeout()++ assert http_client.primp is primp+ assert http_client2.HttpClient2.__init__ is init+++def test_a_primp_without_connect_timeout_still_builds_its_client():+ """primp 0.15 (the ddgs 9.8.0 pin) takes no connect_timeout; the search must still run."""+ built = []++ def Client(**kwargs):+ if "connect_timeout" in kwargs:+ raise TypeError("'connect_timeout' is an invalid keyword argument")+ built.append(kwargs)+ return "client"++ primp = tools._PrimpWithConnectTimeout(SimpleNamespace(Client = Client, TimeoutError = OSError))++ assert primp.Client(timeout = 300) == "client"+ assert built == [{"timeout": 300}]+ assert primp.TimeoutError is OSError+++def test_an_unreachable_engine_says_it_may_be_blocked():+ from ddgs.exceptions import TimeoutException++ exc = TimeoutException(+ "error sending request for url (https://html.duckduckgo.com/html/) > connection timed out"+ )++ result = tools._search_failure_message(exc, 300)++ assert result.startswith("Search failed: the search engines could not be reached within 10s")+ assert "HTTPS_PROXY" in result+ assert '{"url": "<URL>"}' in result+++def test_a_connected_engine_that_answers_too_late_keeps_the_budget_message():+ from ddgs.exceptions import TimeoutException+ exc = TimeoutException("error sending request for url (https://x/) > operation timed out")++ assert (+ tools._search_failure_message(exc, 300)+ == "Search failed: the search engines did not respond within 300s."+ )+++def test_an_engine_failing_fast_does_not_drop_a_slower_engines_answer(fresh_install, monkeypatch):+ """ddgs's batch wait returned on the first failure and dropped the still running engine, so a+ blocked engine hitting its connect cap threw away a slow engine's answer."""+ import time++ from ddgs.ddgs import DDGS+ from ddgs.engines import ENGINES+ from ddgs.exceptions import DDGSException+ from ddgs.results import TextResult++ if callable(getattr(DDGS, "_get_network_client", None)):+ monkeypatch.setattr(DDGS, "_get_network_client", lambda self: None)++ def slow(engine, query, **kwargs):+ time.sleep(0.5)+ return [TextResult(title = "slow answer", href = "https://slow.example/", body = "late")]++ def blocked(engine, query, **kwargs):+ raise DDGSException("connection timed out")++ for name, behaviour in (("wikipedia", slow), ("brave", blocked)):+ cls = ENGINES["text"][name]+ monkeypatch.setattr(cls, "__init__", lambda self, *a, **k: None, raising = False)+ monkeypatch.setattr(cls, "search", behaviour)+ monkeypatch.setattr(tools, "_SEARCH_ENGINE_TIERS", (("wikipedia", "brave"),))+ monkeypatch.setattr(tools, "_wikipedia_search", lambda *args: [])++ result = tools._web_search("anything", max_results = 1, timeout = 30)++ assert "Title: slow answer" in result+++def test_ddgs_still_moves_on_at_the_first_failure(fresh_install):+ """The late-answer fix only records what was pending; ddgs keeps refilling a failed slot at once."""+ import threading+ from concurrent.futures import ThreadPoolExecutor++ from ddgs import ddgs as ddgs_module++ tools._install_ddgs_connect_timeout()+ release = threading.Event()++ def fail():+ raise RuntimeError("blocked")++ with ThreadPoolExecutor(max_workers = 2) as pool:+ slow, failed = pool.submit(release.wait, 5), pool.submit(fail)+ done, not_done = ddgs_module.wait([slow, failed], timeout = 5, return_when = "FIRST_EXCEPTION")+ release.set()++ assert failed in done and slow in not_done