#include "embedding_cache.hpp" #include #include #include namespace svapi { namespace { int64_t systemNow() { return std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch()) .count(); } } // anonymous namespace EmbeddingCache::EmbeddingCache(size_t capacity, size_t maxBytes, uint32_t ttlSec, bool normalize) : capacity_(capacity), maxBytes_(maxBytes), ttlSec_(ttlSec), normalize_(normalize), now_(systemNow) {} std::string EmbeddingCache::normalizeText(const std::string& t) const { if (!normalize_) return t; // lower-case std::string s = t; std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c){ return std::tolower(c); }); // collapse runs of whitespace into a single space and trim std::string out; out.reserve(s.size()); bool prevSpace = true; // treat leading whitespace as trimmed for (char c : s) { if (std::isspace(static_cast(c))) { if (!prevSpace) { out += ' '; prevSpace = true; } } else { out += c; prevSpace = false; } } // trim trailing space added by the loop if (!out.empty() && out.back() == ' ') out.pop_back(); return out; } std::string EmbeddingCache::makeMapKey(const Key& k) const { // Length-prefixed encoding makes the composite key injective: no field // content (even embedded NULs) can forge a separator and collide two // distinct (apiBase, model, text) triples onto the same map key. const std::string text = normalizeText(k.text); std::string mkey; mkey.reserve(k.apiBase.size() + k.model.size() + text.size() + 24); auto append = [&mkey](const std::string& s) { mkey += std::to_string(s.size()); mkey += ':'; mkey += s; }; append(k.apiBase); append(k.model); append(text); return mkey; } void EmbeddingCache::evict() { // Evict from the back (LRU) until both constraints are satisfied. while (!lru_.empty() && (lru_.size() > capacity_ || bytes_ > maxBytes_)) { auto it = std::prev(lru_.end()); bytes_ -= it->second.vec.size() * sizeof(float); index_.erase(it->first); lru_.erase(it); } } std::optional> EmbeddingCache::get(const Key& k) { std::lock_guard lk(mutex_); std::string mkey = makeMapKey(k); auto it = index_.find(mkey); if (it == index_.end()) { ++misses_; return std::nullopt; } auto& entry = it->second->second; // TTL check (lazy expiry) if (ttlSec_ > 0) { int64_t age = now_() - entry.insertedAt; if (age > static_cast(ttlSec_)) { // expire bytes_ -= entry.vec.size() * sizeof(float); lru_.erase(it->second); index_.erase(it); ++misses_; return std::nullopt; } } ++hits_; // Move to front (most-recently used) lru_.splice(lru_.begin(), lru_, it->second); return entry.vec; } void EmbeddingCache::put(const Key& k, std::vector vec) { std::lock_guard lk(mutex_); std::string mkey = makeMapKey(k); size_t vecBytes = vec.size() * sizeof(float); auto it = index_.find(mkey); if (it != index_.end()) { // Replace existing entry bytes_ -= it->second->second.vec.size() * sizeof(float); bytes_ += vecBytes; it->second->second.vec = std::move(vec); it->second->second.insertedAt = now_(); // Move to front lru_.splice(lru_.begin(), lru_, it->second); } else { // New entry: push to front lru_.push_front({mkey, Entry{std::move(vec), now_()}}); index_[mkey] = lru_.begin(); bytes_ += vecBytes; } evict(); } void EmbeddingCache::clear() { std::lock_guard lk(mutex_); lru_.clear(); index_.clear(); bytes_ = 0; } void EmbeddingCache::reconfigure(size_t capacity, size_t maxBytes, uint32_t ttlSec, bool normalize) { std::lock_guard lk(mutex_); capacity_ = capacity; maxBytes_ = maxBytes; ttlSec_ = ttlSec; normalize_ = normalize; evict(); } EmbeddingCache::Stats EmbeddingCache::stats() const { std::lock_guard lk(mutex_); return Stats{hits_, misses_, lru_.size(), capacity_, bytes_}; } void EmbeddingCache::setClockForTesting(std::function fn) { std::lock_guard lk(mutex_); now_ = std::move(fn); } EmbeddingCache& embeddingCache() { static EmbeddingCache instance; return instance; } } // namespace svapi