~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: Complete migration away from get_setting_from_db_main_thread (#594)
LearningCircuit77126f0f7c10
diff --git a/.pre-commit-hooks/check-deprecated-settings-wrapper.py b/.pre-commit-hooks/check-deprecated-settings-wrapper.pyindex 2e1287788f..c46c8977a5 100755--- a/.pre-commit-hooks/check-deprecated-settings-wrapper.py+++ b/.pre-commit-hooks/check-deprecated-settings-wrapper.py@@ -90,8 +90,11 @@ def main():if filepath.suffix != ".py":continue- # Skip the file that defines the function (db_utils.py)- if filepath.name == "db_utils.py":+ # Skip the file that defines the function (db_utils.py) and this hook itself+ if filepath.name in [+ "db_utils.py",+ "check-deprecated-settings-wrapper.py",+ ]:continueerrors = check_file(filepath)@@ -128,9 +131,8 @@ def main():for line_num, error_msg in errors:print(f" Line {line_num}: {error_msg}")- # Return 0 to only warn, not fail- # Change to return 1 when ready to enforce- return 0+ # Return 1 to fail and enforce migration+ return 1return 0diff --git a/src/local_deep_research/benchmarks/graders.py b/src/local_deep_research/benchmarks/graders.pyindex 42b051d236..24174f514e 100644--- a/src/local_deep_research/benchmarks/graders.py+++ b/src/local_deep_research/benchmarks/graders.py@@ -83,18 +83,11 @@ def get_evaluation_llm(else api_key_setting)else:- # Fallback to database if no snapshot (not thread-safe)- from ..utilities.db_utils import get_setting_from_db_main_thread-- try:- api_key = get_setting_from_db_main_thread(- "llm.openai_endpoint.api_key"- )- except RuntimeError:- # In a thread context without snapshot- logger.warning(- "Cannot access database from thread without settings snapshot"- )+ # No settings snapshot available+ logger.warning(+ "No settings snapshot provided for benchmark grader. "+ "API key must be provided via settings_snapshot for thread safety."+ )if not api_key:logger.warning(diff --git a/src/local_deep_research/news/api.py b/src/local_deep_research/news/api.pyindex b9af6674a3..728296bdde 100644--- a/src/local_deep_research/news/api.py+++ b/src/local_deep_research/news/api.py@@ -960,18 +960,19 @@ def create_subscription(# within the Flask application context. For programmatic API access outside# the web context, callers should provide refresh_minutes explicitly to avoid# dependency on the settings database being initialized.- if refresh_minutes is None:- try:- from ..utilities.db_utils import get_setting_from_db_main_thread-- refresh_minutes = get_setting_from_db_main_thread(- "news.subscription.refresh_minutes", 240- )- except Exception:- # Fallback for when settings DB is not available (e.g., programmatic API usage)- refresh_minutes = 240 # Default to 4 hourswith get_user_db_session(user_id) as db_session:+ if refresh_minutes is None:+ try:+ from ..utilities.db_utils import get_settings_manager++ settings_manager = get_settings_manager(db_session, user_id)+ refresh_minutes = settings_manager.get_setting(+ "news.subscription.refresh_minutes", 240+ )+ except Exception:+ # Fallback for when settings DB is not available (e.g., programmatic API usage)+ refresh_minutes = 240 # Default to 4 hours# Create new subscriptionsubscription = NewsSubscription(id=str(uuid.uuid4()),diff --git a/src/local_deep_research/news/web.py b/src/local_deep_research/news/web.pyindex 34015b71cb..c4dbd03829 100644--- a/src/local_deep_research/news/web.py+++ b/src/local_deep_research/news/web.py@@ -80,7 +80,10 @@ def create_news_blueprint():# Only try to get settings if user is logged inif username != "anonymous":# Load user settings using the extracted function- load_user_settings(default_settings)+ from ...database.session_context import get_user_db_session++ with get_user_db_session(username) as db_session:+ load_user_settings(default_settings, db_session, username)return render_template("pages/news-subscription-form.html",@@ -127,7 +130,10 @@ def create_news_blueprint():# Load user's default settings if logged inif username != "anonymous":# Load user settings using the extracted function- load_user_settings(default_settings)+ from ...database.session_context import get_user_db_session++ with get_user_db_session(username) as db_session:+ load_user_settings(default_settings, db_session, username)except Exception as e:logger.exception(@@ -178,36 +184,44 @@ def create_news_blueprint():return bp-def load_user_settings(default_settings):+def load_user_settings(default_settings, db_session=None, username=None):"""Load user settings and update default_settings dictionary.Extracted to avoid code duplication as suggested by djpetti.Args:default_settings: Dictionary to update with user settings+ db_session: Database session for accessing settings+ username: Username for settings context"""+ if not db_session:+ logger.warning("No database session provided, using defaults")+ return+try:- from ..utilities.db_utils import get_setting_from_db_main_thread+ from ..utilities.db_utils import get_settings_manager++ settings_manager = get_settings_manager(db_session, username)default_settings.update({- "iterations": get_setting_from_db_main_thread(+ "iterations": settings_manager.get_setting("search.iterations", 3),- "questions_per_iteration": get_setting_from_db_main_thread(+ "questions_per_iteration": settings_manager.get_setting("search.questions_per_iteration", 5),- "search_engine": get_setting_from_db_main_thread(+ "search_engine": settings_manager.get_setting("search.tool", "auto"),- "model_provider": get_setting_from_db_main_thread(+ "model_provider": settings_manager.get_setting("llm.provider", "OLLAMA"),- "model": get_setting_from_db_main_thread("llm.model", ""),- "search_strategy": get_setting_from_db_main_thread(+ "model": settings_manager.get_setting("llm.model", ""),+ "search_strategy": settings_manager.get_setting("search.search_strategy", "source-based"),- "custom_endpoint": get_setting_from_db_main_thread(+ "custom_endpoint": settings_manager.get_setting("llm.openai_endpoint.url", ""),}diff --git a/src/local_deep_research/utilities/db_utils.py b/src/local_deep_research/utilities/db_utils.pyindex 158ae1172a..d4db48a67e 100644--- a/src/local_deep_research/utilities/db_utils.py+++ b/src/local_deep_research/utilities/db_utils.py@@ -1,6 +1,5 @@import functools-import os-from typing import Any, Callable, Dict+from typing import Any, Callablefrom cachetools import LRUCachefrom flask import g, has_app_context, session as flask_session@@ -142,81 +141,3 @@ def no_db_settings(func: Callable[..., Any]) -> Callable[..., Any]:manager.db_session = db_sessionreturn wrapper---def get_setting_from_db_main_thread(- key: str, default_value: Any | None = None, username: str | None = None-) -> str | Dict[str, Any] | None:- """- Get a setting from the database with fallback to default value.-- DEPRECATED: This function is redundant and will be removed in a future version.- For Flask routes/views, use:- with get_user_db_session(username) as db_session:- settings_manager = get_settings_manager(db_session, username)- value = settings_manager.get_setting(key, default)-- For background threads, use settings_snapshot pattern:- Pass settings_snapshot when creating threads/tasks- Use get_setting_from_snapshot(key, default, settings_snapshot=snapshot)-- Args:- key: The setting key.- default_value: If the setting is not found, it will return this instead.- username: Optional username for thread context (e.g., background research threads).-- Returns:- The setting value.-- """- import warnings-- warnings.warn(- "get_setting_from_db_main_thread is deprecated. Use SettingsManager with proper session context instead.",- DeprecationWarning,- stacklevel=2,- )- # In fallback LLM mode, always return default values without database access- if os.environ.get("LDR_USE_FALLBACK_LLM", ""):- logger.debug(- f"Using default value for {key} in fallback LLM environment"- )- return default_value-- # CRITICAL: Detect if we're in a background thread and raise an error- import threading-- # Check if we're in a background thread- thread_name = threading.current_thread().name-- # Allow MainThread during startup, but not other threads- if not has_app_context() and thread_name != "MainThread":- thread_id = threading.get_ident()- raise RuntimeError(- f"get_db_setting('{key}') called from background thread '{thread_name}' (ID: {thread_id}). "- f"Database access from threads is not allowed. Use settings_snapshot or thread-local settings context."- )-- try:- # Use the new session context to ensure proper database access- from ..database.session_context import get_user_db_session-- try:- with get_user_db_session(username) as db_session:- if db_session:- # Use the unified settings manager- settings_manager = get_settings_manager(- db_session, username- )- return settings_manager.get_setting(- key, default=default_value- )- except Exception:- # If we can't get a session, fall back to default- pass-- except Exception:- logger.exception(f"Error getting setting {key} from database")-- logger.warning(f"Could not read setting '{key}' from the database.")- return default_valuediff --git a/src/local_deep_research/utilities/log_utils.py b/src/local_deep_research/utilities/log_utils.pyindex a226db6013..0d180f0804 100644--- a/src/local_deep_research/utilities/log_utils.py+++ b/src/local_deep_research/utilities/log_utils.py@@ -278,17 +278,8 @@ def config_logger(name: str) -> None:os.environ.get("LDR_ENABLE_FILE_LOGGING", "").lower() == "true")- if not enable_file_logging:- # Try to get from database settings if available- try:- from .db_utils import get_setting_from_db_main_thread-- enable_file_logging = get_setting_from_db_main_thread(- "app.enable_file_logging", False- )- except Exception:- # Database not available yet, stick with default- pass+ # File logging is controlled only by environment variable for simplicity+ # Database settings are not available at logger initialization timeif enable_file_logging:log_file = _LOG_DIR / f"{name}.log"diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex 99bea3f0d0..a059d8442d 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -37,10 +37,7 @@ settings_bp = Blueprint("settings", __name__, url_prefix="/settings")def _get_setting_from_session(key: str, default=None):- """Helper to get a setting using the current session context.-- This is a temporary helper for migrating away from get_setting_from_db_main_thread.- """+ """Helper to get a setting using the current session context."""username = session.get("username")with get_user_db_session(username) as db_session:if db_session:@@ -1495,37 +1492,43 @@ def api_get_available_search_engines():try:# Get search engines using the same approach as search_engines_config.pyfrom ...web_search_engines.search_engines_config import search_config+ from ...database.session_context import get_user_db_sessionusername = session.get("username")- search_engines = search_config(username=username)-- # Extract search engines from config- engines_dict = {}- engine_options = []-- if search_engines:- # Format engines for API response- for engine_id, engine_data in search_engines.items():- engines_dict[engine_id] = {- "display_name": engine_data.get("display_name", engine_id),- "description": engine_data.get("description", ""),- "strengths": engine_data.get("strengths", []),- }+ with get_user_db_session(username) as db_session:+ search_engines = search_config(+ username=username, db_session=db_session+ )- engine_options.append(- {- "value": engine_id,- "label": engine_data.get("display_name", engine_id),+ # Extract search engines from config+ engines_dict = {}+ engine_options = []++ if search_engines:+ # Format engines for API response+ for engine_id, engine_data in search_engines.items():+ engines_dict[engine_id] = {+ "display_name": engine_data.get(+ "display_name", engine_id+ ),+ "description": engine_data.get("description", ""),+ "strengths": engine_data.get("strengths", []),}- )- # If no engines found, log the issue but return empty list- if not engine_options:- logger.warning("No search engines found in configuration")+ engine_options.append(+ {+ "value": engine_id,+ "label": engine_data.get("display_name", engine_id),+ }+ )- return jsonify(- {"engines": engines_dict, "engine_options": engine_options}- )+ # If no engines found, log the issue but return empty list+ if not engine_options:+ logger.warning("No search engines found in configuration")++ return jsonify(+ {"engines": engines_dict, "engine_options": engine_options}+ )except Exception:logger.exception("Error getting available search engines")diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.pyindex bfb6754a64..757d3b0acf 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py@@ -51,6 +51,7 @@ class GooglePSESearchEngine(BaseSearchEngine):llm=llm,max_filtered_results=max_filtered_results,max_results=max_results,+ **kwargs,)self.include_full_content = include_full_content@@ -89,19 +90,31 @@ class GooglePSESearchEngine(BaseSearchEngine):self.region = region# API key and Search Engine ID - check params, env vars, or database- from ...utilities.db_utils import get_setting_from_db_main_thread+ from ...config.thread_settings import get_setting_from_snapshotself.api_key = api_keyif not self.api_key:- self.api_key = get_setting_from_db_main_thread(- "search.engine.web.google_pse.api_key"- )+ try:+ self.api_key = get_setting_from_snapshot(+ "search.engine.web.google_pse.api_key",+ default=None,+ settings_snapshot=self.settings_snapshot,+ )+ except Exception:+ # No settings context available+ passself.search_engine_id = search_engine_idif not self.search_engine_id:- self.search_engine_id = get_setting_from_db_main_thread(- "search.engine.web.google_pse.engine_id"- )+ try:+ self.search_engine_id = get_setting_from_snapshot(+ "search.engine.web.google_pse.engine_id",+ default=None,+ settings_snapshot=self.settings_snapshot,+ )+ except Exception:+ # No settings context available+ passif not self.api_key:raise ValueError(diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_local.py b/src/local_deep_research/web_search_engines/engines/search_engine_local.pyindex eb2e132abb..da6d406249 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_local.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_local.py@@ -31,7 +31,7 @@ from langchain_text_splitters import RecursiveCharacterTextSplitterfrom loguru import loggerfrom ...config import search_config-from ...utilities.db_utils import get_setting_from_db_main_thread+from ...config.thread_settings import get_setting_from_snapshotfrom ...utilities.url_utils import normalize_urlfrom ..search_engine_base import BaseSearchEngine@@ -111,6 +111,7 @@ class LocalEmbeddingManager:chunk_size: int = 1000,chunk_overlap: int = 200,cache_dir: str = ".cache/local_search",+ settings_snapshot: Optional[Dict[str, Any]] = None,):"""Initialize the embedding manager for local document search.@@ -123,6 +124,7 @@ class LocalEmbeddingManager:chunk_size: Size of text chunks for splitting documentschunk_overlap: Overlap between chunkscache_dir: Directory to store embedding cache and index+ settings_snapshot: Optional settings snapshot for background threads"""self.embedding_model = embedding_model@@ -132,6 +134,7 @@ class LocalEmbeddingManager:self.chunk_size = chunk_sizeself.chunk_overlap = chunk_overlapself.cache_dir = Path(cache_dir)+ self.settings_snapshot = settings_snapshot or {}# Create cache directory if it doesn't existself.cache_dir.mkdir(parents=True, exist_ok=True)@@ -168,9 +171,16 @@ class LocalEmbeddingManager:if self.embedding_model_type == "ollama":# Use Ollama for embeddingsif not self.ollama_base_url:- raw_ollama_base_url = get_setting_from_db_main_thread(- "llm.ollama.url", "http://localhost:11434"- )+ try:+ raw_ollama_base_url = get_setting_from_snapshot(+ "llm.ollama.url",+ default="http://localhost:11434",+ settings_snapshot=self.settings_snapshot,+ )+ except Exception:+ # Fallback if no settings context available+ raw_ollama_base_url = "http://localhost:11434"+self.ollama_base_url = (normalize_url(raw_ollama_base_url)if raw_ollama_base_url@@ -733,6 +743,7 @@ class LocalSearchEngine(BaseSearchEngine):chunk_size=chunk_size,chunk_overlap=chunk_overlap,cache_dir=cache_dir,+ settings_snapshot=self.settings_snapshot,)# Index all foldersdiff --git a/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py b/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.pyindex 2a54122e30..60c4306c5e 100644--- a/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py+++ b/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py@@ -16,7 +16,6 @@ from tenacity.wait import wait_basefrom ..tracker import get_trackerfrom ..exceptions import RateLimitErrorfrom .detection import is_llm_rate_limit_error, extract_retry_after-from ....utilities.db_utils import get_setting_from_db_main_threadclass AdaptiveLLMWait(wait_base):@@ -76,12 +75,12 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):def _should_rate_limit(self) -> bool:"""Check if rate limiting should be applied to this LLM."""- # Check LLM-specific switch (disabled by default, independent of search rate limiting)- if not get_setting_from_db_main_thread(- "rate_limiting.llm_enabled", False- ):- return False+ # Rate limiting for LLMs is currently disabled by default+ # TODO: Pass settings_snapshot to enable proper configuration+ return False+ def _check_if_local_model(self) -> bool:+ """Check if the LLM is a local model that shouldn't be rate limited."""# Don't rate limit local modelslocal_providers = ["ollama",@@ -95,7 +94,7 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):logger.debug(f"Skipping rate limiting for local provider: {self.provider}")- return False+ return True# Check if base URL indicates local modelif hasattr(self.base_llm, "base_url"):@@ -107,9 +106,9 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):logger.debug(f"Skipping rate limiting for local URL: {base_url}")- return False+ return True- return True+ return Falsedef _get_rate_limit_key(self) -> str:"""Build composite key: provider-url-model"""diff --git a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py b/src/local_deep_research/web_search_engines/rate_limiting/tracker.pyindex 979ee70140..c06e84865c 100644--- a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py+++ b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py@@ -27,13 +27,11 @@ def _get_db_imports():try:from ...database.models import RateLimitAttempt, RateLimitEstimatefrom ...database.session_context import get_user_db_session- from ...utilities.db_utils import get_setting_from_db_main_thread_db_imports = {"RateLimitAttempt": RateLimitAttempt,"RateLimitEstimate": RateLimitEstimate,"get_user_db_session": get_user_db_session,- "get_setting_from_db_main_thread": get_setting_from_db_main_thread,}except (ImportError, RuntimeError):# Database not available - programmatic modediff --git a/src/local_deep_research/web_search_engines/search_engine_factory.py b/src/local_deep_research/web_search_engines/search_engine_factory.pyindex d69ec96b3c..4bca1a6ce9 100644--- a/src/local_deep_research/web_search_engines/search_engine_factory.py+++ b/src/local_deep_research/web_search_engines/search_engine_factory.py@@ -257,7 +257,9 @@ def _create_full_search_wrapper(config.update(web_engines)else:# Fallback to search_config if no snapshot (not recommended for threads)- config = search_config(username=username)+ config = search_config(+ username=username, settings_snapshot=settings_snapshot+ )if engine_name not in config:logger.warning(f"Engine config for {engine_name} not found")diff --git a/src/local_deep_research/web_search_engines/search_engines_config.py b/src/local_deep_research/web_search_engines/search_engines_config.pyindex 4c484eeb58..896e9a21a0 100644--- a/src/local_deep_research/web_search_engines/search_engines_config.py+++ b/src/local_deep_research/web_search_engines/search_engines_config.py@@ -4,14 +4,60 @@ Loads search engine definitions from the user's configuration."""import json-from typing import Any, Dict, List+from typing import Any, Dict, List, Optional+from sqlalchemy.orm import Sessionfrom loguru import logger-from ..utilities.db_utils import get_setting_from_db_main_thread+from ..config.thread_settings import get_setting_from_snapshot+from ..utilities.db_utils import get_settings_managerfrom .default_search_engines import get_default_elasticsearch_config+def _get_setting(+ key: str,+ default_value: Any = None,+ db_session: Optional[Session] = None,+ settings_snapshot: Optional[Dict[str, Any]] = None,+ username: Optional[str] = None,+) -> Any:+ """+ Get a setting from either a database session or settings snapshot.++ Args:+ key: The setting key+ default_value: Default value if setting not found+ db_session: Database session for direct access+ settings_snapshot: Settings snapshot for thread context+ username: Username for backward compatibility++ Returns:+ The setting value or default_value if not found+ """+ # Try settings snapshot first (thread context)+ if settings_snapshot:+ try:+ return get_setting_from_snapshot(+ key, default_value, settings_snapshot=settings_snapshot+ )+ except Exception as e:+ logger.debug(f"Could not get setting {key} from snapshot: {e}")++ # Try database session if available+ if db_session:+ try:+ settings_manager = get_settings_manager(db_session, username)+ return settings_manager.get_setting(key, default_value)+ except Exception as e:+ logger.debug(f"Could not get setting {key} from db_session: {e}")++ # Return default if all methods fail+ logger.warning(+ f"Could not retrieve setting '{key}', returning default: {default_value}"+ )+ return default_value++def _extract_per_engine_config(raw_config: Dict[str, Any],) -> Dict[str, Dict[str, Any]]:@@ -46,19 +92,37 @@ def _extract_per_engine_config(return nested_config-def search_config(username: str = None) -> Dict[str, Any]:+def search_config(+ username: Optional[str] = None,+ db_session: Optional[Session] = None,+ settings_snapshot: Optional[Dict[str, Any]] = None,+) -> Dict[str, Any]:"""- Returns:- The search engine configuration loaded from the database.+ Returns the search engine configuration loaded from the database or settings snapshot.+ Args:+ username: Username for backward compatibility (deprecated)+ db_session: Database session for direct access (preferred for web routes)+ settings_snapshot: Settings snapshot for thread context (preferred for background threads)++ Returns:+ The search engine configuration loaded from the database or snapshot."""# Extract search engine definitions- config_data = get_setting_from_db_main_thread(- "search.engine.web", {}, username=username+ config_data = _get_setting(+ "search.engine.web",+ {},+ db_session=db_session,+ settings_snapshot=settings_snapshot,+ username=username,)search_engines = _extract_per_engine_config(config_data)- search_engines["auto"] = get_setting_from_db_main_thread(- "search.engine.auto", {}, username=username+ search_engines["auto"] = _get_setting(+ "search.engine.auto",+ {},+ db_session=db_session,+ settings_snapshot=settings_snapshot,+ username=username,)# Add registered retrievers as available search engines@@ -96,8 +160,12 @@ def search_config(username: str = None) -> Dict[str, Any]:search_engines["elasticsearch"] = get_default_elasticsearch_config()# Register local document collections- local_collections_data = get_setting_from_db_main_thread(- "search.engine.local", {}, username=username+ local_collections_data = _get_setting(+ "search.engine.local",+ {},+ db_session=db_session,+ settings_snapshot=settings_snapshot,+ username=username,)local_collections_data = _extract_per_engine_config(local_collections_data)@@ -124,14 +192,18 @@ def search_config(username: str = None) -> Dict[str, Any]:"requires_llm": True,}engine_config_prefix = f"search.engine.local.{collection}"- engine_config["module_path"] = get_setting_from_db_main_thread(+ engine_config["module_path"] = _get_setting(f"{engine_config_prefix}.module_path","local_deep_research.web_search_engines.engines.search_engine_local",+ db_session=db_session,+ settings_snapshot=settings_snapshot,username=username,)- engine_config["class_name"] = get_setting_from_db_main_thread(+ engine_config["class_name"] = _get_setting(f"{engine_config_prefix}.class_name","LocalSearchEngine",+ db_session=db_session,+ settings_snapshot=settings_snapshot,username=username,)@@ -147,25 +219,53 @@ def search_config(username: str = None) -> Dict[str, Any]:return search_engines-def default_search_engine(username: str = None) -> str:+def default_search_engine(+ username: Optional[str] = None,+ db_session: Optional[Session] = None,+ settings_snapshot: Optional[Dict[str, Any]] = None,+) -> str:"""+ Returns the configured default search engine.++ Args:+ username: Username for backward compatibility (deprecated)+ db_session: Database session for direct access (preferred for web routes)+ settings_snapshot: Settings snapshot for thread context (preferred for background threads)+Returns:The configured default search engine.-"""- return get_setting_from_db_main_thread(- "search.engine.DEFAULT_SEARCH_ENGINE", "wikipedia", username=username+ return _get_setting(+ "search.engine.DEFAULT_SEARCH_ENGINE",+ "wikipedia",+ db_session=db_session,+ settings_snapshot=settings_snapshot,+ username=username,)-def local_search_engines(username: str = None) -> List[str]:+def local_search_engines(+ username: Optional[str] = None,+ db_session: Optional[Session] = None,+ settings_snapshot: Optional[Dict[str, Any]] = None,+) -> List[str]:"""+ Returns a list of the enabled local search engines.++ Args:+ username: Username for backward compatibility (deprecated)+ db_session: Database session for direct access (preferred for web routes)+ settings_snapshot: Settings snapshot for thread context (preferred for background threads)+Returns:A list of the enabled local search engines.-"""- local_collections_data = get_setting_from_db_main_thread(- "search.engine.local", {}, username=username+ local_collections_data = _get_setting(+ "search.engine.local",+ {},+ db_session=db_session,+ settings_snapshot=settings_snapshot,+ username=username,)local_collections_data = _extract_per_engine_config(local_collections_data)