openraft 0.10.2

Advanced Raft consensus
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
//! Replication stream.

mod backoff_consumer;
pub(crate) mod backoff_state;
pub(crate) mod event_watcher;
pub(crate) mod inflight_append;
pub(crate) mod inflight_append_queue;
pub(crate) mod payload;
pub(crate) mod replicate;
pub(crate) mod replication_context;
pub(crate) mod replication_handle;
mod replication_session_id;
pub(crate) mod response;
pub(crate) mod snapshot_transmitter;
pub(crate) mod snapshot_transmitter_handle;
pub(crate) mod stream_state;

#[cfg(test)]
mod clear_plan_test;

use std::fmt;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::time::Duration;

use display_more::DisplayOptionExt;
use futures_util::FutureExt;
use futures_util::StreamExt;
use payload::Payload;
pub(crate) use replication_session_id::ReplicationSessionId;
pub(crate) use response::Progress;

/// Fallback delay used when a [`Backoff`] iterator is exhausted.
pub(crate) const EXHAUSTED_BACKOFF_DELAY: Duration = Duration::from_millis(500);
use response::ReplicationResult;
use stream_state::StreamState;
use tracing::Instrument;

use crate::RaftNetworkFactory;
use crate::RaftTypeConfig;
use crate::async_runtime::Mutex;
use crate::async_runtime::Select2;
use crate::async_runtime::watch::WatchReceiver;
use crate::async_runtime::watch::WatchSender;
use crate::base::BoxStream;
use crate::core::notification::Notification;
use crate::display_ext::display_instant::DisplayInstantExt;
use crate::errors::RPCError;
use crate::errors::ReplicationClosed;
use crate::log_id_range::LogIdRange;
use crate::network::Backoff;
use crate::network::NetBackoff;
use crate::network::NetStreamAppend;
use crate::network::RPCOption;
use crate::progress::inflight_id::InflightId;
use crate::raft::AppendError;
use crate::raft::AppendResult;
use crate::raft::ConflictHint;
use crate::raft_state::IOId;
use crate::replication::backoff_consumer::BackoffConsumer;
use crate::replication::backoff_state::BackoffState;
use crate::replication::event_watcher::EventWatcher;
use crate::replication::inflight_append_queue::InflightAppendQueue;
use crate::replication::replicate::Replicate;
use crate::replication::replication_context::ReplicationContext;
use crate::storage::RaftLogStorage;
use crate::type_config::TypeConfigExt;
use crate::type_config::alias::InstantOf;
use crate::type_config::alias::JoinHandleOf;
use crate::type_config::alias::LogIdOf;
use crate::type_config::alias::MutexOf;
use crate::type_config::alias::WatchReceiverOf;
use crate::type_config::alias::WatchSenderOf;
use crate::type_config::async_runtime::mpsc::MpscSender;

/// The error rank that a stream session adds when the target accepted none of the entries it sent.
///
/// It exceeds `BACKOFF_RANK_THRESHOLD` (20), as the rank of `Unreachable` does, so the next session
/// waits on the backoff instead of resending the entries at once. A lower rank would never start
/// the backoff, because each `Ok` answer in a session resets the rank to 0.
const NO_PROGRESS_BACKOFF_RANK: u64 = 100;

