|
@@ -110,139 +110,204 @@ SnapshotManager::SnapshotManager(Config config)
|
|
|
std::filesystem::create_directories(config_.snapshotDir, ec);
|
|
std::filesystem::create_directories(config_.snapshotDir, ec);
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
-std::filesystem::path SnapshotManager::createSnapshot(const MemoryStore& store, uint64_t walSequence) {
|
|
|
|
|
- // Serialize store data
|
|
|
|
|
- uint64_t docCount = 0;
|
|
|
|
|
- uint32_t collCount = 0;
|
|
|
|
|
- std::vector<uint8_t> uncompressedData = serializeStore(store, docCount, collCount);
|
|
|
|
|
- const uint64_t originalUncompressedSize = uncompressedData.size();
|
|
|
|
|
|
|
+namespace {
|
|
|
|
|
|
|
|
- // Build chunked body with streaming compression.
|
|
|
|
|
- // v4 body layout: sequence of [u32 uncompressed_size, u32 compressed_size, bytes...]
|
|
|
|
|
- // terminated by a (0, 0) end marker. Peak memory per chunk is ~16 MB output buffer
|
|
|
|
|
- // instead of LZ4_compressBound(full DB) which used to be ~3 GB for production sizes.
|
|
|
|
|
- constexpr size_t CHUNK_SIZE = 16 * 1024 * 1024; // 16 MB uncompressed per chunk
|
|
|
|
|
|
|
+uint64_t nowMs() {
|
|
|
|
|
+ return static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(
|
|
|
|
|
+ std::chrono::system_clock::now().time_since_epoch()).count());
|
|
|
|
|
+}
|
|
|
|
|
|
|
|
- std::vector<uint8_t> bodyData;
|
|
|
|
|
- uint32_t compressionType = 0;
|
|
|
|
|
|
|
+// 2.21.0 - 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_);
|
|
|
|
|
+ }
|
|
|
|
|
|
|
|
- if (config_.compressionEnabled) {
|
|
|
|
|
-#ifndef DISABLE_LZ4
|
|
|
|
|
- compressionType = 1;
|
|
|
|
|
- // Rough estimate to reduce reallocation thrash; actual size depends on payload compressibility.
|
|
|
|
|
- bodyData.reserve(uncompressedData.size() / 2 + CHUNK_SIZE);
|
|
|
|
|
-
|
|
|
|
|
- size_t offset = 0;
|
|
|
|
|
- while (offset < uncompressedData.size()) {
|
|
|
|
|
- size_t thisChunk = std::min(CHUNK_SIZE, uncompressedData.size() - offset);
|
|
|
|
|
- int compressBound = LZ4_compressBound(static_cast<int>(thisChunk));
|
|
|
|
|
- std::vector<uint8_t> chunkOut(compressBound);
|
|
|
|
|
-
|
|
|
|
|
- int compressedSize = LZ4_compress_default(
|
|
|
|
|
- reinterpret_cast<const char*>(uncompressedData.data() + offset),
|
|
|
|
|
- reinterpret_cast<char*>(chunkOut.data()),
|
|
|
|
|
- static_cast<int>(thisChunk),
|
|
|
|
|
- compressBound
|
|
|
|
|
- );
|
|
|
|
|
- if (compressedSize <= 0) {
|
|
|
|
|
- throw std::runtime_error("LZ4 compression failed at offset " + std::to_string(offset));
|
|
|
|
|
- }
|
|
|
|
|
|
|
+ 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);
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
|
|
|
- // Append length prefixes and compressed data to bodyData
|
|
|
|
|
- uint32_t uncompU32 = static_cast<uint32_t>(thisChunk);
|
|
|
|
|
- uint32_t compU32 = static_cast<uint32_t>(compressedSize);
|
|
|
|
|
- const uint8_t* uncompBytes = reinterpret_cast<const uint8_t*>(&uncompU32);
|
|
|
|
|
- const uint8_t* compBytes = reinterpret_cast<const uint8_t*>(&compU32);
|
|
|
|
|
- bodyData.insert(bodyData.end(), uncompBytes, uncompBytes + 4);
|
|
|
|
|
- bodyData.insert(bodyData.end(), compBytes, compBytes + 4);
|
|
|
|
|
- bodyData.insert(bodyData.end(), chunkOut.begin(), chunkOut.begin() + compressedSize);
|
|
|
|
|
|
|
+ uint64_t uncompressedSize() const { return uncompressed_; }
|
|
|
|
|
+ uint64_t bodySize() const { return body_; }
|
|
|
|
|
+ uint32_t bodyCrc() const { return crc_; }
|
|
|
|
|
|
|
|
- offset += thisChunk;
|
|
|
|
|
- }
|
|
|
|
|
|
|
+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));
|
|
|
|
|
+ }
|
|
|
|
|
|
|
|
- // End marker: two zero u32s
|
|
|
|
|
- uint32_t zero = 0;
|
|
|
|
|
- const uint8_t* zeroBytes = reinterpret_cast<const uint8_t*>(&zero);
|
|
|
|
|
- bodyData.insert(bodyData.end(), zeroBytes, zeroBytes + 4);
|
|
|
|
|
- bodyData.insert(bodyData.end(), zeroBytes, zeroBytes + 4);
|
|
|
|
|
|
|
+ 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;
|
|
|
|
|
+ }
|
|
|
|
|
|
|
|
- // Free the uncompressed buffer — we no longer need it
|
|
|
|
|
- std::vector<uint8_t>().swap(uncompressedData);
|
|
|
|
|
-#else
|
|
|
|
|
- bodyData = std::move(uncompressedData);
|
|
|
|
|
- compressionType = 0;
|
|
|
|
|
|
|
+ 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
|
|
#endif
|
|
|
- } else {
|
|
|
|
|
- bodyData = std::move(uncompressedData);
|
|
|
|
|
|
|
+ emit(stage_.data(), stage_.size());
|
|
|
|
|
+ stage_.clear();
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- // Build header
|
|
|
|
|
- SnapshotHeader header;
|
|
|
|
|
- header.timestamp = static_cast<uint64_t>(
|
|
|
|
|
- std::chrono::duration_cast<std::chrono::milliseconds>(
|
|
|
|
|
- std::chrono::system_clock::now().time_since_epoch()
|
|
|
|
|
- ).count()
|
|
|
|
|
- );
|
|
|
|
|
- header.walSequence = walSequence;
|
|
|
|
|
- header.documentCount = docCount;
|
|
|
|
|
- header.collectionCount = collCount;
|
|
|
|
|
- header.uncompressedSize = originalUncompressedSize;
|
|
|
|
|
- header.compressedSize = bodyData.size();
|
|
|
|
|
- header.compressionType = compressionType;
|
|
|
|
|
|
|
+ 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);
|
|
|
|
|
+ }
|
|
|
|
|
+};
|
|
|
|
|
|
|
|
- // Calculate header checksum (excluding the checksum field itself)
|
|
|
|
|
- header.headerChecksum = crc32::calculate(&header, sizeof(header) - sizeof(header.headerChecksum));
|
|
|
|
|
|
|
+} // 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;
|
|
|
|
|
+}
|
|
|
|
|
|
|
|
- // Generate filename — write to .tmp first, atomic rename at the end
|
|
|
|
|
|
|
+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 snapshotPath = config_.snapshotDir / generateFilename();
|
|
|
std::filesystem::path tmpPath = snapshotPath;
|
|
std::filesystem::path tmpPath = snapshotPath;
|
|
|
tmpPath += ".tmp";
|
|
tmpPath += ".tmp";
|
|
|
|
|
|
|
|
- // Helper to remove tmp on error paths
|
|
|
|
|
auto cleanupTmp = [&tmpPath]() {
|
|
auto cleanupTmp = [&tmpPath]() {
|
|
|
std::error_code ec;
|
|
std::error_code ec;
|
|
|
std::filesystem::remove(tmpPath, ec);
|
|
std::filesystem::remove(tmpPath, ec);
|
|
|
};
|
|
};
|
|
|
|
|
|
|
|
- // Write to temp file
|
|
|
|
|
- {
|
|
|
|
|
|
|
+ try {
|
|
|
std::ofstream file(tmpPath, std::ios::binary | std::ios::trunc);
|
|
std::ofstream file(tmpPath, std::ios::binary | std::ios::trunc);
|
|
|
if (!file) {
|
|
if (!file) {
|
|
|
throw std::runtime_error("Failed to create snapshot tmp file: " + tmpPath.string());
|
|
throw std::runtime_error("Failed to create snapshot tmp file: " + tmpPath.string());
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- // Header + short-write check
|
|
|
|
|
|
|
+ // 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));
|
|
file.write(reinterpret_cast<const char*>(&header), sizeof(header));
|
|
|
- if (!file) {
|
|
|
|
|
- cleanupTmp();
|
|
|
|
|
- throw std::runtime_error("Failed to write snapshot header: " + tmpPath.string());
|
|
|
|
|
- }
|
|
|
|
|
|
|
+ if (!file) throw std::runtime_error("Failed to write snapshot header: " + tmpPath.string());
|
|
|
|
|
|
|
|
- // Body + short-write check
|
|
|
|
|
- file.write(reinterpret_cast<const char*>(bodyData.data()),
|
|
|
|
|
- static_cast<std::streamsize>(bodyData.size()));
|
|
|
|
|
- if (!file) {
|
|
|
|
|
- cleanupTmp();
|
|
|
|
|
- throw std::runtime_error("Failed to write snapshot body (short write): " + tmpPath.string());
|
|
|
|
|
- }
|
|
|
|
|
|
|
+ uint64_t docCount = 0;
|
|
|
|
|
+ uint32_t collCount = 0;
|
|
|
|
|
+ BodyWriter body(file, compress, config_.chunkBytes);
|
|
|
|
|
+ serializeStore(store, body, docCount, collCount);
|
|
|
|
|
+ body.finish();
|
|
|
|
|
|
|
|
- // Trailer (body CRC) + short-write check
|
|
|
|
|
- uint32_t bodyChecksum = crc32::calculate(bodyData.data(), bodyData.size());
|
|
|
|
|
|
|
+ const uint32_t bodyChecksum = body.bodyCrc();
|
|
|
file.write(reinterpret_cast<const char*>(&bodyChecksum), sizeof(bodyChecksum));
|
|
file.write(reinterpret_cast<const char*>(&bodyChecksum), sizeof(bodyChecksum));
|
|
|
- if (!file) {
|
|
|
|
|
- cleanupTmp();
|
|
|
|
|
- throw std::runtime_error("Failed to write snapshot trailer: " + tmpPath.string());
|
|
|
|
|
- }
|
|
|
|
|
|
|
+ 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());
|
|
|
|
|
|
|
|
- // Flush C++ stream buffer
|
|
|
|
|
file.flush();
|
|
file.flush();
|
|
|
- if (!file) {
|
|
|
|
|
- cleanupTmp();
|
|
|
|
|
- throw std::runtime_error("Failed to flush snapshot: " + tmpPath.string());
|
|
|
|
|
- }
|
|
|
|
|
- } // ofstream destructor runs close()
|
|
|
|
|
|
|
+ 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
|
|
|
|
|
|
|
+ // fsync the file descriptor - C++ ofstream does not do this
|
|
|
{
|
|
{
|
|
|
int fd = ::open(tmpPath.c_str(), O_RDONLY);
|
|
int fd = ::open(tmpPath.c_str(), O_RDONLY);
|
|
|
if (fd < 0) {
|
|
if (fd < 0) {
|
|
@@ -259,7 +324,7 @@ std::filesystem::path SnapshotManager::createSnapshot(const MemoryStore& store,
|
|
|
::close(fd);
|
|
::close(fd);
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- // Atomic rename — from this point on, either the final file exists and is complete,
|
|
|
|
|
|
|
+ // Atomic rename - from this point on, either the final file exists and is complete,
|
|
|
// or the .tmp is gone and no snapshot was produced.
|
|
// or the .tmp is gone and no snapshot was produced.
|
|
|
{
|
|
{
|
|
|
std::error_code ec;
|
|
std::error_code ec;
|
|
@@ -277,14 +342,14 @@ std::filesystem::path SnapshotManager::createSnapshot(const MemoryStore& store,
|
|
|
::fsync(dfd);
|
|
::fsync(dfd);
|
|
|
::close(dfd);
|
|
::close(dfd);
|
|
|
}
|
|
}
|
|
|
- // Non-fatal on failure — some filesystems reject O_DIRECTORY
|
|
|
|
|
|
|
+ // Non-fatal on failure - some filesystems reject O_DIRECTORY
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
// Post-write verification (opt-out via config)
|
|
// Post-write verification (opt-out via config)
|
|
|
bool verified = true;
|
|
bool verified = true;
|
|
|
if (config_.validateAfterWrite) {
|
|
if (config_.validateAfterWrite) {
|
|
|
if (!verifySnapshot(snapshotPath)) {
|
|
if (!verifySnapshot(snapshotPath)) {
|
|
|
- // The file exists on disk but is corrupt — delete it so it can't be used
|
|
|
|
|
|
|
+ // The file exists on disk but is corrupt - delete it so it can't be used
|
|
|
std::error_code ec;
|
|
std::error_code ec;
|
|
|
std::filesystem::remove(snapshotPath, ec);
|
|
std::filesystem::remove(snapshotPath, ec);
|
|
|
throw std::runtime_error("Snapshot verification failed after write: " + snapshotPath.string());
|
|
throw std::runtime_error("Snapshot verification failed after write: " + snapshotPath.string());
|
|
@@ -292,18 +357,14 @@ std::filesystem::path SnapshotManager::createSnapshot(const MemoryStore& store,
|
|
|
spdlog::debug("Snapshot verified after write: {}", snapshotPath.string());
|
|
spdlog::debug("Snapshot verified after write: {}", snapshotPath.string());
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- // Cleanup — only evict old snapshots if the new one passed verification
|
|
|
|
|
|
|
+ // Cleanup - only evict old snapshots if the new one passed verification
|
|
|
// (or if cleanup_only_if_verified is disabled)
|
|
// (or if cleanup_only_if_verified is disabled)
|
|
|
if (verified || !config_.cleanupOnlyIfVerified) {
|
|
if (verified || !config_.cleanupOnlyIfVerified) {
|
|
|
cleanupOldSnapshots();
|
|
cleanupOldSnapshots();
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- // v1.9.1 — release freelist pages after the snapshot write. We just
|
|
|
|
|
- // built and threw away the uncompressed serialized buffer
|
|
|
|
|
- // (potentially several GB) plus LZ4 chunk staging buffers; same
|
|
|
|
|
- // post-burst freelist-retention story as the boot-time load above.
|
|
|
|
|
- // Trimming here keeps the periodic snapshot path from drifting RSS
|
|
|
|
|
- // up over the day. Cheap relative to the snapshot write itself.
|
|
|
|
|
|
|
+ // v1.9.1 - release freelist pages after the snapshot write (the per-doc
|
|
|
|
|
+ // JSON text and batch copies; since 2.21.0 no whole-body buffer).
|
|
|
releaseFreelistPages();
|
|
releaseFreelistPages();
|
|
|
|
|
|
|
|
return snapshotPath;
|
|
return snapshotPath;
|
|
@@ -415,6 +476,8 @@ uint64_t SnapshotManager::loadSnapshot(const std::filesystem::path& path, Memory
|
|
|
} else {
|
|
} else {
|
|
|
uncompressedData = std::move(bodyData);
|
|
uncompressedData = std::move(bodyData);
|
|
|
}
|
|
}
|
|
|
|
|
+ // 2.21.0 - the compressed body is not needed while deserializing.
|
|
|
|
|
+ std::vector<uint8_t>().swap(bodyData);
|
|
|
|
|
|
|
|
// Clear store and deserialize
|
|
// Clear store and deserialize
|
|
|
store.clear();
|
|
store.clear();
|
|
@@ -545,17 +608,26 @@ bool SnapshotManager::verifySnapshot(const std::filesystem::path& path) const {
|
|
|
return false;
|
|
return false;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- // Read and verify body
|
|
|
|
|
- std::vector<uint8_t> bodyData(header.compressedSize);
|
|
|
|
|
- file.read(reinterpret_cast<char*>(bodyData.data()),
|
|
|
|
|
- static_cast<std::streamsize>(bodyData.size()));
|
|
|
|
|
- if (!file) {
|
|
|
|
|
- return false;
|
|
|
|
|
|
|
+ // Read and verify the body a block at a time (2.21.0: 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;
|
|
uint32_t storedBodyCrc;
|
|
|
file.read(reinterpret_cast<char*>(&storedBodyCrc), sizeof(storedBodyCrc));
|
|
file.read(reinterpret_cast<char*>(&storedBodyCrc), sizeof(storedBodyCrc));
|
|
|
- uint32_t calculatedBodyCrc = crc32::calculate(bodyData.data(), bodyData.size());
|
|
|
|
|
|
|
+ if (!file) {
|
|
|
|
|
+ return false;
|
|
|
|
|
+ }
|
|
|
|
|
|
|
|
return storedBodyCrc == calculatedBodyCrc;
|
|
return storedBodyCrc == calculatedBodyCrc;
|
|
|
} catch (...) {
|
|
} catch (...) {
|
|
@@ -629,135 +701,87 @@ std::vector<uint8_t> SnapshotManager::decompress(const std::vector<uint8_t>& dat
|
|
|
#endif
|
|
#endif
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
-std::vector<uint8_t> SnapshotManager::serializeStore(const MemoryStore& store,
|
|
|
|
|
- uint64_t& docCount,
|
|
|
|
|
- uint32_t& collCount) const {
|
|
|
|
|
- std::vector<uint8_t> result;
|
|
|
|
|
|
|
+template <typename Sink>
|
|
|
|
|
+void SnapshotManager::serializeStore(const MemoryStore& store, Sink& out,
|
|
|
|
|
+ uint64_t& docCount, uint32_t& collCount) const {
|
|
|
docCount = 0;
|
|
docCount = 0;
|
|
|
collCount = 0;
|
|
collCount = 0;
|
|
|
|
|
|
|
|
|
|
+ // 2.21.0 - 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();
|
|
auto collections = store.getAllCollectionsWithOptions();
|
|
|
collCount = static_cast<uint32_t>(collections.size());
|
|
collCount = static_cast<uint32_t>(collections.size());
|
|
|
|
|
|
|
|
for (const auto& [name, options] : collections) {
|
|
for (const auto& [name, options] : collections) {
|
|
|
- // Write collection name
|
|
|
|
|
- uint16_t nameLen = static_cast<uint16_t>(name.size());
|
|
|
|
|
- result.push_back(static_cast<uint8_t>(nameLen & 0xFF));
|
|
|
|
|
- result.push_back(static_cast<uint8_t>((nameLen >> 8) & 0xFF));
|
|
|
|
|
- result.insert(result.end(), name.begin(), name.end());
|
|
|
|
|
-
|
|
|
|
|
- // Write collection options
|
|
|
|
|
- std::string optionsJson = options.toJson().dump();
|
|
|
|
|
- uint32_t optionsLen = static_cast<uint32_t>(optionsJson.size());
|
|
|
|
|
- for (int i = 0; i < 4; ++i) {
|
|
|
|
|
- result.push_back(static_cast<uint8_t>((optionsLen >> (i * 8)) & 0xFF));
|
|
|
|
|
- }
|
|
|
|
|
- result.insert(result.end(), optionsJson.begin(), optionsJson.end());
|
|
|
|
|
-
|
|
|
|
|
- // Get all documents in collection. 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, and they're
|
|
|
|
|
- // gone forever. Pre-v1.7.3 only wrote in-memory docs; v1.7.0
|
|
|
|
|
- // introduced eviction without a corresponding snapshot path, so any
|
|
|
|
|
- // snapshot taken after eviction silently lost the evicted set.
|
|
|
|
|
- auto docs = store.getAllDocuments(name);
|
|
|
|
|
- auto evictedIds = store.getEvictedDocumentIds(name);
|
|
|
|
|
-
|
|
|
|
|
- // Reserve 8 bytes for the doc count and back-patch after writing,
|
|
|
|
|
- // so we can skip evicted docs that fail to load from WAL without
|
|
|
|
|
- // desynchronising the deserializer's counter.
|
|
|
|
|
- size_t countOffset = result.size();
|
|
|
|
|
- for (int i = 0; i < 8; ++i) result.push_back(0);
|
|
|
|
|
-
|
|
|
|
|
- uint64_t collDocCount = 0;
|
|
|
|
|
-
|
|
|
|
|
- // Write each in-memory document
|
|
|
|
|
- for (const auto& doc : docs) {
|
|
|
|
|
- std::string docJson = doc.toJson().dump();
|
|
|
|
|
- uint32_t docLen = static_cast<uint32_t>(docJson.size());
|
|
|
|
|
- for (int i = 0; i < 4; ++i) {
|
|
|
|
|
- result.push_back(static_cast<uint8_t>((docLen >> (i * 8)) & 0xFF));
|
|
|
|
|
|
|
+ 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;
|
|
|
|
|
+ uint64_t evictedFailed = 0;
|
|
|
|
|
+ auto writeDoc = [&](const std::optional<Document>& doc) {
|
|
|
|
|
+ if (!doc) {
|
|
|
|
|
+ out.u32(0);
|
|
|
|
|
+ return false;
|
|
|
}
|
|
}
|
|
|
- result.insert(result.end(), docJson.begin(), docJson.end());
|
|
|
|
|
- collDocCount++;
|
|
|
|
|
|
|
+ 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);
|
|
|
}
|
|
}
|
|
|
-
|
|
|
|
|
- // Write each evicted document, loading from WAL via the document
|
|
|
|
|
- // load callback. peekEvictedDocument is const and uses the same
|
|
|
|
|
- // path that read queries use to fault evicted docs back in.
|
|
|
|
|
- uint64_t evictedFailed = 0;
|
|
|
|
|
for (const auto& id : evictedIds) {
|
|
for (const auto& id : evictedIds) {
|
|
|
- auto docOpt = store.peekEvictedDocument(name, id);
|
|
|
|
|
- if (!docOpt) {
|
|
|
|
|
- evictedFailed++;
|
|
|
|
|
- continue;
|
|
|
|
|
- }
|
|
|
|
|
- std::string docJson = docOpt->toJson().dump();
|
|
|
|
|
- uint32_t docLen = static_cast<uint32_t>(docJson.size());
|
|
|
|
|
- for (int i = 0; i < 4; ++i) {
|
|
|
|
|
- result.push_back(static_cast<uint8_t>((docLen >> (i * 8)) & 0xFF));
|
|
|
|
|
- }
|
|
|
|
|
- result.insert(result.end(), docJson.begin(), docJson.end());
|
|
|
|
|
- collDocCount++;
|
|
|
|
|
|
|
+ if (!writeDoc(store.peekEvictedDocument(name, id))) ++evictedFailed;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
if (evictedFailed > 0) {
|
|
if (evictedFailed > 0) {
|
|
|
spdlog::warn(
|
|
spdlog::warn(
|
|
|
"Snapshot: {} evicted documents in collection '{}' could not "
|
|
"Snapshot: {} evicted documents in collection '{}' could not "
|
|
|
- "be loaded from WAL — they will be missing from the snapshot. "
|
|
|
|
|
|
|
+ "be loaded - they will be missing from the snapshot. "
|
|
|
"Likely a pre-v1.7.3 snapshot already lost them.",
|
|
"Likely a pre-v1.7.3 snapshot already lost them.",
|
|
|
evictedFailed, name);
|
|
evictedFailed, name);
|
|
|
}
|
|
}
|
|
|
|
|
+ docCount += written;
|
|
|
|
|
|
|
|
- // Back-patch the doc count
|
|
|
|
|
- for (int i = 0; i < 8; ++i) {
|
|
|
|
|
- result[countOffset + i] =
|
|
|
|
|
- static_cast<uint8_t>((collDocCount >> (i * 8)) & 0xFF);
|
|
|
|
|
- }
|
|
|
|
|
|
|
+ // 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);
|
|
|
|
|
|
|
|
- docCount += collDocCount;
|
|
|
|
|
-
|
|
|
|
|
- // v1.9.0 — version history block is now an empty section. History
|
|
|
|
|
- // moved to disk-resident HistoryStore (separate `.hlog` files per
|
|
|
|
|
- // collection under <data_dir>/history/). We still emit the
|
|
|
|
|
- // 8-byte zero count so v1.8.x readers can parse the snapshot
|
|
|
|
|
- // (they'll find no entries and move on). v2.x can drop this
|
|
|
|
|
- // block entirely with a snapshot format bump.
|
|
|
|
|
- uint64_t historyEntryCount = 0;
|
|
|
|
|
- for (int i = 0; i < 8; ++i) {
|
|
|
|
|
- result.push_back(static_cast<uint8_t>((historyEntryCount >> (i * 8)) & 0xFF));
|
|
|
|
|
- }
|
|
|
|
|
-
|
|
|
|
|
- // Write vector data (v3)
|
|
|
|
|
|
|
+ // Vector data (v3)
|
|
|
const auto* vectors = store.getCollectionVectors(name);
|
|
const auto* vectors = store.getCollectionVectors(name);
|
|
|
- uint64_t vecCount = (vectors != nullptr) ? static_cast<uint64_t>(vectors->size()) : 0;
|
|
|
|
|
- for (int i = 0; i < 8; ++i) {
|
|
|
|
|
- result.push_back(static_cast<uint8_t>((vecCount >> (i * 8)) & 0xFF));
|
|
|
|
|
- }
|
|
|
|
|
-
|
|
|
|
|
|
|
+ out.u64(vectors != nullptr ? static_cast<uint64_t>(vectors->size()) : 0);
|
|
|
if (vectors != nullptr) {
|
|
if (vectors != nullptr) {
|
|
|
for (const auto& [docId, vec] : *vectors) {
|
|
for (const auto& [docId, vec] : *vectors) {
|
|
|
- // Write doc ID
|
|
|
|
|
- uint16_t docIdLen = static_cast<uint16_t>(docId.size());
|
|
|
|
|
- result.push_back(static_cast<uint8_t>(docIdLen & 0xFF));
|
|
|
|
|
- result.push_back(static_cast<uint8_t>((docIdLen >> 8) & 0xFF));
|
|
|
|
|
- result.insert(result.end(), docId.begin(), docId.end());
|
|
|
|
|
-
|
|
|
|
|
- // Write vector dimension
|
|
|
|
|
- uint32_t dim = static_cast<uint32_t>(vec.size());
|
|
|
|
|
- for (int i = 0; i < 4; ++i) {
|
|
|
|
|
- result.push_back(static_cast<uint8_t>((dim >> (i * 8)) & 0xFF));
|
|
|
|
|
- }
|
|
|
|
|
-
|
|
|
|
|
- // Write raw float data
|
|
|
|
|
- const uint8_t* floatBytes = reinterpret_cast<const uint8_t*>(vec.data());
|
|
|
|
|
- result.insert(result.end(), floatBytes, floatBytes + dim * sizeof(float));
|
|
|
|
|
|
|
+ out.u16(static_cast<uint16_t>(docId.size()));
|
|
|
|
|
+ out.bytes(docId);
|
|
|
|
|
+ out.u32(static_cast<uint32_t>(vec.size()));
|
|
|
|
|
+ out.bytes(vec.data(), vec.size() * sizeof(float));
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
-
|
|
|
|
|
- return result;
|
|
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
namespace {
|
|
namespace {
|