Skip to content

Keeper: run consecutive read requests in parallel - #100778

Merged
al13n321 merged 28 commits into
masterfrom
parallel-reads
Apr 11, 2026
Merged

al13n321 merged 28 commits into
masterfrom
parallel-reads

Conversation

@al13n321

@al13n321 al13n321 commented Mar 26, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Closes #95937
Closes #95938

If there are multiple read requests in a row, run them in multiple threads. Also applies to subrequests inside MultiRead. Watch manipulation is done separately in one thread.

On a local benchmark with mostly reads and a little writes I got 3.5x speedup (17.5k -> 63k read requests/s, mostly multireads). (keeper-bench config: https://pastila.nl/?00c54ccf/3a1344ec00ea197e7cc9ff44a6f7e5c5#+Z0DiSttp+fmd42D61UWMw==GCM + #100670 , keeper server config: https://pastila.nl/?00a5d52e/744ccab4edd77252f940cb85aadf86bd#BjZhlCPmFgu3zCzv4Zttlg==GCM )

I also tried disabling parallel reads and comparing to a build without this PR, to see if the added overhead of preparing tasks is noticeable. There was no significant difference; actually it got a little faster: 17.2k/s -> 17.5k/s (doesn't feel statistically significant, relative to variance between runs), presumably because the slowdown is outweighed by the speedup from the added batching of reads (read_batch in KeeperDispatcher).

Version info

  • Merged into: 26.4.1.834

@clickhouse-gh

clickhouse-gh Bot commented Mar 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5778d67]

Summary: ❌
Keeper Stress Tests (PR): Grafana: Run details (this run), Grafana: 1vs1 Comparison, Grafana: Historical progression

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, flaky check) failure
00352_external_sorting_and_constants FAIL cidb

AI Review

Summary

This PR batches consecutive Keeper read requests and executes the thread-safe part in parallel, including MultiRead subrequests, with new coordination settings for read batching/threading. The performance goal is clear and potentially impactful, but there are correctness/concurrency issues in the current implementation that should be fixed before merge.

PR Metadata
  • ⚠️ Changelog category is currently Not for changelog, but this PR introduces a user-visible performance feature and multiple new Keeper settings (max_read_batch_size, max_read_batch_bytes_size, parallel_read_threads, parallel_read_chunk_size, parallel_read_min_batch).
  • ⚠️ A changelog entry should be present and specific.

Suggested replacement:

  • Changelog category: Performance Improvement
  • Changelog entry: Keeper now batches consecutive local read requests and can process thread-safe reads in parallel (including subrequests in MultiRead), controlled by new coordination settings: max_read_batch_size, max_read_batch_bytes_size, parallel_read_threads, parallel_read_chunk_size, and parallel_read_min_batch.
Findings

❌ Blockers

  • [src/Coordination/KeeperStorage.cpp:4011] session_and_timeout is accessed without storage_mutex in processLocalRequests; this path now runs in parallel with request processing, while other code erases entries on close. This is a data race on std::unordered_map and can lead to undefined behavior.

    • Suggested fix: guard session_and_timeout access with the same mutex discipline used for concurrent readers/writers (or avoid map access on this path by passing validated timeout/session metadata in request context).
  • [src/Coordination/KeeperStateMachine.cpp:~1470-1500] processReadRequests assumes every response has a non-null request for non-watch responses, but processLocalRequests can emit extra responses from SetWatch/SetWatch2 where request == nullptr. The chassert / dereference path is unsafe.

    • Suggested fix: handle request == nullptr responses explicitly before initializing queue spans; do not dereference null request.

⚠️ Majors

  • [src/Coordination/KeeperDispatcher.cpp:456-473] The code contains a TODO describing known correctness gaps (missed failures across multiple forceWaitAndProcessResult, read-after-write ordering violations, and response ordering hazards under async replication) while executing the path unconditionally.

    • Suggested fix: either harden this path before merge or gate it behind a setting disabled by default until guarantees are enforced.
  • [src/Coordination/KeeperReadThreadPool.cpp:57-72] running_threads is incremented before scheduleOrThrowOnError; if scheduling fails, counters become inconsistent and subsequent scheduling/coordination can misbehave.

    • Suggested fix: increment running_threads only after successful scheduling, or decrement it in the exception path before abort/propagation.

💡 Nits

  • [src/Coordination/KeeperReadThreadPool.h] Remove leftover internal review-note comments (asdqwe ...) from committed header text.
  • [src/Coordination/KeeperDispatcher.cpp] Typo in comment: checke -> check.
  • [src/Coordination/KeeperStorage.cpp / src/Coordination/KeeperStateMachine.cpp / src/Server/KeeperTCPHandler.cpp] Rename opentelemetery identifiers to opentelemetry for consistency and searchability.
  • [src/Common/CurrentMetrics.cpp] Typo in metric description: Meningless -> Meaningless.
  • [src/Coordination/CoordinationSettings.cpp] New read-parallelization settings are added but not emitted in KeeperConfigurationAndSettings::dump, which hurts diagnostics parity.
Tests

⚠️ Add coverage for mixed SetWatch/SetWatch2 batches in processLocalRequests to validate response shaping when extra watch notifications are produced (including null-request response entries).

⚠️ Add concurrency regression coverage for session expiration/close racing with parallel local reads to ensure no unsynchronized access to session-timeout state.

⚠️ Add ordering/consistency tests for sequences of write batches with dependent local reads to validate read-after-write and response ordering under async replication edge cases called out in the TODO.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ⚠️ Keeper core path has unresolved correctness TODO in active execution path.
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ⚠️ Parallel read execution changes ordering/consistency-sensitive behavior; unresolved edge cases documented in code.
SettingsChangesHistory.cpp ➖
PR metadata quality ⚠️ Changelog category/entry do not match user-visible feature and new settings.
Safe rollout ⚠️ Known unresolved consistency/order issues in comments indicate rollout risk.
Compilation time ✅
No large/binary files ✅
Performance & Safety

