Эх сурвалжийг харах

fix: 2.13.0 - a write that keeps the vector stamps an unmarked row

Found by smartbotic-vectorapi's pre-release run at scale: update and upsert
stamped the has-vector marker on a pre-2.13.0 row, patch did not. A legacy
row only ever patched stayed Unknown forever and could never report Missing
if its vector were later lost, and the documented remedy (any write stamps
it) was false for the most common write.

Patch without _vector, and an in-place restore, now stamp an unmarked row in
a vector collection with what is stored, read from the LMDB vector sub-db
(storedVectorExists). Not from coll.vectors: eviction drops a vector from
memory and a reload does not restore it, so the memory map would stamp
false on a row that has one, turning a later loss into a confident None. The
stamp is set on the in-memory document so it travels through WAL and
snapshot; a disk-only stamp would be erased by the boot-time re-mirror.

test_dual_write_mirror plants unmarked rows directly (the vector deliberately
not in memory), patches them, checks true/false in memory and on disk, then
deletes the stamped row's vector and expects Missing. Reverting the stamp
fails 6.
fszontagh 1 сар өмнө
parent
commit
e5bc5676c8

Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 0 - 0
CLAUDE.md


+ 1 - 1
docs/integration-guide.md

@@ -602,7 +602,7 @@ if (!sum.complete) { /* resume: exportCollection(..., sum.lastId, ...) */ }
 | `Present` | the vector is stored; `row.vector` holds it |
 | `None` | the row was written without a vector (or an `update()` without `_vector` removed it) |
 | `Missing` | the row was written WITH a vector and its entry is gone - real data loss; never write it back as a plain document |
-| `Unknown` | no entry, and the row was written before 2.13.0, which recorded no marker |
+| `Unknown` | no entry, and the row was written before 2.13.0, which recorded no marker. Any 2.13.0 write to the row (insert, update, upsert, patch, restore) records one, so touching a legacy collection once makes every row definite |
 | `Unspecified` | vectors were not requested |
 
 Since 2.13.0 a document and its vector are written in ONE transaction, so no

+ 19 - 1
service/src/memory_store.cpp

