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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
//! A replication task confirms a clear only once it reads nothing more for the plan RaftCore
//! dropped. RaftCore purges the logs the plan held back only after the confirmation. Likewise, a
//! task whose stream RaftCore closed reports that it reads the log no more only once it reads
//! nothing more, and RaftCore purges no log until then, or until the task has returned. The task
//! reports it without waiting for the transport, which it lets finish the requests in flight.

mod backoff_test;
mod session_test;

use std::fmt::Debug;
use std::future::Future;
use std::io;
use std::ops::RangeBounds;
use std::sync::Arc;
use std::time::Duration;

use futures_util::FutureExt;
use futures_util::Stream;
use futures_util::StreamExt;

use crate::Config;
use crate::OptionalSend;
use crate::RaftLogReader;
use crate::RaftNetworkFactory;
use crate::async_runtime::MpscReceiver;
use crate::async_runtime::MpscSender;
use crate::async_runtime::WatchReceiver;
use crate::async_runtime::WatchSender;
use crate::base::BoxFuture;
use crate::base::BoxStream;
use crate::core::SharedReplicateBatch;
use crate::core::notification::Notification;
use crate::engine::testing::UTConfig;
use crate::engine::testing::log_id;
use crate::entry::RaftEntry;
use crate::errors::RPCError;
use crate::errors::ReplicationClosed;
use crate::errors::StreamingError;
use crate::errors::Unreachable;
use crate::log_id_range::LogIdRange;
use crate::network::Backoff;
use crate::network::RPCOption;
use crate::network::RaftNetworkV2;
use crate::network::stream_append_sequential;
use crate::progress::inflight_id::InflightId;
use crate::progress::stream_id::StreamId;
use crate::raft::AppendEntriesRequest;
use crate::raft::AppendResult;
use crate::raft::SnapshotResponse;
use crate::raft::VoteRequest;
use crate::raft::VoteResponse;
use crate::raft_state::IOId;
use crate::replication::ReplicationCore;
use crate::replication::event_watcher::EventWatcher;
use crate::replication::replicate::Replicate;
use crate::replication::replication_context::ReplicationContext;
use crate::storage::IOFlushed;
use crate::storage::LogState;
use crate::storage::RaftLogStorage;
use crate::type_config::TypeConfigExt;
use crate::type_config::alias::EntryOf;
use crate::type_config::alias::JoinHandleOf;
use crate::type_config::alias::LogIdOf;
use crate::type_config::alias::MpscReceiverOf;
use crate::type_config::alias::MpscSenderOf;
use crate::type_config::alias::SnapshotOf;
use crate::type_config::alias::VoteOf;
use crate::type_config::alias::WatchReceiverOf;
use crate::type_config::alias::WatchSenderOf;
use crate::vote::raft_vote::RaftVoteExt;

type C = UTConfig;

const TEST_TIMEOUT: Duration = Duration::from_secs(1);

/// A log whose reads each find one entry, once `open` is `true`.
struct GatedLog {
    /// Counts the reads that have started.
    reads: Arc<WatchSenderOf<C, u64>>,
    open: WatchReceiverOf<C, bool>,
}

impl RaftLogReader<C> for GatedLog {
    async fn limited_get_log_entries(&mut self, start: u64, _end: u64) -> Result<Vec<EntryOf<C>>, io::Error> {
        let reads = *self.reads.borrow_watched() + 1;
        self.reads.send(reads).ok();

        self.open.wait_until_ge(&true).await.ok();
        Ok(vec![EntryOf::<C>::new_blank(log_id(1, 1, start))])
    }

    async fn try_get_log_entries<R>(&mut self, _range: R) -> Result<Vec<EntryOf<C>>, io::Error>
    where R: RangeBounds<u64> + Clone + Debug + OptionalSend {
        unreachable!("replication should use limited_get_log_entries")
    }

    async fn read_vote(&mut self) -> Result<Option<VoteOf<C>>, io::Error> {
        unreachable!()
    }
}

impl RaftLogStorage<C> for GatedLog {
    type LogReader = Self;

    async fn get_log_state(&mut self) -> Result<LogState<C>, io::Error> {
        unreachable!()
    }

    async fn get_log_reader(&mut self) -> Self::LogReader {
        unreachable!()
    }

    async fn save_vote(&mut self, _vote: &VoteOf<C>) -> Result<(), io::Error> {
        unreachable!()
    }

