Skip to content

Fix a Keeper node silently ceasing to participate in Raft after a restart that replays local logs - #119463

Merged
antonio2368 merged 28 commits into
masterfrom
fix-keeper-raft-event-loop-wedged-by-log-replay
Oct 6, 2026
Merged

antonio2368 merged 28 commits into
masterfrom
fix-keeper-raft-event-loop-wedged-by-log-replay

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A Keeper node that restarts with log entries its state machine has not applied yet replays them before it accepts anything new from the leader. While it does, the node can stop being a Raft participant altogether while still looking alive:

  • no connection is accepted, no election or heartbeat timer runs, and no further RaftInstance line is logged
  • the process stays up on its other threads and keeps answering four-letter-word commands, so every liveness check passes
  • the node only rejoins when the replay finishes on the commit thread, which is not part of the pool that was consumed

Seen twice in production on a five-node cross-region ensemble, where the replay was slow enough to consume all sixteen threads in 80 s.

Root cause

KeeperServer::callbackFunc parked the calling thread in KeeperContext::waitLocalLogsPreprocessedOrShutdown - a condition_variable::wait with no deadline - for every append_entries request that carried entries and arrived before the replay was over. NuRaft invokes that callback inline on a thread of the pool that also carries the listener, the election and heartbeat timers and every RPC completion, and a leader force-reconnects a peer that stops answering. So one thread was consumed per reconnect until the pool was empty.

The invariant this breaks: no callback invoked from process_req may block for an unbounded time, because it runs on the Raft event loop. A slow replay must cost throughput, never the loop.

Fix

The wait is bounded, and the answer tells the leader to stop asking. The deadline is one
heartbeat less than the smaller of the two Raft limits, read from the values the instance is
running with: past the reconnect limit the leader replaces the connection and discards the
response, past the response limit the cluster counts the node as not responding, and the heartbeat
is margin because the leader's timer starts when it sends. When it expires the request is answered
rather than held, and GotAppendEntryReqFromLeader drops that request's entries, so which entries
may be appended does not change. Answering alone would turn the wedge into a hot loop - ~11000
requests per second on a local three node reproduction - so the response carries a negative
get_next_batch_size_hint_in_bytes, which is how NuRaft asks a leader to fall back to heartbeats,
and heartbeats carry the commit index the replay needs. The hint is computed where it is read:
local logs not preprocessed, and the commit index the leader already sent covering the whole
on-disk tail. A node whose tail diverges answers "keep sending", because it still needs a request
carrying entries to learn where the two logs match.

Only one thread may wait. Every other is turned away at once and its request handled to the
end, so the commit index it carries still lands and the pool cannot drain no matter how often the
leader re-sends. CurrentMetrics::KeeperRaftThreadsWaitingForLogsPreprocessing makes that visible,
since until now the only symptom was an absence of log lines, which nothing can alert on.

tests/integration/test_keeper_raft_event_loop_wedge covers the leader backing off, the divergent
tail still being reconciled, and - with the pause taken away and a failpoint holding one thread -
the wait ending on its deadline and the next thread being turned away. The timed wait itself,
including that shutdown ends it without claiming the logs were preprocessed, is a unit test.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed a Keeper node ceasing to participate in Raft after a restart that has to replay log entries. It stayed alive but outside the quorum until the replay finished.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1658-master (included in 26.10 and later)

A Keeper node that restarts with log entries its state machine has not
applied yet replays them before it accepts anything new from the leader.
While it does, `KeeperServer::callbackFunc` parked the calling thread in
`KeeperContext::waitLocalLogsPreprocessedOrShutdown`, a wait with no
deadline, for every `append_entries` request carrying entries.

NuRaft invokes that callback inline on a thread of the pool that also
carries the listener, the election and heartbeat timers and every RPC
completion, and a leader force-reconnects a peer that stops answering.
So one thread was consumed per reconnect until the pool was empty and
the node stopped being a Raft participant altogether: no accepts, no
timers, no further `RaftInstance` log line, while the process stayed
alive on its other threads and kept answering four-letter-word commands.
Observed in production on a five-node cross-region ensemble, twice,
where the replay was slow enough to consume all sixteen threads in 80 s.

