~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
feat(benchmark): add evaluator info and optional examples to YAML export (#2296)
LearningCircuit4718fdbd809d
diff --git a/community_benchmark_results/README.md b/community_benchmark_results/README.mdindex e9604c1c47..31c53ecfa4 100644--- a/community_benchmark_results/README.md+++ b/community_benchmark_results/README.md@@ -26,6 +26,7 @@ This directory contains community-contributed benchmark results for various LLMs- **Include all metadata**: Hardware specs, configuration, and versions are crucial- **Be honest**: Negative results are as valuable as positive ones- **Add notes**: Your observations help others understand the results+- **Review for PII**: If you include individual examples in your export, review the file for any personally identifiable information before submitting a PR## Recommended Test Configurationdiff --git a/community_benchmark_results/benchmark_template.yaml b/community_benchmark_results/benchmark_template.yamlindex e37e727c0b..bec02179b0 100644--- a/community_benchmark_results/benchmark_template.yaml+++ b/community_benchmark_results/benchmark_template.yaml@@ -44,6 +44,13 @@ configuration:max_tokens: # e.g., 4096local_provider_context_window_size: # from settings+# Evaluator / Grader+evaluator:+ model: # e.g., anthropic/claude-3.7-sonnet+ provider: # e.g., openai_endpoint+ endpoint_url: # e.g., https://openrouter.ai/api/v1+ temperature: # e.g., 0+# Versionsversions:ldr_version: # e.g., 0.6.0@@ -61,3 +68,13 @@ notes: |# Add any observations, errors, or insights here# Example: Model struggled with recent events post-2023# Example: Source-based strategy worked better for complex multi-hop questions++# Individual Examples (optional, auto-generated when "Include examples" is selected)+# IMPORTANT: Review for PII before submitting as a PR+# examples:+# - question: "What is the capital of France?"+# correct_answer: "Paris"+# model_answer: "Paris"+# result: correct+# dataset: simpleqa+# processing_time_seconds: 45.3diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py b/src/local_deep_research/benchmarks/web_api/benchmark_routes.pyindex d520a1b99a..8a5d67e2e4 100644--- a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py+++ b/src/local_deep_research/benchmarks/web_api/benchmark_routes.py@@ -113,6 +113,18 @@ def start_benchmark():"temperature": float(settings_manager.get_setting("llm.temperature", 0.7)),+ "max_tokens": settings_manager.get_setting(+ "llm.max_tokens", 30000+ ),+ "context_window_unrestricted": settings_manager.get_setting(+ "llm.context_window_unrestricted", True+ ),+ "context_window_size": settings_manager.get_setting(+ "llm.context_window_size", 128000+ ),+ "local_context_window_size": settings_manager.get_setting(+ "llm.local_context_window_size", 4096+ ),}# Add provider-specific settings@@ -591,6 +603,78 @@ def get_benchmark_results(benchmark_run_id: int):), 500+@benchmark_bp.route(+ "/api/results/<int:benchmark_run_id>/export", methods=["GET"]+)+@login_required+def export_benchmark_results(benchmark_run_id: int):+ """Get lightweight results for YAML export (no full_response/sources/grader_response)."""+ try:+ from sqlalchemy.orm import load_only++ from ...database.models.benchmark import BenchmarkResult+ from ...database.session_context import get_user_db_session+ from flask import session as flask_session++ username = flask_session.get("username")+ logger.info(+ "Exporting benchmark results for run {} by user {}",+ benchmark_run_id,+ username,+ )+ with get_user_db_session(username) as session:+ results = (+ session.query(BenchmarkResult)+ .options(+ load_only(+ BenchmarkResult.example_id,+ BenchmarkResult.dataset_type,+ BenchmarkResult.question,+ BenchmarkResult.correct_answer,+ BenchmarkResult.extracted_answer,+ BenchmarkResult.is_correct,+ BenchmarkResult.confidence,+ BenchmarkResult.processing_time,+ BenchmarkResult.completed_at,+ )+ )+ .filter(BenchmarkResult.benchmark_run_id == benchmark_run_id)+ .order_by(BenchmarkResult.id.asc())+ .all()+ )++ formatted = []+ for r in results:+ formatted.append(+ {+ "example_id": r.example_id,+ "dataset_type": r.dataset_type.value,+ "question": r.question,+ "correct_answer": r.correct_answer,+ "model_answer": r.extracted_answer,+ "is_correct": r.is_correct,+ "confidence": r.confidence,+ "processing_time": r.processing_time,+ "completed_at": r.completed_at.isoformat()+ if r.completed_at+ else None,+ }+ )++ logger.info(+ "Exported {} results for benchmark run {}",+ len(formatted),+ benchmark_run_id,+ )+ return jsonify({"success": True, "results": formatted})++ except Exception:+ logger.exception("Error exporting benchmark results")+ return jsonify(+ {"success": False, "error": "An internal error has occurred."}+ ), 500++@benchmark_bp.route("/api/configs", methods=["GET"])@login_requireddef get_saved_configs():@@ -698,6 +782,18 @@ def start_benchmark_simple():"temperature": float(settings_manager.get_setting("llm.temperature", 0.7)),+ "max_tokens": settings_manager.get_setting(+ "llm.max_tokens", 30000+ ),+ "context_window_unrestricted": settings_manager.get_setting(+ "llm.context_window_unrestricted", True+ ),+ "context_window_size": settings_manager.get_setting(+ "llm.context_window_size", 128000+ ),+ "local_context_window_size": settings_manager.get_setting(+ "llm.local_context_window_size", 4096+ ),}# Add provider-specific settingsdiff --git a/src/local_deep_research/web/templates/pages/benchmark_results.html b/src/local_deep_research/web/templates/pages/benchmark_results.htmlindex e505ac546d..f3cd4a8c8e 100644--- a/src/local_deep_research/web/templates/pages/benchmark_results.html+++ b/src/local_deep_research/web/templates/pages/benchmark_results.html@@ -841,10 +841,13 @@ function createRunCard(run) {<div class="ldr-summary-label">Avg Time/Question</div></div><div class="ldr-summary-item">- <div style="display: flex; gap: 8px;">+ <div style="display: flex; gap: 8px; flex-wrap: wrap; justify-content: center;">${status === 'completed' ?- `<button class="btn ldr-btn-outline btn-sm ldr-download-btn" onclick="event.stopPropagation(); downloadBenchmarkYAML(${run.id})">+ `<button class="btn ldr-btn-outline btn-sm ldr-download-btn" onclick="event.stopPropagation(); downloadBenchmarkYAML(${run.id}, false)" title="Summary only"><i class="fas fa-download"></i> YAML+ </button>+ <button class="btn ldr-btn-outline btn-sm ldr-download-btn" onclick="event.stopPropagation(); downloadBenchmarkYAML(${run.id}, true)" title="Summary + individual questions & answers">+ <i class="fas fa-download"></i> + Examples</button>` : ''}${status === 'in_progress' ?@@ -1144,7 +1147,17 @@ async function cancelAndDeleteBenchmarkRun(runId) {}}-async function downloadBenchmarkYAML(runId) {+function yamlEscape(str) {+ if (str == null) return '';+ return String(str)+ .replace(/\\/g, '\\\\')+ .replace(/"/g, '\\"')+ .replace(/\n/g, '\\n')+ .replace(/\r/g, '\\r')+ .replace(/\t/g, '\\t');+}++async function downloadBenchmarkYAML(runId, includeExamples = false) {try {// Find the run in our local dataconst run = benchmarkRuns.find(r => r.id === runId);@@ -1163,98 +1176,82 @@ async function downloadBenchmarkYAML(runId) {const modelName = run.search_config?.model_name || 'unknown-model';const cleanModelName = modelName.replace(/[^a-zA-Z0-9.-]/g, '-').toLowerCase();- // Get all relevant settings from database- let localContextWindow = 'Could not fetch';- let maxTokens = 'Could not fetch';- let contextWindowUnrestricted = 'Could not fetch';- let contextWindowSize = 'Could not fetch';- let supportsMaxTokens = 'Could not fetch';-- try {- const settingsResponse = await fetch('/settings/api');- if (settingsResponse.ok) {- const data = await settingsResponse.json();- if (data.status === 'success' && data.settings) {- const settings = data.settings;- // LLM settings - extract the 'value' property from each setting object- localContextWindow = settings['llm.local_context_window_size']?.value || 'Could not fetch';- maxTokens = settings['llm.max_tokens']?.value || 'Could not fetch';- contextWindowUnrestricted = settings['llm.context_window_unrestricted']?.value !== undefined ?- (settings['llm.context_window_unrestricted'].value ? 'Yes' : 'No') : 'Could not fetch';- contextWindowSize = settings['llm.context_window_size']?.value || 'Could not fetch';- supportsMaxTokens = settings['llm.supports_max_tokens']?.value !== undefined ?- (settings['llm.supports_max_tokens'].value ? 'Yes' : 'No') : 'Could not fetch';- }- }- } catch (e) {- console.error('Could not fetch current settings:', e);+ // Read context window / max tokens from search_config (captured at benchmark start)+ const localContextWindow = run.search_config?.local_context_window_size ?? null;+ const cloudContextWindow = run.search_config?.context_window_size ?? null;+ const contextWindowUnrestricted = run.search_config?.context_window_unrestricted ?? null;+ const maxTokens = run.search_config?.max_tokens ?? null;++ // Determine if local provider (ollama, llamacpp, lmstudio)+ const provider = (run.search_config?.provider || '').toLowerCase();+ const isLocalProvider = ['ollama', 'llamacpp', 'lmstudio'].includes(provider);++ // Build evaluator section from evaluation_config (only safe keys, never API keys)+ const evalConfig = run.evaluation_config || {};+ let evaluatorYaml = 'evaluator:\n';+ if (evalConfig.model_name) evaluatorYaml += ` model: ${evalConfig.model_name}\n`;+ if (evalConfig.provider) evaluatorYaml += ` provider: ${evalConfig.provider}\n`;+ if (evalConfig.openai_endpoint_url) evaluatorYaml += ` endpoint_url: ${evalConfig.openai_endpoint_url}\n`;+ if (evalConfig.temperature !== undefined && evalConfig.temperature !== null) {+ evaluatorYaml += ` temperature: ${evalConfig.temperature}\n`;}- // Calculate average search results if availableconst avgSearchResults = formatAvgSearchResults(run).replace(' results', '');- const searchResultsNum = avgSearchResults !== 'N/A' ? avgSearchResults : '# Please fill in';+ const strategy = run.search_config?.search_strategy === 'focused_iteration' ? 'focused_iteration' : 'source_based';+ const correctCount = run.overall_accuracy ? Math.round(run.overall_accuracy * run.total_examples / 100) : 0;- // Generate YAML content- const yamlContent = `# Benchmark Result-# Generated from Local Deep Research v${appVersion}-# Date: ${date}--# Model Information-model: ${modelName}+ // Generate compact YAML — data only, no empty placeholders+ let yamlContent = `model: ${modelName}model_provider: ${run.search_config?.provider || 'unknown'}-quantization: # Please fill in if applicable--# Search Engine (critical for benchmark reproducibility)search_engine: ${run.search_config?.search_tool || 'unknown'}-search_provider_version: # if known, e.g., "latest", "2024.1.0"-average_results_per_query: ${searchResultsNum}--# Hardware-hardware:- gpu: # Please fill in- ram: # Please fill in- cpu: # Please fill in--# Benchmark Results-results:+${avgSearchResults !== 'N/A' ? `average_results_per_query: ${avgSearchResults}\n` : ''}results:dataset: SimpleQAtotal_questions: ${run.total_examples}-- ${run.search_config?.search_strategy === 'focused_iteration' ? 'focused_iteration' : 'source_based'}:- accuracy: ${run.overall_accuracy ? run.overall_accuracy.toFixed(1) : 0}% (${Math.round(run.overall_accuracy * run.total_examples / 100)}/${run.total_examples})+ ${strategy}:+ accuracy: "${run.overall_accuracy ? run.overall_accuracy.toFixed(1) : 0}% (${correctCount}/${run.total_examples})"iterations: ${run.search_config?.iterations || 'N/A'}questions_per_iteration: ${run.search_config?.questions_per_iteration || 'N/A'}- avg_time_per_question: ${formatAvgProcessingTime(run)}- total_tokens_used: # if available--# Configuration+ avg_time_per_question: "${formatAvgProcessingTime(run)}"configuration:- context_window: ${localContextWindow} # Current setting at download time - may differ from benchmark run- temperature: ${run.search_config?.temperature || 'N/A'}- max_tokens: ${maxTokens} # Current setting at download time- local_provider_context_window_size: ${localContextWindow} # Current setting at download time- context_window_unrestricted: ${contextWindowUnrestricted} # Current setting at download time--# Versions-versions:+ temperature: ${run.search_config?.temperature ?? 'N/A'}+${isLocalProvider && localContextWindow != null ? ` context_window: ${localContextWindow} # captured at benchmark start\n` : ''}${!isLocalProvider && contextWindowUnrestricted != null ? ` context_window_unrestricted: ${contextWindowUnrestricted ? 'yes' : 'no'} # captured at benchmark start\n` : ''}${!isLocalProvider && !contextWindowUnrestricted && cloudContextWindow != null ? ` context_window: ${cloudContextWindow} # captured at benchmark start\n` : ''}${maxTokens != null ? ` max_tokens: ${maxTokens} # captured at benchmark start\n` : ''}${evaluatorYaml}versions:ldr_version: ${appVersion}- ollama_version: # if applicable--# Test Details-test_details:- date_tested: ${date}- rate_limiting_issues: # yes/no- search_failures: # number of failed searches, if any--# Notes-notes: |- # Add any observations, errors, or insights here- # Search strategy: ${run.search_config?.search_strategy || 'unknown'}- # Provider: ${run.search_config?.provider || 'unknown'}- # Note: Configuration values are from current settings at download time,- # not necessarily the values used during the benchmark run+date_tested: ${date}`;+ // Optionally append individual examples+ if (includeExamples) {+ try {+ const exportResponse = await fetch(`/benchmark/api/results/${runId}/export`);+ const exportData = await exportResponse.json();++ if (exportData.success && exportData.results.length > 0) {+ yamlContent += `examples:\n`;++ for (const ex of exportData.results) {+ const result = ex.is_correct === true ? 'correct'+ : ex.is_correct === false ? 'incorrect'+ : 'not_graded';+ const time = ex.processing_time != null+ ? Number(ex.processing_time).toFixed(1)+ : null;++ yamlContent += ` - question: "${yamlEscape(ex.question)}"\n`;+ yamlContent += ` correct_answer: "${yamlEscape(ex.correct_answer)}"\n`;+ yamlContent += ` model_answer: "${yamlEscape(ex.model_answer)}"\n`;+ yamlContent += ` result: ${result}\n`;+ yamlContent += ` dataset: ${ex.dataset_type || 'unknown'}\n`;+ if (time !== null) {+ yamlContent += ` processing_time_seconds: ${time}\n`;+ }+ }+ }+ } catch (e) {+ console.error('Error fetching examples for export:', e);+ showAlert('Could not fetch individual examples, downloading without them.', 'warning');+ }+ }+// Create blob and downloadconst blob = new Blob([yamlContent], { type: 'text/yaml' });const url = window.URL.createObjectURL(blob);@@ -1267,7 +1264,7 @@ notes: |window.URL.revokeObjectURL(url);document.body.removeChild(a);- showAlert('Benchmark YAML downloaded! Hardware details are optional but helpful for performance context.', 'success');+ showAlert('Benchmark YAML downloaded successfully.', 'success');} catch (error) {console.error('Error downloading YAML:', error);showAlert('Error downloading YAML: ' + error.message, 'error');diff --git a/tests/benchmarks/web_api/test_benchmark_routes.py b/tests/benchmarks/web_api/test_benchmark_routes.pyindex 6652d6670e..f2fc4d26f9 100644--- a/tests/benchmarks/web_api/test_benchmark_routes.py+++ b/tests/benchmarks/web_api/test_benchmark_routes.py@@ -1069,3 +1069,314 @@ class TestDeleteBenchmarkEndpoint:"/benchmark/api/delete/nonexistent-run-12345")assert response.status_code in [302, 401, 403, 404, 405, 500]+++class TestSearchConfigSnapshotsLLMSettings:+ """Tests that search_config captures LLM settings at benchmark start."""++ def _make_app(self):+ from flask import Blueprint, Flask++ from local_deep_research.benchmarks.web_api.benchmark_routes import (+ benchmark_bp,+ )++ app = Flask(__name__)+ app.config["SECRET_KEY"] = "test-secret"+ app.config["WTF_CSRF_ENABLED"] = False+ # Register auth blueprint stub so url_for("auth.login") resolves+ auth_bp = Blueprint("auth", __name__, url_prefix="/auth")++ @auth_bp.route("/login")+ def login():+ return "login"++ app.register_blueprint(auth_bp)+ app.register_blueprint(benchmark_bp)+ return app++ def test_start_benchmark_captures_llm_settings_in_search_config(self):+ """Verify max_tokens, context_window_size, context_window_unrestricted,+ and local_context_window_size are stored in search_config."""+ app = self._make_app()++ fake_settings = {+ "search.iterations": 8,+ "search.questions_per_iteration": 5,+ "search.tool": "searxng",+ "search.search_strategy": "focused_iteration",+ "llm.model": "gpt-4",+ "llm.provider": "openai",+ "llm.temperature": 0.7,+ "llm.max_tokens": 50000,+ "llm.context_window_unrestricted": False,+ "llm.context_window_size": 64000,+ "llm.local_context_window_size": 8192,+ "llm.openai.api_key": "sk-test",+ "benchmark.evaluation.provider": "openai",+ "benchmark.evaluation.model": "gpt-4",+ "benchmark.evaluation.temperature": 0,+ }++ mock_settings_manager = MagicMock()+ mock_settings_manager.get_setting.side_effect = (+ lambda key, default=None: fake_settings.get(key, default)+ )++ mock_db_session = MagicMock()++ with app.test_client() as client:+ with client.session_transaction() as sess:+ sess["username"] = "testuser"+ sess["session_id"] = "test-session"++ with (+ patch(+ "local_deep_research.database.encrypted_db.db_manager.is_user_connected",+ return_value=True,+ ),+ patch(+ "local_deep_research.database.session_context.get_user_db_session"+ ) as mock_get_session,+ patch(+ "local_deep_research.settings.SettingsManager",+ return_value=mock_settings_manager,+ ),+ patch(+ "local_deep_research.database.session_passwords.session_password_store"+ ) as mock_pw_store,+ patch(+ "local_deep_research.benchmarks.web_api.benchmark_routes.benchmark_service"+ ) as mock_bench_svc,+ ):+ mock_get_session.return_value.__enter__ = Mock(+ return_value=mock_db_session+ )+ mock_get_session.return_value.__exit__ = Mock(+ return_value=False+ )+ mock_pw_store.get_session_password.return_value = "pw"+ mock_bench_svc.create_benchmark_run.return_value = "run-123"+ mock_bench_svc.start_benchmark.return_value = True++ response = client.post(+ "/benchmark/api/start",+ json={+ "datasets_config": {"simpleqa": {"count": 5}},+ },+ content_type="application/json",+ )++ assert response.status_code == 200+ data = response.get_json()+ assert data["success"] is True+ assert data["benchmark_run_id"] == "run-123"++ # Verify search_config passed to create_benchmark_run+ call_kwargs = mock_bench_svc.create_benchmark_run.call_args+ search_config = call_kwargs.kwargs.get(+ "search_config"+ ) or call_kwargs[1].get("search_config")++ assert search_config["max_tokens"] == 50000+ assert search_config["context_window_unrestricted"] is False+ assert search_config["context_window_size"] == 64000+ assert search_config["local_context_window_size"] == 8192+++class TestExportBenchmarkResults:+ """Tests for export_benchmark_results route."""++ def test_export_route_is_callable(self):+ """Test that export_benchmark_results function is callable."""+ from local_deep_research.benchmarks.web_api.benchmark_routes import (+ export_benchmark_results,+ )++ assert callable(export_benchmark_results)++ def test_export_route_exists(self):+ """Test /api/results/<run_id>/export endpoint exists."""+ from flask import Flask+ from local_deep_research.benchmarks.web_api.benchmark_routes import (+ benchmark_bp,+ )++ app = Flask(__name__)+ app.config["SECRET_KEY"] = "test-secret"+ app.register_blueprint(benchmark_bp)++ with app.test_client() as client:+ response = client.get("/benchmark/api/results/1/export")+ assert response.status_code in [200, 302, 401, 403, 500]++ def test_export_returns_lightweight_results(self):+ """Test that export returns results without heavy columns."""+ from datetime import datetime, timezone++ from flask import Flask+ from local_deep_research.benchmarks.web_api.benchmark_routes import (+ benchmark_bp,+ )++ app = Flask(__name__)+ app.config["SECRET_KEY"] = "test-secret"+ app.config["WTF_CSRF_ENABLED"] = False+ app.register_blueprint(benchmark_bp)++ mock_result = MagicMock()+ mock_result.example_id = "q1"+ mock_result.dataset_type.value = "simpleqa"+ mock_result.question = "What is the capital of France?"+ mock_result.correct_answer = "Paris"+ mock_result.extracted_answer = "Paris"+ mock_result.is_correct = True+ mock_result.confidence = "high"+ mock_result.processing_time = 45.3+ mock_result.completed_at = datetime(2025, 1, 1, tzinfo=timezone.utc)++ with app.test_client() as client:+ with client.session_transaction() as sess:+ sess["username"] = "testuser"++ with patch(+ "local_deep_research.benchmarks.web_api.benchmark_routes.login_required",+ lambda f: f,+ ):+ with patch(+ "local_deep_research.web.auth.decorators.login_required",+ lambda f: f,+ ):+ with patch(+ "local_deep_research.benchmarks.web_api.benchmark_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session = MagicMock()+ mock_session_ctx.return_value.__enter__ = Mock(+ return_value=mock_session+ )+ mock_session_ctx.return_value.__exit__ = Mock(+ return_value=False+ )+ mock_query = mock_session.query.return_value+ mock_query.options.return_value = mock_query+ mock_query.filter.return_value = mock_query+ mock_query.order_by.return_value = mock_query+ mock_query.all.return_value = [mock_result]++ response = client.get("/benchmark/api/results/1/export")+ # May redirect due to auth, but route works+ assert response.status_code in [200, 302, 401, 500]++ if response.status_code == 200:+ data = response.get_json()+ assert data["success"] is True+ assert len(data["results"]) == 1+ result = data["results"][0]+ assert (+ result["question"]+ == "What is the capital of France?"+ )+ assert result["model_answer"] == "Paris"+ assert result["is_correct"] is True+ assert result["processing_time"] == 45.3+ # Should NOT contain heavy columns+ assert "full_response" not in result+ assert "sources" not in result+ assert "grader_response" not in result++ def test_export_empty_results(self):+ """Test export with no results returns empty list."""+ from flask import Flask+ from local_deep_research.benchmarks.web_api.benchmark_routes import (+ benchmark_bp,+ )++ app = Flask(__name__)+ app.config["SECRET_KEY"] = "test-secret"+ app.config["WTF_CSRF_ENABLED"] = False+ app.register_blueprint(benchmark_bp)++ with app.test_client() as client:+ with client.session_transaction() as sess:+ sess["username"] = "testuser"++ with patch(+ "local_deep_research.benchmarks.web_api.benchmark_routes.login_required",+ lambda f: f,+ ):+ with patch(+ "local_deep_research.web.auth.decorators.login_required",+ lambda f: f,+ ):+ with patch(+ "local_deep_research.benchmarks.web_api.benchmark_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session = MagicMock()+ mock_session_ctx.return_value.__enter__ = Mock(+ return_value=mock_session+ )+ mock_session_ctx.return_value.__exit__ = Mock(+ return_value=False+ )+ mock_query = mock_session.query.return_value+ mock_query.options.return_value = mock_query+ mock_query.filter.return_value = mock_query+ mock_query.order_by.return_value = mock_query+ mock_query.all.return_value = []++ response = client.get(+ "/benchmark/api/results/999/export"+ )+ assert response.status_code in [200, 302, 401, 500]++ if response.status_code == 200:+ data = response.get_json()+ assert data["success"] is True+ assert len(data["results"]) == 0++ def test_export_orders_by_id_asc(self):+ """Test that export results are ordered by id ascending."""+ from flask import Flask+ from local_deep_research.benchmarks.web_api.benchmark_routes import (+ benchmark_bp,+ )++ app = Flask(__name__)+ app.config["SECRET_KEY"] = "test-secret"+ app.config["WTF_CSRF_ENABLED"] = False+ app.register_blueprint(benchmark_bp)++ with app.test_client() as client:+ with client.session_transaction() as sess:+ sess["username"] = "testuser"++ with patch(+ "local_deep_research.benchmarks.web_api.benchmark_routes.login_required",+ lambda f: f,+ ):+ with patch(+ "local_deep_research.web.auth.decorators.login_required",+ lambda f: f,+ ):+ with patch(+ "local_deep_research.benchmarks.web_api.benchmark_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session = MagicMock()+ mock_session_ctx.return_value.__enter__ = Mock(+ return_value=mock_session+ )+ mock_session_ctx.return_value.__exit__ = Mock(+ return_value=False+ )+ mock_query = mock_session.query.return_value+ mock_query.options.return_value = mock_query+ mock_query.filter.return_value = mock_query+ mock_query.order_by.return_value = mock_query+ mock_query.all.return_value = []++ response = client.get("/benchmark/api/results/1/export")+ assert response.status_code in [200, 302, 401, 500]++ # Verify order_by was called (confirming ASC ordering)+ if response.status_code == 200:+ mock_query.order_by.assert_called_once()