~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
feat(search): disable unavailable engines during LangGraph research (#6653)
LearningCircuit2b1b589ae870
diff --git a/changelog.d/+search-engine-availability.feature.md b/changelog.d/+search-engine-availability.feature.mdnew file mode 100644index 0000000000..4a10b656df--- /dev/null+++ b/changelog.d/+search-engine-availability.feature.md@@ -0,0 +1,16 @@+LangGraph research temporarily removes failed or rate-limited search engines+from action choices, shares cooldowns across subagents, and shows disable+reasons and retry times in research logs and progress. When every search+engine is only cooling down, the agent waits (up to ten minutes) for the first+one to come back instead of stopping or answering without search; only+disables for the whole run can end it. Waiting is bounded per run: fifteen+minutes of cooldown waits in total, and an engine that fails after three+cooldowns in a row, or asks via `Retry-After` for more than ten minutes, is+disabled for the rest of the run. Searches skipped for an unavailable+engine appear in search metrics and on the research details page as+"skipped (engine unavailable)". This applies to engines that report failures+(currently: arxiv, openalex, pubmed, searxng, semantic_scholar, serper,+wayback, wikinews and wikipedia, plus the full-content search wrapper, along+with any engine whose exceptions propagate through the base search pipeline);+engines that do not report failures currently fail silently per request and+are not disabled, as before this change.diff --git a/docs/search-engines.md b/docs/search-engines.mdindex 97a46b5cd9..7e7e9b2a7f 100644--- a/docs/search-engines.md+++ b/docs/search-engines.md@@ -234,6 +234,116 @@ LDR supports multiple search strategies that determine how queries are processed- Use the langgraph-agent strategy, which can route around rate-limited engines- Consider adding premium engines for higher limits+### Temporarily Disabled Engines++During LangGraph research, an engine that reports a failure is removed from+subsequent model tool choices. The lead agent and its subagents share this state+for the research run. Calls already proposed are checked again before engine+creation, so a disabled engine is not repeatedly initialized or queried.+Searches are never serialized: parallel searches of one engine, including its+first calls and retries after a cooldown, run concurrently, and the first+failure disables the engine for all of them. Searches already in flight may+finish.++A cooldown never ends the research. When every search engine the agent (or a+subagent) could use is disabled and at least one of them only for a cooldown,+the next model call waits for the soonest cooldown to end (checking for+cancellation every second, never longer than ten minutes in total) and then+offers that engine again. Tools come back as soon as their cooldown ends, at+any step of the run, not only when a run or report section starts. This can+add waiting time while an engine keeps failing; the research log says how long.++Waiting is bounded per research run, so an engine that keeps failing cannot+keep a run waiting and retrying for hours:++- All cooldown waits in one run share a budget of fifteen minutes (parallel+ subagents waiting at the same time spend it once). When the next cooldown+ would not end within what is left, the cooling engines are disabled for the+ rest of the run instead.+- An engine that enters a cooldown three times in a row without a successful+ search in between (a search with no matches counts as successful) is+ disabled for the rest of the run on its next failure.+- A provider `Retry-After` longer than ten minutes is not waited for: the+ engine is disabled for the rest of the run.++Once that leaves no search engine, the rules below for engines disabled for+the rest of the run apply.++If every search engine is disabled for the rest of the run but page fetching+is enabled, the agent keeps only `fetch_content`: it can still read URLs from+the query or from earlier results, but it cannot find new sources and may+answer without searching (it is told to say when evidence is insufficient). If+every research tool is disabled for the rest of the run, the model is not+called without tools: the research (or the current detailed-report section)+stops, and the answer is written from the sources gathered so far. A section+stopped before gathering any sources is rendered as “*Limited information was+found for this subsection.*”; the research log records the stop as an error+line, while overall report progress continues.+Availability also propagates through the optional full-content search wrapper.++Only engines that report failures take part in this. Currently that is+`arxiv`, `openalex`, `pubmed`, `searxng`, `semantic_scholar`, `serper`,+`wayback`, `wikinews`, and `wikipedia`, plus the full-content search wrapper,+along with any engine whose exceptions propagate through the base search+pipeline. Engines that catch request errors themselves without recording a+failure — most of the remaining engines — currently fail silently per request:+they return empty results, stay available, and are never disabled, exactly as+before this change.++The research log records the reason, disable time, and retry time. The+“selecting next action” status lists the available tools and explains disabled+engines separately. A search skipped because its engine is disabled or cooling+down is recorded in search metrics with the status `skipped_unavailable` and+the reason: the Metrics dashboard and the research details page show these+skips per engine, separately from searches that were sent, so they do not+change call counts, response times or success rates. Cooldowns expire automatically; the engine then becomes+eligible for another search, and the log records that retry is available.++- Rate limits: use the provider's `Retry-After` value when reported, otherwise+ wait five minutes after the engine's retries are exhausted. No cooldown is+ longer than ten minutes: a longer `Retry-After` disables the engine for the+ rest of the research instead. Retries may+ happen in the HTTP client rather than the search pipeline: Semantic+ Scholar's session retries HTTP 429 itself, honoring `Retry-After` up to 30+ seconds per retry (at most five retries), and when those retries run out the engine is disabled for five minutes once its+ fallback queries are also used up. Exhausted retries on HTTP 5xx count as an+ ordinary search failure. Any non-JSON Wikipedia response (normally its HTML+ 429 page) is treated as a rate limit, because its client library discards+ the HTTP status; a non-JSON server error therefore also waits five minutes.+- Connection failures, timeouts, and other search failures: wait one minute.+ HTTP 503 uses the provider's `Retry-After` when reported (a longer one than+ ten minutes disables the engine for the rest of the research).+- A request URL refused by security validation: wait five minutes. The+ validator also refuses hosts that cannot be resolved, so a DNS outage is+ retried rather than treated as a configuration error.+- HTTP 403: wait five minutes, because it is often a temporary bot or firewall+ block. A 403 whose reply is clearly about credentials (it asks for+ authentication or mentions an API key, token, subscription or billing) is+ treated as denied credentials below. So is any 403 from Semantic Scholar+ when an API key is configured: it rejects an invalid key with a plain+ `{"message":"Forbidden"}` reply.+- Denied credentials/access (HTTP 401/402, or such a 403) or a private/loopback+ SearXNG instance URL without server approval, when the engine reports such a+ failure: disable for the rest of the research. Correct the configuration before+ starting another run. This does not change saved engine settings.+- A successful search with no matches is still available. Usable partial+ results also keep an engine available, and so does a search whose results+ all arrived but were then dropped by the relevance filter (or failed a later+ filtering step): the provider answered.+- Errors specific to one query do not disable the engine: a query the provider+ rejects as malformed (HTTP 400, 414 or 422) is reported back to the agent to+ rephrase, and a non-JSON Wayback Machine reply for one URL (such as its+ "blocked site" page) counts only against that URL. SearXNG listing unresponsive backends+ alongside no results counts as no matches, because it does not report which+ backends were queried.++Availability tracking lives in `web_search_engines/engine_availability.py` and+has no LangGraph dependency. `advanced_search_system/tools/search_availability.py`+adapts it to the agent. Engines that catch request exceptions and return an+empty list must preserve the failure using `BaseSearchEngine._record_search_failure`+or set `last_search_failure` to a `SearchFailure`. Optional enrichment errors+should not be reported as search failures.+### No Results Found- Try different search engines- Broaden your querydiff --git a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.pyindex 7a93970d22..ebd4b2fc42 100644--- a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py@@ -54,6 +54,21 @@ from ...utilities.url_utils import ()from ...utilities.json_utils import get_llm_response_textfrom ...database.thread_local_session import thread_cleanup+from ...web_search_engines.engine_availability import (+ MAX_COOLDOWN_SECONDS,+ SearchEngineAvailability,+ available_tool_names,+ engine_failure,+ engine_for_tool,+ search_exhausted,+)+from ..tools.search_availability import (+ NoResearchToolsAvailable,+ SearchAvailabilityMiddleware,+ note_metrics_name,+ run_search,+ wait_for_cooldown,+)from ..tools.fetch import (DEFAULT_MAX_FETCHES_PER_TOPIC,FETCH_MODES,@@ -85,6 +100,11 @@ SUBAGENT_TIMEOUT_SECONDS = 1800 # 30 minutes per subagent, measured from# each subagent's *actual* start time (not from the drain-loop start, which# used to make queued subagents inherit the wall-clock of everything that# ran before them -- see #5014).++# Longest a model call waits, in total, when every search engine it could+# use is cooling down, rather than continuing without search.+COOLDOWN_WAIT_SECONDS = MAX_COOLDOWN_SECONDS+# User-facing sentinels for "the agent produced nothing". _finalize's# missing-citations warning must stay quiet for both — an agent failure# is not a citation gap, and tagging it as one misdirects debugging.@@ -384,6 +404,9 @@ class SearchResultsCollector:self._sources_seen: set[str] = set()self._lock = threading.Lock()self._fetch_counts: dict[str, int] = {}+ # Results recorded per agent (subagent id or "lead"), so a subagent+ # can tell whether it gathered anything itself.+ self._result_counts: dict[str, int] = {}self._total_fetch_count = 0self._all_links = all_links if all_links is not None else []# Canonical URL -> the FIRST citation index allocated for it.@@ -653,6 +676,7 @@ class SearchResultsCollector:self._sources.append(_sanitize_sources_field(link))self._sources_seen.add(key)self._results.append(r)+ self._count_result_locked()indexed.append(r)return start_idx, indexed@@ -916,6 +940,7 @@ class SearchResultsCollector:if "link" not in echoed and "url" in echoed:echoed["link"] = echoed["url"]self._results.append(echoed)+ self._count_result_locked()return reused# Collision-free allocator (same as ``add_results``) so the@@ -940,6 +965,7 @@ class SearchResultsCollector:if "link" not in tracked and "url" in tracked:tracked["link"] = tracked["url"]self._results.append(tracked)+ self._count_result_locked()if key:self._pair_to_index[(key, snippet_key)] = str(index)# ``setdefault`` for the same reason as in@@ -1080,9 +1106,19 @@ class SearchResultsCollector:sid = _current_subagent_context.get() or subagent_id or "lead"return self._fetch_counts.get(sid, 0)+ def _count_result_locked(self) -> None:+ sid = _current_subagent_context.get() or "lead"+ self._result_counts[sid] = self._result_counts.get(sid, 0) + 1++ def result_count_for(self, subagent_id: str | None) -> int:+ """Results recorded by one agent (``None``: the lead) since reset()."""+ with self._lock:+ return self._result_counts.get(subagent_id or "lead", 0)+def reset(self) -> None:"""Clear per-call state. ``_all_links`` is intentionally kept."""with self._lock:+ self._result_counts.clear()self._results.clear()self._sources.clear()self._sources_seen.clear()@@ -1220,58 +1256,44 @@ def _make_web_search_tool(collector: SearchResultsCollector,programmatic_mode: bool = False,description: str = NEUTRAL_PRIMARY_SEARCH_DESCRIPTION,+ availability: SearchEngineAvailability | None = None,):- """Create a ``web_search`` tool that instantiates a fresh engine per call."""+ """Create a primary search tool with research-scoped availability."""+ availability = availability or SearchEngineAvailability()@tooldef web_search(query: str) -> str:"""Search the selected source and return result snippets with source indices."""- from local_deep_research.utilities.resource_utils import safe_closefrom local_deep_research.web_search_engines.search_engine_factory import (create_search_engine,)- engine = create_search_engine(- engine_name=search_engine_name,- llm=model,- settings_snapshot=settings_snapshot,+ results = run_search(+ search_engine_name,+ query,+ lambda: create_search_engine(+ engine_name=search_engine_name,+ llm=model,+ settings_snapshot=settings_snapshot,+ programmatic_mode=programmatic_mode,+ ),+ availability,programmatic_mode=programmatic_mode,)- if engine is None:- return f"Failed to create search engine '{search_engine_name}'."- try:- results = engine.run(query)- if not isinstance(results, list) or not results:- return f"No results found for '{query}'. Try rephrasing."- start, indexed = collector.add_results(- results, engine_name=search_engine_name- )- return _format_results(indexed, start)- except Exception as exc:- logger.exception("web_search tool error")- # Scrub credentials: a search-engine exception can embed the- # request URL, which may carry an API key. Full detail is logged- # server-side above.- return sanitize_error_for_agent(f"Search error: {exc}")- finally:- safe_close(engine, "web search engine")- try:- from local_deep_research.database.thread_local_session import (- cleanup_current_thread,- thread_session_manager,- )-- if not thread_session_manager.in_scope():- cleanup_current_thread()- except Exception: # allow: silent-exception- pass+ if isinstance(results, str):+ return results+ if not results:+ return f"No results found for '{query}'. Try rephrasing."+ start, indexed = collector.add_results(+ results, engine_name=search_engine_name+ )+ return _format_results(indexed, start)web_search.description = descriptionreturn web_search-# Fetch tool builders (full / summary_focus / summary_focus_query / disabled)-# live in ``advanced_search_system.tools.fetch``; see ``build_fetch_tool``.+# Fetch tool builders live in advanced_search_system.tools.fetch.def _make_specialized_search_tool(@@ -1281,52 +1303,39 @@ def _make_specialized_search_tool(settings_snapshot: dict,collector: SearchResultsCollector,programmatic_mode: bool = False,+ availability: SearchEngineAvailability | None = None,):- """Create a ``search_{engine}`` tool for a specific search engine."""+ """Create a specialized search tool with research-scoped availability."""+ availability = availability or SearchEngineAvailability()@tooldef specialized_search(query: str) -> str:- """Search a specialized engine.""" # overridden below- from local_deep_research.utilities.resource_utils import safe_close+ """Search a specialized engine."""from local_deep_research.web_search_engines.search_engine_factory import (create_search_engine,)- engine = create_search_engine(- engine_name=engine_name,- llm=model,- settings_snapshot=settings_snapshot,+ results = run_search(+ engine_name,+ query,+ lambda: create_search_engine(+ engine_name=engine_name,+ llm=model,+ settings_snapshot=settings_snapshot,+ programmatic_mode=programmatic_mode,+ ),+ availability,programmatic_mode=programmatic_mode,)- if engine is None:- return f"Failed to create {engine_name} engine."- try:- results = engine.run(query)- if not isinstance(results, list) or not results:- return f"No results from {engine_name} for '{query}'. Try rephrasing."- start, indexed = collector.add_results(- results, engine_name=engine_name- )- return _format_results(indexed, start)- except Exception as exc:- logger.exception(f"search_{engine_name} tool error")- return sanitize_error_for_agent(- f"Search error ({engine_name}): {exc}"+ if isinstance(results, str):+ return results+ if not results:+ return (+ f"No results from {engine_name} for '{query}'. Try rephrasing.")- finally:- safe_close(engine, f"{engine_name} search engine")- try:- from local_deep_research.database.thread_local_session import (- cleanup_current_thread,- thread_session_manager,- )-- if not thread_session_manager.in_scope():- cleanup_current_thread()- except Exception: # allow: silent-exception- pass+ start, indexed = collector.add_results(results, engine_name=engine_name)+ return _format_results(indexed, start)- # Override name and description after decorationspecialized_search.name = f"search_{engine_name}"specialized_search.description = descriptionreturn specialized_search@@ -1339,6 +1348,7 @@ def _load_specialized_engine_tools(collector: SearchResultsCollector,programmatic_mode: bool = False,egress_context=None,+ availability: SearchEngineAvailability | None = None,) -> list:"""Load tools for all available specialized search engines, filtered byegress policy and per-engine ``agent_enabled`` flag.@@ -1486,6 +1496,7 @@ def _load_specialized_engine_tools(settings_snapshot,collector,programmatic_mode=programmatic_mode,+ availability=availability,))except Exception:@@ -1512,6 +1523,8 @@ def _make_research_subtopic_tool(library_resolver: Any = None,web_search_description: str = NEUTRAL_PRIMARY_SEARCH_DESCRIPTION,max_fetches_per_topic: int | None = None,+ availability: SearchEngineAvailability | None = None,+ wait_for_engines=None,):"""Create the ``research_subtopic`` tool that spawns parallel subagents.@@ -1534,6 +1547,8 @@ def _make_research_subtopic_tool(library / citation URLs fall through to the egress gate unchanged."""+ availability = availability or SearchEngineAvailability(progress_callback)+@tool(description=(f"Delegate parallel research on multiple subtopics. Each subtopic is "@@ -1621,6 +1636,7 @@ def _make_research_subtopic_tool(collector,programmatic_mode=programmatic_mode,description=web_search_description,+ availability=availability,))sub_fetch = build_fetch_tool(@@ -1652,14 +1668,20 @@ def _make_research_subtopic_tool(collector,programmatic_mode=programmatic_mode,egress_context=egress_context,+ availability=availability,))- if not sub_tools:+ disabled = availability.disabled()+ sub_tool_names = [t.name for t in sub_tools]+ if not available_tool_names(+ sub_tool_names, search_engine_name, disabled+ ) or search_exhausted(sub_tool_names, search_engine_name, disabled):# No primary search engine, fetching disabled, and every- # specialized engine filtered out (e.g. STRICT egress scope):- # a tool-less subagent would return un-grounded LLM text- # dressed up as research findings. Refuse instead — before the+ # specialized engine filtered out or currently unavailable+ # (or every search engine unavailable, leaving only fetch+ # without URLs to read): a subagent would return un-grounded+ # LLM text dressed up as research findings. Refuse instead — before the# milestone below, so the UI never announces sub-research that# won't run. (_build_tools drops research_subtopic entirely# when the lead toolbox is otherwise empty; this guard covers@@ -1668,10 +1690,20 @@ def _make_research_subtopic_tool("research_subtopic invoked with no tools available; ""refusing to run tool-less subagents")+ relevant_engines = {+ engine_for_tool(name, search_engine_name)+ for name in sub_tool_names+ }+ explanations = [+ state.describe()+ for name, state in disabled.items()+ if name in relevant_engines+ ]return ("research_subtopic is unavailable: no research tools "- "(search, fetch, or specialized engines) are permitted in "- "this configuration. Answer from sources already gathered."+ "(search, fetch, or specialized engines) are currently "+ "available. Answer from sources already gathered."+ + ("\n" + "\n".join(explanations) if explanations else ""))# Emit progress for UI@@ -1758,6 +1790,13 @@ def _make_research_subtopic_tool(model=model,tools=sub_tools,system_prompt=subagent_prompt,+ middleware=[+ SearchAvailabilityMiddleware(+ availability,+ search_engine_name,+ wait=wait_for_engines,+ )+ ],)result = agent.invoke({"messages": [{"role": "user", "content": topic}]},@@ -1772,6 +1811,21 @@ def _make_research_subtopic_tool(return f"No findings for: {topic}"except GraphRecursionError:return f"Research on '{topic}' reached iteration limit. Partial findings above."+ except NoResearchToolsAvailable as exc:+ logger.warning(+ "Subagent stopped: no research tools remain available"+ )+ # The collector is shared with the lead and the other+ # subagents; only this subagent's own results count here.+ if collector.result_count_for(_current_subagent_context.get()):+ return (+ f"Research on '{topic}' stopped early; sources "+ f"gathered so far are kept. {exc}"+ )+ return (+ f"Research on '{topic}' stopped before any sources "+ f"were gathered. {exc}"+ )except Exception as exc:logger.exception(f"Subagent failed for: {topic[:80]}")return sanitize_error_for_agent(@@ -2078,6 +2132,11 @@ class LangGraphAgentStrategy(BaseSearchStrategy):settings_snapshot=settings_snapshot,)self.collector = SearchResultsCollector(self.all_links_of_system)+ self.engine_availability = SearchEngineAvailability(+ self._update_progress,+ check_cancelled=lambda: self.check_termination(CHECK_CONTEXT_ENTRY),+ )+ self._primary_availability_checked = Falseself._collection_tool_display_names: dict[str, str] = {}self._collection_tool_display_names_loaded = False@@ -2430,11 +2489,32 @@ class LangGraphAgentStrategy(BaseSearchStrategy):if fetch_count > 0else "")+ disabled = self.engine_availability.disabled()+ relevant_engines = {+ engine_for_tool(name, self._search_engine_name) for name in names+ } - {None}+ names = available_tool_names(names, self._search_engine_name, disabled)+ explanations = [+ state.describe(self._display_tool_name(f"search_{name}"))+ for name, state in disabled.items()+ if name in relevant_engines+ ]+ suffix = (+ " · Disabled engines: " + "; ".join(explanations)+ if explanations+ else ""+ )if sources_so_far == 0:return (f"Step {iteration} · planning approach "f"with {len(names)} research tool"- f"{'s' if len(names) != 1 else ''} available…{fetch_part}"+ f"{'s' if len(names) != 1 else ''} available…{fetch_part}{suffix}"+ )+ if not names:+ return (+ f"Step {iteration} · {sources_so_far} source"+ f"{'s' if sources_so_far != 1 else ''} gathered{fetch_part} · "+ f"no research tools currently available; using gathered sources{suffix}")listing = ", ".join(_HEARTBEAT_TOOL_LABELS.get(n) or self._display_tool_name(n)@@ -2443,7 +2523,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):return (f"Step {iteration} · {sources_so_far} source"f"{'s' if sources_so_far != 1 else ''} gathered{fetch_part} · "- f"selecting next action from {listing}"+ f"selecting next action from {listing}{suffix}")def _build_egress_context(self):@@ -2536,6 +2616,19 @@ class LangGraphAgentStrategy(BaseSearchStrategy):# every tool builder so subagent threads — which don't inherit# thread-local state — get the same context as the lead agent.policy_ctx = self._build_egress_context()+ if not self._primary_availability_checked:+ if self.search is not None and self._search_engine_name:+ note_metrics_name(+ self.engine_availability,+ self._search_engine_name,+ self.search,+ )+ failure = engine_failure(self.search)+ if failure is not None:+ self.engine_availability.disable(+ self._search_engine_name, failure+ )+ self._primary_availability_checked = True# Same lifetime rule as policy_ctx: build ONCE, thread through every# tool so the lead agent and pooled subagents resolve the same# library documents. Without this, every fetch call on a library@@ -2639,6 +2732,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):self.collector,programmatic_mode=self.programmatic_mode,description=primary_search_description,+ availability=self.engine_availability,))@@ -2677,6 +2771,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):self.collector,programmatic_mode=self.programmatic_mode,egress_context=policy_ctx,+ availability=self.engine_availability,))@@ -2704,6 +2799,8 @@ class LangGraphAgentStrategy(BaseSearchStrategy):library_resolver=library_resolver,web_search_description=primary_search_description,max_fetches_per_topic=self.max_fetches_per_topic,+ availability=self.engine_availability,+ wait_for_engines=self._wait_for_cooldown,))@@ -2807,9 +2904,9 @@ class LangGraphAgentStrategy(BaseSearchStrategy):"given topic and produce a comprehensive, well-cited report.\n""Do NOT ask clarifying questions, do NOT ask the user anything, ""do NOT offer to help further — just research and report.\n"- "You MUST search the selected source before answering — never answer from memory alone.\n\n"+ "You MUST research using available tools before answering — never answer from memory alone.\n\n""Strategy:\n"- "1. Start with web_search — it queries your selected primary source — for initial exploration.\n"+ "1. Start with web_search when available — it queries your selected primary source — for initial exploration.\n""2. For complex multi-faceted questions, use research_subtopic to "f"investigate specific aspects in parallel (pass 2-{MAX_SUBTOPICS} "f"focused, non-overlapping questions. Batches of "@@ -2836,6 +2933,13 @@ class LangGraphAgentStrategy(BaseSearchStrategy):model=self.model,tools=tools,system_prompt=system_prompt,+ middleware=[+ SearchAvailabilityMiddleware(+ self.engine_availability,+ self._search_engine_name,+ wait=self._wait_for_cooldown,+ )+ ],)except Exception as exc:logger.exception("Failed to create LangGraph agent")@@ -2981,6 +3085,30 @@ class LangGraphAgentStrategy(BaseSearchStrategy):logger.warning("LangGraph agent hit recursion limit, synthesizing partial results")+ except NoResearchToolsAvailable as exc:+ # Every tool was filtered away by disables that last the rest of+ # the run (cooldowns are waited out first). Ending here is safer+ # than calling the model with no tools: several providers reject+ # tool-call history without tools. (A surviving fetch_content is+ # not filtered, so this does not fire for fetch-only runs.) The+ # collector fallback below uses a plain prompt without history.+ logger.warning(+ "LangGraph agent stopped: no research tools remain available"+ )+ if not final_content and not self.collector.results:+ return self._error_result(+ f"Research stopped before any sources were gathered. {exc}"+ )+ self._update_progress(+ f"Research tools unavailable; writing the answer from "+ f"gathered sources. {exc}",+ 85,+ {+ "phase": "engine_availability",+ "type": "warning",+ "status": "tools_exhausted",+ },+ )except Exception as exc:logger.exception("LangGraph agent error")if not final_content and not self.collector.results:@@ -2998,6 +3126,47 @@ class LangGraphAgentStrategy(BaseSearchStrategy):# -- Helpers ------------------------------------------------------------+ def _wait_for_cooldown(self, engines: set[str]) -> None:+ """Wait for one of ``engines`` to leave its cooldown.++ The agent middleware calls this before a model call when every+ search engine the call could use is disabled and at least one only+ for a cooldown (a transient failure or ``Retry-After``). Waiting+ keeps a short outage from ending the research, or from leaving the+ model to answer without search. The whole wait never exceeds+ ``COOLDOWN_WAIT_SECONDS``, even if an engine is disabled again+ meanwhile, and polls the research's termination flag every second.+ Run-long disables are not waited for. Waits are charged to the+ run's cooldown-wait budget; once it is spent, the cooling engines+ are disabled for the rest of the run instead (see+ ``wait_for_cooldown``).+ """+ availability = self.engine_availability+ if not engines or not engines <= availability.disabled().keys():+ return+ wait = availability.seconds_until_retry(engines)+ if wait is None or wait > COOLDOWN_WAIT_SECONDS:+ return+ if wait <= availability.wait_budget_remaining():+ self._update_progress(+ f"All search engines are cooling down; waiting "+ f"{math.ceil(wait)}s before continuing",+ None,+ {+ "phase": "engine_availability",+ "type": "info",+ "status": "waiting",+ },+ )+ wait_for_cooldown(+ availability,+ engines,+ max_wait=COOLDOWN_WAIT_SECONDS,+ # Resolved per call so tests can substitute the module's clock.+ sleep=time.sleep,+ check=lambda: self.check_termination(CHECK_CONTEXT_ENTRY),+ )+def _synthesize_from_collector(self, query: str) -> str:"""Fallback synthesis when the agent was cut short."""# Check cancellation before any synthesis LLM work. This is thediff --git a/src/local_deep_research/advanced_search_system/tools/search_availability.py b/src/local_deep_research/advanced_search_system/tools/search_availability.pynew file mode 100644index 0000000000..45aa319227--- /dev/null+++ b/src/local_deep_research/advanced_search_system/tools/search_availability.py@@ -0,0 +1,275 @@+"""LangChain adapter for the standalone search engine availability tracker."""++import asyncio+import time++from langchain.agents.middleware import AgentMiddleware+from langchain_core.messages import SystemMessage++from ...security.secure_logging import logger+from ...utilities.resource_utils import safe_close+from ...web_search_engines.search_engine_base import (+ BaseSearchEngine,+ metrics_engine_name,+)+from ...web_search_engines.engine_availability import (+ MAX_COOLDOWN_SECONDS,+ SearchEngineAvailability,+ SearchFailure,+ available_tool_names,+ engine_failure,+ engine_for_tool,+ failure_from_exception,+ http_status,+ is_query_error,+)+++class NoResearchToolsAvailable(RuntimeError):+ """Availability filtering removed every research tool from a request.++ Raised instead of calling the model with an empty tool list: several+ providers reject a request that carries tool-call history but defines+ no tools. This covers only an empty list: if ``fetch_content`` survives+ while every search engine is disabled, the model keeps it, since it can+ still read URLs from the query or from earlier results. It can then also+ answer without searching; the prompt tells it to say when evidence is+ insufficient. The message lists only safe disable explanations.++ A cooldown is not a reason to stop: when every search engine is only+ cooling down, the middleware waits for the soonest one instead (see+ ``wait_for_cooldown``). Only disables that last the rest of the run, or+ a wait that hits its bound, end up here.+ """+++def wait_for_cooldown(+ availability: SearchEngineAvailability,+ engines: set[str],+ *,+ max_wait: float = MAX_COOLDOWN_SECONDS,+ sleep=None,+ check=None,+) -> None:+ """Block until one of ``engines`` leaves its cooldown, bounded in total.++ Returns at once when an engine is already available, when every+ remaining disable lasts the rest of the run, or when the soonest retry+ lies beyond the ``max_wait`` bound (measured on the tracker's clock,+ so a re-disable mid-wait cannot extend it). The time spent is charged+ to the run's cooldown-wait budget; once the soonest retry lies beyond+ what is left of it, the cooling ``engines`` are disabled for the rest+ of the run instead of being waited for. ``check`` (by default the+ tracker's ``check_cancelled``) runs before each sleep of at most one+ second, so cancellation stays responsive.+ """+ sleep = sleep or time.sleep+ check = check or availability.check_cancelled+ deadline = availability.now() + max_wait+ with availability.waiting():+ while engines and engines <= availability.disabled().keys():+ if check is not None:+ check()+ remaining = availability.seconds_until_retry(engines)+ if remaining is None:+ return+ if remaining > availability.wait_budget_remaining():+ availability.end_cooldowns(engines)+ return+ if remaining > deadline - availability.now():+ return+ sleep(min(1.0, max(remaining, 0.01)))+++def note_metrics_name(+ availability: SearchEngineAvailability, engine_name: str, engine+) -> None:+ """Tell ``availability`` which name metrics record for ``engine``."""+ # Full-content wrappers delegate the search, and its metrics, inward.+ inner = getattr(engine, "web_search", None)+ availability.note_metrics_name(+ engine_name,+ metrics_engine_name(+ inner if isinstance(inner, BaseSearchEngine) else engine+ ),+ )+++def _record_skipped_search(+ engine_name: str,+ query: str,+ availability: SearchEngineAvailability,+ explanation: str,+) -> None:+ """Keep outages visible in search metrics although nothing was sent."""+ try:+ from ...metrics.search_tracker import (+ SEARCH_STATUS_SKIPPED,+ SearchTracker,+ )++ SearchTracker.record_search(+ engine_name=availability.metrics_name(engine_name),+ query=query,+ success=False,+ error_message=explanation,+ status=SEARCH_STATUS_SKIPPED,+ )+ except Exception as exc:+ logger.warning(+ f"Could not record skipped {engine_name} search "+ f"({type(exc).__name__})"+ )+++def run_search(+ engine_name: str,+ query: str,+ factory,+ availability: SearchEngineAvailability,+ *,+ programmatic_mode: bool = False,+):+ """Return results or a disable explanation, with cleanup on every path.++ A search skipped because the engine is disabled is recorded in search+ metrics (unless ``programmatic_mode``, like the engine's own searches).+ """+ disabled = availability.state(engine_name)+ if disabled is not None:+ explanation = disabled.describe()+ if not programmatic_mode:+ _record_skipped_search(+ engine_name, query, availability, explanation+ )+ return explanation+ engine = None+ try:+ engine = factory()+ if engine is not None:+ note_metrics_name(availability, engine_name, engine)+ if engine is None:+ failure = SearchFailure(+ "Could not initialize search engine; check its configuration"+ )+ else:+ failure = engine_failure(engine)+ if failure is None:+ results = engine.run(query)+ # Usable results win over a failed optional enrichment,+ # fallback attempt or full-content request.+ if isinstance(results, list) and results:+ availability.record_success(engine_name)+ return results+ failure = engine_failure(engine)+ if failure is None:+ availability.record_success(engine_name)+ return []+ return availability.disable(engine_name, failure).describe()+ except Exception as exc:+ # Type name only: provider exceptions can embed request URLs+ # carrying API keys, and loguru would render them.+ logger.warning(f"{engine_name} search failed ({type(exc).__name__})")+ if is_query_error(exc):+ # This query was rejected; the engine still works for others.+ return (+ f"{engine_name} rejected this query "+ f"(HTTP {http_status(exc)}); rephrase it and try again"+ )+ failure = failure_from_exception(exc) or SearchFailure(+ "Search error; a later attempt may succeed"+ )+ return availability.disable(engine_name, failure).describe()+ finally:+ safe_close(engine, f"{engine_name} search engine", allow_none=True)+ try:+ from ...database.thread_local_session import (+ cleanup_current_thread,+ thread_session_manager,+ )++ if not thread_session_manager.in_scope():+ cleanup_current_thread()+ except Exception:+ logger.exception("Could not clean up search tool thread")+++class SearchAvailabilityMiddleware(AgentMiddleware):+ """Remove unavailable tools from every model request, not just the prompt.++ Cooldowns are re-checked on every model call, so a tool comes back as+ soon as its cooldown ends. When every search engine behind the request+ is disabled and at least one of them only for a cooldown, the call+ first waits (bounded) for the soonest cooldown via ``wait``, which+ receives the set of engine names. The default is ``wait_for_cooldown``,+ which checks the tracker's ``check_cancelled`` every second and charges+ the run's cooldown-wait budget.+ """++ def __init__(self, availability, primary_engine, wait=None):+ self.availability = availability+ self.primary_engine = primary_engine+ self.wait = wait or (+ lambda engines: wait_for_cooldown(availability, engines)+ )++ def _filter_request(self, request):+ names = [t.name for t in request.tools]+ relevant = {+ engine_for_tool(name, self.primary_engine) for name in names+ } - {None}+ disabled = self.availability.disabled()+ if (+ relevant+ and relevant <= disabled.keys()+ and self.availability.seconds_until_retry(relevant) is not None+ ):+ # Nothing can search right now, but something will again: a+ # transient failure must not end the run or leave the model+ # answering from memory. Wait instead of filtering.+ self.wait(relevant)+ disabled = self.availability.disabled()+ available = available_tool_names(names, self.primary_engine, disabled)+ tools = [t for t in request.tools if t.name in available]+ explanations = [+ state.describe()+ for name, state in disabled.items()+ if name in relevant+ ]+ if not explanations:+ return request+ if not tools:+ raise NoResearchToolsAvailable(+ "No research tools remain available:\n"+ + "\n".join(explanations)+ )+ guidance = (+ "\nSearch engine availability for this step:\n"+ + "\n".join(explanations)+ + "\nUse only the tools currently supplied. If the primary search "+ "is disabled, use another available source. Do not call disabled "+ "tools or wait for cooldowns; continue with available tools and "+ "sources already gathered. If evidence is insufficient, say so."+ )+ if request.system_message is None:+ message = SystemMessage(content=guidance)+ else:+ # Preserve structured content and any provider-specific metadata.+ content = request.system_message.content+ content = (+ content + guidance+ if isinstance(content, str)+ else [*content, {"type": "text", "text": guidance}]+ )+ message = request.system_message.model_copy(+ update={"content": content}+ )+ return request.override(tools=tools, system_message=message)++ def wrap_model_call(self, request, handler):+ return handler(self._filter_request(request))++ async def awrap_model_call(self, request, handler):+ # Filtering may wait out a cooldown; keep that off the event loop.+ filtered = await asyncio.to_thread(self._filter_request, request)+ return await handler(filtered)diff --git a/src/local_deep_research/metrics/search_tracker.py b/src/local_deep_research/metrics/search_tracker.pyindex ee52b41ecb..bb27575d13 100644--- a/src/local_deep_research/metrics/search_tracker.py+++ b/src/local_deep_research/metrics/search_tracker.py@@ -13,6 +13,13 @@ from ..database.models import SearchCallfrom .database import MetricsDatabasefrom .query_utils import get_research_mode_condition, get_time_filter_condition+# ``success_status`` of a search that was not sent because its engine was+# disabled or cooling down for the research (see engine_availability).+# Recorded so outages stay visible, but not counted as a search attempt:+# it has no response time, and it is excluded from call counts, averages+# and success rates.+SEARCH_STATUS_SKIPPED = "skipped_unavailable"+class SearchTracker:"""Track search engine calls and performance metrics."""@@ -29,8 +36,14 @@ class SearchTracker:response_time_ms: int = 0,success: bool = True,error_message: Optional[str] = None,+ status: Optional[str] = None,) -> None:- """Record a completed search operation directly to database."""+ """Record a completed search operation directly to database.++ ``status`` overrides the success/error status, e.g.+ ``SEARCH_STATUS_SKIPPED`` for a search skipped because its engine+ was unavailable; ``error_message`` then carries the reason.+ """password = None# Extract research context (thread-safe)@@ -55,9 +68,11 @@ class SearchTracker:search_iteration = context.get("search_iteration", 0)# Determine success status- success_status = "success" if success else "error"+ success_status = status or ("success" if success else "error")error_type = None- if error_message:+ if status == SEARCH_STATUS_SKIPPED:+ error_type = "engine_unavailable"+ elif error_message:error_type = (type(error_message).__name__if isinstance(error_message, Exception)@@ -161,16 +176,17 @@ class SearchTracker:query = query.filter(mode_condition)# Get search engine statistics using ORM aggregation+ skipped = SearchCall.success_status == SEARCH_STATUS_SKIPPEDsearch_stats = session.query(SearchCall.search_engine,- func.count().label("call_count"),- func.avg(SearchCall.response_time_ms).label(- "avg_response_time"- ),+ func.sum(case((skipped, 0), else_=1)).label("call_count"),+ func.avg(+ case((skipped, None), else_=SearchCall.response_time_ms)+ ).label("avg_response_time"),func.sum(SearchCall.results_count).label("total_results"),- func.avg(SearchCall.results_count).label(- "avg_results_per_call"- ),+ func.avg(+ case((skipped, None), else_=SearchCall.results_count)+ ).label("avg_results_per_call"),func.sum(case((SearchCall.success_status == "success", 1), else_=0@@ -179,6 +195,9 @@ class SearchTracker:func.sum(case((SearchCall.success_status == "error", 1), else_=0)).label("error_count"),+ func.sum(case((skipped, 1), else_=0)).label(+ "skipped_count"+ ),).filter(SearchCall.search_engine.isnot(None))# Apply same filters to stats query@@ -221,10 +240,11 @@ class SearchTracker:or 0,"success_rate": ((stat.success_count / stat.call_count * 100)- if stat.call_count > 0+ if stat.call_countelse 0),"error_count": stat.error_count or 0,+ "skipped_count": stat.skipped_count or 0,}for stat in search_stats],@@ -269,13 +289,19 @@ class SearchTracker:)# Get search engine stats for this research+ skipped = SearchCall.success_status == SEARCH_STATUS_SKIPPEDengine_stats = (session.query(SearchCall.search_engine,- func.count().label("call_count"),- func.avg(SearchCall.response_time_ms).label(- "avg_response_time"+ func.sum(case((skipped, 0), else_=1)).label(+ "call_count"),+ func.avg(+ case(+ (skipped, None),+ else_=SearchCall.response_time_ms,+ )+ ).label("avg_response_time"),func.sum(SearchCall.results_count).label("total_results"),@@ -285,6 +311,9 @@ class SearchTracker:else_=0,)).label("success_count"),+ func.sum(case((skipped, 1), else_=0)).label(+ "skipped_count"+ ),).filter(SearchCall.research_id == research_id).group_by(SearchCall.search_engine)@@ -292,21 +321,25 @@ class SearchTracker:.all())- # Calculate totals- total_searches = len(search_calls)+ # Calculate totals; skipped searches were never sent.+ attempted = [+ call+ for call in search_calls+ if call.success_status != SEARCH_STATUS_SKIPPED+ ]+ total_searches = len(attempted)+ skipped_searches = len(search_calls) - total_searchestotal_results = sum(call.results_count or 0 for call in search_calls)avg_response_time = (- sum(call.response_time_ms or 0 for call in search_calls)+ sum(call.response_time_ms or 0 for call in attempted)/ total_searchesif total_searches > 0else 0)successful_searches = sum(- 1- for call in search_calls- if call.success_status == "success"+ 1 for call in attempted if call.success_status == "success")success_rate = ((successful_searches / total_searches * 100)@@ -316,6 +349,7 @@ class SearchTracker:return {"total_searches": total_searches,+ "skipped_searches": skipped_searches,"total_results": total_results,"avg_response_time": round(avg_response_time),"success_rate": round(success_rate, 1),@@ -338,9 +372,10 @@ class SearchTracker:"total_results": stat.total_results or 0,"success_rate": ((stat.success_count / stat.call_count * 100)- if stat.call_count > 0+ if stat.call_countelse 0),+ "skipped_count": stat.skipped_count or 0,}for stat in engine_stats],@@ -350,6 +385,7 @@ class SearchTracker:logger.warning("Error getting research search metrics")return {"total_searches": 0,+ "skipped_searches": 0,"total_results": 0,"avg_response_time": 0,"success_rate": 0,@@ -405,6 +441,9 @@ class SearchTracker:# Create time series datatime_series = []for call in search_calls:+ if call.success_status == SEARCH_STATUS_SKIPPED:+ # Not search activity: nothing was sent.+ continuetime_series.append({"timestamp": (diff --git a/src/local_deep_research/web/routers/benchmark.py b/src/local_deep_research/web/routers/benchmark.pyindex 8bba99c536..0ac34fa887 100644--- a/src/local_deep_research/web/routers/benchmark.py+++ b/src/local_deep_research/web/routers/benchmark.py@@ -502,6 +502,9 @@ def get_benchmark_history(total_search_requests = Nonetry:from ...database.models import SearchCall+ from ...metrics.search_tracker import (+ SEARCH_STATUS_SKIPPED,+ )# Get all results for this run to find research_idsresults = (@@ -527,6 +530,10 @@ def get_benchmark_history(research_requests = {}for call in search_calls:+ # A search skipped because its engine was+ # unavailable sent no request.+ if call.success_status == SEARCH_STATUS_SKIPPED:+ continueif call.research_id:if call.research_id not in research_results:research_results[call.research_id] = 0diff --git a/src/local_deep_research/web/static/css/research_details.css b/src/local_deep_research/web/static/css/research_details.cssindex d9dd1db282..291b0ba60e 100644--- a/src/local_deep_research/web/static/css/research_details.css+++ b/src/local_deep_research/web/static/css/research_details.css@@ -139,6 +139,10 @@color: var(--error-color);}+ .ldr-search-status-skipped {+ color: var(--warning-color);+ }+.ldr-loading-spinner {text-align: center;padding: 3rem;diff --git a/src/local_deep_research/web/static/js/components/details.js b/src/local_deep_research/web/static/js/components/details.jsindex 98ed0e9f9c..a9710651f8 100644--- a/src/local_deep_research/web/static/js/components/details.js+++ b/src/local_deep_research/web/static/js/components/details.js@@ -547,6 +547,12 @@}}+ // 'skipped_unavailable': not sent, because the engine was disabled or+ // cooling down for this research.+ function isSkippedSearch(call) {+ return call.success_status === 'skipped_unavailable';+ }+// Display search metricsfunction displaySearchMetrics(searchData) {if (!searchData) return;@@ -557,7 +563,9 @@const avgResponseTime = searchData.avg_response_time || 0;const successRate = searchData.success_rate || 0;- document.getElementById('total-searches').textContent = formatNumber(totalSearches);+ const skippedSearches = searchData.skipped_searches || 0;+ document.getElementById('total-searches').textContent = formatNumber(totalSearches) ++ (skippedSearches ? ` (+${formatNumber(skippedSearches)} skipped)` : '');document.getElementById('total-search-results').textContent = formatNumber(totalResults);document.getElementById('avg-search-response-time').textContent = `${avgResponseTime.toFixed(0)}ms`;document.getElementById('search-success-rate').textContent = `${successRate.toFixed(1)}%`;@@ -567,21 +575,27 @@if (container && searchData.search_calls) {container.innerHTML = '';+ const addDiv = (parent, className, text) => {+ const div = document.createElement('div');+ div.className = className;+ div.textContent = text;+ parent.appendChild(div);+ return div;+ };searchData.search_calls.forEach(call => {const item = document.createElement('div');item.className = 'ldr-search-engine-item';- // bearer:disable javascript_lang_dangerous_insert_html- // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: all interpolations use escapeHtml/esc, numeric coercion, or hardcoded strings- item.innerHTML = `- <div class="ldr-search-engine-info">- <div class="ldr-search-engine-name">${escapeHtml(call.engine || 'Unknown')}</div>- <div class="ldr-search-engine-query">${escapeHtml(call.query || 'No query')}</div>- </div>- <div class="ldr-search-engine-stats">- <div class="ldr-search-results">${formatNumber(call.results_count || 0)} results</div>- <div class="ldr-search-time">${((call.response_time_ms || 0) / 1000).toFixed(1)}s</div>- </div>- `;+ const info = addDiv(item, 'ldr-search-engine-info', '');+ addDiv(info, 'ldr-search-engine-name', call.engine || 'Unknown');+ addDiv(info, 'ldr-search-engine-query', call.query || 'No query');+ const stats = addDiv(item, 'ldr-search-engine-stats', '');+ if (isSkippedSearch(call)) {+ // Not sent: there are no results or response time.+ addDiv(stats, 'ldr-search-status-skipped', 'Skipped (engine unavailable)');+ } else {+ addDiv(stats, 'ldr-search-results', `${formatNumber(call.results_count || 0)} results`);+ addDiv(stats, 'ldr-search-time', `${((call.response_time_ms || 0) / 1000).toFixed(1)}s`);+ }container.appendChild(item);});}@@ -608,6 +622,7 @@</div><div class="ldr-search-engine-stats"><span>${engine.call_count ?? 0} searches</span>+ ${engine.skipped_count ? `<span class="ldr-search-status-skipped">${Number(engine.skipped_count)} skipped (engine unavailable)</span>` : ''}<span>${(engine.success_rate ?? 0).toFixed(1)}% success</span><span>${((engine.avg_response_time ?? 0) / 1000).toFixed(2)}s avg</span><span>${formatNumber(engine.total_results ?? 0)} results</span>@@ -631,8 +646,9 @@const html = searchTimeline.map(search => {const parsedDate = search.timestamp ? new Date(search.timestamp) : null;const timestamp = parsedDate && !isNaN(parsedDate) ? parsedDate.toLocaleTimeString() : '\u2014';- const statusClass = search.success_status === 'success' ? 'ldr-search-status-success' : 'ldr-search-status-error';- const statusText = search.success_status === 'success' ? 'Success' : 'Failed';+ const skipped = isSkippedSearch(search);+ const statusClass = search.success_status === 'success' ? 'ldr-search-status-success' : (skipped ? 'ldr-search-status-skipped' : 'ldr-search-status-error');+ const statusText = search.success_status === 'success' ? 'Success' : (skipped ? 'Skipped (engine unavailable)' : 'Failed');return `<div class="ldr-search-timeline-item"><div style="flex: 1;">@@ -640,7 +656,7 @@<div class="ldr-search-timeline-meta">${timestamp} \u00b7 ${escapeHtml(search.query || 'N/A')}</div></div><div class="ldr-search-timeline-results">- ${formatNumber(search.results_count || 0)} results \u00b7 ${((search.response_time_ms ?? 0) / 1000).toFixed(2)}s+ ${skipped ? 'Not sent' : `${formatNumber(search.results_count || 0)} results \u00b7 ${((search.response_time_ms ?? 0) / 1000).toFixed(2)}s`}</div><span class="${statusClass}" style="margin-left: 0.75rem; font-weight: 600;">${statusText}</span></div>@@ -903,8 +919,9 @@searchChart.destroy();}- // Prepare enhanced search data- const searchCalls = searchData.search_calls.map((call, index) => ({+ // Prepare enhanced search data. Skipped searches were never sent,+ // so they have no result count to plot.+ const searchCalls = searchData.search_calls.filter(call => !isSkippedSearch(call)).map((call, index) => ({label: call.query ? call.query.substring(0, 20) + '...' : `Search ${index + 1}`,results: call.results_count || 0,engine: call.engine || 'Unknown',diff --git a/src/local_deep_research/web/templates/pages/metrics.html b/src/local_deep_research/web/templates/pages/metrics.htmlindex a4bdb6cc35..54455cc459 100644--- a/src/local_deep_research/web/templates/pages/metrics.html+++ b/src/local_deep_research/web/templates/pages/metrics.html@@ -841,6 +841,7 @@<div class="ldr-model-provider">Avg Response: ${(avgResponseTime / 1000).toFixed(1)}s${successRate !== null ? ` | Success: ${successRate.toFixed(1)}%` : ''}+ ${engine.skipped_count ? ` | Skipped (engine unavailable): ${formatNumber(engine.skipped_count)}` : ''}</div></div><div class="ldr-model-stats">diff --git a/src/local_deep_research/web_search_engines/engine_availability.py b/src/local_deep_research/web_search_engines/engine_availability.pynew file mode 100644index 0000000000..285c70d766--- /dev/null+++ b/src/local_deep_research/web_search_engines/engine_availability.py@@ -0,0 +1,517 @@+"""Research-scoped search engine availability, independent of agent frameworks.++Empty results are not failures. Engines report an explicit ``SearchFailure``+when a request cannot work; callers decide when to apply it (after retries and+fallbacks have finished). One tracker is shared by a research run's workers,+never by unrelated users or runs. No settings or credentials are persisted.+"""++from __future__ import annotations++import math+import re+import threading+import time+from contextlib import contextmanager+from dataclasses import dataclass+from datetime import UTC, datetime+from email.utils import parsedate_to_datetime+from typing import Callable++import requests+from urllib3.exceptions import ResponseError++from ..security.secure_logging import logger+from .rate_limiting.exceptions import RateLimitError++# Longest cooldown, and so also the longest a model call waits, in total,+# for a search engine to leave its cooldown when no engine can search,+# rather than ending the research. A provider Retry-After above this is+# not waited for: the engine is disabled for the rest of the run instead.+MAX_COOLDOWN_SECONDS = 600++# Total time one research run (one availability tracker) spends waiting for+# cooldowns. Once it is used up, cooling engines are disabled for the rest+# of the run instead of being waited for again, so a persistently failing+# sole engine cannot keep a run waiting and retrying for hours.+COOLDOWN_WAIT_BUDGET_SECONDS = 900++# Cooldowns an engine may enter in a row without a successful search in+# between. The next failure disables it for the rest of the run.+MAX_CONSECUTIVE_COOLDOWNS = 3++# HTTP 403 is often a temporary bot/WAF block rather than bad credentials;+# unless the reply says it is about authentication, cool down this long.+FORBIDDEN_COOLDOWN_SECONDS = 300++# Words in a 403 reply that mark it as an authentication or billing refusal.+_AUTH_MARKERS = re.compile(+ r"api[ _-]?key|access[ _-]?token|invalid[ _-]?token|unauthori[sz]ed|"+ r"authenticat|credential|subscription|billing|payment",+ re.IGNORECASE,+)+++@dataclass(frozen=True)+class SearchFailure:+ """Safe, actionable reason and cooldown; None means the rest of this run."""++ reason: str+ cooldown_seconds: float | None = 60+++def retry_after_seconds(value, *, now: float | None = None) -> float | None:+ """Parse HTTP Retry-After (seconds or HTTP date), ignoring invalid values."""+ if not isinstance(value, (str, int, float)) or isinstance(value, bool):+ return None+ try:+ seconds = float(value)+ except OverflowError:+ return None+ except (ValueError, TypeError):+ if not isinstance(value, str):+ return None+ try:+ seconds = parsedate_to_datetime(value).timestamp() - (+ time.time() if now is None else now+ )+ except (ValueError, TypeError, OverflowError):+ return None+ if not math.isfinite(seconds) or seconds <= 0:+ return None+ # Provider headers are untrusted; an absurd finite delta must not break+ # timestamp formatting in every subsequent progress/model update.+ try:+ datetime.fromtimestamp(+ (time.time() if now is None else now) + seconds, UTC+ )+ except (OverflowError, OSError, ValueError):+ return None+ return seconds+++def retry_after_from_error(error: object) -> float | None:+ """Preserve Retry-After when providers translate their HTTP exceptions."""+ delay = retry_after_seconds(getattr(error, "retry_after", None))+ if delay is None:+ response = getattr(error, "response", None)+ headers = getattr(response, "headers", None) or {}+ delay = retry_after_seconds(headers.get("Retry-After"))+ return delay+++# HTTP statuses caused by the request's query (malformed syntax, too long,+# unprocessable), not by the provider being down or refusing this client.+QUERY_ERROR_STATUSES = frozenset({400, 414, 422})+++def http_status(error: BaseException) -> int | None:+ """The HTTP status an exception carries, if any."""+ status = getattr(getattr(error, "response", None), "status_code", None)+ if not isinstance(status, int):+ status = getattr(error, "status_code", None)+ return status if isinstance(status, int) else None+++def is_query_error(error: BaseException) -> bool:+ """True when the failure is specific to this query, not to the engine.++ Such an error must not cool the engine down for every other search in+ the run; a different query can still succeed right away.+ """+ return http_status(error) in QUERY_ERROR_STATUSES+++def failure_from_exception(+ error: BaseException, *, bare_403_is_bad_key: bool = False+) -> SearchFailure | None:+ """Classify explicit failures without putting provider text/secrets in UI.++ ``bare_403_is_bad_key``: the failed request carried an API key to a+ provider known to reject an invalid key with a plain HTTP 403 (no+ ``WWW-Authenticate``, nothing telling in the body), so any 403 from it+ is treated as denied credentials. Other 403s stay a temporary block+ unless the reply itself says it is about credentials.+ """+ status = http_status(error)+ if isinstance(error, RateLimitError) or status == 429:+ return SearchFailure(+ "Rate limit reached", retry_after_from_error(error) or 300+ )+ if status in (401, 402) or (+ status == 403 and (bare_403_is_bad_key or _is_auth_refusal(error))+ ):+ return SearchFailure(+ f"Provider denied access (HTTP {status}); check credentials, permissions or quota",+ None,+ )+ if status == 403:+ return SearchFailure(+ "Provider refused the request (HTTP 403); this is often a "+ "temporary block",+ FORBIDDEN_COOLDOWN_SECONDS,+ )+ if isinstance(status, int) and status >= 500:+ return SearchFailure(+ f"Provider unavailable (HTTP {status})",+ (retry_after_from_error(error) if status == 503 else None) or 60,+ )+ if _retries_exhausted_on_429(error):+ # urllib3 already retried (honoring Retry-After) and discarded the+ # response, so no provider delay is left to preserve.+ return SearchFailure("Rate limit reached", 300)+ if isinstance(error, (requests.Timeout, TimeoutError)):+ return SearchFailure("Search request timed out")+ if isinstance(error, (requests.ConnectionError, ConnectionError)):+ return SearchFailure("Could not connect to the search provider")+ if isinstance(error, ValueError) and "security validation" in str(error):+ # The SSRF validator also refuses a host it cannot resolve, and+ # its ValueError does not say which. A transient DNS failure must+ # not take an engine out for the whole run, so use a finite+ # cooldown. A retry is not free: validation resolves the host, and+ # the redirect-hop form of this error is raised only after the+ # provider request was sent. Engines that can identify a policy+ # block (SearXNG's unapproved private instance URL) report a+ # run-long SearchFailure themselves.+ return SearchFailure(+ "Request URL blocked by security validation or its host could "+ "not be resolved; check server configuration and DNS",+ 300,+ )+ return None+++def _is_auth_refusal(error: BaseException) -> bool:+ """Whether a 403 reply says it is about credentials, not a block.++ Reads only the response (never the exception text, whose request URL+ can carry ``api_key=``) and never surfaces what it reads.+ """+ response = getattr(error, "response", None)+ headers = getattr(response, "headers", None) or {}+ try:+ if headers.get("WWW-Authenticate"):+ return True+ text = getattr(response, "text", "")+ except Exception:+ return False+ return isinstance(text, str) and bool(_AUTH_MARKERS.search(text[:4000]))+++def _retries_exhausted_on_429(error: BaseException) -> bool:+ """A mounted ``Retry(status_forcelist=[429, ...])`` gave up on HTTP 429.++ requests raises ``RetryError(MaxRetryError(reason=ResponseError(...)))``+ without a response; only the reason text names the status. Exhausted+ retries on other statuses stay generic transient failures.+ """+ if not isinstance(error, requests.exceptions.RetryError):+ return False+ cause = error.args[0] if error.args else None+ reason = getattr(cause, "reason", None)+ return isinstance(reason, ResponseError) and str(+ reason+ ) == ResponseError.SPECIFIC_ERROR.format(status_code=429)+++@dataclass(frozen=True)+class UnrecordedFailure:+ """A failure that could not be attributed to an engine; not tracked."""++ failure: SearchFailure++ def describe(self, name: str | None = None) -> str:+ return f"{name or 'Search'} failed: {self.failure.reason}"+++@dataclass(frozen=True)+class EngineDisablement:+ engine: str+ failure: SearchFailure+ disabled_at: float+ retry_at: float | None+ deadline: float | None++ def describe(self, name: str | None = None) -> str:+ start = datetime.fromtimestamp(self.disabled_at, UTC).strftime(+ "%Y-%m-%d %H:%M:%S UTC"+ )+ if self.retry_at is None:+ timing = "for the rest of this research; fix configuration before the next run"+ else:+ end = datetime.fromtimestamp(self.retry_at, UTC).strftime(+ "%Y-%m-%d %H:%M:%S UTC"+ )+ duration = math.ceil(self.retry_at - self.disabled_at)+ timing = f"for {duration}s; retry available at {end}"+ return (+ f"{name or self.engine} disabled since {start} {timing}: "+ f"{self.failure.reason}"+ )+++class SearchEngineAvailability:+ """Thread-safe circuit breaker with lazy cooldown expiry and change events.++ No lock is held while a search runs: parallel searches, including the+ first calls to an engine and retries after a cooldown, run concurrently+ and record their outcome under the tracker's lock. The first failure+ wins; later failures of the same outage return the existing state. A+ failure blocks new calls; work already in flight may still return+ usable results. Expiry permits a real retry, not a claim that the+ provider has recovered.+ """++ def __init__(+ self,+ on_change: Callable | None = None,+ *,+ clock: Callable[[], float] = time.monotonic,+ wall_clock: Callable[[], float] = time.time,+ check_cancelled: Callable[[], None] | None = None,+ wait_budget_seconds: float = COOLDOWN_WAIT_BUDGET_SECONDS,+ max_consecutive_cooldowns: int = MAX_CONSECUTIVE_COOLDOWNS,+ ):+ self._clock = clock+ self._wall_clock = wall_clock+ self._on_change = on_change+ # Raises (e.g. ResearchTerminatedException) when the run is+ # cancelled; cooldown waits call it before every sleep.+ self.check_cancelled = check_cancelled+ self._lock = threading.RLock()+ self._disabled: dict[str, EngineDisablement] = {}+ self._metrics_names: dict[str, str] = {}+ self._wait_budget = wait_budget_seconds+ self._max_consecutive_cooldowns = max_consecutive_cooldowns+ self._consecutive_cooldowns: dict[str, int] = {}+ # Wall time with at least one waiter, so parallel workers waiting+ # for the same cooldown spend the budget once, not once each.+ self._waited = 0.0+ self._waiters = 0+ self._waiting_since = 0.0++ def _emit(self, state: EngineDisablement, retry: bool = False):+ message = (+ f"{state.engine}: cooldown ended; available for retry"+ if retry+ else state.describe()+ )+ if retry:+ logger.info(message)+ else:+ logger.warning(message)+ if self._on_change:+ try:+ self._on_change(+ message,+ None,+ {+ "phase": "engine_availability",+ "type": "info" if retry else "warning",+ "engine": state.engine,+ "status": "retry_available" if retry else "disabled",+ "reason": state.failure.reason,+ "disabled_at": state.disabled_at,+ "retry_at": state.retry_at,+ },+ )+ except Exception:+ logger.exception("Could not report search engine availability")++ def disable(+ self, engine: str, failure: SearchFailure+ ) -> EngineDisablement | UnrecordedFailure:+ if not engine:+ # A missing engine name maps to every non-search tool in+ # engine_for_tool; recording it would hide fetch/delegation.+ logger.warning("Ignoring availability failure without an engine")+ return UnrecordedFailure(failure)+ with self._lock:+ current = self._disabled.get(engine)+ if (+ current is not None+ and (+ current.deadline is None or self._clock() < current.deadline+ )+ # A run-long failure (e.g. HTTP 401 from a search already+ # in flight) upgrades a cooldown instead of being dropped.+ and not (+ failure.cooldown_seconds is None+ and current.deadline is not None+ )+ ):+ return current+ now = self._wall_clock()+ delay = failure.cooldown_seconds+ if delay is not None:+ delay = retry_after_seconds(delay, now=now) or 60+ count = self._consecutive_cooldowns.get(engine, 0) + 1+ if delay > MAX_COOLDOWN_SECONDS:+ # The provider asked for longer than this research+ # waits; retrying every few minutes against its stated+ # delay would only fail again.+ failure = SearchFailure(+ f"{failure.reason}; the provider asked to wait "+ f"longer than {MAX_COOLDOWN_SECONDS}s",+ None,+ )+ delay = None+ elif count > self._max_consecutive_cooldowns:+ failure = SearchFailure(+ f"{failure.reason}; still failing after "+ f"{count - 1} cooldowns in a row",+ None,+ )+ delay = None+ else:+ self._consecutive_cooldowns[engine] = count+ state = EngineDisablement(+ engine,+ failure,+ now,+ None if delay is None else now + delay,+ None if delay is None else self._clock() + delay,+ )+ self._disabled[engine] = state+ self._emit(state)+ return state++ def disabled(self) -> dict[str, EngineDisablement]:+ expired = []+ with self._lock:+ now = self._clock()+ for engine, state in list(self._disabled.items()):+ if state.deadline is not None and now >= state.deadline:+ expired.append(self._disabled.pop(engine))+ states = dict(self._disabled)+ for state in expired:+ self._emit(state, retry=True)+ return states++ def now(self) -> float:+ """Current time on the clock that cooldown deadlines use."""+ return self._clock()++ def record_success(self, engine: str) -> None:+ """The engine answered a search; its cooldown streak starts over."""+ with self._lock:+ self._consecutive_cooldowns.pop(engine, None)++ @contextmanager+ def waiting(self):+ """Charge the time spent inside to the run's cooldown-wait budget."""+ with self._lock:+ if self._waiters == 0:+ self._waiting_since = self._clock()+ self._waiters += 1+ try:+ yield+ finally:+ with self._lock:+ self._waiters -= 1+ if self._waiters == 0:+ self._waited += self._clock() - self._waiting_since++ def wait_budget_remaining(self) -> float:+ """Seconds of cooldown waiting this run may still spend."""+ with self._lock:+ waited = self._waited+ if self._waiters:+ waited += self._clock() - self._waiting_since+ return max(0.0, self._wait_budget - waited)++ def end_cooldowns(self, engines) -> None:+ """Disable ``engines`` still cooling down for the rest of the run.++ Used once the run's cooldown-wait budget is spent: waiting again+ is no longer an option, so the usual "no research tools" handling+ applies instead of an endless wait-and-retry cycle.+ """+ for engine in engines:+ state = self.state(engine)+ if state is not None and state.deadline is not None:+ self.disable(+ engine,+ SearchFailure(+ f"{state.failure.reason}; this research already "+ f"waited {math.ceil(self._wait_budget)}s for "+ "search engine cooldowns",+ None,+ ),+ )++ def seconds_until_retry(self, engines) -> float | None:+ """Seconds until the soonest of ``engines`` leaves its cooldown.++ Only finite cooldowns count; None when none of them has one.+ """+ with self._lock:+ now = self._clock()+ remaining = [+ state.deadline - now+ for engine, state in self._disabled.items()+ if engine in engines and state.deadline is not None+ ]+ return max(0.0, min(remaining)) if remaining else None++ def note_metrics_name(self, engine: str, name: str) -> None:+ """Remember the name search metrics record for ``engine``.++ Metrics name engines after their class (``semanticscholar``), not+ their configuration key (``semantic_scholar``). Skipped searches are+ recorded under the same name so they group with real ones.+ """+ with self._lock:+ self._metrics_names[engine] = name++ def metrics_name(self, engine: str) -> str:+ with self._lock:+ return self._metrics_names.get(engine, engine)++ def state(self, engine: str) -> EngineDisablement | None:+ """The engine's current disablement, or None when it may be searched."""+ return self.disabled().get(engine)+++def engine_failure(engine) -> SearchFailure | None:+ """Read explicit engine health, without mistaking empty results for failure."""+ failure = getattr(engine, "last_search_failure", None)+ if isinstance(failure, SearchFailure):+ return failure+ if getattr(engine, "_is_available", None) is False:+ return SearchFailure("Search engine failed its availability check")+ return None+++def engine_for_tool(name: str, primary_engine: str) -> str | None:+ if name == "web_search":+ return primary_engine+ if name.startswith("search_"):+ return name.removeprefix("search_")+ return None+++def search_exhausted(names, primary_engine, disabled) -> bool:+ """The toolbox had search tools, and every one of them is disabled."""+ engines = {engine_for_tool(name, primary_engine) for name in names} - {None}+ return bool(engines) and engines <= disabled.keys()+++def available_tool_names(names, primary_engine, disabled) -> list[str]:+ """Filter an already policy-approved toolbox, including empty delegation.++ Delegation is dropped once availability has removed every search tool:+ its subagents would be left with ``fetch_content`` alone and no URLs+ to read. (A toolbox configured without search is left as it is.)+ """+ available = [+ name+ for name in names+ if (engine := engine_for_tool(name, primary_engine)) is None+ or engine not in disabled+ ]+ if search_exhausted(names, primary_engine, disabled):+ available = [name for name in available if name != "research_subtopic"]+ if available == ["research_subtopic"]:+ return []+ return availablediff --git a/src/local_deep_research/web_search_engines/engines/full_search.py b/src/local_deep_research/web_search_engines/engines/full_search.pyindex 06f6180828..244b004e0d 100644--- a/src/local_deep_research/web_search_engines/engines/full_search.py+++ b/src/local_deep_research/web_search_engines/engines/full_search.py@@ -4,6 +4,7 @@ from typing import Any, Dict, List, Optional, Protocol, runtime_checkablefrom langchain_core.language_models import BaseLLMfrom ...config.search_config import QUALITY_CHECK_DDG_URLS+from ..engine_availability import SearchFailure, engine_failurefrom ...research_library.downloaders.extraction import (batch_fetch_and_extract,)@@ -77,6 +78,11 @@ class FullSearchResults:# specific scope; used to evaluate per-URL fetches below.self.egress_context = egress_context+ @property+ def last_search_failure(self) -> SearchFailure | None:+ """Expose provider failures through the optional full-content wrapper."""+ return engine_failure(self.web_search)+def _downloader_allow_private_ips(self) -> bool:"""The private-fetch grant handed to the download pipeline.diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.pyindex 4cc2bd6a5b..f2c9ab6124 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py@@ -25,6 +25,7 @@ from ...utilities.arxiv_api import (fetch_arxiv_results,)from ..rate_limiting import RateLimitError+from ..engine_availability import retry_after_from_errorfrom ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity# Canonical arXiv identifier shapes, anchored so nothing else slips through@@ -466,6 +467,7 @@ class ArXivSearchEngine(BaseSearchEngine):return previewsexcept Exception as e:+ self._record_search_failure(e)error_msg = str(e)safe_msg = self._scrub_error(e)logger.exception(@@ -485,7 +487,8 @@ class ArXivSearchEngine(BaseSearchEngine):# a full traceback render (chain=True) would re-leak the# secret that safe_msg just scrubbed.raise RateLimitError(- f"arXiv rate limit hit: {safe_msg}"+ f"arXiv rate limit hit: {safe_msg}",+ retry_after=retry_after_from_error(e),) from Nonereturn []diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py b/src/local_deep_research/web_search_engines/engines/search_engine_openalex.pyindex ce46894339..93d1331b92 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py@@ -2,6 +2,8 @@from typing import Any, Dict, List, Optional+import requests+from langchain_core.language_models import BaseLLMfrom ...constants import SNIPPET_LENGTH_LONG, USER_AGENT@@ -436,8 +438,12 @@ class OpenAlexSearchEngine(BaseSearchEngine):"OpenAlex rate limit reached; a free API key from ""https://openalex.org/settings/api raises the daily budget 10x")- raise RateLimitError("OpenAlex rate limit exceeded") # noqa: TRY301 — re-raised by except RateLimitError for base class retry+ raise RateLimitError( # noqa: TRY301 — re-raised for base retry handling+ "OpenAlex rate limit exceeded",+ retry_after=response.headers.get("Retry-After"),+ )+ self._record_search_failure(requests.HTTPError(response=response))# response.text can echo the request (headers included), so it# gets the full dual-scrub — credential shapes AND this# engine's literal key — before it reaches a log sink.@@ -490,6 +496,7 @@ class OpenAlexSearchEngine(BaseSearchEngine):# rather than disappearing into an empty result list.raiseexcept Exception as e:+ self._record_search_failure(e)# logger.warning rather than logger.exception: the traceback# frames hold self.headers (the "Authorization: Bearer <key>"# value) and would render it under loguru diagnose. Samediff --git a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.pyindex 3ce2fbc9c6..57bb4ced78 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py@@ -9,6 +9,7 @@ from ...constants import SNIPPET_LENGTH_LONGfrom ...security.safe_requests import safe_getfrom ...security.secure_logging import loggerfrom ..rate_limiting import RateLimitError+from ..engine_availability import retry_after_from_errorfrom ..search_engine_base import BaseSearchEngine, Exposure, Sensitivityfrom ...utilities.llm_utils import invoke_llm_sync@@ -630,6 +631,7 @@ The default assumption should be that medical and scientific queries want RECENTReturns:List of PubMed IDs matching the query"""+ self.last_search_failure = Nonetry:# Prepare search parametersparams = {@@ -687,6 +689,7 @@ The default assumption should be that medical and scientific queries want RECENTreturn id_listexcept Exception as e:+ self._record_search_failure(e)safe_msg = self._scrub_error(e)logger.warning(f"Error searching PubMed ({type(e).__name__}): {safe_msg}"@@ -800,6 +803,7 @@ The default assumption should be that medical and scientific queries want RECENTreturn summariesexcept Exception as e:+ self._record_search_failure(e)error_msg = str(e)safe_msg = self._scrub_error(error_msg)logger.warning(@@ -820,7 +824,8 @@ The default assumption should be that medical and scientific queries want RECENT# a full traceback render (chain=True) would re-leak the# secret that safe_msg just scrubbed.raise RateLimitError(- f"PubMed rate limit hit: {safe_msg}"+ f"PubMed rate limit hit: {safe_msg}",+ retry_after=retry_after_from_error(e),) from Nonereturn []diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.pyindex 0649462049..4226997595 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py@@ -11,6 +11,7 @@ from ...security.safe_requests import safe_getfrom ..search_engine_base import BaseSearchEngine, Exposure, Sensitivityfrom ...security.secure_logging import loggerfrom ._searxng_rate_limiter import respect_rate_limit+from ..engine_availability import SearchFailure# The operator-approval resolver lives in security/egress/validators.py next# to the allowlist matcher it consults (dependency direction: engine →@@ -245,11 +246,15 @@ class SearXNGSearchEngine(BaseSearchEngine):self._is_available = Trueelse:self._is_available = False+ self._record_search_failure(+ requests.HTTPError(response=response)+ )logger.error(f"Failed to access SearXNG instance at {redact_url_for_log(self.instance_url)}. Status code: {response.status_code}")except (requests.RequestException, ValueError) as e:self._is_available = False+ self._record_search_failure(e)safe_msg = self._scrub_error(e)logger.exception(f"Error while trying to access SearXNG instance at {redact_url_for_log(self.instance_url)} ({type(e).__name__}): {safe_msg}"@@ -258,6 +263,11 @@ class SearXNGSearchEngine(BaseSearchEngine):else:private_url_hint = Falseif private_url_hint:+ self.last_search_failure = SearchFailure(+ "Instance URL is private/loopback and has no server approval; "+ "see docs/SearXNG-Setup.md",+ None,+ )# The dominant self-host case: default localhost:8080 SearXNG# with no operator opt-in. The generic exception above never# names the fix, so surface it explicitly on this runtime@@ -377,7 +387,7 @@ class SearXNGSearchEngine(BaseSearchEngine):if not self._is_available:logger.error(- "SearXNG engine is disabled (no instance URL provided) - cannot run search"+ "SearXNG engine failed its availability check - cannot run search")return []@@ -561,6 +571,10 @@ class SearXNGSearchEngine(BaseSearchEngine):f"SearXNG returned {len(results)} valid results from HTML parsing")else:+ # Not a search failure: SearXNG routinely lists+ # suspended backends, and neither the page nor the+ # JSON API says which backends were queried, so an+ # empty page cannot prove every backend failed.logger.warning("SearXNG returned no valid results. ""This may indicate SearXNG backend engine issues or rate limiting."@@ -568,24 +582,33 @@ class SearXNGSearchEngine(BaseSearchEngine):return resultsexcept ImportError as e:+ self.last_search_failure = SearchFailure(+ "HTML parser is unavailable; check server dependencies",+ None,+ )safe_msg = self._scrub_error(e)logger.exception(f"BeautifulSoup not available for HTML parsing ({type(e).__name__}): {safe_msg}")return []except Exception as e:+ self._record_search_failure(e)safe_msg = self._scrub_error(e)logger.exception(f"Error parsing HTML results ({type(e).__name__}): {safe_msg}")return []else:+ self._record_search_failure(+ requests.HTTPError(response=response)+ )logger.error(f"SearXNG returned status code {response.status_code}")return []except Exception as e:+ self._record_search_failure(e)safe_msg = self._scrub_error(e)logger.exception(f"Error getting SearXNG results ({type(e).__name__}): {safe_msg}"@@ -619,6 +642,9 @@ class SearXNGSearchEngine(BaseSearchEngine):try:data = response.json()except (json.JSONDecodeError, ValueError) as e:+ self.last_search_failure = SearchFailure(+ "Invalid JSON response; check the SearXNG response format"+ )safe_msg = self._scrub_error(e)logger.exception(f"Error parsing JSON results ({type(e).__name__}): {safe_msg}. "@@ -662,6 +688,9 @@ class SearXNGSearchEngine(BaseSearchEngine):f"SearXNG returned {len(results)} valid results from JSON parsing")else:+ # ``unresponsive_engines`` lists only the backends that failed,+ # not the set that was queried, so this cannot show that every+ # backend failed. Treat it as no matches (see the HTML path).logger.warning("SearXNG returned no valid results. ""This may indicate SearXNG backend engine issues or rate limiting."@@ -679,9 +708,7 @@ class SearXNGSearchEngine(BaseSearchEngine):List of preview dictionaries"""if not self._is_available:- logger.warning(- "SearXNG engine is disabled (no instance URL provided)"- )+ logger.warning("SearXNG engine failed its availability check")return []logger.info("Getting SearXNG previews")@@ -820,7 +847,7 @@ https://searxng.github.io/searxng/admin/installation.html"""if not self._is_available:logger.error(- "SearXNG run method called but engine is not available (missing instance URL)"+ "SearXNG run method called but engine failed its availability check")return []diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.pyindex 6e991ecde1..62cbdd6f67 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py@@ -14,6 +14,10 @@ from ...security import SafeSessionfrom ...utilities.llm_utils import invoke_llm_sync+# Longest Retry-After wait honored per HTTP retry.+SEMANTIC_SCHOLAR_RETRY_AFTER_MAX_SECONDS = 30++class SemanticScholarSearchEngine(BaseSearchEngine):"""Semantic Scholar search engine implementation with two-phase approach.@@ -28,6 +32,9 @@ class SemanticScholarSearchEngine(BaseSearchEngine):is_scientific = Trueis_lexical = Trueneeds_llm_relevance_filter = True+ # An invalid x-api-key gets 403 {"message":"Forbidden"} from its API+ # gateway, without WWW-Authenticate. The key is sent on every request.+ bare_403_means_bad_api_key = Truedef __init__(self,@@ -158,6 +165,10 @@ class SemanticScholarSearchEngine(BaseSearchEngine):backoff_factor=self.retry_backoff_factor,status_forcelist=[429, 500, 502, 503, 504],allowed_methods={"HEAD", "GET", "POST", "OPTIONS"},+ # urllib3 otherwise honors Retry-After up to six hours per retry+ # while the agent's tool call blocks. Cap each wait; after the+ # retries, the research-level rate-limit cooldown takes over.+ retry_after_max=SEMANTIC_SCHOLAR_RETRY_AFTER_MAX_SECONDS,)adapter = HTTPAdapter(max_retries=retry_strategy)@@ -249,11 +260,15 @@ class SemanticScholarSearchEngine(BaseSearchEngine):# Handle rate limitingif response.status_code == 429:logger.warning("Semantic Scholar rate limit exceeded")- raise RateLimitError("Semantic Scholar rate limit exceeded")+ raise RateLimitError(+ "Semantic Scholar rate limit exceeded",+ retry_after=response.headers.get("Retry-After"),+ )response.raise_for_status()return response.json() # type: ignore[no-any-return]except requests.RequestException as e:+ self._record_search_failure(e)safe_msg = self._scrub_error(e)logger.warning(f"API request failed: {safe_msg}")return {}@@ -331,6 +346,7 @@ Return ONLY the optimized search query with no explanation.Returns:List of paper dictionaries"""+ self.last_search_failure = Nonetry:# Configure fields to retrievefields = [@@ -381,6 +397,7 @@ Return ONLY the optimized search query with no explanation.return []except Exception as e:+ self._record_search_failure(e)safe_msg = self._scrub_error(e)logger.warning(f"Error in direct search: {safe_msg}")return []diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_serper.py b/src/local_deep_research/web_search_engines/engines/search_engine_serper.pyindex 83e817024c..bc5d9b89d9 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_serper.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_serper.py@@ -146,7 +146,7 @@ class SerperSearchEngine(BaseSearchEngine):)# Check for rate limits- self._raise_if_rate_limit(response.status_code)+ self._raise_if_rate_limit(requests.HTTPError(response=response))response.raise_for_status()@@ -202,11 +202,13 @@ class SerperSearchEngine(BaseSearchEngine):except RateLimitError:raise # Re-raise rate limit errorsexcept requests.exceptions.RequestException as e:+ self._record_search_failure(e)safe_msg = self._scrub_error(e)logger.warning(f"Error getting Serper API results: {safe_msg}")self._raise_if_rate_limit(e)return []except Exception as e:+ self._record_search_failure(e)safe_msg = self._scrub_error(e)logger.warning(f"Unexpected error getting Serper API results: {safe_msg}"diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py b/src/local_deep_research/web_search_engines/engines/search_engine_wayback.pyindex f3731a9c91..f4c2fd4bd9 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py@@ -1,6 +1,8 @@+import jsonimport refrom typing import Any, Dict, List, Optional, Tuple+import requestsfrom langchain_core.language_models import BaseLLMfrom ...research_library.downloaders.extraction import extract_content@@ -162,7 +164,10 @@ class WaybackSearchEngine(BaseSearchEngine):# Check for rate limitif response.status_code == 429:- raise RateLimitError("Wayback Machine rate limit exceeded") # noqa: TRY301 — re-raised by except RateLimitError for base class retry+ raise RateLimitError( # noqa: TRY301 — re-raised for base retry handling+ "Wayback Machine rate limit exceeded",+ retry_after=response.headers.get("Retry-After"),+ )data = response.json()@@ -200,7 +205,8 @@ class WaybackSearchEngine(BaseSearchEngine):# Check for rate limitif response.status_code == 429:raise RateLimitError( # noqa: TRY301 — re-raised by except RateLimitError for base class retry- "Wayback Machine CDX API rate limit exceeded"+ "Wayback Machine CDX API rate limit exceeded",+ retry_after=response.headers.get("Retry-After"),)# Check if response is valid JSON@@ -237,6 +243,12 @@ class WaybackSearchEngine(BaseSearchEngine):# Re-raise rate limit errors for base class retry handlingraiseexcept Exception as e:+ if not isinstance(+ e, (json.JSONDecodeError, requests.exceptions.JSONDecodeError)+ ):+ # A non-JSON reply is per URL (e.g. the archive's+ # "blocked site" page), not a Wayback outage.+ self._record_search_failure(e)safe_msg = self._scrub_error(e)logger.exception(f"Error getting Wayback snapshots for {redact_url_for_log(url)} ({type(e).__name__}): {safe_msg}"diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.py b/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.pyindex dd371cd473..9d9e2f8f9f 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.py@@ -308,9 +308,11 @@ Respond with ONE WORD ONLY: CURRENT, HISTORICAL, or UNCLEAR"""except (requests.exceptions.RequestException,json.JSONDecodeError,- ):+ ) as exc:logger.warning("Error fetching search resultsretrying...")retries += 1+ if retries == MAX_RETRIES:+ self._record_search_failure(exc)return []diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py b/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.pyindex 763a8390b4..75760e0283 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py@@ -5,6 +5,7 @@ import requestsimport wikipediafrom langchain_core.language_models import BaseLLM+from ..engine_availability import SearchFailurefrom ..search_engine_base import BaseSearchEngine, Exposure, Sensitivityfrom ...security import sanitize_for_logfrom ...security.secure_logging import logger@@ -22,6 +23,13 @@ _TRANSIENT_DECODE_ERRORS: tuple = (requests.exceptions.JSONDecodeError,)+# The ``wikipedia`` library discards the response, so the 429 status is not+# available here; classify the decode error as the throttle it almost always+# is instead of letting it fall back to a generic one-minute failure.+_THROTTLED = SearchFailure(+ "Rate limit reached (Wikipedia returned a non-JSON response)", 300+)+class WikipediaSearchEngine(BaseSearchEngine):"""Wikipedia search engine implementation with two-phase approach"""@@ -176,6 +184,7 @@ class WikipediaSearchEngine(BaseSearchEngine):logger.warning(f"Error getting summary for '{safe_title}'")continueexcept _TRANSIENT_DECODE_ERRORS:+ self.last_search_failure = _THROTTLED# MediaWiki almost certainly returned a 429 (or other# non-JSON page) — every remaining title in this batch# will hit the same throttle. Bail out with one warning@@ -188,6 +197,7 @@ class WikipediaSearchEngine(BaseSearchEngine):)breakexcept Exception as e:+ self._record_search_failure(e)safe_msg = self._scrub_error(e)logger.exception(f"Unexpected error for '{safe_title}' "@@ -201,6 +211,7 @@ class WikipediaSearchEngine(BaseSearchEngine):return previewsexcept _TRANSIENT_DECODE_ERRORS:+ self.last_search_failure = _THROTTLED# Same 429-style failure on the outer wikipedia.search() call —# log once at warning level and return an empty list.logger.warning(@@ -208,6 +219,7 @@ class WikipediaSearchEngine(BaseSearchEngine):)return []except Exception as e:+ self._record_search_failure(e)safe_msg = self._scrub_error(e)logger.exception(f"Error getting Wikipedia previews ({type(e).__name__}): {safe_msg}"diff --git a/src/local_deep_research/web_search_engines/rate_limiting/exceptions.py b/src/local_deep_research/web_search_engines/rate_limiting/exceptions.pyindex f65069cd3e..c2f0b1fae0 100644--- a/src/local_deep_research/web_search_engines/rate_limiting/exceptions.py+++ b/src/local_deep_research/web_search_engines/rate_limiting/exceptions.py@@ -6,7 +6,11 @@ Rate limiting specific exceptions for search engines.class RateLimitError(Exception):"""Raised when a search engine hits rate limits."""- pass+ def __init__(+ self, message: str = "Rate limit reached", *, retry_after=None+ ):+ super().__init__(message)+ self.retry_after = retry_afterclass AdaptiveRetryError(Exception):diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.pyindex 05cbf93d8d..c88ee64f02 100644--- a/src/local_deep_research/web_search_engines/search_engine_base.py+++ b/src/local_deep_research/web_search_engines/search_engine_base.py@@ -7,7 +7,6 @@ from urllib.parse import urlparsefrom langchain_core.language_models import BaseLLMfrom ..security.secure_logging import loggerfrom tenacity import (- RetryError,retry,retry_if_exception_type,stop_after_attempt,@@ -23,6 +22,12 @@ from ..security.egress.classification import Exposure, Sensitivityfrom ..utilities.thread_context import clear_search_context, set_search_contextfrom .rate_limiting import RateLimitError, get_tracker+from .engine_availability import (+ SearchFailure,+ failure_from_exception,+ is_query_error,+ retry_after_from_error,+)from ..constants import DEFAULT_SEARCH_TOOLif TYPE_CHECKING:@@ -112,6 +117,11 @@ class AdaptiveWait(wait_base):return self.get_wait_func()+def metrics_engine_name(engine: Any) -> str:+ """The engine name ``SearchTracker`` records for ``engine``'s searches."""+ return type(engine).__name__.replace("SearchEngine", "").lower()++class BaseSearchEngine(ABC):"""Abstract base class for search engines with two-phase retrieval capability.@@ -141,6 +151,13 @@ class BaseSearchEngine(ABC):# Should be overridden by subclasses - defaults to False for safetyis_public = False+ last_search_failure: SearchFailure | None = None+ # True when the provider answers an invalid ``self.api_key`` with a plain+ # HTTP 403 that carries no authentication hint. A 403 on a request sent+ # with a configured key then disables the engine for the run instead of+ # cooling it down again and again.+ bare_403_means_bad_api_key = False+# Class attribute to indicate if this is a generic search engine (vs specialized)# Generic engines are general web search (Google, Bing, etc) vs specialized (arXiv, PubMed).# Note: generic does NOT imply good native ranking — see is_lexical.@@ -713,9 +730,7 @@ class BaseSearchEngine(ABC):set_search_context(research_context)context_was_set = True- engine_name = self.__class__.__name__.replace(- "SearchEngine", ""- ).lower()+ engine_name = metrics_engine_name(self)start_time = time.time()success = True@@ -744,8 +759,10 @@ class BaseSearchEngine(ABC):def _execute_search():nonlocal success, error_message, results_count+ previews_received = Falsetry:# Step 1: Get preview information for items+ self.last_search_failure = Nonepreviews = self._get_previews(query)if not previews:logger.info(@@ -753,6 +770,11 @@ class BaseSearchEngine(ABC):)results_count = 0return []+ # The search request worked. A partial failure while+ # gathering previews, or the relevance filter dropping every+ # result below, does not make the engine unavailable.+ previews_received = True+ self.last_search_failure = None# Pre-filter enrichment: resolve DOIs to OpenAlex source# IDs BEFORE the preview filters run. The@@ -834,10 +856,11 @@ class BaseSearchEngine(ABC):return results- except RateLimitError:+ except RateLimitError as exc:# Only re-raise if rate limiting is enabledif self.rate_tracker.enabled:raise+ self._record_search_failure(exc)# If rate limiting is disabled, treat as regular errorsuccess = Falseerror_message = "Rate limit hit but rate limiting disabled"@@ -847,6 +870,10 @@ class BaseSearchEngine(ABC):results_count = 0return []except Exception as e:+ if not previews_received:+ # Past the previews, the provider already answered: a+ # filter or content error is not an engine outage.+ self._record_search_failure(e)# Other errors - don't retrysuccess = False# Sanitize before it flows to SearchTracker.record_search@@ -863,18 +890,10 @@ class BaseSearchEngine(ABC):try:return _run_with_retry() # type: ignore[no-any-return]- except RetryError as e:- # All retries exhausted- success = False- error_message = self._scrub_error(- f"Rate limited after all retries: {e}"- )- safe_msg = self._scrub_error(e)- logger.warning(- f"{self.__class__.__name__} failed after all retries: {safe_msg}"- )- return []except Exception as e:+ # Includes the last RateLimitError once retries are exhausted:+ # the decorator re-raises it (reraise=True), never RetryError.+ self._record_search_failure(e)success = Falseerror_message = safe_msg = self._scrub_error(e)logger.warning(@@ -1138,6 +1157,29 @@ class BaseSearchEngine(ABC):f"Please provide a valid API key.")+ def _record_search_failure(self, error: BaseException) -> None:+ """Preserve request failures even when an engine returns an empty list.++ Call at search request catch sites, not optional enrichment/fetch paths.+ A later successful attempt or usable results supersede this signal.+ An error specific to this query (HTTP 400) is not recorded: the+ engine itself still works.+ """+ if is_query_error(error):+ return+ bare_403_is_bad_key = self.bare_403_means_bad_api_key and bool(+ getattr(self, "api_key", None)+ )+ self.last_search_failure = (+ failure_from_exception(+ error, bare_403_is_bad_key=bare_403_is_bad_key+ )+ or self.last_search_failure+ or SearchFailure(+ "Search request failed; a later attempt may succeed"+ )+ )+def _is_rate_limit_error(self,error: Union[Exception, str, int],@@ -1231,7 +1273,8 @@ class BaseSearchEngine(ABC):if self._is_rate_limit_error(error, additional_patterns):error_msg = str(error) if not isinstance(error, str) else errorraise RateLimitError(- f"Rate limit detected: {self._sanitize_error_message(error_msg)}"+ f"Rate limit detected: {self._sanitize_error_message(error_msg)}",+ retry_after=retry_after_from_error(error),)def _extract_full_result(self, item: Dict[str, Any]) -> Dict[str, Any]:diff --git a/tests/js/components/details-rich-metrics-runtime.test.js b/tests/js/components/details-rich-metrics-runtime.test.jsindex a352020238..417749c08f 100644--- a/tests/js/components/details-rich-metrics-runtime.test.js+++ b/tests/js/components/details-rich-metrics-runtime.test.js@@ -170,6 +170,14 @@ it('renders rich optional metrics, safe untrusted text, and both timeline views'response_time_ms: 750,timestamp: '2026-08-30T10:00:02Z',success_status: 'success',+ }, {+ // Never sent: the engine was disabled for this research.+ engine: 'pubmed',+ query: 'skipped query',+ results_count: 0,+ response_time_ms: 0,+ timestamp: '2026-08-30T10:00:03Z',+ success_status: 'skipped_unavailable',}],};@@ -305,6 +313,24 @@ it('renders rich optional metrics, safe untrusted text, and both timeline views'instance.config.type === 'line'&& instance.config.data.datasets[0].label === 'Results Found'));+ // Skipped searches are not plotted as 0-result searches.+ expect(searchChart.config.data.datasets[0].data).toEqual([17]);+ expect(searchChart.config.data.labels).toHaveLength(1);+ const breakdownItems = document.querySelectorAll(+ '#search-engine-breakdown .ldr-search-engine-item',+ );+ expect(breakdownItems).toHaveLength(2);+ expect(breakdownItems[0].textContent).toContain(hostile);+ expect(breakdownItems[0].textContent).toContain('17 results');+ const skippedItem = breakdownItems[1];+ expect(skippedItem.querySelector('.ldr-search-status-skipped').textContent)+ .toBe('Skipped (engine unavailable)');+ expect(skippedItem.textContent).not.toContain('results');+ const timelineItems = document.querySelectorAll(+ '#search-timeline .ldr-search-timeline-item',+ );+ expect(timelineItems[1].textContent).toContain('Not sent');+ expect(timelineItems[1].textContent).not.toContain('0 results');const searchTooltips = searchChart.config.options.plugins.tooltip.callbacks;expect(searchTooltips.title([{ dataIndex: 0 }])).toContain('<img src=x');expect(searchTooltips.beforeBody([{ dataIndex: 0 }])).toEqual([diff --git a/tests/metrics/test_search_tracker_coverage.py b/tests/metrics/test_search_tracker_coverage.pyindex 10ded40d1b..ab045d058c 100644--- a/tests/metrics/test_search_tracker_coverage.py+++ b/tests/metrics/test_search_tracker_coverage.py@@ -15,6 +15,7 @@ from unittest.mock import MagicMock, Mock, patchimport pytestfrom local_deep_research.metrics.search_tracker import (+ SEARCH_STATUS_SKIPPED,SearchTracker,)@@ -73,7 +74,7 @@ def _base_context():class TestRecordSearchErrorType:"""Cover the error_type derivation branches in record_search."""- def _record_with_error(self, error_message, context=None):+ def _record_with_error(self, error_message, context=None, status=None):"""Call record_search with the given error_message, returning theSearchCall object added to the session."""ctx = context or _base_context()@@ -97,10 +98,21 @@ class TestRecordSearchErrorType:query="q",success=False,error_message=error_message,+ status=status,)call_obj = mock_session.add.call_args[0][0]return call_obj+ def test_skipped_status_is_recorded_with_its_reason(self):+ """An engine-unavailable skip keeps its own status and reason."""+ call_obj = self._record_with_error(+ "arxiv disabled since ...: Rate limit reached",+ status=SEARCH_STATUS_SKIPPED,+ )+ assert call_obj.success_status == SEARCH_STATUS_SKIPPED+ assert call_obj.error_type == "engine_unavailable"+ assert "Rate limit reached" in call_obj.error_message+def test_exception_instance_extracts_type_name(self):"""When error_message is an Exception, error_type should be its class name."""err = ValueError("bad value")@@ -341,7 +353,7 @@ class TestGetSearchMetricsFormatting:"""Cover data formatting paths in get_search_metrics."""def _make_stat(- self, engine, call_count, avg_rt, total_res, avg_res, succ, err+ self, engine, call_count, avg_rt, total_res, avg_res, succ, err, skip=0):return SimpleNamespace(search_engine=engine,@@ -351,6 +363,7 @@ class TestGetSearchMetricsFormatting:avg_results_per_call=avg_res,success_count=succ,error_count=err,+ skipped_count=skip,)def _make_call(self, engine, query, results_count, rt, status, ts):@@ -380,6 +393,20 @@ class TestGetSearchMetricsFormatting:assert stats[0]["error_count"] == 2assert stats[0]["avg_response_time"] == 200.0+ def test_engine_stats_report_skipped_searches_separately(self):+ """Skipped (engine unavailable) searches are shown, not attempted."""+ mock_db, mock_session = _setup_db_and_session()+ q = _chain_query(mock_session)++ stat = self._make_stat("arxiv", 4, 200.0, 8, 2.0, 3, 1, skip=5)+ q.all.side_effect = [[stat], []]++ tracker = SearchTracker(db=mock_db)+ stats = tracker.get_search_metrics()["search_engine_stats"]+ assert stats[0]["skipped_count"] == 5+ assert stats[0]["call_count"] == 4+ assert stats[0]["success_rate"] == 75.0+def test_engine_stats_zero_call_count(self):"""When call_count is 0, success_rate should be 0."""mock_db, mock_session = _setup_db_and_session()@@ -459,13 +486,14 @@ class TestGetResearchSearchMetrics:timestamp="2025-01-01",)- def _make_engine_stat(self, engine, count, avg_rt, total_res, succ):+ def _make_engine_stat(self, engine, count, avg_rt, total_res, succ, skip=0):return SimpleNamespace(search_engine=engine,call_count=count,avg_response_time=avg_rt,total_results=total_res,success_count=succ,+ skipped_count=skip,)def test_totals_calculated_correctly(self):@@ -491,6 +519,32 @@ class TestGetResearchSearchMetrics:assert len(result["search_calls"]) == 3assert len(result["engine_stats"]) == 1+ def test_skipped_searches_do_not_count_as_attempts(self):+ """An unavailable engine's skipped calls stay visible but separate."""+ mock_db, mock_session = _setup_db_and_session()+ q = _chain_query(mock_session)++ calls = [+ self._make_call(10, 200, "success"),+ self._make_call(0, 400, "error"),+ self._make_call(0, 0, SEARCH_STATUS_SKIPPED),+ self._make_call(0, 0, SEARCH_STATUS_SKIPPED),+ ]+ estat = self._make_engine_stat("brave", 2, 300.0, 10, 1, skip=2)+ q.all.side_effect = [calls, [estat]]++ result = SearchTracker(db=mock_db).get_research_search_metrics("rid")++ assert result["total_searches"] == 2+ assert result["skipped_searches"] == 2+ assert result["avg_response_time"] == 300+ assert result["success_rate"] == 50.0+ assert len(result["search_calls"]) == 4+ assert result["search_calls"][2]["success_status"] == (+ SEARCH_STATUS_SKIPPED+ )+ assert result["engine_stats"][0]["skipped_count"] == 2+def test_empty_research_returns_zeros(self):"""No search calls should produce all-zero totals."""mock_db, mock_session = _setup_db_and_session()diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.pyindex ea47c4ba91..42c49c2ef5 100644--- a/tests/strategies/test_langgraph_agent_strategy.py+++ b/tests/strategies/test_langgraph_agent_strategy.py@@ -5400,7 +5400,9 @@ class TestResearchSubtopicToolOverflow:# could otherwise diverge from MAX_SUBTOPICS.captured = {}- def _fake_create_agent(model=None, tools=None, system_prompt=None):+ def _fake_create_agent(+ model=None, tools=None, system_prompt=None, **kwargs+ ):captured["system_prompt"] = system_promptreturn MagicMock()diff --git a/tests/strategies/test_langgraph_subagent_specialized_engines.py b/tests/strategies/test_langgraph_subagent_specialized_engines.pyindex fddffaaf4c..ed49bb571f 100644--- a/tests/strategies/test_langgraph_subagent_specialized_engines.py+++ b/tests/strategies/test_langgraph_subagent_specialized_engines.py@@ -58,7 +58,7 @@ def _stub_subagent_internals(def fake_make_web_search_tool(*_a, **_k):return SimpleNamespace(name="web_search")- def fake_create_agent(*, model, tools, system_prompt): # noqa: ARG001+ def fake_create_agent(*, model, tools, system_prompt, **kwargs): # noqa: ARG001call_log["create_agent_tool_lists"].append([getattr(t, "name", "?") for t in tools])diff --git a/tests/strategies/test_search_availability.py b/tests/strategies/test_search_availability.pynew file mode 100644index 0000000000..bbca300b05--- /dev/null+++ b/tests/strategies/test_search_availability.py@@ -0,0 +1,1150 @@+"""Real agent-loop and search-tool regressions for engine availability."""++import time+from concurrent.futures import ThreadPoolExecutor+from types import SimpleNamespace+from threading import Barrier, Event+from unittest.mock import Mock, patch++import pytest+import requests+from langchain.agents import create_agent+from langchain.agents.middleware import ModelRequest+from langchain_core.language_models.chat_models import BaseChatModel+from langchain_core.messages import (+ AIMessage,+ HumanMessage,+ SystemMessage,+ ToolMessage,+)+from langchain_core.tools import tool as make_langchain_tool+from langchain_core.outputs import ChatGeneration, ChatResult+from pydantic import Field++from local_deep_research.advanced_search_system.strategies import (+ langgraph_agent_strategy as strategy_module,+)+from local_deep_research.advanced_search_system.tools.search_availability import (+ NoResearchToolsAvailable,+ SearchAvailabilityMiddleware,+ run_search,+)+from local_deep_research.exceptions import ResearchTerminatedException+from local_deep_research.web_search_engines.engine_availability import (+ SearchEngineAvailability,+ SearchFailure,+)+from local_deep_research.web_search_engines.rate_limiting import RateLimitError+from local_deep_research.web_search_engines.search_engine_base import (+ BaseSearchEngine,+)+++FACTORY = "local_deep_research.web_search_engines.search_engine_factory.create_search_engine"+++class ScriptedModel(BaseChatModel):+ responses: list+ seen_tools: list = Field(default_factory=list)++ @property+ def _llm_type(self):+ return "availability-test"++ def bind_tools(self, tools, **kwargs):+ return self.bind(test_tool_names=[t.name for t in tools])++ def _generate(self, messages, stop=None, run_manager=None, **kwargs):+ self.seen_tools.append(kwargs.get("test_tool_names", []))+ return ChatResult(+ generations=[ChatGeneration(message=self.responses.pop(0))]+ )+++def make_tool(name, tracker, model=None, collector=None):+ collector = collector or strategy_module.SearchResultsCollector([])+ if name == "web_search":+ return strategy_module._make_web_search_tool(+ "searxng", model or Mock(), {}, collector, availability=tracker+ )+ return strategy_module._make_specialized_search_tool(+ name.removeprefix("search_"),+ "Search a provider",+ model or Mock(),+ {},+ collector,+ availability=tracker,+ )+++def clock():+ return SimpleNamespace(now=0.0)+++def tracker(clock):+ return SearchEngineAvailability(clock=lambda: clock.now)++[email protected]("name", ["web_search", "search_searxng"])+def test_disabled_engine_is_not_recreated_by_repeated_tool_calls(name, tracker):+ engine = Mock(_is_available=False)+ engine.last_search_failure = SearchFailure("URL blocked", None)+ with patch(FACTORY, return_value=engine) as factory:+ tool = make_tool(name, tracker)+ first = tool.invoke({"query": "one"})+ second = tool.invoke({"query": "two"})+ assert "URL blocked" in first+ assert "disabled since" in second+ assert "Try rephrasing" not in second+ factory.assert_called_once()+ engine.run.assert_not_called()+ engine.close.assert_called_once()+++def test_concurrent_tools_share_failure_and_skip_engine_creation(tracker):+ engine = Mock(_is_available=False)+ engine.last_search_failure = SearchFailure("URL blocked", None)+ progress = Mock()+ tracker._on_change = progress+ tools = [make_tool("web_search", tracker) for _ in range(4)]+ with patch(FACTORY, return_value=engine) as factory:+ with ThreadPoolExecutor(max_workers=4) as pool:+ results = list(pool.map(lambda t: t.invoke({"query": "q"}), tools))+ # Calls already in flight may each have built the engine; the+ # shared failure is recorded once and stops every later call.+ calls = factory.call_count+ assert "disabled since" in tools[0].invoke({"query": "later"})+ assert all("disabled" in result for result in results)+ assert 1 <= calls <= 4+ assert factory.call_count == calls+ progress.assert_called_once()+++def test_zero_results_remain_available(tracker):+ engine = Mock()+ engine.run.return_value = []+ with patch(FACTORY, return_value=engine) as factory:+ tool = make_tool("web_search", tracker)+ assert "Try rephrasing" in tool.invoke({"query": "one"})+ assert "Try rephrasing" in tool.invoke({"query": "two"})+ assert factory.call_count == 2+ assert tracker.disabled() == {}+++def test_partial_results_survive_optional_request_failure(tracker):+ engine = Mock()+ engine.last_search_failure = None++ def search(query):+ engine.last_search_failure = SearchFailure("Optional request failed")+ return [{"title": "Useful result"}]++ engine.run.side_effect = search+ assert run_search("pubmed", "q", lambda: engine, tracker) == [+ {"title": "Useful result"}+ ]+ assert tracker.disabled() == {}+++def test_constructor_exception_is_contained_and_cooled_down(tracker):+ factory = Mock(side_effect=ConnectionError("secret"))+ assert "connect" in run_search("searxng", "q", factory, tracker)+ assert "secret" not in run_search("searxng", "q", factory, tracker)+ factory.assert_called_once()+++def test_model_schema_changes_after_failure_and_cooldown(tracker, clock):+ model = ScriptedModel(+ responses=[+ AIMessage(+ content="",+ tool_calls=[+ {"name": "web_search", "args": {"query": "q"}, "id": "1"}+ ],+ ),+ AIMessage(+ content="",+ tool_calls=[+ {"name": "search_pubmed", "args": {"query": "q"}, "id": "2"}+ ],+ ),+ AIMessage(content="Findings [1]"),+ ]+ )+ tools = [+ make_tool(name, tracker, model)+ for name in ["web_search", "search_pubmed"]+ ]++ def factory(*, engine_name, **kwargs):+ engine = Mock()+ if engine_name == "searxng":+ engine.run.side_effect = RateLimitError("limit", retry_after=300)+ else:++ def search(query):+ clock.now = 300+ return [{"title": "Result", "link": "https://example.org"}]++ engine.run.side_effect = search+ return engine++ with patch(FACTORY, side_effect=factory):+ agent = create_agent(+ model=model,+ tools=tools,+ middleware=[SearchAvailabilityMiddleware(tracker, "searxng")],+ )+ result = agent.invoke(+ {"messages": [{"role": "user", "content": "Research"}]}+ )+ assert result["messages"][-1].content == "Findings [1]"+ assert model.seen_tools == [+ ["web_search", "search_pubmed"],+ ["search_pubmed"],+ ["web_search", "search_pubmed"],+ ]+++def test_all_engines_disabled_never_calls_model_without_tools(tracker):+ """Even without history, an empty tool list would mean memory answers."""+ tracker.disable("searxng", SearchFailure("blocked", None))+ model = ScriptedModel(responses=[AIMessage(content="From memory")])+ tool = make_tool("web_search", tracker, model)+ agent = create_agent(+ model=model,+ tools=[tool],+ middleware=[SearchAvailabilityMiddleware(tracker, "searxng")],+ )+ with pytest.raises(NoResearchToolsAvailable, match="blocked"):+ agent.invoke({"messages": [{"role": "user", "content": "Research"}]})+ assert model.seen_tools == []+++def test_subagent_uses_shared_availability_in_real_model_call(tracker):+ tracker.disable("searxng", SearchFailure("blocked", None))+ model = ScriptedModel(responses=[AIMessage(content="Subtopic findings")])+ with (+ patch.object(strategy_module, "build_fetch_tool", return_value=None),+ patch.object(+ strategy_module,+ "_load_specialized_engine_tools",+ return_value=[make_tool("search_pubmed", tracker)],+ ),+ ):+ tool = strategy_module._make_research_subtopic_tool(+ "searxng",+ model,+ {},+ strategy_module.SearchResultsCollector([]),+ 3,+ availability=tracker,+ )+ assert "Subtopic findings" in tool.invoke({"subtopics": ["one"]})+ assert model.seen_tools == [["search_pubmed"]]+++def test_heartbeat_shows_only_working_choices_and_explains_disabled(+ tracker, clock+):+ strategy = strategy_module.LangGraphAgentStrategy(+ model=Mock(),+ search=Mock(),+ settings_snapshot={"search.tool": "searxng"},+ all_links_of_system=[{"link": "https://example.org"}],+ )+ strategy.engine_availability = tracker+ strategy._tool_names = ["web_search", "search_pubmed", "fetch_content"]+ strategy.collector.record_fetch()+ tracker.disable("searxng", SearchFailure("URL blocked", 300))+ message = strategy._heartbeat_message(3)+ active, disabled = message.split(" · Disabled engines: ")+ assert "PubMed" in active and "page fetching" in active+ assert "1 page fetch attempt" in active+ assert "SearXNG" not in active+ assert "SearXNG" in disabled and "URL blocked" in disabled+ assert "for 300s" in disabled and "retry available at" in disabled+ clock.now = 300+ assert "SearXNG" in strategy._heartbeat_message(4)+ assert "Disabled engines" not in strategy._heartbeat_message(4)+++def test_primary_known_failure_is_seeded_before_model_selection():+ strategy = strategy_module.LangGraphAgentStrategy(+ model=Mock(),+ search=Mock(last_search_failure=SearchFailure("URL blocked", None)),+ settings_snapshot={"search.tool": "searxng"},+ )+ with (+ patch.object(strategy, "_build_egress_context", return_value=None),+ patch.object(strategy, "_build_library_resolver", return_value=None),+ patch.object(+ strategy_module, "_load_specialized_engine_tools", return_value=[]+ ),+ ):+ strategy._build_tools()+ assert "searxng" in strategy.engine_availability.disabled()+++async def test_async_middleware_filters_and_preserves_system_metadata(tracker):+ tracker.disable("searxng", SearchFailure("blocked", None))+ request = ModelRequest(+ model=Mock(),+ messages=[],+ tools=[+ make_tool("web_search", tracker),+ make_tool("search_pubmed", tracker),+ ],+ system_message=SystemMessage(+ content=[{"type": "text", "text": "Research"}],+ additional_kwargs={"test_metadata": True},+ ),+ )+ captured = []++ async def handler(filtered):+ captured.append(filtered)+ return "answer"++ result = await SearchAvailabilityMiddleware(+ tracker, "searxng"+ ).awrap_model_call(request, handler)+ assert result == "answer"+ assert [t.name for t in captured[0].tools] == ["search_pubmed"]+ assert captured[0].system_message.additional_kwargs == {+ "test_metadata": True+ }+ assert len(request.system_message.content) == 1+ assert len(captured[0].system_message.content) == 2+++def test_disabled_states_do_not_reveal_policy_filtered_engines(tracker):+ tracker.disable("private_collection", SearchFailure("private", None))+ request = ModelRequest(+ model=Mock(), messages=[], tools=[make_tool("search_pubmed", tracker)]+ )+ middleware = SearchAvailabilityMiddleware(tracker, "searxng")+ assert middleware.wrap_model_call(request, lambda r: r) is request++[email protected]("cooldown", [None, 300])+def test_stale_delegation_does_not_start_workers_without_usable_tools(+ tracker, cooldown+):+ tracker.disable("searxng", SearchFailure("URL blocked", cooldown))+ progress = Mock()+ with (+ patch.object(strategy_module, "build_fetch_tool", return_value=None),+ patch.object(+ strategy_module, "_load_specialized_engine_tools", return_value=[]+ ),+ patch("langchain.agents.create_agent") as create_subagent,+ ):+ tool = strategy_module._make_research_subtopic_tool(+ "searxng",+ Mock(),+ {},+ strategy_module.SearchResultsCollector([]),+ 3,+ availability=tracker,+ progress_callback=progress,+ )+ result = tool.invoke({"subtopics": ["one", "two"]})+ assert "research_subtopic is unavailable" in result+ assert "URL blocked" in result+ assert "disabled since" in result+ create_subagent.assert_not_called()+ progress.assert_not_called()++[email protected]("cancel_from", ["search", "progress"])+def test_cancellation_propagates_and_still_closes_engine(cancel_from):+ progress = Mock()+ tracker = SearchEngineAvailability(progress)+ engine = Mock(last_search_failure=None)+ if cancel_from == "search":+ engine.run.side_effect = ResearchTerminatedException("cancelled")+ else:+ engine.run.side_effect = ConnectionError("offline")+ progress.side_effect = ResearchTerminatedException("cancelled")+ with pytest.raises(ResearchTerminatedException):+ run_search("searxng", "q", lambda: engine, tracker)+ engine.close.assert_called_once()+ if cancel_from == "search":+ assert tracker.disabled() == {}+ progress.assert_not_called()+ else:+ progress.assert_called_once()+++def test_healthy_searches_are_not_serialized(tracker):+ healthy = Mock(last_search_failure=None)+ healthy.run.return_value = []+ assert run_search("pubmed", "probe", lambda: healthy, tracker) == []+ simultaneous = Barrier(2, timeout=5)++ def factory():+ engine = Mock(last_search_failure=None)++ def search(query):+ simultaneous.wait()+ return [{"title": query}]++ engine.run.side_effect = search+ return engine++ with ThreadPoolExecutor(max_workers=2) as pool:+ results = list(+ pool.map(+ lambda query: run_search("pubmed", query, factory, tracker),+ ["one", "two"],+ )+ )+ assert results == [[{"title": "one"}], [{"title": "two"}]]+ assert tracker.disabled() == {}+++def test_failed_parallel_retries_after_cooldown_disable_once(clock):+ progress = Mock()+ tracker = SearchEngineAvailability(progress, clock=lambda: clock.now)+ tracker.disable("pubmed", SearchFailure("offline", 60))+ clock.now = 60+ factory = Mock(side_effect=ConnectionError("still offline"))+ with ThreadPoolExecutor(max_workers=4) as pool:+ results = list(+ pool.map(+ lambda _: run_search("pubmed", "retry", factory, tracker),+ range(4),+ )+ )+ assert all("disabled since" in result for result in results)+ statuses = [call.args[2]["status"] for call in progress.call_args_list]+ # First disable, its expiry, then exactly one new disable.+ assert statuses == ["disabled", "retry_available", "disabled"]+++def test_tools_exhausted_after_tool_use_stops_instead_of_empty_tool_list(+ tracker,+):+ """Tool-call history sent with no tools is rejected by some providers."""+ model = ScriptedModel(+ responses=[+ AIMessage(+ content="",+ tool_calls=[+ {"name": "web_search", "args": {"query": "q"}, "id": "1"}+ ],+ ),+ AIMessage(content="must not be requested"),+ ]+ )+ engine = Mock(_is_available=False)+ engine.last_search_failure = SearchFailure("URL blocked", None)+ with patch(FACTORY, return_value=engine):+ agent = create_agent(+ model=model,+ tools=[make_tool("web_search", tracker, model)],+ middleware=[SearchAvailabilityMiddleware(tracker, "searxng")],+ )+ with pytest.raises(NoResearchToolsAvailable, match="disabled since"):+ agent.invoke({"messages": [{"role": "user", "content": "q"}]})+ assert model.seen_tools == [["web_search"]]+++def test_transient_failure_on_the_only_engine_waits_instead_of_ending(+ tracker, clock+):+ """A cooldown is not a run-long disable: wait, then search again."""+ model = ScriptedModel(+ responses=[+ AIMessage(+ content="",+ tool_calls=[+ {"name": "web_search", "args": {"query": "q"}, "id": "1"}+ ],+ ),+ AIMessage(+ content="",+ tool_calls=[+ {"name": "web_search", "args": {"query": "q"}, "id": "2"}+ ],+ ),+ AIMessage(content="Findings [1]"),+ ]+ )+ engine = Mock(last_search_failure=None)+ engine.run.side_effect = [+ RateLimitError("limit", retry_after=300),+ [{"title": "Result", "link": "https://example.org"}],+ ]+ waits = []++ def wait(engines):+ waits.append((engines, tracker.seconds_until_retry(engines)))+ clock.now += tracker.seconds_until_retry(engines)++ with patch(FACTORY, return_value=engine):+ agent = create_agent(+ model=model,+ tools=[make_tool("web_search", tracker, model)],+ middleware=[+ SearchAvailabilityMiddleware(tracker, "searxng", wait=wait)+ ],+ )+ result = agent.invoke({"messages": [{"role": "user", "content": "q"}]})+ assert result["messages"][-1].content == "Findings [1]"+ assert waits == [({"searxng"}, 300)]+ assert model.seen_tools == [["web_search"]] * 3+++def test_cooling_engines_are_waited_for_even_when_fetch_survives(+ tracker, clock+):+ """Fetch alone cannot find sources; a cooldown ends before it helps."""++ @make_langchain_tool+ def fetch_content(url: str) -> str:+ """Fetch."""+ return ""++ tracker.disable("searxng", SearchFailure("offline", 60))+ tracker.disable("pubmed", SearchFailure("Rate limit", 300))+ request = ModelRequest(+ model=Mock(),+ messages=[HumanMessage(content="Research")],+ tools=[+ make_tool("web_search", tracker),+ make_tool("search_pubmed", tracker),+ fetch_content,+ ],+ )+ waited = []++ def wait(engines):+ waited.append(engines)+ clock.now = 60++ captured = []+ SearchAvailabilityMiddleware(tracker, "searxng", wait=wait).wrap_model_call(+ request, captured.append+ )+ assert waited == [{"searxng", "pubmed"}]+ assert [t.name for t in captured[0].tools] == [+ "web_search",+ "fetch_content",+ ]+++def test_default_wait_sleeps_until_the_soonest_cooldown(tracker, clock):+ tracker.disable("searxng", SearchFailure("offline", 3))+ sleeps = []++ def sleep(seconds):+ sleeps.append(seconds)+ clock.now += seconds++ from local_deep_research.advanced_search_system.tools import (+ search_availability,+ )++ with patch.object(+ search_availability, "time", SimpleNamespace(sleep=sleep)+ ):+ request = ModelRequest(+ model=Mock(), messages=[], tools=[make_tool("web_search", tracker)]+ )+ captured = []+ SearchAvailabilityMiddleware(tracker, "searxng").wrap_model_call(+ request, captured.append+ )+ assert sum(sleeps) == pytest.approx(3)+ assert max(sleeps) <= 1.0+ assert [t.name for t in captured[0].tools] == ["web_search"]+++def test_research_subtopic_alone_is_not_sent_as_an_empty_tool_list(tracker):+ """Delegation cannot help once its sub-tools are disabled too."""++ @make_langchain_tool+ def research_subtopic(subtopics: list[str]) -> str:+ """Delegate."""+ return ""++ tracker.disable("searxng", SearchFailure("URL blocked", None))+ request = ModelRequest(+ model=Mock(),+ messages=[+ HumanMessage(content="Research"),+ AIMessage(+ content="",+ tool_calls=[+ {"name": "web_search", "args": {"query": "q"}, "id": "1"}+ ],+ ),+ ToolMessage(content="failed", tool_call_id="1"),+ ],+ tools=[make_tool("web_search", tracker), research_subtopic],+ )+ handler = Mock()+ with pytest.raises(NoResearchToolsAvailable, match="URL blocked"):+ SearchAvailabilityMiddleware(tracker, "searxng").wrap_model_call(+ request, handler+ )+ handler.assert_not_called()++[email protected]("has_sources", [True, False])+def test_strategy_ends_research_when_tools_are_exhausted(has_sources):+ strategy = strategy_module.LangGraphAgentStrategy(+ model=Mock(),+ search=Mock(),+ settings_snapshot={"search.tool": "searxng"},+ )+ agent = Mock()++ def stream(*args, **kwargs):+ # analyze_topic resets the collector first; gather during the run.+ if has_sources:+ strategy.collector.add_results(+ [{"title": "Result", "link": "https://example.org"}]+ )+ raise NoResearchToolsAvailable(+ "No research tools remain available:\nsearxng disabled"+ )++ agent.stream.side_effect = stream+ with (+ patch.object(strategy, "_build_tools", return_value=[Mock()]),+ patch("langchain.agents.create_agent", return_value=agent),+ patch.object(+ strategy, "_synthesize_from_collector", return_value="Answer [1]"+ ) as synthesize,+ patch.object(strategy, "_finalize", return_value={"ok": True}) as done,+ ):+ result = strategy.analyze_topic("query")+ if has_sources:+ assert result == {"ok": True}+ synthesize.assert_called_once()+ assert done.call_args.args[1] == "Answer [1]"+ else:+ assert "Research stopped" in result["error"]+ assert "searxng disabled" in result["error"]+ synthesize.assert_not_called()++[email protected]("own_sources", [True, False])+def test_subagent_stops_cleanly_when_tools_are_exhausted(tracker, own_sources):+ collector = strategy_module.SearchResultsCollector([])+ # Another agent's source must not make this subagent claim it kept any.+ collector.add_results(+ [{"title": "Earlier", "link": "https://example.org/earlier"}]+ )+ calls = [+ AIMessage(+ content="",+ tool_calls=[+ {"name": "search_pubmed", "args": {"query": "q"}, "id": str(i)}+ ],+ )+ for i in range(2 if own_sources else 1)+ ]+ model = ScriptedModel(+ responses=[*calls, AIMessage(content="must not be requested")]+ )+ denied = requests.HTTPError(+ response=SimpleNamespace(status_code=401, headers={})+ )+ engine = Mock(last_search_failure=None)+ engine.run.side_effect = (+ [[{"title": "Own", "link": "https://example.org/own"}], denied]+ if own_sources+ else [denied]+ )+ with (+ patch(FACTORY, return_value=engine),+ patch.object(strategy_module, "build_fetch_tool", return_value=None),+ patch.object(+ strategy_module,+ "_load_specialized_engine_tools",+ return_value=[+ make_tool("search_pubmed", tracker, model, collector)+ ],+ ),+ ):+ tool = strategy_module._make_research_subtopic_tool(+ "searxng",+ model,+ {},+ collector,+ 3,+ search_enabled=False,+ availability=tracker,+ )+ result = tool.invoke({"subtopics": ["one"]})+ # Only claim kept sources when this subagent gathered some.+ assert ("sources gathered so far are kept" in result) is own_sources+ assert ("stopped before any sources" in result) is not own_sources+ assert "must not be requested" not in result+ assert model.seen_tools == [["search_pubmed"]] * len(calls)+++def test_primary_failure_without_engine_name_is_not_recorded():+ strategy = strategy_module.LangGraphAgentStrategy(+ model=Mock(),+ search=Mock(last_search_failure=SearchFailure("URL blocked", None)),+ settings_snapshot={"search.tool": "searxng"},+ )+ strategy._search_engine_name = None+ with (+ patch.object(strategy, "_build_egress_context", return_value=None),+ patch.object(strategy, "_build_library_resolver", return_value=None),+ patch.object(+ strategy_module, "_load_specialized_engine_tools", return_value=[]+ ),+ ):+ strategy._build_tools()+ assert strategy.engine_availability.disabled() == {}+++def test_search_exception_is_logged_by_type_only(tracker):+ factory = Mock(side_effect=ConnectionError("https://x/?api_key=SECRET"))+ with patch(+ "local_deep_research.advanced_search_system.tools."+ "search_availability.logger"+ ) as log:+ run_search("searxng", "q", factory, tracker)+ log.warning.assert_called_once()+ message = log.warning.call_args.args[0]+ assert "ConnectionError" in message+ assert "SECRET" not in message+++def test_parallel_first_searches_of_an_engine_run_concurrently(tracker):+ """No first-call probe lock: a slow first search blocks nobody."""+ started, release = Event(), Event()++ def slow_first():+ started.set()+ # Bounded so a serializing regression fails instead of hanging.+ assert release.wait(5)+ engine = Mock(last_search_failure=None)+ engine.run.return_value = [{"title": "slow"}]+ return engine++ fast = Mock(last_search_failure=None)+ fast.run.return_value = [{"title": "fast"}]+ with ThreadPoolExecutor(max_workers=1) as pool:+ slow = pool.submit(run_search, "pubmed", "slow", slow_first, tracker)+ assert started.wait(5)+ # Runs to completion while the first search is still in flight.+ assert run_search("pubmed", "fast", lambda: fast, tracker) == [+ {"title": "fast"}+ ]+ release.set()+ assert slow.result(5) == [{"title": "slow"}]+ assert tracker.disabled() == {}+++def test_detailed_report_section_with_every_engine_disabled_stops(tracker):+ """A later section starts without history; it must not answer from memory."""+ model = ScriptedModel(responses=[AIMessage(content="From memory")])+ strategy = strategy_module.LangGraphAgentStrategy(+ model=model,+ search=Mock(last_search_failure=None),+ settings_snapshot={"search.tool": "searxng"},+ )+ # The same strategy (and tracker) serves every section of the report;+ # an earlier section disabled the only engine.+ strategy.engine_availability = tracker+ tracker.disable("searxng", SearchFailure("URL blocked", None))+ with patch.object(+ strategy,+ "_build_tools",+ return_value=[make_tool("web_search", tracker, model)],+ ):+ result = strategy.analyze_topic("Section two")+ assert (+ "Research stopped before any sources were gathered" in result["error"]+ )+ assert "URL blocked" in result["error"]+ assert model.seen_tools == []+++def test_fetch_survives_when_every_search_engine_is_disabled(tracker):+ """Fetch-only is not terminal: it can still read URLs already known."""++ @make_langchain_tool+ def fetch_content(url: str) -> str:+ """Fetch."""+ return ""++ tracker.disable("searxng", SearchFailure("URL blocked", None))+ request = ModelRequest(+ model=Mock(),+ messages=[HumanMessage(content="Summarize https://example.org")],+ tools=[make_tool("web_search", tracker), fetch_content],+ )+ captured = []+ SearchAvailabilityMiddleware(tracker, "searxng").wrap_model_call(+ request, captured.append+ )+ assert [t.name for t in captured[0].tools] == ["fetch_content"]+ assert "URL blocked" in captured[0].system_message.content+++def _cooldown_strategy(clock, tracker):+ strategy = strategy_module.LangGraphAgentStrategy(+ model=Mock(),+ search=Mock(last_search_failure=None),+ settings_snapshot={"search.tool": "searxng"},+ )+ strategy.engine_availability = tracker+ sleeps = []+ hooks = []++ class FakeTime:+ """Stands in for the strategy module's ``time`` only; sleeps advance+ the tracker clock. Everything else is the real module."""++ def __getattr__(self, name):+ return getattr(time, name)++ def sleep(self, seconds):+ sleeps.append(seconds)+ clock.now += seconds+ for hook in hooks:+ hook()++ fake_time = FakeTime()+ fake_time.hooks = hooks+ return strategy, sleeps, fake_time+++ "cooldown,waits", [(30, True), (300, True), (600, True), (None, False)]+)+def test_waits_out_any_cooldown_but_not_a_run_long_disable(+ tracker, clock, cooldown, waits+):+ strategy, sleeps, fake_time = _cooldown_strategy(clock, tracker)+ tracker.disable("searxng", SearchFailure("offline", cooldown))+ with patch.object(strategy_module, "time", fake_time):+ strategy._wait_for_cooldown({"searxng"})+ assert bool(sleeps) is waits+ if waits:+ assert max(sleeps) <= 1.0+ assert sum(sleeps) == pytest.approx(cooldown, abs=0.05)+ assert tracker.disabled() == {}+ else:+ assert "searxng" in tracker.disabled()+++def test_does_not_wait_while_another_engine_works(tracker, clock):+ strategy, sleeps, fake_time = _cooldown_strategy(clock, tracker)+ tracker.disable("searxng", SearchFailure("offline", 30))+ with (+ patch.object(strategy_module, "time", fake_time),+ patch.object(strategy, "_update_progress") as progress,+ ):+ strategy._wait_for_cooldown({"searxng", "pubmed"})+ assert sleeps == []+ progress.assert_not_called()+++def test_cooldown_wait_honours_cancellation(tracker, clock):+ strategy, sleeps, fake_time = _cooldown_strategy(clock, tracker)+ tracker.disable("searxng", SearchFailure("offline", 30))+ checks = []++ def check_termination(context=None):+ checks.append(context)+ if len(checks) == 3:+ raise ResearchTerminatedException("cancelled")++ strategy.check_termination = check_termination+ with (+ patch.object(strategy_module, "time", fake_time),+ pytest.raises(ResearchTerminatedException),+ ):+ strategy._wait_for_cooldown({"searxng"})+ assert len(sleeps) == 2+ assert set(checks) == {strategy_module.CHECK_CONTEXT_ENTRY}++[email protected]("cooldown", [300, None])+def test_cooldown_wait_is_bounded_when_engine_is_disabled_again(+ tracker, clock, cooldown+):+ """A re-disable mid-wait must neither extend nor restart the wait."""+ strategy, sleeps, fake_time = _cooldown_strategy(clock, tracker)+ tracker.disable("searxng", SearchFailure("offline", 30))+ bound = strategy_module.COOLDOWN_WAIT_SECONDS++ def disable_again():+ # Another worker's retry fails right as the cooldown ends.+ if sum(sleeps) > bound + 1: # an unbounded wait fails, not spins+ raise AssertionError("cooldown wait is unbounded")+ state = tracker.disabled().get("searxng")+ if state is None:+ tracker.disable("searxng", SearchFailure("Rate limit", cooldown))++ fake_time.hooks.append(disable_again)+ with patch.object(strategy_module, "time", fake_time):+ strategy._wait_for_cooldown({"searxng"})+ assert 29 <= sum(sleeps) <= bound+ assert "searxng" in tracker.disabled()+++def test_section_start_waits_then_searches(tracker, clock):+ """End to end: the section's first model call gets web_search back."""+ model = ScriptedModel(responses=[AIMessage(content="Answer")])+ strategy, sleeps, fake_time = _cooldown_strategy(clock, tracker)+ strategy.model = model+ tracker.disable("searxng", SearchFailure("offline", 20))+ with (+ patch.object(strategy_module, "time", fake_time),+ patch.object(+ strategy,+ "_build_tools",+ return_value=[make_tool("web_search", tracker, model)],+ ),+ patch.object(strategy, "_finalize", return_value={"ok": True}),+ ):+ assert strategy.analyze_topic("Section") == {"ok": True}+ assert sum(sleeps) == pytest.approx(20, abs=0.05)+ assert model.seen_tools == [["web_search"]]+++RECORD = (+ "local_deep_research.metrics.search_tracker.SearchTracker.record_search"+)+++def test_skipped_search_is_recorded_in_metrics_with_reason(tracker):+ """Outages must stay visible in metrics although nothing is sent."""+ engine = Mock(_is_available=False)+ engine.last_search_failure = SearchFailure("URL blocked", None)+ with patch(RECORD) as record:+ run_search("pubmed", "first", lambda: engine, tracker)+ record.assert_not_called() # the engine's own run() records failures+ run_search("pubmed", "second", Mock(), tracker)+ record.assert_called_once()+ kwargs = record.call_args.kwargs+ assert kwargs["status"] == "skipped_unavailable"+ assert kwargs["query"] == "second"+ assert kwargs["success"] is False+ assert "URL blocked" in kwargs["error_message"]+++def test_skipped_search_uses_the_engines_metrics_name(tracker):+ class SemanticScholarSearchEngine(BaseSearchEngine):+ def __init__(self):+ self.last_search_failure = SearchFailure("Denied", None)++ def _get_previews(self, query):+ return []++ def _get_full_content(self, items):+ return items++ engine = SemanticScholarSearchEngine()+ wrapper = SimpleNamespace(web_search=engine, close=Mock())+ with patch(RECORD) as record:+ run_search("semantic_scholar", "q", lambda: wrapper, tracker)+ run_search("semantic_scholar", "q", Mock(), tracker)+ assert record.call_args.kwargs["engine_name"] == "semanticscholar"+++def test_programmatic_mode_does_not_record_skipped_searches(tracker):+ tracker.disable("pubmed", SearchFailure("URL blocked", None))+ with patch(RECORD) as record:+ run_search("pubmed", "q", Mock(), tracker, programmatic_mode=True)+ record.assert_not_called()+++def test_metrics_failure_does_not_break_the_search_tool(tracker):+ tracker.disable("pubmed", SearchFailure("URL blocked", None))+ with patch(RECORD, side_effect=RuntimeError("db down")):+ assert "URL blocked" in run_search("pubmed", "q", Mock(), tracker)+++def test_query_rejected_by_the_provider_does_not_disable_the_engine(tracker):+ engine = Mock(last_search_failure=None)+ engine.run.side_effect = requests.HTTPError(+ response=SimpleNamespace(status_code=400, headers={})+ )+ result = run_search("openalex", "bad (query", lambda: engine, tracker)+ assert "rejected this query (HTTP 400)" in result+ assert tracker.disabled() == {}+++def test_delegation_is_refused_when_subagents_could_only_fetch(tracker):+ tracker.disable("searxng", SearchFailure("URL blocked", None))++ @make_langchain_tool+ def fetch_content(url: str) -> str:+ """Fetch."""+ return ""++ with (+ patch.object(+ strategy_module, "build_fetch_tool", return_value=fetch_content+ ),+ patch.object(+ strategy_module, "_load_specialized_engine_tools", return_value=[]+ ),+ patch("langchain.agents.create_agent") as create_subagent,+ ):+ tool = strategy_module._make_research_subtopic_tool(+ "searxng",+ Mock(),+ {},+ strategy_module.SearchResultsCollector([]),+ 3,+ availability=tracker,+ )+ result = tool.invoke({"subtopics": ["one", "two"]})+ assert "research_subtopic is unavailable" in result+ assert "URL blocked" in result+ create_subagent.assert_not_called()+++def _always_rate_limited_run(tracker, clock, retry_after):+ """The only engine answers 429 to every search; the model keeps trying."""+ from local_deep_research.advanced_search_system.tools import (+ search_availability,+ )++ call = {+ "name": "web_search",+ "args": {"query": "q"},+ "id": "1",+ }+ model = ScriptedModel(+ responses=[AIMessage(content="", tool_calls=[call]) for _ in range(30)]+ )+ engine = Mock(last_search_failure=None)+ engine.run.side_effect = RateLimitError("limit", retry_after=retry_after)+ sleeps = []++ def sleep(seconds):+ sleeps.append(seconds)+ clock.now += seconds++ with (+ patch(FACTORY, return_value=engine),+ patch.object(search_availability, "time", SimpleNamespace(sleep=sleep)),+ ):+ agent = create_agent(+ model=model,+ tools=[make_tool("web_search", tracker, model)],+ middleware=[SearchAvailabilityMiddleware(tracker, "searxng")],+ )+ with pytest.raises(NoResearchToolsAvailable):+ agent.invoke(+ {"messages": [{"role": "user", "content": "q"}]},+ {"recursion_limit": 101},+ )+ return engine, sleeps+++def test_persistent_rate_limit_on_the_only_engine_is_bounded_per_run(clock):+ """Many model calls, each waiting 10 min, must not add up to hours."""+ tracker = SearchEngineAvailability(+ clock=lambda: clock.now, max_consecutive_cooldowns=100+ )+ engine, sleeps = _always_rate_limited_run(tracker, clock, 600)+ # 900s budget: one full 600s wait fits, a second one does not.+ assert sum(sleeps) == pytest.approx(600, abs=0.1)+ assert engine.run.call_count == 2+ state = tracker.disabled()["searxng"]+ assert state.retry_at is None+ assert "waited" in state.failure.reason+++def test_repeated_cooldowns_stop_after_the_consecutive_limit(tracker, clock):+ engine, sleeps = _always_rate_limited_run(tracker, clock, 60)+ # Three 60s cooldowns are waited out; the fourth failure ends the run.+ assert sum(sleeps) == pytest.approx(180, abs=0.1)+ assert engine.run.call_count == 4+ assert "cooldowns in a row" in tracker.disabled()["searxng"].failure.reason+++def test_retry_after_beyond_the_cap_is_not_waited_for(tracker, clock):+ engine, sleeps = _always_rate_limited_run(tracker, clock, 3600)+ assert sleeps == []+ assert engine.run.call_count == 1+++def test_a_successful_search_resets_the_cooldown_streak(clock):+ tracker = SearchEngineAvailability(+ clock=lambda: clock.now, max_consecutive_cooldowns=1+ )+ engine = Mock(last_search_failure=None)+ engine.run.side_effect = [+ RateLimitError("limit", retry_after=60),+ [],+ RateLimitError("limit", retry_after=60),+ ]+ with patch(FACTORY, return_value=engine):+ tool = make_tool("web_search", tracker)+ tool.invoke({"query": "one"})+ clock.now += 60+ tool.invoke({"query": "two"}) # answered, even if empty+ tool.invoke({"query": "three"})+ assert tracker.disabled()["searxng"].retry_at is not None+++def test_default_middleware_wait_honours_cancellation(clock):+ """Without an explicit ``wait``, the tracker's cancellation check runs."""+ from local_deep_research.advanced_search_system.tools import (+ search_availability,+ )++ checks = []++ def check_cancelled():+ checks.append(1)+ if len(checks) == 3:+ raise ResearchTerminatedException("cancelled")++ tracker = SearchEngineAvailability(+ clock=lambda: clock.now, check_cancelled=check_cancelled+ )+ tracker.disable("searxng", SearchFailure("offline", 300))+ sleeps = []++ def sleep(seconds):+ sleeps.append(seconds)+ clock.now += seconds++ request = ModelRequest(+ model=Mock(), messages=[], tools=[make_tool("web_search", tracker)]+ )+ with (+ patch.object(search_availability, "time", SimpleNamespace(sleep=sleep)),+ pytest.raises(ResearchTerminatedException),+ ):+ SearchAvailabilityMiddleware(tracker, "searxng").wrap_model_call(+ request, Mock()+ )+ assert len(sleeps) == 2+++def test_strategy_tracker_checks_the_research_termination_flag():+ strategy = strategy_module.LangGraphAgentStrategy(+ model=Mock(),+ search=Mock(last_search_failure=None),+ settings_snapshot={"search.tool": "searxng"},+ )+ with patch.object(+ strategy,+ "check_termination",+ side_effect=ResearchTerminatedException("cancelled"),+ ) as check:+ with pytest.raises(ResearchTerminatedException):+ strategy.engine_availability.check_cancelled()+ check.assert_called_once_with(strategy_module.CHECK_CONTEXT_ENTRY)diff --git a/tests/web/routers/test_benchmark_routes_coverage_port.py b/tests/web/routers/test_benchmark_routes_coverage_port.pyindex 80bfd0356a..512875afcd 100644--- a/tests/web/routers/test_benchmark_routes_coverage_port.py+++ b/tests/web/routers/test_benchmark_routes_coverage_port.py@@ -982,6 +982,43 @@ class TestGetBenchmarkHistory:assert data["runs"][0]["avg_processing_time"] == 15.5assert data["runs"][0]["avg_search_results"] == 20+ def test_history_does_not_count_skipped_searches_as_requests(self):+ """Searches skipped for an unavailable engine sent no request."""+ from local_deep_research.metrics.search_tracker import (+ SEARCH_STATUS_SKIPPED,+ )++ app = _make_app()+ run = self._make_run(5)+ mock_result = MagicMock()+ mock_result.research_id = "res-5"+ calls = []+ for status, count in [+ ("success", 10),+ ("error", 0),+ (SEARCH_STATUS_SKIPPED, 0),+ (SEARCH_STATUS_SKIPPED, 0),+ ]:+ call = MagicMock()+ call.research_id = "res-5"+ call.results_count = count+ call.success_status = status+ calls.append(call)++ with _patch_auth_and_db() as (_svc, _mgr, mock_db):+ mock_db.query.side_effect = _make_routed_query(+ runs=[run],+ avg_processing=None,+ results=[mock_result],+ search_calls=calls,+ )++ resp = _client(app).get("/benchmark/api/history")+ assert resp.status_code == 200, resp.text+ row = resp.json()["runs"][0]+ assert row["total_search_requests"] == 2+ assert row["avg_search_results"] == 10+def test_history_avg_processing_time_none(self):"""Branch: avg_result is None."""app = _make_app()diff --git a/tests/web_search_engines/engines/test_search_availability_signals.py b/tests/web_search_engines/engines/test_search_availability_signals.pynew file mode 100644index 0000000000..50744dee41--- /dev/null+++ b/tests/web_search_engines/engines/test_search_availability_signals.py@@ -0,0 +1,603 @@+"""Provider errors must survive engines that return [] instead of raising."""++from unittest.mock import Mock, patch++import pytest+import requests++from local_deep_research.advanced_search_system.tools.search_availability import (+ run_search,+)+from local_deep_research.web_search_engines.engine_availability import (+ SearchEngineAvailability,+)+from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+)+from local_deep_research.web_search_engines.engines.search_engine_semantic_scholar import (+ SemanticScholarSearchEngine,+)+from local_deep_research.web_search_engines.engines.search_engine_serper import (+ SerperSearchEngine,+)+++SEARX_GET = "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get"+++def response(status=200, body=b""):+ result = requests.Response()+ result.status_code = status+ result._content = body+ return result+++def searxng(**kwargs):+ return SearXNGSearchEngine(+ instance_url="http://localhost:8080",+ settings_snapshot={},+ programmatic_mode=True,+ delay_between_requests=0,+ **kwargs,+ )+++def test_blocked_localhost_is_initialized_only_once(monkeypatch):+ for env in (+ "LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS",+ "LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST",+ "LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL",+ ):+ monkeypatch.delenv(env, raising=False)+ tracker = SearchEngineAvailability()+ with patch(+ SEARX_GET, side_effect=ValueError("URL failed security validation")+ ) as get:+ first = run_search("searxng", "q1", searxng, tracker)+ second = run_search("searxng", "q2", searxng, tracker)+ get.assert_called_once()+ assert "private/loopback" in first+ assert "rest of this research" in second+ assert tracker.disabled()["searxng"].retry_at is None++[email protected]("during_initialization", [True, False])+def test_searxng_http_429_preserves_retry_after(during_initialization):+ limited = response(429)+ limited.headers["Retry-After"] = "720"+ replies = (+ [limited]+ if during_initialization+ else [response(), response(), limited]+ )+ with patch(SEARX_GET, side_effect=replies):+ engine = searxng()+ if not during_initialization:+ assert engine.run("query") == []+ assert engine.last_search_failure.cooldown_seconds == 720+ assert engine.last_search_failure.reason == "Rate limit reached"+++ "body,result_count",+ [+ (b'{"results": []}', 0),+ # SearXNG routinely lists suspended backends; the JSON does not say+ # which backends were queried, so this is an empty search, not a+ # failure of every backend.+ (+ b'{"results": [], "unresponsive_engines": [["google", "rate limited"]]}',+ 0,+ ),+ (+ b'{"results": [{"url": "https://example.org", "title": "Result"}], "unresponsive_engines": [["google", "rate limited"]]}',+ 1,+ ),+ ],+)+def test_searxng_json_unresponsive_backends_do_not_disable_engine(+ body, result_count+):+ with patch(+ SEARX_GET, side_effect=[response(), response(), response(body=body)]+ ):+ engine = searxng(result_format="json")+ results = engine.run("query")+ assert len(results) == result_count+ assert engine.last_search_failure is None+++def test_searxng_html_unresponsive_backend_is_an_empty_search():+ html = b'<article class="result"><h3><a href="/stats?engine=google">Backend failed</a></h3></article>'+ with patch(+ SEARX_GET, side_effect=[response(), response(), response(body=html)]+ ):+ engine = searxng()+ assert engine.run("query") == []+ assert engine.last_search_failure is None+++def test_unresolvable_instance_host_gets_a_finite_cooldown(monkeypatch):+ """A DNS failure fails SSRF validation but must not disable for the run."""+ import socket+ from types import SimpleNamespace++ from local_deep_research.security import ssrf_validator++ for env in (+ "LDR_SEARCH_ALLOW_PRIVATE_ENGINE_URLS",+ "LDR_SEARCH_PRIVATE_ENGINE_URL_ALLOWLIST",+ "LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL",+ ):+ monkeypatch.delenv(env, raising=False)++ def unresolvable(*args, **kwargs):+ raise socket.gaierror(socket.EAI_NONAME, "Name or service not known")++ # The real safe_get runs and refuses at validation, before any request.+ monkeypatch.setattr(ssrf_validator.socket, "getaddrinfo", unresolvable)+ clock = SimpleNamespace(now=0.0)+ tracker = SearchEngineAvailability(clock=lambda: clock.now)+ factory = Mock(+ side_effect=lambda: SearXNGSearchEngine(+ instance_url="https://searx.example.org",+ settings_snapshot={},+ programmatic_mode=True,+ delay_between_requests=0,+ )+ )+ first = run_search("searxng", "q", factory, tracker)+ assert "security validation" in first+ assert "rest of this research" not in first+ assert tracker.disabled()["searxng"].retry_at is not None+ clock.now = 300+ run_search("searxng", "q", factory, tracker)+ assert factory.call_count == 2++[email protected]("outer", [True, False])+def test_wikipedia_non_json_response_is_classified_as_rate_limit(outer):+ from local_deep_research.web_search_engines.engines.search_engine_wikipedia import (+ WikipediaSearchEngine,+ )++ module = (+ "local_deep_research.web_search_engines.engines.search_engine_wikipedia"+ )+ decode_error = requests.exceptions.JSONDecodeError("Expecting value", "", 0)+ engine = WikipediaSearchEngine(settings_snapshot={}, llm=Mock())+ engine.rate_tracker = Mock(enabled=False)+ engine.rate_tracker.apply_rate_limit.return_value = 0.0+ with (+ patch(+ f"{module}.wikipedia.search",+ side_effect=decode_error if outer else None,+ return_value=["Title"],+ ),+ patch(f"{module}.wikipedia.summary", side_effect=decode_error),+ ):+ assert engine._get_previews("query") == []+ assert engine.last_search_failure.reason.startswith("Rate limit")+ assert engine.last_search_failure.cooldown_seconds == 300+ engine.close()+++def test_semantic_scholar_mounted_retry_exhausted_on_429_is_a_rate_limit(+ monkeypatch,+):+ """Production path: the engine's mounted Retry turns 429s into RetryError.++ session.get is NOT patched: the engine's own SafeSession, HTTPAdapter+ and Retry(status_forcelist=[429, ...]) run; only DNS and urllib3's+ per-attempt request are stubbed, so nothing leaves the process.+ """+ import socket++ import urllib3+ from urllib3.connectionpool import HTTPConnectionPool++ def public_address(host, *args, **kwargs):+ return [+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 443))+ ]++ attempts = []++ def respond(self, conn, method, url, **kwargs):+ attempts.append(url)+ return urllib3.HTTPResponse(+ body=b"", status=429, headers={}, preload_content=False+ )++ from local_deep_research.security import dns_pinning++ # SSRF validation resolves via socket.getaddrinfo; connect-time pinning+ # uses the resolver dns_pinning captured at import. Stub both.+ monkeypatch.setattr(socket, "getaddrinfo", public_address)+ monkeypatch.setattr(dns_pinning, "_real_getaddrinfo", public_address)+ monkeypatch.setattr(HTTPConnectionPool, "_make_request", respond)+ engine = SemanticScholarSearchEngine(+ llm=Mock(), settings_snapshot={}, retry_backoff_factor=0+ )+ monkeypatch.setattr(engine, "_respect_rate_limit", lambda: None)+ assert engine._direct_search("query") == []+ assert len(attempts) == engine.max_retries + 1+ assert engine.last_search_failure.reason == "Rate limit reached"+ assert engine.last_search_failure.cooldown_seconds == 300+ engine.close()+++def test_semantic_scholar_retry_after_wait_is_bounded(monkeypatch):+ """A six-hour Retry-After must not park the agent's tool call for hours."""+ import socket++ import urllib3+ from urllib3.connectionpool import HTTPConnectionPool+ from urllib3.util import retry as urllib3_retry++ from local_deep_research.security import dns_pinning++ def public_address(host, *args, **kwargs):+ return [+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 443))+ ]++ def respond(self, conn, method, url, **kwargs):+ return urllib3.HTTPResponse(+ body=b"",+ status=429,+ headers={"Retry-After": "21600"},+ preload_content=False,+ )++ sleeps = []+ monkeypatch.setattr(socket, "getaddrinfo", public_address)+ monkeypatch.setattr(dns_pinning, "_real_getaddrinfo", public_address)+ monkeypatch.setattr(HTTPConnectionPool, "_make_request", respond)+ monkeypatch.setattr(urllib3_retry.time, "sleep", sleeps.append)+ engine = SemanticScholarSearchEngine(llm=Mock(), settings_snapshot={})+ monkeypatch.setattr(engine, "_respect_rate_limit", lambda: None)+ assert engine._direct_search("query") == []+ assert len(sleeps) == engine.max_retries+ assert max(sleeps) <= 30+ assert engine.last_search_failure.reason == "Rate limit reached"+ engine.close()+++def test_semantic_scholar_swallowed_rate_limit_keeps_signal():+ engine = SemanticScholarSearchEngine(+ llm=Mock(), settings_snapshot={}, programmatic_mode=True+ )+ limited = response(429)+ limited.headers["Retry-After"] = "120"+ with (+ patch.object(engine, "_respect_rate_limit"),+ patch.object(engine.session, "get", return_value=limited),+ ):+ assert engine._direct_search("query") == []+ assert engine.last_search_failure.cooldown_seconds == 120+ engine.close()+++ "api_key,run_long", [("invalid-key", True), (None, False)]+)+def test_semantic_scholar_bare_403_with_api_key_is_denied_credentials(+ api_key, run_long+):+ """S2 answers a bad x-api-key with 403 {"message":"Forbidden"} only."""+ engine = SemanticScholarSearchEngine(+ llm=Mock(),+ settings_snapshot={},+ programmatic_mode=True,+ api_key=api_key,+ )+ forbidden = response(403, b'{"message":"Forbidden"}')+ with (+ patch.object(engine, "_respect_rate_limit"),+ patch.object(engine.session, "get", return_value=forbidden),+ ):+ assert engine._direct_search("query") == []+ failure = engine.last_search_failure+ if run_long:+ assert failure.cooldown_seconds is None+ assert "check credentials" in failure.reason+ else:+ # Without a key the 403 cannot be about the key: a block.+ assert failure.cooldown_seconds == 300+ engine.close()+++def test_bare_403_stays_a_block_for_engines_that_did_not_opt_in():+ engine = SerperSearchEngine(api_key="test-api-key", settings_snapshot={})+ assert engine.bare_403_means_bad_api_key is False+ engine._record_search_failure(+ requests.HTTPError(response=response(403, b'{"message":"Forbidden"}'))+ )+ assert engine.last_search_failure.cooldown_seconds == 300+ engine.close()+++def test_serper_retry_after_survives_base_error_handling():+ engine = SerperSearchEngine(api_key="test-api-key", settings_snapshot={})+ engine.programmatic_mode = True+ engine.rate_tracker = Mock(enabled=False)+ limited = response(429)+ limited.headers["Retry-After"] = "240"+ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_serper.safe_post",+ return_value=limited,+ ):+ assert engine.run("query") == []+ assert engine.last_search_failure.cooldown_seconds == 240+ engine.close()+++ "module_name,class_name,method,args,request_name,error",+ [+ (+ "wikipedia",+ "WikipediaSearchEngine",+ "_get_previews",+ ("query",),+ "wikipedia.search",+ requests.HTTPError(response=response(429)),+ ),+ (+ "wikinews",+ "WikinewsSearchEngine",+ "_fetch_search_results",+ ("query", 0),+ "safe_get",+ requests.HTTPError(response=response(429)),+ ),+ (+ "wayback",+ "WaybackSearchEngine",+ "_get_wayback_snapshots",+ ("https://example.org",),+ "safe_get",+ requests.ConnectionError("offline"),+ ),+ ],+)+def test_other_swallowed_request_errors_preserve_health(+ module_name, class_name, method, args, request_name, error+):+ import importlib++ module_path = f"local_deep_research.web_search_engines.engines.search_engine_{module_name}"+ module = importlib.import_module(module_path)+ engine = getattr(module, class_name)(settings_snapshot={}, llm=Mock())+ with patch(f"{module_path}.{request_name}", side_effect=error):+ assert getattr(engine, method)(*args) == []+ assert engine.last_search_failure is not None+ engine.close()+++ "status,delay", [(429, 180), (401, None), (503, 180), (500, 60)]+)+def test_openalex_response_failure_survives_run(status, delay):+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (+ OpenAlexSearchEngine,+ )++ engine = OpenAlexSearchEngine(+ llm=Mock(), settings_snapshot={}, api_key="test-key"+ )+ engine.programmatic_mode = True+ failed = response(status)+ failed.headers["Retry-After"] = "180"+ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_openalex.safe_get",+ return_value=failed,+ ):+ assert engine.run("query") == []+ assert engine.last_search_failure.cooldown_seconds == delay+ engine.close()++[email protected]("during_initialization", [True, False])+def test_full_content_wrapper_preserves_failure_and_prevents_recreation(+ during_initialization,+):+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ limited = response(429)+ limited.headers["Retry-After"] = "420"+ replies = (+ [limited]+ if during_initialization+ else [response(), response(), limited]+ )+ factory = Mock(+ side_effect=lambda: FullSearchResults(llm=None, web_search=searxng())+ )+ tracker = SearchEngineAvailability()+ with patch(SEARX_GET, side_effect=replies):+ first = run_search("searxng", "one", factory, tracker)+ second = run_search("searxng", "two", factory, tracker)+ assert "Rate limit reached" in first+ assert "for 420s" in second+ factory.assert_called_once()+++def test_semantic_scholar_successful_empty_fallback_clears_prior_failure():+ engine = SemanticScholarSearchEngine(llm=Mock(), settings_snapshot={})+ with (+ patch.object(engine, "_respect_rate_limit"),+ patch.object(+ engine.session,+ "get",+ side_effect=[response(429), response(body=b'{"data": []}')],+ ),+ ):+ assert engine._direct_search("one") == []+ assert engine.last_search_failure is not None+ assert engine._direct_search("two") == []+ assert engine.last_search_failure is None+ engine.close()+++def test_pubmed_successful_empty_fallback_clears_prior_failure():+ from local_deep_research.web_search_engines.engines.search_engine_pubmed import (+ PubMedSearchEngine,+ )++ engine = PubMedSearchEngine(llm=Mock(), settings_snapshot={})+ engine.rate_tracker = Mock(enabled=False)+ engine.rate_tracker.apply_rate_limit.return_value = 0.0+ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_pubmed.safe_get",+ side_effect=[+ requests.Timeout(),+ response(body=b'{"esearchresult": {"idlist": [], "count": "0"}}'),+ ],+ ):+ assert engine._search_pubmed("one") == []+ assert engine.last_search_failure is not None+ assert engine._search_pubmed("two") == []+ assert engine.last_search_failure is None+ engine.close()++[email protected]("status,delay", [(429, 480), (500, 60)])+def test_pubmed_required_summaries_failure_survives_base_run(status, delay):+ from local_deep_research.web_search_engines.engines.search_engine_pubmed import (+ PubMedSearchEngine,+ )++ engine = PubMedSearchEngine(llm=Mock(), settings_snapshot={})+ engine.programmatic_mode = True+ engine.rate_tracker = Mock(enabled=False)+ engine.rate_tracker.apply_rate_limit.return_value = 0.0+ failed = response(status)+ failed.headers["Retry-After"] = "480"+ with (+ patch.object(engine, "_optimize_query_for_pubmed", return_value="q"),+ patch.object(+ engine, "_adaptive_search", return_value=(["123"], "test")+ ),+ patch.object(engine, "_get_article_abstracts", return_value={}),+ patch(+ "local_deep_research.web_search_engines.engines.search_engine_pubmed.safe_get",+ return_value=failed,+ ),+ ):+ assert engine.run("query") == []+ assert engine.last_search_failure.cooldown_seconds == delay+ engine.close()+++def test_arxiv_translated_rate_limit_preserves_retry_after():+ from local_deep_research.web_search_engines.engines.search_engine_arxiv import (+ ArXivSearchEngine,+ )++ engine = ArXivSearchEngine(llm=Mock(), settings_snapshot={})+ engine.programmatic_mode = True+ engine.rate_tracker = Mock(enabled=False)+ failed = response(429)+ failed.headers["Retry-After"] = "540"+ with patch.object(+ engine,+ "_get_search_results",+ side_effect=requests.HTTPError("429 rate limited", response=failed),+ ):+ assert engine.run("query") == []+ assert engine.last_search_failure.cooldown_seconds == 540+ engine.close()++[email protected]("closest_only", [True, False])+def test_wayback_rate_limit_preserves_retry_after(closest_only):+ from local_deep_research.web_search_engines.engines.search_engine_wayback import (+ WaybackSearchEngine,+ )++ engine = WaybackSearchEngine(+ llm=Mock(), settings_snapshot={}, closest_only=closest_only+ )+ engine.programmatic_mode = True+ engine.rate_tracker = Mock(enabled=False)+ failed = response(429)+ failed.headers["Retry-After"] = "600"+ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_wayback.safe_get",+ return_value=failed,+ ):+ assert engine.run("https://example.org") == []+ assert engine.last_search_failure.cooldown_seconds == 600+ engine.close()+++def test_wikipedia_summary_request_failure_is_not_a_successful_empty_search():+ from local_deep_research.web_search_engines.engines.search_engine_wikipedia import (+ WikipediaSearchEngine,+ )++ engine = WikipediaSearchEngine(settings_snapshot={})+ engine.programmatic_mode = True+ with (+ patch(+ "local_deep_research.web_search_engines.engines.search_engine_wikipedia.wikipedia.search",+ return_value=["Title"],+ ),+ patch(+ "local_deep_research.web_search_engines.engines.search_engine_wikipedia.wikipedia.summary",+ side_effect=requests.Timeout(),+ ),+ ):+ assert engine.run("query") == []+ assert "timed out" in engine.last_search_failure.reason+ engine.close()+++def test_serper_invalid_payload_is_not_a_successful_empty_search():+ engine = SerperSearchEngine(api_key="test-key", settings_snapshot={})+ engine.programmatic_mode = True+ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_serper.safe_post",+ return_value=response(body=b"[]"),+ ):+ assert engine.run("query") == []+ assert engine.last_search_failure is not None+ engine.close()+++def test_openalex_bad_query_does_not_mark_the_engine_down():+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (+ OpenAlexSearchEngine,+ )++ engine = OpenAlexSearchEngine(+ llm=Mock(), settings_snapshot={}, api_key="test-key"+ )+ engine.programmatic_mode = True+ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_openalex.safe_get",+ return_value=response(400),+ ):+ assert engine.run("query with (bad syntax") == []+ assert engine.last_search_failure is None+ engine.close()+++def test_wayback_non_json_reply_for_one_url_does_not_mark_the_engine_down():+ from local_deep_research.web_search_engines.engines.search_engine_wayback import (+ WaybackSearchEngine,+ )++ engine = WaybackSearchEngine(llm=Mock(), settings_snapshot={})+ blocked = response(403, body=b"<html>Blocked Site Error</html>")+ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_wayback.safe_get",+ return_value=blocked,+ ):+ assert engine._get_wayback_snapshots("https://blocked.example") == []+ assert engine.last_search_failure is None+ engine.close()diff --git a/tests/web_search_engines/test_engine_availability.py b/tests/web_search_engines/test_engine_availability.pynew file mode 100644index 0000000000..f1ef5eef03--- /dev/null+++ b/tests/web_search_engines/test_engine_availability.py@@ -0,0 +1,461 @@+"""Availability transitions use a fake clock, never network requests or sleeps."""++from concurrent.futures import ThreadPoolExecutor+from datetime import UTC, datetime+from email.utils import format_datetime+from types import SimpleNamespace+from unittest.mock import Mock, patch++import pytest+import requests++from local_deep_research.web_search_engines.engine_availability import (+ MAX_COOLDOWN_SECONDS,+ SearchEngineAvailability,+ SearchFailure,+ available_tool_names,+ engine_failure,+ failure_from_exception,+ retry_after_seconds,+)+from local_deep_research.web_search_engines.rate_limiting import RateLimitError+from local_deep_research.web_search_engines.search_engine_base import (+ BaseSearchEngine,+)+++def clock():+ return SimpleNamespace(monotonic=100.0, wall=1_790_000_000.0)+++def tracker(clock):+ return SearchEngineAvailability(+ clock=lambda: clock.monotonic, wall_clock=lambda: clock.wall+ )+++def test_cooldown_logs_one_transition_and_expires_on_monotonic_time(clock):+ events = Mock()+ tracker = SearchEngineAvailability(+ events, clock=lambda: clock.monotonic, wall_clock=lambda: clock.wall+ )+ first = tracker.disable("pubmed", SearchFailure("Rate limit reached", 300))+ assert tracker.disable("pubmed", SearchFailure("duplicate", 900)) == first+ assert events.call_count == 1+ message, _, meta = events.call_args.args+ assert "for 300s" in message and "retry available at" in message+ assert meta["disabled_at"] == clock.wall+ assert meta["retry_at"] == clock.wall + 300+ clock.wall += 86_400 # Wall-clock correction cannot prematurely reopen it.+ clock.monotonic += 299+ assert "pubmed" in tracker.disabled()+ clock.monotonic += 1+ assert tracker.disabled() == {}+ assert events.call_args.args[2]["status"] == "retry_available"+ assert events.call_count == 2+ assert tracker.disabled() == {}+ assert events.call_count == 2+++def test_configuration_failure_is_local_to_research(tracker, clock):+ state = tracker.disable("searxng", SearchFailure("URL blocked", None))+ clock.monotonic += 1_000_000+ assert tracker.disabled()["searxng"] == state+ assert "rest of this research" in state.describe()+ assert state.retry_at is None+ assert SearchEngineAvailability().disabled() == {}+++def test_concurrent_disablement_is_reported_once(clock):+ events = Mock()+ tracker = SearchEngineAvailability(events)+ with ThreadPoolExecutor(max_workers=4) as pool:+ states = list(+ pool.map(+ lambda _: tracker.disable("searxng", SearchFailure("offline")),+ range(20),+ )+ )+ assert len(set(states)) == 1+ assert events.call_count == 1+++ "value", [None, "invalid", "nan", "inf", -1, 0, True, "1e100", 10**500]+)+def test_invalid_retry_after_ignored(value):+ assert retry_after_seconds(value) is None+++def test_retry_after_seconds_and_http_date(clock):+ assert retry_after_seconds("120") == 120+ date = format_datetime(+ datetime.fromtimestamp(clock.wall + 180, UTC), usegmt=True+ )+ assert retry_after_seconds(date, now=clock.wall) == 180+++ "error,reason,delay",+ [+ (RateLimitError("secret", retry_after=90), "Rate limit", 90),+ (requests.Timeout("secret"), "timed out", 60),+ (requests.ConnectionError("secret"), "connect", 60),+ # The validator also refuses unresolvable hosts, so a transient DNS+ # failure must not disable the engine for the whole research.+ (ValueError("URL failed security validation: secret"), "blocked", 300),+ ],+)+def test_classification_uses_safe_reasons(error, reason, delay):+ failure = failure_from_exception(error)+ assert reason in failure.reason+ assert "secret" not in failure.reason+ assert failure.cooldown_seconds == delay+++ "status,delay",+ [(401, None), (402, None), (403, 300), (429, 480), (503, 480), (500, 60)],+)+def test_http_failure_classification_preserves_retry_after(status, delay):+ response = requests.Response()+ response.status_code = status+ response.headers["Retry-After"] = "480"+ failure = failure_from_exception(+ requests.HTTPError(+ "https://user:secret@provider/?api_key=secret", response=response+ )+ )+ assert "secret" not in failure.reason+ assert failure.cooldown_seconds == delay+++ "body,headers",+ [+ (b'{"error": "Invalid API key"}', {}),+ (b"Unauthorized: subscription expired", {}),+ (b"", {"WWW-Authenticate": "Bearer"}),+ ],+)+def test_403_that_is_clearly_about_credentials_lasts_the_run(body, headers):+ response = requests.Response()+ response.status_code = 403+ response._content = body+ response.headers.update(headers)+ failure = failure_from_exception(requests.HTTPError(response=response))+ assert failure.cooldown_seconds is None+ assert "HTTP 403" in failure.reason+++def test_403_block_page_is_a_cooldown_not_a_run_long_disable():+ response = requests.Response()+ response.status_code = 403+ response._content = b"<html>Access denied: automated traffic</html>"+ # The request URL may name api_key; only the response body counts.+ error = requests.HTTPError("https://p/?api_key=x", response=response)+ assert failure_from_exception(error).cooldown_seconds == 300+++def test_cooldown_up_to_the_cap_is_kept(tracker, clock):+ state = tracker.disable(+ "pubmed", SearchFailure("Rate limit", MAX_COOLDOWN_SECONDS)+ )+ assert state.retry_at - state.disabled_at == MAX_COOLDOWN_SECONDS+ clock.monotonic += MAX_COOLDOWN_SECONDS+ assert tracker.disabled() == {}+++def test_provider_retry_after_beyond_the_cap_disables_for_the_run(+ tracker, clock+):+ """Retrying every 10 min against "wait an hour" would only fail again."""+ state = tracker.disable("pubmed", SearchFailure("Rate limit", 3600))+ assert state.retry_at is None+ assert "Rate limit" in state.failure.reason+ assert f"longer than {MAX_COOLDOWN_SECONDS}s" in state.failure.reason+ clock.monotonic += 86_400+ assert "pubmed" in tracker.disabled()+++def test_consecutive_cooldowns_end_in_a_run_long_disable(clock):+ tracker = SearchEngineAvailability(+ clock=lambda: clock.monotonic,+ wall_clock=lambda: clock.wall,+ max_consecutive_cooldowns=3,+ )+ for _ in range(3):+ state = tracker.disable("searxng", SearchFailure("Rate limit", 300))+ assert state.retry_at is not None+ clock.monotonic += 300+ assert tracker.disabled() == {}+ state = tracker.disable("searxng", SearchFailure("Rate limit", 300))+ assert state.retry_at is None+ assert "still failing after 3 cooldowns in a row" in state.failure.reason+++def test_successful_search_resets_the_cooldown_streak(clock):+ tracker = SearchEngineAvailability(+ clock=lambda: clock.monotonic,+ wall_clock=lambda: clock.wall,+ max_consecutive_cooldowns=2,+ )+ for _ in range(5):+ state = tracker.disable("searxng", SearchFailure("offline", 60))+ assert state.retry_at is not None+ clock.monotonic += 60+ tracker.disabled()+ tracker.record_success("searxng")+ # Streaks are per engine.+ tracker.disable("pubmed", SearchFailure("offline", 60))+ clock.monotonic += 60+ tracker.disabled()+ tracker.disable("pubmed", SearchFailure("offline", 60))+ clock.monotonic += 60+ tracker.disabled()+ assert (+ tracker.disable("pubmed", SearchFailure("offline", 60)).retry_at is None+ )+ assert (+ tracker.disable("searxng", SearchFailure("offline", 60)).retry_at+ is not None+ )+++def test_wait_budget_counts_overlapping_waiters_once(clock):+ tracker = SearchEngineAvailability(+ clock=lambda: clock.monotonic,+ wall_clock=lambda: clock.wall,+ wait_budget_seconds=900,+ )+ with tracker.waiting():+ with tracker.waiting():+ clock.monotonic += 100+ assert tracker.wait_budget_remaining() == 800+ clock.monotonic += 100+ clock.monotonic += 1000 # time not spent waiting is free+ assert tracker.wait_budget_remaining() == 700+++def test_end_cooldowns_disables_only_cooling_engines(tracker):+ tracker.disable("searxng", SearchFailure("Rate limit", 300))+ tracker.disable("pubmed", SearchFailure("Bad key", None))+ tracker.end_cooldowns({"searxng", "pubmed", "arxiv"})+ disabled = tracker.disabled()+ assert disabled["searxng"].retry_at is None+ assert "Rate limit" in disabled["searxng"].failure.reason+ assert "waited" in disabled["searxng"].failure.reason+ assert disabled["pubmed"].failure.reason == "Bad key"+ assert "arxiv" not in disabled+++def test_unknown_error_and_empty_engine_are_not_assumed_rate_limited():+ assert failure_from_exception(ValueError("bad query")) is None+ assert engine_failure(SimpleNamespace()) is None+++class FailingEngine(BaseSearchEngine):+ def _get_previews(self, query):+ raise RateLimitError("test", retry_after=120)++[email protected]("retry_enabled,attempts", [(True, 3), (False, 1)])+def test_swallowed_rate_limit_survives_base_retry_exhaustion(+ retry_enabled, attempts+):+ engine = FailingEngine(settings_snapshot={}, programmatic_mode=True)+ engine.rate_tracker = Mock(enabled=retry_enabled)+ engine.rate_tracker.get_wait_time.return_value = 0+ engine._get_previews = Mock(+ side_effect=RateLimitError("test", retry_after=120)+ )+ assert engine.run("query") == []+ assert engine._get_previews.call_count == attempts+ assert engine.last_search_failure.cooldown_seconds == 120+++def test_retry_success_clears_failure_signal():+ engine = FailingEngine(settings_snapshot={}, programmatic_mode=True)+ engine.rate_tracker = Mock(enabled=True)+ engine.rate_tracker.get_wait_time.return_value = 0+ engine.last_search_failure = SearchFailure("old failure")+ engine._get_previews = Mock(+ side_effect=[RateLimitError("test"), [{"title": "result"}]]+ )+ assert engine.run("query") == [{"title": "result"}]+ assert engine.last_search_failure is None+++def test_new_failure_replaces_expired_disablement_without_a_prior_poll(+ tracker, clock+):+ first = tracker.disable("pubmed", SearchFailure("old failure", 60))+ clock.monotonic += 60+ clock.wall += 60+ second = tracker.disable("pubmed", SearchFailure("new failure", 120))+ assert second != first+ assert second.failure.reason == "new failure"+ assert second.retry_at == clock.wall + 120+ assert tracker.disabled()["pubmed"] == second++[email protected]("engine", [None, ""])+def test_missing_engine_name_is_never_recorded(tracker, engine):+ events = Mock()+ tracker._on_change = events+ state = tracker.disable(engine, SearchFailure("blocked", None))+ assert state.describe() == "Search failed: blocked"+ assert tracker.disabled() == {}+ events.assert_not_called()+ names = ["fetch_content", "research_subtopic", "search_pubmed"]+ # Even a stray None key must not hide non-search tools, which map to+ # None in engine_for_tool.+ assert available_tool_names(names, None, {None: object()}) == names+++def _exhausted(status):+ """Drive a real HTTPAdapter + Retry until urllib3 gives up on ``status``.++ Only the pool's per-attempt request is stubbed, so urllib3's own retry+ loop (status_forcelist, increment, MaxRetryError) runs unmodified.+ """+ import urllib3+ from requests.adapters import HTTPAdapter+ from urllib3.connectionpool import HTTPConnectionPool+ from urllib3.util.retry import Retry++ session = requests.Session()+ session.mount(+ "http://",+ HTTPAdapter(+ max_retries=Retry(+ total=2,+ backoff_factor=0,+ status_forcelist=[429, 500, 502, 503, 504],+ allowed_methods={"GET"},+ )+ ),+ )++ def respond(self, conn, method, url, **kwargs):+ return urllib3.HTTPResponse(+ body=b"", status=status, headers={}, preload_content=False+ )++ with patch.object(HTTPConnectionPool, "_make_request", respond):+ with pytest.raises(requests.exceptions.RetryError) as raised:+ session.get("http://provider.invalid/search", timeout=1)+ session.close()+ return raised.value+++def test_exhausted_429_retries_are_a_rate_limit():+ failure = failure_from_exception(_exhausted(429))+ assert failure.reason == "Rate limit reached"+ assert failure.cooldown_seconds == 300+++def test_exhausted_5xx_retries_stay_generic():+ assert failure_from_exception(_exhausted(503)) is None+++def test_seconds_until_retry_reports_soonest_finite_cooldown(tracker, clock):+ tracker.disable("pubmed", SearchFailure("offline", 90))+ tracker.disable("arxiv", SearchFailure("offline", 30))+ tracker.disable("searxng", SearchFailure("blocked", None))+ assert tracker.seconds_until_retry({"pubmed", "arxiv"}) == 30+ assert tracker.seconds_until_retry({"searxng"}) is None+ assert tracker.seconds_until_retry({"wikipedia"}) is None+ clock.monotonic += 40+ assert tracker.seconds_until_retry({"pubmed", "arxiv"}) == 0+++def _http_error(status):+ response = requests.Response()+ response.status_code = status+ return requests.HTTPError(response=response)++[email protected]("status", [400, 414, 422])+def test_query_specific_http_error_is_not_an_engine_failure(status):+ engine = FailingEngine(settings_snapshot={}, programmatic_mode=True)+ engine._record_search_failure(_http_error(status))+ assert engine.last_search_failure is None+ engine._record_search_failure(_http_error(500))+ assert engine.last_search_failure is not None+++class _PreviewEngine(BaseSearchEngine):+ def _get_previews(self, query):+ # One follow-up request failed; the search itself answered.+ self._record_search_failure(requests.Timeout())+ return [{"title": "a"}, {"title": "b"}]++ def _get_full_content(self, items):+ return items+++def test_results_dropped_by_the_relevance_filter_are_not_a_failure():+ engine = _PreviewEngine(settings_snapshot={}, programmatic_mode=True)+ engine.rate_tracker = Mock(enabled=False)+ engine.enable_llm_relevance_filter = True+ engine.llm = Mock()+ with patch.object(engine, "_filter_for_relevance", return_value=[]):+ assert engine.run("query") == []+ assert engine.last_search_failure is None+++def test_error_after_previews_arrived_is_not_an_engine_failure():+ engine = _PreviewEngine(settings_snapshot={}, programmatic_mode=True)+ engine.rate_tracker = Mock(enabled=False)+ engine._content_filters = [Mock()]+ engine._content_filters[0].filter_results.side_effect = KeyError("x")+ assert engine.run("query") == []+ assert engine.last_search_failure is None+++def test_error_before_previews_is_still_an_engine_failure():+ engine = _PreviewEngine(settings_snapshot={}, programmatic_mode=True)+ engine.rate_tracker = Mock(enabled=False)+ engine._get_previews = Mock(side_effect=requests.ConnectionError())+ assert engine.run("query") == []+ assert "connect" in engine.last_search_failure.reason+++def test_delegation_is_not_offered_when_only_fetch_remains():+ names = [+ "web_search",+ "search_pubmed",+ "fetch_content",+ "research_subtopic",+ ]+ disabled = {"searxng": object(), "pubmed": object()}+ assert available_tool_names(names, "searxng", disabled) == ["fetch_content"]+ # While any search tool works, delegation stays.+ assert available_tool_names(names, "searxng", {"pubmed": object()}) == [+ "web_search",+ "fetch_content",+ "research_subtopic",+ ]+ # A toolbox configured without search is not availability's business.+ assert available_tool_names(+ ["fetch_content", "research_subtopic"], "searxng", disabled+ ) == ["fetch_content", "research_subtopic"]+++def test_run_long_failure_upgrades_an_active_cooldown(tracker, clock):+ events = Mock()+ tracker._on_change = events+ tracker.disable("pubmed", SearchFailure("offline", 60))+ # A search already in flight comes back with HTTP 401.+ upgraded = tracker.disable("pubmed", SearchFailure("Denied", None))+ assert upgraded.retry_at is None+ assert upgraded.failure.reason == "Denied"+ assert events.call_count == 2+ clock.monotonic += 3600+ assert tracker.disabled()["pubmed"] == upgraded+ # A cooldown never downgrades a run-long disable.+ assert tracker.disable("pubmed", SearchFailure("offline", 60)) == upgraded+ assert events.call_count == 2diff --git a/tests/web_search_engines/test_search_engine_base_retry.py b/tests/web_search_engines/test_search_engine_base_retry.pyindex 95cf6a756b..224e482d78 100644--- a/tests/web_search_engines/test_search_engine_base_retry.py+++ b/tests/web_search_engines/test_search_engine_base_retry.py@@ -63,7 +63,7 @@ class TestRetryOnRateLimit:assert results[0]["title"] == "Success"def test_exhausted_retries_returns_empty_list(self):- """All 3 attempts fail with RateLimitError -> RetryError caught -> returns []."""+ """All 3 attempts fail with RateLimitError -> re-raised, caught -> returns []."""def always_fail(query):raise RateLimitError("always rate limited")