Pārlūkot izejas kodu

fix: the memory budget covers vectors - counted at boot, released by eviction

A vector loaded at boot (snapshot, WAL replay) was never added to the memory
estimate, and eviction erased only a document's body, so a vector stayed
resident for the life of the process and was written into every snapshot.
One production instance reported 237 MB estimated (46%) with about 615 MiB
of vectors beside it.

- loadVector counts the vector; vectorMemoryBytes_ tracks the vector share,
  reported in the memory line ("of which vectors V MB")
- evictDocument releases the vector while the LMDB mirror is healthy with
  zero drift; a reload reads it back from LMDB (a read error fails the reload)
- the snapshot writes resident and released vectors a batch at a time under
  the collection lock (getVectorIds/copyVectors); a vector deleted meanwhile
  is a zero-length entry the loader skips
- the write handlers copy the vector under the lock (residentVector,
  hasVector) instead of reading the live map without one
- eviction candidates are sized body + vector

Tests: test_dual_write_mirror +1 function (21 checks, incl. a snapshot round
trip); test_snapshot_keeps_evicted gains a vector collection and checks the
vector share before and after the restart. Each part reverted fails a check.
fszontagh 1 mēnesi atpakaļ
vecāks
revīzija
2a998de784

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 0
CLAUDE.md


+ 36 - 0
docs/integration-guide.md

