test_snapshot_durability.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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. std::cout << "PASS: WAL reader resynchronises past damaged records\n";
  460. }
  461. // ──────────────────────────────────────────────────────────
  462. // Test 6: loadWithFallback throws when all snapshots corrupt
  463. // ──────────────────────────────────────────────────────────
  464. void test_loadWithFallback_throws_when_all_corrupt() {
  465. auto dir = makeSnapshotDir("allcorrupt");
  466. SnapshotManager::Config scfg;
  467. scfg.snapshotDir = dir;
  468. scfg.maxSnapshots = 10;
  469. SnapshotManager mgr(scfg);
  470. MemoryStore store(defaultStoreConfig());
  471. store.start();
  472. store.createCollection("docs", CollectionOptions{});
  473. store.insert("docs", makeDoc("d1"));
  474. auto s1 = mgr.createSnapshot(store, 1);
  475. std::this_thread::sleep_for(std::chrono::seconds(1));
  476. store.insert("docs", makeDoc("d2"));
  477. auto s2 = mgr.createSnapshot(store, 2);
  478. store.stop();
  479. // Corrupt both
  480. fs::resize_file(s1, fs::file_size(s1) / 2);
  481. fs::resize_file(s2, fs::file_size(s2) / 2);
  482. MemoryStore store2(defaultStoreConfig());
  483. store2.start();
  484. bool threw = false;
  485. try {
  486. mgr.loadWithFallback(store2);
  487. } catch (const std::exception& e) {
  488. threw = true;
  489. std::string msg = e.what();
  490. assert(msg.find("all") != std::string::npos);
  491. }
  492. assert(threw);
  493. store2.stop();
  494. fs::remove_all(dir);
  495. std::cout << "PASS: loadWithFallback throws when all snapshots corrupt\n";
  496. }
  497. // ──────────────────────────────────────────────────────────
  498. // Test 7: v4 chunked format round-trips at scale (multi-chunk path)
  499. // ──────────────────────────────────────────────────────────
  500. void test_v4_format_roundtrip_at_scale() {
  501. auto dir = makeSnapshotDir("v4scale");
  502. SnapshotManager::Config scfg;
  503. scfg.snapshotDir = dir;
  504. scfg.compressionEnabled = true;
  505. SnapshotManager mgr(scfg);
  506. MemoryStore::Config storeCfg = defaultStoreConfig();
  507. storeCfg.maxMemoryBytes = 512ULL * 1024 * 1024; // room for 10K x ~2 KB docs
  508. MemoryStore store(storeCfg);
  509. store.start();
  510. store.createCollection("docs", CollectionOptions{});
  511. // Make each doc ~2 KB so 10,000 docs > 16 MB, forcing multi-chunk body.
  512. std::string bigString(2000, 'x');
  513. for (int i = 0; i < 10000; i++) {
  514. Document d;
  515. d.id = "d" + std::to_string(i);
  516. d.set_data(nlohmann::json{{"value", bigString}, {"i", i}});
  517. store.insert("docs", d);
  518. }
  519. auto path = mgr.createSnapshot(store, 1);
  520. store.stop();
  521. MemoryStore store2(storeCfg);
  522. store2.start();
  523. uint64_t seq = mgr.loadSnapshot(path, store2);
  524. assert(seq == 1);
  525. auto d = store2.get("docs", "d9999");
  526. assert(d.has_value());
  527. assert((*d).data()["i"].get<int>() == 9999);
  528. store2.stop();
  529. fs::remove_all(dir);
  530. std::cout << "PASS: v4 chunked format round-trips at scale (10K docs, 20MB+)\n";
  531. }
  532. // ──────────────────────────────────────────────────────────
  533. // Test 8: WAL sequence anchoring (regression for v1.7.2)
  534. //
  535. // After a snapshot at sequence S, truncateBefore(S) deletes every WAL
  536. // file (because all entries have sequence ≤ S). The next boot's
  537. // wal_->open() finds no files, so sequence_ stays at 0. Subsequent
  538. // appends would produce 1, 2, 3, … which look "older than the snapshot"
  539. // to the boot AFTER that and get silently dropped by recovery's
  540. // `replay(snapSeq)` filter.
  541. //
  542. // PersistenceManager::replayWal now calls wal_->setSequenceFloor(snapSeq)
  543. // to anchor the WAL counter to the snapshot's walSequence — this test
  544. // exercises that anchoring directly on the WAL.
  545. //
  546. // Bug fingerprint on Zoe (2026-05-07): messages from 10:55–11:41 lost
  547. // across the 11:42 restart; same migration applied twice across the
  548. // two boots because the migrations-applied marker was written with
  549. // sequence 1 and discarded by the next recovery.
  550. // ──────────────────────────────────────────────────────────
  551. void test_wal_sequence_floor_anchors_after_truncate() {
  552. using smartbotic::database::WriteAheadLog;
  553. auto dir = makeSnapshotDir("wal-floor");
  554. WriteAheadLog::Config cfg;
  555. cfg.walDir = dir;
  556. // Phase 1 — fresh WAL, append 5 entries, snapshot at seq=5,
  557. // truncate everything ≤ 5. Mirrors the steady-state cycle.
  558. {
  559. WriteAheadLog wal(cfg);
  560. assert(wal.open());
  561. for (int i = 0; i < 5; ++i) {
  562. auto entry = WriteAheadLog::makeInsertEntry(
  563. "test", makeDoc("d" + std::to_string(i)), "test-node");
  564. uint64_t seq = wal.append(std::move(entry));
  565. assert(seq == static_cast<uint64_t>(i + 1));
  566. }
  567. assert(wal.currentSequence() == 5);
  568. wal.truncateBefore(5);
  569. wal.close();
  570. }
  571. // After truncate the on-disk WAL files are deleted. The next boot
  572. // simulates the post-snapshot startup.
  573. {
  574. WriteAheadLog wal(cfg);
  575. assert(wal.open());
  576. // Without anchoring, sequence_ would be 0 here — that's the bug.
  577. // The recovery path is responsible for raising the floor; the
  578. // WAL itself has no way to know about the snapshot.
  579. assert(wal.currentSequence() == 0);
  580. // Now anchor to the snapshot's walSequence (5).
  581. wal.setSequenceFloor(5);
  582. assert(wal.currentSequence() == 5);
  583. // setSequenceFloor must be monotonic — calling with a lower
  584. // value is a no-op.
  585. wal.setSequenceFloor(3);
  586. assert(wal.currentSequence() == 5);
  587. // Subsequent appends produce 6, 7, … — strictly greater than
  588. // the snapshot's walSequence, so the next boot's recovery
  589. // (which calls `replay(snapSeq)` with snapSeq=5) will see them.
  590. auto entry = WriteAheadLog::makeInsertEntry(
  591. "test", makeDoc("post"), "test-node");
  592. uint64_t seq = wal.append(std::move(entry));
  593. assert(seq == 6);
  594. wal.close();
  595. }
  596. // Phase 2 — re-open one more time, verify sequence_ recovers from
  597. // the new on-disk file at 6 (open() reads the highest entry).
  598. {
  599. WriteAheadLog wal(cfg);
  600. assert(wal.open());
  601. assert(wal.currentSequence() >= 6);
  602. wal.close();
  603. }
  604. fs::remove_all(dir);
  605. std::cout << "PASS: WAL sequence floor anchors after snapshot truncate\n";
  606. }
  607. // ──────────────────────────────────────────────────────────
  608. // Test: snapshot must include evicted documents (v1.7.3 fix)
  609. // ──────────────────────────────────────────────────────────
  610. //
  611. // Pre-v1.7.3: serializeStore() walked only `coll->documents` (in-memory),
  612. // silently omitting docs that had been evicted to stubs. Each snapshot
  613. // rotation truncated the WAL past the snapshot's sequence, deleting the
  614. // only remaining copy of those evicted docs — they were lost forever
  615. // across the next restart.
  616. void test_snapshot_includes_evicted_documents() {
  617. using smartbotic::database::WriteAheadLog;
  618. auto snapDir = makeSnapshotDir("evict-snap");
  619. auto walDir = makeSnapshotDir("evict-wal");
  620. WriteAheadLog::Config walCfg;
  621. walCfg.walDir = walDir;
  622. WriteAheadLog wal(walCfg);
  623. if (!wal.open()) {
  624. std::cerr << "FAIL: wal.open() returned false\n";
  625. std::exit(2);
  626. }
  627. // Tiny memory limit so eviction fires under load.
  628. MemoryStore::Config storeCfg;
  629. storeCfg.nodeId = "test";
  630. storeCfg.maxMemoryBytes = 32ULL * 1024;
  631. storeCfg.evictionThresholdPercent = 50;
  632. storeCfg.evictionTargetPercent = 30;
  633. storeCfg.hotWriteFloorMs = 0; // disable hot-write protection
  634. storeCfg.evictionChunkSize = 1000;
  635. MemoryStore store(storeCfg);
  636. store.start();
  637. store.createCollection("docs", CollectionOptions{});
  638. // Wire load callback: scan WAL for the requested doc, same path
  639. // production uses (database_service.cpp installs a similar lambda
  640. // backed by PersistenceManager::loadDocument).
  641. store.setDocumentLoadCallback(
  642. [&wal](const std::string& coll, const std::string& id,
  643. uint64_t /*walSeq*/) -> std::optional<Document> {
  644. std::optional<Document> found;
  645. wal.replay(0, [&](const smartbotic::database::WalEntry& e) {
  646. if (e.collection == coll && e.documentId == id && e.data.has_value()) {
  647. Document d = Document::fromJson(*e.data);
  648. d.id = id;
  649. d.collection = coll;
  650. found = d;
  651. }
  652. });
  653. return found;
  654. });
  655. // Insert N docs, mirroring to WAL so the load callback can resolve them.
  656. constexpr int N = 100;
  657. for (int i = 0; i < N; ++i) {
  658. Document d = makeDoc("doc-" + std::to_string(i));
  659. {
  660. auto tree = d.data();
  661. tree["padding"] = std::string(300, 'x'); // make eviction meaningful
  662. d.set_data(tree);
  663. }
  664. wal.append(WriteAheadLog::makeInsertEntry("docs", d, "test"));
  665. store.insert("docs", d);
  666. }
  667. // Force eviction.
  668. store.evictDocuments();
  669. auto evictedIds = store.getEvictedDocumentIds("docs");
  670. auto inMemoryDocs = store.getAllDocuments("docs");
  671. assert(!evictedIds.empty());
  672. assert(evictedIds.size() + inMemoryDocs.size() == static_cast<size_t>(N));
  673. // Flush WAL so the load callback (which reads via ifstream) sees every
  674. // entry. In production the WAL is synced periodically by the persistence
  675. // manager; tests need to force it.
  676. wal.sync();
  677. // Take snapshot.
  678. SnapshotManager::Config scfg;
  679. scfg.snapshotDir = snapDir;
  680. SnapshotManager mgr(scfg);
  681. auto path = mgr.createSnapshot(store, wal.currentSequence());
  682. // Load into fresh store with a huge memory budget so eviction doesn't
  683. // fire during verification — we want to see every doc in-memory.
  684. MemoryStore::Config newCfg = storeCfg;
  685. newCfg.maxMemoryBytes = 256ULL * 1024 * 1024;
  686. MemoryStore newStore(newCfg);
  687. newStore.start();
  688. mgr.loadSnapshot(path, newStore);
  689. auto loadedDocs = newStore.getAllDocuments("docs");
  690. auto loadedEvicted = newStore.getEvictedDocumentIds("docs");
  691. const size_t totalLoaded = loadedDocs.size() + loadedEvicted.size();
  692. // Real check (assert is a no-op in Release builds with NDEBUG).
  693. if (totalLoaded != static_cast<size_t>(N)) {
  694. std::cerr << "FAIL: snapshot lost docs — loaded "
  695. << loadedDocs.size() << " in-memory + "
  696. << loadedEvicted.size() << " evicted = "
  697. << totalLoaded << " of " << N << " inserted\n";
  698. std::exit(1);
  699. }
  700. std::unordered_set<std::string> loadedIdSet;
  701. for (const auto& d : loadedDocs) loadedIdSet.insert(d.id);
  702. for (const auto& id : loadedEvicted) loadedIdSet.insert(id);
  703. for (const auto& id : evictedIds) {
  704. if (loadedIdSet.count(id) != 1) {
  705. std::cerr << "FAIL: evicted doc " << id
  706. << " missing from loaded snapshot\n";
  707. std::exit(1);
  708. }
  709. }
  710. wal.close();
  711. fs::remove_all(snapDir);
  712. fs::remove_all(walDir);
  713. std::cout << "PASS: snapshot includes evicted documents ("
  714. << inMemoryDocs.size() << " in-memory + "
  715. << evictedIds.size() << " evicted, all "
  716. << N << " round-tripped)\n";
  717. }
  718. // ──────────────────────────────────────────────────────────
  719. // Test: eviction stubs carry the real WAL sequence (v1.7.4 fix)
  720. // ──────────────────────────────────────────────────────────
  721. //
  722. // Pre-v1.7.4 the stub stored doc.version (1, 2, 3…) under the misleading
  723. // name `walSequence`. Production load callbacks therefore couldn't use
  724. // it as a `fromSequence` hint and fell back to scanning the entire WAL
  725. // from sequence 0 on every evicted-doc fault — O(WAL_size) per fault,
  726. // O(WAL_size × evicted_count) per eviction tick.
  727. void test_evict_stub_carries_real_wal_sequence() {
  728. using smartbotic::database::WriteAheadLog;
  729. auto walDir = makeSnapshotDir("stub-walseq");
  730. WriteAheadLog::Config walCfg;
  731. walCfg.walDir = walDir;
  732. WriteAheadLog wal(walCfg);
  733. if (!wal.open()) { std::cerr << "wal.open failed\n"; std::exit(2); }
  734. MemoryStore::Config storeCfg;
  735. storeCfg.nodeId = "test";
  736. storeCfg.maxMemoryBytes = 32ULL * 1024;
  737. storeCfg.evictionThresholdPercent = 50;
  738. storeCfg.evictionTargetPercent = 30;
  739. storeCfg.hotWriteFloorMs = 0;
  740. storeCfg.evictionChunkSize = 1000;
  741. MemoryStore store(storeCfg);
  742. store.start();
  743. store.createCollection("docs", CollectionOptions{});
  744. // Insert N docs. Mirror to WAL and record the actual sequence on the
  745. // store — this is what database_service.cpp's persist callback does.
  746. constexpr int N = 50;
  747. std::unordered_map<std::string, uint64_t> expectedSeq;
  748. for (int i = 0; i < N; ++i) {
  749. Document d = makeDoc("doc-" + std::to_string(i));
  750. {
  751. auto tree = d.data();
  752. tree["padding"] = std::string(300, 'x');
  753. d.set_data(tree);
  754. }
  755. uint64_t seq = wal.append(WriteAheadLog::makeInsertEntry("docs", d, "test"));
  756. store.insert("docs", d);
  757. store.recordWalSequence("docs", d.id, seq);
  758. expectedSeq[d.id] = seq;
  759. }
  760. // Re-write a few docs so their `walSequence` should match the LATEST
  761. // append, not the first one.
  762. for (int i = 0; i < 5; ++i) {
  763. Document d = makeDoc("doc-" + std::to_string(i));
  764. {
  765. auto tree = d.data();
  766. tree["padding"] = std::string(400, 'y');
  767. d.set_data(tree);
  768. }
  769. d.version = 2;
  770. uint64_t seq = wal.append(WriteAheadLog::makeUpdateEntry("docs", d, "test"));
  771. store.update("docs", d.id, d);
  772. store.recordWalSequence("docs", d.id, seq);
  773. expectedSeq[d.id] = seq;
  774. }
  775. store.evictDocuments();
  776. auto evictedIds = store.getEvictedDocumentIds("docs");
  777. if (evictedIds.empty()) {
  778. std::cerr << "FAIL: no docs evicted — eviction config too lax\n";
  779. std::exit(1);
  780. }
  781. // Every evicted stub must have the real (latest-append) seq, not 0
  782. // and not the per-doc version (1 or 2).
  783. for (const auto& id : evictedIds) {
  784. auto stub = store.getEvictedStub("docs", id);
  785. if (!stub) {
  786. std::cerr << "FAIL: no stub for " << id << "\n";
  787. std::exit(1);
  788. }
  789. uint64_t want = expectedSeq[id];
  790. if (stub->walSequence != want) {
  791. std::cerr << "FAIL: stub.walSequence=" << stub->walSequence
  792. << " for " << id << ", expected " << want
  793. << " (real WAL sequence)\n";
  794. std::exit(1);
  795. }
  796. // Sanity: must not equal a per-doc version counter (≤ 2 here).
  797. if (stub->walSequence <= 2) {
  798. std::cerr << "FAIL: stub.walSequence=" << stub->walSequence
  799. << " looks like a per-doc version, not a WAL seq\n";
  800. std::exit(1);
  801. }
  802. }
  803. wal.close();
  804. fs::remove_all(walDir);
  805. std::cout << "PASS: evict stubs carry real WAL sequence ("
  806. << evictedIds.size() << " stubs verified, all match "
  807. << "their last wal.append() return value)\n";
  808. }
  809. // ──────────────────────────────────────────────────────────
  810. // 2.21.0: the writer streams. A production store was OOM-killed at every
  811. // snapshot because the writer held the whole serialised body, a compressed
  812. // copy beside it, and a copy of each collection's documents.
  813. // ──────────────────────────────────────────────────────────
  814. namespace {
  815. long procStatusKb(const char* key) {
  816. std::ifstream in("/proc/self/status");
  817. std::string line;
  818. const std::string k = std::string(key) + ":";
  819. while (std::getline(in, line)) {
  820. if (line.rfind(k, 0) == 0) return std::stol(line.substr(k.size()));
  821. }
  822. return -1;
  823. }
  824. } // namespace
  825. void test_streaming_snapshot_memory_is_bounded() {
  826. auto dir = makeSnapshotDir("streaming-mem");
  827. SnapshotManager::Config scfg;
  828. scfg.snapshotDir = dir;
  829. SnapshotManager mgr(scfg);
  830. MemoryStore::Config mcfg = defaultStoreConfig();
  831. mcfg.maxMemoryBytes = 8ULL * 1024 * 1024 * 1024; // no eviction in this test
  832. MemoryStore store(mcfg);
  833. store.start();
  834. store.createCollection("big", CollectionOptions{});
  835. // ~160 MB of JSON in ONE collection: the old writer's peak grew by more
  836. // than that (body + compressed body + a copy of the collection). Random
  837. // text so LZ4 cannot shrink the compressed copy to nothing.
  838. uint64_t rng = 88172645463325252ULL;
  839. const int kDocs = 4000;
  840. for (int i = 0; i < kDocs; ++i) {
  841. std::string payload(40000, ' ');
  842. for (auto& c : payload) {
  843. rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17;
  844. c = static_cast<char>('a' + (rng % 26));
  845. }
  846. Document d;
  847. d.id = "d" + std::to_string(i);
  848. d.set_data(nlohmann::json{{"payload", payload}, {"i", i}});
  849. store.insert("big", d);
  850. }
  851. // Reset the high-water mark (Linux >= 4.0), then measure what the
  852. // snapshot itself adds above the current RSS.
  853. { std::ofstream("/proc/self/clear_refs") << "5"; }
  854. const long rssBefore = procStatusKb("VmRSS");
  855. const long hwmReset = procStatusKb("VmHWM");
  856. auto path = mgr.createSnapshot(store, 7);
  857. const long hwmAfter = procStatusKb("VmHWM");
  858. const long growthMb = (hwmAfter - rssBefore) / 1024;
  859. std::cout << " snapshot " << (fs::file_size(path) >> 20) << " MB on disk; peak RSS grew "
  860. << growthMb << " MB over " << (rssBefore >> 10) << " MB (hwm reset to "
  861. << (hwmReset >> 10) << " MB)\n";
  862. if (hwmReset < 0 || hwmReset > rssBefore + 1024) {
  863. std::cout << " (clear_refs unsupported here: memory bound not checked)\n";
  864. } else if (growthMb > 64) {
  865. std::cerr << "FAIL: snapshot peak grew " << growthMb << " MB, expected <= 64 MB\n";
  866. std::exit(1);
  867. }
  868. store.stop();
  869. MemoryStore store2(mcfg);
  870. store2.start();
  871. assert(mgr.loadSnapshot(path, store2) == 7);
  872. for (int i : {0, 1999, kDocs - 1}) {
  873. auto doc = store2.get("big", "d" + std::to_string(i));
  874. assert(doc.has_value());
  875. assert(doc->data()["i"] == i);
  876. assert(doc->data()["payload"].get<std::string>().size() == 40000);
  877. }
  878. assert(store2.getDocumentIds("big").size() == static_cast<size_t>(kDocs));
  879. store2.stop();
  880. fs::remove_all(dir);
  881. std::cout << "PASS: streaming snapshot memory is bounded\n";
  882. }
  883. // Many chunks, documents larger than a chunk, compressed and not.
  884. void test_streaming_snapshot_small_chunks_round_trip() {
  885. for (bool compress : {true, false}) {
  886. auto dir = makeSnapshotDir(compress ? "chunks-lz4" : "chunks-raw");
  887. SnapshotManager::Config scfg;
  888. scfg.snapshotDir = dir;
  889. scfg.chunkBytes = 1000;
  890. scfg.compressionEnabled = compress;
  891. SnapshotManager mgr(scfg);
  892. MemoryStore store(defaultStoreConfig());
  893. store.start();
  894. store.createCollection("a", CollectionOptions{});
  895. store.createCollection("b", CollectionOptions{});
  896. for (int i = 0; i < 300; ++i) {
  897. Document d;
  898. d.id = "x" + std::to_string(i);
  899. d.set_data(nlohmann::json{{"s", std::string(static_cast<size_t>(i * 17), 'q')}, {"i", i}});
  900. store.insert(i % 2 ? "a" : "b", d);
  901. }
  902. auto path = mgr.createSnapshot(store, 5);
  903. assert(mgr.verifySnapshot(path));
  904. auto info = mgr.getSnapshotInfo(path);
  905. assert(info && info->documentCount == 300 && info->collectionCount == 2);
  906. assert(info->compressionType == (compress ? 1u : 0u));
  907. store.stop();
  908. MemoryStore store2(defaultStoreConfig());
  909. store2.start();
  910. assert(mgr.loadSnapshot(path, store2) == 5);
  911. for (int i = 0; i < 300; ++i) {
  912. auto doc = store2.get(i % 2 ? "a" : "b", "x" + std::to_string(i));
  913. assert(doc.has_value());
  914. assert(doc->data()["s"].get<std::string>().size() == static_cast<size_t>(i * 17));
  915. }
  916. store2.stop();
  917. fs::remove_all(dir);
  918. }
  919. std::cout << "PASS: streaming snapshot round-trips over many small chunks\n";
  920. }
  921. // A snapshot that never finished leaves a marker the next boot reports; one
  922. // that finishes (or fails with an exception, which is logged) removes it.
  923. void test_interrupted_snapshot_marker() {
  924. auto dir = makeSnapshotDir("marker");
  925. SnapshotManager::Config scfg;
  926. scfg.snapshotDir = dir;
  927. SnapshotManager mgr(scfg);
  928. assert(!mgr.interruptedSnapshot());
  929. { std::ofstream(mgr.inProgressMarkerPath()) << "1760000000000 406829\n"; }
  930. auto r = mgr.interruptedSnapshot();
  931. assert(r && r->startedMs == 1760000000000ULL && r->walSequence == 406829);
  932. MemoryStore store(defaultStoreConfig());
  933. store.start();
  934. store.createCollection("docs", CollectionOptions{});
  935. store.insert("docs", makeDoc("d1"));
  936. mgr.createSnapshot(store, 3);
  937. assert(!mgr.interruptedSnapshot());
  938. store.stop();
  939. fs::remove_all(dir);
  940. std::cout << "PASS: an interrupted snapshot is reported until one completes\n";
  941. }
  942. // v2.21.0 - an evicted document whose copy cannot be read must FAIL the
  943. // snapshot, not be written as deleted. Written as deleted, it drops out of the
  944. // snapshot, the WAL holding it is truncated, and the next boot comes up without
  945. // it while LMDB keeps it: a disk-only row (one path to the production "ghost").
  946. void test_unreadable_evicted_document_fails_the_snapshot() {
  947. auto dir = makeSnapshotDir("unreadable-evicted");
  948. MemoryStore::Config storeCfg;
  949. storeCfg.nodeId = "test";
  950. storeCfg.maxMemoryBytes = 32ULL * 1024;
  951. storeCfg.evictionThresholdPercent = 50;
  952. storeCfg.evictionTargetPercent = 30;
  953. storeCfg.hotWriteFloorMs = 0;
  954. storeCfg.evictionChunkSize = 1000;
  955. MemoryStore store(storeCfg);
  956. store.start();
  957. store.createCollection("docs", CollectionOptions{});
  958. // Every evicted copy is unreadable.
  959. store.setDocumentLoadCallback([](const std::string&, const std::string&, uint64_t)
  960. -> std::optional<Document> { return std::nullopt; });
  961. for (int i = 0; i < 100; ++i) {
  962. Document d = makeDoc("doc-" + std::to_string(i));
  963. auto tree = d.data();
  964. tree["padding"] = std::string(300, 'x');
  965. d.set_data(tree);
  966. store.insert("docs", d);
  967. }
  968. store.evictDocuments();
  969. const auto evicted = store.getEvictedDocumentIds("docs");
  970. assert(!evicted.empty());
  971. bool threw = false;
  972. try {
  973. (void)store.copyDocuments("docs", evicted, 0, evicted.size());
  974. } catch (const std::runtime_error&) {
  975. threw = true;
  976. }
  977. assert(threw && "copyDocuments must throw for an evicted document it cannot read");
  978. SnapshotManager::Config scfg;
  979. scfg.snapshotDir = dir;
  980. SnapshotManager mgr(scfg);
  981. bool snapFailed = false;
  982. try {
  983. mgr.createSnapshot(store, 7);
  984. } catch (const std::exception&) {
  985. snapFailed = true;
  986. }
  987. assert(snapFailed && "the snapshot must fail rather than omit the document");
  988. assert(mgr.listSnapshots().empty() && "no snapshot file may be left behind");
  989. store.stop();
  990. fs::remove_all(dir);
  991. std::cout << "PASS: an unreadable evicted document fails the snapshot instead of dropping out\n";
  992. }
  993. int main() {
  994. test_atomic_write_leaves_no_tmp();
  995. test_snapshot_round_trip();
  996. test_verification_catches_truncation();
  997. test_loadWithFallback_uses_older_when_newest_corrupt();
  998. test_orphaned_tmp_cleaned_by_listSnapshots();
  999. test_snapshot_survives_concurrent_listing();
  1000. test_wal_append_races_sync();
  1001. test_wal_reader_resyncs_past_damage();
  1002. test_loadWithFallback_throws_when_all_corrupt();
  1003. test_v4_format_roundtrip_at_scale();
  1004. test_wal_sequence_floor_anchors_after_truncate();
  1005. test_snapshot_includes_evicted_documents();
  1006. test_evict_stub_carries_real_wal_sequence();
  1007. test_streaming_snapshot_memory_is_bounded();
  1008. test_streaming_snapshot_small_chunks_round_trip();
  1009. test_interrupted_snapshot_marker();
  1010. test_unreadable_evicted_document_fails_the_snapshot();
  1011. std::cout << "\nAll snapshot durability tests PASSED!\n";
  1012. return 0;
  1013. }