Przeglądaj źródła

fix: the snapshot writer streams to disk; a killed snapshot is reported at the next boot

A snapshot held the working set plus about three more copies (each
collection's documents, the serialised body, its compressed copy, and the
verify read-back). A store that outgrew its host was OOM-killed at every
snapshot, the WAL was never truncated, and recovery grew until boot no longer
fit. The writer now stages one 16 MB chunk at a time, documents are copied in
batches, verify streams, load frees the compressed body early. Format v4 is
unchanged.

A process killed by the kernel cannot log it, so a marker exists while a
snapshot runs; the next boot logs ERROR while it remains, plus the WAL size,
the newest snapshot's age, a WARN at 2x the snapshot trigger, and one line per
boot step after the backfill.
fszontagh 1 miesiąc temu
rodzic
commit
0f727f1693

+ 14 - 0
CHANGELOG.md

@@ -11,6 +11,20 @@ Per-release detail (design, measurements, revert evidence) stays in `CLAUDE.md`;
 consumer-facing usage is in `docs/integration-guide.md`.
 
 ## Unreleased
+### Fixed
+- **[server]** ⚠ A snapshot held the whole store in memory twice more: the
+  serialised body, a compressed copy beside it, and a copy of each collection's
+  documents. A store that outgrew its host was OOM-killed at every snapshot,
+  the WAL was never truncated, and recovery grew with it until the server could
+  no longer boot. The writer now streams to disk a chunk at a time; a snapshot
+  adds a few tens of MB to memory whatever the store's size. The file format is
+  unchanged (older servers read the new files and the reverse).
+### Added
+- **[server]** A snapshot that never finished (the process was killed while
+  writing it) is reported at the next boot as an ERROR, with the WAL size and
+  the age of the newest snapshot; a WARN whenever the WAL reaches twice the
+  size that triggers a snapshot; and an INFO line at recovery naming the WAL
+  size and the newest snapshot. Boot logs each step after the backfill.
 
 ## 2.20.0 - 2026-10-16 (out of cycle: security)
 ### Fixed

Plik diff jest za duży
+ 0 - 0
CLAUDE.md


+ 15 - 0
docs/ROADMAP.md

@@ -130,6 +130,8 @@ detail and the failure modes.
   `index-values`
 - REGEX filters on RE2: linear time, UTF-8 character classes, `(?i)`, an
   invalid pattern refused with `invalid_pattern` (2.20.0)
+- Snapshots stream to disk: the writer's memory peak is a chunk, not the
+  store; a snapshot killed mid-write is reported at the next boot (Unreleased)
 
 ---
 
@@ -361,6 +363,19 @@ joins; see 5c), which does not fit in 10 s. Run the container with
 **Any future `docker run` for this service must carry `--stop-timeout`**, and any
 `docker stop` in a script wants `-t` to match. The deb/systemd path is unaffected.
 
+### 5e. Boot needs the whole dataset in memory (found 2026-10-19)
+
+A production instance on a 2 GB host could not boot: recovery loads the
+snapshot and replays the WAL into MemoryStore, which holds every document,
+and the boot was killed with ~1.5 GB anonymous memory before READY (measured
+with swap: ~1.7 GB at least, during init). The streaming snapshot writer
+(Unreleased) removes the condition that grew the WAL without bound, but a large
+WAL after an unrelated crash, or a store that simply outgrows the host, still
+cannot boot. Cheaper steps first: stream the snapshot LOAD as the writer now
+streams the write (it still holds the decompressed body during
+deserialization); then measure what the WAL replay retains. The real fix is
+item 4 (MemoryStore stops being a full copy of LMDB).
+
 ### 6. Smaller known gaps
 
 - Policy management has no dedicated RPCs; `_policies` is edited through the

+ 6 - 0
service/src/database_service.cpp