/// A task that streams AppendEntries requests to a target follower.
///
/// The request stream generates requests as the transport polls it, independently of the worker's
/// processing of responses. The transport controls how many requests are in flight and yields
/// responses in the order of the requests it sent.
pub(crate) struct ReplicationCore<C, N, LS>
where
    C: RaftTypeConfig,
    N: RaftNetworkFactory<C>,
    LS: RaftLogStorage<C>,
{
    /// Shared context containing node IDs, session info, and notification channel.
    replication_context: ReplicationContext<C>,

    /// The log reader, which every request stream of this task reads the log through.
    ///
    /// It is the only state that the request streams share, with each other and with this task:
    /// each session's stream owns the rest of its [`StreamState`]. A transport may poll a request
    /// stream after its session has ended, so the streams of two sessions may run at the same time.
    /// This task takes the lock to wait until no stream reads, see [`Self::wait_for_reads()`].
    log_reader: Arc<MutexOf<C, LS::LogReader>>,

    /// Resets the backoff of a stream session. Each session's request stream gets a clone, see
    /// [`Self::reconcile_backoff()`].
    backoff_reset_rx: WatchReceiverOf<C, ()>,

    /// Watches the replication plan, accepted and submitted IO, and commit updates from RaftCore.
    ///
    /// The snapshot transmitter reports progress directly to RaftCore through the notification
    /// channel in [`ReplicationContext`], not through these watches.
    event_watcher: EventWatcher<C>,

    /// The next replication payload to send, set when partially completed.
    next_action: Option<Payload<C>>,

    /// Identifies the current in-flight replication batch for progress tracking.
    ///
    /// The responses of a session carry it to RaftCore. A commit probe resets it to `None`.
    inflight_id: Option<InflightId>,

    /// The inflight id of the plan this task adopted last, written only by [`Self::adopt()`].
    ///
    /// Unlike `inflight_id`, a commit probe does not reset it, so it tells whether the plan in
    /// `replicate_rx` is one this task has already run.
    adopted: Option<InflightId>,

    /// The network interface for replicating logs and heartbeat.
    network: Option<N::Network>,

    /// The last log id known to match on the follower.
    remote_matched: Option<LogIdOf<C>>,

    /// Backoff state for rate-limiting retries on persistent errors.
    ///
    /// Encapsulates both the accumulated error rank and the shared backoff iterator
    /// handed to [`StreamState`] via
    /// [`BackoffState::consumer`](crate::replication::backoff_state::BackoffState::consumer).
    /// See [issue #1723](https://github.com/databendlabs/openraft/issues/1723) for the
    /// invariant these two pieces must maintain together.
    backoff_state: BackoffState,
}

impl<C, N, LS> ReplicationCore<C, N, LS>
where
    C: RaftTypeConfig,
    N: RaftNetworkFactory<C>,
    LS: RaftLogStorage<C>,
{
    /// Spawn a new replication task for the target node.
    #[tracing::instrument(level = "trace", skip_all, fields(context=display(&replication_context)
    ))]
    #[allow(clippy::type_complexity)]
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn spawn(
        replication_context: ReplicationContext<C>,
        remote_matched: Option<LogIdOf<C>>,
        network: N::Network,
        log_reader: LS::LogReader,
        event_watcher: EventWatcher<C>,
        backoff_reset_rx: WatchReceiverOf<C, ()>,
        span: tracing::Span,
    ) -> JoinHandleOf<C, Result<(), ReplicationClosed>> {
        tracing::debug!(
            "spawn replication: session_id={}, target={}, matching={}",
            replication_context.stream_id,
            replication_context.target,
            remote_matched.display()
        );

        let this = Self {
            replication_context,
            log_reader: Arc::new(C::mutex(log_reader)),
            backoff_reset_rx,
            inflight_id: None,
            adopted: None,
            event_watcher,
            network: Some(network),
            remote_matched,
            backoff_state: BackoffState::new(),
            next_action: None,
        };

        C::spawn(this.main().instrument(span))
    }

    /// Run the replication loop until it ends, then stop reading the log.
    ///
    /// Once `RaftCore` has closed the stream, it purges the logs that this task could read when the
    /// task reports that it reads the log no more, or when the task has returned, see
    /// [`Notification::ReplicationStopped`]. A transport that polls the request stream on a task
    /// of its own may still poll it after the loop has ended, so the task returns only once no
    /// read runs, see [`Self::wait_for_reads()`].
    async fn main(mut self) -> Result<(), ReplicationClosed> {
        let res = self.replicate().await;

        self.wait_for_reads().await;

        res
    }

    /// Main replication loop that sends AppendEntries requests and processes responses.
    async fn replicate(&mut self) -> Result<(), ReplicationClosed> {
        // Avoid holding a mut ref to self during streaming.
        let mut network = self.network.take().unwrap();

        // reset the streaming state
        self.next_action = None;
        self.inflight_id = None;

        loop {
            tracing::debug!(
                "ReplicationCore: new stream start, next_action = {:?}",
                self.next_action
            );

            self.ensure_still_leading()?;

            // Kept separate from `on_error` because only this scope holds a reference
            // to `network`, which is needed to construct the `Backoff` iterator.
            // If the network returns None, fall back to the policy configured in `Config::backoff`.
            let config = self.replication_context.config.clone();
            self.reconcile_backoff(|| network.backoff().unwrap_or_else(|| config.build_backoff()));

            let mut payload = self.select_next_payload().await?;
            let mut backoff_consumer = self.backoff_state.consumer(
                self.backoff_reset_rx.clone(),
                self.replication_context.cancel_rx.clone(),
            );

            // A failed open may never poll its request stream. Charge the first delay here,
            // then give the session the same consumer for later requests.
            if backoff_consumer.backoff_if_enabled().await? {
                self.ensure_still_leading()?;
                self.next_action = Some(payload);
                payload = self.select_next_payload().await?;
            }

            let (mut session_tx, session_rx) = C::watch_channel(false);
            let result =
                self.run_stream_session(&mut network, &payload, backoff_consumer, &mut session_tx, session_rx).await;
            // Retire this upload before a replacement can start or a clear can release its logs.
            session_tx.send(true).ok();
            self.next_action = result?;
        }
    }

    /// Enable or clear the backoff of the next stream session, as [`BackoffState::reconcile()`]
    /// decides.
    ///
    /// The next session's request stream clones `backoff_reset_rx` and with it which resets it has
    /// seen, so the resets that a new backoff discards here do not reach that stream.
    fn reconcile_backoff(&mut self, backoff_factory: impl FnOnce() -> Backoff) {
        let reset_rx = &mut self.backoff_reset_rx;
        self.backoff_state.reconcile(|| {
            let backoff = backoff_factory();
            // Discard resets from before this backoff; later resets remain pending.
            reset_rx.borrow_and_update();
            backoff
        });
    }

    /// Wait until no request stream of this task reads the log.
    ///
    /// Call it only once every session has ended. A stream reads the log only while it holds the
    /// lock of `log_reader`, and checks under the lock, before and after the read, that its
    /// session has not ended. So once this has taken the lock, no read runs or can start: RaftCore
    /// may purge any log, see [`Self::confirm_clear()`] and [`Notification::ReplicationStopped`].
    async fn wait_for_reads(&self) {
        drop(self.log_reader.lock().await);
    }

    /// Check the two reasons this task must stop before opening another stream: the leader
    /// dropped its handle, or a different leader has taken over locally.
    fn ensure_still_leading(&mut self) -> Result<(), ReplicationClosed> {
        let canceled = self.replication_context.cancel_rx.changed().now_or_never();
        if canceled.map(|x| x.is_err()) == Some(true) {
            tracing::info!("ReplicationCore: canceled, quit");
            return Err(ReplicationClosed::new("canceled"));
        }

        let accepted_io: IOId<C> = self.event_watcher.io_accepted_rx.borrow_watched().clone();
        if self.replication_context.leader_changed(&accepted_io) {
            return Err(ReplicationClosed::new("Leader changed"));
        }

        Ok(())
    }

    /// Decide what the next stream should carry.
    ///
    /// A payload still unfinished is resumed unless [`RaftCore`] has published a plan since this
    /// task last adopted one. Then adopt that plan, as when a reverted log makes a `LogsSince`
    /// payload obsolete: resuming the payload would send entries that may no longer exist. With
    /// nothing to run, block until [`RaftCore`] hands over work.
    ///
    /// [`RaftCore`]: crate::core::RaftCore
    async fn select_next_payload(&mut self) -> Result<Payload<C>, ReplicationClosed> {
        if self.next_action.is_some() {
            let unfinished = self.inflight_id;
            if self.adopt_published().await {
                tracing::info!(
                    "ReplicationCore replaced the unfinished payload of inflight id {} with the plan {}",
                    unfinished.display(),
                    self.inflight_id.display()
                );
            }
        }

        while self.next_action.is_none() {
            self.drain_events().await?;
        }

        Ok(self.next_action.take().unwrap())
    }

    /// Adopt the plan in `replicate_rx` if this task has not adopted it yet, and return whether it
    /// did.
    ///
    /// Every plan RaftCore publishes carries a new inflight id, so a plan other than the one
    /// adopted last is a new one. `inflight_id` cannot tell: a commit probe resets it, while the
    /// channel may still hold a plan this task already ran and RaftCore has finished since. The
    /// decision reads only the value, so it does not depend on which reader of the channel has
    /// marked a change as seen. RaftCore publishes `None` only as the initial value, before any
    /// plan.
    async fn adopt_published(&mut self) -> bool {
        let current = self.event_watcher.replicate_rx.borrow_watched().clone();
        let Some(current) = current else {
            return false;
        };
        if self.adopted == Some(current.inflight_id) {
            return false;
        }

        tracing::debug!("ReplicationCore adopts {}", current);
        self.adopt(current).await;
        true
    }

    /// Run `replicate` from now on, in place of the plan this task ran before.
    ///
    /// A plan without payload clears the earlier plan: [`RaftCore`] waits for this task to confirm
    /// that it no longer reads the log for it, and only then purges the logs that plan could read.
    /// The task adopts a plan only between stream sessions. A session for the earlier plan ends
    /// once its request stream ends, which the stream does at its next request after the plan
    /// changes, and the transport has answered the requests in flight. It is not cut short: a
    /// transport may not survive a request dropped halfway, and a dropped request may take with it
    /// a commit that no later request carries.
    ///
    /// [`RaftCore`]: crate::core::RaftCore
    async fn adopt(&mut self, replicate: Replicate<C>) {
        self.adopted = Some(replicate.inflight_id);
        self.inflight_id = Some(replicate.inflight_id);
        self.next_action = replicate.payload;

        if self.next_action.is_none() {
            self.confirm_clear(replicate.inflight_id).await;
        }
    }

    /// Confirm to [`RaftCore`], answering the clear request `inflight_id`, that this task no longer
    /// reads the log for the plan [`RaftCore`] dropped.
    ///
    /// The task adopts a clear only between stream sessions, so the session that ran the dropped
    /// plan has ended. Its request stream, which a transport that polls it on a task of its own may
    /// still run, reads nothing more once [`Self::wait_for_reads()`] returns.
    ///
    /// [`RaftCore`]: crate::core::RaftCore
    async fn confirm_clear(&mut self, inflight_id: InflightId) {
        self.wait_for_reads().await;

        tracing::debug!("ReplicationCore cleared its plan; confirm inflight_id: {}", inflight_id);
        self.replication_context.notify_cleared(inflight_id).await;
    }

    /// Stream `payload` to the target and consume the responses.
    ///
    /// Returns the payload left to send: `None` when `payload` completed, or when the session
    /// was interrupted and RaftCore will reschedule. An `Err` is fatal and ends the task.
    async fn run_stream_session(
        &mut self,
        network: &mut N::Network,
        payload: &Payload<C>,
        backoff_consumer: BackoffConsumer<C>,
        session_tx: &mut WatchSenderOf<C, bool>,
        session_rx: WatchReceiverOf<C, bool>,
    ) -> Result<Option<Payload<C>>, ReplicationClosed> {
        let inflight_queue = InflightAppendQueue::new();
        let inflight_queue = StdMutex::new(inflight_queue);
        let inflight_queue = Arc::new(inflight_queue);
        let fatal_error = Arc::new(C::mutex(None));

        // The request stream of this session owns its state, so a stream of an earlier session
        // that the transport still polls neither sees nor advances this session's payload.
        let stream_state = StreamState::<C, LS> {
            session_rx,
            has_yielded_request: false,
            inflight_id: self.inflight_id,
            payload: Some(payload.clone()),
            replication_context: self.replication_context.clone(),
            event_watcher: self.event_watcher.clone(),
            backoff_consumer,
            log_reader: self.log_reader.clone(),
            inflight_append_queue: inflight_queue.clone(),
            fatal_error: fatal_error.clone(),
            #[cfg(test)]
            after_leader_check: None,
        };

        let req_strm = stream_state.into_request_stream();

        let rpc_timeout = Duration::from_millis(self.replication_context.config.heartbeat_interval);
        let option = RPCOption::new(rpc_timeout);

        // Once RaftCore closes the stream, the transport finishes the session while this task
        // reports nothing more, see `Self::finish_closed_session()`.
        let mut cancel_rx = self.replication_context.cancel_rx.clone();
        let mut opening = network.stream_append(req_strm, option);
        let Some(resp_strm_res) = C::cancellable_by(&mut opening, cancel_rx.changed()).await else {
            tracing::info!("ReplicationCore: closed while opening a stream");
            let rest = async move {
                if let Ok(resp_strm) = opening.await {
                    Self::drain(resp_strm).await;
                }
            };
            self.finish_closed_session(session_tx, rest).await;
            return Err(ReplicationClosed::new("canceled"));
        };
        // A custom streaming transport may poll the request stream while establishing
        // `stream_append()` and then still return an RPC error. Check the fatal marker here too,
        // because in that case there is no response stream for `handle_response_stream()` to
        // consume.
        if let Some(err) = Self::take_stream_fatal_error(&fatal_error).await {
            return Err(err);
        }

        let mut resp_strm = match resp_strm_res {
            Ok(resp_strm) => resp_strm,
            Err(rpc_err) => {
                self.backoff_state.on_error(rpc_err.backoff_rank());
                self.send_progress_error(rpc_err, "initiate-stream-replication").await;

                return Ok(None);
            }
        };

        let res = self.handle_response_stream(&mut resp_strm, inflight_queue.clone()).await;
        let (acked, continue_res) = match res {
            Ok(stopped) => stopped,
            Err(closed) => {
                self.finish_closed_session(session_tx, Self::drain(resp_strm)).await;
                return Err(closed);
            }
        };
        if let Some(err) = Self::take_stream_fatal_error(&fatal_error).await {
            return Err(err);
        }

        // If the stream stops with an un-handleable status, such as conflict,
        // do not continue the payload.
        let remaining = if let Ok(()) = continue_res {
            match acked {
                None => Some(payload.clone()),
                Some(matching) => payload.clone().update_matching(matching),
            }
        } else {
            None
        };

        // The target accepted none of the entries this session sent. Without a backoff, the next
        // session would resend them at once.
        let no_progress = remaining.as_ref() == Some(payload);
        let has_unacked = {
            let inflight_queue = inflight_queue.lock().unwrap();
            !inflight_queue.is_empty()
        };
        if no_progress && has_unacked {
            self.backoff_state.on_error(NO_PROGRESS_BACKOFF_RANK);
        }

        Ok(remaining)
    }

    async fn take_stream_fatal_error(
        fatal_error: &Arc<MutexOf<C, Option<ReplicationClosed>>>,
    ) -> Option<ReplicationClosed> {
        let mut fatal_error = fatal_error.lock().await;
        fatal_error.take()
    }

    /// Let the transport finish a session after RaftCore has closed the stream, and report nothing
    /// more of it.
    ///
    /// `rest` polls what the transport has not finished: the future that opens the stream and then
    /// the response stream, or the response stream alone. Publishing retirement ends the request
    /// stream, so the transport sends no new request, and `rest` polls the response stream to its
    /// end, even after an error, while the transport answers or fails the requests in flight.
    /// Dropping them instead would make a transport over HTTP/2 reset their streams, and a server
    /// closes the connection with `GOAWAY` once too many reset streams wait for it, failing every
    /// request on it; see the cancellation rules of [`NetStreamAppend::stream_append()`].
    ///
    /// RaftCore runs no purge, and no command queued behind one, while a task that it closed may
    /// still read the log, see [`RaftCore::lingering_replications`]. So the task reports that it
    /// reads the log no more without waiting for `rest`: once [`Self::wait_for_reads()`] has
    /// returned, as [`Self::confirm_clear()`] does. `rest` runs meanwhile, because the transport
    /// may poll the request stream from within it.
    ///
    /// [`RaftCore::lingering_replications`]: crate::core::RaftCore::lingering_replications
    async fn finish_closed_session<F>(&mut self, session_tx: &mut WatchSenderOf<C, bool>, rest: F)
    where F: Future<Output = ()> {
        session_tx.send(true).ok();

        let stop_reading = async {
            self.wait_for_reads().await;
            self.replication_context.notify_stopped().await;
        };
        futures_util::future::join(stop_reading, rest).await;
    }

    /// Poll the responses of a session that RaftCore has closed until the stream ends, and report
    /// none of them.
    ///
    /// An error does not end the stream: a transport may still answer other requests in flight
    /// after it.
    async fn drain(mut resp_strm: BoxStream<'_, Result<AppendResult<C>, RPCError<C>>>) {
        while let Some(rpc_res) = resp_strm.next().await {
            tracing::debug!("ReplicationCore: closed, ignore the response: {:?}", rpc_res);
        }
    }

    /// Consume the response stream, returning its greatest acknowledgement and stop reason.
    ///
    /// Returns `Err` once RaftCore closes the stream, and leaves the rest of `resp_strm` to the
    /// caller.
    async fn handle_response_stream<'s>(
        &mut self,
        resp_strm: &mut BoxStream<'s, Result<AppendResult<C>, RPCError<C>>>,
        inflight_queue: Arc<StdMutex<InflightAppendQueue<C>>>,
    ) -> Result<(Option<Option<LogIdOf<C>>>, Result<(), &'static str>), ReplicationClosed> {
        let mut cancel_rx = self.replication_context.cancel_rx.clone();
        let mut acked: Option<Option<LogIdOf<C>>> = None;

        loop {
            let next_resp = resp_strm.next();
            let cancel = cancel_rx.changed();
            let rpc_res = C::cancellable_by(next_resp, cancel).await;
            let Some(rpc_res) = rpc_res else {
                tracing::info!("ReplicationCore: closed while waiting for a response");
                return Err(ReplicationClosed::new("canceled"));
            };

            let Some(rpc_res) = rpc_res else {
                return Ok((acked, Ok(())));
            };

            tracing::debug!("AppendEntries RPC response: {:?}", rpc_res);

            self.backoff_state.observe(&rpc_res);
            let append_res = match rpc_res {
                Ok(stream_append_res) => stream_append_res,
                Err(rpc_err) => {
                    self.send_progress_error(rpc_err, "stream-replication").await;
                    return Ok((acked, Err("RPCError")));
                }
            };

            match append_res {
                Ok(matching) => {
                    let last_acked_sending_time = {
                        let mut inflight_queue = inflight_queue.lock().unwrap();
                        inflight_queue.drain_acked(&matching)
                    };

                    if let Some(last) = last_acked_sending_time {
                        self.notify_heartbeat_progress(last).await;
                    }

                    acked = acked.max(Some(matching.clone()));

                    let greatest_acked = match &acked {
                        Some(greatest_acked) => greatest_acked.clone(),
                        None => unreachable!("acked was just updated"),
                    };
                    let result = ReplicationResult(Ok(greatest_acked));
                    self.notify_progress(result, None).await;
                }
                Err(append_err) => {
                    match append_err {
                        AppendError::Conflict { log_id, hint } => {
                            let sending_time = {
                                let mut inflight_queue = inflight_queue.lock().unwrap();
                                inflight_queue.drain_conflicted(&log_id)
                            };
                            if let Some(sending_time) = sending_time {
                                self.notify_heartbeat_progress(sending_time).await;
                            }

                            let result = ReplicationResult(Err(log_id));
                            self.notify_progress(result, hint).await;
                        }
                        AppendError::HigherVote(higher) => {
                            self.replication_context
                                .tx_notify
                                .send(Notification::HigherVote {
                                    target: self.replication_context.target.clone(),
                                    higher,
                                    leader_vote: self.replication_context.leader_vote.clone(),
                                })
                                .await
                                .ok();
                        }
                    }

                    return Ok((acked, Err("AppendError")));
                }
            }
        }
    }

    /// Send the error result to RaftCore.
    /// RaftCore will then submit another replication command.
    async fn send_progress_error(&mut self, err: RPCError<C>, when: impl fmt::Display) {
        tracing::warn!(
            "ReplicationCore recv RPCError: {}, when:({}); sending error to RaftCore",
            err,
            when
        );

        // no inflight id means there is no payload is sent, and no one is waiting the response, no need to
        // report.
        if self.inflight_id.is_none() {
            return;
        }
        self.replication_context.notify_progress(Err(err.to_string()), self.inflight_id, None).await;
    }

    /// A successful replication implies a successful heartbeat.
    /// This method notifies [`RaftCore`] with a heartbeat progress.
    ///
    /// [`RaftCore`]: crate::core::RaftCore
    async fn notify_heartbeat_progress(&mut self, sending_time: InstantOf<C>) {
        tracing::debug!("ReplicationCore notify_heartbeat_progress: {}", sending_time.display());
        self.replication_context.notify_heartbeat_progress(sending_time).await;
    }

    /// Notify RaftCore with the success replication result (log matching or conflict).
    ///
    /// `hint` is the conflict hint the target returned with a conflict.
    async fn notify_progress(&mut self, replication_result: ReplicationResult<C>, hint: Option<ConflictHint<C>>) {
        tracing::debug!(
            "{}: target={}, curr_matching={}, result={}, inflight_id={}",
            func_name!(),
            self.replication_context.target,
            self.remote_matched.display(),
            replication_result,
            self.inflight_id.display()
        );

        match &replication_result.0 {
            Ok(matching) => {
                self.remote_matched = matching.clone();

                // No need to notify
                if matching.is_none() && self.inflight_id.is_none() {
                    return;
                }
            }
            Err(_conflict) => {
                // Conflict is not allowed to be less than the current matching.
            }
        }

        // always send Conflict error back, even when the inflight id is None
        // for heartbeat to detect log reversion
        self.replication_context.notify_progress(Ok(replication_result), self.inflight_id, hint).await;
    }

    /// Receive and process events from RaftCore and set `next_action` and `inflight_id`.
    ///
    /// - For log entries: sets `inflight_id = Some(id)` and `next_action = Some(payload)`
    /// - For a clear: sets `inflight_id = Some(id)`, leaves `next_action = None`, and confirms the
    ///   clear to RaftCore, see [`Self::adopt()`]
    /// - For committed update: sets `inflight_id = None` and `next_action =
    ///   Some(empty_range_payload)`
    ///
    /// A plan this task has not adopted is taken without waiting, so a change notification that
    /// was consumed elsewhere costs no plan. Otherwise it blocks until at least one event is
    /// received.
    #[tracing::instrument(level = "trace", skip_all)]
    pub async fn drain_events(&mut self) -> Result<(), ReplicationClosed> {
        tracing::debug!("drain_events");

        if self.adopt_published().await {
            return Ok(());
        }

        let entries = self.event_watcher.replicate_rx.changed();
        let committed = self.event_watcher.committed_rx.changed();

        let selected = C::select2(entries, committed).await;
        match selected {
            Select2::First(entries_res) => {
                entries_res.map_err(|_e| ReplicationClosed::new("replicate_rx closed"))?;
                // The value decides, not the notification: a plan already adopted is skipped.
                self.adopt_published().await;
            }
            Select2::Second(committed_res) => {
                committed_res.map_err(|_e| ReplicationClosed::new("committed_rx closed"))?;

                // Mark the latest commit as seen; the request generator reads it separately.
                self.event_watcher.committed_rx.borrow_and_update();

                let m = self.remote_matched.clone();
                let log_id_range = LogIdRange::new(m.clone(), m);
                self.inflight_id = None;
                self.next_action = Some(Payload::Probe { log_id_range });
            }
        };

        tracing::debug!(
            "drain_events set: inflight_id={:?}, next_action={:?}",
            self.inflight_id,
            self.next_action
        );

        Ok(())
    }
}