forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rag

Clone
★ 0

0 watching0 forksPython2.4 MiBaaf05cfKadir Yönak2 months ago112 commits

base.py173 lines, 6.5 KiBHistoryRawDownload
1"""Cache katmanı — maliyet optimizasyonu (bkz. docs/OPTIMIZATION.md §C,
2docs/reports/RES-002-ragart-analysis.md §4).
3
4RagArt'tan uyarlanmış: 3-katman SQLite cache (Response/Embedding). RagArt'ın
5BOŞLUĞU — canlı token/$ telemetrisi yoktu; biz `src/costlog.py` ile her
6DeepSeek çağrısında GERÇEK maliyeti ölçeriz (bkz. src/generate/generator.py
7cache entegrasyonu: cache hit -> LLM hiç çağrılmaz -> maliyet 0, bu ÖLÇÜLÜR).
8
9Bu modül: `BaseCache` arayüzü + zero-dep `SQLiteCache` (stdlib sqlite3 +
10pickle; ekstra bağımlılık yok). Değer tipi keyfi (Python nesnesi) — pickle ile
11blob'a serialize edilir. TTL saniye cinsinden; `None` = sonsuz (asla süresi
12dolmaz). GC **lazy**: süresi geçmiş kayıt yalnız `get()` sırasında rastlanınca
13silinir (arka plan thread'i YOK — zero-dep ilkesine uygun); `gc_expired()` ile
14elle toplu temizlik de yapılabilir.
15
16**Bilinen sınırlar (fazın dışında, gördüğün eksikler raporunda tekrarlanır):**
17- Tek `threading.Lock` ile korunur — çoklu SÜREÇ (process) arası kilit YOK
18 (yalnız aynı süreç içi thread-safety). Üretimde çoklu worker/process
19 senaryosunda WAL modu + dosya-seviyesi kilit değerlendirilmeli.
20- Lazy GC yalnız erişilen anahtarları temizler; hiç erişilmeyen süresi geçmiş
21 kayıtlar `gc_expired()` elle çağrılmadıkça diskte kalır (sınırsız büyüme
22 riski — üretimde periyodik `gc_expired()` çağrısı/cron gerekir).
23"""
24from __future__ import annotations
25
26import pickle
27import sqlite3
28import threading
29import time
30from dataclasses import dataclass
31
32
33@dataclass
34class CacheStats:
35 """Bir cache backend'inin hit/miss sayaçları (maliyet-kazancı telemetrisi)."""
36 hits: int = 0
37 misses: int = 0
38
39 @property
40 def total(self) -> int:
41 return self.hits + self.misses
42
43 @property
44 def hit_rate(self) -> float:
45 return self.hits / self.total if self.total else 0.0
46
47 def record_hit(self) -> None:
48 self.hits += 1
49
50 def record_miss(self) -> None:
51 self.misses += 1
52
53
54class BaseCache:
55 """Cache arayüzü — backend'ler (SQLite, ileride başka bir şey) bunu uygular.
56 `EmbeddingCache`/`ResponseCache` bu arayüze göre yazılır, backend'e bağımlı
57 değildir (test'te de gerçek SQLite yerine bellek-içi backend enjekte edilebilir)."""
58
59 def get(self, key: str):
60 raise NotImplementedError
61
62 def set(self, key: str, value, ttl: float | None = None) -> None:
63 raise NotImplementedError
64
65 def delete(self, key: str) -> None:
66 raise NotImplementedError
67
68 @property
69 def stats(self) -> CacheStats:
70 raise NotImplementedError
71
72
73_SCHEMA = """
74CREATE TABLE IF NOT EXISTS kv_cache (
75 key TEXT PRIMARY KEY,
76 value BLOB NOT NULL,
77 expires_at REAL,
78 created_at REAL NOT NULL
79)
80"""
81
82
83class SQLiteCache(BaseCache):
84 """stdlib `sqlite3` + `pickle` — zero-dep key -> değer(blob) cache.
85
86 `path`: dosya yolu ya da `":memory:"` (varsayılan — testte tempfile de
87 verilebilir, üretimde kalıcı dosya yolu). `clock`: zaman kaynağı (testte
88 TTL'i gerçek `time.sleep` OLMADAN ilerletmek için enjekte edilebilir)."""
89
90 def __init__(self, path: str = ":memory:", *, clock=time.time):
91 self._clock = clock
92 self._lock = threading.Lock()
93 self._conn = sqlite3.connect(path, check_same_thread=False)
94 with self._lock:
95 self._conn.execute(_SCHEMA)
96 self._conn.commit()
97 self._stats = CacheStats()
98
99 @property
100 def stats(self) -> CacheStats:
101 return self._stats
102
103 def _now(self) -> float:
104 return self._clock()
105
106 def get(self, key: str):
107 with self._lock:
108 row = self._conn.execute(
109 "SELECT value, expires_at FROM kv_cache WHERE key = ?", (key,)
110 ).fetchone()
111 if row is None:
112 self._stats.record_miss()
113 return None
114 value_blob, expires_at = row
115 if expires_at is not None and expires_at <= self._now():
116 # süresi geçmiş -> lazy GC: bu kaydı sil + miss say
117 self._conn.execute("DELETE FROM kv_cache WHERE key = ?", (key,))
118 self._conn.commit()
119 self._stats.record_miss()
120 return None
121 try:
122 value = pickle.loads(value_blob)
123 except Exception:
124 # bozuk/deserialize-edilemeyen kayıt -> PATLAMADAN miss say + sil
125 # (ör. pickle formatı değişmiş, dosya bozulmuş)
126 self._conn.execute("DELETE FROM kv_cache WHERE key = ?", (key,))
127 self._conn.commit()
128 self._stats.record_miss()
129 return None
130 self._stats.record_hit()
131 return value
132
133 def set(self, key: str, value, ttl: float | None = None) -> None:
134 # TTL=0 veya negatif: kayıt anında "geçmiş" sayılır -> YAZMA, ama VARSA eski
135 # değeri SİL. (AUDIT EXP-007 #K2: eskiden bare return önceden yazılmış bir
136 # değeri BIRAKIYORDU → sonraki get() stale HIT dönüyordu; docstring'in "her
137 # zaman miss" sözüyle çelişiyordu. Artık gerçekten miss döner.)
138 if ttl is not None and ttl <= 0:
139 self.delete(key)
140 return
141 now = self._now()
142 expires_at = (now + ttl) if ttl is not None else None
143 blob = pickle.dumps(value)
144 with self._lock:
145 self._conn.execute(
146 "INSERT INTO kv_cache (key, value, expires_at, created_at) VALUES (?, ?, ?, ?) "
147 "ON CONFLICT(key) DO UPDATE SET value=excluded.value, "
148 "expires_at=excluded.expires_at, created_at=excluded.created_at",
149 (key, blob, expires_at, now))
150 self._conn.commit()
151
152 def delete(self, key: str) -> None:
153 with self._lock:
154 self._conn.execute("DELETE FROM kv_cache WHERE key = ?", (key,))
155 self._conn.commit()
156
157 def gc_expired(self) -> int:
158 """Süresi geçmiş TÜM kayıtları elle temizle (lazy GC'nin dışında,
159 periyodik bakım için); silinen satır sayısını döndürür."""
160 now = self._now()
161 with self._lock:
162 cur = self._conn.execute(
163 "DELETE FROM kv_cache WHERE expires_at IS NOT NULL AND expires_at <= ?", (now,))
164 self._conn.commit()
165 return cur.rowcount
166
167 def __len__(self) -> int:
168 with self._lock:
169 row = self._conn.execute("SELECT COUNT(*) FROM kv_cache").fetchone()
170 return row[0] if row else 0
171
172 def close(self) -> None:
173 self._conn.close()