Skip to content

Keeper changelog read-ahead for catch-up and commit reads - #108473

Merged
antonio2368 merged 49 commits into
masterfrom
keeper-changelog-readahead
Aug 10, 2026
Merged

antonio2368 merged 49 commits into
masterfrom
keeper-changelog-readahead

Conversation

@antonio2368

@antonio2368 antonio2368 commented Jun 25, 2026 •

Copy link
Copy Markdown
Member

Reduces changelog_lock and NuRaft lock_ contention on Keeper changelog reads by decoupling read planning from disk I/O and pre-decoding entries ahead of the reader.

Lock-free disk reads (plan/execute split). Catch-up reads (log_entries / log_entries_ext) are split into a PLAN phase that resolves cache entries and disk locations into a LogReadPlan under a shared changelog_lock, and a lock-free EXECUTE phase that does the disk I/O. shared_ptr refs keep ChangelogFileDescription objects alive after the lock is released; a removed_from_disk flag keeps EXECUTE safe against concurrent compaction, and a truncation epoch discards any plan that straddles a concurrent write_at.

Per-peer catch-up read-ahead. When a follower issues log_entries_ext, the leader keeps a per-peer ReadAheadReader that decodes and buffers entries in a dedicated background thread pool. Subsequent requests from the same peer continue where decoding left off, avoiding redundant file reopens and re-decoding across contiguous append_entries rounds. NuRaft's log_store::log_entries_ext gains a peer_id parameter to route each peer's requests to its reader.

Commit read-ahead. The commit path (entry_at_ext) previously fell through to a random disk read per entry under log rotation. It now shares the same ReadAheadReader engine to batch sequential reads ahead of the commit thread.

New log_readahead_* coordination settings control both paths; commit_logs_cache_size_threshold, commit_logs_cache_entry_count_threshold, and latest_logs_cache_entry_count_threshold are now OBSOLETE. New ProfileEvents and CurrentMetrics expose read-ahead activity.

Changelog category (leave one):

  • Improvement

Changelog entry:

Keeper now reads changelog entries with less lock contention: catch-up reads plan under a shared lock and do disk I/O lock-free, and both follower catch-up and the commit path can pre-decode entries in a background thread pool, reducing redundant disk reads and CPU decoding on the leader.

Documentation entry

  • No documentation change required

Version info

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

antonio2368 and others added 10 commits June 19, 2026 14:49
Narrow `changelog_lock` contention on catch-up reads (`log_entries` /
`log_entries_ext`) by splitting the read into two phases:

**PLAN** (shared `changelog_lock`)
`LogEntryStorage::getReadPlan` resolves all cache entries and disk
locations into a `LogReadPlan` (a `std::variant<LogEntryPtr, FileRun>`
vector) while holding the lock.  `shared_ptr` refs keep
`ChangelogFileDescription` objects alive after the lock is released.

**EXECUTE** (lock-free)
`LogEntryStorage::executeReadPlan` performs the actual disk I/O without
any lock.  For uncompressed files it seeks to the stored byte offset and
reads directly.  For compressed files (`.bin.zstd`) it opens the file
through `wrapReadBufferWithCompressionMethod` and skips records
sequentially until the decompressed-stream position matches the stored
offset, then reads the required entries.

**Concurrent compaction safety**
`ChangelogFileDescription` gains a `bool removed_from_disk` flag guarded
by `file_mutex`.  `RemoveChangelog` sets it (under `withLock`) immediately
before calling `disk->removeFile`.  The EXECUTE phase re-checks the flag
under the same lock before opening each file; if set it returns `nullptr`
(NuRaft snapshot fallback), identical to the snapshot-compaction handling
that already existed.

**New data structures**
- `LogReadPlan` — transient plan struct with `FileRun` (coalesced
  contiguous records in one file) and `FillCursor` (Layer 2 placeholder).
- `PrefetchedCacheEntry` (stub) and `sealed` atomic on
  `ChangelogFileDescription` — Layer 2 read-ahead infrastructure,
  not yet wired.

**Fail-points**
Three PAUSEABLE fail-points (`keeper_changelog_read_plan_resolved`,
`keeper_changelog_removed_from_disk_set`,
`keeper_changelog_prefetch_pause`) allow race-condition tests to pause
between the PLAN and EXECUTE phases.

**Tests (6 new TYPED_TEST cases)**
A–D: unit tests for `getReadPlan` / `executeReadPlan` correctness,
size-limiting, `removed_from_disk` fallback, and the PLAN/EXECUTE split
timing (using fail-points and a background compaction thread).
E: end-to-end test verifying that evicted entries are still readable from
disk after reload with a 1-byte cache threshold (both compressed and
uncompressed).
F: TSan stress test — concurrent appends/rotations vs. active-file reads.

Co-Authored-By: Claude Sonnet (Claude Code) <[email protected]>
- NuRaft submodule (contrib/NuRaft): update submodule pointer to the
  in-tree commit that adds int32 peer_id = -1 to log_entries_ext base
  virtual + example update + call site passing p.get_id().
