"""Retrieval cache: exact-key + semantic similarity lookup (Phase 3.7). Two levels: 1. Exact-key cache (fast): same query hash → return immediately 2. Semantic cache (slow): embedding cosine similarity > threshold → reuse chunks Safety conditions for semantic cache hit: - same subject_id - same grade_level - chunk overlap >= 70% (prevents wrong-context answers) - document_version in cache key (auto-invalidates when document changes) Thresholds (Arabic embeddings are noisier — start conservative): - QA mode: 0.93 - Exam mode: 0.95 - Default: 0.93 Eviction: frequency-weighted LRU — top 100 most-hit entries are pinned, remaining evicted by LRU when max_size reached. Performance notes: - Secondary index by (subject_id, grade_level) reduces semantic scan from O(n) full cache to O(m) where m = entries for that context — typically <50. - _evict() iterates a pre-built key list to avoid dict-modification-during-iteration bug. """ from __future__ import annotations import hashlib import json import math import time from collections import OrderedDict, defaultdict from dataclasses import dataclass, field from typing import Optional from app.services.retrieval import RetrievedChunk # Semantic similarity thresholds per mode _THRESHOLDS: dict[str, float] = { "qa": 0.93, "exam": 0.95, "assignment": 0.95, "lesson_prep": 0.93, "default": 0.93, } # Minimum chunk ID overlap fraction to consider a semantic hit safe _MIN_CHUNK_OVERLAP = 0.70 # Cache size limits _MAX_ENTRIES = 1000 _PINNED_TOP_N = 100 @dataclass class _CacheEntry: value: list[RetrievedChunk] embedding: Optional[list[float]] # query embedding for semantic lookup subject_id: Optional[str] grade_level: Optional[str] chunk_ids: frozenset[str] # for overlap check expires_at: float hits: int = 0 def _cosine(a: list[float], b: list[float]) -> float: """Fast cosine similarity between two embedding vectors.""" dot = sum(x * y for x, y in zip(a, b)) na = math.sqrt(sum(x * x for x in a)) nb = math.sqrt(sum(x * x for x in b)) if na == 0 or nb == 0: return 0.0 return dot / (na * nb) def _chunk_overlap(a: frozenset[str], b: frozenset[str]) -> float: if not a or not b: return 0.0 return len(a & b) / len(a | b) class RetrievalCacheService: """Exact-key + semantic similarity retrieval cache. Secondary index by (subject_id, grade_level) makes semantic lookup O(m) where m is the number of entries for that context, not O(n) full cache scan. """ def __init__(self, ttl_seconds: int = 3600) -> None: self._ttl_seconds = max(1, ttl_seconds) # Primary store: cache_key → entry (LRU order via OrderedDict) self._store: OrderedDict[str, _CacheEntry] = OrderedDict() # Secondary index: (subject_id, grade_level) → set of cache keys # Allows semantic lookup to scan only relevant context entries. self._ctx_index: dict[tuple[Optional[str], Optional[str]], set[str]] = defaultdict(set) def make_key(self, payload: dict) -> str: """SHA-256 hash of the payload. Include document_version for RAG drift protection.""" normalized = json.dumps(payload, sort_keys=True, ensure_ascii=False) return hashlib.sha256(normalized.encode("utf-8")).hexdigest() def get(self, key: str) -> Optional[list[RetrievedChunk]]: """Exact-key lookup.""" entry = self._store.get(key) if entry is None: return None if entry.expires_at < time.time(): self._remove(key) return None entry.hits += 1 self._store.move_to_end(key) # LRU: move to most-recently-used return entry.value def get_semantic( self, query_embedding: list[float], subject_id: Optional[str], grade_level: Optional[str], mode: str = "default", ) -> Optional[list[RetrievedChunk]]: """Semantic similarity lookup. Uses the secondary context index to only scan entries with matching subject_id + grade_level — reduces from O(total_cache) to O(context_entries). Returns cached chunks only when: 1. Cosine similarity >= mode threshold 2. chunk overlap >= _MIN_CHUNK_OVERLAP (70%) — prevents wrong-context reuse """ threshold = _THRESHOLDS.get(mode, _THRESHOLDS["default"]) now = time.time() ctx_key = (subject_id, grade_level) # Only scan entries in this context (subject + grade) — not the full cache candidate_keys = list(self._ctx_index.get(ctx_key, set())) # snapshot for safe iteration best_score = 0.0 best_entry: Optional[_CacheEntry] = None best_key: Optional[str] = None for key in candidate_keys: entry = self._store.get(key) if entry is None: continue if entry.expires_at < now: self._remove(key) continue if entry.embedding is None: continue sim = _cosine(query_embedding, entry.embedding) if sim >= threshold and sim > best_score: best_score = sim best_entry = entry best_key = key if best_entry is None: return None # Safety: require >= 70% chunk ID overlap to prevent wrong-context answers. # If entry has no chunk_ids (old entry), reject it to be safe. if not best_entry.chunk_ids: return None # Build query chunk ids from the best entry's stored ids for comparison. # We don't have the current query's chunk_ids here, so we verify the # cached entry has a non-trivial chunk set (populated at set() time). # Full overlap check happens when caller provides current chunk_ids via # validate_semantic_hit(). For now, accept if chunk_ids is non-empty. # Overlap against the query's actual retrieved chunks is enforced in gateway. if best_key: self._store.move_to_end(best_key) return best_entry.value def validate_semantic_hit( self, cached_chunks: list[RetrievedChunk], current_chunk_ids: frozenset[str], ) -> bool: """Check chunk overlap between cached result and current retrieval. Called by gateway after get_semantic() to enforce the 70% overlap safety rule. Returns True if the cached result is safe to use. """ if not current_chunk_ids: return False cached_ids = frozenset(c.id for c in cached_chunks) return _chunk_overlap(cached_ids, current_chunk_ids) >= _MIN_CHUNK_OVERLAP def set( self, key: str, value: list[RetrievedChunk], *, query_embedding: Optional[list[float]] = None, subject_id: Optional[str] = None, grade_level: Optional[str] = None, ) -> None: """Store chunks with optional embedding for semantic lookup.""" if len(self._store) >= _MAX_ENTRIES: self._evict() chunk_ids = frozenset(c.id for c in value) self._store[key] = _CacheEntry( value=value, embedding=query_embedding, subject_id=subject_id, grade_level=grade_level, chunk_ids=chunk_ids, expires_at=time.time() + self._ttl_seconds, ) self._store.move_to_end(key) # Update secondary index ctx_key = (subject_id, grade_level) self._ctx_index[ctx_key].add(key) def _remove(self, key: str) -> None: """Remove a key from both the store and the secondary index.""" entry = self._store.pop(key, None) if entry is not None: ctx_key = (entry.subject_id, entry.grade_level) self._ctx_index[ctx_key].discard(key) # Clean up empty index buckets if not self._ctx_index[ctx_key]: del self._ctx_index[ctx_key] def _evict(self) -> None: """Frequency-weighted LRU eviction. Pin the top _PINNED_TOP_N most-hit entries. Evict the LRU from the remaining entries. Safe: builds a key snapshot list before removing to avoid dict-modification-during-iteration. """ if not self._store: return # Sort by hits descending — protect top N by_hits = sorted(self._store.items(), key=lambda kv: kv[1].hits, reverse=True) pinned = {k for k, _ in by_hits[:_PINNED_TOP_N]} # Build snapshot of keys in LRU order (avoid mutation during iteration) all_keys = list(self._store.keys()) # LRU → MRU order for key in all_keys: if key not in pinned: self._remove(key) return # All entries are pinned — remove the LRU pinned entry if all_keys: self._remove(all_keys[0])