File size: 9,611 Bytes
0ca462b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Intent Engine - Multi-Tier Cache for Search Results

Implements 3-tier caching strategy for optimal performance:
- L1: In-memory LRU cache (10ms access) - Top 1000 queries
- L2: Redis cache (50ms access) - Recent queries (24h)
- L3: Qdrant semantic cache (100ms access) - Similar queries

Usage:
    cache = MultiTierCache()
    result = await cache.get(query)
    if not result:
        result = await search(query)
        await cache.set(query, result)
"""

import hashlib
import logging
from collections import OrderedDict
from datetime import datetime, timedelta
from typing import Any

logger = logging.getLogger(__name__)


class LRUCache:
    """L1: In-memory LRU cache for hot queries"""

    def __init__(self, capacity: int = 1000, ttl_seconds: int = 300):
        self.capacity = capacity
        self.ttl_seconds = ttl_seconds
        self.cache: OrderedDict[str, tuple[Any, datetime]] = OrderedDict()
        self.hits = 0
        self.misses = 0

    def get(self, key: str) -> Any | None:
        """Get item from cache"""
        if key not in self.cache:
            self.misses += 1
            return None

        value, expiry = self.cache[key]

        # Check if expired
        if datetime.now() > expiry:
            del self.cache[key]
            self.misses += 1
            return None

        # Move to end (most recently used)
        self.cache.move_to_end(key)
        self.hits += 1
        return value

    def set(self, key: str, value: Any) -> None:
        """Set item in cache"""
        expiry = datetime.now() + timedelta(seconds=self.ttl_seconds)

        if key in self.cache:
            self.cache.move_to_end(key)

        self.cache[key] = (value, expiry)

        # Evict oldest if over capacity
        while len(self.cache) > self.capacity:
            self.cache.popitem(last=False)

    def stats(self) -> dict[str, Any]:
        """Get cache statistics"""
        total = self.hits + self.misses
        hit_rate = (self.hits / total * 100) if total > 0 else 0
        return {
            "hits": self.hits,
            "misses": self.misses,
            "hit_rate": f"{hit_rate:.1f}%",
            "size": len(self.cache),
            "capacity": self.capacity,
        }


class MultiTierCache:
    """
    Multi-tier caching for search results.

    Tiers:
    - L1: In-memory LRU (10ms) - Most popular queries
    - L2: Redis (50ms) - Recent queries
    - L3: Qdrant semantic (100ms) - Similar queries
    """

    def __init__(self, redis_client=None):
        # L1: In-memory cache (1000 queries, 5 min TTL)
        self.l1_cache = LRUCache(capacity=1000, ttl_seconds=300)

        # L2: Redis cache (will be set from external)
        self.l2_redis = redis_client

        # L2 Redis keys
        self.redis_prefix = "search:cache:"
        self.redis_ttl = 3600  # 1 hour

        # L3: Qdrant semantic cache
        self.l3_qdrant = None
        self.l3_threshold = 0.95  # Similarity threshold

        logger.info("MultiTierCache initialized (L1: LRU, L2: Redis, L3: Qdrant)")

    def set_redis_client(self, redis_client) -> None:
        """Set Redis client for L2 cache"""
        self.l2_redis = redis_client
        logger.info("L2 Redis cache connected")

    def set_qdrant_client(self, qdrant_client) -> None:
        """Set Qdrant client for L3 semantic cache"""
        self.l3_qdrant = qdrant_client
        logger.info("L3 Qdrant semantic cache connected")

    def _generate_cache_key(self, query: str) -> str:
        """Generate consistent cache key from query"""
        # Normalize query
        normalized = query.lower().strip()
        # Generate hash
        key_hash = hashlib.md5(normalized.encode()).hexdigest()[:16]
        return f"{self.redis_prefix}{key_hash}"

    async def get(self, query: str) -> Any | None:
        """
        Get search results from cache (multi-tier).

        Tries L1 → L2 → L3 in order, returns first match.
        Promotes results to higher tiers on hit.
        """
        cache_key = self._generate_cache_key(query)

        # L1: Check in-memory cache (fastest)
        if (result := self.l1_cache.get(cache_key)) is not None:
            logger.debug(f"L1 cache HIT: {query[:50]}")
            return result

        # L2: Check Redis cache
        if self.l2_redis:
            try:
                cached = await self.l2_redis.get(cache_key)
                if cached:
                    import json

                    result = json.loads(cached)
                    # Promote to L1
                    self.l1_cache.set(cache_key, result)
                    logger.debug(f"L2 cache HIT: {query[:50]}")
                    return result
            except Exception as e:
                logger.warning(f"L2 Redis cache error: {e}")

        # L3: Check Qdrant semantic cache (similar queries)
        if self.l3_qdrant:
            try:
                similar_result = await self._find_similar_query(query)
                if similar_result:
                    # Promote to L1 and L2
                    self.l1_cache.set(cache_key, similar_result)
                    await self._set_l2(cache_key, similar_result)
                    logger.debug(f"L3 semantic cache HIT: {query[:50]}")
                    return similar_result
            except Exception as e:
                logger.warning(f"L3 Qdrant cache error: {e}")

        # Cache miss
        logger.debug(f"Cache MISS: {query[:50]}")
        return None

    async def set(self, query: str, result: Any, ttl: int = 3600) -> None:
        """
        Set search results in all cache tiers.

        Args:
            query: Search query
            result: Search results to cache
            ttl: Time to live in seconds
        """
        cache_key = self._generate_cache_key(query)

        # L1: Always cache in memory
        self.l1_cache.set(cache_key, result)

        # L2: Cache in Redis
        await self._set_l2(cache_key, result, ttl)

        # L3: Index query in Qdrant for semantic lookup
        await self._index_query_semantic(query, result)

        logger.debug(f"Cached query: {query[:50]} (L1+L2+L3)")

    async def _set_l2(self, cache_key: str, result: Any, ttl: int = 3600) -> None:
        """Set result in L2 Redis cache"""
        if not self.l2_redis:
            return

        try:
            import json

            # Use RedisCache.set() method instead of raw Redis setex
            await self.l2_redis.set(cache_key, json.dumps(result), ttl=ttl)
        except Exception as e:
            logger.warning(f"Failed to set L2 cache: {e}")

    async def _find_similar_query(self, query: str) -> Any | None:
        """Find similar cached query in Qdrant (L3 semantic cache)"""
        if not self.l3_qdrant:
            return None

        try:
            from app.core.embedding_service import get_embedding_service

            embedding_service = get_embedding_service()
            query_embedding = embedding_service.encode_text(query)

            if query_embedding is None:
                return None

            # Search for similar queries
            similar = self.l3_qdrant.search_similar(
                query_embedding=query_embedding.tolist(),
                limit=1,
                score_threshold=self.l3_threshold,
            )

            if similar and len(similar) > 0:
                result = similar[0]
                if result.get("payload", {}).get("cached_result"):
                    return result["payload"]["cached_result"]
        except Exception as e:
            logger.debug(f"L3 semantic search failed: {e}")

        return None

    async def _index_query_semantic(self, query: str, result: Any) -> None:
        """Index query in Qdrant for future semantic lookup (L3)"""
        if not self.l3_qdrant:
            return

        try:
            from app.core.embedding_service import get_embedding_service

            embedding_service = get_embedding_service()
            query_embedding = embedding_service.encode_text(query)

            if query_embedding is None:
                return

            # Store in Qdrant with cached result using internal client
            # Note: QdrantVectorStore doesn't have upsert method, use internal client directly
            client = self.l3_qdrant._get_client()
            if client:
                from qdrant_client.http.models import PointStruct

                point = PointStruct(
                    id=hashlib.md5(query.encode()).hexdigest(),
                    vector=query_embedding.tolist(),
                    payload={
                        "query": query,
                        "cached_result": result,
                        "timestamp": datetime.now().isoformat(),
                    },
                )
                client.upsert(
                    collection_name=self.l3_qdrant.collection_name,
                    points=[point],
                )
        except Exception as e:
            logger.debug(f"Failed to index query in L3: {e}")

    def get_stats(self) -> dict[str, Any]:
        """Get cache statistics"""
        return {
            "l1": self.l1_cache.stats(),
            "l2": "connected" if self.l2_redis else "disconnected",
            "l3": "connected" if self.l3_qdrant else "disconnected",
        }


# Singleton instance
_cache_instance: MultiTierCache | None = None


def get_multi_tier_cache() -> MultiTierCache:
    """Get or create multi-tier cache singleton"""
    global _cache_instance
    if _cache_instance is None:
        _cache_instance = MultiTierCache()
    return _cache_instance