~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 research failure when encrypted DB password lost after restart (#2816)
LearningCircuita10a19fc6d60
diff --git a/.github/scripts/file-whitelist-check.sh b/.github/scripts/file-whitelist-check.shindex c1342d7051..a184166bba 100755--- a/.github/scripts/file-whitelist-check.sh+++ b/.github/scripts/file-whitelist-check.sh@@ -143,6 +143,7 @@ SAFE_FILENAME_PATTERNS=(".*change_password\.html$""tests/ui_tests/.*password.*\.js$"".*password_validator\.py$"+".*password_utils\.py$")# Check if filename looks suspiciousdiff --git a/.gitleaksignore b/.gitleaksignoreindex f1b09c4f62..a4c8fc96f7 100644--- a/.gitleaksignore+++ b/.gitleaksignore@@ -540,3 +540,14 @@ scripts/generate_config_docs.py:generic-secret:92# report_generator.py: variable name original_iterations in settings restoration codesrc/local_deep_research/report_generator.py:generic-secret:486++# followup routes.py: password retrieval variable names (user_password, auth_data)+src/local_deep_research/followup_research/routes.py:generic-secret:208+src/local_deep_research/followup_research/routes.py:generic-secret:212+src/local_deep_research/followup_research/routes.py:generic-secret:219+src/local_deep_research/followup_research/routes.py:generic-secret:222++# Password utility helper - variable names, not actual secrets+src/local_deep_research/web/auth/password_utils.py:generic-secret:32+src/local_deep_research/web/auth/password_utils.py:generic-secret:45+src/local_deep_research/followup_research/routes.py:generic-secret:206diff --git a/src/local_deep_research/followup_research/routes.py b/src/local_deep_research/followup_research/routes.pyindex ccd3ca951e..e816b01708 100644--- a/src/local_deep_research/followup_research/routes.py+++ b/src/local_deep_research/followup_research/routes.py@@ -2,7 +2,7 @@Flask routes for follow-up research functionality."""-from flask import Blueprint, request, jsonify, session, g+from flask import Blueprint, request, jsonify, sessionfrom loguru import loggerfrom ..constants import ResearchStatus@@ -10,6 +10,7 @@ from .service import FollowUpResearchServicefrom .models import FollowUpRequestfrom ..security.decorators import require_json_bodyfrom ..web.auth.decorators import login_required+from ..web.auth.password_utils import get_user_password# Create blueprintfollowup_bp = Blueprint("followup", __name__, url_prefix="/api/followup")@@ -198,6 +199,33 @@ def start_followup():f"Query type: {type(research_params.get('query')) if isinstance(research_params, dict) else 'N/A'}")+ # Get user password for metrics database access.+ # Uses the shared helper (password_utils) so every route checks the+ # same three sources in the same order — avoids subtle divergence.+ # Must check BEFORE creating ResearchHistory to avoid orphaned records.+ user_password = get_user_password(username)++ if not user_password:+ from ..database.encrypted_db import db_manager++ if db_manager.has_encryption:+ logger.error(+ f"No password available for user {username} with encrypted database - "+ "cannot start follow-up research (session password expired or lost after server restart)"+ )+ # Use success/error keys to match followup API convention+ # (the followup frontend checks data.success and data.error)+ return jsonify(+ {+ "success": False,+ "error": "Your session has expired. Please log out and log back in to start research.",+ }+ ), 401+ else:+ logger.warning(+ f"No password available for metrics access for user {username}"+ )+# Generate new research IDresearch_id = str(uuid.uuid4())@@ -238,36 +266,6 @@ def start_followup():f"Starting follow-up research for query of type: {type(research_params.get('query'))}")- # Get user password for metrics database access- user_password = None- session_id = session.get("session_id")- if session_id:- from ..database.session_passwords import session_password_store-- user_password = session_password_store.retrieve(- username, session_id- )-- # Fallback to g.user_password (set by middleware if temp_auth was used)- if not user_password:- user_password = getattr(g, "user_password", None)-- # Last resort: try temp_auth_store- if not user_password:- from ..database.temp_auth import temp_auth_store-- auth_token = session.get("temp_auth_token")- if auth_token:- # Use peek_auth to avoid consuming the token- auth_data = temp_auth_store.peek_auth(auth_token)- if auth_data and auth_data[0] == username:- user_password = auth_data[1]-- if not user_password:- logger.warning(- f"No password available for metrics access for user {username}"- )-# Get model and search settings from user's settingsmodel_provider = settings_snapshot.get("llm.provider", {}).get("value", "OLLAMA"diff --git a/src/local_deep_research/followup_research/service.py b/src/local_deep_research/followup_research/service.pyindex fb9183498d..f0b2104869 100644--- a/src/local_deep_research/followup_research/service.py+++ b/src/local_deep_research/followup_research/service.py@@ -90,18 +90,30 @@ class FollowUpResearchService:logger.info(f"Found {len(meta_sources)} sources in research_meta, saving to database")- # Save them to the database for future use- saved = sources_service.save_research_sources(- parent_research_id,- meta_sources,- username=self.username,- )- logger.info(f"Saved {saved} sources to database")-- # Now retrieve them properly formatted- resource_list = sources_service.get_research_sources(- parent_research_id, username=self.username- )+ # Source migration is non-fatal: the followup can+ # still proceed using meta_sources directly even if+ # saving to the ResearchResource table fails (e.g.+ # encrypted DB password expired mid-session).+ try:+ saved = sources_service.save_research_sources(+ parent_research_id,+ meta_sources,+ username=self.username,+ )+ logger.info(f"Saved {saved} sources to database")++ # Now retrieve them properly formatted+ resource_list = (+ sources_service.get_research_sources(+ parent_research_id,+ username=self.username,+ )+ )+ except Exception:+ logger.exception(+ f"Failed to save/retrieve sources for parent research "+ f"{parent_research_id} (continuing with raw meta_sources)"+ )# Convert to dictionary formatparent_data = {diff --git a/src/local_deep_research/web/auth/password_utils.py b/src/local_deep_research/web/auth/password_utils.pynew file mode 100644index 0000000000..8cab2c69c0--- /dev/null+++ b/src/local_deep_research/web/auth/password_utils.py@@ -0,0 +1,50 @@+"""+Shared utility for retrieving user passwords from available session sources.++Centralises the 3-source fallback chain (session password store → Flask g →+temp auth store) so every route that needs the current user's DB password+uses the same logic. Without this, each route reimplemented the chain+independently, risking subtle divergence (e.g. one route forgetting to+check temp_auth, or using a different method alias).+"""++from typing import Optional++from flask import g, session+++def get_user_password(username: str) -> Optional[str]:+ """Retrieve user password from available session sources.++ Checks, in order:+ 1. SessionPasswordStore (persistent per-session passwords)+ 2. Flask ``g.user_password`` (set by middleware when temp_auth was used)+ 3. TempAuthStore (one-time tokens stored during login redirect)++ Returns ``None`` when no password can be found — callers must decide+ whether that is acceptable (e.g. non-encrypted databases) or an error+ (encrypted databases → 401).+ """+ from ...database.session_passwords import session_password_store++ session_id = session.get("session_id")+ if session_id:+ password = session_password_store.get_session_password(+ username, session_id+ )+ if password:+ return password++ password = getattr(g, "user_password", None)+ if password:+ return password++ from ...database.temp_auth import temp_auth_store++ auth_token = session.get("temp_auth_token")+ if auth_token:+ auth_data = temp_auth_store.peek_auth(auth_token)+ if auth_data and auth_data[0] == username:+ return auth_data[1]++ return Nonediff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex 6540b4f79d..6fa5bb79be 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -38,8 +38,10 @@ from ...database.models import (UserActiveResearch,)from ...database.models.library import Document as Document+from ...database.encrypted_db import db_managerfrom ...database.session_context import get_user_db_sessionfrom ..auth.decorators import login_required+from ..auth.password_utils import get_user_passwordfrom ..models.database import calculate_durationfrom ..services.research_service import (export_report_to_memory,@@ -59,6 +61,7 @@ from .globals import (# Create a Blueprint for the research applicationresearch_bp = Blueprint("research", __name__)+# NOTE: Routes use session["username"] (not .get()) intentionally.# @login_required guarantees the key exists; direct access fails fast# if the decorator is ever removed.@@ -297,6 +300,31 @@ def start_research():# Default to not queueing if we can't checkshould_queue = False+ # For non-queued research, verify password is available BEFORE creating DB records+ # (queued research gets password later via queue processor)+ user_password = None+ if not should_queue:+ user_password = get_user_password(username)++ if not user_password:+ if db_manager.has_encryption:+ logger.error(+ f"No password available for user {username} with encrypted database - "+ "cannot start research (session password expired or lost after server restart)"+ )+ # Use status/message keys to match the research API convention+ # (the research frontend checks data.status and data.message)+ return jsonify(+ {+ "status": "error",+ "message": "Your session has expired. Please log out and log back in to start research.",+ }+ ), 401+ else:+ logger.warning(+ f"No password available for metrics access for user {username}"+ )+# Create a record in the database with explicit UTC timestampimport uuidimport threading@@ -360,17 +388,7 @@ def start_research():)from ...database.thread_local_session import get_metrics_session- # Get password from session or g- password = getattr(g, "user_password", None)- if not password:- # Try to get from session password store- from ...database.session_passwords import session_password_store-- session_id = session.get("session_id")- if session_id:- password = session_password_store.get_session_password(- username, session_id- )+ password = get_user_password(username)if password:temp_session = get_metrics_session(username, password)@@ -622,38 +640,6 @@ def start_research():else:logger.debug("search.tool NOT in snapshot")- # Get the user's password for metrics access in background thread- # Try session password store first- from ...database.session_passwords import session_password_store-- session_id = session.get("session_id")- user_password = None-- if session_id:- user_password = session_password_store.get_session_password(- username, session_id- )-- # Fallback to g.user_password (set by middleware if temp_auth was used)- if not user_password:- user_password = getattr(g, "user_password", None)-- # Last resort: try temp_auth_store- if not user_password:- from ...database.temp_auth import temp_auth_store-- auth_token = session.get("temp_auth_token")- if auth_token:- # Use peek_auth to avoid consuming the token- auth_data = temp_auth_store.peek_auth(auth_token)- if auth_data and auth_data[0] == username:- user_password = auth_data[1]-- if not user_password:- logger.warning(- f"No password available for metrics access for user {username}"- )-# Start the research process with the selected parametersresearch_thread = start_research_process(research_id,diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 4a3026bf4f..1709858f1e 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -975,21 +975,31 @@ def run_research_process(research_id, query, mode, **kwargs):- Generated at: {datetime.now(UTC).isoformat()}"""- # Save sources to database- from .research_sources_service import ResearchSourcesService-- sources_service = ResearchSourcesService()- if all_links:- logger.info(- f"Quick summary: Saving {len(all_links)} sources to database"- )- sources_saved = sources_service.save_research_sources(- research_id=research_id,- sources=all_links,- username=username,+ # Save sources to database (non-fatal - report should still+ # be saved even if source saving fails)+ try:+ from .research_sources_service import (+ ResearchSourcesService,)- logger.info(- f"Quick summary: Saved {sources_saved} sources for research {research_id}"++ sources_service = ResearchSourcesService()+ if all_links:+ logger.info(+ f"Quick summary: Saving {len(all_links)} sources to database"+ )+ sources_saved = (+ sources_service.save_research_sources(+ research_id=research_id,+ sources=all_links,+ username=username,+ )+ )+ logger.info(+ f"Quick summary: Saved {sources_saved} sources for research {research_id}"+ )+ except Exception:+ logger.exception(+ f"Failed to save sources for research {research_id} (continuing with report save)")# Save report using storage abstraction@@ -1239,24 +1249,30 @@ def run_research_process(research_id, query, mode, **kwargs):final_report["content"])- # Save sources to database- from .research_sources_service import ResearchSourcesService+ # Save sources to database (non-fatal - report should still be saved+ # even if source saving fails, e.g. due to expired session password)+ try:+ from .research_sources_service import ResearchSourcesService- sources_service = ResearchSourcesService()- if (- hasattr(search_system, "all_links_of_system")- and search_system.all_links_of_system- ):- logger.info(- f"Saving {len(search_system.all_links_of_system)} sources to database"- )- sources_saved = sources_service.save_research_sources(- research_id=research_id,- sources=search_system.all_links_of_system,- username=username,- )- logger.info(- f"Saved {sources_saved} sources for research {research_id}"+ sources_service = ResearchSourcesService()+ if (+ hasattr(search_system, "all_links_of_system")+ and search_system.all_links_of_system+ ):+ logger.info(+ f"Saving {len(search_system.all_links_of_system)} sources to database"+ )+ sources_saved = sources_service.save_research_sources(+ research_id=research_id,+ sources=search_system.all_links_of_system,+ username=username,+ )+ logger.info(+ f"Saved {sources_saved} sources for research {research_id}"+ )+ except Exception:+ logger.exception(+ f"Failed to save sources for research {research_id} (continuing with report save)")# Save report to databasediff --git a/tests/followup_research/test_routes_coverage.py b/tests/followup_research/test_routes_coverage.pyindex 148d803833..c935ac9da4 100644--- a/tests/followup_research/test_routes_coverage.py+++ b/tests/followup_research/test_routes_coverage.py@@ -422,7 +422,12 @@ class TestStartFollowupNoPassword:"""start_followup logs a warning when no password is available from any source."""def test_no_password_logs_warning(self, app):- """Logs warning when password cannot be retrieved from any source."""+ """Logs warning when password cannot be retrieved from any source.++ With non-encrypted DB, no password just logs a warning and continues.+ We must mock has_encryption=False, otherwise the early password+ check returns 401 (correct behavior for encrypted DBs).+ """mock_service = Mock()mock_service.perform_followup.return_value = {"query": "q",@@ -433,6 +438,8 @@ class TestStartFollowupNoPassword:"parent_research_id": "p1",}+ mock_db_mgr = MagicMock(has_encryption=False)+with (patch(AUTH_DB_MANAGER, _mock_auth()),patch(SETTINGS_MANAGER, return_value=_make_settings_mock()),@@ -445,6 +452,10 @@ class TestStartFollowupNoPassword:patch(RESEARCH_HISTORY),patch("uuid.uuid4", return_value=Mock(__str__=lambda s: "id4")),patch(f"{MODULE}.logger") as mock_logger,+ patch(+ "local_deep_research.database.encrypted_db.db_manager",+ mock_db_mgr,+ ),):# No session_id and no temp_auth_token in sessionresp = _authed_post(diff --git a/tests/test_followup_api.py b/tests/test_followup_api.pyindex 97a84594ab..e62fe685a0 100644--- a/tests/test_followup_api.py+++ b/tests/test_followup_api.py@@ -25,12 +25,21 @@ class TestFollowUpAPI:@pytest.fixture(autouse=True)def mock_db_manager(self):- """Mock the database manager for all tests."""- with patch(- "local_deep_research.web.auth.decorators.db_manager"- ) as mock_db:- # Mock the database connection check+ """Mock the database manager for all tests.++ has_encryption=False avoids the early password check in routes+ that returns 401 when encrypted DB password is unavailable.+ """+ with (+ patch(+ "local_deep_research.web.auth.decorators.db_manager"+ ) as mock_db,+ patch(+ "local_deep_research.database.encrypted_db.db_manager"+ ) as mock_enc_db,+ ):mock_db.connections = {"testuser": MagicMock()}+ mock_enc_db.has_encryption = Falseyield mock_db@pytest.fixturediff --git a/tests/web/routes/test_encrypted_db_password_check.py b/tests/web/routes/test_encrypted_db_password_check.pynew file mode 100644index 0000000000..48665710a3--- /dev/null+++ b/tests/web/routes/test_encrypted_db_password_check.py@@ -0,0 +1,295 @@+"""+HTTP behavioral tests for encrypted DB password check at research start.++Verifies that /api/start_research returns 401 when the encrypted DB+password is unavailable, and that the check happens BEFORE creating+database records (no orphaned IN_PROGRESS rows).+"""++from contextlib import contextmanager+from unittest.mock import Mock, patch++from flask import Flask, jsonify++from local_deep_research.followup_research.routes import followup_bp+from local_deep_research.web.auth.routes import auth_bp+from local_deep_research.web.routes.research_routes import research_bp+++# ---------------------------------------------------------------------------+# Test Infrastructure+# ---------------------------------------------------------------------------++_ROUTES_MOD = "local_deep_research.web.routes.research_routes"+++def _create_test_app():+ """Create Flask app with auth + research blueprints."""+ app = Flask(__name__)+ app.config["SECRET_KEY"] = "test-secret"+ app.config["WTF_CSRF_ENABLED"] = False+ app.register_blueprint(auth_bp)+ app.register_blueprint(research_bp)++ @app.errorhandler(500)+ def _handle_500(error):+ return jsonify({"error": "Internal server error"}), 500++ return app+++@contextmanager+def _authenticated_client(app, has_encryption=False, password_available=True):+ """Provide test client with mocked auth, DB session, and settings."""+ mock_db = Mock()+ mock_db.connections = {"testuser": True}+ mock_db.has_encryption = has_encryption++ # Chainable mock query+ _mock_query = Mock()+ _mock_query.all.return_value = []+ _mock_query.first.return_value = None+ _mock_query.count.return_value = 0+ _mock_query.scalar.return_value = 0+ _mock_query.filter_by.return_value = _mock_query+ _mock_query.filter.return_value = _mock_query+ _mock_query.order_by.return_value = _mock_query+ _mock_query.limit.return_value = _mock_query++ _mock_db_session = Mock()+ _mock_db_session.query.return_value = _mock_query++ @contextmanager+ def _fake_session(*args, **kwargs):+ yield _mock_db_session++ # Mock session password store+ mock_password_store = Mock()+ if password_available:+ mock_password_store.get_session_password.return_value = "test-password"+ else:+ mock_password_store.get_session_password.return_value = None++ # Mock SettingsManager+ mock_settings_manager = Mock()+ mock_settings_manager.get_setting.side_effect = lambda key, default=None: {+ "llm.provider": "OLLAMA",+ "llm.model": "test-model",+ "search.tool": "searxng",+ "search.iterations": 5,+ "search.questions_per_iteration": 5,+ "search.search_strategy": "source-based",+ "app.max_concurrent_researches": 3,+ }.get(key, default)+ mock_settings_manager.get_all_settings.return_value = {}++ # Mock start_research_process to avoid actually starting threads+ mock_start = Mock()+ mock_start.return_value = Mock() # mock thread++ # Mock SettingsManager constructor to return our mock+ mock_settings_cls = Mock(return_value=mock_settings_manager)++ patches = [+ patch("local_deep_research.web.auth.decorators.db_manager", mock_db),+ patch(f"{_ROUTES_MOD}.db_manager", mock_db),+ patch(+ f"{_ROUTES_MOD}.get_user_db_session",+ side_effect=_fake_session,+ ),+ patch(+ f"{_ROUTES_MOD}.start_research_process",+ mock_start,+ ),+ patch(+ "local_deep_research.database.session_passwords.session_password_store",+ mock_password_store,+ ),+ patch(+ "local_deep_research.settings.manager.SettingsManager",+ mock_settings_cls,+ ),+ patch(+ "local_deep_research.settings.SettingsManager",+ mock_settings_cls,+ ),+ ]++ started = []+ try:+ for p in patches:+ started.append(p.start())+ with app.test_client() as client:+ with client.session_transaction() as sess:+ sess["username"] = "testuser"+ sess["session_id"] = "test-session-id"+ yield client, mock_start, _mock_db_session+ finally:+ for p in patches:+ p.stop()+++def _post_start_research(client):+ """POST a minimal research request."""+ return client.post(+ "/api/start_research",+ json={+ "query": "test query",+ "mode": "quick",+ "model_provider": "OLLAMA",+ "model": "test-model",+ },+ content_type="application/json",+ )+++# ---------------------------------------------------------------------------+# Tests+# ---------------------------------------------------------------------------+++class TestEncryptedDbPasswordCheck:+ """Verify encrypted DB password check at /api/start_research."""++ def test_encrypted_db_no_password_returns_401(self):+ """Encrypted DB + no password → 401 with session expired message."""+ app = _create_test_app()+ with _authenticated_client(+ app, has_encryption=True, password_available=False+ ) as (client, mock_start, mock_db_session):+ resp = _post_start_research(client)+ assert resp.status_code == 401+ data = resp.get_json()+ assert "session has expired" in data["message"].lower()+ # Research should NOT have been started+ mock_start.assert_not_called()+ # No DB record should have been created (core guarantee)+ mock_db_session.add.assert_not_called()++ def test_encrypted_db_with_password_does_not_return_401(self):+ """Encrypted DB + password available → should NOT return 401."""+ app = _create_test_app()+ with _authenticated_client(+ app, has_encryption=True, password_available=True+ ) as (client, _mock_start, _mock_db_session):+ resp = _post_start_research(client)+ # 500 is expected from incomplete mocking (settings snapshot);+ # the key assertion is that the password check passed (not 401).+ assert resp.status_code in (200, 500)++ def test_unencrypted_db_no_password_does_not_return_401(self):+ """Unencrypted DB + no password → should NOT return 401 (warning only)."""+ app = _create_test_app()+ with _authenticated_client(+ app, has_encryption=False, password_available=False+ ) as (client, _mock_start, _mock_db_session):+ resp = _post_start_research(client)+ assert resp.status_code in (200, 500)+++# ---------------------------------------------------------------------------+# Follow-up route tests+# ---------------------------------------------------------------------------++_FOLLOWUP_MOD = "local_deep_research.followup_research.routes"+++def _create_followup_test_app():+ """Create Flask app with auth + followup blueprints."""+ app = Flask(__name__)+ app.config["SECRET_KEY"] = "test-secret"+ app.config["WTF_CSRF_ENABLED"] = False+ app.register_blueprint(auth_bp)+ app.register_blueprint(followup_bp)++ @app.errorhandler(500)+ def _handle_500(error):+ return jsonify({"error": "Internal server error"}), 500++ return app+++@contextmanager+def _authenticated_followup_client(+ app, has_encryption=False, password_available=True+):+ """Provide test client with mocked auth and followup dependencies."""+ mock_db = Mock()+ mock_db.connections = {"testuser": True}+ mock_db.has_encryption = has_encryption++ _mock_db_session = Mock()++ @contextmanager+ def _fake_session(*args, **kwargs):+ yield _mock_db_session++ mock_password_store = Mock()+ if password_available:+ mock_password_store.get_session_password.return_value = "test-password"+ else:+ mock_password_store.get_session_password.return_value = None++ mock_settings_manager = Mock()+ mock_settings_manager.get_all_settings.return_value = {}+ mock_settings_cls = Mock(return_value=mock_settings_manager)++ patches = [+ patch("local_deep_research.web.auth.decorators.db_manager", mock_db),+ patch("local_deep_research.database.encrypted_db.db_manager", mock_db),+ patch(+ "local_deep_research.database.session_passwords.session_password_store",+ mock_password_store,+ ),+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ side_effect=_fake_session,+ ),+ patch(+ "local_deep_research.settings.manager.SettingsManager",+ mock_settings_cls,+ ),+ ]++ started = []+ try:+ for p in patches:+ started.append(p.start())+ with app.test_client() as client:+ with client.session_transaction() as sess:+ sess["username"] = "testuser"+ sess["session_id"] = "test-session-id"+ yield client, _mock_db_session+ finally:+ for p in patches:+ p.stop()+++def _post_followup_start(client):+ """POST a minimal followup start request."""+ return client.post(+ "/api/followup/start",+ json={+ "parent_research_id": "fake-parent-id",+ "question": "follow-up question",+ },+ content_type="application/json",+ )+++class TestFollowupEncryptedDbPasswordCheck:+ """Verify encrypted DB password check at /api/followup/start."""++ def test_encrypted_db_no_password_returns_401(self):+ """Encrypted DB + no password → 401 on followup start."""+ app = _create_followup_test_app()+ with _authenticated_followup_client(+ app, has_encryption=True, password_available=False+ ) as (client, mock_db_session):+ resp = _post_followup_start(client)+ assert resp.status_code == 401+ data = resp.get_json()+ assert data["success"] is False+ assert "session has expired" in data["error"].lower()+ # No DB record should have been created+ mock_db_session.add.assert_not_called()diff --git a/tests/web/routes/test_research_routes_start_research_coverage.py b/tests/web/routes/test_research_routes_start_research_coverage.pyindex 8d254e4d35..720798d61b 100644--- a/tests/web/routes/test_research_routes_start_research_coverage.py+++ b/tests/web/routes/test_research_routes_start_research_coverage.py@@ -117,7 +117,11 @@ def _configure_ms_for_active(ms, active_count=0, max_pos=0):@pytest.fixture()def app():- """Create a minimal Flask app with the research blueprint, auth bypassed."""+ """Create a minimal Flask app with the research blueprint, auth bypassed.++ has_encryption=False avoids the early password check that returns 401+ when no password is available for encrypted databases.+ """flask_app = Flask(__name__)flask_app.secret_key = "test-secret-key"flask_app.config["TESTING"] = True@@ -126,8 +130,12 @@ def app():flask_app.register_blueprint(research_bp)- with patch("local_deep_research.web.auth.decorators.db_manager") as mock_db:+ with (+ patch("local_deep_research.web.auth.decorators.db_manager") as mock_db,+ patch(f"{MODULE}.db_manager") as mock_enc_db,+ ):mock_db.is_user_connected.return_value = True+ mock_enc_db.has_encryption = Falseyield flask_appdiff --git a/tests/web/services/test_source_saving_non_fatal.py b/tests/web/services/test_source_saving_non_fatal.pynew file mode 100644index 0000000000..61e3de28ad--- /dev/null+++ b/tests/web/services/test_source_saving_non_fatal.py@@ -0,0 +1,75 @@+"""+Behavioral tests that source saving failure does not crash research.++The service itself re-raises exceptions (keeping error handling honest).+The callers in research_service.py wrap source saving in try/except so+a failure doesn't prevent the report from being saved.+"""++import pytest+from contextlib import contextmanager+from unittest.mock import Mock, patch++from local_deep_research.database.session_context import DatabaseSessionError+from local_deep_research.web.services.research_sources_service import (+ ResearchSourcesService,+)++_SERVICE_MOD = "local_deep_research.web.services.research_sources_service"+++@contextmanager+def _mock_db_session(mock_session=None):+ """Context manager that yields a mock session."""+ yield mock_session or Mock()+++class TestSourceSavingNonFatal:+ """Source saving failure should not prevent report from being saved."""++ def test_service_raises_on_db_session_error(self):+ """Service re-raises DatabaseSessionError (callers decide if fatal)."""++ def _raise(*args, **kwargs):+ raise DatabaseSessionError("no password")++ with patch(f"{_SERVICE_MOD}.get_user_db_session", side_effect=_raise):+ with pytest.raises(DatabaseSessionError):+ ResearchSourcesService.save_research_sources(+ "test-id",+ [{"url": "https://example.com", "title": "Test"}],+ username="testuser",+ )++ def test_returns_zero_on_empty_sources(self):+ """Empty sources list returns 0 without touching the database."""+ # No need to mock anything — empty list triggers early return+ result = ResearchSourcesService.save_research_sources(+ "test-id", [], username="testuser"+ )+ assert result == 0++ def test_saves_sources_and_returns_count(self):+ """With a working session, saves sources and returns count."""+ mock_session = Mock()+ mock_query = Mock()+ mock_query.count.return_value = 0 # No existing resources+ mock_query.filter_by.return_value = mock_query+ mock_session.query.return_value = mock_query++ with patch(+ f"{_SERVICE_MOD}.get_user_db_session",+ return_value=_mock_db_session(mock_session),+ ):+ result = ResearchSourcesService.save_research_sources(+ "test-id",+ [+ {"url": "https://example.com/1", "title": "Source 1"},+ {"url": "https://example.com/2", "title": "Source 2"},+ ],+ username="testuser",+ )++ assert result == 2+ assert mock_session.add.call_count == 2+ mock_session.commit.assert_called_once()