- KeeperLogStore.{h,cpp}: add NO_PEER_ID sentinel constant and update the
  override signature to match; peer_id is currently unused (L2 engage hook
  reserved for full read-ahead wiring in the next commit).
- Changelog.cpp (ChangelogWriter::setFile): publish sealed = true (release)
  on the just-finalized file AFTER to_log_index correction and move
  callback, NOT inside finalizeCurrentFile() — this is load-bearing for
  the EOF rule (a FILL acquire-load of sealed==true happens-after the
  final to_log_index write, making the plain read race-free).
- Changelog.cpp (readChangelogAndInitWriter): in the post-recovery loop,
  set sealed = true (release) for every historical complete non-broken
  file; the active file (start_index == latest_start_index) and
  broken_at_end files remain sealed = false.
- CoordinationSettings.cpp: add eight new off-by-default Layer 2 settings:
  keeper_log_readahead_enabled (false), _window_bytes (64 MiB),
  _max_peer_readers (8), _eviction_timeout_ms (30000), _pool_threads (0),
  _serve_wait_timeout_ms (50), _foreground_fallback (true), and
  keeper_log_read_request_timeout_ms (0).

NuRaft submodule note: the contrib/NuRaft edits are in-tree only. A
separate upstream NuRaft PR and submodule bump will be needed before
this can be merged into master.

Co-Authored-By: Claude Sonnet (Claude Code) <[email protected]>
…eads

Implements the core read-ahead logic that reduces NuRaft lock hold time
during follower catch-up by pre-decoding log entries on a background
thread pool and serving them to `log_entries_ext` from a warm deque.

Key components:
- `getReadAheadPlan`: walks changelog files building `FillCursor` list
  for sealed, non-`.zstd` files within `keeper_log_readahead_window_bytes`
  budget; gates on DD13 (window vs max_append_size) and .zstd presence
- `serveReadAhead`: Option-2 serve path — warm deque pop, then
  `cv.wait_until` deadline (`keeper_log_read_request_timeout_ms`),
  then direct-read fallback via L1; one `PerPeerReader` per follower
  with generation counter for non-sequential rewind detection
- `fillTask`: Direction-A open-reader fill loop (one `disk->readFile()`
  GET per sealed file, held across parks); detects file move/remove on
  resume via `opened_disk`/`opened_path` comparison; signals
  `fill_done_promise` exactly once at terminal exit
- `retireReaderLocked`: non-blocking terminal retire (no `fill_done.wait()`
  under lock so `serveReadAhead` can be called under NuRaft `lock_`)
- `setReadAheadSettings`: atomic snapshot update under `changelog_lock`
- Dedicated `ThreadPool` (`readahead_pool`) sized ≥ `max_peer_readers`;
  drained in `shutdown()` after joining all fill futures outside locks
- `KeeperLogStore::log_entries_ext` dispatches to L2 when
  `peer_id != NO_PEER_ID && isReadAheadEnabled()`; falls back to L1 path

Tests (88 passing: 11 L2 × 2 typed variants + 33 L1 × 2):
- `L2ReadAheadDisabledPathIdentical`: disabled flag uses L1 path
- `L2ReadAheadConcurrentAppend`: fill while appending entries
- `L2ReadAheadWedgedFillTimeout`: deadline fallback to direct-read
- `L2ReadAheadNonSequentialRewind`: rewind triggers new reader generation
- `L2ReadAheadCompactionDuringServe`: file removal during serve
- `L2ReadAheadShutdownJoinsFills`: shutdown drains all fill futures
- `L2ReadAheadSignatureOverride`: settings enable/disable round-trip
- `L2ReadAheadByteHintTruncation`: byte-hint limits serve output
- `L2ReadAheadServeWaitBound`: serve respects deadline
- `L2ReadAheadTerminalReaderReaping`: closed reader is evicted from map
- `L2ReadAheadTSanStress`: concurrent appends + multi-peer serves

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

- Replace `std::promise`/`shared_future` fill_done with `std::atomic<bool>`
- Remove hot-reload `setReadAheadSettings`; pass `ReadAheadSettings` at construction like `LogFileSettings`
- Wire all read-ahead coordination settings in `KeeperStateManager`
- Replace all-or-nothing deque wait with incremental pop loop in `serveReadAhead`
- Remove `fallback_waiting`, `foreground_fallback`, and the synchronous fallback path
- Add `reader_error` fallback to `executeReadPlan` for fill task decode failures
- Rename fields: `sealed`→`complete`, `ok`→`logs_compacted`, `reserve_hint`→`expected_entry_count`
- Rename `keeper_log_read_request_timeout_ms`→`keeper_log_readahead_fill_timeout_ms`
- Add `keeper_log_readahead_chunk_size` coordination setting
- Add `CurrentMetrics` for the read-ahead thread pool
- Use `TSA_REQUIRES`/`TSA_GUARDED_BY` annotations on read-ahead state
- Simplify and shorten comments throughout; remove internal design tag references

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
Comprehensive simplification of the per-peer decoded read-ahead subsystem
introduced alongside the Keeper changelog read-ahead feature. All changes
are behavior-preserving unless noted.

