test_snapshot_durability.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  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. // v2.21.5 - WriteAheadLog::sync() flushed the std::ofstream WITHOUT the write
  245. // mutex while append() wrote to it under the mutex, from the WAL sync thread
  246. // every interval and from flushWal(). A std::filebuf is not thread-safe: a
  247. // production WAL file held one record a byte shorter than its length prefix,
  248. // and replay abandoned the 160,261 intact records behind it. Writers append
  249. // while another thread syncs in a loop; every entry must replay.
  250. void test_wal_append_races_sync() {
  251. using smartbotic::database::WriteAheadLog;
  252. auto dir = makeSnapshotDir("wal-sync-race");
  253. WriteAheadLog::Config cfg;
  254. cfg.walDir = dir;
  255. constexpr int kWriters = 4, kPerWriter = 15000;
  256. {
  257. WriteAheadLog wal(cfg);
  258. assert(wal.open());
  259. std::atomic<bool> done{false};
  260. std::thread syncer([&] { while (!done.load()) wal.sync(); });
  261. std::vector<std::thread> writers;
  262. for (int w = 0; w < kWriters; ++w) {
  263. writers.emplace_back([&wal, w] {
  264. for (int i = 0; i < kPerWriter; ++i) {
  265. Document d;
  266. d.id = "w" + std::to_string(w) + "-" + std::to_string(i);
  267. d.set_data(nlohmann::json{{"pad", std::string(100 + (i % 400), 'p')}});
  268. wal.append(WriteAheadLog::makeInsertEntry("t", d, "n"));
  269. }
  270. });
  271. }
  272. for (auto& t : writers) t.join();
  273. done = true;
  274. syncer.join();
  275. wal.close();
  276. }
  277. WriteAheadLog wal(cfg);
  278. const uint64_t n = wal.replay(0, [](const auto&) {});
  279. uint64_t unreadable = 0, short_ = 0;
  280. for (const auto& f : wal.lastReplayStats()) {
  281. unreadable += f.unreadable;
  282. if (f.bytesRead < f.fileBytes) ++short_;
  283. }
  284. if (n != static_cast<uint64_t>(kWriters * kPerWriter) || unreadable || short_) {
  285. std::cerr << "replayed " << n << " of " << kWriters * kPerWriter << ", unreadable "
  286. << unreadable << ", files ended early " << short_ << "\n";
  287. }
  288. assert(n == static_cast<uint64_t>(kWriters * kPerWriter));
  289. assert(unreadable == 0 && short_ == 0);
  290. fs::remove_all(dir);
  291. std::cout << "PASS: WAL entries survive appends racing sync()\n";
  292. }
  293. // ──────────────────────────────────────────────────────────
  294. // Test 6: loadWithFallback throws when all snapshots corrupt
  295. // ──────────────────────────────────────────────────────────
  296. void test_loadWithFallback_throws_when_all_corrupt() {
  297. auto dir = makeSnapshotDir("allcorrupt");
  298. SnapshotManager::Config scfg;
  299. scfg.snapshotDir = dir;
  300. scfg.maxSnapshots = 10;
  301. SnapshotManager mgr(scfg);
  302. MemoryStore store(defaultStoreConfig());
  303. store.start();
  304. store.createCollection("docs", CollectionOptions{});
  305. store.insert("docs", makeDoc("d1"));
  306. auto s1 = mgr.createSnapshot(store, 1);
  307. std::this_thread::sleep_for(std::chrono::seconds(1));
  308. store.insert("docs", makeDoc("d2"));
  309. auto s2 = mgr.createSnapshot(store, 2);
  310. store.stop();
  311. // Corrupt both
  312. fs::resize_file(s1, fs::file_size(s1) / 2);
  313. fs::resize_file(s2, fs::file_size(s2) / 2);
  314. MemoryStore store2(defaultStoreConfig());
  315. store2.start();
  316. bool threw = false;
  317. try {
  318. mgr.loadWithFallback(store2);
  319. } catch (const std::exception& e) {
  320. threw = true;
  321. std::string msg = e.what();
  322. assert(msg.find("all") != std::string::npos);
  323. }
  324. assert(threw);
  325. store2.stop();
  326. fs::remove_all(dir);
  327. std::cout << "PASS: loadWithFallback throws when all snapshots corrupt\n";
  328. }
  329. // ──────────────────────────────────────────────────────────
  330. // Test 7: v4 chunked format round-trips at scale (multi-chunk path)
  331. // ──────────────────────────────────────────────────────────
  332. void test_v4_format_roundtrip_at_scale() {
  333. auto dir = makeSnapshotDir("v4scale");
  334. SnapshotManager::Config scfg;
  335. scfg.snapshotDir = dir;
  336. scfg.compressionEnabled = true;
  337. SnapshotManager mgr(scfg);
  338. MemoryStore::Config storeCfg = defaultStoreConfig();
  339. storeCfg.maxMemoryBytes = 512ULL * 1024 * 1024; // room for 10K x ~2 KB docs
  340. MemoryStore store(storeCfg);
  341. store.start();
  342. store.createCollection("docs", CollectionOptions{});
  343. // Make each doc ~2 KB so 10,000 docs > 16 MB, forcing multi-chunk body.
  344. std::string bigString(2000, 'x');
  345. for (int i = 0; i < 10000; i++) {
  346. Document d;
  347. d.id = "d" + std::to_string(i);
  348. d.set_data(nlohmann::json{{"value", bigString}, {"i", i}});
  349. store.insert("docs", d);
  350. }
  351. auto path = mgr.createSnapshot(store, 1);
  352. store.stop();
  353. MemoryStore store2(storeCfg);
  354. store2.start();
  355. uint64_t seq = mgr.loadSnapshot(path, store2);
  356. assert(seq == 1);
  357. auto d = store2.get("docs", "d9999");
  358. assert(d.has_value());
  359. assert((*d).data()["i"].get<int>() == 9999);
  360. store2.stop();
  361. fs::remove_all(dir);
  362. std::cout << "PASS: v4 chunked format round-trips at scale (10K docs, 20MB+)\n";
  363. }
  364. // ──────────────────────────────────────────────────────────
  365. // Test 8: WAL sequence anchoring (regression for v1.7.2)
  366. //
  367. // After a snapshot at sequence S, truncateBefore(S) deletes every WAL
  368. // file (because all entries have sequence ≤ S). The next boot's
  369. // wal_->open() finds no files, so sequence_ stays at 0. Subsequent
  370. // appends would produce 1, 2, 3, … which look "older than the snapshot"
  371. // to the boot AFTER that and get silently dropped by recovery's
  372. // `replay(snapSeq)` filter.
  373. //
  374. // PersistenceManager::replayWal now calls wal_->setSequenceFloor(snapSeq)
  375. // to anchor the WAL counter to the snapshot's walSequence — this test
  376. // exercises that anchoring directly on the WAL.
  377. //
  378. // Bug fingerprint on Zoe (2026-05-07): messages from 10:55–11:41 lost
  379. // across the 11:42 restart; same migration applied twice across the
  380. // two boots because the migrations-applied marker was written with
  381. // sequence 1 and discarded by the next recovery.
  382. // ──────────────────────────────────────────────────────────
  383. void test_wal_sequence_floor_anchors_after_truncate() {
  384. using smartbotic::database::WriteAheadLog;
  385. auto dir = makeSnapshotDir("wal-floor");
  386. WriteAheadLog::Config cfg;
  387. cfg.walDir = dir;
  388. // Phase 1 — fresh WAL, append 5 entries, snapshot at seq=5,
  389. // truncate everything ≤ 5. Mirrors the steady-state cycle.
  390. {
  391. WriteAheadLog wal(cfg);
  392. assert(wal.open());
  393. for (int i = 0; i < 5; ++i) {
  394. auto entry = WriteAheadLog::makeInsertEntry(
  395. "test", makeDoc("d" + std::to_string(i)), "test-node");
  396. uint64_t seq = wal.append(std::move(entry));
  397. assert(seq == static_cast<uint64_t>(i + 1));
  398. }
  399. assert(wal.currentSequence() == 5);
  400. wal.truncateBefore(5);
  401. wal.close();
  402. }
  403. // After truncate the on-disk WAL files are deleted. The next boot
  404. // simulates the post-snapshot startup.
  405. {
  406. WriteAheadLog wal(cfg);
  407. assert(wal.open());
  408. // Without anchoring, sequence_ would be 0 here — that's the bug.
  409. // The recovery path is responsible for raising the floor; the
  410. // WAL itself has no way to know about the snapshot.
  411. assert(wal.currentSequence() == 0);
  412. // Now anchor to the snapshot's walSequence (5).
  413. wal.setSequenceFloor(5);
  414. assert(wal.currentSequence() == 5);
  415. // setSequenceFloor must be monotonic — calling with a lower
  416. // value is a no-op.
  417. wal.setSequenceFloor(3);
  418. assert(wal.currentSequence() == 5);
  419. // Subsequent appends produce 6, 7, … — strictly greater than
  420. // the snapshot's walSequence, so the next boot's recovery
  421. // (which calls `replay(snapSeq)` with snapSeq=5) will see them.
  422. auto entry = WriteAheadLog::makeInsertEntry(
  423. "test", makeDoc("post"), "test-node");
  424. uint64_t seq = wal.append(std::move(entry));
  425. assert(seq == 6);
  426. wal.close();
  427. }
  428. // Phase 2 — re-open one more time, verify sequence_ recovers from
  429. // the new on-disk file at 6 (open() reads the highest entry).
  430. {
  431. WriteAheadLog wal(cfg);
  432. assert(wal.open());
  433. assert(wal.currentSequence() >= 6);
  434. wal.close();
  435. }
  436. fs::remove_all(dir);
  437. std::cout << "PASS: WAL sequence floor anchors after snapshot truncate\n";
  438. }
  439. // ──────────────────────────────────────────────────────────
  440. // Test: snapshot must include evicted documents (v1.7.3 fix)
  441. // ──────────────────────────────────────────────────────────
  442. //
  443. // Pre-v1.7.3: serializeStore() walked only `coll->documents` (in-memory),
  444. // silently omitting docs that had been evicted to stubs. Each snapshot
  445. // rotation truncated the WAL past the snapshot's sequence, deleting the
  446. // only remaining copy of those evicted docs — they were lost forever
  447. // across the next restart.
  448. void test_snapshot_includes_evicted_documents() {
  449. using smartbotic::database::WriteAheadLog;
  450. auto snapDir = makeSnapshotDir("evict-snap");
  451. auto walDir = makeSnapshotDir("evict-wal");
  452. WriteAheadLog::Config walCfg;
  453. walCfg.walDir = walDir;
  454. WriteAheadLog wal(walCfg);
  455. if (!wal.open()) {
  456. std::cerr << "FAIL: wal.open() returned false\n";
  457. std::exit(2);
  458. }
  459. // Tiny memory limit so eviction fires under load.
  460. MemoryStore::Config storeCfg;
  461. storeCfg.nodeId = "test";
  462. storeCfg.maxMemoryBytes = 32ULL * 1024;
  463. storeCfg.evictionThresholdPercent = 50;
  464. storeCfg.evictionTargetPercent = 30;
  465. storeCfg.hotWriteFloorMs = 0; // disable hot-write protection
  466. storeCfg.evictionChunkSize = 1000;
  467. MemoryStore store(storeCfg);
  468. store.start();
  469. store.createCollection("docs", CollectionOptions{});
  470. // Wire load callback: scan WAL for the requested doc, same path
  471. // production uses (database_service.cpp installs a similar lambda
  472. // backed by PersistenceManager::loadDocument).
  473. store.setDocumentLoadCallback(
  474. [&wal](const std::string& coll, const std::string& id,
  475. uint64_t /*walSeq*/) -> std::optional<Document> {
  476. std::optional<Document> found;
  477. wal.replay(0, [&](const smartbotic::database::WalEntry& e) {
  478. if (e.collection == coll && e.documentId == id && e.data.has_value()) {
  479. Document d = Document::fromJson(*e.data);
  480. d.id = id;
  481. d.collection = coll;
  482. found = d;
  483. }
  484. });
  485. return found;
  486. });
  487. // Insert N docs, mirroring to WAL so the load callback can resolve them.
  488. constexpr int N = 100;
  489. for (int i = 0; i < N; ++i) {
  490. Document d = makeDoc("doc-" + std::to_string(i));
  491. {
  492. auto tree = d.data();
  493. tree["padding"] = std::string(300, 'x'); // make eviction meaningful
  494. d.set_data(tree);
  495. }
  496. wal.append(WriteAheadLog::makeInsertEntry("docs", d, "test"));
  497. store.insert("docs", d);
  498. }
  499. // Force eviction.
  500. store.evictDocuments();
  501. auto evictedIds = store.getEvictedDocumentIds("docs");
  502. auto inMemoryDocs = store.getAllDocuments("docs");
  503. assert(!evictedIds.empty());
  504. assert(evictedIds.size() + inMemoryDocs.size() == static_cast<size_t>(N));
  505. // Flush WAL so the load callback (which reads via ifstream) sees every
  506. // entry. In production the WAL is synced periodically by the persistence
  507. // manager; tests need to force it.
  508. wal.sync();
  509. // Take snapshot.
  510. SnapshotManager::Config scfg;
  511. scfg.snapshotDir = snapDir;
  512. SnapshotManager mgr(scfg);
  513. auto path = mgr.createSnapshot(store, wal.currentSequence());
  514. // Load into fresh store with a huge memory budget so eviction doesn't
  515. // fire during verification — we want to see every doc in-memory.
  516. MemoryStore::Config newCfg = storeCfg;
  517. newCfg.maxMemoryBytes = 256ULL * 1024 * 1024;
  518. MemoryStore newStore(newCfg);
  519. newStore.start();
  520. mgr.loadSnapshot(path, newStore);
  521. auto loadedDocs = newStore.getAllDocuments("docs");
  522. auto loadedEvicted = newStore.getEvictedDocumentIds("docs");
  523. const size_t totalLoaded = loadedDocs.size() + loadedEvicted.size();
  524. // Real check (assert is a no-op in Release builds with NDEBUG).
  525. if (totalLoaded != static_cast<size_t>(N)) {
  526. std::cerr << "FAIL: snapshot lost docs — loaded "
  527. << loadedDocs.size() << " in-memory + "
  528. << loadedEvicted.size() << " evicted = "
  529. << totalLoaded << " of " << N << " inserted\n";
  530. std::exit(1);
  531. }
  532. std::unordered_set<std::string> loadedIdSet;
  533. for (const auto& d : loadedDocs) loadedIdSet.insert(d.id);
  534. for (const auto& id : loadedEvicted) loadedIdSet.insert(id);
  535. for (const auto& id : evictedIds) {
  536. if (loadedIdSet.count(id) != 1) {
  537. std::cerr << "FAIL: evicted doc " << id
  538. << " missing from loaded snapshot\n";
  539. std::exit(1);
  540. }
  541. }
  542. wal.close();
  543. fs::remove_all(snapDir);
  544. fs::remove_all(walDir);
  545. std::cout << "PASS: snapshot includes evicted documents ("
  546. << inMemoryDocs.size() << " in-memory + "
  547. << evictedIds.size() << " evicted, all "
  548. << N << " round-tripped)\n";
  549. }
  550. // ──────────────────────────────────────────────────────────
  551. // Test: eviction stubs carry the real WAL sequence (v1.7.4 fix)
  552. // ──────────────────────────────────────────────────────────
  553. //
  554. // Pre-v1.7.4 the stub stored doc.version (1, 2, 3…) under the misleading
  555. // name `walSequence`. Production load callbacks therefore couldn't use
  556. // it as a `fromSequence` hint and fell back to scanning the entire WAL
  557. // from sequence 0 on every evicted-doc fault — O(WAL_size) per fault,
  558. // O(WAL_size × evicted_count) per eviction tick.
  559. void test_evict_stub_carries_real_wal_sequence() {
  560. using smartbotic::database::WriteAheadLog;
  561. auto walDir = makeSnapshotDir("stub-walseq");
  562. WriteAheadLog::Config walCfg;
  563. walCfg.walDir = walDir;
  564. WriteAheadLog wal(walCfg);
  565. if (!wal.open()) { std::cerr << "wal.open failed\n"; std::exit(2); }
  566. MemoryStore::Config storeCfg;
  567. storeCfg.nodeId = "test";
  568. storeCfg.maxMemoryBytes = 32ULL * 1024;
  569. storeCfg.evictionThresholdPercent = 50;
  570. storeCfg.evictionTargetPercent = 30;
  571. storeCfg.hotWriteFloorMs = 0;
  572. storeCfg.evictionChunkSize = 1000;
  573. MemoryStore store(storeCfg);
  574. store.start();
  575. store.createCollection("docs", CollectionOptions{});
  576. // Insert N docs. Mirror to WAL and record the actual sequence on the
  577. // store — this is what database_service.cpp's persist callback does.
  578. constexpr int N = 50;
  579. std::unordered_map<std::string, uint64_t> expectedSeq;
  580. for (int i = 0; i < N; ++i) {
  581. Document d = makeDoc("doc-" + std::to_string(i));
  582. {
  583. auto tree = d.data();
  584. tree["padding"] = std::string(300, 'x');
  585. d.set_data(tree);
  586. }
  587. uint64_t seq = wal.append(WriteAheadLog::makeInsertEntry("docs", d, "test"));
  588. store.insert("docs", d);
  589. store.recordWalSequence("docs", d.id, seq);
  590. expectedSeq[d.id] = seq;
  591. }
  592. // Re-write a few docs so their `walSequence` should match the LATEST
  593. // append, not the first one.
  594. for (int i = 0; i < 5; ++i) {
  595. Document d = makeDoc("doc-" + std::to_string(i));
  596. {
  597. auto tree = d.data();
  598. tree["padding"] = std::string(400, 'y');
  599. d.set_data(tree);
  600. }
  601. d.version = 2;
  602. uint64_t seq = wal.append(WriteAheadLog::makeUpdateEntry("docs", d, "test"));
  603. store.update("docs", d.id, d);
  604. store.recordWalSequence("docs", d.id, seq);
  605. expectedSeq[d.id] = seq;
  606. }
  607. store.evictDocuments();
  608. auto evictedIds = store.getEvictedDocumentIds("docs");
  609. if (evictedIds.empty()) {
  610. std::cerr << "FAIL: no docs evicted — eviction config too lax\n";
  611. std::exit(1);
  612. }
  613. // Every evicted stub must have the real (latest-append) seq, not 0
  614. // and not the per-doc version (1 or 2).
  615. for (const auto& id : evictedIds) {
  616. auto stub = store.getEvictedStub("docs", id);
  617. if (!stub) {
  618. std::cerr << "FAIL: no stub for " << id << "\n";
  619. std::exit(1);
  620. }
  621. uint64_t want = expectedSeq[id];
  622. if (stub->walSequence != want) {
  623. std::cerr << "FAIL: stub.walSequence=" << stub->walSequence
  624. << " for " << id << ", expected " << want
  625. << " (real WAL sequence)\n";
  626. std::exit(1);
  627. }
  628. // Sanity: must not equal a per-doc version counter (≤ 2 here).
  629. if (stub->walSequence <= 2) {
  630. std::cerr << "FAIL: stub.walSequence=" << stub->walSequence
  631. << " looks like a per-doc version, not a WAL seq\n";
  632. std::exit(1);
  633. }
  634. }
  635. wal.close();
  636. fs::remove_all(walDir);
  637. std::cout << "PASS: evict stubs carry real WAL sequence ("
  638. << evictedIds.size() << " stubs verified, all match "
  639. << "their last wal.append() return value)\n";
  640. }
  641. // ──────────────────────────────────────────────────────────
  642. // 2.21.0: the writer streams. A production store was OOM-killed at every
  643. // snapshot because the writer held the whole serialised body, a compressed
  644. // copy beside it, and a copy of each collection's documents.
  645. // ──────────────────────────────────────────────────────────
  646. namespace {
  647. long procStatusKb(const char* key) {
  648. std::ifstream in("/proc/self/status");
  649. std::string line;
  650. const std::string k = std::string(key) + ":";
  651. while (std::getline(in, line)) {
  652. if (line.rfind(k, 0) == 0) return std::stol(line.substr(k.size()));
  653. }
  654. return -1;
  655. }
  656. } // namespace
  657. void test_streaming_snapshot_memory_is_bounded() {
  658. auto dir = makeSnapshotDir("streaming-mem");
  659. SnapshotManager::Config scfg;
  660. scfg.snapshotDir = dir;
  661. SnapshotManager mgr(scfg);
  662. MemoryStore::Config mcfg = defaultStoreConfig();
  663. mcfg.maxMemoryBytes = 8ULL * 1024 * 1024 * 1024; // no eviction in this test
  664. MemoryStore store(mcfg);
  665. store.start();
  666. store.createCollection("big", CollectionOptions{});
  667. // ~160 MB of JSON in ONE collection: the old writer's peak grew by more
  668. // than that (body + compressed body + a copy of the collection). Random
  669. // text so LZ4 cannot shrink the compressed copy to nothing.
  670. uint64_t rng = 88172645463325252ULL;
  671. const int kDocs = 4000;
  672. for (int i = 0; i < kDocs; ++i) {
  673. std::string payload(40000, ' ');
  674. for (auto& c : payload) {
  675. rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17;
  676. c = static_cast<char>('a' + (rng % 26));
  677. }
  678. Document d;
  679. d.id = "d" + std::to_string(i);
  680. d.set_data(nlohmann::json{{"payload", payload}, {"i", i}});
  681. store.insert("big", d);
  682. }
  683. // Reset the high-water mark (Linux >= 4.0), then measure what the
  684. // snapshot itself adds above the current RSS.
  685. { std::ofstream("/proc/self/clear_refs") << "5"; }
  686. const long rssBefore = procStatusKb("VmRSS");
  687. const long hwmReset = procStatusKb("VmHWM");
  688. auto path = mgr.createSnapshot(store, 7);
  689. const long hwmAfter = procStatusKb("VmHWM");
  690. const long growthMb = (hwmAfter - rssBefore) / 1024;
  691. std::cout << " snapshot " << (fs::file_size(path) >> 20) << " MB on disk; peak RSS grew "
  692. << growthMb << " MB over " << (rssBefore >> 10) << " MB (hwm reset to "
  693. << (hwmReset >> 10) << " MB)\n";
  694. if (hwmReset < 0 || hwmReset > rssBefore + 1024) {
  695. std::cout << " (clear_refs unsupported here: memory bound not checked)\n";
  696. } else if (growthMb > 64) {
  697. std::cerr << "FAIL: snapshot peak grew " << growthMb << " MB, expected <= 64 MB\n";
  698. std::exit(1);
  699. }
  700. store.stop();
  701. MemoryStore store2(mcfg);
  702. store2.start();
  703. assert(mgr.loadSnapshot(path, store2) == 7);
  704. for (int i : {0, 1999, kDocs - 1}) {
  705. auto doc = store2.get("big", "d" + std::to_string(i));
  706. assert(doc.has_value());
  707. assert(doc->data()["i"] == i);
  708. assert(doc->data()["payload"].get<std::string>().size() == 40000);
  709. }
  710. assert(store2.getDocumentIds("big").size() == static_cast<size_t>(kDocs));
  711. store2.stop();
  712. fs::remove_all(dir);
  713. std::cout << "PASS: streaming snapshot memory is bounded\n";
  714. }
  715. // Many chunks, documents larger than a chunk, compressed and not.
  716. void test_streaming_snapshot_small_chunks_round_trip() {
  717. for (bool compress : {true, false}) {
  718. auto dir = makeSnapshotDir(compress ? "chunks-lz4" : "chunks-raw");
  719. SnapshotManager::Config scfg;
  720. scfg.snapshotDir = dir;
  721. scfg.chunkBytes = 1000;
  722. scfg.compressionEnabled = compress;
  723. SnapshotManager mgr(scfg);
  724. MemoryStore store(defaultStoreConfig());
  725. store.start();
  726. store.createCollection("a", CollectionOptions{});
  727. store.createCollection("b", CollectionOptions{});
  728. for (int i = 0; i < 300; ++i) {
  729. Document d;
  730. d.id = "x" + std::to_string(i);
  731. d.set_data(nlohmann::json{{"s", std::string(static_cast<size_t>(i * 17), 'q')}, {"i", i}});
  732. store.insert(i % 2 ? "a" : "b", d);
  733. }
  734. auto path = mgr.createSnapshot(store, 5);
  735. assert(mgr.verifySnapshot(path));
  736. auto info = mgr.getSnapshotInfo(path);
  737. assert(info && info->documentCount == 300 && info->collectionCount == 2);
  738. assert(info->compressionType == (compress ? 1u : 0u));
  739. store.stop();
  740. MemoryStore store2(defaultStoreConfig());
  741. store2.start();
  742. assert(mgr.loadSnapshot(path, store2) == 5);
  743. for (int i = 0; i < 300; ++i) {
  744. auto doc = store2.get(i % 2 ? "a" : "b", "x" + std::to_string(i));
  745. assert(doc.has_value());
  746. assert(doc->data()["s"].get<std::string>().size() == static_cast<size_t>(i * 17));
  747. }
  748. store2.stop();
  749. fs::remove_all(dir);
  750. }
  751. std::cout << "PASS: streaming snapshot round-trips over many small chunks\n";
  752. }
  753. // A snapshot that never finished leaves a marker the next boot reports; one
  754. // that finishes (or fails with an exception, which is logged) removes it.
  755. void test_interrupted_snapshot_marker() {
  756. auto dir = makeSnapshotDir("marker");
  757. SnapshotManager::Config scfg;
  758. scfg.snapshotDir = dir;
  759. SnapshotManager mgr(scfg);
  760. assert(!mgr.interruptedSnapshot());
  761. { std::ofstream(mgr.inProgressMarkerPath()) << "1760000000000 406829\n"; }
  762. auto r = mgr.interruptedSnapshot();
  763. assert(r && r->startedMs == 1760000000000ULL && r->walSequence == 406829);
  764. MemoryStore store(defaultStoreConfig());
  765. store.start();
  766. store.createCollection("docs", CollectionOptions{});
  767. store.insert("docs", makeDoc("d1"));
  768. mgr.createSnapshot(store, 3);
  769. assert(!mgr.interruptedSnapshot());
  770. store.stop();
  771. fs::remove_all(dir);
  772. std::cout << "PASS: an interrupted snapshot is reported until one completes\n";
  773. }
  774. // v2.21.0 - an evicted document whose copy cannot be read must FAIL the
  775. // snapshot, not be written as deleted. Written as deleted, it drops out of the
  776. // snapshot, the WAL holding it is truncated, and the next boot comes up without
  777. // it while LMDB keeps it: a disk-only row (one path to the production "ghost").
  778. void test_unreadable_evicted_document_fails_the_snapshot() {
  779. auto dir = makeSnapshotDir("unreadable-evicted");
  780. MemoryStore::Config storeCfg;
  781. storeCfg.nodeId = "test";
  782. storeCfg.maxMemoryBytes = 32ULL * 1024;
  783. storeCfg.evictionThresholdPercent = 50;
  784. storeCfg.evictionTargetPercent = 30;
  785. storeCfg.hotWriteFloorMs = 0;
  786. storeCfg.evictionChunkSize = 1000;
  787. MemoryStore store(storeCfg);
  788. store.start();
  789. store.createCollection("docs", CollectionOptions{});
  790. // Every evicted copy is unreadable.
  791. store.setDocumentLoadCallback([](const std::string&, const std::string&, uint64_t)
  792. -> std::optional<Document> { return std::nullopt; });
  793. for (int i = 0; i < 100; ++i) {
  794. Document d = makeDoc("doc-" + std::to_string(i));
  795. auto tree = d.data();
  796. tree["padding"] = std::string(300, 'x');
  797. d.set_data(tree);
  798. store.insert("docs", d);
  799. }
  800. store.evictDocuments();
  801. const auto evicted = store.getEvictedDocumentIds("docs");
  802. assert(!evicted.empty());
  803. bool threw = false;
  804. try {
  805. (void)store.copyDocuments("docs", evicted, 0, evicted.size());
  806. } catch (const std::runtime_error&) {
  807. threw = true;
  808. }
  809. assert(threw && "copyDocuments must throw for an evicted document it cannot read");
  810. SnapshotManager::Config scfg;
  811. scfg.snapshotDir = dir;
  812. SnapshotManager mgr(scfg);
  813. bool snapFailed = false;
  814. try {
  815. mgr.createSnapshot(store, 7);
  816. } catch (const std::exception&) {
  817. snapFailed = true;
  818. }
  819. assert(snapFailed && "the snapshot must fail rather than omit the document");
  820. assert(mgr.listSnapshots().empty() && "no snapshot file may be left behind");
  821. store.stop();
  822. fs::remove_all(dir);
  823. std::cout << "PASS: an unreadable evicted document fails the snapshot instead of dropping out\n";
  824. }
  825. int main() {
  826. test_atomic_write_leaves_no_tmp();
  827. test_snapshot_round_trip();
  828. test_verification_catches_truncation();
  829. test_loadWithFallback_uses_older_when_newest_corrupt();
  830. test_orphaned_tmp_cleaned_by_listSnapshots();
  831. test_snapshot_survives_concurrent_listing();
  832. test_wal_append_races_sync();
  833. test_loadWithFallback_throws_when_all_corrupt();
  834. test_v4_format_roundtrip_at_scale();
  835. test_wal_sequence_floor_anchors_after_truncate();
  836. test_snapshot_includes_evicted_documents();
  837. test_evict_stub_carries_real_wal_sequence();
  838. test_streaming_snapshot_memory_is_bounded();
  839. test_streaming_snapshot_small_chunks_round_trip();
  840. test_interrupted_snapshot_marker();
  841. test_unreadable_evicted_document_fails_the_snapshot();
  842. std::cout << "\nAll snapshot durability tests PASSED!\n";
  843. return 0;
  844. }