Skip to content

Keeper: put multiple requests into one nuraft log entry - #117436

Merged
al13n321 merged 35 commits into
masterfrom
kb
Nov 5, 2026
Merged

al13n321 merged 35 commits into
masterfrom
kb

Conversation

@al13n321

@al13n321 al13n321 commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Keeper serializes requests into nuraft log entries differently, with batching and more information stored. This increases throughput by 40% on some write-heavy workloads. Use coordination setting use_batched_log_entries to enable; all servers must first be updated to a version that supports it setting.


Changing log entry serialization format.

A few ideas:

  1. Put multiple requests in one log entry to amortize the per-entry overhead throughout nuraft. And to maybe make flow control easier to think about; e.g. maybe we'd make dispatcher target 300 batches/s, then tune all queue sizes etc with a steady 900 log entries per second (300 x 3 servers) in mind, without needing to predict client request rate.
  2. Put dispatcher server id in the log entry, then look at it when processing the (write) request to know whether we need to produce a response or not. To avoid allocating a response and sending it on a journey through responses_queue, only to discard it at the last moment because the client is connected to a different server.
  3. Put commit idx in log entry to avoid the weird localLogsPreprocessed dance on startup.

The 3 changes are not really related to each other, but it seems better to make all serialization changes at once instead of adding 3 new format versions.

In a small local benchmark, the (1) did nothing, but the (2) added +40% (!) throughput somehow. I didn't investigate why. For (3), this PR is writing the value, but its usage on startup is left to be implemented later as it requires all servers everywhere to be switched to the new serialization format before the localLogsPreprocessed code can be removed.


Workflow [PR]
Sync PR [sync-upstream/pr/117436]

Version info

  • Merged into: 26.11.1.1464-master (included in 26.11 and later)

al13n321 and others added 15 commits August 24, 2026 17:23
One list element per preprocessed batch (one Raft log entry) instead of one per request:
`TransactionInfo {zxid, digest, log_idx}` becomes `UncommittedBatchInfo {first_zxid,
last_zxid, digest, log_idx}`, and `uncommitted_transactions` becomes `uncommitted_batches`.

 * `preprocessOneRequest` creates the element for the batch's first transaction-creating
   request and extends it (`last_zxid`, `nodes_digest`) for subsequent ones, so
   `getNextZXIDLocked` and `getNodesDigest(false)` keep working mid-batch.
 * `tryMatchPreprocessedBatch` matches a single element by first/last transaction zxids and
   digest, instead of walking the tail.
 * On commit, `processRequest` validates the zxid against the front batch's range (plus a
   monotonicity check; skipped or reordered commits within a batch would additionally trip
   the delta order chassert), and pops the element / assigns the committed `nodes_digest`
   only when the batch's last transaction commits.
 * On rollback, the element is popped when the batch's first transaction is rolled back
   (requests are rolled back in reverse order).

Note that per-request digests are no longer recorded anywhere; digests are checked at batch
granularity (which matches what the batched log entry format stores anyway).

Also change `TestSystemNodeModify` to start at zxid 1: zxid 0 is reserved for "not assigned
yet" in `KeeperRequestBatch`, and real zxids start at 1.

Co-Authored-By: Claude Fable 5 <[email protected]>
The two remaining keeper-batch2 items:
 * The dispatcher stamps `dispatcher_server_id` on the batches it produces (both in
   `dispatchThread` and in the shutdown `Close`-requests path). Not used yet; see the
   TODO(keeper-batch3) about skipping response creation for foreign batches.
 * The leader patches `committed_log_idx` (a lower bound on the commit point) into the
   entry in the `PreAppendLogLeader` callback, next to `first_zxid` and the digest.
   Not used yet; see the TODO about removing the `localLogsPreprocessed` startup dance.

Also print both fields in `keeper-utils changelog-deserializer` text output.

