~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
perf: Add compound database indexes and persistent thread pool
LearningCircuit53272bc9bfe7
diff --git a/src/local_deep_research/database/models/metrics.py b/src/local_deep_research/database/models/metrics.pyindex 5a5680f3a2..b7f91a1131 100644--- a/src/local_deep_research/database/models/metrics.py+++ b/src/local_deep_research/database/models/metrics.py@@ -7,6 +7,7 @@ from sqlalchemy import (Boolean,Column,Float,+ Index,Integer,String,Text,@@ -85,6 +86,19 @@ class TokenUsage(Base):Integer) # Generation time in nanoseconds (raw from Ollama API)+ # Compound indexes for query performance optimization+ __table_args__ = (+ Index("idx_token_research_timestamp", "research_id", "timestamp"),+ Index(+ "idx_token_model_timestamp",+ "model_provider",+ "model_name",+ "timestamp",+ ),+ Index("idx_token_operation_timestamp", "operation_type", "timestamp"),+ Index("idx_token_research_phase", "research_id", "research_phase"),+ )+def __repr__(self):return f"<TokenUsage(model={self.model_name}, total_tokens={self.total_tokens}, cost=${self.total_cost:.4f})>"@@ -183,5 +197,13 @@ class SearchCall(Base):error_type = Column(String(100))results_count = Column(Integer)+ # Compound indexes for query performance optimization+ __table_args__ = (+ Index("idx_search_research_timestamp", "research_id", "timestamp"),+ Index("idx_search_engine_timestamp", "search_engine", "timestamp"),+ Index("idx_search_success_timestamp", "success", "timestamp"),+ Index("idx_search_research_engine", "research_id", "search_engine"),+ )+def __repr__(self):return f"<SearchCall(engine={self.search_engine}, query='{self.query[:50]}...', success={self.success})>"diff --git a/src/local_deep_research/database/models/rate_limiting.py b/src/local_deep_research/database/models/rate_limiting.pyindex 05c6580574..f69d0e77e3 100644--- a/src/local_deep_research/database/models/rate_limiting.py+++ b/src/local_deep_research/database/models/rate_limiting.py@@ -2,7 +2,7 @@Rate limiting tracking models."""-from sqlalchemy import Boolean, Column, Float, Integer, String+from sqlalchemy import Boolean, Column, Float, Index, Integer, Stringfrom sqlalchemy_utc import UtcDateTime, utcnowfrom .base import Base@@ -24,6 +24,18 @@ class RateLimitAttempt(Base):error_type = Column(String(100), nullable=True)created_at = Column(UtcDateTime, server_default=utcnow(), nullable=False)+ # Compound indexes for query performance optimization+ __table_args__ = (+ Index("idx_ratelimit_engine_timestamp", "engine_type", "timestamp"),+ Index("idx_ratelimit_success_timestamp", "success", "timestamp"),+ Index(+ "idx_ratelimit_engine_success",+ "engine_type",+ "success",+ "timestamp",+ ),+ )+def __repr__(self):return f"<RateLimitAttempt(engine={self.engine_type}, success={self.success}, wait={self.wait_time}s)>"diff --git a/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py b/src/local_deep_research/web_search_engines/engines/parallel_search_engine.pyindex 3eb60308d3..e42b3b6eb1 100644--- a/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py+++ b/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py@@ -83,6 +83,16 @@ class ParallelSearchEngine(BaseSearchEngine):self.engine_cache = {}self.cache_lock = Lock()+ # Persistent thread pool for parallel searches (performance optimization)+ # Reusing threads avoids repeated thread creation/destruction overhead+ self.max_workers = kwargs.get("max_workers", 20)+ self._executor = concurrent.futures.ThreadPoolExecutor(+ max_workers=self.max_workers, thread_name_prefix="parallel_search_"+ )+ logger.debug(+ f"Initialized persistent ThreadPool with {self.max_workers} workers"+ )+# Get available engines (excluding 'meta', 'auto', and 'parallel')self.available_engines = self._get_available_engines()logger.info(@@ -496,70 +506,65 @@ Select up to {self.max_engines_to_select} engines that would best answer this quexcept Exception:logger.exception("Socket emit error (non-critical)")- # Execute all engines in parallel+ # Execute all engines in parallel using persistent thread poolall_results = []engine_results = {}- with concurrent.futures.ThreadPoolExecutor(- max_workers=len(selected_engines)- ) as executor:- # Submit all tasks- future_to_engine = {- executor.submit(- self._execute_single_engine, engine_name, query- ): engine_name- for engine_name in selected_engines- }+ # Submit all tasks to the persistent executor+ future_to_engine = {+ self._executor.submit(+ self._execute_single_engine, engine_name, query+ ): engine_name+ for engine_name in selected_engines+ }++ # Collect results as they complete+ for future in concurrent.futures.as_completed(future_to_engine):+ engine_name = future_to_engine[future]+ try:+ result = future.result()+ engine_results[engine_name] = result++ if result["success"]:+ # Add source information to each result+ for item in result["results"]:+ item["search_engine"] = engine_name+ all_results.extend(result["results"])++ # Emit success event+ try:+ SocketIOService().emit_socket_event(+ "engine_completed",+ {+ "engine": engine_name,+ "success": True,+ "count": result["count"],+ },+ )+ except Exception:+ logger.debug("Socket emit error (non-critical)")+ else:+ # Emit failure event+ try:+ SocketIOService().emit_socket_event(+ "engine_completed",+ {+ "engine": engine_name,+ "success": False,+ "error": result.get("error", "Unknown error"),+ },+ )+ except Exception:+ logger.debug("Socket emit error (non-critical)")- # Collect results as they complete- for future in concurrent.futures.as_completed(future_to_engine):- engine_name = future_to_engine[future]- try:- result = future.result()- engine_results[engine_name] = result-- if result["success"]:- # Add source information to each result- for item in result["results"]:- item["search_engine"] = engine_name- all_results.extend(result["results"])-- # Emit success event- try:- SocketIOService().emit_socket_event(- "engine_completed",- {- "engine": engine_name,- "success": True,- "count": result["count"],- },- )- except Exception:- logger.debug("Socket emit error (non-critical)")- else:- # Emit failure event- try:- SocketIOService().emit_socket_event(- "engine_completed",- {- "engine": engine_name,- "success": False,- "error": result.get(- "error", "Unknown error"- ),- },- )- except Exception:- logger.debug("Socket emit error (non-critical)")-- except Exception as e:- logger.exception(f"Failed to get result from {engine_name}")- engine_results[engine_name] = {- "engine": engine_name,- "success": False,- "error": str(e),- "results": [],- }+ except Exception as e:+ logger.exception(f"Failed to get result from {engine_name}")+ engine_results[engine_name] = {+ "engine": engine_name,+ "success": False,+ "error": str(e),+ "results": [],+ }# Log summarysuccessful_engines = [@@ -653,3 +658,38 @@ Select up to {self.max_engines_to_select} engines that would best answer this qudef invoke(self, query: str) -> List[Dict[str, Any]]:"""Compatibility method for LangChain tools"""return self.run(query)++ def shutdown(self, wait: bool = True):+ """+ Shutdown the persistent thread pool.++ Should be called when the search engine is no longer needed to properly+ cleanup resources and ensure all pending tasks complete.++ Args:+ wait: If True, wait for all pending tasks to complete before shutdown+ """+ if hasattr(self, "_executor"):+ logger.info("Shutting down persistent ThreadPool")+ try:+ self._executor.shutdown(wait=wait)+ logger.info("ThreadPool shutdown complete")+ except Exception:+ logger.exception("Error during ThreadPool shutdown")++ def __del__(self):+ """Ensure thread pool is shutdown on deletion."""+ try:+ self.shutdown(wait=False)+ except Exception:+ # Silently ignore errors during cleanup+ pass++ def __enter__(self):+ """Support using as context manager."""+ return self++ def __exit__(self, exc_type, exc_val, exc_tb):+ """Cleanup on context manager exit."""+ self.shutdown(wait=True)+ return False