Spaces:
Paused

File size: 16,849 Bytes
b7980f7
 
55ffd6d
d8744fd
 
6ba1c48
b7980f7
 
 
55ffd6d
 
b7980f7
 
 
 
 
 
eb621b0
 
1049d57
eb621b0
 
 
 
 
 
2f81f65
 
 
eb621b0
 
 
 
 
 
2f81f65
1049d57
2f81f65
 
 
 
 
 
 
dbc31e7
1049d57
eb621b0
 
b7980f7
1049d57
b7980f7
 
1049d57
 
 
a6dd232
 
 
 
 
 
95e6137
22d93b9
95e6137
a05f53b
 
 
 
 
 
 
17923f1
a05f53b
 
95e6137
d8744fd
a05f53b
 
b7980f7
 
eb2bcc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17923f1
eb2bcc8
 
 
d8744fd
eb2bcc8
 
 
 
d8744fd
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca7df66
 
 
 
 
 
 
 
235f8ef
 
eb621b0
 
 
 
 
 
 
 
235f8ef
 
 
 
eb621b0
 
 
 
 
235f8ef
 
 
 
eb621b0
 
 
 
 
235f8ef
 
 
 
 
 
 
eb621b0
 
 
235f8ef
 
 
55ffd6d
 
235f8ef
f70ee44
 
 
 
6df4737
f70ee44
 
 
 
 
 
55ffd6d
 
f70ee44
6ba1c48
 
 
 
 
 
 
d8744fd
6ba1c48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6df4737
b7980f7
 
 
 
bc1617c
 
 
b7980f7
 
bc1617c
 
 
d8744fd
aa510be
 
bc1617c
 
 
 
b7980f7
add100e
55ffd6d
b7980f7
 
 
7e2936d
b7980f7
55ffd6d
b7980f7
bc1617c
b7980f7
 
add100e
aa510be
add100e
 
35d0374
 
 
aa510be
35d0374
 
 
 
ad4fe35
 
460fc16
 
 
 
 
 
b7980f7
55ffd6d
 
 
 
 
b7980f7
 
bc1617c
b7980f7
 
 
 
 
be01d40
06f7381
 
bc1617c
 
 
06f7381
be01d40
b7980f7
 
 
 
 
6ba1c48
460fc16
 
 
 
aa510be
460fc16
b7980f7
33d43ee
 
b7980f7
 
33d43ee
 
 
 
 
 
 
 
aa510be
33d43ee
 
b7980f7
 
 
 
 
 
 
aa510be
6ba1c48
 
 
 
 
 
 
 
 
 
 
 
b7980f7
aa510be
b7980f7
 
 
 
add100e
55ffd6d
b7980f7
 
 
 
55ffd6d
b7980f7
bc1617c
b7980f7
 
aa510be
add100e
55ffd6d
ad4fe35
 
 
 
b7980f7
55ffd6d
 
 
 
 
b7980f7
 
 
 
2d0e9e3
bc1617c
 
b7980f7
 
6ba1c48
 
b7980f7
 
 
aa510be
b7980f7
aa510be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
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}")