Co-Authored-By: Claude Fable 5 <[email protected]>
Responses to committed requests are only needed on the server whose dispatcher produced
the batch (it owns the batch's client sessions); previously every server created them and
pushed them through its response queue, only to discard them in the response thread.

Now `KeeperStateMachine::commit` compares the batch's `dispatcher_server_id` against this
server's id (newly exposed as `KeeperContext::getServerID`) and passes a `produce_response`
flag down to `KeeperStorageImpl::processOneRequest`, which then skips building and queueing
the response for the request itself. Watch notifications are still produced unconditionally:
the watchers may be sessions owned by any server. `SessionID` responses are skipped in the
same way in the state machine's `SessionID` branch. If the owner is unknown
(`dispatcher_server_id == -1`, e.g. log entries in the old format), all servers produce
responses like before.

Verified with a 3-node smoke test: a changelog on one node contains batches from all three
dispatchers, i.e. each node commits the other nodes' batches through the skip path, while
all clients still receive their responses.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [def4e1c]

Summary: ✅


AI Review

Summary

The PR adds optional batching of Keeper requests into Raft log entries and suppresses direct responses on servers that do not own the originating dispatcher. No blocking correctness findings remain; the changelog names an obsolete setting. Review covered the new output's consumers: leader/follower preprocessing, startup and snapshot-tail replay, commit/rollback, both dispatchers, and keeper-utils; these handle batches directly or retain legacy serialization. The current Praktika report has no failed tests; validation here was static review, without a local build or test run.

PR Metadata

Performance Improvement is appropriate. The required changelog entry describes the benefit and upgrade order, but its activation instruction is incorrect. Replace the entry with:

Keeper can batch write requests into Raft log entries, improving throughput by up to 40% in a local write-heavy benchmark. Enable with the coordination setting write_log_entry_version = 1 after every server in the cluster has been upgraded to a version supporting the new log format.

Findings

💡 Nits

  • src/Coordination/CoordinationSettings.cpp:112 — The changelog references use_batched_log_entries, which is no longer registered. Following that instruction produces an unknown-setting exception. Use write_log_entry_version = 1 in the changelog.
Final Verdict

Status: ✅ Approve. Correct the changelog's setting name as a minor follow-up.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 1, 2026
Comment thread src/Coordination/KeeperStorage.cpp Resolved
Comment thread src/Coordination/KeeperStorageImpl.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing def4e1cb6 with master ec74a8554 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

23 object files changed (+80.96 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Coordination/KeeperCommon.cpp.o 155.07 KiB 204.35 KiB +49.28 KiB (+31.78%)
src/CMakeFiles/dbms.dir/Coordination/KeeperStorage.cpp.o 416.60 KiB 443.20 KiB +26.59 KiB (+6.38%)
src/CMakeFiles/dbms.dir/Coordination/KeeperStateMachine.cpp.o 758.71 KiB 777.87 KiB +19.16 KiB (+2.53%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

57 translation units recompiled, 362 s compile time in total, 56 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.4 s

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 1e58909c-6e49-4c94-bae3-9ca4735952b6
  • MIRAI run: b737ba40-3a7c-479e-8aba-db1efa482e8f
  • PR check IDs:
    • clickbench_1721158_1790298291
    • clickbench_1721462_1790298351
    • clickbench_1721575_1790298369
    • tpch_adapted_1_official_1721691_1790298384
    • tpch_adapted_1_official_1721793_1790298399
    • tpch_adapted_1_official_1721895_1790298406

@zlareb1

zlareb1 commented Sep 1, 2026

Copy link
Copy Markdown
Member

One hardening suggestion on the parsed-batch cache in parseRequestBatch.

A cache hit is keyed by the first request's (session_id, xid), and the only composition check on a hit is chassert(batch->requests.size() == request_count), after which update_patched_fields re-applies the entry's zxid/digest to the cached object and returns it. For the old single-request cache the key fully identified the payload, but a batch's head request does not determine which requests were batched behind it: a batch cached from the PreAppendLogFollower hook (final=false) for an entry that is later truncated on a leader change stays in the cache unless that entry also went through the rollback path, so if the same head (session_id, xid) is ever re-proposed in a differently composed batch, a release build would silently apply the stale composition instead of the log entry — and with keeper_server.digest_enabled defaulting to false there is no digest net to catch the divergence.

As far as I can tell this is unreachable today: the dispatcher drops in-flight requests on stream failure rather than re-sending them (the TODO in KeeperRequestDispatcher), and the cache only engages at min_request_size_for_cache. But the guard is one chassert away from a silent wrong-state path, and the trigger (request re-send) is an already-planned change. Falling back to a re-parse when batch->requests.size() != request_count — or erasing cached batches when their entries are truncated — would make the cache safe by construction rather than by the current dispatcher behavior.

@clickhouse-gh clickhouse-gh Bot added the comp-keeper ClickHouse Keeper (Raft-based coordination layer; ZooKeeper replacement) and ZooKeeper client lib... label Sep 4, 2026
@al13n321

al13n321 commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor Author

entry that is later truncated on a leader change

How does that happen? EDIT: Ok, I've read the next paragraph. Please use a better model or improve your prompt or have a human review the outputs or just refrain from posting comments like this.

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

Makes sense. The only question is how it would work with NuRaft. There are some locks taken while preprocessing and potentially while processing so same append size would now mean completely different amount of requests executed.

al13n321 and others added 4 commits September 14, 2026 15:50
`TestRequestBatchLogEntry` drives one batched log entry with several
requests through `KeeperStateMachine` the way `KeeperServer` does: the
leader parses the entry, assigns the zxid range and digest and patches
them in place, then runs `pre_commit` and `commit`; a follower applies
the patched entry and its digest must match. It also covers a batch
owned by another server's dispatcher (no responses except watch
notifications), rollback of a preprocessed multi-request batch with
reuse of the freed zxids, and rejection of a multi-request entry that
was never stamped with zxids.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Coordination/KeeperStateMachine.cpp Resolved
Comment thread src/Coordination/KeeperServer.cpp Resolved
@al13n321
al13n321 enabled auto-merge September 24, 2026 18:48
@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Dear @antonio2368, 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.

antonio2368 and others added 6 commits November 5, 2026 09:35
# Conflicts:
#	src/Coordination/KeeperStateMachine.cpp
#	src/Coordination/KeeperStateMachine.h
…nature

Tests added on master call `preprocessRequest` with the `digest` argument, which this
branch removed. Drop it, as the branch already did for the other calls.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n `onCommit`

- `KeeperRequestDispatcher::onCommit` gets the `dispatcher_server_id` of the committed
  request's batch (through `CommitCallback`). For a batch from another server's dispatcher it
  only handles `Close` and skips matching against the in-flight batches, which can never match.
  `-1` (unknown, legacy log entries) keeps the old behavior. Add a gtest.
- Replace the four copies of the zxid fallback for legacy log entries with
  `assignZxidToLegacyEntry`.
- `assertDigest` takes `std::string_view`.
- `KeeperRequestBatch::requests` uses `KeeperRequestsForSessions`.
- Fix comments: field order of `header_size`, `ZooKeeperLogSerializationVersion`,
  `patchSerializedRequestBatch`, and the end of `serializeRequestInOldFormat`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…entries` with `write_log_entry_version`

A batch log entry of format version `v` now starts with `INT64_MIN + v`, and the range
`[INT64_MIN, INT64_MIN + 2^16)` is reserved for batch formats (legacy entries start with a
session id, which is never in it). `parseRequestBatch` throws `UNKNOWN_FORMAT_VERSION` for a
version it does not support, instead of misparsing the entry as a legacy one. Before, the
comment said to change the marker for an incompatible format change, but any other marker
went to the legacy parser.

The boolean setting `use_batched_log_entries` becomes `write_log_entry_version` (0: one entry
per request, 1: batch format 1), like `write_snapshot_version`. It is validated on startup
and on hot reload.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With batched log entries only the server whose dispatcher produced the batch creates
responses. But `sessionCleanerTask` runs on the leader and sends the `Close` of an expired
session through the leader's dispatcher, while the session's connection can be on a
follower. That follower created no `Close` response, so its `KeeperTCPHandler` did not
exit and the client waited for its own timeout. Produce the `Close` response on every
server again, as before batched log entries. Add a step to `TestRequestBatchLogEntry`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ACE`

Each step of the test is now its own scope, so a failure names its step. Values that later
steps use are declared before the first step. No change in what the test checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
DECLARE(UInt64, log_slow_cpu_threshold_ms, 100, "Requests for which the CPU (preprocessing and processing) latency is larger than this settings will be logged", 0) \
DECLARE(UInt64, log_slow_connection_operation_threshold_ms, 1000, "Log message if a certain operation took too long inside a single connection", 0) \
DECLARE(Bool, use_xid_64, false, "Enable 64-bit XID. It is disabled by default because of backward compatibility", 0) \
DECLARE(UInt64, write_log_entry_version, 0, "Raft log entry format to write. 0: one log entry per request (readable by all versions). 1: one log entry per batch of write requests. Increase only after all servers in the cluster are upgraded to a version that supports the new format.", HOT_RELOAD) \

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.

💡 [P3] Use the supported setting in the changelog

The changelog still instructs users to enable use_batched_log_entries, but this revision registers write_log_entry_version instead. Following the published instruction would fail with an unknown setting. Please change the activation sentence to: “Enable with the coordination setting write_log_entry_version = 1 after every server in the cluster has been upgraded to a version supporting the new log format.”

@al13n321
al13n321 added this pull request to the merge queue Nov 5, 2026
Merged via the queue into master with commit 5fad0b4 Nov 5, 2026
186 checks passed
@al13n321
al13n321 deleted the kb branch November 5, 2026 21:54
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 5, 2026
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Nov 24, 2026
…ted job

ClickHouse#122111 made the targeted stateless and integration jobs SKIP instead of
ERROR when a test-selection CIDB request times out on every attempt
(`CIDBTimeoutError`). The first selection read, the strict previously-failed
lookup in `Targeting.get_previously_failed_tests_with_info`, re-wrapped any
exception as a plain `RuntimeError`, so a timeout there lost its class
before reaching either `except CIDBTimeoutError` handler and the shard
still ERRORed ("Failed to load test selection" in the stateless job, an
uncaught exception in the integration job). On a `pr-bugfix` PR that drops
`Bugfix validation` and fails `Finish Workflow / Post Hooks`.

Re-raise `CIDBTimeoutError` unchanged in strict mode. Every other failure
(a refused connection, an answered non-OK response) stays wrapped and keeps
failing the job, as ClickHouse#114730 intends. Best-effort mode is unchanged.

CIDB shows 3 such errors, all on 2026-09-24/25 during the CIDB overload
ClickHouse#122111 targets (PRs ClickHouse#118823, ClickHouse#117436, ClickHouse#114865).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-keeper ClickHouse Keeper (Raft-based coordination layer; ZooKeeper replacement) and ZooKeeper client lib... pr-performance Pull request with some performance improvements 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.

4 participants