Skip to content

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.

fix(studio): run built-in text search as a tiered engine allowlist (#11242)

alkinun2bc7b5d4c5e9
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 244eb02a63f..b09de7c637e 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -100,6 +100,13 @@ EMPTY_SEARCH_RESULTS = (
# ddgs signals an empty sweep by raising rather than returning [].
_DDGS_EMPTY_SWEEP = "No results found"
+# 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.
+_SEARCH_ENGINE_TIERS = (
+ ("wikipedia", "brave", "duckduckgo", "mojeek", "startpage"),
+ ("grokipedia", "google", "yahoo"),
+)
+
# Import at module level so the preexec_fn closure triggers no imports in the forked child (which can deadlock
# multi-threaded servers).
_libc = None
@@ -15185,6 +15192,27 @@ def _search_failure_message(exc: BaseException, timeout: int) -> str:
return f"Search failed: {exc}"
+def _resolve_engine_tiers(text_engines) -> list:
+ """``_SEARCH_ENGINE_TIERS`` reduced to the engines this ddgs actually has, in tier order.
+
+ Naming an engine the registry lacks is not an error: ddgs 9.8.0 raises ``KeyError`` on the first
+ unknown name and silently re-runs the request as ``auto``, the Yandex fan-out this exists to
+ prevent, and tier 1 trips it there because 9.8.0 ships no ``startpage``. An empty tier is dropped
+ for the same reason.
+ """
+ engines = text_engines or {}
+ resolved = []
+ for tier in _SEARCH_ENGINE_TIERS:
+ live = [
+ name
+ for name in tier
+ if engines.get(name) is not None and not getattr(engines.get(name), "disabled", False)
+ ]
+ if live:
+ resolved.append(",".join(live))
+ return resolved
+
+
def _image_search_or_none(subjects: list, timeout, cancel_event, website_policy) -> "str | None":
"""``_image_search`` that reports a failure as None instead of raising. Every caller sits inside
``_web_search``'s own ``except``, which would turn a raise into Search failed: ... and throw
@@ -15233,9 +15261,8 @@ def _web_search(
include_images: bool = False,
image_queries = None,
) -> str:
- """Search the web and return formatted results. ddgs fans the query out across its search
- engines, so a single engine refusing is already covered. If ``url`` is provided, fetches that
- page directly instead of searching. ``include_images`` adds image results registered
+ """Search the web through the approved engine tiers and return formatted results. If ``url`` is provided,
+ fetches that page directly instead of searching. ``include_images`` adds image results registered
server-side and offered to the model as ``[[img:<id>]]`` tokens, with a frontend-only
envelope appended: one picture per ``image_queries`` subject when the model named them, else
a handful for the query. ``image_queries`` alone (no query) is a pure image lookup."""
@@ -15268,9 +15295,14 @@ def _web_search(
return "Search cancelled."
try:
from ddgs import DDGS
+ from ddgs.engines import ENGINES
from .web_access_policy import check_url_access, scope_search_query
+ engine_tiers = _resolve_engine_tiers(ENGINES.get("text", {}))
+ if not engine_tiers:
+ return "Search failed: no approved search engine is available."
+
effective_query = scope_search_query(query, website_policy)
# The policy filters below, so ask for a deeper pool when one actually restricts: a page whose top hits are
# all disallowed otherwise yields nothing even when valid results rank just under them. Test the domain lists,
@@ -15279,8 +15311,30 @@ def _web_search(
(website_policy or {}).get(key) for key in ("allowedDomains", "blockedDomains")
)
wanted = max_results * _POLICY_OVERFETCH if restricted else max_results
+ # ddgs applies `timeout` per client, as both the engine HTTP timeout and its fan-out wait, so
+ # a client per tier would restart the budget and a 7s web_search could block ~14s.
+ deadline = time.monotonic() + timeout if timeout else None
client = DDGS(timeout = timeout)
- results = client.text(effective_query, max_results = wanted)
+ # ddgs signals an empty sweep by RAISING, so a tier's exception means try the next tier; the
+ # last is re-raised for _search_failure_message to classify as a single-tier failure would be.
+ results, last_error = [], None
+ for backend in engine_tiers:
+ if cancel_event is not None and cancel_event.is_set():
+ return "Search cancelled."
+ if deadline is not None:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ break
+ client = DDGS(timeout = remaining)
+ try:
+ results = client.text(effective_query, max_results = wanted, backend = backend)
+ except Exception as exc: # noqa: BLE001 - re-raised below when no tier produced anything
+ last_error = exc
+ continue
+ if results:
+ break
+ if not results and last_error is not None:
+ raise last_error
if cancel_event is not None and cancel_event.is_set():
return "Search cancelled."
if not results:
diff --git a/studio/backend/tests/test_search_images.py b/studio/backend/tests/test_search_images.py
index da19656fb9b..b6f0136e765 100644
--- a/studio/backend/tests/test_search_images.py
+++ b/studio/backend/tests/test_search_images.py
@@ -10,7 +10,6 @@ from __future__ import annotations
import asyncio
import io
import json
-import sys
import threading
from email.message import Message
from pathlib import Path
@@ -149,6 +148,7 @@ def test_web_search_appends_tokens_and_envelope_when_images_are_on(monkeypatch):
self,
query,
max_results = 5,
+ **kwargs,
):
return [{"title": "AKC", "href": "https://akc.org/x", "body": "Breeds"}]
@@ -161,7 +161,7 @@ def test_web_search_appends_tokens_and_envelope_when_images_are_on(monkeypatch):
calls["images"] = (query, max_results, kwargs)
return RAW_IMAGES
- monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = FakeDDGS))
+ monkeypatch.setattr("ddgs.DDGS", FakeDDGS)
plain = tools._web_search("dog breeds")
assert "[[img:" not in plain
@@ -194,6 +194,7 @@ def test_web_search_survives_an_image_engine_failure(monkeypatch):
self,
query,
max_results = 5,
+ **kwargs,
):
return [{"title": "AKC", "href": "https://akc.org/x", "body": "Breeds"}]
@@ -205,7 +206,7 @@ def test_web_search_survives_an_image_engine_failure(monkeypatch):
):
raise RuntimeError("engine down")
- monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = FakeDDGS))
+ monkeypatch.setattr("ddgs.DDGS", FakeDDGS)
result = tools._web_search("dog breeds", include_images = True)
assert "Title: AKC" in result
assert search_images.SEARCH_IMAGES_SENTINEL not in result
@@ -220,10 +221,11 @@ def test_web_search_without_an_images_method_is_unchanged(monkeypatch):
self,
query,
max_results = 5,
+ **kwargs,
):
return [{"title": "AKC", "href": "https://akc.org/x", "body": "Breeds"}]
- monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = FakeDDGS))
+ monkeypatch.setattr("ddgs.DDGS", FakeDDGS)
assert tools._web_search("q", include_images = True) == tools._web_search("q")
@@ -280,7 +282,7 @@ class _SubjectDDGS:
def test_image_search_returns_tokens_grouped_by_subject(monkeypatch):
_SubjectDDGS.calls = []
- monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = _SubjectDDGS))
+ monkeypatch.setattr("ddgs.DDGS", _SubjectDDGS)
result = tools._image_search(
["German Shepherd", " german shepherd ", "Labrador", "Nothing Here", "Broken"],
@@ -307,7 +309,7 @@ def test_image_search_returns_tokens_grouped_by_subject(monkeypatch):
def test_image_queries_alone_are_a_pure_image_lookup(monkeypatch):
- monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = _SubjectDDGS))
+ monkeypatch.setattr("ddgs.DDGS", _SubjectDDGS)
off = tools.execute_tool("web_search", {"image_queries": ["Pug"]})
assert off == tools.IMAGE_SEARCH_DISABLED
on = tools.execute_tool("web_search", {"image_queries": ["Pug"]}, search_images = True)
@@ -326,11 +328,12 @@ def test_web_search_with_image_queries_gives_one_picture_per_subject(monkeypatch
self,
query,
max_results = 5,
+ **kwargs,
):
return [{"title": "AKC", "href": "https://akc.org/x", "body": "Breeds"}]
_SubjectDDGS.calls = []
- monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = Both))
+ monkeypatch.setattr("ddgs.DDGS", Both)
result = tools._web_search(
"top dog breeds", include_images = True, image_queries = ["Pug", "Beagle"]
)
@@ -353,6 +356,7 @@ def test_named_subjects_survive_a_text_sweep_that_finds_nothing(monkeypatch):
self,
query,
max_results = 5,
+ **kwargs,
):
return []
@@ -365,6 +369,7 @@ def test_named_subjects_survive_a_text_sweep_that_finds_nothing(monkeypatch):
self,
query,
max_results = 5,
+ **kwargs,
):
raise DDGSException("No results found for the given query.")
@@ -373,12 +378,13 @@ def test_named_subjects_survive_a_text_sweep_that_finds_nothing(monkeypatch):
self,
query,
max_results = 5,
+ **kwargs,
):
return [{"title": "X", "href": "https://blocked.example/x", "body": "b"}]
for engine in (NoText, RaisesEmpty):
_SubjectDDGS.calls = []
- monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = engine))
+ monkeypatch.setattr("ddgs.DDGS", engine)
result = tools._web_search("top dog breeds", include_images = True, image_queries = ["Pug"])
assert tools.EMPTY_SEARCH_RESULTS[0] in result
assert "Pug:\n- [[img:" in result
@@ -394,7 +400,7 @@ def test_named_subjects_survive_a_text_sweep_that_finds_nothing(monkeypatch):
# Every hit filtered out by the website policy is the same empty answer.
_SubjectDDGS.calls = []
- monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = OnlyBlocked))
+ monkeypatch.setattr("ddgs.DDGS", OnlyBlocked)
scoped = tools._web_search(
"top dog breeds",
include_images = True,
@@ -413,11 +419,12 @@ def test_a_genuine_search_failure_carries_no_pictures(monkeypatch):
self,
query,
max_results = 5,
+ **kwargs,
):
raise RuntimeError("upstream exploded")
_SubjectDDGS.calls = []
- monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = Boom))
+ monkeypatch.setattr("ddgs.DDGS", Boom)
result = tools._web_search("top dog breeds", include_images = True, image_queries = ["Pug"])
# Pictures under an error would read as a partial answer.
assert result.startswith("Search failed:") and "[[img:" not in result
@@ -481,7 +488,7 @@ def test_clear_all_chats_invalidates_an_image_lookup_already_in_a_thread(monkeyp
release.wait(2)
return RAW_IMAGES
- monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = BlockingDDGS))
+ monkeypatch.setattr("ddgs.DDGS", BlockingDDGS)
async def race_clear_against_lookup():
task = asyncio.create_task(asyncio.to_thread(tools._image_search, ["Pug"], 20))
@@ -613,7 +620,7 @@ def test_web_search_tool_with_images_adds_the_field_without_touching_the_base():
def test_image_search_caps_the_subject_count(monkeypatch):
_SubjectDDGS.calls = []
- monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = _SubjectDDGS))
+ monkeypatch.setattr("ddgs.DDGS", _SubjectDDGS)
tools._image_search([f"Breed {i}" for i in range(9)])
assert len(_SubjectDDGS.calls) == tools.IMAGE_SEARCH_MAX_QUERIES
@@ -864,7 +871,7 @@ def test_route_serves_registered_thumbnails_only(client, monkeypatch):
def test_lookup_route_returns_subject_images_only_when_enabled(client, monkeypatch):
- monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = _SubjectDDGS))
+ monkeypatch.setattr("ddgs.DDGS", _SubjectDDGS)
monkeypatch.setattr(search_images, "search_images_enabled", lambda: False)
assert (
client.post("/api/inference/search-images/lookup", json = {"subjects": ["Pug"]}).status_code
@@ -1016,6 +1023,7 @@ def _fake_ddgs_with_text(monkeypatch):
self,
query,
max_results = 5,
+ **kwargs,
):
return [{"title": "AKC", "href": "https://akc.org/x", "body": "Breeds"}]
@@ -1027,7 +1035,7 @@ def _fake_ddgs_with_text(monkeypatch):
):
return RAW_IMAGES
- monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = FakeDDGS))
+ monkeypatch.setattr("ddgs.DDGS", FakeDDGS)
def test_a_failing_subject_lookup_does_not_discard_the_text_results(monkeypatch):
diff --git a/studio/backend/tests/test_secure_tools_execute.py b/studio/backend/tests/test_secure_tools_execute.py
index d8c76091e42..28cb040a5f0 100644
--- a/studio/backend/tests/test_secure_tools_execute.py
+++ b/studio/backend/tests/test_secure_tools_execute.py
@@ -172,6 +172,7 @@ def test_web_search_tool_runs_with_mocked_fetch(monkeypatch):
self,
query,
max_results = 5,
+ **kwargs,
):
return [
{
diff --git a/studio/backend/tests/test_web_access_policy.py b/studio/backend/tests/test_web_access_policy.py
index aaba9d05875..e51f32f19da 100644
--- a/studio/backend/tests/test_web_access_policy.py
+++ b/studio/backend/tests/test_web_access_policy.py
@@ -1,10 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-import sys
import urllib.error
from email.message import Message
-from types import SimpleNamespace
import pytest
@@ -132,6 +130,7 @@ def test_web_search_filters_results_before_model_exposure(monkeypatch):
self,
query,
max_results = 5,
+ **kwargs,
):
queries.append((query, max_results))
return [
@@ -140,7 +139,7 @@ def test_web_search_filters_results_before_model_exposure(monkeypatch):
{"title": "Deceptive", "href": "https://arxiv.org.evil.test", "body": "Blocked"},
]
- monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = FakeDDGS))
+ monkeypatch.setattr("ddgs.DDGS", FakeDDGS)
result = tools._web_search("latest paper", website_policy = ARXIV_ONLY)
# A policy filters after the search, so a deeper candidate pool is requested.
@@ -167,10 +166,11 @@ def test_web_search_refills_past_disallowed_results(monkeypatch):
self,
query,
max_results = 5,
+ **kwargs,
):
return blocked_then_allowed[:max_results]
- monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = FakeDDGS))
+ monkeypatch.setattr("ddgs.DDGS", FakeDDGS)
result = tools._web_search("q", website_policy = {"blockedDomains": ["example.com"]})
assert "arxiv.org/abs/0" in result
@@ -190,11 +190,12 @@ def test_web_search_without_a_policy_does_not_overfetch(monkeypatch):
self,
query,
max_results = 5,
+ **kwargs,
):
queries.append((query, max_results))
return [{"title": "T", "href": "https://a.example/1", "body": "B"}]
- monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = FakeDDGS))
+ monkeypatch.setattr("ddgs.DDGS", FakeDDGS)
tools._web_search("q", website_policy = None)
# A run always stores a normalized policy, so the unrestricted case is an object with empty
# lists, not None. Neither may pay the deeper-pool latency.
@@ -231,6 +232,7 @@ def test_web_search_flattens_source_framing_in_untrusted_metadata(monkeypatch):
self,
query,
max_results = 5,
+ **kwargs,
):
return [
{
@@ -243,7 +245,7 @@ def test_web_search_flattens_source_framing_in_untrusted_metadata(monkeypatch):
}
]
- monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = FakeDDGS))
+ monkeypatch.setattr("ddgs.DDGS", FakeDDGS)
result = tools._web_search("paper", website_policy = ARXIV_ONLY)
assert result.count("\nURL:") == 1
assert "URL: https://arxiv.org/abs/real" in result
@@ -296,10 +298,11 @@ def _search_with_raising_ddgs(monkeypatch, exc: Exception) -> str:
self,
query,
max_results = 5,
+ **kwargs,
):
raise exc
- monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = FakeDDGS))
+ monkeypatch.setattr("ddgs.DDGS", FakeDDGS)
return tools._web_search("q", timeout = 7)
diff --git a/studio/backend/tests/test_web_search_tiers.py b/studio/backend/tests/test_web_search_tiers.py
new file mode 100644
index 00000000000..71e61fa241d
--- /dev/null
+++ b/studio/backend/tests/test_web_search_tiers.py
@@ -0,0 +1,223 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Built-in text search runs an approved allowlist, tier by tier, and never reaches Yandex.
+
+Drives the real DDGS engine selector through ``execute_tool``; only each engine's own ``search`` is
+replaced, so the tier strings really are resolved by ddgs and a fan-out cannot hide.
+"""
+
+import time
+
+import pytest
+
+from ddgs.engines import ENGINES
+from ddgs.exceptions import DDGSException
+from ddgs.results import TextResult
+
+from core.inference import tools
+
+TIER1 = ("wikipedia", "brave", "duckduckgo", "mojeek", "startpage")
+TIER2 = ("grokipedia", "google", "yahoo")
+
+
+class _Recorder:
+ """Records every text engine ddgs decides to run, and installs their behaviour."""
+
+ def __init__(self, monkeypatch):
+ self._monkeypatch = monkeypatch
+ self.calls = []
+
+ def _search_for(self, name, behaviour):
+ def search(engine, query, **kwargs):
+ self.calls.append((name, query))
+ if behaviour == "empty":
+ return []
+ if behaviour == "raise":
+ raise DDGSException(f"{name} refused")
+ return [
+ TextResult(
+ title = f"{name} result",
+ href = f"https://{name}.example/source",
+ body = f"A synthetic result from {name}.",
+ )
+ ]
+
+ return search
+
+ def install(self, behaviour_for):
+ for name, cls in ENGINES["text"].items():
+ # __init__ too: building a real engine reaches ddgs's HTTP client, which on the py<3.10
+ # pin raises `Invalid impersonate: "safari_15.6.1"`, so these selection tests would fail
+ # there for an unrelated reason on the one version whose fallback the resolver prevents.
+ self._monkeypatch.setattr(cls, "__init__", lambda self, *a, **k: None, raising = False)
+ self._monkeypatch.setattr(cls, "search", self._search_for(name, behaviour_for(name)))
+
+ @property
+ def names(self):
+ return [name for name, _query in self.calls]
+
+
+def engine_calls(monkeypatch):
+ from ddgs.ddgs import DDGS
+
+ # 9.14.4 defines _get_network_client; a DHT cache hit would skip the engines entirely.
+ if callable(getattr(DDGS, "_get_network_client", None)):
+ monkeypatch.setattr(DDGS, "_get_network_client", lambda self: None)
+ return _Recorder(monkeypatch)
+
+
+def _names(recorder):
+ return recorder.names
+
+
+def _require_two_tiers():
+ """Skip rather than go red if an upstream release ever leaves fewer than two resolvable tiers.
+ Both pins resolve two: 9.14.4 all three members, 9.8.0 yahoo alone."""
+ resolved = tools._resolve_engine_tiers(ENGINES["text"])
+ if len(resolved) < 2:
+ pytest.skip(f"installed ddgs resolves only {len(resolved)} tier(s): {resolved}")
+
+
+def test_tier_one_answers_alone_and_tier_two_is_never_asked(engine_calls):
+ engine_calls.install(lambda name: "results")
+
+ result = tools.execute_tool("web_search", {"query": "unsloth"})
+
+ assert set(_names(engine_calls)) <= set(TIER1)
+ assert not set(_names(engine_calls)) & set(TIER2)
+ assert "yandex" not in _names(engine_calls)
+ assert "URL: https://" in result
+
+
+def test_tier_two_runs_only_after_tier_one_finds_nothing(engine_calls):
+ _require_two_tiers()
+ engine_calls.install(lambda name: "empty" if name in TIER1 else "results")
+
+ result = tools.execute_tool("web_search", {"query": "unsloth"})
+
+ contacted = _names(engine_calls)
+ assert set(contacted) & set(TIER2), "tier 2 was never reached"
+ assert "yandex" not in contacted
+ assert "URL: https://" in result
+
+
+def test_a_tier_one_refusal_falls_through_to_tier_two(engine_calls):
+ _require_two_tiers()
+ engine_calls.install(lambda name: "raise" if name in TIER1 else "results")
+
+ result = tools.execute_tool("web_search", {"query": "unsloth"})
+
+ assert set(_names(engine_calls)) & set(TIER2)
+ assert "URL: https://" in result
+
+
+def test_every_tier_empty_reports_no_results_and_never_widens(engine_calls):
+ engine_calls.install(lambda name: "empty")
+
+ result = tools.execute_tool("web_search", {"query": "unsloth"})
+
+ assert "yandex" not in _names(engine_calls)
+ assert result == tools.EMPTY_SEARCH_RESULTS[0]
+
+
[email protected]("missing", [("startpage",), ("startpage", "grokipedia", "google")])
+def test_an_engine_absent_from_the_registry_does_not_reopen_auto(
+ monkeypatch, engine_calls, missing
+):
+ """9.8.0 raises KeyError on an unknown name and re-runs as auto; 9.14.4 keeps the valid ones.
+ Either way the query must not reach an engine outside the tiers."""
+ engine_calls.install(lambda name: "results")
+ for name in missing:
+ monkeypatch.delitem(ENGINES["text"], name, raising = False)
+
+ expected = set(tools._resolve_engine_tiers(ENGINES["text"])[0].split(","))
+
+ result = tools.execute_tool("web_search", {"query": "unsloth"})
+
+ contacted = set(_names(engine_calls))
+ assert "yandex" not in contacted
+ # Equality, not a subset: as a subset this passed intermittently on the pre-allowlist code, whose
+ # shuffle sometimes kept the dispatched engines inside the tiers anyway.
+ assert (
+ contacted == expected
+ ), f"expected exactly the resolved tier 1 {expected}, got {contacted}"
+ assert "URL: https://" in result
+
+
+def test_no_approved_engine_available_fails_closed(monkeypatch, engine_calls):
+ engine_calls.install(lambda name: "results")
+ for name in TIER1 + TIER2:
+ monkeypatch.delitem(ENGINES["text"], name, raising = False)
+
+ result = tools.execute_tool("web_search", {"query": "unsloth"})
+
+ assert result == "Search failed: no approved search engine is available."
+ assert _names(engine_calls) == [], "a query left the process with no approved engine"
+
+
+def test_disabled_engines_are_dropped_from_a_tier(monkeypatch, engine_calls):
+ engine_calls.install(lambda name: "results")
+ monkeypatch.setattr(ENGINES["text"]["duckduckgo"], "disabled", True)
+
+ tools.execute_tool("web_search", {"query": "unsloth"})
+
+ contacted = set(_names(engine_calls))
+ assert "duckduckgo" not in contacted
+ # Subset, not just "no yandex": absence of one engine passed 1 run in 10 on the pre-allowlist
+ # code, because its shuffle sometimes filled the result budget before reaching Yandex.
+ assert contacted <= set(TIER1) - {"duckduckgo"}, f"an engine outside tier 1 ran: {contacted}"
+ assert "yandex" not in contacted
+
+
+def test_the_caller_timeout_is_one_budget_for_both_tiers(monkeypatch, engine_calls):
+ """Tier 2 inherits what is LEFT of the timeout: a fresh copy doubles what the caller asked for."""
+ from ddgs.ddgs import DDGS
+
+ budgets = []
+ real_init = DDGS.__init__
+
+ def recording_init(self, *args, **kwargs):
+ budgets.append(kwargs.get("timeout"))
+ return real_init(self, *args, **kwargs)
+
+ monkeypatch.setattr(DDGS, "__init__", recording_init)
+
+ # Tier 1 burns most of the budget before coming back empty, so tier 2 runs with what is left.
+ def slow_tier_one(name):
+ if name in TIER1:
+ return "empty"
+ return "results"
+
+ engine_calls.install(slow_tier_one)
+ for name in TIER1:
+ cls = ENGINES["text"].get(name)
+ if cls is not None:
+ inner = cls.search
+ monkeypatch.setattr(
+ cls, "search", lambda self, q, _i = inner, **k: (time.sleep(0.3), _i(self, q, **k))[1]
+ )
+
+ tools.execute_tool("web_search", {"query": "unsloth", "timeout": 3})
+
+ tier_budgets = [b for b in budgets if isinstance(b, (int, float))]
+ assert len(tier_budgets) >= 3, f"expected a client per tier, saw {budgets}"
+ # Each value is the budget REMAINING when that tier starts, so the invariant is that it shrinks
+ # and never exceeds what the caller asked for. Summing them would be summing overlapping windows.
+ assert tier_budgets == sorted(
+ tier_budgets, reverse = True
+ ), f"budget did not shrink: {tier_budgets}"
+ assert (
+ tier_budgets[-1] < tier_budgets[0]
+ ), f"tier 2 was handed {tier_budgets[-1]}, not the remainder of {tier_budgets[0]}"
+ assert max(tier_budgets) <= tier_budgets[0], "a tier was handed more than the original budget"
+
+
+def test_the_resolver_never_names_an_engine_outside_the_tiers():
+ resolved = tools._resolve_engine_tiers(ENGINES["text"])
+ named = {name for tier in resolved for name in tier.split(",")}
+
+ assert named <= set(TIER1) | set(TIER2)
+ assert "yandex" not in named
+ assert "bing" not in named
diff --git a/tests/kaggle/studio_gpu/run_studio_gpu.py b/tests/kaggle/studio_gpu/run_studio_gpu.py
index 16de1964c3d..045675e3f02 100644
--- a/tests/kaggle/studio_gpu/run_studio_gpu.py
+++ b/tests/kaggle/studio_gpu/run_studio_gpu.py
@@ -1953,9 +1953,9 @@ class Payload:
worth catching.
What is deliberately NOT asserted: that the search returned results.
- `_web_search` fans out through ddgs with no API key, and a provider
- rate-limiting a Kaggle egress IP is a fact about the day, not a Studio
- defect. Failing on it would put a red in front of every PR for
+ `_web_search` runs an approved engine allowlist through ddgs with no API
+ key, and those engines rate-limiting a Kaggle egress IP is a fact about
+ the day, not a Studio defect. Failing on it would put a red in front of every PR for
something no reader could act on. The reply and the result count are
recorded so a human can see which happened.
"""
diff --git a/tests/kaggle/test_studio_web_search.py b/tests/kaggle/test_studio_web_search.py
index 6e285d0c903..f4a2f57c47d 100644
--- a/tests/kaggle/test_studio_web_search.py
+++ b/tests/kaggle/test_studio_web_search.py
@@ -15,10 +15,10 @@ It must count only what THIS request wrote. The payload runs several
tool-driven assertions against one long-lived server, and a whole-file grep
would let `assert_code_execution`'s call satisfy this one.
-And it must NOT fail on an empty result set. `_web_search` fans out through
-ddgs with no API key, so a provider rate-limiting a Kaggle egress IP is a fact
-about the day rather than a Studio defect, and failing on it would put a red in
-front of every PR that no reader could act on.
+And it must NOT fail on an empty result set. `_web_search` runs an approved engine
+allowlist through ddgs with no API key, so those engines rate-limiting a Kaggle
+egress IP is a fact about the day rather than a Studio defect, and failing on it
+would put a red in front of every PR that no reader could act on.
"""
from __future__ import annotations