bug: log backup endpoint stalls forever when a flush-event subscriber stops reading
Summary
The backup-stream endpoint is a single-threaded actor. When a forced flush finishes, Endpoint::on_flushed calls CheckpointManager::sync_with_subs_mgr, which blocks the endpoint thread in a std::sync::mpsc receive until the asynchronous subscription-manager task runs the matching closure. That task processes operations strictly in order, and its emit_events path awaits ServerStreamingSink::feed(...) without any deadline. Once a SubscribeFlushEvent client stops reading, the gRPC stream window closes, feed never completes, and the queued Inspect closure never runs. The endpoint thread then stays parked forever: every later flush, resolve, register, and unregister task is queued behind it, and FlushNow never returns. The store's log backup control plane recovers only after the subscriber reads again, disconnects, or TiKV restarts.
What version of TiKV are you using?
I reproduced this on master at commit 7709ab9d738d16f856df990ad9ffb5c1908f84f8 (2026-09-29). Any build with log_backup.enable = true and the same checkpoint manager code is affected.
What operating system and CPU are you using?
Linux x86_64, tested with cargo +nightly-2026-03-21. The defect is a synchronization issue between a synchronous actor and an asynchronous task, so it does not depend on the OS or the CPU. It does require an external subscriber that stops reading its server stream.
Steps to reproduce
- Enable log backup on a store and register a task, so a completed flush produces a checkpoint notification with one event per observed region.
- Open a
SubscribeFlushEventstream. In production the checkpoint advancer holds this stream. It is also available to any client with access to the TiKV gRPC port. - Stop reading from the stream while keeping the connection open. A paused consumer, a backlogged advancer, or a hung process is enough.
- Force a flush with
FlushNow, or wait until a forced flush is already in flight. - The unread notifications exhaust the gRPC stream window.
SubscriptionManager::emit_eventsstays pending infeed(...).await, and theon_flushedcall for the next forced flush parks the endpoint worker thread insync_with_subs_mgr.
Run the integration test below to force this interleaving deterministically:
cargo +nightly-2026-03-21 test -p backup-stream --test integration \
f2_flush_endpoint_parks_when_subscriber_stops_reading -- --nocapturecomponents/backup-stream/tests/integration/mod.rs, inside the mod all module)fn f2_force_flush_result_within(
suite: &super::suite::Suite,
store_id: u64,
dur: Duration,
) -> bool {
let (tx, mut rx) = tokio::sync::mpsc::channel(1);
suite
.endpoints
.get(&store_id)
.unwrap()
.scheduler()
.schedule(Task::ForceFlush(TaskSelector::All, tx))
.unwrap();
run_async_test(async { timeout(dur, rx.recv()).await.is_ok() })
}
fn f2_schedule_checkpoint_probe(suite: &super::suite::Suite) -> std::sync::mpsc::Receiver<()> {
let (tx, rx) = std::sync::mpsc::channel();
suite.run(move || {
let tx = tx.clone();
Task::RegionCheckpointsOp(RegionCheckpointOperation::Get(
RegionSet::Universal,
Box::new(move |_| {
let _ = tx.send(());
}),
))
});
rx
}
#[test]
fn f2_flush_endpoint_parks_when_subscriber_stops_reading() {
let mut suite = SuiteBuilder::new_named("f2_flush_subscriber_stall")
.nodes(1)
.build();
// Long region boundaries make each flush notification about 1 MB.
for i in 1..=64u64 {
let mut raw = make_record_key(1, i * 8);
raw.extend(std::iter::repeat(b'p').take(8 * 1024));
suite.must_split(&Key::from_raw(&raw).into_encoded());
}
let _round1 = run_async_test(suite.write_records(0, 256, 1));
suite.must_register_task(1, "f2_flush_subscriber_stall");
let _round2 = run_async_test(suite.write_records(256, 128, 1));
suite.sync();
std::thread::sleep(Duration::from_secs(1));
let store_id = suite.cluster.leader_of_region(1).unwrap().store_id;
run_async_test(suite.force_flush_files_and_wait("f2_flush_subscriber_stall"));
assert!(f2_force_flush_result_within(
&suite,
store_id,
Duration::from_secs(15)
));
// Subscribe, read one notification to prove delivery, then stop reading.
let mut sub = suite.flush_stream(false);
suite.sync();
std::thread::sleep(Duration::from_secs(1));
{
let (tx, _rx) = tokio::sync::mpsc::channel(1);
suite
.endpoints
.get(&store_id)
.unwrap()
.scheduler()
.schedule(Task::ForceFlush(TaskSelector::All, tx))
.unwrap();
}
match run_async_test(async { timeout(Duration::from_secs(20), sub.next()).await }) {
Ok(Some((_id, resp))) => {
assert!(!resp.events.is_empty());
let key_bytes: usize = resp
.events
.iter()
.map(|e| e.start_key.len() + e.end_key.len())
.sum();
println!(
"[f2] first flush notification: {} events, {} bytes of region keys",
resp.events.len(),
key_bytes
);
assert!(key_bytes > 512 * 1024);
}
other => panic!("expected a flush notification, got {:?}", other),
}
// Wait until one flush result is withheld, then check that the endpoint
// actor itself no longer serves an unrelated checkpoint read.
let mut parked_probe = None;
for _round in 0..32 {
if f2_force_flush_result_within(&suite, store_id, Duration::from_secs(5)) {
continue;
}
let probe_rx = f2_schedule_checkpoint_probe(&suite);
if probe_rx.recv_timeout(Duration::from_secs(10)).is_err() {
parked_probe = Some(probe_rx);
break;
}
}
assert!(parked_probe.is_some());
let parked_probe = parked_probe.unwrap();
// Dropping the subscription releases the parked endpoint.
drop(sub);
assert!(parked_probe.recv_timeout(Duration::from_secs(15)).is_ok());
suite.cluster.shutdown();
}What did you expect?
A subscriber that stops reading must not block the store's log backup endpoint. The forced flush should return, later flushes and checkpoint reads should keep working, and an unresponsive subscriber should be dropped or timed out.
What did happened?
The endpoint worker thread parks in sync_with_subs_mgr and never returns. Every later endpoint task queues behind it, so the whole log backup endpoint for that store stops serving. FlushNow never returns, and the checkpoint advancer cannot advance the global checkpoint until the subscriber reads again or disconnects.
<user>@<host>:~/work/<project>$ cargo +nightly-2026-03-21 test -p backup-stream --test integration f2_flush_endpoint_parks_when_subscriber_stops_reading -- --nocapture
Running tests/integration/mod.rs (target/debug/deps/integration-dd4ef258927e662c)
running 1 test
[f2] first flush notification: 65 events, 1183104 bytes of region keys
test all::f2_flush_endpoint_parks_when_subscriber_stops_reading ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 15 filtered out; finished in 29.22sThe test asserts four things in sequence:
- The first received notification carries 65 events and 1,183,104 bytes of region keys, which confirms that the subscriber is registered and that the manager is pushing events.
- After the client stops reading, a
ForceFlushresult is withheld for more than 5 seconds. - An unrelated
RegionCheckpointsOp::Get(Universal, ...)probe does not answer within 10 seconds, so the endpoint actor itself is parked and the withheld result is not merely a slow flush. - Dropping the subscription makes the parked probe answer within 15 seconds, so the stall is caused by the unread server stream.
Root cause
The endpoint is a single-threaded actor, while the subscription manager is an asynchronous task on the endpoint's own runtime. The endpoint communicates with that task through a blocking rendezvous, and the task's progress depends on an external client that is free to stop reading.
(1) The endpoint actor is single-threaded, and the subscription manager runs as a separate task on the endpoint's runtime.
// components/server/src/server.rs:970–1024 (abridged)
let mut backup_stream_worker = Box::new(LazyWorker::new(BACKUP_STREAM_THREAD));
let backup_stream_scheduler = backup_stream_worker.scheduler();
...
backup_stream_worker.start(backup_stream_endpoint);// components/backup-stream/src/endpoint.rs:224–225
let mut checkpoint_mgr = CheckpointManager::default();
pool.spawn(root!(checkpoint_mgr.spawn_subscription_mgr()));Every endpoint task runs on that one worker thread through Endpoint::run_task and the Runnable implementation.
// components/backup-stream/src/endpoint.rs:1189–1225 (abridged)
pub fn run_task(&mut self, task: Task) {
...
match task {
...
Task::Flushed(result) => self.on_flushed(result),
}
}(2) FlushNow registers a waiter and triggers a flush.
// components/backup-stream/src/service.rs:46–89 (abridged)
let (tx, mut rx) = tokio::sync::mpsc::channel(1);
let task = Task::ForceFlush(TaskSelector::All, tx);
...
ctx.spawn(async move {
while let Some(item) = rx.recv().await {
...
}
if let Err(err) = sink.success(resp.clone()).await {
...
}
})// components/backup-stream/src/endpoint.rs:1013–1028 (abridged)
self.subscribe_flush_done(&handler.task.info.name, sender);
match handler.set_flushing_status_cas(false, true) {
Ok(_) => {
hnd.block_on(self.region_op(ObserveOp::ResolveRegions {
callback: Box::new(move |res| {
try_send!(sched, Task::ExecFlush(task_name, res, fts));
}),
min_ts: mts,
}));
}
Err(_) => {
info!("on_force_flush: a flush is on the way, waiting its finish..."; ...);
}
}The waiter is stored under the task name:
// components/backup-stream/src/endpoint.rs:966–975 (abridged)
fn subscribe_flush_done(&mut self, task: &str, mailbox: Sender<FlushResult>) {
if let Some(old_one) = self.flush_done_subscribers.insert(task.to_owned(), mailbox) {
...
}
}(3) The flush runs on the runtime and posts Task::Flushed back to the endpoint thread.
// components/backup-stream/src/endpoint.rs:1063–1075
fn on_exec_flush(&mut self, task: String, resolved: ResolvedRegions, flush_ts: TimeStamp) {
self.checkpoint_mgr.freeze();
let fut = self.do_flush(task.clone(), resolved, flush_ts);
let sched = self.scheduler.clone();
self.pool.spawn(root!("flush"; async move {
let res = fut.await;
if let Err(ref err) = &res {
err.report("during updating flush status")
}
let flush_res = FlushResult { task, error: res.err().map(Box::new) };
try_send!(sched, Task::Flushed(flush_res));
}));
}(4) on_flushed blocks the endpoint thread in sync_with_subs_mgr.
// components/backup-stream/src/endpoint.rs:1238–1254 (abridged)
fn on_flushed(&mut self, result: FlushResult) {
use tokio::sync::mpsc::error::TrySendError;
if let Some(sender) = self.flush_done_subscribers.remove(&result.task) {
self.checkpoint_mgr.sync_with_subs_mgr(move |_| {
if let Err(err) = sender.try_send(result) {
...
}
})
}
}// components/backup-stream/src/checkpoint_manager.rs:402–422
pub fn sync_with_subs_mgr<T: Send + 'static>(
&mut self,
f: impl FnOnce(&SubscriptionManager) -> T + Send + 'static,
) -> T {
use std::sync::Mutex;
let (tx, rx) = std::sync::mpsc::sync_channel(1);
let t = Arc::new(Mutex::new(None));
let tr = Arc::clone(&t);
self.manager_handle
.as_mut()
.unwrap()
.try_send(SubscriptionOp::Inspect(Box::new(move |x| {
*tr.lock().unwrap() = Some(f(x));
tx.send(()).unwrap();
})))
.unwrap();
rx.recv().unwrap();
let mut t = t.lock().unwrap();
t.take().unwrap()
}rx.recv() has no timeout and no cancellation path. It is a synchronous call on the endpoint worker thread, so the runtime cannot suspend or abort it.
(5) The subscription manager processes operations strictly in order and can stay pending in emit_events.
// components/backup-stream/src/checkpoint_manager.rs:67–87 (abridged)
pub async fn main_loop(mut self) {
...
while let Some(msg) = self.input.next().await {
match msg {
...
SubscriptionOp::Emit(events) => {
self.emit_events(events).await;
}
SubscriptionOp::Inspect(f) => {
f(&self);
}
}
}
...
}// components/backup-stream/src/checkpoint_manager.rs:90–112 (abridged)
async fn emit_events(&mut self, events: Box<[FlushEvent]>) {
...
for (id, sub) in &mut self.subscribers {
let send_all = async {
for es in events.chunks(1024) {
let mut resp = SubscribeFlushEventResponse::new();
resp.set_events(es.to_vec().into());
sub.feed((resp, WriteFlags::default())).await?;
}
sub.flush().await
};
if let Err(err) = send_all.await {
...
}
}
...
}sub is a grpcio::ServerStreamingSink. When the client stops reading, stream-level flow control prevents the send from completing, so feed(...).await stays pending forever. There is no timeout, and no code drops a lagging subscriber. Because Inspect is handled after the pending Emit, the endpoint's rx.recv() never returns.
(6) The subscriber and the notification queue enter through the same paths.
// components/backup-stream/src/service.rs:141–155 (abridged)
fn subscribe_flush_event(
&mut self,
_ctx: RpcContext<'_>,
req: SubscribeFlushEventRequest,
sink: grpcio::ServerStreamingSink<SubscribeFlushEventResponse>,
) {
...
try_send!(
self.endpoint,
Task::RegionCheckpointsOp(RegionCheckpointOperation::Subscribe(sink))
);
}// components/backup-stream/src/endpoint.rs:1321–1328
RegionCheckpointOperation::Subscribe(sub) => {
let fut = self.checkpoint_mgr.add_subscriber(sub);
self.pool.spawn(root!(async move {
if let Err(err) = fut.await {
err.report("adding subscription");
}
}));
}// components/backup-stream/src/checkpoint_manager.rs:307–349 (abridged)
pub fn add_subscriber(&mut self, sub: Subscription) -> BoxFuture<'static, Result<()>> {
let mgr = self.manager_handle.as_ref().cloned();
let initial_data = ...;
async move {
...
mgr.send(SubscriptionOp::Add(sub))
.await
.map_err(...)?;
mgr.send(SubscriptionOp::Emit(initial_data))
.await
.map_err(...)?;
Ok(())
}.boxed()
}Flush notifications are queued by the endpoint with a non-blocking send:
// components/backup-stream/src/checkpoint_manager.rs:351–370 (abridged)
fn notify(&mut self, items: impl Iterator<Item = (Region, TimeStamp)>) {
if let Some(mgr) = self.manager_handle.as_mut() {
let r = items.map(|(r, ts)| { ... }).collect::<Box<[_]>>();
let res = mgr.try_send(SubscriptionOp::Emit(r));
if let Err(err) = res {
warn!("the channel is full, dropping some events."; ...);
}
}
}The resulting wait cycle is:
endpoint worker thread subscription-manager task
Task::Flushed -> on_flushed
sync_with_subs_mgr
try_send(Inspect) ---------------------> queue: [Emit(flush events), Inspect]
rx.recv() blocks <--------------------- main_loop is stuck in Emit
emit_events -> sink.feed(...) -> Pending
(client stopped reading, window closed)The endpoint thread waits on the manager task; the manager task waits on the client. Neither wait is bounded, so the endpoint parks for as long as the client stays connected and silent.
Impact
This is a per-store log backup control plane stall. Once the endpoint thread is parked:
- Every later endpoint task is queued, including periodic flush,
PrepareMinTsForResolve, region observation and deregistration, config changes, and error handling. FlushNownever returns, so the checkpoint advancer cannot confirm or advance the global checkpoint.- The endpoint mailbox eventually fills and
try_send!starts dropping tasks. - A subscriber that reads slowly, rather than not at all, produces repeated long stalls instead of a single park.
Source: tikv/tikv