~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
refactor(metrics): context overflow cleanup (#3801)
LearningCircuitc30168e667b6
diff --git a/src/local_deep_research/web/routes/context_overflow_api.py b/src/local_deep_research/web/routes/context_overflow_api.pyindex 1e569eb40d..ba532e32b3 100644--- a/src/local_deep_research/web/routes/context_overflow_api.py+++ b/src/local_deep_research/web/routes/context_overflow_api.py@@ -56,8 +56,8 @@ def get_context_overflow_metrics():if start_date:query = query.filter(TokenUsage.timestamp >= start_date)- # Get overview statistics - merge count queries using CASE- overview_counts = query.with_entities(+ # --- Merged scalar aggregates (was 3 separate queries) ---+ overview_row = query.with_entities(func.count(TokenUsage.id).label("total_requests"),func.sum(case(@@ -71,36 +71,15 @@ def get_context_overflow_metrics():else_=0,)).label("truncated_requests"),- ).first()-- total_requests = overview_counts.total_requests or 0- requests_with_context = int(- overview_counts.requests_with_context or 0- )- truncated_requests = int(overview_counts.truncated_requests or 0)-- # Calculate truncation rate- truncation_rate: float = 0- if requests_with_context > 0:- truncation_rate = (- truncated_requests / requests_with_context- ) * 100-- # Get average tokens truncated- avg_tokens_truncated = session.query(- func.avg(TokenUsage.tokens_truncated)- ).filter(TokenUsage.context_truncated.is_(True))-- if start_date:- avg_tokens_truncated = avg_tokens_truncated.filter(- TokenUsage.timestamp >= start_date- )-- avg_tokens_truncated = avg_tokens_truncated.scalar() or 0-- # --- Token summary (always populated, no context_limit filter) ---- token_summary_row = query.with_entities(- func.count(TokenUsage.id).label("total_requests"),+ func.avg(+ case(+ (+ TokenUsage.context_truncated.is_(True),+ TokenUsage.tokens_truncated,+ ),+ else_=None,+ )+ ).label("avg_tokens_truncated"),func.coalesce(func.sum(TokenUsage.total_tokens), 0).label("total_tokens"),@@ -117,24 +96,33 @@ def get_context_overflow_metrics():func.max(TokenUsage.prompt_tokens).label("max_prompt_tokens"),).first()+ total_requests = overview_row.total_requests or 0+ requests_with_context = int(overview_row.requests_with_context or 0)+ truncated_requests = int(overview_row.truncated_requests or 0)+ avg_tokens_truncated = overview_row.avg_tokens_truncated or 0++ truncation_rate: float = 0+ if requests_with_context > 0:+ truncation_rate = (+ truncated_requests / requests_with_context+ ) * 100+token_summary = {- "total_requests": token_summary_row.total_requests or 0,- "total_tokens": int(token_summary_row.total_tokens or 0),+ "total_requests": total_requests,+ "total_tokens": int(overview_row.total_tokens or 0),"total_prompt_tokens": int(- token_summary_row.total_prompt_tokens or 0+ overview_row.total_prompt_tokens or 0),"total_completion_tokens": int(- token_summary_row.total_completion_tokens or 0+ overview_row.total_completion_tokens or 0),"avg_prompt_tokens": round(- token_summary_row.avg_prompt_tokens or 0, 0+ overview_row.avg_prompt_tokens or 0, 0),"avg_completion_tokens": round(- token_summary_row.avg_completion_tokens or 0, 0- ),- "max_prompt_tokens": int(- token_summary_row.max_prompt_tokens or 0+ overview_row.avg_completion_tokens or 0, 0),+ "max_prompt_tokens": int(overview_row.max_prompt_tokens or 0),}# --- Model token stats (always populated, no context_limit filter) ---diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.pyindex 022f7d6077..ad534f19a3 100644--- a/src/local_deep_research/web/routes/metrics_routes.py+++ b/src/local_deep_research/web/routes/metrics_routes.py@@ -302,7 +302,7 @@ def get_link_analytics(period="30d", username=None):domain_connections[research_id].append(domain)except Exception:- logger.warning(f"Error parsing URL {resource.url}")+ logger.exception(f"Error parsing URL {resource.url}")# Sort domains by count and get top 10sorted_domains = sorted(@@ -873,7 +873,7 @@ def api_metrics():"total_ratings": total_ratings,}except Exception:- logger.warning("Error getting user satisfaction data")+ logger.exception("Error getting user satisfaction data")user_satisfaction = {"avg_rating": None, "total_ratings": 0}# Get strategy analytics@@ -945,7 +945,7 @@ def api_metrics():"avg_tokens_truncated": int(avg_tokens),}except Exception:- logger.warning(+ logger.exception("Error getting context overflow summary for /api/metrics")diff --git a/src/local_deep_research/web/templates/pages/context_overflow.html b/src/local_deep_research/web/templates/pages/context_overflow.htmlindex 53f7b9e488..c7227e3a94 100644--- a/src/local_deep_research/web/templates/pages/context_overflow.html+++ b/src/local_deep_research/web/templates/pages/context_overflow.html@@ -255,7 +255,7 @@// Empty state: has context data but no truncation events (positive signal)// Also checks chart_data for high-utilization requests (>80%) since the backend- // only flags context_truncated at 95% threshold but the chart warns at 80%.+ // only flags context_truncated at 80% threshold which is the same as the chart warning.const highUtilCount = (chart_data || []).filter(d => {if (!d.context_limit) return false;const original = d.original_prompt_tokens || d.prompt_tokens || 0;@@ -915,7 +915,7 @@${escapeHtml(req.research_query || 'N/A')}</td><td>${escapeHtml(formatModelName(req.model))}</td>- <td>${formatNumber(req.actual_tokens || req.prompt_tokens)}</td>+ <td>${formatNumber(req.prompt_tokens)}</td><td><span class="ldr-context-limit-badge">${formatNumber(req.context_limit)}</span></td><td class="ldr-text-error" style="font-weight: 600;">${formatNumber(req.tokens_truncated || 0)}</td><td>diff --git a/tests/web/routes/test_context_overflow_api_http.py b/tests/web/routes/test_context_overflow_api_http.pyindex e75dbef0cc..ac6fb536e3 100644--- a/tests/web/routes/test_context_overflow_api_http.py+++ b/tests/web/routes/test_context_overflow_api_http.py@@ -103,6 +103,35 @@ def _authenticated_client(app):p.stop()+# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++_TOKEN_SUMMARY_FIELDS = (+ "total_tokens",+ "total_prompt_tokens",+ "total_completion_tokens",+ "avg_prompt_tokens",+ "avg_completion_tokens",+ "max_prompt_tokens",+)+++def _wire_first(mock_query, overview_row, token_row, avg_tokens_truncated=0):+ """Wire mock_query.first() for the merged single-query route.++ The route now issues one .first() returning a row that combines the old+ overview_counts + token_summary_row + AVG(tokens_truncated) scalar.+ Tests still construct two separate mocks for readability; this helper+ merges token_row's fields onto overview_row and wires the single call.+ """+ for field in _TOKEN_SUMMARY_FIELDS:+ setattr(overview_row, field, getattr(token_row, field))+ overview_row.avg_tokens_truncated = avg_tokens_truncated+ mock_query.first.return_value = overview_row++# ---------------------------------------------------------------------------# GET /api/context-overflow# ---------------------------------------------------------------------------@@ -145,16 +174,7 @@ class TestGetContextOverflowMetrics:token_row.avg_completion_tokens = 60.0token_row.max_prompt_tokens = 200- # with_entities().first() should return our mocked rows- call_count = [0]-- def multi_first():- call_count[0] += 1- if call_count[0] == 1:- return overview_row- return token_row-- mock_query.first.side_effect = multi_first+ _wire_first(mock_query, overview_row, token_row)resp = client.get("/api/context-overflow")assert resp.status_code == 200@@ -179,16 +199,7 @@ class TestGetContextOverflowMetrics:max_prompt_tokens=0,)- call_count = [0]-- def multi_first():- call_count[0] += 1- if call_count[0] == 1:- return overview_row- return token_row-- mock_query.first.side_effect = multi_first- mock_query.scalar.return_value = 0+ _wire_first(mock_query, overview_row, token_row)resp = client.get("/api/context-overflow?period=7d")assert resp.status_code == 200@@ -209,14 +220,7 @@ class TestGetContextOverflowMetrics:avg_completion_tokens=0,max_prompt_tokens=0,)- call_count = [0]-- def multi_first():- call_count[0] += 1- return overview_row if call_count[0] == 1 else token_row-- mock_query.first.side_effect = multi_first- mock_query.scalar.return_value = 0+ _wire_first(mock_query, overview_row, token_row)resp = client.get("/api/context-overflow?period=all")assert resp.status_code == 200@@ -237,14 +241,7 @@ class TestGetContextOverflowMetrics:avg_completion_tokens=0,max_prompt_tokens=0,)- call_count = [0]-- def multi_first():- call_count[0] += 1- return overview_row if call_count[0] == 1 else token_row-- mock_query.first.side_effect = multi_first- mock_query.scalar.return_value = 0+ _wire_first(mock_query, overview_row, token_row)resp = client.get("/api/context-overflow?period=invalid")assert resp.status_code == 200@@ -265,14 +262,7 @@ class TestGetContextOverflowMetrics:avg_completion_tokens=0,max_prompt_tokens=0,)- call_count = [0]-- def multi_first():- call_count[0] += 1- return overview_row if call_count[0] == 1 else token_row-- mock_query.first.side_effect = multi_first- mock_query.scalar.return_value = 0+ _wire_first(mock_query, overview_row, token_row)resp = client.get("/api/context-overflow?page=2&per_page=10")assert resp.status_code == 200@@ -296,14 +286,7 @@ class TestGetContextOverflowMetrics:avg_completion_tokens=0,max_prompt_tokens=0,)- call_count = [0]-- def multi_first():- call_count[0] += 1- return overview_row if call_count[0] == 1 else token_row-- mock_query.first.side_effect = multi_first- mock_query.scalar.return_value = 0+ _wire_first(mock_query, overview_row, token_row)resp = client.get("/api/context-overflow?per_page=999")assert resp.status_code == 200@@ -326,14 +309,7 @@ class TestGetContextOverflowMetrics:avg_completion_tokens=0,max_prompt_tokens=0,)- call_count = [0]-- def multi_first():- call_count[0] += 1- return overview_row if call_count[0] == 1 else token_row-- mock_query.first.side_effect = multi_first- mock_query.scalar.return_value = 0+ _wire_first(mock_query, overview_row, token_row)resp = client.get("/api/context-overflow?per_page=-5")assert resp.status_code == 200diff --git a/tests/web/routes/test_context_overflow_coverage.py b/tests/web/routes/test_context_overflow_coverage.pyindex 13bb85401e..6912c1597c 100644--- a/tests/web/routes/test_context_overflow_coverage.py+++ b/tests/web/routes/test_context_overflow_coverage.py@@ -190,11 +190,8 @@ def _build_main_endpoint_session(Exact call order in the source (get_context_overflow_metrics):.first() calls:- 1. overview_counts (query.with_entities(...).first())- 2. token_summary_row (query.with_entities(...).first())-- .scalar() calls:- 1. avg_tokens_truncated (session.query(func.avg(...)).filter(...).scalar())+ 1. overview_row — merged scalar aggregates: counts ++ AVG(tokens_truncated) + token-summary sums/avgs (single query)..all() calls:1. model_token_query (query.with_entities(...).group_by(...).all())@@ -229,11 +226,18 @@ def _build_main_endpoint_session(query = _make_chainable_query()- # .first() — call 1: overview_counts, call 2: token_summary_row- query.first.side_effect = [overview_row, token_summary_row]-- # .scalar() — call 1: avg_tokens_truncated- query.scalar.side_effect = [avg_tokens_scalar]+ # The route now issues a single .first() call returning a row with all+ # overview + token-summary + avg_tokens_truncated fields combined.+ overview_row.total_tokens = token_summary_row.total_tokens+ overview_row.total_prompt_tokens = token_summary_row.total_prompt_tokens+ overview_row.total_completion_tokens = (+ token_summary_row.total_completion_tokens+ )+ overview_row.avg_prompt_tokens = token_summary_row.avg_prompt_tokens+ overview_row.avg_completion_tokens = token_summary_row.avg_completion_tokens+ overview_row.max_prompt_tokens = token_summary_row.max_prompt_tokens+ overview_row.avg_tokens_truncated = avg_tokens_scalar+ query.first.return_value = overview_row# .count() — call 1: all_requests_totalquery.count.side_effect = [all_requests_count]diff --git a/tests/web/routes/test_context_overflow_logic.py b/tests/web/routes/test_context_overflow_logic.pyindex bef9c64744..ae43f66ec0 100644--- a/tests/web/routes/test_context_overflow_logic.py+++ b/tests/web/routes/test_context_overflow_logic.py@@ -94,14 +94,17 @@ def _make_overview_and_token_rows(requests_with_context=0,truncated_requests=0,):- """Create overview + token_summary mock rows."""+ """Create the merged overview row (counts + AVG + token-summary fields).++ The route now issues a single .first() call. The legacy two-row return+ shape is kept so existing call sites don't change — `tk` is the same+ object as `ov`, since fields are merged onto a single mock.+ """overview_row = Mock(total_requests=total_requests,requests_with_context=requests_with_context,truncated_requests=truncated_requests,- )- token_row = Mock(- total_requests=total_requests,+ avg_tokens_truncated=0,total_tokens=0,total_prompt_tokens=0,total_completion_tokens=0,@@ -109,18 +112,12 @@ def _make_overview_and_token_rows(avg_completion_tokens=0,max_prompt_tokens=0,)- return overview_row, token_row+ return overview_row, overview_rowdef _setup_multi_first(mock_query, overview_row, token_row):- """Set up mock_query.first() to return overview, then token row."""- call_count = [0]-- def multi_first():- call_count[0] += 1- return overview_row if call_count[0] == 1 else token_row-- mock_query.first.side_effect = multi_first+ """Wire mock_query.first() to return the (merged) overview row."""+ mock_query.first.return_value = overview_rowmock_query.scalar.return_value = 0