Skip to content

New keeper storage - #107261

Merged
al13n321 merged 17 commits into
masterfrom
kdb
Aug 1, 2026
Merged

al13n321 merged 17 commits into
masterfrom
kdb

Conversation

@al13n321

@al13n321 al13n321 commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

LSM tree, a little similar to rocksdb but specialized and more efficient.

In this PR it's just some dead code in a separate directory, not integrated with keeper. But I have integration implemented and working, it's coming in a separate PR (#108583 , then another smaller one). Early benchmarks say this is 10% faster than the current memory storage.

Explanation (half copied from a github comment in this PR):

The main idea is: serialized znode can be much more compact than fixed-size in-memory structs, especially if a group of znodes is serialized together. Paths can be delta-compressed, stats (zxids, times, versions, etc) can be delta-compressed + group-varinted. E.g. znode version is usually 0; it takes 4 bytes in fixed-size struct, but can take 0.25 bytes in group varint; and paths have very long common prefixes (on average only ~1/5 of a path is the last component, see tool output in #106270 summary). The deltas can be relative to block header, so that we can deserialize any one node on demand if we have a pointer to the block and the node's offset inside the block. See Node.h/Node.cpp for full serialization.

We can have a hash map that maps node path hash (16 bytes) to block+offset where the serialized node lives. Then we can efficiently (~4 group varint decodes) deserialize the node on demand when executing requests. So performance should be on par with current in-memory storage, with much (?) less memory usage.

But if nodes can only be appended to blocks and can't be overwritten or removed, we need some kind of background cleanup. Maybe periodically iterate over nodes in all blocks, skip obsolete ones, write survivors to new blocks, then delete old blocks? Somehow synchronize all that with readers and don't block readers too much? I couldn't come up with such cleanup scheme that's good and much simpler than a full blown LSM tree. So I was tempted to just do a full blown LSM tree. It has its benefits: can store blocks on disk, paths compress better because of sorting, memory usage mostly independent of dataset size (except for the big hashmap with pointers to all nodes; but we can later turn that map into a cache, falling back to rocksdb-like lookup in all memtables and files). Background flushes and merges should be almost free because keeper server only uses a few cpu cores, there are lots of free cores to do background work (though they would eat into memory bandwidth). So I think it makes sense to do a full-blown LSM tree. Seems easy enough.

(I don't think rocksdb can get close to this performance, at least without heroic customizations and tuning. Its lookup checks all memtables, then all files (I'm guessing in keeper we often read znodes that weren't recently written, so would miss memtables? idk). Memtable is a skiplist by default, with pretty slow lookup; but a custom memtable type can be plugged in, we could implement a memtable with hashmap + children sets. In a file, lookup is binary search in the list of blocks, then lookup of the block in block cache, then binary search inside the block. We wouldn't be able to delta-compress stats relative to block header (but paths would be delta compressed sequentially, rocksdb does that for keys). And we'd generally have less control, it would be harder to change things, there'd be much more code to dig through.)

This PR has all the things needed to work: block format, memtables, sorted runs, background flushes (writing memtable to files) and merges, node hashmap, block cache (currently unused). But only has memory-only mode, doesn't write to files. The hope is that even in memory-only mode it'll use less memory than the current memory storage. (But early tests showed higher memory usage, I haven't investigated yet. Maybe this is all wrong, and this writeup will look stupid in hindsight :) )

Implemented a weird but probably important merge feature I haven't seen before: the merge deallocates consumed input blocks on the fly. So a big merge shouldn't cause a 2x spike in memory usage when it already wrote most of the output but didn't delete the inputs yet. It publishes the partial output and truncates the inputs as it goes. For that, each sorted run is stored in a series of files (with disjoint key ranges) instead of one file; merge publishes finished output files and evicts fully consumed input files from memory (probably won't need to delete them from disk until the merge is finished, space usage is not so important). I always wondered why LSM implementations don't do that. (Yes, the standard approach is level-based/tier-based compaction, but it has bad write amplification, IIUC. Which probably wouldn't matter much here. But I wanted to try this other approach anyway, hope it's ok.)

Version info

  • Merged into: 26.8.1.571 (included in 26.8 and later)

@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [caa4f39]

Summary: ✅


AI Review

Summary

This PR adds a standalone LSM-style Keeper storage implementation: serialized node blocks, memtables, sorted runs, background flush/merge workers, and white-box unit tests. The main design looks coherent, but I do not think it is ready to merge yet because one new failure-path issue still turns semantic validation errors into std::abort(), and one previously reported background-publication failure mode is still present in the current code.

Missing context / blind spots
  • ⚠️ The adapter that plugs this storage into KeeperNodesStorage is explicitly deferred to follow-up PRs, so I could only infer request-level behavior such as ZNODEEXISTS / ZNONODE translation from this standalone layer.
  • ⚠️ The file-backed path is still stubbed (SortedFile::loadBlock throws NOT_IMPLEMENTED), so only the memory-only mode was actually reviewable here; on-disk compatibility and restart behavior remain unvalidated.
Findings

⚠️ Majors

  • [src/Coordination/Storage/StorageState.cpp:230] appendCommittedNode and appendUncommittedNode deliberately throw DB::Exception when the action history is invalid, but both helpers then catch everything and call std::abort(). Once the adapter starts using this layer, an ordinary state mismatch that should surface as an exception instead becomes a fatal process abort. Suggested fix: let semantic DB::Exceptions propagate (or translate them at the adapter boundary) and reserve the fatal path for truly unrecoverable failures.
  • [src/Coordination/Storage/BackgroundWork.cpp:203] [dismissed by author -- https://github.com/New keeper storage #107261#discussion_r3599939070] The flush thread still publishes a finished run through fallible flushed_files[memtable->file_seqno] = new_run / sorted_runs.push_back allocations outside any LockMemoryExceptionInThread or local retry boundary. A MEMORY_LIMIT_EXCEEDED or allocator failure after the flush has already succeeded will still abort the process even though the immutable memtable could simply stay queued for later publication. Suggested fix: make the whole publication/reorder-buffer phase no-throw under memory limits, or move it under the same retry discipline as the flush work itself.
Tests
  • ⚠️ NodeSerializationRoundTrip still forces block->compatible_digest = true manually, so it does not protect the production writer path (appendNodeOrStartNewBlock / SortedRunWriter) that regressed earlier. A focused round-trip through Memtable::appendNode or SortedRunWriter would close that gap.
  • ⚠️ There is no coverage for the uncommitted overlay (appendUncommittedNode, getUncommittedNode, cleanupUncommittedState). A small regression that rotates uncommitted memtables across a committed zxid would prove that the newest view still wins while obsolete memtables are cleaned up.
Final Verdict

Not ready. The abort-on-exception path in StorageState and the still-fallible flush publication path should be fixed before this storage layer is merged.

@antonio2368 antonio2368 self-assigned this Jun 11, 2026
@EmeraldShift

Copy link
Copy Markdown
Contributor

Interesting! Just out of curiosity, what's the motivation and design for the new storage? If it's an LSM tree it sounds maybe similar to RocksDB? How does it compare?

@al13n321

al13n321 commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor Author

(EDIT: Old comment, read PR summary instead.)

Why does everyone monitor draft PRs lol.

The main idea is: serialized znode can be much more compact than fixed-size in-memory structs, especially if a group of znodes is serialized together. Paths can be delta-compressed, stats (zxids, times, versions, etc) can be delta-compressed + group-varinted. E.g. znode version is usually 0; it takes 4 bytes in fixed-size struct, but can take 0.25 bytes in group varint; and paths have very long common prefixes (on average only ~1/5 of a path is the last component, see tool output in #106270 summary). The deltas can be relative to block header, so that we can deserialize any one node on demand if we have a pointer to the block and the node's offset inside the block.

We can have a hash map of all the nodes, but values would point to block+offset instead of a fixed-size struct. Reading a node is just one hashmap lookup and ~4 group varint decodes. So performance can be on par with current in-memory storage, with much less memory usage.

But if nodes can only be appended to blocks, we need some kind of background cleanup. Iterate over nodes in all blocks, skip obsolete ones, produce new blocks, delete old blocks; somehow synchronize all that with readers and don't block readers too much. I couldn't come up with such cleanup scheme that's good and much simpler than a full blown LSM tree. And a full blown LSM tree has benefits: can store blocks on disk, paths compress better because of sorting, memory usage mostly independent of dataset size (except for the big hashmap with pointers to all nodes; but we can later turn that map into a cache, falling back to rocksdb-like lookup in all memtables and files). Background flushes and merges should be almost free because keeper server only uses a few cpu cores, there are lots of free cores to do background work (though they would eat into memory bandwidth). So I think it makes sense to do a full-blown LSM tree. Seems easy enough.

I don't think rocksdb can get close to this performance, at least without heroic customizations and tuning. Its lookup checks all memtables, then all files (I'm guessing in keeper we often read znodes that weren't recently written, so would miss memtables? idk). Memtable is a skiplist by default, with pretty slow lookup; but a custom memtable type can be plugged in, we could implement a memtable with hashmap + children sets. In a file, lookup is binary search in the list of blocks, then lookup of the block in block cache, then binary search inside the block. We wouldn't be able to delta-compress stats relative to block header (but paths would be delta compressed sequentially, rocksdb does that for keys). (And we'd generally have less control, it would be harder to change things, there'd be much more code to dig through.)

@al13n321 al13n321 changed the title WIP new keeper storage New keeper storage Jun 26, 2026
@al13n321
al13n321 marked this pull request as ready for review June 26, 2026 07:33
@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jun 26, 2026
Comment thread src/Coordination/Storage/SortedFile.cpp Resolved
Comment thread src/Coordination/Storage/Memtable.cpp Resolved
Comment thread src/Coordination/Storage/Node.cpp Resolved

@antonio2368 antonio2368 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Interesting but complex. I understood the changes, but I will probably understand things better once I see how everything will be integrated.

Comment thread src/Coordination/Storage/SortedFile.cpp Resolved
Comment thread src/Coordination/Storage/SortedRun.cpp Resolved
@al13n321

al13n321 commented Jul 9, 2026

Copy link
Copy Markdown
Contributor Author

but I will probably understand things better once I see how everything will be integrated.

Integration is refactoring in #108583 + adapter like 2de0c33

Comment thread src/Coordination/KeeperCommon.cpp Resolved
@al13n321
al13n321 enabled auto-merge July 14, 2026 02:11
@al13n321
al13n321 enabled auto-merge August 1, 2026 00:14
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 1357/1594 (85.13%) · Uncovered code

Full report · Diff report

@al13n321
al13n321 added this pull request to the merge queue Aug 1, 2026
Merged via the queue into master with commit 20d0eb8 Aug 1, 2026
179 checks passed
@al13n321
al13n321 deleted the kdb branch August 1, 2026 06:04
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants