import json import hashlib import logging import time from datetime import datetime, timezone from typing import Any, Optional, List import redis.asyncio as redis from core.config import get_settings _cache_logger = logging.getLogger(__name__) settings = get_settings() # Initialize a dedicated Redis client for search caching # This uses the CACHE_REDIS_URL to separate it from Arq (Upstash) _redis_client: Optional[redis.Redis] = None # --- L1 MEMORY CACHE (Zero-Latency Layer) --- _l1_cache: dict[str, tuple[Any, float]] = {} MAX_L1_SIZE = 2048 def get_l1_cache(key: str) -> Optional[Any]: """Retrieves an object from the local memory cache if not expired.""" if key in _l1_cache: val, expiry = _l1_cache[key] if time.time() < expiry: # LRU: Move to end to mark as recently used del _l1_cache[key] _l1_cache[key] = (val, expiry) return val else: del _l1_cache[key] return None def set_l1_cache(key: str, val: Any, ttl: int): """Stores an object in the local memory cache with size-based LRU eviction.""" global _l1_cache if key in _l1_cache: del _l1_cache[key] elif len(_l1_cache) >= MAX_L1_SIZE: # LRU Eviction: remove the least recently used items (front of dict) evict_count = max(1, MAX_L1_SIZE // 10) keys_to_evict = list(_l1_cache.keys())[:evict_count] for k in keys_to_evict: _l1_cache.pop(k, None) # safe if another coroutine already removed it _l1_cache[key] = (val, time.time() + ttl) def get_redis_client() -> redis.Redis: """Singleton getter for the async Redis client with primary/fallback awareness.""" global _redis_client if _redis_client is None: # settings.clean_cache_redis_url dynamically resolves the best URL for caching target_url = settings.clean_cache_redis_url # Standardize SSL connection to avoid 'unexpected keyword argument ssl' # If the URL points to a cloud provider and uses 'redis://', upgrade it to 'rediss://' # so redis-py uses the SSLConnection class which natively accepts SSL parameters. if target_url.startswith("redis://") and ("redislabs.com" in target_url or "upstash.io" in target_url or ".com:" in target_url): target_url = target_url.replace("redis://", "rediss://", 1) is_rediss = target_url.startswith("rediss://") # Build connection kwargs redis_kwargs = { "encoding": "utf-8", "decode_responses": True, "socket_connect_timeout": 5.0, "socket_timeout": 5.0, "socket_keepalive": True, "retry_on_timeout": True, "health_check_interval": 30, } if is_rediss: redis_kwargs["ssl_cert_reqs"] = "none" _redis_client = redis.from_url(target_url, **redis_kwargs) return _redis_client _worker_redis_client: Optional[redis.Redis] = None def get_worker_redis_client() -> redis.Redis: """Singleton getter for the async Redis client for background worker metadata (Latches).""" global _worker_redis_client if _worker_redis_client is None: target_url = settings.clean_arq_redis_url if target_url.startswith("redis://") and ("redislabs.com" in target_url or "upstash.io" in target_url or ".com:" in target_url): target_url = target_url.replace("redis://", "rediss://", 1) is_rediss = target_url.startswith("rediss://") redis_kwargs = { "encoding": "utf-8", "decode_responses": True, "socket_connect_timeout": 5.0, "socket_timeout": 5.0, "socket_keepalive": True, "retry_on_timeout": True, "health_check_interval": 30, } if is_rediss: redis_kwargs["ssl_cert_reqs"] = "none" _worker_redis_client = redis.from_url(target_url, **redis_kwargs) return _worker_redis_client def generate_cache_key(prefix: str, workspace_id: str, query: str, filters: Optional[dict] = None) -> str: """Generates a deterministic cache key based on query parameters.""" filter_str = json.dumps(filters, sort_keys=True) if filters else "{}" payload = f"{workspace_id}:{query}:{filter_str}".lower().strip() query_hash = hashlib.sha256(payload.encode()).hexdigest()[:16] return f"cache:search:{prefix}:{workspace_id}:{query_hash}" async def get_cached_search(key: str) -> Optional[Any]: """Retrieves a cached search result from Redis.""" try: client = get_redis_client() data = await client.get(key) if data: return json.loads(data) except Exception: # Fail safe - if Redis is down, just return None to trigger fresh search pass return None async def set_cached_search(key: str, data: Any, ttl: int = 3600) -> None: """Stores a search result in Redis with a Time-To-Live.""" try: client = get_redis_client() await client.set(key, json.dumps(data), ex=ttl) except Exception: # Fail safe pass async def delete_cached_search(key: str) -> None: """Removes a specific cache key from Redis.""" try: client = get_redis_client() await client.delete(key) except Exception: pass # --- Generic Object Caching for API responses --- async def get_cached_object(key: str, use_l1: bool = False) -> Optional[Any]: """Retrieves a JSON-serialized object from Redis (and optionally L1 memory).""" # 1. Check L1 Cache if requested if use_l1: l1_val = get_l1_cache(key) if l1_val is not None: return l1_val try: client = get_redis_client() data = await client.get(key) if data: parsed = json.loads(data) # 2. Backfill L1 Cache if we just fetched from Redis if use_l1: set_l1_cache(key, parsed, ttl=60) # Default L1 TTL of 60s return parsed except Exception: pass return None async def set_cached_object(key: str, data: Any, ttl: int = 300, use_l1: bool = False) -> None: """Stores a JSON-serializable object in Redis with TTL (and optionally L1 memory).""" if use_l1: set_l1_cache(key, data, ttl=min(ttl, 60)) # Cap L1 TTL at 60s try: client = get_redis_client() await client.set(key, json.dumps(data), ex=ttl) except Exception: pass async def invalidate_cache(key: str) -> None: """Explicitly purges a cache key from both Redis and L1.""" if key in _l1_cache: del _l1_cache[key] try: client = get_redis_client() await client.delete(key) except Exception as e: _cache_logger.warning(f"Cache invalidate failed for key={key}: {e}") async def delete_by_pattern(pattern: str) -> None: """Purges all keys matching a specific glob pattern using SCAN for safety.""" try: cursor = 0 client = get_redis_client() while True: cursor, keys = await client.scan(cursor=cursor, match=pattern, count=100) if keys: await client.delete(*keys) if cursor == 0: break except Exception as e: _cache_logger.warning(f"Cache purge failed for pattern={pattern}: {e}") async def invalidate_workspace_semantic_cache(workspace_id: str) -> None: """ Sets a marker in Redis to invalidate all semantic cache entries for a workspace. Entries created before this timestamp will be ignored. """ try: client = get_redis_client() now = datetime.now(timezone.utc).timestamp() await client.set(f"semantic_cache:invalidation:{workspace_id}", str(now), ex=86400) except Exception: pass async def check_rate_limit(key: str, limit: int, window: int) -> bool: """ Generic Sliding Window Rate Limiter using Redis ZSET. Returns True if allowed, False if limit exceeded. """ try: import time client = get_redis_client() now = time.time() pipe = client.pipeline() # Remove old requests pipe.zremrangebyscore(key, 0, now - window) # Count remaining pipe.zcard(key) # Add current request pipe.zadd(key, {str(now): now}) # Set expiry for cleanup pipe.expire(key, window) results = await pipe.execute() current_count = results[1] return current_count < limit except Exception: return True # Fail open on Redis error class SemanticCacheManager: """ Manages semantic LLM response caching using pgvector. Bypasses entirely the LangGraph orchestration if an idential query was asked before. PARTITION KEY: (workspace_id, role_class) - role_class is normalized to 'staff' or 'customer' to prevent cross-persona cache leaks. """ @staticmethod def _normalize_role_class(user_role: str = "", is_agent: bool = False) -> str: """Normalize any role string to a strict partition class.""" role_lower = user_role.lower() if role_lower == "universal": return "universal" if is_agent or "3sc" in role_lower or "agent" in role_lower or "lead" in role_lower or role_lower == "admin": return "staff" return "customer" @staticmethod async def check_cache(workspace_id: Any, query: str, is_agent: bool = False, user_role: str = "customer_user", user_id: Optional[str] = None) -> Optional[dict]: import asyncio from core.llm import get_embeddings from core.database import async_session_factory from models.nexus_semantic_cache import NexusSemanticCache from sqlalchemy import select, update, and_, func import logging logger = logging.getLogger(__name__) role_class = SemanticCacheManager._normalize_role_class(user_role, is_agent) try: # 0. Robust Workspace ID handling if workspace_id is None: return None # 1. Bypass Logic for real-time critical domains (Health/Status) bypass_keywords = ["status", "stable", "online", "health", "pulse", "live", "check"] if any(k in query.lower() for k in bypass_keywords): logger.info(f"♻️ Semantic Cache Bypassed [Live Domain]: ws={str(workspace_id)[:8] if workspace_id else 'None'} q='{query[:30]}'") return None # 2. Skip embedding for very short queries if len(query.strip()) < 5: return None # --- Event-Driven Invalidation Check (Early Exit) --- # Check Redis for the latest workspace-specific invalidation event BEFORE the DB query client = get_redis_client() inv_time_str = await client.get(f"semantic_cache:invalidation:{workspace_id}") inv_time = float(inv_time_str) if inv_time_str else None embedder = get_embeddings() try: query_vector = await asyncio.wait_for(embedder.aembed_query(query), timeout=10.0) except asyncio.TimeoutError: logger.warning(f"Semantic cache embedding timed out for query='{query[:40]}'") return None async with async_session_factory() as db: from sqlalchemy import text stmt = ( select( NexusSemanticCache, NexusSemanticCache.query_embedding.cosine_distance(query_vector).label("distance") ) .where( and_( NexusSemanticCache.workspace_id == workspace_id, NexusSemanticCache.is_agent == (role_class == "staff"), NexusSemanticCache.user_role == role_class, NexusSemanticCache.created_at >= (func.now() - text("INTERVAL '6 hours'")) ) ) .order_by("distance") .limit(1) ) res = await db.execute(stmt) row = res.first() # --- Invalidation Logic --- if row and inv_time: cache_time = row[0].created_at.timestamp() if cache_time < inv_time: logger.info(f"♻️ Semantic Cache Bypassed [Stale]: ws={str(workspace_id)[:8] if workspace_id else 'None'} (Cache={cache_time} < Inv={inv_time})") return None # Tighten Precision: Distance < 0.02 (Very strict similarity) if row and row.distance < 0.02: cache_hit = row[0] # --- ID Collision Safety --- # If the query contains specific IDs (Ticket ID, UUID), they MUST match exactly. import re id_pattern = re.compile(r'\b([0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}|[0-9a-fA-F]{8})\b') query_ids = set(id_pattern.findall(query.lower())) cached_ids = set(id_pattern.findall(cache_hit.query_text.lower())) if query_ids != cached_ids: logger.info(f"♻️ Semantic Cache Bypassed [ID Mismatch]: ws={str(workspace_id)[:8] if workspace_id else 'None'} q_ids={query_ids} vs cached_ids={cached_ids}") return None # Update hit count await db.execute( update(NexusSemanticCache) .where(NexusSemanticCache.id == cache_hit.id) .values(hit_count=NexusSemanticCache.hit_count + 1) ) await db.commit() logger.info(f"🧠 Semantic Cache HIT [{role_class}]: ws={str(workspace_id)[:8] if workspace_id else 'None'} q='{query[:40]}'") results = [] if cache_hit.results_json: try: results = json.loads(cache_hit.results_json) except Exception: logger.error("Failed to decode results_json from semantic cache") return { "answer": cache_hit.response_text, "results": results } except Exception as e: logger.error(f"Semantic Cache Check Failed: {e}") return None @staticmethod async def set_cache(workspace_id: Any, user_id: Any, query: str, response_text: str, results: Optional[List[Any]] = None, is_agent: bool = False, user_role: str = "customer_user"): import asyncio from core.llm import get_embeddings from core.database import async_session_factory from models.nexus_semantic_cache import NexusSemanticCache import logging logger = logging.getLogger(__name__) role_class = SemanticCacheManager._normalize_role_class(user_role, is_agent) try: if workspace_id is None: return # OPTIMIZATION: Skip embedding generation for very short queries if len(query.strip()) < 10: return embedder = get_embeddings() try: query_vector = await asyncio.wait_for(embedder.aembed_query(query), timeout=10.0) except asyncio.TimeoutError: logger.warning(f"Semantic cache set_cache embedding timed out for query='{query[:40]}'") return async with async_session_factory() as db: cache_entry = NexusSemanticCache( workspace_id=workspace_id, user_id=user_id, # Keep user_id in record for audit, but not lookup is_agent=(role_class == "staff"), user_role=role_class, query_text=query, query_embedding=query_vector, response_text=response_text, results_json=json.dumps(results) if results else None ) db.add(cache_entry) await db.commit() logger.info(f"🧠 Semantic Cache SET [{role_class}]: ws={str(workspace_id)[:8] if workspace_id else 'None'} q='{query[:40]}'") except Exception as e: logger.error(f"Semantic Cache Set Failed: {e}")