Skip to content

~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.

Add Phase 2 benchmark and notification tests (86+ tests)

LearningCircuit37ed7dda1abc
diff --git a/tests/benchmarks/test_benchmark_service.py b/tests/benchmarks/test_benchmark_service.py
index 419256f0ff..7d8f8c66a0 100644
--- a/tests/benchmarks/test_benchmark_service.py
+++ b/tests/benchmarks/test_benchmark_service.py
@@ -360,3 +360,266 @@ class TestBenchmarkServiceQueueTrackerIntegration:
task = service.queue_tracker.get_task_status("test-task")
assert task is not None
assert task["status"] == BenchmarkTaskStatus.QUEUED.value
+
+
+class TestBenchmarkServiceQueryHash:
+ """Tests for query hash generation."""
+
+ def test_generate_query_hash(self):
+ """Test generating query hash."""
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkService,
+ )
+
+ with patch(
+ "local_deep_research.benchmarks.web_api.benchmark_service.SocketIOService"
+ ) as mock_socket:
+ mock_socket.return_value = Mock()
+ service = BenchmarkService()
+
+ hash1 = service.generate_query_hash("What is AI?", "simpleqa")
+ hash2 = service.generate_query_hash("What is AI?", "simpleqa")
+
+ # Same question and dataset should produce same hash
+ assert hash1 == hash2
+ assert len(hash1) == 32 # MD5 hex digest
+
+ def test_different_questions_different_hashes(self):
+ """Test that different questions produce different hashes."""
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkService,
+ )
+
+ with patch(
+ "local_deep_research.benchmarks.web_api.benchmark_service.SocketIOService"
+ ) as mock_socket:
+ mock_socket.return_value = Mock()
+ service = BenchmarkService()
+
+ hash1 = service.generate_query_hash("Question 1", "simpleqa")
+ hash2 = service.generate_query_hash("Question 2", "simpleqa")
+
+ assert hash1 != hash2
+
+ def test_different_datasets_different_hashes(self):
+ """Test that different datasets produce different hashes."""
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkService,
+ )
+
+ with patch(
+ "local_deep_research.benchmarks.web_api.benchmark_service.SocketIOService"
+ ) as mock_socket:
+ mock_socket.return_value = Mock()
+ service = BenchmarkService()
+
+ hash1 = service.generate_query_hash("Same question", "simpleqa")
+ hash2 = service.generate_query_hash("Same question", "browsecomp")
+
+ assert hash1 != hash2
+
+ def test_query_hash_strips_whitespace(self):
+ """Test that query hash strips whitespace from question."""
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkService,
+ )
+
+ with patch(
+ "local_deep_research.benchmarks.web_api.benchmark_service.SocketIOService"
+ ) as mock_socket:
+ mock_socket.return_value = Mock()
+ service = BenchmarkService()
+
+ hash1 = service.generate_query_hash(" Question ", "simpleqa")
+ hash2 = service.generate_query_hash("Question", "simpleqa")
+
+ assert hash1 == hash2
+
+
+class TestBenchmarkServiceProgressUpdate:
+ """Tests for progress update functionality."""
+
+ def test_send_progress_update(self):
+ """Test sending progress update."""
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkService,
+ )
+
+ mock_socket = Mock()
+ service = BenchmarkService(socket_service=mock_socket)
+
+ service._send_progress_update(
+ benchmark_run_id=1,
+ completed=5,
+ total=10,
+ )
+
+ # Should have called emit_to_subscribers
+ mock_socket.emit_to_subscribers.assert_called_once()
+ call_args = mock_socket.emit_to_subscribers.call_args
+
+ assert call_args[0][0] == "research_progress"
+ assert call_args[0][1] == 1
+
+ def test_send_progress_update_handles_zero_total(self):
+ """Test progress update handles zero total gracefully."""
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkService,
+ )
+
+ mock_socket = Mock()
+ service = BenchmarkService(socket_service=mock_socket)
+
+ # Should not raise division by zero
+ service._send_progress_update(
+ benchmark_run_id=1,
+ completed=0,
+ total=0,
+ )
+
+ mock_socket.emit_to_subscribers.assert_called_once()
+
+
+class TestBenchmarkQueueTrackerCleanup:
+ """Additional tests for queue tracker cleanup."""
+
+ def test_cleanup_failed_tasks(self):
+ """Test cleanup of old failed tasks."""
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkQueueTracker,
+ BenchmarkTaskStatus,
+ )
+
+ tracker = BenchmarkQueueTracker()
+ tracker.add_task("task-failed", "testuser")
+ tracker.update_task_status("task-failed", BenchmarkTaskStatus.FAILED)
+
+ # Set old timestamp
+ tracker.tasks["task-failed"]["updated_at"] = datetime.now(
+ UTC
+ ) - timedelta(hours=2)
+
+ tracker.cleanup_completed_tasks(max_age_seconds=3600)
+
+ # Failed task should be removed
+ assert tracker.get_task_status("task-failed") is None
+
+ def test_cleanup_cancelled_tasks(self):
+ """Test cleanup of old cancelled tasks."""
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkQueueTracker,
+ BenchmarkTaskStatus,
+ )
+
+ tracker = BenchmarkQueueTracker()
+ tracker.add_task("task-cancelled", "testuser")
+ tracker.update_task_status(
+ "task-cancelled", BenchmarkTaskStatus.CANCELLED
+ )
+
+ # Set old timestamp
+ tracker.tasks["task-cancelled"]["updated_at"] = datetime.now(
+ UTC
+ ) - timedelta(hours=2)
+
+ tracker.cleanup_completed_tasks(max_age_seconds=3600)
+
+ # Cancelled task should be removed
+ assert tracker.get_task_status("task-cancelled") is None
+
+ def test_cleanup_skips_queued_tasks(self):
+ """Test that cleanup doesn't remove queued tasks."""
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkQueueTracker,
+ )
+
+ tracker = BenchmarkQueueTracker()
+ tracker.add_task("task-queued", "testuser")
+ # Keep as QUEUED (default)
+
+ # Set old timestamp
+ tracker.tasks["task-queued"]["created_at"] = datetime.now(
+ UTC
+ ) - timedelta(hours=2)
+
+ tracker.cleanup_completed_tasks(max_age_seconds=3600)
+
+ # Queued task should remain
+ assert tracker.get_task_status("task-queued") is not None
+
+ def test_cleanup_uses_created_at_if_no_updated_at(self):
+ """Test that cleanup uses created_at if updated_at is missing."""
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkQueueTracker,
+ BenchmarkTaskStatus,
+ )
+
+ tracker = BenchmarkQueueTracker()
+ tracker.add_task("task-old", "testuser")
+ tracker.update_task_status("task-old", BenchmarkTaskStatus.COMPLETED)
+
+ # Remove updated_at and set old created_at
+ if "updated_at" in tracker.tasks["task-old"]:
+ del tracker.tasks["task-old"]["updated_at"]
+ tracker.tasks["task-old"]["created_at"] = datetime.now(UTC) - timedelta(
+ hours=2
+ )
+
+ tracker.cleanup_completed_tasks(max_age_seconds=3600)
+
+ # Task should be removed based on created_at
+ assert tracker.get_task_status("task-old") is None
+
+
+class TestBenchmarkServiceCancelBenchmark:
+ """Tests for cancel benchmark functionality."""
+
+ def test_cancel_sets_status_cancelled(self):
+ """Test that cancel sets status to cancelled."""
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkService,
+ )
+
+ mock_socket = Mock()
+ service = BenchmarkService(socket_service=mock_socket)
+
+ # Add an active run
+ service.active_runs[1] = {"status": "running"}
+
+ with patch.object(service, "update_benchmark_status"):
+ service.cancel_benchmark(1, username="testuser")
+
+ assert service.active_runs[1]["status"] == "cancelled"
+
+ def test_cancel_returns_true_on_success(self):
+ """Test that cancel returns True on success."""
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkService,
+ )
+
+ mock_socket = Mock()
+ service = BenchmarkService(socket_service=mock_socket)
+
+ service.active_runs[1] = {"status": "running"}
+
+ with patch.object(service, "update_benchmark_status"):
+ result = service.cancel_benchmark(1, username="testuser")
+
+ assert result is True
+
+
+class TestBenchmarkServiceSyncResults:
+ """Tests for sync pending results functionality."""
+
+ def test_sync_pending_results_returns_zero_for_unknown_run(self):
+ """Test that sync returns 0 for unknown benchmark run."""
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkService,
+ )
+
+ mock_socket = Mock()
+ service = BenchmarkService(socket_service=mock_socket)
+
+ result = service.sync_pending_results(99999, username="testuser")
+
+ assert result == 0
diff --git a/tests/benchmarks/test_comparison_evaluator.py b/tests/benchmarks/test_comparison_evaluator.py
new file mode 100644
index 0000000000..28a20b0809
--- /dev/null
+++ b/tests/benchmarks/test_comparison_evaluator.py
@@ -0,0 +1,290 @@
+"""
+Tests for benchmarks/comparison/evaluator.py
+
+Tests cover:
+- compare_configurations function
+- _calculate_average_metrics function
+- _evaluate_single_configuration function structure
+- Visualization creation functions
+"""
+
+from unittest.mock import patch
+import pytest
+
+
+class TestCompareConfigurationsValidation:
+ """Tests for compare_configurations input validation."""
+
+ @patch("local_deep_research.benchmarks.comparison.evaluator.os.makedirs")
+ def test_returns_error_for_empty_configurations(
+ self, mock_makedirs, tmp_path
+ ):
+ """Test that empty configurations list returns error."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ compare_configurations,
+ )
+
+ result = compare_configurations(
+ query="test query",
+ configurations=[],
+ output_dir=str(tmp_path),
+ )
+
+ assert "error" in result
+ assert result["error"] == "No configurations provided"
+
+ @patch("local_deep_research.benchmarks.comparison.evaluator.os.makedirs")
+ def test_creates_output_directory(self, mock_makedirs):
+ """Test that output directory is created."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ compare_configurations,
+ )
+
+ # Empty configs will return early with error but still create dir
+ compare_configurations(
+ query="test",
+ configurations=[],
+ output_dir="/tmp/test_output",
+ )
+
+ mock_makedirs.assert_called_with("/tmp/test_output", exist_ok=True)
+
+
+class TestCalculateAverageMetrics:
+ """Tests for _calculate_average_metrics function."""
+
+ def test_calculates_average_quality_metrics(self):
+ """Test averaging of quality metrics."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ results = [
+ {"quality_metrics": {"accuracy": 0.8, "source_count": 10}},
+ {"quality_metrics": {"accuracy": 0.6, "source_count": 8}},
+ ]
+
+ avg = _calculate_average_metrics(results)
+
+ assert avg["quality_metrics"]["accuracy"] == pytest.approx(0.7)
+ assert avg["quality_metrics"]["source_count"] == pytest.approx(9.0)
+
+ def test_calculates_average_speed_metrics(self):
+ """Test averaging of speed metrics."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ results = [
+ {
+ "speed_metrics": {
+ "total_duration": 100,
+ "duration_per_question": 10,
+ }
+ },
+ {
+ "speed_metrics": {
+ "total_duration": 80,
+ "duration_per_question": 8,
+ }
+ },
+ ]
+
+ avg = _calculate_average_metrics(results)
+
+ assert avg["speed_metrics"]["total_duration"] == pytest.approx(90.0)
+ assert avg["speed_metrics"]["duration_per_question"] == pytest.approx(
+ 9.0
+ )
+
+ def test_calculates_average_resource_metrics(self):
+ """Test averaging of resource metrics."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ results = [
+ {"resource_metrics": {"memory_mb": 100}},
+ {"resource_metrics": {"memory_mb": 200}},
+ ]
+
+ avg = _calculate_average_metrics(results)
+
+ assert avg["resource_metrics"]["memory_mb"] == pytest.approx(150.0)
+
+ def test_handles_empty_results(self):
+ """Test handling of empty results list."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ avg = _calculate_average_metrics([])
+
+ assert avg == {}
+
+ def test_handles_missing_metrics_categories(self):
+ """Test handling of results with missing metric categories."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ results = [
+ {"quality_metrics": {"accuracy": 0.8}},
+ {}, # No metrics
+ ]
+
+ avg = _calculate_average_metrics(results)
+
+ # Should still have quality_metrics
+ assert "quality_metrics" in avg
+ assert avg["quality_metrics"]["accuracy"] == pytest.approx(0.8)
+
+ def test_handles_none_values(self):
+ """Test handling of None values in metrics."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ results = [
+ {"quality_metrics": {"accuracy": 0.8, "optional": None}},
+ {"quality_metrics": {"accuracy": 0.6, "optional": 0.5}},
+ ]
+
+ avg = _calculate_average_metrics(results)
+
+ # None values should be filtered out
+ assert avg["quality_metrics"]["accuracy"] == pytest.approx(0.7)
+ # Optional should only have one valid value
+ assert avg["quality_metrics"]["optional"] == pytest.approx(0.5)
+
+ def test_handles_mixed_metric_keys(self):
+ """Test handling when results have different metric keys."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _calculate_average_metrics,
+ )
+
+ results = [
+ {"quality_metrics": {"metric_a": 0.8}},
+ {"quality_metrics": {"metric_b": 0.6}},
+ ]
+
+ avg = _calculate_average_metrics(results)
+
+ # Both metrics should be present
+ assert avg["quality_metrics"]["metric_a"] == pytest.approx(0.8)
+ assert avg["quality_metrics"]["metric_b"] == pytest.approx(0.6)
+
+
+class TestMetricWeightsDefault:
+ """Tests for default metric weights."""
+
+ @patch("local_deep_research.benchmarks.comparison.evaluator.os.makedirs")
+ def test_default_metric_weights(self, mock_makedirs):
+ """Test that default metric weights are applied."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ compare_configurations,
+ )
+
+ compare_configurations(
+ query="test",
+ configurations=[],
+ output_dir="/tmp/test",
+ )
+
+ # Empty configs returns early, but we can verify the function signature
+ assert callable(compare_configurations)
+
+
+class TestVisualizationFunctions:
+ """Tests for visualization helper functions."""
+
+ def test_create_metric_comparison_chart_exists(self):
+ """Test that _create_metric_comparison_chart function exists."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _create_metric_comparison_chart,
+ )
+
+ assert callable(_create_metric_comparison_chart)
+
+ def test_create_spider_chart_exists(self):
+ """Test that _create_spider_chart function exists."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _create_spider_chart,
+ )
+
+ assert callable(_create_spider_chart)
+
+ def test_create_pareto_chart_exists(self):
+ """Test that _create_pareto_chart function exists."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _create_pareto_chart,
+ )
+
+ assert callable(_create_pareto_chart)
+
+ def test_create_comparison_visualizations_exists(self):
+ """Test that _create_comparison_visualizations function exists."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _create_comparison_visualizations,
+ )
+
+ assert callable(_create_comparison_visualizations)
+
+
+class TestEvaluateSingleConfiguration:
+ """Tests for _evaluate_single_configuration function."""
+
+ def test_evaluate_single_configuration_exists(self):
+ """Test that _evaluate_single_configuration function exists."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _evaluate_single_configuration,
+ )
+
+ assert callable(_evaluate_single_configuration)
+
+ def test_function_signature(self):
+ """Test function has expected parameters."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ _evaluate_single_configuration,
+ )
+ import inspect
+
+ sig = inspect.signature(_evaluate_single_configuration)
+ params = list(sig.parameters.keys())
+
+ assert "query" in params
+ assert "config" in params
+
+
+class TestConfigurationResultStructure:
+ """Tests for expected result structure."""
+
+ @patch("local_deep_research.benchmarks.comparison.evaluator.os.makedirs")
+ def test_compare_returns_dict(self, mock_makedirs):
+ """Test that compare_configurations returns a dictionary."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ compare_configurations,
+ )
+
+ result = compare_configurations(
+ query="test",
+ configurations=[],
+ output_dir="/tmp/test",
+ )
+
+ assert isinstance(result, dict)
+
+ @patch("local_deep_research.benchmarks.comparison.evaluator.os.makedirs")
+ def test_error_result_has_error_key(self, mock_makedirs):
+ """Test that error results have 'error' key."""
+ from local_deep_research.benchmarks.comparison.evaluator import (
+ compare_configurations,
+ )
+
+ result = compare_configurations(
+ query="test",
+ configurations=[],
+ output_dir="/tmp/test",
+ )
+
+ assert "error" in result
diff --git a/tests/benchmarks/test_datasets_utils.py b/tests/benchmarks/test_datasets_utils.py
index abce546c88..845f3daf2c 100644
--- a/tests/benchmarks/test_datasets_utils.py
+++ b/tests/benchmarks/test_datasets_utils.py
@@ -177,3 +177,87 @@ class TestGetKnownAnswerMap:
for key, value in result.items():
assert isinstance(key, str)
assert isinstance(value, str)
+
+
+class TestDatasetRegistry:
+ """Tests for the DatasetRegistry class."""
+
+ def test_registry_has_register_method(self):
+ """Test that registry has register method."""
+ from local_deep_research.benchmarks.datasets.base import DatasetRegistry
+
+ assert hasattr(DatasetRegistry, "register")
+ assert callable(DatasetRegistry.register)
+
+ def test_registry_has_get_dataset_class_method(self):
+ """Test that registry has get_dataset_class method."""
+ from local_deep_research.benchmarks.datasets.base import DatasetRegistry
+
+ assert hasattr(DatasetRegistry, "get_dataset_class")
+ assert callable(DatasetRegistry.get_dataset_class)
+
+ def test_registry_has_create_dataset_method(self):
+ """Test that registry has create_dataset method."""
+ from local_deep_research.benchmarks.datasets.base import DatasetRegistry
+
+ assert hasattr(DatasetRegistry, "create_dataset")
+ assert callable(DatasetRegistry.create_dataset)
+
+ def test_registry_has_get_available_datasets(self):
+ """Test that registry has get_available_datasets method."""
+ from local_deep_research.benchmarks.datasets.base import DatasetRegistry
+
+ assert hasattr(DatasetRegistry, "get_available_datasets")
+ result = DatasetRegistry.get_available_datasets()
+ assert isinstance(result, list)
+
+ def test_registry_has_load_dataset_method(self):
+ """Test that registry has load_dataset method."""
+ from local_deep_research.benchmarks.datasets.base import DatasetRegistry
+
+ assert hasattr(DatasetRegistry, "load_dataset")
+ assert callable(DatasetRegistry.load_dataset)
+
+ def test_get_unknown_dataset_raises(self):
+ """Test that getting unknown dataset raises ValueError."""
+ from local_deep_research.benchmarks.datasets.base import DatasetRegistry
+ import pytest
+
+ with pytest.raises(ValueError, match="Unknown dataset"):
+ DatasetRegistry.get_dataset_class("nonexistent_dataset_xyz")
+
+
+class TestBenchmarkDatasetBase:
+ """Tests for the BenchmarkDataset abstract base class."""
+
+ def test_benchmark_dataset_is_abstract(self):
+ """Test that BenchmarkDataset is abstract."""
+ from local_deep_research.benchmarks.datasets.base import (
+ BenchmarkDataset,
+ )
+ from abc import ABC
+
+ assert issubclass(BenchmarkDataset, ABC)
+
+ def test_benchmark_dataset_has_abstract_methods(self):
+ """Test that BenchmarkDataset has required abstract methods."""
+ from local_deep_research.benchmarks.datasets.base import (
+ BenchmarkDataset,
+ )
+
+ # Check for abstract methods
+ assert hasattr(BenchmarkDataset, "get_dataset_info")
+ assert hasattr(BenchmarkDataset, "get_default_dataset_path")
+ assert hasattr(BenchmarkDataset, "process_example")
+
+ def test_benchmark_dataset_has_utility_methods(self):
+ """Test that BenchmarkDataset has utility methods."""
+ from local_deep_research.benchmarks.datasets.base import (
+ BenchmarkDataset,
+ )
+
+ assert hasattr(BenchmarkDataset, "load")
+ assert hasattr(BenchmarkDataset, "get_examples")
+ assert hasattr(BenchmarkDataset, "get_example")
+ assert hasattr(BenchmarkDataset, "get_question")
+ assert hasattr(BenchmarkDataset, "get_answer")
diff --git a/tests/benchmarks/test_optuna_optimizer.py b/tests/benchmarks/test_optuna_optimizer.py
new file mode 100644
index 0000000000..acfd1da94d
--- /dev/null
+++ b/tests/benchmarks/test_optuna_optimizer.py
@@ -0,0 +1,425 @@
+"""
+Tests for benchmarks/optimization/optuna_optimizer.py
+
+Tests cover:
+- OptunaOptimizer initialization
+- Default parameter space
+- Weight normalization
+- Convenience optimization functions
+"""
+
+from unittest.mock import Mock, patch
+import pytest
+
+
+class TestOptunaOptimizerInit:
+ """Tests for OptunaOptimizer initialization."""
+
+ @patch(
+ "local_deep_research.benchmarks.optimization.optuna_optimizer.CompositeBenchmarkEvaluator"
+ )
+ def test_init_with_defaults(self, mock_evaluator):
+ """Test initialization with default values."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+ )
+
+ mock_evaluator.return_value = Mock()
+
+ optimizer = OptunaOptimizer(
+ base_query="test query",
+ output_dir="/tmp/test_output",
+ )
+
+ assert optimizer.base_query == "test query"
+ assert optimizer.output_dir == "/tmp/test_output"
+ assert optimizer.n_trials == 30
+ assert optimizer.n_jobs == 1
+ assert optimizer.temperature == 0.7
+
+ @patch(
+ "local_deep_research.benchmarks.optimization.optuna_optimizer.CompositeBenchmarkEvaluator"
+ )
+ def test_init_with_custom_values(self, mock_evaluator):
+ """Test initialization with custom values."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+ )
+
+ mock_evaluator.return_value = Mock()
+
+ optimizer = OptunaOptimizer(
+ base_query="test query",
+ output_dir="/tmp/test",
+ model_name="custom-model",
+ provider="openai",
+ search_tool="google",
+ temperature=0.5,
+ n_trials=50,
+ n_jobs=4,
+ )
+
+ assert optimizer.model_name == "custom-model"
+ assert optimizer.provider == "openai"
+ assert optimizer.search_tool == "google"
+ assert optimizer.temperature == 0.5
+ assert optimizer.n_trials == 50
+ assert optimizer.n_jobs == 4
+
+ @patch(
+ "local_deep_research.benchmarks.optimization.optuna_optimizer.CompositeBenchmarkEvaluator"
+ )
+ def test_init_normalizes_weights(self, mock_evaluator):
+ """Test that metric weights are normalized."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+ )
+
+ mock_evaluator.return_value = Mock()
+
+ optimizer = OptunaOptimizer(
+ base_query="test",
+ metric_weights={"quality": 2, "speed": 2},
+ )
+
+ # Weights should be normalized to sum to 1
+ total = sum(optimizer.metric_weights.values())
+ assert total == pytest.approx(1.0)
+ assert optimizer.metric_weights["quality"] == pytest.approx(0.5)
+ assert optimizer.metric_weights["speed"] == pytest.approx(0.5)
+
+ @patch(
+ "local_deep_research.benchmarks.optimization.optuna_optimizer.CompositeBenchmarkEvaluator"
+ )
+ def test_init_default_benchmark_weights(self, mock_evaluator):
+ """Test default benchmark weights."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+ )
+
+ mock_evaluator.return_value = Mock()
+
+ optimizer = OptunaOptimizer(base_query="test")
+
+ assert "simpleqa" in optimizer.benchmark_weights
+ assert optimizer.benchmark_weights["simpleqa"] == 1.0
+
+ @patch(
+ "local_deep_research.benchmarks.optimization.optuna_optimizer.CompositeBenchmarkEvaluator"
+ )
+ def test_init_custom_benchmark_weights(self, mock_evaluator):
+ """Test custom benchmark weights."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+ )
+
+ mock_evaluator.return_value = Mock()
+
+ optimizer = OptunaOptimizer(
+ base_query="test",
+ benchmark_weights={"simpleqa": 0.6, "browsecomp": 0.4},
+ )
+
+ assert optimizer.benchmark_weights["simpleqa"] == 0.6
+ assert optimizer.benchmark_weights["browsecomp"] == 0.4
+
+ @patch(
+ "local_deep_research.benchmarks.optimization.optuna_optimizer.CompositeBenchmarkEvaluator"
+ )
+ def test_init_generates_study_name(self, mock_evaluator):
+ """Test that study name is generated if not provided."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+ )
+
+ mock_evaluator.return_value = Mock()
+
+ optimizer = OptunaOptimizer(base_query="test")
+
+ assert optimizer.study_name.startswith("ldr_opt_")
+
+ @patch(
+ "local_deep_research.benchmarks.optimization.optuna_optimizer.CompositeBenchmarkEvaluator"
+ )
+ def test_init_uses_custom_study_name(self, mock_evaluator):
+ """Test that custom study name is used."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+ )
+
+ mock_evaluator.return_value = Mock()
+
+ optimizer = OptunaOptimizer(
+ base_query="test",
+ study_name="my_custom_study",
+ )
+
+ assert optimizer.study_name == "my_custom_study"
+
+
+class TestDefaultParamSpace:
+ """Tests for default parameter space."""
+
+ @patch(
+ "local_deep_research.benchmarks.optimization.optuna_optimizer.CompositeBenchmarkEvaluator"
+ )
+ def test_get_default_param_space(self, mock_evaluator):
+ """Test getting default parameter space."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+ )
+
+ mock_evaluator.return_value = Mock()
+
+ optimizer = OptunaOptimizer(base_query="test")
+ param_space = optimizer._get_default_param_space()
+
+ assert "iterations" in param_space
+ assert "questions_per_iteration" in param_space
+ assert "search_strategy" in param_space
+ assert "max_results" in param_space
+
+ @patch(
+ "local_deep_research.benchmarks.optimization.optuna_optimizer.CompositeBenchmarkEvaluator"
+ )
+ def test_iterations_param_space(self, mock_evaluator):
+ """Test iterations parameter space."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+ )
+
+ mock_evaluator.return_value = Mock()
+
+ optimizer = OptunaOptimizer(base_query="test")
+ param_space = optimizer._get_default_param_space()
+
+ iterations = param_space["iterations"]
+ assert iterations["type"] == "int"
+ assert iterations["low"] == 1
+ assert iterations["high"] == 5
+
+ @patch(
+ "local_deep_research.benchmarks.optimization.optuna_optimizer.CompositeBenchmarkEvaluator"
+ )
+ def test_search_strategy_param_space(self, mock_evaluator):
+ """Test search strategy parameter space."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+ )
+
+ mock_evaluator.return_value = Mock()
+
+ optimizer = OptunaOptimizer(base_query="test")
+ param_space = optimizer._get_default_param_space()
+
+ strategy = param_space["search_strategy"]
+ assert strategy["type"] == "categorical"
+ assert "choices" in strategy
+ assert "iterdrag" in strategy["choices"]
+
+
+class TestConvenienceFunctions:
+ """Tests for convenience optimization functions."""
+
+ def test_optimize_parameters_exists(self):
+ """Test that optimize_parameters function exists."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ optimize_parameters,
+ )
+
+ assert callable(optimize_parameters)
+
+ def test_optimize_for_speed_exists(self):
+ """Test that optimize_for_speed function exists."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ optimize_for_speed,
+ )
+
+ assert callable(optimize_for_speed)
+
+ def test_optimize_for_quality_exists(self):
+ """Test that optimize_for_quality function exists."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ optimize_for_quality,
+ )
+
+ assert callable(optimize_for_quality)
+
+ def test_optimize_for_efficiency_exists(self):
+ """Test that optimize_for_efficiency function exists."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ optimize_for_efficiency,
+ )
+
+ assert callable(optimize_for_efficiency)
+
+
+class TestOptimizeFunctionSignatures:
+ """Tests for optimization function signatures."""
+
+ def test_optimize_for_speed_default_weights(self):
+ """Test optimize_for_speed uses speed-focused weights."""
+ import inspect
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ optimize_for_speed,
+ )
+
+ # Check function source for speed weights
+ source = inspect.getsource(optimize_for_speed)
+ assert "speed" in source.lower()
+
+ def test_optimize_for_quality_default_weights(self):
+ """Test optimize_for_quality uses quality-focused weights."""
+ import inspect
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ optimize_for_quality,
+ )
+
+ source = inspect.getsource(optimize_for_quality)
+ assert "quality" in source.lower()
+
+ def test_optimize_for_efficiency_default_weights(self):
+ """Test optimize_for_efficiency uses balanced weights."""
+ import inspect
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ optimize_for_efficiency,
+ )
+
+ source = inspect.getsource(optimize_for_efficiency)
+ assert "resource" in source.lower()
+
+
+class TestOptimizerState:
+ """Tests for optimizer state management."""
+
+ @patch(
+ "local_deep_research.benchmarks.optimization.optuna_optimizer.CompositeBenchmarkEvaluator"
+ )
+ def test_initial_state(self, mock_evaluator):
+ """Test initial optimizer state."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+ )
+
+ mock_evaluator.return_value = Mock()
+
+ optimizer = OptunaOptimizer(base_query="test")
+
+ assert optimizer.best_params is None
+ assert optimizer.study is None
+ assert optimizer.trials_history == []
+
+ @patch(
+ "local_deep_research.benchmarks.optimization.optuna_optimizer.CompositeBenchmarkEvaluator"
+ )
+ def test_optimizer_stores_progress_callback(self, mock_evaluator):
+ """Test that progress callback is stored."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+ )
+
+ mock_evaluator.return_value = Mock()
+
+ callback = Mock()
+ optimizer = OptunaOptimizer(
+ base_query="test",
+ progress_callback=callback,
+ )
+
+ assert optimizer.progress_callback is callback
+
+
+class TestPlottingAvailability:
+ """Tests for plotting availability handling."""
+
+ def test_plotting_available_flag_exists(self):
+ """Test that PLOTTING_AVAILABLE flag exists."""
+ from local_deep_research.benchmarks.optimization import optuna_optimizer
+
+ assert hasattr(optuna_optimizer, "PLOTTING_AVAILABLE")
+ assert isinstance(optuna_optimizer.PLOTTING_AVAILABLE, bool)
+
+
+class TestObjectiveFunction:
+ """Tests for the objective function."""
+
+ @patch(
+ "local_deep_research.benchmarks.optimization.optuna_optimizer.CompositeBenchmarkEvaluator"
+ )
+ def test_objective_method_exists(self, mock_evaluator):
+ """Test that _objective method exists."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+ )
+
+ mock_evaluator.return_value = Mock()
+
+ optimizer = OptunaOptimizer(base_query="test")
+
+ assert hasattr(optimizer, "_objective")
+ assert callable(optimizer._objective)
+
+ @patch(
+ "local_deep_research.benchmarks.optimization.optuna_optimizer.CompositeBenchmarkEvaluator"
+ )
+ def test_run_experiment_method_exists(self, mock_evaluator):
+ """Test that _run_experiment method exists."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+ )
+
+ mock_evaluator.return_value = Mock()
+
+ optimizer = OptunaOptimizer(base_query="test")
+
+ assert hasattr(optimizer, "_run_experiment")
+ assert callable(optimizer._run_experiment)
+
+
+class TestVisualizationMethods:
+ """Tests for visualization methods."""
+
+ @patch(
+ "local_deep_research.benchmarks.optimization.optuna_optimizer.CompositeBenchmarkEvaluator"
+ )
+ def test_create_visualizations_method_exists(self, mock_evaluator):
+ """Test that _create_visualizations method exists."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+ )
+
+ mock_evaluator.return_value = Mock()
+
+ optimizer = OptunaOptimizer(base_query="test")
+
+ assert hasattr(optimizer, "_create_visualizations")
+
+ @patch(
+ "local_deep_research.benchmarks.optimization.optuna_optimizer.CompositeBenchmarkEvaluator"
+ )
+ def test_create_quick_visualizations_method_exists(self, mock_evaluator):
+ """Test that _create_quick_visualizations method exists."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+ )
+
+ mock_evaluator.return_value = Mock()
+
+ optimizer = OptunaOptimizer(base_query="test")
+
+ assert hasattr(optimizer, "_create_quick_visualizations")
+
+ @patch(
+ "local_deep_research.benchmarks.optimization.optuna_optimizer.CompositeBenchmarkEvaluator"
+ )
+ def test_save_results_method_exists(self, mock_evaluator):
+ """Test that _save_results method exists."""
+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (
+ OptunaOptimizer,
+ )
+
+ mock_evaluator.return_value = Mock()
+
+ optimizer = OptunaOptimizer(base_query="test")
+
+ assert hasattr(optimizer, "_save_results")
diff --git a/tests/notifications/__init__.py b/tests/notifications/__init__.py
index e69de29bb2..3e74a2d0e4 100644
--- a/tests/notifications/__init__.py
+++ b/tests/notifications/__init__.py
@@ -0,0 +1 @@
+"""Tests for notifications module."""
diff --git a/tests/notifications/test_queue_helpers.py b/tests/notifications/test_queue_helpers.py
new file mode 100644
index 0000000000..bd1845f4be
--- /dev/null
+++ b/tests/notifications/test_queue_helpers.py
@@ -0,0 +1,236 @@
+"""
+Tests for notifications/queue_helpers.py
+
+Tests cover:
+- send_queue_notification function
+- send_queue_failed_notification function
+- send_queue_failed_notification_from_session function
+- send_research_completed_notification_from_session function
+- send_research_failed_notification_from_session function
+"""
+
+from unittest.mock import Mock, patch
+
+
+class TestSendQueueNotification:
+ """Tests for send_queue_notification function."""
+
+ @patch(
+ "local_deep_research.notifications.queue_helpers.NotificationManager"
+ )
+ def test_sends_notification_with_context(self, mock_manager_class):
+ """Test that notification is sent with correct context."""
+ from local_deep_research.notifications.queue_helpers import (
+ send_queue_notification,
+ )
+ from local_deep_research.notifications.templates import EventType
+
+ mock_manager = Mock()
+ mock_manager.send_notification.return_value = True
+ mock_manager_class.return_value = mock_manager
+
+ result = send_queue_notification(
+ username="testuser",
+ research_id="research-123",
+ query="Test query",
+ settings_snapshot={"key": "value"},
+ position=5,
+ )
+
+ assert result is True
+ mock_manager.send_notification.assert_called_once()
+ call_args = mock_manager.send_notification.call_args
+ assert call_args.kwargs["event_type"] == EventType.RESEARCH_QUEUED
+ context = call_args.kwargs["context"]
+ assert context["query"] == "Test query"
+ assert context["research_id"] == "research-123"
+ assert context["position"] == 5
+
+ @patch(
+ "local_deep_research.notifications.queue_helpers.NotificationManager"
+ )
+ def test_sends_notification_without_position(self, mock_manager_class):
+ """Test notification without position parameter."""
+ from local_deep_research.notifications.queue_helpers import (
+ send_queue_notification,
+ )
+
+ mock_manager = Mock()
+ mock_manager.send_notification.return_value = True
+ mock_manager_class.return_value = mock_manager
+
+ result = send_queue_notification(
+ username="testuser",
+ research_id="research-123",
+ query="Test query",
+ settings_snapshot={},
+ )
+
+ assert result is True
+ context = mock_manager.send_notification.call_args.kwargs["context"]
+ assert "position" not in context
+
+ @patch(
+ "local_deep_research.notifications.queue_helpers.NotificationManager"
+ )
+ def test_handles_exception(self, mock_manager_class):
+ """Test that exceptions are caught and return False."""
+ from local_deep_research.notifications.queue_helpers import (
+ send_queue_notification,
+ )
+
+ mock_manager_class.side_effect = RuntimeError("Connection failed")
+
+ result = send_queue_notification(
+ username="testuser",
+ research_id="research-123",
+ query="Test query",
+ settings_snapshot={},
+ )
+
+ assert result is False
+
+
+class TestSendQueueFailedNotification:
+ """Tests for send_queue_failed_notification function."""
+
+ @patch(
+ "local_deep_research.notifications.queue_helpers.NotificationManager"
+ )
+ def test_sends_failed_notification(self, mock_manager_class):
+ """Test that failed notification is sent."""
+ from local_deep_research.notifications.queue_helpers import (
+ send_queue_failed_notification,
+ )
+ from local_deep_research.notifications.templates import EventType
+
+ mock_manager = Mock()
+ mock_manager.send_notification.return_value = True
+ mock_manager_class.return_value = mock_manager
+
+ result = send_queue_failed_notification(
+ username="testuser",
+ research_id="research-123",
+ query="Test query",
+ error_message="Something went wrong",
+ settings_snapshot={"key": "value"},
+ )
+
+ assert result is True
+ call_args = mock_manager.send_notification.call_args
+ assert call_args.kwargs["event_type"] == EventType.RESEARCH_FAILED
+ context = call_args.kwargs["context"]
+ assert context["error"] == "Something went wrong"
+
+ def test_returns_false_without_settings(self):
+ """Test that returns False when no settings_snapshot provided."""
+ from local_deep_research.notifications.queue_helpers import (
+ send_queue_failed_notification,
+ )
+
+ result = send_queue_failed_notification(
+ username="testuser",
+ research_id="research-123",
+ query="Test query",
+ settings_snapshot=None,
+ )
+
+ assert result is False
+
+ @patch(
+ "local_deep_research.notifications.queue_helpers.NotificationManager"
+ )
+ def test_handles_exception(self, mock_manager_class):
+ """Test that exceptions return False."""
+ from local_deep_research.notifications.queue_helpers import (
+ send_queue_failed_notification,
+ )
+
+ mock_manager_class.side_effect = RuntimeError("Failed")
+
+ result = send_queue_failed_notification(
+ username="testuser",
+ research_id="research-123",
+ query="Test query",
+ settings_snapshot={"key": "value"},
+ )
+
+ assert result is False
+
+
+class TestSendQueueFailedNotificationFromSession:
+ """Tests for send_queue_failed_notification_from_session function."""
+
+ def test_function_exists(self):
+ """Test that the function exists."""
+ from local_deep_research.notifications.queue_helpers import (
+ send_queue_failed_notification_from_session,
+ )
+
+ assert callable(send_queue_failed_notification_from_session)
+
+ def test_function_handles_missing_db(self):
+ """Test function handles database issues gracefully."""
+ from local_deep_research.notifications.queue_helpers import (
+ send_queue_failed_notification_from_session,
+ )
+
+ # Should not raise with invalid session
+ send_queue_failed_notification_from_session(
+ username="testuser",
+ research_id="research-123",
+ query="Test query",
+ error_message="Error occurred",
+ db_session=None,
+ )
+
+
+class TestSendResearchCompletedNotificationFromSession:
+ """Tests for send_research_completed_notification_from_session function."""
+
+ def test_function_exists(self):
+ """Test that the function exists."""
+ from local_deep_research.notifications.queue_helpers import (
+ send_research_completed_notification_from_session,
+ )
+
+ assert callable(send_research_completed_notification_from_session)
+
+ def test_function_handles_missing_db(self):
+ """Test function handles database issues gracefully."""
+ from local_deep_research.notifications.queue_helpers import (
+ send_research_completed_notification_from_session,
+ )
+
+ # Should not raise with invalid session
+ send_research_completed_notification_from_session(
+ username="testuser",
+ research_id="research-123",
+ db_session=None,
+ )
+
+
+class TestSendResearchFailedNotificationFromSession:
+ """Tests for send_research_failed_notification_from_session function."""
+
+ def test_function_exists(self):
+ """Test that the function exists."""
+ from local_deep_research.notifications.queue_helpers import (
+ send_research_failed_notification_from_session,
+ )
+
+ assert callable(send_research_failed_notification_from_session)
+
+ def test_function_handles_missing_db(self):
+ """Test function handles database issues gracefully."""
+ from local_deep_research.notifications.queue_helpers import (
+ send_research_failed_notification_from_session,
+ )
+
+ # Should not raise with invalid session
+ send_research_failed_notification_from_session(
+ username="testuser",
+ research_id="research-123",
+ error_message="Error occurred",
+ db_session=None,
+ )