    async fn append<I>(&mut self, _entries: I, _callback: IOFlushed<C>) -> Result<(), io::Error>
    where
        I: IntoIterator<Item = EntryOf<C>> + OptionalSend,
        I::IntoIter: OptionalSend,
    {
        unreachable!()
    }

    async fn truncate_after(&mut self, _last_log_id: Option<LogIdOf<C>>) -> Result<(), io::Error> {
        unreachable!()
    }

    async fn purge(&mut self, _log_id: LogIdOf<C>) -> Result<(), io::Error> {
        unreachable!()
    }
}

/// How [`PullingNetwork`] runs a session.
enum Session {
    /// The response stream ends after the request stream does.
    Answer,
    /// The session fails at once with an RPC error.
    Fail,
    /// The response stream fails after a storage read has started.
    FailAfterRead,
    /// The transport never finishes opening the stream.
    Hang,
    /// Fail setup without consuming input, then use the sequential adapter.
    SetupThenSequential {
        failures: u64,
        backoff: Option<Vec<Duration>>,
    },
    /// The test controls each upload and its response independently.
    Capture {
        sessions: MpscSenderOf<C, CapturedSession>,
        fail_first_open: bool,
    },
}

struct CapturedSession {
    upload: BoxStream<'static, AppendEntriesRequest<C>>,
    /// The responses the session yields, one at a time: a send waits until the replication task has
    /// taken the response before it. Dropping it ends the response stream.
    responses: MpscSenderOf<C, Result<AppendResult<C>, RPCError<C>>>,
}

/// A transport that polls the request stream on a task of its own, as a gRPC client does, and
/// answers no request.
struct PullingNetwork {
    /// The polling task starts once this is `true`.
    poll: WatchReceiverOf<C, bool>,
    /// The number of sessions the replication task has started opening.
    opened: Arc<WatchSenderOf<C, u64>>,
    /// The number of requests the polling task has taken from the stream.
    pulled: Arc<WatchSenderOf<C, u64>>,
    /// Turns `true` once the request stream has ended.
    ended: Arc<WatchSenderOf<C, bool>>,
    session: Session,
    reads: WatchReceiverOf<C, u64>,
}

impl RaftNetworkFactory<C> for PullingNetwork {
    type Network = Self;

    async fn new_client(&mut self, _target: u64, _node: &()) -> Self {
        unreachable!("the test hands the network to the replication task")
    }
}

impl RaftNetworkV2<C> for PullingNetwork {
    type SnapshotData = ();

