Sfoglia il codice sorgente

fix: WAL replay records no history; max_versions enforced as history grows; eviction and snapshot races

Every boot that replayed the WAL recorded each replayed update and delete
in history again, and for versioning-off collections too (replay runs
before the collection configs load). max_versions was enforced only when
lowered; after each snapshot a capped file that grew past 16 MB and twice
its last pruned size is now pruned.

Eviction recorded the stub after removing the document, so a snapshot
could write it as deleted; the stub now comes first. Snapshots are
serialized (the shutdown snapshot could clash with the periodic one).
Report mode says what adopt would do.
fszontagh 1 mese fa
parent
commit
c0fdaa0aba

File diff suppressed because it is too large
+ 0 - 0
CLAUDE.md


+ 3 - 0
docs/ROADMAP.md

@@ -135,6 +135,9 @@ detail and the failure modes.
 - A row on disk but not in memory is writable (it was readable and every write
   missed it, or an insert overwrote it); a boot audit lists every row the two
   stores disagree on (2.20.2)
+- Snapshots keep evicted rows; failed LMDB copies are repaired at boot;
+  `storage.consistency` repair knobs (2.21.0). WAL replay records no history,
+  and `max_versions` is enforced as history grows (2.21.1)
 
 ---
 

+ 11 - 0
docs/integration-guide.md

@@ -2539,6 +2539,17 @@ it applies these settings:
 `report` changes nothing; the log line says which setting would do what. An
 unknown value is treated as `report`.
 