Lifecycle and state:
- Replace three overlapping "reader finished" signals (bool closed,
  ReaderTerminalState, std::atomic<bool> fill_done) with a single
  ReaderState enum {Running, Exhausted, Compacted, Error, Closed}.
  shutdown() now joins fill tasks via pool->wait() instead of per-reader
  fill_done.wait().
- Move PerPeerReader struct and ReaderState enum from Changelog.h into
  Changelog.cpp (forward declaration only in header).

Dead code and hot-path fixes:
- Delete unreachable getLogEntriesBetween overloads (~110 lines) that
  carried the original prefetch-wedge bug.
- Collapse the triple-discard in serveReadAhead's cache-item branch to a
  single discardBeforeLocked(current_index + 1) call.

Function decomposition:
- Break ~250-line serveReadAhead into ensureReadAheadPoolLocked,
  evictIdleReadersLocked (now O(n) with a size/time gate instead of O(n²)
  unconditional scan), acquireReaderLocked, installPlanLocked, drainReader.
- Break ~370-line fillTask into file-scope helpers: ensureOpenAt (returns
  OpenResult enum replacing three out-booleans), decodeChunk, appendChunk,
  fillFromCursor (returns CursorOutcome {Eof, Restart, Parked, Terminal}).

Resume cursor:
- Consolidate six scattered setResumeCursorLocked calls to a single
  canonical write at the top of each fillFromCursor iteration.
- Clear resume_cursor when installing new pending cursors (superseded).
- ensureOpenAt no longer writes resume_cursor.

Naming and conventions:
- Rename PerPeerReader fields: deque→decoded_entries, deque_front_index→
  decoded_front_index, deque_bytes→decoded_bytes, cv→fill_serve_cv.
- Add entryBytes() helper; use popFrontLocked() in discardBeforeLocked.
- Convert anonymous-namespace helpers to PerPeerReader methods with
  TSA_REQUIRES(deque_mutex) on Locked variants; add generationChangedLocked
  to centralize generation comparisons.
- Rename complete→sealed_for_read_ahead; add markSealedForReadAhead().
- Rename expected_entry_count→requested_entry_count.

Type system:
- Unify LogReadPlan::FileRun and FillCursor into FileSpan {file_description,
  position, first_index, count}. count=0 means read to EOF for fill cursors.
- Move fill cursors into optional<ReadAheadWindow> (alias for deque<FileSpan>)
  on LogReadPlan; readahead_engaged → read_ahead_window.has_value().
- Extract decodeOneRecord shared helper used by both executeReadPlan and
  decodeChunk.

Settings and docs:
- Fix misleading settings descriptions for fill_timeout_ms and window_bytes.
- Fix stale .zstd comment in getReadAheadPlan.
- Remove default argument from virtual log_entries_ext; extract
  buildPlanUnderLock lambda in KeeperLogStore.

Thread-safety annotations:
- Add TSA_REQUIRES(deque_mutex) to all PerPeerReader Locked methods.
- Document remaining TSA_NO_THREAD_SAFETY_ANALYSIS suppressions.

Tests:
- Remove "L2" prefix from all read-ahead test names.
- Rename ReadAheadDisabledPathIdentical→ReadAheadMatchesDirectPath; add
  genuinely-disabled case (ReadAheadSettings{.enabled=false}).
- Rename ReadAheadByteHintTruncation→DirectPathByteHintTruncation.
- Fix reader.detach() → reader.join() in ReadAheadShutdownJoinsFills.
- Fix missing ReadAheadSettings{} in gtest_coordination.cpp and
  gtest_coordination_snapshot.cpp constructors.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
… observability

installPlanLocked now avoids redundant fill rewinds when the fill is already
streaming the requested range:

- Add fillCoverageEndLocked() to PerPeerReader: the exclusive upper bound of
  indices the fill will produce unaided (cascades over pending_cursors back ->
  resume_cursor -> deque -> decoded_front_index, using each file's to_log_index
  since fill cursors read to EOF).

- installPlanLocked three-way classification (fill_timeout_ms == 0 only):
  backward rewind -> resetToIndexLocked; covered (decoded_front_index <= start
  < coverage_end) -> discardBeforeLocked + keep resume_cursor/pending_cursors
  so the fill continues uninterrupted; forward gap -> resetToIndexLocked.
  Append only genuinely-new cursors (first_index >= coverage_end) instead of
  overwriting the full window.

- For fill_timeout_ms != 0: reproduce the previous overwrite behavior verbatim.
  Under a deadline-park the fill re-enters takeNextCursor which returns
  pending_cursors.front() before resume_cursor; skipping the current file and
  appending only a later file would cause a non-contiguous appendChunk -> Error.
  The optimization requires a separate park-retake fix and is gated off for now.

