浏览代码

fix: a row on disk but not in memory is writable; boot audit of the two key sets

Reads are served from LMDB, writes look only in MemoryStore, and since
2.12.1 only reload an evicted document. A row in LMDB with no resident copy
and no eviction stub was readable while patch/update/delete said not-found
and an insert or upsert of its id overwrote it at version 1. Found on a
production instance; no restart repairs it, since MemoryStore is rebuilt
from snapshot + WAL.

A write that misses memory now checks LMDB and loads the row (only while
the mirror is healthy with no drift). The Upsert handler makes the row
resident before deciding inserted. A read-only boot step lists the ids
each store holds that the other does not.
fszontagh 1 月之前
父节点
当前提交
8e522efe8a

+ 31 - 0
CHANGELOG.md

@@ -12,6 +12,37 @@ consumer-facing usage is in `docs/integration-guide.md`.
 
 ## Unreleased
 
+## 2.20.2 - 2026-10-22 (bug fix, server only)
+### Fixed
+- **[server]** ⚠ A row that LMDB held and MemoryStore did not could be read
+  and never written: patch, update and delete answered not-found, and an
+  insert or upsert of its id was ACCEPTED and overwrote it at version 1. Found
+  on a production instance. MemoryStore is rebuilt from snapshot + WAL, never
+  from LMDB, so no restart repaired it. A write that misses memory now checks
+  LMDB and, if the row is there, loads it and applies the write to it (WARN
+  per row). An insert of its id is `AlreadyExists`. Only while LMDB is what
+  reads are served from (mirror healthy, no drift).
+- **[server]** `upsert` reported `inserted=true` for a row that existed but
+  was not in memory (evicted since 2.12.1, or the case above), and skipped
+  keeping the stored ciphertext of unchanged sensitive fields (a spurious
+  history diff). An evicted row's `_created_by` was NOT affected (the store
+  keeps the original); a disk-only row's was, because the upsert re-created it.
+  `_created_by` keeps its meaning (the creator) on every version; 2.20.2 removes
+  an exception, it does not redefine the field. The exception belongs to a ROW,
+  not a date: a disk-only row that an insert or upsert re-created before
+  2.20.2 names that writer, and still will after the upgrade (nothing repairs
+  it retroactively), so an audit across the upgrade compares like with like
+  everywhere else.
+### Added
+- **[server]** Boot step "memory/disk key audit": per collection, the ids LMDB
+  holds that MemoryStore does not and the reverse, logged as ERROR with counts
+  and up to 10 ids each; read-only, changes nothing. Walks keys, never values.
+### Observable
+- **[server]** An insert of an id that is on disk but was not in memory now
+  fails `AlreadyExists` instead of silently overwriting. Each insert of a new
+  id costs one LMDB existence check (microseconds). No format, marker or
+  migration change: 2.20.1 runs on a data directory 2.20.2 has used.
+
 ## 2.20.1 - 2026-10-19 (bug fix, server only)
 ### Fixed
 - **[server]** ⚠ A snapshot held the whole store in memory twice more: the

文件差异内容过多而无法显示
+ 0 - 0
CLAUDE.md


+ 18 - 0
docs/ROADMAP.md

@@ -132,6 +132,9 @@ detail and the failure modes.
   invalid pattern refused with `invalid_pattern` (2.20.0)
 - Snapshots stream to disk: the writer's memory peak is a chunk, not the
   store; a snapshot killed mid-write is reported at the next boot (2.20.1)
+- A row on disk but not in memory is writable (it was readable and every write
+  missed it, or an insert overwrote it); a boot audit lists every row the two
+  stores disagree on (2.20.2)
 
 ---
 
@@ -376,6 +379,21 @@ streams the write (it still holds the decompressed body during
 deserialization); then measure what the WAL replay retains. The real fix is
 item 4 (MemoryStore stops being a full copy of LMDB).
 
+### 5f. How MemoryStore and LMDB came to disagree is not known (found 2026-10-19)
+
+2.20.2 makes a disk-only row writable and the boot audit reports every
+disagreement, but the cause of the production row is not established.
+Candidates, none proven: (1) the pre-2.20.1 snapshot writer listed resident
+documents and evicted ids in two separate steps, so a document evicted between
+them was in neither and dropped from the snapshot, then the WAL holding it was
+truncated (closed by 2.20.1's `copyDocuments`); (2) the old writer skipped an
+evicted document it "could not load"; (3) a delete that reached MemoryStore
+and the WAL but not LMDB (then the row is a resurrected delete, and the first
+write to it keeps it). The audit's output on an affected instance, read
+against its snapshot times, is what can separate them. The reverse
+("in memory only") is reported by the same audit and has no fix yet: those
+rows are writable but invisible to LMDB-served reads.
+
 ### 6. Smaller known gaps
 
 - Policy management has no dedicated RPCs; `_policies` is edited through the

+ 1 - 0
service/src/database_grpc_impl.cpp

@@ -998,6 +998,7 @@ grpc::Status DatabaseGrpcImpl::Upsert(
             }
         }
 
