Skip to content

feat(sharding): Raft Snapshot Compaction and Log Truncation (v1.6.0) - #4147

Merged
makr-code merged 4 commits into
developfrom
copilot/raft-snapshot-compaction-log-truncation
Mar 13, 2026
Merged

makr-code merged 4 commits into
developfrom
copilot/raft-snapshot-compaction-log-truncation

Conversation

Copilot AI commented Mar 12, 2026 •

Copy link
Copy Markdown
Contributor

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)

  • Triggers compaction when estimated in-memory log size exceeds a configurable threshold (default 512 MB)
  • Snapshots compressed with ZSTD level 3 via utils/zstd_codec.cpp; SHA-256 of raw state data stored for integrity
  • On-disk format: raft_snapshot_<index>.bin; retention policy configurable via max_snapshots (default 5)
  • Named constant kDefaultChunkSizeBytes = 4 MB; constructor clamps zero chunk_size_bytes to prevent division-by-zero
  • Chunked transfer API (getChunk / getChunkCount): each chunk carries its own SHA-256 so receivers can verify independently and resume from the last good chunk
  • createAndInstall() enforces Raft safety: rejects snapshot_index > commit_index and validates snapshot_term matches the actual log entry term
  • loadSnapshot() validates minimum file size, enforces checksum_len == 64, checks gcount() after every read, and verifies decompressed.size() == uncompressed_size
RaftSnapshotManager::Config cfg;
cfg.compaction_threshold_bytes = 512ULL * 1024 * 1024;
cfg.compression_level = 3;
RaftSnapshotManager mgr(cfg);

if (mgr.shouldCompact(log)) {
    mgr.createAndInstall(log, last_index, last_term, state_bytes);
    // log.estimatedSizeBytes() drops; entries ≤ last_index evicted
}
// Transfer to lagging replica in fixed-size chunks
for (uint64_t i = 0; i < mgr.getChunkCount(last_index); ++i) {
    auto chunk = mgr.getChunk(last_index, i);
    shipper.sendSnapshot(replica_id, {*chunk});
}

RaftLog additions (raft_log.h / raft_log.cpp)

  • compactUpTo(index, term) — evicts entries ≤ snapshot index, records anchor; rejects requests where snapshot_index > commit_index and never mutates commit_index_
  • estimatedSizeBytes() — drives compaction trigger decision
  • hasEntry() fixed to return true at the snapshot boundary index/term after entries are evicted
  • sha256Hex() handles empty/null buffer safely (no undefined behaviour when state_data is empty)

RaftState additions (raft_state.h / raft_state.cpp)

  • snapshot_index_ / snapshot_term_ persistent fields; setSnapshotMeta() propagates to the embedded RaftLog

WAL Shipper snapshot transfer (wal_shipper.h / wal_shipper.cpp)

  • New SnapshotChunk struct (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 extracted base64Encode() helper (~1.33× overhead vs 2× for hex) to support the >200 MB/s throughput target
  • Missing or not-ready mTLS client now fails in production; only THEMIS_TEST_BUILD simulates success (prevents hidden misconfiguration)
  • chunkSha256() and verifyChunkChecksum() handle empty buffer safely
  • static verifyChunkChecksum(): receiver-side integrity check

Paxos parity (paxos_snapshot.h/.cpp, paxos_wal.h/.cpp)

  • PaxosSnapshot::compress() / decompress() added using utils/zstd_codec.cpp; PaxosSnapshotManager writes PAXZ-magic binary format with JSON fallback on load
  • PaxosWAL::compact(up_to_lsn, node_id): writes SNAPSHOT marker entry then calls WALManager::truncate(); docstring clarifies that truncation is segment-granular (whole segments with segment number < up_to_lsn.segment)

Type of Change

  • Bug fix
  • New feature
  • Refactoring
  • Documentation
  • Other:

Testing

  • Unit tests added/updated
  • Integration tests added/updated
  • Manual testing performed

Replaced stub tests in test_raft_log.cpp and test_raft_wal_integration.cpp with real GTest cases covering: log compaction, snapshot-boundary hasEntry, estimatedSizeBytes, create/load round-trip, chunked access + per-chunk checksum verification, old-snapshot cleanup, verifyChunkChecksum valid/invalid, and RaftState::setSnapshotMeta propagation. Added CompactUpTo_RefusesToCompactUncommitted and CompactUpTo_ExactlyAtCommitIndex boundary tests; fixed all tests to call setCommitIndex() before compactUpTo() to satisfy the new safety guard.

📚 Research & Knowledge (wenn applicable)

  • Diese PR basiert auf wissenschaftlichen Paper(s) oder Best Practices?
    • Falls JA: Research-Dateien in /docs/research/ angelegt?
    • Falls JA: Im Modul-README unter "Wissenschaftliche Grundlagen" verlinkt?
    • Falls JA: In /docs/research/implementation_influence/ eingetragen?

Relevante Quellen:

  • Paper:
  • Best Practice:
  • Architecture Decision:

Checklist

  • Code follows project style guidelines
  • Self-review completed
  • Documentation updated (if needed)
  • No new warnings introduced
Original prompt

This section details on the original issue you should resolve

<issue_title>Raft Snapshot Compaction and Log Truncation</issue_title>
<issue_description>### Context

This issue implements the roadmap item 'Raft Snapshot Compaction and Log Truncation' for the sharding domain. It is sourced from the consolidated roadmap under 🟠 High Priority — Near-term (v1.5.0 – v1.8.0) and targets milestone v1.6.0.

Primary detail section: [ ] Raft Snapshot Compaction and Log Truncation

Goal

Deliver the scoped changes for Raft Snapshot Compaction and Log Truncation in src/sharding/ and complete the linked detail section in a release-ready state for v1.6.0.

Detailed Scope

[ ] Raft Snapshot Compaction and Log Truncation

Priority: High
Target Version: v0.9.0

Implement automated Raft log snapshot compaction in raft_log.cpp and raft_wal_integration.cpp to prevent unbounded WAL growth. Snapshots are compressed with ZSTD (utils/zstd_codec.cpp) and stored via metadata_snapshot.cpp, then transferred to lagging replicas via wal_shipper.cpp.

Implementation Notes:

  • Add RaftSnapshotManager to raft_log.cpp that triggers compaction when log size exceeds a configurable threshold (default 512 MB); store snapshot index and term in raft_state.cpp.
  • Use utils/zstd_codec.cpp for snapshot compression; target compression ratio >3× for typical metadata payloads.
  • wal_shipper.cpp must support chunked snapshot transfer with checksums to tolerate network interruption during lagging-replica catch-up.
  • paxos_snapshot.cpp and paxos_wal.cpp must receive equivalent snapshot compaction support for parity with the Raft path.

Performance Targets:

  • Snapshot creation time for 1 GB Raft state: <10 s.
  • Compressed snapshot size: <35% of uncompressed (ZSTD level 3).
  • Lagging replica catch-up via snapshot transfer: >200 MB/s on 10 GbE LAN.

Acceptance Criteria

  • Add RaftSnapshotManager to raft_log.cpp that triggers compaction when log size exceeds a configurable threshold (default 512 MB); store snapshot index and term in raft_state.cpp.
  • Use utils/zstd_codec.cpp for snapshot compression; target compression ratio >3× for typical metadata payloads.
  • wal_shipper.cpp must support chunked snapshot transfer with checksums to tolerate network interruption during lagging-replica catch-up.
  • paxos_snapshot.cpp and paxos_wal.cpp must receive equivalent snapshot compaction support for parity with the Raft path.
  • Snapshot creation time for 1 GB Raft state: <10 s.
  • Compressed snapshot size: <35% of uncompressed (ZSTD level 3).
  • Lagging replica catch-up via snapshot transfer: >200 MB/s on 10 GbE LAN.

Relationships

References

  • src/ROADMAP.md
  • src/sharding/FUTURE_ENHANCEMENTS.md#-raft-snapshot-compaction-and-log-truncation
  • Source key: roadmap:108:sharding:v1.6.0:raft-snapshot-compaction-and-log-truncation

Generated from the consolidated source roadmap. Keep the roadmap and issue in sync when scope changes.

</issue_description>

Comments on the Issue (you are @copilot in this section)


💡 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.

Copilot AI and others added 2 commits March 12, 2026 20:58
… (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
Copilot AI requested a review from makr-code March 12, 2026 21:01
@makr-code
makr-code marked this pull request as ready for review March 13, 2026 05:15
@makr-code
makr-code requested a review from Copilot March 13, 2026 05:15

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 RaftSnapshotManager with on-disk snapshot persistence, retention cleanup, and chunked snapshot read API; extend RaftLog with compaction + size estimation + snapshot-boundary hasEntry.
  • Add snapshot chunk transfer types/API to WALShipper with per-chunk SHA-256 verification and retries.
  • Add Paxos snapshot compression (PAXZ format w/ JSON fallback) and WAL compaction via WALManager::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 thread src/sharding/wal_shipper.cpp Outdated
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 thread src/sharding/raft_log.cpp
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 thread src/sharding/raft_log.cpp
Comment on lines +244 to +245
const std::string checksum = computeChecksum(state_data.data(), state_data.size());

Comment thread src/sharding/raft_log.cpp Outdated
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 thread tests/test_raft_log.cpp
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 thread src/sharding/raft_log.cpp
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 thread src/sharding/raft_log.cpp
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;
}
@makr-code

Copy link
Copy Markdown
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]>

Copilot AI commented Mar 13, 2026

Copy link
Copy Markdown
Contributor Author

@copilot apply changes based on the comments in this thread

All review comments addressed in commit 3643030:

  • sendSnapshot() hex encoding → replaced with an extracted base64Encode() helper (~1.33× overhead vs 2× for hex); JSON field renamed data_hex → data_b64.
  • createAndInstall() Raft safety → added precondition checks: rejects snapshot_index > commit_index and validates snapshot_term matches the actual log entry term.
  • Empty-buffer SHA-256 → sha256Hex() and chunkSha256() now handle size == 0 without dereferencing a potentially-null pointer.
  • loadSnapshot() bounds checking → validates minimum file size, enforces checksum_len == 64, checks file.gcount() after every read, and verifies decompressed.size() == uncompressed_size.
  • chunk_size_bytes == 0 guard → constructor clamps to kDefaultChunkSizeBytes (named constant, 4 MB).
  • Missing mTLS client → now fails in production; only THEMIS_TEST_BUILD simulates success.
  • compactUpTo() safety → rejects snapshot_index > commit_index and never mutates commit_index_. Added CompactUpTo_RefusesToCompactUncommitted and CompactUpTo_ExactlyAtCommitIndex boundary tests.
  • Paxos WAL docstring → updated to clarify segment-granularity truncation semantics.
  • #include <unistd.h> → added with Windows guard to test_raft_log.cpp.

@makr-code
makr-code merged commit 0fb973e into develop Mar 13, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Raft Snapshot Compaction and Log Truncation

3 participants