embedding_cache.cpp 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. #include "embedding_cache.hpp"
  2. #include <algorithm>
  3. #include <cctype>
  4. #include <chrono>
  5. namespace svapi {
  6. namespace {
  7. int64_t systemNow() {
  8. return std::chrono::duration_cast<std::chrono::seconds>(
  9. std::chrono::system_clock::now().time_since_epoch())
  10. .count();
  11. }
  12. } // anonymous namespace
  13. EmbeddingCache::EmbeddingCache(size_t capacity, size_t maxBytes,
  14. uint32_t ttlSec, bool normalize)
  15. : capacity_(capacity), maxBytes_(maxBytes),
  16. ttlSec_(ttlSec), normalize_(normalize),
  17. now_(systemNow) {}
  18. std::string EmbeddingCache::normalizeText(const std::string& t) const {
  19. if (!normalize_) return t;
  20. // lower-case
  21. std::string s = t;
  22. std::transform(s.begin(), s.end(), s.begin(),
  23. [](unsigned char c){ return std::tolower(c); });
  24. // collapse runs of whitespace into a single space and trim
  25. std::string out;
  26. out.reserve(s.size());
  27. bool prevSpace = true; // treat leading whitespace as trimmed
  28. for (char c : s) {
  29. if (std::isspace(static_cast<unsigned char>(c))) {
  30. if (!prevSpace) { out += ' '; prevSpace = true; }
  31. } else {
  32. out += c;
  33. prevSpace = false;
  34. }
  35. }
  36. // trim trailing space added by the loop
  37. if (!out.empty() && out.back() == ' ') out.pop_back();
  38. return out;
  39. }
  40. std::string EmbeddingCache::makeMapKey(const Key& k) const {
  41. // Length-prefixed encoding makes the composite key injective: no field
  42. // content (even embedded NULs) can forge a separator and collide two
  43. // distinct (apiBase, model, text) triples onto the same map key.
  44. const std::string text = normalizeText(k.text);
  45. std::string mkey;
  46. mkey.reserve(k.apiBase.size() + k.model.size() + text.size() + 24);
  47. auto append = [&mkey](const std::string& s) {
  48. mkey += std::to_string(s.size());
  49. mkey += ':';
  50. mkey += s;
  51. };
  52. append(k.apiBase);
  53. append(k.model);
  54. append(text);
  55. return mkey;
  56. }
  57. void EmbeddingCache::evict() {
  58. // Evict from the back (LRU) until both constraints are satisfied.
  59. while (!lru_.empty() &&
  60. (lru_.size() > capacity_ || bytes_ > maxBytes_)) {
  61. auto it = std::prev(lru_.end());
  62. bytes_ -= it->second.vec.size() * sizeof(float);
  63. index_.erase(it->first);
  64. lru_.erase(it);
  65. }
  66. }
  67. std::optional<std::vector<float>> EmbeddingCache::get(const Key& k) {
  68. std::lock_guard<std::mutex> lk(mutex_);
  69. std::string mkey = makeMapKey(k);
  70. auto it = index_.find(mkey);
  71. if (it == index_.end()) {
  72. ++misses_;
  73. return std::nullopt;
  74. }
  75. auto& entry = it->second->second;
  76. // TTL check (lazy expiry)
  77. if (ttlSec_ > 0) {
  78. int64_t age = now_() - entry.insertedAt;
  79. if (age > static_cast<int64_t>(ttlSec_)) {
  80. // expire
  81. bytes_ -= entry.vec.size() * sizeof(float);
  82. lru_.erase(it->second);
  83. index_.erase(it);
  84. ++misses_;
  85. return std::nullopt;
  86. }
  87. }
  88. ++hits_;
  89. // Move to front (most-recently used)
  90. lru_.splice(lru_.begin(), lru_, it->second);
  91. return entry.vec;
  92. }
  93. void EmbeddingCache::put(const Key& k, std::vector<float> vec) {
  94. std::lock_guard<std::mutex> lk(mutex_);
  95. std::string mkey = makeMapKey(k);
  96. size_t vecBytes = vec.size() * sizeof(float);
  97. auto it = index_.find(mkey);
  98. if (it != index_.end()) {
  99. // Replace existing entry
  100. bytes_ -= it->second->second.vec.size() * sizeof(float);
  101. bytes_ += vecBytes;
  102. it->second->second.vec = std::move(vec);
  103. it->second->second.insertedAt = now_();
  104. // Move to front
  105. lru_.splice(lru_.begin(), lru_, it->second);
  106. } else {
  107. // New entry: push to front
  108. lru_.push_front({mkey, Entry{std::move(vec), now_()}});
  109. index_[mkey] = lru_.begin();
  110. bytes_ += vecBytes;
  111. }
  112. evict();
  113. }
  114. void EmbeddingCache::clear() {
  115. std::lock_guard<std::mutex> lk(mutex_);
  116. lru_.clear();
  117. index_.clear();
  118. bytes_ = 0;
  119. }
  120. void EmbeddingCache::reconfigure(size_t capacity, size_t maxBytes,
  121. uint32_t ttlSec, bool normalize) {
  122. std::lock_guard<std::mutex> lk(mutex_);
  123. capacity_ = capacity;
  124. maxBytes_ = maxBytes;
  125. ttlSec_ = ttlSec;
  126. normalize_ = normalize;
  127. evict();
  128. }
  129. EmbeddingCache::Stats EmbeddingCache::stats() const {
  130. std::lock_guard<std::mutex> lk(mutex_);
  131. return Stats{hits_, misses_, lru_.size(), capacity_, bytes_};
  132. }
  133. void EmbeddingCache::setClockForTesting(std::function<int64_t()> fn) {
  134. std::lock_guard<std::mutex> lk(mutex_);
  135. now_ = std::move(fn);
  136. }
  137. EmbeddingCache& embeddingCache() {
  138. static EmbeddingCache instance;
  139. return instance;
  140. }
  141. } // namespace svapi