فهرست منبع

fix: snapshots kept evicted rows only while their WAL file existed; failed LMDB copies are remembered; consistency repair knobs

A snapshot read an evicted document back only from the WAL. Once the WAL
rotated and a snapshot deleted the old file, a document still evicted at
the next snapshot was written as absent, and the next boot came up without
it while LMDB kept it (7,219 rows on one production instance). The snapshot
now reads evicted documents from LMDB and fails, keeping the WAL, when it
still cannot read one.

A failed copy to LMDB is recorded in mirror-pending.log and repaired from
memory at the next boot, so a snapshot can no longer make it permanent.

storage.consistency decides what the boot key audit does with rows the two
stores already disagree on: disk_only adopt (default) / report / remove,
memory_only report (default) / write / remove. Full lists go to
consistency-report.json.
fszontagh 1 ماه پیش
والد
کامیت
a8364ea442

+ 29 - 0
CHANGELOG.md

@@ -11,6 +11,35 @@ Per-release detail (design, measurements, revert evidence) stays in `CLAUDE.md`;
 consumer-facing usage is in `docs/integration-guide.md`.
 
 ## Unreleased
+### Fixed
+- **[server]** ⚠ A snapshot silently left out every document that stayed
+  evicted across a WAL rotation: it read an evicted document back only from the
+  WAL, and the previous snapshot had deleted that WAL file, so the document was
+  written as absent with a WARN. The next boot came up without it while LMDB
+  kept it (7,219 rows on one production instance, found by the 2.20.2 key
+  audit): readable, invisible to writes, and missing from any backup of
+  `snapshots/` plus `wal/`. The snapshot now reads an evicted document from
+  LMDB, and a document it still cannot read fails the snapshot (the WAL is
+  kept) instead of being dropped.
+- **[server]** A row whose copy to LMDB failed was repaired at the next boot
+  only if its WAL entry still existed; a snapshot in between made the
+  divergence permanent. Failed copies are now recorded durably
+  (`mirror-pending.log` in the data directory) and repaired from memory at the
+  next boot.
+### Added
+- **[server]** `storage.consistency`: what the boot key audit does about rows
+  memory and disk disagree on. `disk_only`: `adopt` (default: load into
+  memory; reads already see them) / `report` / `remove`. `memory_only`:
+  `report` (default) / `write` / `remove`. Complete id lists in
+  `consistency-report.json` in the data directory every boot.
+### Observable
+- **[server]** With the default `disk_only: adopt`, the first boot on this
+  version loads every disk-only row into memory (on the instance above, 7,219
+  rows): memory use rises by their size until eviction trims it, and boot takes
+  longer by the time to read them. Set `disk_only: report` first to see the
+  list before anything acts. The key audit logs at WARN (it was ERROR), and
+  ERROR only when a repair failed.
+
 
 ## 2.20.2 - 2026-10-22 (bug fix, server only)
 ### Fixed

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 0 - 0
CLAUDE.md


+ 19 - 5
docs/ROADMAP.md

@@ -379,10 +379,23 @@ 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)
+### 5f. How MemoryStore and LMDB came to disagree (found 2026-10-19, mostly explained 2026-10-22)
+
+**Explained for the bulk (fixed on main for 2.21.0):** the production
+instance's first 2.20.2 boot reported 7,219 disk-only rows and none the other
+way, after loading its whole store from one snapshot with no WAL replayed and
+nothing evicted. So the snapshot lacked them. Cause: a snapshot read an evicted
+document back only from the WAL; the WAL rotates at 100 MB and a snapshot
+deletes rotated files it covers, so a document still evicted at the next
+snapshot was written as absent ("will be missing from the snapshot"). That is
+candidate (2) below, with the mechanism. Reproduced on the released 2.20.2
+(`tests/load_test/test_snapshot_keeps_evicted.sh` with `SERVER_BIN`: 600 rows,
+3 lost). Fixed by reading evicted documents from LMDB and failing a snapshot
+that still cannot read one; failed LMDB copies are now logged durably and
+repaired at boot; `storage.consistency` repairs what already diverged.
 
 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.
+disagreement. Before the 2026-10-22 production numbers, the cause was open:
 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
@@ -402,9 +415,10 @@ WAL, but in LMDB it found nothing in the home sub-db; the repair then moved the
 stray copy home, i.e. those rows may be DELETED rows the repair resurrected.
 Not yet checked against the history files. The other disk-only rows, and every
 memory-only one (incl. one `default:vectorapi_keys` row), are unexplained. 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. **Any fix must not be
-automatic** (raised by smartbotic-vectorapi): a memory-only row is either a
+("in memory only") is reported by the same audit; 2.21.0's
+`storage.consistency.memory_only` can write or remove them but defaults to
+`report`, because **the repair must not be automatic by default** (raised by
+smartbotic-vectorapi): a memory-only row is either a
 write that never reached LMDB (repair = write it) or a DELETE that never
 reached MemoryStore (repair = remove it), and nothing in the row tells which.
 For an API-key collection the second is a revoked credential, so writing it to

+ 58 - 0
docs/integration-guide.md

