~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: clean up session management issues found during PR #2266 audit (#2471)
LearningCircuit045026eb94de
diff --git a/.gitleaks.toml b/.gitleaks.tomlindex 46fe140316..e4b7f27716 100644--- a/.gitleaks.toml+++ b/.gitleaks.toml@@ -119,6 +119,8 @@ paths = ['''src/local_deep_research/web/static/js/.*\.js$''',# Database session context uses password variable names (not actual secrets)'''src/local_deep_research/database/session_context\.py$''',+ # Database middleware passes password variables between Flask g context and session stores (not actual secrets)+ '''src/local_deep_research/web/auth/database_middleware\.py$''',# SQLCipher utils has key/password variable names inherent to encryption operations (not actual secrets)'''src/local_deep_research/database/sqlcipher_utils\.py$''',# Environment setting definitions use key= parameter names (not actual secrets)@@ -193,6 +195,8 @@ regexes = [# Password parameters and variable assignments (not actual secrets)'''self\.password = password''','''self\.username = username''',+ # Flask g context password variable assignment (not actual secrets)+ '''g\.user_password\s*=\s*password''','''password: Optional\[str\]''','''username: str, password: Optional''',# Database session context - parameter passingdiff --git a/.secrets.baseline b/.secrets.baselineindex 0df2e81b60..44bc7f4ce4 100644--- a/.secrets.baseline+++ b/.secrets.baseline@@ -265,182 +265,182 @@"filename": ".gitleaks.toml","hashed_secret": "ee7d3cb08c30a8bd955cda8e21b80b78a15aa3f4","is_verified": false,- "line_number": 146+ "line_number": 148},{"type": "Hex High Entropy String","filename": ".gitleaks.toml","hashed_secret": "1cc489a21f09249f316b1f4b0ba73f0676f78807","is_verified": false,- "line_number": 148+ "line_number": 150},{"type": "Hex High Entropy String","filename": ".gitleaks.toml","hashed_secret": "af25d9088d3c06ef904dc57d1978d0aa68666628","is_verified": false,- "line_number": 150+ "line_number": 152},{"type": "Hex High Entropy String","filename": ".gitleaks.toml","hashed_secret": "89b464b04612507d15a79643aac575c06f5af1bc","is_verified": false,- "line_number": 152+ "line_number": 154},{"type": "Hex High Entropy String","filename": ".gitleaks.toml","hashed_secret": "691e97e6bf7fcab1d5a4f0737ea8e0b7fa12f7fb","is_verified": false,- "line_number": 153+ "line_number": 155},{"type": "Hex High Entropy String","filename": ".gitleaks.toml","hashed_secret": "f68da4c0286159f56533bc5468944d06a29044d8","is_verified": false,- "line_number": 154+ "line_number": 156},{"type": "Hex High Entropy String","filename": ".gitleaks.toml","hashed_secret": "69661f935ea5e2cc04c3011a707384a380d44102","is_verified": false,- "line_number": 156+ "line_number": 158},{"type": "Hex High Entropy String","filename": ".gitleaks.toml","hashed_secret": "c7a2a1b46d1c166f25834d53bce4caf6107e44f1","is_verified": false,- "line_number": 158+ "line_number": 160},{"type": "Hex High Entropy String","filename": ".gitleaks.toml","hashed_secret": "dcf6a065b7edb9967c0196f5f1f41e22b22a3311","is_verified": false,- "line_number": 160+ "line_number": 162},{"type": "Hex High Entropy String","filename": ".gitleaks.toml","hashed_secret": "685e7798010d51261b2b37ec6fcd7b1dd97a6e83","is_verified": false,- "line_number": 161+ "line_number": 163},{"type": "Hex High Entropy String","filename": ".gitleaks.toml","hashed_secret": "dab915af062b1c78c42a40b43d7d90da0755e779","is_verified": false,- "line_number": 162+ "line_number": 164},{"type": "Hex High Entropy String","filename": ".gitleaks.toml","hashed_secret": "39d0197efeece376b776878a0dac57e8941ca54b","is_verified": false,- "line_number": 163+ "line_number": 165},{"type": "Hex High Entropy String","filename": ".gitleaks.toml","hashed_secret": "ec0c01bb028475264aae96df8883b9cc81623736","is_verified": false,- "line_number": 165+ "line_number": 167},{"type": "Hex High Entropy String","filename": ".gitleaks.toml","hashed_secret": "084ba18202901988211475b143162ccb61e9e682","is_verified": false,- "line_number": 166+ "line_number": 168},{"type": "Hex High Entropy String","filename": ".gitleaks.toml","hashed_secret": "ea31be37a0c5cf86c91f59c3c224e15f76d13140","is_verified": false,- "line_number": 168+ "line_number": 170},{"type": "Hex High Entropy String","filename": ".gitleaks.toml","hashed_secret": "b0d040cd81ad00c5f1523a6e9433ab8adefab74f","is_verified": false,- "line_number": 170+ "line_number": 172},{"type": "Hex High Entropy String","filename": ".gitleaks.toml","hashed_secret": "20de37db62c95eb7e60a9f9048259a9d409c442f","is_verified": false,- "line_number": 172+ "line_number": 174},{"type": "Hex High Entropy String","filename": ".gitleaks.toml","hashed_secret": "c8236e285f5ac4298804407adab79a2b4c9a5173","is_verified": false,- "line_number": 173+ "line_number": 175},{"type": "Secret Keyword","filename": ".gitleaks.toml","hashed_secret": "bba2d9fb0bb98480e928cc811520b7308e964a9d","is_verified": false,- "line_number": 182+ "line_number": 184},{"type": "Secret Keyword","filename": ".gitleaks.toml","hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8","is_verified": false,- "line_number": 194+ "line_number": 196},{"type": "Secret Keyword","filename": ".gitleaks.toml","hashed_secret": "54937937a07e808bf0ccb9966f2534240b9afb24","is_verified": false,- "line_number": 196+ "line_number": 200},{"type": "Secret Keyword","filename": ".gitleaks.toml","hashed_secret": "0c6c4102d4dfec3b1aa41117e0e344046c58a151","is_verified": false,- "line_number": 197+ "line_number": 201},{"type": "Secret Keyword","filename": ".gitleaks.toml","hashed_secret": "145de4585d0ca1755d0e2914fc95d1d0736cb38a","is_verified": false,- "line_number": 203+ "line_number": 207},{"type": "Secret Keyword","filename": ".gitleaks.toml","hashed_secret": "c7812c56225257705652abb417797151861a2026","is_verified": false,- "line_number": 205+ "line_number": 209},{"type": "Secret Keyword","filename": ".gitleaks.toml","hashed_secret": "638bac731294171648258260ff2af4a09bc02aa2","is_verified": false,- "line_number": 210+ "line_number": 214},{"type": "Secret Keyword","filename": ".gitleaks.toml","hashed_secret": "9de8ffafcde513fa5171292c68b0a3fe707f66c9","is_verified": false,- "line_number": 250+ "line_number": 254}],"Dockerfile": [@@ -1912,7 +1912,7 @@"filename": "tests/database/test_thread_local_session.py","hashed_secret": "e727d1464ae12436e899a726da5b2f11d8381b26","is_verified": false,- "line_number": 328+ "line_number": 334}],"tests/embeddings/conftest.py": [@@ -5188,5 +5188,5 @@}]},- "generated_at": "2026-02-28T12:03:11Z"+ "generated_at": "2026-02-28T15:16:09Z"}diff --git a/src/local_deep_research/web/auth/cleanup_middleware.py b/src/local_deep_research/web/auth/cleanup_middleware.pyindex 929841414f..20c4a8568f 100644--- a/src/local_deep_research/web/auth/cleanup_middleware.py+++ b/src/local_deep_research/web/auth/cleanup_middleware.py@@ -5,7 +5,7 @@ Runs in request context where we have database access.from flask import g, sessionfrom loguru import logger-from sqlalchemy.exc import OperationalError, TimeoutError+from sqlalchemy.exc import OperationalError, PendingRollbackError, TimeoutErrorfrom ...database.models import UserActiveResearchfrom .middleware_optimizer import should_skip_database_middleware@@ -54,7 +54,7 @@ def cleanup_completed_research():f"for user {username}")- except (OperationalError, TimeoutError) as e:+ except (OperationalError, PendingRollbackError, TimeoutError) as e:# Handle connection pool exhaustion and timeout errors gracefullylogger.warning(f"Database connection issue during cleanup - skipping: {type(e).__name__}"diff --git a/src/local_deep_research/web/auth/database_middleware.py b/src/local_deep_research/web/auth/database_middleware.pyindex c3e394d596..ae97945730 100644--- a/src/local_deep_research/web/auth/database_middleware.py+++ b/src/local_deep_research/web/auth/database_middleware.py@@ -18,8 +18,8 @@ def ensure_user_database():if should_skip_database_middleware():return- # Check if we already have a session for this request- if hasattr(g, "db_session") and g.db_session:+ # Check if we already ran for this request+ if getattr(g, "_db_initialized", False):return # Already set upusername = session.get("username")@@ -67,12 +67,12 @@ def ensure_user_database():# If we have a password, get or create thread-local sessionif password:try:- # Use thread-local session manager for efficiency- db_session = get_metrics_session(username, password)- if db_session:- g.db_session = db_session- g.user_password = password- g.username = username+ # Open DB and create thread-local session (stored in _local.session).+ # inject_current_user() will set g.db_session separately.+ get_metrics_session(username, password)+ g._db_initialized = True+ g.user_password = password+ g.username = usernameexcept Exception:# Don't log exceptions here to avoid deadlockpassdiff --git a/tests/database/test_thread_local_session.py b/tests/database/test_thread_local_session.pyindex 944adfc2e4..65b850f1b6 100644--- a/tests/database/test_thread_local_session.py+++ b/tests/database/test_thread_local_session.py@@ -3,7 +3,7 @@import threadingfrom unittest.mock import Mock, call, patch-from sqlalchemy.exc import PendingRollbackError+from sqlalchemy.exc import OperationalError, PendingRollbackErrorclass TestThreadLocalSessionManager:@@ -96,7 +96,9 @@ class TestThreadLocalSessionManager:manager = ThreadLocalSessionManager()mock_invalid_session = Mock()- mock_invalid_session.execute.side_effect = Exception("Connection lost")+ mock_invalid_session.execute.side_effect = OperationalError(+ "stmt", {}, Exception("Connection lost")+ )manager._local.session = mock_invalid_session@@ -212,7 +214,9 @@ class TestThreadLocalSessionManager:# Both execute calls fail — rollback doesn't helpmock_old_session.execute.side_effect = PendingRollbackError("test")- mock_old_session.rollback.side_effect = Exception("rollback failed")+ mock_old_session.rollback.side_effect = OperationalError(+ "stmt", {}, Exception("rollback failed")+ )manager._local.session = mock_old_sessionmanager._local.username = "testuser"@@ -265,7 +269,9 @@ class TestThreadLocalSessionManager:manager = ThreadLocalSessionManager()mock_session = Mock()- mock_session.rollback.side_effect = Exception("dead connection")+ mock_session.rollback.side_effect = OperationalError(+ "stmt", {}, Exception("dead connection")+ )manager._local.session = mock_sessionmanager._local.username = "testuser"thread_id = threading.get_ident()diff --git a/tests/web/auth/test_cleanup_middleware.py b/tests/web/auth/test_cleanup_middleware.pyindex 6ec77886a1..42f28c3085 100644--- a/tests/web/auth/test_cleanup_middleware.py+++ b/tests/web/auth/test_cleanup_middleware.py@@ -175,6 +175,36 @@ class TestCleanupCompletedResearch:cleanup_completed_research()mock_db_session.rollback.assert_called()+ def test_handles_pending_rollback_error(self):+ """Should handle PendingRollbackError gracefully."""+ from sqlalchemy.exc import PendingRollbackError++ app = Flask(__name__)+ app.secret_key = "test"++ mock_db_session = MagicMock()+ mock_db_session.query.side_effect = PendingRollbackError(+ "pending rollback"+ )++ with patch(+ "local_deep_research.web.auth.cleanup_middleware.should_skip_database_middleware"+ ) as mock_skip:+ 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++ # Should not raise exception+ cleanup_completed_research()+ mock_db_session.rollback.assert_called()+def test_handles_timeout_error(self):"""Should handle TimeoutError gracefully."""app = Flask(__name__)diff --git a/tests/web/auth/test_database_middleware.py b/tests/web/auth/test_database_middleware.pyindex fe1986a330..d06fc50617 100644--- a/tests/web/auth/test_database_middleware.py+++ b/tests/web/auth/test_database_middleware.py@@ -33,8 +33,8 @@ class TestEnsureUserDatabase:result = ensure_user_database()assert result is None- def test_skips_when_db_session_already_exists(self):- """Should skip when g.db_session already exists."""+ def test_skips_when_already_initialized(self):+ """Should skip when _db_initialized flag is already set."""app = Flask(__name__)app.secret_key = "test"@@ -49,7 +49,7 @@ class TestEnsureUserDatabase:from flask import gwith app.test_request_context("/dashboard"):- g.db_session = MagicMock() # Pre-existing session+ g._db_initialized = Trueresult = ensure_user_database()assert result is None@@ -239,8 +239,8 @@ class TestEnsureUserDatabase:mock_get_session.assert_called_with("testuser", "dummy")- def test_sets_g_db_session(self):- """Should set g.db_session when session is obtained."""+ def test_sets_db_initialized_flag(self):+ """Should set _db_initialized flag when session is obtained."""app = Flask(__name__)app.secret_key = "test"@@ -271,7 +271,7 @@ class TestEnsureUserDatabase:ensure_user_database()- assert g.db_session == mock_db_session+ assert g._db_initialized is Truedef test_sets_g_username(self):"""Should set g.username."""