test_snapshot_durability.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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 <cstring>
  23. #include <filesystem>
  24. #include <fstream>
  25. #include <iostream>
  26. #include <nlohmann/json.hpp>
  27. #include <set>
  28. #include <thread>
  29. #include <unistd.h> // getpid
  30. #include <unordered_set>
  31. namespace fs = std::filesystem;
  32. using smartbotic::database::MemoryStore;
  33. using smartbotic::database::SnapshotManager;
  34. using smartbotic::database::Document;
  35. using smartbotic::database::CollectionOptions;
  36. namespace {
  37. MemoryStore::Config defaultStoreConfig() {
  38. MemoryStore::Config cfg;
  39. cfg.nodeId = "test";
  40. cfg.maxMemoryBytes = 256ULL * 1024 * 1024;
  41. return cfg;
  42. }
  43. fs::path makeSnapshotDir(const std::string& name) {
  44. auto dir = fs::temp_directory_path() /
  45. ("snap-durability-" + name + "-" + std::to_string(::getpid()));
  46. fs::remove_all(dir);
  47. fs::create_directories(dir);
  48. return dir;
  49. }
  50. Document makeDoc(const std::string& id) {
  51. Document d;
  52. d.id = id;
  53. d.set_data(nlohmann::json{{"value", id}});
  54. return d;
  55. }
  56. } // anonymous namespace
  57. // ──────────────────────────────────────────────────────────
  58. // Test 1: atomic write leaves no .tmp file behind
  59. // ──────────────────────────────────────────────────────────
  60. void test_atomic_write_leaves_no_tmp() {
  61. auto dir = makeSnapshotDir("atomic");
  62. SnapshotManager::Config scfg;
  63. scfg.snapshotDir = dir;
  64. scfg.validateAfterWrite = true;
  65. SnapshotManager mgr(scfg);
  66. MemoryStore store(defaultStoreConfig());
  67. store.start();
  68. store.createCollection("docs", CollectionOptions{});
  69. for (int i = 0; i < 50; i++) {
  70. store.insert("docs", makeDoc("d" + std::to_string(i)));
  71. }
  72. auto path = mgr.createSnapshot(store, 42);
  73. // No .tmp files should remain
  74. int tmpCount = 0;
  75. for (auto& e : fs::directory_iterator(dir)) {
  76. if (e.path().extension() == ".tmp") tmpCount++;
  77. }
  78. assert(tmpCount == 0);
  79. // The final file should exist and pass verification
  80. assert(fs::exists(path));
  81. assert(mgr.verifySnapshot(path));
  82. store.stop();
  83. fs::remove_all(dir);
  84. std::cout << "PASS: atomic write leaves no .tmp file behind\n";
  85. }
  86. // ──────────────────────────────────────────────────────────
  87. // Test 2: snapshot round-trips (write then load back)
  88. // ──────────────────────────────────────────────────────────
  89. void test_snapshot_round_trip() {
  90. auto dir = makeSnapshotDir("roundtrip");
  91. SnapshotManager::Config scfg;
  92. scfg.snapshotDir = dir;
  93. SnapshotManager mgr(scfg);
  94. MemoryStore store(defaultStoreConfig());
  95. store.start();
  96. store.createCollection("docs", CollectionOptions{});
  97. for (int i = 0; i < 20; i++) {
  98. store.insert("docs", makeDoc("d" + std::to_string(i)));
  99. }
  100. auto path = mgr.createSnapshot(store, 99);
  101. store.stop();
  102. MemoryStore store2(defaultStoreConfig());
  103. store2.start();
  104. uint64_t seq = mgr.loadSnapshot(path, store2);
  105. assert(seq == 99);
  106. auto doc = store2.get("docs", "d5");
  107. assert(doc.has_value());
  108. store2.stop();
  109. fs::remove_all(dir);
  110. std::cout << "PASS: snapshot round-trip\n";
  111. }
  112. // ──────────────────────────────────────────────────────────
  113. // Test 3: post-write verification catches externally-truncated file
  114. // ──────────────────────────────────────────────────────────
  115. void test_verification_catches_truncation() {
  116. auto dir = makeSnapshotDir("truncate");
  117. SnapshotManager::Config scfg;
  118. scfg.snapshotDir = dir;
  119. SnapshotManager mgr(scfg);
  120. MemoryStore store(defaultStoreConfig());
  121. store.start();
  122. store.createCollection("docs", CollectionOptions{});
  123. for (int i = 0; i < 50; i++) {
  124. store.insert("docs", makeDoc("d" + std::to_string(i)));
  125. }
  126. auto path = mgr.createSnapshot(store, 1);
  127. store.stop();
  128. // Truncate the file AFTER a successful write to simulate the Zoe scenario
  129. uintmax_t original = fs::file_size(path);
  130. fs::resize_file(path, original / 2);
  131. // verifySnapshot should return false
  132. assert(!mgr.verifySnapshot(path));
  133. fs::remove_all(dir);
  134. std::cout << "PASS: post-write verification catches truncation\n";
  135. }
  136. // ──────────────────────────────────────────────────────────
  137. // Test 4: loadWithFallback uses older snapshot when newest is corrupt
  138. // ──────────────────────────────────────────────────────────
  139. void test_loadWithFallback_uses_older_when_newest_corrupt() {
  140. auto dir = makeSnapshotDir("fallback");
  141. SnapshotManager::Config scfg;
  142. scfg.snapshotDir = dir;
  143. scfg.maxSnapshots = 10;
  144. SnapshotManager mgr(scfg);
  145. MemoryStore store(defaultStoreConfig());
  146. store.start();
  147. store.createCollection("docs", CollectionOptions{});
  148. // Older snapshot — 10 docs
  149. for (int i = 0; i < 10; i++) {
  150. store.insert("docs", makeDoc("d" + std::to_string(i)));
  151. }
  152. auto older = mgr.createSnapshot(store, 100);
  153. // Filenames include timestamps down to the second, so sleep to ensure ordering
  154. std::this_thread::sleep_for(std::chrono::seconds(1));
  155. // Newer snapshot — 20 docs
  156. for (int i = 10; i < 20; i++) {
  157. store.insert("docs", makeDoc("d" + std::to_string(i)));
  158. }
  159. auto newer = mgr.createSnapshot(store, 200);
  160. store.stop();
  161. assert(older != newer);
  162. // Corrupt the newer
  163. fs::resize_file(newer, fs::file_size(newer) / 2);
  164. assert(!mgr.verifySnapshot(newer));
  165. // loadWithFallback should transparently fall back to the older
  166. MemoryStore store2(defaultStoreConfig());
  167. store2.start();
  168. fs::path used;
  169. size_t attempted = 0;
  170. uint64_t seq = mgr.loadWithFallback(store2, &used, &attempted);
  171. assert(seq == 100);
  172. assert(used == older);
  173. assert(attempted == 2); // tried newer first, then older
  174. store2.stop();
  175. fs::remove_all(dir);
  176. std::cout << "PASS: loadWithFallback uses older snapshot when newest corrupt\n";
  177. }
  178. // ──────────────────────────────────────────────────────────
  179. // Test 5: orphaned .tmp files cleaned at boot, never by listSnapshots()
  180. // ──────────────────────────────────────────────────────────
  181. // v2.21.4 - listSnapshots() used to delete every .tmp, and GetStats and the
  182. // retention pass call it: a listing while a snapshot was being written killed
  183. // that snapshot ("Failed to reopen snapshot tmp for fsync", seen in production
  184. // right after a boot whose first snapshot was the one that had to truncate a
  185. // 276 MB WAL).
  186. void test_orphaned_tmp_cleaned_by_listSnapshots() {
  187. auto dir = makeSnapshotDir("orphan");
  188. SnapshotManager::Config scfg;
  189. scfg.snapshotDir = dir;
  190. SnapshotManager mgr(scfg);
  191. // Manually plant a fake .tmp like a crashed-mid-write would leave
  192. auto tmp = dir / "snapshot-20260101-120000.dat.tmp";
  193. {
  194. std::ofstream f(tmp);
  195. f << "partial";
  196. }
  197. assert(fs::exists(tmp));
  198. // A listing leaves it alone: it may belong to a snapshot in progress.
  199. (void)mgr.listSnapshots();
  200. assert(fs::exists(tmp));
  201. // Recovery's cleanup removes it.
  202. mgr.removeOrphanedTmpFiles();
  203. assert(!fs::exists(tmp));
  204. fs::remove_all(dir);
  205. std::cout << "PASS: orphaned .tmp cleaned at boot, not by listSnapshots\n";
  206. }
  207. // v2.21.4 - a snapshot completes while another thread keeps listing snapshots
  208. // (what a GetStats poller does).
  209. void test_snapshot_survives_concurrent_listing() {
  210. auto dir = makeSnapshotDir("listing");
  211. SnapshotManager::Config scfg;
  212. scfg.snapshotDir = dir;
  213. scfg.chunkBytes = 64 * 1024;
  214. SnapshotManager mgr(scfg);
  215. MemoryStore store(defaultStoreConfig());
  216. store.start();
  217. store.createCollection("a", CollectionOptions{});
  218. for (int i = 0; i < 4000; ++i) {
  219. Document d;
  220. d.id = "x" + std::to_string(i);
  221. d.set_data(nlohmann::json{{"s", std::string(4000, static_cast<char>('a' + i % 26))}, {"i", i}});
  222. store.insert("a", d);
  223. }
  224. int ok = 0, failed = 0;
  225. for (int round = 0; round < 5; ++round) {
  226. std::atomic<bool> done{false};
  227. std::thread lister([&] {
  228. while (!done.load()) (void)mgr.listSnapshots();
  229. });
  230. try {
  231. auto path = mgr.createSnapshot(store, static_cast<uint64_t>(round + 1));
  232. if (mgr.verifySnapshot(path)) ++ok; else ++failed;
  233. } catch (const std::exception& e) {
  234. std::cerr << "snapshot failed under a concurrent listing: " << e.what() << "\n";
  235. ++failed;
  236. }
  237. done = true;
  238. lister.join();
  239. std::this_thread::sleep_for(std::chrono::milliseconds(1100)); // distinct file names
  240. }
  241. store.stop();
  242. assert(failed == 0 && ok == 5);
  243. fs::remove_all(dir);
  244. std::cout << "PASS: snapshots complete while another thread lists snapshots\n";
  245. }
  246. // v2.21.5 - WriteAheadLog::sync() flushed the std::ofstream WITHOUT the write
  247. // mutex while append() wrote to it under the mutex, from the WAL sync thread
  248. // every interval and from flushWal(). A std::filebuf is not thread-safe: a
  249. // production WAL file held one record a byte shorter than its length prefix,
  250. // and replay abandoned the 160,261 intact records behind it. Writers append
  251. // while another thread syncs in a loop; every entry must replay.
  252. void test_wal_append_races_sync() {
  253. using smartbotic::database::WriteAheadLog;
  254. auto dir = makeSnapshotDir("wal-sync-race");
  255. WriteAheadLog::Config cfg;
  256. cfg.walDir = dir;
  257. constexpr int kWriters = 4, kPerWriter = 15000;
  258. {
  259. WriteAheadLog wal(cfg);
  260. assert(wal.open());
  261. std::atomic<bool> done{false};
  262. std::thread syncer([&] { while (!done.load()) wal.sync(); });
  263. std::vector<std::thread> writers;
  264. for (int w = 0; w < kWriters; ++w) {
  265. writers.emplace_back([&wal, w] {
  266. for (int i = 0; i < kPerWriter; ++i) {
  267. Document d;
  268. d.id = "w" + std::to_string(w) + "-" + std::to_string(i);
  269. d.set_data(nlohmann::json{{"pad", std::string(100 + (i % 400), 'p')}});
  270. wal.append(WriteAheadLog::makeInsertEntry("t", d, "n"));
  271. }
  272. });
  273. }
  274. for (auto& t : writers) t.join();
  275. done = true;
  276. syncer.join();
  277. wal.close();
  278. }
  279. WriteAheadLog wal(cfg);
  280. const uint64_t n = wal.replay(0, [](const auto&) {});
  281. uint64_t unreadable = 0, short_ = 0;
  282. for (const auto& f : wal.lastReplayStats()) {
  283. unreadable += f.unreadable;
  284. if (f.bytesRead < f.fileBytes) ++short_;
  285. }
  286. if (n != static_cast<uint64_t>(kWriters * kPerWriter) || unreadable || short_) {
  287. std::cerr << "replayed " << n << " of " << kWriters * kPerWriter << ", unreadable "
  288. << unreadable << ", files ended early " << short_ << "\n";
  289. }
  290. assert(n == static_cast<uint64_t>(kWriters * kPerWriter));
  291. assert(unreadable == 0 && short_ == 0);
  292. fs::remove_all(dir);
  293. std::cout << "PASS: WAL entries survive appends racing sync()\n";
  294. }
  295. // v2.21.6 - the WAL reader resynchronises past a damaged record instead of
  296. // abandoning the rest of the file (a production file lost 160,261 intact
  297. // records behind one damaged one). Each case damages a real WAL file and
  298. // checks exactly which entries come back.
  299. namespace walresync {
  300. using smartbotic::database::WriteAheadLog;
  301. using smartbotic::database::WalEntry;
  302. constexpr int kN = 200;
  303. std::vector<uint8_t> readAll(const fs::path& p) {
  304. std::ifstream in(p, std::ios::binary);
  305. return {std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
  306. }
  307. void writeAll(const fs::path& p, const std::vector<uint8_t>& b) {
  308. std::ofstream out(p, std::ios::binary | std::ios::trunc);
  309. out.write(reinterpret_cast<const char*>(b.data()), static_cast<std::streamsize>(b.size()));
  310. }
  311. // Record start offsets (the header is 16 bytes, each record is len + body).
  312. std::vector<size_t> offsets(const std::vector<uint8_t>& b) {
  313. std::vector<size_t> o;
  314. size_t off = 16;
  315. while (off + 4 <= b.size()) {
  316. uint32_t len = 0;
  317. std::memcpy(&len, &b[off], 4);
  318. o.push_back(off);
  319. off += 4 + len;
  320. }
  321. return o;
  322. }
  323. fs::path makeWal(const std::string& name, WriteAheadLog::Config& cfg) {
  324. auto dir = makeSnapshotDir(name);
  325. cfg.walDir = dir;
  326. WriteAheadLog wal(cfg);
  327. assert(wal.open());
  328. for (int i = 0; i < kN; ++i) {
  329. Document d;
  330. d.id = "d" + std::to_string(i);
  331. d.set_data(nlohmann::json{{"i", i}, {"pad", std::string(100 + (i * 7) % 90, 'q')}});
  332. wal.append(WriteAheadLog::makeInsertEntry("t", d, "n"));
  333. }
  334. wal.close();
  335. return dir / "wal-current.log";
  336. }
  337. // Replays the WAL; returns the sequences seen and the file's stats.
  338. std::vector<uint64_t> replayAll(WriteAheadLog::Config& cfg, WriteAheadLog::ReplayFileStats& st) {
  339. WriteAheadLog wal(cfg);
  340. std::vector<uint64_t> seqs;
  341. wal.replay(0, [&](const WalEntry& e) { seqs.push_back(e.sequence); });
  342. st = wal.lastReplayStats().at(0);
  343. return seqs;
  344. }
  345. bool missingOnly(const std::vector<uint64_t>& seqs, const std::set<uint64_t>& lost) {
  346. std::vector<uint64_t> want;
  347. for (uint64_t s = 1; s <= kN; ++s) if (!lost.count(s)) want.push_back(s);
  348. if (seqs != want) {
  349. std::cerr << "got " << seqs.size() << " entries, want " << want.size() << "\n";
  350. return false;
  351. }
  352. return true;
  353. }
  354. } // namespace walresync
  355. void test_wal_reader_resyncs_past_damage() {
  356. using namespace walresync;
  357. // A: one byte deleted inside record 50 (the production shape: the record is
  358. // a byte shorter than its length prefix, so everything after it misframes).
  359. {
  360. WriteAheadLog::Config cfg;
  361. auto p = makeWal("resync-delete", cfg);
  362. auto b = readAll(p);
  363. auto o = offsets(b);
  364. b.erase(b.begin() + static_cast<long>(o[49] + 30));
  365. writeAll(p, b);
  366. WriteAheadLog::ReplayFileStats st;
  367. auto seqs = replayAll(cfg, st);
  368. assert(missingOnly(seqs, {50}));
  369. assert(st.unreadable == 1 && st.resynced == 1);
  370. }
  371. // B: one byte flipped inside record 120's data (length intact, checksum fails).
  372. {
  373. WriteAheadLog::Config cfg;
  374. auto p = makeWal("resync-flip", cfg);
  375. auto b = readAll(p);
  376. auto o = offsets(b);
  377. b[o[119] + 40] ^= 0x5a;
  378. writeAll(p, b);
  379. WriteAheadLog::ReplayFileStats st;
  380. auto seqs = replayAll(cfg, st);
  381. assert(missingOnly(seqs, {120}));
  382. assert(st.checksumFailures == 1);
  383. }
  384. // C: record 10's length prefix replaced by garbage.
  385. {
  386. WriteAheadLog::Config cfg;
  387. auto p = makeWal("resync-length", cfg);
  388. auto b = readAll(p);
  389. auto o = offsets(b);
  390. b[o[9]] = 0xf0; b[o[9] + 1] = 0xff; b[o[9] + 2] = 0xff; b[o[9] + 3] = 0x7f;
  391. writeAll(p, b);
  392. WriteAheadLog::ReplayFileStats st;
  393. auto seqs = replayAll(cfg, st);
  394. assert(missingOnly(seqs, {10}));
  395. }
  396. // D: 1,000 bytes zeroed from the middle of record 80: exactly the records
  397. // the region touches are lost.
  398. {
  399. WriteAheadLog::Config cfg;
  400. auto p = makeWal("resync-zero", cfg);
  401. auto b = readAll(p);
  402. auto o = offsets(b);
  403. const size_t from = o[79] + 20, to = from + 1000;
  404. std::set<uint64_t> lost;
  405. for (size_t k = 0; k < o.size(); ++k) {
  406. const size_t end = k + 1 < o.size() ? o[k + 1] : b.size();
  407. if (o[k] < to && end > from) lost.insert(k + 1);
  408. }
  409. std::fill(b.begin() + static_cast<long>(from), b.begin() + static_cast<long>(to), 0);
  410. writeAll(p, b);
  411. WriteAheadLog::ReplayFileStats st;
  412. auto seqs = replayAll(cfg, st);
  413. assert(lost.size() >= 3);
  414. assert(missingOnly(seqs, lost));
  415. }
  416. // E: a torn tail (a crash mid-write): open() cuts it, the sequence continues
  417. // from the last valid record, and an append after it is readable.
  418. {
  419. WriteAheadLog::Config cfg;
  420. auto p = makeWal("resync-torn", cfg);
  421. auto b = readAll(p);
  422. auto o = offsets(b);
  423. b.resize(o.back() + 25); // record 200 half-written
  424. writeAll(p, b);
  425. {
  426. WriteAheadLog wal(cfg);
  427. assert(wal.open());
  428. assert(wal.lastOpenTruncatedBytes() == 25);
  429. assert(wal.currentSequence() == kN - 1);
  430. Document d;
  431. d.id = "after";
  432. d.set_data(nlohmann::json{{"x", 1}});
  433. assert(wal.append(WriteAheadLog::makeInsertEntry("t", d, "n")) == kN);
  434. wal.close();
  435. }
  436. WriteAheadLog::ReplayFileStats st;
  437. auto seqs = replayAll(cfg, st);
  438. assert(seqs.size() == static_cast<size_t>(kN) && seqs.back() == kN);
  439. assert(st.unreadable == 0 && st.bytesRead == st.fileBytes);
  440. }
  441. // F: damage in the current file before a reopen: the highest sequence is
  442. // still found, so a new append does not reuse one already on disk.
  443. {
  444. WriteAheadLog::Config cfg;
  445. auto p = makeWal("resync-reopen", cfg);
  446. auto b = readAll(p);
  447. auto o = offsets(b);
  448. b.erase(b.begin() + static_cast<long>(o[29] + 30));
  449. writeAll(p, b);
  450. WriteAheadLog wal(cfg);
  451. assert(wal.open());
  452. assert(wal.currentSequence() == kN);
  453. Document d;
  454. d.id = "next";
  455. d.set_data(nlohmann::json{{"x", 1}});
  456. assert(wal.append(WriteAheadLog::makeInsertEntry("t", d, "n")) == kN + 1);
  457. wal.close();
  458. }
  459. // G (v2.21.7): whole records removed cleanly (what the 2.21.5 race did to
  460. // 63 records of a production file): the file is perfectly framed, nothing
  461. // is unreadable, and only the sequence gap shows it.
  462. {
  463. WriteAheadLog::Config cfg;
  464. auto p = makeWal("resync-gap", cfg);
  465. auto b = readAll(p);
  466. auto o = offsets(b);
  467. // records 101 and 102 (one run of two), then record 150 (a run of one)
  468. b.erase(b.begin() + static_cast<long>(o[149]), b.begin() + static_cast<long>(o[150]));
  469. b.erase(b.begin() + static_cast<long>(o[100]), b.begin() + static_cast<long>(o[102]));
  470. writeAll(p, b);
  471. WriteAheadLog::ReplayFileStats st;
  472. auto seqs = replayAll(cfg, st);
  473. assert(missingOnly(seqs, {101, 102, 150}));
  474. assert(st.unreadable == 0 && st.bytesRead == st.fileBytes);
  475. assert(st.missingSequences == 3 && st.gapRuns == 2);
  476. }
  477. std::cout << "PASS: WAL reader resynchronises past damaged records\n";
  478. }
  479. // ──────────────────────────────────────────────────────────
  480. // Test 6: loadWithFallback throws when all snapshots corrupt
  481. // ──────────────────────────────────────────────────────────
  482. void test_loadWithFallback_throws_when_all_corrupt() {
  483. auto dir = makeSnapshotDir("allcorrupt");
  484. SnapshotManager::Config scfg;
  485. scfg.snapshotDir = dir;
  486. scfg.maxSnapshots = 10;
  487. SnapshotManager mgr(scfg);
  488. MemoryStore store(defaultStoreConfig());
  489. store.start();
  490. store.createCollection("docs", CollectionOptions{});
  491. store.insert("docs", makeDoc("d1"));
  492. auto s1 = mgr.createSnapshot(store, 1);
  493. std::this_thread::sleep_for(std::chrono::seconds(1));
  494. store.insert("docs", makeDoc("d2"));
  495. auto s2 = mgr.createSnapshot(store, 2);
  496. store.stop();
  497. // Corrupt both
  498. fs::resize_file(s1, fs::file_size(s1) / 2);
  499. fs::resize_file(s2, fs::file_size(s2) / 2);
  500. MemoryStore store2(defaultStoreConfig());
  501. store2.start();
  502. bool threw = false;
  503. try {
  504. mgr.loadWithFallback(store2);
  505. } catch (const std::exception& e) {
  506. threw = true;
  507. std::string msg = e.what();
  508. assert(msg.find("all") != std::string::npos);
  509. }
  510. assert(threw);
  511. store2.stop();
  512. fs::remove_all(dir);
  513. std::cout << "PASS: loadWithFallback throws when all snapshots corrupt\n";
  514. }
  515. // ──────────────────────────────────────────────────────────
  516. // Test 7: v4 chunked format round-trips at scale (multi-chunk path)
  517. // ──────────────────────────────────────────────────────────
  518. void test_v4_format_roundtrip_at_scale() {
  519. auto dir = makeSnapshotDir("v4scale");
  520. SnapshotManager::Config scfg;
  521. scfg.snapshotDir = dir;
  522. scfg.compressionEnabled = true;
  523. SnapshotManager mgr(scfg);
  524. MemoryStore::Config storeCfg = defaultStoreConfig();
  525. storeCfg.maxMemoryBytes = 512ULL * 1024 * 1024; // room for 10K x ~2 KB docs
  526. MemoryStore store(storeCfg);
  527. store.start();
  528. store.createCollection("docs", CollectionOptions{});
  529. // Make each doc ~2 KB so 10,000 docs > 16 MB, forcing multi-chunk body.
  530. std::string bigString(2000, 'x');
  531. for (int i = 0; i < 10000; i++) {
  532. Document d;
  533. d.id = "d" + std::to_string(i);
  534. d.set_data(nlohmann::json{{"value", bigString}, {"i", i}});
  535. store.insert("docs", d);
  536. }
  537. auto path = mgr.createSnapshot(store, 1);
  538. store.stop();
  539. MemoryStore store2(storeCfg);
  540. store2.start();
  541. uint64_t seq = mgr.loadSnapshot(path, store2);
  542. assert(seq == 1);
  543. auto d = store2.get("docs", "d9999");
  544. assert(d.has_value());
  545. assert((*d).data()["i"].get<int>() == 9999);
  546. store2.stop();
  547. fs::remove_all(dir);
  548. std::cout << "PASS: v4 chunked format round-trips at scale (10K docs, 20MB+)\n";
  549. }
  550. // ──────────────────────────────────────────────────────────
  551. // Test 8: WAL sequence anchoring (regression for v1.7.2)
  552. //
  553. // After a snapshot at sequence S, truncateBefore(S) deletes every WAL
  554. // file (because all entries have sequence ≤ S). The next boot's
  555. // wal_->open() finds no files, so sequence_ stays at 0. Subsequent
  556. // appends would produce 1, 2, 3, … which look "older than the snapshot"
  557. // to the boot AFTER that and get silently dropped by recovery's
  558. // `replay(snapSeq)` filter.
  559. //
  560. // PersistenceManager::replayWal now calls wal_->setSequenceFloor(snapSeq)
  561. // to anchor the WAL counter to the snapshot's walSequence — this test
  562. // exercises that anchoring directly on the WAL.
  563. //
  564. // Bug fingerprint on Zoe (2026-05-07): messages from 10:55–11:41 lost
  565. // across the 11:42 restart; same migration applied twice across the
  566. // two boots because the migrations-applied marker was written with
  567. // sequence 1 and discarded by the next recovery.
  568. // ──────────────────────────────────────────────────────────
  569. void test_wal_sequence_floor_anchors_after_truncate() {
  570. using smartbotic::database::WriteAheadLog;
  571. auto dir = makeSnapshotDir("wal-floor");
  572. WriteAheadLog::Config cfg;
  573. cfg.walDir = dir;
  574. // Phase 1 — fresh WAL, append 5 entries, snapshot at seq=5,
  575. // truncate everything ≤ 5. Mirrors the steady-state cycle.
  576. {
  577. WriteAheadLog wal(cfg);
  578. assert(wal.open());
  579. for (int i = 0; i < 5; ++i) {
  580. auto entry = WriteAheadLog::makeInsertEntry(
  581. "test", makeDoc("d" + std::to_string(i)), "test-node");
  582. uint64_t seq = wal.append(std::move(entry));
  583. assert(seq == static_cast<uint64_t>(i + 1));
  584. }
  585. assert(wal.currentSequence() == 5);
  586. wal.truncateBefore(5);
  587. wal.close();
  588. }
  589. // After truncate the on-disk WAL files are deleted. The next boot
  590. // simulates the post-snapshot startup.
  591. {
  592. WriteAheadLog wal(cfg);
  593. assert(wal.open());
  594. // Without anchoring, sequence_ would be 0 here — that's the bug.
  595. // The recovery path is responsible for raising the floor; the
  596. // WAL itself has no way to know about the snapshot.
  597. assert(wal.currentSequence() == 0);
  598. // Now anchor to the snapshot's walSequence (5).
  599. wal.setSequenceFloor(5);
  600. assert(wal.currentSequence() == 5);
  601. // setSequenceFloor must be monotonic — calling with a lower
  602. // value is a no-op.
  603. wal.setSequenceFloor(3);
  604. assert(wal.currentSequence() == 5);
  605. // Subsequent appends produce 6, 7, … — strictly greater than
  606. // the snapshot's walSequence, so the next boot's recovery
  607. // (which calls `replay(snapSeq)` with snapSeq=5) will see them.
  608. auto entry = WriteAheadLog::makeInsertEntry(
  609. "test", makeDoc("post"), "test-node");
  610. uint64_t seq = wal.append(std::move(entry));
  611. assert(seq == 6);
  612. wal.close();
  613. }
  614. // Phase 2 — re-open one more time, verify sequence_ recovers from
  615. // the new on-disk file at 6 (open() reads the highest entry).
  616. {
  617. WriteAheadLog wal(cfg);
  618. assert(wal.open());
  619. assert(wal.currentSequence() >= 6);
  620. wal.close();
  621. }
  622. fs::remove_all(dir);
  623. std::cout << "PASS: WAL sequence floor anchors after snapshot truncate\n";
  624. }
  625. // ──────────────────────────────────────────────────────────
  626. // Test: snapshot must include evicted documents (v1.7.3 fix)
  627. // ──────────────────────────────────────────────────────────
  628. //
  629. // Pre-v1.7.3: serializeStore() walked only `coll->documents` (in-memory),
  630. // silently omitting docs that had been evicted to stubs. Each snapshot
  631. // rotation truncated the WAL past the snapshot's sequence, deleting the
  632. // only remaining copy of those evicted docs — they were lost forever
  633. // across the next restart.
  634. void test_snapshot_includes_evicted_documents() {
  635. using smartbotic::database::WriteAheadLog;
  636. auto snapDir = makeSnapshotDir("evict-snap");
  637. auto walDir = makeSnapshotDir("evict-wal");
  638. WriteAheadLog::Config walCfg;
  639. walCfg.walDir = walDir;
  640. WriteAheadLog wal(walCfg);
  641. if (!wal.open()) {
  642. std::cerr << "FAIL: wal.open() returned false\n";
  643. std::exit(2);
  644. }
  645. // Tiny memory limit so eviction fires under load.
  646. MemoryStore::Config storeCfg;
  647. storeCfg.nodeId = "test";
  648. storeCfg.maxMemoryBytes = 32ULL * 1024;
  649. storeCfg.evictionThresholdPercent = 50;
  650. storeCfg.evictionTargetPercent = 30;
  651. storeCfg.hotWriteFloorMs = 0; // disable hot-write protection
  652. storeCfg.evictionChunkSize = 1000;
  653. MemoryStore store(storeCfg);
  654. store.start();
  655. store.createCollection("docs", CollectionOptions{});
  656. // Wire load callback: scan WAL for the requested doc, same path
  657. // production uses (database_service.cpp installs a similar lambda
  658. // backed by PersistenceManager::loadDocument).
  659. store.setDocumentLoadCallback(
  660. [&wal](const std::string& coll, const std::string& id,
  661. uint64_t /*walSeq*/) -> std::optional<Document> {
  662. std::optional<Document> found;
  663. wal.replay(0, [&](const smartbotic::database::WalEntry& e) {
  664. if (e.collection == coll && e.documentId == id && e.data.has_value()) {
  665. Document d = Document::fromJson(*e.data);
  666. d.id = id;
  667. d.collection = coll;
  668. found = d;
  669. }
  670. });
  671. return found;
  672. });
  673. // Insert N docs, mirroring to WAL so the load callback can resolve them.
  674. constexpr int N = 100;
  675. for (int i = 0; i < N; ++i) {
  676. Document d = makeDoc("doc-" + std::to_string(i));
  677. {
  678. auto tree = d.data();
  679. tree["padding"] = std::string(300, 'x'); // make eviction meaningful
  680. d.set_data(tree);
  681. }
  682. wal.append(WriteAheadLog::makeInsertEntry("docs", d, "test"));
  683. store.insert("docs", d);
  684. }
  685. // Force eviction.
  686. store.evictDocuments();
  687. auto evictedIds = store.getEvictedDocumentIds("docs");
  688. auto inMemoryDocs = store.getAllDocuments("docs");
  689. assert(!evictedIds.empty());
  690. assert(evictedIds.size() + inMemoryDocs.size() == static_cast<size_t>(N));
  691. // Flush WAL so the load callback (which reads via ifstream) sees every
  692. // entry. In production the WAL is synced periodically by the persistence
  693. // manager; tests need to force it.
  694. wal.sync();
  695. // Take snapshot.
  696. SnapshotManager::Config scfg;
  697. scfg.snapshotDir = snapDir;
  698. SnapshotManager mgr(scfg);
  699. auto path = mgr.createSnapshot(store, wal.currentSequence());
  700. // Load into fresh store with a huge memory budget so eviction doesn't
  701. // fire during verification — we want to see every doc in-memory.
  702. MemoryStore::Config newCfg = storeCfg;
  703. newCfg.maxMemoryBytes = 256ULL * 1024 * 1024;
  704. MemoryStore newStore(newCfg);
  705. newStore.start();
  706. mgr.loadSnapshot(path, newStore);
  707. auto loadedDocs = newStore.getAllDocuments("docs");
  708. auto loadedEvicted = newStore.getEvictedDocumentIds("docs");
  709. const size_t totalLoaded = loadedDocs.size() + loadedEvicted.size();
  710. // Real check (assert is a no-op in Release builds with NDEBUG).
  711. if (totalLoaded != static_cast<size_t>(N)) {
  712. std::cerr << "FAIL: snapshot lost docs — loaded "
  713. << loadedDocs.size() << " in-memory + "
  714. << loadedEvicted.size() << " evicted = "
  715. << totalLoaded << " of " << N << " inserted\n";
  716. std::exit(1);
  717. }
  718. std::unordered_set<std::string> loadedIdSet;
  719. for (const auto& d : loadedDocs) loadedIdSet.insert(d.id);
  720. for (const auto& id : loadedEvicted) loadedIdSet.insert(id);
  721. for (const auto& id : evictedIds) {
  722. if (loadedIdSet.count(id) != 1) {
  723. std::cerr << "FAIL: evicted doc " << id
  724. << " missing from loaded snapshot\n";
  725. std::exit(1);
  726. }
  727. }
  728. wal.close();
  729. fs::remove_all(snapDir);
  730. fs::remove_all(walDir);
  731. std::cout << "PASS: snapshot includes evicted documents ("
  732. << inMemoryDocs.size() << " in-memory + "
  733. << evictedIds.size() << " evicted, all "
  734. << N << " round-tripped)\n";
  735. }
  736. // ──────────────────────────────────────────────────────────
  737. // Test: eviction stubs carry the real WAL sequence (v1.7.4 fix)
  738. // ──────────────────────────────────────────────────────────
  739. //
  740. // Pre-v1.7.4 the stub stored doc.version (1, 2, 3…) under the misleading
  741. // name `walSequence`. Production load callbacks therefore couldn't use
  742. // it as a `fromSequence` hint and fell back to scanning the entire WAL
  743. // from sequence 0 on every evicted-doc fault — O(WAL_size) per fault,
  744. // O(WAL_size × evicted_count) per eviction tick.
  745. void test_evict_stub_carries_real_wal_sequence() {
  746. using smartbotic::database::WriteAheadLog;
  747. auto walDir = makeSnapshotDir("stub-walseq");
  748. WriteAheadLog::Config walCfg;
  749. walCfg.walDir = walDir;
  750. WriteAheadLog wal(walCfg);
  751. if (!wal.open()) { std::cerr << "wal.open failed\n"; std::exit(2); }
  752. MemoryStore::Config storeCfg;
  753. storeCfg.nodeId = "test";
  754. storeCfg.maxMemoryBytes = 32ULL * 1024;
  755. storeCfg.evictionThresholdPercent = 50;
  756. storeCfg.evictionTargetPercent = 30;
  757. storeCfg.hotWriteFloorMs = 0;
  758. storeCfg.evictionChunkSize = 1000;
  759. MemoryStore store(storeCfg);
  760. store.start();
  761. store.createCollection("docs", CollectionOptions{});
  762. // Insert N docs. Mirror to WAL and record the actual sequence on the
  763. // store — this is what database_service.cpp's persist callback does.
  764. constexpr int N = 50;
  765. std::unordered_map<std::string, uint64_t> expectedSeq;
  766. for (int i = 0; i < N; ++i) {
  767. Document d = makeDoc("doc-" + std::to_string(i));
  768. {
  769. auto tree = d.data();
  770. tree["padding"] = std::string(300, 'x');
  771. d.set_data(tree);
  772. }
  773. uint64_t seq = wal.append(WriteAheadLog::makeInsertEntry("docs", d, "test"));
  774. store.insert("docs", d);
  775. store.recordWalSequence("docs", d.id, seq);
  776. expectedSeq[d.id] = seq;
  777. }
  778. // Re-write a few docs so their `walSequence` should match the LATEST
  779. // append, not the first one.
  780. for (int i = 0; i < 5; ++i) {
  781. Document d = makeDoc("doc-" + std::to_string(i));
  782. {
  783. auto tree = d.data();
  784. tree["padding"] = std::string(400, 'y');
  785. d.set_data(tree);
  786. }
  787. d.version = 2;
  788. uint64_t seq = wal.append(WriteAheadLog::makeUpdateEntry("docs", d, "test"));
  789. store.update("docs", d.id, d);
  790. store.recordWalSequence("docs", d.id, seq);
  791. expectedSeq[d.id] = seq;
  792. }
  793. store.evictDocuments();
  794. auto evictedIds = store.getEvictedDocumentIds("docs");
  795. if (evictedIds.empty()) {
  796. std::cerr << "FAIL: no docs evicted — eviction config too lax\n";
  797. std::exit(1);
  798. }
  799. // Every evicted stub must have the real (latest-append) seq, not 0
  800. // and not the per-doc version (1 or 2).
  801. for (const auto& id : evictedIds) {
  802. auto stub = store.getEvictedStub("docs", id);
  803. if (!stub) {
  804. std::cerr << "FAIL: no stub for " << id << "\n";
  805. std::exit(1);
  806. }
  807. uint64_t want = expectedSeq[id];
  808. if (stub->walSequence != want) {
  809. std::cerr << "FAIL: stub.walSequence=" << stub->walSequence
  810. << " for " << id << ", expected " << want
  811. << " (real WAL sequence)\n";
  812. std::exit(1);
  813. }
  814. // Sanity: must not equal a per-doc version counter (≤ 2 here).
  815. if (stub->walSequence <= 2) {
  816. std::cerr << "FAIL: stub.walSequence=" << stub->walSequence
  817. << " looks like a per-doc version, not a WAL seq\n";
  818. std::exit(1);
  819. }
  820. }
  821. wal.close();
  822. fs::remove_all(walDir);
  823. std::cout << "PASS: evict stubs carry real WAL sequence ("
  824. << evictedIds.size() << " stubs verified, all match "
  825. << "their last wal.append() return value)\n";
  826. }
  827. // ──────────────────────────────────────────────────────────
  828. // 2.21.0: the writer streams. A production store was OOM-killed at every
  829. // snapshot because the writer held the whole serialised body, a compressed
  830. // copy beside it, and a copy of each collection's documents.
  831. // ──────────────────────────────────────────────────────────
  832. namespace {
  833. long procStatusKb(const char* key) {
  834. std::ifstream in("/proc/self/status");
  835. std::string line;
  836. const std::string k = std::string(key) + ":";
  837. while (std::getline(in, line)) {
  838. if (line.rfind(k, 0) == 0) return std::stol(line.substr(k.size()));
  839. }
  840. return -1;
  841. }
  842. } // namespace
  843. void test_streaming_snapshot_memory_is_bounded() {
  844. auto dir = makeSnapshotDir("streaming-mem");
  845. SnapshotManager::Config scfg;
  846. scfg.snapshotDir = dir;
  847. SnapshotManager mgr(scfg);
  848. MemoryStore::Config mcfg = defaultStoreConfig();
  849. mcfg.maxMemoryBytes = 8ULL * 1024 * 1024 * 1024; // no eviction in this test
  850. MemoryStore store(mcfg);
  851. store.start();
  852. store.createCollection("big", CollectionOptions{});
  853. // ~160 MB of JSON in ONE collection: the old writer's peak grew by more
  854. // than that (body + compressed body + a copy of the collection). Random
  855. // text so LZ4 cannot shrink the compressed copy to nothing.
  856. uint64_t rng = 88172645463325252ULL;
  857. const int kDocs = 4000;
  858. for (int i = 0; i < kDocs; ++i) {
  859. std::string payload(40000, ' ');
  860. for (auto& c : payload) {
  861. rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17;
  862. c = static_cast<char>('a' + (rng % 26));
  863. }
  864. Document d;
  865. d.id = "d" + std::to_string(i);
  866. d.set_data(nlohmann::json{{"payload", payload}, {"i", i}});
  867. store.insert("big", d);
  868. }
  869. // Reset the high-water mark (Linux >= 4.0), then measure what the
  870. // snapshot itself adds above the current RSS.
  871. { std::ofstream("/proc/self/clear_refs") << "5"; }
  872. const long rssBefore = procStatusKb("VmRSS");
  873. const long hwmReset = procStatusKb("VmHWM");
  874. auto path = mgr.createSnapshot(store, 7);
  875. const long hwmAfter = procStatusKb("VmHWM");
  876. const long growthMb = (hwmAfter - rssBefore) / 1024;
  877. std::cout << " snapshot " << (fs::file_size(path) >> 20) << " MB on disk; peak RSS grew "
  878. << growthMb << " MB over " << (rssBefore >> 10) << " MB (hwm reset to "
  879. << (hwmReset >> 10) << " MB)\n";
  880. if (hwmReset < 0 || hwmReset > rssBefore + 1024) {
  881. std::cout << " (clear_refs unsupported here: memory bound not checked)\n";
  882. } else if (growthMb > 64) {
  883. std::cerr << "FAIL: snapshot peak grew " << growthMb << " MB, expected <= 64 MB\n";
  884. std::exit(1);
  885. }
  886. store.stop();
  887. MemoryStore store2(mcfg);
  888. store2.start();
  889. assert(mgr.loadSnapshot(path, store2) == 7);
  890. for (int i : {0, 1999, kDocs - 1}) {
  891. auto doc = store2.get("big", "d" + std::to_string(i));
  892. assert(doc.has_value());
  893. assert(doc->data()["i"] == i);
  894. assert(doc->data()["payload"].get<std::string>().size() == 40000);
  895. }
  896. assert(store2.getDocumentIds("big").size() == static_cast<size_t>(kDocs));
  897. store2.stop();
  898. fs::remove_all(dir);
  899. std::cout << "PASS: streaming snapshot memory is bounded\n";
  900. }
  901. // Many chunks, documents larger than a chunk, compressed and not.
  902. void test_streaming_snapshot_small_chunks_round_trip() {
  903. for (bool compress : {true, false}) {
  904. auto dir = makeSnapshotDir(compress ? "chunks-lz4" : "chunks-raw");
  905. SnapshotManager::Config scfg;
  906. scfg.snapshotDir = dir;
  907. scfg.chunkBytes = 1000;
  908. scfg.compressionEnabled = compress;
  909. SnapshotManager mgr(scfg);
  910. MemoryStore store(defaultStoreConfig());
  911. store.start();
  912. store.createCollection("a", CollectionOptions{});
  913. store.createCollection("b", CollectionOptions{});
  914. for (int i = 0; i < 300; ++i) {
  915. Document d;
  916. d.id = "x" + std::to_string(i);
  917. d.set_data(nlohmann::json{{"s", std::string(static_cast<size_t>(i * 17), 'q')}, {"i", i}});
  918. store.insert(i % 2 ? "a" : "b", d);
  919. }
  920. auto path = mgr.createSnapshot(store, 5);
  921. assert(mgr.verifySnapshot(path));
  922. auto info = mgr.getSnapshotInfo(path);
  923. assert(info && info->documentCount == 300 && info->collectionCount == 2);
  924. assert(info->compressionType == (compress ? 1u : 0u));
  925. store.stop();
  926. MemoryStore store2(defaultStoreConfig());
  927. store2.start();
  928. assert(mgr.loadSnapshot(path, store2) == 5);
  929. for (int i = 0; i < 300; ++i) {
  930. auto doc = store2.get(i % 2 ? "a" : "b", "x" + std::to_string(i));
  931. assert(doc.has_value());
  932. assert(doc->data()["s"].get<std::string>().size() == static_cast<size_t>(i * 17));
  933. }
  934. store2.stop();
  935. fs::remove_all(dir);
  936. }
  937. std::cout << "PASS: streaming snapshot round-trips over many small chunks\n";
  938. }
  939. // A snapshot that never finished leaves a marker the next boot reports; one
  940. // that finishes (or fails with an exception, which is logged) removes it.
  941. void test_interrupted_snapshot_marker() {
  942. auto dir = makeSnapshotDir("marker");
  943. SnapshotManager::Config scfg;
  944. scfg.snapshotDir = dir;
  945. SnapshotManager mgr(scfg);
  946. assert(!mgr.interruptedSnapshot());
  947. { std::ofstream(mgr.inProgressMarkerPath()) << "1760000000000 406829\n"; }
  948. auto r = mgr.interruptedSnapshot();
  949. assert(r && r->startedMs == 1760000000000ULL && r->walSequence == 406829);
  950. MemoryStore store(defaultStoreConfig());
  951. store.start();
  952. store.createCollection("docs", CollectionOptions{});
  953. store.insert("docs", makeDoc("d1"));
  954. mgr.createSnapshot(store, 3);
  955. assert(!mgr.interruptedSnapshot());
  956. store.stop();
  957. fs::remove_all(dir);
  958. std::cout << "PASS: an interrupted snapshot is reported until one completes\n";
  959. }
  960. // v2.21.0 - an evicted document whose copy cannot be read must FAIL the
  961. // snapshot, not be written as deleted. Written as deleted, it drops out of the
  962. // snapshot, the WAL holding it is truncated, and the next boot comes up without
  963. // it while LMDB keeps it: a disk-only row (one path to the production "ghost").
  964. void test_unreadable_evicted_document_fails_the_snapshot() {
  965. auto dir = makeSnapshotDir("unreadable-evicted");
  966. MemoryStore::Config storeCfg;
  967. storeCfg.nodeId = "test";
  968. storeCfg.maxMemoryBytes = 32ULL * 1024;
  969. storeCfg.evictionThresholdPercent = 50;
  970. storeCfg.evictionTargetPercent = 30;
  971. storeCfg.hotWriteFloorMs = 0;
  972. storeCfg.evictionChunkSize = 1000;
  973. MemoryStore store(storeCfg);
  974. store.start();
  975. store.createCollection("docs", CollectionOptions{});
  976. // Every evicted copy is unreadable.
  977. store.setDocumentLoadCallback([](const std::string&, const std::string&, uint64_t)
  978. -> std::optional<Document> { return std::nullopt; });
  979. for (int i = 0; i < 100; ++i) {
  980. Document d = makeDoc("doc-" + std::to_string(i));
  981. auto tree = d.data();
  982. tree["padding"] = std::string(300, 'x');
  983. d.set_data(tree);
  984. store.insert("docs", d);
  985. }
  986. store.evictDocuments();
  987. const auto evicted = store.getEvictedDocumentIds("docs");
  988. assert(!evicted.empty());
  989. bool threw = false;
  990. try {
  991. (void)store.copyDocuments("docs", evicted, 0, evicted.size());
  992. } catch (const std::runtime_error&) {
  993. threw = true;
  994. }
  995. assert(threw && "copyDocuments must throw for an evicted document it cannot read");
  996. SnapshotManager::Config scfg;
  997. scfg.snapshotDir = dir;
  998. SnapshotManager mgr(scfg);
  999. bool snapFailed = false;
  1000. try {
  1001. mgr.createSnapshot(store, 7);
  1002. } catch (const std::exception&) {
  1003. snapFailed = true;
  1004. }
  1005. assert(snapFailed && "the snapshot must fail rather than omit the document");
  1006. assert(mgr.listSnapshots().empty() && "no snapshot file may be left behind");
  1007. store.stop();
  1008. fs::remove_all(dir);
  1009. std::cout << "PASS: an unreadable evicted document fails the snapshot instead of dropping out\n";
  1010. }
  1011. int main() {
  1012. test_atomic_write_leaves_no_tmp();
  1013. test_snapshot_round_trip();
  1014. test_verification_catches_truncation();
  1015. test_loadWithFallback_uses_older_when_newest_corrupt();
  1016. test_orphaned_tmp_cleaned_by_listSnapshots();
  1017. test_snapshot_survives_concurrent_listing();
  1018. test_wal_append_races_sync();
  1019. test_wal_reader_resyncs_past_damage();
  1020. test_loadWithFallback_throws_when_all_corrupt();
  1021. test_v4_format_roundtrip_at_scale();
  1022. test_wal_sequence_floor_anchors_after_truncate();
  1023. test_snapshot_includes_evicted_documents();
  1024. test_evict_stub_carries_real_wal_sequence();
  1025. test_streaming_snapshot_memory_is_bounded();
  1026. test_streaming_snapshot_small_chunks_round_trip();
  1027. test_interrupted_snapshot_marker();
  1028. test_unreadable_evicted_document_fails_the_snapshot();
  1029. std::cout << "\nAll snapshot durability tests PASSED!\n";
  1030. return 0;
  1031. }