/** * Integration tests for v1.6.1 snapshot durability + fallback. * * Exercises SnapshotManager directly (no gRPC server). * * Test cases: * 1. atomic write leaves no .tmp file behind * 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 at boot, never by listSnapshots (2.21.4) * 6. loadWithFallback throws when all snapshots corrupt */ #include "../service/src/persistence/snapshot.hpp" #include "../service/src/persistence/wal.hpp" #include "../service/src/memory_store.hpp" #include "../service/src/document.hpp" #include #include #include #include #include #include #include #include #include #include #include #include // getpid #include namespace fs = std::filesystem; using smartbotic::database::MemoryStore; using smartbotic::database::SnapshotManager; using smartbotic::database::Document; using smartbotic::database::CollectionOptions; namespace { MemoryStore::Config defaultStoreConfig() { MemoryStore::Config cfg; cfg.nodeId = "test"; cfg.maxMemoryBytes = 256ULL * 1024 * 1024; return cfg; } fs::path makeSnapshotDir(const std::string& name) { auto dir = fs::temp_directory_path() / ("snap-durability-" + name + "-" + std::to_string(::getpid())); fs::remove_all(dir); fs::create_directories(dir); return dir; } Document makeDoc(const std::string& id) { Document d; d.id = id; d.set_data(nlohmann::json{{"value", id}}); return d; } } // anonymous namespace // ────────────────────────────────────────────────────────── // Test 1: atomic write leaves no .tmp file behind // ────────────────────────────────────────────────────────── void test_atomic_write_leaves_no_tmp() { auto dir = makeSnapshotDir("atomic"); SnapshotManager::Config scfg; scfg.snapshotDir = dir; scfg.validateAfterWrite = true; SnapshotManager mgr(scfg); MemoryStore store(defaultStoreConfig()); store.start(); store.createCollection("docs", CollectionOptions{}); for (int i = 0; i < 50; i++) { store.insert("docs", makeDoc("d" + std::to_string(i))); } auto path = mgr.createSnapshot(store, 42); // No .tmp files should remain int tmpCount = 0; for (auto& e : fs::directory_iterator(dir)) { if (e.path().extension() == ".tmp") tmpCount++; } assert(tmpCount == 0); // The final file should exist and pass verification assert(fs::exists(path)); assert(mgr.verifySnapshot(path)); store.stop(); fs::remove_all(dir); std::cout << "PASS: atomic write leaves no .tmp file behind\n"; } // ────────────────────────────────────────────────────────── // Test 2: snapshot round-trips (write then load back) // ────────────────────────────────────────────────────────── void test_snapshot_round_trip() { auto dir = makeSnapshotDir("roundtrip"); SnapshotManager::Config scfg; scfg.snapshotDir = dir; SnapshotManager mgr(scfg); MemoryStore store(defaultStoreConfig()); store.start(); store.createCollection("docs", CollectionOptions{}); for (int i = 0; i < 20; i++) { store.insert("docs", makeDoc("d" + std::to_string(i))); } auto path = mgr.createSnapshot(store, 99); store.stop(); MemoryStore store2(defaultStoreConfig()); store2.start(); uint64_t seq = mgr.loadSnapshot(path, store2); assert(seq == 99); auto doc = store2.get("docs", "d5"); assert(doc.has_value()); store2.stop(); fs::remove_all(dir); std::cout << "PASS: snapshot round-trip\n"; } // ────────────────────────────────────────────────────────── // Test 3: post-write verification catches externally-truncated file // ────────────────────────────────────────────────────────── void test_verification_catches_truncation() { auto dir = makeSnapshotDir("truncate"); SnapshotManager::Config scfg; scfg.snapshotDir = dir; SnapshotManager mgr(scfg); MemoryStore store(defaultStoreConfig()); store.start(); store.createCollection("docs", CollectionOptions{}); for (int i = 0; i < 50; i++) { store.insert("docs", makeDoc("d" + std::to_string(i))); } auto path = mgr.createSnapshot(store, 1); store.stop(); // Truncate the file AFTER a successful write to simulate the Zoe scenario uintmax_t original = fs::file_size(path); fs::resize_file(path, original / 2); // verifySnapshot should return false assert(!mgr.verifySnapshot(path)); fs::remove_all(dir); std::cout << "PASS: post-write verification catches truncation\n"; } // ────────────────────────────────────────────────────────── // Test 4: loadWithFallback uses older snapshot when newest is corrupt // ────────────────────────────────────────────────────────── void test_loadWithFallback_uses_older_when_newest_corrupt() { auto dir = makeSnapshotDir("fallback"); SnapshotManager::Config scfg; scfg.snapshotDir = dir; scfg.maxSnapshots = 10; SnapshotManager mgr(scfg); MemoryStore store(defaultStoreConfig()); store.start(); store.createCollection("docs", CollectionOptions{}); // Older snapshot — 10 docs for (int i = 0; i < 10; i++) { store.insert("docs", makeDoc("d" + std::to_string(i))); } auto older = mgr.createSnapshot(store, 100); // Filenames include timestamps down to the second, so sleep to ensure ordering std::this_thread::sleep_for(std::chrono::seconds(1)); // Newer snapshot — 20 docs for (int i = 10; i < 20; i++) { store.insert("docs", makeDoc("d" + std::to_string(i))); } auto newer = mgr.createSnapshot(store, 200); store.stop(); assert(older != newer); // Corrupt the newer fs::resize_file(newer, fs::file_size(newer) / 2); assert(!mgr.verifySnapshot(newer)); // loadWithFallback should transparently fall back to the older MemoryStore store2(defaultStoreConfig()); store2.start(); fs::path used; size_t attempted = 0; uint64_t seq = mgr.loadWithFallback(store2, &used, &attempted); assert(seq == 100); assert(used == older); assert(attempted == 2); // tried newer first, then older store2.stop(); fs::remove_all(dir); std::cout << "PASS: loadWithFallback uses older snapshot when newest corrupt\n"; } // ────────────────────────────────────────────────────────── // 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"); SnapshotManager::Config scfg; scfg.snapshotDir = dir; SnapshotManager mgr(scfg); // Manually plant a fake .tmp like a crashed-mid-write would leave auto tmp = dir / "snapshot-20260101-120000.dat.tmp"; { std::ofstream f(tmp); f << "partial"; } assert(fs::exists(tmp)); // 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 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('a' + i % 26))}, {"i", i}}); store.insert("a", d); } int ok = 0, failed = 0; for (int round = 0; round < 5; ++round) { std::atomic done{false}; std::thread lister([&] { while (!done.load()) (void)mgr.listSnapshots(); }); try { auto path = mgr.createSnapshot(store, static_cast(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"; } // v2.21.5 - WriteAheadLog::sync() flushed the std::ofstream WITHOUT the write // mutex while append() wrote to it under the mutex, from the WAL sync thread // every interval and from flushWal(). A std::filebuf is not thread-safe: a // production WAL file held one record a byte shorter than its length prefix, // and replay abandoned the 160,261 intact records behind it. Writers append // while another thread syncs in a loop; every entry must replay. void test_wal_append_races_sync() { using smartbotic::database::WriteAheadLog; auto dir = makeSnapshotDir("wal-sync-race"); WriteAheadLog::Config cfg; cfg.walDir = dir; constexpr int kWriters = 4, kPerWriter = 15000; { WriteAheadLog wal(cfg); assert(wal.open()); std::atomic done{false}; std::thread syncer([&] { while (!done.load()) wal.sync(); }); std::vector writers; for (int w = 0; w < kWriters; ++w) { writers.emplace_back([&wal, w] { for (int i = 0; i < kPerWriter; ++i) { Document d; d.id = "w" + std::to_string(w) + "-" + std::to_string(i); d.set_data(nlohmann::json{{"pad", std::string(100 + (i % 400), 'p')}}); wal.append(WriteAheadLog::makeInsertEntry("t", d, "n")); } }); } for (auto& t : writers) t.join(); done = true; syncer.join(); wal.close(); } WriteAheadLog wal(cfg); const uint64_t n = wal.replay(0, [](const auto&) {}); uint64_t unreadable = 0, short_ = 0; for (const auto& f : wal.lastReplayStats()) { unreadable += f.unreadable; if (f.bytesRead < f.fileBytes) ++short_; } if (n != static_cast(kWriters * kPerWriter) || unreadable || short_) { std::cerr << "replayed " << n << " of " << kWriters * kPerWriter << ", unreadable " << unreadable << ", files ended early " << short_ << "\n"; } assert(n == static_cast(kWriters * kPerWriter)); assert(unreadable == 0 && short_ == 0); fs::remove_all(dir); std::cout << "PASS: WAL entries survive appends racing sync()\n"; } // v2.21.6 - the WAL reader resynchronises past a damaged record instead of // abandoning the rest of the file (a production file lost 160,261 intact // records behind one damaged one). Each case damages a real WAL file and // checks exactly which entries come back. namespace walresync { using smartbotic::database::WriteAheadLog; using smartbotic::database::WalEntry; constexpr int kN = 200; std::vector readAll(const fs::path& p) { std::ifstream in(p, std::ios::binary); return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; } void writeAll(const fs::path& p, const std::vector& b) { std::ofstream out(p, std::ios::binary | std::ios::trunc); out.write(reinterpret_cast(b.data()), static_cast(b.size())); } // Record start offsets (the header is 16 bytes, each record is len + body). std::vector offsets(const std::vector& b) { std::vector o; size_t off = 16; while (off + 4 <= b.size()) { uint32_t len = 0; std::memcpy(&len, &b[off], 4); o.push_back(off); off += 4 + len; } return o; } fs::path makeWal(const std::string& name, WriteAheadLog::Config& cfg) { auto dir = makeSnapshotDir(name); cfg.walDir = dir; WriteAheadLog wal(cfg); assert(wal.open()); for (int i = 0; i < kN; ++i) { Document d; d.id = "d" + std::to_string(i); d.set_data(nlohmann::json{{"i", i}, {"pad", std::string(100 + (i * 7) % 90, 'q')}}); wal.append(WriteAheadLog::makeInsertEntry("t", d, "n")); } wal.close(); return dir / "wal-current.log"; } // Replays the WAL; returns the sequences seen and the file's stats. std::vector replayAll(WriteAheadLog::Config& cfg, WriteAheadLog::ReplayFileStats& st) { WriteAheadLog wal(cfg); std::vector seqs; wal.replay(0, [&](const WalEntry& e) { seqs.push_back(e.sequence); }); st = wal.lastReplayStats().at(0); return seqs; } bool missingOnly(const std::vector& seqs, const std::set& lost) { std::vector want; for (uint64_t s = 1; s <= kN; ++s) if (!lost.count(s)) want.push_back(s); if (seqs != want) { std::cerr << "got " << seqs.size() << " entries, want " << want.size() << "\n"; return false; } return true; } } // namespace walresync void test_wal_reader_resyncs_past_damage() { using namespace walresync; // A: one byte deleted inside record 50 (the production shape: the record is // a byte shorter than its length prefix, so everything after it misframes). { WriteAheadLog::Config cfg; auto p = makeWal("resync-delete", cfg); auto b = readAll(p); auto o = offsets(b); b.erase(b.begin() + static_cast(o[49] + 30)); writeAll(p, b); WriteAheadLog::ReplayFileStats st; auto seqs = replayAll(cfg, st); assert(missingOnly(seqs, {50})); assert(st.unreadable == 1 && st.resynced == 1); } // B: one byte flipped inside record 120's data (length intact, checksum fails). { WriteAheadLog::Config cfg; auto p = makeWal("resync-flip", cfg); auto b = readAll(p); auto o = offsets(b); b[o[119] + 40] ^= 0x5a; writeAll(p, b); WriteAheadLog::ReplayFileStats st; auto seqs = replayAll(cfg, st); assert(missingOnly(seqs, {120})); assert(st.checksumFailures == 1); } // C: record 10's length prefix replaced by garbage. { WriteAheadLog::Config cfg; auto p = makeWal("resync-length", cfg); auto b = readAll(p); auto o = offsets(b); b[o[9]] = 0xf0; b[o[9] + 1] = 0xff; b[o[9] + 2] = 0xff; b[o[9] + 3] = 0x7f; writeAll(p, b); WriteAheadLog::ReplayFileStats st; auto seqs = replayAll(cfg, st); assert(missingOnly(seqs, {10})); } // D: 1,000 bytes zeroed from the middle of record 80: exactly the records // the region touches are lost. { WriteAheadLog::Config cfg; auto p = makeWal("resync-zero", cfg); auto b = readAll(p); auto o = offsets(b); const size_t from = o[79] + 20, to = from + 1000; std::set lost; for (size_t k = 0; k < o.size(); ++k) { const size_t end = k + 1 < o.size() ? o[k + 1] : b.size(); if (o[k] < to && end > from) lost.insert(k + 1); } std::fill(b.begin() + static_cast(from), b.begin() + static_cast(to), 0); writeAll(p, b); WriteAheadLog::ReplayFileStats st; auto seqs = replayAll(cfg, st); assert(lost.size() >= 3); assert(missingOnly(seqs, lost)); } // E: a torn tail (a crash mid-write): open() cuts it, the sequence continues // from the last valid record, and an append after it is readable. { WriteAheadLog::Config cfg; auto p = makeWal("resync-torn", cfg); auto b = readAll(p); auto o = offsets(b); b.resize(o.back() + 25); // record 200 half-written writeAll(p, b); { WriteAheadLog wal(cfg); assert(wal.open()); assert(wal.lastOpenTruncatedBytes() == 25); assert(wal.currentSequence() == kN - 1); Document d; d.id = "after"; d.set_data(nlohmann::json{{"x", 1}}); assert(wal.append(WriteAheadLog::makeInsertEntry("t", d, "n")) == kN); wal.close(); } WriteAheadLog::ReplayFileStats st; auto seqs = replayAll(cfg, st); assert(seqs.size() == static_cast(kN) && seqs.back() == kN); assert(st.unreadable == 0 && st.bytesRead == st.fileBytes); } // F: damage in the current file before a reopen: the highest sequence is // still found, so a new append does not reuse one already on disk. { WriteAheadLog::Config cfg; auto p = makeWal("resync-reopen", cfg); auto b = readAll(p); auto o = offsets(b); b.erase(b.begin() + static_cast(o[29] + 30)); writeAll(p, b); WriteAheadLog wal(cfg); assert(wal.open()); assert(wal.currentSequence() == kN); Document d; d.id = "next"; d.set_data(nlohmann::json{{"x", 1}}); assert(wal.append(WriteAheadLog::makeInsertEntry("t", d, "n")) == kN + 1); wal.close(); } std::cout << "PASS: WAL reader resynchronises past damaged records\n"; } // ────────────────────────────────────────────────────────── // Test 6: loadWithFallback throws when all snapshots corrupt // ────────────────────────────────────────────────────────── void test_loadWithFallback_throws_when_all_corrupt() { auto dir = makeSnapshotDir("allcorrupt"); SnapshotManager::Config scfg; scfg.snapshotDir = dir; scfg.maxSnapshots = 10; SnapshotManager mgr(scfg); MemoryStore store(defaultStoreConfig()); store.start(); store.createCollection("docs", CollectionOptions{}); store.insert("docs", makeDoc("d1")); auto s1 = mgr.createSnapshot(store, 1); std::this_thread::sleep_for(std::chrono::seconds(1)); store.insert("docs", makeDoc("d2")); auto s2 = mgr.createSnapshot(store, 2); store.stop(); // Corrupt both fs::resize_file(s1, fs::file_size(s1) / 2); fs::resize_file(s2, fs::file_size(s2) / 2); MemoryStore store2(defaultStoreConfig()); store2.start(); bool threw = false; try { mgr.loadWithFallback(store2); } catch (const std::exception& e) { threw = true; std::string msg = e.what(); assert(msg.find("all") != std::string::npos); } assert(threw); store2.stop(); fs::remove_all(dir); std::cout << "PASS: loadWithFallback throws when all snapshots corrupt\n"; } // ────────────────────────────────────────────────────────── // Test 7: v4 chunked format round-trips at scale (multi-chunk path) // ────────────────────────────────────────────────────────── void test_v4_format_roundtrip_at_scale() { auto dir = makeSnapshotDir("v4scale"); SnapshotManager::Config scfg; scfg.snapshotDir = dir; scfg.compressionEnabled = true; SnapshotManager mgr(scfg); MemoryStore::Config storeCfg = defaultStoreConfig(); storeCfg.maxMemoryBytes = 512ULL * 1024 * 1024; // room for 10K x ~2 KB docs MemoryStore store(storeCfg); store.start(); store.createCollection("docs", CollectionOptions{}); // Make each doc ~2 KB so 10,000 docs > 16 MB, forcing multi-chunk body. std::string bigString(2000, 'x'); for (int i = 0; i < 10000; i++) { Document d; d.id = "d" + std::to_string(i); d.set_data(nlohmann::json{{"value", bigString}, {"i", i}}); store.insert("docs", d); } auto path = mgr.createSnapshot(store, 1); store.stop(); MemoryStore store2(storeCfg); store2.start(); uint64_t seq = mgr.loadSnapshot(path, store2); assert(seq == 1); auto d = store2.get("docs", "d9999"); assert(d.has_value()); assert((*d).data()["i"].get() == 9999); store2.stop(); fs::remove_all(dir); std::cout << "PASS: v4 chunked format round-trips at scale (10K docs, 20MB+)\n"; } // ────────────────────────────────────────────────────────── // Test 8: WAL sequence anchoring (regression for v1.7.2) // // After a snapshot at sequence S, truncateBefore(S) deletes every WAL // file (because all entries have sequence ≤ S). The next boot's // wal_->open() finds no files, so sequence_ stays at 0. Subsequent // appends would produce 1, 2, 3, … which look "older than the snapshot" // to the boot AFTER that and get silently dropped by recovery's // `replay(snapSeq)` filter. // // PersistenceManager::replayWal now calls wal_->setSequenceFloor(snapSeq) // to anchor the WAL counter to the snapshot's walSequence — this test // exercises that anchoring directly on the WAL. // // Bug fingerprint on Zoe (2026-05-07): messages from 10:55–11:41 lost // across the 11:42 restart; same migration applied twice across the // two boots because the migrations-applied marker was written with // sequence 1 and discarded by the next recovery. // ────────────────────────────────────────────────────────── void test_wal_sequence_floor_anchors_after_truncate() { using smartbotic::database::WriteAheadLog; auto dir = makeSnapshotDir("wal-floor"); WriteAheadLog::Config cfg; cfg.walDir = dir; // Phase 1 — fresh WAL, append 5 entries, snapshot at seq=5, // truncate everything ≤ 5. Mirrors the steady-state cycle. { WriteAheadLog wal(cfg); assert(wal.open()); for (int i = 0; i < 5; ++i) { auto entry = WriteAheadLog::makeInsertEntry( "test", makeDoc("d" + std::to_string(i)), "test-node"); uint64_t seq = wal.append(std::move(entry)); assert(seq == static_cast(i + 1)); } assert(wal.currentSequence() == 5); wal.truncateBefore(5); wal.close(); } // After truncate the on-disk WAL files are deleted. The next boot // simulates the post-snapshot startup. { WriteAheadLog wal(cfg); assert(wal.open()); // Without anchoring, sequence_ would be 0 here — that's the bug. // The recovery path is responsible for raising the floor; the // WAL itself has no way to know about the snapshot. assert(wal.currentSequence() == 0); // Now anchor to the snapshot's walSequence (5). wal.setSequenceFloor(5); assert(wal.currentSequence() == 5); // setSequenceFloor must be monotonic — calling with a lower // value is a no-op. wal.setSequenceFloor(3); assert(wal.currentSequence() == 5); // Subsequent appends produce 6, 7, … — strictly greater than // the snapshot's walSequence, so the next boot's recovery // (which calls `replay(snapSeq)` with snapSeq=5) will see them. auto entry = WriteAheadLog::makeInsertEntry( "test", makeDoc("post"), "test-node"); uint64_t seq = wal.append(std::move(entry)); assert(seq == 6); wal.close(); } // Phase 2 — re-open one more time, verify sequence_ recovers from // the new on-disk file at 6 (open() reads the highest entry). { WriteAheadLog wal(cfg); assert(wal.open()); assert(wal.currentSequence() >= 6); wal.close(); } fs::remove_all(dir); std::cout << "PASS: WAL sequence floor anchors after snapshot truncate\n"; } // ────────────────────────────────────────────────────────── // Test: snapshot must include evicted documents (v1.7.3 fix) // ────────────────────────────────────────────────────────── // // Pre-v1.7.3: serializeStore() walked only `coll->documents` (in-memory), // silently omitting docs that had been evicted to stubs. Each snapshot // rotation truncated the WAL past the snapshot's sequence, deleting the // only remaining copy of those evicted docs — they were lost forever // across the next restart. void test_snapshot_includes_evicted_documents() { using smartbotic::database::WriteAheadLog; auto snapDir = makeSnapshotDir("evict-snap"); auto walDir = makeSnapshotDir("evict-wal"); WriteAheadLog::Config walCfg; walCfg.walDir = walDir; WriteAheadLog wal(walCfg); if (!wal.open()) { std::cerr << "FAIL: wal.open() returned false\n"; std::exit(2); } // Tiny memory limit so eviction fires under load. MemoryStore::Config storeCfg; storeCfg.nodeId = "test"; storeCfg.maxMemoryBytes = 32ULL * 1024; storeCfg.evictionThresholdPercent = 50; storeCfg.evictionTargetPercent = 30; storeCfg.hotWriteFloorMs = 0; // disable hot-write protection storeCfg.evictionChunkSize = 1000; MemoryStore store(storeCfg); store.start(); store.createCollection("docs", CollectionOptions{}); // Wire load callback: scan WAL for the requested doc, same path // production uses (database_service.cpp installs a similar lambda // backed by PersistenceManager::loadDocument). store.setDocumentLoadCallback( [&wal](const std::string& coll, const std::string& id, uint64_t /*walSeq*/) -> std::optional { std::optional found; wal.replay(0, [&](const smartbotic::database::WalEntry& e) { if (e.collection == coll && e.documentId == id && e.data.has_value()) { Document d = Document::fromJson(*e.data); d.id = id; d.collection = coll; found = d; } }); return found; }); // Insert N docs, mirroring to WAL so the load callback can resolve them. constexpr int N = 100; for (int i = 0; i < N; ++i) { Document d = makeDoc("doc-" + std::to_string(i)); { auto tree = d.data(); tree["padding"] = std::string(300, 'x'); // make eviction meaningful d.set_data(tree); } wal.append(WriteAheadLog::makeInsertEntry("docs", d, "test")); store.insert("docs", d); } // Force eviction. store.evictDocuments(); auto evictedIds = store.getEvictedDocumentIds("docs"); auto inMemoryDocs = store.getAllDocuments("docs"); assert(!evictedIds.empty()); assert(evictedIds.size() + inMemoryDocs.size() == static_cast(N)); // Flush WAL so the load callback (which reads via ifstream) sees every // entry. In production the WAL is synced periodically by the persistence // manager; tests need to force it. wal.sync(); // Take snapshot. SnapshotManager::Config scfg; scfg.snapshotDir = snapDir; SnapshotManager mgr(scfg); auto path = mgr.createSnapshot(store, wal.currentSequence()); // Load into fresh store with a huge memory budget so eviction doesn't // fire during verification — we want to see every doc in-memory. MemoryStore::Config newCfg = storeCfg; newCfg.maxMemoryBytes = 256ULL * 1024 * 1024; MemoryStore newStore(newCfg); newStore.start(); mgr.loadSnapshot(path, newStore); auto loadedDocs = newStore.getAllDocuments("docs"); auto loadedEvicted = newStore.getEvictedDocumentIds("docs"); const size_t totalLoaded = loadedDocs.size() + loadedEvicted.size(); // Real check (assert is a no-op in Release builds with NDEBUG). if (totalLoaded != static_cast(N)) { std::cerr << "FAIL: snapshot lost docs — loaded " << loadedDocs.size() << " in-memory + " << loadedEvicted.size() << " evicted = " << totalLoaded << " of " << N << " inserted\n"; std::exit(1); } std::unordered_set loadedIdSet; for (const auto& d : loadedDocs) loadedIdSet.insert(d.id); for (const auto& id : loadedEvicted) loadedIdSet.insert(id); for (const auto& id : evictedIds) { if (loadedIdSet.count(id) != 1) { std::cerr << "FAIL: evicted doc " << id << " missing from loaded snapshot\n"; std::exit(1); } } wal.close(); fs::remove_all(snapDir); fs::remove_all(walDir); std::cout << "PASS: snapshot includes evicted documents (" << inMemoryDocs.size() << " in-memory + " << evictedIds.size() << " evicted, all " << N << " round-tripped)\n"; } // ────────────────────────────────────────────────────────── // Test: eviction stubs carry the real WAL sequence (v1.7.4 fix) // ────────────────────────────────────────────────────────── // // Pre-v1.7.4 the stub stored doc.version (1, 2, 3…) under the misleading // name `walSequence`. Production load callbacks therefore couldn't use // it as a `fromSequence` hint and fell back to scanning the entire WAL // from sequence 0 on every evicted-doc fault — O(WAL_size) per fault, // O(WAL_size × evicted_count) per eviction tick. void test_evict_stub_carries_real_wal_sequence() { using smartbotic::database::WriteAheadLog; auto walDir = makeSnapshotDir("stub-walseq"); WriteAheadLog::Config walCfg; walCfg.walDir = walDir; WriteAheadLog wal(walCfg); if (!wal.open()) { std::cerr << "wal.open failed\n"; std::exit(2); } 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{}); // Insert N docs. Mirror to WAL and record the actual sequence on the // store — this is what database_service.cpp's persist callback does. constexpr int N = 50; std::unordered_map expectedSeq; for (int i = 0; i < N; ++i) { Document d = makeDoc("doc-" + std::to_string(i)); { auto tree = d.data(); tree["padding"] = std::string(300, 'x'); d.set_data(tree); } uint64_t seq = wal.append(WriteAheadLog::makeInsertEntry("docs", d, "test")); store.insert("docs", d); store.recordWalSequence("docs", d.id, seq); expectedSeq[d.id] = seq; } // Re-write a few docs so their `walSequence` should match the LATEST // append, not the first one. for (int i = 0; i < 5; ++i) { Document d = makeDoc("doc-" + std::to_string(i)); { auto tree = d.data(); tree["padding"] = std::string(400, 'y'); d.set_data(tree); } d.version = 2; uint64_t seq = wal.append(WriteAheadLog::makeUpdateEntry("docs", d, "test")); store.update("docs", d.id, d); store.recordWalSequence("docs", d.id, seq); expectedSeq[d.id] = seq; } store.evictDocuments(); auto evictedIds = store.getEvictedDocumentIds("docs"); if (evictedIds.empty()) { std::cerr << "FAIL: no docs evicted — eviction config too lax\n"; std::exit(1); } // Every evicted stub must have the real (latest-append) seq, not 0 // and not the per-doc version (1 or 2). for (const auto& id : evictedIds) { auto stub = store.getEvictedStub("docs", id); if (!stub) { std::cerr << "FAIL: no stub for " << id << "\n"; std::exit(1); } uint64_t want = expectedSeq[id]; if (stub->walSequence != want) { std::cerr << "FAIL: stub.walSequence=" << stub->walSequence << " for " << id << ", expected " << want << " (real WAL sequence)\n"; std::exit(1); } // Sanity: must not equal a per-doc version counter (≤ 2 here). if (stub->walSequence <= 2) { std::cerr << "FAIL: stub.walSequence=" << stub->walSequence << " looks like a per-doc version, not a WAL seq\n"; std::exit(1); } } wal.close(); fs::remove_all(walDir); std::cout << "PASS: evict stubs carry real WAL sequence (" << evictedIds.size() << " stubs verified, all match " << "their last wal.append() return value)\n"; } // ────────────────────────────────────────────────────────── // 2.21.0: the writer streams. A production store was OOM-killed at every // snapshot because the writer held the whole serialised body, a compressed // copy beside it, and a copy of each collection's documents. // ────────────────────────────────────────────────────────── namespace { long procStatusKb(const char* key) { std::ifstream in("/proc/self/status"); std::string line; const std::string k = std::string(key) + ":"; while (std::getline(in, line)) { if (line.rfind(k, 0) == 0) return std::stol(line.substr(k.size())); } return -1; } } // namespace void test_streaming_snapshot_memory_is_bounded() { auto dir = makeSnapshotDir("streaming-mem"); SnapshotManager::Config scfg; scfg.snapshotDir = dir; SnapshotManager mgr(scfg); MemoryStore::Config mcfg = defaultStoreConfig(); mcfg.maxMemoryBytes = 8ULL * 1024 * 1024 * 1024; // no eviction in this test MemoryStore store(mcfg); store.start(); store.createCollection("big", CollectionOptions{}); // ~160 MB of JSON in ONE collection: the old writer's peak grew by more // than that (body + compressed body + a copy of the collection). Random // text so LZ4 cannot shrink the compressed copy to nothing. uint64_t rng = 88172645463325252ULL; const int kDocs = 4000; for (int i = 0; i < kDocs; ++i) { std::string payload(40000, ' '); for (auto& c : payload) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; c = static_cast('a' + (rng % 26)); } Document d; d.id = "d" + std::to_string(i); d.set_data(nlohmann::json{{"payload", payload}, {"i", i}}); store.insert("big", d); } // Reset the high-water mark (Linux >= 4.0), then measure what the // snapshot itself adds above the current RSS. { std::ofstream("/proc/self/clear_refs") << "5"; } const long rssBefore = procStatusKb("VmRSS"); const long hwmReset = procStatusKb("VmHWM"); auto path = mgr.createSnapshot(store, 7); const long hwmAfter = procStatusKb("VmHWM"); const long growthMb = (hwmAfter - rssBefore) / 1024; std::cout << " snapshot " << (fs::file_size(path) >> 20) << " MB on disk; peak RSS grew " << growthMb << " MB over " << (rssBefore >> 10) << " MB (hwm reset to " << (hwmReset >> 10) << " MB)\n"; if (hwmReset < 0 || hwmReset > rssBefore + 1024) { std::cout << " (clear_refs unsupported here: memory bound not checked)\n"; } else if (growthMb > 64) { std::cerr << "FAIL: snapshot peak grew " << growthMb << " MB, expected <= 64 MB\n"; std::exit(1); } store.stop(); MemoryStore store2(mcfg); store2.start(); assert(mgr.loadSnapshot(path, store2) == 7); for (int i : {0, 1999, kDocs - 1}) { auto doc = store2.get("big", "d" + std::to_string(i)); assert(doc.has_value()); assert(doc->data()["i"] == i); assert(doc->data()["payload"].get().size() == 40000); } assert(store2.getDocumentIds("big").size() == static_cast(kDocs)); store2.stop(); fs::remove_all(dir); std::cout << "PASS: streaming snapshot memory is bounded\n"; } // Many chunks, documents larger than a chunk, compressed and not. void test_streaming_snapshot_small_chunks_round_trip() { for (bool compress : {true, false}) { auto dir = makeSnapshotDir(compress ? "chunks-lz4" : "chunks-raw"); SnapshotManager::Config scfg; scfg.snapshotDir = dir; scfg.chunkBytes = 1000; scfg.compressionEnabled = compress; SnapshotManager mgr(scfg); MemoryStore store(defaultStoreConfig()); store.start(); store.createCollection("a", CollectionOptions{}); store.createCollection("b", CollectionOptions{}); for (int i = 0; i < 300; ++i) { Document d; d.id = "x" + std::to_string(i); d.set_data(nlohmann::json{{"s", std::string(static_cast(i * 17), 'q')}, {"i", i}}); store.insert(i % 2 ? "a" : "b", d); } auto path = mgr.createSnapshot(store, 5); assert(mgr.verifySnapshot(path)); auto info = mgr.getSnapshotInfo(path); assert(info && info->documentCount == 300 && info->collectionCount == 2); assert(info->compressionType == (compress ? 1u : 0u)); store.stop(); MemoryStore store2(defaultStoreConfig()); store2.start(); assert(mgr.loadSnapshot(path, store2) == 5); for (int i = 0; i < 300; ++i) { auto doc = store2.get(i % 2 ? "a" : "b", "x" + std::to_string(i)); assert(doc.has_value()); assert(doc->data()["s"].get().size() == static_cast(i * 17)); } store2.stop(); fs::remove_all(dir); } std::cout << "PASS: streaming snapshot round-trips over many small chunks\n"; } // A snapshot that never finished leaves a marker the next boot reports; one // that finishes (or fails with an exception, which is logged) removes it. void test_interrupted_snapshot_marker() { auto dir = makeSnapshotDir("marker"); SnapshotManager::Config scfg; scfg.snapshotDir = dir; SnapshotManager mgr(scfg); assert(!mgr.interruptedSnapshot()); { std::ofstream(mgr.inProgressMarkerPath()) << "1760000000000 406829\n"; } auto r = mgr.interruptedSnapshot(); assert(r && r->startedMs == 1760000000000ULL && r->walSequence == 406829); MemoryStore store(defaultStoreConfig()); store.start(); store.createCollection("docs", CollectionOptions{}); store.insert("docs", makeDoc("d1")); mgr.createSnapshot(store, 3); assert(!mgr.interruptedSnapshot()); store.stop(); fs::remove_all(dir); 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 { 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(); test_verification_catches_truncation(); test_loadWithFallback_uses_older_when_newest_corrupt(); test_orphaned_tmp_cleaned_by_listSnapshots(); test_snapshot_survives_concurrent_listing(); test_wal_append_races_sync(); test_wal_reader_resyncs_past_damage(); test_loadWithFallback_throws_when_all_corrupt(); test_v4_format_roundtrip_at_scale(); test_wal_sequence_floor_anchors_after_truncate(); test_snapshot_includes_evicted_documents(); test_evict_stub_carries_real_wal_sequence(); 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; }