Bladeren bron

fix: snapshots stall on evicted system rows; stale memory after replay; tmp race

- eviction never takes a system (_) collection: they are not mirrored, so an
  evicted row's only other copy was the WAL and every snapshot after one
  truncation failed (the WAL grew for 15 days on one production instance)
- boot version audit: resident rows older than LMDB's copy are reloaded from
  LMDB; a patch on such a row reverted every field changed since
- listSnapshots() no longer deletes snapshot .tmp files: a listing (GetStats,
  retention) during a write killed that snapshot; orphans go at recovery
- WAL replay extends the systemd start timeout and reports each file
  (applied, unreadable with checksum split, out of order, bytes read)

Tests: test_snapshot_keeps_evicted (configs), test_stale_memory (new),
test_snapshot_durability (+1). Each fix reverted fails its test.
fszontagh 1 week geleden
bovenliggende
commit
87980f53b6

+ 42 - 0
CHANGELOG.md

@@ -13,6 +13,48 @@ consumer-facing usage is in `docs/integration-guide.md`.
 ## Unreleased
 
 ### Fixed
+- **[server]** ⚠ Snapshots stopped completing for good once eviction had
+  moved a row of a system collection (`_collection_meta`, `_views`, ...) out of
+  memory. System collections are not mirrored to LMDB, so the snapshot could
+  read such a row back only from the WAL; after one snapshot truncated the WAL,
+  every later one failed ("evicted document '_collection_meta/...' could not
+  be read for the snapshot"), the WAL was never truncated again and recovery
+  grew with it (15 days, 276 MB, on one production instance). Before 2.21.0
+  the same row was instead written to the snapshot as absent, so the next boot
+  lost that collection's config. System collections are no longer evicted
+  (they hold small metadata). A server already in this state recovers at the
+  restart into this version: the rows come back from the last good snapshot
+  and stay resident, and the first snapshot completes.
+- **[server]** WAL replay now extends systemd's start timeout every 20,000
+  entries, and again before the post-replay LMDB re-mirror; recovery logs
+  `WAL replay: N entries applied`. Before, a replay longer than 10 minutes was
+  killed and restarted from the beginning, a loop that never booted.
+- **[server]** A snapshot could be killed by anything that listed snapshots
+  while it was being written: the listing removed every `snapshot-*.tmp`,
+  including the one in progress ("Failed to reopen snapshot tmp for fsync").
+  `GetStats` and the retention pass list snapshots. Orphaned `.tmp` files
+  (left only by a killed process; a failed write removes its own) are now
+  removed once, during recovery. This is probably also the 2.21.1 "verification
+  failed after write" pair that was put down to two concurrent snapshots.
+- **[server]** ⚠ After an incomplete WAL replay, memory kept older versions
+  of rows LMDB had newer copies of, and nothing noticed. Reads (served from
+  LMDB) were right. But a `patch` or `increment` merged into memory's old body
+  and wrote it over LMDB's newer row, silently reverting every field changed
+  since. `updateIfVersion` compared against memory's older version. History
+  and the next snapshot took the old version, which made it permanent. Found
+  on a production boot that applied 193,776 of the 354,089 entries above its
+  snapshot (cause under investigation). New boot step "memory/disk version
+  audit": every resident row of a mirrored collection whose `_version` or
+  `_updated_at` differs from LMDB's is reloaded from LMDB (no history, WAL or
+  event). It runs only while the mirror is healthy with no drift, and after
+  the re-mirror pass and the mirror-pending replay have written to LMDB every
+  row for which memory is authoritative. Logged per collection (WARN), with a
+  summary.
+- **[server]** WAL replay reports each file: entries applied, already in the
+  snapshot, unreadable (checksum), the sequence range read, and bytes read
+  against the file size. WARN when a file's header is unreadable, an entry
+  fails its checksum, or the file ends early. Before, all three were skipped
+  without a trace.
 - **[docs]** The 2.21.3 guide said the server's `malloc_trim` returns
   released vector memory to the system. The packaged server uses jemalloc, so
   memory goes back through jemalloc's background purge, which the systemd

+ 104 - 0
service/src/database_service.cpp

