~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: address 5 code-level issues from audit (#3379)
LearningCircuit80a1203a111f
diff --git a/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py b/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.pyindex c60eb6d820..1efd9b00f2 100644--- a/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py@@ -922,28 +922,23 @@ Provide a helpful response explaining what was found and why no definitive answeimport asynciotry:- # Run the async method in a new event loop if needed+ # Run async search — detect whether we're inside an event looptry:- loop = asyncio.get_event_loop()- if loop.is_running():- # If loop is already running, create a new task- import concurrent.futures-- with concurrent.futures.ThreadPoolExecutor() as executor:- future = executor.submit(- thread_cleanup(- lambda: asyncio.run(- self._analyze_topic_async(query)- )+ asyncio.get_running_loop()+ # Inside a running loop — run in a thread to avoid nesting+ import concurrent.futures++ with concurrent.futures.ThreadPoolExecutor() as executor:+ future = executor.submit(+ thread_cleanup(+ lambda: asyncio.run(+ self._analyze_topic_async(query)))- return future.result()- else:- return loop.run_until_complete(- self._analyze_topic_async(query))+ return future.result()except RuntimeError:- # No event loop running, create new one+ # No running event loop — safe to use asyncio.run() directlyreturn asyncio.run(self._analyze_topic_async(query))except Exception as e:diff --git a/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py b/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.pyindex 488de0848d..74b0f89829 100644--- a/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py@@ -401,27 +401,19 @@ class LLMDrivenModularStrategy(BaseSearchStrategy):try:import asyncio- # Create a new event loop if none exists or if the current loop is running+ # Run async search — detect whether we're inside an event looptry:- loop = asyncio.get_event_loop()- if loop.is_running():- # If we're already in an async context, run in a new thread- import concurrent.futures-- with concurrent.futures.ThreadPoolExecutor() as executor:- future = executor.submit(- thread_cleanup(- lambda: asyncio.run(self.search(query))- )- )- answer, metadata = future.result()- else:- # If not in async context, run directly- answer, metadata = loop.run_until_complete(- self.search(query)+ asyncio.get_running_loop()+ # Inside a running loop — run in a thread to avoid nesting+ import concurrent.futures++ with concurrent.futures.ThreadPoolExecutor() as executor:+ future = executor.submit(+ thread_cleanup(lambda: asyncio.run(self.search(query))))+ answer, metadata = future.result()except RuntimeError:- # No event loop, create one+ # No running event loop — safe to use asyncio.run() directlyanswer, metadata = asyncio.run(self.search(query))return {diff --git a/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py b/src/local_deep_research/advanced_search_system/strategies/modular_strategy.pyindex 6ae460096e..bab240d8e0 100644--- a/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py@@ -1081,27 +1081,17 @@ Provide a clear, factual answer that addresses the original question and explain# Run the search asynchronouslyimport asyncio- # Create a new event loop if none exists or if the current loop is running+ # Run async search — detect whether we're inside an event looptry:- loop = asyncio.get_event_loop()- if loop.is_running():- # If we're already in an async context, run in a new thread- import concurrent.futures-- with concurrent.futures.ThreadPoolExecutor() as executor:- future = executor.submit(- thread_cleanup(- lambda: asyncio.run(self.search(query))- )- )- answer, metadata = future.result()- else:- # If not in async context, run directly- answer, metadata = loop.run_until_complete(- self.search(query)+ asyncio.get_running_loop()+ # Inside a running loop — run in a thread to avoid nesting+ with ThreadPoolExecutor() as executor:+ future = executor.submit(+ thread_cleanup(lambda: asyncio.run(self.search(query))))+ answer, metadata = future.result()except RuntimeError:- # No event loop, create one+ # No running event loop — safe to use asyncio.run() directlyanswer, metadata = asyncio.run(self.search(query))return {diff --git a/src/local_deep_research/advanced_search_system/strategies/news_strategy.py b/src/local_deep_research/advanced_search_system/strategies/news_strategy.pyindex 836df7fd21..c470e437c6 100644--- a/src/local_deep_research/advanced_search_system/strategies/news_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/news_strategy.py@@ -245,28 +245,20 @@ Ensure variety across different categories when possible.# Analyze findings - handle both sync and async contextstry:# Check if we're already in an async context- loop = asyncio.get_event_loop()- if loop.is_running():- # We're in an async context, create a task- import concurrent.futures-- with concurrent.futures.ThreadPoolExecutor() as executor:- future = executor.submit(- thread_cleanup(- lambda: asyncio.run(- self.analyze_findings(all_findings)- )- )+ asyncio.get_running_loop()+ # We're in an async context — run in a thread to avoid nesting+ import concurrent.futures++ with concurrent.futures.ThreadPoolExecutor() as executor:+ future = executor.submit(+ thread_cleanup(+ lambda: asyncio.run(self.analyze_findings(all_findings)))- analysis = future.result()- else:- # We're in a sync context, use run_until_complete- analysis = loop.run_until_complete(- self.analyze_findings(all_findings))+ analysis = future.result()except RuntimeError:- # No event loop — asyncio.run() creates one, runs the coroutine,- # drains pending tasks, and closes the loop automatically.+ # No running event loop — asyncio.run() creates one, runs the+ # coroutine, drains pending tasks, and closes the loop automatically.analysis = asyncio.run(self.analyze_findings(all_findings))return {diff --git a/src/local_deep_research/database/models/settings.py b/src/local_deep_research/database/models/settings.pyindex bbbab64a03..3190b19e10 100644--- a/src/local_deep_research/database/models/settings.py+++ b/src/local_deep_research/database/models/settings.py@@ -14,7 +14,6 @@ from sqlalchemy import (Integer,String,Text,- UniqueConstraint,)from sqlalchemy_utc import UtcDateTime, utcnow@@ -106,7 +105,8 @@ class Setting(Base):UtcDateTime, server_default=utcnow(), onupdate=utcnow(), nullable=False)- __table_args__ = (UniqueConstraint("key", name="uix_settings_key"),)+ # unique=True on the key column already creates a unique constraint;+ # the separate UniqueConstraint was removed to avoid Alembic autogenerate drift.def __repr__(self):return f"<Setting(key='{self.key}', type={self.type.value})>"diff --git a/src/local_deep_research/utilities/search_utilities.py b/src/local_deep_research/utilities/search_utilities.pyindex 8f200d7c09..9ec3224272 100644--- a/src/local_deep_research/utilities/search_utilities.py+++ b/src/local_deep_research/utilities/search_utilities.py@@ -64,12 +64,12 @@ def extract_links_from_search_results(search_results: List[Dict]) -> List[Dict]:def format_links_to_markdown(all_links: List[Dict]) -> str:- formatted_text = ""+ parts: list[str] = []logger.info(f"Formatting {len(all_links)} links to markdown...")if all_links:# Group links by URL and collect all their indices- url_to_indices = {}+ url_to_indices: dict[str, list] = {}for link in all_links:url = link.get("url")if url is None:@@ -81,7 +81,7 @@ def format_links_to_markdown(all_links: List[Dict]) -> str:url_to_indices[url].append(index)# Format each unique URL with all its indices- seen_urls = set() # Initialize the set here+ seen_urls: set[str] = set()for link in all_links:url = link.get("url")if url is None:@@ -95,12 +95,14 @@ def format_links_to_markdown(all_links: List[Dict]) -> str:# Format as [1, 3, 5] if multiple indices, or just [1] if singleindices_str = f"[{', '.join(map(str, indices))}]"# Add (source nr) as a visible fallback for humans- formatted_text += f"{indices_str} {title} (source nr: {', '.join(map(str, indices))})\n URL: {url}\n\n"+ parts.append(+ f"{indices_str} {title} (source nr: {', '.join(map(str, indices))})\n URL: {url}\n\n"+ )seen_urls.add(url)- formatted_text += "\n"+ parts.append("\n")- return formatted_text+ return "".join(parts)def format_findings(@@ -121,7 +123,7 @@ def format_findings(logger.info(f"Inside format_findings utility. Findings count: {len(findings_list)}, Questions iterations: {len(questions_by_iteration)}")- formatted_text = ""+ parts: list[str] = []# Extract all sources from findingsall_links = []@@ -135,28 +137,28 @@ def format_findings(logger.exception("Error processing search results/links")# Start with the synthesized content (passed as synthesized_content)- formatted_text += f"{synthesized_content}\n\n"+ parts.append(f"{synthesized_content}\n\n")# Add sources section after synthesized content if sources exist- formatted_text += format_links_to_markdown(all_links)+ parts.append(format_links_to_markdown(all_links))- formatted_text += "\n\n" # Separator after synthesized content+ parts.append("\n\n") # Separator after synthesized content# Add Search Questions by Iteration sectionif questions_by_iteration:- formatted_text += "## SEARCH QUESTIONS BY ITERATION\n"- formatted_text += "\n"+ parts.append("## SEARCH QUESTIONS BY ITERATION\n")+ parts.append("\n")for iter_num, questions in questions_by_iteration.items():- formatted_text += f"\n #### Iteration {iter_num}:\n"+ parts.append(f"\n #### Iteration {iter_num}:\n")for i, q in enumerate(questions, 1):- formatted_text += f"{i}. {q}\n"- formatted_text += "\n" + "\n\n"+ parts.append(f"{i}. {q}\n")+ parts.append("\n\n\n")else:logger.warning("No questions by iteration found to format.")# Add Detailed Findings sectionif findings_list:- formatted_text += "## DETAILED FINDINGS\n\n"+ parts.append("## DETAILED FINDINGS\n\n")logger.info(f"Formatting {len(findings_list)} detailed finding items.")for idx, finding in enumerate(findings_list):@@ -169,25 +171,27 @@ def format_findings(search_results = finding.get("search_results", [])# Phase header- formatted_text += "\n"- formatted_text += f"### {phase}\n"- formatted_text += "\n\n"+ parts.append(f"\n### {phase}\n\n\n")question_displayed = False# If this is a follow-up phase, try to show the corresponding questionif isinstance(phase, str) and phase.startswith("Follow-up"):try:- parts = phase.replace("Follow-up Iteration ", "").split(".")- if len(parts) == 2:- iteration = int(parts[0])- question_index = int(parts[1]) - 1+ phase_parts = phase.replace(+ "Follow-up Iteration ", ""+ ).split(".")+ if len(phase_parts) == 2:+ iteration = int(phase_parts[0])+ question_index = int(phase_parts[1]) - 1if (iteration in questions_by_iterationand 0<= question_index< len(questions_by_iteration[iteration])):- formatted_text += f"#### {questions_by_iteration[iteration][question_index]}\n\n"+ parts.append(+ f"#### {questions_by_iteration[iteration][question_index]}\n\n"+ )question_displayed = Trueelse:logger.warning(@@ -210,7 +214,7 @@ def format_findings(if 0 in questions_by_iteration and query_index < len(questions_by_iteration[0]):- formatted_text += (+ parts.append(f"#### {questions_by_iteration[0][query_index]}\n\n")question_displayed = True@@ -229,22 +233,18 @@ def format_findings(and "question" in findingand finding["question"]):- formatted_text += (- f"### SEARCH QUESTION:\n{finding['question']}\n\n"- )+ parts.append(f"### SEARCH QUESTION:\n{finding['question']}\n\n")# Content- formatted_text += f"\n\n{content}\n\n"+ parts.append(f"\n\n{content}\n\n")# Search results if they existif search_results:try:links = extract_links_from_search_results(search_results)if links:- formatted_text += "### SOURCES USED IN THIS SECTION:\n"- formatted_text += (- format_links_to_markdown(links) + "\n\n"- )+ parts.append("### SOURCES USED IN THIS SECTION:\n")+ parts.append(format_links_to_markdown(links) + "\n\n")except Exception:logger.exception(f"Error processing search results/links for finding {idx}"@@ -252,19 +252,19 @@ def format_findings(else:logger.debug(f"No search_results found for finding item {idx}.")- formatted_text += f"{'_' * 80}\n\n"+ parts.append(f"{'_' * 80}\n\n")else:logger.warning("No detailed findings found to format.")# Add summary of all sources at the endif all_links:- formatted_text += "## ALL SOURCES:\n"- formatted_text += format_links_to_markdown(all_links)+ parts.append("## ALL SOURCES:\n")+ parts.append(format_links_to_markdown(all_links))else:logger.info("No unique sources found across all findings to list.")logger.info("Finished format_findings utility.")- return formatted_text+ return "".join(parts)def print_search_results(search_results):diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 39361e1df4..2d8271abd4 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -41,6 +41,8 @@ _global_research_semaphore = threading.Semaphore(_MAX_GLOBAL_CONCURRENT)# Socket.IO emission throttling: minimum interval between progress emissions per research_EMIT_THROTTLE_SECONDS = 0.2 # 200ms+_EMIT_TTL_SECONDS = 3600 # 1 hour — evict stale entries from orphaned research+_emit_cleanup_counter = 0_last_emit_times: dict[str, float] = {}_last_emit_lock = threading.Lock()@@ -523,6 +525,17 @@ def run_research_process(research_id, query, mode, **kwargs):if now - last >= _EMIT_THROTTLE_SECONDS:_last_emit_times[research_id] = nowshould_emit = True+ # Periodic TTL cleanup for orphaned entries+ global _emit_cleanup_counter # noqa: PLW0603+ _emit_cleanup_counter += 1+ if _emit_cleanup_counter % 100 == 0:+ stale = [+ rid+ for rid, t in _last_emit_times.items()+ if now - t > _EMIT_TTL_SECONDS+ ]+ for rid in stale:+ del _last_emit_times[rid]if should_emit:# Basic event data - include message for displaydiff --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 666a9a4910..0215acc662 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@@ -79,10 +79,16 @@ class WikipediaSearchEngine(BaseSearchEngine):logger.info(f"No Wikipedia results found for query: {query}")return []- # Create a cache for full pages (will be populated on-demand)- self._page_cache: dict[str, Any] = {}-- # Generate previews with summaries+ # Generate previews with summaries.+ # NOTE: This loop is intentionally sequential. Do NOT parallelize with+ # ThreadPoolExecutor because:+ # 1. The `wikipedia` PyPI library is not thread-safe — it uses global+ # mutable state (API_URL, RATE_LIMIT_LAST_CALL) and an unlocked cache.+ # Concurrent threads would corrupt the library's built-in rate limiting.+ # 2. self._last_wait_time is a shared instance attribute with no lock —+ # concurrent writes would feed incorrect data to record_outcome().+ # 3. Downstream _filter_for_relevance uses positional indices — random+ # completion order would cause the LLM to select wrong articles.previews = []for title in search_results:try: