File: test_replication.c

package info (click to toggle)
raft 0.22.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,504 kB
  • sloc: ansic: 37,539; makefile: 264; sh: 77; python: 22
file content (2244 lines) | stat: -rw-r--r-- 98,109 bytes parent folder | download | duplicates (2)
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
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
#include "../../src/progress.h"
#include "../lib/cluster.h"
#include "../lib/runner.h"

struct fixture
{
    FIXTURE_CLUSTER;
};

static void *setUp(const MunitParameter params[], MUNIT_UNUSED void *user_data)
{
    struct fixture *f = munit_malloc(sizeof *f);
    SETUP_CLUSTER();
    return f;
}

static void tearDown(void *data)
{
    struct fixture *f = data;
    TEAR_DOWN_CLUSTER();
    free(f);
}

SUITE(replication)

/* A leader doesn't send an initial no-op barrier entry if its committed index
 * is as big as its last log index. */
TEST(replication, NoInitialBarrier, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with 2 voters. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
        CLUSTER_START(id);
    }

    CLUSTER_TRACE(
        "[   0] 1 > term 1, 1 entry (1^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n");

    /* Server 1 becomes candidate and sends a vote request to server 2. */
    CLUSTER_TRACE(
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n");

    /* Server 1 receives the vote result and becomes leader. It does not append
     * any barrier entry. */
    CLUSTER_TRACE(
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n");

    return MUNIT_OK;
}

/* A leader sends an initial no-op barrier entry if its committed index
 * is behind its last log index. */
TEST(replication, InitialBarrier, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with 2 voters. Server 1 has an additioanl
     * entry. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
        if (id == 1) {
            CLUSTER_ADD_ENTRY(id, RAFT_COMMAND, 1 /* term */, 0 /* payload */);
        }
        CLUSTER_START(id);
    }

    CLUSTER_TRACE(
        "[   0] 1 > term 1, 2 entries (1^1..2^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n");

    /* Server 1 becomes candidate and sends a vote request to server 2. */
    CLUSTER_TRACE(
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is longer (2^1 vs 1^1) -> grant vote\n");

    /* Server 1 receives the vote result and becomes leader. It appends
     * a barrier in order to commit all entries from previous terms. */
    CLUSTER_TRACE(
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           replicate 1 new barrier entry (3^2)\n"
        "           probe server 2 sending 1 entry (3^2)\n");

    return MUNIT_OK;
}

/* After receiving an AppendEntriesResult, a leader has set the feature flags of
 * a node. */
TEST(replication, FeatureFlags, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    struct raft *raft;
    unsigned id;

    /* Bootstrap and start a cluster with 2 voters. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
        CLUSTER_START(id);
    }

    /* Server 1 becomes leader and sends the initial heartbeat. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 1 entry (1^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n");

    /* Features were already populated via RequestVote result. */
    raft = CLUSTER_RAFT(1);
    munit_assert_uint(raft->leader_state.progress[1].features, ==, 1);

    /* Server 2 receives the heartbeat and replies. When server 1 receives the
     * response, the feature flags are set. */
    CLUSTER_TRACE(
        "[ 130] 2 > recv append entries from server 1\n"
        "           no new entries to persist\n"
        "[ 140] 1 > recv append entries result from server 2\n");

    munit_assert_uint(raft->leader_state.progress[1].features, ==, 1);

    return MUNIT_OK;
}

/* A leader keeps sending heartbeat messages at regular intervals to
 * maintain leadership. */
TEST(replication, Heartbeat, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with 2 voters. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
        CLUSTER_START(id);
    }

    /* Server 1 becomes leader. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 1 entry (1^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n");

    /* Server 2 receives the first the heartbeat. */
    CLUSTER_TRACE(
        "[ 130] 2 > recv append entries from server 1\n"
        "           no new entries to persist\n");

    /* Server 2 receives a second heartbeat. */
    CLUSTER_TRACE(
        "[ 140] 1 > recv append entries result from server 2\n"
        "[ 170] 1 > timeout as leader\n"
        "           pipeline server 2 sending a heartbeat (no entries)\n"
        "[ 180] 2 > recv append entries from server 1\n"
        "           no new entries to persist\n");

    return MUNIT_OK;
}

/* If a leader replicates some entries during a given heartbeat interval, it
 * skips sending the heartbeat for that interval. */
TEST(replication, SkipHeartbeatIfEntriesHaveSent, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;
    struct raft *raft;
    struct raft_entry entry;

    /* Bootstrap and start a cluster with 2 voters. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
        CLUSTER_START(id);
    }

    /* Server 1 becomes leader. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 1 entry (1^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n"
        "[ 130] 2 > recv append entries from server 1\n"
        "           no new entries to persist\n"
        "[ 140] 1 > recv append entries result from server 2\n");

    raft = CLUSTER_RAFT(1);
    munit_assert_ullong(raft->leader_state.progress[1].last_send, ==, 120);

    /* Server 1 starts replicating a new entry after 5 milliseconds. The
     * heartbeat timeout gets postponed. */
    CLUSTER_ELAPSE(5);

    munit_assert_ullong(raft_timeout(CLUSTER_RAFT(1)), ==, 170);

    entry.term = 2;
    entry.type = RAFT_COMMAND;
    entry.buf.len = 8;
    entry.buf.base = raft_malloc(entry.buf.len);
    munit_assert_not_null(entry.buf.base);
    entry.batch = entry.buf.base;
    CLUSTER_SUBMIT(1 /* ID */, &entry);

    CLUSTER_TRACE(
        "[ 145] 1 > submit 1 new client entry\n"
        "           replicate 1 new command entry (2^2)\n"
        "           pipeline server 2 sending 1 entry (2^2)\n");

    munit_assert_ullong(raft->leader_state.progress[1].last_send, ==, 145);
    munit_assert_ullong(raft_timeout(CLUSTER_RAFT(1)), ==, 195);

    CLUSTER_TRACE(
        "[ 155] 1 > persisted 1 entry (2^2)\n"
        "           next uncommitted entry (2^2) has 1 vote out of 2\n"
        "[ 155] 2 > recv append entries from server 1\n"
        "           start persisting 1 new entry (2^2)\n"
        "[ 165] 2 > persisted 1 entry (2^2)\n"
        "           send success result to 1\n"
        "[ 175] 1 > recv append entries result from server 2\n"
        "           commit 1 new entry (2^2)\n");

    /* When the heartbeat timeout expires again, server 1 sends a fresh
     * heartbeat round.
     *
     * XXX: should we immediately send a heartbeat after the commit index
     *      changes? In order to notify followers. */
    CLUSTER_TRACE(
        "[ 195] 1 > timeout as leader\n"
        "           pipeline server 2 sending a heartbeat (no entries)\n");

    munit_assert_ullong(raft->leader_state.progress[1].last_send, ==, 195);
    munit_assert_ullong(raft_timeout(CLUSTER_RAFT(1)), ==, 245);

    return MUNIT_OK;
}

/* The leader doesn't send replication messages to idle servers. */
TEST(replication, SkipSpare, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with one voter and one spare. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 1 /* voters */);
        CLUSTER_START(id);
    }

    /* Server 1 self-elects, but it does not replicate any entry or send any
     * heartbeat to server 2. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 1 entry (1^1)\n"
        "           self elect and convert to leader\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n"
        "[ 100] 1 > timeout as leader\n");

    CLUSTER_SUBMIT(1 /* ID */, COMMAND, 8 /* size */);

    CLUSTER_TRACE(
        "[ 100] 1 > submit 1 new client entry\n"
        "           replicate 1 new command entry (2^1)\n"
        "[ 110] 1 > persisted 1 entry (2^1)\n"
        "           commit 1 new entry (2^1)\n");

    munit_assert_ullong(raft_commit_index(CLUSTER_RAFT(1)), ==, 2);
    munit_assert_ullong(raft_commit_index(CLUSTER_RAFT(2)), ==, 1);

    return MUNIT_OK;
}

/* A follower remains in probe mode until the leader receives a successful
 * AppendEntries response. */
TEST(replication, Probe, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with 2 voters. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
        CLUSTER_START(id);
    }

    /* Server 1 becomes leader. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 1 entry (1^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n");

    /* Set a network latency higher than the heartbeat timeout for server 2, so
     * server 1 will send a second probe AppendEntries without transitioning to
     * pipeline mode. */
    CLUSTER_SET_NETWORK_LATENCY(2 /* ID */, 100 /* msecs */);

    CLUSTER_TRACE(
        "[ 130] 2 > recv append entries from server 1\n"
        "           no new entries to persist\n");

    /* Server 1 receives a new entry after a few milliseconds. Since the
     * follower is still in probe mode and since an AppendEntries message was
     * already sent recently, it does not send the new entry immediately. */
    CLUSTER_ELAPSE(5);
    CLUSTER_SUBMIT(1 /* ID */, COMMAND, 8 /* size */);

    CLUSTER_TRACE(
        "[ 135] 1 > submit 1 new client entry\n"
        "           replicate 1 new command entry (2^2)\n");

    /* A heartbeat timeout elapses without receiving a response, so server 1
     * sends an new AppendEntries to server 2. This time it includes also the
     * new entry that was accepted in the meantime. */
    CLUSTER_TRACE(
        "[ 145] 1 > persisted 1 entry (2^2)\n"
        "           next uncommitted entry (2^2) has 1 vote out of 2\n"
        "[ 170] 1 > timeout as leader\n"
        "           probe server 2 sending 1 entry (2^2)\n");

    /* Now lower the network latency of server 2, so the AppendEntries result
     * for this last AppendEntries request will get delivered before the
     * response for the original heartbeat AppendEntries request . */
    CLUSTER_SET_NETWORK_LATENCY(2 /* ID */, 10 /* msecs */);

    CLUSTER_TRACE(
        "[ 180] 2 > recv append entries from server 1\n"
        "           start persisting 1 new entry (2^2)\n"
        "[ 190] 2 > persisted 1 entry (2^2)\n"
        "           send success result to 1\n");

    /* Server 1 receives a second entry. Since the follower is still in probe
     * mode and since an AppendEntries message was already sent recently, it
     * does not send the new entry immediately. */
    CLUSTER_ELAPSE(5);
    CLUSTER_SUBMIT(1 /* ID */, COMMAND, 8 /* size */);

    CLUSTER_TRACE(
        "[ 195] 1 > submit 1 new client entry\n"
        "           replicate 1 new command entry (3^2)\n");

    /* Eventually server 1 receives the AppendEntries result for the second
     * request, at that point it transitions to pipeline mode and sends
     * the second entry immediately. */
    CLUSTER_TRACE(
        "[ 200] 1 > recv append entries result from server 2\n"
        "           pipeline server 2 sending 1 entry (3^2)\n"
        "           commit 1 new entry (2^2)\n");

    return MUNIT_OK;
}