getReadAheadPlan now derives fill cursors directly from plan.items FileSpan
entries (one open-ended cursor per unique sealed file at the first non-cached
position) instead of a redundant re-scan of logs_location. Physical gaps from
rolled-back entries (same file appearing as non-contiguous FileSpan items)
disable read-ahead for the entire request — reading to EOF at the gap position
would decode stale content with the correct log index.

Add three ProfileEvents for observability (mandatory for correctness tests
since appendChunk's overlap-skip makes wrong-content bugs invisible at the
output level):
- KeeperLogsReadAheadFillReopens: ensureOpenAt reopen/seek count
- KeeperLogsReadAheadFillDecodedEntries: entries decoded by the fill task
- KeeperLogsReadAheadCursorsInstalled: cursors installed by installPlanLocked

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
B1 — stale entries after writeAt:
Add closeAllReadersLocked() to LogEntryStorage and call it from cleanAfter
so any per-peer reader that has buffered entries from the rewritten range is
retired before the next request. Also clear sealed_for_read_ahead when a
previously-sealed file is reopened in WriteMode::Append so the planner does
not create fill cursors for an actively-written file.

B2 — use-after-free: fill task scheduled after shutdown:
Guard ensureReadAheadPoolLocked with an is_shutdown check. Since shutdown
sets is_shutdown before taking per_peer_readers_mutex and ensureReadAheadPoolLocked
runs under that mutex, the check is properly ordered: a late serveReadAhead
call that races with shutdown sees is_shutdown=true and skips pool creation,
preventing a fill task from capturing `this` after teardown.

M1 — executeReadPlan throws instead of returning nullptr:
Wrap the log_entries_ext body in try/catch and return nullptr on any
exception. NuRaft's log_entries_ext contract requires nullptr (not an
exception) when entries cannot be retrieved; NuRaft treats nullptr as a
signal to trigger snapshot fallback.

M2 — blocking scheduleOrThrowOnError under per_peer_readers_mutex:
Size the read-ahead pool queue to max_peer_readers regardless of pool_threads.
With queue_size < max_peer_readers and long-lived fill tasks occupying all
slots, scheduleOrThrowOnError (blocking) would deadlock while holding
per_peer_readers_mutex.

l1 — Exhausted reader tail discarded (optimality):
In acquireReaderLocked, keep an Exhausted reader when its decoded deque
still covers plan.start_index. installPlanLocked advances decoded_front_index
and returns early (no new cursors — fill is done). drainReader then serves
the buffered tail directly, avoiding a redundant disk re-read for sequential
requests where the fill outpaced the serve.

m1 — racy sleep in ReadAheadShutdownJoinsFills test:
Replace sleep_for(20ms) with FailPointInjection::waitForPause so the test
deterministically confirms the fill is wedged before releasing the failpoint.

m2/m3 — comment and doc fixes:
Correct "read to EOF" comments to "read to to_log_index" (the fill stops at
the file's last sealed logical index, not physical EOF). Update the eviction
timeout setting description to mention the ~2x worst case from the scan gate.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
Tests that the per-peer decoded read-ahead fires correctly when a lagging
follower joins a cluster that has written several sealed log files:

1. Start a 3-node Keeper cluster with a small log cache
   (latest_logs_cache_size_threshold = 10000 bytes) and file rotation every
   1000 entries, with keeper_log_readahead_enabled = true.
2. Stop node3, write 5000 znodes on the 2-node quorum via kazoo — produces
   at least 5 sealed log files on the leader.
3. Start node3 (empty log). It must stream all log entries from the leader
   via log_entries_ext to catch up.
4. Assert:
   - node3 can read back all 5000 znodes with correct values.
   - KeeperLogsReadAheadFillDecodedEntries > 0 on node3, confirming the
     per-peer fill task decoded entries from disk during catch-up.

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

clickhouse-gh Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d5a638d]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
04561_ie_join_storage_join FAIL cidb

AI Review

Summary

This PR splits Keeper changelog reads into a lock-light planning phase plus an out-of-lock execution/read-ahead phase, adds per-peer and commit read-ahead, and bumps NuRaft so follower identity reaches log_entries_ext. The direction is sensible, but the current head is not ready to merge: it regresses supported compress_logs=true deployments, can still serve stale pre-write_at entries from a closed reader, and silently drops existing cache-count limits. The new tests also still do not fully prove the promised behavior or performance gain.

Findings