    fn stream_append<'s, S>(
        &'s mut self,
        mut input: S,
        option: RPCOption,
    ) -> BoxFuture<'s, Result<BoxStream<'s, Result<AppendResult<C>, RPCError<C>>>, RPCError<C>>>
    where
        S: Stream<Item = AppendEntriesRequest<C>> + OptionalSend + Unpin + 'static,
    {
        let opened = *self.opened.borrow_watched() + 1;
        self.opened.send(opened).ok();
        if let Session::Hang = self.session {
            return Box::pin(std::future::pending());
        }
        if let Session::SetupThenSequential { failures, .. } = self.session {
            if opened <= failures {
                let err = RPCError::Unreachable(Unreachable::from_string("stream open failed"));
                return Box::pin(std::future::ready(Err(err)));
            }
            return stream_append_sequential(self, input, option);
        }

        if let Session::Capture {
            sessions,
            fail_first_open,
        } = &self.session
        {
            let fail_open = *fail_first_open && opened == 1;
            let (responses, response_rx) = C::mpsc(1);
            let session = CapturedSession {
                upload: Box::pin(input),
                responses,
            };
            return Box::pin(async move {
                if sessions.send(session).await.is_err() || fail_open {
                    return Err(RPCError::Unreachable(Unreachable::from_string("stream open failed")));
                }

                let response = futures_util::stream::unfold(response_rx, |mut response_rx| async move {
                    let response = response_rx.recv().await?;
                    Some((response, response_rx))
                });
                let response: BoxStream<'s, _> = Box::pin(response);
                Ok(response)
            });
        }

        let mut poll = self.poll.clone();
        let pulled = self.pulled.clone();
        let ended = self.ended.clone();
        let (session_ended, mut session_end_rx) = C::watch_channel(false);
        #[allow(clippy::let_underscore_future)]
        let _ = C::spawn(async move {
            if poll.wait_until_ge(&true).await.is_err() {
                return;
            }

            while input.next().await.is_some() {
                let count = *pulled.borrow_watched() + 1;
                pulled.send(count).ok();
            }
            ended.send(true).ok();
            session_ended.send(true).ok();
        });

        let mut reads = self.reads.clone();
        let responses: BoxStream<'s, Result<AppendResult<C>, RPCError<C>>> =
            if matches!(self.session, Session::Fail | Session::FailAfterRead) {
                let wait_read = matches!(self.session, Session::FailAfterRead);
                let error = RPCError::Unreachable(Unreachable::from_string("node 2 is down"));
                Box::pin(futures_util::stream::once(async move {
                    if wait_read {
                        reads.wait_until_ge(&1).await.unwrap();
                    }
                    Err(error)
                }))
            } else {
                let end = async move {
                    session_end_rx.wait_until_ge(&true).await.ok();
                };
                Box::pin(futures_util::stream::once(end).filter_map(|()| futures_util::future::ready(None)))
            };
        Box::pin(futures_util::future::ready(Ok(responses)))
    }

    fn backoff(&self) -> Option<Backoff> {
        match &self.session {
            Session::SetupThenSequential { backoff, .. } => {
                backoff.clone().map(|delays| Backoff::new(delays.into_iter()))
            }
            _ => None,
        }
    }

    async fn append_entries(
        &mut self,
        rpc: AppendEntriesRequest<C>,
        _option: RPCOption,
    ) -> Result<AppendResult<C>, RPCError<C>> {
        assert!(matches!(self.session, Session::SetupThenSequential { .. }));
        let pulled = *self.pulled.borrow_watched() + 1;
        self.pulled.send(pulled).unwrap();
        Ok(Ok(rpc.log_id_range().last))
    }

    async fn vote(&mut self, _rpc: VoteRequest<C>, _option: RPCOption) -> Result<VoteResponse<C>, RPCError<C>> {
        unreachable!()
    }

    async fn full_snapshot(
        &mut self,
        _vote: VoteOf<C>,
        _snapshot: SnapshotOf<C, ()>,
        _cancel: impl Future<Output = ReplicationClosed> + OptionalSend + 'static,
        _option: RPCOption,
    ) -> Result<SnapshotResponse<C>, StreamingError<C>> {
        unreachable!()
    }
}

/// The channels a test drives and watches a replication task to node 2 through.
struct Harness {
    replicate_tx: WatchSenderOf<C, Option<Replicate<C>>>,
    committed_tx: WatchSenderOf<C, Option<LogIdOf<C>>>,
    notifications: MpscReceiverOf<C, Notification<C>>,
    reads: WatchReceiverOf<C, u64>,
    open_reads: WatchSenderOf<C, bool>,
    poll: WatchSenderOf<C, bool>,
    opened: WatchReceiverOf<C, u64>,
    pulled: WatchReceiverOf<C, u64>,
    ended: WatchReceiverOf<C, bool>,
    /// Resolves once the replication task returns.
    join: JoinHandleOf<C, Result<(), ReplicationClosed>>,
    /// Dropping it closes the stream, as RaftCore does.
    cancel_tx: WatchSenderOf<C, ()>,
    backoff_reset_tx: WatchSenderOf<C, ()>,
}

/// Spawn a replication task to node 2, whose log is submitted through index 20 and matches it
/// through index 5. `open_reads` lets log reads return at once, `poll` lets the transport poll the
/// request stream at once, and `session` sets how the transport runs each session, see
/// [`PullingNetwork`]. Next to the harness, it returns a value that keeps the other channels of the
/// task open.
fn spawn_replication(open_reads: bool, poll: bool, session: Session) -> (Harness, impl Sized) {
    spawn_replication_with_config(open_reads, poll, session, Config::default())
}

