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: address PR #2031 code review feedback

LearningCircuit62bd310a12bc
diff --git a/src/local_deep_research/metrics/token_counter.py b/src/local_deep_research/metrics/token_counter.py
index 993628b809..6ea5a6cb59 100644
--- a/src/local_deep_research/metrics/token_counter.py
+++ b/src/local_deep_research/metrics/token_counter.py
@@ -851,7 +851,7 @@ class TokenCounter:
.all()
)
for model_name, model_provider in provider_results:
- provider_map[model_name] = model_provider
+ provider_map.setdefault(model_name, model_provider)
by_model = []
for stat in model_stats:
diff --git a/src/local_deep_research/utilities/search_cache.py b/src/local_deep_research/utilities/search_cache.py
index 5d035f51c3..52ebe608f7 100644
--- a/src/local_deep_research/utilities/search_cache.py
+++ b/src/local_deep_research/utilities/search_cache.py
@@ -11,7 +11,6 @@ from functools import lru_cache
from pathlib import Path
from typing import Any, Dict, List, Optional
-from cachetools import TTLCache
from loguru import logger
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
@@ -59,14 +58,13 @@ class SearchCache:
self._memory_cache = {}
self._access_times = {}
- # Stampede protection: bounded TTL caches for events, locks, and results
- # TTL of 60 seconds to auto-cleanup stale entries
- self._fetch_events: TTLCache = TTLCache(maxsize=1000, ttl=60)
- self._fetch_locks: TTLCache = TTLCache(maxsize=1000, ttl=60)
+ # Stampede protection: events and locks for each query being fetched
+ self._fetch_events = {} # query_hash -> threading.Event (signals completion)
+ self._fetch_locks = {} # query_hash -> threading.Lock (prevents concurrent fetch)
self._fetch_locks_lock = (
threading.Lock()
) # Protects the fetch dictionaries
- self._fetch_results: TTLCache = TTLCache(maxsize=1000, ttl=60)
+ self._fetch_results = {} # query_hash -> results (temporary storage during fetch)
def _init_db(self):
"""Initialize SQLite database for persistent cache using SQLAlchemy."""
diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.py
index df2927cf32..73c00416d0 100644
--- a/src/local_deep_research/web/routes/metrics_routes.py
+++ b/src/local_deep_research/web/routes/metrics_routes.py
@@ -1,6 +1,7 @@
"""Routes for metrics dashboard."""
from datetime import datetime, timedelta, UTC
+from urllib.parse import urlparse
from flask import Blueprint, jsonify, request, session as flask_session
from loguru import logger
@@ -33,6 +34,18 @@ metrics_bp = Blueprint("metrics", __name__, url_prefix="/metrics")
# if the decorator is ever removed.
+def _extract_domain(url):
+ """Extract normalized domain from URL, stripping www. prefix."""
+ try:
+ parsed = urlparse(url)
+ domain = parsed.netloc.lower()
+ if domain.startswith("www."):
+ domain = domain[4:]
+ return domain if domain else None
+ except (ValueError, AttributeError):
+ return None
+
+
def get_rating_analytics(period="30d", research_mode="all", username=None):
"""Get rating analytics for the specified period and research mode."""
try:
@@ -184,8 +197,6 @@ def get_link_analytics(period="30d", username=None):
}
# Extract domains from URLs
- from urllib.parse import urlparse
-
domain_counts = {}
domain_researches = {} # Track which researches used each domain
source_types = {}
@@ -206,15 +217,9 @@ def get_link_analytics(period="30d", username=None):
all_domains = set()
for resource in resources:
if resource.url:
- try:
- parsed = urlparse(resource.url)
- domain = parsed.netloc.lower()
- if domain.startswith("www."):
- domain = domain[4:]
- if domain:
- all_domains.add(domain)
- except Exception:
- pass
+ domain = _extract_domain(resource.url)
+ if domain:
+ all_domains.add(domain)
# Batch load all domain classifications in one query (fix N+1)
domain_classifications_map = {}
@@ -232,11 +237,9 @@ def get_link_analytics(period="30d", username=None):
for resource in resources:
if resource.url:
try:
- parsed = urlparse(resource.url)
- domain = parsed.netloc.lower()
- # Remove www. prefix
- if domain.startswith("www."):
- domain = domain[4:]
+ domain = _extract_domain(resource.url)
+ if not domain:
+ continue
# Count domains
domain_counts[domain] = domain_counts.get(domain, 0) + 1
@@ -1092,8 +1095,6 @@ def api_research_link_metrics(research_id):
)
# Extract domain information
- from urllib.parse import urlparse
-
domain_counts = {}
# Generic category counting from LLM classifications
@@ -1103,15 +1104,9 @@ def api_research_link_metrics(research_id):
all_domains = set()
for resource in resources:
if resource.url:
- try:
- parsed = urlparse(resource.url)
- domain = parsed.netloc.lower()
- if domain.startswith("www."):
- domain = domain[4:]
- if domain:
- all_domains.add(domain)
- except:
- pass
+ domain = _extract_domain(resource.url)
+ if domain:
+ all_domains.add(domain)
# Batch load all domain classifications in one query (fix N+1)
domain_classifications_map = {}
@@ -1129,10 +1124,9 @@ def api_research_link_metrics(research_id):
for resource in resources:
if resource.url:
try:
- parsed = urlparse(resource.url)
- domain = parsed.netloc.lower()
- if domain.startswith("www."):
- domain = domain[4:]
+ domain = _extract_domain(resource.url)
+ if not domain:
+ continue
domain_counts[domain] = domain_counts.get(domain, 0) + 1
@@ -2157,24 +2151,15 @@ def api_classification_progress():
# Get counts of classified vs unclassified domains
with get_user_db_session(username) as session:
# Count total unique domains
- from urllib.parse import urlparse
-
resources = session.query(ResearchResource.url).distinct().all()
domains = set()
all_domains = []
for (url,) in resources:
if url:
- try:
- parsed = urlparse(url)
- domain = parsed.netloc.lower()
- if domain.startswith("www."):
- domain = domain[4:]
- if domain:
- domains.add(domain)
- except (ValueError, AttributeError):
- # urlparse can raise ValueError for malformed URLs
- continue
+ domain = _extract_domain(url)
+ if domain:
+ domains.add(domain)
all_domains = sorted(list(domains))
total_domains = len(domains)
diff --git a/tests/utilities/test_search_cache_stampede.py b/tests/utilities/test_search_cache_stampede.py
index 26fbf59b03..57ef216481 100644
--- a/tests/utilities/test_search_cache_stampede.py
+++ b/tests/utilities/test_search_cache_stampede.py
@@ -12,7 +12,6 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
from unittest.mock import patch
import pytest
-from cachetools import TTLCache
class TestStampedeProtectionConcurrency:
@@ -648,36 +647,3 @@ class TestCacheInvalidation:
assert len(cache._memory_cache) == 0
assert len(cache._access_times) == 0
-
-
-class TestBoundedTTLCacheStampedeProtection:
- """Tests for bounded TTLCache in stampede protection dicts."""
-
- @pytest.fixture
- def cache(self):
- """Create a fresh cache instance for each test."""
- with tempfile.TemporaryDirectory() as tmpdir:
- from local_deep_research.utilities.search_cache import SearchCache
-
- cache = SearchCache(
- cache_dir=tmpdir, max_memory_items=100, default_ttl=3600
- )
- yield cache
-
- def test_fetch_events_is_ttl_cache(self, cache):
- """Stampede _fetch_events should be a bounded TTLCache."""
- assert isinstance(cache._fetch_events, TTLCache)
- assert cache._fetch_events.maxsize == 1000
- assert cache._fetch_events.ttl == 60
-
- def test_fetch_locks_is_ttl_cache(self, cache):
- """Stampede _fetch_locks should be a bounded TTLCache."""
- assert isinstance(cache._fetch_locks, TTLCache)
- assert cache._fetch_locks.maxsize == 1000
- assert cache._fetch_locks.ttl == 60
-
- def test_fetch_results_is_ttl_cache(self, cache):
- """Stampede _fetch_results should be a bounded TTLCache."""
- assert isinstance(cache._fetch_results, TTLCache)
- assert cache._fetch_results.maxsize == 1000
- assert cache._fetch_results.ttl == 60