@@ -2340,6 +2340,42 @@ The server tracks four pressure levels based on current usage vs. `max_memory_mb
 
 Query current state via `smartbotic-db-cli status` or the `GetMemoryStats` RPC.
 
+#### Vectors count against the budget (2.21.2+)
+
+A stored vector is part of what memory holds, and from 2.21.2 it is counted
+and freed like the rest of the document:
+
+- **Counted everywhere it enters memory.** Before 2.21.2 a vector loaded at
+  boot (from the snapshot or the WAL) was never added to the estimate, so a
+  vector store reported a fraction of what it held: one production instance
+  read `237 MB estimated (46%)` with about 615 MiB of 4096-dimension vectors
+  resident beside it.
+- **Released by eviction.** Eviction used to remove only the body and leave
+  the vector in memory for the life of the process, so the budget could never
+  reclaim the largest thing in a vector store. Evicting a document now
+  releases its vector too, but only while the LMDB mirror is healthy with zero
+  drift (LMDB then holds the current copy). A write or read that reloads the
+  document reloads the vector from LMDB. Search is served from LMDB as before,
+  so a released vector still ranks.
+- **Reported on its own.** The periodic memory line reads
+  `Memory check: N MB estimated (P%, pressure=...), of which vectors V MB, ...`.
+  `V` is the resident vector share of `N`. The first line is logged within
+  one eviction tick of startup, so it serves as the boot figure.
+
+**Before upgrading a vector-heavy instance to 2.21.2,** compare the vector
+share with the budget. At the first boot the estimate rises by every resident
+vector (about `dimension x 4 + 32` bytes each), and a store whose budget was
+sized from the old figure can boot straight into `hard` or `emergency`
+pressure. At `emergency` writes are refused with `RESOURCE_EXHAUSTED` until
+eviction has released enough vectors. You can avoid that in either of two
+ways:
+
+- Raise `storage.memory.max_memory_mb` (conf.d drop-in) to cover the old
+  estimate plus the vectors before upgrading. Memory use is then unchanged.
+- Keep the budget and let eviction release vectors. Resident memory falls,
+  at the cost of a burst of `RESOURCE_EXHAUSTED` writes right after the boot,
+  and the drain cap below may pause eviction at `soft`.
+
 #### Drain cap (2.4.3+)
 
 Eviction assumes the memory estimate falls as documents leave. When memory is

+ 14 - 31
service/src/database_grpc_impl.cpp

@@ -563,12 +563,8 @@ grpc::Status DatabaseGrpcImpl::Insert(
         std::string id = store_.insert(request->collection(), doc);
 
         // Persist vector if the document had a _vector field
-        auto* vectors = store_.getCollectionVectors(request->collection());
-        if (vectors) {
-            auto vit = vectors->find(id);
-            if (vit != vectors->end()) {
-                persistence_.logVecPut(request->collection(), id, vit->second);
-            }
+        if (auto vec = store_.residentVector(request->collection(), id)) {
+            persistence_.logVecPut(request->collection(), id, *vec);
         }
 
         response->set_id(id);
@@ -787,11 +783,9 @@ grpc::Status DatabaseGrpcImpl::Update(
         }
 
         // Persist vector changes
-        auto* vectors = store_.getCollectionVectors(request->collection());
-        if (vectors) {
-            auto vit = vectors->find(request->id());
-            if (vit != vectors->end()) {
-                persistence_.logVecPut(request->collection(), request->id(), vit->second);
+        if (store_.collectionExists(request->collection())) {
+            if (auto vec = store_.residentVector(request->collection(), request->id())) {
+                persistence_.logVecPut(request->collection(), request->id(), *vec);
             } else {
                 // Vector was removed (update without _vector field removes existing vector)
                 persistence_.logVecDelete(request->collection(), request->id());
@@ -927,12 +921,8 @@ grpc::Status DatabaseGrpcImpl::PatchDocument(
 
         // Persist vector changes (store_.patchDocument handles WAL for the document itself
         // via emitPersist, but vector WAL entries need explicit logging)
-        auto* vectors = store_.getCollectionVectors(request->collection());
-        if (vectors) {
-            auto vit = vectors->find(request->id());
-            if (vit != vectors->end()) {
-                persistence_.logVecPut(request->collection(), request->id(), vit->second);
-            }
+        if (auto vec = store_.residentVector(request->collection(), request->id())) {
+            persistence_.logVecPut(request->collection(), request->id(), *vec);
         }
 
         response->set_new_version(newVersion);
@@ -1030,15 +1020,11 @@ grpc::Status DatabaseGrpcImpl::Upsert(
         std::string id = store_.upsert(request->collection(), doc);
 
         // Persist vector changes
-        auto* vectors = store_.getCollectionVectors(request->collection());
-        if (vectors) {
-            auto vit = vectors->find(id);
-            if (vit != vectors->end()) {
-                persistence_.logVecPut(request->collection(), id, vit->second);
-            } else if (existed) {
-                // Existing doc updated without _vector — remove old vector
-                persistence_.logVecDelete(request->collection(), id);
-            }
+        if (auto vec = store_.residentVector(request->collection(), id)) {
+            persistence_.logVecPut(request->collection(), id, *vec);
+        } else if (existed && store_.collectionExists(request->collection())) {
+            // Existing doc updated without _vector - remove old vector
+            persistence_.logVecDelete(request->collection(), id);
         }
 
         auto updated = store_.get(request->collection(), id);
@@ -1132,11 +1118,8 @@ grpc::Status DatabaseGrpcImpl::Delete(
     }
 
     // Check if document has a vector before deleting (remove() erases it from memory)
-    bool hadVector = false;
-    auto* vectors = store_.getCollectionVectors(request->collection());
-    if (vectors) {
-        hadVector = vectors->count(request->id()) > 0;
-    }
+    // v2.21.2 - resident, or released by eviction (the stub records it).
+    const bool hadVector = store_.hasVector(request->collection(), request->id());
 
     bool deleted = store_.remove(request->collection(), request->id(), request->actor());
 

+ 171 - 5
service/src/memory_store.cpp

@@ -207,6 +207,7 @@ bool MemoryStore::dropCollection(const std::string& name) {
 
     uint64_t docCount = 0;
     uint64_t totalSize = 0;
+    uint64_t vectorSize = 0;
     {
         std::shared_lock<std::shared_mutex> collLock(it->second->mutex);
         docCount = it->second->documents.size();
@@ -217,8 +218,9 @@ bool MemoryStore::dropCollection(const std::string& name) {
             totalSize += estimateDocumentSize(doc);
         }
         for (const auto& [id, vec] : it->second->vectors) {
-            totalSize += estimateVectorSize(vec);
+            vectorSize += estimateVectorSize(vec);
         }
+        totalSize += vectorSize;
     }
 
     collections_.erase(it);
@@ -243,6 +245,7 @@ bool MemoryStore::dropCollection(const std::string& name) {
 
     // Update memory tracking atomically
     estimatedMemoryBytes_.fetch_sub(totalSize, std::memory_order_relaxed);
+    vectorMemoryBytes_.fetch_sub(vectorSize, std::memory_order_relaxed);
     }   // globalMutex_ released here — see below.
 
     // v2.11.0 close-out (round-3 review, item 2) — release any TTL blocked-set
@@ -2418,9 +2421,9 @@ void MemoryStore::storeVector(CollectionData& coll, const std::string& docId,
 
     // Update memory counter by the delta
     if (newSize > oldSize) {
-        estimatedMemoryBytes_.fetch_add(newSize - oldSize, std::memory_order_relaxed);
+        addVectorBytes(newSize - oldSize);
     } else if (oldSize > newSize) {
-        estimatedMemoryBytes_.fetch_sub(oldSize - newSize, std::memory_order_relaxed);
+        subVectorBytes(oldSize - newSize);
     }
 }
 
@@ -2429,7 +2432,7 @@ void MemoryStore::removeVector(CollectionData& coll, const std::string& docId) {
     if (it != coll.vectors.end()) {
         uint64_t freed = estimateVectorSize(it->second);
         coll.vectors.erase(it);
-        estimatedMemoryBytes_.fetch_sub(freed, std::memory_order_relaxed);
+        subVectorBytes(freed);
     }
     coll.vectorNorms.erase(docId);
 }
@@ -2532,11 +2535,26 @@ void MemoryStore::loadVector(const std::string& collection, const std::string& d
                               std::vector<float> vec) {
     CollectionData* coll = getOrCreateCollection(collection);
 
+    // v2.21.2 - a zero-length entry is a snapshot placeholder for a vector
+    // deleted while the snapshot was written (see copyVectors), not a vector.
+    if (vec.empty()) return;
+
     std::unique_lock<std::shared_mutex> lock(coll->mutex);
 
+    // v2.21.2 - counted, through storeVector's accounting. Boot-loaded
+    // vectors (snapshot, WAL replay) used to bypass the estimate entirely, so
+    // a store of mostly vectors reported a fraction of what it held and the
+    // memory budget never saw them.
+    uint64_t oldSize = 0;
+    if (auto existing = coll->vectors.find(docId); existing != coll->vectors.end()) {
+        oldSize = estimateVectorSize(existing->second);
+    }
     coll->vectors[docId] = std::move(vec);
     coll->vectorNorms[docId] = computeNorm(coll->vectors[docId].data(),
                                             coll->vectors[docId].size());
+    const uint64_t newSize = estimateVectorSize(coll->vectors[docId]);
+    if (newSize > oldSize) addVectorBytes(newSize - oldSize);
+    else if (oldSize > newSize) subVectorBytes(oldSize - newSize);
 }
 
 // ===== TTL Management =====
@@ -2917,6 +2935,7 @@ MemoryStore::Stats MemoryStore::getStats() const {
 
     // Use atomic counter for document memory (O(1) instead of O(n) iteration)
     stats.estimatedMemoryBytes = estimatedMemoryBytes_.load(std::memory_order_relaxed);
+    stats.vectorMemoryBytes = vectorMemoryBytes_.load(std::memory_order_relaxed);
 
     return stats;
 }
@@ -3371,6 +3390,101 @@ std::vector<std::optional<Document>> MemoryStore::copyDocuments(
     return out;
 }
 
+bool MemoryStore::canReleaseVector(const std::string& collection) const {
+    if (!docStoreResolver_ || !mirrorHealthy_ || !mirrorDriftCount_) return false;
+    if (!mirrorHealthy() || mirrorDriftCount() != 0) return false;
+    try {
+        const auto pc = smartbotic::database::parseProjectCollection(collection);
+        if (pc.collection.empty() || pc.collection.front() == '_') return false;  // never mirrored
+        return docStoreResolver_(pc.project) != nullptr;
+    } catch (const std::exception&) {
+        return false;
+    }
+}
+
+std::optional<std::vector<float>> MemoryStore::readStoredVector(
+    const std::string& collection, const std::string& id) const {
+    if (!docStoreResolver_) return std::nullopt;
+    const auto pc = smartbotic::database::parseProjectCollection(collection);
+    auto* ds = docStoreResolver_(pc.project);
+    if (ds == nullptr) return std::nullopt;
+    return ds->get_vector(pc.collection, id);
+}
+
+std::optional<std::vector<float>> MemoryStore::residentVector(
+    const std::string& collection, const std::string& id) const {
+    const CollectionData* coll = getCollection(collection);
+    if (coll == nullptr) return std::nullopt;
+    std::shared_lock<std::shared_mutex> lock(coll->mutex);
+    auto it = coll->vectors.find(id);
+    if (it == coll->vectors.end()) return std::nullopt;
+    return it->second;
+}
+
+bool MemoryStore::hasVector(const std::string& collection, const std::string& id) const {
+    if (const CollectionData* coll = getCollection(collection)) {
+        std::shared_lock<std::shared_mutex> lock(coll->mutex);
+        if (coll->vectors.count(id) != 0) return true;
+    }
+    auto stub = getEvictedStub(collection, id);
+    return stub && stub->vectorEvicted;
+}
+
+std::vector<std::string> MemoryStore::getVectorIds(const std::string& collection) const {
+    std::vector<std::string> ids;
+    if (const CollectionData* coll = getCollection(collection)) {
+        std::shared_lock<std::shared_mutex> lock(coll->mutex);
+        ids.reserve(coll->vectors.size());
+        for (const auto& [id, vec] : coll->vectors) ids.push_back(id);
+    }
+    // Evicted after the resident ids were listed: listed twice, written
+    // twice, and the loader keeps one. Never missed.
+    std::shared_lock<std::shared_mutex> lock(evictionMutex_);
+    if (auto it = evictedDocs_.find(collection); it != evictedDocs_.end()) {
+        for (const auto& [id, stub] : it->second) {
+            if (stub.vectorEvicted) ids.push_back(id);
+        }
+    }
+    return ids;
+}
+
+std::vector<std::optional<std::vector<float>>> MemoryStore::copyVectors(
+    const std::string& collection, const std::vector<std::string>& ids,
+    size_t from, size_t count) const {
+    std::vector<std::optional<std::vector<float>>> out;
+    const size_t end = std::min(ids.size(), from + count);
+    if (from >= end) return out;
+    out.resize(end - from);
+    std::vector<size_t> missing;
+    if (const CollectionData* coll = getCollection(collection)) {
+        std::shared_lock<std::shared_mutex> lock(coll->mutex);
+        for (size_t i = from; i < end; ++i) {
+            auto it = coll->vectors.find(ids[i]);
+            if (it != coll->vectors.end()) out[i - from] = it->second;
+            else missing.push_back(i);
+        }
+    } else {
+        for (size_t i = from; i < end; ++i) missing.push_back(i);
+    }
+    // Released by eviction (before or after the listing): read from LMDB,
+    // outside the collection lock. A read ERROR throws (the snapshot is
+    // abandoned and the WAL kept). A vector LMDB does not have is written as
+    // absent: it was released only because LMDB held it, so absence means it
+    // was deleted meanwhile, and failing every snapshot over it would grow
+    // the WAL without bound (the 2.20.1 outage).
+    for (size_t i : missing) {
+        auto stub = getEvictedStub(collection, ids[i]);
+        if (stub && stub->vectorEvicted) {
+            out[i - from] = readStoredVector(collection, ids[i]);
+            continue;
+        }
+        // No released copy: reloaded since the memory pass (the stub goes
+        // after the vector is back in memory), or deleted. Look once more.
+        out[i - from] = residentVector(collection, ids[i]);
+    }
+    return out;
+}
+
 std::vector<std::pair<std::string, CollectionOptions>> MemoryStore::getAllCollectionsWithOptions() const {
     std::shared_lock<std::shared_mutex> lock(globalMutex_);
 
@@ -3523,6 +3637,7 @@ void MemoryStore::clear() {
     // Reset the memory accounting counter — every document, version entry,
     // and vector just went away, so any pending increments are stale.
     estimatedMemoryBytes_.store(0, std::memory_order_relaxed);
+    vectorMemoryBytes_.store(0, std::memory_order_relaxed);
 }
 
 // ===== Private Methods =====
@@ -4075,10 +4190,14 @@ uint64_t MemoryStore::getWalSequence(const std::string& collection,
 
 void MemoryStore::logMemoryCheck() {
     auto stats = getStats();
-    spdlog::info("Memory check: {} MB estimated ({}%, pressure={}), {} docs, {} evicted",
+    // v2.21.2 - the vector share is reported on its own: it is usually the
+    // largest single thing in a vector store and was invisible before.
+    spdlog::info("Memory check: {} MB estimated ({}%, pressure={}), of which vectors {} MB, "
+                "{} docs, {} evicted",
                 stats.estimatedMemoryBytes / (1024 * 1024),
                 pressurePercent(),
                 memoryPressureToString(pressure()),
+                stats.vectorMemoryBytes / (1024 * 1024),
                 stats.totalDocuments,
                 stats.evictedCount);
 
@@ -4359,6 +4478,10 @@ uint64_t MemoryStore::evictOneChunk() {
                 c.lastAccessedAt = doc.lastAccessedAt > 0 ? doc.lastAccessedAt
                                  : (doc.updatedAt > 0 ? doc.updatedAt : doc.createdAt);
                 c.estimatedSize = estimateDocumentSize(doc);
+                // v2.21.2 - eviction releases the vector too.
+                if (auto vit = collPtr->vectors.find(docId); vit != collPtr->vectors.end()) {
+                    c.estimatedSize += estimateVectorSize(vit->second);
+                }
                 c.priority = collPtr->options.memoryPriority;
                 candidates.push_back(std::move(c));
             }
@@ -4507,6 +4630,10 @@ std::vector<std::pair<std::string, std::string>> MemoryStore::selectDocumentsFor
                 uint64_t accessTime = doc.lastAccessedAt > 0 ? doc.lastAccessedAt :
                                       (doc.updatedAt > 0 ? doc.updatedAt : doc.createdAt);
                 uint64_t size = estimateDocumentSize(doc);
+                // v2.21.2 - eviction releases the vector too.
+                if (auto vit = coll->vectors.find(id); vit != coll->vectors.end()) {
+                    size += estimateVectorSize(vit->second);
+                }
                 docs.emplace_back(accessTime, size, collName, id);
             }
         }
@@ -4547,6 +4674,21 @@ bool MemoryStore::evictDocument(const std::string& collection, const std::string
     stub.estimatedSize = estimateDocumentSize(it->second);
     stub.evictedAt = currentTimeMs();
 
+    // v2.21.2 - release the vector too. Eviction used to leave coll.vectors
+    // alone, so a vector outlived its body for the life of the process (and,
+    // through the snapshot's vector section, across restarts), and the one
+    // mechanism that frees memory under pressure could not touch the largest
+    // thing in a vector store. Only while LMDB holds the current copy; a
+    // reload, the snapshot and the degraded search read it from there.
+    uint64_t vectorFreed = 0;
+    if (auto vit = coll->vectors.find(id);
+        vit != coll->vectors.end() && canReleaseVector(collection)) {
+        vectorFreed = estimateVectorSize(vit->second);
+        coll->vectors.erase(vit);
+        coll->vectorNorms.erase(id);
+        stub.vectorEvicted = true;
+    }
+
     // Remove from expiration index
     if (it->second.expiresAt > 0) {
         removeFromExpirationIndex(*coll, id, it->second.expiresAt);
@@ -4584,6 +4726,7 @@ bool MemoryStore::evictDocument(const std::string& collection, const std::string
 
     // Update memory tracking atomically (subtract evicted document size).
     estimatedMemoryBytes_.fetch_sub(stub.estimatedSize, std::memory_order_relaxed);
+    if (vectorFreed > 0) subVectorBytes(vectorFreed);
 
     SPDLOG_DEBUG("Evicted document {}/{} (size: {} bytes)", collection, id, stub.estimatedSize);
 
@@ -4627,6 +4770,26 @@ std::optional<Document> MemoryStore::loadEvictedDocument(const std::string& coll
         return std::nullopt;
     }
 
+    // v2.21.2 - bring back the vector eviction released. Read before taking
+    // the collection lock and stored only if this call is the one that
+    // inserts the document. A read error fails the reload (the stub stays, so
+    // a write refuses rather than proceed without the vector, and an undo
+    // copy taken by that write would otherwise lose it).
+    std::optional<std::vector<float>> vector;
+    if (stub.vectorEvicted) {
+        try {
+            vector = readStoredVector(collection, id);
+        } catch (const std::exception& e) {
+            spdlog::warn("Failed to recover the vector of evicted document {}/{}: {}",
+                         collection, id, e.what());
+            return std::nullopt;
+        }
+        if (!vector) {
+            spdlog::warn("Evicted document {}/{} had a vector, and the on-disk store has "
+                         "none for it; reloaded without one", collection, id);
+        }
+    }
+
     doc->collection = collection;
 
     // Re-insert into memory (hot-load). Another reader may have raced us; if so,
@@ -4658,6 +4821,9 @@ std::optional<Document> MemoryStore::loadEvictedDocument(const std::string& coll
             }
 
             coll->documents.emplace(id, *doc);
+            if (vector && coll->vectors.find(id) == coll->vectors.end()) {
+                storeVector(*coll, id, *vector);
+            }
             inserted = true;
             returned = *doc;
         }

+ 61 - 3
service/src/memory_store.hpp

@@ -198,6 +198,10 @@ public:
         uint64_t walSequence;      // WAL sequence for recovery
         uint64_t estimatedSize;    // Original size (for stats)
         uint64_t evictedAt;        // When document was evicted
+        // v2.21.2 - eviction also released the document's vector from memory
+        // (coll.vectors); the copy is in the LMDB vector sub-db, which a
+        // reload, the snapshot and the degraded similarity search read.
+        bool vectorEvicted = false;
     };
 
     explicit MemoryStore(Config config = Config{});
@@ -868,12 +872,45 @@ public:
         float minScore = 0.0f);
 
     /**
-     * Get all vectors for a collection (for snapshotting/persistence).
+     * Get all vectors for a collection (boot-time migration only: the map is
+     * returned without a lock, so nothing may be writing or evicting).
      * @return Pointer to vectors map, or nullptr if collection not found
      */
     [[nodiscard]] const std::unordered_map<std::string, std::vector<float>>*
         getCollectionVectors(const std::string& collection) const;
 
+    /**
+     * v2.21.2 - a copy of one document's resident vector, taken under the
+     * collection lock (nullopt = none in memory). The write handlers use it to
+     * log VEC_PUT/VEC_DELETE; they used to read the map with no lock at all.
+     */
+    [[nodiscard]] std::optional<std::vector<float>> residentVector(
+        const std::string& collection, const std::string& id) const;
+
+    /**
+     * v2.21.2 - does the document have a vector, resident or released by
+     * eviction (its stub says so)? For the delete handler's VEC_DELETE.
+     */
+    [[nodiscard]] bool hasVector(const std::string& collection, const std::string& id) const;
+
+    /**
+     * v2.21.2 - the ids the snapshot writes vectors for: every resident vector
+     * plus every evicted document whose vector eviction released. With
+     * copyVectors this writes the vector section a batch at a time, under the
+     * collection lock (it used to iterate the live map without one).
+     */
+    [[nodiscard]] std::vector<std::string> getVectorIds(const std::string& collection) const;
+
+    /**
+     * v2.21.2 - one entry per id, in order: the resident vector, else the
+     * released one read from LMDB, else nullopt (deleted since it was listed).
+     * Throws when LMDB cannot be read, abandoning the snapshot so the WAL that
+     * holds the vector is kept (as copyDocuments does for bodies).
+     */
+    [[nodiscard]] std::vector<std::optional<std::vector<float>>> copyVectors(
+        const std::string& collection, const std::vector<std::string>& ids,
+        size_t from, size_t count) const;
+
     /**
      * Load a vector directly (for snapshot/WAL recovery, bypasses event callbacks).
      */
@@ -990,6 +1027,8 @@ public:
         uint64_t totalDocuments = 0;
         uint64_t totalCollections = 0;
         uint64_t estimatedMemoryBytes = 0;
+        // v2.21.2 - the part of estimatedMemoryBytes that is resident vectors.
+        uint64_t vectorMemoryBytes = 0;
         uint64_t expiredCount = 0;
         // v2.11.0 close-out — TTL expiry REFUSAL EVENTS, because a relation
         // blocked the delete (a `restrict` relation with live children, or the
@@ -1346,6 +1385,24 @@ private:
     // Vector storage helpers
     void storeVector(CollectionData& coll, const std::string& docId, const std::vector<float>& vec);
     void removeVector(CollectionData& coll, const std::string& docId);
+    // v2.21.2 - vector bytes go into BOTH counters: the estimate the budget
+    // and eviction act on, and the vector share reported beside it.
+    void addVectorBytes(uint64_t n) noexcept {
+        estimatedMemoryBytes_.fetch_add(n, std::memory_order_relaxed);
+        vectorMemoryBytes_.fetch_add(n, std::memory_order_relaxed);
+    }
+    void subVectorBytes(uint64_t n) noexcept {
+        estimatedMemoryBytes_.fetch_sub(n, std::memory_order_relaxed);
+        vectorMemoryBytes_.fetch_sub(n, std::memory_order_relaxed);
+    }
+    // v2.21.2 - may eviction release this document's vector? Only when LMDB
+    // is known to hold the current copy: a mirror wired for the project,
+    // healthy, with zero drift (the gate LMDB-served reads use).
+    [[nodiscard]] bool canReleaseVector(const std::string& collection) const;
+    // v2.21.2 - the document's vector from the LMDB vector sub-db. nullopt
+    // when there is none (or no store is wired); THROWS on a read error.
+    [[nodiscard]] std::optional<std::vector<float>> readStoredVector(
+        const std::string& collection, const std::string& id) const;
     // v1.11 — operates on Document. If the doc has a "_vector" field, returns it
     // and strips the field from doc.data_binary (re-encodes the doc once).
     std::vector<float> extractVector(CollectionData& coll, Document& doc);
@@ -1464,8 +1521,8 @@ private:
     // to stamp an UNMARKED (pre-2.13.0) row, so every kind of write leaves a
     // definite marker - otherwise a legacy row only ever patched could never
     // report MISSING. Answered from the LMDB vector sub-db, the durable copy:
-    // coll.vectors is not, since eviction drops a vector from memory and a
-    // reload does not restore it. Called under the collection's write lock,
+    // coll.vectors is not, since eviction releases a vector from memory
+    // (v2.21.2; before that a reload never fetched one). Called under the collection's write lock,
     // which every writer of this document holds, so it cannot change under us.
     bool storedVectorExists(const std::string& collection, const std::string& id,
                             const CollectionData& coll) const;
@@ -1550,6 +1607,7 @@ private:
 
     // Incremental memory tracking - avoids expensive recalculation in getStats()
     std::atomic<uint64_t> estimatedMemoryBytes_{0};
+    std::atomic<uint64_t> vectorMemoryBytes_{0};   // v2.21.2, see addVectorBytes
 
     // Track last observed pressure for edge-triggered event fanout (T10)
     // mutable because pressure() is const but may update this as a side effect

+ 19 - 7
service/src/persistence/snapshot.cpp

@@ -768,15 +768,26 @@ void SnapshotManager::serializeStore(const MemoryStore& store, Sink& out,
         // in HistoryStore); the 8-byte zero count keeps v1.8.x readers happy.
         out.u64(0);
 
-        // Vector data (v3)
-        const auto* vectors = store.getCollectionVectors(name);
-        out.u64(vectors != nullptr ? static_cast<uint64_t>(vectors->size()) : 0);
-        if (vectors != nullptr) {
-            for (const auto& [docId, vec] : *vectors) {
+        // Vector data (v3). v2.21.2 - a batch at a time under the collection
+        // lock (it iterated the live map with no lock), and including the
+        // vectors eviction released, read back from LMDB. Like the doc count,
+        // the vector count precedes the entries, so a vector deleted before it
+        // is copied is written as a zero-length entry, which the loader skips
+        // (a pre-2.21.2 loader stores an empty vector, which scores nothing).
+        const auto vectorIds = store.getVectorIds(name);
+        out.u64(static_cast<uint64_t>(vectorIds.size()));
+        for (size_t i = 0; i < vectorIds.size(); i += kBatch) {
+            const auto vecs = store.copyVectors(name, vectorIds, i, kBatch);
+            for (size_t j = 0; j < vecs.size(); ++j) {
+                const std::string& docId = vectorIds[i + j];
                 out.u16(static_cast<uint16_t>(docId.size()));
                 out.bytes(docId);
-                out.u32(static_cast<uint32_t>(vec.size()));
-                out.bytes(vec.data(), vec.size() * sizeof(float));
+                if (!vecs[j]) {
+                    out.u32(0);
+                    continue;
+                }
+                out.u32(static_cast<uint32_t>(vecs[j]->size()));
+                out.bytes(vecs[j]->data(), vecs[j]->size() * sizeof(float));
             }
         }
     }
@@ -1023,6 +1034,7 @@ void SnapshotManager::deserializeStore(const std::vector<uint8_t>& data, MemoryS
                 }
                 size_t byteCount = static_cast<size_t>(dim) * sizeof(float);
                 if (off + byteCount > slice.vecSectionEnd) break;
+                if (dim == 0) continue;   // v2.21.2 placeholder: deleted while written
                 std::vector<float> vec(dim);
                 std::memcpy(vec.data(), &data[off], byteCount);
                 off += byteCount;

+ 9 - 0
tests/CMakeLists.txt

@@ -453,8 +453,17 @@ add_executable(test_dual_write_mirror
     ${CMAKE_CURRENT_SOURCE_DIR}/../service/src/relations/relation_index.cpp
     ${CMAKE_CURRENT_SOURCE_DIR}/../service/src/storage/secondary_index.cpp
     ${CMAKE_CURRENT_SOURCE_DIR}/../service/src/storage/subdb_identity.cpp
+    ${CMAKE_CURRENT_SOURCE_DIR}/../service/src/persistence/snapshot.cpp
 )
 
+# v2.21.2 - snapshot.cpp, for the released-vector snapshot round trip.
+if(TEST_LZ4_FOUND)
+    target_link_libraries(test_dual_write_mirror PRIVATE ${TEST_LZ4_LIBRARIES})
+    target_include_directories(test_dual_write_mirror PRIVATE ${TEST_LZ4_INCLUDE_DIRS})
+else()
+    target_link_libraries(test_dual_write_mirror PRIVATE lz4)
+endif()
+
 target_include_directories(test_dual_write_mirror PRIVATE
     ${CMAKE_CURRENT_SOURCE_DIR}/../service/src
     ${LMDB_INCLUDE_DIR}

+ 27 - 0
tests/load_test/test_snapshot_keeps_evicted.cpp

@@ -4,6 +4,11 @@
 // boot came up without it while LMDB kept it (7,219 rows on one production
 // instance, found by the 2.20.2 boot key audit).
 //
+// v2.21.2 - plus a vector collection: eviction now releases a vector from
+// memory too, so the snapshot must read a released vector back from LMDB and
+// the restarted server must hold every one of them (the script checks the
+// vector share of the memory line).
+//
 // Phases: seed (insert, wait for eviction) | check (after a restart)
 
 #include <smartbotic/database/client.hpp>
@@ -22,6 +27,15 @@ static void ck(bool c, const std::string& m) {
 // rotates and the snapshot after it deletes the first file - the state in which
 // an evicted row could no longer be read back from the WAL.
 static constexpr int kRows = 600;
+static constexpr int kVecRows = 300;
+static constexpr uint32_t kDim = 4096;   // 300 x 16 KiB = 4.7 MiB of vectors
+
+static std::vector<float> vectorFor(int i) {
+    std::vector<float> v(kDim, 0.0f);
+    v[static_cast<size_t>(i) % kDim] = 1.0f;          // row i is its own nearest neighbour
+    v[(static_cast<size_t>(i) * 7 + 1) % kDim] = 0.5f;
+    return v;
+}
 
 static uint64_t statFor(Client& c, bool evicted) {
     const auto s = c.getMemoryStats();
@@ -43,6 +57,12 @@ int main(int argc, char** argv) {
     c.connect();
 
     if (phase == "seed") {
+        // Vector rows first: they are the oldest, so eviction (capped at half
+        // the documents present when an episode starts) takes them first.
+        ck(c.createCollection("vecs", 0, false, 0, kDim), "seed: vector collection created");
+        for (int i = 0; i < kVecRows; ++i) {
+            c.insert("vecs", {{"i", i}, {"_vector", vectorFor(i)}}, "v" + std::to_string(i));
+        }
         for (int i = 0; i < kRows; ++i) {
             c.insert("kept", {{"i", i}, {"pad", std::string(200000, 'x')}}, "k" + std::to_string(i));
         }
@@ -57,6 +77,13 @@ int main(int argc, char** argv) {
         ck(statFor(c, false) == kRows && statFor(c, true) == 0,
            "check: every row is resident again after the restart (nothing evicted)");
         ck(c.count("kept") == kRows, "check: every row readable");
+        ck(c.count("vecs") == kVecRows, "check: every vector row readable");
+        int own = 0;
+        for (int i = 0; i < kVecRows; i += 30) {
+            auto r = c.similaritySearch("vecs", vectorFor(i), 1);
+            if (!r.empty() && r.front().id == "v" + std::to_string(i)) ++own;
+        }
+        ck(own == kVecRows / 30, "check: sampled vector rows are their own nearest neighbour");
     } else {
         return 2;
     }

+ 15 - 2
tests/load_test/test_snapshot_keeps_evicted.sh

@@ -30,6 +30,7 @@ cat > "$DIR/config.json" <<CFG
       "eviction_target_percent": 20,
       "eviction_check_interval_ms": 200,
       "hot_write_floor_ms": 0,
+      "eviction_max_episode_percent": 100,
       "memory_soft_percent": 50,
       "memory_hard_percent": 2000,
       "memory_emergency_percent": 4000
@@ -56,7 +57,7 @@ client() { LD_LIBRARY_PATH="$ROOT/build/client" "$DIR/t" "$1" 2>&1 | grep -v '\[
 fails=0
 ck() { if eval "$2"; then echo "ok   $1"; else echo "FAIL $1"; fails=$((fails+1)); fi; }
 
-config 1
+config 16   # vectors fit under the soft line; the 200 KB rows start the episode
 start 1
 client seed || fails=$((fails+1))
 # Two snapshots after eviction: the first truncates the WAL, the second must
@@ -68,16 +69,28 @@ for _ in $(seq 1 60); do
 done
 ck "two snapshots taken while rows were evicted" \
    "[[ \$(grep -c 'Created snapshot' '$DIR/server1.log') -ge $((base + 2)) ]]"
+# v2.21.2 - eviction released the vectors: a memory line logged after the
+# seed reports (almost) none resident.
+mc=$(grep -c "Memory check" "$DIR/server1.log" || true)
+for _ in $(seq 1 40); do
+    [[ $(grep -c "Memory check" "$DIR/server1.log" || true) -gt $mc ]] && break
+    sleep 0.5
+done
+ck "eviction released the vectors (vector share under 4 MB after the seed)" \
+   "grep 'Memory check' '$DIR/server1.log' | tail -1 | grep -q 'of which vectors [0-3] MB'"
 ck "no snapshot reported rows it could not load" "! grep -q 'could not be read for the snapshot\|will be missing from the snapshot' '$DIR/server1.log'"
 stop
 
 # Restart with a budget that evicts nothing, so memory holds every row resident.
 config 8192
 start 2
+for _ in $(seq 1 40); do grep -q "Memory check" "$DIR/server2.log" && break; sleep 0.5; done
+ck "boot 2: every vector is back in memory and counted (4 MB)" \
+   "grep 'Memory check' '$DIR/server2.log' | head -1 | grep -q 'of which vectors 4 MB'"
 ck "boot 2: key audit finds nothing on disk only" "grep -q 'key audit: .* consistent' '$DIR/server2.log'"
 client check || fails=$((fails+1))
 ck "no snapshot failed" "! grep -q 'Failed to create snapshot' '$DIR/server1.log' '$DIR/server2.log'"
-grep -h "Recovery complete\|key audit: [0-9]" "$DIR/server2.log" || true
+grep -h "Recovery complete\|key audit: [0-9]\|Memory check" "$DIR/server2.log" || true
 stop
 
 [[ $fails -eq 0 ]] && echo "OK - snapshot keeps evicted rows" || echo "FAILED ($fails)"

+ 152 - 0
tests/test_dual_write_mirror.cpp

@@ -16,6 +16,7 @@
 #include <optional>
 #include <stdexcept>
 #include <map>
+#include <set>
 #include <string>
 #include <unistd.h>
 
@@ -28,6 +29,7 @@
 #include "storage/dual_write_mirror.hpp"
 #include "storage/lmdb_env.hpp"
 #include "storage/mirror_pending.hpp"
+#include "persistence/snapshot.hpp"
 #include <fstream>
 
 namespace fs = std::filesystem;
@@ -781,6 +783,155 @@ void test_scan_vectors_round_trip() {
 
 }  // namespace
 
+// v2.21.2 - eviction releases a document's vector, a reload brings it back,
+// and vectors are counted wherever they enter memory. Found on a production
+// instance: ~615 MiB of vectors loaded at boot were outside the estimate, and
+// eviction could not free them (it erased the body and left coll.vectors).
+void test_eviction_releases_vectors() {
+    TmpEnv tmp("vec-evict");
+    LmdbDocumentStore doc_store(tmp.env);
+    std::atomic<bool> healthy{true};
+    std::atomic<uint64_t> drift{0};
+
+    MemoryStore::Config cfg;
+    cfg.nodeId = "test-node";
+    cfg.maxMemoryBytes = 64 * 1024;      // far below what is inserted: all of it is evictable
+    cfg.hotWriteFloorMs = 0;
+    MemoryStore mem(cfg);
+    mem.setDocumentStoreMirror([&doc_store](std::string_view) { return &doc_store; },
+                               &healthy, &drift);
+    mem.setDocumentLoadCallback([&doc_store](const std::string& c, const std::string& id,
+                                             uint64_t) { return doc_store.get(c, id); });
+
+    constexpr uint32_t kDim = 256;
+    const uint64_t kVecBytes = kDim * sizeof(float) + 32;   // estimateVectorSize
+    smartbotic::database::CollectionOptions opts;
+    opts.vectorDimension = kDim;
+    mem.createCollection("emb", opts);
+
+    auto vectorFor = [](int i) {
+        std::vector<float> v(kDim);
+        for (uint32_t k = 0; k < kDim; ++k) v[k] = static_cast<float>(i * 1000 + k);
+        return v;
+    };
+    constexpr int kRows = 40;
+    for (int i = 0; i < kRows; ++i) {
+        Document d;
+        d.id = "v" + std::to_string(i);
+        d.collection = "emb";
+        d.set_data({{"i", i}, {"_vector", vectorFor(i)}});
+        mem.insert("emb", d);
+    }
+    check(mem.getStats().vectorMemoryBytes == kRows * kVecBytes,
+          "vector evict: inserted vectors counted in the vector share");
+
+    // Boot-loaded vectors are counted too (they bypassed the estimate).
+    const uint64_t estBefore = mem.getStats().estimatedMemoryBytes;
+    mem.loadVector("emb", "boot-only", vectorFor(999));
+    check(mem.getStats().estimatedMemoryBytes == estBefore + kVecBytes &&
+              mem.getStats().vectorMemoryBytes == (kRows + 1) * kVecBytes,
+          "vector evict: loadVector adds to the estimate and the vector share");
+    mem.loadVector("emb", "boot-only", vectorFor(999));
+    check(mem.getStats().vectorMemoryBytes == (kRows + 1) * kVecBytes,
+          "vector evict: loading the same vector again counts it once");
+    mem.loadVector("emb", "placeholder", {});
+    check(!mem.residentVector("emb", "placeholder").has_value(),
+          "vector evict: a zero-length snapshot entry is not stored as a vector");
+
+    const uint64_t evicted = mem.evictDocuments();
+    check(evicted > 0, "vector evict: eviction ran");
+    std::vector<std::string> evictedIds;
+    for (int i = 0; i < kRows; ++i) {
+        const std::string id = "v" + std::to_string(i);
+        if (mem.isDocumentEvicted("emb", id)) evictedIds.push_back(id);
+    }
+    check(evictedIds.size() == evicted, "vector evict: stubs for every evicted document");
+    bool allReleased = true;
+    for (const auto& id : evictedIds) allReleased &= !mem.residentVector("emb", id).has_value();
+    check(allReleased, "vector evict: an evicted document's vector left memory");
+    check(mem.getStats().vectorMemoryBytes == (kRows + 1 - evicted) * kVecBytes,
+          "vector evict: the vector share fell by the released vectors");
+    check(!evictedIds.empty() && mem.hasVector("emb", evictedIds.front()),
+          "vector evict: hasVector still reports a released vector");
+
+    // The snapshot's view: every vector, resident or released, exact bytes.
+    const auto ids = mem.getVectorIds("emb");
+    check(ids.size() == kRows + 1, "vector evict: getVectorIds lists resident + released");
+    const auto vecs = mem.copyVectors("emb", ids, 0, ids.size());
+    bool exact = vecs.size() == ids.size();
+    for (size_t j = 0; exact && j < ids.size(); ++j) {
+        if (ids[j] == "boot-only") { exact = vecs[j] && *vecs[j] == vectorFor(999); continue; }
+        exact = vecs[j] && *vecs[j] == vectorFor(std::stoi(ids[j].substr(1)));
+    }
+    check(exact, "vector evict: copyVectors returns every vector byte-exact");
+
+    // A write reloads the document, and with it the vector.
+    const std::string back = evictedIds.front();
+    mem.ensureResident("emb", back);
+    check(!mem.isDocumentEvicted("emb", back), "vector evict: reload brought the body back");
+    auto reloaded = mem.residentVector("emb", back);
+    check(reloaded && *reloaded == vectorFor(std::stoi(back.substr(1))),
+          "vector evict: reload brought the vector back, exact");
+    check(mem.patchDocument("emb", back, {{"p", 1}}) > 0 &&
+              mem.residentVector("emb", back).has_value() &&
+              doc_store.get_vector("emb", back).has_value(),
+          "vector evict: a patch after the reload keeps the vector, in memory and on disk");
+
+    // A delete of a still-evicted document removes its vector everywhere.
+    const std::string gone = evictedIds.back();
+    check(mem.remove("emb", gone), "vector evict: delete an evicted document");
+    check(!mem.hasVector("emb", gone) && !doc_store.get_vector("emb", gone).has_value(),
+          "vector evict: deleted document has no vector anywhere");
+    const auto afterIds = mem.getVectorIds("emb");
+    check(std::find(afterIds.begin(), afterIds.end(), gone) == afterIds.end(),
+          "vector evict: deleted document not listed for the snapshot");
+
+    // Mirror unhealthy: LMDB may be behind, so the vector must stay resident.
+    healthy = false;
+    Document d;
+    d.id = "unhealthy";
+    d.collection = "emb";
+    d.set_data({{"_vector", vectorFor(7)}});
+    mem.insert("emb", d);
+    for (int i = 0; i < kRows; ++i) {   // push the estimate over the target again
+        Document more;
+        more.id = "u" + std::to_string(i);
+        more.collection = "emb";
+        more.set_data({{"_vector", vectorFor(i)}});
+        mem.insert("emb", more);
+    }
+    for (int round = 0; round < 50 && !mem.isDocumentEvicted("emb", "unhealthy"); ++round) {
+        mem.evictDocuments();   // the newest row goes last
+    }
+    check(mem.isDocumentEvicted("emb", "unhealthy") &&
+              mem.residentVector("emb", "unhealthy").has_value(),
+          "vector evict: an unhealthy mirror keeps the vector resident");
+    healthy = true;
+
+    // The snapshot carries every vector, released ones read from LMDB, and a
+    // store loaded from it has them all resident and counted.
+    const auto snapDir = make_tmpdir("vec-evict-snap");
+    smartbotic::database::SnapshotManager::Config scfg;
+    scfg.snapshotDir = snapDir;
+    smartbotic::database::SnapshotManager mgr(scfg);
+    const auto path = mgr.createSnapshot(mem, 1);
+    MemoryStore loaded(cfg);
+    mgr.loadSnapshot(path, loaded);
+    const auto expectIds = mem.getVectorIds("emb");
+    bool allBack = !expectIds.empty();
+    for (const auto& id : expectIds) {
+        auto want = mem.copyVectors("emb", {id}, 0, 1).front();
+        auto got = loaded.residentVector("emb", id);
+        allBack &= want && got && *want == *got;
+    }
+    check(allBack, "vector evict: every vector (resident and released) survives a snapshot");
+    check(!loaded.hasVector("emb", gone), "vector evict: the deleted vector is not in the snapshot");
+    std::set<std::string> distinct(expectIds.begin(), expectIds.end());
+    check(loaded.getStats().vectorMemoryBytes == distinct.size() * kVecBytes,
+          "vector evict: a store loaded from the snapshot counts its vectors");
+    fs::remove_all(snapDir);
+}
+
 int main() {
     test_unit_null_store_is_noop();
     test_unit_system_collection_skipped();
@@ -801,6 +952,7 @@ int main() {
     test_sync_doc_store_from_memory();
     test_backfill_iteration_pattern();
     test_scan_vectors_round_trip();
+    test_eviction_releases_vectors();
 
     std::cout << "dual_write_mirror: " << g_pass << " passed, " << g_fail << " failed\n";
     return g_fail == 0 ? 0 : 1;

Daži faili netika attēloti, jo izmaiņu fails ir pārāk liels