~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
Add comprehensive strategy monitoring system (#434)
LearningCircuitfcc565154c72
diff --git a/src/local_deep_research/web/database/models.py b/src/local_deep_research/web/database/models.pyindex 9b2d56a0c4..505803551d 100644--- a/src/local_deep_research/web/database/models.py+++ b/src/local_deep_research/web/database/models.py@@ -145,6 +145,26 @@ class Setting(Base):__table_args__ = (UniqueConstraint("key", name="uix_settings_key"),)+class ResearchStrategy(Base):+ """Database model for tracking research strategies used"""++ __tablename__ = "research_strategies"++ id = Column(Integer, primary_key=True, index=True)+ research_id = Column(+ Integer,+ ForeignKey("research.id", ondelete="CASCADE"),+ nullable=False,+ unique=True,+ index=True,+ )+ strategy_name = Column(String(100), nullable=False, index=True)+ created_at = Column(DateTime, server_default=func.now(), nullable=False)++ # Relationship+ research = relationship("Research", backref="strategy")++class Journal(Base):"""Database model for storing information about academic journals.diff --git a/src/local_deep_research/web/database/schema_upgrade.py b/src/local_deep_research/web/database/schema_upgrade.pyindex 0d7def1f57..09a7f35a24 100644--- a/src/local_deep_research/web/database/schema_upgrade.py+++ b/src/local_deep_research/web/database/schema_upgrade.py@@ -4,10 +4,10 @@ Handles schema upgrades for existing ldr.db databases."""import os-import sqlite3import sysfrom loguru import logger+from sqlalchemy import create_engine, inspect# Add the parent directory to sys.path to allow relative importssys.path.append(@@ -24,51 +24,66 @@ except ImportError:)DB_PATH = os.path.join(project_root, "src", "data", "ldr.db")+from .models import Base, ResearchStrategy-def check_table_exists(conn, table_name):++def remove_research_log_table(engine):"""- Check if a table exists in the database+ Remove the redundant research_log table if it existsArgs:- conn: SQLite connection- table_name: Name of the table+ engine: SQLAlchemy engineReturns:- bool: True if table exists, False otherwise+ bool: True if operation was successful, False otherwise"""- cursor = conn.cursor()- cursor.execute(- "SELECT name FROM sqlite_master WHERE type='table' AND name=?",- (table_name,),- )- return cursor.fetchone() is not None+ try:+ inspector = inspect(engine)++ # Check if table exists+ if inspector.has_table("research_log"):+ # For SQLite, we need to use raw SQL for DROP TABLE+ with engine.connect() as conn:+ conn.execute("DROP TABLE research_log")+ conn.commit()+ logger.info("Successfully removed redundant 'research_log' table")+ return True+ else:+ logger.info("Table 'research_log' does not exist, no action needed")+ return True+ except Exception:+ logger.exception("Error removing research_log table")+ return False-def remove_research_log_table(conn):+def create_research_strategy_table(engine):"""- Remove the redundant research_log table if it exists+ Create the research_strategies table if it doesn't existArgs:- conn: SQLite connection+ engine: SQLAlchemy engineReturns:bool: True if operation was successful, False otherwise"""try:- cursor = conn.cursor()+ inspector = inspect(engine)# Check if table exists- if check_table_exists(conn, "research_log"):- # For SQLite, DROP TABLE is the way to remove a table- cursor.execute("DROP TABLE research_log")- conn.commit()- logger.info("Successfully removed redundant 'research_log' table")+ if not inspector.has_table("research_strategies"):+ # Create the table using ORM+ Base.metadata.create_all(+ engine, tables=[ResearchStrategy.__table__]+ )+ logger.info("Successfully created 'research_strategies' table")return Trueelse:- logger.info("Table 'research_log' does not exist, no action needed")+ logger.info(+ "Table 'research_strategies' already exists, no action needed"+ )return Trueexcept Exception:- logger.exception("Error removing research_log table")+ logger.exception("Error creating research_strategies table")return False@@ -89,14 +104,14 @@ def run_schema_upgrades():logger.info(f"Running schema upgrades on {DB_PATH}")try:- # Connect to the database- conn = sqlite3.connect(DB_PATH)+ # Create SQLAlchemy engine+ engine = create_engine(f"sqlite:///{DB_PATH}")# 1. Remove the redundant research_log table- remove_research_log_table(conn)+ remove_research_log_table(engine)- # Close connection- conn.close()+ # 2. Create research_strategies table+ create_research_strategy_table(engine)logger.info("Schema upgrades completed successfully")return Truediff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.pyindex a039aabe12..7c6269ae0a 100644--- a/src/local_deep_research/web/routes/history_routes.py+++ b/src/local_deep_research/web/routes/history_routes.py@@ -11,6 +11,7 @@ from ..models.database import (get_total_logs_for_research,)from ..routes.globals import get_globals+from ..services.research_service import get_research_strategy# Initialize loggerlogger = logging.getLogger(__name__)@@ -213,6 +214,9 @@ def get_research_details(research_id):# Get logs from the dedicated log databaselogs = get_logs_for_research(research_id)+ # Get strategy information+ strategy_name = get_research_strategy(research_id)+globals_dict = get_globals()active_research = globals_dict["active_research"]@@ -239,6 +243,7 @@ def get_research_details(research_id):"query": result.get("query"),"mode": result.get("mode"),"status": result.get("status"),+ "strategy": strategy_name,"progress": active_research.get(research_id, {}).get("progress", 100 if result.get("status") == "completed" else 0),diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.pyindex 86c9a63a72..18a00c5045 100644--- a/src/local_deep_research/web/routes/metrics_routes.py+++ b/src/local_deep_research/web/routes/metrics_routes.py@@ -11,7 +11,7 @@ from ...metrics.db_models import ResearchRating, TokenUsagefrom ...metrics.query_utils import get_time_filter_conditionfrom ...metrics.search_tracker import get_search_trackerfrom ...utilities.db_utils import get_db_session-from ..database.models import Research+from ..database.models import Research, ResearchStrategyfrom ..utils.templates import render_template_with_defaults# Create a Blueprint for metrics@@ -103,6 +103,199 @@ def get_rating_analytics(period="30d", research_mode="all"):}+def get_available_strategies():+ """Get list of all available search strategies from the search system."""+ # This list comes from the AdvancedSearchSystem.__init__ method+ strategies = [+ {"name": "standard", "description": "Basic iterative search strategy"},+ {+ "name": "iterdrag",+ "description": "Iterative Dense Retrieval Augmented Generation",+ },+ {+ "name": "source-based",+ "description": "Focuses on finding and extracting from sources",+ },+ {+ "name": "parallel",+ "description": "Runs multiple search queries in parallel",+ },+ {"name": "rapid", "description": "Quick single-pass search"},+ {+ "name": "recursive",+ "description": "Recursive decomposition of complex queries",+ },+ {+ "name": "iterative",+ "description": "Loop-based reasoning with persistent knowledge",+ },+ {"name": "adaptive", "description": "Adaptive step-by-step reasoning"},+ {+ "name": "smart",+ "description": "Automatically chooses best strategy based on query",+ },+ {+ "name": "browsecomp",+ "description": "Optimized for BrowseComp-style puzzle queries",+ },+ {+ "name": "evidence",+ "description": "Enhanced evidence-based verification with improved candidate discovery",+ },+ {+ "name": "constrained",+ "description": "Progressive constraint-based search that narrows candidates step by step",+ },+ {+ "name": "parallel-constrained",+ "description": "Parallel constraint-based search with combined constraint execution",+ },+ {+ "name": "early-stop-constrained",+ "description": "Parallel constraint search with immediate evaluation and early stopping at 99% confidence",+ },+ {+ "name": "smart-query",+ "description": "Smart query generation strategy",+ },+ {+ "name": "dual-confidence",+ "description": "Dual confidence scoring with positive/negative/uncertainty",+ },+ {+ "name": "dual-confidence-with-rejection",+ "description": "Dual confidence with early rejection of poor candidates",+ },+ {+ "name": "concurrent-dual-confidence",+ "description": "Concurrent search & evaluation with progressive constraint relaxation",+ },+ {+ "name": "modular",+ "description": "Modular architecture using constraint checking and candidate exploration modules",+ },+ {+ "name": "modular-parallel",+ "description": "Modular strategy with parallel exploration",+ },+ {+ "name": "focused-iteration",+ "description": "Focused iteration strategy optimized for accuracy",+ },+ {+ "name": "browsecomp-entity",+ "description": "Entity-focused search for BrowseComp questions with knowledge graph building",+ },+ ]+ return strategies+++def get_strategy_analytics(period="30d"):+ """Get strategy usage analytics for the specified period."""+ try:+ # Calculate date range+ days_map = {"7d": 7, "30d": 30, "90d": 90, "365d": 365, "all": None}+ days = days_map.get(period, 30)++ session = get_db_session()++ try:+ # Check if we have any ResearchStrategy records+ strategy_count = session.query(ResearchStrategy).count()++ if strategy_count == 0:+ logger.warning("No research strategies found in database")+ return {+ "strategy_analytics": {+ "total_research_with_strategy": 0,+ "total_research": 0,+ "most_popular_strategy": None,+ "strategy_usage": [],+ "strategy_distribution": {},+ "available_strategies": get_available_strategies(),+ "message": "Strategy tracking not yet available - run a research to start tracking",+ }+ }++ # Base query for strategy usage (no JOIN needed since we just want strategy counts)+ query = session.query(+ ResearchStrategy.strategy_name,+ func.count(ResearchStrategy.id).label("usage_count"),+ )++ # Apply time filter if specified+ if days:+ cutoff_date = datetime.now() - timedelta(days=days)+ query = query.filter(ResearchStrategy.created_at >= cutoff_date)++ # Group by strategy and order by usage+ strategy_results = (+ query.group_by(ResearchStrategy.strategy_name)+ .order_by(func.count(ResearchStrategy.id).desc())+ .all()+ )++ # Get total strategy count for percentage calculation+ total_query = session.query(ResearchStrategy)+ if days:+ total_query = total_query.filter(+ ResearchStrategy.created_at >= cutoff_date+ )+ total_research = total_query.count()++ finally:+ session.close()++ # Format strategy data+ strategy_usage = []+ strategy_distribution = {}++ for strategy_name, usage_count in strategy_results:+ percentage = (+ (usage_count / total_research * 100)+ if total_research > 0+ else 0+ )+ strategy_usage.append(+ {+ "strategy": strategy_name,+ "count": usage_count,+ "percentage": round(percentage, 1),+ }+ )+ strategy_distribution[strategy_name] = usage_count++ # Find most popular strategy+ most_popular = strategy_usage[0]["strategy"] if strategy_usage else None++ return {+ "strategy_analytics": {+ "total_research_with_strategy": sum(+ item["count"] for item in strategy_usage+ ),+ "total_research": total_research,+ "most_popular_strategy": most_popular,+ "strategy_usage": strategy_usage,+ "strategy_distribution": strategy_distribution,+ "available_strategies": get_available_strategies(),+ }+ }++ except Exception as e:+ logger.exception(f"Error getting strategy analytics: {e}")+ return {+ "strategy_analytics": {+ "total_research_with_strategy": 0,+ "total_research": 0,+ "most_popular_strategy": None,+ "strategy_usage": [],+ "strategy_distribution": {},+ "available_strategies": get_available_strategies(),+ "error": str(e),+ }+ }++@metrics_bp.route("/")def metrics_dashboard():"""Render the metrics dashboard page."""@@ -159,10 +352,14 @@ def api_metrics():logger.warning(f"Error getting user satisfaction data: {e}")user_satisfaction = {"avg_rating": None, "total_ratings": 0}+ # Get strategy analytics+ strategy_data = get_strategy_analytics(period)+# Combine metricscombined_metrics = {**token_metrics,**search_metrics,+ **strategy_data,"user_satisfaction": user_satisfaction,}diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 4cc0cee6b9..762c82f52f 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -13,7 +13,9 @@ from ...report_generator import IntegratedReportGeneratorfrom ...search_system import AdvancedSearchSystemfrom ...utilities.log_utils import log_for_researchfrom ...utilities.search_utilities import extract_links_from_search_results+from ...utilities.db_utils import get_db_sessionfrom ...utilities.threading_utils import thread_context, thread_with_app_context+from ..database.models import ResearchStrategyfrom ..models.database import calculate_duration, get_db_connectionfrom .socket_service import SocketIOService@@ -22,6 +24,82 @@ _PROJECT_ROOT = Path(__file__).parents[4]OUTPUT_DIR = _PROJECT_ROOT / "research_outputs"+def save_research_strategy(research_id, strategy_name):+ """+ Save the strategy used for a research to the database.++ Args:+ research_id: The ID of the research+ strategy_name: The name of the strategy used+ """+ try:+ logger.debug(+ f"save_research_strategy called with research_id={research_id}, strategy_name={strategy_name}"+ )+ session = get_db_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}"+ )++ session.commit()+ logger.info(+ f"Saved strategy '{strategy_name}' for research {research_id}"+ )+ finally:+ session.close()+ except Exception:+ logger.exception("Error saving research strategy")+++def get_research_strategy(research_id):+ """+ Get the strategy used for a research.++ Args:+ research_id: The ID of the research++ Returns:+ str: The strategy name or None if not found+ """+ try:+ session = get_db_session()++ try:+ strategy = (+ session.query(ResearchStrategy)+ .filter_by(research_id=research_id)+ .first()+ )++ return strategy.strategy_name if strategy else None+ finally:+ session.close()+ except Exception:+ logger.exception("Error getting research strategy")+ return None++def start_research_process(research_id,query,@@ -138,6 +216,13 @@ def run_research_process("strategy", "source-based") # Default to source-based+ # Save the strategy to the database+ logger.debug(+ f"About to call save_research_strategy with research_id={research_id}, strategy={strategy}"+ )+ save_research_strategy(research_id, strategy)+ logger.debug("save_research_strategy call completed")+# Log all parameters for debugginglogger.info("Research parameters: provider=%s, model=%s, search_engine=%s, "diff --git a/src/local_deep_research/web/static/js/components/details.js b/src/local_deep_research/web/static/js/components/details.jsindex b39b41763c..767da8d28e 100644--- a/src/local_deep_research/web/static/js/components/details.js+++ b/src/local_deep_research/web/static/js/components/details.js@@ -43,6 +43,17 @@document.getElementById('details-content').style.display = 'none';document.getElementById('error').style.display = 'none';+ // Load research details (includes strategy)+ console.log('Fetching research details...');+ const detailsResponse = await fetch(`/history/details/${researchId}`);+ console.log('Details response status:', detailsResponse.status);++ let researchDetails = null;+ if (detailsResponse.ok) {+ researchDetails = await detailsResponse.json();+ console.log('Research details loaded:', researchDetails);+ }+// Load research metricsconsole.log('Fetching research metrics...');const metricsResponse = await fetch(`/metrics/api/metrics/research/${researchId}`);@@ -62,6 +73,11 @@metricsData = metricsResult.metrics;console.log('Metrics data loaded:', metricsData);+ // Display research details first+ if (researchDetails) {+ displayResearchDetails(researchDetails);+ }+// Load timeline metricsconsole.log('Fetching timeline metrics...');const timelineResponse = await fetch(`/metrics/api/metrics/research/${researchId}/timeline`);@@ -162,6 +178,40 @@}}+ // Display research details from history endpoint+ function displayResearchDetails(details) {+ console.log('displayResearchDetails called with:', details);++ // Update basic research info+ if (details.query) {+ document.getElementById('research-query').textContent = details.query;+ }+ if (details.mode) {+ document.getElementById('research-mode').textContent = details.mode;+ }+ if (details.created_at) {+ const date = new Date(details.created_at);+ document.getElementById('research-date').textContent = date.toLocaleString();+ }++ // Update strategy information+ if (details.strategy) {+ document.getElementById('research-strategy').textContent = details.strategy;+ } else {+ document.getElementById('research-strategy').textContent = 'Not recorded';+ }++ // Update progress+ if (details.progress !== undefined) {+ const progressFill = document.getElementById('detail-progress-fill');+ const progressText = document.getElementById('detail-progress-percentage');+ if (progressFill && progressText) {+ progressFill.style.width = `${details.progress}%`;+ progressText.textContent = `${details.progress}%`;+ }+ }+ }+// Display basic research metricsfunction displayResearchMetrics() {console.log('displayResearchMetrics called with:', metricsData);@@ -633,7 +683,7 @@const requiredIds = ['loading', 'error', 'details-content', 'total-tokens', 'prompt-tokens','completion-tokens', 'llm-calls', 'avg-response-time', 'model-used',- 'research-query', 'research-mode', 'research-date', 'total-cost',+ 'research-query', 'research-mode', 'research-date', 'research-strategy', 'total-cost','phase-breakdown', 'search-engine-breakdown', 'timeline-chart', 'search-chart'];diff --git a/src/local_deep_research/web/templates/pages/details.html b/src/local_deep_research/web/templates/pages/details.htmlindex 65ad949d14..4dc34f23a8 100644--- a/src/local_deep_research/web/templates/pages/details.html+++ b/src/local_deep_research/web/templates/pages/details.html@@ -212,6 +212,10 @@<span class="metadata-label">Model:</span><span id="model-used" class="metadata-value"></span></div>+ <div class="metadata-item">+ <span class="metadata-label">Strategy:</span>+ <span id="research-strategy" class="metadata-value">-</span>+ </div><div class="metadata-item"><span class="metadata-label">Total Cost:</span><span id="total-cost" class="metadata-value">$0.00</span>diff --git a/src/local_deep_research/web/templates/pages/metrics.html b/src/local_deep_research/web/templates/pages/metrics.htmlindex b13afe1cbb..1abc710767 100644--- a/src/local_deep_research/web/templates/pages/metrics.html+++ b/src/local_deep_research/web/templates/pages/metrics.html@@ -648,6 +648,17 @@</div></div>+ <!-- Strategy Usage -->+ <div>+ <h4 class="tooltip" data-tooltip="Shows which research strategies were used most frequently. Strategies determine how the system approaches and structures research queries.">+ <i class="fas fa-chess"></i> Research Strategies+ <i class="fas fa-info-circle info-icon"></i>+ </h4>+ <div id="strategy-breakdown">+ <!-- Populated dynamically -->+ </div>+ </div>+<!-- Research Phase Analysis --><div><h4><i class="fas fa-project-diagram"></i> Research Phases</h4>@@ -1176,6 +1187,55 @@searchContainer.appendChild(item);});+ // Display strategy breakdown+ const strategyContainer = document.getElementById('strategy-breakdown');+ strategyContainer.innerHTML = '';++ // Get strategy data from metricsData (added by our API)+ const strategyData = metricsData.strategy_analytics;++ // Log strategy data for debugging+ console.log('Strategy data received:', strategyData);++ if (strategyData && strategyData.strategy_usage && strategyData.strategy_usage.length > 0) {+ strategyData.strategy_usage.forEach(strategy => {+ const item = document.createElement('div');+ item.className = 'model-usage-item';+ item.innerHTML = `+ <div class="model-info">+ <div class="model-name">${strategy.strategy}</div>+ <div class="model-provider">${strategy.percentage}% of research sessions</div>+ </div>+ <div class="model-stats">+ <div class="token-count">${formatNumber(strategy.count)} uses</div>+ <div class="call-count">${strategyData.most_popular_strategy === strategy.strategy ? '👑 Most Popular' : ''}</div>+ </div>+ `;+ strategyContainer.appendChild(item);+ });+ } else {+ const noDataMsg = document.createElement('div');+ noDataMsg.style.textAlign = 'center';+ noDataMsg.style.color = 'var(--text-secondary)';+ noDataMsg.style.padding = '1rem';++ let message = 'No strategy data yet. <a href="/research/" style="color: var(--accent-tertiary);">Start a research</a> to track strategies!';++ // Show different message based on what data we have+ if (strategyData) {+ if (strategyData.message) {+ message = strategyData.message;+ } else if (strategyData.total_research > 0 && strategyData.total_research_with_strategy === 0) {+ message = `Found ${strategyData.total_research} research sessions but no strategy data. Strategy tracking was recently added - new research will be tracked!`;+ } else if (strategyData.error) {+ message = `Error loading strategy data: ${strategyData.error}`;+ }+ }++ noDataMsg.innerHTML = message;+ strategyContainer.appendChild(noDataMsg);+ }+// Display phase breakdownconst phaseContainer = document.getElementById('phase-breakdown');phaseContainer.innerHTML = '';diff --git a/tests/run_all_tests.py b/tests/run_all_tests.pyindex 92dc8dfe52..c0b33744f0 100755--- a/tests/run_all_tests.py+++ b/tests/run_all_tests.py@@ -329,6 +329,7 @@ class TestRunner:"tests/test_wikipedia_url_security.py","tests/test_search_engines_enhanced.py","tests/test_utils.py",+ "tests/test_research_strategy_orm.py","tests/feature_tests/","tests/fix_tests/","--cov=src",diff --git a/tests/test_research_strategy_orm.py b/tests/test_research_strategy_orm.pynew file mode 100644index 0000000000..4537c493c0--- /dev/null+++ b/tests/test_research_strategy_orm.py@@ -0,0 +1,224 @@+"""Test the ORM implementation for ResearchStrategy model and related functions."""++import pytest+from sqlalchemy import create_engine, event+from sqlalchemy.orm import sessionmaker++from src.local_deep_research.web.database.models import (+ Base,+ Research,+ ResearchMode,+ ResearchStatus,+ ResearchStrategy,+)+from src.local_deep_research.web.services.research_service import (+ get_research_strategy,+ save_research_strategy,+)+++def test_db():+ """Create a test database for each test."""+ # Create an in-memory SQLite database with foreign key support+ engine = create_engine("sqlite:///:memory:")++ # Enable foreign key constraints for SQLite+ @event.listens_for(engine, "connect")+ def set_sqlite_pragma(dbapi_connection, connection_record):+ cursor = dbapi_connection.cursor()+ cursor.execute("PRAGMA foreign_keys=ON")+ cursor.close()++ Base.metadata.create_all(engine)++ # Create session+ SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)+ session = SessionLocal()++ yield session++ session.close()+++def test_research(test_db):+ """Create a test research record."""+ research = Research(+ query="Test query for strategy",+ status=ResearchStatus.COMPLETED,+ mode=ResearchMode.QUICK,+ )+ test_db.add(research)+ test_db.commit()+ test_db.refresh(research)+ return research+++def test_save_research_strategy(test_research, monkeypatch):+ """Test saving a research strategy."""++ # Mock get_db_session to return our test session+ def mock_get_db_session():+ # Create a new session from the same engine+ engine = test_research._sa_instance_state.session.bind+ SessionLocal = sessionmaker(+ bind=engine, autocommit=False, autoflush=False+ )+ return SessionLocal()++ monkeypatch.setattr(+ "src.local_deep_research.web.services.research_service.get_db_session",+ mock_get_db_session,+ )++ # Test saving a strategy+ strategy_name = "source-based"+ save_research_strategy(test_research.id, strategy_name)++ # Verify the strategy was saved+ session = mock_get_db_session()+ strategy = (+ session.query(ResearchStrategy)+ .filter_by(research_id=test_research.id)+ .first()+ )++ assert strategy is not None+ assert strategy.strategy_name == strategy_name+ assert strategy.research_id == test_research.id++ session.close()+++def test_update_research_strategy(test_research, monkeypatch):+ """Test updating an existing research strategy."""++ # Mock get_db_session+ def mock_get_db_session():+ engine = test_research._sa_instance_state.session.bind+ SessionLocal = sessionmaker(+ bind=engine, autocommit=False, autoflush=False+ )+ return SessionLocal()++ monkeypatch.setattr(+ "src.local_deep_research.web.services.research_service.get_db_session",+ mock_get_db_session,+ )++ # Save initial strategy+ initial_strategy = "source-based"+ save_research_strategy(test_research.id, initial_strategy)++ # Update to a new strategy+ new_strategy = "iterative"+ save_research_strategy(test_research.id, new_strategy)++ # Verify the strategy was updated+ session = mock_get_db_session()+ strategy = (+ session.query(ResearchStrategy)+ .filter_by(research_id=test_research.id)+ .first()+ )++ assert strategy is not None+ assert strategy.strategy_name == new_strategy++ # Ensure there's only one strategy record for this research+ strategy_count = (+ session.query(ResearchStrategy)+ .filter_by(research_id=test_research.id)+ .count()+ )+ assert strategy_count == 1++ session.close()+++def test_get_research_strategy(test_research, monkeypatch):+ """Test retrieving a research strategy."""++ # Mock get_db_session+ def mock_get_db_session():+ engine = test_research._sa_instance_state.session.bind+ SessionLocal = sessionmaker(+ bind=engine, autocommit=False, autoflush=False+ )+ return SessionLocal()++ monkeypatch.setattr(+ "src.local_deep_research.web.services.research_service.get_db_session",+ mock_get_db_session,+ )++ # Test when no strategy exists+ strategy = get_research_strategy(test_research.id)+ assert strategy is None++ # Save a strategy+ strategy_name = "parallel"+ save_research_strategy(test_research.id, strategy_name)++ # Test retrieving the strategy+ strategy = get_research_strategy(test_research.id)+ assert strategy == strategy_name+++def test_get_research_strategy_nonexistent(monkeypatch):+ """Test retrieving a strategy for a non-existent research."""++ # Mock get_db_session+ def mock_get_db_session():+ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ SessionLocal = sessionmaker(+ bind=engine, autocommit=False, autoflush=False+ )+ return SessionLocal()++ monkeypatch.setattr(+ "src.local_deep_research.web.services.research_service.get_db_session",+ mock_get_db_session,+ )++ # Test with non-existent research ID+ strategy = get_research_strategy(99999)+ assert strategy is None+++def test_research_strategy_relationship(test_db, test_research):+ """Test the relationship between Research and ResearchStrategy."""+ # Create a strategy+ strategy = ResearchStrategy(+ research_id=test_research.id, strategy_name="recursive"+ )+ test_db.add(strategy)+ test_db.commit()++ # Verify the relationship works+ # The backref creates a list since it's a one-to-many relationship+ assert len(test_research.strategy) == 1+ assert test_research.strategy[0].strategy_name == "recursive"+ assert strategy.research.query == "Test query for strategy"+++def test_research_strategy_unique_constraint(test_db, test_research):+ """Test that only one strategy can exist per research."""+ # Create first strategy+ strategy1 = ResearchStrategy(+ research_id=test_research.id, strategy_name="standard"+ )+ test_db.add(strategy1)+ test_db.commit()++ # Try to create a second strategy for the same research+ strategy2 = ResearchStrategy(+ research_id=test_research.id, strategy_name="rapid"+ )+ test_db.add(strategy2)++ # Should raise an integrity error due to unique constraint+ with pytest.raises(Exception): # SQLAlchemy will raise IntegrityError+ test_db.commit()