+        store_.ensureResident(request->collection(), request->id());   // v2.20.2
         bool existed = store_.exists(request->collection(), request->id());
 
         Document doc;

+ 107 - 1
service/src/database_service.cpp

@@ -15,6 +15,9 @@
 #include <sstream>
 #include <map>
 #include <set>
+#include <algorithm>
+#include <chrono>
+#include <iterator>
 #include "storage/lmdb_env.hpp"
 #include "storage/migrate_v1_to_v2.hpp"
 #include "storage/project_store.hpp"
@@ -271,12 +274,17 @@ bool DatabaseService::initialize() {
         // data-location problem an operator repairs offline with
         // `smartbotic-db-cli reconcile-subdbs`, not a reason to refuse
         // service on the other 99% of the dataset.
-        // 2.21.0 - each remaining boot step logs its start, so a boot that
+        // 2.20.1 - each remaining boot step logs its start, so a boot that
         // dies here (a production crash loop on 2026-10-19 died about 3 s
         // after the backfill line, with nothing logged) shows which step.
         spdlog::info("Boot: sub-db placement audit");
         auditSubdbPlacement();
 
+        // v2.20.2 - rows LMDB holds that MemoryStore does not (readable, and
+        // before 2.20.2 not writable), and the reverse. Read-only, advisory.
+        spdlog::info("Boot: memory/disk key audit");
+        auditMemoryDiskKeys();
+
         // v2.6.0 — stamp `project: "default"` onto file records written before
         // files were namespaced. Idempotent, and advisory: a file-metadata
         // stamp is not a reason to refuse service, so failures warn only.
@@ -1048,6 +1056,104 @@ void DatabaseService::auditSubdbPlacement() {
     }
 }
 
