test_snapshot_durability.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. /**
  2. * Integration tests for v1.6.1 snapshot durability + fallback.
  3. *
  4. * Exercises SnapshotManager directly (no gRPC server).
  5. *
  6. * Test cases:
  7. * 1. atomic write leaves no .tmp file behind
  8. * 2. snapshot round-trip (write then load back)
  9. * 3. post-write verification catches externally-truncated file
  10. * 4. loadWithFallback uses older snapshot when newest is corrupt
  11. * 5. orphaned .tmp files cleaned at boot, never by listSnapshots (2.21.4)
  12. * 6. loadWithFallback throws when all snapshots corrupt
  13. */
  14. #include "../service/src/persistence/snapshot.hpp"
  15. #include "../service/src/persistence/wal.hpp"
  16. #include "../service/src/memory_store.hpp"
  17. #include "../service/src/document.hpp"
  18. #include <atomic>
  19. #include <cassert>
  20. #include <chrono>
  21. #include <cstdint>
  22. #include <filesystem>
  23. #include <fstream>
  24. #include <iostream>
  25. #include <nlohmann/json.hpp>
  26. #include <thread>
  27. #include <unistd.h> // getpid
  28. #include <unordered_set>
  29. namespace fs = std::filesystem;
  30. using smartbotic::database::MemoryStore;
  31. using smartbotic::database::SnapshotManager;
  32. using smartbotic::database::Document;
  33. using smartbotic::database::CollectionOptions;
  34. namespace {
  35. MemoryStore::Config defaultStoreConfig() {
  36. MemoryStore::Config cfg;
  37. cfg.nodeId = "test";
  38. cfg.maxMemoryBytes = 256ULL * 1024 * 1024;
  39. return cfg;
  40. }
  41. fs::path makeSnapshotDir(const std::string& name) {
  42. auto dir = fs::temp_directory_path() /
  43. ("snap-durability-" + name + "-" + std::to_string(::getpid()));
  44. fs::remove_all(dir);
  45. fs::create_directories(dir);
  46. return dir;
  47. }
  48. Document makeDoc(const std::string& id) {
  49. Document d;
  50. d.id = id;
  51. d.set_data(nlohmann::json{{"value", id}});
  52. return d;
  53. }
  54. } // anonymous namespace
  55. // ──────────────────────────────────────────────────────────
  56. // Test 1: atomic write leaves no .tmp file behind
  57. // ──────────────────────────────────────────────────────────
  58. void test_atomic_write_leaves_no_tmp() {
  59. auto dir = makeSnapshotDir("atomic");
  60. SnapshotManager::Config scfg;
  61. scfg.snapshotDir = dir;
  62. scfg.validateAfterWrite = true;
  63. SnapshotManager mgr(scfg);
  64. MemoryStore store(defaultStoreConfig());
  65. store.start();
  66. store.createCollection("docs", CollectionOptions{});
  67. for (int i = 0; i < 50; i++) {
  68. store.insert("docs", makeDoc("d" + std::to_string(i)));
  69. }
  70. auto path = mgr.createSnapshot(store, 42);
  71. // No .tmp files should remain
  72. int tmpCount = 0;
  73. for (auto& e : fs::directory_iterator(dir)) {
  74. if (e.path().extension() == ".tmp") tmpCount++;
  75. }
  76. assert(tmpCount == 0);
  77. // The final file should exist and pass verification
  78. assert(fs::exists(path));
  79. assert(mgr.verifySnapshot(path));
  80. store.stop();
  81. fs::remove_all(dir);
  82. std::cout << "PASS: atomic write leaves no .tmp file behind\n";
  83. }
  84. // ──────────────────────────────────────────────────────────
  85. // Test 2: snapshot round-trips (write then load back)
  86. // ──────────────────────────────────────────────────────────
  87. void test_snapshot_round_trip() {
  88. auto dir = makeSnapshotDir("roundtrip");
  89. SnapshotManager::Config scfg;
  90. scfg.snapshotDir = dir;
  91. SnapshotManager mgr(scfg);
  92. MemoryStore store(defaultStoreConfig());
  93. store.start();
  94. store.createCollection("docs", CollectionOptions{});
  95. for (int i = 0; i < 20; i++) {
  96. store.insert("docs", makeDoc("d" + std::to_string(i)));
  97. }
  98. auto path = mgr.createSnapshot(store, 99);
  99. store.stop();
  100. MemoryStore store2(defaultStoreConfig());
  101. store2.start();
  102. uint64_t seq = mgr.loadSnapshot(path, store2);
  103. assert(seq == 99);
  104. auto doc = store2.get("docs", "d5");
  105. assert(doc.has_value());
  106. store2.stop();
  107. fs::remove_all(dir);
  108. std::cout << "PASS: snapshot round-trip\n";
  109. }
  110. // ──────────────────────────────────────────────────────────
  111. // Test 3: post-write verification catches externally-truncated file
  112. // ──────────────────────────────────────────────────────────
  113. void test_verification_catches_truncation() {
  114. auto dir = makeSnapshotDir("truncate");
  115. SnapshotManager::Config scfg;
  116. scfg.snapshotDir = dir;
  117. SnapshotManager mgr(scfg);
  118. MemoryStore store(defaultStoreConfig());
  119. store.start();
  120. store.createCollection("docs", CollectionOptions{});
  121. for (int i = 0; i < 50; i++) {
  122. store.insert("docs", makeDoc("d" + std::to_string(i)));
  123. }
  124. auto path = mgr.createSnapshot(store, 1);
  125. store.stop();
  126. // Truncate the file AFTER a successful write to simulate the Zoe scenario
  127. uintmax_t original = fs::file_size(path);
  128. fs::resize_file(path, original / 2);
  129. // verifySnapshot should return false
  130. assert(!mgr.verifySnapshot(path));
  131. fs::remove_all(dir);
  132. std::cout << "PASS: post-write verification catches truncation\n";
  133. }
  134. // ──────────────────────────────────────────────────────────
  135. // Test 4: loadWithFallback uses older snapshot when newest is corrupt
  136. // ──────────────────────────────────────────────────────────
  137. void test_loadWithFallback_uses_older_when_newest_corrupt() {
  138. auto dir = makeSnapshotDir("fallback");
  139. SnapshotManager::Config scfg;
  140. scfg.snapshotDir = dir;
  141. scfg.maxSnapshots = 10;
  142. SnapshotManager mgr(scfg);
  143. MemoryStore store(defaultStoreConfig());
  144. store.start();
  145. store.createCollection("docs", CollectionOptions{});
  146. // Older snapshot — 10 docs
  147. for (int i = 0; i < 10; i++) {
  148. store.insert("docs", makeDoc("d" + std::to_string(i)));
  149. }
  150. auto older = mgr.createSnapshot(store, 100);
  151. // Filenames include timestamps down to the second, so sleep to ensure ordering
  152. std::this_thread::sleep_for(std::chrono::seconds(1));
  153. // Newer snapshot — 20 docs
  154. for (int i = 10; i < 20; i++) {
  155. store.insert("docs", makeDoc("d" + std::to_string(i)));
  156. }
  157. auto newer = mgr.createSnapshot(store, 200);
  158. store.stop();
  159. assert(older != newer);
  160. // Corrupt the newer
  161. fs::resize_file(newer, fs::file_size(newer) / 2);
  162. assert(!mgr.verifySnapshot(newer));
  163. // loadWithFallback should transparently fall back to the older
  164. MemoryStore store2(defaultStoreConfig());
  165. store2.start();
  166. fs::path used;
  167. size_t attempted = 0;
  168. uint64_t seq = mgr.loadWithFallback(store2, &used, &attempted);
  169. assert(seq == 100);
  170. assert(used == older);
  171. assert(attempted == 2); // tried newer first, then older
  172. store2.stop();
  173. fs::remove_all(dir);
  174. std::cout << "PASS: loadWithFallback uses older snapshot when newest corrupt\n";
  175. }
  176. // ──────────────────────────────────────────────────────────
  177. // Test 5: orphaned .tmp files cleaned at boot, never by listSnapshots()
  178. // ──────────────────────────────────────────────────────────
  179. // v2.21.4 - listSnapshots() used to delete every .tmp, and GetStats and the
  180. // retention pass call it: a listing while a snapshot was being written killed
  181. // that snapshot ("Failed to reopen snapshot tmp for fsync", seen in production
  182. // right after a boot whose first snapshot was the one that had to truncate a
  183. // 276 MB WAL).
  184. void test_orphaned_tmp_cleaned_by_listSnapshots() {
  185. auto dir = makeSnapshotDir("orphan");
  186. SnapshotManager::Config scfg;
  187. scfg.snapshotDir = dir;
  188. SnapshotManager mgr(scfg);
  189. // Manually plant a fake .tmp like a crashed-mid-write would leave
  190. auto tmp = dir / "snapshot-20260101-120000.dat.tmp";
  191. {
  192. std::ofstream f(tmp);
  193. f << "partial";
  194. }
  195. assert(fs::exists(tmp));
  196. // A listing leaves it alone: it may belong to a snapshot in progress.
  197. (void)mgr.listSnapshots();
  198. assert(fs::exists(tmp));
  199. // Recovery's cleanup removes it.
  200. mgr.removeOrphanedTmpFiles();
  201. assert(!fs::exists(tmp));
  202. fs::remove_all(dir);
  203. std::cout << "PASS: orphaned .tmp cleaned at boot, not by listSnapshots\n";
  204. }
  205. // v2.21.4 - a snapshot completes while another thread keeps listing snapshots
  206. // (what a GetStats poller does).
  207. void test_snapshot_survives_concurrent_listing() {
  208. auto dir = makeSnapshotDir("listing");
  209. SnapshotManager::Config scfg;
  210. scfg.snapshotDir = dir;
  211. scfg.chunkBytes = 64 * 1024;
  212. SnapshotManager mgr(scfg);
  213. MemoryStore store(defaultStoreConfig());
  214. store.start();
  215. store.createCollection("a", CollectionOptions{});
  216. for (int i = 0; i < 4000; ++i) {
  217. Document d;
  218. d.id = "x" + std::to_string(i);
  219. d.set_data(nlohmann::json{{"s", std::string(4000, static_cast<char>('a' + i % 26))}, {"i", i}});
  220. store.insert("a", d);
  221. }
  222. int ok = 0, failed = 0;
  223. for (int round = 0; round < 5; ++round) {
  224. std::atomic<bool> done{false};
  225. std::thread lister([&] {
  226. while (!done.load()) (void)mgr.listSnapshots();
  227. });
  228. try {
  229. auto path = mgr.createSnapshot(store, static_cast<uint64_t>(round + 1));
  230. if (mgr.verifySnapshot(path)) ++ok; else ++failed;
  231. } catch (const std::exception& e) {
  232. std::cerr << "snapshot failed under a concurrent listing: " << e.what() << "\n";
  233. ++failed;
  234. }
  235. done = true;
  236. lister.join();
  237. std::this_thread::sleep_for(std::chrono::milliseconds(1100)); // distinct file names
  238. }
  239. store.stop();
  240. assert(failed == 0 && ok == 5);
  241. fs::remove_all(dir);
  242. std::cout << "PASS: snapshots complete while another thread lists snapshots\n";
  243. }
  244. // ──────────────────────────────────────────────────────────
  245. // Test 6: loadWithFallback throws when all snapshots corrupt
  246. // ──────────────────────────────────────────────────────────
  247. void test_loadWithFallback_throws_when_all_corrupt() {
  248. auto dir = makeSnapshotDir("allcorrupt");
  249. SnapshotManager::Config scfg;
  250. scfg.snapshotDir = dir;
  251. scfg.maxSnapshots = 10;
  252. SnapshotManager mgr(scfg);
  253. MemoryStore store(defaultStoreConfig());
  254. store.start();
  255. store.createCollection("docs", CollectionOptions{});
  256. store.insert("docs", makeDoc("d1"));
  257. auto s1 = mgr.createSnapshot(store, 1);
  258. std::this_thread::sleep_for(std::chrono::seconds(1));
  259. store.insert("docs", makeDoc("d2"));
  260. auto s2 = mgr.createSnapshot(store, 2);
  261. store.stop();
  262. // Corrupt both
  263. fs::resize_file(s1, fs::file_size(s1) / 2);
  264. fs::resize_file(s2, fs::file_size(s2) / 2);
  265. MemoryStore store2(defaultStoreConfig());
  266. store2.start();
  267. bool threw = false;
  268. try {
  269. mgr.loadWithFallback(store2);
  270. } catch (const std::exception& e) {
  271. threw = true;
  272. std::string msg = e.what();
  273. assert(msg.find("all") != std::string::npos);
  274. }
  275. assert(threw);
  276. store2.stop();
  277. fs::remove_all(dir);
  278. std::cout << "PASS: loadWithFallback throws when all snapshots corrupt\n";
  279. }
  280. // ──────────────────────────────────────────────────────────
  281. // Test 7: v4 chunked format round-trips at scale (multi-chunk path)
  282. // ──────────────────────────────────────────────────────────
  283. void test_v4_format_roundtrip_at_scale() {
  284. auto dir = makeSnapshotDir("v4scale");
  285. SnapshotManager::Config scfg;
  286. scfg.snapshotDir = dir;
  287. scfg.compressionEnabled = true;
  288. SnapshotManager mgr(scfg);
  289. MemoryStore::Config storeCfg = defaultStoreConfig();
  290. storeCfg.maxMemoryBytes = 512ULL * 1024 * 1024; // room for 10K x ~2 KB docs
  291. MemoryStore store(storeCfg);
  292. store.start();
  293. store.createCollection("docs", CollectionOptions{});
  294. // Make each doc ~2 KB so 10,000 docs > 16 MB, forcing multi-chunk body.
  295. std::string bigString(2000, 'x');
  296. for (int i = 0; i < 10000; i++) {
  297. Document d;
  298. d.id = "d" + std::to_string(i);
  299. d.set_data(nlohmann::json{{"value", bigString}, {"i", i}});
  300. store.insert("docs", d);
  301. }
  302. auto path = mgr.createSnapshot(store, 1);
  303. store.stop();
  304. MemoryStore store2(storeCfg);
  305. store2.start();
  306. uint64_t seq = mgr.loadSnapshot(path, store2);
  307. assert(seq == 1);
  308. auto d = store2.get("docs", "d9999");
  309. assert(d.has_value());
  310. assert((*d).data()["i"].get<int>() == 9999);
  311. store2.stop();
  312. fs::remove_all(dir);
  313. std::cout << "PASS: v4 chunked format round-trips at scale (10K docs, 20MB+)\n";
  314. }
  315. // ──────────────────────────────────────────────────────────
  316. // Test 8: WAL sequence anchoring (regression for v1.7.2)
  317. //
  318. // After a snapshot at sequence S, truncateBefore(S) deletes every WAL
  319. // file (because all entries have sequence ≤ S). The next boot's
  320. // wal_->open() finds no files, so sequence_ stays at 0. Subsequent
  321. // appends would produce 1, 2, 3, … which look "older than the snapshot"
  322. // to the boot AFTER that and get silently dropped by recovery's
  323. // `replay(snapSeq)` filter.
  324. //
  325. // PersistenceManager::replayWal now calls wal_->setSequenceFloor(snapSeq)
  326. // to anchor the WAL counter to the snapshot's walSequence — this test
  327. // exercises that anchoring directly on the WAL.
  328. //
  329. // Bug fingerprint on Zoe (2026-05-07): messages from 10:55–11:41 lost
  330. // across the 11:42 restart; same migration applied twice across the
  331. // two boots because the migrations-applied marker was written with
  332. // sequence 1 and discarded by the next recovery.
  333. // ──────────────────────────────────────────────────────────
  334. void test_wal_sequence_floor_anchors_after_truncate() {
  335. using smartbotic::database::WriteAheadLog;
  336. auto dir = makeSnapshotDir("wal-floor");
  337. WriteAheadLog::Config cfg;
  338. cfg.walDir = dir;
  339. // Phase 1 — fresh WAL, append 5 entries, snapshot at seq=5,
  340. // truncate everything ≤ 5. Mirrors the steady-state cycle.
  341. {
  342. WriteAheadLog wal(cfg);
  343. assert(wal.open());
  344. for (int i = 0; i < 5; ++i) {
  345. auto entry = WriteAheadLog::makeInsertEntry(
  346. "test", makeDoc("d" + std::to_string(i)), "test-node");
  347. uint64_t seq = wal.append(std::move(entry));
  348. assert(seq == static_cast<uint64_t>(i + 1));
  349. }
  350. assert(wal.currentSequence() == 5);
  351. wal.truncateBefore(5);
  352. wal.close();
  353. }
  354. // After truncate the on-disk WAL files are deleted. The next boot
  355. // simulates the post-snapshot startup.
  356. {
  357. WriteAheadLog wal(cfg);
  358. assert(wal.open());
  359. // Without anchoring, sequence_ would be 0 here — that's the bug.
  360. // The recovery path is responsible for raising the floor; the
  361. // WAL itself has no way to know about the snapshot.
  362. assert(wal.currentSequence() == 0);
  363. // Now anchor to the snapshot's walSequence (5).
  364. wal.setSequenceFloor(5);
  365. assert(wal.currentSequence() == 5);
  366. // setSequenceFloor must be monotonic — calling with a lower
  367. // value is a no-op.
  368. wal.setSequenceFloor(3);
  369. assert(wal.currentSequence() == 5);
  370. // Subsequent appends produce 6, 7, … — strictly greater than
  371. // the snapshot's walSequence, so the next boot's recovery
  372. // (which calls `replay(snapSeq)` with snapSeq=5) will see them.
  373. auto entry = WriteAheadLog::makeInsertEntry(
  374. "test", makeDoc("post"), "test-node");
  375. uint64_t seq = wal.append(std::move(entry));
  376. assert(seq == 6);
  377. wal.close();
  378. }
  379. // Phase 2 — re-open one more time, verify sequence_ recovers from
  380. // the new on-disk file at 6 (open() reads the highest entry).
  381. {
  382. WriteAheadLog wal(cfg);
  383. assert(wal.open());
  384. assert(wal.currentSequence() >= 6);
  385. wal.close();
  386. }
  387. fs::remove_all(dir);
  388. std::cout << "PASS: WAL sequence floor anchors after snapshot truncate\n";
  389. }
  390. // ──────────────────────────────────────────────────────────
  391. // Test: snapshot must include evicted documents (v1.7.3 fix)
  392. // ──────────────────────────────────────────────────────────
  393. //
  394. // Pre-v1.7.3: serializeStore() walked only `coll->documents` (in-memory),
  395. // silently omitting docs that had been evicted to stubs. Each snapshot
  396. // rotation truncated the WAL past the snapshot's sequence, deleting the
  397. // only remaining copy of those evicted docs — they were lost forever
  398. // across the next restart.
  399. void test_snapshot_includes_evicted_documents() {
  400. using smartbotic::database::WriteAheadLog;
  401. auto snapDir = makeSnapshotDir("evict-snap");
  402. auto walDir = makeSnapshotDir("evict-wal");
  403. WriteAheadLog::Config walCfg;
  404. walCfg.walDir = walDir;
  405. WriteAheadLog wal(walCfg);
  406. if (!wal.open()) {
  407. std::cerr << "FAIL: wal.open() returned false\n";
  408. std::exit(2);
  409. }
  410. // Tiny memory limit so eviction fires under load.
  411. MemoryStore::Config storeCfg;
  412. storeCfg.nodeId = "test";
  413. storeCfg.maxMemoryBytes = 32ULL * 1024;
  414. storeCfg.evictionThresholdPercent = 50;
  415. storeCfg.evictionTargetPercent = 30;
  416. storeCfg.hotWriteFloorMs = 0; // disable hot-write protection
  417. storeCfg.evictionChunkSize = 1000;
  418. MemoryStore store(storeCfg);
  419. store.start();
  420. store.createCollection("docs", CollectionOptions{});
  421. // Wire load callback: scan WAL for the requested doc, same path
  422. // production uses (database_service.cpp installs a similar lambda
  423. // backed by PersistenceManager::loadDocument).
  424. store.setDocumentLoadCallback(
  425. [&wal](const std::string& coll, const std::string& id,
  426. uint64_t /*walSeq*/) -> std::optional<Document> {
  427. std::optional<Document> found;
  428. wal.replay(0, [&](const smartbotic::database::WalEntry& e) {
  429. if (e.collection == coll && e.documentId == id && e.data.has_value()) {
  430. Document d = Document::fromJson(*e.data);
  431. d.id = id;
  432. d.collection = coll;
  433. found = d;
  434. }
  435. });
  436. return found;
  437. });
  438. // Insert N docs, mirroring to WAL so the load callback can resolve them.
  439. constexpr int N = 100;
  440. for (int i = 0; i < N; ++i) {
  441. Document d = makeDoc("doc-" + std::to_string(i));
  442. {
  443. auto tree = d.data();
  444. tree["padding"] = std::string(300, 'x'); // make eviction meaningful
  445. d.set_data(tree);
  446. }
  447. wal.append(WriteAheadLog::makeInsertEntry("docs", d, "test"));
  448. store.insert("docs", d);
  449. }
  450. // Force eviction.
  451. store.evictDocuments();
  452. auto evictedIds = store.getEvictedDocumentIds("docs");
  453. auto inMemoryDocs = store.getAllDocuments("docs");
  454. assert(!evictedIds.empty());
  455. assert(evictedIds.size() + inMemoryDocs.size() == static_cast<size_t>(N));
  456. // Flush WAL so the load callback (which reads via ifstream) sees every
  457. // entry. In production the WAL is synced periodically by the persistence
  458. // manager; tests need to force it.
  459. wal.sync();
  460. // Take snapshot.
  461. SnapshotManager::Config scfg;
  462. scfg.snapshotDir = snapDir;
  463. SnapshotManager mgr(scfg);
  464. auto path = mgr.createSnapshot(store, wal.currentSequence());
  465. // Load into fresh store with a huge memory budget so eviction doesn't
  466. // fire during verification — we want to see every doc in-memory.
  467. MemoryStore::Config newCfg = storeCfg;
  468. newCfg.maxMemoryBytes = 256ULL * 1024 * 1024;
  469. MemoryStore newStore(newCfg);
  470. newStore.start();
  471. mgr.loadSnapshot(path, newStore);
  472. auto loadedDocs = newStore.getAllDocuments("docs");
  473. auto loadedEvicted = newStore.getEvictedDocumentIds("docs");
  474. const size_t totalLoaded = loadedDocs.size() + loadedEvicted.size();
  475. // Real check (assert is a no-op in Release builds with NDEBUG).
  476. if (totalLoaded != static_cast<size_t>(N)) {
  477. std::cerr << "FAIL: snapshot lost docs — loaded "
  478. << loadedDocs.size() << " in-memory + "
  479. << loadedEvicted.size() << " evicted = "
  480. << totalLoaded << " of " << N << " inserted\n";
  481. std::exit(1);
  482. }
  483. std::unordered_set<std::string> loadedIdSet;
  484. for (const auto& d : loadedDocs) loadedIdSet.insert(d.id);
  485. for (const auto& id : loadedEvicted) loadedIdSet.insert(id);
  486. for (const auto& id : evictedIds) {
  487. if (loadedIdSet.count(id) != 1) {
  488. std::cerr << "FAIL: evicted doc " << id
  489. << " missing from loaded snapshot\n";
  490. std::exit(1);
  491. }
  492. }
  493. wal.close();
  494. fs::remove_all(snapDir);
  495. fs::remove_all(walDir);
  496. std::cout << "PASS: snapshot includes evicted documents ("
  497. << inMemoryDocs.size() << " in-memory + "
  498. << evictedIds.size() << " evicted, all "
  499. << N << " round-tripped)\n";
  500. }
  501. // ──────────────────────────────────────────────────────────
  502. // Test: eviction stubs carry the real WAL sequence (v1.7.4 fix)
  503. // ──────────────────────────────────────────────────────────
  504. //
  505. // Pre-v1.7.4 the stub stored doc.version (1, 2, 3…) under the misleading
  506. // name `walSequence`. Production load callbacks therefore couldn't use
  507. // it as a `fromSequence` hint and fell back to scanning the entire WAL
  508. // from sequence 0 on every evicted-doc fault — O(WAL_size) per fault,
  509. // O(WAL_size × evicted_count) per eviction tick.
  510. void test_evict_stub_carries_real_wal_sequence() {
  511. using smartbotic::database::WriteAheadLog;
  512. auto walDir = makeSnapshotDir("stub-walseq");
  513. WriteAheadLog::Config walCfg;
  514. walCfg.walDir = walDir;
  515. WriteAheadLog wal(walCfg);
  516. if (!wal.open()) { std::cerr << "wal.open failed\n"; std::exit(2); }
  517. MemoryStore::Config storeCfg;
  518. storeCfg.nodeId = "test";
  519. storeCfg.maxMemoryBytes = 32ULL * 1024;
  520. storeCfg.evictionThresholdPercent = 50;
  521. storeCfg.evictionTargetPercent = 30;
  522. storeCfg.hotWriteFloorMs = 0;
  523. storeCfg.evictionChunkSize = 1000;
  524. MemoryStore store(storeCfg);
  525. store.start();
  526. store.createCollection("docs", CollectionOptions{});
  527. // Insert N docs. Mirror to WAL and record the actual sequence on the
  528. // store — this is what database_service.cpp's persist callback does.
  529. constexpr int N = 50;
  530. std::unordered_map<std::string, uint64_t> expectedSeq;
  531. for (int i = 0; i < N; ++i) {
  532. Document d = makeDoc("doc-" + std::to_string(i));
  533. {
  534. auto tree = d.data();
  535. tree["padding"] = std::string(300, 'x');
  536. d.set_data(tree);
  537. }
  538. uint64_t seq = wal.append(WriteAheadLog::makeInsertEntry("docs", d, "test"));
  539. store.insert("docs", d);
  540. store.recordWalSequence("docs", d.id, seq);
  541. expectedSeq[d.id] = seq;
  542. }
  543. // Re-write a few docs so their `walSequence` should match the LATEST
  544. // append, not the first one.
  545. for (int i = 0; i < 5; ++i) {
  546. Document d = makeDoc("doc-" + std::to_string(i));
  547. {
  548. auto tree = d.data();
  549. tree["padding"] = std::string(400, 'y');
  550. d.set_data(tree);
  551. }
  552. d.version = 2;
  553. uint64_t seq = wal.append(WriteAheadLog::makeUpdateEntry("docs", d, "test"));
  554. store.update("docs", d.id, d);
  555. store.recordWalSequence("docs", d.id, seq);
  556. expectedSeq[d.id] = seq;
  557. }
  558. store.evictDocuments();
  559. auto evictedIds = store.getEvictedDocumentIds("docs");
  560. if (evictedIds.empty()) {
  561. std::cerr << "FAIL: no docs evicted — eviction config too lax\n";
  562. std::exit(1);
  563. }
  564. // Every evicted stub must have the real (latest-append) seq, not 0
  565. // and not the per-doc version (1 or 2).
  566. for (const auto& id : evictedIds) {
  567. auto stub = store.getEvictedStub("docs", id);
  568. if (!stub) {
  569. std::cerr << "FAIL: no stub for " << id << "\n";
  570. std::exit(1);
  571. }
  572. uint64_t want = expectedSeq[id];
  573. if (stub->walSequence != want) {
  574. std::cerr << "FAIL: stub.walSequence=" << stub->walSequence
  575. << " for " << id << ", expected " << want
  576. << " (real WAL sequence)\n";
  577. std::exit(1);
  578. }
  579. // Sanity: must not equal a per-doc version counter (≤ 2 here).
  580. if (stub->walSequence <= 2) {
  581. std::cerr << "FAIL: stub.walSequence=" << stub->walSequence
  582. << " looks like a per-doc version, not a WAL seq\n";
  583. std::exit(1);
  584. }
  585. }
  586. wal.close();
  587. fs::remove_all(walDir);
  588. std::cout << "PASS: evict stubs carry real WAL sequence ("
  589. << evictedIds.size() << " stubs verified, all match "
  590. << "their last wal.append() return value)\n";
  591. }
  592. // ──────────────────────────────────────────────────────────
  593. // 2.21.0: the writer streams. A production store was OOM-killed at every
  594. // snapshot because the writer held the whole serialised body, a compressed
  595. // copy beside it, and a copy of each collection's documents.
  596. // ──────────────────────────────────────────────────────────
  597. namespace {
  598. long procStatusKb(const char* key) {
  599. std::ifstream in("/proc/self/status");
  600. std::string line;
  601. const std::string k = std::string(key) + ":";
  602. while (std::getline(in, line)) {
  603. if (line.rfind(k, 0) == 0) return std::stol(line.substr(k.size()));
  604. }
  605. return -1;
  606. }
  607. } // namespace
  608. void test_streaming_snapshot_memory_is_bounded() {
  609. auto dir = makeSnapshotDir("streaming-mem");
  610. SnapshotManager::Config scfg;
  611. scfg.snapshotDir = dir;
  612. SnapshotManager mgr(scfg);
  613. MemoryStore::Config mcfg = defaultStoreConfig();
  614. mcfg.maxMemoryBytes = 8ULL * 1024 * 1024 * 1024; // no eviction in this test
  615. MemoryStore store(mcfg);
  616. store.start();
  617. store.createCollection("big", CollectionOptions{});
  618. // ~160 MB of JSON in ONE collection: the old writer's peak grew by more
  619. // than that (body + compressed body + a copy of the collection). Random
  620. // text so LZ4 cannot shrink the compressed copy to nothing.
  621. uint64_t rng = 88172645463325252ULL;
  622. const int kDocs = 4000;
  623. for (int i = 0; i < kDocs; ++i) {
  624. std::string payload(40000, ' ');
  625. for (auto& c : payload) {
  626. rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17;
  627. c = static_cast<char>('a' + (rng % 26));
  628. }
  629. Document d;
  630. d.id = "d" + std::to_string(i);
  631. d.set_data(nlohmann::json{{"payload", payload}, {"i", i}});
  632. store.insert("big", d);
  633. }
  634. // Reset the high-water mark (Linux >= 4.0), then measure what the
  635. // snapshot itself adds above the current RSS.
  636. { std::ofstream("/proc/self/clear_refs") << "5"; }
  637. const long rssBefore = procStatusKb("VmRSS");
  638. const long hwmReset = procStatusKb("VmHWM");
  639. auto path = mgr.createSnapshot(store, 7);
  640. const long hwmAfter = procStatusKb("VmHWM");
  641. const long growthMb = (hwmAfter - rssBefore) / 1024;
  642. std::cout << " snapshot " << (fs::file_size(path) >> 20) << " MB on disk; peak RSS grew "
  643. << growthMb << " MB over " << (rssBefore >> 10) << " MB (hwm reset to "
  644. << (hwmReset >> 10) << " MB)\n";
  645. if (hwmReset < 0 || hwmReset > rssBefore + 1024) {
  646. std::cout << " (clear_refs unsupported here: memory bound not checked)\n";
  647. } else if (growthMb > 64) {
  648. std::cerr << "FAIL: snapshot peak grew " << growthMb << " MB, expected <= 64 MB\n";
  649. std::exit(1);
  650. }
  651. store.stop();
  652. MemoryStore store2(mcfg);
  653. store2.start();
  654. assert(mgr.loadSnapshot(path, store2) == 7);
  655. for (int i : {0, 1999, kDocs - 1}) {
  656. auto doc = store2.get("big", "d" + std::to_string(i));
  657. assert(doc.has_value());
  658. assert(doc->data()["i"] == i);
  659. assert(doc->data()["payload"].get<std::string>().size() == 40000);
  660. }
  661. assert(store2.getDocumentIds("big").size() == static_cast<size_t>(kDocs));
  662. store2.stop();
  663. fs::remove_all(dir);
  664. std::cout << "PASS: streaming snapshot memory is bounded\n";
  665. }
  666. // Many chunks, documents larger than a chunk, compressed and not.
  667. void test_streaming_snapshot_small_chunks_round_trip() {
  668. for (bool compress : {true, false}) {
  669. auto dir = makeSnapshotDir(compress ? "chunks-lz4" : "chunks-raw");
  670. SnapshotManager::Config scfg;
  671. scfg.snapshotDir = dir;
  672. scfg.chunkBytes = 1000;
  673. scfg.compressionEnabled = compress;
  674. SnapshotManager mgr(scfg);
  675. MemoryStore store(defaultStoreConfig());
  676. store.start();
  677. store.createCollection("a", CollectionOptions{});
  678. store.createCollection("b", CollectionOptions{});
  679. for (int i = 0; i < 300; ++i) {
  680. Document d;
  681. d.id = "x" + std::to_string(i);
  682. d.set_data(nlohmann::json{{"s", std::string(static_cast<size_t>(i * 17), 'q')}, {"i", i}});
  683. store.insert(i % 2 ? "a" : "b", d);
  684. }
  685. auto path = mgr.createSnapshot(store, 5);
  686. assert(mgr.verifySnapshot(path));
  687. auto info = mgr.getSnapshotInfo(path);
  688. assert(info && info->documentCount == 300 && info->collectionCount == 2);
  689. assert(info->compressionType == (compress ? 1u : 0u));
  690. store.stop();
  691. MemoryStore store2(defaultStoreConfig());
  692. store2.start();
  693. assert(mgr.loadSnapshot(path, store2) == 5);
  694. for (int i = 0; i < 300; ++i) {
  695. auto doc = store2.get(i % 2 ? "a" : "b", "x" + std::to_string(i));
  696. assert(doc.has_value());
  697. assert(doc->data()["s"].get<std::string>().size() == static_cast<size_t>(i * 17));
  698. }
  699. store2.stop();
  700. fs::remove_all(dir);
  701. }
  702. std::cout << "PASS: streaming snapshot round-trips over many small chunks\n";
  703. }
  704. // A snapshot that never finished leaves a marker the next boot reports; one
  705. // that finishes (or fails with an exception, which is logged) removes it.
  706. void test_interrupted_snapshot_marker() {
  707. auto dir = makeSnapshotDir("marker");
  708. SnapshotManager::Config scfg;
  709. scfg.snapshotDir = dir;
  710. SnapshotManager mgr(scfg);
  711. assert(!mgr.interruptedSnapshot());
  712. { std::ofstream(mgr.inProgressMarkerPath()) << "1760000000000 406829\n"; }
  713. auto r = mgr.interruptedSnapshot();
  714. assert(r && r->startedMs == 1760000000000ULL && r->walSequence == 406829);
  715. MemoryStore store(defaultStoreConfig());
  716. store.start();
  717. store.createCollection("docs", CollectionOptions{});
  718. store.insert("docs", makeDoc("d1"));
  719. mgr.createSnapshot(store, 3);
  720. assert(!mgr.interruptedSnapshot());
  721. store.stop();
  722. fs::remove_all(dir);
  723. std::cout << "PASS: an interrupted snapshot is reported until one completes\n";
  724. }
  725. // v2.21.0 - an evicted document whose copy cannot be read must FAIL the
  726. // snapshot, not be written as deleted. Written as deleted, it drops out of the
  727. // snapshot, the WAL holding it is truncated, and the next boot comes up without
  728. // it while LMDB keeps it: a disk-only row (one path to the production "ghost").
  729. void test_unreadable_evicted_document_fails_the_snapshot() {
  730. auto dir = makeSnapshotDir("unreadable-evicted");
  731. MemoryStore::Config storeCfg;
  732. storeCfg.nodeId = "test";
  733. storeCfg.maxMemoryBytes = 32ULL * 1024;
  734. storeCfg.evictionThresholdPercent = 50;
  735. storeCfg.evictionTargetPercent = 30;
  736. storeCfg.hotWriteFloorMs = 0;
  737. storeCfg.evictionChunkSize = 1000;
  738. MemoryStore store(storeCfg);
  739. store.start();
  740. store.createCollection("docs", CollectionOptions{});
  741. // Every evicted copy is unreadable.
  742. store.setDocumentLoadCallback([](const std::string&, const std::string&, uint64_t)
  743. -> std::optional<Document> { return std::nullopt; });
  744. for (int i = 0; i < 100; ++i) {
  745. Document d = makeDoc("doc-" + std::to_string(i));
  746. auto tree = d.data();
  747. tree["padding"] = std::string(300, 'x');
  748. d.set_data(tree);
  749. store.insert("docs", d);
  750. }
  751. store.evictDocuments();
  752. const auto evicted = store.getEvictedDocumentIds("docs");
  753. assert(!evicted.empty());
  754. bool threw = false;
  755. try {
  756. (void)store.copyDocuments("docs", evicted, 0, evicted.size());
  757. } catch (const std::runtime_error&) {
  758. threw = true;
  759. }
  760. assert(threw && "copyDocuments must throw for an evicted document it cannot read");
  761. SnapshotManager::Config scfg;
  762. scfg.snapshotDir = dir;
  763. SnapshotManager mgr(scfg);
  764. bool snapFailed = false;
  765. try {
  766. mgr.createSnapshot(store, 7);
  767. } catch (const std::exception&) {
  768. snapFailed = true;
  769. }
  770. assert(snapFailed && "the snapshot must fail rather than omit the document");
  771. assert(mgr.listSnapshots().empty() && "no snapshot file may be left behind");
  772. store.stop();
  773. fs::remove_all(dir);
  774. std::cout << "PASS: an unreadable evicted document fails the snapshot instead of dropping out\n";
  775. }
  776. int main() {
  777. test_atomic_write_leaves_no_tmp();
  778. test_snapshot_round_trip();
  779. test_verification_catches_truncation();
  780. test_loadWithFallback_uses_older_when_newest_corrupt();
  781. test_orphaned_tmp_cleaned_by_listSnapshots();
  782. test_snapshot_survives_concurrent_listing();
  783. test_loadWithFallback_throws_when_all_corrupt();
  784. test_v4_format_roundtrip_at_scale();
  785. test_wal_sequence_floor_anchors_after_truncate();
  786. test_snapshot_includes_evicted_documents();
  787. test_evict_stub_carries_real_wal_sequence();
  788. test_streaming_snapshot_memory_is_bounded();
  789. test_streaming_snapshot_small_chunks_round_trip();
  790. test_interrupted_snapshot_marker();
  791. test_unreadable_evicted_document_fails_the_snapshot();
  792. std::cout << "\nAll snapshot durability tests PASSED!\n";
  793. return 0;
  794. }