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.

fix: Fix benchmark display and search metrics tracking issues (#800)

LearningCircuit9e60040f9b72
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index a05b07f680..4f86435a0d 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -579,7 +579,18 @@ def analyze_documents(
Provide a concise summary of the key information found in these documents related to the query.
"""
+ import time
+
+ llm_start_time = time.time()
+ logger.info(
+ f"Starting LLM summary generation (prompt length: {len(summary_prompt)} chars)..."
+ )
+
summary_response = llm.invoke(summary_prompt)
+
+ llm_elapsed = time.time() - llm_start_time
+ logger.info(f"LLM summary generation completed in {llm_elapsed:.2f}s")
+
if hasattr(summary_response, "content"):
summary = remove_think_tags(summary_response.content)
else:
diff --git a/src/local_deep_research/benchmarks/graders.py b/src/local_deep_research/benchmarks/graders.py
index f97307dc97..353d1f8640 100644
--- a/src/local_deep_research/benchmarks/graders.py
+++ b/src/local_deep_research/benchmarks/graders.py
@@ -177,6 +177,13 @@ def grade_single_result(
)
try:
+ import time
+
+ eval_llm_start = time.time()
+ logger.info(
+ f"Starting grading LLM call (prompt length: {len(grading_prompt)} chars)..."
+ )
+
# Grade using LLM
if hasattr(evaluation_llm, "invoke") and callable(
evaluation_llm.invoke
@@ -195,6 +202,9 @@ def grade_single_result(
# Fallback for other LLM interfaces
grading_response = str(evaluation_llm(grading_prompt))
+ eval_llm_elapsed = time.time() - eval_llm_start
+ logger.info(f"Grading LLM call completed in {eval_llm_elapsed:.2f}s")
+
# Extract grading information using regex
if dataset_type.lower() == "browsecomp":
# BrowseComp-specific extraction
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py b/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
index 7c2eee306c..517fac2a0b 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
@@ -559,21 +559,6 @@ def get_benchmark_results(benchmark_run_id: int):
f"Error getting search results for result {result.example_id}"
)
- # Fallback to sources if available and we didn't find metrics
- if search_result_count == 0 and result.sources:
- try:
- if isinstance(result.sources, list):
- search_result_count = len(result.sources)
- elif (
- isinstance(result.sources, dict)
- and "all_links_of_system" in result.sources
- ):
- search_result_count = len(
- result.sources["all_links_of_system"]
- )
- except:
- pass
-
formatted_results.append(
{
"example_id": result.example_id,
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_service.py b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
index f90e790b7f..ac5ba5024f 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_service.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
@@ -363,7 +363,24 @@ class BenchmarkService:
}
# Process tasks
+ logger.info(
+ f"Benchmark {benchmark_run_id} starting to process {len(task_queue)} tasks"
+ )
for i, task in enumerate(task_queue):
+ # Check if benchmark has been cancelled
+ if (
+ benchmark_run_id in self.active_runs
+ and self.active_runs[benchmark_run_id].get("status")
+ == "cancelled"
+ ):
+ logger.info(
+ f"Benchmark {benchmark_run_id} was cancelled, stopping processing"
+ )
+ break
+
+ logger.info(
+ f"Benchmark {benchmark_run_id} processing task {i + 1}/{len(task_queue)}"
+ )
try:
# Add username and password to task for metrics tracking
task["username"] = benchmark_data.get("username")
@@ -384,6 +401,11 @@ class BenchmarkService:
# Update progress
progress_info["completed_examples"] += 1
+ logger.info(
+ f"Benchmark {benchmark_run_id} task {i + 1}/{len(task_queue)} completed successfully. "
+ f"Progress: {progress_info['completed_examples']}/{progress_info['total_examples']} total examples"
+ )
+
# Send real-time update
self._send_progress_update(
benchmark_run_id,
@@ -392,8 +414,12 @@ class BenchmarkService:
)
except Exception as e:
- logger.exception(f"Error processing task {i}")
+ logger.exception(f"Error processing task {i}: {str(e)}")
progress_info["failed_examples"] += 1
+ logger.info(
+ f"Benchmark {benchmark_run_id} task {i + 1}/{len(task_queue)} failed. "
+ f"Total failed: {progress_info['failed_examples']}"
+ )
# Check if this is a rate limiting error
error_str = str(e).lower()
@@ -415,11 +441,26 @@ class BenchmarkService:
# Mark as completed in memory tracker
progress_info["end_time"] = datetime.now(UTC)
- memory_tracker.update_task_status(task_id, "completed")
+
+ # Check if benchmark was cancelled
+ was_cancelled = (
+ benchmark_run_id in self.active_runs
+ and self.active_runs[benchmark_run_id].get("status")
+ == "cancelled"
+ )
+
+ if was_cancelled:
+ memory_tracker.update_task_status(task_id, "cancelled")
+ status = BenchmarkStatus.CANCELLED
+ message = "Benchmark cancelled by user"
+ else:
+ memory_tracker.update_task_status(task_id, "completed")
+ status = BenchmarkStatus.COMPLETED
+ message = "Benchmark completed successfully"
# Store completion info for later database update
self.active_runs[benchmark_run_id]["completion_info"] = {
- "status": BenchmarkStatus.COMPLETED,
+ "status": status,
"end_time": progress_info["end_time"],
"completed_examples": progress_info["completed_examples"],
"failed_examples": progress_info["failed_examples"],
@@ -430,9 +471,15 @@ class BenchmarkService:
"research_progress",
benchmark_run_id,
{
- "status": "completed",
- "message": "Benchmark completed successfully",
- "progress": 100,
+ "status": "cancelled" if was_cancelled else "completed",
+ "message": message,
+ "progress": (
+ progress_info["completed_examples"]
+ / progress_info["total_examples"]
+ * 100
+ )
+ if progress_info["total_examples"] > 0
+ else 0,
"benchmark_run_id": benchmark_run_id,
},
)
@@ -516,6 +563,12 @@ class BenchmarkService:
) -> Dict:
"""Process a single benchmark task."""
try:
+ logger.info(
+ f"Starting benchmark task {task['task_index'] + 1}: "
+ f"example_id={task['example_id']}, dataset={task['dataset_type']}, "
+ f"question_preview='{task['question'][:100]}...'"
+ )
+
# Get settings context from thread-local storage
from ...config.thread_settings import get_settings_context
@@ -525,14 +578,21 @@ class BenchmarkService:
import uuid
tracking_id = str(uuid.uuid4())
+ logger.info(
+ f"Task {task['example_id']} assigned tracking_id: {tracking_id}"
+ )
# Format query
formatted_query = format_query(
task["question"], task["dataset_type"]
)
+ logger.info(
+ f"Task {task['example_id']} formatted query: '{formatted_query[:150]}...'"
+ )
# Run research with progress callback for WebSocket updates
start_time = time.time()
+ logger.info(f"Task {task['example_id']} starting research phase...")
def benchmark_progress_callback(
status: str, progress: int, data: dict
@@ -616,9 +676,17 @@ class BenchmarkService:
user_password=user_password, # Pass password for metrics tracking
)
processing_time = time.time() - start_time
+ logger.info(
+ f"Task {task['example_id']} research completed in {processing_time:.2f}s, "
+ f"model={search_config.get('model_name')}, provider={search_config.get('provider')}"
+ )
# Extract answer
response = search_result.get("summary", "")
+ logger.info(
+ f"Task {task['example_id']} response length: {len(response)} chars"
+ )
+
extracted_data = extract_answer_from_response(
response, task["dataset_type"]
)
@@ -627,6 +695,9 @@ class BenchmarkService:
if isinstance(extracted_data, dict)
else str(extracted_data)
)
+ logger.info(
+ f"Task {task['example_id']} extracted answer: '{extracted_answer[:100]}...'"
+ )
# Extract sources - handle both direct sources and all_links_of_system
sources = search_result.get("sources", [])
@@ -655,6 +726,9 @@ class BenchmarkService:
# Evaluate result - requires proper grading model
try:
+ logger.info(f"Task {task['example_id']} starting evaluation...")
+ eval_start_time = time.time()
+
# Always attempt evaluation, regardless of provider
# Modern local models like Ollama are capable of grading
# Try to evaluate with proper model
@@ -672,6 +746,10 @@ class BenchmarkService:
evaluation_config,
settings_context.snapshot,
)
+ eval_time = time.time() - eval_start_time
+ logger.info(
+ f"Task {task['example_id']} evaluation completed in {eval_time:.2f}s"
+ )
if eval_result and not eval_result.get("grading_error"):
result.update(
{
diff --git a/src/local_deep_research/metrics/search_tracker.py b/src/local_deep_research/metrics/search_tracker.py
index c34df86586..9518c2953d 100644
--- a/src/local_deep_research/metrics/search_tracker.py
+++ b/src/local_deep_research/metrics/search_tracker.py
@@ -400,8 +400,32 @@ _search_tracker = None
def get_search_tracker() -> SearchTracker:
- """Get the global search tracker instance."""
+ """Get the global search tracker instance with proper authentication."""
global _search_tracker
if _search_tracker is None:
- _search_tracker = SearchTracker()
+ # Try to get credentials from Flask session if available
+ try:
+ from flask import session as flask_session
+ from ..database.session_passwords import session_password_store
+
+ username = flask_session.get("username")
+ session_id = flask_session.get("session_id")
+ user_password = None
+
+ if session_id and username:
+ user_password = session_password_store.get_session_password(
+ username, session_id
+ )
+
+ # Create metrics DB with credentials
+ from .database import MetricsDatabase
+
+ metrics_db = MetricsDatabase(
+ username=username, password=user_password
+ )
+ _search_tracker = SearchTracker(db=metrics_db)
+ except (ImportError, RuntimeError):
+ # Fall back to default if not in Flask context
+ _search_tracker = SearchTracker()
+
return _search_tracker
diff --git a/src/local_deep_research/web/templates/pages/benchmark.html b/src/local_deep_research/web/templates/pages/benchmark.html
index c303c8623f..fdf9b15062 100644
--- a/src/local_deep_research/web/templates/pages/benchmark.html
+++ b/src/local_deep_research/web/templates/pages/benchmark.html
@@ -596,6 +596,11 @@
<strong style="color: #2196f3;">🔧 For Shared Resources:</strong> When using SearXNG or other shared engines, reduce iterations and questions per iteration in Settings to minimize load on shared infrastructure.
</p>
</div>
+ <div id="context-window-warning" style="display: none; background: rgba(255, 152, 0, 0.1); border: 1px solid rgba(255, 152, 0, 0.3); padding: 12px; border-radius: 6px; margin-top: 12px;">
+ <p style="margin: 0; font-size: 0.9rem; color: #e0e0e0;">
+ <strong style="color: #ff9800;">⚠️ Context Window Requirement:</strong> The "Focused Iteration" search strategy requires a high context window (probably 15k+ tokens) even for local models. Lower context windows may cause failures or incomplete results.
+ </p>
+ </div>
</div>
</div>
<div class="guidelines-sidebar">
@@ -726,7 +731,7 @@
</div>
<div style="font-size: 0.9rem; color: var(--text-muted); text-align: center;">
- <i class="fas fa-info-circle"></i> To change any settings, go to <a href="/research/" target="_blank" style="color: var(--primary-color);">Settings Dashboard</a>
+ <i class="fas fa-info-circle"></i> To change any settings, go to <a href="/" target="_blank" style="color: var(--primary-color);">Settings Dashboard</a>
</div>
</div>
</fieldset>
@@ -1467,7 +1472,20 @@ function checkForRunningBenchmark() {
async function loadCurrentSettings() {
console.log('Starting loadCurrentSettings...');
+ // Declare variables in function scope for access in all blocks
+ let llmProviderData = null;
+ let llmModelData = null;
+ let searchToolData = null;
+ let iterationsData = null;
+ let questionsData = null;
+ let strategyData = null;
+ let evalProviderData = null;
+ let evalModelData = null;
+ let evalTempData = null;
+ let evalEndpointData = null;
+
try {
+ console.log('Starting to fetch settings...');
// Load settings individually
const [
llmProviderResp,
@@ -1492,19 +1510,25 @@ async function loadCurrentSettings() {
fetch('/settings/api/benchmark.evaluation.temperature'),
fetch('/settings/api/benchmark.evaluation.endpoint_url')
]);
+ console.log('Fetched all settings responses');
// Parse responses
- const llmProviderData = await llmProviderResp.json();
- const llmModelData = await llmModelResp.json();
- const searchToolData = await searchToolResp.json();
- const iterationsData = await iterationsResp.json();
- const questionsData = await questionsResp.json();
- const strategyData = await strategyResp.json();
+ llmProviderData = await llmProviderResp.json();
+ llmModelData = await llmModelResp.json();
+ searchToolData = await searchToolResp.json();
+ iterationsData = await iterationsResp.json();
+ questionsData = await questionsResp.json();
+ strategyData = await strategyResp.json();
evalProviderData = await evalProviderResp.json();
evalModelData = await evalModelResp.json();
evalTempData = await evalTempResp.json();
evalEndpointData = await evalEndpointResp.json();
+ console.log('Parsed settings data:', {
+ llmProvider: llmProviderData,
+ searchStrategy: strategyData
+ });
+
// Display LLM settings with error handling
try {
const providerEl = document.getElementById('current-provider');
@@ -1556,12 +1580,50 @@ async function loadCurrentSettings() {
document.getElementById('current-questions').textContent = 'ERROR: Failed to load';
}
- // Display search strategy
+ // Display search strategy and check for context window warning
if (strategyData && strategyData.value) {
- document.getElementById('current-strategy').textContent =
- strategyData.value || 'ERROR: No value';
+ const searchStrategy = strategyData.value || 'ERROR: No value';
+ // Display the strategy with hyphens for readability
+ const displayStrategy = searchStrategy.replace(/_/g, '-');
+ document.getElementById('current-strategy').textContent = displayStrategy;
+
+ console.log('Strategy data:', strategyData);
+ console.log('Provider data:', llmProviderData);
+
+ // Check if we need to show context window warning
+ const contextWarning = document.getElementById('context-window-warning');
+ console.log('Context warning element found:', !!contextWarning);
+
+ if (contextWarning) {
+ // Show warning if using focused_iteration with Ollama
+ const provider = llmProviderData?.value || '';
+ const isOllama = provider.toLowerCase() === 'ollama';
+
+ // Check for both focused_iteration and focused-iteration (handle both formats)
+ const isFocusedIteration = searchStrategy === 'focused_iteration' ||
+ searchStrategy === 'focused-iteration';
+
+ console.log('Context warning check:', {
+ searchStrategy,
+ provider,
+ isOllama,
+ isFocusedIteration,
+ shouldShow: isFocusedIteration && isOllama
+ });
+
+ if (isFocusedIteration && isOllama) {
+ contextWarning.style.display = 'block';
+ console.log('WARNING SHOULD BE VISIBLE NOW');
+ } else {
+ contextWarning.style.display = 'none';
+ console.log('Warning hidden');
+ }
+ } else {
+ console.log('Context warning element NOT FOUND in DOM');
+ }
} else {
document.getElementById('current-strategy').textContent = 'ERROR: Failed to load';
+ console.log('Strategy data not available');
}
// Display evaluation settings (commented out as these elements don't exist)
@@ -1599,11 +1661,11 @@ function updateCurrentQuestion(status) {
currentProcessingStatus.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
currentProcessingStatus.className = 'processing-status processing';
- // Show progress info
- const progressText = `Processing example ${status.completed_examples + 1} of ${status.total_examples}`;
+ // Show progress info - show what's actually completed, not what's "next"
+ const progressText = `Completed ${status.completed_examples} of ${status.total_examples} examples`;
currentQuestionText.textContent = progressText;
- currentDataset.textContent = 'Active';
- currentExampleId.textContent = `Example ${status.completed_examples + 1}`;
+ currentDataset.textContent = status.completed_examples < status.total_examples ? 'Active' : 'Completed';
+ currentExampleId.textContent = `${status.completed_examples}/${status.total_examples} processed`;
} else if (status.status === 'completed') {
currentProcessingStatus.innerHTML = '<i class="fas fa-check-circle"></i> Benchmark completed!';
currentProcessingStatus.className = 'processing-status completed';
diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.py
index 759d57cb39..01d72a9eca 100644
--- a/src/local_deep_research/web_search_engines/search_engine_base.py
+++ b/src/local_deep_research/web_search_engines/search_engine_base.py
@@ -177,22 +177,15 @@ class BaseSearchEngine(ABC):
if not self.programmatic_mode:
from ..metrics.search_tracker import get_search_tracker
- tracker = get_search_tracker()
-
# For thread-safe context propagation: if we have research_context parameter, use it
# Otherwise, try to inherit from current thread context (normal case)
# This allows strategies running in threads to explicitly pass context when needed
if research_context:
# Explicit context provided - use it and set it for this thread
set_search_context(research_context)
- else:
- # Search tracker will not work without research context.
- logger.debug("Search metrics tracking disabled: no context.")
- tracker = None
- else:
- logger.debug(
- "Search metrics tracking disabled in programmatic mode"
- )
+
+ # Get tracker after context is set (either from parameter or thread)
+ tracker = get_search_tracker()
engine_name = self.__class__.__name__.replace(
"SearchEngine", ""