| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156 |
- #include "embedding_cache.hpp"
- #include <algorithm>
- #include <cctype>
- #include <chrono>
- namespace svapi {
- namespace {
- int64_t systemNow() {
- return std::chrono::duration_cast<std::chrono::seconds>(
- 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<unsigned char>(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<std::vector<float>> EmbeddingCache::get(const Key& k) {
- std::lock_guard<std::mutex> 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<int64_t>(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<float> vec) {
- std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> lk(mutex_);
- capacity_ = capacity;
- maxBytes_ = maxBytes;
- ttlSec_ = ttlSec;
- normalize_ = normalize;
- evict();
- }
- EmbeddingCache::Stats EmbeddingCache::stats() const {
- std::lock_guard<std::mutex> lk(mutex_);
- return Stats{hits_, misses_, lru_.size(), capacity_, bytes_};
- }
- void EmbeddingCache::setClockForTesting(std::function<int64_t()> fn) {
- std::lock_guard<std::mutex> lk(mutex_);
- now_ = std::move(fn);
- }
- EmbeddingCache& embeddingCache() {
- static EmbeddingCache instance;
- return instance;
- }
- } // namespace svapi
|