@@ -271,12 +271,17 @@ bool DatabaseService::initialize() {
         // data-location problem an operator repairs offline with
         // `smartbotic-db-cli reconcile-subdbs`, not a reason to refuse
         // service on the other 99% of the dataset.
+        // 2.21.0 - each remaining boot step logs its start, so a boot that
+        // dies here (a production crash loop on 2026-10-19 died about 3 s
+        // after the backfill line, with nothing logged) shows which step.
+        spdlog::info("Boot: sub-db placement audit");
         auditSubdbPlacement();
 
         // v2.6.0 — stamp `project: "default"` onto file records written before
         // files were namespaced. Idempotent, and advisory: a file-metadata
         // stamp is not a reason to refuse service, so failures warn only.
         if (files_) {
+            spdlog::info("Boot: file records");
             try {
                 const uint32_t stamped = files_->stampMissingProjects();
                 if (stamped > 0) {
@@ -304,6 +309,7 @@ bool DatabaseService::initialize() {
         // is ahead, and that fallback must stay.
         // v2.17.0 - encrypt what must be encrypted, and remove the plaintext
         // copies, before anything can read or replicate them.
+        spdlog::info("Boot: encryption at rest");
         migrateEncryptionAtRest();
 
         store_->markMirrorDriftBaseline();

+ 36 - 0
service/src/memory_store.cpp

@@ -3297,6 +3297,42 @@ std::vector<Document> MemoryStore::getAllDocuments(const std::string& collection
     return docs;
 }
 
+std::vector<std::string> MemoryStore::getDocumentIds(const std::string& collection) const {
+    const CollectionData* coll = getCollection(collection);
+    if (!coll) return {};
+    std::shared_lock<std::shared_mutex> lock(coll->mutex);
+    std::vector<std::string> ids;
+    ids.reserve(coll->documents.size());
+    for (const auto& [id, doc] : coll->documents) ids.push_back(id);
+    return ids;
+}
+
+std::vector<std::optional<Document>> MemoryStore::copyDocuments(
+    const std::string& collection, const std::vector<std::string>& ids,
+    size_t from, size_t count) const {
+    std::vector<std::optional<Document>> out;
+    const size_t end = std::min(ids.size(), from + count);
+    if (from >= end) return out;
+    out.resize(end - from);
+    std::vector<size_t> missing;
+    if (const CollectionData* coll = getCollection(collection)) {
+        std::shared_lock<std::shared_mutex> lock(coll->mutex);
+        for (size_t i = from; i < end; ++i) {
+            auto it = coll->documents.find(ids[i]);
+            if (it != coll->documents.end()) out[i - from] = it->second;
+            else missing.push_back(i);
+        }
+    } else {
+        for (size_t i = from; i < end; ++i) missing.push_back(i);
+    }
+    // Evicted after the ids were listed: read the evicted copy, outside the
+    // collection lock (peekEvictedDocument takes its own locks). A document
+    // must not drop out of a snapshot because eviction moved it meanwhile -
+    // the WAL entries holding it are truncated once the snapshot completes.
+    for (size_t i : missing) out[i - from] = peekEvictedDocument(collection, ids[i]);
+    return out;
+}
+
 std::vector<std::pair<std::string, CollectionOptions>> MemoryStore::getAllCollectionsWithOptions() const {
     std::shared_lock<std::shared_mutex> lock(globalMutex_);
 

+ 17 - 0
service/src/memory_store.hpp

@@ -1167,6 +1167,23 @@ public:
      */
     [[nodiscard]] std::vector<Document> getAllDocuments(const std::string& collection) const;
 
+    /**
+     * 2.21.0 - the ids of the documents resident in a collection (not the
+     * evicted ones; see getEvictedDocumentIds). With copyDocuments below this
+     * lets the snapshot writer copy a collection a batch at a time instead of
+     * holding a copy of all of it (getAllDocuments) next to the original.
+     */
+    [[nodiscard]] std::vector<std::string> getDocumentIds(const std::string& collection) const;
+
+    /**
+     * 2.21.0 - copies of the named documents, one entry per id, in order:
+     * the resident copy, else the evicted copy (peekEvictedDocument), else
+     * nullopt (deleted since the ids were listed). One shared lock per call.
+     */
+    [[nodiscard]] std::vector<std::optional<Document>> copyDocuments(
+        const std::string& collection, const std::vector<std::string>& ids,
+        size_t from, size_t count) const;
+
     /**
      * Get all collections with their options (for snapshotting).
      */

+ 55 - 1
service/src/persistence/persistence_manager.cpp

@@ -180,6 +180,7 @@ RecoveryOutcome PersistenceManager::recover(MemoryStore& store) {
 
     auto snapshots = snapshotMgr_->listSnapshots();
     outcome.snapshotsAvailable = snapshots.size();
+    reportSnapshotHealthAtBoot(snapshots);
 
     // ForceEmpty — ignore everything, start clean (files preserved on disk)
     if (config_.recoveryMode == RecoveryMode::ForceEmpty) {
@@ -697,6 +698,56 @@ void PersistenceManager::snapshotLoop() {
     }
 }
 
+namespace {
+std::string megabytes(uint64_t bytes) {
+    return std::to_string((bytes + (1 << 19)) >> 20) + " MB";
+}
+}  // namespace
+
+// 2.21.0 - make a snapshot that is not completing visible. On a production
+// instance the hourly snapshot was OOM-killed for three days: systemd restarted
+// the service each time, the journal recorded only status=9/KILL, the WAL was
+// never truncated, and recovery grew with it until boot itself no longer fit.
+// A killed process cannot log its own death, so the next boot reports it.
+void PersistenceManager::reportSnapshotHealthAtBoot(
+    const std::vector<std::filesystem::path>& snapshots) const {
+    const uint64_t walBytes = walSizeBytes();
+    std::string lastGood = "none";
+    if (!snapshots.empty()) {
+        std::error_code ec;
+        const auto mtime = std::filesystem::last_write_time(snapshots.front(), ec);
+        if (!ec) {
+            const auto age = std::chrono::duration_cast<std::chrono::minutes>(
+                std::filesystem::file_time_type::clock::now() - mtime).count();
+            lastGood = snapshots.front().filename().string() + ", " + std::to_string(age) + " min old";
+        }
+    }
+    spdlog::info("Recovery input: WAL {}, newest snapshot {}", megabytes(walBytes), lastGood);
+
+    if (auto interrupted = snapshotMgr_->interruptedSnapshot()) {
+        const auto age = interrupted->startedMs == 0
+            ? std::string("unknown")
+            : std::to_string((static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(
+                  std::chrono::system_clock::now().time_since_epoch()).count()) - interrupted->startedMs) / 60000) + " min ago";
+        spdlog::error("The previous snapshot did NOT complete: one started {} (WAL sequence {}) and "
+                      "the process died before it finished - most likely killed (out of memory: "
+                      "check the kernel log for oom-kill). Until a snapshot completes the WAL is not "
+                      "truncated and every recovery replays all of it (WAL now {}, newest snapshot {}).",
+                      age, interrupted->walSequence, megabytes(walBytes), lastGood);
+    }
+    warnIfWalOutgrewSnapshots(walBytes);
+}
+
+void PersistenceManager::warnIfWalOutgrewSnapshots(uint64_t walBytes) const {
+    const uint64_t trigger = config_.maxWalSizeMb * 1024 * 1024;
+    if (trigger == 0 || walBytes < 2 * trigger) return;
+    spdlog::warn("The WAL is {} - {}x the {} that triggers a snapshot - so snapshots have not been "
+                 "completing. Recovery time and memory grow with the WAL; find out why (an ERROR "
+                 "'Failed to create snapshot', or a boot reporting 'The previous snapshot did NOT "
+                 "complete').",
+                 megabytes(walBytes), walBytes / trigger, megabytes(trigger));
+}
+
 void PersistenceManager::createSnapshot() {
     const MemoryStore* store = nullptr;
     {
@@ -709,6 +760,8 @@ void PersistenceManager::createSnapshot() {
         return;
     }
 
+    warnIfWalOutgrewSnapshots(walSizeBytes());
+
     try {
         uint64_t walSeq = wal_->currentSequence();
         auto snapshotPath = snapshotMgr_->createSnapshot(*store, walSeq);
@@ -730,7 +783,8 @@ void PersistenceManager::createSnapshot() {
         }
 
     } catch (const std::exception& e) {
-        spdlog::error("Failed to create snapshot: {}", e.what());
+        spdlog::error("Failed to create snapshot: {} (the WAL is not truncated until one "
+                      "completes; WAL now {})", e.what(), megabytes(walSizeBytes()));
     }
 }
 

+ 2 - 0
service/src/persistence/persistence_manager.hpp

@@ -357,6 +357,8 @@ private:
      * Create a snapshot (called by snapshotLoop or forceSnapshot).
      */
     void createSnapshot();
+    void reportSnapshotHealthAtBoot(const std::vector<std::filesystem::path>& snapshots) const;
+    void warnIfWalOutgrewSnapshots(uint64_t walBytes) const;
 
     /**
      * Check if snapshot is needed based on WAL size or time.

+ 244 - 220
service/src/persistence/snapshot.cpp

@@ -110,139 +110,204 @@ SnapshotManager::SnapshotManager(Config config)
     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
-    } 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 tmpPath = snapshotPath;
     tmpPath += ".tmp";
 
-    // Helper to remove tmp on error paths
     auto cleanupTmp = [&tmpPath]() {
         std::error_code ec;
         std::filesystem::remove(tmpPath, ec);
     };
 
-    // Write to temp file
-    {
+    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());
         }
 
-        // 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));
-        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));
-        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();
-        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);
         if (fd < 0) {
@@ -259,7 +324,7 @@ std::filesystem::path SnapshotManager::createSnapshot(const MemoryStore& store,
         ::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.
     {
         std::error_code ec;
@@ -277,14 +342,14 @@ std::filesystem::path SnapshotManager::createSnapshot(const MemoryStore& store,
             ::fsync(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)
     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
+            // 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());
@@ -292,18 +357,14 @@ std::filesystem::path SnapshotManager::createSnapshot(const MemoryStore& store,
         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)
     if (verified || !config_.cleanupOnlyIfVerified) {
         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();
 
     return snapshotPath;
@@ -415,6 +476,8 @@ uint64_t SnapshotManager::loadSnapshot(const std::filesystem::path& path, Memory
     } else {
         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
     store.clear();
@@ -545,17 +608,26 @@ bool SnapshotManager::verifySnapshot(const std::filesystem::path& path) const {
             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;
         file.read(reinterpret_cast<char*>(&storedBodyCrc), sizeof(storedBodyCrc));
-        uint32_t calculatedBodyCrc = crc32::calculate(bodyData.data(), bodyData.size());
+        if (!file) {
+            return false;
+        }
 
         return storedBodyCrc == calculatedBodyCrc;
     } catch (...) {
@@ -629,135 +701,87 @@ std::vector<uint8_t> SnapshotManager::decompress(const std::vector<uint8_t>& dat
 #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;
     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();
     collCount = static_cast<uint32_t>(collections.size());
 
     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) {
-            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) {
             spdlog::warn(
                 "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.",
                 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);
-        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) {
             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 {

+ 28 - 4
service/src/persistence/snapshot.hpp

@@ -95,6 +95,19 @@ public:
         // NEW in v1.6.1: durability
         bool validateAfterWrite = true;
         bool cleanupOnlyIfVerified = true;
+
+        // 2.21.0: uncompressed bytes per LZ4 chunk. The writer streams one
+        // chunk at a time to disk, so this (plus its compressed copy) is the
+        // writer's buffer, not the store's size. Tests lower it.
+        size_t chunkBytes = 16 * 1024 * 1024;
+    };
+
+    /// 2.21.0 - a snapshot that started and never finished (the process was
+    /// killed while writing it: OOM, SIGKILL, power). Read at boot from the
+    /// marker createSnapshot leaves while it runs.
+    struct InterruptedSnapshot {
+        uint64_t startedMs = 0;      // wall clock, ms since epoch
+        uint64_t walSequence = 0;    // the WAL sequence it was taken at
     };
 
     explicit SnapshotManager(Config config);
@@ -165,6 +178,16 @@ public:
     /// v2.17.0 - delete every snapshot except `keep` (the at-rest seal).
     size_t removeAllExcept(const std::filesystem::path& keep);
 
+    /// 2.21.0 - the snapshot that was in progress when the process last died,
+    /// if any. A process killed by the kernel cannot log its own death, so
+    /// this is how the NEXT boot learns that snapshots are not completing
+    /// (the marker stays until a snapshot completes, so every boot of a crash
+    /// loop reports it).
+    [[nodiscard]] std::optional<InterruptedSnapshot> interruptedSnapshot() const;
+
+    /// Path of the in-progress marker (for tests and the CLI).
+    [[nodiscard]] std::filesystem::path inProgressMarkerPath() const;
+
 private:
     /**
      * Generate a filename for a new snapshot.
@@ -183,11 +206,12 @@ private:
                                                    uint64_t uncompressedSize) const;
 
     /**
-     * Serialize store data to bytes.
+     * Serialize store data into `sink`, a piece at a time (2.21.0: before,
+     * this returned the whole body as one buffer).
      */
-    [[nodiscard]] std::vector<uint8_t> serializeStore(const MemoryStore& store,
-                                                       uint64_t& docCount,
-                                                       uint32_t& collCount) const;
+    template <typename Sink>
+    void serializeStore(const MemoryStore& store, Sink& sink,
+                        uint64_t& docCount, uint32_t& collCount) const;
 
     /**
      * Deserialize bytes into store.

+ 6 - 2
service/src/persistence/wal.cpp

@@ -53,8 +53,8 @@ static const uint32_t table[256] = {
     0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
 };
 
-uint32_t calculate(const void* data, size_t length) {
-    uint32_t crc = 0xFFFFFFFF;
+uint32_t extend(uint32_t crc, const void* data, size_t length) {
+    crc ^= 0xFFFFFFFF;
     const uint8_t* bytes = static_cast<const uint8_t*>(data);
     for (size_t i = 0; i < length; ++i) {
         crc = table[(crc ^ bytes[i]) & 0xFF] ^ (crc >> 8);
@@ -62,6 +62,10 @@ uint32_t calculate(const void* data, size_t length) {
     return crc ^ 0xFFFFFFFF;
 }
 
+uint32_t calculate(const void* data, size_t length) {
+    return extend(0, data, length);
+}
+
 uint32_t calculate(const std::string& str) {
     return calculate(str.data(), str.size());
 }

+ 4 - 0
service/src/persistence/wal.hpp

@@ -239,6 +239,10 @@ private:
 namespace crc32 {
     uint32_t calculate(const void* data, size_t length);
     uint32_t calculate(const std::string& str);
+    // Continue a CRC over more bytes: extend(calculate(a), b) == calculate(a + b),
+    // and extend(0, x) == calculate(x). Lets a writer checksum a body it never
+    // holds whole (the 2.21.0 streaming snapshot writer).
+    uint32_t extend(uint32_t crc, const void* data, size_t length);
 }
 
 } // namespace smartbotic::database

+ 147 - 0
tests/test_snapshot_durability.cpp

@@ -627,6 +627,150 @@ void test_evict_stub_carries_real_wal_sequence() {
               << "their last wal.append() return value)\n";
 }
 
+// ──────────────────────────────────────────────────────────
+// 2.21.0: the writer streams. A production store was OOM-killed at every
+// snapshot because the writer held the whole serialised body, a compressed
+// copy beside it, and a copy of each collection's documents.
+// ──────────────────────────────────────────────────────────
+namespace {
+long procStatusKb(const char* key) {
+    std::ifstream in("/proc/self/status");
+    std::string line;
+    const std::string k = std::string(key) + ":";
+    while (std::getline(in, line)) {
+        if (line.rfind(k, 0) == 0) return std::stol(line.substr(k.size()));
+    }
+    return -1;
+}
+}  // namespace
+
+void test_streaming_snapshot_memory_is_bounded() {
+    auto dir = makeSnapshotDir("streaming-mem");
+    SnapshotManager::Config scfg;
+    scfg.snapshotDir = dir;
+    SnapshotManager mgr(scfg);
+
+    MemoryStore::Config mcfg = defaultStoreConfig();
+    mcfg.maxMemoryBytes = 8ULL * 1024 * 1024 * 1024;  // no eviction in this test
+    MemoryStore store(mcfg);
+    store.start();
+    store.createCollection("big", CollectionOptions{});
+    // ~160 MB of JSON in ONE collection: the old writer's peak grew by more
+    // than that (body + compressed body + a copy of the collection). Random
+    // text so LZ4 cannot shrink the compressed copy to nothing.
+    uint64_t rng = 88172645463325252ULL;
+    const int kDocs = 4000;
+    for (int i = 0; i < kDocs; ++i) {
+        std::string payload(40000, ' ');
+        for (auto& c : payload) {
+            rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17;
+            c = static_cast<char>('a' + (rng % 26));
+        }
+        Document d;
+        d.id = "d" + std::to_string(i);
+        d.set_data(nlohmann::json{{"payload", payload}, {"i", i}});
+        store.insert("big", d);
+    }
+
+    // Reset the high-water mark (Linux >= 4.0), then measure what the
+    // snapshot itself adds above the current RSS.
+    { std::ofstream("/proc/self/clear_refs") << "5"; }
+    const long rssBefore = procStatusKb("VmRSS");
+    const long hwmReset = procStatusKb("VmHWM");
+    auto path = mgr.createSnapshot(store, 7);
+    const long hwmAfter = procStatusKb("VmHWM");
+    const long growthMb = (hwmAfter - rssBefore) / 1024;
+    std::cout << "  snapshot " << (fs::file_size(path) >> 20) << " MB on disk; peak RSS grew "
+              << growthMb << " MB over " << (rssBefore >> 10) << " MB (hwm reset to "
+              << (hwmReset >> 10) << " MB)\n";
+    if (hwmReset < 0 || hwmReset > rssBefore + 1024) {
+        std::cout << "  (clear_refs unsupported here: memory bound not checked)\n";
+    } else if (growthMb > 64) {
+        std::cerr << "FAIL: snapshot peak grew " << growthMb << " MB, expected <= 64 MB\n";
+        std::exit(1);
+    }
+    store.stop();
+
+    MemoryStore store2(mcfg);
+    store2.start();
+    assert(mgr.loadSnapshot(path, store2) == 7);
+    for (int i : {0, 1999, kDocs - 1}) {
+        auto doc = store2.get("big", "d" + std::to_string(i));
+        assert(doc.has_value());
+        assert(doc->data()["i"] == i);
+        assert(doc->data()["payload"].get<std::string>().size() == 40000);
+    }
+    assert(store2.getDocumentIds("big").size() == static_cast<size_t>(kDocs));
+    store2.stop();
+    fs::remove_all(dir);
+    std::cout << "PASS: streaming snapshot memory is bounded\n";
+}
+
+// Many chunks, documents larger than a chunk, compressed and not.
+void test_streaming_snapshot_small_chunks_round_trip() {
+    for (bool compress : {true, false}) {
+        auto dir = makeSnapshotDir(compress ? "chunks-lz4" : "chunks-raw");
+        SnapshotManager::Config scfg;
+        scfg.snapshotDir = dir;
+        scfg.chunkBytes = 1000;
+        scfg.compressionEnabled = compress;
+        SnapshotManager mgr(scfg);
+
+        MemoryStore store(defaultStoreConfig());
+        store.start();
+        store.createCollection("a", CollectionOptions{});
+        store.createCollection("b", CollectionOptions{});
+        for (int i = 0; i < 300; ++i) {
+            Document d;
+            d.id = "x" + std::to_string(i);
+            d.set_data(nlohmann::json{{"s", std::string(static_cast<size_t>(i * 17), 'q')}, {"i", i}});
+            store.insert(i % 2 ? "a" : "b", d);
+        }
+        auto path = mgr.createSnapshot(store, 5);
+        assert(mgr.verifySnapshot(path));
+        auto info = mgr.getSnapshotInfo(path);
+        assert(info && info->documentCount == 300 && info->collectionCount == 2);
+        assert(info->compressionType == (compress ? 1u : 0u));
+        store.stop();
+
+        MemoryStore store2(defaultStoreConfig());
+        store2.start();
+        assert(mgr.loadSnapshot(path, store2) == 5);
+        for (int i = 0; i < 300; ++i) {
+            auto doc = store2.get(i % 2 ? "a" : "b", "x" + std::to_string(i));
+            assert(doc.has_value());
+            assert(doc->data()["s"].get<std::string>().size() == static_cast<size_t>(i * 17));
+        }
+        store2.stop();
+        fs::remove_all(dir);
+    }
+    std::cout << "PASS: streaming snapshot round-trips over many small chunks\n";
+}
+
+// A snapshot that never finished leaves a marker the next boot reports; one
+// that finishes (or fails with an exception, which is logged) removes it.
+void test_interrupted_snapshot_marker() {
+    auto dir = makeSnapshotDir("marker");
+    SnapshotManager::Config scfg;
+    scfg.snapshotDir = dir;
+    SnapshotManager mgr(scfg);
+    assert(!mgr.interruptedSnapshot());
+
+    { std::ofstream(mgr.inProgressMarkerPath()) << "1760000000000 406829\n"; }
+    auto r = mgr.interruptedSnapshot();
+    assert(r && r->startedMs == 1760000000000ULL && r->walSequence == 406829);
+
+    MemoryStore store(defaultStoreConfig());
+    store.start();
+    store.createCollection("docs", CollectionOptions{});
+    store.insert("docs", makeDoc("d1"));
+    mgr.createSnapshot(store, 3);
+    assert(!mgr.interruptedSnapshot());
+    store.stop();
+    fs::remove_all(dir);
+    std::cout << "PASS: an interrupted snapshot is reported until one completes\n";
+}
+
 int main() {
     test_atomic_write_leaves_no_tmp();
     test_snapshot_round_trip();
@@ -638,6 +782,9 @@ int main() {
     test_wal_sequence_floor_anchors_after_truncate();
     test_snapshot_includes_evicted_documents();
     test_evict_stub_carries_real_wal_sequence();
+    test_streaming_snapshot_memory_is_bounded();
+    test_streaming_snapshot_small_chunks_round_trip();
+    test_interrupted_snapshot_marker();
     std::cout << "\nAll snapshot durability tests PASSED!\n";
     return 0;
 }

Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików