~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: improve CI test stability with singleton isolation and timeouts
LearningCircuitf6a9b20c3d83
diff --git a/pyproject.toml b/pyproject.tomlindex eb9f784253..eadefc0f75 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -160,6 +160,9 @@ markers = ["slow: marks slow tests","asyncio: marks async tests that use asyncio",]+# Global timeout for all tests - fail fast instead of hanging+timeout = 60+timeout_method = "signal"[tool.coverage.run]source = ["src"]diff --git a/tests/api_tests_with_login/pytest_tests/conftest.py b/tests/api_tests_with_login/pytest_tests/conftest.pyindex f9811e213b..5037c21cba 100644--- a/tests/api_tests_with_login/pytest_tests/conftest.py+++ b/tests/api_tests_with_login/pytest_tests/conftest.py@@ -4,7 +4,7 @@ Pytest configuration and shared fixtures for API testsimport jsonimport subprocess-import time+import uuidimport pytestimport requestsfrom pathlib import Path@@ -13,7 +13,8 @@ import os# Base URL for testsBASE_URL = os.environ.get("LDR_TEST_BASE_URL", "http://127.0.0.1:5000")-TEST_USERNAME = f"testuser_{int(time.time())}"+# Use UUID for unique usernames to avoid collisions in parallel tests+TEST_USERNAME = f"testuser_{uuid.uuid4().hex[:12]}"TEST_PASSWORD = "testpass123"diff --git a/tests/conftest.py b/tests/conftest.pyindex d7c2ae67b5..39b1a430bc 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -3,10 +3,12 @@ import sysimport tempfileimport typesimport shutil+import uuidfrom pathlib import Pathfrom unittest.mock import Mockimport pytest+from loguru import loggerfrom sqlalchemy import create_enginefrom sqlalchemy.exc import SQLAlchemyErrorfrom sqlalchemy.orm import sessionmaker, Session@@ -42,6 +44,99 @@ except ImportError:pass+def generate_unique_test_username(prefix: str = "pytest_user") -> str:+ """Generate unique username using UUID instead of timestamp.++ This ensures no collisions when running tests in parallel with pytest-xdist.+ """+ return f"{prefix}_{uuid.uuid4().hex[:12]}"++[email protected](autouse=True)+def reset_all_singletons():+ """Reset all singletons before and after each test.++ This ensures proper isolation when running with pytest-xdist (-n auto).+ Without this, singleton state can leak between tests running in parallel,+ causing intermittent failures.+ """++ def _reset():+ # SocketIOService+ try:+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ SocketIOService._instance = None+ except ImportError:+ pass++ # NewsScheduler (both class and module-level)+ try:+ from src.local_deep_research.news.subscription_manager import (+ scheduler,+ )++ scheduler.NewsScheduler._instance = None+ # Also reset module-level global if it exists+ if hasattr(scheduler, "_scheduler_instance"):+ scheduler._scheduler_instance = None+ except ImportError:+ pass++ # ProviderDiscovery - reset both class-level and module-level state+ try:+ from src.local_deep_research.llm.providers import auto_discovery+ from src.local_deep_research.llm.providers.auto_discovery import (+ ProviderDiscovery,+ )++ # Reset class-level singleton+ ProviderDiscovery._instance = None+ ProviderDiscovery._providers = {}+ if hasattr(ProviderDiscovery, "_discovered"):+ ProviderDiscovery._discovered = False++ # Reset the module-level singleton instance's state+ if hasattr(auto_discovery, "provider_discovery"):+ auto_discovery.provider_discovery._discovered = False+ auto_discovery.provider_discovery._providers = {}+ except ImportError:+ pass++ # DocumentSchedulerUtil+ try:+ from src.local_deep_research.research_scheduler import (+ document_scheduler,+ )++ if hasattr(document_scheduler, "_scheduler_util_instance"):+ document_scheduler._scheduler_util_instance = None+ except ImportError:+ pass++ _reset()+ yield+ _reset()++[email protected](autouse=True)+def database_operation_timeout():+ """Set shorter timeouts for database operations in tests.++ This helps tests fail fast instead of hanging indefinitely when+ database contention occurs.+ """+ original = os.environ.get("LDR_DB_BUSY_TIMEOUT")+ os.environ["LDR_DB_BUSY_TIMEOUT"] = "5000" # 5 seconds in tests+ yield+ if original:+ os.environ["LDR_DB_BUSY_TIMEOUT"] = original+ else:+ os.environ.pop("LDR_DB_BUSY_TIMEOUT", None)++def pytest_configure(config):"""Configure pytest with custom markers."""config.addinivalue_line(@@ -77,7 +172,11 @@ def temp_data_dir():@pytest.fixture(autouse=True)def cleanup_database_connections():- """Clean up database connections before and after each test."""+ """Clean up database connections before and after each test.++ This fixture ensures proper cleanup of database connections with+ logging for debugging CI issues.+ """# Import here to avoid circular importsfrom src.local_deep_research.database.encrypted_db import db_managerfrom src.local_deep_research.web.auth.routes import session_manager@@ -88,12 +187,12 @@ def cleanup_database_connections():yield- # Close any open connections+ # Close any open connections with loggingfor username, engine in list(db_manager.connections.items()):try:engine.dispose()- except Exception:- pass+ except Exception as e:+ logger.warning(f"Failed to dispose engine for '{username}': {e}")# Clear connections and sessions after testdb_manager.connections.clear()@@ -136,11 +235,8 @@ def client(app):@pytest.fixturedef authenticated_client(app, temp_data_dir):"""Create a test client with an authenticated user."""- # Import here to avoid circular imports- import time-- # Create unique test username to avoid conflicts- test_username = f"pytest_user_{int(time.time() * 1000)}"+ # Create unique test username using UUID to avoid conflicts in parallel tests+ test_username = generate_unique_test_username()test_password = "testpassword123"# Clear any existing user databasediff --git a/tests/llm_providers/test_auto_discovery.py b/tests/llm_providers/test_auto_discovery.pyindex 62166045f0..3ceb79f77e 100644--- a/tests/llm_providers/test_auto_discovery.py+++ b/tests/llm_providers/test_auto_discovery.py@@ -201,14 +201,11 @@ class TestProviderDiscovery:class TestModuleFunctions:- """Tests for module-level convenience functions."""+ """Tests for module-level convenience functions.- @pytest.fixture(autouse=True)- def reset_singleton(self):- """Reset singleton before each test."""- ProviderDiscovery._instance = None- ProviderDiscovery._providers = {}- yield+ Note: Singleton reset is handled by the global reset_all_singletons fixture+ in tests/conftest.py.+ """def test_discover_providers_function(self):"""discover_providers() function works."""@@ -217,11 +214,13 @@ class TestModuleFunctions:result = discover_providers()assert isinstance(result, dict)- @pytest.mark.skip(- reason="Singleton caching prevents force_refresh from working as expected in tests"- )def test_discover_providers_force_refresh(self):- """discover_providers() supports force_refresh."""+ """discover_providers() supports force_refresh.++ This test was previously skipped due to singleton caching issues.+ The global reset_all_singletons fixture now properly resets the+ ProviderDiscovery singleton between tests.+ """with patch("pathlib.Path.glob") as mock_glob:mock_glob.return_value = []discover_providers()@@ -244,14 +243,11 @@ class TestModuleFunctions:class TestProviderDiscoveryIntegration:- """Integration tests for provider discovery."""+ """Integration tests for provider discovery.- @pytest.fixture(autouse=True)- def reset_singleton(self):- """Reset singleton before each test."""- ProviderDiscovery._instance = None- ProviderDiscovery._providers = {}- yield+ Note: Singleton reset is handled by the global reset_all_singletons fixture+ in tests/conftest.py.+ """def test_discovers_real_providers(self):"""Discovers actual provider implementations."""diff --git a/tests/rate_limiting/test_rate_limiting.py b/tests/rate_limiting/test_rate_limiting.pyindex a4df868826..81c6760465 100644--- a/tests/rate_limiting/test_rate_limiting.py+++ b/tests/rate_limiting/test_rate_limiting.py@@ -74,11 +74,12 @@ class TestAdaptiveRateLimitTracker(unittest.TestCase):except:pass- @pytest.mark.skipif(- os.environ.get("CI") == "true", reason="Test hangs in CI environment"- )+ @pytest.mark.timeout(30)def test_get_wait_time_new_engine(self):- """Test getting wait time for a new engine."""+ """Test getting wait time for a new engine.++ Uses timeout marker instead of skipping to fail fast if DB operations hang.+ """# Reset any existing data for test enginestry:self.tracker.reset_engine("TestEngine")@@ -105,11 +106,12 @@ class TestAdaptiveRateLimitTracker(unittest.TestCase):local_wait = self.tracker.get_wait_time("LocalSearchEngine")self.assertEqual(local_wait, 0.0) # No wait for local search- @pytest.mark.skipif(- os.environ.get("CI") == "true", reason="Test hangs in CI environment"- )+ @pytest.mark.timeout(30)def test_record_outcome_and_learning(self):- """Test recording outcomes and learning from them."""+ """Test recording outcomes and learning from them.++ Uses timeout marker instead of skipping to fail fast if DB operations hang.+ """engine_type = "TestEngine"# Record several successful attempts with different wait times@@ -229,12 +231,12 @@ class TestAdaptiveRateLimitTracker(unittest.TestCase):# Clean uptracker.reset_engine(engine_type)- @pytest.mark.skipif(- os.environ.get("CI") == "true",- reason="Test hangs in CI environment due to database operations",- )+ @pytest.mark.timeout(30)def test_reset_engine(self):- """Test resetting an engine's data."""+ """Test resetting an engine's data.++ Uses timeout marker instead of skipping to fail fast if DB operations hang.+ """# Use unique engine name for this testimport uuid@@ -295,11 +297,12 @@ class TestAdaptiveRateLimitTracker(unittest.TestCase):avg_wait_time_after, avg_wait_time_before * 0.5) # Should be significantly lower- @pytest.mark.skipif(- os.environ.get("CI") == "true", reason="Test hangs in CI environment"- )+ @pytest.mark.timeout(30)def test_reset_engine_simple(self):- """Simple test for reset functionality that works in CI."""+ """Simple test for reset functionality.++ Uses timeout marker instead of skipping to fail fast if DB operations hang.+ """engine_type = "TestEngine_Simple_Reset"# Just test in-memory operations without databasediff --git a/tests/web_services/test_socket_service.py b/tests/web_services/test_socket_service.pyindex 150ee2ef5f..5f1f6ddec2 100644--- a/tests/web_services/test_socket_service.py+++ b/tests/web_services/test_socket_service.py@@ -8,23 +8,11 @@ from unittest.mock import Mock, MagicMock, patchclass TestSocketIOServiceSingleton:- """Tests for SocketIOService singleton pattern."""+ """Tests for SocketIOService singleton pattern.- def setup_method(self):- """Reset singleton before each test."""- from local_deep_research.web.services.socket_service import (- SocketIOService,- )-- SocketIOService._instance = None-- def teardown_method(self):- """Reset singleton after each test."""- from local_deep_research.web.services.socket_service import (- SocketIOService,- )-- SocketIOService._instance = None+ Note: Singleton reset is handled by the global reset_all_singletons fixture+ in tests/conftest.py.+ """def test_requires_app_on_first_creation(self):"""Test that Flask app is required on first creation."""@@ -78,23 +66,11 @@ class TestSocketIOServiceSingleton:class TestSocketIOServiceInit:- """Tests for SocketIOService initialization."""-- def setup_method(self):- """Reset singleton before each test."""- from local_deep_research.web.services.socket_service import (- SocketIOService,- )-- SocketIOService._instance = None-- def teardown_method(self):- """Reset singleton after each test."""- from local_deep_research.web.services.socket_service import (- SocketIOService,- )+ """Tests for SocketIOService initialization.- SocketIOService._instance = None+ Note: Singleton reset is handled by the global reset_all_singletons fixture+ in tests/conftest.py.+ """def test_initializes_socketio_with_correct_params(self, mock_flask_app):"""Test that SocketIO is initialized with correct parameters."""@@ -169,7 +145,11 @@ class TestSocketIOServiceInit:class TestSocketIOServiceEmitSocketEvent:- """Tests for emit_socket_event method."""+ """Tests for emit_socket_event method.++ Note: Singleton reset is handled by the global reset_all_singletons fixture+ in tests/conftest.py.+ """@pytest.fixturedef service(self, mock_flask_app):@@ -178,8 +158,6 @@ class TestSocketIOServiceEmitSocketEvent:SocketIOService,)- SocketIOService._instance = None-mock_socketio = MagicMock()with patch(@@ -190,14 +168,6 @@ class TestSocketIOServiceEmitSocketEvent:service._SocketIOService__socketio = mock_socketioreturn service, mock_socketio- def teardown_method(self):- """Reset singleton after each test."""- from local_deep_research.web.services.socket_service import (- SocketIOService,- )-- SocketIOService._instance = None-def test_emits_to_all_when_no_room(self, service):"""Test emitting to all clients when no room specified."""svc, mock_socketio = service@@ -245,7 +215,11 @@ class TestSocketIOServiceEmitSocketEvent:class TestSocketIOServiceEmitToSubscribers:- """Tests for emit_to_subscribers method."""+ """Tests for emit_to_subscribers method.++ Note: Singleton reset is handled by the global reset_all_singletons fixture+ in tests/conftest.py.+ """@pytest.fixturedef service(self, mock_flask_app):@@ -254,8 +228,6 @@ class TestSocketIOServiceEmitToSubscribers:SocketIOService,)- SocketIOService._instance = None-mock_socketio = MagicMock()with patch(@@ -266,14 +238,6 @@ class TestSocketIOServiceEmitToSubscribers:service._SocketIOService__socketio = mock_socketioreturn service, mock_socketio- def teardown_method(self):- """Reset singleton after each test."""- from local_deep_research.web.services.socket_service import (- SocketIOService,- )-- SocketIOService._instance = None-def test_emits_formatted_event(self, service, sample_research_id):"""Test that event is emitted with formatted name."""svc, mock_socketio = service@@ -397,7 +361,11 @@ class TestSocketIOServiceEmitToSubscribers:class TestSocketIOServiceSubscriptionManagement:- """Tests for subscription management."""+ """Tests for subscription management.++ Note: Singleton reset is handled by the global reset_all_singletons fixture+ in tests/conftest.py.+ """@pytest.fixturedef service_with_mocks(self, mock_flask_app):@@ -406,8 +374,6 @@ class TestSocketIOServiceSubscriptionManagement:SocketIOService,)- SocketIOService._instance = None-mock_socketio = MagicMock()with patch(@@ -418,14 +384,6 @@ class TestSocketIOServiceSubscriptionManagement:service._SocketIOService__socketio = mock_socketioreturn service, mock_socketio- def teardown_method(self):- """Reset singleton after each test."""- from local_deep_research.web.services.socket_service import (- SocketIOService,- )-- SocketIOService._instance = None-def test_subscribe_adds_client(self, service_with_mocks, mock_request, sample_research_id):@@ -514,7 +472,11 @@ class TestSocketIOServiceSubscriptionManagement:class TestSocketIOServiceErrorHandling:- """Tests for error handling methods."""+ """Tests for error handling methods.++ Note: Singleton reset is handled by the global reset_all_singletons fixture+ in tests/conftest.py.+ """@pytest.fixturedef service(self, mock_flask_app):@@ -523,8 +485,6 @@ class TestSocketIOServiceErrorHandling:SocketIOService,)- SocketIOService._instance = None-mock_socketio = MagicMock()with patch(@@ -534,14 +494,6 @@ class TestSocketIOServiceErrorHandling:service = SocketIOService(app=mock_flask_app)return service- def teardown_method(self):- """Reset singleton after each test."""- from local_deep_research.web.services.socket_service import (- SocketIOService,- )-- SocketIOService._instance = None-def test_socket_error_returns_false(self, service):"""Test that socket error handler returns False."""result = service._SocketIOService__handle_socket_error(@@ -571,7 +523,11 @@ class TestSocketIOServiceErrorHandling:class TestSocketIOServiceRun:- """Tests for run method."""+ """Tests for run method.++ Note: Singleton reset is handled by the global reset_all_singletons fixture+ in tests/conftest.py.+ """@pytest.fixturedef service(self, mock_flask_app):@@ -580,8 +536,6 @@ class TestSocketIOServiceRun:SocketIOService,)- SocketIOService._instance = None-mock_socketio = MagicMock()with patch(@@ -592,14 +546,6 @@ class TestSocketIOServiceRun:service._SocketIOService__socketio = mock_socketioreturn service, mock_socketio, mock_flask_app- def teardown_method(self):- """Reset singleton after each test."""- from local_deep_research.web.services.socket_service import (- SocketIOService,- )-- SocketIOService._instance = None-def test_run_calls_socketio_run(self, service):"""Test that run method calls socketio.run."""svc, mock_socketio, mock_app = service@@ -634,7 +580,11 @@ class TestSocketIOServiceRun:class TestSocketIOServiceLogging:- """Tests for logging behavior."""+ """Tests for logging behavior.++ Note: Singleton reset is handled by the global reset_all_singletons fixture+ in tests/conftest.py.+ """@pytest.fixturedef service(self, mock_flask_app):@@ -643,8 +593,6 @@ class TestSocketIOServiceLogging:SocketIOService,)- SocketIOService._instance = None-mock_socketio = MagicMock()with patch(@@ -654,14 +602,6 @@ class TestSocketIOServiceLogging:service = SocketIOService(app=mock_flask_app)return service- def teardown_method(self):- """Reset singleton after each test."""- from local_deep_research.web.services.socket_service import (- SocketIOService,- )-- SocketIOService._instance = None-def test_logging_enabled_by_default(self, service):"""Test that logging is enabled by default."""assert service._SocketIOService__logging_enabled is True