❌ Blockers

  • [src/Coordination/Changelog.cpp:1177, src/Coordination/Changelog.cpp:1384, src/Coordination/Changelog.cpp:2231, src/Coordination/KeeperStateMachine.cpp:200] compress_logs=true is a supported Keeper mode, but the new disk-backed read paths now reject compressed changelog files once entries age out of latest_logs_cache. That turns follower catch-up into snapshot fallback, commit misses into NOT_IMPLEMENTED, historical entry_at / pack into hard failures, and local tail replay into LOGICAL_ERROR even though the log is still present on disk.
    Suggested fix: keep compressed changelog reads on a decompression-aware path, or teach the new planners/fillers to reopen via wrapReadBufferWithCompressionMethod and skip decoded records until the stored decompressed offset.
  • [src/Coordination/Changelog.cpp:2647] cleanAfter closes read-ahead readers on write_at, but drainReader still consumes decoded_entries before honoring ReaderState::Closed. An in-flight serve can therefore return pre-rewrite entries after the log has been truncated and replaced.
    Suggested fix: make Closed terminal before any deque pop, or clear the decoded deque when closing/resetting a reader.
  • [src/Coordination/CoordinationSettings.cpp:90-92, src/Coordination/CoordinationSettings.cpp:162-166] latest_logs_cache_entry_count_threshold and commit_logs_cache_entry_count_threshold used to be real memory caps; this PR now accepts them but ignores them, while only commit_logs_cache_size_threshold gets a migration path. Existing Keeper configs can therefore upgrade cleanly yet silently lose their configured entry-count limits.
    Suggested fix: preserve the old semantics, translate them into the new behavior, or reject the obsolete keys loudly at startup.

⚠️ Majors

  • [src/Coordination/Changelog.cpp:776, src/Coordination/Changelog.cpp:2327-2336] validateReadAheadSettings rejects log_readahead_pool_threads < log_readahead_max_peer_readers even when log_readahead_enabled=false and only the commit reader uses the pool. That makes commit-only configs like log_readahead_enabled=false, log_readahead_pool_threads=1 fail startup for no runtime reason.
    Suggested fix: gate that validation on peer read-ahead being enabled, or honor the explicit pool size for the commit-only pool too.

💡 Nits

  • [docs/guides/oss/deployment-and-scaling/keeper/index.mdx:87] The Keeper settings table still documents log_readahead_enabled as defaulting to false, while the code and test_keeper_four_word_command now use true.
    Suggested fix: update the docs to the shipped default, or keep the setting default-off if the rollout is still meant to be opt-in.
Tests
  • ⚠️ [tests/integration/test_keeper_readahead/test.py:140-146] The current pfev delta checks only prove that the fill task ran. They still pass if node3 catch-up warmed a cursor and then fell back to direct reads. Please also assert that KeeperLogsReadAheadTimeoutFallbacks stays flat, or check an equivalent signal that distinguishes true read-ahead service from timeout fallback.
  • ⚠️ [src/Coordination/tests/gtest_coordination_changelog.cpp:3640-3644] The compacted-range regression test should deterministically assert nullptr for [1, 6) after compact(20). Accepting a short non-null batch teaches the suite to allow a log_entries_ext contract violation and can hide the exact stale-reader bug this area is trying to catch.
  • ⚠️ The PR promises lower changelog_lock / NuRaft lock contention and less redundant disk decode work, but there is still no focused Keeper before/after measurement for catch-up or commit reads. The generic ClickBench green run is off-path for this code. A small reproducible benchmark or pfev/latency measurement on Keeper catch-up would close that gap.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.90% +0.10%

Changed lines: Changed C/C++ lines covered: 2993/3162 (94.66%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements submodule changed At least one submodule changed in this PR. labels Jun 25, 2026
const auto & path = file_run.file_description->path;
LOG_TRACE(log, "Reading from path {} {} entries", path, file_run.count);

auto raw_file = file_run.file_description->disk->readFile(path, getReadSettings());

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.

LogLocation::position for .bin.zstd files is produced while reading through wrapReadBufferWithCompressionMethod, so it is a decompressed-stream position. This plan execution path opens the raw file and seeks to that offset, and the read-ahead fill path does the same when it opens held_buf. After a restart with compress_logs=true and a small cache, evicted historical entries become FileSpans; reading from the raw zstd stream then decodes the wrong bytes and log_entries_ext returns nullptr, forcing snapshot fallback instead of log catch-up.

Please restore a compressed-file branch shared by executeReadPlan and the fill task (wrap the read buffer and skip decoded records until the stored position), or keep compressed spans out of these raw-read paths until they are supported.

Comment thread src/Coordination/KeeperLogStore.cpp Resolved
Comment thread src/Coordination/Changelog.cpp Resolved
Comment thread src/Common/CurrentMetrics.cpp Resolved
- Remove `LOGICAL_ERROR` error code declaration that was unused in `KeeperLogStore.cpp`
- Remove unnecessary `// namespace` comment from anonymous namespace in `Changelog.cpp`
- Log exception in `catch (...)` block when draining readahead pool on shutdown in `Changelog.cpp`
- Add `// Ok` comment to `catch (...)` in readahead test that passes `nullptr` to a promise on failure
- Remove `f` prefix from f-string literal with no placeholders in integration test

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
return fallback_from(item_idx, consumed);
}

if (!reader->decoded_entries.empty())

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.