fn spawn_replication_with_config(
    open_reads: bool,
    poll: bool,
    session: Session,
    config: Config,
) -> (Harness, impl Sized) {
    let vote = VoteOf::<C>::new_committed(1, 1).to_committed();
    let (replicate_tx, replicate_rx) = C::watch_channel(None);
    let (committed_tx, committed_rx) = C::watch_channel(None);
    let submitted = IOId::new_log_io(vote.clone(), Some(log_id(1, 1, 20)));
    let (io_tx, io_rx) = C::watch_channel(submitted);
    let (cancel_tx, cancel_rx) = C::watch_channel(());
    let (backoff_reset_tx, backoff_reset_rx) = C::watch_channel(());
    let (probe_tx, quorum_loss_probe_rx) = C::watch_channel(None);
    let (tx_notify, notifications) = C::mpsc(16);
    let (reads_tx, reads) = C::watch_channel(0);
    let (open_reads_tx, open_reads_rx) = C::watch_channel(open_reads);
    let (poll_tx, poll_rx) = C::watch_channel(poll);
    let (opened_tx, opened) = C::watch_channel(0);
    let (pulled_tx, pulled) = C::watch_channel(0);
    let (ended_tx, ended) = C::watch_channel(false);

    let context = ReplicationContext {
        id: 1,
        target: 2,
        leader_vote: vote,
        stream_id: StreamId::new(1),
        config: Arc::new(config),
        tx_notify,
        cancel_rx,
        replicate_batch: SharedReplicateBatch::new(),
        quorum_loss_probe_rx,
    };
    let event_watcher = EventWatcher {
        replicate_rx,
        committed_rx,
        io_accepted_rx: io_rx.clone(),
        io_submitted_rx: io_rx,
    };
    let network = PullingNetwork {
        poll: poll_rx,
        opened: Arc::new(opened_tx),
        pulled: Arc::new(pulled_tx),
        ended: Arc::new(ended_tx),
        session,
        reads: reads.clone(),
    };
    let log = GatedLog {
        reads: Arc::new(reads_tx),
        open: open_reads_rx,
    };

    let join = ReplicationCore::<C, PullingNetwork, GatedLog>::spawn(
        context,
        Some(log_id(1, 1, 5)),
        network,
        log,
        event_watcher,
        backoff_reset_rx,
        tracing::Span::none(),
    );

    let harness = Harness {
        replicate_tx,
        committed_tx,
        notifications,
        reads,
        open_reads: open_reads_tx,
        poll: poll_tx,
        opened,
        pulled,
        ended,
        join,
        cancel_tx,
        backoff_reset_tx,
    };
    (harness, (io_tx, probe_tx))
}

/// Wait for the next notification, which must be the confirmation of the clear `inflight_id`.
async fn expect_cleared(notifications: &mut MpscReceiverOf<C, Notification<C>>, inflight_id: InflightId) {
    let notification = C::timeout(TEST_TIMEOUT, notifications.recv()).await.unwrap().unwrap();
    let cleared = match &notification {
        Notification::ReplicateCleared { inflight_id: id, .. } => *id == inflight_id,
        _ => false,
    };
    assert!(
        cleared,
        "expect the clear {} confirmed, got: {}",
        inflight_id, notification
    );
}

/// Wait for the next notification, which must be the RPC error that ended the session of the plan
/// `inflight_id`.
async fn expect_failed(notifications: &mut MpscReceiverOf<C, Notification<C>>, inflight_id: InflightId) {
    let notification = C::timeout(TEST_TIMEOUT, notifications.recv()).await.unwrap().unwrap();
    let failed = match &notification {
        Notification::ReplicationProgress {
            progress,
            inflight_id: id,
            ..
        } => progress.result.is_err() && *id == Some(inflight_id),
        _ => false,
    };
    assert!(
        failed,
        "expect the RPC error of plan {}, got: {}",
        inflight_id, notification
    );
}

/// Wait for the next notification, which must be the report that the closed stream to node 2
/// reads the log no more.
async fn expect_stopped(notifications: &mut MpscReceiverOf<C, Notification<C>>) {
    let notification = C::timeout(TEST_TIMEOUT, notifications.recv()).await.unwrap().unwrap();
    let stopped = match &notification {
        Notification::ReplicationStopped { stream_id, target } => *stream_id == StreamId::new(1) && *target == 2,
        _ => false,
    };
    assert!(
        stopped,
        "expect the report that the stream reads the log no more, got: {}",
        notification
    );
}

/// A read for a plan that RaftCore clears may still be running when the clear arrives. The
/// replication task confirms the clear only once the read has returned and the stream session has
/// ended, and it sends nothing the read returned.
#[test]
fn clear_is_confirmed_once_a_running_read_returns() {
    C::run(async {
        let (mut h, _channels) = spawn_replication(false, true, Session::Answer);
        let plan = InflightId::new(1);
        let clear = InflightId::new(2);

        tracing::info!("--- a plan for the logs after index 5 starts a read, which the log holds");
        {
            h.replicate_tx.send(Some(Replicate::new_logs_since(Some(log_id(1, 1, 5)), plan))).unwrap();
            C::timeout(TEST_TIMEOUT, h.reads.wait_until_ge(&1)).await.unwrap().unwrap();
        }

        tracing::info!("--- RaftCore clears the plan: no confirmation while the read runs");
        {
            h.replicate_tx.send(Some(Replicate::new_clear(clear))).unwrap();

            C::sleep(Duration::from_millis(100)).await;
            let notification = h.notifications.try_recv();
            assert!(notification.is_err(), "expect no notification while the read runs");
        }

        tracing::info!("--- the read returns: the stream sends nothing, and the task confirms the clear");
        {
            h.open_reads.send(true).unwrap();
            expect_cleared(&mut h.notifications, clear).await;

            C::timeout(TEST_TIMEOUT, h.ended.wait_until_ge(&true)).await.unwrap().unwrap();
            assert_eq!(0, *h.pulled.borrow_watched(), "the stream ends without a request");
            assert_eq!(1, *h.reads.borrow_watched());
        }
    });
}

/// A read started before its session failed still holds back confirmation of a clear.
#[test]
fn clear_is_confirmed_once_a_read_that_outlived_its_session_returns() {
    C::run(async {
        let (mut h, _channels) = spawn_replication(false, true, Session::FailAfterRead);
        let plan = InflightId::new(1);
        let clear = InflightId::new(2);

        tracing::info!("--- a plan for the logs after index 5 starts a session, which fails");
        {
            h.replicate_tx.send(Some(Replicate::new_logs_since(Some(log_id(1, 1, 5)), plan))).unwrap();
            expect_failed(&mut h.notifications, plan).await;
        }

        tracing::info!("--- RaftCore clears the plan: no confirmation while the read runs");
        {
            h.replicate_tx.send(Some(Replicate::new_clear(clear))).unwrap();

            C::sleep(Duration::from_millis(100)).await;
            let notification = h.notifications.try_recv();
            assert!(notification.is_err(), "expect no notification while the read runs");
        }

        tracing::info!("--- the read returns: the stream sends nothing, and the task confirms the clear");
        {
            h.open_reads.send(true).unwrap();
            expect_cleared(&mut h.notifications, clear).await;

            C::timeout(TEST_TIMEOUT, h.ended.wait_until_ge(&true)).await.unwrap().unwrap();
            assert_eq!(0, *h.pulled.borrow_watched(), "the stream ends without a request");
            assert_eq!(1, *h.reads.borrow_watched());
        }
    });
}

/// Once the replication task confirms a clear, the request stream of the cleared plan reads
/// nothing, also when the transport polls it only after the session ended. The plan here is a
/// probe, whose stream reads at once instead of waiting for new logs.
#[test]
fn stream_reads_nothing_once_the_clear_is_confirmed() {
    C::run(async {
        let (mut h, _channels) = spawn_replication(true, false, Session::Fail);
        let plan = InflightId::new(1);
        let clear = InflightId::new(2);

        tracing::info!(
            "--- a probe of the entries after index 5 starts a session, which fails before the transport polls"
        );
        {
            let probe = LogIdRange::new(Some(log_id(1, 1, 5)), Some(log_id(1, 1, 9)));
            h.replicate_tx.send(Some(Replicate::new_probe(probe, plan))).unwrap();
            expect_failed(&mut h.notifications, plan).await;
        }

        tracing::info!("--- RaftCore clears the plan, and the task confirms it");
        {
            h.replicate_tx.send(Some(Replicate::new_clear(clear))).unwrap();
            expect_cleared(&mut h.notifications, clear).await;
        }

        tracing::info!("--- the transport polls the stream only now: it ends without a read");
        {
            h.poll.send(true).unwrap();

            C::timeout(TEST_TIMEOUT, h.ended.wait_until_ge(&true)).await.unwrap().unwrap();
            assert_eq!(0, *h.pulled.borrow_watched(), "the stream ends without a request");
            assert_eq!(0, *h.reads.borrow_watched());
        }
    });
}

/// A commit probe whose session ends without an answer is resumed. The task does not replace it
/// with the plan it ran before, which RaftCore did not publish again and may have finished since:
/// here a clear that the task already confirmed.
#[test]
fn unfinished_commit_probe_is_resumed() {
    C::run(async {
        let (mut h, _channels) = spawn_replication(true, true, Session::Answer);
        let clear = InflightId::new(1);

        tracing::info!("--- RaftCore clears the plan for node 2, and the task confirms it");
        {
            h.replicate_tx.send(Some(Replicate::new_clear(clear))).unwrap();
            expect_cleared(&mut h.notifications, clear).await;
        }

        tracing::info!("--- index 5 commits: the task sends a commit probe, which gets no answer");
        {
            h.committed_tx.send(Some(log_id(1, 1, 5))).unwrap();
            C::timeout(TEST_TIMEOUT, h.pulled.wait_until_ge(&1)).await.unwrap().unwrap();
        }

        tracing::info!(
            "--- the task resends the probe, and does not confirm clear {} again",
            clear
        );
        {
            C::timeout(TEST_TIMEOUT, h.pulled.wait_until_ge(&2)).await.unwrap().unwrap();

            if let Ok(notification) = h.notifications.try_recv() {
                panic!("expect no notification, got: {}", notification);
            }
        }
    });
}

/// When RaftCore closes the stream after a session has ended, a read that the transport started on
/// a task of its own may still be running. The replication task returns only once that read has
/// returned, and the stream reads nothing more, because RaftCore purges the logs the task might
/// read once it has returned.
#[test]
fn closed_task_returns_once_a_running_read_returns() {
    C::run(async {
        let (mut h, _channels) = spawn_replication(false, true, Session::FailAfterRead);
        let plan = InflightId::new(1);

        tracing::info!("--- a plan starts a read, then its session fails while the log holds the read");
        {
            h.replicate_tx.send(Some(Replicate::new_logs_since(Some(log_id(1, 1, 5)), plan))).unwrap();
            expect_failed(&mut h.notifications, plan).await;

            C::timeout(TEST_TIMEOUT, h.reads.wait_until_ge(&1)).await.unwrap().unwrap();
        }

        tracing::info!("--- RaftCore closes the stream: the task does not return while the read runs");
        {
            drop(h.replicate_tx);
            drop(h.cancel_tx);

            let res = C::timeout(Duration::from_millis(100), &mut h.join).await;
            assert!(res.is_err(), "expect the task to wait for the read, got: {:?}", res);
        }

        tracing::info!("--- the read returns: the task returns, and the stream reads nothing more");
        {
            h.open_reads.send(true).unwrap();
            let res = C::timeout(TEST_TIMEOUT, h.join).await.unwrap();
            assert!(res.is_ok(), "the task returned without panicking: {:?}", res);

            C::timeout(TEST_TIMEOUT, h.ended.wait_until_ge(&true)).await.unwrap().unwrap();
            assert_eq!(1, *h.reads.borrow_watched());
        }
    });
}

/// RaftCore may close the stream while the transport is still opening it. The replication task
/// reports at once that it reads the log no more, because RaftCore runs no purge, and no command
/// queued behind it, until then. It keeps polling the transport, which would reset the stream of a
/// dropped open.
#[test]
fn closed_task_releases_the_log_while_a_stream_is_being_opened() {
    C::run(async {
        let (mut h, _channels) = spawn_replication(true, false, Session::Hang);
        let plan = InflightId::new(1);

        tracing::info!("--- a plan starts a session, whose stream the transport never finishes opening");
        {
            h.replicate_tx.send(Some(Replicate::new_logs_since(Some(log_id(1, 1, 5)), plan))).unwrap();
            C::timeout(TEST_TIMEOUT, h.opened.wait_until_ge(&1)).await.unwrap().unwrap();
        }

        tracing::info!("--- RaftCore closes the stream: the task releases the log, but keeps opening the stream");
        {
            drop(h.replicate_tx);
            drop(h.cancel_tx);

            expect_stopped(&mut h.notifications).await;
            assert_eq!(0, *h.reads.borrow_watched());

            let res = C::timeout(Duration::from_millis(100), &mut h.join).await;
            assert!(
                res.is_err(),
                "expect the task to wait for the transport, got: {:?}",
                res
            );
        }
    });
}

