~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
chore: remove dead SearchCache utility, deprecate orphaned table (#4621)
LearningCircuitc00f4710b028
diff --git a/bearer.yml b/bearer.ymlindex d13193e967..a1e5bc38e1 100644--- a/bearer.yml+++ b/bearer.yml@@ -27,7 +27,6 @@ rule:## Usage locations:# - research_service.py: Content deduplication hashes- # - search_cache.py: Cache key generation# - benchmark_service.py: Test result identification- python_lang_weak_hash_md5 # DevSkim: ignore DS126858 - this is a rule name, not actual MD5 usagediff --git a/docs/developing/resource-cleanup.md b/docs/developing/resource-cleanup.mdindex 425d14e889..a4cd90a75a 100644--- a/docs/developing/resource-cleanup.md+++ b/docs/developing/resource-cleanup.md@@ -352,11 +352,10 @@ here is the full ledger:##### Minor findings (not steady-state leaks; worth knowing)-- **Daemon threads without explicit shutdown.** `search_cache.py`- cache-cleanup thread, `journal_reputation_filter.py` background- fetcher, `log_utils.py` queue processor. All daemonized — reaped by- the OS at process exit. Not steady-state leaks; no per-request- growth.+- **Daemon threads without explicit shutdown.**+ `journal_reputation_filter.py` background fetcher, `log_utils.py`+ queue processor. All daemonized — reaped by the OS at process exit.+ Not steady-state leaks; no per-request growth.- **Abandoned-research thread on socket disconnect.** If a clientcloses the tab mid-research, the socket subscription is removed butthe research thread keeps running until completion;diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.pyindex 7c9b335b64..5854eeaa41 100644--- a/src/local_deep_research/api/research_functions.py+++ b/src/local_deep_research/api/research_functions.py@@ -296,8 +296,8 @@ def quick_summary("user_password": kwargs.get("user_password"), # Include password for metrics tracking- # Carried so SearchCache._get_query_hash can read the active- # egress scope and avoid cross-scope cache hits.+ # Thread-safe settings snapshot propagated to background search+ # threads (engine config, per-user resolution, egress scope)."settings_snapshot": kwargs.get("settings_snapshot") or {},}set_search_context(search_context)diff --git a/src/local_deep_research/database/models/cache.py b/src/local_deep_research/database/models/cache.pyindex d2a27cc08a..8ca505eb8b 100644--- a/src/local_deep_research/database/models/cache.py+++ b/src/local_deep_research/database/models/cache.py@@ -77,7 +77,16 @@ class Cache(Base):class SearchCache(Base):- """Search cache for storing query results with TTL and LRU eviction."""+ """Search cache for storing query results with TTL and LRU eviction.++ .. deprecated::+ ORPHANED — the ``SearchCache`` utility class that read/wrote this+ table was removed as dead code (its only consumer, an experimental+ search strategy, was deleted in #4420). Nothing reads from or writes+ to this table any longer. The model/table is retained for now to+ avoid a schema migration; removal is tracked in #4620. Do not add new+ users — see the issue before relying on it.+ """__tablename__ = "search_cache"diff --git a/src/local_deep_research/utilities/search_cache.py b/src/local_deep_research/utilities/search_cache.pydeleted file mode 100644index 79e26963a4..0000000000--- a/src/local_deep_research/utilities/search_cache.py+++ /dev/null@@ -1,610 +0,0 @@-"""-Search Cache Utility-Provides intelligent caching for search results to avoid repeated queries.-Includes TTL, LRU eviction, and query normalization.-"""--import atexit-import hashlib-import threading-import time-from functools import lru_cache-from pathlib import Path-from typing import Any, Dict, List, Optional--from loguru import logger-from sqlalchemy import create_engine-from sqlalchemy.engine import Engine-from sqlalchemy.orm import sessionmaker--from ..config.paths import get_cache_directory-from ..database.models import Base, SearchCache as SearchCacheModel-from ..security.egress.policy import DEFAULT_EGRESS_SCOPE-from .thread_context import get_search_context---class SearchCache:- """- Persistent cache for search results with TTL and LRU eviction.- Stores results in SQLite for persistence across sessions.- """-- def __init__(- self,- cache_dir: Optional[str] = None,- max_memory_items: int = 1000,- default_ttl: int = 3600,- ):- """- Initialize search cache.-- Args:- cache_dir: Directory for cache database. Defaults to data/__CACHE_DIR__- max_memory_items: Maximum items in memory cache- default_ttl: Default time-to-live in seconds (1 hour default)- """- self.max_memory_items = max_memory_items- self.default_ttl = default_ttl-- # Setup cache directory- if cache_dir is None:- cache_dir_path: Path = get_cache_directory() / "search_cache"- else:- cache_dir_path = Path(cache_dir)-- cache_dir_path.mkdir(parents=True, exist_ok=True)- self.db_path = cache_dir_path / "search_cache.db"- # Initialize database- self.engine: Optional[Engine] = None- self._init_db()-- # In-memory cache for frequently accessed items- self._memory_cache: Dict[str, Dict[str, Any]] = {}- self._access_times: Dict[str, int] = {}- self._memory_lock = threading.Lock()-- # Stampede protection: events and locks for each query being fetched- #- # Lock ordering (to avoid deadlocks):- # _fetch_locks_lock -> _memory_lock- #- self._fetch_events: Dict[- str, threading.Event- ] = {} # query_hash -> threading.Event (signals completion)- self._fetch_locks: Dict[- str, threading.Lock- ] = {} # query_hash -> threading.Lock (prevents concurrent fetch)- self._fetch_locks_lock = (- threading.Lock()- ) # Protects the fetch dictionaries- self._fetch_results: Dict[- str, Optional[List[Dict[str, Any]]]- ] = {} # query_hash -> results (temporary storage during fetch)-- def _init_db(self):- """Initialize SQLite database for persistent cache using SQLAlchemy."""- try:- # Create engine and session- self.engine = create_engine(f"sqlite:///{self.db_path}")- Base.metadata.create_all(- self.engine, tables=[SearchCacheModel.__table__]- )- self.Session = sessionmaker(bind=self.engine)- except Exception:- logger.exception("Failed to initialize search cache database")-- def _normalize_query(self, query: str) -> str:- """Normalize query for consistent caching."""- # Convert to lowercase and remove extra whitespace- normalized = " ".join(query.lower().strip().split())-- # Remove common punctuation that doesn't affect search- return normalized.replace('"', "").replace("'", "")-- def _get_query_hash(- self, query: str, search_engine: str = "default"- ) -> str:- """Generate hash for query + search engine + username + scope.-- Incorporates the current user's username into the hash so that- different users' cached results are isolated from each other.-- Also incorporates the active egress policy scope, so a- ``scope=BOTH`` cache entry isn't returned to a later- ``scope=PRIVATE_ONLY`` query — that would be a clean policy- bypass via warm cache. Old cached entries (written before this- column existed) miss on lookup and get rewritten naturally.- """- normalized_query = self._normalize_query(query)- # Get username + scope from thread context for per-user,- # per-policy cache isolation.- username = ""- # Default to the registered default scope so that "no search- # context" and "context without a policy snapshot" hash- # identically — both represent the no-policy situation.- scope = DEFAULT_EGRESS_SCOPE- context = get_search_context()- if context:- username = context.get("username", "") or ""- settings_snapshot = context.get("settings_snapshot") or {}- scope_raw = settings_snapshot.get(- "policy.egress_scope", DEFAULT_EGRESS_SCOPE- )- if isinstance(scope_raw, dict) and "value" in scope_raw:- scope_raw = scope_raw["value"]- scope = str(scope_raw or DEFAULT_EGRESS_SCOPE).lower()- cache_key = f"{username}:{scope}:{search_engine}:{normalized_query}"- return hashlib.sha256(cache_key.encode()).hexdigest()-- def _cleanup_expired(self):- """Remove expired entries from database."""- try:- current_time = int(time.time())- with self.Session() as session:- deleted = (- session.query(SearchCacheModel)- .filter(SearchCacheModel.expires_at < current_time)- .delete()- )- session.commit()- if deleted > 0:- logger.debug(f"Cleaned up {deleted} expired cache entries")- except Exception:- logger.exception("Failed to cleanup expired cache entries")-- def _evict_lru_memory(self):- """Evict least recently used items from memory cache.-- Must be called with ``self._memory_lock`` already held.- """- if len(self._memory_cache) <= self.max_memory_items:- return-- # Sort by access time and remove oldest- sorted_items = sorted(self._access_times.items(), key=lambda x: x[1])- items_to_remove = (- len(self._memory_cache) - self.max_memory_items + 100- ) # Remove extra for efficiency-- for query_hash, _ in sorted_items[:items_to_remove]:- self._memory_cache.pop(query_hash, None)- self._access_times.pop(query_hash, None)-- def get(- self, query: str, search_engine: str = "default"- ) -> Optional[List[Dict[str, Any]]]:- """- Get cached search results for a query.-- Args:- query: Search query- search_engine: Search engine identifier for cache partitioning-- Returns:- Cached results or None if not found/expired- """- query_hash = self._get_query_hash(query, search_engine)- current_time = int(time.time())-- # Check memory cache first- with self._memory_lock:- if query_hash in self._memory_cache:- entry = self._memory_cache[query_hash]- if entry["expires_at"] > current_time:- self._access_times[query_hash] = current_time- logger.debug(- f"Cache hit (memory) for query: {query[:50]}..."- )- return entry["results"]- # Expired, remove from memory- self._memory_cache.pop(query_hash, None)- self._access_times.pop(query_hash, None)-- # Check database cache- try:- with self.Session() as session:- cache_entry = (- session.query(SearchCacheModel)- .filter(- SearchCacheModel.query_hash == query_hash,- SearchCacheModel.expires_at > current_time,- )- .first()- )-- if cache_entry:- results = cache_entry.results-- # Update access statistics- cache_entry.access_count += 1- cache_entry.last_accessed = current_time- session.commit()-- # Add to memory cache- with self._memory_lock:- self._memory_cache[query_hash] = {- "results": results,- "expires_at": cache_entry.expires_at,- }- self._access_times[query_hash] = current_time- self._evict_lru_memory()-- logger.debug(- f"Cache hit (database) for query: {query[:50]}..."- )- return results-- except Exception:- logger.exception("Failed to retrieve from search cache")-- logger.debug(f"Cache miss for query: {query[:50]}...")- return None-- def put(- self,- query: str,- results: List[Dict[str, Any]],- search_engine: str = "default",- ttl: Optional[int] = None,- ) -> bool:- """- Store search results in cache.-- Args:- query: Search query- results: Search results to cache- search_engine: Search engine identifier- ttl: Time-to-live in seconds (uses default if None)-- Returns:- True if successfully cached- """- if not results: # Don't cache empty results- return False-- query_hash = self._get_query_hash(query, search_engine)- current_time = int(time.time())- expires_at = current_time + (ttl or self.default_ttl)-- try:- # Store in database- with self.Session() as session:- # Check if entry exists- existing = (- session.query(SearchCacheModel)- .filter_by(query_hash=query_hash)- .first()- )-- if existing:- # Update existing entry- existing.query_text = self._normalize_query(query) # type: ignore[assignment]- existing.results = results # type: ignore[assignment]- existing.created_at = current_time # type: ignore[assignment]- existing.expires_at = expires_at # type: ignore[assignment]- existing.access_count = 1 # type: ignore[assignment]- existing.last_accessed = current_time # type: ignore[assignment]- else:- # Create new entry- cache_entry = SearchCacheModel(- query_hash=query_hash,- query_text=self._normalize_query(query),- results=results,- created_at=current_time,- expires_at=expires_at,- access_count=1,- last_accessed=current_time,- )- session.add(cache_entry)-- session.commit()-- # Store in memory cache- with self._memory_lock:- self._memory_cache[query_hash] = {- "results": results,- "expires_at": expires_at,- }- self._access_times[query_hash] = current_time- self._evict_lru_memory()-- logger.debug(f"Cached results for query: {query[:50]}...")- return True-- except Exception:- logger.exception("Failed to store in search cache")- return False-- def get_or_fetch(- self,- query: str,- fetch_func,- search_engine: str = "default",- ttl: Optional[int] = None,- ) -> Optional[List[Dict[str, Any]]]:- """- Get cached results or fetch with stampede protection.-- This is the recommended way to use the cache. It ensures only one thread- fetches data for a given query, preventing cache stampedes.-- Args:- query: Search query- fetch_func: Function to call if cache miss (should return results list)- search_engine: Search engine identifier- ttl: Time-to-live for cached results-- Returns:- Search results (from cache or freshly fetched)- """- query_hash = self._get_query_hash(query, search_engine)-- # Try to get from cache first- results = self.get(query, search_engine)- if results is not None:- return results-- # Acquire lock for this query to prevent stampede- fetch_lock = None # set inside _fetch_locks_lock- fetch_event = None # set inside _fetch_locks_lock- with self._fetch_locks_lock:- # Double-check after acquiring lock- results = self.get(query, search_engine)- if results is not None:- return results-- # Check if another thread started fetching while we waited- event: Optional[threading.Event] = None- if query_hash in self._fetch_events:- existing_event = self._fetch_events[query_hash]- # Check if this is a stale event (already set means fetch completed)- if existing_event.is_set():- # Previous fetch completed, clean up and start fresh- del self._fetch_events[query_hash]- del self._fetch_locks[query_hash]- if query_hash in self._fetch_results:- del self._fetch_results[query_hash]- # Create new event/lock for this fetch- event = threading.Event()- self._fetch_events[query_hash] = event- self._fetch_locks[query_hash] = threading.Lock()- # Capture references while still holding _fetch_locks_lock- fetch_lock = self._fetch_locks[query_hash]- fetch_event = event- event = None # Signal we should fetch- else:- # Another thread is actively fetching- event = existing_event- else:- # We are the first thread to fetch this query- event = threading.Event()- self._fetch_events[query_hash] = event- self._fetch_locks[query_hash] = threading.Lock()- # Capture references while still holding _fetch_locks_lock- fetch_lock = self._fetch_locks[query_hash]- fetch_event = event- event = None # Signal we should fetch-- # If another thread is fetching, wait for it- if event is not None:- event.wait(timeout=30)- with self._fetch_locks_lock:- result = self._fetch_results.get(query_hash)- if result is not None:- return result- # Re-check cache, and if still miss, return None (fetch failed)- return self.get(query, search_engine)-- # We are the thread that should fetch (fetch_lock/fetch_event were- # captured inside _fetch_locks_lock above when event was set to None).- # The guard below is a defensive "can't happen" check: whenever event- # is None, both references were assigned in that same locked block. If- # a future refactor ever breaks the invariant, degrade to a cache miss- # instead of raising -- raising would propagate without setting- # fetch_event, stranding any waiting threads for the full 30s timeout.- if fetch_lock is None or fetch_event is None:- logger.error(- "fetch_lock/fetch_event not set inside _fetch_locks_lock; "- "treating query '{}' as a fetch failure",- query[:50],- )- return None- with fetch_lock:- # Triple-check (another thread might have fetched while we waited for lock)- results = self.get(query, search_engine)- if results is not None:- fetch_event.set() # Signal completion- return results-- logger.debug(- f"Fetching results for query: {query[:50]}... (stampede protected)"- )-- try:- # Fetch the results- results = fetch_func()-- if results:- # Store in cache- self.put(query, results, search_engine, ttl)-- # Store temporarily for other waiting threads- with self._fetch_locks_lock:- self._fetch_results[query_hash] = results-- return results-- except Exception:- logger.exception(- f"Failed to fetch results for query: {query[:50]}"- )- # Store None to indicate fetch failed- with self._fetch_locks_lock:- self._fetch_results[query_hash] = None- return None-- finally:- # Signal completion to waiting threads- fetch_event.set()-- # Clean up after a delay- def cleanup():- time.sleep(2) # Give waiting threads time to get results- with self._fetch_locks_lock:- self._fetch_locks.pop(query_hash, None)- self._fetch_events.pop(query_hash, None)- self._fetch_results.pop(query_hash, None)-- # Run cleanup in background- threading.Thread(target=cleanup, daemon=True).start()-- def invalidate(self, query: str, search_engine: str = "default") -> bool:- """Invalidate cached results for a specific query."""- query_hash = self._get_query_hash(query, search_engine)-- try:- # Remove from memory- with self._memory_lock:- self._memory_cache.pop(query_hash, None)- self._access_times.pop(query_hash, None)-- # Remove from database- with self.Session() as session:- deleted = (- session.query(SearchCacheModel)- .filter_by(query_hash=query_hash)- .delete()- )- session.commit()-- logger.debug(f"Invalidated cache for query: {query[:50]}...")- return deleted > 0-- except Exception:- logger.exception("Failed to invalidate cache")- return False-- def clear_all(self) -> bool:- """Clear all cached results."""- try:- with self._memory_lock:- self._memory_cache.clear()- self._access_times.clear()-- with self.Session() as session:- session.query(SearchCacheModel).delete()- session.commit()-- logger.info("Cleared all search cache")- return True-- except Exception:- logger.exception("Failed to clear search cache")- return False-- def dispose(self):- """- Dispose of the database engine and clean up resources.-- Call this method during application shutdown to prevent file descriptor leaks.- After calling dispose(), this cache instance should no longer be used.- """- if hasattr(self, "engine") and self.engine:- try:- self.engine.dispose()- logger.debug("SearchCache engine disposed")- except Exception:- logger.exception("Error disposing SearchCache engine")- finally:- self.engine = None-- def __del__(self):- """Destructor to ensure engine is disposed."""- self.dispose()-- def get_stats(self) -> Dict[str, Any]:- """Get cache statistics."""- try:- current_time = int(time.time())- with self.Session() as session:- # Total entries- total_entries = (- session.query(SearchCacheModel)- .filter(SearchCacheModel.expires_at > current_time)- .count()- )-- # Total expired entries- expired_entries = (- session.query(SearchCacheModel)- .filter(SearchCacheModel.expires_at <= current_time)- .count()- )-- # Average access count- from sqlalchemy import func-- avg_access_result = (- session.query(func.avg(SearchCacheModel.access_count))- .filter(SearchCacheModel.expires_at > current_time)- .scalar()- )- avg_access = avg_access_result or 0-- with self._memory_lock:- memory_cache_size = len(self._memory_cache)-- return {- "total_valid_entries": total_entries,- "expired_entries": expired_entries,- "memory_cache_size": memory_cache_size,- "average_access_count": round(avg_access, 2),- "cache_hit_potential": (- f"{(total_entries / (total_entries + 1)) * 100:.1f}%"- if total_entries > 0- else "0%"- ),- }-- except Exception:- logger.exception("Failed to get cache stats")- return {"error": "Cache stats unavailable"}---# Global cache instance-_global_cache = None-_global_cache_lock = threading.Lock()---def get_search_cache() -> SearchCache:- """Get global search cache instance."""- global _global_cache- if _global_cache is None:- with _global_cache_lock:- if _global_cache is None:- _global_cache = SearchCache()- return _global_cache---def _dispose_global_cache():- global _global_cache- if _global_cache is not None:- _global_cache.dispose()- _global_cache = None---atexit.register(_dispose_global_cache)---@lru_cache(maxsize=100)-def normalize_entity_query(entity: str, constraint: str) -> str:- """- Normalize entity + constraint combination for consistent caching.- Uses LRU cache for frequent normalizations.- """- # Remove quotes and normalize whitespace- entity_clean = " ".join(entity.strip().lower().split())- constraint_clean = " ".join(constraint.strip().lower().split())-- # Create canonical form- return f"{entity_clean} {constraint_clean}"diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 554dd7cfd9..9cdeba4939 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -982,11 +982,8 @@ def run_research_process(research_id, query, mode, **kwargs):"search_engine_selected": search_engine,"username": username, # Add username for queue operations"user_password": user_password, # Add password for metrics access- # SearchCache hash includes the active egress scope read from- # this snapshot, so a scope=BOTH cache entry doesn't get- # returned to a later scope=PRIVATE_ONLY query. Without the- # snapshot here, the cache scope-tag silently degrades to- # "both" and the bypass is not closed.+ # Thread-safe settings snapshot propagated to background search+ # threads (engine config, per-user resolution, egress scope)."settings_snapshot": settings_snapshot,"chat_session_id": kwargs.get("chat_session_id"),}diff --git a/tests/security/test_egress_cache_and_fullsearch.py b/tests/security/test_egress_cache_and_fullsearch.pyindex 23eafd44d4..4580ab620f 100644--- a/tests/security/test_egress_cache_and_fullsearch.py+++ b/tests/security/test_egress_cache_and_fullsearch.py@@ -1,14 +1,9 @@-"""Integration tests for two real egress Policy Enforcement Points:+"""Integration tests for the ``full_search.py`` egress Policy Enforcement Point:-1. ``utilities/search_cache.py`` — the N17 fix that folds the active egress- scope into the cache key, so a warm cache populated under one scope can- never be served to a query running under a stricter scope- (cross-scope cache poisoning / policy bypass via warm cache).--2. ``web_search_engines/engines/full_search.py`` — per-URL egress gating in- the full-content fetch path: when an ``egress_context`` is present, URLs- that ``evaluate_url`` denies for the scope are dropped before any network- fetch, allowed ones are kept, and the denial audit log is URL-redacted.+``web_search_engines/engines/full_search.py`` — per-URL egress gating in the+full-content fetch path: when an ``egress_context`` is present, URLs that+``evaluate_url`` denies for the scope are dropped before any network fetch,+allowed ones are kept, and the denial audit log is URL-redacted.These drive the REAL call-site code. Only unavoidable heavy deps are mocked(the network ``batch_fetch_and_extract`` and the SSRF ``validate_url``, so the@@ -26,8 +21,6 @@ from local_deep_research.security.egress.policy import (EgressContext,EgressScope,)-from local_deep_research.utilities.search_cache import SearchCache-from local_deep_research.utilities.thread_context import search_contextfrom local_deep_research.web_search_engines.engines import full_search as fs@@ -36,14 +29,6 @@ from local_deep_research.web_search_engines.engines import full_search as fs# ----------------------------------------------------------------------------def _scope_context(scope: str, username: str = "alice") -> dict:- """Mirror the real search-context shape the cache reads scope from."""- return {- "username": username,- "settings_snapshot": {"policy.egress_scope": {"value": scope}},- }--def _make_ctx(scope: EgressScope) -> EgressContext:return EgressContext(scope=scope,@@ -70,99 +55,7 @@ _PRIVATE_URL = "http://10.0.0.5/api"# ===========================================================================-# (1) search_cache scope keying — no cross-scope cache poisoning-# ===========================================================================---def test_cache_entry_not_served_across_scopes(tmp_path):- """A result cached under PRIVATE_ONLY must NOT be returned to the same- query running under PUBLIC_ONLY or BOTH (and vice-versa); the same- query under the SAME scope still hits."""- cache = SearchCache(cache_dir=str(tmp_path))- try:- results = [{"title": "secret", "link": _PRIVATE_URL}]-- with search_context(_scope_context("private_only")):- assert cache.put("quarterly numbers", results) is True- # Same scope, same query -> hit.- assert cache.get("quarterly numbers") == results-- # Different scope -> the private-scope entry must be invisible.- with search_context(_scope_context("public_only")):- assert cache.get("quarterly numbers") is None- with search_context(_scope_context("both")):- assert cache.get("quarterly numbers") is None-- # Back to the original scope -> still a hit (key is stable per scope).- with search_context(_scope_context("private_only")):- assert cache.get("quarterly numbers") == results- finally:- cache.dispose()---def test_cache_does_not_leak_public_results_into_private_scope(tmp_path):- """Mirror direction: PUBLIC_ONLY-cached results must not satisfy a- PRIVATE_ONLY lookup."""- cache = SearchCache(cache_dir=str(tmp_path))- try:- pub_results = [{"title": "public", "link": _PUBLIC_URL}]- with search_context(_scope_context("public_only")):- assert cache.put("market data", pub_results) is True- assert cache.get("market data") == pub_results-- with search_context(_scope_context("private_only")):- assert cache.get("market data") is None- finally:- cache.dispose()---def test_query_hash_distinct_per_scope_stable_within_scope(tmp_path):- """The hash folds scope: differs across scopes, identical within a scope."""- cache = SearchCache(cache_dir=str(tmp_path))- try:- with search_context(_scope_context("private_only")):- h_priv = cache._get_query_hash("same query")- with search_context(_scope_context("public_only")):- h_pub = cache._get_query_hash("same query")- with search_context(_scope_context("both")):- h_both = cache._get_query_hash("same query")- with search_context(_scope_context("private_only")):- h_priv_again = cache._get_query_hash("same query")-- # All three scopes produce distinct keys.- assert len({h_priv, h_pub, h_both}) == 3- # Same scope + same query is deterministic.- assert h_priv == h_priv_again- finally:- cache.dispose()---def test_no_context_hashes_identically_to_explicit_adaptive(tmp_path):- """Documented invariant: "no policy snapshot" and an explicit ADAPTIVE- scope (the registered default) must hash identically, so unset-context- runs and explicit-default runs share one cache partition rather than- fragmenting."""- cache = SearchCache(cache_dir=str(tmp_path))- try:- # No search context at all.- h_none = cache._get_query_hash("topic")- # Explicit ADAPTIVE with an empty username (the no-context default).- with search_context(- {- "username": "",- "settings_snapshot": {- "policy.egress_scope": {"value": "adaptive"}- },- }- ):- h_adaptive = cache._get_query_hash("topic")- assert h_none == h_adaptive- finally:- cache.dispose()---# ===========================================================================-# (2) full_search per-URL egress gating+# full_search per-URL egress gating# ===========================================================================diff --git a/tests/security/test_egress_policy.py b/tests/security/test_egress_policy.pyindex 01b3f2f655..59f9937092 100644--- a/tests/security/test_egress_policy.py+++ b/tests/security/test_egress_policy.py@@ -1732,32 +1732,6 @@ def test_evaluate_retriever_scopes():retriever_registry.unregister(name)-def test_n17_cache_hash_includes_scope():- """N17: SearchCache hash differs between scope=BOTH and- scope=PRIVATE_ONLY for the same query, preventing cross-scope- cache-hit bypass.- """- from local_deep_research.utilities.search_cache import SearchCache-- with patch(- "local_deep_research.utilities.search_cache.get_search_context",- side_effect=[- {- "username": "u",- "settings_snapshot": {"policy.egress_scope": "both"},- },- {- "username": "u",- "settings_snapshot": {"policy.egress_scope": "private_only"},- },- ],- ):- cache = SearchCache.__new__(SearchCache)- h1 = cache._get_query_hash("vega lite syntax", "wikipedia")- h2 = cache._get_query_hash("vega lite syntax", "wikipedia")- assert h1 != h2, "scope must participate in the cache hash"--def test_n8_unknown_scope_raises_after_context_from_snapshot():"""N8: unknown scope is fail-closed at context build time.Verified separately above; this test pins the error reason code.@@ -1933,14 +1907,14 @@ def test_n16_policy_setting_triggers_audit_logger():def test_n17_research_context_carries_settings_snapshot():- """Regression for the wiring bug caught during the follow-up pass:- every site that calls ``set_search_context`` must populate- ``settings_snapshot`` — without it, ``SearchCache._get_query_hash``- silently reads {} and degrades to scope='both' regardless of- policy, re-opening the cache-hit bypass that N17 was meant to- close. Pins the contract by inspecting the source of each known- call site so a future regression fails at unit-test time, not at- runtime.+ """Every site that calls ``set_search_context`` must populate+ ``settings_snapshot`` — the live egress-policy scope, engine config,+ and per-user resolution are all read from it, so a constructor that+ drops it silently degrades them to defaults. (Originally caught as the+ N17 cache-key wiring bug; the search cache has since been removed, but+ the contract still matters for the live egress path.) Pins the contract+ by inspecting the source of each known call site so a future regression+ fails at unit-test time, not at runtime."""import inspectdiff --git a/tests/test_search_cache_stampede.py b/tests/test_search_cache_stampede.pydeleted file mode 100644index 0c3b951e31..0000000000--- a/tests/test_search_cache_stampede.py+++ /dev/null@@ -1,290 +0,0 @@-"""-Test search cache stampede protection functionality.-"""--import concurrent.futures-import threading-import time-import unittest-from tempfile import TemporaryDirectory-from typing import List, Dict, Any--from local_deep_research.utilities.search_cache import SearchCache---class TestSearchCacheStampede(unittest.TestCase):- """Test that SearchCache properly prevents cache stampedes."""-- def setUp(self):- """Set up test cache with temporary directory."""- self.temp_dir = TemporaryDirectory()- self.cache = SearchCache(- cache_dir=self.temp_dir.name, max_memory_items=100, default_ttl=60- )-- # Track API calls- self.api_call_count = 0- self.api_call_lock = threading.Lock()- self.api_call_threads = []-- def tearDown(self):- """Clean up temporary directory."""- self.temp_dir.cleanup()-- def mock_api_call(self, query: str) -> List[Dict[str, Any]]:- """Mock API call that simulates slow external search."""- with self.api_call_lock:- self.api_call_count += 1- self.api_call_threads.append(threading.current_thread().name)-- # Simulate network latency- time.sleep(0.1)-- # Return mock results- return [- {"title": f"Result 1 for {query}", "url": "http://example.com/1"},- {"title": f"Result 2 for {query}", "url": "http://example.com/2"},- ]-- def test_single_thread_caching(self):- """Test basic caching works for a single thread."""- query = "test query single"-- # First call - should miss cache and call API- results = self.cache.get_or_fetch(- query, lambda: self.mock_api_call(query)- )-- self.assertEqual(self.api_call_count, 1)- self.assertIsNotNone(results)- self.assertEqual(len(results), 2)-- # Second call - should hit cache- results2 = self.cache.get_or_fetch(- query, lambda: self.mock_api_call(query)- )-- self.assertEqual(self.api_call_count, 1) # No additional API call- self.assertEqual(results, results2)-- def test_stampede_protection(self):- """Test that multiple concurrent requests only trigger one API call."""- query = "test query stampede"- num_threads = 10- results_list = []- barrier = threading.Barrier(num_threads)-- def fetch_with_cache(thread_id):- """Function each thread will run."""- barrier.wait() # Ensure all threads start simultaneously- results = self.cache.get_or_fetch(- query, lambda: self.mock_api_call(query)- )- results_list.append((thread_id, results))- return results-- # Launch multiple threads concurrently- with concurrent.futures.ThreadPoolExecutor(- max_workers=num_threads- ) as executor:- futures = [- executor.submit(fetch_with_cache, i) for i in range(num_threads)- ]- concurrent.futures.wait(futures)-- # Check that only ONE API call was made despite multiple threads- self.assertEqual(- self.api_call_count,- 1,- f"Expected 1 API call but got {self.api_call_count}. "- f"Threads that called API: {self.api_call_threads}",- )-- # Check all threads got the same results- self.assertEqual(len(results_list), num_threads)- first_result = results_list[0][1]- for thread_id, result in results_list:- self.assertEqual(- result,- first_result,- f"Thread {thread_id} got different results",- )-- def test_different_queries_not_blocked(self):- """Test that different queries can be fetched concurrently."""- queries = [f"query_{i}" for i in range(5)]- results_dict = {}-- def fetch_query(query):- results = self.cache.get_or_fetch(- query, lambda: self.mock_api_call(query)- )- results_dict[query] = results- return results-- # Launch threads for different queries- with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:- futures = [executor.submit(fetch_query, query) for query in queries]- concurrent.futures.wait(futures)-- # Each unique query should trigger exactly one API call- self.assertEqual(- self.api_call_count,- 5,- f"Expected 5 API calls for 5 different queries, got {self.api_call_count}",- )-- # Verify each query got cached- for query in queries:- cached = self.cache.get(query)- self.assertIsNotNone(cached)- self.assertEqual(cached, results_dict[query])-- def test_expired_cache_refetch(self):- """Test that expired cache entries trigger refetch with stampede protection."""- query = "test expiring query"-- # First fetch with very short TTL- self.cache.get_or_fetch(- query,- lambda: self.mock_api_call(query),- ttl=1, # 1 second TTL- )-- self.assertEqual(self.api_call_count, 1)-- # Wait for cache to expire- time.sleep(1.5) # allow: unmarked-sleep-- # Multiple threads try to fetch expired entry- num_threads = 5- results_list = []- barrier = threading.Barrier(num_threads)-- def fetch_expired():- barrier.wait() # Ensure all threads start simultaneously- return self.cache.get_or_fetch(- query, lambda: self.mock_api_call(query)- )-- with concurrent.futures.ThreadPoolExecutor(- max_workers=num_threads- ) as executor:- futures = [- executor.submit(fetch_expired) for _ in range(num_threads)- ]- for future in concurrent.futures.as_completed(futures):- results_list.append(future.result())-- # Should have made exactly 2 API calls total (initial + refetch after expiry)- self.assertEqual(- self.api_call_count,- 2,- f"Expected 2 API calls (initial + refetch), got {self.api_call_count}",- )-- # All threads should get the same refreshed results- for results in results_list:- self.assertEqual(results, results_list[0])-- def test_get_during_fetch(self):- """Test that get() returns None while another thread is fetching."""- query = "test get during fetch"- fetch_started = threading.Event()- fetch_complete = threading.Event()-- def slow_fetch():- fetch_started.set()- time.sleep(0.5) # allow: unmarked-sleep # Simulate slow API- fetch_complete.set()- return self.mock_api_call(query)-- def thread1_fetch():- """First thread - initiates fetch."""- return self.cache.get_or_fetch(query, slow_fetch)-- def thread2_get():- """Second thread - checks cache during fetch."""- fetch_started.wait() # Ensure fetch has started- result = self.cache.get(query)- return result-- def thread3_get_or_fetch():- """Third thread - uses get_or_fetch during fetch."""- fetch_started.wait() # Ensure fetch has started- time.sleep(0.1) # Small delay- result = self.cache.get_or_fetch(- query, lambda: self.mock_api_call(query)- )- return result-- with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:- future1 = executor.submit(thread1_fetch)- future2 = executor.submit(thread2_get)- future3 = executor.submit(thread3_get_or_fetch)-- # Thread 2 should return None (cache miss during fetch)- result2 = future2.result()- self.assertIsNone(result2, "get() should return None during fetch")-- # Thread 3 should wait and get results without calling API again- result3 = future3.result()- self.assertIsNotNone(- result3, "get_or_fetch() should wait and get results"- )-- # Thread 1 completes the fetch- result1 = future1.result()- self.assertIsNotNone(result1)- self.assertEqual(result1, result3)-- # Only one API call should have been made- self.assertEqual(self.api_call_count, 1)-- def test_fetch_error_handling(self):- """Test that fetch errors don't break stampede protection."""- query = "test error query"- attempt_count = 0-- def failing_fetch():- nonlocal attempt_count- attempt_count += 1- if attempt_count < 2:- raise Exception("API error")- return self.mock_api_call(query)-- # First attempt fails- result1 = self.cache.get_or_fetch(query, failing_fetch)- self.assertIsNone(result1)- self.assertEqual(attempt_count, 1)-- # Second attempt succeeds- result2 = self.cache.get_or_fetch(query, failing_fetch)- self.assertIsNotNone(result2)- self.assertEqual(attempt_count, 2)-- # Third attempt uses cache- result3 = self.cache.get_or_fetch(query, failing_fetch)- self.assertEqual(result2, result3)- self.assertEqual(attempt_count, 2) # No additional attempt-- def test_cleanup_of_locks(self):- """Test that locks are cleaned up after fetching."""- # audit: PUNCHLIST reviewed 2026-05 — issue resolved by prior PR (recommendation: refactor: replace sleep with deterministic trigger or expose hook).- query = "test cleanup"-- # Fetch and cache- self.cache.get_or_fetch(query, lambda: self.mock_api_call(query))-- # Wait for cleanup thread to run (cleanup delay is 2 seconds)- time.sleep(3) # allow: unmarked-sleep-- # Check that locks and events have been cleaned up- query_hash = self.cache._get_query_hash(query)- self.assertNotIn(query_hash, self.cache._fetch_locks)- self.assertNotIn(query_hash, self.cache._fetch_events)- self.assertNotIn(query_hash, self.cache._fetch_results)---if __name__ == "__main__":- unittest.main()diff --git a/tests/utilities/test_normalize_entity_query.py b/tests/utilities/test_normalize_entity_query.pydeleted file mode 100644index 7061e568c3..0000000000--- a/tests/utilities/test_normalize_entity_query.py+++ /dev/null@@ -1,170 +0,0 @@-"""-Tests for normalize_entity_query utility function.--This function normalizes entity + constraint combinations for consistent-caching, using LRU cache for performance. It was previously untested.--Covers:-- Basic normalization (lowercase, whitespace)-- Quote stripping behavior (via .split())-- Empty/whitespace inputs-- Unicode handling-- LRU cache behavior (same input → same output)-"""---def _get_fn():- """Import and return normalize_entity_query, clearing its LRU cache."""- from local_deep_research.utilities.search_cache import (- normalize_entity_query,- )-- normalize_entity_query.cache_clear()- return normalize_entity_query---class TestNormalizeEntityQueryBasics:- """Basic normalization tests."""-- def test_lowercases_entity(self):- """Entity is lowercased."""- fn = _get_fn()- result = fn("John Smith", "born")- assert "john smith" in result-- def test_lowercases_constraint(self):- """Constraint is lowercased."""- fn = _get_fn()- result = fn("python", "RELEASE DATE")- assert "release date" in result-- def test_combines_entity_and_constraint(self):- """Result is 'entity constraint' with a space separator."""- fn = _get_fn()- result = fn("python", "release date")- assert result == "python release date"-- def test_strips_leading_trailing_whitespace(self):- """Leading/trailing whitespace is removed."""- fn = _get_fn()- result = fn(" python ", " release date ")- assert result == "python release date"-- def test_collapses_internal_whitespace(self):- """Multiple internal spaces collapsed to single space."""- fn = _get_fn()- result = fn("John Michael Smith", "birth date")- assert result == "john michael smith birth date"-- def test_tabs_and_newlines_normalized(self):- """Tabs and newlines treated as whitespace and collapsed."""- fn = _get_fn()- result = fn("John\tSmith", "born\nin")- assert result == "john smith born in"---class TestNormalizeEntityQueryEdgeCases:- """Edge cases and unusual inputs."""-- def test_empty_entity(self):- """Empty entity produces just the constraint."""- fn = _get_fn()- result = fn("", "born")- assert result == " born"-- def test_empty_constraint(self):- """Empty constraint produces just the entity."""- fn = _get_fn()- result = fn("python", "")- assert result == "python "-- def test_both_empty(self):- """Both empty produces a single space."""- fn = _get_fn()- result = fn("", "")- assert result == " "-- def test_whitespace_only_entity(self):- """Whitespace-only entity is stripped to empty."""- fn = _get_fn()- result = fn(" ", "born")- assert result == " born"-- def test_unicode_characters(self):- """Unicode characters are preserved and lowercased."""- fn = _get_fn()- result = fn("Ünîcödé", "Tëst")- assert result == "ünîcödé tëst"-- def test_special_characters_preserved(self):- """Special characters like hyphens and dots are preserved."""- fn = _get_fn()- result = fn("Marie-Curie", "birth.date")- assert result == "marie-curie birth.date"-- def test_numbers_preserved(self):- """Numbers in entity/constraint are preserved."""- fn = _get_fn()- result = fn("Python 3.12", "release 2024")- assert result == "python 3.12 release 2024"---class TestNormalizeEntityQueryDeterminism:- """Tests that normalization is deterministic and consistent."""-- def test_same_input_same_output(self):- """Same inputs always produce the same result."""- fn = _get_fn()- r1 = fn("Test Entity", "test constraint")- r2 = fn("Test Entity", "test constraint")- assert r1 == r2-- def test_case_variations_produce_same_result(self):- """Different cases of the same entity produce identical results."""- fn = _get_fn()- r1 = fn("John Smith", "born")- r2 = fn("JOHN SMITH", "BORN")- r3 = fn("john smith", "born")- assert r1 == r2 == r3-- def test_whitespace_variations_produce_same_result(self):- """Different whitespace of the same entity produce identical results."""- fn = _get_fn()- r1 = fn("John Smith", "born")- r2 = fn(" John Smith ", " born ")- assert r1 == r2---class TestNormalizeEntityQueryCache:- """Tests for LRU cache behavior."""-- def test_cache_info_starts_empty(self):- """After cache_clear, cache starts with zero hits/misses."""- fn = _get_fn()- info = fn.cache_info()- assert info.hits == 0- assert info.misses == 0-- def test_cache_hit_on_repeat_call(self):- """Second call with same args is a cache hit."""- fn = _get_fn()- fn("test", "query")- fn("test", "query")- info = fn.cache_info()- assert info.hits == 1- assert info.misses == 1-- def test_different_args_are_cache_misses(self):- """Different arguments are separate cache entries."""- fn = _get_fn()- fn("entity1", "constraint1")- fn("entity2", "constraint2")- info = fn.cache_info()- assert info.misses == 2- assert info.hits == 0-- def test_cache_maxsize_is_100(self):- """LRU cache has maxsize of 100."""- fn = _get_fn()- info = fn.cache_info()- assert info.maxsize == 100diff --git a/tests/utilities/test_search_cache.py b/tests/utilities/test_search_cache.pydeleted file mode 100644index 0bbb00772b..0000000000--- a/tests/utilities/test_search_cache.py+++ /dev/null@@ -1,746 +0,0 @@-"""-Comprehensive tests for search_cache module.-Tests caching, TTL, LRU eviction, stampede protection, and persistence.-"""--import tempfile-import threading-import time-from pathlib import Path-from unittest.mock import patch--import pytest-from freezegun import freeze_time---class TestSearchCacheInit:- """Tests for SearchCache initialization."""-- def test_init_with_defaults(self):- """Test initialization with default parameters."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- cache = SearchCache(cache_dir=tmpdir)-- assert cache.max_memory_items == 1000- assert cache.default_ttl == 3600-- def test_init_with_custom_params(self):- """Test initialization with custom parameters."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- cache = SearchCache(- cache_dir=tmpdir,- max_memory_items=500,- default_ttl=7200,- )-- assert cache.max_memory_items == 500- assert cache.default_ttl == 7200-- def test_creates_cache_directory(self):- """Test that cache directory is created."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- cache_dir = Path(tmpdir) / "new_cache"- SearchCache(cache_dir=str(cache_dir))-- assert cache_dir.exists()-- def test_creates_database_file(self):- """Test that database file is created."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- cache = SearchCache(cache_dir=tmpdir)-- assert cache.db_path.exists()-- def test_initializes_empty_memory_cache(self):- """Test that memory cache starts empty."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- cache = SearchCache(cache_dir=tmpdir)-- assert cache._memory_cache == {}- assert cache._access_times == {}---class TestSearchCacheNormalization:- """Tests for query normalization."""-- @pytest.fixture- def cache(self):- """Create a SearchCache instance."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- yield SearchCache(cache_dir=tmpdir)-- def test_normalizes_to_lowercase(self, cache):- """Test that queries are lowercased."""- result = cache._normalize_query("HELLO WORLD")-- assert result == "hello world"-- def test_removes_extra_whitespace(self, cache):- """Test that extra whitespace is removed."""- result = cache._normalize_query("hello world")-- assert result == "hello world"-- def test_strips_leading_trailing_whitespace(self, cache):- """Test that leading/trailing whitespace is stripped."""- result = cache._normalize_query(" hello world ")-- assert result == "hello world"-- def test_removes_quotes(self, cache):- """Test that quotes are removed."""- result = cache._normalize_query("\"hello\" 'world'")-- assert result == "hello world"---class TestSearchCacheHashing:- """Tests for query hashing."""-- @pytest.fixture- def cache(self):- """Create a SearchCache instance."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- yield SearchCache(cache_dir=tmpdir)-- def test_same_query_same_hash(self, cache):- """Test that same query produces same hash."""- hash1 = cache._get_query_hash("test query")- hash2 = cache._get_query_hash("test query")-- assert hash1 == hash2-- def test_different_queries_different_hashes(self, cache):- """Test that different queries produce different hashes."""- hash1 = cache._get_query_hash("query one")- hash2 = cache._get_query_hash("query two")-- assert hash1 != hash2-- def test_normalized_queries_same_hash(self, cache):- """Test that normalized equivalent queries have same hash."""- hash1 = cache._get_query_hash("HELLO WORLD")- hash2 = cache._get_query_hash("hello world")-- assert hash1 == hash2-- def test_different_engines_different_hashes(self, cache):- """Test that different search engines produce different hashes."""- hash1 = cache._get_query_hash("test", search_engine="google")- hash2 = cache._get_query_hash("test", search_engine="bing")-- assert hash1 != hash2---class TestSearchCachePutGet:- """Tests for put and get operations."""-- @pytest.fixture- def cache(self):- """Create a SearchCache instance."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- yield SearchCache(cache_dir=tmpdir)-- def test_put_stores_results(self, cache):- """Test that put stores results."""- results = [{"title": "Test", "url": "https://test.com"}]-- success = cache.put("test query", results)-- assert success is True-- def test_get_retrieves_stored_results(self, cache):- """Test that get retrieves stored results."""- results = [{"title": "Test", "url": "https://test.com"}]- cache.put("test query", results)-- retrieved = cache.get("test query")-- assert retrieved == results-- def test_get_returns_none_for_missing(self, cache):- """Test that get returns None for missing queries."""- result = cache.get("nonexistent query")-- assert result is None-- def test_put_rejects_empty_results(self, cache):- """Test that empty results are not cached."""- success = cache.put("test query", [])-- assert success is False-- def test_put_updates_existing_entry(self, cache):- """Test that put updates existing entry."""- results1 = [{"title": "First"}]- results2 = [{"title": "Second"}]-- cache.put("test query", results1)- cache.put("test query", results2)-- retrieved = cache.get("test query")- assert retrieved == results2-- def test_get_uses_memory_cache_first(self, cache):- """Test that get checks memory cache first."""- results = [{"title": "Test"}]- cache.put("test query", results)-- # Second get should use memory cache- with patch.object(cache, "Session") as mock_session:- retrieved = cache.get("test query")-- # Should not access database- mock_session.assert_not_called()- assert retrieved == results-- def test_custom_ttl(self, cache):- """Test that custom TTL is respected.-- SearchCache uses int(time.time()) for expires_at comparison- (search_cache.py:118, :160), so freezegun mocks the clock- deterministically — no real sleep needed.- """- results = [{"title": "Test"}]-- with freeze_time("2026-01-01 00:00:00") as frozen:- cache.put("test query", results, ttl=2)-- # Should be available immediately- assert cache.get("test query") is not None-- # Advance past TTL- frozen.tick(2.5)-- # Clear memory cache to force DB check- cache._memory_cache.clear()-- assert cache.get("test query") is None---class TestSearchCacheExpiration:- """Tests for cache expiration."""-- @pytest.fixture- def cache(self):- """Create a SearchCache instance with short TTL."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- yield SearchCache(cache_dir=tmpdir, default_ttl=1)-- def test_expired_entries_not_returned(self, cache):- """Test that expired entries are not returned.-- Migrated from real time.sleep(1.5) to freezegun. The cache's- default_ttl is 1s for this fixture (see fixture above).- """- results = [{"title": "Test"}]-- with freeze_time("2026-01-01 00:00:00") as frozen:- cache.put("test query", results)-- # Advance past TTL- frozen.tick(1.5)-- # Clear memory cache to force DB check- cache._memory_cache.clear()-- assert cache.get("test query") is None-- def test_expired_memory_entries_removed(self, cache):- """Test that expired memory entries are removed.-- Migrated from real time.sleep(1.5) to freezegun.- """- results = [{"title": "Test"}]-- with freeze_time("2026-01-01 00:00:00") as frozen:- cache.put("test query", results)-- # Advance past TTL- frozen.tick(1.5)-- # Access should remove expired entry from memory- cache.get("test query")-- query_hash = cache._get_query_hash("test query")- assert query_hash not in cache._memory_cache---class TestSearchCacheLRUEviction:- """Tests for LRU memory eviction."""-- def test_evicts_when_over_limit(self):- """Test that LRU eviction occurs when over limit."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- cache = SearchCache(cache_dir=tmpdir, max_memory_items=5)-- # Add more items than limit- for i in range(10):- results = [{"title": f"Result {i}"}]- cache.put(f"query {i}", results)-- # Memory cache should be limited- assert (- len(cache._memory_cache) <= 5 + 100- ) # +100 for efficiency buffer---class TestSearchCacheInvalidate:- """Tests for cache invalidation."""-- @pytest.fixture- def cache(self):- """Create a SearchCache instance."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- yield SearchCache(cache_dir=tmpdir)-- def test_invalidate_removes_entry(self, cache):- """Test that invalidate removes entry."""- results = [{"title": "Test"}]- cache.put("test query", results)-- cache.invalidate("test query")-- assert cache.get("test query") is None-- def test_invalidate_removes_from_memory(self, cache):- """Test that invalidate removes from memory cache."""- results = [{"title": "Test"}]- cache.put("test query", results)-- cache.invalidate("test query")-- query_hash = cache._get_query_hash("test query")- assert query_hash not in cache._memory_cache-- def test_invalidate_returns_true_if_found(self, cache):- """Test that invalidate returns True if entry found."""- results = [{"title": "Test"}]- cache.put("test query", results)-- result = cache.invalidate("test query")-- assert result is True-- def test_invalidate_returns_false_if_not_found(self, cache):- """Test that invalidate returns False if entry not found."""- result = cache.invalidate("nonexistent query")-- assert result is False---class TestSearchCacheClearAll:- """Tests for clear_all operation."""-- @pytest.fixture- def cache(self):- """Create a SearchCache instance."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- yield SearchCache(cache_dir=tmpdir)-- def test_clear_all_removes_all_entries(self, cache):- """Test that clear_all removes all entries."""- cache.put("query 1", [{"title": "1"}])- cache.put("query 2", [{"title": "2"}])-- cache.clear_all()-- assert cache.get("query 1") is None- assert cache.get("query 2") is None-- def test_clear_all_empties_memory_cache(self, cache):- """Test that clear_all empties memory cache."""- cache.put("test query", [{"title": "Test"}])-- cache.clear_all()-- assert cache._memory_cache == {}- assert cache._access_times == {}-- def test_clear_all_returns_true(self, cache):- """Test that clear_all returns True on success."""- result = cache.clear_all()-- assert result is True---class TestSearchCacheStats:- """Tests for cache statistics."""-- @pytest.fixture- def cache(self):- """Create a SearchCache instance."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- yield SearchCache(cache_dir=tmpdir)-- def test_stats_returns_dict(self, cache):- """Test that stats returns a dictionary."""- stats = cache.get_stats()-- assert isinstance(stats, dict)-- def test_stats_includes_required_keys(self, cache):- """Test that stats includes required keys."""- stats = cache.get_stats()-- assert "total_valid_entries" in stats- assert "memory_cache_size" in stats-- def test_stats_reflects_cache_state(self, cache):- """Test that stats reflect actual cache state."""- cache.put("test query", [{"title": "Test"}])-- stats = cache.get_stats()-- assert stats["total_valid_entries"] >= 1- assert stats["memory_cache_size"] >= 1---class TestSearchCacheGetOrFetch:- """Tests for get_or_fetch with stampede protection."""-- @pytest.fixture- def cache(self):- """Create a SearchCache instance."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- yield SearchCache(cache_dir=tmpdir)-- def test_returns_cached_if_available(self, cache):- """Test that cached results are returned without fetching."""- results = [{"title": "Cached"}]- cache.put("test query", results)-- fetch_called = []-- def fetch_func():- fetch_called.append(True)- return [{"title": "Fetched"}]-- result = cache.get_or_fetch("test query", fetch_func)-- assert result == results- assert len(fetch_called) == 0-- def test_calls_fetch_func_on_miss(self, cache):- """Test that fetch_func is called on cache miss."""- expected = [{"title": "Fetched"}]-- def fetch_func():- return expected-- result = cache.get_or_fetch("test query", fetch_func)-- assert result == expected-- def test_caches_fetched_results(self, cache):- """Test that fetched results are cached."""- expected = [{"title": "Fetched"}]-- def fetch_func():- return expected-- cache.get_or_fetch("test query", fetch_func)-- # Second call should use cache- cached = cache.get("test query")- assert cached == expected-- def test_handles_fetch_exception(self, cache):- """Test that fetch exceptions are handled gracefully."""-- def fetch_func():- raise Exception("Fetch failed")-- result = cache.get_or_fetch("test query", fetch_func)-- assert result is None-- def test_stampede_protection_single_fetch(self, cache):- """Test that only one thread fetches during stampede."""- # audit: PUNCHLIST reviewed 2026-05 — KEEP (OK).- fetch_count = []-- def slow_fetch():- fetch_count.append(1)- time.sleep(0.2) # allow: unmarked-sleep- return [{"title": "Result"}]-- threads = []- results = []-- def worker():- result = cache.get_or_fetch("same query", slow_fetch)- results.append(result)-- # Start multiple threads simultaneously- for _ in range(5):- t = threading.Thread(target=worker)- threads.append(t)- t.start()-- # Wait for all threads- for t in threads:- t.join(timeout=5)-- # All threads should get results- assert len(results) == 5- # But fetch should only be called once (or very few times due to race)- assert len(fetch_count) <= 2---class TestGlobalCacheInstance:- """Tests for global cache singleton."""-- def test_get_search_cache_returns_instance(self):- """Test that get_search_cache returns a SearchCache instance."""- from local_deep_research.utilities.search_cache import (- get_search_cache,- SearchCache,- )-- cache = get_search_cache()-- assert isinstance(cache, SearchCache)-- def test_get_search_cache_returns_same_instance(self):- """Test that get_search_cache returns same instance."""- from local_deep_research.utilities.search_cache import (- get_search_cache,- )-- cache1 = get_search_cache()- cache2 = get_search_cache()-- assert cache1 is cache2---class TestNormalizeEntityQuery:- """Tests for normalize_entity_query function."""-- def test_normalizes_entity_and_constraint(self):- """Test that entity and constraint are normalized."""- from local_deep_research.utilities.search_cache import (- normalize_entity_query,- )-- result = normalize_entity_query("ENTITY NAME", "CONSTRAINT VALUE")-- assert result == "entity name constraint value"-- def test_removes_extra_whitespace(self):- """Test that extra whitespace is removed."""- from local_deep_research.utilities.search_cache import (- normalize_entity_query,- )-- result = normalize_entity_query("entity name", "constraint value")-- assert result == "entity name constraint value"-- def test_strips_values(self):- """Test that values are stripped."""- from local_deep_research.utilities.search_cache import (- normalize_entity_query,- )-- result = normalize_entity_query(" entity ", " constraint ")-- assert result == "entity constraint"-- def test_caches_results(self):- """Test that results are cached via lru_cache."""- from local_deep_research.utilities.search_cache import (- normalize_entity_query,- )-- # Clear cache- normalize_entity_query.cache_clear()-- # First call- normalize_entity_query("test", "value")-- # Check cache info- cache_info = normalize_entity_query.cache_info()- assert cache_info.misses == 1-- # Second call with same args- normalize_entity_query("test", "value")-- cache_info = normalize_entity_query.cache_info()- assert cache_info.hits == 1---class TestSearchCacheResourceCleanup:- """Tests for engine disposal and resource management."""-- def test_dispose_disposes_engine(self):- """Test that dispose() calls engine.dispose()."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- cache = SearchCache(cache_dir=tmpdir)-- # Mock the engine- mock_engine = cache.engine- original_dispose = mock_engine.dispose-- dispose_called = []-- def track_dispose():- dispose_called.append(True)- original_dispose()-- mock_engine.dispose = track_dispose-- cache.dispose()-- assert len(dispose_called) == 1-- def test_dispose_sets_engine_to_none(self):- """Test that dispose() sets engine to None."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- cache = SearchCache(cache_dir=tmpdir)-- # Verify engine exists- assert cache.engine is not None-- cache.dispose()-- # Engine should be None after dispose- assert cache.engine is None-- def test_dispose_handles_no_engine(self):- """Test that dispose() handles missing engine gracefully."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- cache = SearchCache(cache_dir=tmpdir)-- # Dispose twice - should not raise- cache.dispose()- cache.dispose()-- assert cache.engine is None-- def test_dispose_handles_exception(self):- """Test that dispose() handles engine.dispose() exceptions."""- from local_deep_research.utilities.search_cache import SearchCache- from unittest.mock import Mock-- with tempfile.TemporaryDirectory() as tmpdir:- cache = SearchCache(cache_dir=tmpdir)-- # Mock engine to raise on dispose- mock_engine = Mock()- mock_engine.dispose.side_effect = Exception("Dispose failed")- cache.engine = mock_engine-- # Should not raise, just log the exception- cache.dispose()-- # Engine should be set to None even after exception- assert cache.engine is None-- def test_del_calls_dispose(self):- """Test that __del__ calls dispose()."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- cache = SearchCache(cache_dir=tmpdir)-- with patch.object(cache, "dispose") as mock_dispose:- cache.__del__()- mock_dispose.assert_called_once()---class TestSearchCacheEdgeCases:- """Tests for edge cases and error handling."""-- def test_handles_special_characters_in_query(self):- """Test handling of special characters in queries."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- cache = SearchCache(cache_dir=tmpdir)-- results = [{"title": "Test"}]- query = "test & query with <special> 'chars'"-- cache.put(query, results)- retrieved = cache.get(query)-- assert retrieved == results-- def test_handles_unicode_queries(self):- """Test handling of unicode queries."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- cache = SearchCache(cache_dir=tmpdir)-- results = [{"title": "Test"}]- query = "café naïve 日本語"-- cache.put(query, results)- retrieved = cache.get(query)-- assert retrieved == results-- def test_handles_very_long_queries(self):- """Test handling of very long queries."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- cache = SearchCache(cache_dir=tmpdir)-- results = [{"title": "Test"}]- query = "x" * 10000-- cache.put(query, results)- retrieved = cache.get(query)-- assert retrieved == results-- def test_handles_empty_query(self):- """Test handling of empty query."""- from local_deep_research.utilities.search_cache import SearchCache-- with tempfile.TemporaryDirectory() as tmpdir:- cache = SearchCache(cache_dir=tmpdir)-- results = [{"title": "Test"}]-- cache.put("", results)- retrieved = cache.get("")-- assert retrieved == resultsdiff --git a/tests/utilities/test_search_cache_coverage.py b/tests/utilities/test_search_cache_coverage.pydeleted file mode 100644index ff4f7e8d38..0000000000--- a/tests/utilities/test_search_cache_coverage.py+++ /dev/null@@ -1,313 +0,0 @@-"""-Coverage tests for search_cache.py targeting exception paths and edge cases-not covered by existing test files.--Focuses on:-- _init_db exception handling-- _cleanup_expired success and exception paths-- get/put/invalidate/clear_all/get_stats DB exception paths-- get_or_fetch stale event cleanup-- _dispose_global_cache cleanup and noop-when-None-"""--import threading-from unittest.mock import MagicMock, patch---# ----------------------------------------------------------------------------# Helpers-# ------------------------------------------------------------------------------def _make_cache(tmpdir):- """Create a SearchCache backed by a temp directory."""- from local_deep_research.utilities.search_cache import SearchCache-- return SearchCache(cache_dir=str(tmpdir))---# ----------------------------------------------------------------------------# _init_db exception path-# ------------------------------------------------------------------------------class TestInitDbException:- """_init_db should log and swallow exceptions so the constructor doesn't crash."""-- def test_init_db_exception_is_logged_and_swallowed(self, tmp_path):- """When create_engine or metadata.create_all raises, _init_db catches it."""- from local_deep_research.utilities.search_cache import SearchCache-- with patch(- "local_deep_research.utilities.search_cache.create_engine",- side_effect=RuntimeError("disk full"),- ):- # Should not raise – the exception is caught internally- cache = SearchCache(cache_dir=str(tmp_path / "bad_db"))- # engine / Session may not be set, but the object exists- assert cache.max_memory_items == 1000---# ----------------------------------------------------------------------------# _cleanup_expired-# ------------------------------------------------------------------------------class TestCleanupExpired:- """Tests for the _cleanup_expired helper."""-- def test_cleanup_expired_deletes_old_entries(self, tmp_path):- """Expired entries are removed from the database."""- cache = _make_cache(tmp_path)- # Insert an entry that is already expired (ttl=-10)- cache.put("old query", [{"title": "stale"}], ttl=-10)- # The entry won't be returned by get (expired), but row exists in DB.- cache._cleanup_expired()- # After cleanup the DB row should be gone; get still returns None.- result = cache.get("old query")- assert result is None-- def test_cleanup_expired_logs_deleted_count(self, tmp_path):- """When entries are deleted, a debug log is emitted."""- cache = _make_cache(tmp_path)- cache.put("q1", [{"a": 1}], ttl=-5)- with patch(- "local_deep_research.utilities.search_cache.logger"- ) as mock_logger:- cache._cleanup_expired()- # At least one debug call about cleaned entries- assert mock_logger.debug.called or mock_logger.exception.called-- def test_cleanup_expired_exception_is_caught(self, tmp_path):- """If the DB query fails, the exception is logged, not raised."""- cache = _make_cache(tmp_path)- # Replace Session with one that raises- original_session = cache.Session- cache.Session = MagicMock(side_effect=RuntimeError("connection lost"))- # Should not raise- cache._cleanup_expired()- # Restore- cache.Session = original_session---# ----------------------------------------------------------------------------# get – DB exception path-# ------------------------------------------------------------------------------class TestGetDbException:- """When the database query inside get() fails, it should return None."""-- def test_get_returns_none_on_db_error(self, tmp_path):- cache = _make_cache(tmp_path)- # Ensure nothing in memory cache so it falls through to DB- cache._memory_cache.clear()-- mock_session = MagicMock()- mock_session.__enter__ = MagicMock(- side_effect=RuntimeError("db locked")- )- mock_session.__exit__ = MagicMock(return_value=False)- cache.Session = MagicMock(return_value=mock_session)-- result = cache.get("any query")- assert result is None---# ----------------------------------------------------------------------------# put – DB exception path-# ------------------------------------------------------------------------------class TestPutDbException:- """When the database write inside put() fails, it should return False."""-- def test_put_returns_false_on_db_error(self, tmp_path):- cache = _make_cache(tmp_path)-- mock_session = MagicMock()- mock_session.__enter__ = MagicMock(- side_effect=RuntimeError("read-only")- )- mock_session.__exit__ = MagicMock(return_value=False)- cache.Session = MagicMock(return_value=mock_session)-- result = cache.put("query", [{"data": 1}])- assert result is False---# ----------------------------------------------------------------------------# invalidate – DB exception path-# ------------------------------------------------------------------------------class TestInvalidateDbException:- """When the database delete inside invalidate() fails, it returns False."""-- def test_invalidate_returns_false_on_db_error(self, tmp_path):- cache = _make_cache(tmp_path)-- mock_session = MagicMock()- mock_session.__enter__ = MagicMock(side_effect=RuntimeError("corrupt"))- mock_session.__exit__ = MagicMock(return_value=False)- cache.Session = MagicMock(return_value=mock_session)-- result = cache.invalidate("query")- assert result is False-- def test_invalidate_clears_memory_even_on_db_error(self, tmp_path):- """Memory cache entries are removed before attempting DB delete."""- cache = _make_cache(tmp_path)- # Populate memory cache- cache.put("query", [{"v": 1}])- query_hash = cache._get_query_hash("query")- assert query_hash in cache._memory_cache-- # Now break the DB- mock_session = MagicMock()- mock_session.__enter__ = MagicMock(side_effect=RuntimeError("corrupt"))- mock_session.__exit__ = MagicMock(return_value=False)- cache.Session = MagicMock(return_value=mock_session)-- cache.invalidate("query")- # Memory should be cleared even though DB failed- assert query_hash not in cache._memory_cache---# ----------------------------------------------------------------------------# clear_all – DB exception path-# ------------------------------------------------------------------------------class TestClearAllDbException:- """When the DB delete inside clear_all() fails, it returns False."""-- def test_clear_all_returns_false_on_db_error(self, tmp_path):- cache = _make_cache(tmp_path)-- mock_session = MagicMock()- mock_session.__enter__ = MagicMock(side_effect=RuntimeError("locked"))- mock_session.__exit__ = MagicMock(return_value=False)- cache.Session = MagicMock(return_value=mock_session)-- result = cache.clear_all()- assert result is False---# ----------------------------------------------------------------------------# get_stats – DB exception path-# ------------------------------------------------------------------------------class TestGetStatsDbException:- """When the DB query inside get_stats() fails, an error dict is returned."""-- def test_get_stats_returns_error_dict_on_db_failure(self, tmp_path):- cache = _make_cache(tmp_path)-- mock_session = MagicMock()- mock_session.__enter__ = MagicMock(side_effect=RuntimeError("gone"))- mock_session.__exit__ = MagicMock(return_value=False)- cache.Session = MagicMock(return_value=mock_session)-- stats = cache.get_stats()- assert "error" in stats- assert stats["error"] == "Cache stats unavailable"---# ----------------------------------------------------------------------------# get_or_fetch – stale event cleanup branch-# ------------------------------------------------------------------------------class TestGetOrFetchStaleEventCleanup:- """- When get_or_fetch encounters a stale (already-set) event for a query_hash,- it should clean up the old event/lock/result and create fresh ones, then- proceed to fetch.- """-- def test_stale_event_triggers_fresh_fetch(self, tmp_path):- cache = _make_cache(tmp_path)- query = "stale test query"- query_hash = cache._get_query_hash(query)-- # Pre-populate a stale (already-set) event- stale_event = threading.Event()- stale_event.set() # marks it as completed / stale- cache._fetch_events[query_hash] = stale_event- cache._fetch_locks[query_hash] = threading.Lock()- cache._fetch_results[query_hash] = [{"old": True}]-- fetch_called = threading.Event()-- def mock_fetch():- fetch_called.set()- return [{"fresh": True}]-- result = cache.get_or_fetch(query, mock_fetch)-- # The stale event should have been replaced and fetch should have run- assert fetch_called.is_set()- assert result == [{"fresh": True}]---# ----------------------------------------------------------------------------# _dispose_global_cache-# ------------------------------------------------------------------------------class TestDisposeGlobalCache:- """Tests for the module-level _dispose_global_cache function."""-- def test_dispose_global_cache_calls_dispose_and_resets(self):- """When _global_cache is set, dispose() is called and it is set to None."""- import local_deep_research.utilities.search_cache as sc-- mock_cache = MagicMock()- original = sc._global_cache- try:- sc._global_cache = mock_cache- sc._dispose_global_cache()- mock_cache.dispose.assert_called_once()- assert sc._global_cache is None- finally:- sc._global_cache = original-- def test_dispose_global_cache_noop_when_none(self):- """When _global_cache is already None, nothing happens."""- import local_deep_research.utilities.search_cache as sc-- original = sc._global_cache- try:- sc._global_cache = None- # Should not raise- sc._dispose_global_cache()- assert sc._global_cache is None- finally:- sc._global_cache = original---# ----------------------------------------------------------------------------# clear_all – memory is cleared even when DB fails-# ------------------------------------------------------------------------------class TestClearAllMemoryCleared:- """Verify memory caches are cleared before the DB call in clear_all."""-- def test_clear_all_clears_memory_even_on_db_error(self, tmp_path):- cache = _make_cache(tmp_path)- cache.put("q", [{"v": 1}])- assert len(cache._memory_cache) > 0-- # Break the DB- mock_session = MagicMock()- mock_session.__enter__ = MagicMock(side_effect=RuntimeError("boom"))- mock_session.__exit__ = MagicMock(return_value=False)- cache.Session = MagicMock(return_value=mock_session)-- cache.clear_all()- # Memory caches should still be cleared (they are cleared before DB call)- assert len(cache._memory_cache) == 0- assert len(cache._access_times) == 0diff --git a/tests/utilities/test_search_cache_eviction.py b/tests/utilities/test_search_cache_eviction.pydeleted file mode 100644index 53a86bfd7a..0000000000--- a/tests/utilities/test_search_cache_eviction.py+++ /dev/null@@ -1,172 +0,0 @@-"""Tests for SearchCache._normalize_query and _evict_lru_memory.--_normalize_query handles query normalization for consistent caching.-_evict_lru_memory manages memory cache size via LRU eviction.-Both have zero prior test coverage.-"""--import pytest--from local_deep_research.utilities.search_cache import SearchCache---def cache(tmp_path):- """Create a SearchCache with a temp database."""- return SearchCache(- cache_dir=str(tmp_path / "search_cache"),- default_ttl=3600,- max_memory_items=5,- )---# ── _normalize_query ──---class TestNormalizeQuery:- """Tests for _normalize_query method."""-- def test_converts_to_lowercase(self, cache):- assert cache._normalize_query("Hello World") == "hello world"-- def test_strips_whitespace(self, cache):- assert cache._normalize_query(" hello ") == "hello"-- def test_collapses_internal_whitespace(self, cache):- assert (- cache._normalize_query("hello world test") == "hello world test"- )-- def test_removes_double_quotes(self, cache):- assert cache._normalize_query('"hello world"') == "hello world"-- def test_removes_single_quotes(self, cache):- assert cache._normalize_query("it's a test") == "its a test"-- def test_preserves_other_punctuation(self, cache):- assert cache._normalize_query("hello, world!") == "hello, world!"-- def test_empty_string(self, cache):- assert cache._normalize_query("") == ""-- def test_tabs_and_newlines_collapsed(self, cache):- assert (- cache._normalize_query("hello\tworld\ntest") == "hello world test"- )-- def test_unicode_preserved(self, cache):- result = cache._normalize_query("Héllo Wörld")- assert result == "héllo wörld"-- def test_mixed_quotes_all_removed(self, cache):- result = cache._normalize_query("\"it's\" a 'test'")- assert '"' not in result- assert "'" not in result---# ── _evict_lru_memory ──---class TestEvictLruMemory:- """Tests for _evict_lru_memory method."""-- def test_no_eviction_when_under_limit(self, cache):- cache._memory_cache = {"a": 1, "b": 2}- cache._access_times = {"a": 100, "b": 200}- cache.max_memory_items = 5-- cache._evict_lru_memory()-- assert len(cache._memory_cache) == 2-- def test_eviction_when_over_limit(self, cache):- cache.max_memory_items = 3- # Add 5 items- for i in range(5):- key = f"key_{i}"- cache._memory_cache[key] = {"data": i}- cache._access_times[key] = i * 100 # Older items have lower times-- cache._evict_lru_memory()-- # Should have evicted to get below limit- assert len(cache._memory_cache) <= cache.max_memory_items-- def test_evicts_oldest_items_first(self, cache):- # _evict_lru_memory removes (count - max + 100) items for efficiency.- # With max=200 and count=250: removes 250-200+100=150 oldest items.- cache.max_memory_items = 200- for i in range(250):- cache._memory_cache[f"key_{i}"] = {"data": i}- cache._access_times[f"key_{i}"] = i-- cache._evict_lru_memory()-- remaining = set(cache._memory_cache.keys())- # 100 items should survive (250 - 150 removed)- assert len(remaining) == 100- # Remaining items should be the newest (highest access times)- for key in remaining:- idx = int(key.split("_")[1])- assert idx >= 150 # Only items 150-249 should survive-- def test_eviction_removes_from_both_caches(self, cache):- cache.max_memory_items = 1- cache._memory_cache = {"a": 1, "b": 2, "c": 3}- cache._access_times = {"a": 100, "b": 200, "c": 300}-- cache._evict_lru_memory()-- # Evicted items should be removed from both dicts- for key in list(cache._memory_cache.keys()):- assert key in cache._access_times-- def test_no_eviction_at_exact_limit(self, cache):- cache.max_memory_items = 3- cache._memory_cache = {"a": 1, "b": 2, "c": 3}- cache._access_times = {"a": 100, "b": 200, "c": 300}-- cache._evict_lru_memory()-- assert len(cache._memory_cache) == 3-- def test_empty_cache_no_error(self, cache):- cache._memory_cache = {}- cache._access_times = {}- cache.max_memory_items = 5-- cache._evict_lru_memory() # Should not raise-- assert len(cache._memory_cache) == 0---# ── _get_query_hash ──---class TestGetQueryHash:- """Tests for _get_query_hash determinism and partitioning."""-- def test_same_query_same_hash(self, cache):- h1 = cache._get_query_hash("hello world")- h2 = cache._get_query_hash("hello world")- assert h1 == h2-- def test_case_insensitive_hashing(self, cache):- h1 = cache._get_query_hash("Hello World")- h2 = cache._get_query_hash("hello world")- assert h1 == h2-- def test_different_engines_different_hashes(self, cache):- h1 = cache._get_query_hash("test", "google")- h2 = cache._get_query_hash("test", "bing")- assert h1 != h2-- def test_whitespace_normalized_before_hashing(self, cache):- h1 = cache._get_query_hash("hello world")- h2 = cache._get_query_hash("hello world")- assert h1 == h2-- def test_quotes_stripped_before_hashing(self, cache):- h1 = cache._get_query_hash('"hello world"')- h2 = cache._get_query_hash("hello world")- assert h1 == h2diff --git a/tests/utilities/test_search_cache_high_value.py b/tests/utilities/test_search_cache_high_value.pydeleted file mode 100644index 5e6d979b51..0000000000--- a/tests/utilities/test_search_cache_high_value.py+++ /dev/null@@ -1,382 +0,0 @@-"""-High-value pure-logic tests for search_cache.py.--Focuses on _normalize_query, _get_query_hash, _evict_lru_memory,-and normalize_entity_query with edge cases not covered by existing tests.-Uses init bypass via patch.object to avoid DB/filesystem side effects.-"""--import hashlib--from unittest.mock import patch--from local_deep_research.utilities.thread_context import clear_search_context---# ----------------------------------------------------------------------------# Helper: build a SearchCache without __init__ side effects-# ------------------------------------------------------------------------------def _make_cache(max_memory_items=1000, default_ttl=3600):- """Create a SearchCache instance with init bypassed."""- from local_deep_research.utilities.search_cache import SearchCache-- with patch.object(SearchCache, "__init__", lambda self, *a, **kw: None):- cache = SearchCache()- cache.max_memory_items = max_memory_items- cache.default_ttl = default_ttl- cache._memory_cache = {}- cache._access_times = {}- return cache---# ===========================================================================-# _normalize_query-# ===========================================================================---class TestNormalizeQueryHighValue:- """Edge-case and boundary tests for _normalize_query."""-- def test_only_whitespace_returns_empty(self):- """A string of only spaces/tabs normalizes to empty string."""- cache = _make_cache()- assert cache._normalize_query(" \t \n ") == ""-- def test_only_quotes_returns_empty(self):- """A string containing only quotes normalizes to empty."""- cache = _make_cache()- assert cache._normalize_query("\"'\"'") == ""-- def test_mixed_case_with_numbers(self):- """Numbers are preserved while letters are lowered."""- cache = _make_cache()- assert (- cache._normalize_query("Python 3.12 RELEASE")- == "python 3.12 release"- )-- def test_multiple_consecutive_quotes_removed(self):- """Back-to-back quotes are all stripped."""- cache = _make_cache()- assert cache._normalize_query("'''hello'''") == "hello"-- def test_newline_and_carriage_return_collapsed(self):- """CR and LF are treated as whitespace and collapsed."""- cache = _make_cache()- assert cache._normalize_query("hello\r\nworld") == "hello world"-- def test_preserves_hyphens_and_underscores(self):- """Hyphens and underscores are not stripped."""- cache = _make_cache()- result = cache._normalize_query("self-driving_cars")- assert result == "self-driving_cars"-- def test_unicode_lowercasing(self):- """Non-ASCII characters are lowercased properly."""- cache = _make_cache()- assert cache._normalize_query("STRASSE") == "strasse"- assert cache._normalize_query("CAFE") == "cafe"-- def test_idempotent(self):- """Normalizing an already-normalized string returns same result."""- cache = _make_cache()- first = cache._normalize_query(" HELLO 'world' ")- second = cache._normalize_query(first)- assert first == second-- def test_single_character(self):- """Single character query works."""- cache = _make_cache()- assert cache._normalize_query("A") == "a"-- def test_query_with_embedded_tabs(self):- """Tabs between words are collapsed to single space."""- cache = _make_cache()- assert cache._normalize_query("a\t\tb\t\tc") == "a b c"---# ===========================================================================-# _get_query_hash-# ===========================================================================---class TestGetQueryHashHighValue:- """Edge-case and determinism tests for _get_query_hash."""-- def setup_method(self):- """Clear any leaked search context before each test."""- clear_search_context()-- 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) == 64- assert all(c in "0123456789abcdef" for c in result)-- def test_hash_matches_manual_sha256(self):- """Hash matches manually computed SHA-256 of- 'username:scope:engine:normalized_query'. The scope component- (N17) defaults to 'adaptive' (the registered default) when no- policy snapshot is in context."""- cache = _make_cache()- result = cache._get_query_hash("Hello World", search_engine="google")- # No search context set: username empty, scope defaults to "adaptive".- expected_input = ":adaptive: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 = ":adaptive:default:test"- expected = hashlib.sha256(expected_input.encode()).hexdigest()- assert result == expected-- def test_empty_query_hashes_consistently(self):- """Empty string query produces a valid, consistent hash."""- cache = _make_cache()- h1 = cache._get_query_hash("")- h2 = cache._get_query_hash("")- assert h1 == h2- assert len(h1) == 64-- def test_same_query_different_engines_differ(self):- """Same normalized query with different engines yields different hashes."""- cache = _make_cache()- hashes = {- cache._get_query_hash("test", engine)- for engine in ["google", "bing", "duckduckgo", "default"]- }- assert len(hashes) == 4-- def test_normalization_applied_before_hashing(self):- """Queries that differ only by case/whitespace/quotes hash equally."""- cache = _make_cache()- variants = [- "Hello World",- " hello world ",- "'hello' \"world\"",- "HELLO WORLD",- ]- 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-# ===========================================================================---class TestEvictLruMemoryHighValue:- """Edge-case and boundary tests for LRU eviction logic."""-- def test_no_eviction_when_empty(self):- """Empty cache triggers no eviction and no errors."""- cache = _make_cache(max_memory_items=10)- cache._evict_lru_memory()- assert len(cache._memory_cache) == 0-- def test_no_eviction_at_exact_limit(self):- """Cache at exactly max_memory_items does not evict."""- cache = _make_cache(max_memory_items=3)- cache._memory_cache = {"a": 1, "b": 2, "c": 3}- cache._access_times = {"a": 10, "b": 20, "c": 30}- cache._evict_lru_memory()- assert len(cache._memory_cache) == 3-- def test_eviction_removes_extra_100_beyond_needed(self):- """Eviction removes (count - max + 100) items for efficiency."""- cache = _make_cache(max_memory_items=50)- for idx in range(60):- key = f"k{idx}"- cache._memory_cache[key] = idx- cache._access_times[key] = idx- # items_to_remove = 60 - 50 + 100 = 110, but only 60 items exist- # so all 60 will be attempted for removal (capped by sorted list)- cache._evict_lru_memory()- # All items removed since items_to_remove > total- assert len(cache._memory_cache) == 0-- def test_eviction_preserves_newest_when_buffer_fits(self):- """When count - max + 100 < count, newest items survive."""- cache = _make_cache(max_memory_items=200)- for idx in range(250):- key = f"item_{idx}"- cache._memory_cache[key] = {"val": idx}- cache._access_times[key] = idx # lower idx = older- # items_to_remove = 250 - 200 + 100 = 150- cache._evict_lru_memory()- assert len(cache._memory_cache) == 100- # Only items 150..249 should remain- for idx in range(150, 250):- assert f"item_{idx}" in cache._memory_cache-- def test_eviction_keeps_access_times_in_sync(self):- """After eviction, _memory_cache and _access_times have same keys."""- cache = _make_cache(max_memory_items=5)- for idx in range(20):- key = f"k{idx}"- cache._memory_cache[key] = idx- cache._access_times[key] = idx * 10- cache._evict_lru_memory()- assert set(cache._memory_cache.keys()) == set(- cache._access_times.keys()- )-- def test_eviction_with_equal_access_times(self):- """Eviction still works when all access times are identical."""- cache = _make_cache(max_memory_items=2)- for idx in range(5):- key = f"k{idx}"- cache._memory_cache[key] = idx- cache._access_times[key] = 100 # all same timestamp- cache._evict_lru_memory()- # items_to_remove = 5 - 2 + 100 = 103, so all removed- assert len(cache._memory_cache) == 0-- def test_single_item_over_limit(self):- """max_memory_items=0 with one item triggers eviction."""- cache = _make_cache(max_memory_items=0)- cache._memory_cache = {"only": "item"}- cache._access_times = {"only": 999}- cache._evict_lru_memory()- assert len(cache._memory_cache) == 0-- def test_access_times_missing_key_does_not_crash(self):- """If a memory_cache key is missing from access_times, no crash."""- cache = _make_cache(max_memory_items=1)- cache._memory_cache = {"a": 1, "b": 2, "c": 3}- # Only some keys in access_times -- eviction sorts on access_times- cache._access_times = {"a": 10, "c": 30}- # Should not raise; eviction pops from both dicts safely- cache._evict_lru_memory()- # Just verify no crash and some items were removed- assert len(cache._memory_cache) <= 1 or len(cache._memory_cache) == 3---# ===========================================================================-# normalize_entity_query (standalone function)-# ===========================================================================---class TestNormalizeEntityQueryHighValue:- """Edge-case tests for the standalone normalize_entity_query function."""-- @staticmethod- def _get_fn():- from local_deep_research.utilities.search_cache import (- normalize_entity_query,- )-- normalize_entity_query.cache_clear()- return normalize_entity_query-- def test_entity_with_quotes_preserved(self):- """Unlike _normalize_query, normalize_entity_query does NOT strip quotes."""- fn = self._get_fn()- result = fn('"quoted"', "constraint")- assert (- '"' in result- ) # quotes remain because function only splits/strips-- def test_constraint_with_quotes_preserved(self):- """Quotes in constraint are preserved."""- fn = self._get_fn()- result = fn("entity", "'quoted'")- assert "'" in result-- def test_very_long_inputs(self):- """Long entity and constraint strings are handled."""- fn = self._get_fn()- entity = "word " * 500- constraint = "term " * 500- result = fn(entity.strip(), constraint.strip())- assert "word" in result- assert "term" in result-- def test_numeric_entity(self):- """Purely numeric entity is preserved."""- fn = self._get_fn()- result = fn("12345", "count")- assert result == "12345 count"-- def test_entity_and_constraint_separated_by_single_space(self):- """Output always has exactly one space between entity and constraint."""- fn = self._get_fn()- result = fn("abc", "xyz")- assert result == "abc xyz"- # No double spaces- assert " " not in result-- def test_mixed_whitespace_in_both(self):- """Tabs, newlines, and multiple spaces all collapse."""- fn = self._get_fn()- result = fn("a\t\tb", "c\n\nd")- assert result == "a b c d"-- def test_cache_distinguishes_swapped_args(self):- """(entity, constraint) != (constraint, entity) in cache."""- fn = self._get_fn()- r1 = fn("alpha", "beta")- r2 = fn("beta", "alpha")- assert r1 != r2- info = fn.cache_info()- assert info.misses == 2diff --git a/tests/utilities/test_search_cache_persistence.py b/tests/utilities/test_search_cache_persistence.pydeleted file mode 100644index 9c0a5accb5..0000000000--- a/tests/utilities/test_search_cache_persistence.py+++ /dev/null@@ -1,175 +0,0 @@-"""Tests for search cache persistence and caching edge cases.--These tests exercise the SearchCache's persistence across instances,-the get_or_fetch lifecycle with falsy results, and JSON serialization-roundtrips through SQLite.-"""--import pytest--from local_deep_research.utilities.search_cache import SearchCache---def cache_dir(tmp_path):- """Provide a temporary cache directory."""- return str(tmp_path / "test_cache")---def cache(cache_dir):- """Provide a SearchCache instance with a temporary directory."""- c = SearchCache(cache_dir=cache_dir)- yield c- c.dispose()---class TestPersistenceAcrossInstances:- """Tests for data surviving across cache instance lifecycles."""-- def test_persistence_across_cache_instances(self, cache_dir):- """Data put with instance 1 survives after dispose and re-creation.- This is the fundamental purpose of the persistent cache."""- cache1 = SearchCache(cache_dir=cache_dir)- results = [{"title": "Persistent Result", "url": "https://example.com"}]- cache1.put("persistent query", results, "test_engine")- cache1.dispose()-- # Create a new instance with the same directory- cache2 = SearchCache(cache_dir=cache_dir)- retrieved = cache2.get("persistent query", "test_engine")- cache2.dispose()-- assert retrieved is not None- assert len(retrieved) == 1- assert retrieved[0]["title"] == "Persistent Result"---class TestGetOrFetchWithFalsyResults:- """Tests for get_or_fetch behavior with empty/None results."""-- def test_empty_list_result_not_cached_via_get_or_fetch(self, cache):- """fetch_func returns [] (falsy) — it's returned to caller but NOT- cached, causing re-fetch on next call. This documents the behavior- where put() rejects empty results."""- call_count = 0-- def fetch_empty():- nonlocal call_count- call_count += 1- return []-- # First call: fetches and returns []- result1 = cache.get_or_fetch("empty query", fetch_empty, "test_engine")- assert result1 == []- assert call_count == 1-- # Clear memory cache to force DB lookup- cache._memory_cache.clear()-- # Second call: fetches AGAIN because [] wasn't cached- result2 = cache.get_or_fetch("empty query", fetch_empty, "test_engine")- assert result2 == []- assert (- call_count == 2- ) # Called again because empty results aren't cached-- def test_fetch_returning_none_path(self, cache):- """fetch_func returning None (not exception) goes through the full- stampede protection path and returns None."""-- def fetch_none():- return None-- result = cache.get_or_fetch("none query", fetch_none, "test_engine")- assert result is None-- def test_fetch_exception_returns_none(self, cache):- """fetch_func raising an exception returns None (not the exception)."""-- def fetch_error():- raise RuntimeError("network error")-- result = cache.get_or_fetch("error query", fetch_error, "test_engine")- assert result is None---class TestMemoryCacheMasksDbAccess:- """Tests documenting memory cache interaction with DB stats."""-- def test_memory_cache_masks_db_access_count(self, cache):- """Memory cache satisfies reads, so DB access_count never increments- beyond the initial put. This documents a stats limitation."""- results = [{"title": "Test", "url": "https://example.com"}]- cache.put("stats query", results, "test_engine")-- # Multiple reads from memory cache- for _ in range(5):- cache.get("stats query", "test_engine")-- # Check DB access_count - should be 1 (from initial put)- # because all reads were served from memory cache- with cache.Session() as session:- from local_deep_research.database.models import (- SearchCache as SearchCacheModel,- )-- query_hash = cache._get_query_hash("stats query", "test_engine")- entry = (- session.query(SearchCacheModel)- .filter_by(query_hash=query_hash)- .first()- )- assert entry is not None- # access_count stays at 1 because memory cache serves all reads- assert entry.access_count == 1---class TestJsonSerializationRoundtrip:- """Tests for complex data surviving SQLite JSON serialization."""-- def test_complex_nested_results_json_roundtrip(self, cache_dir):- """Deeply nested structures with None, unicode, and special chars- survive the SQLite JSON serialization roundtrip."""- complex_results = [- {- "title": "Unicode Test: \u00e4\u00f6\u00fc \u00df \u2603 \u2764",- "url": "https://example.com/path?q=test&lang=en",- "metadata": {- "nested": {- "deep": {- "value": 42,- "list": [1, None, "three", True, False],- }- },- "empty_dict": {},- "empty_list": [],- "null_value": None,- },- "snippet": 'Text with "quotes" and\nnewlines\tand\ttabs',- }- ]-- cache = SearchCache(cache_dir=cache_dir)- cache.put("complex query", complex_results, "test_engine")- cache.dispose()-- # Retrieve from a fresh instance (forces DB read)- cache2 = SearchCache(cache_dir=cache_dir)- retrieved = cache2.get("complex query", "test_engine")- cache2.dispose()-- assert retrieved is not None- assert len(retrieved) == 1- result = retrieved[0]- assert "\u00e4\u00f6\u00fc" in result["title"]- assert result["metadata"]["nested"]["deep"]["value"] == 42- assert result["metadata"]["nested"]["deep"]["list"] == [- 1,- None,- "three",- True,- False,- ]- assert result["metadata"]["null_value"] is None- assert "\n" in result["snippet"]diff --git a/tests/utilities/test_search_cache_stampede.py b/tests/utilities/test_search_cache_stampede.pydeleted file mode 100644index 67c40bfd5f..0000000000--- a/tests/utilities/test_search_cache_stampede.py+++ /dev/null@@ -1,644 +0,0 @@-"""-Tests for search_cache.py - Stampede Protection, LRU Eviction, Query Normalization, TTL--Tests cover edge cases, concurrency scenarios, and error conditions that could-cause production issues.-"""--import tempfile-import threading-import time-from concurrent.futures import ThreadPoolExecutor, as_completed-from unittest.mock import patch--import pytest-from freezegun import freeze_time---class TestStampedeProtectionConcurrency:- """Tests for stampede protection in concurrent scenarios."""-- @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_concurrent_requests_single_fetch(self, cache):- """Multiple threads requesting same query should result in single fetch call."""- fetch_count = 0- fetch_lock = threading.Lock()-- def slow_fetch():- nonlocal fetch_count- with fetch_lock:- fetch_count += 1- time.sleep(0.1) # Simulate slow fetch- return [{"title": "Result", "link": "https://example.com"}]-- threads = []- results = []- result_lock = threading.Lock()-- def worker():- result = cache.get_or_fetch("test query", slow_fetch, "engine1")- with result_lock:- results.append(result)-- # Start 5 concurrent threads requesting the same query- for _ in range(5):- t = threading.Thread(target=worker)- threads.append(t)- t.start()-- for t in threads:- t.join(timeout=5)-- # Only one fetch should have occurred- assert fetch_count == 1- # All threads should have received results- assert len(results) == 5- for r in results:- assert r is not None-- def test_waiting_thread_receives_result(self, cache):- """Thread waiting on event should get result when fetch completes."""- fetch_started = threading.Event()- fetch_complete = threading.Event()-- def controlled_fetch():- fetch_started.set()- fetch_complete.wait(timeout=5)- return [{"title": "Fetched", "link": "https://example.com"}]-- results = []-- def fetching_worker():- result = cache.get_or_fetch(- "shared query", controlled_fetch, "engine1"- )- results.append(("fetcher", result))-- def waiting_worker():- # Wait for fetch to start- fetch_started.wait(timeout=5)- time.sleep(0.05) # Ensure we're waiting on the fetch- result = cache.get_or_fetch(- "shared query", lambda: "should not run", "engine1"- )- results.append(("waiter", result))-- t1 = threading.Thread(target=fetching_worker)- t2 = threading.Thread(target=waiting_worker)-- t1.start()- t2.start()-- # Let the fetch complete- fetch_started.wait(timeout=2)- time.sleep(0.1) # Give waiter time to start waiting- fetch_complete.set()-- t1.join(timeout=5)- t2.join(timeout=5)-- assert len(results) == 2- # Both should have received the same result- for role, result in results:- assert result is not None- assert result[0]["title"] == "Fetched"-- def test_fetch_failure_handled_by_waiters(self, cache):- """When fetch fails, waiting threads handle gracefully."""- fetch_started = threading.Event()-- def failing_fetch():- fetch_started.set()- time.sleep(0.1)- raise RuntimeError("Fetch failed")-- results = []-- def worker():- result = cache.get_or_fetch(- "failing query", failing_fetch, "engine1"- )- results.append(result)-- t1 = threading.Thread(target=worker)- t2 = threading.Thread(target=worker)-- t1.start()- fetch_started.wait(timeout=2)- time.sleep(0.05)- t2.start()-- t1.join(timeout=5)- t2.join(timeout=5)-- # Both should have None results (failure case)- assert len(results) == 2- # At least one should be None due to failure- assert any(r is None for r in results)-- def test_stale_event_cleanup(self, cache):- """Completed fetch events are properly cleaned up."""-- def quick_fetch():- return [{"title": "Quick", "link": "https://example.com"}]-- # First fetch- cache.get_or_fetch("cleanup test", quick_fetch, "engine1")-- # Wait for cleanup thread- time.sleep(3) # allow: unmarked-sleep-- # Internal state should be cleaned up- query_hash = cache._get_query_hash("cleanup test", "engine1")- assert query_hash not in cache._fetch_events- assert query_hash not in cache._fetch_locks- assert query_hash not in cache._fetch_results-- def test_timeout_on_waiting_for_event(self, cache):- """30-second timeout works properly (structure test)."""- # We can't easily test 30 second timeout, but we can verify the mechanism- # by checking the source code contains the timeout parameter-- import inspect-- source = inspect.getsource(cache.get_or_fetch)- # The wait call in the code has a timeout parameter- assert "timeout=30" in source or "timeout=" in source- # The timeout is hardcoded to 30 seconds in the code-- def test_cleanup_thread_execution(self, cache):- """Background cleanup thread removes fetch artifacts."""-- def fetch_func():- return [{"title": "Cleanup test", "link": "https://example.com"}]-- cache.get_or_fetch("cleanup thread test", fetch_func, "engine1")- query_hash = cache._get_query_hash("cleanup thread test", "engine1")-- # Immediately after fetch, artifacts should exist- # Note: They might already be cleaned up by the daemon thread- # Wait for cleanup (2 second delay + some buffer)- time.sleep(3) # allow: unmarked-sleep-- # After cleanup, should be removed- assert query_hash not in cache._fetch_events- assert query_hash not in cache._fetch_locks-- def test_many_concurrent_requests(self, cache):- """20+ threads requesting same key simultaneously."""- fetch_count = 0- lock = threading.Lock()-- def counting_fetch():- nonlocal fetch_count- with lock:- fetch_count += 1- time.sleep(0.05)- return [{"title": "Mass test", "link": "https://example.com"}]-- results = []- result_lock = threading.Lock()-- def worker():- result = cache.get_or_fetch("mass query", counting_fetch, "engine1")- with result_lock:- results.append(result)-- with ThreadPoolExecutor(max_workers=25) as executor:- futures = [executor.submit(worker) for _ in range(25)]- for f in as_completed(futures, timeout=10):- f.result()-- # Should have only fetched once- assert fetch_count == 1- # All threads should have results- assert len(results) == 25- assert all(r is not None for r in results)-- def test_different_keys_independent(self, cache):- """Concurrent requests for different keys don't block each other.-- Measure each thread's fetch-end timestamp and assert their spread is- small. If the cache's per-key locking forced serialization, end times- would be staggered by ~0.1s each (≥0.4s spread for 5 threads). True- parallelism makes the spread close to zero, plus thread-scheduling- jitter — independent of overall CI load (which previously dominated- wall-clock thresholds and made the test flaky on slow runners).- """- end_times = {}- lock = threading.Lock()-- def timed_fetch(key):- time.sleep(0.1)- with lock:- end_times[key] = time.time()- return [- {"title": f"Result {key}", "link": f"https://example.com/{key}"}- ]-- def worker(key):- cache.get_or_fetch(- f"query_{key}", lambda: timed_fetch(key), "engine1"- )-- threads = [threading.Thread(target=worker, args=(i,)) for i in range(5)]- for t in threads:- t.start()- for t in threads:- t.join(timeout=5)-- assert len(end_times) == 5, "Some threads failed to complete"-- # Serial floor: spread ≥ 0.4s (4 gaps of 0.1s between 5 sleeps).- # Parallel: spread is just thread-scheduling jitter.- # 0.3s threshold sits well below the serial floor and well above- # realistic jitter, even on loaded runners.- spread = max(end_times.values()) - min(end_times.values())- assert spread < 0.3, (- f"End-times spread {spread:.3f}s suggests serialization "- f"(serial floor is 0.4s). End times: {sorted(end_times.values())}"- )---class TestLRUEviction:- """Tests for LRU eviction behavior."""-- @pytest.fixture- def small_cache(self):- """Create a cache with small max_memory_items for eviction testing."""- with tempfile.TemporaryDirectory() as tmpdir:- from local_deep_research.utilities.search_cache import SearchCache-- cache = SearchCache(- cache_dir=tmpdir, max_memory_items=5, default_ttl=3600- )- yield cache-- def test_eviction_at_max_items(self, small_cache):- """Items evicted when max_memory_items exceeded."""- # Add more items than the limit- for i in range(10):- small_cache.put(f"query_{i}", [{"title": f"Result {i}"}], "engine1")-- # Memory cache should not exceed max + cleanup buffer- assert (- len(small_cache._memory_cache) <= small_cache.max_memory_items + 100- )-- def test_access_time_updates_on_get(self, small_cache):- """Getting item updates access time."""- small_cache.put("test_query", [{"title": "Test"}], "engine1")- query_hash = small_cache._get_query_hash("test_query", "engine1")-- initial_access_time = small_cache._access_times.get(query_hash)-- time.sleep(0.1)-- # Access the item- small_cache.get("test_query", "engine1")-- new_access_time = small_cache._access_times.get(query_hash)-- assert new_access_time >= initial_access_time-- def test_eviction_order_with_concurrent_access(self, small_cache):- """LRU order maintained under concurrent access."""- # Pre-populate cache- for i in range(5):- small_cache.put(- f"concurrent_{i}", [{"title": f"Result {i}"}], "engine1"- )-- def access_worker(key):- for _ in range(10):- small_cache.get(f"concurrent_{key}", "engine1")- time.sleep(0.001)-- threads = [- threading.Thread(target=access_worker, args=(i,)) for i in range(3)- ]- for t in threads:- t.start()- for t in threads:- t.join(timeout=5)-- # Cache should still be functional - get shouldn't crash- small_cache.get("concurrent_0", "engine1")- # Result might be None if evicted, but shouldn't raise an exception-- def test_memory_cache_size_tracking(self, small_cache):- """Size accurately tracked during add/evict."""- initial_size = len(small_cache._memory_cache)-- small_cache.put("track_test", [{"title": "Tracked"}], "engine1")-- # Size should have increased- assert len(small_cache._memory_cache) == initial_size + 1-- # Access times should match memory cache- assert len(small_cache._access_times) == len(small_cache._memory_cache)---class TestQueryNormalization:- """Tests for query normalization."""-- @pytest.fixture- def cache(self):- """Create a fresh cache instance."""- 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_case_insensitive_matching(self, cache):- """'Hello World' and 'hello world' hit same cache."""- cache.put("Hello World", [{"title": "Result"}], "engine1")-- result = cache.get("hello world", "engine1")- assert result is not None- assert result[0]["title"] == "Result"-- def test_whitespace_normalization(self, cache):- """Extra whitespace normalized."""- cache.put("query with spaces", [{"title": "Spaced"}], "engine1")-- result = cache.get("query with spaces", "engine1")- assert result is not None- assert result[0]["title"] == "Spaced"-- # Leading/trailing whitespace too- result2 = cache.get(" query with spaces ", "engine1")- assert result2 is not None-- def test_quote_removal(self, cache):- """Quotes removed for normalization."""- cache.put('search "with quotes"', [{"title": "Quoted"}], "engine1")-- result = cache.get("search with quotes", "engine1")- assert result is not None- assert result[0]["title"] == "Quoted"-- # Single quotes too- cache.put("search 'single quotes'", [{"title": "Single"}], "engine1")- result2 = cache.get("search single quotes", "engine1")- assert result2 is not None-- def test_search_engine_partitioning(self, cache):- """Different engines have different cache keys."""- cache.put("shared query", [{"title": "Engine1"}], "engine1")- cache.put("shared query", [{"title": "Engine2"}], "engine2")-- result1 = cache.get("shared query", "engine1")- result2 = cache.get("shared query", "engine2")-- assert result1[0]["title"] == "Engine1"- assert result2[0]["title"] == "Engine2"-- def test_special_characters_preserved(self, cache):- """Non-quote special chars preserved."""- cache.put("query with @#$% symbols", [{"title": "Special"}], "engine1")-- result = cache.get("query with @#$% symbols", "engine1")- assert result is not None- assert result[0]["title"] == "Special"-- def test_empty_query_handling(self, cache):- """Empty strings handled gracefully."""- # Empty query shouldn't crash- result = cache.get("", "engine1")- assert result is None-- # Put empty results shouldn't work- success = cache.put("", [], "engine1")- assert success is False # Empty results shouldn't be cached---class TestTTLExpiration:- """Tests for TTL-based expiration."""-- @pytest.fixture- def short_ttl_cache(self):- """Create a cache with very short TTL for expiration testing."""- 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=1- ) # 1 second TTL- yield cache-- def test_expired_entry_not_returned(self, short_ttl_cache):- """Expired entry returns None."""- # SUT compares int(time.time()) against stored expires_at, so we can- # freeze the clock and tick forward instead of sleeping real time.- with freeze_time("2026-01-01 00:00:00") as frozen:- short_ttl_cache.put(- "expiring", [{"title": "Temp"}], "engine1", ttl=4- )-- # Immediately should work- result = short_ttl_cache.get("expiring", "engine1")- assert result is not None-- # Advance past expiration- frozen.tick(5)-- result = short_ttl_cache.get("expiring", "engine1")- assert result is None-- def test_expired_entry_removed_from_memory(self, short_ttl_cache):- """Expired entry removed on access."""- with freeze_time("2026-01-01 00:00:00") as frozen:- short_ttl_cache.put(- "memory_expire", [{"title": "Temp"}], "engine1", ttl=2- )- query_hash = short_ttl_cache._get_query_hash(- "memory_expire", "engine1"- )-- assert query_hash in short_ttl_cache._memory_cache-- frozen.tick(3)-- # Access triggers removal- short_ttl_cache.get("memory_expire", "engine1")-- assert query_hash not in short_ttl_cache._memory_cache-- def test_cleanup_removes_expired_from_database(self, short_ttl_cache):- """_cleanup_expired removes DB entries."""- with freeze_time("2026-01-01 00:00:00") as frozen:- short_ttl_cache.put(- "db_expire", [{"title": "DB"}], "engine1", ttl=2- )-- frozen.tick(3)-- # Run cleanup- short_ttl_cache._cleanup_expired()-- # Should not be in database- result = short_ttl_cache.get("db_expire", "engine1")- assert result is None-- def test_ttl_boundary_condition(self, short_ttl_cache):- """Entry at exact TTL boundary."""- # Use a mock to test boundary precisely- with patch("time.time") as mock_time:- mock_time.return_value = 1000-- short_ttl_cache.put(- "boundary", [{"title": "Boundary"}], "engine1", ttl=100- )-- # At exactly TTL boundary (expires_at = 1100)- mock_time.return_value = 1100-- # Entry should be expired at exact boundary- # (expires_at > current_time is the check, so at 1100 it's expired)- query_hash = short_ttl_cache._get_query_hash("boundary", "engine1")- entry = short_ttl_cache._memory_cache.get(query_hash)- if entry:- # At boundary, expires_at (1100) is not > current_time (1100)- assert entry["expires_at"] <= 1100-- def test_ttl_with_clock_drift(self):- """Handles minor time inconsistencies."""- 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- )-- # This tests that the cache doesn't break with normal time progression- cache.put("drift_test", [{"title": "Drift"}], "engine1")-- # Multiple rapid accesses shouldn't cause issues- for _ in range(100):- cache.get("drift_test", "engine1")-- result = cache.get("drift_test", "engine1")- assert result is not None-- def test_negative_ttl_immediate_expiry(self):- """Negative TTL expires immediately; zero TTL uses default (code behavior)."""- 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- )-- # Negative TTL - definitely expired- cache.put(- "negative_ttl", [{"title": "Negative"}], "engine1", ttl=-10- )- result = cache.get("negative_ttl", "engine1")- assert result is None-- # Note: Zero TTL uses default TTL due to `ttl or self.default_ttl` in the code- # This documents the current behavior - 0 is falsy, so default is used- cache.put("zero_ttl", [{"title": "Zero"}], "engine1", ttl=0)- result = cache.get("zero_ttl", "engine1")- # With ttl=0, the code uses default_ttl (3600), so it's NOT expired- assert result is not None # Documents actual behavior---class TestCacheStatistics:- """Tests for cache statistics functionality."""-- @pytest.fixture- def cache(self):- """Create a fresh cache instance."""- 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_get_stats_returns_valid_structure(self, cache):- """Stats return expected keys."""- stats = cache.get_stats()-- assert "total_valid_entries" in stats- assert "expired_entries" in stats- assert "memory_cache_size" in stats- assert "average_access_count" in stats- assert "cache_hit_potential" in stats-- def test_stats_update_after_operations(self, cache):- """Stats reflect cache operations."""- initial_stats = cache.get_stats()-- cache.put("stats_test", [{"title": "Test"}], "engine1")-- new_stats = cache.get_stats()-- assert (- new_stats["memory_cache_size"]- == initial_stats["memory_cache_size"] + 1- )---class TestCacheInvalidation:- """Tests for cache invalidation."""-- @pytest.fixture- def cache(self):- """Create a fresh cache instance."""- 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_invalidate_removes_entry(self, cache):- """Invalidate removes specific entry."""- cache.put("to_invalidate", [{"title": "Remove"}], "engine1")-- assert cache.get("to_invalidate", "engine1") is not None-- cache.invalidate("to_invalidate", "engine1")-- assert cache.get("to_invalidate", "engine1") is None-- def test_invalidate_specific_engine(self, cache):- """Invalidate only affects specified engine."""- cache.put("shared", [{"title": "E1"}], "engine1")- cache.put("shared", [{"title": "E2"}], "engine2")-- cache.invalidate("shared", "engine1")-- assert cache.get("shared", "engine1") is None- assert cache.get("shared", "engine2") is not None-- def test_clear_all_removes_everything(self, cache):- """Clear all empties entire cache."""- for i in range(10):- cache.put(f"query_{i}", [{"title": f"R{i}"}], "engine1")-- cache.clear_all()-- for i in range(10):- assert cache.get(f"query_{i}", "engine1") is None-- assert len(cache._memory_cache) == 0- assert len(cache._access_times) == 0