/* A follower transitions to pipeline mode after the leader receives a
 * successful AppendEntries response from it. */
TEST(replication, Pipeline, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    struct raft *raft;
    unsigned id;

    /* Bootstrap and start a cluster with 2 voters. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
        CLUSTER_START(id);
    }

    /* Server 1 becomes leader. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 1 entry (1^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n"
        "[ 130] 2 > recv append entries from server 1\n"
        "           no new entries to persist\n"
        "[ 140] 1 > recv append entries result from server 2\n");

    /* Server 1 receives a new entry after 5 milliseconds, just before the
     * heartbeat timeout expires. Since the follower has transitioned to
     * pipeline mode the new entry is sent immediately and the next index is
     * optimistically increased. */
    CLUSTER_ELAPSE(5);
    CLUSTER_SUBMIT(1 /* ID */, COMMAND, 8 /* size */);

    CLUSTER_TRACE(
        "[ 145] 1 > submit 1 new client entry\n"
        "           replicate 1 new command entry (2^2)\n"
        "           pipeline server 2 sending 1 entry (2^2)\n");

    raft = CLUSTER_RAFT(1);
    munit_assert_ullong(raft->leader_state.progress[1].next_index, ==, 3);

    /* After another 15 milliseconds, before receiving the response for this
     * last AppendEntries RPC and before the heartbeat timeout expires, server 1
     * accepts a second entry, which is also replicated immediately. */
    CLUSTER_TRACE(
        "[ 155] 1 > persisted 1 entry (2^2)\n"
        "           next uncommitted entry (2^2) has 1 vote out of 2\n"
        "[ 155] 2 > recv append entries from server 1\n"
        "           start persisting 1 new entry (2^2)\n"
        "[ 165] 2 > persisted 1 entry (2^2)\n"
        "           send success result to 1\n");

    CLUSTER_ELAPSE(5);
    CLUSTER_SUBMIT(1 /* ID */, COMMAND, 8 /* size */);

    CLUSTER_TRACE(
        "[ 170] 1 > submit 1 new client entry\n"
        "           replicate 1 new command entry (3^2)\n"
        "           pipeline server 2 sending 1 entry (3^2)\n");

    munit_assert_ullong(raft->leader_state.progress[1].next_index, ==, 4);

    /* Eventually server 1 receives AppendEntries results for both entries. */
    CLUSTER_TRACE(
        "[ 175] 1 > recv append entries result from server 2\n"
        "           commit 1 new entry (2^2)\n"
        "[ 180] 1 > persisted 1 entry (3^2)\n"
        "           next uncommitted entry (3^2) has 1 vote out of 2\n"
        "[ 180] 2 > recv append entries from server 1\n"
        "           start persisting 1 new entry (3^2)\n"
        "[ 190] 2 > persisted 1 entry (3^2)\n"
        "           send success result to 1\n"
        "[ 200] 1 > recv append entries result from server 2\n"
        "           commit 1 new entry (3^2)\n");

    return MUNIT_OK;
}

/* A follower disconnects while in probe mode. */
TEST(replication, Disconnect, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with 2 voters. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
        CLUSTER_START(id);
    }

    /* Server 1 becomes leader. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 1 entry (1^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n");

    CLUSTER_DISCONNECT(1, 2);

    /* After the heartbeat timeout server 1 retries, this time it succeeds. */
    CLUSTER_TRACE(
        "[ 170] 1 > timeout as leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n");

    CLUSTER_RECONNECT(1, 2);

    CLUSTER_TRACE(
        "[ 180] 2 > recv append entries from server 1\n"
        "           no new entries to persist\n");

    return MUNIT_OK;
}

/* A follower disconnects while in pipeline mode. */
TEST(replication, PipelineDisconnect, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    struct raft *raft;
    unsigned id;

    /* Bootstrap and start a cluster with 2 voters. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
        CLUSTER_START(id);
    }

    /* Server 1 becomes leader and then sends a first round of heartbeats,
     * transitioning server 2 into pipeline mode. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 1 entry (1^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n"
        "[ 130] 2 > recv append entries from server 1\n"
        "           no new entries to persist\n"
        "[ 140] 1 > recv append entries result from server 2\n");

    /* Server 1 starts to replicate a few entries, however server 2 disconnects
     * before it can receive them. */
    CLUSTER_ELAPSE(10);
    CLUSTER_SUBMIT(1 /* ID */, COMMAND, 8 /* size */);
    CLUSTER_SUBMIT(1 /* ID */, COMMAND, 8 /* size */);

    CLUSTER_TRACE(
        "[ 150] 1 > submit 1 new client entry\n"
        "           replicate 1 new command entry (2^2)\n"
        "           pipeline server 2 sending 1 entry (2^2)\n"
        "[ 150] 1 > submit 1 new client entry\n"
        "           replicate 1 new command entry (3^2)\n"
        "           pipeline server 2 sending 1 entry (3^2)\n");

    raft = CLUSTER_RAFT(1);
    munit_assert_ullong(raft->leader_state.progress[1].next_index, ==, 4);

    CLUSTER_DISCONNECT(1, 2);

    /* A full election timeout eventually elapses, and since server 1 did not
     * receive any message from server 2, it transitions server 2 back to probe
     * mode. */
    CLUSTER_TRACE(
        "[ 160] 1 > persisted 1 entry (2^2)\n"
        "           next uncommitted entry (2^2) has 1 vote out of 2\n"
        "[ 160] 1 > persisted 1 entry (3^2)\n"
        "           next uncommitted entry (2^2) has 1 vote out of 2\n"
        "[ 200] 1 > timeout as leader\n"
        "           pipeline server 2 sending a heartbeat (no entries)\n"
        "[ 250] 1 > timeout as leader\n"
        "           server 2 is unreachable -> abort pipeline\n"
        "           probe server 2 sending 2 entries (2^2..3^2)\n");

    munit_assert_ullong(raft->leader_state.progress[1].next_index, ==, 2);

    /* After reconnection the follower eventually replicates the entries and
     * reports back. */
    CLUSTER_RECONNECT(1, 2);

    CLUSTER_TRACE(
        "[ 260] 2 > recv append entries from server 1\n"
        "           start persisting 2 new entries (2^2..3^2)\n"
        "[ 270] 2 > persisted 2 entry (2^2..3^2)\n"
        "           send success result to 1\n");

    return MUNIT_OK;
}

/* Receive the same entry a second time, before the first has been persisted. */
TEST(replication, ReceiveSameEntryTwice, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with 2 voters. The both have an additional
     * uncommitted entry at index 2. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
        CLUSTER_ADD_ENTRY(id, RAFT_COMMAND, 1 /* term */, 0 /* payload */);
        CLUSTER_START(id);
    }

    /* Set a high disk latency for server 2, so persisting the entry at index 2
     * will takes a long time. */
    CLUSTER_SET_DISK_LATENCY(2 /* ID */, 60 /* msecs */);

    /* Server 1 becomes leader and then sends a barrier since it has an
     * uncommitted entry at index 1. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 2 entries (1^1..2^1)\n"
        "[   0] 2 > term 1, 2 entries (1^1..2^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (2^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           replicate 1 new barrier entry (3^2)\n"
        "           probe server 2 sending 1 entry (3^2)\n");

    /* Server 2 takes a long time to persist the entry, and since replication
     * for server 2 is still in the probe state, server 1 eventually sends again
     * the same entry. Server 2 receives it, but it doesn't persist it again to
     * disk, since the first persist request is still in flight. */
    CLUSTER_TRACE(
        "[ 130] 1 > persisted 1 entry (3^2)\n"
        "           next uncommitted entry (2^1) has 1 vote out of 2\n"
        "[ 130] 2 > recv append entries from server 1\n"
        "           start persisting 1 new entry (3^2)\n"
        "[ 170] 1 > timeout as leader\n"
        "           probe server 2 sending 1 entry (3^2)\n");

    /* Eventually the original persist entries request from server 2 succeeds,
     * and is reported back to server 1. */
    CLUSTER_TRACE(
        "[ 180] 2 > recv append entries from server 1\n"
        "           no new entries to persist\n"
        "[ 190] 2 > persisted 1 entry (3^2)\n"
        "           send success result to 1\n"
        "[ 190] 1 > recv append entries result from server 2\n"
        "           pipeline server 2 sending 1 entry (3^2)\n"
        "           next uncommitted entry (2^1) has 2 votes out of 2\n"
        "[ 200] 1 > recv append entries result from server 2\n"
        "           commit 2 new entries (2^1..3^2)\n");

    return MUNIT_OK;
}

/* If the term in the request is stale, the server rejects it. */
TEST(replication, AppendEntriesRequestHasStaleTerm, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with 3 voters. */
    for (id = 1; id <= 3; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 3 /* servers */, 3 /* voters */);
        CLUSTER_START(id);
    }

    /* Server 1 wins the elections. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 1 entry (1^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n"
        "[   0] 3 > term 1, 1 entry (1^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 110] 3 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 3 -> convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n"
        "           probe server 3 sending a heartbeat (no entries)\n");

    /* Partition server 1 from the other two and set a very high election
     * timeout on it, so it will keep sending heartbeats. */
    CLUSTER_SET_ELECTION_TIMEOUT(1 /* ID */, 250 /* timeout */, 0 /* delta */);
    CLUSTER_DISCONNECT(1, 2);
    CLUSTER_DISCONNECT(2, 1);
    CLUSTER_DISCONNECT(1, 3);
    CLUSTER_DISCONNECT(3, 1);

    /* Server 2 eventually times out and starts an election. */
    CLUSTER_SET_ELECTION_TIMEOUT(2 /* ID */, 30 /* timeout */, 0 /* delta */);
    CLUSTER_TRACE(
        "[ 140] 2 > timeout as follower\n"
        "           convert to candidate, start election for term 3\n");

    /* Reconnect server 1 with server 3, so server 3 will receive the next
     * hearbeat that server 1 sends to it */
    CLUSTER_RECONNECT(1, 3);
    CLUSTER_RECONNECT(3, 1);

    /* Eventually server 2 gets elected and server 1 sends a new heartbeat. */
    CLUSTER_TRACE(
        "[ 150] 3 > recv request vote from server 2\n"
        "           remote term is higher (3 vs 2) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 160] 2 > recv request vote result from server 3\n"
        "           quorum reached with 2 votes out of 3 -> convert to leader\n"
        "           probe server 1 sending a heartbeat (no entries)\n"
        "           probe server 3 sending a heartbeat (no entries)\n");

    /* Server 3 receives the heartbeat from server 1 and rejects it. */
    CLUSTER_TRACE(
        "[ 170] 3 > recv append entries from server 2\n"
        "           no new entries to persist\n"
        "[ 170] 1 > timeout as leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n"
        "           probe server 3 sending a heartbeat (no entries)\n"
        "[ 180] 2 > recv append entries result from server 3\n"
        "[ 180] 3 > recv append entries from server 1\n"
        "           local term is higher (3 vs 2) -> reject\n");

    /* Server 1 receives the reject message and steps down. */
    CLUSTER_TRACE(
        "[ 190] 1 > recv append entries result from server 3\n"
        "           remote term is higher (3 vs 2) -> bump term, step down\n");

    return MUNIT_OK;
}

/* If the log of the receiving server is shorter than prevLogIndex, the request
 * is rejected . */
TEST(replication, FollowerHasMissingEntries, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with 2 voters. Server 1 has an entry that
     * server 2 doesn't have. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
        if (id == 1) {
            CLUSTER_ADD_ENTRY(id, RAFT_COMMAND, 1 /* term */, 0 /* payload */);
        }
        CLUSTER_START(id);
    }

    /* Server 1 wins the election because it has a longer log. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 2 entries (1^1..2^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is longer (2^1 vs 1^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           replicate 1 new barrier entry (3^2)\n"
        "           probe server 2 sending 1 entry (3^2)\n"
        "[ 130] 1 > persisted 1 entry (3^2)\n"
        "           next uncommitted entry (2^1) has 1 vote out of 2\n");

    /* Server 1 replicates a no-op entry to server 2, which initially rejects
     * it, because it's missing the one before. */
    CLUSTER_TRACE(
        "[ 130] 2 > recv append entries from server 1\n"
        "           missing previous entry (2^1) -> reject\n");

    /* Server 1 sends the missing entry. */
    CLUSTER_TRACE(
        "[ 140] 1 > recv append entries result from server 2\n"
        "           log mismatch -> send old entries\n"
        "           probe server 2 sending 2 entries (2^1..3^2)\n"
        "[ 150] 2 > recv append entries from server 1\n"
        "           start persisting 2 new entries (2^1..3^2)\n"
        "[ 160] 2 > persisted 2 entry (2^1..3^2)\n"
        "           send success result to 1\n"
        "[ 170] 1 > recv append entries result from server 2\n"
        "           commit 2 new entries (2^1..3^2)\n");

    return MUNIT_OK;
}

/* If the term of the last log entry on the server is different from the one
 * in prevLogTerm, and value of prevLogIndex is greater than the server's commit
 * index (i.e. this is a normal inconsistency), we reject the request. */
TEST(replication, PrevLogTermMismatch, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;
    return 0;

    /* Bootstrap and start a cluster with 2 voters. The two servers have an
     * entry with conflicting terms at index 2. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 3 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
    }
    CLUSTER_ADD_ENTRY(1, RAFT_COMMAND, 3 /* term */, 0 /* payload */);
    CLUSTER_ADD_ENTRY(2, RAFT_COMMAND, 2 /* term */, 0 /* payload */);
    CLUSTER_START(1);
    CLUSTER_START(2);

    /* Server 1 becomes leader because its last entry has a higher term. */
    CLUSTER_TRACE(
        "[   0] 1 > term 3, 2 entries (1^1..2^3)\n"
        "[   0] 2 > term 3, 2 entries (1^1..2^2)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 4\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (4 vs 3) -> bump term\n"
        "           local log older (2^2 vs 2^3) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           replicate 1 new entry (3^4)\n"
        "           probe server 2 sending 1 entry (3^4)\n");

    /* Server 2 rejects the initial AppendEntries request from server 1. */
    CLUSTER_TRACE(
        "[ 130] 1 > persisted 1 entry (3^4)\n"
        "           next uncommitted entry (3^4) has 1 vote out of 2\n"
        "[ 130] 2 > recv append entries from server 1\n"
        "           previous term mismatch -> reject\n");

    /* Server 1 overwrites server 2's log. */
    CLUSTER_TRACE(
        "[ 140] 1 > recv append entries result from server 2\n"
        "           log mismatch -> send old entries\n"
        "           probe server 2 sending 2 entries (2.3..3.4)\n"
        "[ 150] 2 > recv append entries from server 1\n"
        "           log mismatch (2^2 vs 2^3) -> truncate\n"
        "           start persisting 2 new entries (2^3..3^4)\n"
        "[ 160] 2 > persisted 2 entry (2^3..3^4)\n"
        "           send success result to 1\n"
        "[ 160] 1 > timeout as leader\n"
        "[ 170] 1 > recv append entries result from server 2\n"
        "           commit 2 new entries (2^3..3^4)\n");

    return MUNIT_OK;
}

/* The follower has an uncommitted log entry that conflicts with a new one sent
 * by the leader (same index but different term). The follower's conflicting log
 * entry happens to be a configuration change. In that case the follower
 * discards the conflicting entry from its log and rolls back its configuration
 * to the initial one contained in the log entry at index 1. */
TEST(replication, RollbackConfigurationToInitial, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;
    struct raft_configuration conf; /* Uncommitted configuration at index 2 */
    struct raft_entry entry;
    struct raft *raft;
    int rv;

    /* Bootstrap and start a cluster with 2 voters. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 2 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
    }

    /* Both servers have an entry at index 2, but with conflicting terms. The
     * entry of the second server is a configuration change. */
    CLUSTER_ADD_ENTRY(1 /* ID */, RAFT_COMMAND, 2 /* term */, 0 /* payload */);

    CLUSTER_FILL_CONFIGURATION(&conf, 2 /* n */, 2 /* voters */, 0 /* stand */);
    entry.type = RAFT_CHANGE;
    entry.term = 1;
    rv = raft_configuration_add(&conf, 3, "3", 2);
    munit_assert_int(rv, ==, 0);
    raft_configuration_encode(&conf, &entry.buf);
    munit_assert_int(rv, ==, 0);
    CLUSTER_ADD_ENTRY(2 /* ID */, &entry);
    raft_free(entry.buf.base);
    raft_configuration_close(&conf);

    /* At startup the server 2 uses the most recent configuration, i.e. the
     * one contained in the entry that we just added. The server can't know yet
     * if it's committed or not, and regards it as pending configuration
     * change. */
    CLUSTER_START(1 /* ID */);
    CLUSTER_START(2 /* ID */);
    CLUSTER_TRACE(
        "[   0] 1 > term 2, 2 entries (1^1..2^2)\n"
        "[   0] 2 > term 2, 2 entries (1^1..2^1)\n");

    raft = CLUSTER_RAFT(2);
    munit_assert_uint(raft->configuration.n, ==, 3);
    munit_assert_ullong(raft->configuration_uncommitted_index, ==, 2);
    munit_assert_ullong(raft->configuration_committed_index, ==, 1);

    /* Server 1 gets elected. */
    CLUSTER_TRACE(
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 3\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (3 vs 2) -> bump term\n"
        "           remote log is more recent (2^2 vs 2^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           replicate 1 new barrier entry (3^3)\n"
        "           probe server 2 sending 1 entry (3^3)\n");

    /* Server 2 eventually replicates the server 1's log entry at index 2,
     * truncating its own log and rolling back to the configuration contained in
     * the log entry at index 1. */
    CLUSTER_TRACE(
        "[ 130] 1 > persisted 1 entry (3^3)\n"
        "           next uncommitted entry (2^2) has 1 vote out of 2\n"
        "[ 130] 2 > recv append entries from server 1\n"
        "           previous term mismatch -> reject\n"
        "[ 140] 1 > recv append entries result from server 2\n"
        "           log mismatch -> send old entries\n"
        "           probe server 2 sending 2 entries (2^2..3^3)\n"
        "[ 150] 2 > recv append entries from server 1\n"
        "           log mismatch (2^1 vs 2^2) -> truncate\n"
        "           roll back uncommitted configuration (2^1)\n"
        "           start persisting 2 new entries (2^2..3^3)\n");

    munit_assert_uint(raft->configuration.n, ==, 2);
    munit_assert_ullong(raft->configuration_uncommitted_index, ==, 0);
    munit_assert_ullong(raft->configuration_committed_index, ==, 1);

    return MUNIT_OK;
}

/* The follower has an uncommitted log entry that conflicts with a new one sent
 * by the leader (same index but different term). The follower's conflicting log
 * entry happens to be a configuration change. There's also an older committed
 * configuration entry present. In that case the follower discards the
 * conflicting entry from its log and rolls back its configuration to the
 * committed one in the older configuration entry. */
TEST(replication, RollbackConfigurationToPrevious, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;
    struct raft_entry entry;
    struct raft_configuration conf; /* Uncommitted configuration at index 3 */
    struct raft *raft;
    int rv;

    /* Bootstrap a cluster with 2 voters. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 3 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
    }

    /* Both servers have a matching configuration entry at index 2. */
    CLUSTER_ADD_ENTRY(1, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
    CLUSTER_ADD_ENTRY(2, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);

    /* Both servers have an entry at index 3, but with conflicting terms. The
     * entry of the second server is a configuration change. */
    CLUSTER_ADD_ENTRY(1, RAFT_COMMAND, 2 /* term */, 0 /* payload */);

    CLUSTER_FILL_CONFIGURATION(&conf, 2 /* n */, 2 /* voters */, 0 /* stand */);
    entry.type = RAFT_CHANGE;
    entry.term = 1;
    raft_configuration_add(&conf, 3, "3", 2);
    rv = raft_configuration_encode(&conf, &entry.buf);
    munit_assert_int(rv, ==, 0);
    CLUSTER_ADD_ENTRY(2, &entry);
    raft_configuration_close(&conf);
    raft_free(entry.buf.base);

    CLUSTER_START(1);
    CLUSTER_START(2);

    /* At startup the second server uses the most recent configuration, i.e. the
     * one contained in the log entry at index 3. The server can't know yet if
     * it's committed or not, and regards it as pending configuration change. */
    CLUSTER_TRACE(
        "[   0] 1 > term 3, 3 entries (1^1..3^2)\n"
        "[   0] 2 > term 3, 3 entries (1^1..3^1)\n");

    raft = CLUSTER_RAFT(2);
    munit_assert_uint(raft->configuration.n, ==, 3);
    munit_assert_ullong(raft->configuration_uncommitted_index, ==, 3);
    munit_assert_ullong(raft->configuration_committed_index, ==, 2);

    /* The first server gets elected. */
    CLUSTER_TRACE(
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 4\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (4 vs 3) -> bump term\n"
        "           remote log is more recent (3^2 vs 3^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           replicate 1 new barrier entry (4^4)\n"
        "           probe server 2 sending 1 entry (4^4)\n");
    return 0;

    /* Server 2 eventually replicates the server 1's log entry at index 3,
     * truncating its own log and rolling back to the configuration contained in
     * the log entry at index 2. */
    CLUSTER_TRACE(
        "[ 130] 1 > persisted 1 entry (4^4)\n"
        "           next uncommitted entry (4^4) has 1 vote out of 2\n"
        "[ 130] 2 > recv append entries from server 1\n"
        "           previous term mismatch -> reject\n"
        "[ 140] 1 > recv append entries result from server 2\n"
        "           log mismatch -> send old entries\n"
        "           probe server 2 sending 2 entries (3.2..4.4)\n"
        "[ 150] 2 > recv append entries from server 1\n"
        "           log mismatch (3^1 vs 3^2) -> truncate\n"
        "           roll back uncommitted configuration (3^1)\n"
        "           start persisting 2 new entries (3^2..4^4)\n")

    munit_assert_uint(raft->configuration.n, ==, 2);
    munit_assert_ullong(raft->configuration_uncommitted_index, ==, 0);
    munit_assert_ullong(raft->configuration_committed_index, ==, 2);

    return MUNIT_OK;
}

/* The follower has an uncommitted log entry that conflicts with a new one sent
 * by the leader (same index but different term). The follower's conflicting log
 * entry happens to be a configuration change. The follower's log has been
 * truncated after a snashot and does not contain the previous committed
 * configuration anymore. In that case the follower discards the conflicting
 * entry from its log and rolls back its configuration to the previous committed
 * one, which was cached when the snapshot was restored. */
TEST(replication, RollbackConfigurationToSnapshot, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    struct raft_entry entry;
    struct raft_configuration conf; /* Uncommitted configuration at index 2 */
    struct raft *raft;
    int rv;

    /* Bootstrap server 1, creating a log entry at index 1 containing
     * the initial configuration. */
    CLUSTER_SET_TERM(1 /* ID */, 3 /* term */);
    CLUSTER_ADD_ENTRY(1 /* ID */, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);

    /* Server 2 has a snapshot up to entry 1. Entry 1 is not present in the
     * log. */
    CLUSTER_SET_TERM(2 /* ID */, 3 /* term */);
    CLUSTER_SET_SNAPSHOT(2 /*                                               */,
                         1 /* last index                                    */,
                         1 /* last term                                     */,
                         2 /* N servers                                     */,
                         2 /* N voting                                      */,
                         1 /* conf index                                    */);

    /* Both servers have an entry at index 2, but with conflicting terms. The
     * entry of the second server is a configuration change and gets appended to
     * the truncated log. */
    CLUSTER_ADD_ENTRY(1 /* ID */, RAFT_COMMAND, 3 /* term */, 0 /* payload */);

    CLUSTER_FILL_CONFIGURATION(&conf, 2 /* n */, 2 /* voters */, 0 /* stand */);
    entry.type = RAFT_CHANGE;
    entry.term = 2;
    rv = raft_configuration_add(&conf, 3, "3", 2);
    munit_assert_int(rv, ==, 0);
    rv = raft_configuration_encode(&conf, &entry.buf);
    munit_assert_int(rv, ==, 0);
    CLUSTER_ADD_ENTRY(2 /* ID */, &entry);
    raft_configuration_close(&conf);
    raft_free(entry.buf.base);

    /* At startup server 2 uses the most recent configuration, i.e. the one
     * contained in the log entry at index 2. The server can't know yet if it's
     * committed or not, and regards it as pending configuration change. */
    CLUSTER_START(1 /* ID */);
    CLUSTER_START(2 /* ID */);
    CLUSTER_TRACE(
        "[   0] 1 > term 3, 2 entries (1^1..2^3)\n"
        "[   0] 2 > term 3, 1 snapshot (1^1), 1 entry (2^2)\n");

    raft = CLUSTER_RAFT(2);
    munit_assert_uint(raft->configuration.n, ==, 3);
    munit_assert_ullong(raft->configuration_uncommitted_index, ==, 2);
    munit_assert_ullong(raft->configuration_committed_index, ==, 1);

    /* Server 1 becomes leader. */
    CLUSTER_TRACE(
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 4\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (4 vs 3) -> bump term\n"
        "           remote log is more recent (2^3 vs 2^2) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           replicate 1 new barrier entry (3^4)\n"
        "           probe server 2 sending 1 entry (3^4)\n");

    /* Server 2 eventually replicates the server 1's log entry at index 3,
     * truncating its own log and rolling back to the configuration contained in
     * the snapshot, which is not present in the log anymore but was cached at
     * startup. */
    CLUSTER_TRACE(
        "[ 130] 1 > persisted 1 entry (3^4)\n"
        "           next uncommitted entry (2^3) has 1 vote out of 2\n"
        "[ 130] 2 > recv append entries from server 1\n"
        "           previous term mismatch -> reject\n"
        "[ 140] 1 > recv append entries result from server 2\n"
        "           log mismatch -> send old entries\n"
        "           probe server 2 sending 2 entries (2^3..3^4)\n"
        "[ 150] 2 > recv append entries from server 1\n"
        "           log mismatch (2^2 vs 2^3) -> truncate\n"
        "           roll back uncommitted configuration (2^2)\n"
        "           start persisting 2 new entries (2^3..3^4)\n");

    munit_assert_uint(raft->configuration.n, ==, 2);
    munit_assert_ullong(raft->configuration_uncommitted_index, ==, 0);
    munit_assert_ullong(raft->configuration_committed_index, ==, 1);

    return MUNIT_OK;
}

/* A write log request is submitted for outstanding log entries. If some entries
 * are already existing in the log, they will be skipped. */
TEST(replication, SkipExistingEntries, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with 2 voters. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
        CLUSTER_START(id);
    }

    /* Server 1 becomes leader. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 1 entry (1^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n");

    /* The follower receives and responds to the first heartbeat, and the leader
     * transitions it to pipeline mode. */
    CLUSTER_TRACE(
        "[ 130] 2 > recv append entries from server 1\n"
        "           no new entries to persist\n"
        "[ 140] 1 > recv append entries result from server 2\n");

    /* Submit a new entry. */
    CLUSTER_SUBMIT(1 /* ID */, COMMAND, 8 /* size */);

    /* The follower eventually receive the entry. */
    CLUSTER_TRACE(
        "[ 140] 1 > submit 1 new client entry\n"
        "           replicate 1 new command entry (2^2)\n"
        "           pipeline server 2 sending 1 entry (2^2)\n"
        "[ 150] 1 > persisted 1 entry (2^2)\n"
        "           next uncommitted entry (2^2) has 1 vote out of 2\n"
        "[ 150] 2 > recv append entries from server 1\n"
        "           start persisting 1 new entry (2^2)\n"
        "[ 160] 2 > persisted 1 entry (2^2)\n"
        "           send success result to 1\n");

    /* The follower disconnects and the leader does not get notified about
     * the result. The leader tries to send a heartbeat but fails, so it
     * transitions the follower back to probe mode and eventually sends the
     * entry again. */
    CLUSTER_DISCONNECT(1, 2);
    CLUSTER_DISCONNECT(2, 1);

    CLUSTER_TRACE(
        "[ 190] 1 > timeout as leader\n"
        "           pipeline server 2 sending a heartbeat (no entries)\n"
        "[ 240] 1 > timeout as leader\n"
        "           server 2 is unreachable -> abort pipeline\n"
        "           probe server 2 sending 1 entry (2^2)\n");

    /* The follower reconnects, it receives the duplicate entry but does not
     * persist again. */
    CLUSTER_RECONNECT(1, 2);
    CLUSTER_RECONNECT(2, 1);
    CLUSTER_TRACE(
        "[ 250] 2 > recv append entries from server 1\n"
        "           no new entries to persist\n");

    return MUNIT_OK;
}

/* If the index and term of the last snapshot on the server matches prevLogIndex
 * and prevLogTerm the request is accepted. */
