| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072 |
- #include "snapshot.hpp"
- #include "wal.hpp"
- #include "../json_parse.hpp"
- #include <algorithm>
- #include <atomic>
- #include <cerrno>
- #include <chrono>
- #include <cstring>
- #include <fstream>
- #include <iomanip>
- #include <sstream>
- #include <system_error>
- #include <thread>
- #include <fcntl.h>
- #include <unistd.h>
- #include <spdlog/spdlog.h>
- #ifndef DISABLE_LZ4
- #include <lz4.h>
- #endif
- #if defined(__GLIBC__) && !defined(__APPLE__)
- #include <malloc.h>
- #endif
- namespace {
- // v1.9.1 — `malloc_trim(0)` after a big-buffer phase finishes. The
- // snapshot write and load paths both build multi-GB transient buffers
- // (uncompressed body + LZ4 chunks; per-collection JSON parses). When
- // those buffers free, glibc parks the pages on its arena freelist and
- // only reclaims them lazily during subsequent small allocations. For a
- // quiescent post-boot or post-snapshot process those allocations may
- // not arrive for hours, so the operator-visible VmRSS stays inflated
- // even though `estimatedMemoryBytes_` is correct. Trimming explicitly
- // here turns a 2.8 GB no-op back into a 2.8 GB drop (measured on Zoe
- // 2026-05-13 12:07 via the SIGUSR2 handler from v1.8.3 — same call,
- // just automated). No-op on non-glibc platforms.
- void releaseFreelistPages() {
- #if defined(__GLIBC__) && !defined(__APPLE__)
- ::malloc_trim(0);
- #endif
- }
- } // namespace
- namespace smartbotic::database {
- namespace {
- // Decompress a v4-chunked LZ4 body produced by createSnapshot.
- // Body layout: sequence of [u32 uncomp_size, u32 comp_size, LZ4 bytes...] terminated
- // by a (0, 0) end marker. Returns the full concatenated uncompressed payload.
- std::vector<uint8_t> decompressChunked(const std::vector<uint8_t>& body,
- uint64_t uncompressedSize) {
- #ifndef DISABLE_LZ4
- std::vector<uint8_t> out;
- out.reserve(uncompressedSize);
- size_t offset = 0;
- while (offset + 8 <= body.size()) {
- uint32_t uncompU32 = 0;
- uint32_t compU32 = 0;
- std::memcpy(&uncompU32, body.data() + offset, 4);
- std::memcpy(&compU32, body.data() + offset + 4, 4);
- offset += 8;
- if (uncompU32 == 0 && compU32 == 0) {
- break; // end marker
- }
- if (offset + compU32 > body.size()) {
- throw std::runtime_error("Snapshot chunk extends past body");
- }
- size_t outStart = out.size();
- out.resize(outStart + uncompU32);
- int decompressed = LZ4_decompress_safe(
- reinterpret_cast<const char*>(body.data() + offset),
- reinterpret_cast<char*>(out.data() + outStart),
- static_cast<int>(compU32),
- static_cast<int>(uncompU32)
- );
- if (decompressed < 0 || static_cast<uint32_t>(decompressed) != uncompU32) {
- throw std::runtime_error("Snapshot chunk decompression failed");
- }
- offset += compU32;
- }
- if (out.size() != uncompressedSize) {
- throw std::runtime_error("Decompressed size mismatch: expected " +
- std::to_string(uncompressedSize) + " got " +
- std::to_string(out.size()));
- }
- return out;
- #else
- (void)body;
- (void)uncompressedSize;
- throw std::runtime_error("LZ4 disabled — cannot decompress chunked snapshot body");
- #endif
- }
- } // namespace
- SnapshotManager::SnapshotManager(Config config)
- : config_(std::move(config)) {
- // Create snapshot directory if it doesn't exist
- std::error_code ec;
- std::filesystem::create_directories(config_.snapshotDir, ec);
- }
- namespace {
- uint64_t nowMs() {
- return static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::system_clock::now().time_since_epoch()).count());
- }
- // 2.20.1 - the snapshot body, written to disk as it is produced. Before this
- // the writer built the whole serialised store in one buffer, then a second
- // (compressed) buffer beside it, and copied every resident document of a
- // collection before serialising it: a peak of the working set plus roughly two
- // more copies of it. A store that outgrew its host was OOM-killed at every
- // snapshot, the WAL was never truncated, and recovery grew with it until boot
- // itself no longer fit (a production instance, 2026-10-19). Now the peak is
- // one chunk and its compressed copy, whatever the store's size.
- //
- // Bytes on disk are unchanged (format v4): a sequence of
- // [u32 uncompressed_size, u32 compressed_size, bytes] chunks and a (0, 0) end
- // marker when compressed; the raw body when not. The CRC trailer covers the
- // body exactly as before, computed as it is written.
- class BodyWriter {
- public:
- BodyWriter(std::ofstream& out, bool compress, size_t chunkBytes)
- : out_(out), compress_(compress), chunk_(chunkBytes == 0 ? 1 : chunkBytes) {
- stage_.reserve(chunk_);
- }
- void bytes(const void* data, size_t n) {
- const auto* p = static_cast<const uint8_t*>(data);
- while (n > 0) {
- const size_t take = std::min(n, chunk_ - stage_.size());
- stage_.insert(stage_.end(), p, p + take);
- p += take;
- n -= take;
- uncompressed_ += take;
- if (stage_.size() == chunk_) flushChunk();
- }
- }
- void bytes(const std::string& s) { bytes(s.data(), s.size()); }
- void u16(uint16_t v) { le(v, 2); }
- void u32(uint32_t v) { le(v, 4); }
- void u64(uint64_t v) { le(v, 8); }
- void finish() {
- if (!stage_.empty()) flushChunk();
- if (compress_) {
- const uint32_t zero = 0;
- emit(&zero, 4);
- emit(&zero, 4);
- }
- }
- uint64_t uncompressedSize() const { return uncompressed_; }
- uint64_t bodySize() const { return body_; }
- uint32_t bodyCrc() const { return crc_; }
- private:
- void le(uint64_t v, int width) {
- uint8_t b[8];
- for (int i = 0; i < width; ++i) b[i] = static_cast<uint8_t>((v >> (i * 8)) & 0xFF);
- bytes(b, static_cast<size_t>(width));
- }
- void emit(const void* data, size_t n) {
- out_.write(static_cast<const char*>(data), static_cast<std::streamsize>(n));
- if (!out_) throw std::runtime_error("snapshot write failed (short write)");
- crc_ = crc32::extend(crc_, data, n);
- body_ += n;
- }
- void flushChunk() {
- #ifndef DISABLE_LZ4
- if (compress_) {
- const int bound = LZ4_compressBound(static_cast<int>(stage_.size()));
- if (packed_.size() < static_cast<size_t>(bound)) packed_.resize(static_cast<size_t>(bound));
- const int packedSize = LZ4_compress_default(
- reinterpret_cast<const char*>(stage_.data()), reinterpret_cast<char*>(packed_.data()),
- static_cast<int>(stage_.size()), bound);
- if (packedSize <= 0) {
- throw std::runtime_error("LZ4 compression failed at offset " +
- std::to_string(uncompressed_ - stage_.size()));
- }
- const uint32_t uncompU32 = static_cast<uint32_t>(stage_.size());
- const uint32_t compU32 = static_cast<uint32_t>(packedSize);
- emit(&uncompU32, 4);
- emit(&compU32, 4);
- emit(packed_.data(), static_cast<size_t>(packedSize));
- stage_.clear();
- return;
- }
- #endif
- emit(stage_.data(), stage_.size());
- stage_.clear();
- }
- std::ofstream& out_;
- const bool compress_;
- const size_t chunk_;
- std::vector<uint8_t> stage_;
- std::vector<uint8_t> packed_;
- uint64_t uncompressed_ = 0;
- uint64_t body_ = 0;
- uint32_t crc_ = 0;
- };
- constexpr const char* kInProgressMarker = "snapshot.in-progress";
- // Removes the in-progress marker when createSnapshot returns or throws. Only a
- // process that dies mid-snapshot leaves it behind, which is what it reports.
- struct MarkerGuard {
- std::filesystem::path path;
- ~MarkerGuard() {
- std::error_code ec;
- std::filesystem::remove(path, ec);
- }
- };
- } // namespace
- std::filesystem::path SnapshotManager::inProgressMarkerPath() const {
- return config_.snapshotDir / kInProgressMarker;
- }
- std::optional<SnapshotManager::InterruptedSnapshot> SnapshotManager::interruptedSnapshot() const {
- std::ifstream in(inProgressMarkerPath());
- if (!in) return std::nullopt;
- InterruptedSnapshot r;
- in >> r.startedMs >> r.walSequence; // a torn marker still reports, with zeros
- return r;
- }
- std::filesystem::path SnapshotManager::createSnapshot(const MemoryStore& store, uint64_t walSequence) {
- MarkerGuard marker{inProgressMarkerPath()};
- {
- std::ofstream m(marker.path, std::ios::trunc);
- m << nowMs() << ' ' << walSequence << '\n';
- // Best effort: a missing marker only loses the next boot's report.
- }
- bool compress = config_.compressionEnabled;
- #ifdef DISABLE_LZ4
- compress = false;
- #endif
- // Generate filename - write to .tmp first, atomic rename at the end
- std::filesystem::path snapshotPath = config_.snapshotDir / generateFilename();
- std::filesystem::path tmpPath = snapshotPath;
- tmpPath += ".tmp";
- auto cleanupTmp = [&tmpPath]() {
- std::error_code ec;
- std::filesystem::remove(tmpPath, ec);
- };
- try {
- std::ofstream file(tmpPath, std::ios::binary | std::ios::trunc);
- if (!file) {
- throw std::runtime_error("Failed to create snapshot tmp file: " + tmpPath.string());
- }
- // Placeholder header; the real one (sizes, counts, checksum) is known
- // only once the body has been written, and is written over it below.
- SnapshotHeader header;
- file.write(reinterpret_cast<const char*>(&header), sizeof(header));
- if (!file) throw std::runtime_error("Failed to write snapshot header: " + tmpPath.string());
- uint64_t docCount = 0;
- uint32_t collCount = 0;
- BodyWriter body(file, compress, config_.chunkBytes);
- serializeStore(store, body, docCount, collCount);
- body.finish();
- const uint32_t bodyChecksum = body.bodyCrc();
- file.write(reinterpret_cast<const char*>(&bodyChecksum), sizeof(bodyChecksum));
- if (!file) throw std::runtime_error("Failed to write snapshot trailer: " + tmpPath.string());
- header.timestamp = nowMs();
- header.walSequence = walSequence;
- header.documentCount = docCount;
- header.collectionCount = collCount;
- header.uncompressedSize = body.uncompressedSize();
- header.compressedSize = body.bodySize();
- header.compressionType = compress ? 1 : 0;
- header.headerChecksum =
- crc32::calculate(&header, sizeof(header) - sizeof(header.headerChecksum));
- file.seekp(0);
- file.write(reinterpret_cast<const char*>(&header), sizeof(header));
- if (!file) throw std::runtime_error("Failed to write snapshot header: " + tmpPath.string());
- file.flush();
- if (!file) throw std::runtime_error("Failed to flush snapshot: " + tmpPath.string());
- } catch (...) {
- cleanupTmp();
- releaseFreelistPages();
- throw;
- }
- // fsync the file descriptor - C++ ofstream does not do this
- {
- int fd = ::open(tmpPath.c_str(), O_RDONLY);
- if (fd < 0) {
- cleanupTmp();
- throw std::runtime_error("Failed to reopen snapshot tmp for fsync: " + tmpPath.string());
- }
- if (::fsync(fd) != 0) {
- int saved_errno = errno;
- ::close(fd);
- cleanupTmp();
- throw std::runtime_error("fsync failed on snapshot tmp (errno=" +
- std::to_string(saved_errno) + "): " + tmpPath.string());
- }
- ::close(fd);
- }
- // Atomic rename - from this point on, either the final file exists and is complete,
- // or the .tmp is gone and no snapshot was produced.
- {
- std::error_code ec;
- std::filesystem::rename(tmpPath, snapshotPath, ec);
- if (ec) {
- cleanupTmp();
- throw std::runtime_error("Snapshot rename failed: " + ec.message());
- }
- }
- // fsync the containing directory so the rename is durable after crash
- {
- int dfd = ::open(config_.snapshotDir.c_str(), O_RDONLY | O_DIRECTORY);
- if (dfd >= 0) {
- ::fsync(dfd);
- ::close(dfd);
- }
- // Non-fatal on failure - some filesystems reject O_DIRECTORY
- }
- // Post-write verification (opt-out via config)
- bool verified = true;
- if (config_.validateAfterWrite) {
- if (!verifySnapshot(snapshotPath)) {
- // The file exists on disk but is corrupt - delete it so it can't be used
- std::error_code ec;
- std::filesystem::remove(snapshotPath, ec);
- throw std::runtime_error("Snapshot verification failed after write: " + snapshotPath.string());
- }
- spdlog::debug("Snapshot verified after write: {}", snapshotPath.string());
- }
- // Cleanup - only evict old snapshots if the new one passed verification
- // (or if cleanup_only_if_verified is disabled)
- if (verified || !config_.cleanupOnlyIfVerified) {
- cleanupOldSnapshots();
- }
- // v1.9.1 - release freelist pages after the snapshot write (the per-doc
- // JSON text and batch copies; since 2.20.1 no whole-body buffer).
- releaseFreelistPages();
- return snapshotPath;
- }
- uint64_t SnapshotManager::loadLatestSnapshot(MemoryStore& store) {
- auto snapshots = listSnapshots();
- if (snapshots.empty()) {
- return 0;
- }
- return loadSnapshot(snapshots.front(), store);
- }
- uint64_t SnapshotManager::loadWithFallback(MemoryStore& store,
- std::filesystem::path* outUsed,
- size_t* outAttempted) {
- auto snapshots = listSnapshots(); // already sorted newest-first
- if (outAttempted) *outAttempted = 0;
- if (snapshots.empty()) {
- throw std::runtime_error("loadWithFallback: no snapshots available");
- }
- std::string lastError;
- for (size_t i = 0; i < snapshots.size(); ++i) {
- const auto& path = snapshots[i];
- if (outAttempted) (*outAttempted)++;
- try {
- uint64_t seq = loadSnapshot(path, store);
- if (outUsed) *outUsed = path;
- if (i > 0) {
- spdlog::error(
- "Loaded fallback snapshot (index {} of {}): {} "
- "— newer snapshots were corrupt",
- i, snapshots.size(), path.string());
- }
- return seq;
- } catch (const std::exception& e) {
- lastError = e.what();
- spdlog::warn("Snapshot load failed for {}: {} — trying next older",
- path.string(), e.what());
- // Note: store.clear() is called by loadSnapshot() before writing,
- // so a partial load followed by retry on the next snapshot is safe.
- }
- }
- throw std::runtime_error("loadWithFallback: all " +
- std::to_string(snapshots.size()) +
- " snapshots failed to load (last error: " +
- lastError + ")");
- }
- uint64_t SnapshotManager::loadSnapshot(const std::filesystem::path& path, MemoryStore& store) {
- std::ifstream file(path, std::ios::binary);
- if (!file) {
- throw std::runtime_error("Failed to open snapshot file: " + path.string());
- }
- // Read header
- SnapshotHeader header;
- file.read(reinterpret_cast<char*>(&header), sizeof(header));
- if (!file) {
- throw std::runtime_error("Failed to read snapshot header");
- }
- // Verify magic
- if (std::memcmp(header.magic, "CALSNAP1", 8) != 0) {
- throw std::runtime_error("Invalid snapshot file magic");
- }
- // Verify header checksum
- uint32_t expectedHeaderCrc = crc32::calculate(&header, sizeof(header) - sizeof(header.headerChecksum));
- if (header.headerChecksum != expectedHeaderCrc) {
- throw std::runtime_error("Snapshot header checksum mismatch");
- }
- // Read body
- std::vector<uint8_t> bodyData(header.compressedSize);
- file.read(reinterpret_cast<char*>(bodyData.data()),
- static_cast<std::streamsize>(bodyData.size()));
- if (!file) {
- throw std::runtime_error("Failed to read snapshot body");
- }
- // Read and verify body checksum
- uint32_t storedBodyCrc;
- file.read(reinterpret_cast<char*>(&storedBodyCrc), sizeof(storedBodyCrc));
- uint32_t calculatedBodyCrc = crc32::calculate(bodyData.data(), bodyData.size());
- if (storedBodyCrc != calculatedBodyCrc) {
- throw std::runtime_error("Snapshot body checksum mismatch");
- }
- // Decompress if needed
- std::vector<uint8_t> uncompressedData;
- if (header.compressionType == 1) {
- if (header.version >= 4) {
- // v4: chunked LZ4 body
- uncompressedData = decompressChunked(bodyData, header.uncompressedSize);
- } else {
- // v3 and earlier: single LZ4 block
- uncompressedData = decompress(bodyData, header.uncompressedSize);
- if (uncompressedData.empty()) {
- throw std::runtime_error("Failed to decompress snapshot");
- }
- }
- } else {
- uncompressedData = std::move(bodyData);
- }
- // 2.20.1 - the compressed body is not needed while deserializing.
- std::vector<uint8_t>().swap(bodyData);
- // Clear store and deserialize
- store.clear();
- deserializeStore(uncompressedData, store, header.version);
- // v1.9.1 — release allocator freelist pages now that the multi-GB
- // transient buffers (decompressed body + per-doc JSON parses) are
- // gone. Without this, glibc keeps those pages parked on the per-
- // thread freelist; VmRSS stays high until subsequent small allocs
- // happen to land in the right bin. On Zoe (5 GB snapshot) this
- // drops post-boot RSS by ~2.8 GB.
- releaseFreelistPages();
- return header.walSequence;
- }
- std::vector<std::filesystem::path> SnapshotManager::listSnapshots() const {
- std::vector<std::pair<uint64_t, std::filesystem::path>> snapshots;
- // Clean up .tmp files left from crashed writes (they start with "snapshot-" and end with ".tmp")
- {
- std::error_code scan_ec;
- for (const auto& entry : std::filesystem::directory_iterator(config_.snapshotDir, scan_ec)) {
- if (!entry.is_regular_file()) continue;
- const auto& p = entry.path();
- if (p.extension() == ".tmp" &&
- p.filename().string().starts_with("snapshot-")) {
- std::error_code rm_ec;
- std::filesystem::remove(p, rm_ec);
- spdlog::info("Removed orphaned snapshot tmp file: {}", p.string());
- }
- }
- }
- std::error_code ec;
- for (const auto& entry : std::filesystem::directory_iterator(config_.snapshotDir, ec)) {
- if (entry.is_regular_file()) {
- const auto& path = entry.path();
- if (path.filename().string().starts_with("snapshot-") &&
- path.extension() == ".dat") {
- // Read header to get timestamp
- std::ifstream file(path, std::ios::binary);
- if (file) {
- SnapshotHeader header;
- file.read(reinterpret_cast<char*>(&header), sizeof(header));
- if (file && std::memcmp(header.magic, "CALSNAP1", 8) == 0) {
- snapshots.emplace_back(header.timestamp, path);
- }
- }
- }
- }
- }
- // Sort by timestamp descending (newest first)
- std::sort(snapshots.begin(), snapshots.end(),
- [](const auto& a, const auto& b) { return a.first > b.first; });
- std::vector<std::filesystem::path> result;
- result.reserve(snapshots.size());
- for (const auto& [_, path] : snapshots) {
- result.push_back(path);
- }
- return result;
- }
- std::optional<SnapshotHeader> SnapshotManager::getSnapshotInfo(const std::filesystem::path& path) const {
- std::ifstream file(path, std::ios::binary);
- if (!file) {
- return std::nullopt;
- }
- SnapshotHeader header;
- file.read(reinterpret_cast<char*>(&header), sizeof(header));
- if (!file) {
- return std::nullopt;
- }
- if (std::memcmp(header.magic, "CALSNAP1", 8) != 0) {
- return std::nullopt;
- }
- return header;
- }
- size_t SnapshotManager::removeAllExcept(const std::filesystem::path& keep) {
- size_t removed = 0;
- for (const auto& p : listSnapshots()) {
- if (p == keep) continue;
- std::error_code ec;
- if (std::filesystem::remove(p, ec)) ++removed;
- }
- return removed;
- }
- void SnapshotManager::cleanupOldSnapshots() {
- auto snapshots = listSnapshots();
- // Delete snapshots beyond the max count
- while (snapshots.size() > config_.maxSnapshots) {
- const auto& oldestPath = snapshots.back();
- std::error_code ec;
- std::filesystem::remove(oldestPath, ec);
- snapshots.pop_back();
- }
- }
- bool SnapshotManager::verifySnapshot(const std::filesystem::path& path) const {
- try {
- std::ifstream file(path, std::ios::binary);
- if (!file) {
- return false;
- }
- // Read and verify header
- SnapshotHeader header;
- file.read(reinterpret_cast<char*>(&header), sizeof(header));
- if (!file) {
- return false;
- }
- if (std::memcmp(header.magic, "CALSNAP1", 8) != 0) {
- return false;
- }
- uint32_t expectedHeaderCrc = crc32::calculate(&header, sizeof(header) - sizeof(header.headerChecksum));
- if (header.headerChecksum != expectedHeaderCrc) {
- return false;
- }
- // Read and verify the body a block at a time (2.20.1: it used to be
- // read whole, a third copy of the store's size at the end of a write).
- std::vector<char> block(1 << 20);
- uint32_t calculatedBodyCrc = 0;
- uint64_t remaining = header.compressedSize;
- while (remaining > 0) {
- const size_t n = static_cast<size_t>(std::min<uint64_t>(remaining, block.size()));
- file.read(block.data(), static_cast<std::streamsize>(n));
- if (!file) {
- return false;
- }
- calculatedBodyCrc = crc32::extend(calculatedBodyCrc, block.data(), n);
- remaining -= n;
- }
- uint32_t storedBodyCrc;
- file.read(reinterpret_cast<char*>(&storedBodyCrc), sizeof(storedBodyCrc));
- if (!file) {
- return false;
- }
- return storedBodyCrc == calculatedBodyCrc;
- } catch (...) {
- return false;
- }
- }
- std::string SnapshotManager::generateFilename() const {
- auto now = std::chrono::system_clock::now();
- auto time = std::chrono::system_clock::to_time_t(now);
- auto tm = *std::localtime(&time);
- std::ostringstream oss;
- oss << "snapshot-"
- << std::put_time(&tm, "%Y%m%d-%H%M%S")
- << ".dat";
- return oss.str();
- }
- std::vector<uint8_t> SnapshotManager::compress(const std::vector<uint8_t>& data) const {
- #ifndef DISABLE_LZ4
- if (data.empty()) {
- return {};
- }
- int maxCompressedSize = LZ4_compressBound(static_cast<int>(data.size()));
- std::vector<uint8_t> compressed(maxCompressedSize);
- int compressedSize = LZ4_compress_default(
- reinterpret_cast<const char*>(data.data()),
- reinterpret_cast<char*>(compressed.data()),
- static_cast<int>(data.size()),
- maxCompressedSize
- );
- if (compressedSize <= 0) {
- return {}; // Compression failed
- }
- compressed.resize(compressedSize);
- return compressed;
- #else
- return {}; // Compression disabled
- #endif
- }
- std::vector<uint8_t> SnapshotManager::decompress(const std::vector<uint8_t>& data,
- uint64_t uncompressedSize) const {
- #ifndef DISABLE_LZ4
- if (data.empty() || uncompressedSize == 0) {
- return {};
- }
- std::vector<uint8_t> decompressed(uncompressedSize);
- int decompressedSize = LZ4_decompress_safe(
- reinterpret_cast<const char*>(data.data()),
- reinterpret_cast<char*>(decompressed.data()),
- static_cast<int>(data.size()),
- static_cast<int>(uncompressedSize)
- );
- if (decompressedSize < 0 || static_cast<uint64_t>(decompressedSize) != uncompressedSize) {
- return {}; // Decompression failed
- }
- return decompressed;
- #else
- return {}; // Compression disabled
- #endif
- }
- template <typename Sink>
- void SnapshotManager::serializeStore(const MemoryStore& store, Sink& out,
- uint64_t& docCount, uint32_t& collCount) const {
- docCount = 0;
- collCount = 0;
- // 2.20.1 - documents are copied a batch at a time under the collection's
- // shared lock (MemoryStore::copyDocuments), never a whole collection.
- constexpr size_t kBatch = 256;
- auto collections = store.getAllCollectionsWithOptions();
- collCount = static_cast<uint32_t>(collections.size());
- for (const auto& [name, options] : collections) {
- out.u16(static_cast<uint16_t>(name.size()));
- out.bytes(name);
- const std::string optionsJson = options.toJson().dump();
- out.u32(static_cast<uint32_t>(optionsJson.size()));
- out.bytes(optionsJson);
- // Snapshot must include both in-memory docs AND docs that have been
- // evicted to stubs - otherwise truncateBefore(walSeq) after this
- // snapshot deletes the WAL entries that hold the only remaining copy
- // of the evicted docs (pre-v1.7.3 lost them that way).
- const auto residentIds = store.getDocumentIds(name);
- const auto evictedIds = store.getEvictedDocumentIds(name);
- // The doc count goes BEFORE the documents, and with a streaming writer
- // it cannot be back-patched once its chunk is on disk. So it counts
- // every listed id, and an id whose document is gone by the time it is
- // copied (deleted since: the delete is after walSeq and is replayed)
- // is written as a zero-length entry. Every reader since v1.8 skips
- // one: the deserializer catches the parse error of an empty body.
- out.u64(static_cast<uint64_t>(residentIds.size() + evictedIds.size()));
- uint64_t written = 0;
- auto writeDoc = [&](const std::optional<Document>& doc) {
- if (!doc) {
- out.u32(0);
- return false;
- }
- const std::string docJson = doc->toJson().dump();
- out.u32(static_cast<uint32_t>(docJson.size()));
- out.bytes(docJson);
- ++written;
- return true;
- };
- for (size_t i = 0; i < residentIds.size(); i += kBatch) {
- for (const auto& doc : store.copyDocuments(name, residentIds, i, kBatch)) writeDoc(doc);
- }
- // v2.21.0 - through copyDocuments too, not peekEvictedDocument: an id
- // reloaded into memory since it was listed is copied from memory (it
- // used to be written as absent and so dropped), and one whose evicted
- // copy cannot be read THROWS, abandoning this snapshot so the WAL that
- // holds it is kept. It used to be written as absent with a WARN, after
- // which the WAL was truncated and the next boot came up without it
- // while LMDB still had it.
- for (size_t i = 0; i < evictedIds.size(); i += kBatch) {
- for (const auto& doc : store.copyDocuments(name, evictedIds, i, kBatch)) writeDoc(doc);
- }
- docCount += written;
- // v1.9.0 - version history block is an empty section (history lives
- // in HistoryStore); the 8-byte zero count keeps v1.8.x readers happy.
- out.u64(0);
- // Vector data (v3). v2.21.2 - a batch at a time under the collection
- // lock (it iterated the live map with no lock), and including the
- // vectors eviction released, read back from LMDB. Like the doc count,
- // the vector count precedes the entries, so a vector deleted before it
- // is copied is written as a zero-length entry, which the loader skips
- // (a pre-2.21.2 loader stores an empty vector, which scores nothing).
- const auto vectorIds = store.getVectorIds(name);
- out.u64(static_cast<uint64_t>(vectorIds.size()));
- for (size_t i = 0; i < vectorIds.size(); i += kBatch) {
- const auto vecs = store.copyVectors(name, vectorIds, i, kBatch);
- for (size_t j = 0; j < vecs.size(); ++j) {
- const std::string& docId = vectorIds[i + j];
- out.u16(static_cast<uint16_t>(docId.size()));
- out.bytes(docId);
- if (!vecs[j]) {
- out.u32(0);
- continue;
- }
- out.u32(static_cast<uint32_t>(vecs[j]->size()));
- out.bytes(vecs[j]->data(), vecs[j]->size() * sizeof(float));
- }
- }
- }
- }
- namespace {
- // v1.8.0 — slice describing where one collection's bytes live in the
- // decompressed snapshot body, used by the two-phase parallel deserializer.
- struct CollectionSlice {
- std::string name;
- CollectionOptions options;
- uint64_t docCount = 0;
- size_t docSectionStart = 0;
- size_t docSectionEnd = 0;
- uint64_t historyEntryCount = 0;
- size_t historySectionStart = 0;
- size_t historySectionEnd = 0;
- uint64_t vecCount = 0;
- size_t vecSectionStart = 0;
- size_t vecSectionEnd = 0;
- };
- } // namespace
- void SnapshotManager::deserializeStore(const std::vector<uint8_t>& data, MemoryStore& store,
- uint32_t snapshotVersion) const {
- // v1.8.0 — two-phase parallel deserializer. Before this, a 5 GB snapshot
- // with many JSON-encoded documents pinned a single core at 100% for tens
- // of seconds during boot. The serialized format is a concatenation of
- // independent per-collection blocks, so we:
- // 1. Walk the body once with pure byte arithmetic (no JSON parsing) to
- // record each collection's name, options, and the byte ranges that
- // hold its docs / history / vectors. This is cheap and stays in L2.
- // 2. Create the collections sequentially so global state (collection
- // map, options) is consistent before workers start.
- // 3. Spawn N worker threads (N = hardware_concurrency capped at the
- // number of collections) that pull work off a shared index counter
- // and parse + load each collection's payload in isolation. JSON
- // parsing — the actual hot path — runs in parallel; per-collection
- // MemoryStore mutexes mean no two workers contend on the same
- // collection's documents map.
- //
- // For workloads with many small/medium collections (e.g. ShadowMan, with
- // ~30 collections) this drops boot time roughly linearly with cores. For
- // a single-giant-collection workload there is no within-collection
- // parallelism yet; that would be a follow-up.
- // ===== Phase 1: scan body byte-by-byte to find collection slices =====
- std::vector<CollectionSlice> slices;
- size_t offset = 0;
- while (offset < data.size()) {
- CollectionSlice slice;
- // Collection name
- if (offset + 2 > data.size()) break;
- uint16_t nameLen = static_cast<uint16_t>(data[offset]) |
- (static_cast<uint16_t>(data[offset + 1]) << 8);
- offset += 2;
- if (offset + nameLen > data.size()) break;
- slice.name.assign(reinterpret_cast<const char*>(&data[offset]), nameLen);
- offset += nameLen;
- // Collection options (small JSON — keep parsing here, sequential)
- if (offset + 4 > data.size()) break;
- uint32_t optionsLen = 0;
- for (int i = 0; i < 4; ++i) {
- optionsLen |= static_cast<uint32_t>(data[offset++]) << (i * 8);
- }
- if (offset + optionsLen > data.size()) break;
- std::string optionsJson(reinterpret_cast<const char*>(&data[offset]), optionsLen);
- offset += optionsLen;
- try {
- slice.options = CollectionOptions::fromJson(smartbotic::db::parse_to_nlohmann(optionsJson));
- } catch (const nlohmann::json::exception&) {
- // Defaults — same fallback as the pre-v1.8 path.
- }
- // Document section — record its byte range, skip past without parsing
- if (offset + 8 > data.size()) break;
- for (int i = 0; i < 8; ++i) {
- slice.docCount |= static_cast<uint64_t>(data[offset++]) << (i * 8);
- }
- slice.docSectionStart = offset;
- for (uint64_t i = 0; i < slice.docCount; ++i) {
- if (offset + 4 > data.size()) { offset = data.size(); break; }
- uint32_t docLen = 0;
- for (int j = 0; j < 4; ++j) {
- docLen |= static_cast<uint32_t>(data[offset++]) << (j * 8);
- }
- if (offset + docLen > data.size()) { offset = data.size(); break; }
- offset += docLen;
- }
- slice.docSectionEnd = offset;
- // History section (v2+)
- if (snapshotVersion >= 2) {
- if (offset + 8 > data.size()) break;
- for (int i = 0; i < 8; ++i) {
- slice.historyEntryCount |= static_cast<uint64_t>(data[offset++]) << (i * 8);
- }
- slice.historySectionStart = offset;
- for (uint64_t h = 0; h < slice.historyEntryCount; ++h) {
- if (offset + 2 > data.size()) { offset = data.size(); break; }
- uint16_t docIdLen = static_cast<uint16_t>(data[offset]) |
- (static_cast<uint16_t>(data[offset + 1]) << 8);
- offset += 2;
- if (offset + docIdLen > data.size()) { offset = data.size(); break; }
- offset += docIdLen;
- if (offset + 4 > data.size()) { offset = data.size(); break; }
- uint32_t versionCount = 0;
- for (int i = 0; i < 4; ++i) {
- versionCount |= static_cast<uint32_t>(data[offset++]) << (i * 8);
- }
- for (uint32_t v = 0; v < versionCount; ++v) {
- if (offset + 4 > data.size()) { offset = data.size(); break; }
- uint32_t verLen = 0;
- for (int i = 0; i < 4; ++i) {
- verLen |= static_cast<uint32_t>(data[offset++]) << (i * 8);
- }
- if (offset + verLen > data.size()) { offset = data.size(); break; }
- offset += verLen;
- }
- }
- slice.historySectionEnd = offset;
- }
- // Vector section (v3+)
- if (snapshotVersion >= 3) {
- if (offset + 8 > data.size()) break;
- for (int i = 0; i < 8; ++i) {
- slice.vecCount |= static_cast<uint64_t>(data[offset++]) << (i * 8);
- }
- slice.vecSectionStart = offset;
- for (uint64_t v = 0; v < slice.vecCount; ++v) {
- if (offset + 2 > data.size()) { offset = data.size(); break; }
- uint16_t docIdLen = static_cast<uint16_t>(data[offset]) |
- (static_cast<uint16_t>(data[offset + 1]) << 8);
- offset += 2;
- if (offset + docIdLen > data.size()) { offset = data.size(); break; }
- offset += docIdLen;
- if (offset + 4 > data.size()) { offset = data.size(); break; }
- uint32_t dim = 0;
- for (int i = 0; i < 4; ++i) {
- dim |= static_cast<uint32_t>(data[offset++]) << (i * 8);
- }
- size_t byteCount = static_cast<size_t>(dim) * sizeof(float);
- if (offset + byteCount > data.size()) { offset = data.size(); break; }
- offset += byteCount;
- }
- slice.vecSectionEnd = offset;
- }
- slices.push_back(std::move(slice));
- }
- // ===== Phase 2: create all collections sequentially =====
- // Doing this before workers start means each worker only mutates its own
- // collection's per-coll mutex, never the global collections map.
- for (const auto& slice : slices) {
- store.createCollection(slice.name, slice.options);
- }
- // ===== Phase 3: parallel parse + load per collection =====
- // Worker: pop a slice index, parse + load all of its docs / history /
- // vectors. JSON parsing is the dominant cost; per-collection isolation
- // means no shared-mutex contention except on the lock-free atomics.
- const auto loadOneSlice = [&data, &store, snapshotVersion](const CollectionSlice& slice) {
- const std::string& collName = slice.name;
- // --- Documents ---
- size_t off = slice.docSectionStart;
- for (uint64_t i = 0; i < slice.docCount && off < slice.docSectionEnd; ++i) {
- if (off + 4 > slice.docSectionEnd) break;
- uint32_t docLen = 0;
- for (int j = 0; j < 4; ++j) {
- docLen |= static_cast<uint32_t>(data[off++]) << (j * 8);
- }
- if (off + docLen > slice.docSectionEnd) break;
- std::string docJson(reinterpret_cast<const char*>(&data[off]), docLen);
- off += docLen;
- try {
- Document doc = Document::fromJson(smartbotic::db::parse_to_nlohmann(docJson));
- store.loadDocument(collName, doc);
- } catch (const nlohmann::json::exception&) {
- // Skip invalid document — same tolerance as pre-v1.8.
- }
- }
- // --- History ---
- if (snapshotVersion >= 2) {
- off = slice.historySectionStart;
- for (uint64_t h = 0; h < slice.historyEntryCount && off < slice.historySectionEnd; ++h) {
- if (off + 2 > slice.historySectionEnd) break;
- uint16_t docIdLen = static_cast<uint16_t>(data[off]) |
- (static_cast<uint16_t>(data[off + 1]) << 8);
- off += 2;
- if (off + docIdLen > slice.historySectionEnd) break;
- std::string docId(reinterpret_cast<const char*>(&data[off]), docIdLen);
- off += docIdLen;
- if (off + 4 > slice.historySectionEnd) break;
- uint32_t versionCount = 0;
- for (int i = 0; i < 4; ++i) {
- versionCount |= static_cast<uint32_t>(data[off++]) << (i * 8);
- }
- std::deque<DocumentVersion> history;
- for (uint32_t v = 0; v < versionCount; ++v) {
- if (off + 4 > slice.historySectionEnd) break;
- uint32_t verLen = 0;
- for (int i = 0; i < 4; ++i) {
- verLen |= static_cast<uint32_t>(data[off++]) << (i * 8);
- }
- if (off + verLen > slice.historySectionEnd) break;
- std::string verJson(reinterpret_cast<const char*>(&data[off]), verLen);
- off += verLen;
- try {
- auto ver = DocumentVersion::fromJson(smartbotic::db::parse_to_nlohmann(verJson));
- history.push_back(std::move(ver));
- } catch (const nlohmann::json::exception&) {
- // Skip invalid version entry.
- }
- }
- if (!history.empty()) {
- store.loadVersionHistory(collName, docId, std::move(history));
- }
- }
- }
- // --- Vectors ---
- if (snapshotVersion >= 3) {
- off = slice.vecSectionStart;
- for (uint64_t v = 0; v < slice.vecCount && off < slice.vecSectionEnd; ++v) {
- if (off + 2 > slice.vecSectionEnd) break;
- uint16_t docIdLen = static_cast<uint16_t>(data[off]) |
- (static_cast<uint16_t>(data[off + 1]) << 8);
- off += 2;
- if (off + docIdLen > slice.vecSectionEnd) break;
- std::string docId(reinterpret_cast<const char*>(&data[off]), docIdLen);
- off += docIdLen;
- if (off + 4 > slice.vecSectionEnd) break;
- uint32_t dim = 0;
- for (int i = 0; i < 4; ++i) {
- dim |= static_cast<uint32_t>(data[off++]) << (i * 8);
- }
- size_t byteCount = static_cast<size_t>(dim) * sizeof(float);
- if (off + byteCount > slice.vecSectionEnd) break;
- if (dim == 0) continue; // v2.21.2 placeholder: deleted while written
- std::vector<float> vec(dim);
- std::memcpy(vec.data(), &data[off], byteCount);
- off += byteCount;
- store.loadVector(collName, docId, std::move(vec));
- }
- }
- };
- if (slices.size() <= 1) {
- // Trivial fast path — single collection, no parallelism overhead.
- for (const auto& slice : slices) loadOneSlice(slice);
- return;
- }
- const size_t hwc = std::thread::hardware_concurrency();
- const size_t workerCount = std::min(slices.size(), hwc > 0 ? hwc : 4);
- std::atomic<size_t> nextSlice{0};
- std::vector<std::thread> workers;
- workers.reserve(workerCount);
- for (size_t w = 0; w < workerCount; ++w) {
- workers.emplace_back([&]() {
- for (;;) {
- size_t i = nextSlice.fetch_add(1, std::memory_order_relaxed);
- if (i >= slices.size()) break;
- loadOneSlice(slices[i]);
- }
- });
- }
- for (auto& t : workers) t.join();
- spdlog::info("Snapshot deserialized: {} collections via {} workers",
- slices.size(), workerCount);
- }
- } // namespace smartbotic::database
|