The invariant this restores: no callback invoked from `process_req` may
block for an unbounded time, because it runs on the Raft event loop. A
slow replay must cost throughput, never the loop.

The wait now admits one thread at a time and gives it a deadline of
`heart_beat_interval_ms` times `raft_limits_response_limit`, the period
after which the leader stops expecting a response. Nothing about which
entries may be appended changes: giving up converges on the branch the
code already takes while the replay is far from done, where
`GotAppendEntryReqFromLeader` drops every entry of the request.

Declining quickly, on its own, turns the problem into a hot loop - the
follower answers "accepted" immediately and the leader immediately
re-sends, measured at ~11000 requests per second on a local three node
reproduction. So `get_next_batch_size_hint_in_bytes` now returns a
negative hint, which is how NuRaft asks a leader to fall back to
heartbeats, and heartbeats are what carry the commit index the replay
needs. The hint is armed only once the node knows its replay can finish
from what it already has: a node whose tail diverges from the leader's
still needs a request carrying entries to learn where the two logs
match, and pausing unconditionally would leave it unable to recover.

`CurrentMetrics::KeeperRaftThreadsWaitingForLogsPreprocessing` makes the
state visible, since until now the only symptom was an absence of log
lines, which nothing can alert on.

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

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9145254]

Summary: ✅


AI Review

Summary

This PR bounds the startup-time wait in Keeper's append_entries handling, asks the leader to fall back to heartbeats once the follower's on-disk tail can finish replay without more entry-bearing requests, and adds focused unit and integration coverage for timeout, divergent-tail, and snapshot-install paths. After reviewing the current diff and prior discussion, I do not see a remaining correctness, concurrency, or evidence gap that should block merge.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 9145254.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.20% +0.10%
Branches 79.70% 79.60% -0.10%