@@ -249,6 +249,11 @@ bool DatabaseService::initialize() {
         // Must be after applyRelationDeclarations() AND
         // applyIndexDeclarations(); backfillIntoDocStore() below already sits
         // at this point for the same reason. Never throws.
+#ifdef HAVE_SYSTEMD
+        // v2.21.4 - after a long replay this pass covers every id it touched.
+        sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
+        sd_notify(0, "STATUS=Re-mirroring replayed documents to LMDB");
+#endif
         persistence_->runPendingRemirror(*store_, recovery_outcome_);
 
         // Run migrations if enabled
@@ -284,6 +289,8 @@ bool DatabaseService::initialize() {
         // before 2.20.2 not writable), and the reverse. Read-only, advisory.
         spdlog::info("Boot: mirror-pending replay");
         replayMirrorPending();
+        spdlog::info("Boot: memory/disk version audit");
+        repairStaleResidentRows();
         spdlog::info("Boot: memory/disk key audit");
         auditMemoryDiskKeys();
 
@@ -1087,6 +1094,103 @@ void DatabaseService::replayMirrorPending() {
     }
 }
 
+// v2.21.4 - a production boot replayed 193,776 of the 354,089 WAL entries
+// above its snapshot (cause under investigation; the per-file replay lines
+// now show where entries go). LMDB had every write, because each one was
+// mirrored at write time, so reads were right; MemoryStore kept the snapshot's
+// older version of every row written in the gap, and MemoryStore is the base
+// of a patch (old fields + the patch, mirrored over LMDB's newer row), of
+// updateIfVersion's check, of history and of the next snapshot - which then
+// made the old version permanent. The key audit compares ids only, so it saw
+// nothing.
+//
+// LMDB is authoritative here: the re-mirror pass and the mirror-pending replay
+// have already written to LMDB every row for which memory is authoritative
+// (rows the replay applied, rows whose LMDB copy failed), so a difference that
+// remains means memory is behind. Runs before the listener starts (no writer
+// races it) and only while the mirror is healthy with zero drift. Reads every
+// resident row of every mirrored collection from LMDB once.
+uint64_t DatabaseService::repairStaleResidentRows() {
+    if (!projects_ || !store_) return 0;
+    if (!mirror_healthy_.load(std::memory_order_relaxed) ||
+        mirror_drift_count_.load(std::memory_order_relaxed) != 0) {
+        spdlog::warn("version audit: skipped (the LMDB mirror is unhealthy or has drift, so "
+                     "LMDB may be behind memory)");
+        return 0;
+    }
+    namespace sd = smartbotic::database;
+    const auto started = std::chrono::steady_clock::now();
+    uint64_t checked = 0, reloaded = 0, failed = 0;
+    constexpr size_t kBatch = 256;
+
+    for (const auto& name : store_->listCollections()) {
+        sd::ResolvedCollection rc;
+        try {
+            rc = sd::resolveCollection(name);
+        } catch (const std::exception&) {
+            continue;
+        }
+        if (rc.collection.empty() || rc.collection.front() == '_') continue;
+        auto* ds = docStore(rc.project);
+        if (!ds) continue;
+
+        const auto ids = store_->getDocumentIds(name);
+        std::vector<std::string> stale;
+        for (size_t from = 0; from < ids.size(); from += kBatch) {
+            const auto mem = store_->copyDocuments(name, ids, from, kBatch);
+            for (size_t k = 0; k < mem.size(); ++k) {
+                if (!mem[k]) continue;   // deleted meanwhile
+                ++checked;
+                std::optional<Document> disk;
+                try {
+                    disk = ds->get(rc.collection, ids[from + k]);
+                } catch (const std::exception& e) {
+                    ++failed;
+                    spdlog::warn("version audit: {}/{}: LMDB read failed: {}",
+                                 name, ids[from + k], e.what());
+                    continue;
+                }
+                if (!disk) continue;   // memory only: the key audit reports it
+                if (disk->version != mem[k]->version || disk->updatedAt != mem[k]->updatedAt) {
+                    stale.push_back(ids[from + k]);
+                }
+            }
+        }
+        if (stale.empty()) continue;
+
+        uint64_t done = 0;
+        for (const auto& id : stale) {
+            try {
+                // A reload, not a write: no history entry, no WAL, no event.
+                MemoryStore::HistorySuppression noHistory(*store_);
+                if (store_->unloadDocument(name, id) && store_->adoptFromDocStore(name, id, true)) {
+                    ++done;
+                } else {
+                    ++failed;
+                }
+            } catch (const std::exception& e) {
+                ++failed;
+                spdlog::warn("version audit: {}/{}: reload failed: {}", name, id, e.what());
+            }
+        }
+        reloaded += done;
+        std::string sample;
+        for (size_t i = 0; i < stale.size() && i < 10; ++i) sample += (i ? ", " : "") + stale[i];
+        spdlog::warn("version audit: {}: {} resident row(s) were older than LMDB's copy, "
+                     "{} reloaded from LMDB (e.g. {})", name, stale.size(), done, sample);
+    }
+
+    const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
+                        std::chrono::steady_clock::now() - started).count();
+    if (reloaded > 0 || failed > 0) {
+        spdlog::warn("version audit: {} resident row(s) checked, {} reloaded from LMDB, "
+                     "{} failed ({} ms)", checked, reloaded, failed, ms);
+    } else {
+        spdlog::info("version audit: {} resident row(s) agree with LMDB ({} ms)", checked, ms);
+    }
+    return reloaded;
+}
+
 void DatabaseService::auditMemoryDiskKeys() {
     if (!projects_ || !store_) return;
     namespace sd = smartbotic::database;

+ 4 - 0
service/src/database_service.hpp

@@ -381,6 +381,10 @@ 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.4 - reload from LMDB every resident row whose _version or
+    // _updated_at differs from LMDB's (memory left behind by an incomplete
+    // WAL replay). Returns the number of rows reloaded.
+    uint64_t repairStaleResidentRows();
     // 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);

+ 17 - 2
service/src/memory_store.cpp

@@ -32,6 +32,14 @@
 
 namespace smartbotic::database {
 
+namespace {
+// `_collection_meta`, `_views`, ... (global) - never mirrored to LMDB.
+bool isSystemCollectionName(const std::string& name) {
+    const auto pc = parseProjectCollection(name);
+    return !pc.collection.empty() && pc.collection.front() == '_';
+}
+}  // namespace
+
 const char* memoryPressureToString(MemoryPressure p) {
     switch (p) {
         case MemoryPressure::Normal:    return "normal";
@@ -4626,6 +4634,13 @@ uint64_t MemoryStore::evictOneChunk() {
         std::shared_lock<std::shared_mutex> glock(globalMutex_);
         for (const auto& [collName, collPtr] : collections_) {
             if (collPtr->options.pinned) continue;  // never evict pinned collections
+            // v2.21.4 - nor a system collection. It is never mirrored to LMDB,
+            // so an evicted row's only other copy is the WAL, and once a
+            // snapshot truncated that, every later snapshot failed on the row
+            // and the WAL grew without bound (15 days on one production
+            // instance; before 2.21.0 the snapshot wrote the row as absent and
+            // the next boot lost the collection's config). They are small.
+            if (isSystemCollectionName(collName)) continue;
 
             std::shared_lock<std::shared_mutex> clock(collPtr->mutex);
             candidates.reserve(candidates.size() + collPtr->documents.size());
@@ -4792,8 +4807,8 @@ std::vector<std::pair<std::string, std::string>> MemoryStore::selectDocumentsFor
         std::shared_lock<std::shared_mutex> globalLock(globalMutex_);
 
         for (const auto& [collName, coll] : collections_) {
-            // Skip pinned collections
-            if (coll->options.pinned) {
+            // Skip pinned and system collections (see getEvictionCandidates)
+            if (coll->options.pinned || isSystemCollectionName(collName)) {
                 continue;
             }
 

+ 34 - 0
service/src/persistence/persistence_manager.cpp

@@ -1,6 +1,9 @@
 #include "persistence_manager.hpp"
 
 #include <spdlog/spdlog.h>
+#ifdef HAVE_SYSTEMD
+#include <systemd/sd-daemon.h>
+#endif
 
 #include <optional>
 #include <stdexcept>
@@ -178,6 +181,7 @@ RecoveryOutcome PersistenceManager::recover(MemoryStore& store) {
         currentStore_ = &store;
     }
 
+    snapshotMgr_->removeOrphanedTmpFiles();   // before the snapshot thread starts
     auto snapshots = snapshotMgr_->listSnapshots();
     outcome.snapshotsAvailable = snapshots.size();
     reportSnapshotHealthAtBoot(snapshots);
@@ -253,8 +257,21 @@ RecoveryOutcome PersistenceManager::recover(MemoryStore& store) {
         // v2.21.1 - replay records no history: each replayed write appended
         // its version when it was first made (see MemoryStore::HistorySuppression).
         MemoryStore::HistorySuppression noHistory(store);
+        // v2.21.4 - a replay outlasting the 10-minute start allowance was
+        // killed by systemd and started over at the next restart: a loop that
+        // never boots. A stalled snapshot leaves a WAL of hundreds of
+        // thousands of entries (~324,000 on one production instance, ~5 min).
+        uint64_t applied = 0;
         uint64_t replayed = wal_->replay(fromSequence, [&](const WalEntry& entry) {
             applyWalEntry(store, entry);
+            if (++applied % 20000 == 0) {
+#ifdef HAVE_SYSTEMD
+                sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
+                sd_notify(0, ("STATUS=Replaying the WAL: " + std::to_string(applied) +
+                              " entries").c_str());
+#endif
+                spdlog::info("WAL replay: {} entries applied", applied);
+            }
             const std::string key = entry.collection + "\x1f" + entry.documentId;
             if (entry.opType == WalOpType::INSERT || entry.opType == WalOpType::UPDATE ||
                 entry.opType == WalOpType::UPSERT) {
@@ -273,6 +290,23 @@ RecoveryOutcome PersistenceManager::recover(MemoryStore& store) {
         });
         outcome.walEntriesReplayed = replayed;
         spdlog::info("Replayed {} WAL entries from sequence {}", replayed, fromSequence);
+        // v2.21.4 - per file, so a replay can be checked against the sequence
+        // range the file names and the WAL's final sequence imply.
+        for (const auto& f : wal_->lastReplayStats()) {
+            const bool endedEarly = f.headerReadable && f.bytesRead < f.fileBytes;
+            const bool suspect = !f.headerReadable || f.unreadable > 0 || endedEarly ||
+                                 f.outOfOrder > 0;
+            const std::string line = fmt::format(
+                "WAL file {}: {} applied, {} already in the snapshot, {} unreadable "
+                "({} checksum, first at byte {}), {} out of sequence order, "
+                "sequences {}-{}, read {} of {} bytes{}",
+                f.path.filename().string(), f.applied, f.atOrBelow, f.unreadable,
+                f.checksumFailures, f.firstUnreadableOffset, f.outOfOrder,
+                f.firstSequence, f.lastSequence, f.bytesRead, f.fileBytes,
+                !f.headerReadable ? " (HEADER UNREADABLE, file skipped)"
+                : endedEarly      ? " (ended early: a torn or zeroed record)" : "");
+            if (suspect) spdlog::warn("{}", line); else spdlog::info("{}", line);
+        }
 
         std::vector<std::pair<std::string, std::string>> toRemirror;
         toRemirror.reserve(touched.size());

+ 20 - 15
service/src/persistence/snapshot.cpp

@@ -494,23 +494,28 @@ uint64_t SnapshotManager::loadSnapshot(const std::filesystem::path& path, Memory
     return header.walSequence;
 }
 
-std::vector<std::filesystem::path> SnapshotManager::listSnapshots() const {
-    std::vector<std::pair<uint64_t, std::filesystem::path>> snapshots;
-
-    // Clean up .tmp files left from crashed writes (they start with "snapshot-" and end with ".tmp")
-    {
-        std::error_code scan_ec;
-        for (const auto& entry : std::filesystem::directory_iterator(config_.snapshotDir, scan_ec)) {
-            if (!entry.is_regular_file()) continue;
-            const auto& p = entry.path();
-            if (p.extension() == ".tmp" &&
-                p.filename().string().starts_with("snapshot-")) {
-                std::error_code rm_ec;
-                std::filesystem::remove(p, rm_ec);
-                spdlog::info("Removed orphaned snapshot tmp file: {}", p.string());
-            }
+// v2.21.4 - this used to run inside listSnapshots(), which GetStats and the
+// retention pass also call, so a listing while a snapshot was being written
+// deleted that snapshot's own .tmp and it failed ("Failed to reopen snapshot
+// tmp for fsync"). A failed write removes its own .tmp, so the only orphan is
+// one a killed process left: recovery removes those, before the snapshot
+// thread starts.
+void SnapshotManager::removeOrphanedTmpFiles() const {
+    std::error_code scan_ec;
+    for (const auto& entry : std::filesystem::directory_iterator(config_.snapshotDir, scan_ec)) {
+        if (!entry.is_regular_file()) continue;
+        const auto& p = entry.path();
+        if (p.extension() == ".tmp" &&
+            p.filename().string().starts_with("snapshot-")) {
+            std::error_code rm_ec;
+            std::filesystem::remove(p, rm_ec);
+            spdlog::info("Removed orphaned snapshot tmp file: {}", p.string());
         }
     }
+}
+
+std::vector<std::filesystem::path> SnapshotManager::listSnapshots() const {
+    std::vector<std::pair<uint64_t, std::filesystem::path>> snapshots;
 
     std::error_code ec;
     for (const auto& entry : std::filesystem::directory_iterator(config_.snapshotDir, ec)) {

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

@@ -160,6 +160,10 @@ public:
      */
     [[nodiscard]] std::vector<std::filesystem::path> listSnapshots() const;
 
+    /** Remove snapshot .tmp files a killed process left. Boot only: a snapshot
+     *  in progress owns its .tmp. */
+    void removeOrphanedTmpFiles() const;
+
     /**
      * Get info about a snapshot file.
      */

+ 42 - 3
service/src/persistence/wal.cpp

@@ -474,14 +474,25 @@ void WriteAheadLog::sync() {
 uint64_t WriteAheadLog::replay(uint64_t fromSequence, std::function<void(const WalEntry&)> callback) {
     auto walFiles = getWalFiles();
     uint64_t count = 0;
+    std::vector<ReplayFileStats> all;
 
     for (const auto& file : walFiles) {
-        count += replayFile(file, fromSequence, callback);
+        ReplayFileStats stats;
+        stats.path = file;
+        count += replayFile(file, fromSequence, callback, stats);
+        all.push_back(std::move(stats));
     }
 
+    std::lock_guard<std::mutex> lock(replayStatsMutex_);
+    lastReplayStats_ = std::move(all);
     return count;
 }
 
+std::vector<WriteAheadLog::ReplayFileStats> WriteAheadLog::lastReplayStats() const {
+    std::lock_guard<std::mutex> lock(replayStatsMutex_);
+    return lastReplayStats_;
+}
+
 uint64_t WriteAheadLog::totalSizeBytes() const {
     uint64_t total = 0;
     auto walFiles = getWalFiles();
@@ -709,16 +720,22 @@ void WriteAheadLog::writeHeader() {
 }
 
 uint64_t WriteAheadLog::replayFile(const std::filesystem::path& path, uint64_t fromSequence,
-                                    const std::function<void(const WalEntry&)>& callback) {
+                                    const std::function<void(const WalEntry&)>& callback,
+                                    ReplayFileStats& stats) {
+    std::error_code size_ec;
+    stats.fileBytes = std::filesystem::file_size(path, size_ec);
     std::ifstream file(path, std::ios::binary);
     if (!file) {
+        stats.headerReadable = false;
         return 0;
     }
 
     auto header = readHeader(file);
     if (!header) {
+        stats.headerReadable = false;
         return 0;
     }
+    stats.bytesRead = static_cast<uint64_t>(file.tellg());
 
     uint64_t count = 0;
 
@@ -733,15 +750,37 @@ uint64_t WriteAheadLog::replayFile(const std::filesystem::path& path, uint64_t f
         std::memcpy(entryData.data(), &length, 4);
         file.read(reinterpret_cast<char*>(entryData.data() + 4), length);
         if (!file) break;
+        const uint64_t entryOffset = stats.bytesRead;
+        stats.bytesRead += 4 + static_cast<uint64_t>(length);
 
         // Deserialize and invoke callback
         auto entry = WalEntry::deserialize(entryData);
-        if (entry && entry->sequence > fromSequence) {
+        if (!entry) {
+            ++stats.unreadable;
+            if (stats.firstUnreadableOffset == 0) stats.firstUnreadableOffset = entryOffset;
+            if (length >= 4) {
+                uint32_t stored = 0;
+                for (int i = 0; i < 4; ++i) {
+                    stored |= static_cast<uint32_t>(entryData[entryData.size() - 4 + i]) << (i * 8);
+                }
+                if (stored != crc32::calculate(entryData.data() + 4, length - 4)) {
+                    ++stats.checksumFailures;
+                }
+            }
+            continue;
+        }
+        if (stats.firstSequence == 0) stats.firstSequence = entry->sequence;
+        else if (entry->sequence <= stats.lastSequence) ++stats.outOfOrder;
+        stats.lastSequence = entry->sequence;
+        if (entry->sequence > fromSequence) {
             callback(*entry);
             count++;
+        } else {
+            ++stats.atOrBelow;
         }
     }
 
+    stats.applied = count;
     return count;
 }
 

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

@@ -120,6 +120,28 @@ public:
      */
     uint64_t replay(uint64_t fromSequence, std::function<void(const WalEntry&)> callback);
 
+    /**
+     * v2.21.4 - what the last replay() found in each file. Before, an entry
+     * failing its checksum was skipped and a torn or zeroed record ended the
+     * file without any trace, so a replay that applied fewer entries than the
+     * sequence range implies could not be told from one that was complete.
+     */
+    struct ReplayFileStats {
+        std::filesystem::path path;
+        bool headerReadable = true;
+        uint64_t applied = 0;        // passed to the callback
+        uint64_t atOrBelow = 0;      // already in the snapshot
+        uint64_t unreadable = 0;     // checksum or format failure, skipped
+        uint64_t checksumFailures = 0;   // of `unreadable`
+        uint64_t firstUnreadableOffset = 0;  // byte offset, 0 = none
+        uint64_t outOfOrder = 0;     // sequence not above the previous entry's
+        uint64_t firstSequence = 0;  // of readable entries, 0 = none
+        uint64_t lastSequence = 0;
+        uint64_t bytesRead = 0;      // header + every entry read
+        uint64_t fileBytes = 0;      // < this means the file ended early
+    };
+    std::vector<ReplayFileStats> lastReplayStats() const;
+
     /**
      * Get the current sequence number.
      */
@@ -220,7 +242,12 @@ private:
 
     // Read entries from a file
     uint64_t replayFile(const std::filesystem::path& path, uint64_t fromSequence,
-                        const std::function<void(const WalEntry&)>& callback);
+                        const std::function<void(const WalEntry&)>& callback,
+                        ReplayFileStats& stats);
+    // replay() also runs at runtime from several threads (an evicted
+    // document's read, replication), so the record is guarded.
+    mutable std::mutex replayStatsMutex_;
+    std::vector<ReplayFileStats> lastReplayStats_;
 
     Config config_;
     std::atomic<bool> isOpen_{false};

+ 20 - 0
tests/load_test/test_snapshot_keeps_evicted.cpp

@@ -9,6 +9,14 @@
 // the restarted server must hold every one of them (the script checks the
 // vector share of the memory line).
 //
+// v2.21.4 - plus collection configs: their `_collection_meta` rows are the
+// oldest, coldest rows in the store, so eviction took them first, and a system
+// collection is never mirrored to LMDB, so the snapshot could read them back
+// only from the WAL. After the first snapshot truncated it, every later
+// snapshot failed ("evicted document '_collection_meta/...' could not be read
+// for the snapshot") and the WAL grew without bound - 15 days and 276 MB on one
+// production instance. System collections are no longer evicted.
+//
 // Phases: seed (insert, wait for eviction) | check (after a restart)
 
 #include <smartbotic/database/client.hpp>
@@ -57,6 +65,13 @@ int main(int argc, char** argv) {
     c.connect();
 
     if (phase == "seed") {
+        // First, so these `_collection_meta` rows are the oldest in the store.
+        for (const char* name : {"cfg_a", "cfg_b", "cfg_c"}) {
+            Client::CollectionConfig cc;
+            cc.timestampPrecision = "";
+            cc.versioningEnabled = false;
+            ck(c.configureCollection(name, cc), std::string("seed: configured ") + name);
+        }
         // Vector rows first: they are the oldest, so eviction (capped at half
         // the documents present when an episode starts) takes them first.
         ck(c.createCollection("vecs", 0, false, 0, kDim), "seed: vector collection created");
@@ -77,6 +92,11 @@ int main(int argc, char** argv) {
         ck(statFor(c, false) == kRows && statFor(c, true) == 0,
            "check: every row is resident again after the restart (nothing evicted)");
         ck(c.count("kept") == kRows, "check: every row readable");
+        for (const char* name : {"cfg_a", "cfg_b", "cfg_c"}) {
+            const auto cc = c.getCollectionConfig(name);
+            ck(cc.versioningEnabled == false,
+               std::string("check: the config of ") + name + " survived (versioning off)");
+        }
         ck(c.count("vecs") == kVecRows, "check: every vector row readable");
         int own = 0;
         for (int i = 0; i < kVecRows; i += 30) {

+ 70 - 0
tests/load_test/test_stale_memory.cpp

@@ -0,0 +1,70 @@
+// v2.21.4 - memory older than LMDB after an incomplete WAL replay.
+//
+// A production boot replayed 193,776 of the 354,089 WAL entries above its
+// snapshot. LMDB had every write (each is mirrored at write time) so reads were
+// right, but MemoryStore kept the snapshot's older version of every row written
+// in the gap, and a patch merges into MemoryStore's body: old fields + the
+// patch, mirrored over LMDB's newer row. The script recreates that state (the
+// WAL holding the newer writes is removed before a boot) and the boot's
+// version audit must reload those rows from LMDB.
+//
+// Phases: seed | newer | check
+
+#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:9042";
+    cfg.writeRetries = 0;
+    Client c(cfg);
+    c.connect();
+
+    if (phase == "seed") {
+        for (int i = 0; i < 20; ++i) {
+            c.insert("rows", {{"state", "old"}, {"n", 1}}, "r" + std::to_string(i));
+        }
+        c.insert("untouched", {{"state", "same"}}, "u0");
+    } else if (phase == "newer") {
+        // Only in the WAL (removed before the next boot) and in LMDB.
+        for (int i = 0; i < 10; ++i) {
+            ck(c.patch("rows", "r" + std::to_string(i), {{"state", "new"}, {"added", true}}),
+               "newer: patched r" + std::to_string(i));
+        }
+    } else if (phase == "check") {
+        // Reads come from LMDB and were right either way.
+        auto r0 = c.get("rows", "r0");
+        ck(r0 && (*r0)["state"] == "new" && (*r0)["_version"] == 2, "check: r0 reads the newer version");
+        // A patch merges into memory's copy: with stale memory it would drop
+        // `added` and put `state` back to "old".
+        for (int i = 0; i < 10; ++i) {
+            const std::string id = "r" + std::to_string(i);
+            ck(c.patch("rows", id, {{"n", 2}}), "check: patched " + id);
+            auto d = c.get("rows", id);
+            ck(d && (*d)["state"] == "new" && (*d).value("added", false) == true &&
+               (*d)["n"] == 2 && (*d)["_version"] == 3,
+               "check: " + id + " keeps the newer fields after a patch (version 3)");
+        }
+        // Rows memory had right are untouched.
+        auto r15 = c.get("rows", "r15");
+        ck(r15 && (*r15)["state"] == "old" && (*r15)["_version"] == 1, "check: r15 unchanged");
+        // updateIfVersion against the version a read returned.
+        auto r1 = c.get("rows", "r1");
+        nlohmann::json body = {{"state", "replaced"}};
+        ck(r1 && c.updateIfVersion("rows", "r1", body, (*r1)["_version"].get<uint64_t>()),
+           "check: updateIfVersion at the version a read returned succeeds");
+    } else {
+        return 2;
+    }
+    std::cout << phase << ": " << pass << " passed, " << fail << " failed\n";
+    return fail == 0 ? 0 : 1;
+}

+ 66 - 0
tests/load_test/test_stale_memory.sh

@@ -0,0 +1,66 @@
+#!/usr/bin/env bash
+# v2.21.4 e2e - the boot's version audit reloads rows that memory holds in an
+# older version than LMDB (what an incomplete WAL replay leaves).
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+cd "$SCRIPT_DIR"
+
+DIR=/tmp/sbdb-stale-memory
+PORT=9042
+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 },
+    "persistence": { "snapshot_interval_sec": 3600 }
+  }
+}
+CFG
+
+g++ -std=c++20 -O1 -o "$DIR/t" test_stale_memory.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
+}
+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))
+kill "$SERVER_PID"; wait "$SERVER_PID" || true    # graceful: the snapshot holds version 1
+start 2
+client newer || fails=$((fails+1))
+kill -9 "$SERVER_PID"; wait "$SERVER_PID" 2>/dev/null || true
+SERVER_PID=""
+# The newer writes are now in LMDB and in the WAL only. Losing the WAL is what
+# an incomplete replay amounts to for these rows.
+rm -f "$DIR"/data/wal/wal-*.log
+start 3
+ck "boot 3: the version audit reloaded the 10 rows" \
+   "grep -q 'version audit: default:rows: 10 resident row(s) were older than LMDB' '$DIR/server3.log'"
+ck "boot 3: the summary counts them" \
+   "grep -q 'version audit: .* checked, 10 reloaded from LMDB, 0 failed' '$DIR/server3.log'"
+client check || fails=$((fails+1))
+grep -h "version audit" "$DIR/server3.log" || true
+kill "$SERVER_PID"; wait "$SERVER_PID" || true
+SERVER_PID=""
+
+[[ $fails -eq 0 ]] && echo "OK - stale memory reloaded from LMDB" || echo "FAILED ($fails)"
+exit $(( fails > 0 ))

+ 55 - 4
tests/test_snapshot_durability.cpp

@@ -8,7 +8,7 @@
  *   2. snapshot round-trip (write then load back)
  *   3. post-write verification catches externally-truncated file
  *   4. loadWithFallback uses older snapshot when newest is corrupt
- *   5. orphaned .tmp files cleaned by listSnapshots
+ *   5. orphaned .tmp files cleaned at boot, never by listSnapshots (2.21.4)
  *   6. loadWithFallback throws when all snapshots corrupt
  */
 
@@ -17,6 +17,7 @@
 #include "../service/src/memory_store.hpp"
 #include "../service/src/document.hpp"
 
+#include <atomic>
 #include <cassert>
 #include <chrono>
 #include <cstdint>
@@ -210,8 +211,13 @@ void test_loadWithFallback_uses_older_when_newest_corrupt() {
 }
 
 // ──────────────────────────────────────────────────────────
-// Test 5: orphaned .tmp files cleaned by listSnapshots()
+// Test 5: orphaned .tmp files cleaned at boot, never by listSnapshots()
 // ──────────────────────────────────────────────────────────
+// v2.21.4 - listSnapshots() used to delete every .tmp, and GetStats and the
+// retention pass call it: a listing while a snapshot was being written killed
+// that snapshot ("Failed to reopen snapshot tmp for fsync", seen in production
+// right after a boot whose first snapshot was the one that had to truncate a
+// 276 MB WAL).
 void test_orphaned_tmp_cleaned_by_listSnapshots() {
     auto dir = makeSnapshotDir("orphan");
 
@@ -227,13 +233,57 @@ void test_orphaned_tmp_cleaned_by_listSnapshots() {
     }
     assert(fs::exists(tmp));
 
-    // listSnapshots should clean up the .tmp on its pre-scan pass
+    // A listing leaves it alone: it may belong to a snapshot in progress.
     (void)mgr.listSnapshots();
+    assert(fs::exists(tmp));
 
+    // Recovery's cleanup removes it.
+    mgr.removeOrphanedTmpFiles();
     assert(!fs::exists(tmp));
 
     fs::remove_all(dir);
-    std::cout << "PASS: orphaned .tmp cleaned by listSnapshots\n";
+    std::cout << "PASS: orphaned .tmp cleaned at boot, not by listSnapshots\n";
+}
+
+// v2.21.4 - a snapshot completes while another thread keeps listing snapshots
+// (what a GetStats poller does).
+void test_snapshot_survives_concurrent_listing() {
+    auto dir = makeSnapshotDir("listing");
+    SnapshotManager::Config scfg;
+    scfg.snapshotDir = dir;
+    scfg.chunkBytes = 64 * 1024;
+    SnapshotManager mgr(scfg);
+
+    MemoryStore store(defaultStoreConfig());
+    store.start();
+    store.createCollection("a", CollectionOptions{});
+    for (int i = 0; i < 4000; ++i) {
+        Document d;
+        d.id = "x" + std::to_string(i);
+        d.set_data(nlohmann::json{{"s", std::string(4000, static_cast<char>('a' + i % 26))}, {"i", i}});
+        store.insert("a", d);
+    }
+    int ok = 0, failed = 0;
+    for (int round = 0; round < 5; ++round) {
+        std::atomic<bool> done{false};
+        std::thread lister([&] {
+            while (!done.load()) (void)mgr.listSnapshots();
+        });
+        try {
+            auto path = mgr.createSnapshot(store, static_cast<uint64_t>(round + 1));
+            if (mgr.verifySnapshot(path)) ++ok; else ++failed;
+        } catch (const std::exception& e) {
+            std::cerr << "snapshot failed under a concurrent listing: " << e.what() << "\n";
+            ++failed;
+        }
+        done = true;
+        lister.join();
+        std::this_thread::sleep_for(std::chrono::milliseconds(1100));  // distinct file names
+    }
+    store.stop();
+    assert(failed == 0 && ok == 5);
+    fs::remove_all(dir);
+    std::cout << "PASS: snapshots complete while another thread lists snapshots\n";
 }
 
 // ──────────────────────────────────────────────────────────
@@ -831,6 +881,7 @@ int main() {
     test_verification_catches_truncation();
     test_loadWithFallback_uses_older_when_newest_corrupt();
     test_orphaned_tmp_cleaned_by_listSnapshots();
+    test_snapshot_survives_concurrent_listing();
     test_loadWithFallback_throws_when_all_corrupt();
     test_v4_format_roundtrip_at_scale();
     test_wal_sequence_floor_anchors_after_truncate();