Spaces:
Running on Zero

File size: 6,363 Bytes
5e0b6f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Semantic query cache.

* Embeds the (guardrail-processed) query with the shared MiniLM model.
* Keeps entries {query, embedding, answer, route, meta, ts} in memory for O(n)
  cosine lookup.
* **In-memory by default** - every process/app start begins EMPTY. Within one
  running session: a fresh query runs the full pipeline; a later similar query
  (cosine >= threshold) returns the cached answer and skips RAG entirely.
  Set `CP_CACHE_PERSIST=1` to also mirror entries to disk across restarts.

Only *safe, non-HITL, non-retried* answers are cached (see graph/nodes/finalize).
Guardrails always run before the cache so an injected query can neither be served
from nor written to it.
"""

from __future__ import annotations

import json
import threading
import time
from collections import OrderedDict
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional

from controlplane.config import settings


@dataclass
class CacheHit:
    answer: str
    similarity: float
    meta: Dict[str, Any]
    query: str


class SemanticCache:
    def __init__(self, store_dir: Optional[Path] = None, threshold: Optional[float] = None,
                 persist: Optional[bool] = None) -> None:
        self.store_dir = Path(store_dir or settings.cache_store_dir)
        self.persist = settings.cache_persist if persist is None else persist
        self.file = self.store_dir / "entries.jsonl"
        self.threshold = threshold if threshold is not None else settings.cache_threshold
        self._entries: List[Dict[str, Any]] = []
        self._matrix = None
        self._lock = threading.Lock()
        self._loaded = False

    # ---- lifecycle -------------------------------------------------------------
    def load(self) -> "SemanticCache":
        if self._loaded:
            return self
        with self._lock:
            if self._loaded:
                return self
            entries: List[Dict[str, Any]] = []
            if self.persist and self.file.exists():
                for line in self.file.read_text(encoding="utf-8").splitlines():
                    line = line.strip()
                    if line:
                        try:
                            entries.append(json.loads(line))
                        except Exception:
                            continue
            self._entries = entries
            self._rebuild_matrix()
            self._loaded = True
        return self

    def _rebuild_matrix(self) -> None:
        try:
            import numpy as np

            self._matrix = (
                np.asarray([e["embedding"] for e in self._entries], dtype="float32")
                if self._entries
                else None
            )
        except Exception:
            self._matrix = None

    # ---- embedding -------------------------------------------------------------
    @staticmethod
    def _embed(text: str):
        from controlplane.retrievers.registry import get_minilm

        model = get_minilm()
        if model is None:
            return None
        return model.encode([text], normalize_embeddings=True)[0]

    # ---- lookup -------------------------------------------------------------
    def lookup(self, query: str) -> Optional[CacheHit]:
        if not settings.cache_enabled:
            return None
        self.load()
        if not self._entries or self._matrix is None:
            return None
        import numpy as np

        q = self._embed(query)
        if q is None:
            return None
        sims = self._matrix @ np.asarray(q, dtype="float32")
        best = int(np.argmax(sims))
        score = float(sims[best])
        if score >= self.threshold:
            e = self._entries[best]
            return CacheHit(answer=e["answer"], similarity=score, meta=e.get("meta", {}), query=e["query"])
        return None

    # ---- write -------------------------------------------------------------
    def add(self, query: str, answer: str, meta: Optional[Dict[str, Any]] = None) -> bool:
        if not settings.cache_enabled or not answer.strip():
            return False
        self.load()
        emb = self._embed(query)
        if emb is None:
            return False
        entry = {
            "query": query,
            "embedding": [float(x) for x in emb],
            "answer": answer,
            "route": (meta or {}).get("selected_kb"),
            "meta": meta or {},
            "ts": time.time(),
        }
        with self._lock:
            self._entries.append(entry)
            self._rebuild_matrix()
            if self.persist:
                self.store_dir.mkdir(parents=True, exist_ok=True)
                with open(self.file, "a", encoding="utf-8") as f:
                    f.write(json.dumps(entry, ensure_ascii=False) + "\n")
        return True

    def clear(self) -> None:
        with self._lock:
            self._entries = []
            self._matrix = None
            if self.persist and self.file.exists():
                self.file.unlink()

    def entries(self) -> List[Dict[str, Any]]:
        self.load()
        return [{"query": e["query"], "route": e.get("route"), "ts": e.get("ts")} for e in self._entries]

    def __len__(self) -> int:
        self.load()
        return len(self._entries)


_caches: "OrderedDict[str, SemanticCache]" = OrderedDict()
_caches_lock = threading.Lock()
_MAX_NAMESPACES = 256          # LRU bound so many sign-ins can't grow memory forever


def get_cache(namespace: Optional[str] = None) -> SemanticCache:
    """One isolated cache per namespace (the signed-in user's id in the web app),
    so one user's answers are never served to - or cleared by - another user.
    `None`/"" is the shared default used by the CLI scripts and tests."""
    ns = (namespace or "").strip()
    with _caches_lock:
        cache = _caches.get(ns)
        if cache is None:
            store = settings.cache_store_dir if not ns else settings.cache_store_dir / _safe_dir(ns)
            cache = SemanticCache(store_dir=store)
            _caches[ns] = cache
            while len(_caches) > _MAX_NAMESPACES:
                _caches.popitem(last=False)
        else:
            _caches.move_to_end(ns)
        return cache


def _safe_dir(ns: str) -> str:
    import hashlib

    return "u_" + hashlib.sha256(ns.encode("utf-8")).hexdigest()[:24]