~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: prevent server overload and white page under sustained load (#2326)
LearningCircuit1f93aaec799f
diff --git a/.pre-commit-hooks/check-env-vars.py b/.pre-commit-hooks/check-env-vars.pyindex d0fcf3f0e1..337f69dd4c 100755--- a/.pre-commit-hooks/check-env-vars.py+++ b/.pre-commit-hooks/check-env-vars.py@@ -24,6 +24,7 @@ ALLOWED_PATTERNS = {"migrations/",# Bootstrap modules (run before SettingsManager is initialized)"log_utils.py", # Logger init before DB/SettingsManager+ "research_service.py", # Semaphore init at import time, before SettingsManager"server_config.py", # Fail-closed security validation for LDR_APP_ALLOW_REGISTRATIONS"security/rate_limiter.py", # Module-level RATE_LIMIT_FAIL_CLOSED at decorator time"sqlcipher_utils.py", # Encryption init needs LDR_TEST_MODE before SettingsManagerdiff --git a/docker-compose.yml b/docker-compose.ymlindex 849de6621d..208c7974d3 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -122,6 +122,31 @@ services:volumes:- ldr_data:/data- ldr_scripts:/scripts+ # ============================================================================+ # LOCAL DOCUMENT COLLECTIONS (Optional)+ # Mount your document directories here to search them with LDR.+ #+ # For Unraid users, replace paths with your Unraid shares:+ # - /mnt/user/documents/personal:/local_collections/personal_notes/:ro+ # - /mnt/user/documents/projects:/local_collections/project_docs/:ro+ # - /mnt/user/papers:/local_collections/research_papers/:ro+ #+ # The :ro (read-only) suffix is recommended for safety.+ # ============================================================================+ - ./local_collections/personal_notes:/local_collections/personal_notes/:ro+ - ./local_collections/project_docs:/local_collections/project_docs/:ro+ - ./local_collections/research_papers:/local_collections/research_papers/:ro+ # Resource limits to prevent OOM-killing the host under load+ deploy:+ resources:+ limits:+ memory: 4G+ cpus: '4'+ # Allow SQLCipher mlock() without noisy kernel warnings+ ulimits:+ memlock:+ soft: -1+ hard: -1# ============================================================================# CONTAINER SECURITY — Principle of Least Privilege# ============================================================================diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_service.py b/src/local_deep_research/benchmarks/web_api/benchmark_service.pyindex d809750d46..1b1bce8026 100644--- a/src/local_deep_research/benchmarks/web_api/benchmark_service.py+++ b/src/local_deep_research/benchmarks/web_api/benchmark_service.py@@ -11,6 +11,7 @@ from typing import Any, Dict, List, Optionalfrom loguru import loggerfrom ...api.research_functions import quick_summary+from ...web.services.research_service import _global_research_semaphorefrom ...database.models.benchmark import (BenchmarkResult,BenchmarkRun,@@ -484,12 +485,18 @@ class BenchmarkService:task["username"] = benchmark_data.get("username")task["user_password"] = benchmark_data.get("user_password")- # Process single task- result = self._process_benchmark_task(- task,- search_config,- evaluation_config,- )+ # Acquire the global research semaphore so benchmark+ # tasks count against the server-wide concurrency limit+ _global_research_semaphore.acquire()+ try:+ # Process single task+ result = self._process_benchmark_task(+ task,+ search_config,+ evaluation_config,+ )+ finally:+ _global_research_semaphore.release()# Store result in memory for now (will be saved later)if "results" not in self.active_runs[benchmark_run_id]:diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex 5eabfae54e..1f40fdf151 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -130,6 +130,21 @@"value": 3,"visible": true},+ "app.max_global_concurrent_researches": {+ "category": "app_interface",+ "description": "Maximum number of concurrent research processes allowed across all users (server-wide). Set via env var LDR_SERVER_MAX_CONCURRENT_RESEARCH. Requires server restart.",+ "editable": false,+ "env_var": "LDR_SERVER_MAX_CONCURRENT_RESEARCH",+ "max_value": 1000,+ "min_value": 1,+ "name": "Max Global Concurrent Researches",+ "options": null,+ "step": 1,+ "type": "APP",+ "ui_element": "number",+ "value": 10,+ "visible": false+ },"app.queue_mode": {"category": "app_interface","description": "Queue processing mode: 'direct' for immediate execution, 'queue' for background processing",diff --git a/src/local_deep_research/security/security_headers.py b/src/local_deep_research/security/security_headers.pyindex 49b0cfa07f..3895ea4e31 100644--- a/src/local_deep_research/security/security_headers.py+++ b/src/local_deep_research/security/security_headers.py@@ -80,6 +80,12 @@ class SecurityHeaders:app.config.setdefault("SECURITY_COEP_POLICY", "credentialless")self.app = app++ # Pre-compute static header values once at startup to avoid+ # regenerating identical strings on every response+ self._cached_csp = self.get_csp_policy()+ self._cached_permissions_policy = self.get_permissions_policy()+app.after_request(self.add_security_headers)# Validate CORS configuration at startup@@ -160,8 +166,7 @@ class SecurityHeaders:to 'require-corp', but this may break cross-origin API access."""# Content Security Policy - prevents XSS and injection attacks- csp = self.get_csp_policy()- response.headers["Content-Security-Policy"] = csp+ response.headers["Content-Security-Policy"] = self._cached_csp# Anti-clickjacking protectionresponse.headers["X-Frame-Options"] = "SAMEORIGIN"@@ -178,7 +183,7 @@ class SecurityHeaders:response.headers["Cross-Origin-Resource-Policy"] = "same-origin"# Permissions Policy - disable dangerous features- response.headers["Permissions-Policy"] = self.get_permissions_policy()+ response.headers["Permissions-Policy"] = self._cached_permissions_policy# Remove server version information to prevent information disclosureresponse.headers.pop("Server", None)diff --git a/src/local_deep_research/settings/env_definitions/__init__.py b/src/local_deep_research/settings/env_definitions/__init__.pyindex f1a0f56848..6ce53ff6d5 100644--- a/src/local_deep_research/settings/env_definitions/__init__.py+++ b/src/local_deep_research/settings/env_definitions/__init__.py@@ -7,6 +7,7 @@ from .bootstrap import BOOTSTRAP_SETTINGSfrom .db_config import DB_CONFIG_SETTINGSfrom .news_scheduler import NEWS_SCHEDULER_SETTINGSfrom .security import SECURITY_SETTINGS+from .server import SERVER_SETTINGS# Combine all settings for easy accessALL_SETTINGS = {@@ -15,6 +16,7 @@ ALL_SETTINGS = {"db_config": DB_CONFIG_SETTINGS,"news_scheduler": NEWS_SCHEDULER_SETTINGS,"security": SECURITY_SETTINGS,+ "server": SERVER_SETTINGS,}__all__ = [@@ -23,5 +25,6 @@ __all__ = ["DB_CONFIG_SETTINGS","NEWS_SCHEDULER_SETTINGS","SECURITY_SETTINGS",+ "SERVER_SETTINGS","ALL_SETTINGS",]diff --git a/src/local_deep_research/settings/env_definitions/server.py b/src/local_deep_research/settings/env_definitions/server.pynew file mode 100644index 0000000000..528e3541fd--- /dev/null+++ b/src/local_deep_research/settings/env_definitions/server.py@@ -0,0 +1,19 @@+"""+Server runtime environment settings.++These settings control server-level parameters that require a restart+to take effect. They are not editable via the UI.+"""++from ..env_settings import IntegerSetting++SERVER_SETTINGS = [+ IntegerSetting(+ key="server.max_concurrent_research",+ description="Server-wide maximum concurrent research operations. Requires restart.",+ min_value=1,+ max_value=1000,+ default=10,+ deprecated_env_var="LDR_MAX_GLOBAL_CONCURRENT",+ ),+]diff --git a/src/local_deep_research/web/auth/cleanup_middleware.py b/src/local_deep_research/web/auth/cleanup_middleware.pyindex 20c4a8568f..738d6f9e98 100644--- a/src/local_deep_research/web/auth/cleanup_middleware.py+++ b/src/local_deep_research/web/auth/cleanup_middleware.py@@ -3,6 +3,8 @@ Middleware to clean up completed research records.Runs in request context where we have database access."""+import random+from flask import g, sessionfrom loguru import loggerfrom sqlalchemy.exc import OperationalError, PendingRollbackError, TimeoutError@@ -15,11 +17,19 @@ def cleanup_completed_research():"""Clean up completed research records for the current user.Called as a before_request handler.++ Runs on only ~1% of requests to avoid unnecessary DB queries on+ every authenticated request (same sampling pattern used by+ session cleanup in middleware_optimizer.should_skip_session_cleanup)."""# Skip for requests that don't need database accessif should_skip_database_middleware():return+ # Only run cleanup on ~1% of requests to reduce per-request overhead+ if random.randint(1, 100) > 1: # noqa: S311 — not cryptographic, just sampling+ return+username = session.get("username")if username and hasattr(g, "db_session") and g.db_session:diff --git a/src/local_deep_research/web/auth/decorators.py b/src/local_deep_research/web/auth/decorators.pyindex b47086ee5f..a4a5f9e62d 100644--- a/src/local_deep_research/web/auth/decorators.py+++ b/src/local_deep_research/web/auth/decorators.py@@ -90,38 +90,42 @@ def get_current_db_session():def inject_current_user():"""Flask before_request handler to inject current user into g.++ Note: ensure_user_database() middleware already sets g.db_session+ when possible. We reuse that to avoid a redundant db_manager call."""g.current_user = current_user()if g.current_user:- # Try to get the database session- try:- g.db_session = db_manager.get_session(g.current_user)- if g.db_session is None:- # Check if we have an active database connection for this user- if not db_manager.is_user_connected(g.current_user):- # For authenticated users without a database connection,- # we need to handle this differently based on the route type-- # For API routes and auth routes, allow the request to continue- # The individual route handlers will deal with the missing database- if (- request.path.startswith("/api/")- or request.path.startswith("/auth/")- or request.path.startswith("/settings/api/")- ):- logger.debug(- f"No database for user {g.current_user} on API/auth route"- )- else:- # For regular routes, this is a stale session that needs clearing- logger.debug(- f"Clearing stale session for user {g.current_user}"- )- session.clear()- g.current_user = None- g.db_session = None- except Exception:- logger.exception(f"Error getting session for user {g.current_user}")+ # Reuse the session already established by ensure_user_database()+ if hasattr(g, "db_session") and g.db_session is not None:+ return++ # No session from earlier middleware — check connectivity+ if not db_manager.is_user_connected(g.current_user):+ # For API/auth routes, allow the request to continue+ if (+ request.path.startswith("/api/")+ or request.path.startswith("/auth/")+ or request.path.startswith("/settings/api/")+ ):+ logger.debug(+ f"No database for user {g.current_user} on API/auth route"+ )+ else:+ logger.debug(+ f"Clearing stale session for user {g.current_user}"+ )+ session.clear()+ g.current_user = Noneg.db_session = None+ else:+ # User is connected but session wasn't set by earlier middleware+ try:+ g.db_session = db_manager.get_session(g.current_user)+ except Exception:+ logger.exception(+ f"Error getting session for user {g.current_user}"+ )+ g.db_session = Noneelse:g.db_session = Nonediff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 0bd668197b..6b9fcc37f0 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -1,6 +1,7 @@import hashlibimport jsonimport threading+import timefrom datetime import datetime, UTCfrom pathlib import Path@@ -24,11 +25,24 @@ from ...utilities.log_utils import log_for_researchfrom ...utilities.search_utilities import extract_links_from_search_resultsfrom ...utilities.threading_utils import thread_context, thread_with_app_contextfrom ..models.database import calculate_duration+from ...settings.env_registry import get_env_settingfrom .socket_service import SocketIOServiceOUTPUT_DIR = get_research_outputs_directory()+# Global concurrent research limit (server-wide, across all users)+_MAX_GLOBAL_CONCURRENT = get_env_setting(+ "server.max_concurrent_research", default=10+)+_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+_last_emit_times: dict[str, float] = {}+_last_emit_lock = threading.Lock()++def _parse_research_metadata(research_meta) -> dict:"""Parse research_meta into a dict, handling both dict and JSON string types."""if isinstance(research_meta, dict):@@ -212,9 +226,19 @@ def start_research_process(# Pass the app context to the thread.run_research_callback = thread_with_app_context(run_research_callback)+ # Wrap callback with global concurrency limiter+ original_callback = run_research_callback++ def _rate_limited_callback(*args, **kw):+ _global_research_semaphore.acquire()+ try:+ return original_callback(*args, **kw)+ finally:+ _global_research_semaphore.release()+# Start research process in a background threadthread = threading.Thread(- target=run_research_callback,+ target=_rate_limited_callback,args=(thread_context(),research_id,@@ -503,14 +527,35 @@ def run_research_process(f"Cannot queue progress update for research {research_id} - no username available")- # Emit a socket event+ # Emit a socket event (throttled to avoid event storms)try:- # Basic event data- event_data = {"progress": adjusted_progress}-- SocketIOService().emit_to_subscribers(- "progress", research_id, event_data+ # Always emit completion/error states immediately;+ # throttle intermediate progress updates+ phase = metadata.get("phase", "")+ is_final = (+ phase+ in (+ "complete",+ "error",+ "report_complete",+ )+ or adjusted_progress == 100)++ should_emit = is_final+ if not is_final:+ now = time.monotonic()+ with _last_emit_lock:+ last = _last_emit_times.get(research_id, 0)+ if now - last >= _EMIT_THROTTLE_SECONDS:+ _last_emit_times[research_id] = now+ should_emit = True++ if should_emit:+ event_data = {"progress": adjusted_progress}+ SocketIOService().emit_to_subscribers(+ "progress", research_id, event_data+ )except Exception:logger.exception("Socket emit error (non-critical)")@@ -1655,6 +1700,10 @@ def cleanup_research_resources(if research_id in termination_flags:del termination_flags[research_id]+ # Clean up throttle state for this research+ with _last_emit_lock:+ _last_emit_times.pop(research_id, None)+# Send a final message to subscriberstry:# Import here to avoid circular imports@@ -1692,6 +1741,15 @@ def cleanup_research_resources("research_progress", research_id, final_message)+ # Clean up socket subscriptions for this research to prevent+ # unbounded growth of the socket_subscriptions dict+ if research_id in socket_subscriptions:+ del socket_subscriptions[research_id]+ logger.debug(+ "Cleaned up socket subscriptions for research %s",+ research_id,+ )+except Exception:logger.exception("Error sending final cleanup message")diff --git a/src/local_deep_research/web/services/socket_service.py b/src/local_deep_research/web/services/socket_service.pyindex 761e07d981..6a1a15371e 100644--- a/src/local_deep_research/web/services/socket_service.py+++ b/src/local_deep_research/web/services/socket_service.py@@ -174,11 +174,10 @@ class SocketIOService:self.__logging_enabled = Falsetry:- # Emit to the general channel for the researchfull_event = f"{event_base}_{research_id}"- self.__socketio.emit(full_event, data)- # Emit to specific subscribers+ # Emit only to specific subscribers (no broadcast) to avoid+ # duplicate messages and reduce server load under concurrencywith self.__lock:subscriptions = self.__socket_subscriptions.get(research_id)if subscriptions is not None:@@ -193,6 +192,10 @@ class SocketIOService:self.__log_exception(f"Error emitting to subscriber {sid}")+ else:+ # No targeted subscribers yet — broadcast so early+ # listeners still receive the event+ self.__socketio.emit(full_event, data)return Trueexcept Exception:diff --git a/src/local_deep_research/web/static/js/services/socket.js b/src/local_deep_research/web/static/js/services/socket.jsindex ad6a1c8a69..dd3245425d 100644--- a/src/local_deep_research/web/static/js/services/socket.js+++ b/src/local_deep_research/web/static/js/services/socket.js@@ -43,17 +43,18 @@ window.socket = (function() {// Create a new socket instancetry {- // Use polling only to avoid WebSocket issues+ // Prefer WebSocket with polling fallback for lower latency+ // and reduced server load vs polling-onlysocket = io(baseUrl, {path: '/socket.io',reconnection: true,reconnectionDelay: 1000,reconnectionAttempts: 5,- transports: ['polling'] // Use only polling to avoid WebSocket issues+ transports: ['websocket', 'polling']});setupSocketEvents();- SafeLogger.log('Socket.IO initialized with polling only strategy');+ SafeLogger.log('Socket.IO initialized with websocket+polling strategy');} catch (error) {SafeLogger.error('Error initializing Socket.IO:', error);// Set a flag that we're not connected - will use polling for updatesdiff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.jsonindex 75446e73d2..bdb0cfc728 100644--- a/tests/settings/golden_master_settings.json+++ b/tests/settings/golden_master_settings.json@@ -126,6 +126,21 @@"value": 3,"visible": true},+ "app.max_global_concurrent_researches": {+ "category": "app_interface",+ "description": "Maximum number of concurrent research processes allowed across all users (server-wide). Set via env var LDR_SERVER_MAX_CONCURRENT_RESEARCH. Requires server restart.",+ "editable": false,+ "env_var": "LDR_SERVER_MAX_CONCURRENT_RESEARCH",+ "max_value": 1000,+ "min_value": 1,+ "name": "Max Global Concurrent Researches",+ "options": null,+ "step": 1,+ "type": "APP",+ "ui_element": "number",+ "value": 10,+ "visible": false+ },"app.max_user_query_length": {"category": "search_parameters","description": "Maximum character length for user queries before disabling direct search. Longer queries will use LLM-generated questions only.",diff --git a/tests/settings/test_settings_defaults_integrity.py b/tests/settings/test_settings_defaults_integrity.pyindex 53b40b8908..49f17e5bba 100644--- a/tests/settings/test_settings_defaults_integrity.py+++ b/tests/settings/test_settings_defaults_integrity.py@@ -258,6 +258,7 @@ def _is_web_consumed_setting(key: str) -> bool:"app.enable_file_logging","app.enable_notifications","app.enable_web",+ "app.max_global_concurrent_researches","app.theme","app.web_interface",}diff --git a/tests/web/auth/test_cleanup_middleware.py b/tests/web/auth/test_cleanup_middleware.pyindex 42f28c3085..ed24dc2a46 100644--- a/tests/web/auth/test_cleanup_middleware.py+++ b/tests/web/auth/test_cleanup_middleware.py@@ -9,12 +9,23 @@ Tests cover:from unittest.mock import MagicMock, patch+import pytestfrom flask import Flaskclass TestCleanupCompletedResearch:"""Tests for cleanup_completed_research function."""+ @pytest.fixture(autouse=True)+ def _bypass_random_gate(self):+ """Ensure the 1% random sampling gate always passes so tests+ exercise the actual cleanup logic."""+ with patch(+ "local_deep_research.web.auth.cleanup_middleware.random.randint",+ return_value=1,+ ):+ yield+def test_skips_when_middleware_should_skip(self):"""Should skip cleanup when should_skip_database_middleware returns True."""app = Flask(__name__)@@ -321,3 +332,35 @@ class TestCleanupCompletedResearch:mock_db_session.query.return_value.filter_by.return_value.limit.assert_called_with(50)++ def test_skips_cleanup_on_random_sampling(self, _bypass_random_gate):+ """Should skip cleanup when random sampling doesn't select this request."""+ app = Flask(__name__)+ app.secret_key = "test"++ mock_db_session = MagicMock()++ with (+ patch(+ "local_deep_research.web.auth.cleanup_middleware.should_skip_database_middleware"+ ) as mock_skip,+ patch(+ "local_deep_research.web.auth.cleanup_middleware.random.randint",+ return_value=50,+ ),+ ):+ mock_skip.return_value = False++ from local_deep_research.web.auth.cleanup_middleware import (+ cleanup_completed_research,+ )+ from flask import session, g++ with app.test_request_context("/dashboard"):+ session["username"] = "testuser"+ g.db_session = mock_db_session++ result = cleanup_completed_research()++ assert result is None+ mock_db_session.query.assert_not_called()