@@ -1549,7 +1549,10 @@ uint64_t MemoryStore::patchDocument(const std::string& collection, const std::st
     auto vec = extractVector(*coll, it->second);
     if (!vec.empty()) {
         storeVector(*coll, id, vec);
-        it->second.hasVector = true;   // v2.13.0 - only a supplied vector changes it
+        it->second.hasVector = true;   // v2.13.0 - a supplied vector
+    } else if (coll->options.vectorDimension > 0 && !it->second.hasVector) {
+        // v2.13.0 - an unmarked (pre-2.13.0) row: record what is stored now.
+        it->second.hasVector = storedVectorExists(collection, id, *coll);
     }
     // v2.13.0 - a patch without `_vector` keeps both the vector and its marker.
     const auto vc = vec.empty() ? smartbotic::db::storage::VectorChange::keep()
@@ -2980,6 +2983,10 @@ uint64_t MemoryStore::restoreToVersion(const std::string& collection, const std:
         docIt->second.encrypted = targetVer.encrypted;
         docIt->second.encryptedFields = targetVer.encryptedFields;
         docIt->second.nodeId = config_.nodeId;
+        // v2.13.0 - stamp an unmarked row, as patch does (the vector is kept).
+        if (coll->options.vectorDimension > 0 && !docIt->second.hasVector) {
+            docIt->second.hasVector = storedVectorExists(collection, id, *coll);
+        }
 
         restoredDoc = docIt->second;
     } else {
@@ -3484,6 +3491,17 @@ MemoryStore::replaceVectorChange(const CollectionData& coll, const std::vector<f
     return vec.empty() ? VectorChange::remove() : VectorChange::put(vec);
 }
 
+bool MemoryStore::storedVectorExists(const std::string& collection, const std::string& id,
+                                     const CollectionData& coll) const {
+    if (docStoreResolver_) {
+        auto pc = smartbotic::database::parseProjectCollection(collection);
+        if (auto* ds = docStoreResolver_(pc.project)) {
+            return ds->get_vector(pc.collection, id).has_value();
+        }
+    }
+    return coll.vectors.find(id) != coll.vectors.end();   // no durable store (unit tests)
+}
+
 bool MemoryStore::needsUndoSnapshot(const std::string& collection) const {
     // No mirror => no rejection is possible, but also no cost worth reasoning
     // about; report true so the ONE rule callers follow ("snapshot iff this

+ 11 - 0
service/src/memory_store.hpp

@@ -1281,6 +1281,17 @@ private:
     replaceVectorChange(const CollectionData& coll, const std::vector<float>& vec,
                         Document& doc);
 
+    // v2.13.0 - is a vector stored for this document right now? Asked by the
+    // writes that keep the vector (patch without `_vector`, in-place restore)
+    // 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,
+    // 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;
+
     // v2.0 Stage 5 — mirror a vector write/delete into the LMDB sub-db
     // `_vectors_<collection>`. Called from within the per-collection
     // write lock, after the doc mirror. For INSERT/UPDATE: pass the

+ 65 - 0
tests/test_dual_write_mirror.cpp

@@ -15,6 +15,7 @@
 #include <memory>
 #include <optional>
 #include <stdexcept>
+#include <map>
 #include <string>
 #include <unistd.h>
 
@@ -434,6 +435,69 @@ void test_vector_mirror_via_memory_store() {
     check(healthy.load() && drift.load() == 0, "vector via memstore: clean");
 }
 
+// v2.13.0 - every kind of write leaves a definite has-vector marker. Found by
+// smartbotic-vectorapi's pre-release run: patch did not stamp an unmarked
+// (pre-2.13.0) row, so a legacy row only ever patched stayed Unknown forever -
+// and could never report Missing if its vector were later lost. The legacy
+// rows are planted directly (no marker in LMDB or in memory), and the vector
+// is deliberately NOT loaded into memory, as for a row evicted and reloaded:
+// the stamp must come from the LMDB vector sub-db, the durable copy.
+void test_patch_stamps_unmarked_rows() {
+    TmpEnv tmp("patch-stamp");
+    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 = 64ULL * 1024 * 1024;
+    MemoryStore mem(cfg);
+    mem.setDocumentStoreMirror([&doc_store](std::string_view) { return &doc_store; },
+                               &healthy, &drift);
+    smartbotic::database::CollectionOptions opts;
+    opts.vectorDimension = 4;
+    mem.createCollection("emb", opts);
+
+    auto legacy = [&](const std::string& id, bool withVector) {
+        Document d;
+        d.id = id;
+        d.collection = "emb";
+        d.set_data({{"label", id}});
+        doc_store.put("emb", id, d);   // no marker on disk
+        if (withVector) doc_store.put_vector("emb", id, {1.f, 2.f, 3.f, 4.f});
+        mem.loadDocument("emb", d);    // no marker, no vector in memory
+    };
+    legacy("L1", true);
+    legacy("L0", false);
+    check(!doc_store.get("emb", "L1")->hasVector && !doc_store.get("emb", "L0")->hasVector,
+          "patch stamp: the planted rows really are unmarked");
+
+    check(mem.patchDocument("emb", "L1", {{"p", 1}}) > 0, "patch stamp: patch L1");
+    check(mem.patchDocument("emb", "L0", {{"p", 1}}) > 0, "patch stamp: patch L0");
+
+    auto m1 = mem.get("emb", "L1");
+    auto m0 = mem.get("emb", "L0");
+    check(m1 && m1->hasVector == true, "patch stamp: in memory, the row with a stored vector -> true");
+    check(m0 && m0->hasVector == false, "patch stamp: in memory, the row without one -> false");
+    check(doc_store.get("emb", "L1")->hasVector == true, "patch stamp: on disk, L1 -> true");
+    check(doc_store.get("emb", "L0")->hasVector == false, "patch stamp: on disk, L0 -> false");
+    check(doc_store.get_vector("emb", "L1").has_value(), "patch stamp: the vector itself is untouched");
+
+    // The point of the marker: a vector lost AFTER the stamp is reported as
+    // lost, not as "unknown".
+    doc_store.del_vector("emb", "L1");
+    std::map<std::string, DocumentStore::ExportVectorState> states;
+    doc_store.export_scan("emb", "", true, {}, [](uint64_t) {},
+                          [&](Document&& d, DocumentStore::ExportVectorState st, const float*, size_t) {
+                              states[d.id] = st;
+                              return true;
+                          });
+    check(states["L1"] == DocumentStore::ExportVectorState::Missing,
+          "patch stamp: a stamped row whose vector is then lost reports MISSING");
+    check(states["L0"] == DocumentStore::ExportVectorState::None,
+          "patch stamp: a stamped row that never had one reports NONE");
+    check(healthy.load() && drift.load() == 0, "patch stamp: clean");
+}
+
 // Simulates DatabaseService::backfillIntoDocStore — populate MemoryStore
 // without a persist callback (no live mirror), then walk listCollections +
 // getAllDocuments and feed each doc into applyDualWriteMirror with
@@ -548,6 +612,7 @@ int main() {
     test_vector_mirror_empty_is_noop_on_insert();
     test_vector_mirror_system_collection_skipped();
     test_vector_mirror_via_memory_store();
+    test_patch_stamps_unmarked_rows();
     test_backfill_iteration_pattern();
     test_scan_vectors_round_trip();
 

Энэ ялгаанд хэт олон файл өөрчлөгдсөн тул зарим файлыг харуулаагүй болно