~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
fix(research): prevent premature cooldown and subagent cutoffs (#6930)
LearningCircuitfbd6bb1a5f2d
diff --git a/changelog.d/+search-engine-availability.feature.md b/changelog.d/+search-engine-availability.feature.mdindex 4a10b656df..a3d0bbb806 100644--- a/changelog.d/+search-engine-availability.feature.md+++ b/changelog.d/+search-engine-availability.feature.md@@ -1,14 +1,20 @@LangGraph research temporarily removes failed or rate-limited search enginesfrom action choices, shares cooldowns across subagents, and shows disablereasons 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+engine is only cooling down, the agent waits for the first one to come back+instead of stopping or answering without search; only+disables for the whole run can end it. Cooldown waits share a configurable+one-hour budget per run, including when a concurrent search starts another+cooldown during a wait. Repeated temporary failures and provider `Retry-After`+values keep their cooldowns while budget remains; a `Retry-After` longer than a+day (or than the wait budget, if larger) disables the engine for the run. The+subagent deadline is configurable and defaults to two hours, with enough time+for the cooldown budget plus 30 minutes of work; cancelling a run stops the+lead agent waiting for running subagents within a minute, and each of those+subagents before its next model call (one in the middle of a model or tool+call can take until that call returns). 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, alongwith any engine whose exceptions propagate through the base search pipeline);diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex 466b87c236..8be0ec683b 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -120,10 +120,12 @@ They are not available in the Web UI because they are needed to start the applic| `general.knowledge_accumulation` | `LDR_GENERAL_KNOWLEDGE_ACCUMULATION` | `ITERATION` | How to compress accumulated knowledge between search iterations. 'ITERATION': Compress and carry forward knowledge after each iteration completes (default). 'QUESTION': Compress after every individual question within an iteration (more aggressive, saves tokens). 'NO_KNOWLEDGE': Start fresh each iteration with no carried-forward context. | APP || `general.knowledge_accumulation_context_limit` | `LDR_GENERAL_KNOWLEDGE_ACCUMULATION_CONTEXT_LIMIT` | `2000000` | Maximum character count for accumulated knowledge context. Reserved for future use — not currently enforced at runtime. | APP || `general.output_instructions` | `LDR_GENERAL_OUTPUT_INSTRUCTIONS` | `` | Customize how research outputs are formatted: language, tone, style, formatting preferences, audience level, etc. Examples: 'Respond in Spanish with formal tone' \| 'Use simple language for beginners' \| 'Be concise with bullet points'. Leave empty for default English output. | APP |+| `langgraph_agent.cooldown_wait_budget_seconds` | `LDR_LANGGRAPH_AGENT_COOLDOWN_WAIT_BUDGET_SECONDS` | `3600` | Total time in seconds one LangGraph research run may spend waiting when all usable search engines are cooling down. Parallel waits share the same budget. Default is one hour; increase it for providers with long rate limits. This does not limit LLM inference or the overall research duration. Set to 0 to skip cooldown waiting and use the sources already gathered. | SEARCH || `langgraph_agent.include_sub_research` | `LDR_LANGGRAPH_AGENT_INCLUDE_SUB_RESEARCH` | `true` | Enable parallel subagent research. When enabled, the agent can decompose complex questions into subtopics and research them simultaneously using separate subagents. | SEARCH || `langgraph_agent.max_iterations` | `LDR_LANGGRAPH_AGENT_MAX_ITERATIONS` | `50` | Maximum number of agent reasoning cycles (each cycle = one LLM call + one tool call). Higher values let the agent search more thoroughly but use more tokens. The agent typically needs 10-20 cycles for simple queries and 30-50 for complex multi-faceted research. | SEARCH || `langgraph_agent.max_sub_iterations` | `LDR_LANGGRAPH_AGENT_MAX_SUB_ITERATIONS` | `8` | Maximum reasoning cycles per subagent when researching subtopics in parallel. Each subagent investigates one aspect of the question independently. | SEARCH || `langgraph_agent.max_subagent_workers` | `LDR_LANGGRAPH_AGENT_MAX_SUBAGENT_WORKERS` | `4` | Maximum number of subagents that may run in parallel within a single research_subtopic call. Each call runs up to min(this setting, the number of subtopics passed to that call) workers; a call accepts at most 10 subtopics, so values above 10 do not increase per-call concurrency. Any subtopics beyond the pool size queue within that call and start as workers free up (a queued subagent keeps its own per-task budget — it is NOT killed by a shared loop timer). The lead agent may issue several research_subtopic calls concurrently in one turn, each with its own worker pool, so total concurrency across calls can be a multiple of this value. Tune this to match what your LLM backend can sustain in parallel (Ollama / LMStudio / llama.cpp `OLLAMA_NUM_PARALLEL`, an OpenAI tier limit, etc.). Lower values reduce concurrent LLM/search load; recommended to keep this low for local LLM backends. | SEARCH |+| `langgraph_agent.subagent_timeout_seconds` | `LDR_LANGGRAPH_AGENT_SUBAGENT_TIMEOUT_SECONDS` | `7200` | Per-subagent wall-clock deadline in seconds, measured from when the subagent starts. The default is two hours to support slow local LLMs. Cooldown waits count toward this time; the effective deadline is automatically at least the configured search cooldown wait budget plus 30 minutes, so cooldown waiting alone cannot exhaust it. Increase this for especially slow models. The LangGraph lead agent has no corresponding per-agent deadline. The separate llm.request_timeout setting controls how long an individual LLM request may be inactive. | SEARCH || `llm.allowed_local_hostnames` | `LDR_LLM_ALLOWED_LOCAL_HOSTNAMES` | ``[]`` | Hostnames the policy will treat as local in addition to loopback / RFC1918 / link-local. Use for self-hosted services on custom hostnames (e.g. 'ollama.lan'). Public hostnames added here are rejected at save time. | LLM || `llm.anthropic.api_key` | `LDR_LLM_ANTHROPIC_API_KEY` | `` | Your Anthropic API key for Claude models. Get one at console.anthropic.com. Required when using the Anthropic provider. | LLM || `llm.anthropic_endpoint.api_key` | `LDR_LLM_ANTHROPIC_ENDPOINT_API_KEY` | `` | Optional API key for your Anthropic-compatible endpoint. Leave blank for self-hosted servers that don't require authentication. | LLM |diff --git a/docs/search-engines.md b/docs/search-engines.mdindex 32fb0c434b..72abf12661 100644--- a/docs/search-engines.md+++ b/docs/search-engines.md@@ -256,26 +256,36 @@ first calls and retries after a cooldown, run concurrently, and the firstfailure disables the engine for all of them. Searches already in flight mayfinish.-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.+When every search engine the agent (or a subagent) could use is cooling down,+the next model call waits for the soonest cooldown to end, checking for+cancellation every second. Tools come back as soon as their cooldown ends, at+any step of the run, not only when a run or report section starts. The+research log says how long the next wait is expected to take.++Cooldown waits in one run share a one-hour budget by default; parallel+subagents waiting at the same time spend it once. Set+`langgraph_agent.cooldown_wait_budget_seconds` to allow longer waits (or to+zero to skip waiting). This budget covers only waiting for search engines; it+does not limit time spent searching, running the LLM, or writing the report.+Subagents have a separate two-hour wall-clock deadline by default, adjustable+with `langgraph_agent.subagent_timeout_seconds`. Its effective value is at+least the cooldown wait budget plus 30 minutes, so a subagent can complete a+full cooldown wait and still have time to work. Cancelling the research stops+the lead agent waiting for running subagents within a minute, not at their+deadline, also when it waits for several subagent batches at once. Each of+those subagents stops before its next model call, so one in the middle of a+model call or a tool call (such as a slow search or page fetch) can take until+that call returns. A subagent already past its deadline is no longer waited+for and may keep running until it finishes, even after a cancel.+For a local model that is silent for more than 30 minutes on one request,+also raise `llm.request_timeout`; that setting is separate from research+cooldown waits and subagent deadlines.+Temporary failures and provider `Retry-After` values keep their cooldowns,+even after repeated failures. When the next cooldown cannot finish within the+remaining wait budget, the cooling engines are disabled for the rest of the+run. A `Retry-After` longer than a day (or longer than the wait budget, if that+is larger) is not treated as a cooldown at all: the engine is disabled for the+rest of the run at once, with that reason.Once that leaves no search engine, the rules below for engines disabled forthe rest of the run apply.@@ -311,9 +321,9 @@ change call counts, response times or success rates. Cooldowns expire automaticaeligible 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+ wait five minutes after the engine's retries are exhausted. A `Retry-After`+ longer than a day (or than the wait budget, if that is larger), here or for+ HTTP 503 below, disables the engine for the rest of the run instead. Retries mayhappen in the HTTP client rather than the search pipeline: SemanticScholar's session retries HTTP 429 itself, honoring `Retry-After` up to 30seconds per retry (at most five retries), and when those retries run out the engine is disabled for five minutes once its@@ -322,8 +332,7 @@ eligible for another search, and the log records that retry is available.429 page) is treated as a rate limit, because its client library discardsthe 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).+ HTTP 503 uses the provider's `Retry-After` when reported.- A request URL refused by security validation: wait five minutes. Thevalidator also refuses hosts that cannot be resolved, so a DNS outage isretried rather than treated as a configuration error.diff --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 16b58fd1e9..a50cf9471c 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@@ -27,6 +27,7 @@ from langgraph.errors import GraphRecursionErrorfrom loguru import loggerfrom ...citation_handler import CitationHandler+from ...exceptions import ResearchTerminatedExceptionfrom ...security.egress import EngineClassification, classify_enginefrom ...security import (redact_url_for_log,@@ -56,7 +57,7 @@ from ...utilities.url_utils import (from ...utilities.json_utils import get_llm_response_textfrom ...database.thread_local_session import thread_cleanupfrom ...web_search_engines.engine_availability import (- MAX_COOLDOWN_SECONDS,+ COOLDOWN_WAIT_BUDGET_SECONDS,SearchEngineAvailability,available_tool_names,engine_failure,@@ -101,14 +102,19 @@ DEFAULT_MAX_ITERATIONS = (50 # agent needs many more cycles than pipeline strategies)MIN_ITERATIONS = 10 # below this the agent can barely do anything useful-SUBAGENT_TIMEOUT_SECONDS = 1800 # 30 minutes per subagent, measured from+SUBAGENT_TIMEOUT_SECONDS = 7200 # 2 hours 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+SUBAGENT_WORK_AFTER_COOLDOWN_SECONDS = 1800 # Leave at least 30 minutes after+# the configured search cooldown budget for LLM work and synthesis.+MIN_SUBAGENT_TIMEOUT_SECONDS = 60 # Lower bound of the user setting; keep it+# equal to ``min_value`` of ``langgraph_agent.subagent_timeout_seconds`` in+# default_settings.json, which also keeps the default on the form's step grid.+SUBAGENT_POLL_SECONDS = 60.0 # Longest the research_subtopic drain loop waits+# before looking again: it re-checks for cancellation on every wake, and+# never hands ``threading.Condition.wait`` a value above+# ``threading.TIMEOUT_MAX`` however large a deadline the user configures.# User-facing sentinels for "the agent produced nothing". _finalize's# missing-citations warning must stay quiet for both — an agent failure@@ -134,8 +140,8 @@ MAX_SUBAGENT_WORKERS = 4 # default pool size when the user has not set# start as workers free up; each queued subagent keeps its own per-task# budget from its actual start time.SUBAGENT_TIMEOUT_OVERALL_MULTIPLIER = 2 # safety cap multiplier: the overall-# drain-loop wall-clock is bounded to ``SUBAGENT_TIMEOUT_SECONDS * multiplier``-# seconds so a pathological hang cannot block the lead forever. This is a+# drain-loop wall-clock is bounded to the effective subagent timeout times+# this multiplier, so a pathological hang cannot block the lead forever. This is a# backstop only -- the per-task deadline above is what actually kills an# individual subagent. The multiplier is intentionally small (2) because the# worst case (queued subtopics) is already covered by per-task deadlines; we@@ -1764,6 +1770,7 @@ def _make_research_subtopic_tool(max_fetches_per_topic: int | None = None,availability: SearchEngineAvailability | None = None,wait_for_engines=None,+ subagent_timeout_seconds: float | None = None,):"""Create the ``research_subtopic`` tool that spawns parallel subagents.@@ -1801,6 +1808,11 @@ def _make_research_subtopic_tool("""Description passed via ``@tool(description=...)`` above — f-strings can't be docstrings."""from langchain.agents import create_agent+ timeout_seconds = (+ SUBAGENT_TIMEOUT_SECONDS+ if subagent_timeout_seconds is None+ else subagent_timeout_seconds+ )if not subtopics:return "No subtopics provided."@@ -2123,6 +2135,11 @@ def _make_research_subtopic_tool(with search_context(captured_search_context):return run_subagent(topic)return run_subagent(topic)+ except ResearchTerminatedException:+ # This subagent's check may have cleared the run's single-use+ # termination flag; record the cancel for the other threads.+ availability.note_cancelled()+ raisefinally:_current_subagent_context.reset(sub_token)with task_state_changed:@@ -2134,7 +2151,7 @@ def _make_research_subtopic_tool(# case queue wait (ceil(subtopics/workers) waves) plus slack. This is# only a backstop; each started task has its own earlier deadline.overall_timeout_seconds = (- SUBAGENT_TIMEOUT_SECONDS+ timeout_seconds* max(1, math.ceil(len(subtopics) / effective_workers))* SUBAGENT_TIMEOUT_OVERALL_MULTIPLIER)@@ -2147,13 +2164,24 @@ def _make_research_subtopic_tool(logger.warning(f"Subagent timed out (per-task): {topic[:80]} "f"ran {elapsed:.1f}s of "- f"{SUBAGENT_TIMEOUT_SECONDS}s budget"+ f"{timeout_seconds}s budget")ordered_results[task_id] = (f"Research on '{topic}' timed out after {elapsed:.1f}s "- f"(per-subagent budget is {SUBAGENT_TIMEOUT_SECONDS}s)."+ f"(per-subagent budget is {timeout_seconds}s).")+ # The drain loop reads the research's termination flag but must not+ # consume it: availability.check_cancelled would clear it (the first+ # check to see it cleans up the run), hiding the cancel from parallel+ # research_subtopic calls and from running subagents. None outside a+ # research run, which is then never treated as cancelled.+ from ...llm.cancellation import (+ get_current_research_id,+ is_termination_requested,+ )++ research_id = get_current_research_id()executor = ThreadPoolExecutor(max_workers=effective_workers)futures = {}try:@@ -2188,7 +2216,7 @@ def _make_research_subtopic_tool(if (futures[future][0] in task_start_timesand now - task_start_times[futures[future][0]]- >= SUBAGENT_TIMEOUT_SECONDS+ >= timeout_seconds)]if expired:@@ -2201,13 +2229,39 @@ def _make_research_subtopic_tool(deadlines = [overall_deadline]deadlines.extend(task_start_times[futures[future][0]]- + SUBAGENT_TIMEOUT_SECONDS+ + timeout_secondsfor future in pendingif futures[future][0] in task_start_times)- task_state_changed.wait(- timeout=max(0.0, min(deadlines) - now)+ # Capped so large user-configured deadlines stay+ # below threading.TIMEOUT_MAX on every platform.+ wait_seconds = max(+ 0.0,+ min(SUBAGENT_POLL_SECONDS, min(deadlines) - now),)+ if not task_state_changed.wait(timeout=wait_seconds):+ # Timed out with nothing finished. Leave the lock+ # so the cancellation check below can run, then+ # come back around to re-read the deadlines.+ break++ # A cancelled run must not stay blocked behind a subagent+ # stuck in a slow LLM call until its per-task deadline (hours+ # by default); this runs on every wake, outside the lock. The+ # run's cleanup clears the flag once the lead has stopped, so+ # the cancel is also recorded on the shared tracker: parallel+ # drain loops, cooldown waits and each subagent's next model+ # call read it there. Like a raise from the LLM wrappers' own+ # check, this one leaves the run's single cleanup to the+ # ResearchTerminatedException handler in run_research_process.+ if availability.cancelled() or is_termination_requested(+ research_id+ ):+ availability.note_cancelled()+ raise ResearchTerminatedException(+ "Research was terminated by user while waiting for "+ "subagents"+ )# A completed future can still have exceeded its own budget.# Check the worker-recorded duration before accepting its@@ -2218,7 +2272,7 @@ def _make_research_subtopic_tool(task_id, topic = futures[future]start = task_start_times[task_id]elapsed = max(0.0, task_end_times[task_id] - start)- if elapsed >= SUBAGENT_TIMEOUT_SECONDS:+ if elapsed >= timeout_seconds:_record_per_task_timeout(task_id, topic, elapsed)continuetry:@@ -2258,7 +2312,7 @@ def _make_research_subtopic_tool(f"the overall safety budget of "f"{overall_timeout_seconds}s expired "f"(queued for {queued_elapsed:.1f}s; its "- f"{SUBAGENT_TIMEOUT_SECONDS}s per-subagent "+ f"{timeout_seconds}s per-subagent "f"budget begins at task start).")else:@@ -2267,14 +2321,14 @@ def _make_research_subtopic_tool(f"Subagent exceeded overall safety cap: "f"{topic[:80]} ran {elapsed:.1f}s of "f"{overall_timeout_seconds}s overall / "- f"{SUBAGENT_TIMEOUT_SECONDS}s per-task budget"+ f"{timeout_seconds}s per-task budget")ordered_results[task_id] = (f"Research on '{topic}' did not finish within "f"the overall safety budget of "f"{overall_timeout_seconds}s (ran "f"{elapsed:.1f}s; per-subagent budget is "- f"{SUBAGENT_TIMEOUT_SECONDS}s)."+ f"{timeout_seconds}s).")future.cancel()pending.clear()@@ -2375,9 +2429,44 @@ class LangGraphAgentStrategy(BaseSearchStrategy):settings_snapshot=settings_snapshot,)self.collector = SearchResultsCollector(self.all_links_of_system)+ raw_wait_budget = self.get_setting(+ "langgraph_agent.cooldown_wait_budget_seconds",+ COOLDOWN_WAIT_BUDGET_SECONDS,+ )+ try:+ wait_budget_seconds = float(raw_wait_budget)+ except (TypeError, ValueError, OverflowError):+ wait_budget_seconds = math.nan+ if not math.isfinite(wait_budget_seconds) or wait_budget_seconds < 0:+ logger.warning(+ "Invalid langgraph_agent.cooldown_wait_budget_seconds; "+ f"using {COOLDOWN_WAIT_BUDGET_SECONDS}s"+ )+ wait_budget_seconds = COOLDOWN_WAIT_BUDGET_SECONDSself.engine_availability = SearchEngineAvailability(self._update_progress,check_cancelled=lambda: self.check_termination(CHECK_CONTEXT_ENTRY),+ wait_budget_seconds=wait_budget_seconds,+ )+ raw_subagent_timeout = self.get_setting(+ "langgraph_agent.subagent_timeout_seconds", SUBAGENT_TIMEOUT_SECONDS+ )+ try:+ configured_subagent_timeout = float(raw_subagent_timeout)+ except (TypeError, ValueError, OverflowError):+ configured_subagent_timeout = math.nan+ if (+ not math.isfinite(configured_subagent_timeout)+ or configured_subagent_timeout < MIN_SUBAGENT_TIMEOUT_SECONDS+ ):+ logger.warning(+ "Invalid langgraph_agent.subagent_timeout_seconds; "+ f"using {SUBAGENT_TIMEOUT_SECONDS}s"+ )+ configured_subagent_timeout = SUBAGENT_TIMEOUT_SECONDS+ self.subagent_timeout_seconds = max(+ configured_subagent_timeout,+ wait_budget_seconds + SUBAGENT_WORK_AFTER_COOLDOWN_SECONDS,)self._primary_availability_checked = Falseself._collection_tool_display_names: dict[str, str] = {}@@ -2432,6 +2521,38 @@ class LangGraphAgentStrategy(BaseSearchStrategy):# Derive the search engine name for creating fresh instancesself._search_engine_name = self._resolve_engine_name()+ def set_progress_callback(self, callback) -> None:+ """Set the progress callback, recording every cancel it raises.++ In a research run this callback is also the cancellation check: the+ first call to see the run's termination flag cleans the run up,+ which clears that single-use flag, and raises+ ``ResearchTerminatedException``. This strategy and its tools reach+ it only as ``self.progress_callback``: through ``_update_progress``+ and ``check_termination`` (so also the availability tracker's+ reports and cancellation checks) and as the callback each tool is+ built with. It therefore runs on the lead's thread, in the lead's+ parallel tool calls and in subagents. Whichever thread sees the+ cancel, the wrapper records it on the run's shared tracker+ (``SearchEngineAvailability.note_cancelled``) before re-raising, so+ drain loops, cooldown waits and subagents still stop once the flag+ is gone. Recording cleans nothing up; the run's single cleanup stays+ with the callback, or else with the handler in+ ``run_research_process``.+ """+ if callback is None:+ super().set_progress_callback(callback)+ return++ def progress_callback(*args, **kwargs):+ try:+ return callback(*args, **kwargs)+ except ResearchTerminatedException:+ self.engine_availability.note_cancelled()+ raise++ super().set_progress_callback(progress_callback)+@staticmethoddef _coerce_max_subagent_workers(raw: Any) -> int:"""Validate and clamp the user-supplied pool size.@@ -3045,6 +3166,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):max_fetches_per_topic=self.max_fetches_per_topic,availability=self.engine_availability,wait_for_engines=self._wait_for_cooldown,+ subagent_timeout_seconds=self.subagent_timeout_seconds,))@@ -3378,9 +3500,10 @@ class LangGraphAgentStrategy(BaseSearchStrategy):search engine the call could use is disabled and at least one onlyfor a cooldown (a transient failure or ``Retry-After``). Waitingkeeps 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.+ model to answer without search. The whole wait never exceeds the+ run's remaining configured wait budget, 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 therun's cooldown-wait budget; once it is spent, the cooling enginesare disabled for the rest of the run instead (see@@ -3390,7 +3513,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):if not engines or not engines <= availability.disabled().keys():returnwait = availability.seconds_until_retry(engines)- if wait is None or wait > COOLDOWN_WAIT_SECONDS:+ if wait is None:returnif wait <= availability.wait_budget_remaining():self._update_progress(@@ -3406,7 +3529,6 @@ class LangGraphAgentStrategy(BaseSearchStrategy):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),diff --git a/src/local_deep_research/advanced_search_system/tools/search_availability.py b/src/local_deep_research/advanced_search_system/tools/search_availability.pyindex 45aa319227..c1783b7a1f 100644--- a/src/local_deep_research/advanced_search_system/tools/search_availability.py+++ b/src/local_deep_research/advanced_search_system/tools/search_availability.py@@ -6,6 +6,7 @@ import timefrom langchain.agents.middleware import AgentMiddlewarefrom langchain_core.messages import SystemMessage+from ...exceptions import ResearchTerminatedExceptionfrom ...security.secure_logging import loggerfrom ...utilities.resource_utils import safe_closefrom ...web_search_engines.search_engine_base import (@@ -13,7 +14,6 @@ from ...web_search_engines.search_engine_base import (metrics_engine_name,)from ...web_search_engines.engine_availability import (- MAX_COOLDOWN_SECONDS,SearchEngineAvailability,SearchFailure,available_tool_names,@@ -47,37 +47,45 @@ 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.+ """Block until one of ``engines`` leaves its cooldown, within the run budget.- 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.+ Returns at once when an engine is already available or when every+ remaining disable lasts the rest of the run. Once the soonest retry lies+ beyond the run's remaining cooldown-wait budget, it disables the cooling+ ``engines`` for the rest of the run (``end_cooldowns``) and returns+ instead of waiting. A concurrent search can start another cooldown+ during this wait; it must not leave the model with no search tool while+ the run can still wait for a retry. Parallel waiters spend the shared+ budget once. ``check`` (by default the tracker's ``check_cancelled``)+ runs before each sleep of at most one second, so cancellation stays+ responsive; a cancel already recorded on the tracker+ (``note_cancelled``) ends the wait as well."""sleep = sleep or time.sleepcheck = check or availability.check_cancelled- deadline = availability.now() + max_waitwith availability.waiting():while engines and engines <= availability.disabled().keys():+ if availability.cancelled():+ raise ResearchTerminatedException(+ "Research was terminated by user during a cooldown wait"+ )if check is not None:- check()+ try:+ check()+ except ResearchTerminatedException:+ # The run's termination flag is single-use; record the+ # cancel so parallel waiters and subagents stop too.+ availability.note_cancelled()+ raiseremaining = availability.seconds_until_retry(engines)if remaining is None:returnif remaining > availability.wait_budget_remaining():availability.end_cooldowns(engines)return- if remaining > deadline - availability.now():- returnsleep(min(1.0, max(remaining, 0.01)))@@ -203,7 +211,9 @@ class SearchAvailabilityMiddleware(AgentMiddleware):first waits (bounded) for the soonest cooldown via ``wait``, whichreceives 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.+ the run's cooldown-wait budget. Once the cancel is recorded on the+ tracker (``note_cancelled``), every further model call raises+ ``ResearchTerminatedException`` instead."""def __init__(self, availability, primary_engine, wait=None):@@ -214,6 +224,10 @@ class SearchAvailabilityMiddleware(AgentMiddleware):)def _filter_request(self, request):+ # The run's termination flag is gone once the run has cleaned up, so+ # a subagent back from a slow model call would otherwise keep going.+ if self.availability.cancelled():+ raise ResearchTerminatedException("Research was terminated by user")names = [t.name for t in request.tools]relevant = {engine_for_tool(name, self.primary_engine) for name in namesdiff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex ee6920f26e..080418af36 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -1204,6 +1204,34 @@"value": 4,"visible": true},+ "langgraph_agent.cooldown_wait_budget_seconds": {+ "category": "langgraph_agent",+ "description": "Total time in seconds one LangGraph research run may spend waiting when all usable search engines are cooling down. Parallel waits share the same budget. Default is one hour; increase it for providers with long rate limits. This does not limit LLM inference or the overall research duration. Set to 0 to skip cooldown waiting and use the sources already gathered.",+ "editable": true,+ "max_value": null,+ "min_value": 0,+ "name": "Search Cooldown Wait Budget (seconds)",+ "options": null,+ "step": 60,+ "type": "SEARCH",+ "ui_element": "number",+ "value": 3600,+ "visible": true+ },+ "langgraph_agent.subagent_timeout_seconds": {+ "category": "langgraph_agent",+ "description": "Per-subagent wall-clock deadline in seconds, measured from when the subagent starts. The default is two hours to support slow local LLMs. Cooldown waits count toward this time; the effective deadline is automatically at least the configured search cooldown wait budget plus 30 minutes, so cooldown waiting alone cannot exhaust it. Increase this for especially slow models. The LangGraph lead agent has no corresponding per-agent deadline. The separate llm.request_timeout setting controls how long an individual LLM request may be inactive.",+ "editable": true,+ "max_value": null,+ "min_value": 60,+ "name": "Subagent Timeout (seconds)",+ "options": null,+ "step": 60,+ "type": "SEARCH",+ "ui_element": "number",+ "value": 7200,+ "visible": true+ },"focused_iteration.adaptive_questions": {"category": "focused_iteration","description": "When enabled (1), the system monitors recent search success and warns the LLM to broaden queries if 3+ searches in a recent window returned no results. When disabled (0), queries are generated without feedback from previous result counts.",diff --git a/src/local_deep_research/web_search_engines/engine_availability.py b/src/local_deep_research/web_search_engines/engine_availability.pyindex 285c70d766..337b6672c0 100644--- a/src/local_deep_research/web_search_engines/engine_availability.py+++ b/src/local_deep_research/web_search_engines/engine_availability.py@@ -24,21 +24,19 @@ from urllib3.exceptions import ResponseErrorfrom ..security.secure_logging import loggerfrom .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+# sole engine cannot keep a run waiting indefinitely. Users can adjust this+# per research run with langgraph_agent.cooldown_wait_budget_seconds.+COOLDOWN_WAIT_BUDGET_SECONDS = 3600-# 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+# Longest provider Retry-After kept as a temporary cooldown; a larger wait+# budget raises this limit. A longer delay is not one this research can plan+# around (an HTTP date years away parses to centuries of seconds), so the+# engine is disabled for the rest of the run with that reason, instead of+# being shown as "temporary" with an absurd retry time.+MAX_TEMPORARY_COOLDOWN_SECONDS = 24 * 60 * 60# 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.@@ -270,14 +268,18 @@ class SearchEngineAvailability: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,+ max_consecutive_cooldowns: int | None = None,):self._clock = clockself._wall_clock = wall_clockself._on_change = on_change# Raises (e.g. ResearchTerminatedException) when the run is- # cancelled; cooldown waits call it before every sleep.+ # cancelled; cooldown waits call it before every sleep. In a research+ # run the call that sees the cancel first also clears the run's+ # single-use termination flag while cleaning up; see note_cancelled.self.check_cancelled = check_cancelled+ # Set once any thread sharing this tracker has seen the run cancelled.+ self._cancelled = threading.Event()self._lock = threading.RLock()self._disabled: dict[str, EngineDisablement] = {}self._metrics_names: dict[str, str] = {}@@ -346,17 +348,18 @@ class SearchEngineAvailability:if delay is not None:delay = retry_after_seconds(delay, now=now) or 60count = 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.+ longest = max(self._wait_budget, MAX_TEMPORARY_COOLDOWN_SECONDS)+ if delay > longest:failure = SearchFailure(f"{failure.reason}; the provider asked to wait "- f"longer than {MAX_COOLDOWN_SECONDS}s",+ f"longer than {math.ceil(longest)}s",None,)delay = None- elif count > self._max_consecutive_cooldowns:+ elif (+ self._max_consecutive_cooldowns is not None+ and count > self._max_consecutive_cooldowns+ ):failure = SearchFailure(f"{failure.reason}; still failing after "f"{count - 1} cooldowns in a row",@@ -388,6 +391,23 @@ class SearchEngineAvailability:self._emit(state, retry=True)return states+ def note_cancelled(self) -> None:+ """Record that this run was cancelled, for every thread sharing it.++ The run's termination flag is single-use: the first check to see it+ clears it while cleaning up, and so does the cleanup after the lead+ agent stops. In the LangGraph strategy that check is the research+ progress callback, which records every cancel it raises, on any+ thread; drain loops, subagent workers and cooldown waits also record+ the cancels they see. Parallel drain loops, cooldown waits and+ running subagents read this record, so they stop as well.+ """+ self._cancelled.set()++ def cancelled(self) -> bool:+ """Whether a cancel has been recorded (``note_cancelled``)."""+ return self._cancelled.is_set()+def now(self) -> float:"""Current time on the clock that cooldown deadlines use."""return self._clock()@@ -433,9 +453,8 @@ class SearchEngineAvailability:self.disable(engine,SearchFailure(- f"{state.failure.reason}; this research already "- f"waited {math.ceil(self._wait_budget)}s for "- "search engine cooldowns",+ f"{state.failure.reason}; cooldown exceeds this "+ "research's remaining search wait budget",None,),)diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.jsonindex 2cf3578992..8d119e92e7 100644--- a/tests/settings/golden_master_settings.json+++ b/tests/settings/golden_master_settings.json@@ -1120,6 +1120,20 @@"value": "","visible": true},+ "langgraph_agent.cooldown_wait_budget_seconds": {+ "category": "langgraph_agent",+ "description": "Total time in seconds one LangGraph research run may spend waiting when all usable search engines are cooling down. Parallel waits share the same budget. Default is one hour; increase it for providers with long rate limits. This does not limit LLM inference or the overall research duration. Set to 0 to skip cooldown waiting and use the sources already gathered.",+ "editable": true,+ "max_value": null,+ "min_value": 0,+ "name": "Search Cooldown Wait Budget (seconds)",+ "options": null,+ "step": 60,+ "type": "SEARCH",+ "ui_element": "number",+ "value": 3600,+ "visible": true+ },"langgraph_agent.include_sub_research": {"category": "langgraph_agent","description": "Enable parallel subagent research. When enabled, the agent can decompose complex questions into subtopics and research them simultaneously using separate subagents.",@@ -1176,6 +1190,20 @@"value": 4,"visible": true},+ "langgraph_agent.subagent_timeout_seconds": {+ "category": "langgraph_agent",+ "description": "Per-subagent wall-clock deadline in seconds, measured from when the subagent starts. The default is two hours to support slow local LLMs. Cooldown waits count toward this time; the effective deadline is automatically at least the configured search cooldown wait budget plus 30 minutes, so cooldown waiting alone cannot exhaust it. Increase this for especially slow models. The LangGraph lead agent has no corresponding per-agent deadline. The separate llm.request_timeout setting controls how long an individual LLM request may be inactive.",+ "editable": true,+ "max_value": null,+ "min_value": 60,+ "name": "Subagent Timeout (seconds)",+ "options": null,+ "step": 60,+ "type": "SEARCH",+ "ui_element": "number",+ "value": 7200,+ "visible": true+ },"llm.allowed_local_hostnames": {"category": "policy","description": "Hostnames the policy will treat as local in addition to loopback / RFC1918 / link-local. Use for self-hosted services on custom hostnames (e.g. 'ollama.lan'). Public hostnames added here are rejected at save time.",diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.pyindex 8b78ff797d..849fdf5f19 100644--- a/tests/strategies/test_langgraph_agent_strategy.py+++ b/tests/strategies/test_langgraph_agent_strategy.py@@ -4254,8 +4254,14 @@ class TestSearchResultsCollectorFetchTracking:def test_build_tools_honors_mutated_max_fetches(self):"""Verify single-read contract: mutating strategy.max_fetches_per_topic- is honored by _build_tools without redundant re-reading from snapshot."""+ is honored by _build_tools without redundant re-reading from snapshot.+ The strategy's effective subagent timeout and its availability tracker+ reach research_subtopic the same way: without the timeout the tool+ would silently fall back to the module default and cut subagents off+ mid-cooldown-wait; without the tracker its drain loop could not see+ a cancellation."""from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ SUBAGENT_TIMEOUT_SECONDS,LangGraphAgentStrategy,)@@ -4267,6 +4273,9 @@ class TestSearchResultsCollectorFetchTracking:)assert strategy.max_fetches_per_topic == 5strategy.max_fetches_per_topic = 2+ # Distinct from the module default, so a tool that fell back to it+ # (or ignored the argument) cannot satisfy the assertion below.+ strategy.subagent_timeout_seconds = SUBAGENT_TIMEOUT_SECONDS + 1800with (patch(@@ -4282,6 +4291,17 @@ class TestSearchResultsCollectorFetchTracking:assert mock_build_fetch.call_args.kwargs["max_fetches"] == 2assert mock_make_sub.call_args.kwargs["max_fetches_per_topic"] == 2+ assert (+ mock_make_sub.call_args.kwargs["subagent_timeout_seconds"]+ == strategy.subagent_timeout_seconds+ == SUBAGENT_TIMEOUT_SECONDS + 1800+ )+ # The tool's drain loops and subagents share the run's tracker:+ # its cooldowns, and the record of a cancel one of them has seen.+ assert (+ mock_make_sub.call_args.kwargs["availability"]+ is strategy.engine_availability+ )def test_subagent_budget_wiring_and_shared_collector(self):"""Verify subagent wiring:diff --git a/tests/strategies/test_langgraph_subagent_timeout_5014.py b/tests/strategies/test_langgraph_subagent_timeout_5014.pyindex 4b75a4fdd4..6de24e8b80 100644--- a/tests/strategies/test_langgraph_subagent_timeout_5014.py+++ b/tests/strategies/test_langgraph_subagent_timeout_5014.py@@ -22,9 +22,16 @@ queued-subagent false-positive and the actual-elapsed reporting are bothgenuinely validated."""+import threadingimport time+import uuid+from contextlib import contextmanager+from types import SimpleNamespacefrom unittest.mock import MagicMock, patch+import pytest+from langchain.agents.middleware import ModelRequest+import local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy as modfrom local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (MAX_SUBAGENT_WORKERS,@@ -32,13 +39,26 @@ from local_deep_research.advanced_search_system.strategies.langgraph_agent_stratSearchResultsCollector,_make_research_subtopic_tool,)+from local_deep_research.exceptions import ResearchTerminatedException+from local_deep_research.utilities.thread_context import search_context+from local_deep_research.web import research_state+from local_deep_research.web_search_engines.engine_availability import (+ SearchEngineAvailability,+ SearchFailure,+)# Small budget so tests run in well under a second while still exercising the# per-task timeout path.TEST_TIMEOUT = 0.2+FACTORY = "local_deep_research.web_search_engines.search_engine_factory.create_search_engine"+-def _build_tool(max_subagent_workers=MAX_SUBAGENT_WORKERS, sleep_map=None):+def _build_tool(+ max_subagent_workers=MAX_SUBAGENT_WORKERS,+ sleep_map=None,+ subagent_timeout_seconds=None,+):"""Build a research_subtopic tool whose subagents sleep per ``sleep_map``.``sleep_map``: subtopic -> seconds the subagent sleeps (simulated work).@@ -54,6 +74,7 @@ def _build_tool(max_subagent_workers=MAX_SUBAGENT_WORKERS, sleep_map=None):collector=collector,max_sub_iterations=8,max_subagent_workers=max_subagent_workers,+ subagent_timeout_seconds=subagent_timeout_seconds,)agent_mock = MagicMock()@@ -129,6 +150,69 @@ class TestResearchSubtopicPerTaskTimeout:assert "finding for slow topic" not in resultassert "did not finish within the overall safety budget" not in result+ def test_configured_timeout_reaches_the_worker_deadline(self):+ """The configured deadline replaces the module default.++ The patched default (TEST_TIMEOUT) would time the 0.3s worker out;+ the configured deadline is an hour. Nothing here races the clock:+ the worker can never come close to the configured deadline, and a+ tool that ignored it would always time out (a sleep never returns+ early).+ """+ tool, agent_mock = _build_tool(+ sleep_map={"slow local model": TEST_TIMEOUT * 1.5},+ subagent_timeout_seconds=3600,+ )+ with (+ patch.object(+ mod, "_make_web_search_tool", return_value=MagicMock()+ ),+ patch.object(mod, "build_fetch_tool", return_value=None),+ patch("langchain.agents.create_agent", return_value=agent_mock),+ patch.object(mod, "SUBAGENT_TIMEOUT_SECONDS", TEST_TIMEOUT),+ ):+ result = tool.invoke({"subtopics": ["slow local model"]})+ assert "finding for slow local model" in result+ assert "timed out" not in result++ def test_configured_timeout_is_enforced_as_the_worker_deadline(self):+ """...and it is the deadline that applies, not just a bigger number.++ The patched default is an hour while the configured deadline is+ TEST_TIMEOUT; the 0.3s worker overruns it (a sleep never returns+ early), whichever order the drain loop notices that in.+ """+ tool, agent_mock = _build_tool(+ sleep_map={"slow local model": TEST_TIMEOUT * 1.5},+ subagent_timeout_seconds=TEST_TIMEOUT,+ )+ with (+ patch.object(+ mod, "_make_web_search_tool", return_value=MagicMock()+ ),+ patch.object(mod, "build_fetch_tool", return_value=None),+ patch("langchain.agents.create_agent", return_value=agent_mock),+ patch.object(mod, "SUBAGENT_TIMEOUT_SECONDS", 3600),+ ):+ result = tool.invoke({"subtopics": ["slow local model"]})+ assert "Research on 'slow local model' timed out after" in result+ assert f"per-subagent budget is {TEST_TIMEOUT}s" in result+ assert "finding for slow local model" not in result++ def test_large_configured_timeout_does_not_overflow_condition_wait(self):+ tool, agent_mock = _build_tool(+ sleep_map={"topic": 0.02}, subagent_timeout_seconds=1e308+ )+ with (+ patch.object(+ mod, "_make_web_search_tool", return_value=MagicMock()+ ),+ patch.object(mod, "build_fetch_tool", return_value=None),+ patch("langchain.agents.create_agent", return_value=agent_mock),+ ):+ result = tool.invoke({"subtopics": ["topic"]})+ assert "finding for topic" in result+def test_per_task_deadline_from_actual_start_not_submit(self):"""Even when a subagent is queued for a long time, its per-task budgetis measured from its *actual* start, so a short-running queued task is@@ -242,3 +326,338 @@ class TestResearchSubtopicPerTaskTimeout:max_sub_iterations=8,)assert strategy.max_subagent_workers == 6+++@contextmanager+def _drain_patches(create_agent):+ with (+ patch.object(mod, "_make_web_search_tool", return_value=MagicMock()),+ patch.object(mod, "build_fetch_tool", return_value=None),+ patch("langchain.agents.create_agent", new=create_agent),+ # Wake the drain loops in milliseconds, not minutes.+ patch.object(mod, "SUBAGENT_POLL_SECONDS", 0.01),+ ):+ yield+++class TestResearchSubtopicDrainCancellation:+ """After a cancel, the lead must not stay blocked behind a stuck subagent.++ A subagent inside a slow LLM call cannot see the cancel, and its per-task+ deadline is hours away by default, so the drain loop itself has to look.+ The research's termination flag is single-use: the check that sees it+ first cleans the run up (``handle_termination`` -> ``cleanup_research``),+ which clears it, and so does the cleanup once the lead has stopped. These+ tests use the real flag registry; ``run.check_cancelled`` is that check.+ """++ # Bounds for the waits below, so that a regression fails in seconds+ # instead of waiting out a per-task deadline.+ STOP_SECONDS = 5+ STUCK_SECONDS = 30++ @pytest.fixture+ def run(self):+ research_id = f"drain-cancel-{uuid.uuid4().hex}"+ consumed = []++ def check_cancelled():+ # What research_service's progress_callback does when it sees+ # the flag: handle_termination cleans the run up, clearing it.+ if research_state.is_termination_requested(research_id):+ consumed.append(threading.current_thread().name)+ research_state.cleanup_research(research_id)+ raise ResearchTerminatedException("cancelled")++ yield SimpleNamespace(+ id=research_id, check_cancelled=check_cancelled, consumed=consumed+ )+ research_state.clear_termination_flag(research_id)++ @staticmethod+ def _tool(run):+ return _make_research_subtopic_tool(+ search_engine_name="duckduckgo",+ model=MagicMock(),+ settings_snapshot={"search.tool": {"value": "duckduckgo"}},+ collector=SearchResultsCollector([]),+ max_sub_iterations=8,+ # The strategy wires the research's consuming check in here.+ availability=SearchEngineAvailability(+ check_cancelled=run.check_cancelled+ ),+ )++ def _subagents(self, run, release):+ """A ``create_agent`` stand-in and what its subagents did.++ Each subagent is stuck in a slow model call until ``release``; its+ next model call then goes through the middleware the real agent loop+ runs every model call through. A subagent whose topic starts with+ "consumer" instead sees the cancel at its own check first, which+ clears the flag before any drain loop looks.+ """+ state = SimpleNamespace(+ started=threading.Semaphore(0),+ done=threading.Semaphore(0),+ go=threading.Event(),+ stopped=[],+ model_calls=[],+ )++ def create_agent(*, middleware, **_kwargs):+ def invoke(payload, _config=None):+ topic = payload["messages"][0]["content"]+ state.started.release()+ try:+ if topic.startswith("consumer"):+ state.go.wait(timeout=self.STUCK_SECONDS)+ with research_state._lock:+ research_state.set_termination_flag(run.id)+ run.check_cancelled()+ release.wait(timeout=self.STUCK_SECONDS)+ request = ModelRequest(+ model=MagicMock(), messages=[], tools=[]+ )+ try:+ middleware[0].wrap_model_call(+ request,+ lambda _request: state.model_calls.append(topic),+ )+ except ResearchTerminatedException:+ state.stopped.append(topic)+ raise+ return {+ "messages": [MagicMock(content=f"finding for {topic}")]+ }+ finally:+ state.done.release()++ agent = MagicMock()+ agent.invoke.side_effect = invoke+ return agent++ return create_agent, state++ @staticmethod+ def _drain(tool, run, topic, outcomes):+ """Run one research_subtopic call on its own thread, as the lead's+ tool node does for each call of a turn."""++ def target():+ with search_context({"research_id": run.id}):+ try:+ outcomes[topic] = tool.invoke({"subtopics": [topic]})+ except BaseException as exc: # asserted by the caller+ outcomes[topic] = exc++ thread = threading.Thread(target=target, daemon=True)+ thread.start()+ return thread++ @staticmethod+ def _lead_tools(run):+ """The lead's web_search and research_subtopic, built by the strategy.++ The strategy's progress callback acts like research_service's: every+ call checks the flag, and the first to see it cleans the run up,+ clearing the flag, and raises. ``phases`` lists the calls in order.+ Call within a patch of ``_load_specialized_engine_tools``.+ """+ strategy = LangGraphAgentStrategy(+ model=MagicMock(),+ search=MagicMock(last_search_failure=None),+ settings_snapshot={"search.tool": "searxng"},+ )+ phases = []++ def progress_callback(_message, _percent, metadata):+ phases.append(metadata.get("phase"))+ run.check_cancelled()++ strategy.set_progress_callback(progress_callback)+ with (+ patch.object(strategy, "_build_egress_context", return_value=None),+ patch.object(+ strategy, "_build_library_resolver", return_value=None+ ),+ patch.object(mod, "build_fetch_tool", return_value=None),+ ):+ tools = {tool.name: tool for tool in strategy._build_tools()}+ return tools["web_search"], tools["research_subtopic"], phases++ def test_a_later_wake_stops_the_lead_and_leaves_the_flag_set(self, run):+ """The cancel arrives after the drain loop has woken several times.++ The loop stops the lead without clearing the flag; the run's single+ cleanup follows from the exception it raises.+ """+ tool = self._tool(run)+ release = threading.Event()+ create_agent, subagents = self._subagents(run, release)+ outcomes = {}+ try:+ with _drain_patches(create_agent):+ drain = self._drain(tool, run, "stuck topic", outcomes)+ assert subagents.started.acquire(timeout=self.STOP_SECONDS)+ time.sleep(0.05) # several drain-loop wakes with no cancel+ assert drain.is_alive()+ research_state.set_termination_flag(run.id)+ drain.join(timeout=self.STOP_SECONDS)+ assert not drain.is_alive()+ finally:+ release.set()+ assert subagents.done.acquire(timeout=self.STOP_SECONDS)+ assert isinstance(outcomes["stuck topic"], ResearchTerminatedException)+ assert run.consumed == []+ assert research_state.is_termination_requested(run.id)++ def test_one_cancel_stops_parallel_drain_loops_and_their_subagents(+ self, run+ ):+ """Two research_subtopic calls of one turn wait on stuck subagents.++ One cancel stops both, and once the run's cleanup has cleared the+ flag, each subagent still stops at its next model call.+ """+ tool = self._tool(run)+ release = threading.Event()+ create_agent, subagents = self._subagents(run, release)+ outcomes = {}+ topics = ["first batch", "second batch"]+ try:+ with _drain_patches(create_agent):+ drains = [self._drain(tool, run, t, outcomes) for t in topics]+ for _ in topics:+ assert subagents.started.acquire(timeout=self.STOP_SECONDS)+ research_state.set_termination_flag(run.id)+ for drain in drains:+ drain.join(timeout=self.STOP_SECONDS)+ assert not any(drain.is_alive() for drain in drains)+ for topic in topics:+ assert isinstance(outcomes[topic], ResearchTerminatedException)+ # Neither loop consumed the flag. The run's one cleanup, from+ # run_research_process's handler for the exception, clears it.+ assert run.consumed == []+ assert research_state.is_termination_requested(run.id)+ research_state.cleanup_research(run.id)+ finally:+ release.set()+ for _ in topics:+ assert subagents.done.acquire(timeout=self.STOP_SECONDS)+ assert sorted(subagents.stopped) == topics+ assert subagents.model_calls == []++ def test_a_subagent_clearing_the_flag_still_stops_every_drain_loop(+ self, run+ ):+ """A subagent's own check sees the cancel first and clears the flag,+ as a search's progress update can. The other call's drain loop and+ stuck subagent stop as well."""+ tool = self._tool(run)+ release = threading.Event()+ create_agent, subagents = self._subagents(run, release)+ outcomes = {}+ topics = ["consumer batch", "stuck batch"]+ try:+ with _drain_patches(create_agent):+ drains = [self._drain(tool, run, t, outcomes) for t in topics]+ for _ in topics:+ assert subagents.started.acquire(timeout=self.STOP_SECONDS)+ subagents.go.set()+ for drain in drains:+ drain.join(timeout=self.STOP_SECONDS)+ assert not any(drain.is_alive() for drain in drains)+ for topic in topics:+ assert isinstance(outcomes[topic], ResearchTerminatedException)+ # The subagent's check was the run's one cleanup.+ assert len(run.consumed) == 1+ assert not research_state.is_termination_requested(run.id)+ finally:+ release.set()+ for _ in topics:+ assert subagents.done.acquire(timeout=self.STOP_SECONDS)+ assert subagents.stopped == ["stuck batch"]+ assert subagents.model_calls == []++ def test_a_lead_search_clearing_the_flag_still_stops_the_drain_loop(+ self, run+ ):+ """The lead's own web_search, in the same turn as a research_subtopic+ call, sees the cancel first: its engine fails, and the progress+ update reporting that disable clears the flag. The drain loop and its+ stuck subagent stop as well."""+ release = threading.Event()+ create_agent, subagents = self._subagents(run, release)+ engine = MagicMock(last_search_failure=SearchFailure("offline", 60))+ outcomes = {}+ try:+ with patch.object(+ mod, "_load_specialized_engine_tools", return_value=[]+ ):+ web_search, research_subtopic, phases = self._lead_tools(run)+ with _drain_patches(create_agent):+ drain = self._drain(+ research_subtopic, run, "stuck batch", outcomes+ )+ assert subagents.started.acquire(timeout=self.STOP_SECONDS)+ # Set and consumed before any drain-loop wake can look.+ with (+ research_state._lock,+ patch(FACTORY, return_value=engine),+ ):+ research_state.set_termination_flag(run.id)+ with pytest.raises(ResearchTerminatedException):+ web_search.invoke({"query": "lead query"})+ drain.join(timeout=self.STOP_SECONDS)+ assert phases[-1] == "engine_availability"+ assert len(run.consumed) == 1+ assert not research_state.is_termination_requested(run.id)+ assert not drain.is_alive()+ assert isinstance(+ outcomes["stuck batch"], ResearchTerminatedException+ )+ finally:+ release.set()+ assert subagents.done.acquire(timeout=self.STOP_SECONDS)+ assert subagents.stopped == ["stuck batch"]+ assert subagents.model_calls == []++ def test_a_second_call_clearing_the_flag_still_stops_the_first(self, run):+ """A second research_subtopic call of the turn sees the cancel first,+ at its start milestone, before starting any subagent. The first+ call's drain loop and its stuck subagent stop as well."""+ release = threading.Event()+ create_agent, subagents = self._subagents(run, release)+ outcomes = {}+ try:+ with patch.object(+ mod, "_load_specialized_engine_tools", return_value=[]+ ):+ _web_search, research_subtopic, phases = self._lead_tools(run)+ with _drain_patches(create_agent):+ drain = self._drain(+ research_subtopic, run, "first batch", outcomes+ )+ assert subagents.started.acquire(timeout=self.STOP_SECONDS)+ # Set and consumed before any drain-loop wake can look.+ with research_state._lock:+ research_state.set_termination_flag(run.id)+ with pytest.raises(ResearchTerminatedException):+ research_subtopic.invoke(+ {"subtopics": ["second batch"]}+ )+ drain.join(timeout=self.STOP_SECONDS)+ # The first call's milestone, then the second's.+ assert phases == ["sub_research", "sub_research"]+ assert len(run.consumed) == 1+ assert not research_state.is_termination_requested(run.id)+ assert not drain.is_alive()+ assert isinstance(+ outcomes["first batch"], ResearchTerminatedException+ )+ finally:+ release.set()+ assert subagents.done.acquire(timeout=self.STOP_SECONDS)+ assert subagents.stopped == ["first batch"]+ assert subagents.model_calls == []diff --git a/tests/strategies/test_search_availability.py b/tests/strategies/test_search_availability.pyindex bbca300b05..b22980ada3 100644--- a/tests/strategies/test_search_availability.py+++ b/tests/strategies/test_search_availability.py@@ -1,9 +1,11 @@"""Real agent-loop and search-tool regressions for engine availability."""+import jsonimport timefrom concurrent.futures import ThreadPoolExecutor+from importlib import resourcesfrom types import SimpleNamespace-from threading import Barrier, Event+from threading import Barrier, Event, Lock, get_identfrom unittest.mock import Mock, patchimport pytest@@ -28,6 +30,7 @@ from local_deep_research.advanced_search_system.tools.search_availability importNoResearchToolsAvailable,SearchAvailabilityMiddleware,run_search,+ wait_for_cooldown,)from local_deep_research.exceptions import ResearchTerminatedExceptionfrom local_deep_research.web_search_engines.engine_availability import (@@ -565,6 +568,51 @@ def test_default_wait_sleeps_until_the_soonest_cooldown(tracker, clock):assert [t.name for t in captured[0].tools] == ["web_search"][email protected]("keep_fetch", [False, True])+def test_concurrent_redisable_keeps_waiting_within_run_budget(+ tracker, clock, keep_fetch+):+ """A second outage must not end research while its retry fits the budget."""+ tracker.disable("searxng", SearchFailure("first outage", 300))+ tools = [make_tool("web_search", tracker)]+ if keep_fetch:++ @make_langchain_tool+ def fetch_content(url: str) -> str:+ """Fetch a known page."""+ return ""++ tools.append(fetch_content)++ request = ModelRequest(model=Mock(), messages=[], tools=tools)+ re_disabled = False+ sleeps = []++ def sleep(seconds):+ nonlocal re_disabled+ sleeps.append(seconds)+ clock.now += seconds+ if clock.now >= 300 and not re_disabled:+ re_disabled = True+ # Another in-flight search fails as the first cooldown ends.+ tracker.disable("searxng", SearchFailure("second outage", 600))++ captured = []+ middleware = SearchAvailabilityMiddleware(+ tracker,+ "searxng",+ wait=lambda engines: wait_for_cooldown(tracker, engines, sleep=sleep),+ )+ middleware.wrap_model_call(request, captured.append)++ assert re_disabled+ assert sum(sleeps) == pytest.approx(900)+ assert [tool.name for tool in captured[0].tools] == [+ tool.name for tool in tools+ ]+ assert tracker.disabled() == {}++def test_research_subtopic_alone_is_not_sent_as_an_empty_tool_list(tracker):"""Delegation cannot help once its sub-tools are disabled too."""@@ -878,10 +926,16 @@ def test_cooldown_wait_honours_cancellation(tracker, clock):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."""+ """A re-disable mid-wait can extend the wait, never past the run budget.++ Another worker's retry fails as each cooldown ends. A temporary+ re-disable keeps the waiter waiting for as long as its next retry still+ fits the remaining wait budget; a run-long one ends the wait at once.+ """strategy, sleeps, fake_time = _cooldown_strategy(clock, tracker)- tracker.disable("searxng", SearchFailure("offline", 30))- bound = strategy_module.COOLDOWN_WAIT_SECONDS+ first_wait = 30+ tracker.disable("searxng", SearchFailure("offline", first_wait))+ bound = tracker.wait_budget_remaining()def disable_again():# Another worker's retry fails right as the cooldown ends.@@ -894,7 +948,12 @@ def test_cooldown_wait_is_bounded_when_engine_is_disabled_again(fake_time.hooks.append(disable_again)with patch.object(strategy_module, "time", fake_time):strategy._wait_for_cooldown({"searxng"})- assert 29 <= sum(sleeps) <= bound+ if cooldown is None:+ expected = first_wait+ else:+ expected = first_wait + cooldown * ((bound - first_wait) // cooldown)+ assert sum(sleeps) == pytest.approx(expected, abs=1)+ assert sum(sleeps) <= boundassert "searxng" in tracker.disabled()@@ -1052,33 +1111,41 @@ def _always_rate_limited_run(tracker, clock, retry_after):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- )+ """Repeated 10-minute cooldowns use the shared one-hour budget."""+ tracker = SearchEngineAvailability(clock=lambda: clock.now)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+ assert sum(sleeps) == pytest.approx(3600, abs=0.1)+ assert engine.run.call_count == 7state = tracker.disabled()["searxng"]assert state.retry_at is None- assert "waited" in state.failure.reason+ assert "wait budget" in state.failure.reason-def test_repeated_cooldowns_stop_after_the_consecutive_limit(tracker, clock):+def test_repeated_cooldowns_continue_past_three_failures(clock):+ tracker = SearchEngineAvailability(+ clock=lambda: clock.now, wait_budget_seconds=240+ )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+ assert sum(sleeps) == pytest.approx(240, abs=0.1)+ assert engine.run.call_count == 5+ assert "wait budget" 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)+def test_retry_after_beyond_the_budget_is_not_waited_for(tracker, clock):+ engine, sleeps = _always_rate_limited_run(tracker, clock, 7200)assert sleeps == []assert engine.run.call_count == 1+def test_configured_two_hour_budget_waits_for_hour_long_retry(clock):+ tracker = SearchEngineAvailability(+ clock=lambda: clock.now, wait_budget_seconds=7200+ )+ engine, sleeps = _always_rate_limited_run(tracker, clock, 3600)+ assert sum(sleeps) == pytest.approx(7200, abs=0.1)+ assert engine.run.call_count == 3++def test_a_successful_search_resets_the_cooldown_streak(clock):tracker = SearchEngineAvailability(clock=lambda: clock.now, max_consecutive_cooldowns=1@@ -1134,6 +1201,54 @@ def test_default_middleware_wait_honours_cancellation(clock):assert len(sleeps) == 2+def test_one_cancel_stops_every_parallel_cooldown_wait(clock):+ """The research's termination flag is single-use.++ The check that sees it first cleans the run up and clears it, as+ research_service's progress_callback does, so the other waiter has to+ learn of the cancel from the tracker they share.+ """+ cancel, lock, consumed = Event(), Lock(), []++ def check_cancelled():+ with lock:+ if not cancel.is_set():+ return+ cancel.clear()+ consumed.append(get_ident())+ raise ResearchTerminatedException("cancelled")++ tracker = SearchEngineAvailability(+ clock=lambda: clock.now, check_cancelled=check_cancelled+ )+ tracker.disable("searxng", SearchFailure("offline", 300))+ all_waiting = Barrier(3, timeout=5)+ waiting = set()+ give_up = time.monotonic() + 5++ def sleep(_seconds):+ # Real time passes but the tracker's clock does not, so only the+ # cancel can end these waits.+ if get_ident() not in waiting:+ waiting.add(get_ident())+ all_waiting.wait()+ elif time.monotonic() > give_up:+ raise TimeoutError("this cooldown wait never saw the cancel")+ else:+ time.sleep(0.001)++ with ThreadPoolExecutor(max_workers=2) as pool:+ waits = [+ pool.submit(wait_for_cooldown, tracker, {"searxng"}, sleep=sleep)+ for _ in range(2)+ ]+ all_waiting.wait()+ cancel.set()+ outcomes = [wait.exception(timeout=10) for wait in waits]+ assert all(isinstance(o, ResearchTerminatedException) for o in outcomes)+ assert len(consumed) == 1++def test_strategy_tracker_checks_the_research_termination_flag():strategy = strategy_module.LangGraphAgentStrategy(model=Mock(),@@ -1148,3 +1263,65 @@ def test_strategy_tracker_checks_the_research_termination_flag():with pytest.raises(ResearchTerminatedException):strategy.engine_availability.check_cancelled()check.assert_called_once_with(strategy_module.CHECK_CONTEXT_ENTRY)+++ "configured,expected",+ [("7200", 7200), (0, 0), (float("nan"), 3600), (-1, 3600)],+)+def test_strategy_uses_configured_cooldown_wait_budget(configured, expected):+ strategy = strategy_module.LangGraphAgentStrategy(+ model=Mock(),+ search=Mock(last_search_failure=None),+ settings_snapshot={+ "search.tool": "searxng",+ "langgraph_agent.cooldown_wait_budget_seconds": configured,+ },+ )+ assert strategy.engine_availability.wait_budget_remaining() == expected+++ "wait_budget,timeout,expected",+ [+ (3600, 10800, 10800),+ (7200, 7200, 9000),+ (0, 60, 1800),+ (3600, "bad", 7200),+ # Below the setting's minimum is invalid; the minimum itself is kept+ # (then raised to the cooldown budget plus 30 minutes).+ (3600, 59, 7200),+ (3600, 60, 5400),+ ],+)+def test_subagent_timeout_allows_the_full_cooldown_budget(+ wait_budget, timeout, expected+):+ strategy = strategy_module.LangGraphAgentStrategy(+ model=Mock(),+ search=Mock(last_search_failure=None),+ settings_snapshot={+ "search.tool": "searxng",+ "langgraph_agent.cooldown_wait_budget_seconds": wait_budget,+ "langgraph_agent.subagent_timeout_seconds": timeout,+ },+ )+ assert strategy.subagent_timeout_seconds == expected+++def test_subagent_timeout_setting_matches_the_strategy_bounds():+ """The stored default and minimum, the form's step grid and the+ strategy's own validation must agree."""+ defaults = json.loads(+ (+ resources.files("local_deep_research")+ / "defaults"+ / "default_settings.json"+ ).read_text(encoding="utf-8")+ )+ setting = defaults["langgraph_agent.subagent_timeout_seconds"]+ assert setting["value"] == strategy_module.SUBAGENT_TIMEOUT_SECONDS+ assert setting["min_value"] == strategy_module.MIN_SUBAGENT_TIMEOUT_SECONDS+ # A number input steps from its min: a default off that grid reads as+ # invalid in the form and its spinner snaps to a different value.+ assert (setting["value"] - setting["min_value"]) % setting["step"] == 0diff --git a/tests/strategies/test_strategy_instantiation.py b/tests/strategies/test_strategy_instantiation.pyindex 903e240959..757043e523 100644--- a/tests/strategies/test_strategy_instantiation.py+++ b/tests/strategies/test_strategy_instantiation.py@@ -171,7 +171,10 @@ class TestProgressCallbackSetup:callback = Mock()strategy.set_progress_callback(callback)- assert strategy.progress_callback == callback+ # A strategy may store a wrapper (langgraph-agent records cancels+ # on its availability tracker) that forwards every update.+ strategy.progress_callback("Searching", 10, {"phase": "search"})+ callback.assert_called_once_with("Searching", 10, {"phase": "search"})class TestStrategyDefaultValues:diff --git a/tests/web_search_engines/test_engine_availability.py b/tests/web_search_engines/test_engine_availability.pyindex f1ef5eef03..51ceaf07f7 100644--- a/tests/web_search_engines/test_engine_availability.py+++ b/tests/web_search_engines/test_engine_availability.py@@ -10,7 +10,8 @@ import pytestimport requestsfrom local_deep_research.web_search_engines.engine_availability import (- MAX_COOLDOWN_SECONDS,+ COOLDOWN_WAIT_BUDGET_SECONDS,+ MAX_TEMPORARY_COOLDOWN_SECONDS,SearchEngineAvailability,SearchFailure,available_tool_names,@@ -159,28 +160,104 @@ def test_403_block_page_is_a_cooldown_not_a_run_long_disable():assert failure_from_exception(error).cooldown_seconds == 300-def test_cooldown_up_to_the_cap_is_kept(tracker, clock):+def test_one_hour_cooldown_is_kept(tracker, clock):state = tracker.disable(- "pubmed", SearchFailure("Rate limit", MAX_COOLDOWN_SECONDS)+ "pubmed", SearchFailure("Rate limit", COOLDOWN_WAIT_BUDGET_SECONDS))- assert state.retry_at - state.disabled_at == MAX_COOLDOWN_SECONDS- clock.monotonic += MAX_COOLDOWN_SECONDS+ assert state.retry_at - state.disabled_at == COOLDOWN_WAIT_BUDGET_SECONDS+ clock.monotonic += COOLDOWN_WAIT_BUDGET_SECONDSassert tracker.disabled() == {}-def test_provider_retry_after_beyond_the_cap_disables_for_the_run(+def test_provider_retry_after_beyond_the_wait_budget_stays_temporary(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+ state = tracker.disable("pubmed", SearchFailure("Rate limit", 7200))+ assert state.retry_at == clock.wall + 7200assert "Rate limit" in state.failure.reason- assert f"longer than {MAX_COOLDOWN_SECONDS}s" in state.failure.reason- clock.monotonic += 86_400+ clock.monotonic += 7200+ assert tracker.disabled() == {}+++def test_absurd_retry_after_disables_for_the_run_with_a_clear_reason(+ tracker, clock+):+ """An HTTP date years away is no cooldown to show or plan around."""+ date = format_datetime(+ datetime(9998, 12, 31, 23, 59, 59, tzinfo=UTC), usegmt=True+ )+ delay = retry_after_seconds(date, now=clock.wall)+ assert delay > 10**11 # parseable, so it reaches the tracker as-is+ state = tracker.disable(+ "pubmed", SearchFailure("Rate limit reached", delay)+ )+ assert state.retry_at is None+ assert "Rate limit reached" in state.failure.reason+ assert (+ f"asked to wait longer than {MAX_TEMPORARY_COOLDOWN_SECONDS}s"+ in state.failure.reason+ )+ described = state.describe()+ assert "for the rest of this research" in described+ assert "9998" not in described+ clock.monotonic += 10 * 365 * 86_400assert "pubmed" in tracker.disabled()-def test_consecutive_cooldowns_end_in_a_run_long_disable(clock):+def test_provider_error_with_an_absurd_retry_after_disables_for_the_run(+ tracker,+):+ failure = failure_from_exception(RateLimitError("x", retry_after=10**9))+ assert failure.cooldown_seconds == 10**9+ assert tracker.disable("pubmed", failure).retry_at is None+++ "budget,delay,temporary",+ [+ (COOLDOWN_WAIT_BUDGET_SECONDS, MAX_TEMPORARY_COOLDOWN_SECONDS, True),+ (+ COOLDOWN_WAIT_BUDGET_SECONDS,+ MAX_TEMPORARY_COOLDOWN_SECONDS + 1,+ False,+ ),+ # A zero budget means "never wait", not "every cooldown is run-long".+ (0, 7200, True),+ # A budget above the limit raises it: whatever a waiter could wait+ # for must stay a cooldown.+ (3 * 86_400, 2 * 86_400, True),+ (3 * 86_400, 3 * 86_400, True),+ (3 * 86_400, 3 * 86_400 + 1, False),+ ],+)+def test_longest_temporary_cooldown_follows_the_wait_budget(+ clock, budget, delay, temporary+):+ tracker = SearchEngineAvailability(+ clock=lambda: clock.monotonic,+ wall_clock=lambda: clock.wall,+ wait_budget_seconds=budget,+ )+ state = tracker.disable("pubmed", SearchFailure("Rate limit", delay))+ assert (state.retry_at is not None) is temporary+ if temporary:+ assert state.retry_at - state.disabled_at == delay+ else:+ assert "asked to wait longer than" in state.failure.reason+++def test_default_does_not_disable_after_three_temporary_failures(clock):+ tracker = SearchEngineAvailability(+ clock=lambda: clock.monotonic, wall_clock=lambda: clock.wall+ )+ for _ in range(4):+ state = tracker.disable("searxng", SearchFailure("Rate limit", 60))+ assert state.retry_at is not None+ clock.monotonic += 60+ assert tracker.disabled() == {}+++def test_opt_in_consecutive_cooldown_limit(clock):tracker = SearchEngineAvailability(clock=lambda: clock.monotonic,wall_clock=lambda: clock.wall,@@ -246,7 +323,7 @@ def test_end_cooldowns_disables_only_cooling_engines(tracker):disabled = tracker.disabled()assert disabled["searxng"].retry_at is Noneassert "Rate limit" in disabled["searxng"].failure.reason- assert "waited" in disabled["searxng"].failure.reason+ assert "wait budget" in disabled["searxng"].failure.reasonassert disabled["pubmed"].failure.reason == "Bad key"assert "arxiv" not in disabled