The intended throughput improvement is promising, but safety/correctness concerns (unsynchronized shared state, null-request handling, and unresolved ordering guarantees) currently outweigh performance gains for merge readiness.

Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Fix the session_and_timeout synchronization bug in parallel local reads.
    • Fix null-request response handling in processReadRequests.
    • Resolve (or safely gate) the documented ordering/consistency gaps in the parallel read-after-write flow.
    • Correct changelog metadata to match user-visible behavior.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Mar 26, 2026
Comment thread src/Coordination/KeeperReadThreadPool.h Resolved
Comment thread src/Coordination/KeeperDispatcher.cpp Resolved
@antonio2368 antonio2368 self-assigned this Mar 26, 2026
/// Bump session expiry times along the way.
if (session_id != prev_session_id)
{
session_expiry_queue.addNewSessionOrUpdate(session_id, session_and_timeout[session_id]);

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.

session_and_timeout is accessed here without storage_mutex, but this function now runs in parallel with request processing and session_and_timeout can be erased on close (processRequest, same file, session_and_timeout.erase(session_id)). std::unordered_map does not support concurrent read/write, so this is UB (data race / possible iterator-bucket corruption).

Please read timeout under storage_mutex (or make this map access synchronized another way) before calling session_expiry_queue.addNewSessionOrUpdate.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

(No, session_and_timeout.erase(session_id) is not in a read request, let alone any of the requests in is_request_thread_safe list.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

What, no, (a) session_and_timeout seems to be protected by process_and_responses_lock, which is locked here, (b) "this function now runs in parallel with request processing" - it doesn't.

@al13n321
al13n321 requested a review from antonio2368 March 28, 2026 09:07
@al13n321
al13n321 marked this pull request as ready for review March 28, 2026 09:07
Comment thread src/Coordination/KeeperStateMachine.h Resolved
Comment thread src/Coordination/KeeperStateMachine.cpp Resolved
Comment thread src/Coordination/KeeperStorage.cpp Resolved
DECLARE(UInt64, max_requests_batch_bytes_size, 100*1024, "Max size in bytes of batch of requests that can be sent to RAFT", 0) \
DECLARE(UInt64, max_read_batch_size, 100000, "Max size of batch of consecutive read requests that can be executed at once, possibly in parallel", 0) \
DECLARE(UInt64, max_read_batch_bytes_size, 10000000, "Max size in bytes of batch of consecutive read requests that can be executed at once, possibly in parallel", 0) \
DECLARE(UInt64, parallel_read_threads, 8, "Number of threads for parallel local read request processing. 0 means disabled.", 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.

The PR adds new coordination settings (max_read_batch_size, max_read_batch_bytes_size, parallel_read_threads, parallel_read_chunk_size, parallel_read_min_batch) in LIST_OF_COORDINATION_SETTINGS, but KeeperConfigurationAndSettings::dump doesn't emit them. As a result, conf/diagnostics output silently omits active values, which makes production debugging and config drift analysis harder.

Please extend dump to include these settings, consistent with existing settings serialization.

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.

Please do

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Is there a reason dump doesn't just iterate over the settings (BaseSettings::all()) and print all of them?

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.

It seems it can do that

@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

Comment thread src/Coordination/KeeperDispatcher.cpp Resolved
@al13n321

al13n321 commented Apr 8, 2026

Copy link
Copy Markdown
Contributor Author

flaky check: #102116

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

Cool

DECLARE(UInt64, max_requests_batch_bytes_size, 100*1024, "Max size in bytes of batch of requests that can be sent to RAFT", 0) \
DECLARE(UInt64, max_read_batch_size, 100000, "Max size of batch of consecutive read requests that can be executed at once, possibly in parallel", 0) \
DECLARE(UInt64, max_read_batch_bytes_size, 10000000, "Max size in bytes of batch of consecutive read requests that can be executed at once, possibly in parallel", 0) \
DECLARE(UInt64, parallel_read_threads, 8, "Number of threads for parallel local read request processing. 0 means disabled.", 0) \

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.

Please do

Comment thread src/Coordination/KeeperCommon.h Resolved
Comment thread src/Coordination/KeeperStorage.cpp Resolved
Comment thread src/Coordination/KeeperStorage.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

The flaky check failure is fixed in #102148, let's update the branch.

Comment thread src/Coordination/KeeperDispatcher.cpp Outdated
return false;

server->putLocalReadRequest(request_info);
server->putLocalReadRequests({request_info});

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.

KeeperOverDispatcher registers callbacks before calling putLocalReadRequest. With this new behavior, putLocalReadRequest can now return false (e.g. no callback/live-session entry) without throwing, and all callers in KeeperOverDispatcher ignore the return value. That leaves the callback in callback_state->callbacks forever and no response is ever sent.

This is a real behavior regression: before this PR local reads always enqueued, now they can be dropped silently.

Please either (a) keep old behavior for local reads by throwing on failure (like putRequest), or (b) make all KeeperOverDispatcher::{exists,get,list,check,getACL} call sites handle false by erasing the registered callback and invoking it with an explicit error response.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Unrelated to this PR, but fixed.

@al13n321
al13n321 enabled auto-merge April 11, 2026 02:18
@clickhouse-gh

clickhouse-gh Bot commented Apr 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.00% +0.00%
Functions 90.90% 90.90% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 81.75% (748/915) | lost baseline coverage: 97 line(s) · Uncovered code

Full report · Diff report

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.

Split Keeper MultiRead requests into multiple smaller requests Parallel execution of read requests in Keeper

4 participants