Quellcode durchsuchen

fix: release mirrored vectors from memory; served_from_memory on Find/SimilaritySearch

Every vector was held twice: in MemoryStore and, for search, in LMDB's
pages. While the mirror is healthy every vector read is LMDB-served, so the
memory copy only competed with the page cache (616 MiB on one 2 GB host,
whose first search per collection took 1.4-5.1 s while memory went to swap).

The eviction loop now drops a vector once LMDB holds a byte-identical copy
(mirror healthy, zero drift, no write in flight); a write reads it back
first; snapshot, residentVector and the degraded search read released
vectors from LMDB. served_from_memory (capability of the same name) tells a
caller which store answered; client SearchPath overloads, no struct grows.
fszontagh vor 3 Wochen
Ursprung
Commit
fc78e7f5be

+ 22 - 0
CHANGELOG.md

@@ -12,7 +12,29 @@ consumer-facing usage is in `docs/integration-guide.md`.
 
 ## Unreleased
 
+### Added
+- **[both]** `served_from_memory` on `FindResponse` and
+  `SimilaritySearchResponse`, capability `served_from_memory`: true when
+  MemoryStore answered instead of LMDB (mirror unhealthy or drifted, or a `_`
+  system collection). Client: `Client::SearchPath` filled by new overloads
+  `similaritySearch(..., filters, SearchPath&)` and
+  `findWithMetrics(..., SearchPath&)`. No existing struct changes size. Before
+  this a degraded vector search looked exactly like a healthy one.
+
 ### Fixed
+- **[server]** Every vector was held twice: in MemoryStore (616 MiB on one
+  production instance) and, for search, in LMDB's pages. Search, get and
+  export already read LMDB, so the memory copy only competed with the page
+  cache; on a 2 GB host the first search on a large collection took 1.4-5.1 s
+  while process memory went to swap. The eviction loop now drops a vector from
+  memory once LMDB holds a byte-identical copy (mirror healthy, zero drift, no
+  write in flight); a write reads it back first; the degraded search reads
+  released vectors from LMDB, so it loses none. The memory line adds
+  `(R more in LMDB only)`. **Observable:** the estimate falls by the vector
+  share within seconds of boot; nothing a client reads changes. **Latency:**
+  a write to a row whose vector was released does one extra LMDB read
+  (`dimension x 4` bytes); a degraded search reads every released vector from
+  LMDB.
 - **[server]** Every boot logged eight "v2.0 deprecation: storage.memory.<key>
   is deprecated and will be removed in v2.1" warnings for `max_memory_mb` and
   the eviction keys. They were never removed and no removal is planned: they

Datei-Diff unterdrückt, da er zu groß ist
+ 0 - 0
CLAUDE.md


+ 40 - 0
client/include/smartbotic/database/client.hpp

@@ -348,6 +348,12 @@ public:
         /// `invalid_pattern`. Older servers used std::regex (ECMAScript) and
         /// answered an invalid pattern with an empty result.
         static constexpr const char* kRe2RegexFilters = "re2_regex_filters";
+        /// 2.21.3: Find and SimilaritySearch responses say whether the
+        /// server's in-memory fallback answered instead of LMDB; read it
+        /// through the SearchPath overloads. Without this capability the
+        /// server cannot say, and SearchPath::servedFromMemory is false
+        /// regardless.
+        static constexpr const char* kServedFromMemory = "served_from_memory";
     };
 
     struct ServerInfo {
@@ -871,6 +877,28 @@ public:
     [[nodiscard]] FindResult findWithMetrics(const std::string& collection,
                                               const QueryOptions& options);
 
+    /**
+     * v2.21.3 - which store answered a find() or similaritySearch().
+     *
+     * servedFromMemory is true when the server's in-memory fallback answered
+     * instead of LMDB: the LMDB mirror is unhealthy or drifted (an operator
+     * condition), or the collection is a `_` system collection. It is
+     * meaningful only when serverSupports(Capability::kServedFromMemory); an
+     * older server never sets it, so there false means "cannot say".
+     *
+     * A separate type filled through an out-parameter overload, never a new
+     * member of FindResult or SimilarityResult: those are returned by value,
+     * and growing them under soname 2 crashes installed consumers.
+     */
+    struct SearchPath {
+        bool servedFromMemory = false;
+    };
+
+    /** findWithMetrics(), also reporting which store answered. */
+    [[nodiscard]] FindResult findWithMetrics(const std::string& collection,
+                                              const QueryOptions& options,
+                                              SearchPath& pathOut);
+
     // ===== Export (v2.13.0) =====
 
     /** What an exported row says about its vector. */
@@ -1010,6 +1038,18 @@ public:
         float minScore,
         const std::vector<Filter>& filters);
 
