~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: remove dead code and fix socket subscription cleanup from PR #2326 (#2492)
LearningCircuit3aedc213db23
diff --git a/.pre-commit-hooks/check-env-vars.py b/.pre-commit-hooks/check-env-vars.pyindex 337f69dd4c..d0fcf3f0e1 100755--- a/.pre-commit-hooks/check-env-vars.py+++ b/.pre-commit-hooks/check-env-vars.py@@ -24,7 +24,6 @@ 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/src/local_deep_research/web/auth/decorators.py b/src/local_deep_research/web/auth/decorators.pyindex a4a5f9e62d..a06a25a05c 100644--- a/src/local_deep_research/web/auth/decorators.py+++ b/src/local_deep_research/web/auth/decorators.py@@ -90,17 +90,10 @@ 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:- # 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+ # Check connectivityif not db_manager.is_user_connected(g.current_user):# For API/auth routes, allow the request to continueif (diff --git a/src/local_deep_research/web/routes/globals.py b/src/local_deep_research/web/routes/globals.pyindex 7eced1386a..83f2a4f860 100644--- a/src/local_deep_research/web/routes/globals.py+++ b/src/local_deep_research/web/routes/globals.py@@ -2,10 +2,9 @@Stores global state."""-# Active research processes and socket subscriptions+# Active research processesactive_research = {}-socket_subscriptions = {}-# Add termination flags dictionary+# Termination flags dictionarytermination_flags = {}@@ -17,6 +16,5 @@ def get_globals():"""return {"active_research": active_research,- "socket_subscriptions": socket_subscriptions,"termination_flags": termination_flags,}diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex a1146756c3..45aed0cd46 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -1726,49 +1726,30 @@ def cleanup_research_resources(# Send a final message to subscriberstry:- # Import here to avoid circular imports- from ..routes.globals import get_globals-- globals_dict = get_globals()- socket_subscriptions = globals_dict.get("socket_subscriptions", {})-- # Send a final message to any remaining subscribers with explicit status- if socket_subscriptions.get(research_id):- # Use the proper status message based on database status- if current_status in (- ResearchStatus.SUSPENDED,- ResearchStatus.FAILED,- ):- final_message = {- "status": current_status,- "message": f"Research was {current_status}",- "progress": 0, # For suspended research, show 0% not 100%- }- else:- final_message = {- "status": ResearchStatus.COMPLETED,- "message": "Research process has ended and resources have been cleaned up",- "progress": 100,- }-- logger.info(- "Sending final %s socket message for research %s",- current_status,- research_id,- )+ if current_status in (ResearchStatus.SUSPENDED, ResearchStatus.FAILED):+ final_message = {+ "status": current_status,+ "message": f"Research was {current_status}",+ "progress": 0,+ }+ else:+ final_message = {+ "status": ResearchStatus.COMPLETED,+ "message": "Research process has ended and resources have been cleaned up",+ "progress": 100,+ }- SocketIOService().emit_to_subscribers(- "research_progress", research_id, final_message- )+ logger.info(+ "Sending final %s socket message for research %s",+ current_status,+ research_id,+ )+ SocketIOService().emit_to_subscribers(+ "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,- )+ # Clean up socket subscriptions for this research+ SocketIOService().remove_subscriptions_for_research(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 6a1a15371e..490fb6ab05 100644--- a/src/local_deep_research/web/services/socket_service.py+++ b/src/local_deep_research/web/services/socket_service.py@@ -180,10 +180,12 @@ class SocketIOService:# duplicate messages and reduce server load under concurrencywith self.__lock:subscriptions = self.__socket_subscriptions.get(research_id)- if subscriptions is not None:+ if subscriptions:subscriptions = (subscriptions.copy()) # snapshot avoids RuntimeError+ else:+ subscriptions = Noneif subscriptions is not None:for sid in subscriptions:try:@@ -206,6 +208,15 @@ class SocketIOService:finally:self.__logging_enabled = True+ def remove_subscriptions_for_research(self, research_id: str) -> None:+ """Remove all socket subscriptions for a completed research."""+ with self.__lock:+ removed = self.__socket_subscriptions.pop(research_id, None)+ if removed is not None:+ self.__log_info(+ f"Removed {len(removed)} subscription(s) for research {research_id}"+ )+def __handle_connect(self, request):"""Handle client connection"""self.__log_info(f"Client connected: {request.sid}")diff --git a/tests/web/routes/test_globals.py b/tests/web/routes/test_globals.pyindex 246bdfc6c8..e129fe1be1 100644--- a/tests/web/routes/test_globals.py+++ b/tests/web/routes/test_globals.py@@ -3,7 +3,6 @@from local_deep_research.web.routes.globals import (active_research,get_globals,- socket_subscriptions,termination_flags,)@@ -15,10 +14,6 @@ class TestGlobalVariables:"""active_research should be a dict."""assert isinstance(active_research, dict)- def test_socket_subscriptions_is_dict(self):- """socket_subscriptions should be a dict."""- assert isinstance(socket_subscriptions, dict)-def test_termination_flags_is_dict(self):"""termination_flags should be a dict."""assert isinstance(termination_flags, dict)@@ -27,19 +22,17 @@ class TestGlobalVariables:class TestGetGlobals:"""Tests for the get_globals() helper."""- def test_returns_dict_with_all_three_keys(self):- """get_globals should return a dict containing the three expected keys."""+ def test_returns_dict_with_all_keys(self):+ """get_globals should return a dict containing the expected keys."""result = get_globals()assert isinstance(result, dict)assert "active_research" in result- assert "socket_subscriptions" in resultassert "termination_flags" in resultdef test_returns_same_objects_as_module_level(self):"""The returned values should be the actual module-level dicts (same identity)."""result = get_globals()assert result["active_research"] is active_research- assert result["socket_subscriptions"] is socket_subscriptionsassert result["termination_flags"] is termination_flagsdef test_modifying_returned_dict_modifies_module_state(self):diff --git a/tests/web/routes/test_globals_extended.py b/tests/web/routes/test_globals_extended.pyindex bb118126cc..cacbba80ba 100644--- a/tests/web/routes/test_globals_extended.py+++ b/tests/web/routes/test_globals_extended.py@@ -5,7 +5,6 @@ Tests cover:- Global variable initialization- get_globals() function- Active research tracking-- Socket subscriptions management- Termination flags management- Thread safety considerations"""@@ -20,12 +19,6 @@ class TestGlobalVariableInitialization:assert isinstance(active_research, dict)assert len(active_research) == 0- def test_socket_subscriptions_initialized_as_dict(self):- """socket_subscriptions should be initialized as empty dict."""- socket_subscriptions = {}- assert isinstance(socket_subscriptions, dict)- assert len(socket_subscriptions) == 0-def test_termination_flags_initialized_as_dict(self):"""termination_flags should be initialized as empty dict."""termination_flags = {}@@ -39,12 +32,10 @@ class TestGetGlobals:def test_returns_dict(self):"""get_globals should return a dict."""active_research = {}- socket_subscriptions = {}termination_flags = {}globals_dict = {"active_research": active_research,- "socket_subscriptions": socket_subscriptions,"termination_flags": termination_flags,}@@ -54,27 +45,15 @@ class TestGetGlobals:"""Globals dict should contain active_research key."""globals_dict = {"active_research": {},- "socket_subscriptions": {},"termination_flags": {},}assert "active_research" in globals_dict- def test_contains_socket_subscriptions_key(self):- """Globals dict should contain socket_subscriptions key."""- globals_dict = {- "active_research": {},- "socket_subscriptions": {},- "termination_flags": {},- }-- assert "socket_subscriptions" in globals_dict-def test_contains_termination_flags_key(self):"""Globals dict should contain termination_flags key."""globals_dict = {"active_research": {},- "socket_subscriptions": {},"termination_flags": {},}@@ -162,74 +141,6 @@ class TestActiveResearchTracking:assert active_research["test-123"]["status"] == "completed"-class TestSocketSubscriptionsManagement:- """Tests for socket subscriptions management."""-- def test_add_subscription(self):- """Should be able to add subscription."""- socket_subscriptions = {}- research_id = "test-123"- socket_id = "socket-abc"-- if research_id not in socket_subscriptions:- socket_subscriptions[research_id] = set()- socket_subscriptions[research_id].add(socket_id)-- assert socket_id in socket_subscriptions[research_id]-- def test_remove_subscription(self):- """Should be able to remove subscription."""- socket_subscriptions = {"test-123": {"socket-abc", "socket-def"}}-- socket_subscriptions["test-123"].discard("socket-abc")- assert "socket-abc" not in socket_subscriptions["test-123"]- assert "socket-def" in socket_subscriptions["test-123"]-- def test_get_subscribers(self):- """Should be able to get subscribers for research."""- socket_subscriptions = {"test-123": {"socket-abc", "socket-def"}}-- subscribers = socket_subscriptions.get("test-123", set())- assert len(subscribers) == 2-- def test_no_subscribers_returns_empty(self):- """No subscribers should return empty set."""- socket_subscriptions = {}-- subscribers = socket_subscriptions.get("test-123", set())- assert len(subscribers) == 0-- def test_multiple_research_subscriptions(self):- """Should track subscriptions for multiple research."""- socket_subscriptions = {- "research-1": {"socket-1", "socket-2"},- "research-2": {"socket-3"},- }-- assert len(socket_subscriptions["research-1"]) == 2- assert len(socket_subscriptions["research-2"]) == 1-- def test_same_socket_multiple_research(self):- """Same socket can subscribe to multiple research."""- socket_subscriptions = {- "research-1": {"socket-1"},- "research-2": {"socket-1"},- }-- assert "socket-1" in socket_subscriptions["research-1"]- assert "socket-1" in socket_subscriptions["research-2"]-- def test_cleanup_empty_subscription_set(self):- """Should cleanup empty subscription sets."""- socket_subscriptions = {"test-123": {"socket-abc"}}-- socket_subscriptions["test-123"].discard("socket-abc")- if not socket_subscriptions["test-123"]:- del socket_subscriptions["test-123"]-- assert "test-123" not in socket_subscriptions--class TestTerminationFlagsManagement:"""Tests for termination flags management."""@@ -317,14 +228,6 @@ class TestConcurrentAccess:class TestGlobalStateIsolation:"""Tests for global state isolation."""- def test_active_research_independent_of_subscriptions(self):- """active_research should be independent of socket_subscriptions."""- active_research = {"test-123": {}}- socket_subscriptions = {"test-456": set()}-- assert "test-123" not in socket_subscriptions- assert "test-456" not in active_research-def test_termination_flags_independent(self):"""termination_flags should be independent."""active_research = {"test-123": {}}@@ -338,12 +241,10 @@ class TestGlobalStateIsolation:def test_globals_dict_is_snapshot(self):"""get_globals returns references, not copies."""active_research = {}- socket_subscriptions = {}termination_flags = {}globals_dict = {"active_research": active_research,- "socket_subscriptions": socket_subscriptions,"termination_flags": termination_flags,}diff --git a/tests/web/services/test_research_service.py b/tests/web/services/test_research_service.pyindex af22067a62..509b9f8441 100644--- a/tests/web/services/test_research_service.py+++ b/tests/web/services/test_research_service.py@@ -368,10 +368,9 @@ class TestCleanupResearchResources:@patch("local_deep_research.settings.env_registry.is_test_mode")@patch("local_deep_research.web.queue.processor_v2.queue_processor")- @patch("local_deep_research.web.routes.globals.get_globals")@patch("local_deep_research.web.services.socket_service.SocketIOService")def test_cleanup_removes_from_active_research(- self, mock_socket, mock_get_globals, mock_queue, mock_test_mode+ self, mock_socket, mock_queue, mock_test_mode):"""cleanup_research_resources removes from active_research."""from local_deep_research.web.services.research_service import (@@ -379,7 +378,6 @@ class TestCleanupResearchResources:)mock_test_mode.return_value = False- mock_get_globals.return_value = {"socket_subscriptions": {}}active_research = {123: {"thread": Mock(), "progress": 100}}termination_flags = {123: False}@@ -393,10 +391,9 @@ class TestCleanupResearchResources:@patch("local_deep_research.settings.env_registry.is_test_mode")@patch("local_deep_research.web.queue.processor_v2.queue_processor")- @patch("local_deep_research.web.routes.globals.get_globals")@patch("local_deep_research.web.services.socket_service.SocketIOService")def test_cleanup_notifies_queue_processor(- self, mock_socket, mock_get_globals, mock_queue, mock_test_mode+ self, mock_socket, mock_queue, mock_test_mode):"""cleanup_research_resources notifies queue processor."""from local_deep_research.web.services.research_service import (@@ -404,7 +401,6 @@ class TestCleanupResearchResources:)mock_test_mode.return_value = False- mock_get_globals.return_value = {"socket_subscriptions": {}}active_research = {}termination_flags = {}diff --git a/tests/web/services/test_research_service_lifecycle.py b/tests/web/services/test_research_service_lifecycle.pyindex 80fc18cd81..93d459bf1b 100644--- a/tests/web/services/test_research_service_lifecycle.py+++ b/tests/web/services/test_research_service_lifecycle.py@@ -15,10 +15,9 @@ class TestResourceCleanup:@patch("local_deep_research.settings.env_registry.is_test_mode")@patch("local_deep_research.web.queue.processor_v2.queue_processor")- @patch("local_deep_research.web.routes.globals.get_globals")@patch("local_deep_research.web.services.socket_service.SocketIOService")def test_cleanup_removes_from_active_dict(- self, mock_socket, mock_get_globals, mock_queue, mock_test_mode+ self, mock_socket, mock_queue, mock_test_mode):"""Cleanup removes research from active_research dict."""from local_deep_research.web.services.research_service import (@@ -26,7 +25,6 @@ class TestResourceCleanup:)mock_test_mode.return_value = False- mock_get_globals.return_value = {"socket_subscriptions": {}}active_research = {123: {"thread": Mock(), "progress": 100}}termination_flags = {}@@ -39,10 +37,9 @@ class TestResourceCleanup:@patch("local_deep_research.settings.env_registry.is_test_mode")@patch("local_deep_research.web.queue.processor_v2.queue_processor")- @patch("local_deep_research.web.routes.globals.get_globals")@patch("local_deep_research.web.services.socket_service.SocketIOService")def test_cleanup_notifies_queue_processor(- self, mock_socket, mock_get_globals, mock_queue, mock_test_mode+ self, mock_socket, mock_queue, mock_test_mode):"""Cleanup notifies queue processor of completion."""from local_deep_research.web.services.research_service import (@@ -50,7 +47,6 @@ class TestResourceCleanup:)mock_test_mode.return_value = False- mock_get_globals.return_value = {"socket_subscriptions": {}}active_research = {}termination_flags = {}@@ -79,10 +75,9 @@ class TestResourceCleanup:@patch("local_deep_research.settings.env_registry.is_test_mode")@patch("local_deep_research.web.queue.processor_v2.queue_processor")- @patch("local_deep_research.web.routes.globals.get_globals")@patch("local_deep_research.web.services.socket_service.SocketIOService")def test_cleanup_socket_emit_failure_handling(- self, mock_socket_class, mock_get_globals, mock_queue, mock_test_mode+ self, mock_socket_class, mock_queue, mock_test_mode):"""Cleanup handles socket emit failure gracefully."""from local_deep_research.web.services.research_service import (@@ -93,9 +88,6 @@ class TestResourceCleanup:mock_socket = Mock()mock_socket.emit_to_subscribers.side_effect = Exception("Socket error")mock_socket_class.return_value = mock_socket- mock_get_globals.return_value = {- "socket_subscriptions": {123: ["subscriber"]}- }active_research = {}termination_flags = {}@@ -107,10 +99,9 @@ class TestResourceCleanup:@patch("local_deep_research.settings.env_registry.is_test_mode")@patch("local_deep_research.web.queue.processor_v2.queue_processor")- @patch("local_deep_research.web.routes.globals.get_globals")@patch("local_deep_research.web.services.socket_service.SocketIOService")def test_cleanup_database_session_handling(- self, mock_socket, mock_get_globals, mock_queue, mock_test_mode+ self, mock_socket, mock_queue, mock_test_mode):"""Cleanup handles database session properly."""from local_deep_research.web.services.research_service import (@@ -118,7 +109,6 @@ class TestResourceCleanup:)mock_test_mode.return_value = False- mock_get_globals.return_value = {"socket_subscriptions": {}}active_research = {}termination_flags = {}