Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix: Rename settings cache directory to settings_cache

LearningCircuite0874237b6b7
diff --git a/src/local_deep_research/settings/cached_manager.py b/src/local_deep_research/settings/cached_manager.py
index 856a32a88d..05fca7692f 100644
--- a/src/local_deep_research/settings/cached_manager.py
+++ b/src/local_deep_research/settings/cached_manager.py
@@ -10,8 +10,8 @@ from sqlalchemy.orm import Session
from loguru import logger
from .manager import SettingsManager
-from .cache.decorators import cached, invalidate_cache
-from .cache.strategies import HierarchicalInvalidationStrategy
+from .settings_cache.decorators import cached, invalidate_cache
+from .settings_cache.strategies import HierarchicalInvalidationStrategy
from ..database.models import Setting
from ..web.models.settings import BaseSetting
@@ -124,7 +124,7 @@ class CachedSettingsManager(SettingsManager):
# Full cache invalidation after bulk import
if self._cache_strategy:
# Use full invalidation for bulk operations
- from .cache.strategies import FullInvalidationStrategy
+ from .settings_cache.strategies import FullInvalidationStrategy
strategy = FullInvalidationStrategy()
strategy.invalidate(self.user_id, "settings", [])
@@ -140,7 +140,7 @@ class CachedSettingsManager(SettingsManager):
self._cache_strategy.invalidate(self.user_id, "settings", keys)
else:
# Full invalidation
- from .cache.strategies import FullInvalidationStrategy
+ from .settings_cache.strategies import FullInvalidationStrategy
strategy = FullInvalidationStrategy()
strategy.invalidate(self.user_id, "settings", [])
diff --git a/src/local_deep_research/settings/settings_cache/__init__.py b/src/local_deep_research/settings/settings_cache/__init__.py
new file mode 100644
index 0000000000..65d6fff9cc
--- /dev/null
+++ b/src/local_deep_research/settings/settings_cache/__init__.py
@@ -0,0 +1,20 @@
+"""
+Cache infrastructure for settings management.
+
+This module provides caching decorators and strategies for the settings system.
+"""
+
+from .decorators import cached, invalidate_cache
+from .strategies import (
+ CacheStrategy,
+ KeyInvalidationStrategy,
+ PatternInvalidationStrategy,
+)
+
+__all__ = [
+ "cached",
+ "invalidate_cache",
+ "CacheStrategy",
+ "KeyInvalidationStrategy",
+ "PatternInvalidationStrategy",
+]
diff --git a/src/local_deep_research/settings/settings_cache/decorators.py b/src/local_deep_research/settings/settings_cache/decorators.py
new file mode 100644
index 0000000000..244bd9f0a5
--- /dev/null
+++ b/src/local_deep_research/settings/settings_cache/decorators.py
@@ -0,0 +1,163 @@
+"""
+Cache decorators for settings management.
+
+This module provides decorators to add caching functionality to any method
+without changing its implementation.
+"""
+
+import functools
+from typing import Callable, Optional
+from loguru import logger
+
+from ...memory_cache.config import get_thread_local_cache
+
+
+def cached(
+ namespace: str = "settings",
+ ttl: Optional[int] = None,
+ key_prefix: Optional[str] = None,
+) -> Callable:
+ """
+ Decorator to cache method results.
+
+ Args:
+ namespace: Cache namespace
+ ttl: Time to live in seconds (None for default)
+ key_prefix: Optional prefix for cache keys
+
+ Returns:
+ Decorated function
+ """
+
+ def decorator(func: Callable) -> Callable:
+ @functools.wraps(func)
+ def wrapper(self, *args, **kwargs):
+ # Build cache key
+ cache_key = f"{func.__name__}"
+ if args:
+ cache_key += f":{':'.join(str(arg) for arg in args)}"
+ if kwargs:
+ sorted_kwargs = sorted(kwargs.items())
+ cache_key += (
+ f":{':'.join(f'{k}={v}' for k, v in sorted_kwargs)}"
+ )
+
+ if key_prefix:
+ cache_key = f"{key_prefix}:{cache_key}"
+
+ # Get cache instance
+ cache = get_thread_local_cache()
+
+ # Try to get from cache
+ try:
+ # For settings, we need the user_id
+ user_id = getattr(self, "user_id", "global")
+ value = cache.get(user_id, namespace, cache_key)
+
+ # Check if we got a value (not NO_VALUE)
+ from dogpile.cache.api import NO_VALUE
+
+ if value is not NO_VALUE:
+ logger.debug(f"Cache hit for {namespace}:{cache_key}")
+ return value
+ except Exception as e:
+ logger.warning(f"Cache get failed for {cache_key}: {e}")
+
+ # Call the original function
+ result = func(self, *args, **kwargs)
+
+ # Store in cache
+ try:
+ user_id = getattr(self, "user_id", "global")
+ expiration_time = ttl if ttl is not None else None
+ cache.set(
+ user_id,
+ namespace,
+ cache_key,
+ result,
+ expiration_time=expiration_time,
+ )
+ logger.debug(f"Cached result for {namespace}:{cache_key}")
+ except Exception as e:
+ logger.warning(f"Cache set failed for {cache_key}: {e}")
+
+ return result
+
+ # Store metadata on wrapper for introspection
+ wrapper._cached = True
+ wrapper._cache_namespace = namespace
+ wrapper._cache_ttl = ttl
+
+ return wrapper
+
+ return decorator
+
+
+def invalidate_cache(
+ namespace: str = "settings", pattern: Optional[str] = None
+) -> Callable:
+ """
+ Decorator to invalidate cache after method execution.
+
+ Args:
+ namespace: Cache namespace to invalidate
+ pattern: Optional pattern for selective invalidation
+
+ Returns:
+ Decorated function
+ """
+
+ def decorator(func: Callable) -> Callable:
+ @functools.wraps(func)
+ def wrapper(self, *args, **kwargs):
+ # Call the original function first
+ result = func(self, *args, **kwargs)
+
+ # Only invalidate if the operation was successful
+ if result not in (False, None):
+ try:
+ cache = get_thread_local_cache()
+ user_id = getattr(self, "user_id", "global")
+
+ if pattern:
+ # Pattern-based invalidation
+ cache.invalidate(user_id, namespace, pattern)
+ logger.debug(
+ f"Invalidated cache pattern {namespace}:{pattern}"
+ )
+ else:
+ # Invalidate entire namespace
+ cache.invalidate(user_id, namespace)
+ logger.debug(f"Invalidated cache namespace {namespace}")
+
+ except Exception as e:
+ logger.warning(f"Cache invalidation failed: {e}")
+
+ return result
+
+ # Store metadata
+ wrapper._invalidates_cache = True
+ wrapper._invalidate_namespace = namespace
+ wrapper._invalidate_pattern = pattern
+
+ return wrapper
+
+ return decorator
+
+
+def cache_key(*key_args: str) -> Callable:
+ """
+ Decorator to specify which arguments should be used for cache key generation.
+
+ Args:
+ *key_args: Names of arguments to include in cache key
+
+ Returns:
+ Decorated function
+ """
+
+ def decorator(func: Callable) -> Callable:
+ func._cache_key_args = key_args
+ return func
+
+ return decorator
diff --git a/src/local_deep_research/settings/settings_cache/optimizations.py b/src/local_deep_research/settings/settings_cache/optimizations.py
new file mode 100644
index 0000000000..66aa100994
--- /dev/null
+++ b/src/local_deep_research/settings/settings_cache/optimizations.py
@@ -0,0 +1,228 @@
+"""
+Performance optimization utilities for settings cache.
+
+This module provides additional performance optimizations for the settings system.
+"""
+
+from typing import Dict, List, Any, Set
+from collections import defaultdict
+from loguru import logger
+import time
+
+
+class SettingsAccessPatternTracker:
+ """
+ Track access patterns to optimize cache warming and prefetching.
+ """
+
+ def __init__(self, window_size: int = 1000):
+ self.access_history: List[tuple] = [] # (timestamp, key)
+ self.access_count: Dict[str, int] = defaultdict(int)
+ self.co_access: Dict[str, Set[str]] = defaultdict(set)
+ self.window_size = window_size
+
+ def track_access(self, key: str) -> None:
+ """Track a setting access."""
+ timestamp = time.time()
+ self.access_history.append((timestamp, key))
+ self.access_count[key] += 1
+
+ # Maintain window size
+ if len(self.access_history) > self.window_size:
+ self.access_history.pop(0)
+
+ # Track co-access patterns (settings accessed together)
+ if len(self.access_history) > 1:
+ recent_keys = [k for _, k in self.access_history[-10:]]
+ for other_key in recent_keys:
+ if other_key != key:
+ self.co_access[key].add(other_key)
+ self.co_access[other_key].add(key)
+
+ def get_hot_keys(self, top_n: int = 20) -> List[str]:
+ """Get the most frequently accessed keys."""
+ sorted_keys = sorted(
+ self.access_count.items(), key=lambda x: x[1], reverse=True
+ )
+ return [key for key, _ in sorted_keys[:top_n]]
+
+ def get_related_keys(self, key: str) -> Set[str]:
+ """Get keys frequently accessed together with the given key."""
+ return self.co_access.get(key, set())
+
+ def suggest_prefetch(self, key: str) -> List[str]:
+ """Suggest keys to prefetch based on access patterns."""
+ related = self.get_related_keys(key)
+ # Sort by access frequency
+ return sorted(
+ related, key=lambda k: self.access_count.get(k, 0), reverse=True
+ )[:5]
+
+
+class LazySettingsLoader:
+ """
+ Lazy loading wrapper for settings that delays database access.
+ """
+
+ def __init__(self, manager, key: str, default: Any = None):
+ self._manager = manager
+ self._key = key
+ self._default = default
+ self._value = None
+ self._loaded = False
+
+ def __repr__(self):
+ if not self._loaded:
+ return f"<LazySettings({self._key}, not loaded)>"
+ return f"<LazySettings({self._key}={self._value})>"
+
+ def get(self) -> Any:
+ """Load the setting value if not already loaded."""
+ if not self._loaded:
+ self._value = self._manager.get_setting(self._key, self._default)
+ self._loaded = True
+ return self._value
+
+ # Make it behave like the actual value when accessed
+ def __getattr__(self, name):
+ return getattr(self.get(), name)
+
+ def __str__(self):
+ return str(self.get())
+
+ def __bool__(self):
+ return bool(self.get())
+
+
+class SettingsPrefetcher:
+ """
+ Intelligent prefetching based on access patterns.
+ """
+
+ def __init__(self, manager, tracker: SettingsAccessPatternTracker):
+ self.manager = manager
+ self.tracker = tracker
+
+ def prefetch_for_operation(self, operation: str) -> Dict[str, Any]:
+ """
+ Prefetch settings commonly needed for a specific operation.
+
+ Args:
+ operation: Operation name (e.g., 'research', 'search', 'export')
+
+ Returns:
+ Dictionary of prefetched settings
+ """
+ # Define common setting groups per operation
+ operation_settings = {
+ "research": [
+ "llm.provider",
+ "llm.model",
+ "llm.temperature",
+ "llm.max_tokens",
+ "search.tool",
+ "search.iterations",
+ "search.questions_per_iteration",
+ "research.max_results",
+ "research.timeout",
+ ],
+ "search": [
+ "search.tool",
+ "search.iterations",
+ "search.questions_per_iteration",
+ "search.timeout",
+ "search.max_results_per_query",
+ ],
+ "export": [
+ "report.format",
+ "report.include_metadata",
+ "report.include_sources",
+ "report.citation_style",
+ ],
+ "ui": [
+ "app.theme",
+ "app.language",
+ "app.version",
+ "app.lock_settings",
+ "ui.show_tooltips",
+ "ui.animation_speed",
+ ],
+ }
+
+ keys = operation_settings.get(operation, [])
+
+ # Add frequently co-accessed keys
+ additional_keys = set()
+ for key in keys:
+ additional_keys.update(self.tracker.suggest_prefetch(key))
+
+ all_keys = list(set(keys) | additional_keys)
+
+ # Use batch get for efficiency
+ return self.manager.get_settings_batch(all_keys)
+
+ def adaptive_prefetch(self, initial_key: str) -> Dict[str, Any]:
+ """
+ Adaptively prefetch based on access patterns.
+
+ Args:
+ initial_key: The key being accessed
+
+ Returns:
+ Dictionary of prefetched settings
+ """
+ # Track the access
+ self.tracker.track_access(initial_key)
+
+ # Get related keys
+ related_keys = self.tracker.suggest_prefetch(initial_key)
+
+ if related_keys:
+ # Prefetch related keys
+ all_keys = [initial_key] + list(related_keys)
+ return self.manager.get_settings_batch(all_keys)
+ else:
+ # Just get the single key
+ return {initial_key: self.manager.get_setting(initial_key)}
+
+
+def optimize_settings_for_request(settings_manager, request_type: str) -> None:
+ """
+ Optimize settings for a specific request type by warming cache.
+
+ Args:
+ settings_manager: The settings manager instance
+ request_type: Type of request (e.g., 'research', 'api', 'ui')
+ """
+ # Define settings to warm per request type
+ request_settings = {
+ "research": [
+ "llm.*", # All LLM settings
+ "search.*", # All search settings
+ "research.*", # All research settings
+ ],
+ "api": [
+ "api.rate_limit",
+ "api.timeout",
+ "api.max_requests",
+ "llm.provider",
+ "llm.model",
+ ],
+ "ui": [
+ "app.*", # All app settings
+ "ui.*", # All UI settings
+ ],
+ }
+
+ settings_to_warm = request_settings.get(request_type, [])
+
+ for setting in settings_to_warm:
+ if "*" in setting:
+ # Preload by prefix
+ prefix = setting.rstrip(".*")
+ settings_manager.preload_settings_by_prefix(prefix)
+ else:
+ # Warm individual setting
+ settings_manager.get_setting(setting)
+
+ logger.debug(f"Warmed cache for {request_type} request")
diff --git a/src/local_deep_research/settings/settings_cache/strategies.py b/src/local_deep_research/settings/settings_cache/strategies.py
new file mode 100644
index 0000000000..dbb07a3db6
--- /dev/null
+++ b/src/local_deep_research/settings/settings_cache/strategies.py
@@ -0,0 +1,123 @@
+"""
+Cache invalidation strategies for settings management.
+
+This module provides different strategies for invalidating cached settings
+based on various criteria.
+"""
+
+from abc import ABC, abstractmethod
+from typing import List, Optional
+from loguru import logger
+
+from ...memory_cache.config import get_thread_local_cache
+
+
+class CacheStrategy(ABC):
+ """Abstract base class for cache invalidation strategies."""
+
+ @abstractmethod
+ def invalidate(self, user_id: str, namespace: str, keys: List[str]) -> None:
+ """
+ Invalidate cache entries based on the strategy.
+
+ Args:
+ user_id: User identifier
+ namespace: Cache namespace
+ keys: List of keys that changed
+ """
+ pass
+
+
+class KeyInvalidationStrategy(CacheStrategy):
+ """Invalidate specific cache keys."""
+
+ def invalidate(self, user_id: str, namespace: str, keys: List[str]) -> None:
+ """Invalidate specific keys in the cache."""
+ cache = get_thread_local_cache()
+
+ for key in keys:
+ try:
+ # Invalidate the specific key (exact match)
+ cache.invalidate(user_id, namespace, key)
+ logger.debug(f"Invalidated cache key {namespace}:{key}")
+ except Exception as e:
+ logger.warning(f"Failed to invalidate key {key}: {e}")
+
+
+class PatternInvalidationStrategy(CacheStrategy):
+ """Invalidate cache entries matching patterns."""
+
+ def __init__(self, patterns: Optional[List[str]] = None):
+ """
+ Initialize with optional patterns.
+
+ Args:
+ patterns: List of patterns to match for invalidation
+ """
+ self.patterns = patterns or []
+
+ def invalidate(self, user_id: str, namespace: str, keys: List[str]) -> None:
+ """Invalidate entries matching patterns."""
+ cache = get_thread_local_cache()
+
+ # If no patterns, invalidate based on key prefixes
+ if not self.patterns:
+ # Generate patterns from keys (e.g., "llm.model" -> "llm.*")
+ patterns = set()
+ for key in keys:
+ parts = key.split(".")
+ if len(parts) > 1:
+ # Invalidate the entire category
+ patterns.add(f"{parts[0]}.*")
+ patterns.add(f"{key}*")
+ self.patterns = list(patterns)
+
+ # Invalidate based on patterns
+ for pattern in self.patterns:
+ try:
+ cache.invalidate(user_id, namespace, pattern)
+ logger.debug(f"Invalidated cache pattern {namespace}:{pattern}")
+ except Exception as e:
+ logger.warning(f"Failed to invalidate pattern {pattern}: {e}")
+
+
+class HierarchicalInvalidationStrategy(CacheStrategy):
+ """Invalidate cache entries based on hierarchical keys."""
+
+ def invalidate(self, user_id: str, namespace: str, keys: List[str]) -> None:
+ """Invalidate entries based on hierarchical relationships."""
+ cache = get_thread_local_cache()
+
+ # Build hierarchy patterns
+ patterns = set()
+ for key in keys:
+ parts = key.split(".")
+
+ # Add patterns for all levels
+ for i in range(1, len(parts) + 1):
+ partial_key = ".".join(parts[:i])
+ patterns.add(f"{partial_key}*")
+
+ # Now we can use pattern-based invalidation
+ for pattern in patterns:
+ try:
+ cache.invalidate(user_id, namespace, pattern)
+ logger.debug(f"Invalidated cache pattern {namespace}:{pattern}")
+ except Exception as e:
+ logger.warning(f"Failed to invalidate pattern {pattern}: {e}")
+
+
+class FullInvalidationStrategy(CacheStrategy):
+ """Invalidate the entire namespace."""
+
+ def invalidate(self, user_id: str, namespace: str, keys: List[str]) -> None:
+ """Invalidate the entire namespace."""
+ cache = get_thread_local_cache()
+
+ try:
+ cache.invalidate(user_id, namespace)
+ logger.debug(
+ f"Invalidated entire namespace {namespace} for user {user_id}"
+ )
+ except Exception as e:
+ logger.warning(f"Failed to invalidate namespace {namespace}: {e}")