Repository navigation
Keeper changelog read-ahead for catch-up and commit reads - #108473
Conversation
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]>
|
Workflow [PR], commit [d5a638d] Summary: ❌
AI ReviewSummaryThis 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 Findings❌ Blockers
💡 Nits
Tests
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 2993/3162 (94.66%) · Uncovered code |
| 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()); |
There was a problem hiding this comment.
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.
- 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()) |
There was a problem hiding this comment.
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.
**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]>
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (9 of 43)
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
|
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
left a comment
There was a problem hiding this comment.
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
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 sizes216 object files changed (+173.20 KiB total), 0 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units180 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. Translation units without a recent master baseline:
Symbol sizes
|
| 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) \ |
There was a problem hiding this comment.
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.
| 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}" |
There was a problem hiding this comment.
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.
Add the missing ReadAheadSettings argument required by KeeperLogStore.\n\nCI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108473&sha=1138e42503f8e94ded4682be29c24d311cdc5814&name_0=PR&name_1=Build%20%28arm_tidy%29\nRelated: #108473
Record the CI report and related pull request as separate paragraphs. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108473&sha=1138e42503f8e94ded4682be29c24d311cdc5814&name_0=PR&name_1=Build%20%28arm_tidy%29 Related: #108473
| // 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) |
There was a problem hiding this comment.
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.
03ead64 to
d5a638d
Compare
|
Hi @antonio2368 @kssenii — a couple of suggestions to make this PR easier for reviewers and the changelog reader. Description (currently
Ignore this if the current title/body is intentional. |
Reduces
changelog_lockand NuRaftlock_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 aLogReadPlanunder a sharedchangelog_lock, and a lock-free EXECUTE phase that does the disk I/O.shared_ptrrefs keepChangelogFileDescriptionobjects alive after the lock is released; aremoved_from_diskflag keeps EXECUTE safe against concurrent compaction, and a truncation epoch discards any plan that straddles a concurrentwrite_at.Per-peer catch-up read-ahead. When a follower issues
log_entries_ext, the leader keeps a per-peerReadAheadReaderthat 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 contiguousappend_entriesrounds. NuRaft'slog_store::log_entries_extgains apeer_idparameter 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 sameReadAheadReaderengine 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, andlatest_logs_cache_entry_count_thresholdare nowOBSOLETE. NewProfileEventsandCurrentMetricsexpose read-ahead activity.Changelog category (leave one):
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
Version info
26.8.1.1086(included in26.8and later)