+- **The settings are instance-wide**: they act on every collection of every
+  project the audit compares. To repair one project's rows, write or delete
+  them by id through the ordinary API instead (an upsert or patch of a
+  memory-only row copies it to disk; a delete removes it from both).
+- **`adopt` loads a row unchanged**: its `_version` and `_updated_at` stay as
+  they were. A disk-only row whose collection exists only on disk (not in
+  memory) cannot be adopted (its options, such as the vector dimension, are
+  unknown) and is reported as "not adoptable".
+- **`consistency-report.json` is overwritten at every boot**; copy it before a
+  restart if you want to keep it.
+
 **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`).

+ 19 - 7
service/src/database_service.cpp

@@ -1124,6 +1124,7 @@ void DatabaseService::auditMemoryDiskKeys() {
     };
     uint64_t diskOnlyTotal = 0, memOnlyTotal = 0, compared = 0;
     uint64_t adopted = 0, diskRemoved = 0, written = 0, memRemoved = 0, actionFailed = 0;
+    uint64_t notAdoptable = 0;   // disk-only rows whose collection exists only on disk
 
     for (const auto& project : projects_->listOpen()) {
         auto* ds = docStore(project);
@@ -1193,7 +1194,7 @@ void DatabaseService::auditMemoryDiskKeys() {
                                                    ? qualified : namesIt->second.front();
                         for (const auto& id : diskOnly) {
                             try {
-                                (store_->adoptFromDocStore(target, id) ? done : failed).push_back(id);
+                                (store_->adoptFromDocStore(target, id, /*quiet=*/true) ? done : failed).push_back(id);
                             } catch (const std::exception& e) {
                                 spdlog::error("key audit: adopting {}/{} failed: {}", qualified, id, e.what());
                                 failed.push_back(id);
@@ -1215,10 +1216,16 @@ void DatabaseService::auditMemoryDiskKeys() {
                         diskRemoved += done.size();
                     }
                     actionFailed += failed.size();
+                    // Counted under every policy, so `report` can price `adopt`
+                    // before anything acts (asked by smartbotic-vectorapi).
+                    if (!inMemory) notAdoptable += diskOnly.size();
                     const std::string action =
-                        diskPolicy == "report" ? "reported" :
-                        (diskPolicy == "adopt" && !inMemory) ? "reported (collection not in memory)" :
-                        diskPolicy == "adopt" ? "adopted into memory" : "removed from disk";
+                        diskPolicy == "report"
+                            ? (inMemory ? "reported (adopt would load them)"
+                                        : "reported (not adoptable: the collection exists only on disk)") :
+                        (diskPolicy == "adopt" && !inMemory)
+                            ? "reported (not adoptable: the collection exists only on disk)" :
+                        diskPolicy == "adopt" ? "adopted into memory (loaded unchanged)" : "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,
@@ -1227,7 +1234,8 @@ void DatabaseService::auditMemoryDiskKeys() {
                                                          : "",
                                   failed.empty() ? "" : fmt::format("; {} FAILED", failed.size()),
                                   samples(diskOnly));
-                    entry["disk_only"] = {{"action", action}, {"ids", diskOnly}, {"failed", failed}};
+                    entry["disk_only"] = {{"action", action}, {"collection_in_memory", inMemory},
+                                          {"ids", diskOnly}, {"failed", failed}};
                 }
                 if (!memOnly.empty()) {
                     memOnlyTotal += memOnly.size();
@@ -1277,6 +1285,8 @@ void DatabaseService::auditMemoryDiskKeys() {
     report["compared"] = compared;
     report["disk_only"] = diskOnlyTotal;
     report["memory_only"] = memOnlyTotal;
+    report["adopted"] = adopted;
+    report["not_adoptable"] = notAdoptable;
     report["milliseconds"] = ms;
     try {
         const auto path = std::filesystem::path(config_.dataDirectory) / "consistency-report.json";
@@ -1296,10 +1306,12 @@ void DatabaseService::auditMemoryDiskKeys() {
         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. "
+                    "not adoptable (their collection exists only on disk; counted under any "
+                    "policy), {} 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);
+                    adopted, notAdoptable, diskRemoved, written, memRemoved, actionFailed);
     }
 }
 

+ 44 - 13
service/src/memory_store.cpp

@@ -3000,6 +3000,7 @@ void MemoryStore::saveToHistory(CollectionData& coll, const Document& currentDoc
     // `estimatedMemoryBytes_` with the version's overhead. That was
     // the dominant source of the Zoe RSS gap; see docs/incidents/2026-04-22-zoe-rss-exceeds-budget.md.
     if (!historyStore_) return;
+    if (historySuppressed_.load(std::memory_order_relaxed) > 0) return;   // v2.21.1: WAL replay
 
     // v2.4.5 — per-collection versioning switch. Checked here rather than at
     // each of the ~10 write sites that call saveToHistory, so there is exactly
@@ -3023,13 +3024,34 @@ void MemoryStore::saveToHistory(CollectionData& coll, const Document& currentDoc
     ver.createdBy = currentDoc.createdBy;
 
     historyStore_->append(currentDoc.collection, currentDoc.id, ver);
-    // Per-collection `max_versions` pruning runs in the snapshot loop
-    // (PersistenceManager::createSnapshot calls historyStore_->prune for
-    // every collection that has a cap set). Doing it inline on every
+    // Per-collection `max_versions` is enforced after each snapshot by
+    // enforceVersionCaps() (v2.21.1; before, nothing enforced it although
+    // this comment said the snapshot loop did). Doing it inline on every
     // write would either rewrite the file each time (expensive) or
     // require an in-memory counter we no longer keep.
 }
 
+size_t MemoryStore::enforceVersionCaps() const {
+    if (!historyStore_) return 0;
+    std::vector<std::pair<std::string, uint32_t>> capped;
+    {
+        std::shared_lock<std::shared_mutex> lock(globalMutex_);
+        for (const auto& [name, coll] : collections_) {
+            std::shared_lock<std::shared_mutex> collLock(coll->mutex);
+            if (coll->options.maxVersions > 0) capped.emplace_back(name, coll->options.maxVersions);
+        }
+    }
+    size_t pruned = 0;
+    for (const auto& [name, maxVersions] : capped) {
+        try {
+            if (historyStore_->pruneIfGrown(name, maxVersions)) ++pruned;
+        } catch (const std::exception& e) {
+            spdlog::warn("history cap: '{}' could not be pruned: {}", name, e.what());
+        }
+    }
+    return pruned;
+}
+
 MemoryStore::VersionHistoryResult MemoryStore::getVersionHistory(
     const std::string& collection, const std::string& id,
     uint32_t limit, uint32_t offset) const {
@@ -3667,7 +3689,8 @@ std::vector<std::string> memoryAliasesOf(const smartbotic::database::ProjectColl
 }
 }  // namespace
 
-bool MemoryStore::adoptFromDocStore(const std::string& collection, const std::string& id) {
+bool MemoryStore::adoptFromDocStore(const std::string& collection, const std::string& id,
+                                    bool quiet) {
     // Only while LMDB is what reads are served from: with the mirror unhealthy
     // or drifted, MemoryStore may be AHEAD of LMDB (a row deleted here whose
     // delete never reached LMDB), and adopting would resurrect it.
@@ -3734,9 +3757,11 @@ bool MemoryStore::adoptFromDocStore(const std::string& collection, const std::st
         stats_.totalDocuments++;
     }
     estimatedMemoryBytes_.fetch_add(size, std::memory_order_relaxed);
-    spdlog::warn("write to {}/{}: the row was on disk but not in memory (readable, not "
-                 "writable before 2.20.2); loaded it so the write applies to it. The boot "
-                 "audit lists every such row.", collection, id);
+    if (!quiet) {
+        spdlog::warn("write to {}/{}: the row was on disk but not in memory (readable, not "
+                     "writable before 2.20.2); loaded it unchanged so the write applies to it. "
+                     "The boot key audit lists every such row.", collection, id);
+    }
     return true;
 }
 
@@ -4527,6 +4552,18 @@ bool MemoryStore::evictDocument(const std::string& collection, const std::string
         removeFromExpirationIndex(*coll, id, it->second.expiresAt);
     }
 
+    // v2.21.1 - the stub goes in BEFORE the document leaves, still under the
+    // collection lock (lock order collection -> eviction, as everywhere). It
+    // used to be added after the collection lock was released, leaving a
+    // moment in which the document was in neither map: a snapshot that had
+    // listed it as resident then found neither a document nor a stub and
+    // wrote it as deleted, and a write saw "absent". Briefly in both maps is
+    // harmless (a snapshot writes it twice; the loader keeps one).
+    {
+        std::unique_lock<std::shared_mutex> evictLock(evictionMutex_);
+        evictedDocs_[collection][id] = stub;
+    }
+
     // Remove document from memory
     coll->documents.erase(it);
 
@@ -4537,12 +4574,6 @@ bool MemoryStore::evictDocument(const std::string& collection, const std::string
 
     collLock.unlock();
 
-    // Store stub in evicted map
-    {
-        std::unique_lock<std::shared_mutex> evictLock(evictionMutex_);
-        evictedDocs_[collection][id] = stub;
-    }
-
     // Update stats
     {
         std::lock_guard<std::mutex> statsLock(statsMutex_);

+ 35 - 1
service/src/memory_store.hpp

@@ -235,6 +235,35 @@ public:
      */
     void setHistoryStore(HistoryStore* hs) { historyStore_ = hs; }
 
+    /**
+     * v2.21.1 - while one of these exists, no write records a history version.
+     * Recovery holds one across WAL replay: every replayed UPDATE/UPSERT/DELETE
+     * already appended its history version when it was first written (history
+     * is appended before the WAL entry), so recording it again duplicated it
+     * on EVERY boot - and replay runs before the collection configs are
+     * loaded, so it ignored versioning OFF too. One production instance
+     * carried 1.9 GB of history on two collections with versioning off.
+     */
+    class HistorySuppression {
+    public:
+        explicit HistorySuppression(MemoryStore& s) : s_(s) { s_.historySuppressed_.fetch_add(1); }
+        ~HistorySuppression() { s_.historySuppressed_.fetch_sub(1); }
+        HistorySuppression(const HistorySuppression&) = delete;
+        HistorySuppression& operator=(const HistorySuppression&) = delete;
+    private:
+        MemoryStore& s_;
+    };
+
+    /**
+     * v2.21.1 - enforce every collection's maxVersions on its history file.
+     * It used to be enforced only when the cap was LOWERED (a comment claimed
+     * the snapshot loop pruned; nothing did), so a capped collection's history
+     * grew without bound. Called after each snapshot; a file is rewritten only
+     * once it has grown past HistoryStore::pruneIfGrown's threshold, so a large
+     * file is not re-read every hour. Returns the number of files pruned.
+     */
+    size_t enforceVersionCaps() const;
+
     /**
      * v2.3 — attach a project-routing LMDB mirror. The resolver looks
      * up the right DocumentStore for a project name; MemoryStore parses
@@ -1361,7 +1390,11 @@ private:
     // 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);
+    // `quiet`: no per-row WARN (the boot key audit adopts thousands at once
+    // and logs one summary; the per-row line also read as "a write touched my
+    // row", which adoption is not - the row is loaded unchanged).
+    bool adoptFromDocStore(const std::string& collection, const std::string& id,
+                           bool quiet = false);
 
     /**
      * v2.21.0 - make LMDB agree with MemoryStore for the named rows
@@ -1557,6 +1590,7 @@ private:
     // v1.9.0 — disk-resident version history backend. Nullable; when null,
     // history operations no-op (no history kept).
     HistoryStore* historyStore_ = nullptr;
+    std::atomic<int> historySuppressed_{0};   // v2.21.1, see HistorySuppression
 
     // v2.3 — dual-write target. Resolver routes per-project lookup; the
     // atomic pointers are owned by DatabaseService. When the resolver is

+ 23 - 0
service/src/persistence/history_store.cpp

@@ -5,6 +5,7 @@
 
 #include <algorithm>
 #include <cstring>
+#include <filesystem>
 #include <functional>
 #include <stdexcept>
 #include <system_error>
@@ -234,6 +235,28 @@ void HistoryStore::dropCollection(const std::string& collection) {
     std::filesystem::remove(filePath(collection), ec);
 }
 
+bool HistoryStore::pruneIfGrown(const std::string& collection, uint32_t maxVersions) {
+    if (maxVersions == 0) return false;
+    std::error_code ec;
+    const auto path = filePath(collection);
+    const uint64_t before = std::filesystem::file_size(path, ec);
+    if (ec || before < kPruneMinBytes) return false;
+    {
+        std::lock_guard<std::mutex> lock(prunedSizesGuard_);
+        auto it = prunedSizes_.find(collection);
+        if (it != prunedSizes_.end() && before <= 2 * it->second) return false;
+    }
+    prune(collection, maxVersions);
+    const uint64_t after = std::filesystem::file_size(path, ec);
+    {
+        std::lock_guard<std::mutex> lock(prunedSizesGuard_);
+        prunedSizes_[collection] = ec ? before : after;
+    }
+    spdlog::info("history cap: '{}' pruned to the newest {} version(s) per document: {} -> {} bytes",
+                 collection, maxVersions, before, ec ? before : after);
+    return true;
+}
+
 void HistoryStore::prune(const std::string& collection, uint32_t maxVersions) {
     if (maxVersions == 0) return;  // 0 means unlimited
 

+ 12 - 0
service/src/persistence/history_store.hpp

@@ -107,6 +107,15 @@ public:
      */
     void prune(const std::string& collection, uint32_t maxVersions);
 
+    /**
+     * v2.21.1 - prune(collection, maxVersions) if the file has grown enough
+     * to be worth a rewrite: at least kPruneMinBytes and more than twice its
+     * size after the previous prune by this process (the first call in a
+     * process prunes any file over kPruneMinBytes). Returns true if it pruned.
+     */
+    bool pruneIfGrown(const std::string& collection, uint32_t maxVersions);
+    static constexpr uint64_t kPruneMinBytes = 16ULL * 1024 * 1024;
+
     /**
      * v2.17.0 - apply `transform` to every stored version of `collection`, in
      * file order, and rewrite the file (tmp + rename) if any changed. Used by
@@ -139,6 +148,9 @@ private:
     // the name returns), so a reference stays valid for the store's life.
     mutable std::mutex fileMutexesGuard_;
     mutable std::unordered_map<std::string, std::unique_ptr<std::mutex>> fileMutexes_;
+    // v2.21.1 - file size after the last prune by this process (pruneIfGrown).
+    std::mutex prunedSizesGuard_;
+    std::unordered_map<std::string, uint64_t> prunedSizes_;
     [[nodiscard]] std::mutex& fileMutex(const std::string& collection) const;
 
     [[nodiscard]] std::filesystem::path filePath(const std::string& collection) const;

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

@@ -250,6 +250,9 @@ RecoveryOutcome PersistenceManager::recover(MemoryStore& store) {
         std::vector<std::pair<std::string, std::string>> touched;
         std::unordered_map<std::string, size_t> touchedIndex;
         std::vector<bool> touchedAlive;
+        // 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);
         uint64_t replayed = wal_->replay(fromSequence, [&](const WalEntry& entry) {
             applyWalEntry(store, entry);
             const std::string key = entry.collection + "\x1f" + entry.documentId;
@@ -749,6 +752,7 @@ void PersistenceManager::warnIfWalOutgrewSnapshots(uint64_t walBytes) const {
 }
 
 void PersistenceManager::createSnapshot() {
+    std::lock_guard<std::mutex> oneAtATime(createSnapshotMutex_);   // v2.21.1
     const MemoryStore* store = nullptr;
     {
         std::lock_guard<std::mutex> lock(storeMutex_);
@@ -782,6 +786,10 @@ void PersistenceManager::createSnapshot() {
             snapshotCallback_(snapshotPath);
         }
 
+        // v2.21.1 - maxVersions on disk; a file is rewritten only once it has
+        // grown past HistoryStore::pruneIfGrown's threshold.
+        store->enforceVersionCaps();
+
     } catch (const std::exception& e) {
         spdlog::error("Failed to create snapshot: {} (the WAL is not truncated until one "
                       "completes; WAL now {})", e.what(), megabytes(walSizeBytes()));

+ 5 - 0
service/src/persistence/persistence_manager.hpp

@@ -382,6 +382,11 @@ private:
 
     // Snapshot control
     std::mutex snapshotMutex_;
+    // v2.21.1 - one snapshot at a time. The shutdown's final snapshot
+    // (forceSnapshot) could run while the periodic thread was mid-snapshot;
+    // within one second both used the same file name and its .tmp, and one
+    // failed verification or renamed the other's half-written file.
+    std::mutex createSnapshotMutex_;
     std::condition_variable snapshotCv_;
     bool snapshotRequested_ = false;
 

+ 2 - 0
tests/load_test/test_disk_only_rows.sh

@@ -67,6 +67,8 @@ ck "boot 2: audit names the 4 disk-only rows" \
    "grep -q 'key audit: default:ghosts: 4 row(s) on disk but not in memory.*ghost1, ghost2, ghost3, ghost4' '$DIR/server2.log'"
 ck "boot 2: audit names the memory-only row" \
    "grep -q 'key audit: default:ghosts: 1 row(s) in memory but not on disk.*ids: b1' '$DIR/server2.log'"
+ck "boot 2: report mode says what adopt would do" \
+   "grep -q 'reported (adopt would load them)' '$DIR/server2.log' && grep -q '\"collection_in_memory\": true' '$DIR/data/consistency-report.json'"
 ck "boot 2: audit summary" "grep -q 'key audit: .* 4 row(s) on disk only, 1 in memory only' '$DIR/server2.log'"
 client check || fails=$((fails+1))
 ck "boot 2: each adopted row logged once" "[[ \$(grep -c 'the row was on disk but not in memory' '$DIR/server2.log') -eq 4 ]]"

+ 54 - 0
tests/load_test/test_replay_history.cpp

@@ -0,0 +1,54 @@
+// v2.21.1 - WAL replay must not record version history. Each replayed
+// UPDATE/UPSERT/DELETE already appended its history version when first written,
+// so a boot that replayed the WAL appended it again; and replay runs before the
+// collection configs are loaded, so it recorded history for collections with
+// versioning OFF too. One production boot replaying 14,998 entries wrote 1.9 GB
+// of history into two versioning-off collections.
+//
+// Phases: write (then the server is SIGKILLed, so the next boot replays) | 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:9039";
+    cfg.writeRetries = 0;
+    Client c(cfg);
+    c.connect();
+
+    if (phase == "write") {
+        c.insert("hist", {{"n", 0}}, "h1");
+        c.insert("nohist", {{"n", 0}}, "n1");
+        Client::CollectionConfig off;
+        off.timestampPrecision = "";
+        off.versioningEnabled = false;
+        ck(c.configureCollection("nohist", off), "write: versioning switched off on nohist");
+        for (int i = 1; i <= 3; ++i) {
+            c.patch("hist", "h1", {{"n", i}});
+            c.patch("nohist", "n1", {{"n", i}});
+        }
+        ck(c.getVersionHistory("hist", "h1").versions.size() == 3, "write: hist has 3 versions");
+        ck(c.getVersionHistory("nohist", "n1").versions.empty(), "write: nohist has none");
+    } else if (phase == "check") {
+        const auto h = c.getVersionHistory("hist", "h1").versions.size();
+        ck(h == 3, "check: after a replaying boot hist still has 3 versions (got " + std::to_string(h) + ")");
+        const auto n = c.getVersionHistory("nohist", "n1").versions.size();
+        ck(n == 0, "check: nohist still has none (got " + std::to_string(n) + ")");
+        auto doc = c.get("hist", "h1");
+        ck(doc && (*doc)["n"] == 3, "check: the replayed writes themselves applied");
+    } else {
+        return 2;
+    }
+    std::cout << phase << ": " << pass << " passed, " << fail << " failed\n";
+    return fail == 0 ? 0 : 1;
+}

+ 58 - 0
tests/load_test/test_replay_history.sh

@@ -0,0 +1,58 @@
+#!/usr/bin/env bash
+# v2.21.1 e2e - a boot that replays the WAL records no history (and none for a
+# versioning-off collection). SERVER_BIN runs it against another binary.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+cd "$SCRIPT_DIR"
+
+DIR=/tmp/sbdb-replay-history
+PORT=9039
+rm -rf "$DIR"
+mkdir -p "$DIR/data"
+cat > "$DIR/config.json" <<CFG
+{
+  "storage": {
+    "data_directory": "$DIR/data",
+    "bind_address": "127.0.0.1",
+    "rpc_port": $PORT,
+    "encryption": { "enabled": false },
+    "migrations": { "enabled": false },
+    "replication": { "enabled": false }
+  }
+}
+CFG
+
+g++ -std=c++20 -O1 -o "$DIR/t" test_replay_history.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 -9 $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
+
+start 1
+client write || fails=$((fails+1))
+sleep 1   # the WAL syncs every 100 ms by default
+kill -9 "$SERVER_PID"; wait "$SERVER_PID" 2>/dev/null || true; SERVER_PID=""
+
+start 2
+if grep -qE "Replayed [1-9][0-9]* WAL entries" "$DIR/server2.log"; then
+    echo "ok   boot 2 replayed the WAL"
+else
+    echo "FAIL boot 2 did not replay the WAL (the test would prove nothing)"; fails=$((fails+1))
+fi
+client check || fails=$((fails+1))
+kill "$SERVER_PID"; wait "$SERVER_PID" || true; SERVER_PID=""
+
+[[ $fails -eq 0 ]] && echo "OK - replay records no history" || echo "FAILED ($fails)"
+exit $(( fails > 0 ))

+ 6 - 2
tests/load_test/test_snapshot_keeps_evicted.cpp

@@ -26,7 +26,10 @@ 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;
+        // Memory "holds" a row resident or as an eviction stub; the restarted
+        // server may evict again (200 KB rows), so resident alone races.
+        if (cs.collection == "default:kept")
+            return evicted ? cs.evictedStubCount : cs.documentCount + cs.evictedStubCount;
     }
     return 0;
 }
@@ -51,7 +54,8 @@ int main(int argc, char** argv) {
         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(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");
     } else {
         return 2;

+ 3 - 1
tests/load_test/test_snapshot_keeps_evicted.sh

@@ -71,10 +71,12 @@ ck "two snapshots taken while rows were evicted" \
 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
+# Restart with a budget that evicts nothing, so memory holds every row resident.
+config 8192
 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))
+ck "no snapshot failed" "! grep -q 'Failed to create snapshot' '$DIR/server1.log' '$DIR/server2.log'"
 grep -h "Recovery complete\|key audit: [0-9]" "$DIR/server2.log" || true
 stop
 

+ 21 - 0
tests/test_history_audit_scan.cpp

@@ -156,6 +156,27 @@ int main() {
     check(hs.forEach("missing", [](const std::string&, const DocumentVersion&) {}) == 0,
           "a collection without history visits nothing");
 
+    // v2.21.1 - maxVersions enforced when a file has grown, not only when the
+    // cap is lowered. Before, a capped collection's history grew without bound.
+    {
+        const auto size = [&] { return std::filesystem::file_size(dir / "history" / "capped.hlog"); };
+        DocumentVersion big;
+        big.set_data({{"pad", std::string(64 * 1024, 'y')}});
+        uint64_t n = 0;
+        // ~20 MB: 320 versions of 64 KB over 8 documents (40 each).
+        for (; n < 320; ++n) { big.version = n; hs.append("capped", "c" + std::to_string(n % 8), big); }
+        check(size() > HistoryStore::kPruneMinBytes, "cap: the file is past the prune threshold");
+        check(!hs.pruneIfGrown("tiny-or-absent", 1), "cap: an absent or small file is left alone");
+        const auto before = size();
+        check(hs.pruneIfGrown("capped", 2), "cap: the first call prunes a file over the threshold");
+        check(size() < before / 10, "cap: the file shrank to about 2 versions per document");
+        check(hs.getVersions("capped", "c3", 100, 0).size() == 2, "cap: 2 versions remain per document");
+        check(!hs.pruneIfGrown("capped", 2), "cap: not again until it has grown");
+        for (; n < 1000; ++n) { big.version = n; hs.append("capped", "c" + std::to_string(n % 8), big); }
+        check(hs.pruneIfGrown("capped", 2), "cap: pruned again once it grew past twice its size");
+        check(hs.getVersions("capped", "c5", 100, 0).size() == 2, "cap: still 2 per document");
+    }
+
     std::filesystem::remove_all(dir);
     std::cout << (failures == 0 ? "PASS" : "FAILED") << "\n";
     return failures == 0 ? 0 : 1;

Some files were not shown because too many files changed in this diff