/// When RaftCore closes the stream, the replication task ends the request stream but reads the
/// responses until the transport ends them, even after an error, because a dropped request in
/// flight resets its stream. It reports that it reads the log no more once the read that the
/// transport started has returned, without waiting for the responses, and it reports none of them.
#[test]
fn closed_task_lets_the_transport_finish_its_requests() {
    C::run(async {
        let (sessions, mut captures) = C::mpsc(2);
        let (mut h, _channels) = spawn_replication(true, false, Session::Capture {
            sessions,
            fail_first_open: false,
        });

        tracing::info!("--- a plan sends the entry at index 6, then the transport starts the read of the next one");
        let (responses, pulling) = {
            let plan = InflightId::new(1);
            h.replicate_tx.send(Some(Replicate::new_logs_since(Some(log_id(1, 1, 5)), plan))).unwrap();
            let CapturedSession { mut upload, responses } =
                C::timeout(TEST_TIMEOUT, captures.recv()).await.unwrap().unwrap();

            let request = C::timeout(TEST_TIMEOUT, upload.next()).await.unwrap().unwrap();
            assert_eq!(vec![EntryOf::<C>::new_blank(log_id(1, 1, 6))], request.entries);

            h.open_reads.send(false).unwrap();
            let pulling = C::spawn(async move { upload.next().await.is_none() });
            C::timeout(TEST_TIMEOUT, h.reads.wait_until_ge(&2)).await.unwrap().unwrap();
            (responses, pulling)
        };

        tracing::info!("--- RaftCore closes the stream: the task reports nothing while the read runs");
        {
            drop(h.replicate_tx);
            drop(h.cancel_tx);

            let res = C::timeout(Duration::from_millis(100), h.notifications.recv()).await;
            assert!(res.is_err(), "expect no report before the read returns");
        }

        tracing::info!("--- the read returns: the request stream ends, and the task releases the log");
        {
            h.open_reads.send(true).unwrap();
            let ended = C::timeout(TEST_TIMEOUT, pulling).await.unwrap().unwrap();
            assert!(
                ended,
                "expect the request stream to end instead of sending the entry read"
            );

            expect_stopped(&mut h.notifications).await;
        }

        tracing::info!("--- the task reads the response to index 6, then reads on after an error");
        {
            let res = C::timeout(Duration::from_millis(100), &mut h.join).await;
            assert!(res.is_err(), "expect the task to wait for the response stream to end");

            let error = RPCError::Unreachable(Unreachable::from_string("node 2 is down"));
            let ack = || Ok(Ok(Some(log_id(1, 1, 6))));
            for response in [ack(), Err(error), ack()] {
                let sent = C::timeout(TEST_TIMEOUT, responses.send(response)).await.unwrap();
                sent.expect("the task keeps reading the response stream");
            }

            let res = C::timeout(Duration::from_millis(100), &mut h.join).await;
            assert!(
                res.is_err(),
                "expect the task to read on after the error, until the stream ends"
            );
        }

        tracing::info!("--- the transport ends the responses: the task returns, and has reported none of them");
        {
            drop(responses);

            let res = C::timeout(TEST_TIMEOUT, h.join).await.unwrap();
            let closed = res.expect("the task returned without panicking");
            assert!(closed.is_err(), "expect the task to return because it was closed");

            let notification = C::timeout(TEST_TIMEOUT, h.notifications.recv()).await.unwrap();
            assert!(notification.is_none(), "expect no report after the close");
        }
    });
}

/// Response EOF releases an upload that is already waiting for more logs.
#[test]
fn response_eof_releases_idle_upload() {
    C::run(async {
        let (sessions, mut captures) = C::mpsc(2);
        let (h, _channels) = spawn_replication(true, false, Session::Capture {
            sessions,
            fail_first_open: false,
        });
        let idle = Replicate::new_logs_since(Some(log_id(1, 1, 20)), InflightId::new(1));

        tracing::info!("--- wait for logs beyond the submitted index, then close the response of that upload");
        {
            h.replicate_tx.send(Some(idle)).unwrap();
            let mut session = C::timeout(TEST_TIMEOUT, captures.recv()).await.unwrap().unwrap();
            let pending = session.upload.next().now_or_never();
            assert!(pending.is_none(), "the upload should wait for more logs");

            drop(session.responses);
            let request = C::timeout(TEST_TIMEOUT, session.upload.next()).await.expect("EOF must release the upload");
            assert!(request.is_none(), "the upload should end at EOF");
        }
    });
}