@@ -15,6 +15,7 @@ How to install, configure, and integrate smartbotic-database into your C++ proje
 - [Upgrading from Legacy Packages](#upgrading-from-legacy-packages)
 - [Drop-in configuration (conf.d)](#drop-in-configuration-confd)
 - [Eviction & Memory Pressure](#eviction--memory-pressure)
+- [Memory and disk consistency](#memory-and-disk-consistency-storageconsistency-2210)
 - [Access Policy — row and column level security](#access-policy--row-and-column-level-security-270)
 
 ---
@@ -2503,6 +2504,63 @@ Also shown in `smartbotic-db-cli status` output (if the CLI exposes it; otherwis
 
 **Pressure stays at `hard` despite quiet writes** — check `eviction_target_percent`; eviction stops when usage drops below this. If you want eviction to drain further during idle, raise `max_memory_mb` or lower the target.
 
+### Memory and disk consistency (`storage.consistency`, 2.21.0+)
+
+The server holds every document twice: in memory (rebuilt at boot from the
+newest snapshot plus the WAL) and on disk in LMDB (where reads are served
+from). Writes check memory. When the two disagree about a row:
+
+- **On disk only:** reads find it. Before 2.20.2 every write said not-found
+  and an insert of its id overwrote it; since 2.20.2 a write loads it first.
+- **In memory only:** writes find it (an insert of its id is `AlreadyExists`),
+  reads do not.
+
+Every boot runs a read-only **key audit** that compares the two per collection
+and logs a WARN line per collection plus a summary. The **complete** id lists
+go to `<data_directory>/consistency-report.json` (rewritten every boot). Then
+it applies these settings:
+
+```json
+{
+  "storage": {
+    "consistency": {
+      "disk_only": "adopt",
+      "memory_only": "report"
+    }
+  }
+}
+```
+
+| Setting | Values | Default | What it does |
+|---|---|---|---|
+| `disk_only` | `adopt` / `report` / `remove` | `adopt` | `adopt` loads the rows into memory (reads already see them, so nothing visible changes; they are in the next snapshot again). `remove` deletes them from disk. |
+| `memory_only` | `report` / `write` / `remove` | `report` | `write` copies the rows to disk (they become readable). `remove` deletes them from memory, through the ordinary delete path (WAL, history, a `DELETE` event with actor `system:consistency-repair`). |
+
+`report` changes nothing; the log line says which setting would do what. An
+unknown value is treated as `report`.
+
+**Why `memory_only` defaults to `report`:** nothing in a row says which side
+is right. A memory-only row is either a write whose disk copy failed (repair:
+`write`) or a delete that reached the disk and not memory (repair: `remove`).
+For an API-key collection the second is a revoked key, which `write` would put
+back into service. Look at `consistency-report.json` and decide per row.
+
+**Rows whose disk copy is KNOWN to have failed are repaired regardless of
+these settings.** Since 2.21.0 a failed copy is recorded in
+`<data_directory>/mirror-pending.log`, and the next boot copies those rows
+from memory (written if memory has them, deleted from disk if not). For those
+rows memory is right by construction.
+
+**Backups: copy the whole data directory.** Before 2.21.0 a snapshot silently
+left out a document that had stayed evicted across a WAL rotation (its copy was
+read back from a WAL file the previous snapshot had deleted). Such rows lived
+only in LMDB (`projects/*/env/data.mdb`), so a backup of `snapshots/` plus
+`wal/` lacked them, and `Recovery complete: N docs` (which counts memory) still
+looked right. On 2.21.0 the snapshot reads evicted rows from LMDB, and the first
+boot's `adopt` puts the lost rows back into memory and the next snapshot. A
+backup is still the whole data directory, as the package's pre-upgrade backup
+already copies it.
+
 ### Configuring for Your Project
 
 Consumer projects typically enable migrations by configuring the database via their own `postinst` script:

+ 232 - 23
service/src/database_service.cpp

@@ -282,6 +282,8 @@ bool DatabaseService::initialize() {
 
         // 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: mirror-pending replay");
+        replayMirrorPending();
         spdlog::info("Boot: memory/disk key audit");
         auditMemoryDiskKeys();
 
@@ -1056,10 +1058,41 @@ void DatabaseService::auditSubdbPlacement() {
     }
 }
 
+void DatabaseService::recordMirrorFailure(const std::string& collection, const std::string& id) {
+    if (!mirror_pending_) return;
+    if (!mirror_pending_->append(collection, id)) {
+        spdlog::error("mirror-pending: could not record {}/{} in {} - if a snapshot truncates "
+                      "its WAL entry before the next boot, only the boot key audit will find it",
+                      collection, id, mirror_pending_->path().string());
+    }
+}
+
+void DatabaseService::replayMirrorPending() {
+    if (!mirror_pending_ || !store_) return;
+    const auto rows = mirror_pending_->load();
+    if (rows.empty()) return;
+    spdlog::warn("mirror-pending: {} row(s) whose LMDB copy failed earlier; bringing LMDB in "
+                 "line with memory", rows.size());
+    const auto r = store_->syncDocStoreFromMemory(rows);
+    if (!mirror_pending_->replace(r.failed)) {
+        spdlog::error("mirror-pending: could not rewrite {}", mirror_pending_->path().string());
+    }
+    if (r.failed.empty()) {
+        spdlog::info("mirror-pending: repaired {} row(s): {} written, {} deleted from LMDB",
+                     rows.size(), r.written, r.deleted);
+    } else {
+        spdlog::error("mirror-pending: {} written, {} deleted, {} still failing (kept for the "
+                      "next boot; reads for this process are served from memory)",
+                      r.written, r.deleted, r.failed.size());
+    }
+}
+
 void DatabaseService::auditMemoryDiskKeys() {
     if (!projects_ || !store_) return;
     namespace sd = smartbotic::database;
     const auto started = std::chrono::steady_clock::now();
+    const std::string& diskPolicy = config_.consistencyDiskOnly;
+    const std::string& memPolicy = config_.consistencyMemoryOnly;
 
     // LMDB sub-db ("project:collection") -> the MemoryStore names that feed
     // it. A default-project collection may also live under its bare legacy
@@ -1081,11 +1114,17 @@ void DatabaseService::auditMemoryDiskKeys() {
             if (i) out += ", ";
             out += ids[i];
         }
-        if (ids.size() > 10) out += ", ...";
+        if (ids.size() > 10) out += ", ... (all in consistency-report.json)";
         return out;
     };
 
+    nlohmann::json report = {
+        {"policy", {{"disk_only", diskPolicy}, {"memory_only", memPolicy}}},
+        {"collections", nlohmann::json::array()},
+    };
     uint64_t diskOnlyTotal = 0, memOnlyTotal = 0, compared = 0;
+    uint64_t adopted = 0, diskRemoved = 0, written = 0, memRemoved = 0, actionFailed = 0;
+
     for (const auto& project : projects_->listOpen()) {
         auto* ds = docStore(project);
         if (!ds) continue;
@@ -1107,36 +1146,126 @@ void DatabaseService::auditMemoryDiskKeys() {
             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));
+                // id -> the MemoryStore name holding it (the first alias wins).
+                std::vector<std::pair<std::string, std::string>> mem;
+                const auto namesIt = memNames.find(qualified);
+                if (namesIt != memNames.end()) {
+                    for (const auto& n : namesIt->second) {
+                        for (auto& id : store_->getDocumentIds(n)) mem.emplace_back(std::move(id), n);
+                        for (auto& id : store_->getEvictedDocumentIds(n)) mem.emplace_back(std::move(id), n);
                     }
                 }
-                std::sort(mem.begin(), mem.end());
-                mem.erase(std::unique(mem.begin(), mem.end()), mem.end());
+                std::stable_sort(mem.begin(), mem.end(),
+                                 [](const auto& a, const auto& b) { return a.first < b.first; });
+                mem.erase(std::unique(mem.begin(), mem.end(),
+                                      [](const auto& a, const auto& b) { return a.first == b.first; }),
+                          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));
+                std::vector<std::string> diskOnly;
+                std::vector<std::pair<std::string, std::string>> memOnly;   // id, memory name
+                {
+                    size_t i = 0, j = 0;
+                    while (i < disk->size() || j < mem.size()) {
+                        if (j == mem.size() || (i < disk->size() && (*disk)[i] < mem[j].first)) {
+                            diskOnly.push_back((*disk)[i++]);
+                        } else if (i == disk->size() || mem[j].first < (*disk)[i]) {
+                            memOnly.push_back(mem[j++]);
+                        } else {
+                            ++i; ++j;
+                        }
+                    }
+                }
                 ++compared;
+                if (diskOnly.empty() && memOnly.empty()) continue;
+
+                nlohmann::json entry = {{"collection", qualified}};
                 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));
+                    // Adoption needs the collection in memory (its options:
+                    // vector dimension, TTL); one only on disk is reported.
+                    const bool inMemory = namesIt != memNames.end();
+                    std::vector<std::string> done, failed;
+                    if (diskPolicy == "adopt" && inMemory) {
+                        const std::string target = std::find(namesIt->second.begin(),
+                                                             namesIt->second.end(), qualified)
+                                                       != namesIt->second.end()
+                                                   ? qualified : namesIt->second.front();
+                        for (const auto& id : diskOnly) {
+                            try {
+                                (store_->adoptFromDocStore(target, id) ? done : failed).push_back(id);
+                            } catch (const std::exception& e) {
+                                spdlog::error("key audit: adopting {}/{} failed: {}", qualified, id, e.what());
+                                failed.push_back(id);
+                            }
+                        }
+                        adopted += done.size();
+                    } else if (diskPolicy == "remove") {
+                        for (const auto& id : diskOnly) {
+                            try {
+                                ds->del(coll, id);
+                                ds->del_vector(coll, id);
+                                done.push_back(id);
+                            } catch (const std::exception& e) {
+                                spdlog::error("key audit: removing {}/{} from disk failed: {}",
+                                              qualified, id, e.what());
+                                failed.push_back(id);
+                            }
+                        }
+                        diskRemoved += done.size();
+                    }
+                    actionFailed += failed.size();
+                    const std::string action =
+                        diskPolicy == "report" ? "reported" :
+                        (diskPolicy == "adopt" && !inMemory) ? "reported (collection not in memory)" :
+                        diskPolicy == "adopt" ? "adopted into memory" : "removed from disk";
+                    spdlog::warn("key audit: {}: {} row(s) on disk but not in memory (reads find them; "
+                                 "2.20.2+ loads one when it is written) - {}{}{}. ids: {}",
+                                  qualified, diskOnly.size(), action,
+                                  diskPolicy == "report" ? "; set storage.consistency.disk_only to adopt "
+                                                           "(load into memory) or remove (delete from disk)"
+                                                         : "",
+                                  failed.empty() ? "" : fmt::format("; {} FAILED", failed.size()),
+                                  samples(diskOnly));
+                    entry["disk_only"] = {{"action", action}, {"ids", diskOnly}, {"failed", failed}};
                 }
                 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));
+                    std::vector<std::string> ids, failed;
+                    for (const auto& [id, n] : memOnly) ids.push_back(id);
+                    if (memPolicy == "write") {
+                        std::vector<std::pair<std::string, std::string>> rows;
+                        for (const auto& [id, n] : memOnly) rows.emplace_back(n, id);
+                        const auto r = store_->syncDocStoreFromMemory(rows);
+                        written += r.written;
+                        for (const auto& [c, id] : r.failed) failed.push_back(id);
+                    } else if (memPolicy == "remove") {
+                        for (const auto& [id, n] : memOnly) {
+                            try {
+                                if (store_->remove(n, id, "system:consistency-repair")) ++memRemoved;
+                                else failed.push_back(id);
+                            } catch (const std::exception& e) {
+                                spdlog::error("key audit: removing {}/{} from memory failed: {}",
+                                              qualified, id, e.what());
+                                failed.push_back(id);
+                            }
+                        }
+                    }
+                    actionFailed += failed.size();
+                    const std::string action =
+                        memPolicy == "report" ? "reported" :
+                        memPolicy == "write" ? "written to disk" : "removed from memory";
+                    spdlog::warn("key audit: {}: {} row(s) in memory but not on disk (writes find them, "
+                                 "reads served from disk do not) - {}{}{}. ids: {}",
+                                  qualified, memOnly.size(), action,
+                                  memPolicy == "report" ? "; set storage.consistency.memory_only to write "
+                                                          "(make them readable) or remove (delete them)"
+                                                        : "",
+                                  failed.empty() ? "" : fmt::format("; {} FAILED", failed.size()),
+                                  samples(ids));
+                    entry["memory_only"] = {{"action", action}, {"ids", ids}, {"failed", failed}};
                 }