TEST(replication, MatchingLastSnapshot, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;

    /* Server 1 has 2 entries, at index 1 and. 2 */
    CLUSTER_SET_TERM(1 /* ID */, 2 /* term */);
    CLUSTER_ADD_ENTRY(1 /* ID */, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
    CLUSTER_ADD_ENTRY(1 /* ID */, RAFT_COMMAND, 2 /* term */, 0 /* payload */);

    /* Server 2 has a snapshot up to entry 2 */
    CLUSTER_SET_TERM(2 /* ID */, 2 /* term */);
    CLUSTER_SET_SNAPSHOT(2, /* ID                                        */
                         2, /* last index                                */
                         2, /* last term                                 */
                         2, /* N servers                                 */
                         2, /* N voting                                  */
                         1 /* conf index                                */);

    CLUSTER_START(1 /* ID */);
    CLUSTER_START(2 /* ID */);

    CLUSTER_TRACE(
        "[   0] 1 > term 2, 2 entries (1^1..2^2)\n"
        "[   0] 2 > term 2, 1 snapshot (2^2)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 3\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (3 vs 2) -> bump term\n"
        "           remote log is equal (2^2) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           replicate 1 new barrier entry (3^3)\n"
        "           probe server 2 sending 1 entry (3^3)\n");

    CLUSTER_TRACE(
        "[ 130] 1 > persisted 1 entry (3^3)\n"
        "           next uncommitted entry (2^2) has 1 vote out of 2\n"
        "[ 130] 2 > recv append entries from server 1\n"
        "           start persisting 1 new entry (3^3)\n"
        "[ 140] 2 > persisted 1 entry (3^3)\n"
        "           send success result to 1\n"
        "[ 150] 1 > recv append entries result from server 2\n"
        "           commit 2 new entries (2^2..3^3)\n");

    return MUNIT_OK;
}

/* If a candidate server receives a request containing the same term as its
 * own, it it steps down to follower and accept the request . */
TEST(replication, CandidateRecvRequestWithSameTerm, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with 3 voters and one existing entry. */
    for (id = 1; id <= 3; id++) {
        CLUSTER_SET_TERM(id, 2 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 3 /* servers */, 3 /* voters */);
        CLUSTER_ADD_ENTRY(id, RAFT_COMMAND, 2 /* term */, 0 /* payload */);
        CLUSTER_START(id);
    }

    /* Disconnect server 3 from the other two and set a low election timeout on
     * it, so it will immediately start an election. */
    CLUSTER_DISCONNECT(3, 1);
    CLUSTER_DISCONNECT(1, 3);
    CLUSTER_DISCONNECT(3, 2);
    CLUSTER_DISCONNECT(2, 3);
    CLUSTER_SET_ELECTION_TIMEOUT(3 /* ID */, 50 /* timeout */, 40 /* delta */);

    CLUSTER_TRACE(
        "[   0] 1 > term 2, 2 entries (1^1..2^2)\n"
        "[   0] 2 > term 2, 2 entries (1^1..2^2)\n"
        "[   0] 3 > term 2, 2 entries (1^1..2^2)\n"
        "[  90] 3 > timeout as follower\n"
        "           convert to candidate, start election for term 3\n");

    /* Server 1 wins the election and start replicating a no-op entry since
     * this an uncommitted log entry from another term. */
    CLUSTER_TRACE(
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 3\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (3 vs 2) -> bump term\n"
        "           remote log is equal (2^2) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 3 -> convert to leader\n"
        "           replicate 1 new barrier entry (3^3)\n"
        "           probe server 2 sending 1 entry (3^3)\n"
        "           probe server 3 sending 1 entry (3^3)\n");

    /* Now reconnect server 3, which eventually steps down and replicates the
     * barrier entry. */
    CLUSTER_RECONNECT(3, 1);
    CLUSTER_RECONNECT(1, 3);

    CLUSTER_TRACE(
        "[ 130] 1 > persisted 1 entry (3^3)\n"
        "           next uncommitted entry (2^2) has 1 vote out of 3\n"
        "[ 130] 2 > recv append entries from server 1\n"
        "           start persisting 1 new entry (3^3)\n"
        "[ 130] 3 > recv append entries from server 1\n"
        "           discovered leader (1) -> step down \n"
        "           start persisting 1 new entry (3^3)\n");

    return MUNIT_OK;
}

/* If a candidate server receives an append entries request contaning an higher
 * term than its own, it it steps down to follower and accept the request. */
TEST(replication, CandidateRecvRequestWithHigherTerm, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with 3 voters. */
    for (id = 1; id <= 3; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 3 /* servers */, 3 /* voters */);
        CLUSTER_START(id);
    }

    /* Set a high election timeout on server 2, so it won't become candidate */
    CLUSTER_SET_ELECTION_TIMEOUT(2 /* ID */, 250 /* timeout */, 0 /* delta */);

    /* Disconnect server 3 from the other two. */
    CLUSTER_DISCONNECT(3, 1);
    CLUSTER_DISCONNECT(1, 3);
    CLUSTER_DISCONNECT(3, 2);
    CLUSTER_DISCONNECT(2, 3);

    /* Set a low election timeout on server 1, and disconnect it from server 2,
     * so by the time it starts the second round, server 3 will have turned
     * candidate */
    CLUSTER_SET_ELECTION_TIMEOUT(1 /* ID */, 50 /* timeout */, 47 /* delta */);
    CLUSTER_DISCONNECT(1, 2);
    CLUSTER_DISCONNECT(2, 1);

    /* Server 3 becomes candidate, and server 1 already is candidate. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 1 entry (1^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n"
        "[   0] 3 > term 1, 1 entry (1^1)\n"
        "[  97] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 160] 3 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n");

    /* Server 1 starts a new election, while server 3 is still candidate */
    CLUSTER_SET_ELECTION_TIMEOUT(1 /* ID */, 50 /* timeout */, 14 /* delta */);
    CLUSTER_TRACE(
        "[ 161] 1 > timeout as candidate\n"
        "           stay candidate, start election for term 3\n");

    /* Reconnect the server 1 and server 2, let the election succeed and
     * the initial heartbeat to be sent. */
    CLUSTER_RECONNECT(1, 2);
    CLUSTER_RECONNECT(2, 1);
    CLUSTER_TRACE(
        "[ 171] 2 > recv request vote from server 1\n"
        "           remote term is higher (3 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 181] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 3 -> convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n"
        "           probe server 3 sending a heartbeat (no entries)\n");

    /* Now reconnect the server 3, which eventually steps down when it receives
     * the heartbeat. */
    CLUSTER_RECONNECT(3, 1);
    CLUSTER_RECONNECT(1, 3);
    CLUSTER_TRACE(
        "[ 191] 2 > recv append entries from server 1\n"
        "           no new entries to persist\n"
        "[ 191] 3 > recv append entries from server 1\n"
        "           remote term is higher (3 vs 2) -> bump term, step down\n"
        "           no new entries to persist\n");

    return MUNIT_OK;
}

/* If the server handling the response is not the leader, the result is
 * ignored. */
TEST(replication, ReceiveResultButNotLeader, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with 2 voters. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
        CLUSTER_START(id);
    }

    /* Server 1 becomes leader. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 1 entry (1^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n");

    /* Set a very high-latency for server 2's outgoing messages, so server 1
     * won't get notified about the results for a while. */
    CLUSTER_SET_NETWORK_LATENCY(2 /* ID */, 100 /* latency */);

    /* Set a low election timeout on server 1 so it will step down very soon. */
    CLUSTER_SET_ELECTION_TIMEOUT(1 /* ID */, 30 /* timeout */, 15 /* delta */);

    /* Eventually server 1 steps down becomes candidate. */
    CLUSTER_TRACE(
        "[ 130] 2 > recv append entries from server 1\n"
        "           no new entries to persist\n"
        "[ 150] 1 > timeout as leader\n"
        "           unable to contact majority of cluster -> step down\n"
        "[ 195] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 3\n");

    /* The AppendEntries result eventually gets delivered, but the candidate
     * ignores it. */
    CLUSTER_TRACE(
        "[ 205] 2 > recv request vote from server 1\n"
        "           local server has a leader (server 1) -> reject\n"
        "[ 230] 1 > recv append entries result from server 2\n"
        "           local server is not leader -> ignore\n");

    return MUNIT_OK;
}

/* If the response has a term which is lower than the server's one, it's
 * ignored. */
TEST(replication, ReceiveResultWithLowerTerm, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with 3 voters. */
    for (id = 1; id <= 3; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 3 /* servers */, 3 /* voters */);
        CLUSTER_START(id);
    }

    /* Server 1 becomes leader. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 1 entry (1^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n"
        "[   0] 3 > term 1, 1 entry (1^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 110] 3 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 3 -> convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n"
        "           probe server 3 sending a heartbeat (no entries)\n");

    /* Set a very high-latency for the server 2's outgoing messages, so server 1
     * won't get notified about the results for a while. */
    CLUSTER_SET_NETWORK_LATENCY(2 /* ID */, 80 /* latency */);

    /* Set a high election timeout on server 2, so it won't become candidate */
    CLUSTER_SET_ELECTION_TIMEOUT(2 /* ID */, 500 /* timeout */, 0 /* delta */);

    /* Disconnect server 1 from server 3 and set a low election timeout on it so
     * it will step down very soon. */
    CLUSTER_DISCONNECT(1, 3);
    CLUSTER_DISCONNECT(3, 1);
    CLUSTER_SET_ELECTION_TIMEOUT(1 /* ID */, 20 /* timeout */, 20 /* delta */);

    CLUSTER_TRACE(
        "[ 130] 2 > recv append entries from server 1\n"
        "           no new entries to persist\n"
        "[ 140] 1 > timeout as leader\n"
        "           unable to contact majority of cluster -> step down\n");

    /* Make server 1 become leader again. */
    CLUSTER_RECONNECT(1, 3);
    CLUSTER_RECONNECT(3, 1);
    CLUSTER_TRACE(
        "[ 180] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 3\n"
        "[ 190] 2 > recv request vote from server 1\n"
        "           local server has a leader (server 1) -> reject\n"
        "[ 190] 3 > recv request vote from server 1\n"
        "           remote term is higher (3 vs 2) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 200] 1 > recv request vote result from server 3\n"
        "           quorum reached with 2 votes out of 3 -> convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n"
        "           probe server 3 sending a heartbeat (no entries)\n");

    /* Eventually deliver to server 1 the result message sent by server 2 in the
     * previous term. */
    CLUSTER_TRACE(
        "[ 210] 1 > recv append entries result from server 2\n"
        "           local term is higher (3 vs 2) -> ignore\n");

    return MUNIT_OK;
}

