Repository navigation
feat(sharding): Raft Snapshot Compaction and Log Truncation (v1.6.0) - #4147
Merged
makr-code merged 4 commits intoMar 13, 2026
Merged
Conversation
… (v1.6.0) - Add RaftSnapshotManager to raft_log.h/raft_log.cpp with configurable 512 MB compaction threshold, ZSTD-level-3 compression, SHA-256 integrity checks, and chunked transfer API for lagging replicas - Add compactUpTo()/setSnapshotMeta()/estimatedSizeBytes() to RaftLog with snapshot-boundary fix in hasEntry() - Add setSnapshotMeta()/getSnapshotIndex()/getSnapshotTerm() to RaftState - Add SnapshotChunk/SnapshotTransferResult structs plus sendSnapshot() and static verifyChunkChecksum() to WALShipper for chunked snapshot transfer with per-chunk SHA-256 checksums - Add PaxosSnapshot::compress()/decompress() using utils/zstd_codec.cpp; update PaxosSnapshotManager to write ZSTD-compressed binary format - Add PaxosWAL::compact() for WAL log truncation after Paxos snapshots - Replace stub tests in test_raft_log.cpp and test_raft_wal_integration.cpp with real unit tests covering compaction, chunks, and snapshot meta Co-authored-by: makr-code <[email protected]>
…eeded, add namespace comment Co-authored-by: makr-code <[email protected]>
Copilot
AI
changed the title
[WIP] Implement raft snapshot compaction and log truncation
feat(sharding): Raft Snapshot Compaction and Log Truncation (v1.6.0)
Mar 12, 2026
makr-code
marked this pull request as ready for review
March 13, 2026 05:15
Contributor
There was a problem hiding this comment.
Pull request overview
Implements snapshot-based log/WAL compaction for sharding consensus paths to prevent unbounded log growth, adding a Raft snapshot manager (ZSTD-compressed, chunk-addressable) and a chunked snapshot transfer API in the WAL shipper, plus Paxos WAL compaction/compressed snapshots for parity.
Changes:
- Add
RaftSnapshotManagerwith on-disk snapshot persistence, retention cleanup, and chunked snapshot read API; extendRaftLogwith compaction + size estimation + snapshot-boundaryhasEntry. - Add snapshot chunk transfer types/API to
WALShipperwith per-chunk SHA-256 verification and retries. - Add Paxos snapshot compression (
PAXZformat w/ JSON fallback) and WAL compaction viaWALManager::truncate, plus new/updated unit tests.
Reviewed changes
Copilot reviewed 12 out of 12 changed files in this pull request and generated 11 comments.
Show a summary per file
| File | Description |
|---|---|
include/sharding/raft_log.h |
Declares Raft log compaction/size estimation APIs and the new RaftSnapshotManager + snapshot structs. |
src/sharding/raft_log.cpp |
Implements log compaction/size estimation and snapshot persistence/load/chunking logic. |
include/sharding/raft_state.h |
Adds snapshot index/term state to RaftState public API. |
src/sharding/raft_state.cpp |
Implements snapshot metadata setters/getters and propagates meta to embedded RaftLog. |
include/sharding/wal_shipper.h |
Introduces SnapshotChunk + SnapshotTransferResult and snapshot transfer/verification APIs. |
src/sharding/wal_shipper.cpp |
Implements chunk checksum verification and chunked snapshot send with retry/backoff. |
include/sharding/paxos_snapshot.h |
Adds ZSTD compression/decompression API and compression-level configuration for the snapshot manager. |
src/sharding/paxos_snapshot.cpp |
Implements PAXZ compressed snapshot format with legacy JSON fallback on load. |
include/sharding/paxos_wal.h |
Adds compact() API for Paxos WAL. |
src/sharding/paxos_wal.cpp |
Implements Paxos WAL compaction by writing a SNAPSHOT marker + truncating WAL segments. |
tests/test_raft_log.cpp |
Replaces stub with unit tests for compaction, size estimation, snapshot create/load, chunking, retention cleanup. |
tests/test_raft_wal_integration.cpp |
Adds integration-ish tests for chunk checksum verification and RaftState::setSnapshotMeta propagation. |
You can also share your feedback on Copilot code review. Take the survey.
Comment on lines
+588
to
+602
| // Encode binary data as hex to stay JSON-compatible | ||
| std::ostringstream data_hex; | ||
| for (uint8_t b : chunk.data) { | ||
| data_hex << std::hex << std::setw(2) << std::setfill('0') | ||
| << static_cast<int>(b); | ||
| } | ||
| nlohmann::json body = { | ||
| {"snapshot_index", chunk.snapshot_index}, | ||
| {"snapshot_term", chunk.snapshot_term}, | ||
| {"chunk_index", chunk.chunk_index}, | ||
| {"total_chunks", chunk.total_chunks}, | ||
| {"last_chunk", chunk.last_chunk}, | ||
| {"checksum", chunk.checksum}, | ||
| {"data_hex", data_hex.str()} | ||
| }; |
| #include <optional> | ||
| #include <string> | ||
| #include <vector> | ||
| #include <functional> |
Comment on lines
+298
to
+301
| // 5. Compact the in-memory Raft log | ||
| log.compactUpTo(snapshot_index, snapshot_term); | ||
|
|
||
| // 6. Remove old snapshots beyond retention limit |
Comment on lines
+244
to
+245
| const std::string checksum = computeChecksum(state_data.data(), state_data.size()); | ||
|
|
Comment on lines
+327
to
+377
| auto read64 = [&]() -> uint64_t { | ||
| uint64_t v = 0; | ||
| file.read(reinterpret_cast<char*>(&v), sizeof(v)); | ||
| return v; | ||
| }; | ||
| auto read32 = [&]() -> uint32_t { | ||
| uint32_t v = 0; | ||
| file.read(reinterpret_cast<char*>(&v), sizeof(v)); | ||
| return v; | ||
| }; | ||
|
|
||
| RaftSnapshot snap; | ||
| snap.snapshot_index = read64(); | ||
| snap.snapshot_term = read64(); | ||
| snap.uncompressed_size = read64(); | ||
| snap.timestamp = read64(); | ||
|
|
||
| const uint32_t checksum_len = read32(); | ||
| snap.checksum.resize(checksum_len); | ||
| file.read(snap.checksum.data(), static_cast<std::streamsize>(checksum_len)); | ||
|
|
||
| // Read remaining bytes as compressed data | ||
| const std::streampos data_start = file.tellg(); | ||
| file.seekg(0, std::ios::end); | ||
| const std::streampos data_end = file.tellg(); | ||
| const size_t data_size = static_cast<size_t>(data_end - data_start); | ||
| file.seekg(data_start); | ||
|
|
||
| snap.data.resize(data_size); | ||
| if (data_size > 0) { | ||
| file.read(reinterpret_cast<char*>(snap.data.data()), | ||
| static_cast<std::streamsize>(data_size)); | ||
| } | ||
| file.close(); | ||
|
|
||
| // Decompress to verify checksum | ||
| if (!snap.data.empty()) { | ||
| auto decompressed = themis::utils::zstd_decompress(snap.data); | ||
| if (decompressed.empty() && snap.uncompressed_size > 0) { | ||
| spdlog::error("RaftSnapshotManager: decompression failed for snapshot {}", | ||
| snapshot_index); | ||
| return std::nullopt; | ||
| } | ||
| const std::string actual_checksum = | ||
| computeChecksum(decompressed.data(), decompressed.size()); | ||
| if (actual_checksum != snap.checksum) { | ||
| spdlog::error("RaftSnapshotManager: checksum mismatch for snapshot {} " | ||
| "(expected={} actual={})", | ||
| snapshot_index, snap.checksum, actual_checksum); | ||
| return std::nullopt; | ||
| } |
Comment on lines
+263
to
+285
| bool PaxosWAL::compact(const LSN& up_to_lsn, const std::string& node_id) { | ||
| std::lock_guard<std::mutex> lock(mutex_); | ||
|
|
||
| if (!wal_manager_) { | ||
| spdlog::error("PaxosWAL::compact: WAL not initialized"); | ||
| return false; | ||
| } | ||
|
|
||
| try { | ||
| // 1. Write a SNAPSHOT marker entry so replay code can detect the | ||
| // compaction boundary. | ||
| nlohmann::json marker_data = { | ||
| {"compacted_up_to_lsn", up_to_lsn.toString()}, | ||
| {"compaction_ts", std::chrono::duration_cast<std::chrono::milliseconds>( | ||
| std::chrono::system_clock::now().time_since_epoch()).count()} | ||
| }; | ||
| PaxosWALEntry marker = createEntry( | ||
| PaxosWALEntryType::SNAPSHOT, 0, 0, node_id, marker_data); | ||
| wal_manager_->append(marker.toWALEntry()); | ||
|
|
||
| // 2. Delegate to WALManager for the actual segment truncation | ||
| wal_manager_->truncate(up_to_lsn); | ||
|
|
Comment on lines
+93
to
+96
| void SetUp() override { | ||
| snapshot_dir_ = std::filesystem::temp_directory_path() / | ||
| ("test_raft_snap_" + std::to_string(::getpid())); | ||
| std::filesystem::create_directories(snapshot_dir_); |
Comment on lines
+522
to
+537
| // Compute SHA-256 of a buffer and return a lowercase hex string. | ||
| static std::string chunkSha256(const uint8_t* data, size_t size) { | ||
| unsigned char hash[SHA256_DIGEST_LENGTH]; | ||
| SHA256(data, size, hash); | ||
| std::ostringstream oss; | ||
| for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i) { | ||
| oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(hash[i]); | ||
| } | ||
| return oss.str(); | ||
| } | ||
|
|
||
| /* static */ bool WALShipper::verifyChunkChecksum(const SnapshotChunk& chunk) { | ||
| const std::string computed = | ||
| chunkSha256(chunk.data.data(), chunk.data.size()); | ||
| return computed == chunk.checksum; | ||
| } |
Comment on lines
+150
to
+164
| void RaftLog::compactUpTo(uint64_t snapshot_index, uint64_t snapshot_term) { | ||
| std::lock_guard<std::mutex> lock(mutex_); | ||
| // Erase all entries at or below snapshot_index | ||
| auto it = log_.upper_bound(snapshot_index); | ||
| log_.erase(log_.begin(), it); | ||
|
|
||
| // Record snapshot anchor so hasEntry() and prevLogIndex checks still work | ||
| snapshot_index_ = snapshot_index; | ||
| snapshot_term_ = snapshot_term; | ||
|
|
||
| // Commit index cannot go below the snapshot | ||
| if (commit_index_ < snapshot_index) { | ||
| commit_index_ = snapshot_index; | ||
| } | ||
| } |
Comment on lines
+422
to
+434
| size_t RaftSnapshotManager::getChunkCount(uint64_t snapshot_index) const { | ||
| std::lock_guard<std::mutex> lock(mutex_); | ||
|
|
||
| std::string path = snapshotPath(snapshot_index); | ||
| if (!std::filesystem::exists(path)) { | ||
| return 0; | ||
| } | ||
| const size_t file_size = std::filesystem::file_size(path); | ||
| if (file_size == 0) { | ||
| return 0; | ||
| } | ||
| return (file_size + config_.chunk_size_bytes - 1) / config_.chunk_size_bytes; | ||
| } |
Owner
|
@copilot apply changes based on the comments in this thread |
- raft_log.cpp: compactUpTo() refuses snapshot_index > commit_index; commit_index never advanced by compaction - raft_log.cpp: createAndInstall() validates commit_index bound and snapshot_term against actual log entry term - raft_log.cpp/wal_shipper.cpp: sha256Hex()/chunkSha256() handle empty/null buffer safely - raft_log.cpp: loadSnapshot() validates file size, enforces exact checksum_len=64, checks gcount() after every read, verifies decompressed size matches stored metadata - raft_log.h/raft_log.cpp: chunk_size_bytes=0 clamped to named constant RaftSnapshotManager::kDefaultChunkSizeBytes (4 MB) - wal_shipper.cpp: hex encoding replaced with extracted base64Encode() utility (~1.33x overhead vs 2x hex); field renamed data_hex->data_b64 - wal_shipper.cpp: missing/not-ready mTLS client fails in production; only THEMIS_TEST_BUILD simulates success - paxos_wal.h: compact() docstring clarifies segment-granularity semantics - tests/test_raft_log.cpp: add #include <unistd.h>, fix commit_index setup before compactUpTo(), add CompactUpTo_RefusesToCompactUncommitted and CompactUpTo_ExactlyAtCommitIndex boundary tests - tests/test_raft_wal_integration.cpp: add commit before compactUpTo Co-authored-by: makr-code <[email protected]>
Contributor
Author
All review comments addressed in commit
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Implements automated Raft log snapshot compaction to prevent unbounded WAL growth, with ZSTD compression and chunked snapshot transfer for lagging-replica catch-up. Adds equivalent compaction support to the Paxos path for parity. Includes safety hardening based on review feedback: Raft safety guards, input validation, secure transport encoding, and production-safe mTLS enforcement.
Description
RaftSnapshotManager(new —raft_log.h/raft_log.cpp)utils/zstd_codec.cpp; SHA-256 of raw state data stored for integrityraft_snapshot_<index>.bin; retention policy configurable viamax_snapshots(default 5)kDefaultChunkSizeBytes = 4 MB; constructor clamps zerochunk_size_bytesto prevent division-by-zerogetChunk/getChunkCount): each chunk carries its own SHA-256 so receivers can verify independently and resume from the last good chunkcreateAndInstall()enforces Raft safety: rejectssnapshot_index > commit_indexand validatessnapshot_termmatches the actual log entry termloadSnapshot()validates minimum file size, enforceschecksum_len == 64, checksgcount()after every read, and verifiesdecompressed.size() == uncompressed_sizeRaftLogadditions (raft_log.h/raft_log.cpp)compactUpTo(index, term)— evicts entries ≤ snapshot index, records anchor; rejects requests wheresnapshot_index > commit_indexand never mutatescommit_index_estimatedSizeBytes()— drives compaction trigger decisionhasEntry()fixed to returntrueat the snapshot boundary index/term after entries are evictedsha256Hex()handles empty/null buffer safely (no undefined behaviour whenstate_datais empty)RaftStateadditions (raft_state.h/raft_state.cpp)snapshot_index_/snapshot_term_persistent fields;setSnapshotMeta()propagates to the embeddedRaftLogWAL Shipper snapshot transfer (
wal_shipper.h/wal_shipper.cpp)SnapshotChunkstruct (index, term, chunk offset, total chunks, payload, SHA-256,last_chunk)sendSnapshot(): per-chunk retry loop with exponential back-off, mTLS POST to/api/v1/snapshot/chunk; chunk payload encoded as base64 (data_b64) via extractedbase64Encode()helper (~1.33× overhead vs 2× for hex) to support the >200 MB/s throughput targetTHEMIS_TEST_BUILDsimulates success (prevents hidden misconfiguration)chunkSha256()andverifyChunkChecksum()handle empty buffer safelystatic verifyChunkChecksum(): receiver-side integrity checkPaxos parity (
paxos_snapshot.h/.cpp,paxos_wal.h/.cpp)PaxosSnapshot::compress()/decompress()added usingutils/zstd_codec.cpp;PaxosSnapshotManagerwritesPAXZ-magic binary format with JSON fallback on loadPaxosWAL::compact(up_to_lsn, node_id): writes SNAPSHOT marker entry then callsWALManager::truncate(); docstring clarifies that truncation is segment-granular (whole segments with segment number< up_to_lsn.segment)Type of Change
Testing
Replaced stub tests in
test_raft_log.cppandtest_raft_wal_integration.cppwith real GTest cases covering: log compaction, snapshot-boundaryhasEntry,estimatedSizeBytes, create/load round-trip, chunked access + per-chunk checksum verification, old-snapshot cleanup,verifyChunkChecksumvalid/invalid, andRaftState::setSnapshotMetapropagation. AddedCompactUpTo_RefusesToCompactUncommittedandCompactUpTo_ExactlyAtCommitIndexboundary tests; fixed all tests to callsetCommitIndex()beforecompactUpTo()to satisfy the new safety guard.📚 Research & Knowledge (wenn applicable)
/docs/research/angelegt?/docs/research/implementation_influence/eingetragen?Relevante Quellen:
Checklist
Original prompt
💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.