+                report["collections"].push_back(std::move(entry));
             } catch (const std::exception& e) {
                 spdlog::warn("key audit: {} could not be audited: {}", qualified, e.what());
             }
@@ -1145,12 +1274,32 @@ void DatabaseService::auditMemoryDiskKeys() {
 
     const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
         std::chrono::steady_clock::now() - started).count();
+    report["compared"] = compared;
+    report["disk_only"] = diskOnlyTotal;
+    report["memory_only"] = memOnlyTotal;
+    report["milliseconds"] = ms;
+    try {
+        const auto path = std::filesystem::path(config_.dataDirectory) / "consistency-report.json";
+        const auto tmp = path.string() + ".tmp";
+        {
+            std::ofstream out(tmp, std::ios::trunc);
+            out << report.dump(2) << "\n";
+        }
+        std::filesystem::rename(tmp, path);
+    } catch (const std::exception& e) {
+        spdlog::warn("key audit: could not write consistency-report.json: {}", e.what());
+    }
+
     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);
+        spdlog::log(actionFailed > 0 ? spdlog::level::err : spdlog::level::warn,
+                    "key audit: {} collection(s) compared, {} row(s) on disk only, {} in "
+                    "memory only ({} ms). Policy disk_only={} memory_only={}: {} adopted, {} "
+                    "removed from disk, {} written to disk, {} removed from memory, {} failed. "
+                    "Full lists: consistency-report.json in the data directory.",
+                    compared, diskOnlyTotal, memOnlyTotal, ms, diskPolicy, memPolicy,
+                    adopted, diskRemoved, written, memRemoved, actionFailed);
     }
 }
 
@@ -1225,6 +1374,7 @@ bool DatabaseService::backfillIntoDocStore() {
             }
             if (mirror_drift_count_.load(std::memory_order_relaxed) > drift_before) {
                 ++total_failures;
+                recordMirrorFailure(qualified, doc.id);   // v2.21.0
             }
             ++total_docs;
             if (total_docs % 10000 == 0) {
@@ -1414,6 +1564,24 @@ DatabaseService::Config DatabaseService::parseConfig(const nlohmann::json& json)
         config.bindAddress = db.value("bind_address", config.bindAddress);
         config.rpcPort = db.value("rpc_port", config.rpcPort);
 
+        if (db.contains("consistency") && db["consistency"].is_object()) {
+            const auto& c = db["consistency"];
+            config.consistencyDiskOnly = c.value("disk_only", config.consistencyDiskOnly);
+            config.consistencyMemoryOnly = c.value("memory_only", config.consistencyMemoryOnly);
+        }
+        if (config.consistencyDiskOnly != "adopt" && config.consistencyDiskOnly != "report" &&
+            config.consistencyDiskOnly != "remove") {
+            spdlog::error("storage.consistency.disk_only '{}' is not adopt|report|remove; using report",
+                          config.consistencyDiskOnly);
+            config.consistencyDiskOnly = "report";
+        }
+        if (config.consistencyMemoryOnly != "report" && config.consistencyMemoryOnly != "write" &&
+            config.consistencyMemoryOnly != "remove") {
+            spdlog::error("storage.consistency.memory_only '{}' is not report|write|remove; using report",
+                          config.consistencyMemoryOnly);
+            config.consistencyMemoryOnly = "report";
+        }
+
         // v2.4 — parse the per-listener fleet. If "listeners" is set,
         // it overrides the legacy bind_address+rpc_port. Otherwise we
         // synthesise one listener below using those legacy fields.
@@ -1795,6 +1963,11 @@ void DatabaseService::setupComponents() {
             },
             &mirror_healthy_,
             &mirror_drift_count_);
+        mirror_pending_ = std::make_unique<smartbotic::db::storage::MirrorPendingLog>(
+            std::filesystem::path(config_.dataDirectory) / "mirror-pending.log");
+        store_->setMirrorFailureSink([this](const std::string& collection, const std::string& id) {
+            recordMirrorFailure(collection, id);
+        });
     }
 
     // Create persistence manager. Start from any persistenceConfig values the