/* If the response has a term which is higher than the server's one, step down
 * to follower. */
TEST(replication, ReceiveResultWithHigherTerm, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with 3 voters. */
    for (id = 1; id <= 3; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 3 /* servers */, 3 /* voters */);
        CLUSTER_START(id);
    }

    /* Server 1 becomes leader. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 1 entry (1^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n"
        "[   0] 3 > term 1, 1 entry (1^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 110] 3 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 3 -> convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n"
        "           probe server 3 sending a heartbeat (no entries)\n");

    /* Set a very high election timeout for server 1 so it won't step down.
     */
    CLUSTER_SET_ELECTION_TIMEOUT(1 /* ID */, 500 /* timeout */, 0 /* delta */);

    /* Disconnect the server 1 from the rest of the cluster. */
    CLUSTER_DISCONNECT(1, 2);
    CLUSTER_DISCONNECT(2, 1);
    CLUSTER_DISCONNECT(1, 3);
    CLUSTER_DISCONNECT(3, 1);

    /* Eventually a new leader gets electected */
    CLUSTER_TRACE(
        "[ 170] 1 > timeout as leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n"
        "           probe server 3 sending a heartbeat (no entries)\n"
        "[ 220] 1 > timeout as leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n"
        "           probe server 3 sending a heartbeat (no entries)\n"
        "[ 240] 2 > timeout as follower\n"
        "           convert to candidate, start election for term 3\n"
        "[ 250] 3 > recv request vote from server 2\n"
        "           remote term is higher (3 vs 2) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 260] 2 > recv request vote result from server 3\n"
        "           quorum reached with 2 votes out of 3 -> convert to leader\n"
        "           probe server 1 sending a heartbeat (no entries)\n"
        "           probe server 3 sending a heartbeat (no entries)\n");

    /* Reconnect the old leader server 1 to the current follower server 3,
     * which eventually replies with an AppendEntries result containing an
     * higher term. */
    CLUSTER_RECONNECT(1, 3);
    CLUSTER_RECONNECT(3, 1);
    CLUSTER_TRACE(
        "[ 270] 3 > recv append entries from server 2\n"
        "           no new entries to persist\n"
        "[ 270] 1 > timeout as leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n"
        "           probe server 3 sending a heartbeat (no entries)\n"
        "[ 280] 2 > recv append entries result from server 3\n"
        "[ 280] 3 > recv append entries from server 1\n"
        "           local term is higher (3 vs 2) -> reject\n"
        "[ 290] 1 > recv append entries result from server 3\n"
        "           remote term is higher (3 vs 2) -> bump term, step down\n");

    return MUNIT_OK;
}

/* A leader with slow disk commits an entry that it hasn't persisted yet,
 * because enough followers to have a majority have aknowledged that they have
 * appended the entry. The leader's last_stored field hence lags behind its
 * commit_index. A new leader gets elected, with a higher commit index, and
 * sends an an entry to the old leader, that needs to update its commit_index
 * taking into account its lagging last_stored. */
TEST(replication, LastStoredLaggingBehindCommitIndex, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with 3 voters. All servers have an
     * uncommitted log entry. */
    for (id = 1; id <= 3; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 3 /* servers */, 3 /* voters */);
        CLUSTER_ADD_ENTRY(id, RAFT_COMMAND, 1 /* term */, 0 /* payload */);
        CLUSTER_START(id);
    }

    /* Server 1 will take a long time to persist the initial barrier entry at
     * index 3. */
    CLUSTER_SET_DISK_LATENCY(1 /* ID */, 1000 /* latency */);

    /* Server 1 gets elected and creates a no-op entry at index 2 */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 2 entries (1^1..2^1)\n"
        "[   0] 2 > term 1, 2 entries (1^1..2^1)\n"
        "[   0] 3 > term 1, 2 entries (1^1..2^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (2^1) -> grant vote\n"
        "[ 110] 3 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (2^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 3 -> convert to leader\n"
        "           replicate 1 new barrier entry (3^2)\n"
        "           probe server 2 sending 1 entry (3^2)\n"
        "           probe server 3 sending 1 entry (3^2)\n");

    /* Server 1 commits the no-op entry at index 2 even if it did not
     * persist it yet. */
    CLUSTER_TRACE(
        "[ 120] 1 > recv request vote result from server 3\n"
        "           local server is leader -> ignore\n"
        "[ 130] 2 > recv append entries from server 1\n"
        "           start persisting 1 new entry (3^2)\n"
        "[ 130] 3 > recv append entries from server 1\n"
        "           start persisting 1 new entry (3^2)\n"
        "[ 140] 2 > persisted 1 entry (3^2)\n"
        "           send success result to 1\n"
        "[ 140] 3 > persisted 1 entry (3^2)\n"
        "           send success result to 1\n"
        "[ 150] 1 > recv append entries result from server 2\n"
        "           next uncommitted entry (2^1) has 2 votes out of 3\n"
        "[ 150] 1 > recv append entries result from server 3\n"
        "           commit 2 new entries (2^1..3^2)\n");

    munit_assert_ullong(CLUSTER_RAFT(1)->last_stored, ==, 2);
    munit_assert_ullong(CLUSTER_RAFT(1)->commit_index, ==, 3);

    /* Server 2 stored barrier entry 3, but did not yet receive a
     * notification from server 1 about the new commit index. */
    munit_assert_ullong(CLUSTER_RAFT(2)->last_stored, ==, 3);
    munit_assert_ullong(CLUSTER_RAFT(2)->commit_index, ==, 1);

    /* Disconnect server 1 from server 2 and 3. */
    CLUSTER_DISCONNECT(1, 2);
    CLUSTER_DISCONNECT(1, 3);

    /* Set a very high election timeout on server 1, so it won't step down
     * for a while, even if disconnected. */
    CLUSTER_SET_ELECTION_TIMEOUT(1, 500 /* timeout */, 0 /* delta */);

    /* Server 2 and 3 eventually timeout and start an election, server 2
     * wins (lower election timeouts to make that happen faster). */
    CLUSTER_SET_ELECTION_TIMEOUT(2, 40 /* timeout */, 0 /* delta */);
    CLUSTER_SET_ELECTION_TIMEOUT(3, 40 /* timeout */, 10 /* delta */);
    CLUSTER_TRACE(
        "[ 170] 1 > timeout as leader\n"
        "           pipeline server 2 sending a heartbeat (no entries)\n"
        "           pipeline server 3 sending a heartbeat (no entries)\n"
        "[ 170] 2 > timeout as follower\n"
        "           convert to candidate, start election for term 3\n"
        "[ 180] 1 > recv request vote from server 2\n"
        "           local server is leader -> reject\n"
        "[ 180] 3 > recv request vote from server 2\n"
        "           local server has a leader (server 1) -> reject\n"
        "[ 180] 3 > timeout as follower\n"
        "           convert to candidate, start election for term 3\n"
        "[ 190] 2 > recv request vote result from server 3\n"
        "           remote term is lower (2 vs 3) -> ignore\n"
        "[ 190] 1 > recv request vote from server 3\n"
        "           local server is leader -> reject\n"
        "[ 190] 2 > recv request vote from server 3\n"
        "           already voted for server 2 -> don't grant vote\n"
        "[ 200] 3 > recv request vote result from server 2\n"
        "           vote not granted\n"
        "[ 210] 2 > timeout as candidate\n"
        "           stay candidate, start election for term 4\n"
        "[ 220] 1 > recv request vote from server 2\n"
        "           local server is leader -> reject\n"
        "[ 220] 3 > recv request vote from server 2\n"
        "           remote term is higher (4 vs 3) -> bump term, step down\n"
        "           remote log is equal (3^2) -> grant vote\n"
        "[ 220] 1 > timeout as leader\n"
        "           server 2 is unreachable -> abort pipeline\n"
        "           server 3 is unreachable -> abort pipeline\n"
        "           probe server 2 sending a heartbeat (no entries)\n"
        "           probe server 3 sending a heartbeat (no entries)\n"
        "[ 230] 2 > recv request vote result from server 3\n"
        "           quorum reached with 2 votes out of 3 -> convert to leader\n"
        "           replicate 1 new barrier entry (4^4)\n"
        "           probe server 1 sending 1 entry (4^4)\n"
        "           probe server 3 sending 1 entry (4^4)\n");

    /* Server 2 commits the barrier entry at index 4 that it created at the
     * start of its term. */
    CLUSTER_TRACE(
        "[ 240] 2 > persisted 1 entry (4^4)\n"
        "           next uncommitted entry (3^2) has 1 vote out of 3\n"
        "[ 240] 1 > recv append entries from server 2\n"
        "           remote term is higher (4 vs 2) -> bump term, step down\n"
        "           start persisting 1 new entry (4^4)\n"
        "[ 240] 3 > recv append entries from server 2\n"
        "           start persisting 1 new entry (4^4)\n"
        "[ 250] 3 > persisted 1 entry (4^4)\n"
        "           send success result to 2\n"
        "[ 260] 2 > recv append entries result from server 3\n"
        "           commit 3 new entries (2^1..4^4)\n");

    /* Reconnect server 1 to server 2, which will replicate entry 4 to
     * it. */
    CLUSTER_RECONNECT(1, 2);

    CLUSTER_TRACE(
        "[ 270] 2 > timeout as leader\n"
        "[ 280] 2 > timeout as leader\n"
        "           server 3 is unreachable -> abort pipeline\n"
        "           probe server 1 sending 1 entry (4^4)\n"
        "           probe server 3 sending a heartbeat (no entries)\n"
        "[ 290] 1 > recv append entries from server 2\n"
        "           no new entries to persist\n");

    return MUNIT_OK;
}

