bug: snapshot recovery hangs forever when a region can never become leader
Bug Report
Summary
LeaderKeeper::elect_and_wait_all_ready drives the second phase of BR snapshot recovery. It loops until every requested region becomes a leader in the local store, sleeps 10 seconds between rounds, and has no deadline, no retry limit, and no failure path. RecoverRegion answers the client only after this loop returns. When one region can never become leader, failed_leader stays non-empty forever, so the loop retries indefinitely and the RPC never returns. BR then waits in the recover-region phase with no error and no timeout. Two conditions produce a region that can never become leader: the region is absent from the store FSM registry, in which case both the leader probe and the forced campaign route to RegionNotFound, or the peer is present but its campaign never wins, in which case the failed campaign result is discarded inside the peer FSM.
What version of TiKV are you using?
I reproduced this on master at commit 7709ab9d738d16f856df990ad9ffb5c1908f84f8 (2026-09-29). Any build that contains components/snap_recovery/src/leader_keeper.rs with the same election loop is affected.
What operating system and CPU are you using?
Linux x86_64 with cargo +nightly-2026-03-21. The defect is a control-flow issue in the recovery service and does not depend on the OS or the CPU.
Steps to reproduce
- Start a store in BR snapshot recovery mode.
RecoverDatais registered only in that mode (components/server/src/server.rs:1427–1433). - Start a
RecoverRegioncall whose region list contains a region that cannot become leader locally. BR builds this list from the region metadata it collected earlier, so a region that was merged or destroyed after collection is one plausible case. - The handler reads the client stream, builds a
LeaderKeeper, and runselect_and_wait_all_ready. - For the failing region,
check_leaderreturnsRegionNotFoundor a header error, andforce_leadereither returnsRegionNotFoundor succeeds without ever making the peer a leader. The region is pushed tofailed_leaderon every round. - The loop sleeps 10 seconds and repeats forever.
RecoverRegionnever reachessink.successorsink.fail, so the client waits with no response.
The unit test below starts the real LeaderKeeper against a router whose leader probe always fails and whose campaign never succeeds. It asserts that elect_and_wait_all_ready does not return within 13 seconds, and that the loop retried and issued campaigns in that window.
cargo +nightly-2026-03-21 test -p snap_recovery --lib \
poc_elect_wait_never_returns -- --nocapturecomponents/snap_recovery/src/leader_keeper.rs, inside the #[cfg(test)] mod test module)#[cfg(test)]
mod f4_poc_elect_wait_forever {
use std::{
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
time::Duration,
};
use engine_rocks::RocksEngine;
use engine_traits::KvEngine;
use raftstore::store::{CasualRouter, SignificantRouter};
use tikv_util::future::block_on_timeout;
use super::LeaderKeeper;
struct NeverReadyStore {
leader_checks: Arc<AtomicUsize>,
campaigns: Arc<AtomicUsize>,
}
impl<EK: KvEngine> SignificantRouter<EK> for NeverReadyStore {
fn significant_send(
&self,
_region_id: u64,
msg: raftstore::store::SignificantMsg<EK::Snapshot>,
) -> raftstore::errors::Result<()> {
self.leader_checks.fetch_add(1, Ordering::SeqCst);
if let raftstore::store::SignificantMsg::LeaderCallback(cb) = msg {
let mut resp = kvproto::raft_cmdpb::RaftCmdResponse::default();
let mut err = kvproto::errorpb::Error::new();
err.set_not_leader(kvproto::errorpb::NotLeader::new());
resp.mut_header().set_error(err);
cb.invoke_with_response(resp);
}
Ok(())
}
}
impl<EK: KvEngine> CasualRouter<EK> for NeverReadyStore {
fn send(
&self,
_region_id: u64,
msg: raftstore::store::CasualMessage<EK>,
) -> raftstore::errors::Result<()> {
if let raftstore::store::CasualMessage::Campaign(_) = msg {
self.campaigns.fetch_add(1, Ordering::SeqCst);
}
Ok(())
}
}
// The election loop has no deadline and no failure path: a region that can
// never become ready keeps `failed_leader` non-empty forever.
#[test]
fn poc_elect_wait_never_returns() {
let leader_checks = Arc::new(AtomicUsize::new(0));
let campaigns = Arc::new(AtomicUsize::new(0));
let store = NeverReadyStore {
leader_checks: Arc::clone(&leader_checks),
campaigns: Arc::clone(&campaigns),
};
let mut lk = LeaderKeeper::<RocksEngine, _>::new(store, vec![7u64]);
let timed_out =
block_on_timeout(lk.elect_and_wait_all_ready(), Duration::from_secs(13)).is_err();
assert!(timed_out, "elect_and_wait_all_ready must not return");
assert!(leader_checks.load(Ordering::SeqCst) >= 2);
assert!(campaigns.load(Ordering::SeqCst) >= 2);
}
}What did you expect?
The recovery service should either bring every requested region to a leader state or fail with an error that identifies the region that could not be made leader. One unreachable region should not block the whole restore operation forever.
What did happened?
elect_and_wait_all_ready never returns, so RecoverRegion never sends a response. The client sees a stream that stays open with no reply. On the server side the loop keeps running: every 10 seconds it sends a read-index proposal and a campaign for the failing region, and because of the debug_assert! described below it also re-probes every region that already succeeded. BR cannot finish the recover-region phase, so the restore cannot move to the next phase or report a meaningful error. The test below finishes in 13.00 seconds, which is the block_on_timeout(13s) window with no return from the production loop.
<user>@<host>:~/work/<project>$ cargo +nightly-2026-03-21 test -p snap_recovery --lib poc_elect_wait_never_returns -- --nocapture
Running unittests src/lib.rs (target/debug/deps/snap_recovery-6b397525c9ff4e77)
running 1 test
test leader_keeper::test::f4_poc_elect_wait_forever::poc_elect_wait_never_returns ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 5 filtered out; finished in 13.00s
<user>@<host>:~/work/<project>$Root cause
The wait is a retry loop with a single exit condition, and nothing in the loop can turn a terminal failure into an error. The chain has six links. First, the loop retries until failed_leader is empty and returns no value at all. Second, step() records the failure for every region that fails and discards the campaign failure that would identify an unreachable region. Third, a region missing from the store FSM registry fails both the read-index probe and the campaign with RegionNotFound, and that state does not change by itself. Fourth, a present peer can still never become leader because the campaign result is dropped inside the peer FSM. Fifth, the only way to stop the loop is a later recovery RPC, and the handler does not watch the client stream. Sixth, after the election the same handler waits on one wait-apply notification per region, also without a deadline.
(1) The election loop has one exit condition and no failure path.
// components/snap_recovery/src/leader_keeper.rs:69–83
pub async fn elect_and_wait_all_ready(&mut self) {
loop {
let now = Instant::now();
let res = self.step().await;
info!("finished leader keeper stepping."; "result" => ?res, "take" => ?now.elapsed());
GLOBAL_TIMER_HANDLE
.delay(now + Duration::from_secs(10))
.compat()
.await
.expect("wrong with global timer, cannot stepping.");
if res.failed_leader.is_empty() {
return;
}
}
}The function returns (), so the caller has no way to learn that a region is permanently stuck. The campaign_failed list that step() fills is never used here, and there is no retry limit or deadline. The RecoverRegion handler treats this call as a required step, so one bad region holds the whole RPC.
(2) step() records failures, ignores the terminal one, and its success bookkeeping is compiled out in release builds.
// components/snap_recovery/src/leader_keeper.rs:85–110 (abridged)
pub async fn step(&mut self) -> StepResult {
const CONCURRENCY: usize = 256;
let r = Mutex::new(StepResult::default());
let success = Mutex::new(HashSet::new());
let regions = self.not_leader.iter().copied().collect::<Vec<_>>();
for batch in regions.as_slice().chunks(CONCURRENCY) {
let tasks = batch.iter().map(|region_id| async {
match self.check_leader(*region_id).await {
Ok(_) => {
success.lock().unwrap().insert(*region_id);
return;
}
Err(err) => r.lock().unwrap().failed_leader.push((*region_id, err)),
};
if let Err(err) = self.force_leader(*region_id) {
r.lock().unwrap().campaign_failed.push((*region_id, err));
}
});
futures::future::join_all(tasks).await;
}
success.lock().unwrap().iter().for_each(|i| {
debug_assert!(self.not_leader.remove(i));
});
r.into_inner().unwrap()
}The removal of a successful region from not_leader sits inside debug_assert!, so the side effect runs only in debug builds. Release builds keep every region ever seen in not_leader, and each round re-probes all of them. The StepResult carries both lists, but only failed_leader is read by the loop.
(3) A missing region fails both probes, and the router maps both to RegionNotFound.
// components/snap_recovery/src/leader_keeper.rs:112–134 (abridged)
async fn check_leader(&self, region_id: u64) -> Result<()> {
let (cb, fut) = paired_future_callback();
let msg = SignificantMsg::LeaderCallback(Callback::<EK::Snapshot>::read(cb));
self.router.significant_send(region_id, msg)?;
let resp = fut
.await
.map_err(|_err| Error::Other("canceled by store".into()))?;
let header = resp.response.get_header();
if header.has_error() {
return Err(Error::Other(box_err!(
"got error: {:?}",
header.get_error()
)));
}
Ok(())
}
fn force_leader(&self, region_id: u64) -> Result<()> {
let msg = CasualMessage::Campaign(CampaignType::ForceLeader);
self.router.send(region_id, msg)?;
// We have nothing to do...
Ok(())
}// components/raftstore/src/store/transport.rs:74–90 (abridged)
impl<EK, ER> CasualRouter<EK> for RaftRouter<EK, ER>
where
EK: KvEngine,
ER: RaftEngine,
{
#[inline]
fn send(&self, region_id: u64, msg: CasualMessage<EK>) -> Result<()> {
match self
.router
.send(region_id, PeerMsg::CasualMessage(Box::new(msg)))
{
Ok(()) => Ok(()),
Err(TrySendError::Full(_)) => Err(Error::Transport(DiscardReason::Full)),
Err(TrySendError::Disconnected(_)) => Err(Error::RegionNotFound(region_id)),
}
}
}// components/raftstore/src/store/transport.rs:99–123 (abridged)
impl<EK, ER> SignificantRouter<EK> for RaftRouter<EK, ER>
where
EK: KvEngine,
ER: RaftEngine,
{
#[inline]
fn significant_send(&self, region_id: u64, msg: SignificantMsg<EK::Snapshot>) -> Result<()> {
if let Err(SendError(msg)) = self
.router
.force_send(region_id, PeerMsg::SignificantMsg(Box::new(msg)))
{
if msg.is_send_failure_ignorable() {
warn!("failed to send significant msg"; "msg" => ?msg);
} else {
error!("failed to send significant msg"; "msg" => ?msg);
}
return Err(Error::RegionNotFound(region_id));
}
Ok(())
}
}When the region is not registered in the store FSM, significant_send fails because force_send cannot find a mailbox, and the message with its callback is dropped. CasualRouter::send reports the same condition as RegionNotFound. Both errors are stable, so failed_leader and campaign_failed stay populated for that region on every round.
(4) A present peer can still never win, and the campaign result is discarded.
// components/raftstore/src/store/fsm/peer.rs:1479–1483
match campaign_type {
CampaignType::ForceLeader => {
// Forcely campaign to be the leader of the region.
let _ = self.fsm.peer.raft_group.campaign();
}The LeaderCallback probe goes through a read-index proposal on the same peer:
// components/raftstore/src/store/fsm/peer.rs:2347–2354
fn on_leader_callback(&mut self, cb: Callback<EK::Snapshot>) {
let msg = new_read_index_request(
self.region_id(),
self.region().get_region_epoch().clone(),
self.fsm.peer.peer.clone(),
);
self.propose_raft_command_internal(msg, cb, DiskFullOpt::NotAllowedOnFull);
}The campaign result is discarded, so a peer that cannot win the election produces no error and no signal beyond the next failing probe. The loop therefore cannot distinguish "not yet ready" from "will never be ready".
(5) RecoverRegion only replies after the loop returns, and the only abort path is a later recovery RPC.
// components/snap_recovery/src/services.rs:314–343 (abridged)
fn recover_region(
&mut self,
ctx: RpcContext<'_>,
mut stream: RequestStream<RecoverRegionRequest>,
sink: ClientStreamingSink<RecoverRegionResponse>,
) {
let mut raft_router = Mutex::new(self.router.clone());
let store_id = self.get_store_id();
info!("start to recover the region");
let task = async move {
let mut leaders = Vec::new();
while let Some(req) = stream.next().await {
let req = req.map_err(|e| eprintln!("rpc recv fail: {}", e)).unwrap();
if req.as_leader {
REGION_EVENT_COUNTER.promote_to_leader.inc();
leaders.push(req.region_id);
} else {
REGION_EVENT_COUNTER.keep_follower.inc();
}
}
let mut lk = LeaderKeeper::new(&raft_router, leaders.clone());
// ...
lk.elect_and_wait_all_ready().await;
info!("all region leader assigned done"; "count" => %leaders.len());
drop(lk);// components/snap_recovery/src/services.rs:396–406
let (state, task) = RecoverRegionState::wrap_task(task);
self.replace_last_recover_region(format!("recover_region by {}", ctx.peer()), state);
self.threads.spawn_ok(async move {
let res = match task.await {
Ok(resp) => sink.success(resp),
Err(Aborted) => sink.fail(RpcStatus::new(RpcStatusCode::ABORTED)),
};
if let Err(err) = res.await {
warn!("failed to response recover region rpc"; "err" => %err);
}
});// components/snap_recovery/src/services.rs:197–221 (abridged)
fn abort_last_recover_region(&self, place: impl Display) {
let mut last_state_lock = self.last_recovery_region_rpc.lock().unwrap();
Self::abort_last_recover_region_of(place, &mut last_state_lock)
}
fn replace_last_recover_region(&self, place: impl Display, new_state: RecoverRegionState) {
let mut last_state_lock = self.last_recovery_region_rpc.lock().unwrap();
Self::abort_last_recover_region_of(place, &mut last_state_lock);
*last_state_lock = Some(new_state);
}
fn abort_last_recover_region_of(
place: impl Display,
last_state_lock: &mut Option<RecoverRegionState>,
) {
if let Some(last_state) = last_state_lock.take() {
// ...
if !last_state.finished.load(Ordering::SeqCst) {
last_state.abort.abort();
warn!("Last task not finished, aborting it.");
}
}
}The task is aborted only when a new RecoverRegion or ReadRegionMeta call arrives; ReadRegionMeta calls the same abort as a workaround:
// components/snap_recovery/src/services.rs:304–308
// Hacking: Sometimes, the client may omit the RPC call to `recover_region` if
// no leader should be register to some (unfortunate) store. So we abort
// last recover region here too, anyway this RPC implies a consequent
// `recover_region` for now.
self.abort_last_recover_region(format_args!("read_region_meta by {}", ctx.peer()));A client that is waiting for the current RecoverRegion response does not send another recovery RPC, so nothing aborts the stuck task. The handler stops reading the client stream after the first loop, so a client disconnect does not cancel it either.
(6) The same handler then waits on one wait-apply notification per region, again without a deadline.
// components/snap_recovery/src/services.rs:347–379 (abridged)
let mut rx_apply = Vec::with_capacity(leaders.len());
for ®ion_id in &leaders {
let (tx, rx) = oneshot::channel();
REGION_EVENT_COUNTER.start_wait_leader_apply.inc();
let wait_apply = SnapshotBrWaitApplySyncer::new(region_id, tx);
if let Err(e) = raft_router.get_mut().unwrap().significant_send(
region_id,
SignificantMsg::SnapshotBrWaitApply(SnapshotBrWaitApplyRequest::relaxed(
wait_apply.clone(),
)),
) {
error!(
"failed to send wait apply";
"region_id" => region_id,
"err" => ?e,
);
}
rx_apply.push(rx);
}
// leader apply to last log
for (rid, rx) in leaders.iter().zip(rx_apply) {
CURRENT_WAIT_APPLY_LEADER.set(*rid as _);
match rx.await {
Ok(_) => {
debug!("leader apply to last log"; "region_id" => rid);
}
Err(e) => {
error!("leader failed to apply to last log"; "error" => ?e);
}
}
REGION_EVENT_COUNTER.finish_wait_leader_apply.inc();
}The sender fires only when the last SnapshotBrWaitApplySyncer clone is dropped:
// components/raftstore/src/store/snapshot_backup.rs:329–341
impl Drop for SyncerCore {
fn drop(&mut self) {
if let Some(ch) = self.feedback.take() {
let report = self.make_success_result();
if let Err(report) = ch.send(report) {
warn!("reply waitapply states failure."; "report" => ?report);
}Source: tikv/tikv