|
| 1 | +"""Content-addressable cache for LLM context deduplication.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import hashlib |
| 6 | +import math |
| 7 | +import sqlite3 |
| 8 | +import time |
| 9 | +from dataclasses import dataclass |
| 10 | + |
| 11 | + |
| 12 | +@dataclass |
| 13 | +class CacheEntry: |
| 14 | + hash: str |
| 15 | + content: str |
| 16 | + token_count: int |
| 17 | + hit_count: int |
| 18 | + first_seen: int |
| 19 | + last_seen: int |
| 20 | + source: str |
| 21 | + |
| 22 | + |
| 23 | +@dataclass |
| 24 | +class CacheLookupResult: |
| 25 | + hit: bool |
| 26 | + hash: str |
| 27 | + entry: CacheEntry | None = None |
| 28 | + tokens_saved: int = 0 |
| 29 | + |
| 30 | + |
| 31 | +@dataclass |
| 32 | +class CacheStats: |
| 33 | + total_entries: int |
| 34 | + total_tokens_cached: int |
| 35 | + total_tokens_saved: int |
| 36 | + hit_rate: float |
| 37 | + top_sources: list[tuple[str, int]] |
| 38 | + |
| 39 | + |
| 40 | +def estimate_tokens(content: str) -> int: |
| 41 | + """Estimate token count using chars/4 approximation.""" |
| 42 | + if not content: |
| 43 | + return 0 |
| 44 | + return math.ceil(len(content) / 4) |
| 45 | + |
| 46 | + |
| 47 | +def hash_content(content: str) -> str: |
| 48 | + """SHA-256 hex digest for content-addressable lookup.""" |
| 49 | + return hashlib.sha256(content.encode()).hexdigest() |
| 50 | + |
| 51 | + |
| 52 | +class ContentCache: |
| 53 | + """SQLite-backed content-hash cache with token savings tracking.""" |
| 54 | + |
| 55 | + def __init__(self, db: sqlite3.Connection) -> None: |
| 56 | + self._db = db |
| 57 | + self._init_schema() |
| 58 | + |
| 59 | + def _init_schema(self) -> None: |
| 60 | + self._db.executescript(""" |
| 61 | + CREATE TABLE IF NOT EXISTS content_cache ( |
| 62 | + hash TEXT PRIMARY KEY, |
| 63 | + content TEXT NOT NULL, |
| 64 | + token_count INTEGER NOT NULL, |
| 65 | + hit_count INTEGER NOT NULL DEFAULT 0, |
| 66 | + first_seen INTEGER NOT NULL, |
| 67 | + last_seen INTEGER NOT NULL, |
| 68 | + source TEXT NOT NULL DEFAULT '' |
| 69 | + ); |
| 70 | + CREATE INDEX IF NOT EXISTS idx_cache_source ON content_cache(source); |
| 71 | + """) |
| 72 | + |
| 73 | + def lookup(self, content: str, source: str = "") -> CacheLookupResult: |
| 74 | + """Check if content exists. Increments hit_count on hit.""" |
| 75 | + h = hash_content(content) |
| 76 | + row = self._db.execute( |
| 77 | + "SELECT * FROM content_cache WHERE hash = ?", (h,) |
| 78 | + ).fetchone() |
| 79 | + |
| 80 | + if not row: |
| 81 | + return CacheLookupResult(hit=False, hash=h) |
| 82 | + |
| 83 | + now = int(time.time()) |
| 84 | + self._db.execute( |
| 85 | + "UPDATE content_cache SET hit_count = hit_count + 1, last_seen = ? WHERE hash = ?", |
| 86 | + (now, h), |
| 87 | + ) |
| 88 | + if source and source != row[5]: |
| 89 | + self._db.execute( |
| 90 | + "UPDATE content_cache SET source = ? WHERE hash = ?", (source, h) |
| 91 | + ) |
| 92 | + self._db.commit() |
| 93 | + |
| 94 | + entry = CacheEntry( |
| 95 | + hash=row[0], content=row[1], token_count=row[2], |
| 96 | + hit_count=row[3] + 1, first_seen=row[4], |
| 97 | + last_seen=now, source=source or row[5], |
| 98 | + ) |
| 99 | + return CacheLookupResult(hit=True, hash=h, entry=entry, tokens_saved=entry.token_count) |
| 100 | + |
| 101 | + def put(self, content: str, source: str = "") -> CacheEntry: |
| 102 | + """Insert or update a cache entry.""" |
| 103 | + h = hash_content(content) |
| 104 | + token_count = estimate_tokens(content) |
| 105 | + now = int(time.time()) |
| 106 | + |
| 107 | + existing = self._db.execute( |
| 108 | + "SELECT hash FROM content_cache WHERE hash = ?", (h,) |
| 109 | + ).fetchone() |
| 110 | + |
| 111 | + if existing: |
| 112 | + self._db.execute( |
| 113 | + "UPDATE content_cache SET hit_count = hit_count + 1, last_seen = ?, source = ? WHERE hash = ?", |
| 114 | + (now, source, h), |
| 115 | + ) |
| 116 | + else: |
| 117 | + self._db.execute( |
| 118 | + "INSERT INTO content_cache (hash, content, token_count, hit_count, first_seen, last_seen, source) VALUES (?, ?, ?, 0, ?, ?, ?)", |
| 119 | + (h, content, token_count, now, now, source), |
| 120 | + ) |
| 121 | + self._db.commit() |
| 122 | + |
| 123 | + row = self._db.execute( |
| 124 | + "SELECT * FROM content_cache WHERE hash = ?", (h,) |
| 125 | + ).fetchone() |
| 126 | + return CacheEntry( |
| 127 | + hash=row[0], content=row[1], token_count=row[2], |
| 128 | + hit_count=row[3], first_seen=row[4], last_seen=row[5], source=row[6], |
| 129 | + ) |
| 130 | + |
| 131 | + def get_stats(self) -> CacheStats: |
| 132 | + """Aggregate cache statistics.""" |
| 133 | + row = self._db.execute(""" |
| 134 | + SELECT COUNT(*), COALESCE(SUM(token_count), 0), |
| 135 | + COALESCE(SUM(hit_count * token_count), 0), |
| 136 | + COALESCE(SUM(hit_count), 0) |
| 137 | + FROM content_cache |
| 138 | + """).fetchone() |
| 139 | + |
| 140 | + total_entries, total_cached, total_saved, total_hits = row |
| 141 | + hit_rate = total_hits / (total_hits + total_entries) if (total_hits + total_entries) > 0 else 0.0 |
| 142 | + |
| 143 | + top = self._db.execute(""" |
| 144 | + SELECT source, SUM(hit_count * token_count) as saved |
| 145 | + FROM content_cache WHERE source != '' |
| 146 | + GROUP BY source ORDER BY saved DESC LIMIT 10 |
| 147 | + """).fetchall() |
| 148 | + |
| 149 | + return CacheStats( |
| 150 | + total_entries=total_entries, |
| 151 | + total_tokens_cached=total_cached, |
| 152 | + total_tokens_saved=total_saved, |
| 153 | + hit_rate=hit_rate, |
| 154 | + top_sources=[(r[0], r[1]) for r in top], |
| 155 | + ) |
| 156 | + |
| 157 | + def clear(self) -> None: |
| 158 | + """Remove all entries.""" |
| 159 | + self._db.execute("DELETE FROM content_cache") |
| 160 | + self._db.commit() |
0 commit comments