/* A leader with slow disk commits an entry that it hasn't persisted yet,
 * because enough followers to have a majority have aknowledged that they have
 * appended the entry. The leader's last_stored field hence lags behind its
 * commit_index. A new leader gets elected, with a higher commit index and sends
 * first a new entry than a heartbeat to the old leader, that needs to update
 * its commit_index taking into account its lagging last_stored.
 *
 * XXX: this test duplicates the one above, but it's kept because the change it
 * is associated with was fixing an assertion in the legacy compat layer. */

/* A follower finds that is has no leader anymore after it completes persisting
 * entries. No AppendEntries RPC result is sent in that case. */
TEST(replication, NoLeaderAfterPersistingEntries, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with 2 voters. Both have an additional
     * entry at index 2.*/
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
        CLUSTER_ADD_ENTRY(id, RAFT_COMMAND, 1 /* term */, 0 /* payload */);
        CLUSTER_START(id);
    }

    /* Make sure that persisting entries on server 1 will take a long time. */
    CLUSTER_SET_DISK_LATENCY(1 /* ID */, 50 /* latency */);

    /* Server 1 becomes the leader. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 2 entries (1^1..2^1)\n"
        "[   0] 2 > term 1, 2 entries (1^1..2^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (2^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           replicate 1 new barrier entry (3^2)\n"
        "           probe server 2 sending 1 entry (3^2)\n");

    /* Disconnect server 1, so it will step down and become follower (lower
     * its election timeout to make this happen sooner). */
    CLUSTER_DISCONNECT(1, 2);
    CLUSTER_DISCONNECT(2, 1);
    CLUSTER_SET_ELECTION_TIMEOUT(1 /* ID */, 40 /* timeout */, 0 /* delta*/);

    CLUSTER_TRACE(
        "[ 160] 1 > timeout as leader\n"
        "           unable to contact majority of cluster -> step down\n");

    /* Server 1 has stepped down and is now a follower, however its hasn't
     * persisted the barrier entry yet. */
    munit_assert_int(raft_state(CLUSTER_RAFT(1)), ==, RAFT_FOLLOWER);
    munit_assert_ullong(CLUSTER_RAFT(1)->last_stored, ==, 2);

    /* Wait for the long disk write to complete */
    CLUSTER_TRACE("[ 170] 1 > persisted 1 entry (3^2)\n");

    /* The writes have now completed, one for the barrier entry at the start
     * of the term and one for the command entry we submitted. */
    munit_assert_ullong(CLUSTER_RAFT(1)->last_stored, ==, 3);

    return MUNIT_OK;
}

/* While pipelining entries, the leader receives an AppendEntries response with
 * a stale reject index. */
TEST(replication, PipelineStaleRejectedIndex, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with 2 voters. Server 1 has an additional
     * entry at index 2.*/
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
        if (id == 1) {
            CLUSTER_ADD_ENTRY(id, RAFT_COMMAND, 1 /* term */, 0 /* payload */);
        }
        CLUSTER_START(id);
    }

    /* Server 1 becomes the leader. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 2 entries (1^1..2^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is longer (2^1 vs 1^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           replicate 1 new barrier entry (3^2)\n"
        "           probe server 2 sending 1 entry (3^2)\n"
        "[ 130] 1 > persisted 1 entry (3^2)\n"
        "           next uncommitted entry (2^1) has 1 vote out of 2\n");

    /* Server 2 receives a heartbeat with an entry that it does not have, but
     * the network is slow, so server 1 will receive the response much later. */
    CLUSTER_SET_NETWORK_LATENCY(2 /* ID */, 100 /* latency */);
    CLUSTER_TRACE(
        "[ 130] 2 > recv append entries from server 1\n"
        "           missing previous entry (2^1) -> reject\n"
        "[ 170] 1 > timeout as leader\n"
        "           probe server 2 sending 1 entry (3^2)\n");

    /* This time the network is faster, and server 2's response to the second
     * heartbeat will arrive before then first response. */
    CLUSTER_SET_NETWORK_LATENCY(2 /* ID */, 10 /* latency */);
    CLUSTER_TRACE(
        "[ 180] 2 > recv append entries from server 1\n"
        "           missing previous entry (2^1) -> reject\n"
        "[ 190] 1 > recv append entries result from server 2\n"
        "           log mismatch -> send old entries\n"
        "           probe server 2 sending 2 entries (2^1..3^2)\n"
        "[ 200] 2 > recv append entries from server 1\n"
        "           start persisting 2 new entries (2^1..3^2)\n"
        "[ 210] 2 > persisted 2 entry (2^1..3^2)\n"
        "           send success result to 1\n"
        "[ 220] 1 > recv append entries result from server 2\n"
        "           commit 2 new entries (2^1..3^2)\n"
        "[ 220] 1 > timeout as leader\n"
        "[ 230] 1 > recv append entries result from server 2\n"
        "           stale rejected index (2 vs match index 3) -> ignore\n");

    return MUNIT_OK;
}

/* The raft_max_inflight_entries() setting controls how many un-acknowledged
 * entries can be in-flight in pipeline mode. */
TEST(replication, PipelineMaxInflight, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Set the maximum in-flight entries number to 2. */
    raft_set_max_inflight_entries(CLUSTER_RAFT(1), 2);

    /* Bootstrap and start a cluster with 2 voters. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 2 /* servers */, 2 /* voters */);
        CLUSTER_START(id);
    }

    /* Server 1 becomes leader and eventually switches server 2 to pipeline
     * mode. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 1 entry (1^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum reached with 2 votes out of 2 -> convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n"
        "[ 130] 2 > recv append entries from server 1\n"
        "           no new entries to persist\n"
        "[ 140] 1 > recv append entries result from server 2\n"
        "[ 170] 1 > timeout as leader\n"
        "           pipeline server 2 sending a heartbeat (no entries)\n");

    /* Two entries are submitted and immediately sent to server 2. */
    CLUSTER_SUBMIT(1 /* ID */, COMMAND, 8 /* size */);
    CLUSTER_SUBMIT(1 /* ID */, COMMAND, 8 /* size */);

    CLUSTER_TRACE(
        "[ 170] 1 > submit 1 new client entry\n"
        "           replicate 1 new command entry (2^2)\n"
        "           pipeline server 2 sending 1 entry (2^2)\n"
        "[ 170] 1 > submit 1 new client entry\n"
        "           replicate 1 new command entry (3^2)\n"
        "           pipeline server 2 sending 1 entry (3^2)\n");

    CLUSTER_SUBMIT(1 /* ID */, COMMAND, 8 /* size */);

    /* A third entry is submitted, but it's not replicated immediately, because
     * the inflight limit has been reached. */
    CLUSTER_TRACE(
        "[ 170] 1 > submit 1 new client entry\n"
        "           replicate 1 new command entry (4^2)\n"
        "           pipeline server 2 sending a heartbeat (no entries)\n");

    return MUNIT_OK;
}

/* After having sent a snapshot and waiting for a response, the leader receives
 * an AppendEntries response with a stale reject index. */
TEST(replication, StaleRejectedIndexSnapshot, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    struct raft_configuration configuration;
    struct raft_entry entry;
    unsigned id;
    int rv;

    /* Set very low threshold and trailing entries number. */
    CLUSTER_SET_SNAPSHOT_THRESHOLD(1 /* ID */, 3 /* n. entries */);
    CLUSTER_SET_SNAPSHOT_TRAILING(1 /* ID */, 0 /* n. entries */);

    /* Bootstrap and start a cluster with 1 voter and 1 stand-by. Server 1 has
     * an additional entry. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);

        CLUSTER_FILL_CONFIGURATION(&configuration, 2, 1, 1 /* stand-by */);
        entry.type = RAFT_CHANGE;
        entry.term = 1;
        rv = raft_configuration_encode(&configuration, &entry.buf);
        munit_assert_int(rv, ==, 0);
        raft_configuration_close(&configuration);
        test_cluster_add_entry(&f->cluster_, id, &entry);
        raft_free(entry.buf.base);

        if (id == 1) {
            CLUSTER_ADD_ENTRY(id, RAFT_COMMAND, 1 /* term */, 0 /* payload */);
        }

        CLUSTER_START(id);
    }

    /* Server 1 becomes leader. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 2 entries (1^1..2^1)\n"
        "           self elect and convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n");

    /* Server 2 receives a heartbeat with an entry that it does not have, but
     * the network is slow, so server 1 will receive the response much later. */
    CLUSTER_SET_NETWORK_LATENCY(2 /* ID */, 80 /* latency */);
    CLUSTER_TRACE(
        "[  10] 2 > recv append entries from server 1\n"
        "           missing previous entry (2^1) -> reject\n");

    /* Server 1 commits a new entry and takes a snapshot. */
    CLUSTER_SUBMIT(1 /* ID */, COMMAND, 8 /* size */);

    CLUSTER_TRACE(
        "[  10] 1 > submit 1 new client entry\n"
        "           replicate 1 new command entry (3^1)\n"
        "[  20] 1 > persisted 1 entry (3^1)\n"
        "           commit 1 new entry (3^1)\n"
        "[  20] 1 > new snapshot (3^1), 0 trailing entries\n");

    /* Eventually server 2 receives the snapshot, but takes a long time to
     * persist it. */
    CLUSTER_SET_NETWORK_LATENCY(2 /* ID */, 10 /* latency */);
    CLUSTER_SET_DISK_LATENCY(2 /* ID */, 100 /* latency */);
    CLUSTER_TRACE(
        "[  50] 1 > timeout as leader\n"
        "           missing previous entry at index 2 -> needs snapshot\n"
        "           probe server 2 sending a heartbeat (no entries)\n"
        "[  60] 2 > recv append entries from server 1\n"
        "           missing previous entry (3^1) -> reject\n"
        "[  70] 1 > recv append entries result from server 2\n"
        "           log mismatch -> send old entries\n"
        "           missing previous entry at index 1 -> needs snapshot\n"
        "           sending snapshot (3^1) to server 2\n"
        "[  80] 2 > recv install snapshot from server 1\n"
        "           start persisting snapshot (3^1)\n");

    /* Server 1 finally receives the original AppendEntries response and ignores
     * it. */
    CLUSTER_TRACE(
        "[  90] 1 > recv append entries result from server 2\n"
        "           stale rejected index (2 vs snapshot index 3) -> ignore\n");

    return MUNIT_OK;
}