+void DatabaseService::auditMemoryDiskKeys() {
+    if (!projects_ || !store_) return;
+    namespace sd = smartbotic::database;
+    const auto started = std::chrono::steady_clock::now();
+
+    // LMDB sub-db ("project:collection") -> the MemoryStore names that feed
+    // it. A default-project collection may also live under its bare legacy
+    // name; both resolve to one sub-db, so both count as "in memory".
+    std::map<std::string, std::vector<std::string>> memNames;
+    for (const auto& name : store_->listCollections()) {
+        try {
+            auto rc = sd::resolveCollection(name);
+            if (rc.collection.empty() || rc.collection.front() == '_') continue;
+            memNames[rc.qualified].push_back(name);
+        } catch (const std::exception&) {
+            continue;   // a malformed legacy key; the backfill already reported it
+        }
+    }
+
+    const auto samples = [](const std::vector<std::string>& ids) {
+        std::string out;
+        for (size_t i = 0; i < ids.size() && i < 10; ++i) {
+            if (i) out += ", ";
+            out += ids[i];
+        }
+        if (ids.size() > 10) out += ", ...";
+        return out;
+    };
+
+    uint64_t diskOnlyTotal = 0, memOnlyTotal = 0, compared = 0;
+    for (const auto& project : projects_->listOpen()) {
+        auto* ds = docStore(project);
+        if (!ds) continue;
+        std::set<std::string> collections;
+        try {
+            for (auto& c : ds->list_collections()) collections.insert(std::move(c));
+        } catch (const std::exception& e) {
+            spdlog::warn("key audit: project '{}' could not be listed: {}", project, e.what());
+            continue;
+        }
+        const std::string prefix = project + sd::kProjectSeparator;
+        for (const auto& [qualified, names] : memNames) {
+            if (qualified.rfind(prefix, 0) == 0) collections.insert(qualified.substr(prefix.size()));
+        }
+
+        for (const auto& coll : collections) {
+            if (coll.empty() || coll.front() == '_') continue;
+            const std::string qualified = prefix + coll;
+            try {
+                auto disk = ds->list_ids(coll);
+                if (!disk) continue;   // backend cannot list
+                std::vector<std::string> mem;
+                if (auto it = memNames.find(qualified); it != memNames.end()) {
+                    for (const auto& n : it->second) {
+                        for (auto& id : store_->getDocumentIds(n)) mem.push_back(std::move(id));
+                        for (auto& id : store_->getEvictedDocumentIds(n)) mem.push_back(std::move(id));
+                    }
+                }
+                std::sort(mem.begin(), mem.end());
+                mem.erase(std::unique(mem.begin(), mem.end()), mem.end());
+                std::sort(disk->begin(), disk->end());   // already key order; cheap insurance
+
+                std::vector<std::string> diskOnly, memOnly;
+                std::set_difference(disk->begin(), disk->end(), mem.begin(), mem.end(),
+                                    std::back_inserter(diskOnly));
+                std::set_difference(mem.begin(), mem.end(), disk->begin(), disk->end(),
+                                    std::back_inserter(memOnly));
+                ++compared;
+                if (!diskOnly.empty()) {
+                    diskOnlyTotal += diskOnly.size();
+                    spdlog::error("key audit: {}: {} row(s) on disk but not in memory - reads "
+                                  "find them; before 2.20.2 every write said not-found and an "
+                                  "insert of the id overwrote them; a write now loads them. "
+                                  "ids: {}", qualified, diskOnly.size(), samples(diskOnly));
+                }
+                if (!memOnly.empty()) {
+                    memOnlyTotal += memOnly.size();
+                    spdlog::error("key audit: {}: {} row(s) in memory but not on disk - writes "
+                                  "find them, reads served from disk do not. ids: {}",
+                                  qualified, memOnly.size(), samples(memOnly));
+                }
+            } catch (const std::exception& e) {
+                spdlog::warn("key audit: {} could not be audited: {}", qualified, e.what());
+            }
+        }
+    }
+
+    const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
+        std::chrono::steady_clock::now() - started).count();
+    if (diskOnlyTotal == 0 && memOnlyTotal == 0) {
+        spdlog::info("key audit: {} collection(s) consistent ({} ms)", compared, ms);
+    } else {
+        spdlog::error("key audit: {} collection(s) compared, {} row(s) on disk only, {} in "
+                      "memory only ({} ms). Changes nothing; see the lines above.",
+                      compared, diskOnlyTotal, memOnlyTotal, ms);
+    }
+}
+
 bool DatabaseService::backfillIntoDocStore() {
     if (!projects_) {
         // Registry open failed earlier; nothing to back-fill into.

+ 3 - 0
service/src/database_service.hpp

@@ -369,6 +369,9 @@ private:
     // `collection` disagrees with the sub-db they occupy. Logs ERROR per
     // affected project and leaves a summary; never fails startup.
     void auditSubdbPlacement();
+    // v2.20.2 - read-only: compares each collection's LMDB ids with
+    // MemoryStore's (resident + evicted) and logs both differences.
+    void auditMemoryDiskKeys();
 
     // v2.9.0 — arm the write path and query planner with the index declarations
     // persisted in _collection_meta. Must run at boot, after config load.

+ 89 - 1
service/src/memory_store.cpp

@@ -3623,7 +3623,11 @@ void MemoryStore::emitEvictionBurst(uint64_t docs, uint64_t bytesFreed) {
 }
 
 void MemoryStore::reloadIfEvicted(const std::string& collection, const std::string& id) {
-    if (id.empty() || !getEvictedStub(collection, id)) return;   // the common case: resident
+    if (id.empty()) return;
+    if (!getEvictedStub(collection, id)) {
+        adoptFromDocStore(collection, id);   // v2.20.2
+        return;
+    }
     if (loadEvictedDocument(collection, id)) return;
     // The load failed. If the stub is gone, someone else reloaded (or deleted)
     // it meanwhile and the write may proceed against the real state. If the
@@ -3636,6 +3640,90 @@ void MemoryStore::reloadIfEvicted(const std::string& collection, const std::stri
     }
 }
 
+namespace {
+// The MemoryStore names that share one LMDB sub-db: a default-project
+// collection may also exist under its bare legacy name (pre-2.3 data, and the
+// pre-2.4.5 client bug), and both resolve to the same `default` sub-db.
+std::vector<std::string> memoryAliasesOf(const smartbotic::database::ProjectCollection& pc) {
+    std::vector<std::string> out{pc.project + smartbotic::database::kProjectSeparator + pc.collection};
+    if (pc.project == smartbotic::database::kDefaultProject) out.push_back(pc.collection);
+    return out;
+}
+}  // namespace
+
+bool MemoryStore::adoptFromDocStore(const std::string& collection, const std::string& id) {
+    // Only while LMDB is what reads are served from: with the mirror unhealthy
+    // or drifted, MemoryStore may be AHEAD of LMDB (a row deleted here whose
+    // delete never reached LMDB), and adopting would resurrect it.
+    if (!docStoreResolver_ || !mirrorHealthy_ || !mirrorDriftCount_) return false;
+    if (!mirrorHealthy() || mirrorDriftCount() != 0) return false;
+
+    smartbotic::database::ProjectCollection pc;
+    try {
+        pc = smartbotic::database::parseProjectCollection(collection);
+    } catch (const std::exception&) {
+        return false;
+    }
+    if (pc.collection.front() == '_') return false;   // system collections are never mirrored
+
+    CollectionData* coll = const_cast<CollectionData*>(getCollection(collection));
+    if (coll == nullptr) return false;
+    {
+        std::shared_lock<std::shared_mutex> lock(coll->mutex);
+        if (coll->documents.count(id) != 0) return false;   // resident: the common case
+    }
+
+    auto* ds = docStoreResolver_(pc.project);
+    if (ds == nullptr) return false;
+    try {
+        // Cheap, and a miss is every insert of a new id.
+        if (!ds->exists(pc.collection, id)) return false;
+    } catch (const std::exception& e) {
+        spdlog::warn("write to {}/{}: could not check the on-disk store for a row missing "
+                     "from memory ({}); proceeding as before 2.20.2", collection, id, e.what());
+        return false;
+    }
+
+    // A legacy alias of this collection holding the id is the alias problem,
+    // not this one; leave it as it was rather than make a second copy.
+    for (const auto& alias : memoryAliasesOf(pc)) {
+        if (alias == collection) continue;
+        if (getEvictedStub(alias, id)) return false;
+        if (const auto* other = getCollection(alias)) {
+            std::shared_lock<std::shared_mutex> lock(other->mutex);
+            if (other->documents.count(id) != 0) return false;
+        }
+    }
+
+    std::unique_lock<std::shared_mutex> lock(coll->mutex);
+    if (coll->documents.count(id) != 0) return false;   // a concurrent write got here first
+    if (getEvictedStub(collection, id)) return false;     // evicted meanwhile; reloadIfEvicted's job
+    // Read under the collection lock: every write mirrors to LMDB under this
+    // same lock, so the body read here is the current one.
+    std::optional<Document> doc = ds->get(pc.collection, id);
+    if (!doc) return false;   // deleted between the two reads
+
+    doc->collection = collection;
+    doc->lastAccessedAt = currentTimeMs();
+    if (doc->expiresAt > 0) addToExpirationIndex(*coll, id, doc->expiresAt);
+    if (coll->options.vectorDimension > 0) {
+        if (auto vec = ds->get_vector(pc.collection, id)) storeVector(*coll, id, *vec);
+    }
+    const uint64_t size = estimateDocumentSize(*doc);
+    coll->documents.emplace(id, std::move(*doc));
+    lock.unlock();
+
+    {
+        std::lock_guard<std::mutex> statsLock(statsMutex_);
+        stats_.totalDocuments++;
+    }
+    estimatedMemoryBytes_.fetch_add(size, std::memory_order_relaxed);
+    spdlog::warn("write to {}/{}: the row was on disk but not in memory (readable, not "
+                 "writable before 2.20.2); loaded it so the write applies to it. The boot "
+                 "audit lists every such row.", collection, id);
+    return true;
+}
+
 void MemoryStore::emitPersist(const std::string& collection, const std::string& id,
                               const std::optional<Document>& doc, EventType eventType,
                               const std::optional<std::string>& actor) {

+ 22 - 0
service/src/memory_store.hpp

@@ -671,6 +671,16 @@ public:
      */
     [[nodiscard]] bool exists(const std::string& collection, const std::string& id) const;
 
+    // v2.20.2 - bring an evicted or on-disk-only document into memory before
+    // a handler asks exists()/get() about it, under the write paths' rules
+    // (reloadIfEvicted). Upsert decides `inserted` that way: without this a
+    // disk-only row (and, since 2.12.1, an evicted one) was reported as newly
+    // inserted, its createdBy was overwritten and its unchanged encrypted
+    // fields re-encrypted.
+    void ensureResident(const std::string& collection, const std::string& id) {
+        reloadIfEvicted(collection, id);
+    }
+
     /**
      * Update with optimistic locking.
      * @param expectedVersion Expected version of the document
@@ -1323,8 +1333,20 @@ private:
     // and OVERWROTE it, upsert re-created it at version 1. Throws (fails
     // closed) when a stub exists but the document cannot be reloaded - writing
     // as if it did not exist is exactly the bug.
+    // v2.20.2 - and a document that is in LMDB but in NEITHER map (not
+    // resident, no eviction stub) is loaded from LMDB too: reads are served
+    // from LMDB, so it was readable, while every write said "not found" and an
+    // insert or upsert of its id OVERWROTE it at version 1. Found on a
+    // 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.20.2 - see reloadIfEvicted. Only while the mirror is healthy with no
+    // drift (otherwise MemoryStore may be ahead of LMDB, and adopting would
+    // resurrect a row deleted here). Skips system collections and an id held
+    // under a legacy bare/qualified alias of the collection. Logs WARN.
+    bool adoptFromDocStore(const std::string& collection, const std::string& id);
+
     // v2.0 Stage 4 — mirror a write into the LMDB DocumentStore. Called
     // from within the per-collection write lock, BEFORE lock release, so
     // any subsequent LMDB read by any thread observes the same state as

+ 7 - 0
service/src/storage/document_store.hpp

@@ -103,6 +103,13 @@ public:
     virtual ScanResult scan(std::string_view collection,
                             const smartbotic::database::Query& query) = 0;
 
+    // v2.20.2 - every document id in a collection, in key order, without
+    // reading a value. nullopt = this backend cannot list (the boot key-set
+    // audit then skips it).
+    virtual std::optional<std::vector<std::string>> list_ids(std::string_view /*collection*/) {
+        return std::nullopt;
+    }
+
     // List user-visible collection names (sub-dbs that don't start with `_`).
     // Sorted alphabetically. Empty if no collections exist yet.
     virtual std::vector<std::string> list_collections() = 0;

+ 21 - 0
service/src/storage/document_store_lmdb.cpp

@@ -1313,6 +1313,27 @@ LmdbDocumentStore::lookupIndexRangeTxn(ReadTxn& rtxn,
     return ids;
 }
 
+std::optional<std::vector<std::string>>
+LmdbDocumentStore::list_ids(std::string_view collection) {
+    std::vector<std::string> ids;
+    ReadTxn rtxn(env_);
+    auto dbi_opt = try_open_for_read(rtxn, collection);
+    if (!dbi_opt) return ids;
+    MDB_cursor* cur = nullptr;
+    mdb_check(mdb_cursor_open(rtxn.raw(), *dbi_opt, &cur), "cursor_open (list_ids)");
+    struct G { MDB_cursor* c; ~G() { if (c) mdb_cursor_close(c); } } g{cur};
+    MDB_val k{0, nullptr};
+    MDB_val v{0, nullptr};
+    // The value is only a pointer into the map; it is never touched, so a
+    // large row's overflow pages are not read.
+    int rc = mdb_cursor_get(cur, &k, &v, MDB_FIRST);
+    while (rc == MDB_SUCCESS) {
+        if (!is_identity_key(to_sv(k))) ids.emplace_back(to_sv(k));
+        rc = mdb_cursor_get(cur, &k, &v, MDB_NEXT);
+    }
+    return ids;
+}
+
 uint64_t LmdbDocumentStore::build_index(std::string_view collection,
                                          const std::string& field) {
     // Walk the collection once and index every row. Idempotent thanks to

+ 2 - 0
service/src/storage/document_store_lmdb.hpp

@@ -468,6 +468,8 @@ public:
 
     std::vector<std::string> list_collections() override;
 
+    std::optional<std::vector<std::string>> list_ids(std::string_view collection) override;
+
     bool drop_collection(std::string_view collection) override;
 
     // v2.0 Stage 5 — vector sub-db ops (see DocumentStore base).

+ 61 - 0
tests/load_test/lmdb_row_tool.cpp

@@ -0,0 +1,61 @@
+// v2.20.2 - manufactures the production "ghost row" state for
+// test_disk_only_rows.sh: a row in LMDB that MemoryStore (rebuilt from
+// snapshot + WAL, never from LMDB) does not hold, and the reverse.
+//
+// Opens its own MDB_env, so it must ONLY run while the server is stopped (see
+// relidx_drop_tool.cpp for why: POSIX locks are per process).
+//
+// Usage: lmdb_row_tool <env_dir> <subdb> copy <src_id> <dst_id>
+//          writes src's stored value under dst, with its "id" rewritten
+//        lmdb_row_tool <env_dir> <subdb> del <id>
+
+#include <lmdb.h>
+
+#include <iostream>
+#include <string>
+
+static int die(const char* what, int rc) {
+    std::cerr << what << ": " << mdb_strerror(rc) << "\n";
+    return 1;
+}
+
+int main(int argc, char** argv) {
+    if (argc < 5) {
+        std::cerr << "usage: lmdb_row_tool <env_dir> <subdb> copy <src> <dst> | del <id>\n";
+        return 2;
+    }
+    const std::string op = argv[3];
+    MDB_env* env = nullptr;
+    int rc = mdb_env_create(&env);
+    if (rc) return die("env_create", rc);
+    mdb_env_set_maxdbs(env, 512);
+    mdb_env_set_mapsize(env, 1ULL << 30);
+    if ((rc = mdb_env_open(env, argv[1], 0, 0644))) return die("env_open", rc);
+    MDB_txn* txn = nullptr;
+    if ((rc = mdb_txn_begin(env, nullptr, 0, &txn))) return die("txn_begin", rc);
+    MDB_dbi dbi;
+    if ((rc = mdb_dbi_open(txn, argv[2], 0, &dbi))) return die("dbi_open", rc);
+
+    if (op == "copy" && argc == 6) {
+        const std::string src = argv[4], dst = argv[5];
+        MDB_val k{src.size(), const_cast<char*>(src.data())}, v;
+        if ((rc = mdb_get(txn, dbi, &k, &v))) return die("get src", rc);
+        std::string body(static_cast<char*>(v.mv_data), v.mv_size);
+        const std::string from = "\"id\":\"" + src + "\"", to = "\"id\":\"" + dst + "\"";
+        const auto pos = body.find(from);
+        if (pos == std::string::npos) { std::cerr << "no id field in the stored value\n"; return 1; }
+        body.replace(pos, from.size(), to);
+        MDB_val dk{dst.size(), const_cast<char*>(dst.data())}, dv{body.size(), body.data()};
+        if ((rc = mdb_put(txn, dbi, &dk, &dv, MDB_NOOVERWRITE))) return die("put dst", rc);
+    } else if (op == "del" && argc == 5) {
+        const std::string id = argv[4];
+        MDB_val k{id.size(), const_cast<char*>(id.data())};
+        if ((rc = mdb_del(txn, dbi, &k, nullptr))) return die("del", rc);
+    } else {
+        std::cerr << "bad arguments\n";
+        return 2;
+    }
+    if ((rc = mdb_txn_commit(txn))) return die("commit", rc);
+    mdb_env_close(env);
+    return 0;
+}

+ 84 - 0
tests/load_test/test_disk_only_rows.cpp

@@ -0,0 +1,84 @@
+// v2.20.2 - a row LMDB holds and MemoryStore does not ("ghost row", found on a
+// production instance): reads are served from LMDB and found it, every write
+// looked only in MemoryStore, so patch/update/delete answered not-found and an
+// insert or upsert of its id was ACCEPTED and overwrote it at version 1.
+// test_disk_only_rows.sh plants such rows with the server stopped; this drives
+// a real client against them.
+//
+// Phases: seed | check | after
+
+#include <smartbotic/database/client.hpp>
+
+#include <iostream>
+#include <string>
+
+using namespace smartbotic::database;
+static int pass = 0, fail = 0;
+static void ck(bool c, const std::string& m) {
+    if (c) { ++pass; } else { ++fail; std::cerr << "FAIL: " << m << "\n"; }
+}
+
+int main(int argc, char** argv) {
+    const std::string phase = argc > 1 ? argv[1] : "";
+    Client::Config cfg;
+    cfg.address = "127.0.0.1:9037";
+    cfg.writeRetries = 0;
+    Client c(cfg);
+    c.connect();
+    const std::string C = "ghosts";
+
+    if (phase == "seed") {
+        c.insert(C, {{"n", 1}, {"keep", "me"}}, "a1");
+        c.insert(C, {{"n", 1}}, "b1");
+        c.insert(C, {{"n", 1}}, "c1");
+        ck(c.get(C, "a1").has_value(), "seed: a1 stored");
+    } else if (phase == "check") {
+        // The planted rows are readable - the production symptom's first half.
+        auto g1 = c.get(C, "ghost1");
+        ck(g1 && (*g1)["n"] == 1, "check: ghost1 is readable");
+        ck(!c.get(C, "b1").has_value(), "check: b1 (deleted on disk only) reads as absent");
+
+        // An insert of the id must not overwrite it.
+        bool dup = false;
+        try {
+            c.insert(C, {{"n", 99}}, "ghost1");
+        } catch (const Client::AlreadyExists&) {
+            dup = true;
+        } catch (const std::exception& e) {
+            std::cerr << "insert threw: " << e.what() << "\n";
+        }
+        ck(dup, "check: insert of ghost1 is refused AlreadyExists");
+        auto g1b = c.get(C, "ghost1");
+        ck(g1b && (*g1b)["n"] == 1 && (*g1b)["_version"] == 1, "check: ghost1 untouched by the insert");
+
+        Client::Failure f;
+        ck(c.patch(C, "ghost1", {{"n", 2}}, f) == 2, "check: patch of ghost1 applies (version 2)");
+        auto g1c = c.get(C, "ghost1");
+        ck(g1c && (*g1c)["n"] == 2 && (*g1c)["keep"] == "me", "check: patched body read back, other fields kept");
+
+        ck(c.remove(C, "ghost2"), "check: remove of ghost2 returns true");
+        ck(!c.get(C, "ghost2").has_value(), "check: ghost2 is gone");
+
+        ck(c.update(C, "ghost3", {{"n", 3}}), "check: update of ghost3 applies");
+        auto g3 = c.get(C, "ghost3");
+        ck(g3 && (*g3)["n"] == 3 && (*g3)["_version"] == 2, "check: ghost3 at version 2");
+
+        ck(!c.upsert(C, {{"n", 4}}, "ghost4").second, "check: upsert of ghost4 reports isNew=false");
+        auto g4 = c.get(C, "ghost4");
+        ck(g4 && (*g4)["n"] == 4 && (*g4)["_version"] == 2,
+           "check: upsert of ghost4 updates (version 2), not re-created at version 1");
+    } else if (phase == "after") {
+        auto g1 = c.get(C, "ghost1");
+        ck(g1 && (*g1)["n"] == 2, "after restart: ghost1 keeps the patch");
+        ck(!c.get(C, "ghost2").has_value(), "after restart: ghost2 stays deleted");
+        auto g3 = c.get(C, "ghost3");
+        ck(g3 && (*g3)["n"] == 3, "after restart: ghost3 keeps the update");
+        Client::Failure f;
+        ck(c.patch(C, "ghost1", {{"n", 5}}, f) == 3, "after restart: ghost1 is an ordinary row (patch -> 3)");
+    } else {
+        std::cerr << "usage: t seed|check|after\n";
+        return 2;
+    }
+    std::cout << phase << ": " << pass << " passed, " << fail << " failed\n";
+    return fail == 0 ? 0 : 1;
+}

+ 80 - 0
tests/load_test/test_disk_only_rows.sh

@@ -0,0 +1,80 @@
+#!/usr/bin/env bash
+# v2.20.2 e2e - rows LMDB holds and MemoryStore does not ("ghost rows"), and
+# the reverse, manufactured with the server stopped. Checks the boot key audit
+# names them, every write path reaches a ghost row, and the result survives a
+# restart.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+cd "$SCRIPT_DIR"
+
+DIR=/tmp/sbdb-disk-only-rows
+PORT=9037
+ENV="$DIR/data/projects/default/env"
+rm -rf "$DIR"
+mkdir -p "$DIR/data"
+cat > "$DIR/config.json" <<CFG
+{
+  "storage": {
+    "data_directory": "$DIR/data",
+    "bind_address": "127.0.0.1",
+    "rpc_port": $PORT,
+    "encryption": { "enabled": false },
+    "migrations": { "enabled": false },
+    "replication": { "enabled": false }
+  }
+}
+CFG
+
+echo "=== building test binaries ==="
+g++ -std=c++20 -O1 -o "$DIR/t" test_disk_only_rows.cpp \
+    -I"$ROOT/client/include" -I"$ROOT/build/client" \
+    -L"$ROOT/build/client" -lsmartbotic-db-client -lspdlog -lfmt -pthread
+g++ -std=c++20 -O1 -o "$DIR/rowtool" lmdb_row_tool.cpp -llmdb
+
+SERVER_PID=""
+trap '[[ -n "$SERVER_PID" ]] && kill $SERVER_PID 2>/dev/null; wait 2>/dev/null || true' EXIT
+start() {
+    "$ROOT/build/service/smartbotic-database" --config "$DIR/config.json" > "$DIR/server$1.log" 2>&1 &
+    SERVER_PID=$!
+    for _ in $(seq 1 120); do grep -q "Notified systemd: READY" "$DIR/server$1.log" && return 0; sleep 0.5; done
+    echo "server did not start"; tail -20 "$DIR/server$1.log"; exit 1
+}
+stop() { kill "$SERVER_PID"; wait "$SERVER_PID" || true; SERVER_PID=""; }
+client() { LD_LIBRARY_PATH="$ROOT/build/client" "$DIR/t" "$1" 2>&1 | grep -v '\[error\]\|\[info\]\|\[warning\]'; return "${PIPESTATUS[0]}"; }
+
+fails=0
+ck() { if eval "$2"; then echo "ok   $1"; else echo "FAIL $1"; fails=$((fails+1)); fi; }
+
+start 1
+client seed || fails=$((fails+1))
+ck "boot 1: key audit runs and is clean" "grep -q 'key audit: .* consistent' '$DIR/server1.log'"
+stop
+
+# The production state: rows only on disk, and one deleted on disk only.
+for g in ghost1 ghost2 ghost3 ghost4; do "$DIR/rowtool" "$ENV" ghosts copy a1 "$g"; done
+"$DIR/rowtool" "$ENV" ghosts del b1
+
+start 2
+ck "boot 2: audit names the 4 disk-only rows" \
+   "grep -q 'key audit: default:ghosts: 4 row(s) on disk but not in memory.*ghost1, ghost2, ghost3, ghost4' '$DIR/server2.log'"
+ck "boot 2: audit names the memory-only row" \
+   "grep -q 'key audit: default:ghosts: 1 row(s) in memory but not on disk.*ids: b1' '$DIR/server2.log'"
+ck "boot 2: audit summary" "grep -q 'key audit: .* 4 row(s) on disk only, 1 in memory only' '$DIR/server2.log'"
+client check || fails=$((fails+1))
+ck "boot 2: each adopted row logged once" "[[ \$(grep -c 'the row was on disk but not in memory' '$DIR/server2.log') -eq 4 ]]"
+stop
+
+start 3
+ck "boot 3: the written rows are no longer disk-only" \
+   "! grep -q 'row(s) on disk but not in memory' '$DIR/server3.log'"
+ck "boot 3: b1 is still reported (nothing wrote it)" \
+   "grep -q 'key audit: default:ghosts: 1 row(s) in memory but not on disk.*ids: b1' '$DIR/server3.log'"
+client after || fails=$((fails+1))
+grep -h 'key audit:.*ms)' "$DIR"/server*.log || true
+stop
+
+[[ $fails -eq 0 ]] && echo "OK - disk-only rows e2e passed" || echo "FAILED ($fails)"
+exit $(( fails > 0 ))

+ 105 - 0
tests/test_dual_write_mirror.cpp

@@ -498,6 +498,110 @@ void test_patch_stamps_unmarked_rows() {
     check(healthy.load() && drift.load() == 0, "patch stamp: clean");
 }
 
+// v2.20.2 - a row in LMDB that MemoryStore does not hold (not resident, no
+// eviction stub). Found on a production instance: reads (served from LMDB)
+// returned it, every write said not-found, and an insert or upsert of its id
+// was ACCEPTED and overwrote it at version 1. MemoryStore is rebuilt from
+// snapshot + WAL, never from LMDB, so a restart could not repair it. Every
+// write path must now find the row; the planted rows are written to LMDB
+// only, exactly the production state.
+void test_lmdb_only_rows_are_writable() {
+    using smartbotic::database::DuplicateDocumentId;
+    TmpEnv tmp("lmdb-only");
+    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);
+    const std::string C = "proj:things";
+    mem.createCollection(C, {});
+    mem.insert(C, make_doc("resident", C, {{"n", 0}}));   // the collection exists in memory
+
+    auto plant = [&](const std::string& id, uint64_t version) {
+        Document d = make_doc(id, "things", {{"n", 1}, {"keep", "me"}});
+        d.version = version;
+        doc_store.put("things", id, d);   // LMDB only
+    };
+    for (const char* id : {"patch", "update", "cas", "upsert", "insert", "remove", "upsert-gone"}) {
+        plant(id, 7);
+    }
+    check(!mem.get(C, "patch").has_value(), "lmdb-only: the planted row is not in memory");
+
+    check(mem.patchDocument(C, "patch", {{"n", 2}}) == 8, "lmdb-only: patch applies, version 7 -> 8");
+    auto p = doc_store.get("things", "patch");
+    check(p && p->data()["n"] == 2 && p->data()["keep"] == "me",
+          "lmdb-only: patch merged into the on-disk body (other fields kept)");
+
+    check(mem.update(C, "update", make_doc("update", C, {{"n", 3}})), "lmdb-only: update applies");
+    auto u = doc_store.get("things", "update");
+    check(u && u->data()["n"] == 3 && u->version == 8, "lmdb-only: update wrote version 8");
+
+    check(mem.updateIfVersion(C, "cas", make_doc("cas", C, {{"n", 4}}), 7),
+          "lmdb-only: updateIfVersion against the on-disk version applies");
+
+    Document up = make_doc("upsert", C, {{"n", 5}});
+    mem.upsert(C, up);
+    auto us = doc_store.get("things", "upsert");
+    check(us && us->version == 8 && us->createdAt == 1731628800000ULL,
+          "lmdb-only: upsert updates (version 8, createdAt kept), not re-created at version 1");
+
+    bool dup = false;
+    try {
+        mem.insert(C, make_doc("insert", C, {{"n", 99}}));
+    } catch (const DuplicateDocumentId&) {
+        dup = true;
+    }
+    check(dup, "lmdb-only: insert of the id is refused as a duplicate");
+    auto ins = doc_store.get("things", "insert");
+    check(ins && ins->data()["n"] == 1 && ins->version == 7, "lmdb-only: insert left the row untouched");
+
+    check(mem.remove(C, "remove"), "lmdb-only: remove returns true");
+    check(!doc_store.get("things", "remove").has_value(), "lmdb-only: remove deleted it on disk");
+
+    // A row deleted from LMDB between reads is simply absent.
+    check(mem.patchDocument(C, "never-existed", {{"n", 1}}) == 0, "lmdb-only: a truly absent row is still not found");
+    check(!mem.get(C, "never-existed").has_value(), "lmdb-only: and nothing was conjured");
+
+    // Mirror not healthy: MemoryStore may be ahead of LMDB (a delete here that
+    // never reached LMDB), so nothing is adopted - the old behaviour.
+    healthy.store(false);
+    check(mem.patchDocument(C, "upsert-gone", {{"n", 6}}) == 0,
+          "lmdb-only: with the mirror unhealthy, nothing is loaded from LMDB");
+    healthy.store(true);
+    drift.store(1);
+    check(mem.patchDocument(C, "upsert-gone", {{"n", 6}}) == 0,
+          "lmdb-only: with drift, nothing is loaded from LMDB");
+    drift.store(0);
+
+    // A legacy bare alias holding the id: no second copy is made.
+    mem.createCollection("things", {});
+    mem.loadDocument("things", make_doc("aliased", "things", {{"n", 1}}));
+    plant("aliased", 7);
+    check(mem.patchDocument("default:things", "aliased", {{"n", 2}}) == 0,
+          "lmdb-only: an id held under the bare alias is not copied into the qualified name");
+
+    // Vectors come along, so a MemoryStore-served search still sees the row.
+    smartbotic::database::CollectionOptions vopts;
+    vopts.vectorDimension = 4;
+    mem.createCollection("proj:emb", vopts);
+    mem.insert("proj:emb", make_doc("seed", "proj:emb", {{"n", 0}}));
+    {
+        Document d = make_doc("v", "emb", {{"n", 1}});
+        d.hasVector = true;
+        doc_store.put("emb", "v", d);
+        doc_store.put_vector("emb", "v", {1.f, 0.f, 0.f, 0.f});
+    }
+    check(mem.patchDocument("proj:emb", "v", {{"n", 2}}) == 2, "lmdb-only: patch of a vector row applies");
+    auto vecs = mem.getCollectionVectors("proj:emb");
+    check(vecs && vecs->count("v") == 1, "lmdb-only: its vector was loaded with it");
+    check(doc_store.get_vector("emb", "v").has_value(), "lmdb-only: and kept on disk");
+    check(healthy.load() && drift.load() == 0, "lmdb-only: clean");
+}
+
 // Simulates DatabaseService::backfillIntoDocStore — populate MemoryStore
 // without a persist callback (no live mirror), then walk listCollections +
 // getAllDocuments and feed each doc into applyDualWriteMirror with
@@ -613,6 +717,7 @@ int main() {
     test_vector_mirror_system_collection_skipped();
     test_vector_mirror_via_memory_store();
     test_patch_stamps_unmarked_rows();
+    test_lmdb_only_rows_are_writable();
     test_backfill_iteration_pattern();
     test_scan_vectors_round_trip();
 

部分文件因为文件数量过多而无法显示