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: add per-user isolation to search cache keys (#2866)

LearningCircuit7a36ca5e9283
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index 49ab2961a4..060bac74eb 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -337,6 +337,7 @@ def generate_report(
searches_per_section: int = 2,
retrievers: dict[str, Any] | None = None,
llms: dict[str, Any] | None = None,
+ username: str | None = None,
provider: str | None = None,
api_key: str | None = None,
temperature: float | None = None,
@@ -430,9 +431,25 @@ def generate_report(
register_llm(name, llm_instance)
logger.info(f"Registered {len(llms)} LLMs: {list(llms.keys())}")
+ import uuid
+
+ search_context = {
+ "research_id": str(uuid.uuid4()),
+ "research_query": query,
+ "research_mode": "report",
+ "research_phase": "init",
+ "search_iteration": 0,
+ "search_engine_selected": kwargs.get("search_tool"),
+ "username": username,
+ "user_password": kwargs.get("user_password"),
+ }
+ set_search_context(search_context)
+
system = None
try:
- system = _init_search_system(retrievers=retrievers, llms=llms, **kwargs)
+ system = _init_search_system(
+ retrievers=retrievers, llms=llms, username=username, **kwargs
+ )
# Set progress callback if provided
if progress_callback:
system.set_progress_callback(progress_callback)
@@ -466,6 +483,7 @@ def generate_report(
finally:
if system is not None:
_close_system(system)
+ clear_search_context()
@no_db_settings
@@ -474,6 +492,7 @@ def detailed_research(
research_id: str | None = None,
retrievers: dict[str, Any] | None = None,
llms: dict[str, Any] | None = None,
+ username: str | None = None,
**kwargs: Any,
) -> dict[str, Any]:
"""
@@ -486,6 +505,7 @@ def detailed_research(
research_id: Optional research ID (int or UUID string) for tracking metrics
retrievers: Optional dictionary of {name: retriever} pairs to use as search engines
llms: Optional dictionary of {name: llm} pairs to use as language models
+ username: Optional username for per-user cache isolation
**kwargs: Configuration for the search system
Returns:
@@ -524,13 +544,17 @@ def detailed_research(
"research_phase": "init",
"search_iteration": 0,
"search_engine_selected": kwargs.get("search_tool"),
+ "username": username,
+ "user_password": kwargs.get("user_password"),
}
set_search_context(search_context)
system = None
try:
# Initialize system
- system = _init_search_system(retrievers=retrievers, llms=llms, **kwargs)
+ system = _init_search_system(
+ retrievers=retrievers, llms=llms, username=username, **kwargs
+ )
# Perform detailed research
results = system.analyze_topic(query)
diff --git a/src/local_deep_research/utilities/search_cache.py b/src/local_deep_research/utilities/search_cache.py
index c69ab59adc..7e61293ae7 100644
--- a/src/local_deep_research/utilities/search_cache.py
+++ b/src/local_deep_research/utilities/search_cache.py
@@ -18,6 +18,7 @@ from sqlalchemy.orm import sessionmaker
from ..config.paths import get_cache_directory
from ..database.models import Base, SearchCache as SearchCacheModel
+from .thread_context import get_search_context
class SearchCache:
@@ -92,12 +93,19 @@ class SearchCache:
def _get_query_hash(
self, query: str, search_engine: str = "default"
) -> str:
- """Generate hash for query + search engine combination."""
+ """Generate hash for query + search engine + username combination.
+
+ Incorporates the current user's username into the hash so that
+ different users' cached results are isolated from each other.
+ """
normalized_query = self._normalize_query(query)
- cache_key = f"{search_engine}:{normalized_query}"
- return hashlib.md5( # DevSkim: ignore DS126858
- cache_key.encode(), usedforsecurity=False
- ).hexdigest()
+ # Get username from thread context for per-user cache isolation
+ username = ""
+ context = get_search_context()
+ if context:
+ username = context.get("username", "") or ""
+ cache_key = f"{username}:{search_engine}:{normalized_query}"
+ return hashlib.sha256(cache_key.encode()).hexdigest()
def _cleanup_expired(self):
"""Remove expired entries from database."""
diff --git a/tests/utilities/test_search_cache_high_value.py b/tests/utilities/test_search_cache_high_value.py
index 1cc31e5484..018ff693f0 100644
--- a/tests/utilities/test_search_cache_high_value.py
+++ b/tests/utilities/test_search_cache_high_value.py
@@ -103,31 +103,28 @@ class TestNormalizeQueryHighValue:
class TestGetQueryHashHighValue:
"""Edge-case and determinism tests for _get_query_hash."""
- def test_hash_is_md5_hex_string(self):
- """Hash output is a 32-char lowercase hex string (MD5)."""
+ def test_hash_is_sha256_hex_string(self):
+ """Hash output is a 64-char lowercase hex string (SHA-256)."""
cache = _make_cache()
result = cache._get_query_hash("test")
- assert len(result) == 32
+ assert len(result) == 64
assert all(c in "0123456789abcdef" for c in result)
- def test_hash_matches_manual_md5(self):
- """Hash matches manually computed MD5 of 'engine:normalized_query'."""
+ def test_hash_matches_manual_sha256(self):
+ """Hash matches manually computed SHA-256 of 'username:engine:normalized_query'."""
cache = _make_cache()
result = cache._get_query_hash("Hello World", search_engine="google")
- expected_input = "google:hello world"
- expected = hashlib.md5(
- expected_input.encode(), usedforsecurity=False
- ).hexdigest()
+ # No search context set, so username is empty string
+ expected_input = ":google:hello world"
+ expected = hashlib.sha256(expected_input.encode()).hexdigest()
assert result == expected
def test_default_engine_is_default(self):
"""Default search_engine parameter is 'default'."""
cache = _make_cache()
result = cache._get_query_hash("test")
- expected_input = "default:test"
- expected = hashlib.md5(
- expected_input.encode(), usedforsecurity=False
- ).hexdigest()
+ expected_input = ":default:test"
+ expected = hashlib.sha256(expected_input.encode()).hexdigest()
assert result == expected
def test_empty_query_hashes_consistently(self):
@@ -136,7 +133,7 @@ class TestGetQueryHashHighValue:
h1 = cache._get_query_hash("")
h2 = cache._get_query_hash("")
assert h1 == h2
- assert len(h1) == 32
+ assert len(h1) == 64
def test_same_query_different_engines_differ(self):
"""Same normalized query with different engines yields different hashes."""
@@ -159,6 +156,60 @@ class TestGetQueryHashHighValue:
hashes = {cache._get_query_hash(v) for v in variants}
assert len(hashes) == 1
+ def test_different_users_produce_different_hashes(self):
+ """Different usernames in search context yield different cache keys."""
+ from local_deep_research.utilities.thread_context import (
+ set_search_context,
+ clear_search_context,
+ )
+
+ cache = _make_cache()
+
+ set_search_context({"username": "alice"})
+ hash_alice = cache._get_query_hash("test query", "google")
+ clear_search_context()
+
+ set_search_context({"username": "bob"})
+ hash_bob = cache._get_query_hash("test query", "google")
+ clear_search_context()
+
+ assert hash_alice != hash_bob
+
+ def test_no_context_matches_empty_username(self):
+ """No search context produces same hash as empty-string username."""
+ from local_deep_research.utilities.thread_context import (
+ set_search_context,
+ clear_search_context,
+ )
+
+ cache = _make_cache()
+
+ # No context set
+ clear_search_context()
+ hash_no_ctx = cache._get_query_hash("test query")
+
+ # Empty username
+ set_search_context({"username": ""})
+ hash_empty = cache._get_query_hash("test query")
+ clear_search_context()
+
+ assert hash_no_ctx == hash_empty
+
+ def test_same_user_same_query_produces_same_hash(self):
+ """Same user + same query always produces the same hash."""
+ from local_deep_research.utilities.thread_context import (
+ set_search_context,
+ clear_search_context,
+ )
+
+ cache = _make_cache()
+ set_search_context({"username": "alice"})
+ h1 = cache._get_query_hash("test query", "google")
+ h2 = cache._get_query_hash("test query", "google")
+ clear_search_context()
+
+ assert h1 == h2
+
# ===========================================================================
# _evict_lru_memory