/* If a follower receives a heartbeat containing a prev_log_index which is
 * behind its last_stored index, it sets the last_log_index to the value of
 * prev_log_index. This prevents the follower from telling the leader that it
 * reached a certain index without first checking the log matching property. */
TEST(replication, LastStoredAheadOfPrevLogIndex, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    struct raft_configuration configuration;
    struct raft_entry entry;
    unsigned id;
    int rv;

    /* Bootstrap and start a cluster with 1 voters and 1 stand-by. The stand-by
     * has an additional entry. */
    for (id = 1; id <= 2; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);

        CLUSTER_FILL_CONFIGURATION(&configuration, 2, 1, 1 /* stand-by */);
        entry.type = RAFT_CHANGE;
        entry.term = 1;
        rv = raft_configuration_encode(&configuration, &entry.buf);
        munit_assert_int(rv, ==, 0);
        raft_configuration_close(&configuration);
        test_cluster_add_entry(&f->cluster_, id, &entry);
        raft_free(entry.buf.base);

        if (id == 2) {
            CLUSTER_ADD_ENTRY(id, RAFT_COMMAND, 2 /* term */, 0 /* payload */);
        }

        CLUSTER_START(id);
    }

    /* Start the cluster, server 1 will self elect and send an heartbeat to
     * server 2. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 1 entry (1^1)\n"
        "           self elect and convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n"
        "[   0] 2 > term 1, 2 entries (1^1..2^2)\n");

    /* Submit an entry, which won't be immediately sent to server 2, because
     * it's still in probe mode. */
    CLUSTER_SUBMIT(1 /* ID */, COMMAND, 8 /* size */);
    CLUSTER_TRACE(
        "[   0] 1 > submit 1 new client entry\n"
        "           replicate 1 new command entry (2^1)\n"
        "[  10] 1 > persisted 1 entry (2^1)\n"
        "           commit 1 new entry (2^1)\n");

    /* Server 2 receives the heartbeat from server 1. The two servers have now a
     * conflicting entry at term 2, but since this heartbeat only contains up to
     * entry 1, no conflict is detected yet by server 2, which sends a success
     * result. */
    CLUSTER_TRACE(
        "[  10] 2 > recv append entries from server 1\n"
        "           no new entries to persist\n"
        "[  20] 1 > recv append entries result from server 2\n"
        "           pipeline server 2 sending 1 entry (2^1)\n");

    /* Disconnect server 2, which eventually gets back to probe mode. */
    CLUSTER_DISCONNECT(1, 2);
    CLUSTER_TRACE(
        "[  70] 1 > timeout as leader\n"
        "           pipeline server 2 sending a heartbeat (no entries)\n"
        "[ 120] 1 > timeout as leader\n"
        "           server 2 is unreachable -> abort pipeline\n"
        "           probe server 2 sending 1 entry (2^1)\n");

    /* Reconnect server 2, which eventually receives the conflicting entry at
     * index 2 and truncates its log. */
    CLUSTER_RECONNECT(1, 2);
    CLUSTER_TRACE(
        "[ 130] 2 > recv append entries from server 1\n"
        "           log mismatch (2^2 vs 2^1) -> truncate\n"
        "           start persisting 1 new entry (2^1)\n");

    return MUNIT_OK;
}

/* If a follower completes persisting an entry at an index that was not yet sent
 * by the current leader and checked via the log matching property, no
 * successful result for it will be sent. */
TEST(replication, LastStoredAheadOfLastMatched, setUp, tearDown, 0, NULL)
{
    struct fixture *f = data;
    unsigned id;

    /* Bootstrap and start a cluster with 5 voters. */
    for (id = 1; id <= 5; id++) {
        CLUSTER_SET_TERM(id, 1 /* term */);
        CLUSTER_ADD_ENTRY(id, RAFT_CHANGE, 5 /* servers */, 5 /* voters */);
        CLUSTER_START(id);
    }

    /* Server 1 becomes leader. */
    CLUSTER_TRACE(
        "[   0] 1 > term 1, 1 entry (1^1)\n"
        "[   0] 2 > term 1, 1 entry (1^1)\n"
        "[   0] 3 > term 1, 1 entry (1^1)\n"
        "[   0] 4 > term 1, 1 entry (1^1)\n"
        "[   0] 5 > term 1, 1 entry (1^1)\n"
        "[ 100] 1 > timeout as follower\n"
        "           convert to candidate, start election for term 2\n"
        "[ 110] 2 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 110] 3 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 110] 4 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 110] 5 > recv request vote from server 1\n"
        "           remote term is higher (2 vs 1) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 120] 1 > recv request vote result from server 2\n"
        "           quorum not reached, only 2 votes out of 5\n"
        "[ 120] 1 > recv request vote result from server 3\n"
        "           quorum reached with 3 votes out of 5 -> convert to leader\n"
        "           probe server 2 sending a heartbeat (no entries)\n"
        "           probe server 3 sending a heartbeat (no entries)\n"
        "           probe server 4 sending a heartbeat (no entries)\n"
        "           probe server 5 sending a heartbeat (no entries)\n");

    /* Submit a new entry. */
    CLUSTER_SUBMIT(1 /* ID */, COMMAND, 8 /* size */);

    /* Disconnect server 1 from all servers except server 3, which will be the
     * only one receiving it. */
    CLUSTER_DISCONNECT(1, 2);
    CLUSTER_DISCONNECT(2, 1);
    CLUSTER_DISCONNECT(1, 4);
    CLUSTER_DISCONNECT(4, 1);
    CLUSTER_DISCONNECT(1, 5);
    CLUSTER_DISCONNECT(5, 1);

    /* Server 3 receives it but will take a long time to persist it. */
    CLUSTER_SET_DISK_LATENCY(3 /* ID */, 130 /* latency */);
    CLUSTER_TRACE(
        "[ 120] 1 > submit 1 new client entry\n"
        "           replicate 1 new command entry (2^2)\n"
        "[ 130] 1 > persisted 1 entry (2^2)\n"
        "           next uncommitted entry (2^2) has 1 vote out of 5\n"
        "[ 130] 3 > recv append entries from server 1\n"
        "           no new entries to persist\n"
        "[ 140] 1 > recv append entries result from server 3\n"
        "           pipeline server 3 sending 1 entry (2^2)\n"
        "[ 150] 3 > recv append entries from server 1\n"
        "           start persisting 1 new entry (2^2)\n");

    /* Crash server 1. Eventually server 2 becomes leader with votes from server
     * 4 and 5. */
    CLUSTER_STOP(1 /* ID */);

    CLUSTER_TRACE(
        "[ 240] 2 > timeout as follower\n"
        "           convert to candidate, start election for term 3\n"
        "[ 250] 3 > recv request vote from server 2\n"
        "           local server has a leader (server 1) -> reject\n"
        "[ 250] 4 > recv request vote from server 2\n"
        "           remote term is higher (3 vs 2) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 250] 5 > recv request vote from server 2\n"
        "           remote term is higher (3 vs 2) -> bump term\n"
        "           remote log is equal (1^1) -> grant vote\n"
        "[ 260] 2 > recv request vote result from server 3\n"
        "           remote term is lower (2 vs 3) -> ignore\n"
        "[ 260] 2 > recv request vote result from server 4\n"
        "           quorum not reached, only 2 votes out of 5\n"
        "[ 260] 2 > recv request vote result from server 5\n"
        "           quorum reached with 3 votes out of 5 -> convert to leader\n"
        "           probe server 1 sending a heartbeat (no entries)\n"
        "           probe server 3 sending a heartbeat (no entries)\n"
        "           probe server 4 sending a heartbeat (no entries)\n"
        "           probe server 5 sending a heartbeat (no entries)\n");

    /* Server 3 receives the heartbeat from server 2 and chances its term and
     * leader. */
    CLUSTER_TRACE(
        "[ 270] 3 > recv append entries from server 2\n"
        "           remote term is higher (3 vs 2) -> bump term\n"
        "           no new entries to persist\n");
    CLUSTER_DISCONNECT(3, 2);

    /* Server 3 completes persisting the entry at index 2 that was sent to it by
     * server 1 at term 2. */
    CLUSTER_TRACE(
        "[ 270] 4 > recv append entries from server 2\n"
        "           no new entries to persist\n"
        "[ 270] 5 > recv append entries from server 2\n"
        "           no new entries to persist\n"
        "[ 280] 3 > persisted 1 entry (2^2)\n"
        "           send success result to 2\n");
    CLUSTER_RECONNECT(3, 2);

    /* Submit a new entry to server 2, which will have the same index of the
     * entry that server 3 just persisted. */
    CLUSTER_SUBMIT(2 /* ID */, COMMAND, 8 /* size */);
    CLUSTER_TRACE(
        "[ 280] 2 > submit 1 new client entry\n"
        "           replicate 1 new command entry (2^3)\n"
        "[ 280] 2 > recv append entries result from server 4\n"
        "           pipeline server 4 sending 1 entry (2^3)\n"
        "[ 280] 2 > recv append entries result from server 5\n"
        "           pipeline server 5 sending 1 entry (2^3)\n"
        "[ 290] 2 > persisted 1 entry (2^3)\n"
        "           next uncommitted entry (2^3) has 1 vote out of 5\n");

    /* Server 2 receives the result from server 3, which does *not* contain the
     * conflicting entry. */
    CLUSTER_TRACE(
        "[ 290] 2 > recv append entries result from server 3\n"
        "           pipeline server 3 sending 1 entry (2^3)\n");

    /* Server 3 receives the conflicting entry and replaces its own one. */
    CLUSTER_TRACE(
        "[ 290] 4 > recv append entries from server 2\n"
        "           start persisting 1 new entry (2^3)\n"
        "[ 290] 5 > recv append entries from server 2\n"
        "           start persisting 1 new entry (2^3)\n"
        "[ 300] 3 > recv append entries from server 2\n"
        "           log mismatch (2^2 vs 2^3) -> truncate\n"
        "           start persisting 1 new entry (2^3)\n");

    return MUNIT_OK;
}