~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
fix: UnboundLocalError, infinite recursion in get_stats, N+1 queries
LearningCircuit38637f9835f3
diff --git a/src/local_deep_research/metrics/token_counter.py b/src/local_deep_research/metrics/token_counter.pyindex a3079acb4f..5a48372aaa 100644--- a/src/local_deep_research/metrics/token_counter.py+++ b/src/local_deep_research/metrics/token_counter.py@@ -1039,6 +1039,16 @@ class TokenCounter:row.engine_type for row in engine_types_query.all()]+ # Batch-load all estimates (fix N+1 query)+ estimates_map = {}+ if engine_types:+ all_estimates = (+ session.query(RateLimitEstimate)+ .filter(RateLimitEstimate.engine_type.in_(engine_types))+ .all()+ )+ estimates_map = {e.engine_type: e for e in all_estimates}+for engine_type in engine_types:engine_attempts_list = [a for a in attempts if a.engine_type == engine_type@@ -1049,11 +1059,7 @@ class TokenCounter:)# Get estimate if exists- estimate = (- session.query(RateLimitEstimate)- .filter(RateLimitEstimate.engine_type == engine_type)- .first()- )+ estimate = estimates_map.get(engine_type)# Calculate recent success raterecent_success_rate = (diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.pyindex 86f64484c0..8fcb7c3a66 100644--- a/src/local_deep_research/web/routes/metrics_routes.py+++ b/src/local_deep_research/web/routes/metrics_routes.py@@ -335,24 +335,36 @@ def get_link_analytics(period="30d", username=None):for domain, classification in domain_classifications_map.items()}- # Get research details for top domains+ # Batch-load research details for top domains (fix N+1 query)+ all_research_ids = []+ domain_research_id_lists = {}for domain, _ in top_10_domains:if domain in domain_researches:- research_ids = list(domain_researches[domain])[- :3- ] # Get up to 3 recent researches- researches = (- session.query(ResearchHistory)- .filter(ResearchHistory.id.in_(research_ids))- .all()- )- domain_recent_research[domain] = [- {- "id": r.id,- "query": r.query[:50] if r.query else "Research",- }- for r in researches- ]+ ids = list(domain_researches[domain])[:3]+ domain_research_id_lists[domain] = ids+ all_research_ids.extend(ids)++ research_by_id = {}+ if all_research_ids:+ researches = (+ session.query(ResearchHistory)+ .filter(ResearchHistory.id.in_(all_research_ids))+ .all()+ )+ research_by_id = {r.id: r for r in researches}++ for domain, ids in domain_research_id_lists.items():+ domain_recent_research[domain] = [+ {+ "id": r_id,+ "query": research_by_id[r_id].query[:50]+ if research_by_id.get(r_id)+ and research_by_id[r_id].query+ else "Research",+ }+ for r_id in ids+ if r_id in research_by_id+ ]return {"link_analytics": {diff --git a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py b/src/local_deep_research/web_search_engines/rate_limiting/tracker.pyindex 6daa686d10..ae2e2fb96c 100644--- a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py+++ b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py@@ -526,6 +526,35 @@ class AdaptiveRateLimitTracker:f"(success rate: {success_rate:.1%})")+ def _get_in_memory_stats(+ self, engine_type: Optional[str] = None+ ) -> List[Tuple[str, float, float, float, float, int, float]]:+ """Return stats from in-memory caches (no DB access)."""+ with self._cache_lock:+ stats = []+ engines_to_check = (+ [engine_type]+ if engine_type+ else list(self.current_estimates.keys())+ )+ for engine in engines_to_check:+ if engine in self.current_estimates:+ est = self.current_estimates[engine]+ attempts = self.recent_attempts.get(engine)+ attempt_count = len(attempts) if attempts else 0+ stats.append(+ (+ engine,+ est["base"],+ est["min"],+ est["max"],+ time.time(),+ attempt_count,+ est.get("confidence", 0.0),+ )+ )+ return stats+def get_stats(self, engine_type: Optional[str] = None) -> List[Tuple[str, float, float, float, float, int, float]]:@@ -541,35 +570,11 @@ class AdaptiveRateLimitTracker:# Skip database operations in test/fallback modeif use_fallback_llm() or is_ci_environment():logger.debug("Skipping database stats in test/CI mode")- # Return stats from in-memory estimates- with self._cache_lock:- stats = []- engines_to_check = (- [engine_type]- if engine_type- else list(self.current_estimates.keys())- )- for engine in engines_to_check:- if engine in self.current_estimates:- est = self.current_estimates[engine]- attempts = self.recent_attempts.get(engine)- attempt_count = len(attempts) if attempts else 0- stats.append(- (- engine,- est["base"],- est["min"],- est["max"],- time.time(),- attempt_count,- est.get("confidence", 0.0),- )- )- return stats+ return self._get_in_memory_stats(engine_type)# Skip database operations in programmatic modeif self.programmatic_mode:- return stats+ return self._get_in_memory_stats(engine_type)try:db_imports = _get_db_imports()@@ -605,7 +610,7 @@ class AdaptiveRateLimitTracker:except Exception as e:logger.warning(f"Failed to get rate limit stats from DB: {e}")# Return in-memory stats as fallback- return self.get_stats(engine_type)+ return self._get_in_memory_stats(engine_type)def reset_engine(self, engine_type: str) -> None:"""diff --git a/tests/web_search_engines/rate_limiting/test_tracker_quality_stats.py b/tests/web_search_engines/rate_limiting/test_tracker_quality_stats.pyindex 19a0c0acb1..6a782c8001 100644--- a/tests/web_search_engines/rate_limiting/test_tracker_quality_stats.py+++ b/tests/web_search_engines/rate_limiting/test_tracker_quality_stats.py@@ -500,21 +500,31 @@ class TestGetStatsProgrammaticMode:"local_deep_research.web_search_engines.rate_limiting.tracker.is_ci_environment",return_value=False,)- def test_get_stats_programmatic_mode_bug(self, _mock_ci, _mock_fb):- """BUG: programmatic_mode=True + non-CI → NameError on 'stats'.+ def test_get_stats_programmatic_mode_returns_in_memory_stats(+ self, _mock_ci, _mock_fb+ ):+ """programmatic_mode=True + non-CI returns in-memory stats."""+ tracker = _make_tracker()++ # Pre-populate in-memory data+ with tracker._cache_lock:+ tracker.current_estimates["test_engine"] = {+ "base": 1.0,+ "min": 0.5,+ "max": 2.0,+ "confidence": 0.9,+ }+ tracker.recent_attempts["test_engine"] = [1, 2, 3]- Line 558 does `return stats` but `stats` is only defined inside- the `if use_fallback_llm() or is_ci_environment():` block (line 534).- When that block is skipped, `stats` is undefined.- """- tracker = _make_tracker()-- # This should raise NameError because of the bug at line 558- try:- tracker.get_stats()- # If it doesn't raise, the bug has been fixed- except NameError:- pass # Expected: confirms the bug exists+ result = tracker.get_stats()+ assert len(result) == 1+ engine, base, min_w, max_w, _, attempts, confidence = result[0]+ assert engine == "test_engine"+ assert base == 1.0+ assert min_w == 0.5+ assert max_w == 2.0+ assert attempts == 3+ assert confidence == 0.9# ── cleanup_old_data ────────────────────────────────────────────────