@@ -1861,6 +2034,32 @@ void DatabaseService::setupComponents() {
     store_->setDocumentLoadCallback([this](const std::string& collection,
                                            const std::string& id,
                                            uint64_t walSequence) -> std::optional<Document> {
+        // v2.21.0 - LMDB first. The WAL scan below finds an evicted document
+        // only while the WAL still holds its last write; a snapshot truncates
+        // that, so a document still evicted at the NEXT snapshot could not be
+        // read and was written as absent ("will be missing from the
+        // snapshot"). The next boot then came up without it while LMDB still
+        // had it: 7,219 such rows on one production instance. LMDB holds
+        // every write to an evicted document (a write reloads it first), so it
+        // is the right source while the mirror is healthy with no drift; the
+        // WAL stays the fallback for system collections and a degraded mirror.
+        if (projects_ && mirror_healthy_.load(std::memory_order_relaxed) &&
+            mirror_drift_count_.load(std::memory_order_relaxed) == 0) {
+            try {
+                const auto pc = smartbotic::database::parseProjectCollection(collection);
+                if (!pc.collection.empty() && pc.collection.front() != '_') {
+                    if (auto* ds = docStore(pc.project)) {
+                        if (auto doc = ds->get(pc.collection, id)) {
+                            doc->collection = collection;
+                            return doc;
+                        }
+                    }
+                }
+            } catch (const std::exception& e) {
+                spdlog::warn("evicted {}/{}: LMDB read failed ({}); trying the WAL",
+                             collection, id, e.what());
+            }
+        }
         uint64_t fromSequence = walSequence > 0 ? walSequence - 1 : 0;
         return persistence_->loadDocument(collection, id, fromSequence);
     });
@@ -2073,6 +2272,16 @@ void DatabaseService::applyReplicatedEntry(const databasepb::ReplicationEntry& e
                                 entry.collection());
                     if (auto* ds = projects_->getOrCreate(pc.project)) {
                         std::optional<Document> opt_doc(doc);
+                        const uint64_t drift_before =
+                            mirror_drift_count_.load(std::memory_order_relaxed);
+                        struct RecordOnDrift {   // v2.21.0 - however the block exits
+                            DatabaseService* self; const std::string& c; const std::string& id;
+                            uint64_t before;
+                            ~RecordOnDrift() {
+                                if (self->mirror_drift_count_.load(std::memory_order_relaxed) > before)
+                                    self->recordMirrorFailure(c, id);
+                            }
+                        } recordOnDrift{this, entry.collection(), doc.id, drift_before};
                         try {
                             smartbotic::db::storage::applyDualWriteMirror(
                                 ds, mirror_healthy_, mirror_drift_count_,

+ 15 - 0
service/src/database_service.hpp

@@ -2,6 +2,7 @@
 
 #include "document.hpp"
 #include "memory_store.hpp"
+#include "storage/mirror_pending.hpp"
 #include "database_grpc_impl.hpp"
 #include "persistence/persistence_manager.hpp"
 #include "persistence/history_store.hpp"
@@ -119,6 +120,14 @@ public:
         std::string bindAddress = "0.0.0.0";
         uint16_t rpcPort = 9004;
 
+        // v2.21.0 - `storage.consistency`: what the boot key audit does about
+        // rows MemoryStore and LMDB disagree on whose cause is unknown (rows
+        // whose LMDB copy is KNOWN to have failed are repaired from the
+        // mirror-pending log regardless). disk_only: adopt | report | remove;
+        // memory_only: report | write | remove. An unknown value means report.
+        std::string consistencyDiskOnly = "adopt";
+        std::string consistencyMemoryOnly = "report";
+
         // Bootstrap/service registration
         std::string webapiUrl;
         std::string serviceKey;
@@ -372,6 +381,9 @@ private:
     // v2.20.2 - read-only: compares each collection's LMDB ids with
     // MemoryStore's (resident + evicted) and logs both differences.
     void auditMemoryDiskKeys();
+    // v2.21.0 - re-mirror the rows whose LMDB copy failed (mirror-pending log).
+    void replayMirrorPending();
+    void recordMirrorFailure(const std::string& collection, const std::string& id);
 
     // 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.
@@ -489,6 +501,9 @@ private:
     // before engaging — a degraded mirror means LMDB is missing writes.
     std::atomic<bool> mirror_healthy_{true};
     std::atomic<uint64_t> mirror_drift_count_{0};
+    // v2.21.0 - rows whose LMDB mirror write failed, kept until a boot
+    // re-mirrors them (storage/mirror_pending.hpp).
+    std::unique_ptr<smartbotic::db::storage::MirrorPendingLog> mirror_pending_;
 
     std::unique_ptr<PersistenceManager> persistence_;
     std::unique_ptr<HistoryStore> history_store_;  // v1.9.0 — disk-resident history

+ 79 - 1
service/src/memory_store.cpp

@@ -1084,6 +1084,9 @@ MemoryStore::RemirrorBatchResult MemoryStore::remirrorDocuments(
                       coll, id, what);
         mirrorDriftCount_->fetch_add(1, std::memory_order_relaxed);
         ++result.failed;
+        // v2.21.0 - the WAL entry that made this row eligible is truncated by
+        // the next snapshot; record it so a later boot still repairs it.
+        if (mirrorFailureSink_) mirrorFailureSink_(coll, id);
     };
 
     // ⚠ v2.11.0 final review (finding 3) — Deferred holds NO Document.
@@ -3329,7 +3332,20 @@ std::vector<std::optional<Document>> MemoryStore::copyDocuments(
     // collection lock (peekEvictedDocument takes its own locks). A document
     // must not drop out of a snapshot because eviction moved it meanwhile -
     // the WAL entries holding it are truncated once the snapshot completes.
-    for (size_t i : missing) out[i - from] = peekEvictedDocument(collection, ids[i]);
+    for (size_t i : missing) {
+        out[i - from] = peekEvictedDocument(collection, ids[i]);
+        // v2.21.0 - nullopt means "deleted meanwhile" ONLY if no stub remains.
+        // A stub whose copy cannot be read is a document that exists: writing
+        // it as absent would drop it from the snapshot, the WAL holding it is
+        // truncated next, and the next boot comes up without it while LMDB
+        // still has it (a disk-only row). Fail the snapshot instead; the WAL
+        // is kept and the next attempt retries.
+        if (!out[i - from] && getEvictedStub(collection, ids[i])) {
+            throw std::runtime_error("evicted document '" + collection + "/" + ids[i] +
+                                     "' could not be read for the snapshot; snapshot "
+                                     "abandoned so the WAL that holds it is kept");
+        }
+    }
     return out;
 }
 
@@ -3724,6 +3740,60 @@ bool MemoryStore::adoptFromDocStore(const std::string& collection, const std::st
     return true;
 }
 
+MemoryStore::MirrorRepairResult MemoryStore::syncDocStoreFromMemory(
+    const std::vector<std::pair<std::string, std::string>>& rows) {
+    using smartbotic::db::storage::VectorChange;
+    MirrorRepairResult result;
+    if (!docStoreResolver_) return result;
+    for (const auto& [collection, id] : rows) {
+        try {
+            const auto pc = smartbotic::database::parseProjectCollection(collection);
+            if (pc.collection.front() == '_') continue;   // never mirrored
+            auto* ds = docStoreResolver_(pc.project);
+            if (ds == nullptr) throw std::runtime_error("project store unavailable");
+
+            std::optional<Document> doc;
+            std::vector<float> vec;
+            uint32_t dimension = 0;
+            if (const auto* coll = getCollection(collection)) {
+                std::shared_lock<std::shared_mutex> lock(coll->mutex);
+                dimension = coll->options.vectorDimension;
+                if (auto it = coll->documents.find(id); it != coll->documents.end()) {
+                    doc = it->second;
+                    if (auto vit = coll->vectors.find(id); vit != coll->vectors.end()) vec = vit->second;
+                }
+            }
+            if (!doc && getEvictedStub(collection, id)) {
+                doc = peekEvictedDocument(collection, id);
+                if (!doc) throw std::runtime_error("evicted copy could not be read");
+            }
+
+            if (doc) {
+                // The vector: what memory holds; else what the row's marker
+                // says; else leave LMDB's alone (an evicted row's vector is
+                // not reloaded into memory, so absence here proves nothing).
+                VectorChange vc = VectorChange::keep();
+                if (dimension > 0) {
+                    if (!vec.empty()) vc = VectorChange::put(vec);
+                    else if (doc->hasVector == false) vc = VectorChange::remove();
+                }
+                ds->put_with_vector(pc.collection, id, *doc, vc);
+                ++result.written;
+            } else {
+                ds->del(pc.collection, id);
+                ds->del_vector(pc.collection, id);
+                ++result.deleted;
+            }
+        } catch (const std::exception& e) {
+            spdlog::error("mirror repair: {}/{} could not be brought in line with memory: {}",
+                          collection, id, e.what());
+            if (mirrorDriftCount_) mirrorDriftCount_->fetch_add(1, std::memory_order_relaxed);
+            result.failed.emplace_back(collection, id);
+        }
+    }
+    return result;
+}
+
 void MemoryStore::emitPersist(const std::string& collection, const std::string& id,
                               const std::optional<Document>& doc, EventType eventType,
                               const std::optional<std::string>& actor) {
@@ -3751,9 +3821,13 @@ void MemoryStore::mirrorWriteToDocStore(const std::string& collection, const std
     auto pc = smartbotic::database::parseProjectCollection(collection);
     auto* ds = docStoreResolver_(pc.project);
     if (!ds) return;
+    const uint64_t driftBefore = mirrorDriftCount_->load(std::memory_order_relaxed);
     smartbotic::db::storage::applyDualWriteMirror(
         ds, *mirrorHealthy_, *mirrorDriftCount_,
         pc.collection, id, doc, eventType, vc);
+    if (mirrorFailureSink_ && mirrorDriftCount_->load(std::memory_order_relaxed) > driftBefore) {
+        mirrorFailureSink_(collection, id);   // v2.21.0
+    }
 }
 
 smartbotic::db::storage::VectorChange
@@ -3821,9 +3895,13 @@ void MemoryStore::mirrorVectorToDocStore(const std::string& collection, const st
     auto pc = smartbotic::database::parseProjectCollection(collection);
     auto* ds = docStoreResolver_(pc.project);
     if (!ds) return;
+    const uint64_t driftBefore = mirrorDriftCount_->load(std::memory_order_relaxed);
     smartbotic::db::storage::applyVectorMirror(
         ds, *mirrorHealthy_, *mirrorDriftCount_,
         pc.collection, id, vec, eventType);
+    if (mirrorFailureSink_ && mirrorDriftCount_->load(std::memory_order_relaxed) > driftBefore) {
+        mirrorFailureSink_(collection, id);   // v2.21.0
+    }
 }
 
 void MemoryStore::mirrorDropToDocStore(const std::string& collection) {

+ 38 - 2
service/src/memory_store.hpp

@@ -259,6 +259,19 @@ public:
                                 std::atomic<bool>* healthy,
                                 std::atomic<uint64_t>* drift);
 
+    /**
+     * v2.21.0 - called with (qualified collection, id) whenever a mirror write
+     * of that row to LMDB failed (the write itself stands in MemoryStore and
+     * the WAL). DatabaseService records it durably (storage/mirror_pending.hpp)
+     * so a later boot re-mirrors the row even after a snapshot has truncated
+     * the WAL entry that would otherwise be the only trace of it. May be
+     * called for a row that did not fail (the check is "drift went up during
+     * this call", and drift is shared); re-mirroring such a row is harmless.
+     */
+    using MirrorFailureSink = std::function<void(const std::string& collection,
+                                                 const std::string& id)>;
+    void setMirrorFailureSink(MirrorFailureSink sink) { mirrorFailureSink_ = std::move(sink); }
+
     /**
      * v2.11.0 final review (finding 6) — read-only view of the mirror's
      * health, for code that holds a MemoryStore& but not a DatabaseService&
@@ -1178,7 +1191,7 @@ public:
     [[nodiscard]] std::vector<Document> getAllDocuments(const std::string& collection) const;
 
     /**
-     * 2.21.0 - the ids of the documents resident in a collection (not the
+     * 2.20.1 - the ids of the documents resident in a collection (not the
      * evicted ones; see getEvictedDocumentIds). With copyDocuments below this
      * lets the snapshot writer copy a collection a batch at a time instead of
      * holding a copy of all of it (getAllDocuments) next to the original.
@@ -1186,9 +1199,11 @@ public:
     [[nodiscard]] std::vector<std::string> getDocumentIds(const std::string& collection) const;
 
     /**
-     * 2.21.0 - copies of the named documents, one entry per id, in order:
+     * 2.20.1 - copies of the named documents, one entry per id, in order:
      * the resident copy, else the evicted copy (peekEvictedDocument), else
      * nullopt (deleted since the ids were listed). One shared lock per call.
+     * v2.21.0 - THROWS when a document is still evicted but its copy cannot
+     * be read: writing it as deleted would drop it from the snapshot.
      */
     [[nodiscard]] std::vector<std::optional<Document>> copyDocuments(
         const std::string& collection, const std::vector<std::string>& ids,
@@ -1345,8 +1360,28 @@ private:
     // 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.
+public:
     bool adoptFromDocStore(const std::string& collection, const std::string& id);
 
+    /**
+     * v2.21.0 - make LMDB agree with MemoryStore for the named rows
+     * ((qualified collection, id) pairs): a row MemoryStore holds (resident or
+     * evicted) is written to LMDB with its vector, a row it does not hold is
+     * deleted from LMDB with its vector. MemoryStore is NOT changed. Used for
+     * the rows of the mirror-pending log (MemoryStore is authoritative for
+     * them by construction) and for the "memory_only": "write" repair knob.
+     * Never throws; a row that fails is returned in `failed` (and bumps drift,
+     * which is correct: MemoryStore is ahead of LMDB for it).
+     */
+    struct MirrorRepairResult {
+        uint64_t written = 0;
+        uint64_t deleted = 0;
+        std::vector<std::pair<std::string, std::string>> failed;
+    };
+    MirrorRepairResult syncDocStoreFromMemory(
+        const std::vector<std::pair<std::string, std::string>>& rows);
+private:
+
     // 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
@@ -1528,6 +1563,7 @@ private:
     // unset, mirrorWriteToDocStore / mirrorVectorToDocStore are no-ops
     // (preserves test/bootstrap paths that don't wire LMDB).
     DocumentStoreResolver docStoreResolver_;
+    MirrorFailureSink mirrorFailureSink_;
 
     // v2.13.1 - the largest stored body (JSON text) a read can still send back;
     // 0 = no limit. Set by DatabaseService from the gRPC send limit.

+ 1 - 1
service/src/persistence/persistence_manager.cpp

@@ -704,7 +704,7 @@ std::string megabytes(uint64_t bytes) {
 }
 }  // namespace
 
-// 2.21.0 - make a snapshot that is not completing visible. On a production
+// 2.20.1 - make a snapshot that is not completing visible. On a production
 // instance the hourly snapshot was OOM-killed for three days: systemd restarted
 // the service each time, the journal recorded only status=9/KILL, the WAL was
 // never truncated, and recovery grew with it until boot itself no longer fit.

+ 14 - 16
service/src/persistence/snapshot.cpp

@@ -117,7 +117,7 @@ uint64_t nowMs() {
         std::chrono::system_clock::now().time_since_epoch()).count());
 }
 
-// 2.21.0 - the snapshot body, written to disk as it is produced. Before this
+// 2.20.1 - the snapshot body, written to disk as it is produced. Before this
 // the writer built the whole serialised store in one buffer, then a second
 // (compressed) buffer beside it, and copied every resident document of a
 // collection before serialising it: a peak of the working set plus roughly two
@@ -364,7 +364,7 @@ std::filesystem::path SnapshotManager::createSnapshot(const MemoryStore& store,
     }
 
     // v1.9.1 - release freelist pages after the snapshot write (the per-doc
-    // JSON text and batch copies; since 2.21.0 no whole-body buffer).
+    // JSON text and batch copies; since 2.20.1 no whole-body buffer).
     releaseFreelistPages();
 
     return snapshotPath;
@@ -476,7 +476,7 @@ uint64_t SnapshotManager::loadSnapshot(const std::filesystem::path& path, Memory
     } else {
         uncompressedData = std::move(bodyData);
     }
-    // 2.21.0 - the compressed body is not needed while deserializing.
+    // 2.20.1 - the compressed body is not needed while deserializing.
     std::vector<uint8_t>().swap(bodyData);
 
     // Clear store and deserialize
@@ -608,7 +608,7 @@ bool SnapshotManager::verifySnapshot(const std::filesystem::path& path) const {
             return false;
         }
 
-        // Read and verify the body a block at a time (2.21.0: it used to be
+        // Read and verify the body a block at a time (2.20.1: it used to be
         // read whole, a third copy of the store's size at the end of a write).
         std::vector<char> block(1 << 20);
         uint32_t calculatedBodyCrc = 0;
@@ -707,7 +707,7 @@ void SnapshotManager::serializeStore(const MemoryStore& store, Sink& out,
     docCount = 0;
     collCount = 0;
 
-    // 2.21.0 - documents are copied a batch at a time under the collection's
+    // 2.20.1 - documents are copied a batch at a time under the collection's
     // shared lock (MemoryStore::copyDocuments), never a whole collection.
     constexpr size_t kBatch = 256;
 
@@ -738,7 +738,6 @@ void SnapshotManager::serializeStore(const MemoryStore& store, Sink& out,
         out.u64(static_cast<uint64_t>(residentIds.size() + evictedIds.size()));
 
         uint64_t written = 0;
-        uint64_t evictedFailed = 0;
         auto writeDoc = [&](const std::optional<Document>& doc) {
             if (!doc) {
                 out.u32(0);
@@ -753,16 +752,15 @@ void SnapshotManager::serializeStore(const MemoryStore& store, Sink& out,
         for (size_t i = 0; i < residentIds.size(); i += kBatch) {
             for (const auto& doc : store.copyDocuments(name, residentIds, i, kBatch)) writeDoc(doc);
         }
-        for (const auto& id : evictedIds) {
-            if (!writeDoc(store.peekEvictedDocument(name, id))) ++evictedFailed;
-        }
-
-        if (evictedFailed > 0) {
-            spdlog::warn(
-                "Snapshot: {} evicted documents in collection '{}' could not "
-                "be loaded - they will be missing from the snapshot. "
-                "Likely a pre-v1.7.3 snapshot already lost them.",
-                evictedFailed, name);
+        // v2.21.0 - through copyDocuments too, not peekEvictedDocument: an id
+        // reloaded into memory since it was listed is copied from memory (it
+        // used to be written as absent and so dropped), and one whose evicted
+        // copy cannot be read THROWS, abandoning this snapshot so the WAL that
+        // holds it is kept. It used to be written as absent with a WARN, after
+        // which the WAL was truncated and the next boot came up without it
+        // while LMDB still had it.
+        for (size_t i = 0; i < evictedIds.size(); i += kBatch) {
+            for (const auto& doc : store.copyDocuments(name, evictedIds, i, kBatch)) writeDoc(doc);
         }
         docCount += written;
 

+ 4 - 4
service/src/persistence/snapshot.hpp

@@ -96,13 +96,13 @@ public:
         bool validateAfterWrite = true;
         bool cleanupOnlyIfVerified = true;
 
-        // 2.21.0: uncompressed bytes per LZ4 chunk. The writer streams one
+        // 2.20.1: uncompressed bytes per LZ4 chunk. The writer streams one
         // chunk at a time to disk, so this (plus its compressed copy) is the
         // writer's buffer, not the store's size. Tests lower it.
         size_t chunkBytes = 16 * 1024 * 1024;
     };
 
-    /// 2.21.0 - a snapshot that started and never finished (the process was
+    /// 2.20.1 - a snapshot that started and never finished (the process was
     /// killed while writing it: OOM, SIGKILL, power). Read at boot from the
     /// marker createSnapshot leaves while it runs.
     struct InterruptedSnapshot {
@@ -178,7 +178,7 @@ public:
     /// v2.17.0 - delete every snapshot except `keep` (the at-rest seal).
     size_t removeAllExcept(const std::filesystem::path& keep);
 
-    /// 2.21.0 - the snapshot that was in progress when the process last died,
+    /// 2.20.1 - the snapshot that was in progress when the process last died,
     /// if any. A process killed by the kernel cannot log its own death, so
     /// this is how the NEXT boot learns that snapshots are not completing
     /// (the marker stays until a snapshot completes, so every boot of a crash
@@ -206,7 +206,7 @@ private:
                                                    uint64_t uncompressedSize) const;
 
     /**
-     * Serialize store data into `sink`, a piece at a time (2.21.0: before,
+     * Serialize store data into `sink`, a piece at a time (2.20.1: before,
      * this returned the whole body as one buffer).
      */
     template <typename Sink>

+ 1 - 1
service/src/persistence/wal.hpp

@@ -241,7 +241,7 @@ namespace crc32 {
     uint32_t calculate(const std::string& str);
     // Continue a CRC over more bytes: extend(calculate(a), b) == calculate(a + b),
     // and extend(0, x) == calculate(x). Lets a writer checksum a body it never
-    // holds whole (the 2.21.0 streaming snapshot writer).
+    // holds whole (the 2.20.1 streaming snapshot writer).
     uint32_t extend(uint32_t crc, const void* data, size_t length);
 }
 

+ 112 - 0
service/src/storage/mirror_pending.hpp

@@ -0,0 +1,112 @@
+#pragma once
+
+// v2.21.0 - rows whose LMDB mirror write failed, kept DURABLY until a later
+// boot has re-mirrored them from MemoryStore.
+//
+// Why it has to exist: a write lands in MemoryStore and the WAL, then the
+// mirror copies it to LMDB. When that copy throws, applyDualWriteMirror logs,
+// bumps drift and flips health, so this process serves reads from MemoryStore
+// and stays correct. The next boot re-mirrors only what WAL replay touches, and
+// health starts clean. If an hourly snapshot has truncated the WAL in between,
+// nothing remembers the row: it stays in MemoryStore only (a failed put) or in
+// LMDB only (a failed delete) for good, and reads served from LMDB disagree
+// with writes. This file is that memory.
+//
+// For a row named here MemoryStore is AUTHORITATIVE, without guessing: the
+// write reached MemoryStore and the WAL and only the copy failed. So the boot
+// repair is unambiguous: present in MemoryStore -> write it to LMDB, absent ->
+// delete it from LMDB.
+//
+// Format: one JSON array ["<qualified collection>", "<id>"] per line, appended
+// and fdatasync'd before the failing write returns. Duplicates are harmless
+// (load() dedups); a torn last line (crash mid-append) is skipped.
+
+#include <fcntl.h>
+#include <unistd.h>
+
+#include <cstdio>
+#include <filesystem>
+#include <fstream>
+#include <mutex>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include <nlohmann/json.hpp>
+
+namespace smartbotic::db::storage {
+
+class MirrorPendingLog {
+public:
+    using Entry = std::pair<std::string, std::string>;   // qualified collection, id
+
+    explicit MirrorPendingLog(std::filesystem::path path) : path_(std::move(path)) {}
+
+    const std::filesystem::path& path() const noexcept { return path_; }
+
+    // Never throws: it runs inside a write path whose mirror already failed.
+    // Returns false when the record could not be made durable (the caller
+    // logs it; the row is then repairable only by the boot audit's knobs).
+    bool append(const std::string& collection, const std::string& id) noexcept {
+        try {
+            const std::string line = nlohmann::json::array({collection, id}).dump() + "\n";
+            std::lock_guard<std::mutex> lock(mutex_);
+            const int fd = ::open(path_.c_str(), O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);
+            if (fd < 0) return false;
+            bool ok = ::write(fd, line.data(), line.size()) == static_cast<ssize_t>(line.size());
+            ok = ok && ::fdatasync(fd) == 0;
+            ::close(fd);
+            return ok;
+        } catch (...) {
+            return false;
+        }
+    }
+
+    // Every distinct entry, in first-seen order.
+    std::vector<Entry> load() const {
+        std::vector<Entry> out;
+        std::set<Entry> seen;
+        std::lock_guard<std::mutex> lock(mutex_);
+        std::ifstream in(path_);
+        std::string line;
+        while (std::getline(in, line)) {
+            try {
+                auto j = nlohmann::json::parse(line);
+                if (!j.is_array() || j.size() != 2 || !j[0].is_string() || !j[1].is_string()) continue;
+                Entry e{j[0].get<std::string>(), j[1].get<std::string>()};
+                if (seen.insert(e).second) out.push_back(std::move(e));
+            } catch (...) {
+                continue;   // a torn last line
+            }
+        }
+        return out;
+    }
+
+    // Replace the file with `remaining` (write a temp file, fsync, rename).
+    // Empty removes it.
+    bool replace(const std::vector<Entry>& remaining) {
+        std::lock_guard<std::mutex> lock(mutex_);
+        std::error_code ec;
+        if (remaining.empty()) {
+            std::filesystem::remove(path_, ec);
+            return !ec;
+        }
+        const auto tmp = path_.string() + ".tmp";
+        {
+            std::ofstream out(tmp, std::ios::trunc);
+            for (const auto& [c, id] : remaining) out << nlohmann::json::array({c, id}).dump() << "\n";
+            if (!out) return false;
+        }
+        const int fd = ::open(tmp.c_str(), O_RDONLY | O_CLOEXEC);
+        if (fd >= 0) { ::fdatasync(fd); ::close(fd); }
+        std::filesystem::rename(tmp, path_, ec);
+        return !ec;
+    }
+
+private:
+    std::filesystem::path path_;
+    mutable std::mutex mutex_;
+};
+
+}  // namespace smartbotic::db::storage

+ 28 - 2
tests/load_test/test_disk_only_rows.cpp

@@ -5,7 +5,7 @@
 // test_disk_only_rows.sh plants such rows with the server stopped; this drives
 // a real client against them.
 //
-// Phases: seed | check | after
+// Phases: seed | check | after | knobs | removed (v2.21.0)
 
 #include <smartbotic/database/client.hpp>
 
@@ -31,6 +31,7 @@ int main(int argc, char** argv) {
         c.insert(C, {{"n", 1}, {"keep", "me"}}, "a1");
         c.insert(C, {{"n", 1}}, "b1");
         c.insert(C, {{"n", 1}}, "c1");
+        c.insert(C, {{"n", 1}}, "c2");
         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.
@@ -75,8 +76,33 @@ int main(int argc, char** argv) {
         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 if (phase == "knobs") {
+        ck(!c.get(C, "ghost5").has_value(), "knobs: disk_only=remove deleted ghost5");
+        ck(!c.get(C, "ghost6").has_value(), "knobs: the pending replay deleted ghost6 (memory never had it)");
+        ck(c.get(C, "c1").has_value() && c.get(C, "b1").has_value(),
+           "knobs: memory_only=write made c1 and b1 readable");
+        ck(c.get(C, "c2").has_value(), "knobs: the pending replay made c2 readable");
+    } else if (phase == "removed") {
+        ck(!c.get(C, "c1").has_value(), "removed: c1 is not readable");
+        bool inserted = false;
+        try {
+            c.insert(C, {{"n", 7}}, "c1");
+            inserted = true;
+        } catch (const std::exception& e) {
+            std::cerr << "insert threw: " << e.what() << "\n";
+        }
+        ck(inserted, "removed: memory_only=remove freed the id (an insert succeeds)");
+        bool dup = false;
+        try {
+            c.insert(C, {{"n", 8}}, "ghost7");
+        } catch (const Client::AlreadyExists&) {
+            dup = true;
+        }
+        ck(dup, "removed: ghost7, adopted at boot, is a duplicate for insert");
+        Client::Failure f;
+        ck(c.patch(C, "ghost7", {{"n", 9}}, f) == 2, "removed: ghost7 patches like an ordinary row");
     } else {
-        std::cerr << "usage: t seed|check|after\n";
+        std::cerr << "usage: t seed|check|after|knobs|removed\n";
         return 2;
     }
     std::cout << phase << ": " << pass << " passed, " << fail << " failed\n";

+ 50 - 2
tests/load_test/test_disk_only_rows.sh

@@ -15,6 +15,7 @@ PORT=9037
 ENV="$DIR/data/projects/default/env"
 rm -rf "$DIR"
 mkdir -p "$DIR/data"
+config() {   # $1 disk_only policy, $2 memory_only policy
 cat > "$DIR/config.json" <<CFG
 {
   "storage": {
@@ -23,10 +24,14 @@ cat > "$DIR/config.json" <<CFG
     "rpc_port": $PORT,
     "encryption": { "enabled": false },
     "migrations": { "enabled": false },
-    "replication": { "enabled": false }
+    "replication": { "enabled": false },
+    "consistency": { "disk_only": "$1", "memory_only": "$2" }
   }
 }
 CFG
+}
+# Boot 2 must NOT adopt at boot: it tests that each WRITE loads its row.
+config report report
 
 echo "=== building test binaries ==="
 g++ -std=c++20 -O1 -o "$DIR/t" test_disk_only_rows.cpp \
@@ -73,7 +78,50 @@ ck "boot 3: the written rows are no longer disk-only" \
 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
+
+# v2.21.0 - the knobs and the mirror-pending log. Planted with the server stopped:
+#   ghost5  on disk only            -> disk_only=remove deletes it from disk
+#   c1      deleted on disk only    -> memory_only=write writes it back (b1 too)
+#   c2      deleted on disk only, AND named in mirror-pending.log
+#           -> the replay writes it back, whatever the knobs say
+#   ghost6  on disk only, AND named in mirror-pending.log
+#           -> memory is authoritative for it: the replay deletes it from disk
+"$DIR/rowtool" "$ENV" ghosts copy a1 ghost5
+"$DIR/rowtool" "$ENV" ghosts copy a1 ghost6
+"$DIR/rowtool" "$ENV" ghosts del c1
+"$DIR/rowtool" "$ENV" ghosts del c2
+printf '["default:ghosts","c2"]\n["default:ghosts","ghost6"]\n' > "$DIR/data/mirror-pending.log"
+config remove write
+start 4
+ck "boot 4: the pending replay ran" "grep -q 'mirror-pending: repaired 2 row(s): 1 written, 1 deleted' '$DIR/server4.log'"
+ck "boot 4: the pending log is gone once repaired" "[[ ! -e '$DIR/data/mirror-pending.log' ]]"
+ck "boot 4: disk-only ghost5 removed from disk" \
+   "grep -q 'ghosts: 1 row(s) on disk but not in memory.* - removed from disk.*ids: ghost5' '$DIR/server4.log'"
+ck "boot 4: memory-only b1, c1 written to disk" \
+   "grep -q 'ghosts: 2 row(s) in memory but not on disk.* - written to disk.*ids: b1, c1' '$DIR/server4.log'"
+ck "boot 4: report file lists them" \
+   "grep -q '\"ghost5\"' '$DIR/data/consistency-report.json' && grep -q '\"memory_only\": 2' '$DIR/data/consistency-report.json'"
+client knobs || fails=$((fails+1))
+stop
+
+config adopt report
+start 5
+ck "boot 5: consistent after the repairs" "grep -q 'key audit: .* consistent' '$DIR/server5.log'"
+stop
+
+# memory_only=remove: a row deleted on disk only is deleted from memory too.
+"$DIR/rowtool" "$ENV" ghosts del c1
+# disk_only=adopt (the default): a disk-only row is loaded at boot.
+"$DIR/rowtool" "$ENV" ghosts copy a1 ghost7
+config adopt remove
+start 6
+ck "boot 6: disk-only ghost7 adopted at boot" \
+   "grep -q 'ghosts: 1 row(s) on disk but not in memory.* - adopted into memory.*ids: ghost7' '$DIR/server6.log' && grep -q '1 adopted' '$DIR/server6.log'"
+ck "boot 6: memory-only c1 removed from memory" \
+   "grep -q 'ghosts: 1 row(s) in memory but not on disk.* - removed from memory.*ids: c1' '$DIR/server6.log'"
+client removed || fails=$((fails+1))
+grep -h 'key audit: [0-9]' "$DIR"/server*.log || true
 stop
 
 [[ $fails -eq 0 ]] && echo "OK - disk-only rows e2e passed" || echo "FAILED ($fails)"

+ 61 - 0
tests/load_test/test_snapshot_keeps_evicted.cpp

@@ -0,0 +1,61 @@
+// v2.21.0 - a document that stays evicted across two snapshots must still be in
+// the second. The evicted copy used to be read back only from the WAL, which
+// the first snapshot truncates, so the second wrote it as absent and the next
+// boot came up without it while LMDB kept it (7,219 rows on one production
+// instance, found by the 2.20.2 boot key audit).
+//
+// Phases: seed (insert, wait for eviction) | check (after a restart)
+
+#include <smartbotic/database/client.hpp>
+
+#include <chrono>
+#include <iostream>
+#include <string>
+#include <thread>
+
+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"; }
+}
+// 600 x 200 KB is ~120 MB of WAL: past the 100 MB file size, so the WAL
+// rotates and the snapshot after it deletes the first file - the state in which
+// an evicted row could no longer be read back from the WAL.
+static constexpr int kRows = 600;
+
+static uint64_t statFor(Client& c, bool evicted) {
+    const auto s = c.getMemoryStats();
+    for (const auto& cs : s.collections) {
+        if (cs.collection == "default:kept") return evicted ? cs.evictedStubCount : cs.documentCount;
+    }
+    return 0;
+}
+
+int main(int argc, char** argv) {
+    const std::string phase = argc > 1 ? argv[1] : "";
+    Client::Config cfg;
+    cfg.address = "127.0.0.1:9038";
+    cfg.writeRetries = 0;
+    Client c(cfg);
+    c.connect();
+
+    if (phase == "seed") {
+        for (int i = 0; i < kRows; ++i) {
+            c.insert("kept", {{"i", i}, {"pad", std::string(200000, 'x')}}, "k" + std::to_string(i));
+        }
+        uint64_t evicted = 0;
+        for (int t = 0; t < 100 && evicted == 0; ++t) {
+            std::this_thread::sleep_for(std::chrono::milliseconds(200));
+            evicted = statFor(c, true);
+        }
+        std::cout << "evicted stubs: " << evicted << "\n";
+        ck(evicted > 0, "seed: eviction really happened (else the test proves nothing)");
+    } else if (phase == "check") {
+        ck(statFor(c, false) == kRows, "check: every row is back in memory after the restart");
+        ck(c.count("kept") == kRows, "check: every row readable");
+    } else {
+        return 2;
+    }
+    std::cout << phase << ": " << pass << " passed, " << fail << " failed\n";
+    return fail == 0 ? 0 : 1;
+}

+ 82 - 0
tests/load_test/test_snapshot_keeps_evicted.sh

@@ -0,0 +1,82 @@
+#!/usr/bin/env bash
+# v2.21.0 e2e - rows evicted across two snapshots survive a restart (the
+# snapshot reads an evicted row's copy from LMDB, not only from the WAL).
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+cd "$SCRIPT_DIR"
+
+DIR=/tmp/sbdb-snapshot-keeps-evicted
+PORT=9038
+rm -rf "$DIR"
+mkdir -p "$DIR/data"
+config() {   # $1 max_memory_mb
+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 },
+    "consistency": { "disk_only": "report" },
+    "persistence": { "snapshot_interval_sec": 2 },
+    "memory": {
+      "max_memory_mb": $1,
+      "eviction_threshold_percent": 50,
+      "eviction_target_percent": 20,
+      "eviction_check_interval_ms": 200,
+      "hot_write_floor_ms": 0,
+      "memory_soft_percent": 50,
+      "memory_hard_percent": 2000,
+      "memory_emergency_percent": 4000
+    }
+  }
+}
+CFG
+}
+
+g++ -std=c++20 -O1 -o "$DIR/t" test_snapshot_keeps_evicted.cpp \
+    -I"$ROOT/client/include" -I"$ROOT/build/client" \
+    -L"$ROOT/build/client" -lsmartbotic-db-client -lspdlog -lfmt -pthread
+
+SERVER_PID=""
+trap '[[ -n "$SERVER_PID" ]] && kill $SERVER_PID 2>/dev/null; wait 2>/dev/null || true' EXIT
+start() {
+    "${SERVER_BIN:-$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; }
+
+config 1
+start 1
+client seed || fails=$((fails+1))
+# Two snapshots after eviction: the first truncates the WAL, the second must
+# still find every evicted row.
+base=$(grep -c "Created snapshot" "$DIR/server1.log" || true)
+for _ in $(seq 1 60); do
+    [[ $(grep -c "Created snapshot" "$DIR/server1.log" || true) -ge $((base + 2)) ]] && break
+    sleep 0.5
+done
+ck "two snapshots taken while rows were evicted" \
+   "[[ \$(grep -c 'Created snapshot' '$DIR/server1.log') -ge $((base + 2)) ]]"
+ck "no snapshot reported rows it could not load" "! grep -q 'could not be read for the snapshot\|will be missing from the snapshot' '$DIR/server1.log'"
+stop
+
+config 512
+start 2
+ck "boot 2: key audit finds nothing on disk only" "grep -q 'key audit: .* consistent' '$DIR/server2.log'"
+client check || fails=$((fails+1))
+grep -h "Recovery complete\|key audit: [0-9]" "$DIR/server2.log" || true
+stop
+
+[[ $fails -eq 0 ]] && echo "OK - snapshot keeps evicted rows" || echo "FAILED ($fails)"
+exit $(( fails > 0 ))

+ 81 - 0
tests/test_dual_write_mirror.cpp

@@ -27,6 +27,8 @@
 #include "storage/document_store_lmdb.hpp"
 #include "storage/dual_write_mirror.hpp"
 #include "storage/lmdb_env.hpp"
+#include "storage/mirror_pending.hpp"
+#include <fstream>
 
 namespace fs = std::filesystem;
 
@@ -602,6 +604,82 @@ void test_lmdb_only_rows_are_writable() {
     check(healthy.load() && drift.load() == 0, "lmdb-only: clean");
 }
 
+// v2.21.0 - the durable record of rows whose LMDB copy failed.
+void test_mirror_pending_log() {
+    using smartbotic::db::storage::MirrorPendingLog;
+    const std::string path = make_tmpdir("pending") + ".log";
+    MirrorPendingLog log(path);
+    check(log.load().empty(), "pending: absent file loads empty");
+    check(log.append("p:c", "a") && log.append("p:c", "b") && log.append("p:c", "a"),
+          "pending: appends succeed");
+    check(log.append("p:c", "tab\tand\nnewline"), "pending: an id with control characters appends");
+    { std::ofstream(path, std::ios::app) << "[\"p:c\", \"torn"; }   // a crash mid-append
+    auto rows = log.load();
+    check(rows.size() == 3 && rows[0].second == "a" && rows[1].second == "b" &&
+          rows[2].second == "tab\tand\nnewline",
+          "pending: load dedups, keeps first-seen order, survives a torn last line");
+    check(log.replace({{"p:c", "b"}}) && log.load().size() == 1, "pending: replace keeps only what failed");
+    check(log.replace({}) && !fs::exists(path), "pending: replace with nothing removes the file");
+}
+
+// v2.21.0 - a failed mirror write reaches the sink with the qualified name.
+void test_mirror_failure_reaches_the_sink() {
+    ThrowingStore throwing;
+    std::atomic<bool> healthy{true};
+    std::atomic<uint64_t> drift{0};
+    MemoryStore::Config cfg;
+    cfg.nodeId = "test-node";
+    MemoryStore mem(cfg);
+    mem.setDocumentStoreMirror([&throwing](std::string_view) { return &throwing; }, &healthy, &drift);
+    std::vector<std::pair<std::string, std::string>> sunk;
+    mem.setMirrorFailureSink([&](const std::string& c, const std::string& id) { sunk.emplace_back(c, id); });
+    mem.createCollection("proj:things", {});
+    mem.insert("proj:things", make_doc("x1", "proj:things", {{"n", 1}}));
+    check(!healthy.load() && drift.load() > 0, "sink: the mirror really failed");
+    check(!sunk.empty() && sunk.front() == std::make_pair(std::string("proj:things"), std::string("x1")),
+          "sink: the failed row is reported with its qualified collection");
+    // A write after the failure fails too (the store is still broken) and is reported too.
+    sunk.clear();
+    mem.remove("proj:things", "x1");
+    check(!sunk.empty() && sunk.back().second == "x1", "sink: a failed delete is reported");
+}
+
+// v2.21.0 - LMDB brought in line with memory for named rows: write what
+// memory holds (with its vector), delete what it does not.
+void test_sync_doc_store_from_memory() {
+    TmpEnv tmp("sync");
+    LmdbDocumentStore doc_store(tmp.env);
+    std::atomic<bool> healthy{true};
+    std::atomic<uint64_t> drift{0};
+    MemoryStore::Config cfg;
+    cfg.nodeId = "test-node";
+    MemoryStore mem(cfg);
+    mem.setDocumentStoreMirror([&doc_store](std::string_view) { return &doc_store; }, &healthy, &drift);
+    smartbotic::database::CollectionOptions vopts;
+    vopts.vectorDimension = 4;
+    mem.createCollection("proj:emb", vopts);
+
+    // memory only: loadDocument never mirrors (the state a failed put leaves)
+    Document m = make_doc("m", "proj:emb", {{"n", 1}});
+    m.hasVector = true;
+    mem.loadDocument("proj:emb", m);
+    mem.loadVector("proj:emb", "m", {1.f, 2.f, 3.f, 4.f});
+    // disk only: what a failed delete leaves
+    doc_store.put("emb", "d", make_doc("d", "emb", {{"n", 2}}));
+    doc_store.put_vector("emb", "d", {4.f, 3.f, 2.f, 1.f});
+    check(!doc_store.get("emb", "m") && doc_store.get("emb", "d"), "sync: the two diverged rows are planted");
+
+    auto r = mem.syncDocStoreFromMemory({{"proj:emb", "m"}, {"proj:emb", "d"}, {"_sys", "x"}});
+    check(r.written == 1 && r.deleted == 1 && r.failed.empty(), "sync: one written, one deleted, none failed");
+    auto onDisk = doc_store.get("emb", "m");
+    check(onDisk && onDisk->data()["n"] == 1, "sync: the memory row is now on disk");
+    auto v = doc_store.get_vector("emb", "m");
+    check(v && v->size() == 4 && (*v)[0] == 1.f, "sync: with its vector");
+    check(!doc_store.get("emb", "d") && !doc_store.get_vector("emb", "d"),
+          "sync: the disk-only row and its vector are gone");
+    check(mem.get("proj:emb", "m") && !mem.get("proj:emb", "d"), "sync: memory is unchanged");
+}
+
 // Simulates DatabaseService::backfillIntoDocStore — populate MemoryStore
 // without a persist callback (no live mirror), then walk listCollections +
 // getAllDocuments and feed each doc into applyDualWriteMirror with
@@ -718,6 +796,9 @@ int main() {
     test_vector_mirror_via_memory_store();
     test_patch_stamps_unmarked_rows();
     test_lmdb_only_rows_are_writable();
+    test_mirror_pending_log();
+    test_mirror_failure_reaches_the_sink();
+    test_sync_doc_store_from_memory();
     test_backfill_iteration_pattern();
     test_scan_vectors_round_trip();
 

+ 55 - 0
tests/test_snapshot_durability.cpp

@@ -771,6 +771,60 @@ void test_interrupted_snapshot_marker() {
     std::cout << "PASS: an interrupted snapshot is reported until one completes\n";
 }
 
+// v2.21.0 - an evicted document whose copy cannot be read must FAIL the
+// snapshot, not be written as deleted. Written as deleted, it drops out of the
+// snapshot, the WAL holding it is truncated, and the next boot comes up without
+// it while LMDB keeps it: a disk-only row (one path to the production "ghost").
+void test_unreadable_evicted_document_fails_the_snapshot() {
+    auto dir = makeSnapshotDir("unreadable-evicted");
+    MemoryStore::Config storeCfg;
+    storeCfg.nodeId = "test";
+    storeCfg.maxMemoryBytes = 32ULL * 1024;
+    storeCfg.evictionThresholdPercent = 50;
+    storeCfg.evictionTargetPercent = 30;
+    storeCfg.hotWriteFloorMs = 0;
+    storeCfg.evictionChunkSize = 1000;
+    MemoryStore store(storeCfg);
+    store.start();
+    store.createCollection("docs", CollectionOptions{});
+    // Every evicted copy is unreadable.
+    store.setDocumentLoadCallback([](const std::string&, const std::string&, uint64_t)
+                                      -> std::optional<Document> { return std::nullopt; });
+    for (int i = 0; i < 100; ++i) {
+        Document d = makeDoc("doc-" + std::to_string(i));
+        auto tree = d.data();
+        tree["padding"] = std::string(300, 'x');
+        d.set_data(tree);
+        store.insert("docs", d);
+    }
+    store.evictDocuments();
+    const auto evicted = store.getEvictedDocumentIds("docs");
+    assert(!evicted.empty());
+
+    bool threw = false;
+    try {
+        (void)store.copyDocuments("docs", evicted, 0, evicted.size());
+    } catch (const std::runtime_error&) {
+        threw = true;
+    }
+    assert(threw && "copyDocuments must throw for an evicted document it cannot read");
+
+    SnapshotManager::Config scfg;
+    scfg.snapshotDir = dir;
+    SnapshotManager mgr(scfg);
+    bool snapFailed = false;
+    try {
+        mgr.createSnapshot(store, 7);
+    } catch (const std::exception&) {
+        snapFailed = true;
+    }
+    assert(snapFailed && "the snapshot must fail rather than omit the document");
+    assert(mgr.listSnapshots().empty() && "no snapshot file may be left behind");
+    store.stop();
+    fs::remove_all(dir);
+    std::cout << "PASS: an unreadable evicted document fails the snapshot instead of dropping out\n";
+}
+
 int main() {
     test_atomic_write_leaves_no_tmp();
     test_snapshot_round_trip();
@@ -785,6 +839,7 @@ int main() {
     test_streaming_snapshot_memory_is_bounded();
     test_streaming_snapshot_small_chunks_round_trip();
     test_interrupted_snapshot_marker();
+    test_unreadable_evicted_document_fails_the_snapshot();
     std::cout << "\nAll snapshot durability tests PASSED!\n";
     return 0;
 }

برخی فایل ها در این مقایسه diff نمایش داده نمی شوند زیرا تعداد فایل ها بسیار زیاد است