+    /**
+     * v2.21.3 - the filtered search above, also reporting which store
+     * answered (see SearchPath). An empty `filters` is the plain search.
+     */
+    [[nodiscard]] std::vector<SimilarityResult> similaritySearch(
+        const std::string& collection,
+        const std::vector<float>& queryVector,
+        uint32_t topK,
+        float minScore,
+        const std::vector<Filter>& filters,
+        SearchPath& pathOut);
+
     // ===== Collection Management =====
 
     bool createCollection(const std::string& name, uint32_t defaultTtlSeconds = 0,

+ 21 - 2
client/src/client.cpp

@@ -1032,7 +1032,8 @@ public:
 
     Client::FindResult findWithMetrics(const std::string& collection,
                                         const Client::QueryOptions& options,
-                                        const std::vector<std::string>& projection = {}) {
+                                        const std::vector<std::string>& projection = {},
+                                        Client::SearchPath* pathOut = nullptr) {
         smartbotic::databasepb::FindRequest request;
         request.set_collection(qualify(collection));
 
@@ -1092,6 +1093,7 @@ public:
         result.walMatchCount = response.wal_match_count();
         result.memorySearchMicros = response.memory_search_micros();
         result.walSearchMicros = response.wal_search_micros();
+        if (pathOut) pathOut->servedFromMemory = response.served_from_memory();
 
         result.documents.reserve(response.documents_size());
         for (const auto& doc : response.documents()) {
@@ -1230,7 +1232,8 @@ public:
     std::vector<Client::SimilarityResult> similaritySearch(
         const std::string& collection, const std::vector<float>& queryVector,
         uint32_t topK, float minScore,
-        const std::vector<Client::Filter>& filters = {}) {
+        const std::vector<Client::Filter>& filters = {},
+        Client::SearchPath* pathOut = nullptr) {
         // v2.15.0 - a server that answers GetServerInfo and lacks the feature
         // is refused before sending. A pre-2.15.0 server cannot say, so for it
         // the response's filters_applied (below) remains the guard.
@@ -1278,6 +1281,8 @@ public:
                                 R"({"reason":"filters_unsupported"})"));
         }
 
+        if (pathOut) pathOut->servedFromMemory = response.served_from_memory();
+
         std::vector<Client::SimilarityResult> results;
         results.reserve(response.results_size());
         for (const auto& r : response.results()) {
@@ -3415,6 +3420,12 @@ Client::FindResult Client::findWithMetrics(const std::string& collection,
     return impl_->findWithMetrics(collection, options);
 }
 
+Client::FindResult Client::findWithMetrics(const std::string& collection,
+                                            const QueryOptions& options,
+                                            SearchPath& pathOut) {
+    return impl_->findWithMetrics(collection, options, {}, &pathOut);
+}
+
 uint64_t Client::count(const std::string& collection,
                                const std::vector<Filter>& filters) {
     return impl_->count(collection, filters);
@@ -3462,6 +3473,14 @@ std::vector<Client::SimilarityResult> Client::similaritySearch(
     return impl_->similaritySearch(collection, queryVector, topK, minScore, filters);
 }
 
+std::vector<Client::SimilarityResult> Client::similaritySearch(
+    const std::string& collection, const std::vector<float>& queryVector,
+    uint32_t topK, float minScore, const std::vector<Filter>& filters,
+    SearchPath& pathOut) {
+    return impl_->similaritySearch(collection, queryVector, topK, minScore, filters,
+                                   &pathOut);
+}
+
 bool Client::createCollection(const std::string& name, uint32_t defaultTtlSeconds,
                               bool encrypted, uint32_t maxVersions, uint32_t vectorDimension) {
     return impl_->createCollection(name, defaultTtlSeconds, encrypted, maxVersions, vectorDimension);

+ 58 - 0
docs/integration-guide.md

@@ -2383,6 +2383,64 @@ ways:
   during that time, `createCollection` included, so bootstrap steps a service
   runs at startup fail until pressure drops.
 
+#### Mirrored vectors leave memory (2.21.3+)
+
+While the LMDB mirror is healthy, every read of a vector (similarity search,
+filtered search, `get`/`find` with `WithVector`, export) is served from LMDB,
+so the copy MemoryStore kept was a second copy of the same bytes. On a small
+host the two competed: one production instance (1973 MB RAM) held 616 MiB of
+vectors in memory while search pulled the same vectors through the page cache,
+and the first search on a large collection took 1.4-5.1 s reading them from
+disk while process memory went to swap.
+
+From 2.21.3 the eviction loop drops a vector from memory on every tick
+(about every 5 s) once LMDB holds a **byte-identical** copy, whatever the
+memory pressure:
+
+- **Only while the mirror is healthy with zero drift**, and never for a
+  document with a write in flight. A vector LMDB lacks or disagrees with stays
+  in memory (WARN `Vector release: N vector(s) kept in memory ...`) until the
+  next write to the row.
+- **A write reads it back first.** Every write path (insert over an id,
+  update, conditional update, upsert, patch, set ops, restore, delete) reads
+  a released vector back from LMDB before it runs, so the write sees the
+  document exactly as before. If LMDB cannot be read, the write fails rather
+  than proceed as if the row had no vector.
+- **Nothing a client reads changes.** Search, get and export already read
+  LMDB. The snapshot reads released vectors from LMDB. The degraded search
+  (mirror unhealthy) scores released vectors by reading them from LMDB, so it
+  loses no candidates; an LMDB read error there is an error, not a shorter
+  answer.
+- **The memory line** reads `..., of which vectors V MB (R more in LMDB
+  only), ...`: `V` is what is still in memory, `R` the number released. After
+  a release of 16 MB or more the server calls `malloc_trim` so the freed
+  memory goes back to the system. At boot the snapshot still loads every
+  vector into memory (the boot peak is unchanged); the first tick releases them.
+
+Not changed: the first search on a collection still reads its vectors from
+disk into the page cache (about `rows x dimension x 4` bytes). With the
+duplicate gone that cache has room to stay.
+
+#### Which store answered: `served_from_memory` (2.21.3+)
+
+`FindResponse` and `SimilaritySearchResponse` carry `served_from_memory`
+(capability `served_from_memory`): true when MemoryStore answered instead of
+LMDB, i.e. the mirror is unhealthy or drifted, or the collection is a `_`
+system collection. Every server with the capability always sets it; from an
+older server false means "cannot say". Read it through the out-parameter
+overloads (a separate type, so no returned struct changes size):
+
+```cpp
+Client::SearchPath path;
+auto hits = db.similaritySearch("kb", vec, 5, 0.0f, filters, path);   // filters may be {}
+auto page = db.findWithMetrics("kb", Client::QueryOptions{}, path);
+if (!db.serverSupports(Client::Capability::kServedFromMemory)) { /* unknown */ }
+else if (path.servedFromMemory) { /* degraded: an operator condition */ }
+```
+
+On a find, `memoryMatchCount` is not a substitute: it is 0 on the LMDB path
+but also 0 on a degraded find that matched nothing.
+
 #### Drain cap (2.4.3+)
 
 Eviction assumes the memory estimate falls as documents leave. When memory is

+ 9 - 0
proto/database.proto

@@ -509,6 +509,11 @@ message FindResponse {
     uint32 wal_match_count = 6;         // Documents matched from WAL
     uint64 memory_search_micros = 7;    // Time spent searching memory (µs)
     uint64 wal_search_micros = 8;       // Time spent loading/searching WAL (µs)
+    // v2.21.3 (capability `served_from_memory`) - true when MemoryStore
+    // answered instead of LMDB: the mirror is unhealthy or drifted, or the
+    // collection is a `_` system collection. Every server with the capability
+    // sets it; from an older server false means "cannot say", not "LMDB".
+    bool served_from_memory = 9;
 }
 
 message CountRequest {
@@ -615,6 +620,10 @@ message SimilaritySearchResponse {
     // never sets it, so a client that sent filters and reads false must NOT
     // use the results: they are unfiltered.
     bool filters_applied = 2;
+    // v2.21.3 (capability `served_from_memory`) - true when MemoryStore's
+    // degraded search answered instead of LMDB (mirror unhealthy or drifted).
+    // Same rule as FindResponse.served_from_memory.
+    bool served_from_memory = 3;
 }
 
 message SimilarityResult {

+ 2 - 0
service/src/database_grpc_impl.cpp

@@ -1698,6 +1698,7 @@ grpc::Status DatabaseGrpcImpl::Find(
     response->set_wal_match_count(result.walMatchCount);
     response->set_memory_search_micros(result.memorySearchMicros);
     response->set_wal_search_micros(result.walSearchMicros);
+    response->set_served_from_memory(!used_lmdb);   // v2.21.3
 
     for (auto& doc : result.documents) {
         encryption_.decryptSensitiveFields(doc);
@@ -2032,6 +2033,7 @@ grpc::Status DatabaseGrpcImpl::SimilaritySearch(
             }
         }
         response->set_filters_applied(true);
+        response->set_served_from_memory(!used_lmdb);   // v2.21.3
 
         for (auto& result : results) {
             // Decrypt sensitive fields before returning

+ 186 - 9
service/src/memory_store.cpp

@@ -11,6 +11,7 @@
 
 #if defined(__GLIBC__) && !defined(__APPLE__)
 #include <malloc.h>
+#include <cstring>
 #endif
 
 #include <spdlog/spdlog.h>
@@ -2407,6 +2408,8 @@ std::vector<float> MemoryStore::extractVector(CollectionData& coll, Document& do
 void MemoryStore::storeVector(CollectionData& coll, const std::string& docId,
                                const std::vector<float>& vec) {
     if (vec.empty()) return;
+    coll.releasedVectors.erase(docId);      // v2.21.3 - memory holds it again
+    coll.vectorsKeptResident.erase(docId);
 
     uint64_t oldSize = 0;
     auto existing = coll.vectors.find(docId);
@@ -2428,6 +2431,8 @@ void MemoryStore::storeVector(CollectionData& coll, const std::string& docId,
 }
 
 void MemoryStore::removeVector(CollectionData& coll, const std::string& docId) {
+    coll.releasedVectors.erase(docId);      // v2.21.3
+    coll.vectorsKeptResident.erase(docId);
     auto it = coll.vectors.find(docId);
     if (it != coll.vectors.end()) {
         uint64_t freed = estimateVectorSize(it->second);
@@ -2465,7 +2470,7 @@ std::vector<MemoryStore::SimilarityResult> MemoryStore::similaritySearch(
 
     std::shared_lock<std::shared_mutex> collLock(coll.mutex);
 
-    if (coll.vectors.empty()) {
+    if (coll.vectors.empty() && coll.releasedVectors.empty()) {
         return {};
     }
 
@@ -2493,6 +2498,21 @@ std::vector<MemoryStore::SimilarityResult> MemoryStore::similaritySearch(
             scored.push_back({docId, score});
         }
     }
+    // v2.21.3 - vectors released to LMDB are scored from there, so this
+    // degraded path (mirror unhealthy) does not lose them. LMDB's copy is
+    // current: it was byte-identical when released, and every write since
+    // would have read it back into memory first. A read error throws (the
+    // caller gets an error, not a silently shorter answer).
+    for (const auto& docId : coll.releasedVectors) {
+        auto vec = readStoredVector(collection, docId);
+        if (!vec || vec->size() != queryVector.size()) continue;
+        const float score = cosineSimilaritySIMD(
+            queryVector.data(), vec->data(), vec->size(), queryNorm,
+            computeNorm(vec->data(), vec->size()));
+        if (score >= minScore) {
+            scored.push_back({docId, score});
+        }
+    }
 
     // partial_sort for top-K
     uint32_t k = std::min(topK, static_cast<uint32_t>(scored.size()));
@@ -2540,6 +2560,7 @@ void MemoryStore::loadVector(const std::string& collection, const std::string& d
     if (vec.empty()) return;
 
     std::unique_lock<std::shared_mutex> lock(coll->mutex);
+    coll->releasedVectors.erase(docId);   // v2.21.3
 
     // v2.21.2 - counted, through storeVector's accounting. Boot-loaded
     // vectors (snapshot, WAL replay) used to bypass the estimate entirely, so
@@ -3415,16 +3436,20 @@ 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;
+    {
+        std::shared_lock<std::shared_mutex> lock(coll->mutex);
+        auto it = coll->vectors.find(id);
+        if (it != coll->vectors.end()) return it->second;
+        if (coll->releasedVectors.count(id) == 0) return std::nullopt;
+    }
+    return readStoredVector(collection, id);   // v2.21.3 - released
 }
 
 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;
+        if (coll->releasedVectors.count(id) != 0) return true;   // v2.21.3
     }
     auto stub = getEvictedStub(collection, id);
     return stub && stub->vectorEvicted;
@@ -3434,8 +3459,9 @@ std::vector<std::string> MemoryStore::getVectorIds(const std::string& collection
     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());
+        ids.reserve(coll->vectors.size() + coll->releasedVectors.size());
         for (const auto& [id, vec] : coll->vectors) ids.push_back(id);
+        for (const auto& id : coll->releasedVectors) ids.push_back(id);   // v2.21.3
     }
     // Evicted after the resident ids were listed: listed twice, written
     // twice, and the loader keeps one. Never missed.
@@ -3456,11 +3482,13 @@ std::vector<std::optional<std::vector<float>>> MemoryStore::copyVectors(
     if (from >= end) return out;
     out.resize(end - from);
     std::vector<size_t> missing;
+    std::vector<size_t> released;   // v2.21.3 - in LMDB only
     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 if (coll->releasedVectors.count(ids[i]) != 0) released.push_back(i);
             else missing.push_back(i);
         }
     } else {
@@ -3472,6 +3500,9 @@ std::vector<std::optional<std::vector<float>>> MemoryStore::copyVectors(
     // 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).
+    // A released vector of a resident document: same reasoning, LMDB holds
+    // the current copy (a write reads it back into memory first).
+    for (size_t i : released) out[i - from] = readStoredVector(collection, ids[i]);
     for (size_t i : missing) {
         auto stub = getEvictedStub(collection, ids[i]);
         if (stub && stub->vectorEvicted) {
@@ -3485,6 +3516,137 @@ std::vector<std::optional<std::vector<float>>> MemoryStore::copyVectors(
     return out;
 }
 
+void MemoryStore::restoreReleasedVector(const std::string& collection, const std::string& id) {
+    if (const CollectionData* coll = getCollection(collection)) {
+        std::shared_lock<std::shared_mutex> lock(coll->mutex);
+        if (coll->releasedVectors.count(id) == 0) return;
+    } else {
+        return;
+    }
+    // Read outside the collection lock; a read error throws and fails the
+    // write, which must not proceed as if the row had no vector.
+    auto vec = readStoredVector(collection, id);
+
+    std::shared_lock<std::shared_mutex> globalLock(globalMutex_);
+    auto it = collections_.find(collection);
+    if (it == collections_.end()) return;
+    CollectionData& coll = *it->second;
+    std::unique_lock<std::shared_mutex> lock(coll.mutex);
+    // Gone from the set meanwhile: another write restored it (and may have
+    // changed it since), or it was deleted. Either way not ours to restore.
+    if (coll.releasedVectors.count(id) == 0) return;
+    if (vec) {
+        storeVector(coll, id, *vec);   // also takes it out of releasedVectors
+    } else {
+        // Released only because LMDB held it; nothing deletes it there
+        // without going through a write, which restores first. Never expected.
+        coll.releasedVectors.erase(id);
+        spdlog::warn("Vector of {}/{} was released to LMDB and is no longer there; "
+                     "the document continues without one", collection, id);
+    }
+}
+
+size_t MemoryStore::releaseMirroredVectors() {
+    if (!docStoreResolver_) return 0;
+    std::vector<std::string> names;
+    {
+        std::shared_lock<std::shared_mutex> globalLock(globalMutex_);
+        for (const auto& [name, coll] : collections_) {
+            if (coll->options.vectorDimension > 0) names.push_back(name);
+        }
+    }
+    constexpr size_t kBatch = 256;   // vectors per hold of the collection lock
+    size_t released = 0, keptResident = 0;
+    uint64_t freed = 0;
+    for (const auto& name : names) {
+        if (!canReleaseVector(name)) continue;
+        smartbotic::db::storage::DocumentStore* ds = nullptr;
+        std::string subName;
+        try {
+            const auto pc = smartbotic::database::parseProjectCollection(name);
+            ds = docStoreResolver_(pc.project);
+            subName = pc.collection;
+        } catch (const std::exception&) {
+            continue;
+        }
+        if (ds == nullptr) continue;
+
+        for (;;) {
+            std::shared_lock<std::shared_mutex> globalLock(globalMutex_);
+            auto it = collections_.find(name);
+            if (it == collections_.end()) break;
+            CollectionData& coll = *it->second;
+            std::unique_lock<std::shared_mutex> lock(coll.mutex);
+            // Re-checked under the lock: a mirror failure since the check
+            // above means LMDB may be behind, and nothing may be released.
+            if (!canReleaseVector(name)) break;
+            size_t inBatch = 0, examined = 0;
+            for (auto vit = coll.vectors.begin();
+                 vit != coll.vectors.end() && examined < kBatch;) {
+                const std::string& id = vit->first;
+                if (coll.vectorsKeptResident.count(id) != 0 || hasInFlightWrite(coll, id)) {
+                    ++vit;
+                    continue;
+                }
+                ++examined;
+                // Byte-exact or not at all: a vector LMDB lacks or disagrees
+                // with would be lost by releasing it.
+                std::optional<std::vector<float>> stored;
+                try {
+                    stored = ds->get_vector(subName, id);
+                } catch (const std::exception& e) {
+                    spdlog::warn("Vector release: LMDB read of {}/{} failed ({}); kept in memory",
+                                 name, id, e.what());
+                    coll.vectorsKeptResident.insert(id);
+                    ++keptResident;
+                    ++vit;
+                    continue;
+                }
+                const auto& vec = vit->second;
+                if (!stored || stored->size() != vec.size() ||
+                    std::memcmp(stored->data(), vec.data(), vec.size() * sizeof(float)) != 0) {
+                    coll.vectorsKeptResident.insert(id);
+                    ++keptResident;
+                    ++vit;
+                    continue;
+                }
+                const uint64_t size = estimateVectorSize(vec);
+                coll.vectorNorms.erase(id);
+                coll.releasedVectors.insert(id);
+                vit = coll.vectors.erase(vit);
+                subVectorBytes(size);
+                freed += size;
+                ++released;
+                ++inBatch;
+            }
+            if (inBatch == 0) break;   // nothing left this collection can release
+        }
+    }
+    if (keptResident > 0) {
+        spdlog::warn("Vector release: {} vector(s) kept in memory because LMDB's copy is "
+                     "missing or differs; a write to the row retries", keptResident);
+    }
+    if (released > 0) {
+        spdlog::info("Released {} vector(s) ({} MB) from memory; LMDB holds them",
+                     released, freed / (1024 * 1024));
+#if defined(__GLIBC__) && !defined(__APPLE__)
+        // Thousands of 16 KB blocks freed at once sit in the heap otherwise.
+        if (freed >= 16ULL * 1024 * 1024) ::malloc_trim(0);
+#endif
+    }
+    return released;
+}
+
+size_t MemoryStore::releasedVectorCount() const {
+    size_t n = 0;
+    std::shared_lock<std::shared_mutex> globalLock(globalMutex_);
+    for (const auto& [name, coll] : collections_) {
+        std::shared_lock<std::shared_mutex> lock(coll->mutex);
+        n += coll->releasedVectors.size();
+    }
+    return n;
+}
+
 std::vector<std::pair<std::string, CollectionOptions>> MemoryStore::getAllCollectionsWithOptions() const {
     std::shared_lock<std::shared_mutex> lock(globalMutex_);
 
@@ -3779,6 +3941,7 @@ void MemoryStore::reloadIfEvicted(const std::string& collection, const std::stri
     if (id.empty()) return;
     if (!getEvictedStub(collection, id)) {
         adoptFromDocStore(collection, id);   // v2.20.2
+        restoreReleasedVector(collection, id);   // v2.21.3
         return;
     }
     if (loadEvictedDocument(collection, id)) return;
@@ -4192,12 +4355,14 @@ void MemoryStore::logMemoryCheck() {
     auto stats = getStats();
     // 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",
+    // v2.21.3 - plus how many vectors live in LMDB only (released).
+    spdlog::info("Memory check: {} MB estimated ({}%, pressure={}), of which vectors {} MB "
+                "({} more in LMDB only), {} docs, {} evicted",
                 stats.estimatedMemoryBytes / (1024 * 1024),
                 pressurePercent(),
                 memoryPressureToString(pressure()),
                 stats.vectorMemoryBytes / (1024 * 1024),
+                releasedVectorCount(),
                 stats.totalDocuments,
                 stats.evictedCount);
 
@@ -4235,6 +4400,14 @@ void MemoryStore::evictionLoop() {
 
         evictionCheckCount_++;
 
+        // v2.21.3 - every tick, whatever the pressure: a vector LMDB holds is
+        // a second copy in memory (search, get and export read LMDB).
+        try {
+            releaseMirroredVectors();
+        } catch (const std::exception& e) {
+            spdlog::error("Vector release failed: {}", e.what());
+        }
+
         // Log memory status every 12 checks (~60s with default 5s interval)
         if (evictionCheckCount_ % 12 == 1) {
             logMemoryCheck();
@@ -4681,12 +4854,16 @@ bool MemoryStore::evictDocument(const std::string& collection, const std::string
     // 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;
+    // v2.21.3 - not one the release sweep found LMDB disagreeing with.
     if (auto vit = coll->vectors.find(id);
-        vit != coll->vectors.end() && canReleaseVector(collection)) {
+        vit != coll->vectors.end() && canReleaseVector(collection) &&
+        coll->vectorsKeptResident.count(id) == 0) {
         vectorFreed = estimateVectorSize(vit->second);
         coll->vectors.erase(vit);
         coll->vectorNorms.erase(id);
         stub.vectorEvicted = true;
+    } else if (coll->releasedVectors.erase(id) != 0) {
+        stub.vectorEvicted = true;   // v2.21.3 - already in LMDB only
     }
 
     // Remove from expiration index

+ 29 - 0
service/src/memory_store.hpp

@@ -886,6 +886,22 @@ public:
      */
     [[nodiscard]] std::optional<std::vector<float>> residentVector(
         const std::string& collection, const std::string& id) const;
+    // v2.21.3 - also a vector releaseMirroredVectors() moved out of memory,
+    // read back from LMDB (THROWS on a read error). The update handler logs
+    // VEC_DELETE when this answers nullopt, so it must never miss one.
+
+    /**
+     * v2.21.3 - drop from memory every resident vector LMDB holds a
+     * byte-identical copy of, while the mirror is healthy with zero drift
+     * (canReleaseVector). Skips documents with a write in flight. A write
+     * reads the vector back before it runs; search, export and get read
+     * LMDB anyway. Returns the number released. Called by the eviction loop
+     * on every tick; public for the tests.
+     */
+    size_t releaseMirroredVectors();
+
+    /** v2.21.3 - how many vectors are released (in LMDB only) right now. */
+    [[nodiscard]] size_t releasedVectorCount() const;
 
     /**
      * v2.21.2 - does the document have a vector, resident or released by
@@ -1326,6 +1342,15 @@ private:
         // per-collection .hlog files under <data_dir>/history/.
         std::unordered_map<std::string, std::vector<float>> vectors;       // docId -> embedding vector
         std::unordered_map<std::string, float> vectorNorms;                // cached L2 norms
+        // v2.21.3 - resident documents whose vector is no longer in memory:
+        // LMDB held a byte-identical copy when releaseMirroredVectors()
+        // dropped it, and every write reads it back first
+        // (restoreReleasedVector), so LMDB's copy stays the current one.
+        // Disjoint from `vectors`; storeVector/removeVector take an id out.
+        std::unordered_set<std::string> releasedVectors;
+        // v2.21.3 - vectors the sweep found LMDB disagreeing with: kept
+        // resident (releasing them would lose them) until the next write.
+        std::unordered_set<std::string> vectorsKeptResident;
         uint64_t createdAt = 0;
         uint64_t updatedAt = 0;
         mutable std::shared_mutex mutex;
@@ -1441,6 +1466,10 @@ private:
     // production instance. MemoryStore is rebuilt from snapshot + WAL, never
     // from LMDB, so once the two disagree no restart repairs it.
     void reloadIfEvicted(const std::string& collection, const std::string& id);
+    // v2.21.3 - read a released vector back into memory before a write, so
+    // the write paths (and their undo copies) see it as before. THROWS when
+    // LMDB cannot be read: the write fails rather than drop the vector.
+    void restoreReleasedVector(const std::string& collection, const std::string& id);
 
     // v2.20.2 - see reloadIfEvicted. Only while the mirror is healthy with no
     // drift (otherwise MemoryStore may be ahead of LMDB, and adopting would

+ 2 - 1
service/src/server_capabilities.hpp

@@ -18,7 +18,7 @@
 
 namespace smartbotic::database {
 
-inline constexpr std::array<std::string_view, 26> kServerCapabilities = {
+inline constexpr std::array<std::string_view, 27> kServerCapabilities = {
     "projects",              // 2.3.0  <project>:<collection> namespaces
     "access_policy",         // 2.7.0  row/column security
     "query_projection",      // 2.7.1  FindRequest.projection
@@ -45,6 +45,7 @@ inline constexpr std::array<std::string_view, 26> kServerCapabilities = {
     "typed_range_filters",   // 2.18.0 GT/GTE/LT/LTE match number~number and string~string only
     "document_expires_at",   // 2.19.0 _expires_at filterable; reserved in write bodies
     "re2_regex_filters",     // 2.20.0 REGEX filters use RE2 (UTF-8, linear); invalid_pattern refusals
+    "served_from_memory",    // 2.21.3 Find/SimilaritySearch responses say whether MemoryStore answered
 };
 
 }  // namespace smartbotic::database

+ 22 - 0
tests/load_test/test_filtered_similarity.cpp

@@ -277,6 +277,28 @@ static int check() {
         }
         ck(same, "empty filters: same as the plain search");
     }
+    // v2.21.3 - which store answered. LMDB serves a healthy, non-system
+    // collection; MemoryStore serves `_` system collections.
+    {
+        Client::SearchPath path;
+        path.servedFromMemory = true;
+        const auto a = c.similaritySearch("kb", q, 30, 0.0f, std::vector<F>{}, path);
+        ck(a.size() == 30 && !path.servedFromMemory,
+           "served_from_memory: a healthy search is served by LMDB (false)");
+        path.servedFromMemory = true;
+        (void)c.similaritySearch("kb", q, 5, 0.0f, {F::eq("dept", "b")}, path);
+        ck(!path.servedFromMemory, "served_from_memory: a filtered search too");
+        path.servedFromMemory = true;
+        const auto f = c.findWithMetrics("kb", Client::QueryOptions{}, path);
+        ck(!f.documents.empty() && !path.servedFromMemory,
+           "served_from_memory: findWithMetrics on LMDB (false)");
+        path.servedFromMemory = false;
+        (void)c.findWithMetrics("_collection_meta", Client::QueryOptions{}, path);
+        ck(path.servedFromMemory,
+           "served_from_memory: a system collection is served from memory (true)");
+        ck(c.serverSupports(Client::Capability::kServedFromMemory),
+           "served_from_memory: capability advertised");
+    }
     // A collection without a vector dimension: empty, not an error.
     {
         bool threw = false;

+ 1 - 0
tests/load_test/test_server_info.cpp

@@ -44,6 +44,7 @@ static const std::vector<const char*> kAllCaps = {
     Cap::kExportCollection, Cap::kWriteSizeGuard, Cap::kFilteredSimilarity, Cap::kServerInfo,
     Cap::kClientVersionHeader, Cap::kCollectionSchema, Cap::kEncryptionAtRest,
     Cap::kTypedRangeFilters, Cap::kDocumentExpiresAt, Cap::kRe2RegexFilters,
+    Cap::kServedFromMemory,
 };
 
 // Ordinary calls a client of any version makes; they must work across versions.

+ 6 - 2
tests/load_test/test_snapshot_keeps_evicted.sh

@@ -85,8 +85,12 @@ stop
 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'"
+# v2.21.3 - the snapshot brings all 300 vectors back (counted, 4 MB), and the
+# release sweep, which runs before the first memory line, moves them to LMDB.
+ck "boot 2: every vector came back and was released to LMDB (300)" \
+   "grep -q 'Released 300 vector(s) (4 MB) from memory' '$DIR/server2.log'"
+ck "boot 2: the memory line shows them in LMDB only" \
+   "grep 'Memory check' '$DIR/server2.log' | head -1 | grep -q 'of which vectors 0 MB (300 more in LMDB only)'"
 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'"

+ 166 - 0
tests/test_dual_write_mirror.cpp

@@ -17,6 +17,7 @@
 #include <stdexcept>
 #include <map>
 #include <set>
+#include <cmath>
 #include <string>
 #include <unistd.h>
 
@@ -932,6 +933,170 @@ void test_eviction_releases_vectors() {
     fs::remove_all(snapDir);
 }
 
+// v2.21.3 - a vector LMDB holds byte-identically is dropped from memory; every
+// read path gets it from LMDB and every write reads it back first.
+void test_mirrored_vectors_released() {
+    TmpEnv tmp("vec-release");
+    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 = 96 * 1024;
+    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 = 64;
+    const uint64_t kVecBytes = kDim * sizeof(float) + 32;   // estimateVectorSize
+    smartbotic::database::CollectionOptions opts;
+    opts.vectorDimension = kDim;
+    mem.createCollection("rel", opts);
+    auto vectorFor = [](int i) {
+        std::vector<float> v(kDim);
+        for (uint32_t k = 0; k < kDim; ++k) v[k] = static_cast<float>(std::sin((i + 1) * (k + 1) * 0.7));
+        return v;
+    };
+    auto put = [&](const std::string& id, std::optional<std::vector<float>> vec) {
+        Document d;
+        d.id = id;
+        d.collection = "rel";
+        nlohmann::json body = {{"id", id}};
+        if (vec) body["_vector"] = *vec;
+        d.set_data(body);
+        return d;
+    };
+    constexpr int kRows = 20;
+    for (int i = 0; i < kRows; ++i) mem.insert("rel", put("r" + std::to_string(i), vectorFor(i)));
+    mem.loadVector("rel", "orphan", vectorFor(99));   // in memory, NOT in LMDB
+
+    check(mem.releaseMirroredVectors() == kRows, "release: every mirrored vector released");
+    check(mem.releasedVectorCount() == kRows, "release: counted as in LMDB only");
+    check(mem.getStats().vectorMemoryBytes == kVecBytes,
+          "release: the vector share fell to the one vector LMDB lacks");
+    check(mem.residentVector("rel", "orphan").has_value() &&
+              mem.releaseMirroredVectors() == 0,
+          "release: a vector LMDB lacks stays in memory, and is not retried");
+
+    bool exact = true;
+    for (int i = 0; i < kRows; ++i) {
+        auto v = mem.residentVector("rel", "r" + std::to_string(i));
+        exact &= v && *v == vectorFor(i) && mem.hasVector("rel", "r" + std::to_string(i));
+    }
+    check(exact, "release: residentVector/hasVector answer for released vectors, exact");
+    const auto ids = mem.getVectorIds("rel");
+    const auto vecs = mem.copyVectors("rel", ids, 0, ids.size());
+    exact = ids.size() == kRows + 1;
+    for (size_t j = 0; exact && j < ids.size(); ++j) {
+        const int i = ids[j] == "orphan" ? 99 : std::stoi(ids[j].substr(1));
+        exact = vecs[j] && *vecs[j] == vectorFor(i);
+    }
+    check(exact, "release: the snapshot view lists and copies every vector, exact");
+
+    // A patch without _vector reads the vector back and keeps it.
+    check(mem.patchDocument("rel", "r0", {{"p", 1}}) > 0, "release: patch a released row");
+    auto v0 = doc_store.get_vector("rel", "r0");
+    check(v0 && *v0 == vectorFor(0) && mem.getStats().vectorMemoryBytes == 2 * kVecBytes,
+          "release: the patch kept the vector, back in memory and unchanged on disk");
+    check(mem.releaseMirroredVectors() == 1, "release: released again by the next sweep");
+
+    // An update with a new vector replaces it; one without removes it.
+    mem.update("rel", "r1", put("r1", vectorFor(501)));
+    auto v1 = mem.residentVector("rel", "r1");
+    auto d1 = doc_store.get_vector("rel", "r1");
+    check(v1 && *v1 == vectorFor(501) && d1 && *d1 == vectorFor(501),
+          "release: an update replaces a released vector, memory and disk");
+    mem.update("rel", "r2", put("r2", std::nullopt));
+    check(!mem.hasVector("rel", "r2") && !doc_store.get_vector("rel", "r2"),
+          "release: an update without _vector removes a released vector everywhere");
+    check(mem.remove("rel", "r3") && !mem.hasVector("rel", "r3") &&
+              !doc_store.get_vector("rel", "r3"),
+          "release: a delete removes a released vector everywhere");
+    const auto after = mem.getVectorIds("rel");
+    check(std::find(after.begin(), after.end(), "r2") == after.end() &&
+              std::find(after.begin(), after.end(), "r3") == after.end(),
+          "release: removed vectors are not listed for the snapshot");
+
+    // LMDB disagreeing with memory: kept resident (releasing would lose it).
+    mem.insert("rel", put("mismatch", vectorFor(7)));
+    doc_store.put_vector("rel", "mismatch", vectorFor(8));
+    mem.releaseMirroredVectors();
+    auto vm = mem.residentVector("rel", "mismatch");
+    check(vm && *vm == vectorFor(7) && mem.getStats().vectorMemoryBytes >= kVecBytes * 2,
+          "release: a vector LMDB disagrees with stays in memory");
+
+    // The degraded search scores released vectors from LMDB.
+    mem.releaseMirroredVectors();
+    healthy = false;
+    auto top = mem.similaritySearch("rel", vectorFor(5), 1, -1.0f);
+    check(top.size() == 1 && top[0].id == "r5" && top[0].score > 0.9999f,
+          "release: degraded search finds a released vector");
+    auto all = mem.similaritySearch("rel", vectorFor(5), 1000, -1.0f);
+    // r0..r19 minus r2 (no vector) and r3 (deleted), plus mismatch; orphan has no document.
+    check(all.size() == kRows - 2 + 1, "release: degraded search ranks every vector");
+    mem.insert("rel", put("while-unhealthy", vectorFor(11)));
+    check(mem.releaseMirroredVectors() == 0 &&
+              mem.residentVector("rel", "while-unhealthy").has_value(),
+          "release: nothing is released while the mirror is unhealthy");
+    healthy = true;
+    drift = 1;
+    check(mem.releaseMirroredVectors() == 0, "release: nothing is released with drift");
+    drift = 0;
+
+    // Eviction of a row whose vector is already released marks the stub.
+    mem.releaseMirroredVectors();
+    for (int i = 0; i < 40; ++i) {   // bodies large enough to put the store over budget
+        Document big = put("pad" + std::to_string(i), std::nullopt);
+        big.set_data({{"pad", std::string(4096, 'x')}});
+        mem.insert("rel", big);
+    }
+    std::string ev;
+    for (int round = 0; round < 50 && ev.empty(); ++round) {
+        mem.evictDocuments();
+        for (int i = 4; i < kRows && ev.empty(); ++i) {
+            if (mem.isDocumentEvicted("rel", "r" + std::to_string(i))) ev = "r" + std::to_string(i);
+        }
+    }
+    check(!ev.empty() && mem.hasVector("rel", ev),
+          "release: an evicted row with a released vector still has one");
+    if (!ev.empty()) {
+        mem.ensureResident("rel", ev);
+        auto vev = mem.residentVector("rel", ev);
+        check(vev && *vev == vectorFor(std::stoi(ev.substr(1))),
+              "release: reload brings the vector back, exact");
+    }
+
+    // A snapshot carries released vectors; the loaded store holds them all.
+    mem.releaseMirroredVectors();
+    const auto snapDir = make_tmpdir("vec-release-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("rel");
+    bool allBack = expectIds.size() > 10;
+    for (const auto& id : expectIds) {
+        auto want = mem.copyVectors("rel", {id}, 0, 1).front();
+        auto got = loaded.residentVector("rel", id);
+        if (!(want && got && *want == *got)) {
+            std::cerr << "snapshot mismatch " << id << " want=" << want.has_value()
+                      << " got=" << got.has_value() << "\n";
+            allBack = false;
+        }
+    }
+    check(allBack, "release: every released vector survives a snapshot, exact");
+    auto vmis = loaded.residentVector("rel", "mismatch");
+    check(vmis && *vmis == vectorFor(7),
+          "release: the snapshot keeps memory's copy of the vector LMDB disagreed with");
+    fs::remove_all(snapDir);
+}
+
 int main() {
     test_unit_null_store_is_noop();
     test_unit_system_collection_skipped();
@@ -953,6 +1118,7 @@ int main() {
     test_backfill_iteration_pattern();
     test_scan_vectors_round_trip();
     test_eviction_releases_vectors();
+    test_mirrored_vectors_released();
 
     std::cout << "dual_write_mirror: " << g_pass << " passed, " << g_fail << " failed\n";
     return g_fail == 0 ? 0 : 1;

Einige Dateien werden nicht angezeigt, da zu viele Dateien in diesem Diff geändert wurden.