Changed lines: Changed C/C++ lines covered: 55/57 (96.49%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 11, 2026
Comment thread src/Coordination/KeeperServer.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-keeper ClickHouse Keeper (Raft-based coordination layer; ZooKeeper replacement) and ZooKeeper client lib... label Sep 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9145254ab with master b3916c57c (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 915744a54; 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.

Compile time of recompiled translation units

49 translation units recompiled, 351 s compile time in total, 49 of them have a recent master baseline.

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

Job report

@tiandiwonder
tiandiwonder marked this pull request as draft September 17, 2026 13:25
The negative batch size hint started out fed by a flag that each arm of
the `ProcessReq` switch assigned, which made the two assignments a
protocol: add a third arm, forget one of them, and the node either
silences the leader it needs or keeps a hot loop running. The flag also
latched - its only refresher was the traffic it suppressed, so once
armed, nothing short of the end of the replay was going to arrive and
reconsider it, and the assignment in the `else` arm existed only to
cover the case where the arm above had already armed it.

`get_next_batch_size_hint_in_bytes` is read on every append_entries
response, so it can just ask. `KeeperServer` installs the condition
before the Raft server starts, and it is evaluated where the answer is
used: local logs not preprocessed, and the commit index the leader has
already sent covers the whole on-disk tail. A node whose tail diverges
answers "keep sending" because the second half is false, rather than
because some earlier request happened to visit the right arm, and a
rolled back `get_target_committed_log_idx` is reflected at once instead
of waiting for a request that the pause is preventing. Both arms of the
switch go back to doing one thing each.

The tests gain the assertion that the hint works, which is what the fix
depends on in the ordinary case: no thread may ever find another one
already waiting, because the leader is paused before a second request
carrying entries can arrive. Both verification runs recorded zero such
refusals; only the intermediate version without the hint produced them,
44002 in a four second replay. If that line ever appears, the leader
kept sending at full speed and the one-thread cap became load-bearing,
which is how the wedge starts. The leader also has to stay paused: once
the node has given up and asked for heartbeats, no further request
carrying entries may arrive for the rest of the replay.
`test_divergent_local_logs_are_reconciled` gains the same refusal check
and the released-wait check the first test already had.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@tiandiwonder
tiandiwonder force-pushed the fix-keeper-raft-event-loop-wedged-by-log-replay branch from 834ad3f to ca453a9 Compare September 17, 2026 23:22
tiandiwonder and others added 3 commits September 18, 2026 09:28
Nothing exercised the refusal that enforces the bound, and nothing could:
the negative batch size hint stops the leader before a second request
carrying entries can arrive, so a run in which the hint works is a run in
which no thread ever finds another one already waiting. Both verification
runs recorded zero refusals; only the intermediate version of this fix,
which had the bounded wait but not the hint, produced them - 44002 in a
four second replay.

`nuraft_test_disable_append_entries_pause` takes the hint away for one
node, which is the only way to reach the state the bound exists for. It
is read once, where the condition is installed, so it costs nothing on
the response path. The setting is not for production use and says so,
following `nuraft_test_mode` in the same file.

The new test gives node2 a replay to do with the hint disabled, so the
leader re-sends every batch as fast as it is refused, and asserts that
threads really were turned away, that no more than one ever waited at a
time, that every wait was released, and that node2 still caught up -
which it can only do if a turned-away thread still lets the commit index
advance, the reason the request is handled to the end rather than
declined.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`wait_for` with a predicate returns the predicate, and the predicate also
holds on shutdown, so the caller logged `preprocessed=true` for a wait that
ended with the logs still unpreprocessed. Return the preprocessing state
itself: the value is only ever logged, but a trace line that says the
opposite of what happened is worse than none.

The deadline is the product of two coordination settings, so saturate it
the way `waitCommittedUpto` in the same file already does rather than
converting it raw - a large enough product overflows the conversion to the
clock's duration and the wait then ends immediately.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The deadline was the product of two raw coordination settings. Both are
bounded to `int32` where they enter NuRaft, but the settings themselves are
not, so a large enough pair could wrap the product before it reached the
saturating conversion - and after a runtime parameter change the settings no
longer say what the instance is actually running with.

Read them back the way `isClusterHealthy` and the responding-peer counts in
this file already do, from `get_current_params` and the Raft limits.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@tiandiwonder tiandiwonder changed the title Keep the Keeper Raft event loop running while local logs are replayed Fix a Keeper node silently ceasing to participate in Raft after a restart that replays local logs Sep 18, 2026
tiandiwonder and others added 16 commits September 18, 2026 01:56
The comment claimed that node2 catching up proves a turned-away thread let
the commit index advance. It does not: the admitted thread times out and has
its request handled to the end as well, so the catch-up is consistent with
the turned-away requests contributing nothing. It is still worth asserting -
a regression that dropped those requests instead of handling them would show
up here - but the comment should not promise a causal link the assertion
cannot carry.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The deadline was the whole of `response_limit_`, described as the period
after which the leader stops expecting a response. It is not that:
`response_limit_` is the window after which a peer counts as not
responding, which feeds leadership expiry and the snapshot sync context
timeout. What reacts to the silence on the `append_entries` path, and
re-sends, is `reconnect_limit_` - and once the leader has replaced the
connection, the response that would have carried the hint arrives on the
old one and is discarded as a stale RPC response, so the hint has to be
repeated a round trip later.

The deadline is now one heartbeat less than the smaller of the two.
Smaller, because both have to hold: answer before the leader replaces
the connection, and before the cluster counts this node as failed. One
heartbeat of margin, because the leader's timer starts when it sends and
this one when the request is received, so waiting for the whole limit
means answering after it has already expired. Counted in heartbeats
rather than as a fixed margin, because one heartbeat is 100 ms in the
integration test and subtracting a second from that underflows.

At the defaults this moves the deadline from 10 s to 9.5 s, `response_limit_`
20 being the smaller of the two. On the ensemble where this was observed,
which runs `raft_limits_reconnect_limit` 10, it moves from 10 s - past the
5 s reconnect, so the first response was always discarded - to 4.5 s.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Ten lines for four, two of which restated the `min` and the subtraction
below them. What is left is what the code cannot say: why reading the
running values rather than the settings, why the smaller of the two
limits, and why one less than it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Which thread runs it: private, one call site, and reaching the answer
means knowing that NuRaft invokes `raft_callback_` inline from
`process_req` on an asio worker. The rest of the paragraph said that one
thread waits and that it waits for a bounded time, which the two
statements under it already say.
Three things, all of them the same mistake in different places: an assertion
that is not synchronised with the condition it asserts.

`test_raft_event_loop_is_not_wedged_by_log_replay` required a thread to have
reached the wait and ended it on its deadline. Since the pause condition and
the arm that waits are the same predicate, the requests that would reach the
wait are exactly the ones the pause stops, so nothing here forces one to
arrive in that window. It failed twice in a row locally: the one request that
came took the `ignoring` arm at `get_target_committed_log_idx=0` against a
tail at 162, correctly, and the replay finished 0.48 s later. The
`waiting <= 1` loop passed vacuously on an empty event list, and the timeline
check would have raised `ValueError` from `max()` on it. All three are gone;
what stays is the part that does not depend on a wait happening, that the
leader backs off and that no thread is ever turned away.

`test_one_thread_waits_when_the_leader_is_never_paused` required two threads
at the wait at once. Taking the hint away lets the leader keep sending, but
the deadline is now one heartbeat less than the interval after which it
re-sends, so the overlap cannot be produced by timing at all - raising the
limits makes it strictly worse, since the reconnect then lands after the wait
has already ended. It recorded 0 refusals. A `PAUSEABLE` failpoint holds the
admitted thread with the slot taken, which is what the second thread has to
meet; it records 2842. The failpoint is enabled from the config, because the
first wait happens while the server is still coming up.

The deadline itself moves to a unit test, where it needs no cluster and no
timing: not preprocessed ends on the deadline and reports false, preprocessed
returns at once and reports true, and shutdown ends the wait but still reports
false - the last of which had no coverage at all.

Also restores the `__init__.py` that "Say what the catch-up assertion in the
unpaused test establishes" deleted: the file is empty, so `--stat` showed it
as `| 0`, which is what an unchanged file looks like, and the raw status that
would have said `D` was not read. `various_checks.sh` wants one per test
directory.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The deadline is one heartbeat less than the smaller of the response and
reconnect limits, and was floored at one heartbeat. Both settings accept 0 and
1 - the integration test runs `raft_limits_reconnect_limit` 1 - and at those
values the floor made the wait a whole heartbeat, which is the reconnect
interval itself. So the answer carrying the hint could go out exactly when or
after the leader had already replaced the connection and would discard it,
which is the thing this deadline exists to avoid. The defaults, 50 and 20, are
unaffected: they leave 19 heartbeats of margin.

It now waits for none of it in that case. Answering at once is what the
contract asks for when there is no margin, and a zero wait is already a state
this path handles - `heart_beat_interval_ms` 0 in the functional test config
produces one today, and it converges on the branch that drops the request's
entries.

The three test configs described the old derivation. They now say the wait is
none of it there, and that the bound on waiting threads is reached through the
failpoint rather than through this timing, which is what actually holds it.

Also drops the last causal claim from the catch-up comment in the unpaused
test: a later request carries the same commit index or a newer one, so the
node recovering does not establish which request got it there.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The derivation sat inline in the callback, which needs a running Raft instance
to reach, so nothing covered it: restoring the one-heartbeat floor it just lost
would have kept every test green. It has been wrong twice in this pull request
already - once taking `response_limit_` for the period after which the leader
stops expecting a response, once flooring the margin at a heartbeat - which is
reason enough to pin it.

`getLocalLogsPreprocessingWaitMs` now lives next to
`getValueOrMaxInt32AndLogWarning`, which narrows the same two settings, and
carries the reasoning that was in the callback. The arithmetic is unchanged.

The test covers both orderings of the two limits, the ordinary case, every way
the smaller one can be 0 or 1, and a zero heartbeat interval, which is what the
functional test config runs. Restoring the floor turns the 0 and 1 cases red,
checked by making that change and running them.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Of the three, the setting names itself and "not preprocessed" needs no
help. Why the leader's commit index covering the on-disk tail is the
safety condition does. The paragraph also argued that the answer has to
be computed rather than remembered, which the declaration of
`get_next_batch_size_hint_in_bytes` already says, and that the leader is
producing work that is thrown away, which is why the mechanism exists
rather than why this predicate is shaped this way.

The setting gets a line of its own; it had none, and its name alone does
not say that nothing but a test should set it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The condition reads as three conjuncts, and the code names all three.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The release was in the body, so it only ran when everything after it
passed. A paused failpoint is released by disabling it and by nothing
else - shutdown does not - so a failure before that line left an asio
worker waiting on `resume_cv` for good, and `raft_instance->shutdown()`
then joined a pool with a thread that never returns. The path most
likely to take it is the one that matters: the loop that gives up when no
thread ever reaches the admission gate, i.e. a real failure of this
test, whose cause would then be buried under a shutdown that timed out.

The release in the body stays, because it is not cleanup there - it lets
the thread go on to do a real bounded wait. Disabling a fail point that
is not enabled is a documented no-op, so running it twice is fine, and
the one in the handler swallows its exception: the server may already be
gone, and this must not replace the failure that got us here.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The description sat inside the body and the call site carried a second
copy of half of it. It reads better above the definition, and the two
things the function does - one waiter, bounded wait - are the summary
worth having there. What it said beyond that, that other callers return
at once and that the caller drops the entries either way, is visible at
both places it was written.

The two comments in the body go as well: what the failpoint is for and
where the limits are read from.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`nuraft_test_disable_append_entries_pause` existed only so one test
could reach the state the bound of one waiting thread is there for, and
coordination settings are not a private place to keep such a thing: the
`conf` four-letter-word command dumps every one of them, so it was
listed on every production node for anyone reading `conf` to wonder
about.

Fail points are the facility for this, and the same test already writes
a `<fail_points_active>` block into the config, so the second entry
costs nothing. Read inside the condition rather than once at install
time, because config fail points are applied in `Server.cpp` and this
does not depend on that happening before `launchRaftServer`.

Both fail points are now disabled in the teardown. The new one is not
paused, so nothing was holding a thread on it, but it stays enabled
until told otherwise and restoring the config only takes effect on the
next start - any test added after this one would have inherited a node
whose pause was off, with nothing to say so.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
All three nodes ran `raft_limits_reconnect_limit` 1, and the deadline is
one heartbeat less than the smaller of that and the response limit - so
it came out as nothing, and every one of these tests exercised a bounded
wait that never waited. The arithmetic has a unit test; the wait itself
had no coverage at all.

The limit decides two unrelated things on two different nodes: on the
node that replays it bounds that node's own wait, and on the leader it
decides how often the leader re-sends. So 3 on node2 alone buys a 100 ms
wait there while the leader keeps re-sending on its own 1.

That makes the wait and the leader's re-send interval both 100 ms, so
whether a second thread arrives while the first is waiting is a coin
flip rather than impossible. The fail point is what makes it certain, so
the test does not rest on that either way.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Extracting the derivation bought a test of two integers multiplied. What has
actually been wrong here twice is neither the multiplication nor the floor in
isolation: it was reading the raw settings instead of the values NuRaft is
running with, and the extracted function cannot tell the two apart - it is
handed whatever the caller chose. Nor can it show that the callback uses the
result. So the test covered the part that does not break and left the wiring
that does, which is worse than not having it, because it reads as coverage.

The arithmetic goes back next to its only caller. `KeeperCommon` is for helpers
with more than one call site or a boundary worth stating on its own; this is
two lines under the comment that explains them.

`WaitLocalLogsPreprocessedOrShutdown` stays: it exercises the timed wait
itself, including that shutdown ends it without claiming the logs were
preprocessed, which is a distinction this pull request got wrong once and which
nothing else covers.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The assertion that the wait ends on its deadline was dropped when it became
unreliable, and the failpoint that made the refusal certain is what keeps it
that way: parked from the first wait on, no wait ever runs its own course, so
`preprocessed=false` never appears. What survived asserts that a wait ended,
which an unbounded wait also does - the commit thread notifies it once the
replay is over - so it distinguishes nothing.

The two properties want opposite setups, so they get a phase each. First the
hint alone is taken away: the leader keeps sending, threads reach the wait one
after another with nothing holding them, and each comes back with the logs
still not preprocessed. Then node2 is killed, given a second tail, and brought
back with the failpoint armed from the start, so the first wait is held and the
next thread meets an occupied gate.

Neither phase has a window to lose. Arming the failpoint over SQL between the
two, in one replay, does: the replay is about a second here, ten waits of a
hundred milliseconds, and a poll plus a query costs as much - measured, the
refusal never arrived. This run records 8 waits ended on the deadline in the
first phase and 261 threads turned away in the second.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Three ways the waiting-thread bound could hold without meaning anything.

A line that matched the wait patterns but not the timestamp-and-thread regex
was skipped, so the count it belonged to came out short and the bound held on
what was left. It now fails, naming the line.

The count had an upper bound only. Going negative means the starts and stops
are not paired - a stop whose start was rotated away, say - which says the
picture is incomplete just as loudly as exceeding one says the pool is at risk.
Both loops now bound it from below too.

And in the unpaused test the list can be asserted non-empty, because there a
wait is certain: the failpoint holds one, so its start and its release are both
in the log. The other two tests cannot have that assertion - whether a request
reaches the wait there is the timing that the pause condition decides, which is
why they do not assert on the wait at all.

The final `waiting == 0` was already on both of the loops that had one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@tiandiwonder
tiandiwonder marked this pull request as ready for review September 18, 2026 12:53
Two assertions and one assumption, all of them timing.

`assert not grep_log(node2, ADMISSION_DECLINED)` in the first two tests says no
thread ever found the wait occupied. The reviewer pointed out that this is not
an invariant: the leader re-sends after `raft_limits_reconnect_limit`
heartbeats, 100 ms here, and the deadline is also 100 ms, so a second request
can arrive while the first waiter is still in the wait and log that line with
the fix working exactly as intended. Both are gone. What survives in the first
test is the refusal count staying flat, which is the hint working; the bound
itself belongs to the third test, where a failpoint makes it certain.

The third test's second phase was not certain either, which two runs under
load showed: one entry-bearing request in the whole window, no second thread,
no refusal. The tail is written before the restart, so it is one batch, and
the parked request takes it; what the leader sends afterwards carries no
entries and returns before the gate. The earlier passing runs were the leader's
retry cadence happening to re-send, which the test does not control.

So the test now writes while it waits. With entries to send, the leader sends
them, and the second thread arrives because something made it arrive: 38
refusals against 39 entry-bearing requests, on a machine at load 30, where the
previous construction produced one request and none.

Worth knowing when reading a failure here: the failpoint pauses before the
`waiting for preprocessing` line, so a parked thread logs nothing at all.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment on lines +108 to +131
def grep_log(node, pattern):
"""Lines matching `pattern` that the node logged since it was last started.

Every integration test runs with `rotateOnOpen`, so a start rotates the previous
`clickhouse-server.log` away and opens an empty one: the current file holds exactly the run
that is being looked at, and the whole of it. Addressing it by a line number taken before
the restart would point past the end of the new, shorter file and quietly match nothing.
"""
output = node.exec_in_container(
["bash", "-c", f"grep -E -- '{pattern}' {SERVER_LOG}; true"]
)
return [line for line in output.splitlines() if line]


def count_in_log(node, pattern):
"""Number of lines matching `pattern` since the node was last started.

Counted in the container rather than returned, because the run that disables the pause
produces tens of thousands of these.
"""
output = node.exec_in_container(
["bash", "-c", f"grep -E -c -- '{pattern}' {SERVER_LOG} || true"]
)
return int(output.strip() or 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.

Don't we already have helper functions for this?

A follower that restarts with a tail the new leader does not have rolls
`last_log_idx_on_disk` back to the last common index on the first request
carrying entries. When that index is already committed - a snapshot sits at it -
nothing but another such request runs `preprocess_logs`: `ProcessReq` returns on
empty entries and `StateMachineExecution` has nothing left to commit. The pause
condition armed right there, the leader fell back to heartbeats, and the node
never served again: 325 empty heartbeats in 60 s in
`test_start_without_zookeeper`. The pause now also requires something left to
commit locally.

Everything on disk can be committed without a commit announcing it in two ways -
a divergent tail rolled back onto the committed index, and a snapshot the leader
sends because it compacted past the node's tail. In both, only a request
carrying entries ends the replay, which is what the pause must not suppress.

Tests: `test_divergent_local_logs_over_a_snapshot_are_reconciled` puts the node
in exactly that state and fails 2/2 without the fix;
`test_replay_overtaken_by_an_installed_snapshot_is_finished` covers the snapshot
arm, with node1 and node3 keeping one log item so a `csnp` compacts them, and it
wedges without the fix too. The rollback test now asserts it reached that state
and ended it that way. The writer in
`test_one_thread_waits_when_the_leader_is_never_paused` starts before the
restart so the gate is reached, and the local log helpers give way to
`grep_in_log` / `count_in_log`, as asked in review.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119463&sha=b452b1c51f03f385a5b16550a912701ddd9afd6d&name_0=PR
PR: #119463

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Coordination/KeeperServer.cpp Resolved
Comment thread src/Coordination/KeeperServer.cpp Resolved
Comment thread src/Coordination/KeeperServer.cpp Resolved
Comment thread src/Coordination/KeeperServer.cpp Resolved
Comment thread src/Coordination/KeeperServer.h Resolved
tiandiwonder and others added 3 commits September 30, 2026 09:02
It predates this fix and the branch's meaning did not change, so rewording it
only widens the diff. Why that branch exists, and why a running commit is
excluded, belongs with the pause condition it mirrors.
…node waits, shorter comments

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Drop the note on the fail point: what a test needs from it belongs with the
test. State the condition in two lines - when to pause, and why not to once
everything is committed.
Comment thread src/Coordination/KeeperServer.cpp Resolved
@antonio2368

Copy link
Copy Markdown
Member

failure seems related

On slow builds the snapshot took long enough for node2 to step down
after losing its quorum, so the write came too late to be appended and
the test never created a divergence (`amd_tsan` and `amd_msan`,
targeted). `csnp` snapshots the committed index, so writing first does
not move it off the index the logs share.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@antonio2368
antonio2368 added this pull request to the merge queue Oct 6, 2026
Merged via the queue into master with commit e3d5930 Oct 6, 2026
294 of 295 checks passed
@antonio2368
antonio2368 deleted the fix-keeper-raft-event-loop-wedged-by-log-replay branch October 6, 2026 12:13
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 6, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Oct 7, 2026
Edited by the nightly changelog CI job following .claude/skills/edit-changelog/SKILL.md.

Changelog-revert: 123739 123588 Revert "Revert "Cancel vector similarity index builds when a merge or mutation is cancelled""
Changelog-revert: 124268 119463 Revert "Fix a Keeper node silently ceasing to participate in Raft after a restart that replays local logs"
Changelog-deleted-entry: 119463 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Fixed a Keeper node ceasing to participate in Raft after a restart that has to replay log entries. It stayed alive but outside the quorum until the replay finished. [#119463](#119463) ([Shaohua Wang](https://github.com/tiandiwonder)).
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-bugfix Pull request with bugfix, not backported by default 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.

3 participants