/// An upload retained after an open error must end while its replacement holds the log reader.
#[test]
fn failed_open_releases_upload_while_replacement_reads() {
    C::run(async {
        let (sessions, mut captures) = C::mpsc(2);
        let (mut h, _channels) = spawn_replication(false, false, Session::Capture {
            sessions,
            fail_first_open: true,
        });

        tracing::info!("--- retain the upload from the failed open");
        let mut failed = {
            let plan = InflightId::new(1);
            let logs = Replicate::new_logs_since(Some(log_id(1, 1, 5)), plan);
            h.replicate_tx.send(Some(logs)).unwrap();
            let session = C::timeout(TEST_TIMEOUT, captures.recv()).await.unwrap().unwrap();
            expect_failed(&mut h.notifications, plan).await;
            session
        };

        tracing::info!("--- poll the failed upload while the replacement holds the log reader");
        {
            let prev = Some(log_id(1, 1, 8));
            let logs = Replicate::new_logs_since(prev, InflightId::new(2));
            h.replicate_tx.send(Some(logs)).unwrap();
            let mut replacement = C::timeout(TEST_TIMEOUT, captures.recv()).await.unwrap().unwrap();
            let pending = replacement.upload.next().now_or_never();
            assert!(pending.is_none(), "the replacement should wait for storage");
            C::timeout(TEST_TIMEOUT, h.reads.wait_until_ge(&1)).await.unwrap().unwrap();

            let request = C::timeout(TEST_TIMEOUT, failed.upload.next())
                .await
                .expect("the failed upload must end without waiting for storage");
            assert!(request.is_none(), "the failed upload should end without a request");

            h.open_reads.send(true).unwrap();
            let request = C::timeout(TEST_TIMEOUT, replacement.upload.next()).await.unwrap().unwrap();
            let entries = vec![EntryOf::<C>::new_blank(log_id(1, 1, 9))];
            assert_eq!(prev, request.prev_log_id);
            assert_eq!(entries, request.entries);
        }
    });
}

/// A transport may keep the request stream of a session that has ended without polling it again.
/// A stream waiting for new logs holds no lock then, so the next session reads and sends its
/// entries, and the old stream, polled at last, ends without a request.
#[test]
fn kept_upload_of_an_ended_session_does_not_block_the_next_one() {
    C::run(async {
        let (sessions, mut captures) = C::mpsc(2);
        let (h, _channels) = spawn_replication(true, false, Session::Capture {
            sessions,
            fail_first_open: false,
        });

        tracing::info!(
            "--- session 1 waits for logs after index 20; RaftCore publishes another plan, and the session ends"
        );
        let mut kept = {
            let idle = Replicate::new_logs_since(Some(log_id(1, 1, 20)), InflightId::new(1));
            h.replicate_tx.send(Some(idle)).unwrap();
            let CapturedSession { mut upload, responses } =
                C::timeout(TEST_TIMEOUT, captures.recv()).await.unwrap().unwrap();
            let pending = upload.next().now_or_never();
            assert!(pending.is_none(), "the upload should wait for more logs");

            let next = Replicate::new_logs_since(Some(log_id(1, 1, 5)), InflightId::new(2));
            h.replicate_tx.send(Some(next)).unwrap();
            drop(responses);
            upload
        };

        tracing::info!(
            "--- the transport keeps session 1's upload without polling it: session 2 sends the entry at index 6"
        );
        let _second = {
            let mut second = C::timeout(TEST_TIMEOUT, captures.recv()).await.unwrap().unwrap();
            let request = C::timeout(TEST_TIMEOUT, second.upload.next()).await.unwrap().unwrap();
            assert_eq!(Some(log_id(1, 1, 5)), request.prev_log_id);
            assert_eq!(vec![EntryOf::<C>::new_blank(log_id(1, 1, 6))], request.entries);
            second
        };

        tracing::info!("--- the transport polls session 1's upload at last: it ends without a request");
        {
            let request = C::timeout(TEST_TIMEOUT, kept.next()).await.unwrap();
            assert!(request.is_none(), "expect the upload to end, got: {:?}", request);
        }
    });
}

/// A completed read must not give the dead session a request, even before RaftCore changes its
/// plan.
#[test]
fn failed_session_discards_a_running_read_result() {
    C::run(async {
        let (mut h, _channels) = spawn_replication(false, true, Session::FailAfterRead);
        let plan = InflightId::new(1);
        h.replicate_tx.send(Some(Replicate::new_logs_since(Some(log_id(1, 1, 5)), plan))).unwrap();
        expect_failed(&mut h.notifications, plan).await;

        tracing::info!("--- let the failed session's read finish without clearing or replacing its plan");
        h.open_reads.send(true).unwrap();
        let ended = C::timeout(TEST_TIMEOUT, h.ended.wait_until_ge(&true)).await;
        assert!(
            ended.is_ok(),
            "failed session keeps reading after its running read returns"
        );
        assert_eq!(
            *h.pulled.borrow_watched(),
            0,
            "the completed read belongs to an ended session"
        );
        assert_eq!(*h.reads.borrow_watched(), 1);
    });
}