~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: eliminate DB connection leaks via context manager improvements (#2595)
LearningCircuit62fa75e8b637
diff --git a/src/local_deep_research/library/download_management/status_tracker.py b/src/local_deep_research/library/download_management/status_tracker.pyindex 1c656ea101..201ad2d100 100644--- a/src/local_deep_research/library/download_management/status_tracker.py+++ b/src/local_deep_research/library/download_management/status_tracker.py@@ -60,75 +60,73 @@ class ResourceStatusTracker:failure: Classified failure objectsession: Optional existing database session to reuse"""- # Use provided session or create new one- should_close = session is None- if session is None:- session = self._get_session()+ if session is not None:+ self._apply_failure(session, resource_id, failure)+ return- try:- # Get or create status record- status = (- session.query(ResourceDownloadStatus)- .filter_by(resource_id=resource_id)- .first()- )+ with self._get_session() as session:+ self._apply_failure(session, resource_id, failure)+ session.commit()- if not status:- status = ResourceDownloadStatus(resource_id=resource_id)- session.add(status)-- # Update status information- if failure.is_permanent():- status.status = "permanently_failed"- status.retry_after_timestamp = None- status.failure_type = failure.error_type- status.failure_message = failure.message- status.permanent_failure_at = datetime.now(UTC)- logger.info(- f"[STATUS_TRACKER] Marked resource {resource_id} as permanently failed: {failure.error_type}"- )- else:- status.status = "temporarily_failed"- status.retry_after_timestamp = (- failure.created_at + failure.retry_after- )- status.failure_type = failure.error_type- status.failure_message = failure.message- logger.info(- f"[STATUS_TRACKER] Marked resource {resource_id} as temporarily failed: {failure.error_type}, retry after: {failure.retry_after}"- )+ def _apply_failure(+ self, session: Session, resource_id: int, failure: BaseFailure+ ) -> None:+ """Apply failure status updates to a session (does not commit)."""+ # Get or create status record+ status = (+ session.query(ResourceDownloadStatus)+ .filter_by(resource_id=resource_id)+ .first()+ )- # Update retry statistics- # Ensure total_retry_count is initialized (handle None from legacy data)- if status.total_retry_count is None:- status.total_retry_count = 0- status.total_retry_count += 1- status.last_attempt_at = datetime.now(UTC)-- # Check if retry is today- today = datetime.now(UTC).date()- last_attempt = (- status.last_attempt_at.date()- if status.last_attempt_at- else None+ if not status:+ status = ResourceDownloadStatus(resource_id=resource_id)+ session.add(status)++ # Update status information+ if failure.is_permanent():+ status.status = "permanently_failed"+ status.retry_after_timestamp = None+ status.failure_type = failure.error_type+ status.failure_message = failure.message+ status.permanent_failure_at = datetime.now(UTC)+ logger.info(+ f"[STATUS_TRACKER] Marked resource {resource_id} as permanently failed: {failure.error_type}")- if last_attempt == today:- # Ensure today_retry_count is initialized (handle None from legacy data)- if status.today_retry_count is None:- status.today_retry_count = 0- status.today_retry_count += 1- else:- status.today_retry_count = 1-- # Only commit if we created the session- if should_close:- session.commit()- logger.debug(- f"[STATUS_TRACKER] Updated failure status for resource {resource_id}"+ else:+ status.status = "temporarily_failed"+ status.retry_after_timestamp = (+ failure.created_at + failure.retry_after)- finally:- if should_close:- session.close()+ status.failure_type = failure.error_type+ status.failure_message = failure.message+ logger.info(+ f"[STATUS_TRACKER] Marked resource {resource_id} as temporarily failed: {failure.error_type}, retry after: {failure.retry_after}"+ )++ # Update retry statistics+ # Ensure total_retry_count is initialized (handle None from legacy data)+ if status.total_retry_count is None:+ status.total_retry_count = 0+ status.total_retry_count += 1+ status.last_attempt_at = datetime.now(UTC)++ # Check if retry is today+ today = datetime.now(UTC).date()+ last_attempt = (+ status.last_attempt_at.date() if status.last_attempt_at else None+ )+ if last_attempt == today:+ # Ensure today_retry_count is initialized (handle None from legacy data)+ if status.today_retry_count is None:+ status.today_retry_count = 0+ status.today_retry_count += 1+ else:+ status.today_retry_count = 1++ logger.debug(+ f"[STATUS_TRACKER] Updated failure status for resource {resource_id}"+ )def mark_success(self, resource_id: int, session: Optional[Session] = None@@ -140,34 +138,31 @@ class ResourceStatusTracker:resource_id: Resource identifiersession: Optional existing database session to reuse"""- # Use provided session or create new one- should_close = session is None- if session is None:- session = self._get_session()+ if session is not None:+ self._apply_success(session, resource_id)+ return- try:- status = (- session.query(ResourceDownloadStatus)- .filter_by(resource_id=resource_id)- .first()- )+ with self._get_session() as session:+ self._apply_success(session, resource_id)+ session.commit()- if status:- status.status = "completed"- status.failure_type = None- status.failure_message = None- status.retry_after_timestamp = None- status.updated_at = datetime.now(UTC)- logger.info(- f"[STATUS_TRACKER] Marked resource {resource_id} as successfully completed"- )+ def _apply_success(self, session: Session, resource_id: int) -> None:+ """Apply success status updates to a session (does not commit)."""+ status = (+ session.query(ResourceDownloadStatus)+ .filter_by(resource_id=resource_id)+ .first()+ )- # Only commit if we created the session- if should_close:- session.commit()- finally:- if should_close:- session.close()+ if status:+ status.status = "completed"+ status.failure_type = None+ status.failure_message = None+ status.retry_after_timestamp = None+ status.updated_at = datetime.now(UTC)+ logger.info(+ f"[STATUS_TRACKER] Marked resource {resource_id} as successfully completed"+ )def can_retry(self, resource_id: int) -> tuple[bool, Optional[str]]:"""diff --git a/src/local_deep_research/security/file_integrity/integrity_manager.py b/src/local_deep_research/security/file_integrity/integrity_manager.pyindex 65812406a0..d756f55010 100644--- a/src/local_deep_research/security/file_integrity/integrity_manager.py+++ b/src/local_deep_research/security/file_integrity/integrity_manager.py@@ -194,26 +194,33 @@ class FileIntegrityManager:"""normalized_path = self._normalize_path(file_path)+ # First check if record existswith get_user_db_session(self.username, self.password) as session:record = (session.query(FileIntegrityRecord).filter_by(file_path=normalized_path).first())+ has_record = record is not None- if not record:- logger.warning(- f"[FILE_INTEGRITY] No record found for {file_path}, creating one"- )- # Create record if it doesn't exist- try:- # Need to commit and return since we're in a different session- session.close()- self.record_file(file_path)- return True, None- except Exception as e:- logger.exception("[FILE_INTEGRITY] Failed to create record")- return False, f"Failed to create integrity record: {str(e)}"+ if not has_record:+ logger.warning(+ f"[FILE_INTEGRITY] No record found for {file_path}, creating one"+ )+ try:+ self.record_file(file_path)+ return True, None+ except Exception as e:+ logger.exception("[FILE_INTEGRITY] Failed to create record")+ return False, f"Failed to create integrity record: {str(e)}"++ # Re-enter context for verification+ with get_user_db_session(self.username, self.password) as session:+ record = (+ session.query(FileIntegrityRecord)+ .filter_by(file_path=normalized_path)+ .first()+ )# Check if verification neededif not force and not self._needs_verification(record, file_path):diff --git a/src/local_deep_research/utilities/search_cache.py b/src/local_deep_research/utilities/search_cache.pyindex 52ebe608f7..97b71e17a0 100644--- a/src/local_deep_research/utilities/search_cache.py+++ b/src/local_deep_research/utilities/search_cache.py@@ -4,6 +4,7 @@ Provides intelligent caching for search results to avoid repeated queries.Includes TTL, LRU eviction, and query normalization."""+import atexitimport hashlibimport threadingimport time@@ -512,6 +513,15 @@ def get_search_cache() -> SearchCache:return _global_cache+def _dispose_global_cache():+ global _global_cache+ if _global_cache is not None:+ _global_cache.dispose()+++atexit.register(_dispose_global_cache)++@lru_cache(maxsize=100)def normalize_entity_query(entity: str, constraint: str) -> str:"""diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex 12f3805880..b73a341d92 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -466,6 +466,11 @@ def create_app():queue_processor.start()logger.info("Started research queue processor v2")+ # Register shutdown cleanup for thread engine disposal+ import atexit++ atexit.register(db_manager.cleanup_all_thread_engines)+logger.info("App factory completed successfully")return app, socket_servicediff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.pyindex 09396371b0..41b8d59be5 100644--- a/src/local_deep_research/web/auth/routes.py+++ b/src/local_deep_research/web/auth/routes.py@@ -18,7 +18,7 @@ from flask import ()from loguru import logger-from ...database.auth_db import get_auth_db_session+from ...database.auth_db import auth_db_sessionfrom ...database.encrypted_db import db_managerfrom ...database.models.auth import Userfrom ...database.thread_local_session import thread_cleanup@@ -162,27 +162,23 @@ def _perform_post_login_tasks(username: str, password: str) -> None:# 1. Settings version check + migrationtry:from ...settings.manager import SettingsManager+ from ...database.session_context import get_user_db_session- db_session = db_manager.get_session(username)- try:- if db_session:- settings_manager = SettingsManager(db_session)- if not settings_manager.db_version_matches_package():- logger.info(- f"Database version mismatch for {username} "- "- loading missing default settings"- )- settings_manager.load_from_defaults_file(- commit=True, overwrite=False- )- settings_manager.update_db_version()- logger.info(- f"Missing default settings loaded and version "- f"updated for user {username}"- )- finally:- if db_session:- db_session.close()+ with get_user_db_session(username) as db_session:+ settings_manager = SettingsManager(db_session)+ if not settings_manager.db_version_matches_package():+ logger.info(+ f"Database version mismatch for {username} "+ "- loading missing default settings"+ )+ settings_manager.load_from_defaults_file(+ commit=True, overwrite=False+ )+ settings_manager.update_db_version()+ logger.info(+ f"Missing default settings loaded and version "+ f"updated for user {username}"+ )except Exception:logger.exception(f"Post-login settings migration failed for {username}")@@ -203,8 +199,7 @@ def _perform_post_login_tasks(username: str, password: str) -> None:# 3. Update last_login in auth DB + notify news schedulertry:- auth_db = get_auth_db_session()- try:+ with auth_db_session() as auth_db:user = auth_db.query(User).filter_by(username=username).first()if user:user.last_login = datetime.now(UTC)@@ -224,8 +219,6 @@ def _perform_post_login_tasks(username: str, password: str) -> None:logger.exception("Could not update scheduler on login")auth_db.commit()- finally:- auth_db.close()except Exception:logger.exception(f"Post-login auth DB update failed for {username}")@@ -233,18 +226,13 @@ def _perform_post_login_tasks(username: str, password: str) -> None:try:from ...database.models import ProviderModel- user_db_session = db_manager.get_session(username)- try:- if user_db_session:- deleted_count = user_db_session.query(ProviderModel).delete()- user_db_session.commit()- logger.info(- f"Cleared {deleted_count} cached models "- f"for user {username} on login"- )- finally:- if user_db_session:- user_db_session.close()+ with get_user_db_session(username) as user_db_session:+ deleted_count = user_db_session.query(ProviderModel).delete()+ user_db_session.commit()+ logger.info(+ f"Cleared {deleted_count} cached models "+ f"for user {username} on login"+ )except Exception:logger.exception(f"Post-login model cache clear failed for {username}")@@ -330,36 +318,30 @@ def register():), 400# Create user in auth database- auth_db = get_auth_db_session()- try:- new_user = User(username=username)- auth_db.add(new_user)- auth_db.commit()- except IntegrityError:- # Catch duplicate username specifically (race condition case)- # This handles the edge case where two requests for the same username- # pass the user_exists() check simultaneously- logger.warning(f"Duplicate username attempted: {username}")- auth_db.rollback()- auth_db.close()- flash("Registration failed. Please try a different username.", "error")- return render_template(- "auth/register.html", has_encryption=db_manager.has_encryption- ), 400- except Exception:- logger.exception(f"Registration failed for {username}")- auth_db.rollback()- flash("Registration failed. Please try again.", "error")- return render_template(- "auth/register.html", has_encryption=db_manager.has_encryption- ), 500- finally:- # Note: In success case, we've already committed; in exception case,- # we rollback and close above, but finally ensures close if commit succeeded+ with auth_db_session() as auth_db:try:- auth_db.close()+ new_user = User(username=username)+ auth_db.add(new_user)+ auth_db.commit()+ except IntegrityError:+ # Catch duplicate username specifically (race condition case)+ # This handles the edge case where two requests for the same username+ # pass the user_exists() check simultaneously+ logger.warning(f"Duplicate username attempted: {username}")+ auth_db.rollback()+ flash(+ "Registration failed. Please try a different username.", "error"+ )+ return render_template(+ "auth/register.html", has_encryption=db_manager.has_encryption+ ), 400except Exception:- pass # Already closed in exception handler+ logger.exception(f"Registration failed for {username}")+ auth_db.rollback()+ flash("Registration failed. Please try again.", "error")+ return render_template(+ "auth/register.html", has_encryption=db_manager.has_encryption+ ), 500try:# Create encrypted database for userdiff --git a/src/local_deep_research/web/queue/manager.py b/src/local_deep_research/web/queue/manager.pyindex 536f8ac7bc..9807b326bd 100644--- a/src/local_deep_research/web/queue/manager.py+++ b/src/local_deep_research/web/queue/manager.py@@ -3,7 +3,7 @@from loguru import loggerfrom sqlalchemy import func-from ...database.encrypted_db import db_manager+from ...database.session_context import get_user_db_sessionfrom ...database.models import QueuedResearch, ResearchHistoryfrom .processor_v2 import queue_processor@@ -26,11 +26,7 @@ class QueueManager:Returns:int: Queue position"""- session = db_manager.get_session(username)- if not session:- raise ValueError(f"No database connection for user {username}")-- with session:+ with get_user_db_session(username) as session:# Get the next position in queue for this usermax_position = (session.query(func.max(QueuedResearch.position))@@ -91,11 +87,7 @@ class QueueManager:Returns:int: Current queue position or None if not in queue"""- session = db_manager.get_session(username)- if not session:- return None-- with session:+ with get_user_db_session(username) as session:queued = (session.query(QueuedResearch).filter_by(username=username, research_id=research_id)@@ -129,11 +121,7 @@ class QueueManager:Returns:bool: True if removed, False if not found"""- session = db_manager.get_session(username)- if not session:- return False-- with session:+ with get_user_db_session(username) as session:queued = (session.query(QueuedResearch).filter_by(username=username, research_id=research_id)@@ -167,11 +155,7 @@ class QueueManager:Returns:list: List of queued research info"""- session = db_manager.get_session(username)- if not session:- return []-- with session:+ with get_user_db_session(username) as session:queued_items = (session.query(QueuedResearch).filter_by(username=username)diff --git a/src/local_deep_research/web/routes/research_routes_orm.py b/src/local_deep_research/web/routes/research_routes_orm.pydeleted file mode 100644index f865740b2f..0000000000--- a/src/local_deep_research/web/routes/research_routes_orm.py+++ /dev/null@@ -1,460 +0,0 @@-"""-Research routes using SQLAlchemy ORM instead of raw SQL.-This is a converted version showing how to replace raw SQL with ORM queries.-"""--import json-from datetime import datetime, UTC-from pathlib import Path--from flask import (- Blueprint,- jsonify,- request,-)-from loguru import logger--from ...config.paths import get_research_outputs_directory-from ...constants import ResearchStatus-from ...database.models import ResearchHistory-from ...database.session_context import get_user_db_session-from ...security import filter_research_metadata, strip_settings_snapshot-from ...security.decorators import require_json_body-from ..auth.decorators import login_required-from ..models.database import calculate_duration-from .globals import (- append_research_log,- cleanup_research,- get_active_research_count,- get_research_field,- is_research_active,- is_research_thread_alive,- iter_active_research,- set_termination_flag,-)--# Create a Blueprint for the research application-research_bp = Blueprint("research", __name__)--# Output directory for research results-OUTPUT_DIR = get_research_outputs_directory()---# Example conversions from the original file:---def check_research_status_orm(research_id):- """- Check research status using ORM instead of raw SQL.-- Original SQL:- SELECT status FROM research_history WHERE id = ?- """- with get_user_db_session() as db_session:- research = (- db_session.query(ResearchHistory).filter_by(id=research_id).first()- )- return research.status if research else None---def update_research_status_orm(research_id, new_status):- """- Update research status using ORM.-- Original SQL:- UPDATE research_history SET status = ? WHERE id = ?- """- with get_user_db_session() as db_session:- research = (- db_session.query(ResearchHistory).filter_by(id=research_id).first()- )- if research:- research.status = new_status- db_session.commit()- return True- return False---def update_progress_log_orm(research_id, progress_log):- """- Update progress log using ORM.-- Original SQL:- UPDATE research_history SET progress_log = ? WHERE id = ?- """- with get_user_db_session() as db_session:- research = (- db_session.query(ResearchHistory).filter_by(id=research_id).first()- )- if research:- research.progress_log = progress_log- db_session.commit()- return True- return False---@research_bp.route("/api/start_research", methods=["POST"])-@login_required-@require_json_body(error_format="status")-def start_research():- """Start research with ORM operations."""- data = request.json- query = data.get("query")- mode = data.get("mode", "quick")-- # ... validation code ...-- # Check if there's any active research that's actually still running- if get_active_research_count() > 0:- # Verify each active research is still valid- stale_research_ids = []- with get_user_db_session() as db_session:- for research_id, research_data in iter_active_research():- # Check database status using ORM- research = (- db_session.query(ResearchHistory)- .filter_by(id=research_id)- .first()- )-- # If the research doesn't exist in DB or is not in_progress, it's stale- if (- not research- or research.status != ResearchStatus.IN_PROGRESS- or not is_research_thread_alive(research_id)- ):- stale_research_ids.append(research_id)-- # Clean up any stale research processes- for stale_id in stale_research_ids:- logger.info(f"Cleaning up stale research process: {stale_id}")- cleanup_research(stale_id)-- # Create a record in the database with ORM- created_at = datetime.now(UTC).isoformat()-- # Save research settings in the metadata field- research_settings = {- "model_provider": data.get("model_provider", "OLLAMA"),- "model": data.get("model"),- # ... other settings ...- }-- with get_user_db_session() as db_session:- research = ResearchHistory(- query=query,- mode=mode,- status=ResearchStatus.IN_PROGRESS,- created_at=created_at,- progress_log=[{"time": created_at, "progress": 0}],- research_meta=research_settings,- )- db_session.add(research)- db_session.commit()- research_id = research.id-- # Start the research process- # ... rest of the function ...-- return jsonify({"status": "success", "research_id": research_id})---@research_bp.route("/api/terminate/<string:research_id>", methods=["POST"])-@login_required-def terminate_research(research_id):- """Terminate research using ORM."""- try:- with get_user_db_session() as db_session:- # Check if the research exists and is in progress- research = (- db_session.query(ResearchHistory)- .filter_by(id=research_id)- .first()- )-- if not research:- return jsonify(- {"status": "error", "message": "Research not found"}- ), 404-- # If it's not in progress, return an error- if research.status != ResearchStatus.IN_PROGRESS:- return (- jsonify(- {- "status": "error",- "message": "Research is not in progress",- }- ),- 400,- )-- # Check if it's in the active_research dict- if not is_research_active(research_id):- # Update the status in the database- research.status = ResearchStatus.SUSPENDED- db_session.commit()- return jsonify(- {"status": "success", "message": "Research terminated"}- )-- # Set the termination flag- set_termination_flag(research_id)-- # Log the termination request- timestamp = datetime.now(UTC).isoformat()- termination_message = "Research termination requested by user"- current_progress = get_research_field(research_id, "progress", 0)-- # Create log entry- log_entry = {- "time": timestamp,- "message": termination_message,- "progress": current_progress,- "metadata": {"phase": "termination"},- }-- # Add to in-memory log- append_research_log(research_id, log_entry)-- # Update the log in the database- if research.progress_log:- try:- current_log = research.progress_log- if isinstance(current_log, str):- current_log = json.loads(current_log)- except Exception:- current_log = []- else:- current_log = []-- current_log.append(log_entry)- research.progress_log = current_log- research.status = ResearchStatus.SUSPENDED- db_session.commit()-- logger.log("MILESTONE", f"Research ended: {termination_message}")-- return jsonify({"status": "success", "message": "Research terminated"})-- finally:- db_session.close()---@research_bp.route("/api/delete/<string:research_id>", methods=["DELETE"])-@login_required-def delete_research(research_id):- """Delete research using ORM."""- db_session = get_user_db_session()-- try:- # Get the research record- research = (- db_session.query(ResearchHistory).filter_by(id=research_id).first()- )-- if not research:- return jsonify(- {"status": "error", "message": "Research not found"}- ), 404-- # Get report path before deletion- report_path = research.report_path-- # Delete from database- db_session.delete(research)- db_session.commit()-- # Delete report file if exists- if report_path and Path(report_path).exists():- try:- Path(report_path).unlink()- logger.info(f"Deleted report file: {report_path}")- except Exception:- logger.exception("Failed to delete report file")-- return jsonify(- {"status": "success", "message": "Research deleted successfully"}- )-- except Exception:- db_session.rollback()- logger.exception("Error deleting research")- return jsonify(- {- "status": "error",- "message": "An internal error occurred while deleting the research.",- }- ), 500- finally:- db_session.close()---@research_bp.route("/api/clear_history", methods=["POST"])-@login_required-def clear_history():- """Clear history using ORM."""- db_session = get_user_db_session()-- try:- # Get all research records- all_research = db_session.query(ResearchHistory).all()-- # Delete report files- deleted_files = 0- for research in all_research:- if research.report_path and Path(research.report_path).exists():- try:- Path(research.report_path).unlink()- deleted_files += 1- except Exception:- logger.exception(- f"Failed to delete file {research.report_path}"- )-- # Delete all records- deleted_count = db_session.query(ResearchHistory).delete()- db_session.commit()-- logger.info(- f"Cleared history: {deleted_count} records, {deleted_files} files"- )-- return jsonify(- {- "status": "success",- "message": f"Deleted {deleted_count} research records and {deleted_files} report files",- }- )-- except Exception:- db_session.rollback()- logger.exception("Error clearing history")- return jsonify(- {- "status": "error",- "message": "An internal error occurred while clearing the history.",- }- ), 500- finally:- db_session.close()---@research_bp.route("/api/history", methods=["GET"])-@login_required-def api_get_history():- """Get history using ORM with pagination."""- page = max(1, request.args.get("page", 1, type=int))- per_page = request.args.get("per_page", 50, type=int)- per_page = max(1, min(per_page, 500))-- db_session = get_user_db_session()-- try:- # Query with pagination- query = db_session.query(ResearchHistory).order_by(- ResearchHistory.created_at.desc()- )-- # Get total count- total = query.count()-- # Get paginated results- research_items = (- query.offset((page - 1) * per_page).limit(per_page).all()- )-- # Convert to dictionaries- history_data = []- for item in research_items:- data = {- "id": item.id,- "query": item.query,- "mode": item.mode,- "status": item.status,- "created_at": item.created_at,- "completed_at": item.completed_at,- "duration_seconds": item.duration_seconds,- "metadata": filter_research_metadata(item.research_meta),- "progress": item.progress,- "title": item.title,- }-- # Calculate duration if not set- if not data["duration_seconds"] and data["created_at"]:- data["duration_seconds"] = calculate_duration(- data["created_at"], data["completed_at"]- )-- history_data.append(data)-- return jsonify(- {- "history": history_data,- "total": total,- "page": page,- "per_page": per_page,- "total_pages": (total + per_page - 1) // per_page,- }- )-- except Exception:- logger.exception("Error fetching history")- return jsonify(- {- "status": "error",- "message": "An internal error occurred while fetching the history.",- }- ), 500- finally:- db_session.close()---@research_bp.route("/api/research/<string:research_id>")-@login_required-def api_get_research(research_id):- """Get research details using ORM."""- try:- with get_user_db_session() as db_session:- research = (- db_session.query(ResearchHistory)- .filter_by(id=research_id)- .first()- )-- if not research:- return jsonify(- {"status": "error", "message": "Research not found"}- ), 404-- # Convert to dictionary- data = {- "id": research.id,- "query": research.query,- "mode": research.mode,- "status": research.status,- "created_at": research.created_at,- "completed_at": research.completed_at,- "duration_seconds": research.duration_seconds,- "metadata": strip_settings_snapshot(research.research_meta),- "progress": research.progress,- "title": research.title,- }-- # Add logs if available- if is_research_active(research_id):- data["logs"] = get_research_field(research_id, "log", [])-- return jsonify(data)-- except Exception:- logger.exception("Error fetching research")- return jsonify(- {- "status": "error",- "message": "An internal error occurred while fetching the research.",- }- ), 500---# Add more converted routes as needed...diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex 12bfca117b..1c6628a6cb 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -609,28 +609,22 @@ def reset_to_defaults():"""Reset all settings to their default values"""username = session["username"]- with get_user_db_session(username) as db_session:- # Import default settings from files- try:- # Create settings manager with proper session context- username = session["username"]- with get_user_db_session(username) as db_session:- settings_mgr = SettingsManager(db_session)- # Import settings from default files- settings_mgr.load_from_defaults_file()+ try:+ with get_user_db_session(username) as db_session:+ settings_mgr = SettingsManager(db_session)+ settings_mgr.load_from_defaults_file()- logger.info("Successfully imported settings from default files")+ logger.info("Successfully imported settings from default files")- except Exception:- logger.exception("Error importing default settings")+ except Exception:+ logger.exception("Error importing default settings")- # Return success- return jsonify(- {- "status": "success",- "message": "All settings have been reset to default values",- }- )+ return jsonify(+ {+ "status": "success",+ "message": "All settings have been reset to default values",+ }+ )@settings_bp.route("/save_settings", methods=["POST"])diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 4943b28174..ccac402336 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -138,36 +138,33 @@ def save_research_strategy(research_id, strategy_name, username=None):f"save_research_strategy called with research_id={research_id}, strategy_name={strategy_name}")with get_user_db_session(username) as session:- try:- # Check if a strategy already exists for this research- existing_strategy = (- session.query(ResearchStrategy)- .filter_by(research_id=research_id)- .first()- )-- if existing_strategy:- # Update existing strategy- existing_strategy.strategy_name = strategy_name- logger.debug(- f"Updating existing strategy for research {research_id}"- )- else:- # Create new strategy record- new_strategy = ResearchStrategy(- research_id=research_id, strategy_name=strategy_name- )- session.add(new_strategy)- logger.debug(- f"Creating new strategy record for research {research_id}"- )+ # Check if a strategy already exists for this research+ existing_strategy = (+ session.query(ResearchStrategy)+ .filter_by(research_id=research_id)+ .first()+ )- session.commit()- logger.info(- f"Saved strategy '{strategy_name}' for research {research_id}"+ if existing_strategy:+ # Update existing strategy+ existing_strategy.strategy_name = strategy_name+ logger.debug(+ f"Updating existing strategy for research {research_id}")- finally:- session.close()+ else:+ # Create new strategy record+ new_strategy = ResearchStrategy(+ research_id=research_id, strategy_name=strategy_name+ )+ session.add(new_strategy)+ logger.debug(+ f"Creating new strategy record for research {research_id}"+ )++ session.commit()+ logger.info(+ f"Saved strategy '{strategy_name}' for research {research_id}"+ )except Exception:logger.exception("Error saving research strategy")@@ -185,16 +182,13 @@ def get_research_strategy(research_id, username=None):"""try:with get_user_db_session(username) as session:- try:- strategy = (- session.query(ResearchStrategy)- .filter_by(research_id=research_id)- .first()- )+ strategy = (+ session.query(ResearchStrategy)+ .filter_by(research_id=research_id)+ .first()+ )- return strategy.strategy_name if strategy else None- finally:- session.close()+ return strategy.strategy_name if strategy else Noneexcept Exception:logger.exception("Error getting research strategy")return Nonediff --git a/tests/security/test_pagination_bounds.py b/tests/security/test_pagination_bounds.pyindex ee0ce146a3..0f1ae5c0b7 100644--- a/tests/security/test_pagination_bounds.py+++ b/tests/security/test_pagination_bounds.py@@ -32,37 +32,6 @@ class TestHistoryRoutesPagination:assert "max(0, offset)" in source or "max(0,offset)" in source-class TestResearchRoutesPagination:- """Verify api_get_history enforces page/per_page bounds."""-- def test_source_clamps_per_page_to_500(self):- """per_page should be clamped to max 500."""- from local_deep_research.web.routes.research_routes_orm import (- api_get_history,- )-- source = inspect.getsource(api_get_history)- assert "min(per_page, 500)" in source or "min(per_page,500)" in source-- def test_source_clamps_page_min_1(self):- """page should be clamped to min 1."""- from local_deep_research.web.routes.research_routes_orm import (- api_get_history,- )-- source = inspect.getsource(api_get_history)- assert "max(1," in source-- def test_source_clamps_per_page_min_1(self):- """per_page should be clamped to min 1."""- from local_deep_research.web.routes.research_routes_orm import (- api_get_history,- )-- source = inspect.getsource(api_get_history)- assert "max(1, min(per_page" in source--class TestContextOverflowCap:"""Verify time series query has a limit cap."""diff --git a/tests/web/queue/test_queue_manager.py b/tests/web/queue/test_queue_manager.pyindex 797bad323f..c4e4c84db5 100644--- a/tests/web/queue/test_queue_manager.py+++ b/tests/web/queue/test_queue_manager.py@@ -8,8 +8,34 @@ Tests cover:- QueueManager.get_user_queue"""+from contextlib import contextmanagerfrom unittest.mock import MagicMock, patch+import pytest++from local_deep_research.database.session_context import DatabaseSessionError+++def _mock_user_db_session(mock_session):+ """Create a mock context manager that yields the given session."""++ @contextmanager+ def _ctx(username=None, password=None):+ yield mock_session++ return _ctx+++def _mock_user_db_session_error():+ """Create a mock context manager that raises DatabaseSessionError."""++ @contextmanager+ def _ctx(username=None, password=None):+ raise DatabaseSessionError("No database connection")+ yield # noqa: unreachable — needed for generator syntax++ return _ctx+class TestQueueManagerAddToQueue:"""Tests for QueueManager.add_to_queue method."""@@ -24,10 +50,9 @@ class TestQueueManagerAddToQueue:mock_session.query.return_value = mock_querywith patch(- "local_deep_research.web.queue.manager.db_manager"- ) as mock_db_manager:- mock_db_manager.get_session.return_value = mock_session-+ "local_deep_research.web.queue.manager.get_user_db_session",+ _mock_user_db_session(mock_session),+ ):with patch("local_deep_research.web.queue.manager.queue_processor") as mock_processor:@@ -51,15 +76,14 @@ class TestQueueManagerAddToQueue:)def test_add_to_queue_no_connection(self):- """Test add_to_queue raises error when no connection."""+ """Test add_to_queue raises DatabaseSessionError when no connection."""with patch(- "local_deep_research.web.queue.manager.db_manager"- ) as mock_db_manager:- mock_db_manager.get_session.return_value = None-+ "local_deep_research.web.queue.manager.get_user_db_session",+ _mock_user_db_session_error(),+ ):from local_deep_research.web.queue.manager import QueueManager- try:+ with pytest.raises(DatabaseSessionError):QueueManager.add_to_queue(username="testuser",research_id="test-id-123",@@ -67,9 +91,6 @@ class TestQueueManagerAddToQueue:mode="detailed",settings={},)- assert False, "Should have raised ValueError"- except ValueError as e:- assert "No database connection" in str(e)def test_add_to_queue_with_existing_items(self):"""Test add_to_queue with existing items in queue."""@@ -81,10 +102,9 @@ class TestQueueManagerAddToQueue:mock_session.query.return_value = mock_querywith patch(- "local_deep_research.web.queue.manager.db_manager"- ) as mock_db_manager:- mock_db_manager.get_session.return_value = mock_session-+ "local_deep_research.web.queue.manager.get_user_db_session",+ _mock_user_db_session(mock_session),+ ):with patch("local_deep_research.web.queue.manager.queue_processor"):from local_deep_research.web.queue.manager import (QueueManager,@@ -123,10 +143,9 @@ class TestQueueManagerGetQueuePosition:mock_session.query.return_value = mock_querywith patch(- "local_deep_research.web.queue.manager.db_manager"- ) as mock_db_manager:- mock_db_manager.get_session.return_value = mock_session-+ "local_deep_research.web.queue.manager.get_user_db_session",+ _mock_user_db_session(mock_session),+ ):from local_deep_research.web.queue.manager import QueueManagerresult = QueueManager.get_queue_position(@@ -145,10 +164,9 @@ class TestQueueManagerGetQueuePosition:mock_session.query.return_value = mock_querywith patch(- "local_deep_research.web.queue.manager.db_manager"- ) as mock_db_manager:- mock_db_manager.get_session.return_value = mock_session-+ "local_deep_research.web.queue.manager.get_user_db_session",+ _mock_user_db_session(mock_session),+ ):from local_deep_research.web.queue.manager import QueueManagerresult = QueueManager.get_queue_position(@@ -158,19 +176,17 @@ class TestQueueManagerGetQueuePosition:assert result is Nonedef test_get_queue_position_no_connection(self):- """Test get_queue_position returns None when no connection."""+ """Test get_queue_position raises DatabaseSessionError when no connection."""with patch(- "local_deep_research.web.queue.manager.db_manager"- ) as mock_db_manager:- mock_db_manager.get_session.return_value = None-+ "local_deep_research.web.queue.manager.get_user_db_session",+ _mock_user_db_session_error(),+ ):from local_deep_research.web.queue.manager import QueueManager- result = QueueManager.get_queue_position(- username="testuser", research_id="test-id-123"- )-- assert result is None+ with pytest.raises(DatabaseSessionError):+ QueueManager.get_queue_position(+ username="testuser", research_id="test-id-123"+ )class TestQueueManagerRemoveFromQueue:@@ -190,10 +206,9 @@ class TestQueueManagerRemoveFromQueue:mock_session.query.return_value = mock_querywith patch(- "local_deep_research.web.queue.manager.db_manager"- ) as mock_db_manager:- mock_db_manager.get_session.return_value = mock_session-+ "local_deep_research.web.queue.manager.get_user_db_session",+ _mock_user_db_session(mock_session),+ ):from local_deep_research.web.queue.manager import QueueManagerresult = QueueManager.remove_from_queue(@@ -213,10 +228,9 @@ class TestQueueManagerRemoveFromQueue:mock_session.query.return_value = mock_querywith patch(- "local_deep_research.web.queue.manager.db_manager"- ) as mock_db_manager:- mock_db_manager.get_session.return_value = mock_session-+ "local_deep_research.web.queue.manager.get_user_db_session",+ _mock_user_db_session(mock_session),+ ):from local_deep_research.web.queue.manager import QueueManagerresult = QueueManager.remove_from_queue(@@ -226,19 +240,17 @@ class TestQueueManagerRemoveFromQueue:assert result is Falsedef test_remove_from_queue_no_connection(self):- """Test remove_from_queue returns False when no connection."""+ """Test remove_from_queue raises DatabaseSessionError when no connection."""with patch(- "local_deep_research.web.queue.manager.db_manager"- ) as mock_db_manager:- mock_db_manager.get_session.return_value = None-+ "local_deep_research.web.queue.manager.get_user_db_session",+ _mock_user_db_session_error(),+ ):from local_deep_research.web.queue.manager import QueueManager- result = QueueManager.remove_from_queue(- username="testuser", research_id="test-id-123"- )-- assert result is False+ with pytest.raises(DatabaseSessionError):+ QueueManager.remove_from_queue(+ username="testuser", research_id="test-id-123"+ )class TestQueueManagerGetUserQueue:@@ -288,10 +300,9 @@ class TestQueueManagerGetUserQueue:mock_session.query.side_effect = query_side_effectwith patch(- "local_deep_research.web.queue.manager.db_manager"- ) as mock_db_manager:- mock_db_manager.get_session.return_value = mock_session-+ "local_deep_research.web.queue.manager.get_user_db_session",+ _mock_user_db_session(mock_session),+ ):from local_deep_research.web.queue.manager import QueueManagerresult = QueueManager.get_user_queue(username="testuser")@@ -314,10 +325,9 @@ class TestQueueManagerGetUserQueue:mock_session.query.return_value = mock_querywith patch(- "local_deep_research.web.queue.manager.db_manager"- ) as mock_db_manager:- mock_db_manager.get_session.return_value = mock_session-+ "local_deep_research.web.queue.manager.get_user_db_session",+ _mock_user_db_session(mock_session),+ ):from local_deep_research.web.queue.manager import QueueManagerresult = QueueManager.get_user_queue(username="testuser")@@ -325,14 +335,12 @@ class TestQueueManagerGetUserQueue:assert result == []def test_get_user_queue_no_connection(self):- """Test get_user_queue returns empty list when no connection."""+ """Test get_user_queue raises DatabaseSessionError when no connection."""with patch(- "local_deep_research.web.queue.manager.db_manager"- ) as mock_db_manager:- mock_db_manager.get_session.return_value = None-+ "local_deep_research.web.queue.manager.get_user_db_session",+ _mock_user_db_session_error(),+ ):from local_deep_research.web.queue.manager import QueueManager- result = QueueManager.get_user_queue(username="testuser")-- assert result == []+ with pytest.raises(DatabaseSessionError):+ QueueManager.get_user_queue(username="testuser")diff --git a/tests/web/routes/test_research_routes_orm.py b/tests/web/routes/test_research_routes_orm.pydeleted file mode 100644index 988d1a1863..0000000000--- a/tests/web/routes/test_research_routes_orm.py+++ /dev/null@@ -1,858 +0,0 @@-"""-Tests for web/routes/research_routes_orm.py--Tests cover:-- ORM helper functions (check_research_status_orm, update_research_status_orm, update_progress_log_orm)-- Research endpoints (start_research, terminate, delete, clear_history, history, get_research)-"""--from unittest.mock import MagicMock, patch--from flask import Flask---class TestCheckResearchStatusOrm:- """Tests for check_research_status_orm helper function."""-- def test_returns_status_for_existing_research(self):- """Should return status for existing research."""- mock_research = MagicMock()- mock_research.status = "in_progress"-- mock_db_session = MagicMock()- mock_db_session.query.return_value.filter_by.return_value.first.return_value = mock_research-- with patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session:- mock_get_session.return_value.__enter__ = MagicMock(- return_value=mock_db_session- )- mock_get_session.return_value.__exit__ = MagicMock(- return_value=False- )-- from local_deep_research.web.routes.research_routes_orm import (- check_research_status_orm,- )-- result = check_research_status_orm("research_123")- assert result == "in_progress"-- def test_returns_none_for_nonexistent_research(self):- """Should return None for nonexistent research."""- mock_db_session = MagicMock()- mock_db_session.query.return_value.filter_by.return_value.first.return_value = None-- with patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session:- mock_get_session.return_value.__enter__ = MagicMock(- return_value=mock_db_session- )- mock_get_session.return_value.__exit__ = MagicMock(- return_value=False- )-- from local_deep_research.web.routes.research_routes_orm import (- check_research_status_orm,- )-- result = check_research_status_orm("nonexistent_123")- assert result is None---class TestUpdateResearchStatusOrm:- """Tests for update_research_status_orm helper function."""-- def test_returns_true_when_research_updated(self):- """Should return True when research is updated."""- mock_research = MagicMock()- mock_db_session = MagicMock()- mock_db_session.query.return_value.filter_by.return_value.first.return_value = mock_research-- with patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session:- mock_get_session.return_value.__enter__ = MagicMock(- return_value=mock_db_session- )- mock_get_session.return_value.__exit__ = MagicMock(- return_value=False- )-- from local_deep_research.web.routes.research_routes_orm import (- update_research_status_orm,- )-- result = update_research_status_orm("research_123", "completed")- assert result is True- assert mock_research.status == "completed"- mock_db_session.commit.assert_called_once()-- def test_returns_false_when_research_not_found(self):- """Should return False when research is not found."""- mock_db_session = MagicMock()- mock_db_session.query.return_value.filter_by.return_value.first.return_value = None-- with patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session:- mock_get_session.return_value.__enter__ = MagicMock(- return_value=mock_db_session- )- mock_get_session.return_value.__exit__ = MagicMock(- return_value=False- )-- from local_deep_research.web.routes.research_routes_orm import (- update_research_status_orm,- )-- result = update_research_status_orm("nonexistent_123", "completed")- assert result is False- mock_db_session.commit.assert_not_called()---class TestUpdateProgressLogOrm:- """Tests for update_progress_log_orm helper function."""-- def test_returns_true_when_progress_log_updated(self):- """Should return True when progress log is updated."""- mock_research = MagicMock()- mock_db_session = MagicMock()- mock_db_session.query.return_value.filter_by.return_value.first.return_value = mock_research-- new_log = [{"time": "2024-01-01", "progress": 50}]-- with patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session:- mock_get_session.return_value.__enter__ = MagicMock(- return_value=mock_db_session- )- mock_get_session.return_value.__exit__ = MagicMock(- return_value=False- )-- from local_deep_research.web.routes.research_routes_orm import (- update_progress_log_orm,- )-- result = update_progress_log_orm("research_123", new_log)- assert result is True- assert mock_research.progress_log == new_log- mock_db_session.commit.assert_called_once()-- def test_returns_false_when_research_not_found(self):- """Should return False when research is not found."""- mock_db_session = MagicMock()- mock_db_session.query.return_value.filter_by.return_value.first.return_value = None-- with patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session:- mock_get_session.return_value.__enter__ = MagicMock(- return_value=mock_db_session- )- mock_get_session.return_value.__exit__ = MagicMock(- return_value=False- )-- from local_deep_research.web.routes.research_routes_orm import (- update_progress_log_orm,- )-- result = update_progress_log_orm("nonexistent_123", [])- assert result is False---class TestTerminateResearchEndpoint:- """Tests for /api/terminate/<research_id> endpoint."""-- def test_returns_404_for_nonexistent_research(self):- """Should return 404 when research doesn't exist."""- app = Flask(__name__)- app.secret_key = "test"- app.config["WTF_CSRF_ENABLED"] = False-- mock_db_session = MagicMock()- mock_db_session.query.return_value.filter_by.return_value.first.return_value = None-- with (- patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session,- patch(- "local_deep_research.web.auth.decorators.db_manager"- ) as mock_db_manager,- ):- mock_get_session.return_value.__enter__ = MagicMock(- return_value=mock_db_session- )- mock_get_session.return_value.__exit__ = MagicMock(- return_value=False- )- mock_db_manager.connections.get.return_value = MagicMock()-- from local_deep_research.web.routes.research_routes_orm import (- research_bp,- )-- app.register_blueprint(research_bp)-- with app.test_client() as client:- with client.session_transaction() as sess:- sess["username"] = "testuser"-- response = client.post("/api/terminate/nonexistent_123")- assert response.status_code == 404- assert response.json["status"] == "error"- assert "not found" in response.json["message"]-- def test_returns_400_for_non_in_progress_research(self):- """Should return 400 when research is not in progress."""- app = Flask(__name__)- app.secret_key = "test"- app.config["WTF_CSRF_ENABLED"] = False-- mock_research = MagicMock()- mock_research.status = "completed"-- mock_db_session = MagicMock()- mock_db_session.query.return_value.filter_by.return_value.first.return_value = mock_research-- with (- patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session,- patch(- "local_deep_research.web.auth.decorators.db_manager"- ) as mock_db_manager,- ):- mock_get_session.return_value.__enter__ = MagicMock(- return_value=mock_db_session- )- mock_get_session.return_value.__exit__ = MagicMock(- return_value=False- )- mock_db_manager.connections.get.return_value = MagicMock()-- from local_deep_research.web.routes.research_routes_orm import (- research_bp,- )-- app.register_blueprint(research_bp)-- with app.test_client() as client:- with client.session_transaction() as sess:- sess["username"] = "testuser"-- response = client.post("/api/terminate/research_123")- assert response.status_code == 400- assert "not in progress" in response.json["message"]---class TestDeleteResearchEndpoint:- """Tests for /api/delete/<research_id> endpoint."""-- def test_returns_404_for_nonexistent_research(self):- """Should return 404 when research doesn't exist."""- app = Flask(__name__)- app.secret_key = "test"- app.config["WTF_CSRF_ENABLED"] = False-- mock_db_session = MagicMock()- mock_db_session.query.return_value.filter_by.return_value.first.return_value = None-- with (- patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session,- patch(- "local_deep_research.web.auth.decorators.db_manager"- ) as mock_db_manager,- ):- mock_get_session.return_value = mock_db_session- mock_db_manager.connections.get.return_value = MagicMock()-- from local_deep_research.web.routes.research_routes_orm import (- research_bp,- )-- app.register_blueprint(research_bp)-- with app.test_client() as client:- with client.session_transaction() as sess:- sess["username"] = "testuser"-- response = client.delete("/api/delete/nonexistent_123")- assert response.status_code == 404- assert response.json["status"] == "error"-- def test_deletes_research_and_report_file(self):- """Should delete research and associated report file."""- app = Flask(__name__)- app.secret_key = "test"- app.config["WTF_CSRF_ENABLED"] = False-- mock_research = MagicMock()- mock_research.report_path = "/tmp/report.md"-- mock_db_session = MagicMock()- mock_db_session.query.return_value.filter_by.return_value.first.return_value = mock_research-- with (- patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session,- patch(- "local_deep_research.web.auth.decorators.db_manager"- ) as mock_db_manager,- patch(- "local_deep_research.web.routes.research_routes_orm.Path"- ) as mock_path,- ):- mock_get_session.return_value = mock_db_session- mock_db_manager.connections.get.return_value = MagicMock()- mock_path_instance = MagicMock()- mock_path_instance.exists.return_value = True- mock_path.return_value = mock_path_instance-- from local_deep_research.web.routes.research_routes_orm import (- research_bp,- )-- app.register_blueprint(research_bp)-- with app.test_client() as client:- with client.session_transaction() as sess:- sess["username"] = "testuser"-- response = client.delete("/api/delete/research_123")- assert response.status_code == 200- assert response.json["status"] == "success"- mock_db_session.delete.assert_called_once_with(mock_research)-- def test_handles_exception_returns_500(self):- """Should return 500 on database error."""- app = Flask(__name__)- app.secret_key = "test"- app.config["WTF_CSRF_ENABLED"] = False-- mock_db_session = MagicMock()- mock_db_session.query.side_effect = Exception("Database error")-- with (- patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session,- patch(- "local_deep_research.web.auth.decorators.db_manager"- ) as mock_db_manager,- ):- mock_get_session.return_value = mock_db_session- mock_db_manager.connections.get.return_value = MagicMock()-- from local_deep_research.web.routes.research_routes_orm import (- research_bp,- )-- app.register_blueprint(research_bp)-- with app.test_client() as client:- with client.session_transaction() as sess:- sess["username"] = "testuser"-- response = client.delete("/api/delete/research_123")- assert response.status_code == 500---class TestClearHistoryEndpoint:- """Tests for /api/clear_history endpoint."""-- def test_clears_all_research_records(self):- """Should delete all research records."""- app = Flask(__name__)- app.secret_key = "test"- app.config["WTF_CSRF_ENABLED"] = False-- mock_db_session = MagicMock()- mock_db_session.query.return_value.all.return_value = []- mock_db_session.query.return_value.delete.return_value = 5-- with (- patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session,- patch(- "local_deep_research.web.auth.decorators.db_manager"- ) as mock_db_manager,- ):- mock_get_session.return_value = mock_db_session- mock_db_manager.connections.get.return_value = MagicMock()-- from local_deep_research.web.routes.research_routes_orm import (- research_bp,- )-- app.register_blueprint(research_bp)-- with app.test_client() as client:- with client.session_transaction() as sess:- sess["username"] = "testuser"-- response = client.post("/api/clear_history")- assert response.status_code == 200- assert response.json["status"] == "success"- assert "5" in response.json["message"]-- def test_deletes_report_files(self):- """Should delete associated report files."""- app = Flask(__name__)- app.secret_key = "test"- app.config["WTF_CSRF_ENABLED"] = False-- mock_research = MagicMock()- mock_research.report_path = "/tmp/report.md"-- mock_db_session = MagicMock()- mock_db_session.query.return_value.all.return_value = [mock_research]- mock_db_session.query.return_value.delete.return_value = 1-- with (- patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session,- patch(- "local_deep_research.web.auth.decorators.db_manager"- ) as mock_db_manager,- patch(- "local_deep_research.web.routes.research_routes_orm.Path"- ) as mock_path,- ):- mock_get_session.return_value = mock_db_session- mock_db_manager.connections.get.return_value = MagicMock()- mock_path_instance = MagicMock()- mock_path_instance.exists.return_value = True- mock_path.return_value = mock_path_instance-- from local_deep_research.web.routes.research_routes_orm import (- research_bp,- )-- app.register_blueprint(research_bp)-- with app.test_client() as client:- with client.session_transaction() as sess:- sess["username"] = "testuser"-- response = client.post("/api/clear_history")- assert response.status_code == 200- mock_path_instance.unlink.assert_called_once()-- def test_handles_exception_returns_500(self):- """Should return 500 on database error."""- app = Flask(__name__)- app.secret_key = "test"- app.config["WTF_CSRF_ENABLED"] = False-- mock_db_session = MagicMock()- mock_db_session.query.return_value.all.side_effect = Exception(- "DB error"- )-- with (- patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session,- patch(- "local_deep_research.web.auth.decorators.db_manager"- ) as mock_db_manager,- ):- mock_get_session.return_value = mock_db_session- mock_db_manager.connections.get.return_value = MagicMock()-- from local_deep_research.web.routes.research_routes_orm import (- research_bp,- )-- app.register_blueprint(research_bp)-- with app.test_client() as client:- with client.session_transaction() as sess:- sess["username"] = "testuser"-- response = client.post("/api/clear_history")- assert response.status_code == 500---class TestHistoryEndpoint:- """Tests for /api/history endpoint."""-- def test_returns_paginated_history(self):- """Should return paginated history."""- app = Flask(__name__)- app.secret_key = "test"- app.config["WTF_CSRF_ENABLED"] = False-- mock_research = MagicMock()- mock_research.id = "research_123"- mock_research.query = "test query"- mock_research.mode = "quick"- mock_research.status = "completed"- mock_research.created_at = "2024-01-01T00:00:00"- mock_research.completed_at = "2024-01-01T01:00:00"- mock_research.duration_seconds = 3600- mock_research.report_path = "/tmp/report.md"- mock_research.research_meta = {}- mock_research.progress = 100- mock_research.title = "Test Research"-- mock_query = MagicMock()- mock_query.count.return_value = 1- mock_query.offset.return_value.limit.return_value.all.return_value = [- mock_research- ]-- mock_db_session = MagicMock()- mock_db_session.query.return_value.order_by.return_value = mock_query-- with (- patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session,- patch(- "local_deep_research.web.auth.decorators.db_manager"- ) as mock_db_manager,- ):- mock_get_session.return_value = mock_db_session- mock_db_manager.connections.get.return_value = MagicMock()-- from local_deep_research.web.routes.research_routes_orm import (- research_bp,- )-- app.register_blueprint(research_bp)-- with app.test_client() as client:- with client.session_transaction() as sess:- sess["username"] = "testuser"-- response = client.get("/api/history")- assert response.status_code == 200- assert "history" in response.json- assert "total" in response.json- assert "page" in response.json- assert "per_page" in response.json- assert "total_pages" in response.json-- def test_uses_default_pagination_values(self):- """Should use default pagination values."""- app = Flask(__name__)- app.secret_key = "test"- app.config["WTF_CSRF_ENABLED"] = False-- mock_query = MagicMock()- mock_query.count.return_value = 0- mock_query.offset.return_value.limit.return_value.all.return_value = []-- mock_db_session = MagicMock()- mock_db_session.query.return_value.order_by.return_value = mock_query-- with (- patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session,- patch(- "local_deep_research.web.auth.decorators.db_manager"- ) as mock_db_manager,- ):- mock_get_session.return_value = mock_db_session- mock_db_manager.connections.get.return_value = MagicMock()-- from local_deep_research.web.routes.research_routes_orm import (- research_bp,- )-- app.register_blueprint(research_bp)-- with app.test_client() as client:- with client.session_transaction() as sess:- sess["username"] = "testuser"-- response = client.get("/api/history")- assert response.status_code == 200- assert response.json["page"] == 1- assert response.json["per_page"] == 50-- def test_accepts_pagination_parameters(self):- """Should accept pagination parameters."""- app = Flask(__name__)- app.secret_key = "test"- app.config["WTF_CSRF_ENABLED"] = False-- mock_query = MagicMock()- mock_query.count.return_value = 100- mock_query.offset.return_value.limit.return_value.all.return_value = []-- mock_db_session = MagicMock()- mock_db_session.query.return_value.order_by.return_value = mock_query-- with (- patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session,- patch(- "local_deep_research.web.auth.decorators.db_manager"- ) as mock_db_manager,- ):- mock_get_session.return_value = mock_db_session- mock_db_manager.connections.get.return_value = MagicMock()-- from local_deep_research.web.routes.research_routes_orm import (- research_bp,- )-- app.register_blueprint(research_bp)-- with app.test_client() as client:- with client.session_transaction() as sess:- sess["username"] = "testuser"-- response = client.get("/api/history?page=2&per_page=10")- assert response.status_code == 200- assert response.json["page"] == 2- assert response.json["per_page"] == 10-- def test_handles_exception_returns_500(self):- """Should return 500 on database error."""- app = Flask(__name__)- app.secret_key = "test"- app.config["WTF_CSRF_ENABLED"] = False-- mock_db_session = MagicMock()- mock_db_session.query.side_effect = Exception("Database error")-- with (- patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session,- patch(- "local_deep_research.web.auth.decorators.db_manager"- ) as mock_db_manager,- ):- mock_get_session.return_value = mock_db_session- mock_db_manager.connections.get.return_value = MagicMock()-- from local_deep_research.web.routes.research_routes_orm import (- research_bp,- )-- app.register_blueprint(research_bp)-- with app.test_client() as client:- with client.session_transaction() as sess:- sess["username"] = "testuser"-- response = client.get("/api/history")- assert response.status_code == 500---class TestGetResearchEndpoint:- """Tests for /api/research/<research_id> endpoint."""-- def test_returns_research_details(self):- """Should return research details."""- app = Flask(__name__)- app.secret_key = "test"- app.config["WTF_CSRF_ENABLED"] = False-- mock_research = MagicMock()- mock_research.id = "research_123"- mock_research.query = "test query"- mock_research.mode = "quick"- mock_research.status = "completed"- mock_research.created_at = "2024-01-01T00:00:00"- mock_research.completed_at = "2024-01-01T01:00:00"- mock_research.duration_seconds = 3600- mock_research.report_path = "/tmp/report.md"- mock_research.research_meta = {}- mock_research.progress_log = []- mock_research.progress = 100- mock_research.title = "Test Research"-- mock_db_session = MagicMock()- mock_db_session.query.return_value.filter_by.return_value.first.return_value = mock_research-- with (- patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session,- patch(- "local_deep_research.web.auth.decorators.db_manager"- ) as mock_db_manager,- patch(- "local_deep_research.web.routes.research_routes_orm.is_research_active",- return_value=False,- ),- ):- mock_get_session.return_value.__enter__ = MagicMock(- return_value=mock_db_session- )- mock_get_session.return_value.__exit__ = MagicMock(- return_value=False- )- mock_db_manager.connections.get.return_value = MagicMock()-- from local_deep_research.web.routes.research_routes_orm import (- research_bp,- )-- app.register_blueprint(research_bp)-- with app.test_client() as client:- with client.session_transaction() as sess:- sess["username"] = "testuser"-- response = client.get("/api/research/research_123")- assert response.status_code == 200- assert response.json["id"] == "research_123"- assert response.json["query"] == "test query"-- def test_returns_404_for_nonexistent_research(self):- """Should return 404 when research doesn't exist."""- app = Flask(__name__)- app.secret_key = "test"- app.config["WTF_CSRF_ENABLED"] = False-- mock_db_session = MagicMock()- mock_db_session.query.return_value.filter_by.return_value.first.return_value = None-- with (- patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session,- patch(- "local_deep_research.web.auth.decorators.db_manager"- ) as mock_db_manager,- ):- mock_get_session.return_value.__enter__ = MagicMock(- return_value=mock_db_session- )- mock_get_session.return_value.__exit__ = MagicMock(- return_value=False- )- mock_db_manager.connections.get.return_value = MagicMock()-- from local_deep_research.web.routes.research_routes_orm import (- research_bp,- )-- app.register_blueprint(research_bp)-- with app.test_client() as client:- with client.session_transaction() as sess:- sess["username"] = "testuser"-- response = client.get("/api/research/nonexistent_123")- assert response.status_code == 404-- def test_includes_logs_for_active_research(self):- """Should include logs for active research."""- app = Flask(__name__)- app.secret_key = "test"- app.config["WTF_CSRF_ENABLED"] = False-- mock_research = MagicMock()- mock_research.id = "research_123"- mock_research.query = "test query"- mock_research.mode = "quick"- mock_research.status = "in_progress"- mock_research.created_at = "2024-01-01T00:00:00"- mock_research.completed_at = None- mock_research.duration_seconds = None- mock_research.report_path = None- mock_research.research_meta = {}- mock_research.progress_log = []- mock_research.progress = 50- mock_research.title = "Test Research"-- mock_db_session = MagicMock()- mock_db_session.query.return_value.filter_by.return_value.first.return_value = mock_research-- active_logs = [{"time": "2024-01-01", "message": "Starting"}]-- with (- patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session,- patch(- "local_deep_research.web.auth.decorators.db_manager"- ) as mock_db_manager,- patch(- "local_deep_research.web.routes.research_routes_orm.is_research_active",- return_value=True,- ),- patch(- "local_deep_research.web.routes.research_routes_orm.get_research_field",- return_value=active_logs,- ),- ):- mock_get_session.return_value.__enter__ = MagicMock(- return_value=mock_db_session- )- mock_get_session.return_value.__exit__ = MagicMock(- return_value=False- )- mock_db_manager.connections.get.return_value = MagicMock()-- from local_deep_research.web.routes.research_routes_orm import (- research_bp,- )-- app.register_blueprint(research_bp)-- with app.test_client() as client:- with client.session_transaction() as sess:- sess["username"] = "testuser"-- response = client.get("/api/research/research_123")- assert response.status_code == 200- assert "logs" in response.json- assert response.json["logs"] == active_logs-- def test_handles_exception_returns_500(self):- """Should return 500 on database error."""- app = Flask(__name__)- app.secret_key = "test"- app.config["WTF_CSRF_ENABLED"] = False-- with (- patch(- "local_deep_research.web.routes.research_routes_orm.get_user_db_session"- ) as mock_get_session,- patch(- "local_deep_research.web.auth.decorators.db_manager"- ) as mock_db_manager,- ):- mock_get_session.return_value.__enter__ = MagicMock(- side_effect=Exception("DB error")- )- mock_get_session.return_value.__exit__ = MagicMock(- return_value=False- )- mock_db_manager.connections.get.return_value = MagicMock()-- from local_deep_research.web.routes.research_routes_orm import (- research_bp,- )-- app.register_blueprint(research_bp)-- with app.test_client() as client:- with client.session_transaction() as sess:- sess["username"] = "testuser"-- response = client.get("/api/research/research_123")- assert response.status_code == 500