cleanAfter closes all per-peer readers because entries after writeAt are stale, but drainReader still consumes decoded_entries before checking ReaderState::Closed. A log_entries_ext request can build its plan, release changelog_lock, then race with write_at; closeAllReadersLocked marks this reader Closed and erases it from the map, but the in-flight drainReader still has the shared_ptr and will pop buffered old entries here if decoded_front_index == needed_index. That can send pre-rewrite log entries after the log was truncated/replaced.

Please make Closed terminal before serving the deque, or clear the decoded deque in closeReaderLocked and force the in-flight request to return nullptr/rebuild instead of using stale buffered entries.

@antonio2368
antonio2368 marked this pull request as draft June 25, 2026 13:59
**Blocker: log_entries must not return nullptr**

`log_entries` was delegating to `log_entries_ext`, inheriting its
`catch (...) → nullptr` contract. Local callers such as
`KeeperStateMachine::preprocessUncommittedLogEntries` dereference the
result immediately without a null check. Implement `log_entries`
directly — plan under shared lock, execute without exception wrapping —
so failures propagate as exceptions rather than null pointers.

**Blocker: shutdown race / null readahead pool**

`is_shutdown` was a plain `bool` written in `shutdown()` before taking
`per_peer_readers_mutex`, while `ensureReadAheadPoolLocked` reads it
under that mutex — a data race (UB). Changed to `std::atomic<bool>`.

Additionally, if `shutdown()` set `is_shutdown` before the first call
to `serveReadAhead`, `ensureReadAheadPoolLocked` returns early without
creating the pool, then `acquireReaderLocked` unconditionally called
`readahead_pool->scheduleOrThrowOnError` on a null pointer. Added an
explicit null check in `acquireReaderLocked` that returns `nullptr`
(falling back to `executeReadPlan`) when the pool is absent after
shutdown races.

**Major: readahead thread-pool metrics missing from keeper_metrics**

`KeeperChangelogReadAheadThreads`, `KeeperChangelogReadAheadThreadsActive`,
and `KeeperChangelogReadAheadThreadsScheduled` were registered globally
but not added to `APPLY_FOR_KEEPER_METRICS`, so the `prometheus_keeper_only`
path omitted them. Added to `KeeperConstants.cpp`.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR changes only Keeper changelog read-ahead, coordination tooling, documentation, and CI config — none of which a ClickBench SELECT runs. Yet every one of the nine flagged ClickBench queries moved in the same slower direction (+6% to +27%), which for an off-path change points to run-to-run and co-location variance rather than a real regression. The Q16 and Q17 regressions are downgraded on that basis, and the remaining envelope-suppressed rows are consistent with the same reading. No flagged query exercises the modified code, so no action is needed.

clickbench

⚠️ 9 inconclusive

