Skip to content

Add a chunked Keeper snapshot format for parallel snapshot loading - #107884

Closed
antonio2368 wants to merge 32 commits into
masterfrom
keeper-v8-parallel-snapshot
Closed

antonio2368 wants to merge 32 commits into
masterfrom
keeper-v8-parallel-snapshot

Conversation

@antonio2368

@antonio2368 antonio2368 commented Jun 18, 2026 •

Copy link
Copy Markdown
Member

Closes: #101606

Most of the changes are new unit tests, so don't be afraid.

Motivation

Keeper cold-start snapshot loading is single-threaded and memory-latency-bound. The legacy snapshot is one ZSTD stream, so neither decompression nor parsing can be parallelized; on a large snapshot (~56M nodes) loading takes ~28–30s, during which the node cannot serve.

Approach

This adds snapshot format version 9 ("chunked"), opt-in via keeper_server.coordination_settings.write_snapshot_version=9 (the default stays 6). The snapshot body is split into independently-compressed ZSTD chunks indexed by a CKFS header — one METADATA chunk, K NODES chunks (each holding snapshot_chunk_size nodes), and one SESSIONS chunk, each described by {type, offset, size, node_count}. Because every NODES chunk is its own ZSTD frame, the chunks are decompressed and parsed in parallel: each worker builds a thread-local node batch, then a serial finalize splices the batches into the container, builds the index, connects children, and validates. Readers auto-detect the format by the CKFS magic, so a cluster can upgrade readers first and only later flip writers to version 9.

Note: version 8 is reserved for TTL node support (introduced separately). The chunked format starts at version 9.

Results

On a 56M-node snapshot (32-core host) cold-load drops from ~28–30s (serial) to ~17s at 4 threads and ~15–16s at 8 — roughly 1.7–1.9× faster. The remaining floor is the serial finalize (index build + children-connect, ~12s). Snapshot size is unchanged.

New coordination settings: snapshot_chunk_size (nodes per chunk, default 100000) and snapshot_deser_threads (deserialization threads on load, default 4; 0 = all cores; 1 = serial).

Changelog category (leave one):

  • Improvement

Changelog entry:

Added an opt-in chunked Keeper snapshot format, enabled by setting keeper_server.coordination_settings.write_snapshot_version=9, that splits the snapshot into independently-compressed chunks so snapshot deserialization can run in parallel, speeding up snapshot loading on large snapshots. The default snapshot format is unchanged and the new format is auto-detected on read. Two new settings control it: snapshot_chunk_size and snapshot_deser_threads.

antonio2368 and others added 13 commits June 17, 2026 13:23
…ttings (inert)

Adds the V8 chunked-ZSTD snapshot format constants and header helpers
(KeeperSnapshotV8.{h,cpp}), SnapshotVersion::V8 enum value (MAX_SUPPORTED
remains V7), ACLMap::addUsageBatch for parallel deserialisation, two new
CoordinationSettings (snapshot_deser_threads, snapshot_chunk_size),
KeeperSnapshotDeserThreads{,Active,Scheduled} CurrentMetrics, and the
KEEPER_SNAPSHOT_LOAD thread-name constant.  No behaviour changes: no V8
code path is reachable until C3 raises MAX_SUPPORTED_SNAPSHOT_VERSION.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add the V8 snapshot write path in `KeeperSnapshotManager` behind a
version-check gate. `MAX_SUPPORTED_SNAPSHOT_VERSION` stays V7 so no
operational code path can request V8 yet; the new code is exercised
only by the explicit-version GTest added in this commit.

Changes:

`KeeperSnapshotManager.cpp`:
- Add `serializeV8` template function (anonymous namespace) that writes
  the chunked-ZSTD V8 format to a raw (unwrapped) `WriteBuffer`:
  - Preallocates a zero-filled header placeholder of size
    `13 + 17 * chunk_count` bytes.
  - Emits one METADATA frame (version byte, `snapshot_meta`, zxid,
    digest, `session_id_counter`, sorted ACL map).
  - Emits ≥ 1 NODES frames (each prefixed with a `uint64_t node_count`,
    serialised with V7 per-node encoding, skipping system nodes under
    `/keeper`). Frame count is pre-computed from `snapshot_chunk_size`.
  - Emits one SESSIONS frame (sorted sessions + optional cluster
    config, same layout as the legacy tail).
  - Per-frame one-shot ZSTD compression via `ZSTD_compress2` (level 3,
    checksum enabled), recording `V8FrameDescriptor` entries.
  - Returns the frame table; callers backpatch the header via
    `packV8Header`.
- `serializeSnapshotToBuffer`: V8 branch writes to a raw
  `WriteBufferFromNuraftBuffer`, calls `serializeV8`, finalizes, then
  `memcpy`-patches the header into the start of the nuraft buffer.
- `serializeSnapshotToDisk`: V8 branch writes to the raw file writer,
  captures `writer->count()` (true file size) *before* seeking back,
  emits `KeeperSnapshotWrittenBytes` from that captured value (U3 fix),
  then `seek(0) + write` to backpatch the header.
- Static `KeeperStorageSnapshot::serialize` gets a reject-guard: throws
  `LOGICAL_ERROR` if `version >= V8` (the legacy streaming serialiser
  cannot backpatch its already-wrapped writer).

`KeeperStateMachine.cpp`:
- In `create_snapshot`: capture `write_version` before constructing
  `KeeperStorageSnapshot`; add `if constexpr (use_rocksdb)` clamp to
  V7 so RocksDB storage never requests V8.

`KeeperSnapshotV8.h` (F2 fix from C1 review):
- Reword the byte-order comment: remove the false claim that "all
  ClickHouse platforms are LE" (s390x is big-endian); replace with
  "native byte order, no byte-swapping" + homogeneous-cluster caveat.

`gtest_coordination_snapshot.cpp`:
- Add `KeeperSnapshotV8Write.InspectBytes` test: builds a small
  `KeeperMemoryStorage` with a few nodes, constructs a V8 snapshot
  via explicit version bypass, calls `serializeSnapshotToBuffer`,
  parses the returned buffer with `parseAndValidateV8Header`, asserts
  magic "CKFS", version 8, chunk_count ≥ 3, correct frame type
  ordering, ZSTD magic at each frame offset, and decompresses the
  first NODES frame to verify `node_count` ≥ 1.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…able V8

Adds the validating sequential V8 reader (`readNodeV8`, `deserializeV8FromBuffer`)
and the load API (`MemorySnapshotLoadHandle`, `beginMemorySnapshotLoad`,
`finalizeMemorySnapshotLoad`).  Bumps `MAX_SUPPORTED_SNAPSHOT_VERSION` to V8 so
`write_snapshot_version=8` is accepted (opt-in); the default write version is
unchanged at 6.

Reader-level rejection tests added for `finalizeMemorySnapshotLoad` (steps 2–4)
and `readNodeV8` (parse-time negative `num_children` check).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Parallelize per-NODES-frame deserialization in the V8 snapshot reader
to reduce snapshot load time on multi-core nodes.

## Changes

### `KeeperSnapshotManager.h`
- Add `mutable std::optional<ThreadPool> deser_pool` and
  `size_t deser_threads = 1` members for the optional per-frame
  deserialization pool.

### `KeeperSnapshotManager.cpp` — `deserializeV8FromBuffer`
**F3 streaming decompression (all frames):**
- Replace one-shot `ZSTD_getFrameContentSize` + `ZSTD_decompress` +
  `ReadBufferFromString` with `ReadBufferFromMemory` →
  `wrapReadBufferWithCompressionMethod(Zstd)` for METADATA, NODES, and
  SESSIONS frames. Each frame gets its own `ZSTD_DCtx` via the wrapper,
  eliminating the unbounded-allocation risk from `getFrameContentSize`.

**Parallel NODES frame loop:**
- Pre-initialize `std::vector<MemorySnapshotLoadHandle> handles(K)`
  serially before scheduling any tasks (U1 lifecycle: only serial code
  touches `storage`; workers write exclusively to `handles[f]`).
- Dispatch one pool task per NODES frame when
  `load_full_storage && deser_pool.has_value() && K > 1`.
- Guard: `try { schedule all; wait(); } catch (...) { wait(); throw; }`
  drains the pool before `handles`/lambdas go out of scope.
- Worker sets thread name via `ThreadGroupSwitcher` (mirrors
  `KeeperReadThreadPool`). `shutdown_on_exception=false` keeps the
  pool reusable across snapshot loads.
- Serial fallback unchanged when `deser_threads == 1` or K ≤ 1.

**Pool construction (constructor):**
- Compute `deser_threads`: `snapshot_deser_threads=0` → auto
  (`clamp(cores/2, 1, 4)`); explicit → `clamp(value, 1, 8)`.
- Pre-create pool in the constructor (never under `snapshots_lock`).
- Pool omitted (optional empty) when `deser_threads == 1`.

### `gtest_coordination_snapshot.cpp` — two new C4 tests
- `KeeperSnapshotV8Parallel/DigestRecalculationOnLoad`: serialize V8
  with `digestEnabled=false` (NO_DIGEST in file), load with
  `digestEnabled=true`; verify `nodes_digest` is non-zero and
  consistent across two loads (recalculate_digest path exercises the
  per-handle `digest_sum` accumulation).
- `KeeperSnapshotV8Parallel/ParallelVsSequential`: force K=3 NODES
  frames via `snapshot_chunk_size=4`, load with `deser_threads=1` and
  `deser_threads=8`, assert: equal node counts, equal data per path,
  equal digest, equal ephemeral ownership, and byte-identical
  re-serialization (deterministic frame-order splice).

## Scope guard
- No V8 format change.
- No validation logic change.
- `finalizeMemorySnapshotLoad` algorithm unchanged.
- RocksDB still fails closed on V8.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- gtest: KeeperMemorySnapshotApplyTest::ApplyV8SnapshotReplacesCommittedState
  Applies a V8 buffer through the follower apply_snapshot path; asserts
  committed state replaced, children rebuilt, committed_ephemerals correct,
  nodes_digest non-zero, and last_commit_index matches snapshot index.
  Uses snapshot_chunk_size=2 to exercise multiple NODES frames (parallel path).

- Integration test: test_keeper_compression/test_with_v8.py
  Single-node Keeper with write_snapshot_version=8 + ZSTD compression;
  triggers a snapshot via 6 writes, restarts, and verifies state.

- Integration test: test_keeper_snapshots_multinode/test_v8_multinode.py
  3-node cluster with write_snapshot_version=8; stops a follower, writes 12
  nodes (triggers V8 snapshot), restarts follower, polls lgif last_snapshot_idx
  to confirm the follower received and applied the V8 snapshot, then verifies
  all nodes are readable.

- CHANGELOG: Performance Improvement entry documenting ~1.7-1.9x speedup,
  opt-in via write_snapshot_version=8, new settings (snapshot_chunk_size,
  snapshot_deser_threads), and the mixed-version operational rule.

- C3-F2: Expand single-line LocalInsertBatch method bodies to Allman style.
- C3-F4: Update stale "still V7" gtest comments to reflect V8 is now MAX.
- C3-F5: Fix SessionsTrailingBytesRejected to exercise the SESSIONS-frame
  EOF drain (not readVarUInt): serialize WITH cluster_config, then append
  one trailing byte; assert CORRUPTED_DATA from the drain check.
- C4-F3: Guard deser_pool construction with if constexpr (!use_rocksdb) so
  RocksDB managers don't create an unused thread pool.
Purely lexical rename of the Keeper "V8 snapshot" format to the
"chunked snapshot" format. The on-disk format is unchanged:
- CKFS magic bytes: identical
- Version byte: 8 (unchanged; SnapshotVersion::V8 enum ordinal preserved)
- Byte layout: identical

Changes:
- KeeperSnapshotV8.{h,cpp} → KeeperChunkedSnapshot.{h,cpp}
- KEEPER_V8_MAGIC/VERSION/MIN_CHUNK_COUNT → KEEPER_CHUNKED_SNAPSHOT_*
- V8ChunkType → SnapshotChunkType
- V8FrameDescriptor → SnapshotChunkDescriptor
- v8HeaderSize/packV8Header/parseAndValidateV8Header → chunkedSnapshot* equivalents
- serializeV8/deserializeV8FromBuffer/isV8Snapshot → chunkedSnapshot* equivalents
- makeV8FrameReader → makeChunkReader
- readNodeV8 → readChunkedSnapshotNode
- drainV8MetadataFrameTail → drainChunkedSnapshotMetadataChunkTail
- All "V8 snapshot" strings in comments and error messages
- Integration test configs/scripts: v8node* → chunked_node*
- gtest suite names: KeeperV8* → KeeperChunkedSnapshot*

ZstdInflatingReadBuffer::require_frame_complete_ is NOT renamed
(it is a genuine ZSTD stream primitive, not our format's concept).

Confirmed by: all gtests pass (129/129), build exit 0.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Shorten comments and make them self-contained; drop references to
implementation stages, commit numbers, and the design document.
Comments-only; no behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Rename local cursor p->cursor and descriptor cd->descriptor in parseAndValidateChunkedSnapshotHeader. No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… the chunk header

NODES chunks are now compressed via a streaming ZstdDeflatingWriteBuffer (no full-chunk
uncompressed materialization; per-frame content checksum preserved). The per-chunk
node_count moves from the chunk body into the header descriptor (descriptor 17->25 bytes),
so it is known from the header and no in-frame placeholder/backpatch is needed. On-disk
chunked (v8) format changed; it is unreleased and opt-in.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ffer

METADATA and SESSIONS chunks now stream through ZstdDeflatingWriteBuffer
like NODES, via one shared write_chunk helper; removes the manual ZSTD
context and the one-shot compress_and_record path. Write-only change;
chunks remain standard ZSTD frames so the reader is unaffected; no
format change.

Update the decompressSnapshotChunk test helper to use ZSTD streaming
decompression (ZSTD_DStream) instead of ZSTD_getFrameContentSize +
ZSTD_decompress, so it works for both one-shot frames and streaming
frames produced by ZstdDeflatingWriteBuffer (which does not embed the
decompressed content size in the frame header).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Reformatting and readability (variable renames, comment trimming/shortening); drop the drainChunkedSnapshotMetadataChunkTail helper so the metadata-only fast path returns after reading snapshot_meta (matches the legacy metadata path; full validation still happens on full load); simplify the finalize root check to !container.contains("/"); remove the now-redundant splice-allocator static_assert; std::span{batches}. No on-disk format change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…g, 0 = all cores

Default deserialization-thread count is now 4 (was 0/auto). The value is used as-is with no clamping; 0 means use all CPU cores. 1 still runs serially (no pool).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
deserializeChunkedSnapshotMetadataFromBuffer now returns after reading snapshot_meta, like the legacy metadata path; remove the drainChunkedSnapshotMetadataChunkTail helper (it duplicated the full deserializer's METADATA parsing). The full load still fully validates the METADATA chunk. Remove the MetadataTailTamperedRejected test which asserted the now-removed fast-path check.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1ab6beb]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb
AST fuzzer (amd_tsan) FAIL
Logical error: Block structure mismatch in A stream: different columns: (STID: 0993-28b7) FAIL cidb, issue

AI Review

Summary

This PR adds an opt-in V9 chunked Keeper snapshot format and parallel load path. The main architecture is plausible and the added tests cover many normal and corrupt-read cases, but several current issues still leave apply_snapshot able to pass a non-destructive pre-check and then fail after the old KeeperStorage has been dropped. I would not merge until the V9 metadata validation and semantic descriptor validation are tightened.

Findings

❌ Blockers

  • [src/Coordination/KeeperSnapshotManager.cpp:1532] deserializeSnapshotMetadataFromBuffer still validates only the V9 chunk version and SnapshotMetadata before apply_snapshot drops the old storage. The full load later parses zxid, digest, session_id_counter, ACLs, sessions/config, and trailing bytes under the fatal post-storage.reset path. A corrupt METADATA tail can therefore pass the pre-reset identity check at KeeperStateMachine.cpp:891 and terminate after KeeperStateMachine.cpp:919. Reuse the full METADATA parser in the metadata-only path, or otherwise consume and drain the entire METADATA chunk before storage.reset.
  • [src/Coordination/KeeperSnapshotManager.cpp:1327] V9 descriptor validation still allows duplicate METADATA chunks and no NODES chunks. Full load keeps the last METADATA, while the metadata-only path stops at the first one at KeeperSnapshotManager.cpp:1537; zero NODES is rejected only later as missing root. Reject duplicate METADATA and require at least one NODES descriptor in parseAndValidateChunkedSnapshot, so the pre-reset and full-load paths validate the same snapshot identity.

⚠️ Majors

  • [src/Coordination/KeeperSnapshotManager.cpp:1347] The inner METADATA version accepts any value >= V9, so a corrupt or future version 10 is parsed as today layout even though MAX_SUPPORTED_SNAPSHOT_VERSION is V9. Reject version_byte != KEEPER_CHUNKED_SNAPSHOT_VERSION, or at least version_byte > MAX_SUPPORTED_SNAPSHOT_VERSION, in both full-load and metadata-only paths.
  • [src/Coordination/KeeperSnapshotManager.cpp:616] The writer still compresses each V9 chunk into a WriteBufferFromOwnString before copying it to raw_out. Since snapshot_chunk_size is a node-count limit rather than a byte limit, large znodes can create very large transient allocations even on the direct-to-disk path. Stream ZstdDeflatingWriteBuffer into raw_out, or add an enforced byte bound.
  • [src/Coordination/KeeperSnapshotManager.cpp:599] [dismissed by author -- https://github.com/Add a chunked Keeper snapshot format for parallel snapshot loading #107884#discussion_r3437342744] snapshot_chunk_size=0 is still silently coerced to 1, which can turn a large snapshot into one chunk per node with a huge footer and millions of load tasks. I still consider this an operational risk unless 0 is rejected or explicitly documented as a bounded/safe mode.

💡 Nits

  • [src/Coordination/CoordinationSettings.cpp:82] write_snapshot_version says "supported: 9 and above for chunked format", but the setting still defaults to 6, accepts 6..9, and 8 remains the TTL-capable non-chunked version. Please phrase it as supported 6-9, with 9 enabling the chunked format.
Tests
  • ⚠️ Add focused corruption tests for the apply_snapshot pre-reset boundary: corrupt METADATA after SnapshotMetadata, duplicate METADATA with conflicting identities, and zero NODES.
  • ⚠️ Add a future/corrupt inner METADATA version test, not only a front-header version test.
  • ⚠️ Add coverage or validation for snapshot_chunk_size=0 if that setting value remains accepted.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: fully validate V9 METADATA before storage.reset, reject semantic descriptor shapes that make metadata-only and full-load disagree, reject unsupported inner metadata versions, and address the unbounded chunk materialization path or enforce a byte limit.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 18, 2026
"Chunked snapshot: unexpected version byte {} in METADATA chunk (expected 8)",
version_byte);

return deserializeSnapshotMetadata(rbuf);

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.

apply_snapshot uses this fast path before storage.reset as the non-destructive check of the snapshot file, but for chunked snapshots it only reads snapshot_meta. The rest of the METADATA chunk (zxid, digest, session_id_counter, ACL map, and the EOF drain) is left until deserializeSnapshotFromBuffer runs after the old storage has been dropped, where any parse error goes through the fatal terminate path. Please make this path consume and validate the whole METADATA chunk (or share the full METADATA parser and drain rbuf.eof) while still skipping the NODES and SESSIONS chunks.

Comment thread CHANGELOG.md Resolved
@JTCunning JTCunning added the comp-keeper ClickHouse Keeper (Raft-based coordination layer; ZooKeeper replacement) and ZooKeeper client lib... label Jun 18, 2026
antonio2368 and others added 2 commits June 18, 2026 17:53
Remove the closing-brace namespace comments in KeeperChunkedSnapshot.{h,cpp} and the now-unused ErrorCodes::CANNOT_COMPRESS declaration in KeeperSnapshotManager.cpp.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…jepsen tests

Set write_snapshot_version=8 in: the functional-test keeper config (tests/config/config.d/keeper_port.xml); the integration keeper-cluster configs (helpers/keeper_config{1,2,3}.xml, used by the zoo1/2/3 keeper containers); a new instance-wide embedded config (helpers/0_common_keeper_chunked_snapshot.xml, wired in via cluster.py) that merges the setting into integration tests running keeper embedded on a server instance and is inert elsewhere; and the jepsen keeper configs. The default for real deployments stays 6.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@al13n321

al13n321 commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

(I didn't read the PR yet, but I was thinking about a similar thing recently.)

  • Backpatching the header wouldn't work on S3, if we ever implement writing snapshots directly to S3, right? Maybe we should put metadata into a footer instead, similar to parquet? Maybe the last 16 bytes of the file would be footer size and version number, preceded by the footer.
  • (For parallel writing it would be more convenient if chunks were in separate files, so we don't have to accumulate a whole chunk in memory and send it to another thread for writing. But maybe it's fine, we can just make chunks pretty small, e.g. 32 MB. Dealing with multiple files is probably more inconvenient than this.)
  • (For the LSM tree storage it will be convenient to allow duplicate paths in snapshots, with later occurrences overriding the earlier ones, or something like that. But idk what exactly that should look like yet, and it doesn't seem important, so we don't have to think about it yet.)

antonio2368 and others added 2 commits June 18, 2026 17:59
Match argument-comment names to the KeeperSnapshotManager parameter (compress_snapshots_zstd_) for bugprone-argument-comment, and split two multi-variable declarations for readability-isolate-declaration in gtest_coordination_snapshot.cpp.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The chunked (V8) snapshot writes a fixed 13-byte front header ("CKFS" magic + version + chunk_count, all known before any chunk) first, then the chunk ZSTD frames, then the descriptor-table footer at the end. The footer is self-locating (footer_offset = buf_size - chunk_count*25), so there is no trailer. The write is fully append-only (no seek/backpatch) in both serializeSnapshotToBuffer and serializeSnapshotToDisk, enabling future streaming/S3 writes.

Detection (looksLikeChunkedSnapshot) is structural and version-independent: it checks the CKFS magic plus a valid chunk_count and footer layout, so a legacy CompressedWriteBuffer snapshot whose front bytes coincidentally begin with "CKFS" is not misrouted, and a future version with a compatible footer routes to the parser (UNKNOWN_FORMAT_VERSION). A fail-closed guard in the legacy readers rejects a corrupt stream that decompresses to inner version byte 8.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@al13n321

al13n321 commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

The new format can even be forward-compatible: write everything in the current format (must include ClusterConfig), then append a footer that tells where the different parts begin. Current reader ignores unused bytes at the end, inside ClusterConfig::deserialize, AFAICT.

EDIT: Nevermind, compression is different (each chunk vs whole file). Unless zstd stream consists of independent blocks and we can control where their boundaries are? Doesn't sound worth it.

(A little awkward that we'd have to leave version number unchanged. Then the new reader will have to use something else to guess whether the file uses the new format. I guess we should make the last 8 bytes be a randomly generated magic number and check that. For future, we should add something like "minor version" or "min compatible version" in the footer, so that we can bump the version but tell older readers that they can read this too.)

@al13n321 al13n321 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.

Pretty vibey, all new code with no attempt to deduplicate it with the existing code. If you're ok with that, I guess I'm ok with that.

I'll probably need to reorganize it all anyway for LSM tree; I'm currently refactoring it to make KeeperStorage pull information from snapshot reader, instead of KeeperSnapshotManager knowing about KeeperStorage internals:

struct KeeperSnapshotReader
{
    ReadBuffer & in;

    SnapshotMetadataPtr snapshot_meta;
    ClusterConfigPtr cluster_config;
    size_t node_count = 0;
    int64_t commit_zxid = 0;
    int64_t session_id_counter = 0;
    ACLMap acl_map;

    KeeperSnapshotReader(ReadBuffer & in_) : in(in_) {}

    /// How to read a snapshot:
    ///   readHeaderAndACLMap();
    ///   while (readNodePathAndDataSize(...))
    ///       readNodeDataAndStats(...);
    ///   readSessionsAndClusterConfig(...);

    void readHeaderAndACLMap();

    bool readNodePathAndDataSize(std::string & out_path, size_t & out_data_size);
    void readNodeDataAndStats(char * out_data, KeeperNodeStats & out_stats);

    void readSessionsAndClusterConfig(KeeperStorage & storage);
};

Guess this PR will be merged first, and I'll do a big rebase, that's fine.

Requesting changes for the footer, I don't insist on all the other nitpicks since they mostly don't affect the format.

- Fix all syntax errors in gtest_coordination_snapshot.cpp (extra parens,
  missing EXPECT_THROW exception types, looksLikeChunkedSnapshot → isChunkedSnapshot)
- Refactor test helpers: use WriteBufferFromOwnString/ReadBufferFromString/
  ReadBufferFromNuraftBuffer/WriteBufferFromNuraftBuffer instead of raw pointers
  and nuraft::buffer::alloc; use ZstdInflatingReadBuffer/ZstdDeflatingWriteBuffer
  in decompressSnapshotChunk and replaceFirstChunkOfType
- Consolidate all chunked snapshot tests under CoordinationChunkedSnapshotTest
- Extract makeKeeperContext() helper (23 boilerplate blocks collapsed)
- Shorten verbose comments throughout test file and KeeperStorage.h/cpp
- Remove redundant updateValueForLoad (reuse updateValue); drop MissingParentInNodesFrame test
- Remove GlobalArena pointer from LocalInsertBatch and size/arena from KeyDeleter
  (GlobalArena is stateless — just new[]/delete[])
- Parallel snapshot load: switch from one-task-per-chunk to one-worker-per-thread
  with atomic fetch_add, reducing handle count from chunks to min(threads, chunks)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
for (const auto & chunk_descriptor : chunks)
{
if (chunk_descriptor.type == SnapshotChunkType::METADATA)
metadata_chunk_info = &chunk_descriptor;

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.

Relaxing chunk ordering still needs singleton validation for chunks whose semantics must be unique. Right now a footer with two METADATA descriptors is accepted: this full-load path keeps the last one, while deserializeChunkedSnapshotMetadataFromBuffer stops at the first one. In apply_snapshot, the pre-reset identity check can therefore pass on the first METADATA chunk, then after storage.reset this path reads a different/corrupt second METADATA chunk and reaches the fatal terminate path. Please reject duplicate METADATA chunks (and zero NODES chunks) during parseAndValidateChunkedSnapshot, or otherwise make the metadata-only and full-load paths select the same validated singleton before the old storage is dropped.

@antonio2368

Copy link
Copy Markdown
Member Author

Maybe this can wait until I refactor snapshot deserialization (62e1691 ) and serialization (2d73f36 )?

@al13n321 feel free to decide what's the easiest for you. I tried to fix the vibe code mess, so most of the code is now reused.

1. `test_keeper_zookeeper_converter` / `test_keeper_snapshot_small_distance`:
   `deserializeStorageData` (ZooKeeper format) uses `'/'` as a loop terminator
   and never inserts the root node. The `insert_initial_root` consolidation in
   commit `1a008d01e65` stopped the `KeeperStorage` constructor from pre-inserting
   root when `initialize_system_nodes=false`, so the post-processing pass that
   calls `updateValue('/', ...)` for direct children crashed with
   `Could not find key: '/'`.
   Fix: insert an empty root in `deserializeStorageData` when the container
   doesn't already have one.

2. `test_keeper_compression::test_select` (`test_with_compression.py` /
   `test_without_compression.py`): `configs/keeper.xml` hostname was changed from
   `node1` to `node_v8` for the new V8 test but the file is shared by all three
   test files. Nodes named `node1` then failed to start because DNS resolution for
   `node_v8` failed.
   Fix: restore `configs/keeper.xml` with `hostname=node1`; give `test_with_v8.py`
   its own `configs/keeper_v8_base.xml` with `hostname=node_v8`.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Comment thread src/Coordination/KeeperStateMachine.cpp Resolved
… configs to node1

`configs/keeper_with_compression.xml` had its ZooKeeper host changed from
`node1` to `node_v8` for the new V8 test, but it is shared by
`test_with_compression.py` and `test_without_compression.py` which use
`node1`. The server on `node1` failed to start because it tried to connect
to `node_v8:9181` as its ZooKeeper endpoint.

Restore `keeper_with_compression.xml` to `node1` (matching master).
Add `keeper_with_compression_v8.xml` with `node_v8` for `test_with_v8.py`
(which already got its own `keeper_v8_base.xml` in the previous commit).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@antonio2368
antonio2368 requested a review from al13n321 June 24, 2026 10:40
antonio2368 and others added 2 commits June 25, 2026 10:57
Master introduced `SnapshotVersion::V8` for TTL nodes (`destroy_time`/`ttl`).
Our branch also used `V8` for the chunked independently-compressed ZSTD format,
causing a version collision.

Resolution:
- Keep master's `V8 = 8` for TTL node serialization
- Rename our chunked format to `V9 = 9`
- `MAX_SUPPORTED_SNAPSHOT_VERSION` updated to `V9`
- Legacy reader now rejects `>= V9` (allowing V8 TTL snapshots through)
- `serializeSnapshotToBuffer` / `saveSnapshotToDisk` use chunked path for `>= V9`
- RocksDB clamp in `KeeperStateMachine` updated from V7 to V8 (RocksDB supports TTL but not chunked)
- `serialize()` guards: TTL check for `< V8`, chunked guard for `>= V9`
- Inner METADATA chunk version byte remains V8 (describes TTL field layout)
- All integration test configs and gtest references updated to `write_snapshot_version=9`
- Combined master's `captured_storage` capture fix in `scheduleSnapshotDeletion`
- Combined master's `detachSnapshotForRemoval` private method with our `deserializeChunkedSnapshotFromBuffer`

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
`moveSnapshotBetweenDisks` and `getSnapshotPathUpToLogIdx` were orphaned
during the master merge conflict resolution — master already provides
equivalent functionality via `KeeperSnapshotManager` member functions,
so the file-local helpers are dead code. Removing them fixes
`-Werror=unused-function` build failures.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
When loading a V9 (chunked) snapshot, `ttl_paths` and `committed_ttl_nodes`
were never populated: the node stats (including the TTL deadline) were
deserialized correctly, but the per-chunk worker handle had no place to
accumulate TTL paths and `finalizeMemorySnapshotLoad` never merged them into
storage. After a reload from a chunked snapshot, TTL-based node expiry would
therefore stop working.

Fix:
- Add `local_ttl_paths` to `MemorySnapshotLoadHandle` so each worker thread
  can record TTL nodes it processes.
- In the `process_nodes_chunk` lambda (KeeperSnapshotManager.cpp), push the
  path onto `current_handle.local_ttl_paths` when `node.stats.isTTL()`.
- In `finalizeMemorySnapshotLoad` (KeeperStorage.cpp), merge `local_ttl_paths`
  into `storage.ttl_paths` and bump `storage.committed_ttl_nodes`; annotate
  the function `TSA_NO_THREAD_SAFETY_ANALYSIS` because it runs on the init
  thread (no contention) and the other field merges already had this implicit
  exemption.

Reported in: #107884 (comment)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
DECLARE(Bool, check_node_acl_on_remove, false, "When trying to remove a node, check ACLs from both the node itself and the parent node. If disabled, default behaviour will be used where only ACL from the parent node is checked", 0) \
DECLARE(UInt64, snapshot_transfer_chunk_size, 0, "Chunk size in bytes for snapshot transfer between Keeper nodes. Larger values reduce round-trips but increase per-message memory usage. 0 means disabled: the whole snapshot is sent as a single NuRaft object (compatibility behaviour).", 0) \
DECLARE(UInt64, write_snapshot_version, 6, "Snapshot format version to write (supported: 8 and above). Increase only after all nodes in the cluster are upgraded to a version that supports the new format", 0) \
DECLARE(UInt64, write_snapshot_version, 6, "Snapshot format version to write (supported: 9 and above for chunked format). Increase only after all nodes in the cluster are upgraded to a version that supports the new format", 0) \

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.

write_snapshot_version still defaults to 6 and KeeperContext::getWriteSnapshotVersion accepts the range 6..9; 8 also remains the non-chunked version needed for CREATE_TTL. Saying "supported: 9 and above" makes the default look unsupported and hides the 8 rollout path. Please phrase this as something like "supported: 6-9; 9 enables the chunked format" and keep the TTL-only 8 case explicit.

Master removed the Keeper RocksDB storage and unified the list-request
types. Resolve the conflicts by following master: de-template
`KeeperStorage`, `KeeperStorageSnapshot`, `KeeperSnapshotManager`, and
`SnapshotDeserializationResult` onto the single concrete `KeeperStorage`
(node type `KeeperMemNode`), dropping the `use_rocksdb` branches and the
`KeeperStorageSnapshotPtr` variant.

The chunked V9 snapshot format and parallel per-chunk deserialization are
preserved. The extracted helpers (`serializeSessionsAndConfig`,
`deserializeSessionsAndConfig`, `prepareDeserializedNode`,
`serializeChunkedSnapshot`, `MemorySnapshotLoadHandle`,
`beginMemorySnapshotLoad`, `finalizeMemorySnapshotLoad`) carry over
de-templated and are verified equivalent to master's inline logic. The
`KeeperStorage` constructor keeps the branch's behaviour of inserting root
`/` only when `initialize_system_nodes` is set, so chunked snapshot load
takes root from the snapshot data.

Drop dead RocksDB plumbing from the Coordination gtests (`setRocksDBOptions`,
`setRocksDBDisk`).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

uint8_t version_byte = 0;
readBinary(version_byte, metadata_rbuf);
if (version_byte < static_cast<uint8_t>(SnapshotVersion::V9))

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.

The chunked format now has a single supported version (KEEPER_CHUNKED_SNAPSHOT_VERSION == 9), but this accepts any version_byte >= 9 from the METADATA chunk. A corrupt or future snapshot with metadata version 10 will be interpreted as the current layout and can get past the pre-apply validation path; the legacy reader rejects current_version > MAX_SUPPORTED_SNAPSHOT_VERSION before parsing for this reason. Please reject version_byte != KEEPER_CHUNKED_SNAPSHOT_VERSION (or at least > MAX_SUPPORTED_SNAPSHOT_VERSION) in both full-load and metadata-only parsing before using it as SnapshotVersion.

…est assets

F5: The chunked snapshot format was written as a V9 envelope but with a hardcoded
V8 version byte inside the METADATA chunk body and V8 passed to
`serializeStorageMetaFields`. The `KEEPER_CHUNKED_SNAPSHOT_VERSION` outer-envelope
constant was also 8. Now everything is consistently V9:
- `KEEPER_CHUNKED_SNAPSHOT_VERSION = 9` in `KeeperChunkedSnapshot.h`
- METADATA chunk body writes `snapshot.version` (V9) instead of hardcoded V8
- `serializeStorageMetaFields` receives `snapshot.version` instead of V8
- Read-side checks `version_byte < V9` (reject old/unknown) instead of `!= V8`,
  accepting V9 and any future body version

Fix all gtest assertions that hardcoded the outer front-header version byte as
8u: replace with `DB::KEEPER_CHUNKED_SNAPSHOT_VERSION`. Update the two
"unsupported future version" tests to use `KEEPER_CHUNKED_SNAPSHOT_VERSION + 1`
instead of 9. Rename `LegacyInnerVersion8RejectedByLegacyReader` to
`LegacyInnerUnsupportedVersionRejectedByLegacyReader` and update it to use
`MAX_SUPPORTED_SNAPSHOT_VERSION + 1` — V8 is a valid legacy format, only
versions above max trigger `UNKNOWN_FORMAT_VERSION` in the legacy reader.

F6: Rename `test_keeper_compression` v8-named assets to `chunked`:
- `test_with_v8.py` → `test_with_chunked.py` (node, function, variable, comment names)
- `keeper_v8_base.xml` → `keeper_chunked_base.xml` (hostname updated)
- `keeper_v8_settings.xml` → `keeper_chunked_settings.xml`
- `keeper_with_compression_v8.xml` → `keeper_with_compression_chunked.xml` (host updated)
- `CurrentMetrics.cpp`: metric help strings updated to say "chunked" instead of "V8"

59/59 snapshot gtests pass. Integration test `test_with_chunked` passes.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
@antonio2368
antonio2368 force-pushed the keeper-v8-parallel-snapshot branch from 84ed526 to 1ab6beb Compare June 29, 2026 09:00
@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.70% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 1713/1796 (95.38%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 17 line(s) · Uncovered code

Full report · Diff report

@al13n321 al13n321 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.

Looks correct, here's some nitpicking, up to you how much of it to address before merging. I'll have to rewrite half of it to resolve conflicts with #108583 anyway (but at least the non-nit comments are orthogonal to that).

{
writeString(KEEPER_CHUNKED_SNAPSHOT_MAGIC, out);
writeBinary(KEEPER_CHUNKED_SNAPSHOT_VERSION, out);
writeBinary(chunk_count, out);

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.

I'd rather do the parquet thing and put footer size at the end of the file, potentially doing two seeks+reads to read it (first read the fixed-size post-footer that has footer size, format version, and magic bytes, then read the footer; or speculatively read the last 64KiB right away, then do a second bigger read if the footer size turns out bigger than that). Because it seems needlessly limiting to rely on (1) footer size being calculable like this, and (2) the writer knowing all inputs of the footer size calculation in advance (in this case chunk_count). E.g. maybe we'll want to put some variable-length info into chunk metadata (e.g. min/max node paths); or maybe the writer would cut chunks based on serialized size rather than node count, or won't know the number of nodes in advance; (or hand out LSM tree data parts to threads and have them cut chunks independently, so number of chunks wouldn't be exactly equal to total_nodes/nodes_per_chunk; though it's unlikely we'll end up doing this exact thing because we want to either merge data parts for dedup or dump them as is (count known in advance)).

void packChunkedSnapshotHeader(uint64_t chunk_count, WriteBuffer & out)
{
writeString(KEEPER_CHUNKED_SNAPSHOT_MAGIC, out);
writeBinary(KEEPER_CHUNKED_SNAPSHOT_VERSION, out);

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.

nit: This is SnapshotVersion, and the plan is to continue incrementing it for future format changes, right? Maybe pass the actual requested version here, and change the if (check_version && version != KEEPER_CHUNKED_SNAPSHOT_VERSION) to version >= KEEPER_CHUNKED_SNAPSHOT_VERSION && version <= MAX_SUPPORTED_SNAPSHOT_VERSION.

Comment on lines +137 to +140
catch (...) // Ok: any IO or structural error means the buffer is not a chunked snapshot
{
return false;
}

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.

nit: This seems weird, and will probably produce confusing error messages if snapshot is chunked but malformed. Maybe just read the first 4 bytes and compare to magic? Maybe make it 8 bytes, otherwise 1 in 4 billion legacy snapshots would accidentally start with magic bytes since CompressedReadBuffer's data starts with a checksum.

nit2: Why use both std::expected and exceptions?

working_buffer = internal_buffer;
return cur + offset;
}
if (whence == SEEK_END)

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.

nit: I'd rather make SeekableReadBuffer inherit WithFileSize and implement tryGetFileSize() in all SeekableReadBuffer implementations (there are not many, and it seems straightforward) than implement SEEK_END and SEEK_CUR in ReadBufferFromS3 and ReadBufferFromFileDescriptor. Relative seeks seem generally less useful and more awkward to implement and use than querying file size, at least for all the SeekableReadBuffer implementations I've seen in clickhouse.

return derived.pos - derived.internal_buffer.begin();
}

std::unique_ptr<ReadBufferFromMemory> ReadBufferFromMemory::getView(size_t offset, std::optional<size_t> size)

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.

I'd rather use readBigAt instead (reading a whole compressed chunk into a buffer, it's fine; called from deser threads), because it'll work with S3 and file read buffers.

Comment on lines +85 to +88
/// With require_frame_complete, a non-zero ret at EOF means the ZSTD frame epilogue
/// (e.g. 4-byte content checksum) was never consumed — integrity check silently skipped.
if (require_frame_complete && ret != 0)
throw Exception(

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.

Which other users of ZstdInflatingReadBuffer need to ignore this error? Why is this check more important for keeper snapshots than for all the other uses of ZstdInflatingReadBuffer? Can't it be the default and only behavior?

Comment on lines +78 to +79
/// This restores the integrity guarantee that the superseded one-shot ZSTD_decompress
/// path provided: a corrupt or truncated frame is detected rather than accepted.

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.

I don't understand what this is referring to. The data is written by ZstdDeflatingWriteBuffer the same way before and after this PR? How does this PR affect the validity/usefulness of the unexpected-eof check? Do you just mean there are more opportunities to perform the check: at the end of each chunk instead of at the end of whole snapshot? Seems arbitrary and not worth the extra code and long comment. Adding the ret != 0 check unconditionally for everyone would be good, if that's valid (i.e. if ZstdInflatingReadBuffer is never used to intentionally read truncated data, which would be weird).

@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Dear @kssenii, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Dear @al13n321, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@alexey-milovidov

Copy link
Copy Markdown
Member

The format sounds like over-engineering. We have CompressedReadBuffer/CompressedWriteBuffer and mark files, which are trivial and used everywhere in the code. We are not tied to the ZSTD framing format, and we don't have to use it. Moreover, there is a trivial solution of writing more than one file.

@alexey-milovidov

Copy link
Copy Markdown
Member

Waiting for the resolution of conflicts.

@alexey-milovidov alexey-milovidov added the close in a month if not active This will be closed in case of no information label Jul 31, 2026
@alexey-milovidov

alexey-milovidov commented Jul 31, 2026 •

Copy link
Copy Markdown
Member

If @al13n321 said it is good, the code is good to merge.

@antonio2368

Copy link
Copy Markdown
Member Author

More optimal snapshot format will be implemented as part of new storage efforts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

close in a month if not active This will be closed in case of no information comp-keeper ClickHouse Keeper (Raft-based coordination layer; ZooKeeper replacement) and ZooKeeper client lib... pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RFC: Parallel Keeper Snapshot Reads via Chunked ZSTD Frames

5 participants