Flagged queries (9 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 723 825 +14.1% <0.0001 This PR only touches Keeper changelog read-ahead, coordination utilities, docs and CI config; a ClickBench aggregation SELECT never exercises that path, so +14.1% is off-path variance, not a real regression.
⚠️ 17 not_sure 468 575 +22.9% <0.0001 Same off-path story as Q16: a Keeper-only change cannot slow a ClickBench SELECT, so treat the +22.9% as run-to-run variance rather than a PR effect.
⚠️ 18 not_sure 1266 1454 +14.9% <0.0001 Envelope-suppressed and correctly left as not_sure: the +14.9% sits in master's variance band and the PR touches only Keeper code this query never runs.
⚠️ 28 not_sure 1036 1100 +6.2% <0.0001 Borderline with mixed signals from the two tests; the change is off-path for a Keeper-only PR, so not_sure is the right call.
⚠️ 30 not_sure 277 350 +26.4% <0.0001 Within master's variance band and off-path for this PR; the +26.4% is consistent with instance variance, not a Keeper change.
⚠️ 31 not_sure 386 471 +22.0% <0.0001 Envelope-suppressed correctly: +22.0% falls inside the current master band and this SELECT does not touch the changed Keeper path.
⚠️ 32 not_sure 1308 1664 +27.2% <0.0001 Within the variance band and off-path; the +27.2% is part of the same across-the-board slower shift, not a real regression.
⚠️ 33 not_sure 1238 1370 +10.7% <0.0001 Envelope-suppressed and off-path for a Keeper-only PR; +10.7% is consistent with run-to-run variance.
⚠️ 34 not_sure 1230 1358 +10.4% <0.0001 Same as Q33: within master's band and off-path, so +10.4% reads as instance variance.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 27c33124-f901-4efa-9f92-c61633d79995
  • MIRAI run: 076b59c9-142b-447f-881f-944480c67123
  • PR check IDs:
    • clickbench_145499_1786097173
    • clickbench_145505_1786097173
    • clickbench_145511_1786097173
    • tpch_adapted_1_official_145517_1786097173
    • tpch_adapted_1_official_145523_1786097173
    • tpch_adapted_1_official_145570_1786097173

antonio2368 and others added 5 commits June 25, 2026 19:48
Fix clang-tidy errors in `gtest_coordination_changelog.cpp`:
- Rename `/*batch_size_hint=*/` argument comments to match the actual
  parameter name `batch_size_hint_in_bytes` (`bugprone-argument-comment`)
- Add `// Ok` comment to the empty `catch (const DB::Exception &)` block
  in `ConcurrentAppendVsActiveFileRead` (`bugprone-empty-catch`)
- Cast `idx` to `size_t` before adding 1 in the stress test appender to
  avoid the misplaced-widening-cast warning (`bugprone-misplaced-widening-cast`)

Skip the compressed variant of `ActiveFileEvictedEntryStillReturned`:
`executeReadPlan` seeks using decompressed offsets recorded in `LogLocation`,
which does not work on raw `.bin.zstd` files. The compressed log path is
out of scope for this PR; skip the compressed type variant to keep CI green.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- `KeeperLogStore::log_entries`: add `TSA_NO_THREAD_SAFETY_ANALYSIS` to
  suppress the thread-safety-analysis warning when `executeReadPlan` is
  called outside the lock (lock-free execution is intentional; the plan
  was built while holding the lock)
- `KeeperLogStore.cpp`: fix argument comment `/*batch_size_hint_in_bytes=*/`
  → `/*max_size_bytes=*/` to match the actual parameter name
- `LogEntryStorage::shutdown`: use `is_shutdown.exchange(true)` instead
  of `std::exchange(is_shutdown, true)` — `std::atomic<bool>` is not
  copyable, so `std::exchange` triggers a compile error
- `gtest_coordination_changelog.cpp`: annotate the intentionally empty
  catch block with `NOLINT(bugprone-empty-catch)`

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108473&sha=latest&name_0=PR

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
… tests

`makeMemoryContextForSnapshotApply` no longer accepts a `rocksdb` path
argument (removed in master). Keep `DB::ReadAheadSettings{}` in the
`KeeperLogStore` constructor (still required by our branch).

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
… in sanitizers

With serve_wait_timeout_ms=100ms, drainReader would fall back to a direct
read before the fill thread got CPU time to reach the failpoint in slow
sanitizer (tsan/msan/coverage) builds. Once drainReader returned via
fallback, log_entries_ext returned quickly, but waitForPause on the main
thread was still blocked waiting for the fill to hit the wedge failpoint.
The fill eventually reached it — but the window between drainReader's
fallback return and the fill reaching the failpoint was wide enough in
sanitizer builds that the test framework timed out.

Fix: raise serve_wait_timeout_ms to 60 000 ms in this test so drainReader
always waits for the fill to deliver entries rather than falling back.
The fill delivers entries within milliseconds of disableFailPoint being
called, so the 60 s ceiling is never reached in practice.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108473&sha=e1b243bec5dd73336bc0c64ddd3bf1c27cf1b045&name_0=PR

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

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

The above comments are non-blocking, so LGTM

# Conflicts:
#	src/Common/CurrentMetrics.cpp
#	src/Common/FailPoint.cpp
#	src/Coordination/KeeperConstants.cpp
#	src/Coordination/tests/gtest_coordination_changelog.cpp
#	src/Coordination/tests/gtest_coordination_snapshot.cpp
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d5a638db8 with master 13262cad6 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 377d22737; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.17 MiB 687.41 MiB -2.76 MiB (-0.40%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

216 object files changed (+173.20 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Coordination/Changelog.cpp.o 764.70 KiB 868.73 KiB +104.03 KiB (+13.60%)
src/CMakeFiles/dbms.dir/Coordination/KeeperLogStore.cpp.o 62.19 KiB 92.28 KiB +30.09 KiB (+48.39%)

737 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

180 translation units recompiled, 454 s compile time in total, 45 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.07 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +20.3 s (+8%) in total before that adjustment.

Translation units without a recent master baseline:

  • contrib/nuraft-cmake/__/NuRaft/src/asio_service.cxx: 9.7 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp: 7.7 s
  • contrib/rocksdb-cmake/__/rocksdb/db/db_impl/db_impl_secondary.cc: 6.7 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/Target/AArch64/AArch64FastISel.cpp: 6.1 s
Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse ProfileEvents::global_counters_storage 11.00 MiB 11.06 MiB +64.00 KiB (+0.57%)
programs/clickhouse-keeper ProfileEvents::global_counters_storage 11.00 MiB 11.06 MiB +64.00 KiB (+0.57%)

Job report

Comment on lines +90 to +92
DECLARE(UInt64, latest_logs_cache_entry_count_threshold, 200'000, "Deprecated, has no effect. The latest logs cache is bounded by latest_logs_cache_size_threshold alone.", SettingsTierType::OBSOLETE) \
DECLARE(UInt64, commit_logs_cache_size_threshold, 500_MiB, "Deprecated. Used as the value of log_readahead_commit_window_bytes if that setting is not itself set.", SettingsTierType::OBSOLETE) \
DECLARE(UInt64, commit_logs_cache_entry_count_threshold, 100'000, "Deprecated, has no effect. Use log_readahead_commit_window_bytes instead.", SettingsTierType::OBSOLETE) \

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.

latest_logs_cache_entry_count_threshold and commit_logs_cache_entry_count_threshold used to be real cache limits, but this change turns them into accepted no-ops while only commit_logs_cache_size_threshold gets a migration path. That means an existing Keeper config can upgrade cleanly yet silently lose an explicit memory cap, allowing many more small log entries to accumulate up to the byte thresholds. Please either preserve the old semantics, translate the old count limits into the new behavior, or reject these obsolete keys loudly so operators do not get a silent rollout change.

Comment on lines +140 to +146
assert fill_decoded_after - fill_decoded_before > 0, (
"Expected KeeperLogsReadAheadFillDecodedEntries to increase across node1+node2 "
f"during catch-up, before={fill_decoded_before}, after={fill_decoded_after}"
)
assert cursors_installed_after - cursors_installed_before > 0, (
"Expected KeeperLogsReadAheadCursorsInstalled to increase across node1+node2 "
f"during catch-up, before={cursors_installed_before}, after={cursors_installed_after}"

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 two positive-delta checks here only prove that the fill task started at least once; they do not prove that node3's catch-up was actually served by read-ahead. drainReader increments KeeperLogsReadAheadTimeoutFallbacks when the batch is already served through the direct-read fallback, and ReadAheadTimeoutFallbackFastForwardsFill in the gtest suite exercises exactly that path. In that state both KeeperLogsReadAheadFillDecodedEntries and KeeperLogsReadAheadCursorsInstalled can still increase, so this test still passes even if catch-up degrades to direct disk reads after warming a cursor. Please also assert that KeeperLogsReadAheadTimeoutFallbacks stays flat (or check another direct-read/fallback signal) across node3 catch-up.

// Fully compacted range: nullptr is the expected steady-state result, but this must not crash or
// deadlock even if a reader still in flight hands back a short batch instead.
auto r3 = changelog.log_entries_ext(1, 6, 0, /*peer_id=*/6);
if (r3 != nullptr)

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.

NuRaft's log_entries_ext contract is to return nullptr if any entry in the requested range cannot be retrieved. After compact(20), [1, 6) is wholly below start_index(), so allowing a non-null short batch here teaches the test suite to accept a contract violation and can hide the race where a paused read-ahead reader leaks compacted entries instead of forcing snapshot fallback.

Please make this deterministic and assert r3 == nullptr here, using the existing compaction failpoints if needed.

@antonio2368
antonio2368 force-pushed the keeper-changelog-readahead branch from 03ead64 to d5a638d Compare August 7, 2026 14:11
@antonio2368
antonio2368 enabled auto-merge August 10, 2026 10:58
@antonio2368
antonio2368 added this pull request to the merge queue Aug 10, 2026
Merged via the queue into master with commit 6b7369f Aug 10, 2026
353 of 356 checks passed
@antonio2368
antonio2368 deleted the keeper-changelog-readahead branch August 10, 2026 11:19
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 10, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @antonio2368 @kssenii — a couple of suggestions to make this PR easier for reviewers and the changelog reader.

Description (currently incomplete):

  • Why: The body describes peer catch-up read-ahead as a new mechanism gated by the new log_readahead_* settings but never states which default it ships with. src/Coordination/CoordinationSettings.cpp:119 declares log_readahead_enabled as true (on by default for every Keeper after upgrade, including the new fill thread pool and up to log_readahead_max_peer_readers x log_readahead_window_bytes of decoded buffers), while the settings table added in the same diff (docs/guides/oss/deployment-and-scaling/keeper/index.mdx:87) documents the default as false and the new integration test enables it explicitly with the comment 'Enable read-ahead for the catch-up path'. The body also does not mention that latest_logs_cache_entry_count_threshold becomes inert.

  • Suggested addition:

    Please state the intended default for log_readahead_enabled: the declaration in src/Coordination/CoordinationSettings.cpp:119 is true, but the settings table added in this PR (docs/.../keeper/index.mdx:87) documents false, and tests/integration/test_keeper_readahead/configs/enable_keeper1.xml sets it explicitly ('Enable read-ahead for the catch-up path'). If on-by-default is intended, the docs row and the changelog entry should say so (it also enables the read-ahead thread pool and up to log_readahead_max_peer_readers x log_readahead_window_bytes of decoded buffers by default); if not, the declaration default should be flipped. Worth also noting in the changelog that latest_logs_cache_entry_count_threshold and commit_logs_cache_entry_count_threshold are now no-ops, so the in-memory log caches are bounded by size only.

Ignore this if the current title/body is intentional.

This branch was successfully deployed

1 active deployment
staging - docs — d5a638db Deployed Aug 7, 2026 by mintlify[bot]
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-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants