kividb 1.2.1

A fast RedisĀ®-compatible in-memory store written in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
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
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
// src/replication/replica_client.rs
//
// Replica handshake and replication stream.
//
// Sequence:
//   1. TCP connect to master
//   2. AUTH [user] <pass>              →  +OK        (only with masterauth)
//   3. PING                            →  +PONG
//   4. REPLCONF listening-port <port>  →  +OK
//   5. REPLCONF capa psync2            →  +OK
//   6. PSYNC <repl_id> <offset+1>      →  +CONTINUE: the stream carries on
//      (PSYNC ? -1 the first time)         from where this replica is; skip to 9
//                                      →  +FULLRESYNC <repl_id> <offset>
//   7. Read the payload: "$<len>\r\n" then <len> raw bytes → staging store
//   8. Dataset guard, then swap staging in
//   9. Command stream: parse RESP inline, execute each write command
//
// Every step is bounded by `repl-timeout`. On any failure the session ends,
// the link is reported down, and the outer loop retries.

use crate::config::Config;
use crate::replication::{FullSyncGuard, HubTx, LinkState, ReplState};
use crate::resp::parse::parse_resp_command;
use crate::store::{self, SharedTsIndex, Store};
use crate::vector::{CompactionTx, DictStore, IndexStore};
use crate::wait_table::WaitTable;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;
use tokio::sync::mpsc;
use tokio::sync::mpsc::error::TryRecvError;

/// Owns the replica link state for the *current* replication task only.
///
/// Link state lives in one shared `ReplState`, but during a re-point
/// (`REPLICAOF` issued while already a slave) two sessions briefly coexist:
/// the newly-spawned task connects and starts streaming from the new master
/// before the superseded task notices its epoch is stale and returns. Without
/// the generation check here, the stale task's `Drop` fires *after* the new
/// task is up and marks the link down — so a replica that is fully caught up
/// and streaming from its new master reports `master_link_status:down`
/// indefinitely (found live: both sessions completed their handshake
/// successfully per the connection log, yet the flag stuck at `false`).
///
/// Every transition therefore only touches the shared state while this
/// guard's generation is still the live one. A superseded task's guard is a
/// no-op instead of overwriting whatever the current generation has set.
struct SlaveUpstreamGuard {
    rs: Arc<ReplState>,
    generation: u64,
}

impl SlaveUpstreamGuard {
    /// A connection attempt is starting. The link is *not* up yet: it is up
    /// once the dataset has been synced and the stream is flowing, which is
    /// [`Self::mark_synced`].
    fn connect(repl_state: &Arc<ReplState>, generation: u64) -> Self {
        let guard = Self {
            rs: Arc::clone(repl_state),
            generation,
        };
        guard.set(LinkState::Connecting);
        guard
    }

    fn set(&self, state: LinkState) {
        if self.rs.generation() == self.generation {
            self.rs.set_link_state(state);
        }
    }

    fn mark_syncing(&self) {
        self.set(LinkState::Sync);
    }

    fn mark_synced(&self) {
        self.set(LinkState::Connected);
    }
}

impl Drop for SlaveUpstreamGuard {
    fn drop(&mut self) {
        self.set(LinkState::Connect);
    }
}

/// Everything a replication client needs, bundled so it can be started from
/// anywhere: `--replicaof` at boot, `REPLICAOF`, `CLUSTER REPLICATE`, and the
/// cluster bus when a failover re-points this node.
#[derive(Clone)]
pub struct ReplicaStarter {
    pub store: Store,
    pub index_store: IndexStore,
    pub dict_store: DictStore,
    pub wait_table: Arc<WaitTable>,
    pub ts_index: SharedTsIndex,
    pub config: Arc<Config>,
    pub compaction_tx: CompactionTx,
    pub repl_state: Arc<ReplState>,
    pub hub_tx: HubTx,
    /// The server's own pub/sub hub, client registry, tracking table and
    /// monitor registry. Replicated writes are applied against these so that
    /// clients connected to the *replica* see their effects — keyspace
    /// notifications, `PUBLISH`es relayed from the master, client-side-cache
    /// invalidations, `MONITOR` lines. Applied against private stand-ins (as
    /// they used to be) all of that went nowhere.
    pub pubsub: crate::pubsub::PubSubHub,
    pub client_registry: crate::client_registry::ClientRegistry,
    pub tracking_table: crate::tracking::TrackingTable,
    pub monitor_registry: crate::monitor::SharedMonitorRegistry,
}

impl ReplicaStarter {
    pub fn from_ctx(ctx: &crate::commands::ctx::Ctx<'_>) -> Self {
        Self {
            pubsub: ctx.pubsub.clone(),
            client_registry: Arc::clone(ctx.client_registry),
            tracking_table: Arc::clone(ctx.tracking_table),
            monitor_registry: Arc::clone(ctx.monitor_registry),
            store: Arc::clone(ctx.store),
            index_store: Arc::clone(ctx.index_store),
            dict_store: Arc::clone(ctx.dict_store),
            wait_table: Arc::clone(ctx.wait_table),
            ts_index: Arc::clone(ctx.ts_index),
            config: Arc::clone(ctx.config),
            compaction_tx: ctx.compaction_tx.clone(),
            repl_state: Arc::clone(ctx.repl_state),
            hub_tx: ctx.hub_tx.clone(),
        }
    }

    /// Become a replica of `host:port`, starting now.
    ///
    /// The role change is synchronous: by the time this returns the node is a
    /// replica — read-only, reporting `role:slave` and the new master's
    /// address — even if that master is unreachable. It used to stay a
    /// writable `master` until the first sync succeeded, so a node told to
    /// follow a master that was down kept accepting writes it would later
    /// throw away.
    ///
    /// The client itself runs on its own thread and runtime, so it competes
    /// with neither the tokio workers nor the io_uring ones, and can be
    /// started from places that have no runtime at all.
    pub fn start(&self, host: String, port: u16) {
        let generation = self.repl_state.begin_replication_epoch();
        self.repl_state.set_master_addr(&host, port);
        self.repl_state.become_slave();
        self.repl_state.set_link_state(LinkState::Connect);
        // As Redis ends them: a client blocked on a master waits for what
        // only a master is written (#591). Counted first: a command that
        // parks from here on, before it is listed as blocked, sees the
        // count change and ends as the sweep would have ended it.
        crate::commands::blocking::note_role_change(&self.repl_state);
        let ended = self.client_registry.end_blocked_for_role_change();
        if ended > 0 {
            log_info!("Replication: ended {ended} blocked client(s): this node is now a replica");
        }

        let starter = self.clone();
        let spawned = std::thread::Builder::new()
            .name("kividb-replica".into())
            .spawn(move || {
                match tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                {
                    Ok(rt) => rt.block_on(start_replica(starter, host, port, generation)),
                    Err(e) => log_error!("Replication: could not start replication runtime: {e}"),
                }
            });
        if let Err(e) = spawned {
            log_error!("Replication: could not start replication thread: {e}");
        }
    }
}

/// Why a replication session ended without an I/O error.
enum SessionEnd {
    /// The master closed the connection.
    MasterClosed,
    /// A newer `REPLICAOF` or a promotion took over; this task must stop.
    Superseded,
    /// `CLIENT KILL` ended the link to the master; it is made again.
    Killed,
}

#[derive(Debug)]
enum SessionError {
    /// Something went wrong talking to the master; retry soon.
    Link(String),
    /// The dataset guard refused the full resync. The local dataset is intact.
    Refused(String),
    /// The master lost its dataset, and this replica, which holds it, is
    /// taking over rather than syncing from it. The local dataset is intact.
    TakingOver(String),
    /// The master sent what this replica can't hold: a dataset it refuses to
    /// load whole for what is in it (a type, or a set member's TTL, it has
    /// nowhere to keep), or a write it can't apply (a KeyDB member TTL on a
    /// set, KeyDB's `RREPLAY`). Following on would lose data, so it doesn't;
    /// it says why, in the log and in `INFO replication`. The same master
    /// sends the same again, and each try is a full sync on it, so it tries
    /// again after a minute, then less and less often (see
    /// [`unfollowable_delay`]). A payload cut short, or one that fails its
    /// checksum, is a broken link, not this.
    Unfollowable(String),
    /// See [`SessionEnd::Superseded`].
    Superseded,
}

impl From<std::io::Error> for SessionError {
    fn from(e: std::io::Error) -> Self {
        SessionError::Link(e.to_string())
    }
}

impl From<String> for SessionError {
    fn from(e: String) -> Self {
        SessionError::Link(e)
    }
}

/// How often a waiting replication task re-checks whether it has been
/// superseded. Bounds how long a task blocked on an unreachable master can
/// outlive the `REPLICAOF` that replaced it.
const EPOCH_CHECK_INTERVAL: Duration = Duration::from_millis(200);

/// Delay between connection attempts. One second, as in Redis: a master that
/// comes back should be picked up promptly.
const RECONNECT_DELAY: Duration = Duration::from_secs(1);

/// How long to wait after the `n`th refusal in a row of what the master
/// sent ([`SessionError::Unfollowable`], from 0): a minute, doubling up to
/// ten. It is decided by what the master holds, and the master sends it
/// again until someone changes that.
fn unfollowable_delay(n: u32) -> Duration {
    Duration::from_secs((60u64 << n.min(4)).min(600))
}

/// Delay after the dataset guard refuses a sync. Retrying sooner would only
/// re-download a payload that will be refused again; the operator has to act.
const REFUSED_RETRY_DELAY: Duration = Duration::from_secs(10);

/// Run the replication client until this node is promoted or re-pointed.
///
/// `my_generation` is the replication epoch [`ReplicaStarter::start`] claimed
/// for this task. Any later `REPLICAOF` or promotion bumps the epoch, and this
/// task stops at its next check — that is what makes re-pointing a replica
/// work while its role stays `"slave"` throughout.
pub async fn start_replica(
    starter: ReplicaStarter,
    master_host: String,
    master_port: u16,
    my_generation: u64,
) {
    let repl_state = Arc::clone(&starter.repl_state);
    let mut failures: u64 = 0;
    // Refusals in a row of what the master sent (`Unfollowable`).
    let mut unfollowable: u32 = 0;

    loop {
        if repl_state.generation() != my_generation {
            log_info!(
                "Replication: Superseded by a newer REPLICAOF (epoch {my_generation} → {}) — \
                 stopping replication client for {master_host}:{master_port}",
                repl_state.generation()
            );
            return;
        }
        if !repl_state.is_slave() {
            log_info!("Replication: No longer a replica — stopping replication client");
            return;
        }

        // A master that stays down is retried every second; say so once, then
        // once a minute, rather than once per attempt.
        let verbose = failures == 0 || failures.is_multiple_of(60);
        if verbose {
            log_info!("Replication: Connecting to master {master_host}:{master_port}...");
        }

        let delay = match run_replication_session(
            &starter,
            &master_host,
            master_port,
            my_generation,
            verbose,
        )
        .await
        {
            Ok(SessionEnd::Superseded) | Err(SessionError::Superseded) => {
                log_info!(
                    "Replication: Replication session for {master_host}:{master_port} superseded — \
                     stopping replication client"
                );
                return;
            }
            Ok(SessionEnd::MasterClosed) => {
                log_warn!("Replication: Master closed the connection — reconnecting");
                failures = 0;
                unfollowable = 0;
                RECONNECT_DELAY
            }
            Ok(SessionEnd::Killed) => {
                log_warn!(
                    "Replication: The link to the master was killed (CLIENT KILL) — reconnecting"
                );
                failures = 0;
                unfollowable = 0;
                RECONNECT_DELAY
            }
            Err(SessionError::Link(e)) => {
                unfollowable = 0;
                if verbose {
                    log_warn!(
                        "Replication: Replication link to {master_host}:{master_port} failed: {e} — \
                         retrying every {}s",
                        RECONNECT_DELAY.as_secs()
                    );
                }
                failures += 1;
                RECONNECT_DELAY
            }
            Err(SessionError::Refused(reason)) => {
                // Loud on purpose: this node is deliberately not in sync, and
                // nothing else about it will say why.
                let first = repl_state
                    .full_syncs_refused
                    .fetch_add(1, Ordering::Relaxed)
                    == 0;
                *repl_state.last_sync_refusal.write() = Some(reason.clone());
                if first || verbose {
                    log_error!(
                        "Replication: FULL RESYNC REFUSED from {master_host}:{master_port}: \
                         {reason}. The local dataset has been kept and this replica is NOT in \
                         sync. If the master's dataset really is the one to keep, run \
                         `CONFIG SET replica-full-sync-guard off` on this replica (it retries \
                         every {}s); otherwise promote this node with `REPLICAOF NO ONE`.",
                        REFUSED_RETRY_DELAY.as_secs()
                    );
                }
                failures += 1;
                REFUSED_RETRY_DELAY
            }
            Err(SessionError::Unfollowable(reason)) => {
                // Every time: a minute or more apart, and each says why this
                // replica is not in sync.
                let delay = unfollowable_delay(unfollowable);
                unfollowable = unfollowable.saturating_add(1);
                *repl_state.last_sync_refusal.write() = Some(reason.clone());
                log_error!(
                    "Replication: NOT following {master_host}:{master_port}: {reason}. This \
                     replica is NOT in sync; it tries again in {}s.",
                    delay.as_secs()
                );
                failures += 1;
                delay
            }
            Err(SessionError::TakingOver(reason)) => {
                let first = repl_state
                    .full_syncs_refused
                    .fetch_add(1, Ordering::Relaxed)
                    == 0;
                *repl_state.last_sync_refusal.write() = Some(reason.clone());
                if first || verbose {
                    log_error!(
                        "Replication: NOT syncing from {master_host}:{master_port}: {reason}. \
                         The local dataset has been kept."
                    );
                }
                failures += 1;
                // Soon again: the takeover is being decided, and asked for
                // again if it fails.
                RECONNECT_DELAY
            }
        };

        // Sleep in short steps so a promotion or re-point stops this task
        // promptly instead of after the full delay — and so an operator who
        // has just relaxed the guard does not wait out a refusal backoff.
        let guard_setting = |rs: &ReplState| {
            (
                rs.full_sync_guard(),
                rs.full_sync_guard_ratio.load(Ordering::Relaxed),
            )
        };
        let guard_at_sleep = guard_setting(&repl_state);
        let wake = Instant::now() + delay;
        while Instant::now() < wake {
            if delay == REFUSED_RETRY_DELAY && guard_setting(&repl_state) != guard_at_sleep {
                break;
            }
            tokio::time::sleep(EPOCH_CHECK_INTERVAL.min(delay)).await;
            if repl_state.generation() != my_generation {
                log_info!("Replication: Superseded during reconnect backoff — stopping");
                return;
            }
            if !repl_state.is_slave() {
                log_info!("Replication: Role changed during reconnect backoff — stopping");
                return;
            }
        }
    }
}

/// Await `fut`, giving up if it takes longer than `timeout` or if this task is
/// superseded in the meantime.
///
/// This is what keeps a replica from waiting forever on a master that has
/// vanished without closing the connection — powered off, partitioned, or
/// behind a firewall that now drops its packets. Such a peer produces no error
/// at all; the only signal is the absence of a reply.
async fn guarded<T, E: std::fmt::Display>(
    fut: impl std::future::Future<Output = Result<T, E>>,
    timeout: Duration,
    repl_state: &ReplState,
    my_generation: u64,
    what: &str,
) -> Result<T, SessionError> {
    // Checked before each wait as well as during it: on a link that keeps
    // delivering, the timer below never fires, and a session that had been
    // superseded would read a whole payload before noticing.
    if repl_state.generation() != my_generation {
        return Err(SessionError::Superseded);
    }
    tokio::pin!(fut);
    let deadline = Instant::now() + timeout;
    loop {
        tokio::select! {
            res = &mut fut => {
                return res.map_err(|e| SessionError::Link(format!("{what}: {e}")));
            }
            _ = tokio::time::sleep(EPOCH_CHECK_INTERVAL) => {
                if repl_state.generation() != my_generation {
                    return Err(SessionError::Superseded);
                }
                if Instant::now() >= deadline {
                    return Err(SessionError::Link(format!(
                        "{what}: no response from master within {}s",
                        timeout.as_secs()
                    )));
                }
            }
        }
    }
}

/// Ask the kernel to notice a dead peer too, as a second line of defence.
///
/// The application-level timeout needs the master to send heartbeats, which a
/// master running an older build does not. These options need no cooperation:
/// keepalive probes an otherwise idle connection, and on Linux
/// `TCP_USER_TIMEOUT` caps how long written-but-unacknowledged data (our
/// `REPLCONF ACK`s) may sit before the socket is failed — without it that cap
/// is the kernel's retransmission limit, about 15 minutes.
fn tune_replication_socket(stream: &TcpStream, timeout: Duration) {
    let sock = socket2::SockRef::from(stream);
    let keepalive = socket2::TcpKeepalive::new()
        .with_time(Duration::from_secs(15))
        .with_interval(Duration::from_secs(5));
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    let keepalive = keepalive.with_retries(3);
    let _ = sock.set_tcp_keepalive(&keepalive);
    #[cfg(target_os = "linux")]
    let _ = sock.set_tcp_user_timeout(Some(timeout));
    #[cfg(not(target_os = "linux"))]
    let _ = timeout;
}

async fn run_replication_session(
    starter: &ReplicaStarter,
    host: &str,
    port: u16,
    my_generation: u64,
    verbose: bool,
) -> Result<SessionEnd, SessionError> {
    let ReplicaStarter {
        store,
        index_store,
        dict_store,
        wait_table,
        ts_index,
        config,
        compaction_tx,
        repl_state,
        ..
    } = starter;

    let timeout = repl_state.repl_timeout();
    let upstream = SlaveUpstreamGuard::connect(repl_state, my_generation);

    let addr = format!("{host}:{port}");
    let stream = guarded(
        TcpStream::connect(&addr),
        timeout,
        repl_state,
        my_generation,
        "connect",
    )
    .await?;
    stream.set_nodelay(true)?;
    tune_replication_socket(&stream, timeout);
    // How the link is listed among this node's clients, once it streams.
    let link_addrs = (
        stream
            .peer_addr()
            .map_or_else(|_| addr.clone(), |a| a.to_string()),
        stream
            .local_addr()
            .map(|a| a.to_string())
            .unwrap_or_default(),
    );

    // Over TLS with `tls-replication` (or `tls-cluster`): see `node_tls`.
    type Reader = Box<dyn tokio::io::AsyncRead + Unpin + Send>;
    type Writer = Box<dyn tokio::io::AsyncWrite + Unpin + Send>;
    let (reader, mut writer): (Reader, Writer) = if crate::node_tls::replication() {
        let tls = guarded(
            crate::node_tls::connect_async(host, stream),
            timeout,
            repl_state,
            my_generation,
            "TLS handshake",
        )
        .await?;
        let (r, w) = tokio::io::split(tls);
        (Box::new(r), Box::new(w))
    } else {
        let (r, w) = stream.into_split();
        (Box::new(r), Box::new(w))
    };
    let mut reader = BufReader::new(reader);

    // ── Phase 0: AUTH, when the master requires it ───────────────────────
    let (master_user, master_auth) = repl_state.master_credentials();
    if !master_auth.is_empty() {
        // As the default user when no user is given: `AUTH <password>`
        // is refused by a master that has no password (#135).
        let user = if master_user.is_empty() {
            "default"
        } else {
            master_user.as_str()
        };
        let parts = vec!["AUTH", user, master_auth.as_str()];
        send_command(&mut writer, &parts).await?;
        let reply = guarded(
            read_line(&mut reader),
            timeout,
            repl_state,
            my_generation,
            "AUTH",
        )
        .await?;
        if !reply.starts_with("+OK") {
            return Err(SessionError::Link(format!(
                "master rejected AUTH: {}",
                reply.trim_start_matches('-')
            )));
        }
    }

    // ── Phase 1: PING ────────────────────────────────────────────────────
    writer.write_all(b"*1\r\n$4\r\nPING\r\n").await?;
    let pong = guarded(
        read_line(&mut reader),
        timeout,
        repl_state,
        my_generation,
        "PING",
    )
    .await?;
    if pong.starts_with("-NOAUTH") {
        return Err(SessionError::Link(
            "master requires authentication — set `masterauth` (and `masteruser` for an ACL \
             user) on this replica"
                .into(),
        ));
    }
    if !pong.starts_with("+PONG") && !pong.starts_with("$4") {
        return Err(SessionError::Link(format!("expected PONG, got: {pong}")));
    }
    // If the master sent a bulk PONG ($4\r\nPONG), consume the second line
    if pong.starts_with("$4") {
        let _ = guarded(
            read_line(&mut reader),
            timeout,
            repl_state,
            my_generation,
            "PING",
        )
        .await?;
    }

    // ── Phase 2: REPLCONF listening-port ────────────────────────────────
    // The port clients reach *this* node on, so the master's `INFO` and `ROLE`
    // list the replica by an address someone can actually connect to rather
    // than this connection's ephemeral source port. As in Redis, that is the
    // TLS port when the replica replicates over TLS, and it is when there is
    // no plaintext port (port 0); otherwise the plaintext port. Both as they
    // are now: `CONFIG SET` moves them.
    let listening_port = if config.replica_announced_port != 0 {
        config.replica_announced_port
    } else {
        use crate::listen::{Kind, current_port, server_of};
        let plain = current_port(server_of(config), Kind::Plain);
        let tls = current_port(server_of(config), Kind::Tls);
        if tls != 0 && (plain == 0 || crate::node_tls::replication()) {
            tls
        } else {
            plain
        }
    };
    send_command(
        &mut writer,
        &["REPLCONF", "listening-port", &listening_port.to_string()],
    )
    .await?;
    expect_ok(
        &mut reader,
        "REPLCONF listening-port",
        timeout,
        repl_state,
        my_generation,
    )
    .await?;

    // ── Phase 3: REPLCONF capa psync2 ───────────────────────────────────
    send_command(&mut writer, &["REPLCONF", "capa", "psync2"]).await?;
    expect_ok(
        &mut reader,
        "REPLCONF capa",
        timeout,
        repl_state,
        my_generation,
    )
    .await?;

    // ── Phase 3b: which release the master is ───────────────────────────
    // A `FT.DROPINDEX … DD` in the stream is run as the master that sent it
    // ran it: a 1.2.0 release candidate deleted the documents and left each
    // replica to delete its own; 1.1 and before kept them (see
    // `replication::dd_deleted_by`). Releases since send the deletes and
    // never `DD`. A master that does not say is taken to have kept them.
    send_command(&mut writer, &["INFO", "server"]).await?;
    let head = guarded(
        read_line(&mut reader),
        timeout,
        repl_state,
        my_generation,
        "INFO server",
    )
    .await?;
    let mut master_info = None;
    if let Some(len) = head.strip_prefix('$').and_then(|n| n.parse::<usize>().ok()) {
        let mut body = vec![0u8; len + 2];
        guarded(
            reader.read_exact(&mut body),
            timeout,
            repl_state,
            my_generation,
            "INFO server",
        )
        .await?;
        master_info = Some(String::from_utf8_lossy(&body).into_owned());
    }
    let master_version = master_info.as_deref().and_then(|info| {
        info.lines()
            .find_map(|line| line.strip_prefix("kividb_version:"))
            .map(|version| version.trim().to_string())
    });
    repl_state.master_dd_deletes.store(
        master_version
            .as_deref()
            .is_some_and(crate::replication::dd_deleted_by),
        std::sync::atomic::Ordering::Relaxed,
    );
    // Whether the master sends a `DEL` for every key it expires (KiviDB
    // since 1.1.3, Redis always). One that does not (1.1.2 and before) is
    // followed as replicas followed every master before 1.1.3: this node
    // expires keys by its own clock, and deletes them here only (a replica
    // propagates nothing). Otherwise none it expired would ever go (#231).
    let propagates = crate::replication::expiry_propagated_by(master_info.as_deref());
    let master_uptime = master_info
        .as_deref()
        .and_then(crate::replication::uptime_in);
    if !propagates {
        log_info!(
            "Replication: The master (KiviDB {}) does not send the deletion of the keys it \
             expires: this replica expires keys itself while it follows it",
            master_version.as_deref().unwrap_or("?")
        );
        repl_state.expiry_sweep_owed.store(true, Ordering::Relaxed);
    } else if master_info.is_none() {
        log_info!(
            "Replication: The master did not answer INFO server: it is taken to send the \
             deletion of every key it expires, and this replica expires none itself"
        );
    }
    repl_state
        .master_propagates_expiry
        .store(propagates, Ordering::Relaxed);
    // The same for hash fields. A master that sends none (KiviDB 1.2.0 and
    // before, or one that did not answer) is followed as before: this node
    // expires fields by its own clock.
    let propagates_fields = crate::replication::field_expiry_propagated_by(master_info.as_deref());
    if !propagates_fields {
        log_info!(
            "Replication: The master does not say it sends the deletion of the hash fields it \
             expires: this replica expires hash fields itself while it follows it"
        );
        repl_state
            .field_expiry_sweep_owed
            .store(true, Ordering::Relaxed);
    }
    repl_state
        .master_propagates_field_expiry
        .store(propagates_fields, Ordering::Relaxed);

    // ── Phase 4: PSYNC ───────────────────────────────────────────────────
    // If this node's dataset is a known position in a master's stream — it
    // was following one and lost the connection, or was restarted cleanly —
    // ask for the stream from there. The master continues if it is that
    // master and still has what follows in its backlog; otherwise it answers
    // with a full resync, exactly as it does to `PSYNC ? -1`.
    //
    // A master that cannot continue may offer the fingerprint of its dataset
    // instead (see `replication::digest`): if this node's dataset has the
    // same one, it holds exactly what that master started with, and asks to
    // be continued from there. Masters that do not know the capability
    // answer it with an error, which is fine.
    //
    // And a master that came back without its dataset says so
    // (`+LOSTDATA <its node id>`) to a replica that takes that word, instead
    // of offering a sync: see `ClusterState::check_dataset_at_start`.
    send_command(
        &mut writer,
        &["REPLCONF", "capa", "dataset-digest", "capa", "lost-data"],
    )
    .await?;
    let _ = guarded(
        read_line(&mut reader),
        timeout,
        repl_state,
        my_generation,
        "REPLCONF capa dataset-digest",
    )
    .await?;
    // Where this node's dataset stands, kept aside: `resume` below may be
    // replaced by what a fingerprint offer leads to.
    let held = repl_state.resync_point.lock().clone();
    let mut resume = held.clone();
    let (ask_id, ask_offset) = match &resume {
        Some(point) => (point.repl_id.clone(), (point.offset + 1).to_string()),
        None => ("?".to_string(), "-1".to_string()),
    };
    send_command(&mut writer, &["PSYNC", &ask_id, &ask_offset]).await?;
    // The master takes its cut before replying, which on a large dataset is
    // not instant — but it is still bounded by the same timeout.
    let mut fullresync = guarded(
        read_line(&mut reader),
        timeout,
        repl_state,
        my_generation,
        "PSYNC",
    )
    .await?;
    // The master lost its dataset in a restart. If this node holds what it
    // had, this node takes over from it (the master serves nothing until
    // then); otherwise it says it has nothing to keep by asking again, and
    // is sent the master's dataset as usual.
    if let Some(node) = fullresync.trim().strip_prefix("+LOSTDATA ") {
        let node = node.trim().to_string();
        let local_keys = count_keys(store);
        let ours = repl_state
            .stream_origin()
            .is_none_or(|origin| origin == node);
        if local_keys > 0 && ours && repl_state.full_sync_guard() != FullSyncGuard::Off {
            let reason = format!(
                "the master lost its dataset in a restart, and this replica holds {local_keys} \
                 keys of it"
            );
            let reason = if repl_state.request_take_over(&node, &reason) {
                format!("{reason}; taking over from it")
            } else {
                reason
            };
            return Err(SessionError::TakingOver(reason));
        }
        send_command(&mut writer, &["PSYNC", "?", "-1"]).await?;
        resume = None;
        fullresync = guarded(
            read_line(&mut reader),
            timeout,
            repl_state,
            my_generation,
            "PSYNC",
        )
        .await?;
    }
    if let Some(offer) = fullresync.trim().strip_prefix("+DIGEST ") {
        let mut parts = offer.split_whitespace();
        let offered = parts.next().map(str::to_string).zip(
            parts
                .next()
                .and_then(|hex| u64::from_str_radix(hex, 16).ok()),
        );
        let ours = {
            let store = store.clone();
            tokio::task::spawn_blocking(move || crate::replication::digest::dataset_digest(&store))
                .await
                .ok()
        };
        let (ask_id, ask_offset) = match offered {
            Some((id, digest)) if ours == Some(digest) && id.len() == 40 => {
                log_info!(
                    "Replication: This dataset is the master's at the start of its stream {id} \
                     — asking to be continued from there"
                );
                resume = Some(crate::replication::ResyncPoint {
                    repl_id: id.clone(),
                    offset: 0,
                    db: 0,
                });
                (id, "1".to_string())
            }
            _ => {
                resume = None;
                ("?".to_string(), "-1".to_string())
            }
        };
        send_command(&mut writer, &["PSYNC", &ask_id, &ask_offset]).await?;
        fullresync = guarded(
            read_line(&mut reader),
            timeout,
            repl_state,
            my_generation,
            "PSYNC",
        )
        .await?;
    }
    let tok: Vec<&str> = fullresync.split_whitespace().collect();
    let cmd0 = tok
        .first()
        .map(|s| s.trim_start_matches('+').to_ascii_uppercase())
        .unwrap_or_default();

    // The stream as it will be read below: what has arrived and is not yet
    // applied, how many bytes have arrived in all, and which database the
    // next command is for.
    let mut repl_buf: Vec<u8> = Vec::with_capacity(4096);
    let mut temp = [0u8; 16 * 1024];
    let mut selected_db = 0usize;
    let mut offset: u64;

    if cmd0 == "CONTINUE" {
        let Some(point) = resume else {
            return Err(SessionError::Link(
                "master answered +CONTINUE to a request for a full resync".into(),
            ));
        };
        selected_db = point.db;
        let prelude_len = {
            let buffered = reader.buffer();
            let len = buffered.len();
            repl_buf.extend_from_slice(buffered);
            reader.consume(len);
            len
        };
        offset = point.offset + prelude_len as u64;
        // A master that was this one's sibling, promoted since, continues the
        // old stream under its own id: follow that id from here on (#109).
        if let Some(id) = tok
            .get(1)
            .filter(|id| id.len() == 40 && **id != point.repl_id)
            && let Some(current) = repl_state.resync_point.lock().as_mut()
        {
            log_info!(
                "Replication: The master continues {} as {id}",
                current.repl_id
            );
            current.repl_id = id.to_string();
        }
        repl_state.set_stream_origin(repl_state.cluster_master_node());
        log_info!(
            "Replication: Partial resync: continuing from offset {} — no dataset transfer",
            point.offset
        );
        // This dataset may hold keys that went past their time under a
        // master that sent no `DEL`s (a release before 1.1.3, followed by
        // this node or by the one that wrote what it loaded at startup):
        // this master, which does send them, will never send theirs. Before
        // anything of its stream is applied (its writes find the keys as
        // they are here), the keys whose time ended before this master
        // started are deleted. A later one is its to expire: it was alive
        // at its start, and its `DEL` comes in the stream. Only this node's
        // clock is read, against the master's uptime: no clock of the
        // master's. The uptime is whole seconds, rounded down: a second
        // more is taken off.
        if propagates && repl_state.expiry_sweep_owed.load(Ordering::Relaxed) {
            match master_uptime {
                Some(uptime) => {
                    let before = crate::commands::helpers::now_ms()
                        .saturating_sub(uptime.saturating_add(1).saturating_mul(1000));
                    let (store, index_store) = (Arc::clone(store), Arc::clone(index_store));
                    let deleted = tokio::task::spawn_blocking(move || {
                        crate::commands::helpers::expire_keys_due_before(
                            &store,
                            &index_store,
                            before,
                        )
                    })
                    .await
                    .unwrap_or(0);
                    if deleted > 0 {
                        log_info!(
                            "Replication: Deleted {deleted} keys that expired before the master \
                             started, which no master would have sent the deletion of"
                        );
                    }
                    repl_state.expiry_sweep_owed.store(false, Ordering::Relaxed);
                }
                None => log_info!(
                    "Replication: The master did not say how long it has been up: keys \
                     already past their time are left for its deletions"
                ),
            }
        }
        // The same for hash fields past their deadline.
        if propagates_fields
            && repl_state.field_expiry_sweep_owed.load(Ordering::Relaxed)
            && let Some(uptime) = master_uptime
        {
            let before = crate::commands::helpers::now_ms()
                .saturating_sub(uptime.saturating_add(1).saturating_mul(1000));
            let store = Arc::clone(store);
            let index_store = Arc::clone(index_store);
            let removed = tokio::task::spawn_blocking(move || {
                crate::field_expiry::expire_fields_due_before(&store, &index_store, before)
            })
            .await
            .unwrap_or(0);
            if removed > 0 {
                log_info!(
                    "Replication: Removed {removed} hash fields whose deadline passed before \
                     the master started, which no master would have sent the deletion of"
                );
            }
            repl_state
                .field_expiry_sweep_owed
                .store(false, Ordering::Relaxed);
        }
    } else {
        if tok.len() < 3 || cmd0 != "FULLRESYNC" {
            return Err(SessionError::Link(format!(
                "expected +FULLRESYNC or +CONTINUE, got: {fullresync}"
            )));
        }
        let master_repl_id = tok[1].to_string();
        let master_offset: u64 = tok[2].parse().map_err(|_| {
            format!(
                "expected numeric replication offset after FULLRESYNC, got `{}`",
                tok[2]
            )
        })?;
        if verbose {
            log_info!("Replication: Full resync from {master_repl_id} offset={master_offset}");
        }
        upstream.mark_syncing();
        // From here until it has loaded the payload and streamed, this node
        // does not stand for election: it may soon hold part of the
        // master's dataset, or none of it.
        repl_state.note_full_sync_started();
        // The node this replica was following until a moment ago (within
        // `repl-timeout`), now under a replication id whose stream does not
        // continue the one this dataset is a position in: it restarted
        // without that stream. A dataset much smaller than this one is then
        // not this one's successor, whatever the guard's mode; see
        // `full_sync_refusal_with`. (A replica cut off for longer has no
        // say: the master may have shrunk meanwhile, by deletes or expiry.)
        let master_node = repl_state.cluster_master_node();
        let down_since = repl_state.master_link_down_since_ms.load(Ordering::Relaxed);
        let recently_in_sync = down_since == 0
            || crate::replication::unix_ms().saturating_sub(down_since)
                <= repl_state.repl_timeout().as_millis() as u64;
        let history_lost = recently_in_sync
            && held
                .as_ref()
                .is_some_and(|point| point.repl_id != master_repl_id)
            && master_node.is_some()
            && repl_state.stream_origin() == master_node;
        let lost_from = master_node.filter(|_| history_lost);

        // ── Phase 5: Receive the payload ─────────────────────────────────────
        // Format: $<len>\r\n<len bytes>
        // Note: no trailing \r\n after the payload (unlike normal bulk strings)
        let rdb_header = guarded(
            read_line(&mut reader),
            timeout,
            repl_state,
            my_generation,
            "payload header",
        )
        .await?;
        if !rdb_header.starts_with('$') {
            return Err(SessionError::Link(format!(
                "expected payload bulk header, got: {rdb_header}"
            )));
        }
        let rdb_len: usize = rdb_header[1..]
            .trim()
            .parse()
            .map_err(|_| format!("bad payload length: {rdb_header}"))?;
        if verbose {
            log_info!("Replication: Receiving full-sync payload ({rdb_len} bytes)...");
        }

        // Read in pieces so the timeout measures *silence*, not total transfer
        // time: a large payload on a slow link is fine, a stalled one is not.
        let mut rdb_bytes = vec![0u8; rdb_len];
        let mut filled = 0usize;
        while filled < rdb_len {
            let n = guarded(
                reader.read(&mut rdb_bytes[filled..]),
                timeout,
                repl_state,
                my_generation,
                "payload",
            )
            .await?;
            if n == 0 {
                return Err(SessionError::Link(format!(
                    "master closed the connection {filled} bytes into a {rdb_len}-byte payload"
                )));
            }
            filled += n;
            repl_state.note_master_io();
        }

        // ── Phase 6: Load into staging, check, swap ──────────────────────────
        // Nothing below touches the live dataset until the payload has parsed
        // completely and the guard has passed. A payload that fails to parse used
        // to be logged and then treated as an empty dataset, which was swapped in
        // over the live one.
        //
        // `repl-diskless-load` decides what happens to the old dataset meanwhile.
        // Kept until the new one is loaded (`swapdb`), a full resync needs memory
        // for two datasets — a replica sized for one is killed for it, on every
        // restart. Dropped first (the default, as in Redis), it needs memory for
        // one.
        //
        // Dropping first is done only for a payload that has been *read through
        // to the end* (`verify_snapshot`): every key and value parsed, nothing
        // kept. A transfer the master did not finish never gets this far — the
        // read above fails — and a payload that cannot be read is found out
        // here, with the old dataset still in place. Either way the replica
        // carries on serving what it had. (v1.0.4 did not: a full sync that
        // failed part-way left the replica with no keys at all.)
        // The last look at the epoch before the live dataset is touched, and
        // the lock that keeps the epoch from changing until the master's
        // dataset is in place (see `ReplState::dataset_commit`). A session
        // superseded by a promotion or a re-point stops here, with the local
        // dataset as it was.
        let commit = repl_state.dataset_commit.lock();
        if repl_state.generation() != my_generation || !repl_state.is_slave() {
            return Err(SessionError::Superseded);
        }
        let local_keys = count_keys(store);
        let is_kdb = rdb_bytes.len() >= 8 && rdb_bytes[..8] == *crate::snapshot::KDB_MAGIC;
        let verified_keys =
            if local_keys > 0 && is_kdb && repl_state.flush_before_load.load(Ordering::Relaxed) {
                Some(
                    crate::snapshot::verify_snapshot(rdb_bytes.as_slice()).map_err(|e| {
                        let e = crate::snapshot::refusal_of_payload(e);
                        SessionError::Link(format!(
                            "full-sync payload is not a valid KDB image ({e}); the local dataset \
                         is untouched"
                        ))
                    })?,
                )
            } else {
                None
            };
        // Cleared when this guard drops, so an error anywhere below cannot leave
        // the replica answering `LOADING` forever.
        let syncing;
        let staged = match verified_keys {
            Some(incoming_keys) => {
                guard_full_sync(repl_state, local_keys, incoming_keys, lost_from.as_deref())?;
                // The dataset is about to be replaced: it is no position in
                // any stream until the new one is in.
                repl_state.set_resync_point(None);
                syncing = SyncInProgress::begin(repl_state);
                {
                    let _cut = crate::write_gate::cut();
                    let empty = store::new_store(config.databases);
                    store::swap_kv_with_staging(store, &empty);
                    crate::aof::log_superseded();
                    index_store.write().clear();
                    dict_store.write().clear();
                    crate::store::rebuild_ts_label_index(store, ts_index);
                    wait_table.clear();
                    // `empty` now holds the old dataset, and takes it with
                    // it.
                }
                crate::commands::memory::purge_allocator();
                log_warn!(
                    "Replication: Dropped the {local_keys} local keys before loading {incoming_keys} \
                     from the master"
                );
                if let Some(delay) = test_load_delay() {
                    std::thread::sleep(delay);
                }
                load_full_sync_payload(&rdb_bytes, config.databases)?
            }
            None => {
                let staged = load_full_sync_payload(&rdb_bytes, config.databases)?;
                guard_full_sync(repl_state, local_keys, staged.keys, lost_from.as_deref())?;
                repl_state.set_resync_point(None);
                syncing = SyncInProgress::begin(repl_state);
                staged
            }
        };
        drop(rdb_bytes);

        // The master's libraries, in place of this node's, before the dataset
        // is: a failure here leaves the dataset as it was, and the master's
        // command stream, which may call them, comes after.
        crate::snapshot::restore_functions(staged.functions)
            .map_err(|e| SessionError::Link(format!("full sync: {e}")))?;
        {
            // Stop the world for the swap, the same way a checkpoint does, so a
            // local AOF record cannot straddle it.
            let _cut = crate::write_gate::cut();
            store::swap_kv_with_staging(store, &staged.store);
            // The open log is of the dataset this replaced (#350).
            crate::aof::log_superseded();
            index_store.write().clear();
            dict_store.write().clear();
            crate::store::rebuild_ts_label_index(store, ts_index);
            wait_table.clear();
        }
        // The hashes with field TTLs are the ones just received.
        crate::field_expiry::rescan(store);
        *repl_state.last_sync_refusal.write() = None;
        log_info!(
            "Replication: Full sync loaded: {} keys ({} with a TTL), replacing {local_keys} local keys",
            staged.keys,
            staged.keys_with_ttl
        );
        // The swap dropped the entire previous dataset. Those are small allocations
        // that glibc parks in its arenas, so without this the replica keeps the old
        // dataset's footprint resident on top of the new one.
        drop(staged.store);
        crate::commands::memory::purge_allocator();

        // ── Phase 7: Command stream ──────────────────────────────────────────
        // After the payload the master sends a continuous stream of RESP-encoded
        // write commands. Anything already buffered behind the payload is the
        // start of that stream and counts toward the offset.
        let prelude_len = {
            let buffered = reader.buffer();
            let len = buffered.len();
            repl_buf.extend_from_slice(buffered);
            reader.consume(len);
            len
        };
        offset = master_offset.saturating_add(prelude_len as u64);
        // The dataset now in place is the master's at `master_offset`; nothing
        // of the stream has been applied to it yet.
        repl_state.set_resync_point(Some(crate::replication::ResyncPoint {
            repl_id: master_repl_id.clone(),
            offset: master_offset,
            db: 0,
        }));
        repl_state.set_stream_origin(repl_state.cluster_master_node());
        // Every key in it that this master expires is sent as a `DEL`, if
        // it sends them at all: nothing is left for a sweep.
        if propagates {
            repl_state.expiry_sweep_owed.store(false, Ordering::Relaxed);
        }
        if propagates_fields {
            repl_state
                .field_expiry_sweep_owed
                .store(false, Ordering::Relaxed);
        }
        // The dataset is the master's from here on; a promotion now finds it
        // whole and stops this session at its next look at the epoch.
        drop(commit);

        // Rebuild what the payload describes but does not contain: search indexes
        // are sent as definitions and rebuilt here from the values. That can take
        // a while, so the socket is drained into `repl_buf` meanwhile — otherwise
        // the master's queue for this replica grows until it is evicted for
        // falling behind, and the resync starts over.
        crate::vector::restore_dictionaries(index_store, staged.dictionaries);
        if !staged.index_schemas.is_empty() {
            let schemas = staged.index_schemas;
            let store_bg = Arc::clone(store);
            let index_bg = Arc::clone(index_store);
            log_info!(
                "Replication: Rebuilding {} search index(es) from the synced dataset",
                schemas.len()
            );
            let rebuild = tokio::task::spawn_blocking(move || {
                crate::vector::register_index_schemas(
                    &index_bg,
                    &schemas,
                    &std::collections::HashMap::new(),
                );
                for schema in &schemas {
                    let def = match index_bg.read().get(&schema.name) {
                        Some(d) => d.clone(),
                        None => continue,
                    };
                    let db_i = def.db_index.min(store_bg.len().saturating_sub(1));
                    crate::vector::backfill_from_db(&store_bg[db_i], &def);
                }
            });
            tokio::pin!(rebuild);
            loop {
                tokio::select! {
                    res = &mut rebuild => {
                        if let Err(e) = res {
                            log_error!("Replication: index rebuild after full sync failed: {e}");
                        }
                        break;
                    }
                    res = reader.get_mut().read(&mut temp) => {
                        let n = res?;
                        if n == 0 {
                            return Ok(SessionEnd::MasterClosed);
                        }
                        repl_buf.extend_from_slice(&temp[..n]);
                        offset += n as u64;
                        repl_state.note_master_io();
                    }
                }
            }
        }

        drop(syncing);

        // Rebase this node's AOF onto the dataset we just received.
        //
        // A full resync replaces the entire store. The AOF does not follow: left
        // alone it would hold whatever this node logged *before* the resync, and
        // the incoming stream would then append on top of it — a log that replays
        // to a dataset this node never had. On a first-time replica the failure is
        // the mirror image: the AOF holds only the stream, and none of the keys the
        // payload delivered, so replaying it loses everything that existed at sync
        // time.
        //
        // Checkpoint writes dump.kdb and resets the AOF to an empty delta, which is
        // what dump-then-AOF recovery expects. The stream then appends onto that
        // delta.
        //
        // Done before entering the stream, not concurrently with it: the swap
        // discards whatever is queued for the writer (correct only while writes are
        // quiesced), so the stream must not be appending yet.
        if crate::aof::AOF_ENABLED.load(Ordering::Relaxed) {
            let store_for_rewrite = Arc::clone(store);
            let index_for_rewrite = Arc::clone(index_store);
            let repl_state_for_rewrite = Arc::clone(repl_state);
            log_info!("Replication: AOF is on — rebasing it onto the synced dataset");
            let rebased = tokio::task::spawn_blocking(move || {
                crate::replication::save_dataset(
                    &store_for_rewrite,
                    &index_for_rewrite,
                    &repl_state_for_rewrite,
                )
            })
            .await;
            if !matches!(rebased, Ok(Ok(()))) {
                // The stream is about to append to an AOF that does not describe
                // the synced dataset. Say so loudly rather than log onto a base
                // that was never rebased.
                log_error!(
                    "Replication: post-sync AOF rebase failed ({rebased:?}); this replica's AOF \
                 does not match its dataset — run BGREWRITEAOF before relying on it"
                );
            }
        }
    }

    // One amortized scaffold for millions of APPLYs — rebuilding this per instruction was tens of μs each.
    let repl_apply = ReplicationApplyEnv::new(starter);
    // `selected_db` persists across commands — SELECT in the stream mutates it.

    // How far the stream has been *applied*: what has arrived, less the
    // incomplete command still sitting in `repl_buf`. This is the offset
    // reported, acknowledged, and continued from.
    let mut applied = offset - repl_buf.len() as u64;
    if !publish_applied(repl_state, my_generation, applied) {
        return Ok(SessionEnd::Superseded);
    }

    let ack_interval = Duration::from_secs(1);
    send_ack(&mut writer, applied, timeout).await?;
    let mut last_ack = Instant::now();

    // The link is up from here: synced, and about to stream. Listed among
    // the clients as the master (`flags=M`), as Redis lists it.
    let mut master_link = crate::client_registry::MasterLink::register(
        &starter.client_registry,
        link_addrs.0,
        link_addrs.1,
    );
    upstream.mark_synced();
    repl_state.note_master_io();
    log_info!("Replication: Synced with {addr}. Entering command stream.");

    // Silence detection. A healthy master is never quiet for long — it writes
    // a PING into the stream every `repl-ping-replica-period` — so a link with
    // no bytes for `repl-timeout` is a dead one. The deadline is only armed
    // once a heartbeat has actually been seen, because a master running an
    // older build sends none: timing *that* out would tear down a healthy idle
    // link every minute and force a full resync each time. Against such a
    // master the kernel-level options set in `tune_replication_socket` are
    // what notice a dead peer.
    let mut last_io = Instant::now();
    let mut heartbeats_seen = false;
    // Bytes already in `repl_buf` (the prelude, or what arrived during the
    // index rebuild) must be applied before blocking on the socket.
    let mut pending_input = !repl_buf.is_empty();
    // How far into `repl_buf` a transaction still arriving has been looked
    // through for its `EXEC` (`transaction_at`).
    let mut transaction_scanned = 0usize;

    loop {
        // Nothing is written to `repl_offset` on the way out, here or below:
        // every batch has already published its position, and a session that
        // has been superseded has no position to publish. A promoted node's
        // offset is its own stream's by then, and a re-pointed one's is the
        // new session's. Writing the old position over it took back the
        // writes a promoted master had taken meanwhile; the next full sync
        // restarted the backlog at the shorter offset, and replicas continued
        // before it were later sent the stream from the middle of a command.
        if repl_state.generation() != my_generation {
            log_info!(
                "Replication: Command stream from {addr} superseded (epoch {my_generation}) — \
                 dropping connection"
            );
            return Ok(SessionEnd::Superseded);
        }

        // Whether this turn found the socket drained: the read came back with
        // less than it could hold, or with nothing for a while. Once what was
        // read is applied, the replica has all the master has sent so far.
        let mut drained = false;
        if !pending_input {
            let inner = reader.get_mut();
            // `AsyncReadExt::read` is cancel-safe for a TcpStream — on the timeout
            // branch nothing has been consumed from the socket, so re-issuing the
            // read on the next iteration loses no bytes. `None` = the epoch-check
            // tick fired with no data available; fall through to the ACK heartbeat
            // below rather than `continue`, or an idle replica would stop ACKing.
            let read_n = tokio::select! {
                res = inner.read(&mut temp) => Some(res?),
                _ = tokio::time::sleep(EPOCH_CHECK_INTERVAL) => None,
                // `CLIENT KILL` of the master link: dropped where it stands,
                // between commands, and continued from there.
                () = master_link.killed() => {
                    log_info!("Replication: Link to {addr} killed by CLIENT KILL");
                    return Ok(SessionEnd::Killed);
                }
            };
            match read_n {
                Some(0) => {
                    return Ok(SessionEnd::MasterClosed);
                }
                Some(n) => {
                    repl_buf.extend_from_slice(&temp[..n]);
                    offset += n as u64;
                    last_io = Instant::now();
                    repl_state.note_master_io();
                    master_link.touch();
                    pending_input = true;
                    drained = n < temp.len();
                }
                None => {
                    drained = true;
                    let timeout = repl_state.repl_timeout();
                    if heartbeats_seen && last_io.elapsed() > timeout {
                        return Err(SessionError::Link(format!(
                            "no data from master for {}s (repl-timeout) — master is \
                             unreachable",
                            timeout.as_secs()
                        )));
                    }
                }
            }
        }

        let mut applied_commands = false;
        if pending_input {
            pending_input = false;
            // One command, a write the master sent as it is.
            macro_rules! apply {
                ($cmd:expr) => {
                    repl_apply
                        .apply_command(
                            $cmd,
                            store,
                            repl_state,
                            index_store,
                            dict_store,
                            wait_table,
                            ts_index,
                            config,
                            compaction_tx,
                            &mut selected_db,
                            &crate::watch::ForStore(store),
                            addr.as_str(),
                        )
                        .map_err(|e| {
                            // Where the dataset stands is no longer known to
                            // be a point in the stream: resync in full.
                            repl_state.set_resync_point(None);
                            match e.downcast::<crate::replication::keydb::Unfollowable>() {
                                Ok(why) => SessionError::Unfollowable(why.0),
                                Err(e) => SessionError::Link(e.to_string()),
                            }
                        })?
                };
            }
            // Commands one by one up to a `MULTI`; then the transaction it
            // opens, as one step, once its `EXEC` has arrived; and so on.
            // A transaction not yet arrived in full stays in `repl_buf`, not
            // applied and not counted: should the link drop now, it is asked
            // for again from its `MULTI` (as Redis keeps a replica's offset
            // at the `MULTI` until the `EXEC`).
            // The command at the front takes the gate alone as it is
            // applied (one that writes keys of several shards, a script):
            // the turn that stopped before it found so.
            let mut next_alone = false;
            // What the turns have applied of `repl_buf`, let go of once they
            // are done. Drained after each turn, it moved the rest of the
            // buffer every time, and a stream of such commands is a turn each.
            let mut head = 0usize;
            loop {
                let transaction = match transaction_at(&repl_buf[head..], &mut transaction_scanned)
                {
                    StreamTransaction::Whole(whole) => Some(whole),
                    StreamTransaction::Partial => break,
                    StreamTransaction::None => None,
                };
                // The gate before the lock below, never after, alone or not:
                // a command can hold the gate while it waits for that lock
                // (`SAVE` does, and a promotion). A transaction, or such a
                // command, waiting for the gate alone after the lock waited
                // for ever; so did any command waiting for its slot of the
                // gate after the lock, behind a script taking the gate alone,
                // slot by slot, which was waiting for the `SAVE`'s slot. The
                // replica stopped (#373). The commands of the turn find the
                // gate held on this thread, and take nothing more of it.
                // A command that takes the gate alone is applied on a turn of
                // its own, the gate taken here.
                let alone = transaction.is_some() || std::mem::take(&mut next_alone);
                // The master's heartbeats apply nothing, and take no gate: a
                // turn of them alone, so that an idle link is acknowledged
                // however long a script, or anything else holding the gate
                // alone, takes.
                let heartbeats = !alone && heartbeat_at(&repl_buf[head..]);
                let _alone = alone.then(crate::command_gate::enter_alone);
                let _gate = (!alone && !heartbeats).then(crate::command_gate::enter);
                // The commands and the position move together: whoever holds
                // this lock sees a dataset that is exactly the stream up to the
                // resync point. A save takes it to record that point beside the
                // dataset it writes.
                let _applying = repl_state.apply_lock.lock();
                // Looked at under the lock a promotion takes to read where the
                // stream stands (`become_master`): what was read from the old
                // master after that is not this node's to apply any more, nor
                // to count in an offset that is now its own stream's.
                if repl_state.generation() != my_generation {
                    log_info!(
                        "Replication: Command stream from {addr} superseded (epoch \
                         {my_generation}) — dropping connection"
                    );
                    return Ok(SessionEnd::Superseded);
                }
                let parse_pos = match transaction {
                    Some(whole) => {
                        // As `EXEC` runs on the master: alone, so that no
                        // reader here sees half of it; as one write, so that
                        // no snapshot or backup is cut inside it; and to this
                        // node's AOF as one group, between its own `MULTI`
                        // and `EXEC`.
                        let _whole = crate::write_gate::enter();
                        let _propagation = repl_apply.propagation_group(repl_state);
                        heartbeats_seen |= whole.heartbeat;
                        for cmd in whole.commands {
                            apply!(cmd);
                        }
                        whole.len
                    }
                    None => {
                        let mut parse_pos = 0usize;
                        while let Some((consumed, cmd)) =
                            parse_resp_command(&repl_buf[head + parse_pos..])
                        {
                            if is_named(&cmd, b"MULTI") {
                                // Applied whole, on the next turn.
                                break;
                            }
                            if is_named(&cmd, b"PING") {
                                // The master's heartbeat. Nothing to apply.
                                heartbeats_seen = true;
                                parse_pos += consumed;
                                continue;
                            }
                            if heartbeats {
                                // The rest, on a turn with the gate.
                                break;
                            }
                            // One that takes the gate alone: on the next
                            // turn, alone, unless this is that turn; which
                            // goes on as long as the commands want it alone,
                            // and no further.
                            let wants_alone =
                                crate::commands::handler::applied_takes_the_gate_alone(
                                    store,
                                    selected_db,
                                    &cmd,
                                );
                            if wants_alone && !alone {
                                next_alone = true;
                                break;
                            }
                            if alone && !wants_alone && parse_pos > 0 {
                                break;
                            }
                            apply!(cmd.iter().map(|v| v.to_vec()).collect());
                            parse_pos += consumed;
                            // Holding the gate shared, a turn ends when
                            // something waits to take it alone, as the gate
                            // was let go of between commands when each took
                            // it: a script or `EXEC` waits for one command, not
                            // for all the stream had buffered.
                            if !alone && crate::command_gate::taker_waiting() {
                                break;
                            }
                        }
                        parse_pos
                    }
                };
                if parse_pos == 0 {
                    if next_alone {
                        continue;
                    }
                    break;
                }
                applied_commands = true;
                let read: Vec<u8> = repl_buf[head..head + parse_pos].to_vec();
                head += parse_pos;
                transaction_scanned = 0;
                applied = offset - (repl_buf.len() - head) as u64;
                repl_state.repl_offset.store(applied, Ordering::Relaxed);
                if let Some(point) = repl_state.resync_point.lock().as_mut() {
                    point.offset = applied;
                    point.db = selected_db;
                }
                // Kept in this node's backlog, in the master's numbering: if it
                // is promoted, the master's other replicas carry on from it (#109).
                repl_state.record_received(read, applied);
            }
            repl_buf.drain(0..head);
            // What is left is the start of a command still arriving — or, if
            // the master sent the stream from a position that is not where
            // this replica stands, the middle of one. That never parses: the
            // replica would wait for ever, applying nothing and acknowledging
            // the same offset, and look healthy from both sides. Resync in
            // full instead.
            if !crate::resp::parse::can_start_command(&repl_buf)
                || !crate::resp::parse::can_start_command(&repl_buf[transaction_scanned..])
            {
                repl_state.set_resync_point(None);
                return Err(SessionError::Link(format!(
                    "the master's stream does not read as commands from offset {applied} \
                     (it was sent from another position than this replica's) — resyncing in full"
                )));
            }
        }

        // Its records to this node's AOF: no reply waits to write them.
        if applied_commands {
            crate::aof::stream_applied();
        }
        // In step with the master: its data's age counts from here.
        if drained {
            repl_state.note_in_step();
        }

        // REPLCONF ACK — heartbeat ~1 Hz when idle; **immediate** after applying commands so the
        // master can unblock WAIT without waiting for more replication traffic (otherwise we sit in
        // `read()` forever after the last propagating write and never hit the timer).
        if applied_commands || last_ack.elapsed() >= ack_interval {
            send_ack(&mut writer, applied, repl_state.repl_timeout()).await?;
            last_ack = Instant::now();
        }
    }
}

/// Publish `applied` as this node's replication offset, unless the session
/// that applied it has been superseded — by a promotion, whose stream the
/// offset now counts, or by a re-point, whose session owns it. Under the lock
/// a promotion takes to read where the stream stands, so that the two cannot
/// cross. False when superseded.
fn publish_applied(repl_state: &ReplState, my_generation: u64, applied: u64) -> bool {
    let _applying = repl_state.apply_lock.lock();
    if repl_state.generation() != my_generation {
        return false;
    }
    repl_state.repl_offset.store(applied, Ordering::Relaxed);
    true
}

/// Whether the stream's next command is the master's heartbeat, `PING`.
/// A command of one word is looked at only: most are not.
fn heartbeat_at(buf: &[u8]) -> bool {
    buf.starts_with(b"*1\r\n")
        && parse_resp_command(buf).is_some_and(|(_, cmd)| is_named(&cmd, b"PING"))
}

/// Whether `cmd` is the bare command `name` — `MULTI`, `EXEC`, `PING`.
fn is_named(cmd: &[&[u8]], name: &[u8]) -> bool {
    cmd.len() == 1 && cmd[0].eq_ignore_ascii_case(name)
}

/// What the front of the stream holds.
enum StreamTransaction {
    /// Not a `MULTI`.
    None,
    /// A `MULTI` whose `EXEC` has not arrived yet.
    Partial,
    Whole(WholeTransaction),
}

/// A transaction from the master, `MULTI` to `EXEC`.
struct WholeTransaction {
    /// Bytes of the stream it takes, `MULTI` and `EXEC` included.
    len: usize,
    /// The commands between them.
    commands: Vec<Vec<Vec<u8>>>,
    /// A heartbeat came in the middle of it.
    heartbeat: bool,
}

/// The transaction at the front of `buf`, if one is.
///
/// A large one — a script that wrote a million keys — arrives over many
/// reads, and is looked at again after each. `scanned` keeps how far it has
/// been looked through already (0 for none), so that it is not parsed from
/// its start every time.
fn transaction_at(buf: &[u8], scanned: &mut usize) -> StreamTransaction {
    let multi_len = match parse_resp_command(buf) {
        Some((consumed, cmd)) if is_named(&cmd, b"MULTI") => consumed,
        _ => return StreamTransaction::None,
    };
    let mut pos = (*scanned).max(multi_len);
    let end = loop {
        match parse_resp_command(&buf[pos..]) {
            Some((consumed, cmd)) => {
                let at = pos;
                pos += consumed;
                if is_named(&cmd, b"EXEC") {
                    break at;
                }
            }
            None => {
                *scanned = pos;
                return StreamTransaction::Partial;
            }
        }
    };
    let mut whole = WholeTransaction {
        len: pos,
        commands: Vec::new(),
        heartbeat: false,
    };
    let mut at = multi_len;
    while at < end {
        let Some((consumed, cmd)) = parse_resp_command(&buf[at..]) else {
            break;
        };
        at += consumed;
        if is_named(&cmd, b"PING") {
            // The master's heartbeat, sent while the transaction was on
            // its way. Nothing to apply.
            whole.heartbeat = true;
        } else if !is_named(&cmd, b"MULTI") {
            // A `MULTI` inside one is not something a master sends; Redis
            // refuses it and carries on with the transaction, as here.
            whole
                .commands
                .push(cmd.iter().map(|v| v.to_vec()).collect());
        }
    }
    StreamTransaction::Whole(whole)
}

/// For the tests of a replica stopped in the middle of a full sync, and
/// never set otherwise: `KIVIDB_TEST_FULL_SYNC_LOAD_DELAY_MS`, how long a
/// replica waits between dropping its dataset and loading the master's.
fn test_load_delay() -> Option<Duration> {
    static DELAY: std::sync::OnceLock<Option<Duration>> = std::sync::OnceLock::new();
    *DELAY.get_or_init(|| {
        let ms: u64 = std::env::var("KIVIDB_TEST_FULL_SYNC_LOAD_DELAY_MS")
            .ok()?
            .parse()
            .ok()?;
        Some(Duration::from_millis(ms))
    })
}

/// Holds `slave_sync_in_progress` for as long as it lives.
struct SyncInProgress<'a>(&'a ReplState);

impl<'a> SyncInProgress<'a> {
    fn begin(repl_state: &'a ReplState) -> Self {
        repl_state
            .slave_sync_in_progress
            .store(true, Ordering::SeqCst);
        Self(repl_state)
    }
}

impl Drop for SyncInProgress<'_> {
    fn drop(&mut self) {
        self.0.slave_sync_in_progress.store(false, Ordering::SeqCst);
    }
}

/// A full-sync payload, parsed into stores that are not yet live.
struct StagedSync {
    store: Store,
    index_schemas: Vec<crate::vector::IndexSchema>,
    dictionaries: Vec<(String, Vec<String>)>,
    /// The master's function libraries, from a KDB image or a Redis RDB file
    /// that has any.
    functions: Option<Vec<u8>>,
    keys: usize,
    keys_with_ttl: usize,
}

/// Parse a full-sync payload into fresh staging stores.
///
/// The master sends a native KDB image (`KIVIDB01`); a Redis master sends an
/// RDB. Either way a payload that does not parse is an error — the caller
/// must not go on to replace the live dataset with whatever was read so far.
fn load_full_sync_payload(payload: &[u8], databases: usize) -> Result<StagedSync, SessionError> {
    let staging_store = store::new_store(databases);
    // A key past its time is loaded all the same: the master's `DEL` of it
    // is on its way, and the writes made to it before are in the stream.
    // Nothing is swept meanwhile either (a replica's sweep deletes nothing,
    // and this is a staging store; but the node's role can change under it).
    let _hold = crate::expiry::hold();
    let _loading = crate::expiry::Loading::start();

    let is_kividb = payload.len() >= 8 && payload[..8] == *crate::snapshot::KDB_MAGIC;
    let (dbs, expiries, index_schemas, dictionaries, functions) = if is_kividb {
        let loaded = crate::snapshot::load_snapshot_bytes(payload).map_err(|e| {
            let e = crate::snapshot::refusal_of_payload(e);
            SessionError::Link(format!("full-sync payload is not a valid KDB image: {e}"))
        })?;
        (
            loaded.dbs,
            loaded.expiries,
            loaded.index_schemas,
            loaded.dictionaries,
            loaded.functions,
        )
    } else {
        let (dbs, expiries, functions) =
            crate::snapshot::load_redis_rdb_from(payload).map_err(|e| {
                let what = format!("full-sync payload is not a valid RDB: {e}");
                // Refused for what it holds (it would be refused again), not
                // cut short or corrupt: see `SessionError::Unfollowable`.
                if crate::snapshot::is_unrepresentable(&e) {
                    SessionError::Unfollowable(what)
                } else {
                    SessionError::Link(what)
                }
            })?;
        (dbs, expiries, Vec::new(), Vec::new(), functions)
    };

    let keys = crate::snapshot::restore_into_store(dbs, &staging_store);
    let keys_with_ttl = crate::snapshot::restore_expiries_into_store(expiries, &staging_store);
    Ok(StagedSync {
        store: staging_store,
        index_schemas,
        dictionaries,
        functions,
        keys,
        keys_with_ttl,
    })
}

fn count_keys(store: &Store) -> usize {
    store
        .iter()
        .flat_map(|db| db.iter())
        .map(|shard| shard.read().len())
        .sum()
}

/// Decide whether a full resync may replace the local dataset.
///
/// A full resync is destructive by design — the replica's dataset is replaced
/// with the master's — and that is exactly right when the master is the
/// authority. It is catastrophic when the "master" is a freshly built, empty
/// node that inherited an address this replica was still configured to follow:
/// the replica holds the only copy of the data and is about to overwrite it
/// with nothing. The engine is the one component that can see both sizes, so
/// it refuses, keeps what it has, and says so.
///
/// Returns `Err(Refused)` with the reason; `Ok` means proceed.
///
/// `lost_from`: the node this replica follows, when it has restarted without
/// the stream this replica's dataset is from (see `full_sync_refusal_with`).
/// A sync from it that is refused for that is followed by a takeover.
fn guard_full_sync(
    repl_state: &ReplState,
    local_keys: usize,
    incoming_keys: usize,
    lost_from: Option<&str>,
) -> Result<(), SessionError> {
    let ratio = repl_state.full_sync_guard_ratio.load(Ordering::Relaxed);
    match full_sync_refusal_with(
        repl_state.full_sync_guard(),
        ratio,
        local_keys,
        incoming_keys,
        lost_from.is_some(),
    ) {
        Some(reason) => match lost_from {
            Some(node) if repl_state.request_take_over(node, &reason) => Err(
                SessionError::TakingOver(format!("{reason}; taking over from it")),
            ),
            _ => Err(SessionError::Refused(reason)),
        },
        None => Ok(()),
    }
}

/// The guard's decision, as a pure function of its inputs.
#[cfg(test)]
pub(crate) fn full_sync_refusal(
    guard: FullSyncGuard,
    ratio_percent: u64,
    local_keys: usize,
    incoming_keys: usize,
) -> Option<String> {
    full_sync_refusal_with(guard, ratio_percent, local_keys, incoming_keys, false)
}

/// [`full_sync_refusal`], told whether the master is the node this replica's
/// dataset came from, restarted without the stream that dataset is a
/// position in (`history_lost`). Its dataset is then not one that grew out of
/// this replica's: a much smaller one — below `ratio_percent` of this one's
/// keys — is refused in `empty` mode too. That is what a master killed with
/// no persistence looks like once clients have written a few keys to it:
/// the "no keys" check alone gave way to it at the first write. A master
/// restarted from its AOF or snapshot holds about what the replica holds,
/// and is followed as before.
pub(crate) fn full_sync_refusal_with(
    guard: FullSyncGuard,
    ratio_percent: u64,
    local_keys: usize,
    incoming_keys: usize,
    history_lost: bool,
) -> Option<String> {
    if guard == FullSyncGuard::Off || local_keys == 0 {
        return None;
    }
    if incoming_keys == 0 {
        return Some(format!(
            "the master has no keys, and this replica holds {local_keys}"
        ));
    }
    if history_lost
        && (incoming_keys as u128) * 100 < (local_keys as u128) * (ratio_percent as u128)
    {
        return Some(format!(
            "the master restarted without the stream this replica's dataset is from, and holds \
             {incoming_keys} keys, fewer than {ratio_percent}% of the {local_keys} this replica \
             holds"
        ));
    }
    if guard == FullSyncGuard::Shrink
        && (incoming_keys as u128) * 100 < (local_keys as u128) * (ratio_percent as u128)
    {
        return Some(format!(
            "the master holds {incoming_keys} keys, fewer than {ratio_percent}% of the \
             {local_keys} this replica holds"
        ));
    }
    None
}

// ── Helpers ───────────────────────────────────────────────────────────────────

async fn read_line(
    reader: &mut BufReader<impl AsyncReadExt + Unpin>,
) -> Result<String, std::io::Error> {
    let mut line = String::new();
    let n = reader.read_line(&mut line).await?;
    if n == 0 {
        return Err(std::io::Error::new(
            std::io::ErrorKind::UnexpectedEof,
            "master closed the connection",
        ));
    }
    Ok(line.trim_end_matches(['\r', '\n']).to_string())
}

async fn send_command(
    writer: &mut (impl AsyncWriteExt + Unpin),
    parts: &[&str],
) -> Result<(), std::io::Error> {
    let mut buf = format!("*{}\r\n", parts.len());
    for p in parts {
        buf.push_str(&format!("${}\r\n{}\r\n", p.len(), p));
    }
    writer.write_all(buf.as_bytes()).await
}

/// The most a replica may have sent that is not yet a whole `REPLCONF ACK`.
pub(crate) const ACK_PENDING_MAX: usize = 64 * 1024;

/// `REPLCONF ACK <offset>`, bounded: a peer that has stopped reading must not
/// be able to park this task in a write forever.
async fn send_ack(
    writer: &mut (impl AsyncWriteExt + Unpin),
    offset: u64,
    timeout: Duration,
) -> Result<(), SessionError> {
    let offset_s = offset.to_string();
    let ack = format!(
        "*3\r\n$8\r\nREPLCONF\r\n$3\r\nACK\r\n${}\r\n{}\r\n",
        offset_s.len(),
        offset_s
    );
    match tokio::time::timeout(timeout, writer.write_all(ack.as_bytes())).await {
        Ok(res) => Ok(res?),
        Err(_) => Err(SessionError::Link(format!(
            "could not write to master for {}s — master is unreachable",
            timeout.as_secs()
        ))),
    }
}

async fn expect_ok(
    reader: &mut BufReader<impl AsyncReadExt + Unpin>,
    context: &str,
    timeout: Duration,
    repl_state: &ReplState,
    my_generation: u64,
) -> Result<(), SessionError> {
    let line = guarded(
        read_line(reader),
        timeout,
        repl_state,
        my_generation,
        context,
    )
    .await?;
    if line.starts_with("+OK") || line.starts_with("+ok") {
        Ok(())
    } else {
        Err(SessionError::Link(format!(
            "{context}: expected +OK, got: {line}"
        )))
    }
}

/// Built once when entering the master's replication byte stream — not per APPLY.
///
/// Previously every replicated command reconstructed channels, ACL, client registry,
/// latency, etc.; at high master throughput that dominated catch‑up latency after bursts.
pub(crate) struct ReplicationApplyEnv {
    /// Where an applied write's AOF record goes.
    ///
    /// Two callers with opposite requirements share this struct:
    ///
    /// * The **replication stream** must append. A replica that applies its
    ///   master's writes without logging them keeps an empty AOF, so promoting
    ///   it produces a durable-looking node with nothing on disk.
    /// * **AOF replay** must not. It is re-executing the log; appending would
    ///   write every record straight back into the file it is reading.
    aof_tx: Box<dyn crate::commands::ctx::AofSender>,
    /// False for replay (see above). When true, each command still re-checks
    /// `AOF_ENABLED` so a runtime `CONFIG SET appendonly` takes effect without
    /// waiting for the replica to reconnect.
    aof_live: bool,
    /// Draining task consumes stray hub messages if a command mistakenly propagates locally.
    discard_hub_tx: crate::replication::HubTx,
    /// Held only by [`Self::new_inert`], which has no runtime to spawn a drainer
    /// on. Keeping the receiver alive means a stray send buffers instead of
    /// failing; nothing should ever arrive, because every command applied
    /// through this env runs with `apply_replication: true` and so never
    /// reaches the propagation path at all.
    _inert_hub_rx: Option<tokio::sync::mpsc::UnboundedReceiver<crate::replication::HubMsg>>,
    lastsave: Arc<parking_lot::RwLock<i64>>,
    started_at: std::time::Instant,
    pubsub: crate::pubsub::PubSubHub,
    acl_store: crate::acl::AclStore,
    acl_log: crate::acl::SharedAclLog,
    slowlog: crate::slowlog::SharedSlowLog,
    latency: crate::latency::SharedLatencyTracker,
    cluster: std::sync::Arc<crate::cluster::ClusterState>,
    monitor_registry: crate::monitor::SharedMonitorRegistry,
    tracking_table: crate::tracking::TrackingTable,
    client_registry: crate::client_registry::ClientRegistry,
}

impl ReplicationApplyEnv {
    /// A transaction from the master, as one group to this node's AOF (and,
    /// were anything to go to the hub, there too). See
    /// [`crate::replication::PropagationGroup`].
    fn propagation_group<'a>(
        &'a self,
        repl_state: &'a ReplState,
    ) -> crate::replication::PropagationGroup<'a> {
        crate::replication::PropagationGroup::begin(
            repl_state,
            &self.discard_hub_tx,
            self.aof_tx.as_ref(),
        )
    }

    /// For the replication stream: applied writes are appended to this node's
    /// own AOF, and their client-visible side effects go to the server's real
    /// hubs (see [`ReplicaStarter`]).
    fn new(starter: &ReplicaStarter) -> Self {
        let (discard_hub_tx, mut hub_rx) =
            tokio::sync::mpsc::unbounded_channel::<crate::replication::HubMsg>();
        tokio::spawn(async move { while hub_rx.recv().await.is_some() {} });
        let mut env = Self::with_hub(
            discard_hub_tx,
            None,
            Box::new(crate::commands::ctx::GlobalAofSender),
            true,
        );
        env.pubsub = starter.pubsub.clone();
        env.client_registry = Arc::clone(&starter.client_registry);
        env.tracking_table = Arc::clone(&starter.tracking_table);
        env.monitor_registry = Arc::clone(&starter.monitor_registry);
        env
    }

    /// Same environment, but usable with no tokio runtime available, and with
    /// AOF appends disabled.
    ///
    /// AOF replay runs during startup, before (and on the io_uring path,
    /// entirely outside) the runtime that `new` needs for its drain task, so it
    /// keeps the receiver instead of spawning a consumer for it.
    pub(crate) fn new_inert() -> Self {
        let (discard_hub_tx, hub_rx) =
            tokio::sync::mpsc::unbounded_channel::<crate::replication::HubMsg>();
        Self::with_hub(
            discard_hub_tx,
            Some(hub_rx),
            Box::new(crate::commands::ctx::NoopAofSender),
            false,
        )
    }

    fn with_hub(
        discard_hub_tx: crate::replication::HubTx,
        inert_hub_rx: Option<tokio::sync::mpsc::UnboundedReceiver<crate::replication::HubMsg>>,
        aof_tx: Box<dyn crate::commands::ctx::AofSender>,
        aof_live: bool,
    ) -> Self {
        Self {
            aof_tx,
            aof_live,
            discard_hub_tx,
            _inert_hub_rx: inert_hub_rx,
            lastsave: Arc::new(parking_lot::RwLock::new(0i64)),
            started_at: std::time::Instant::now(),
            pubsub: crate::pubsub::PubSubHub::new(),
            acl_store: crate::acl::new_acl_store(""),
            acl_log: crate::acl::new_acl_log(),
            slowlog: crate::slowlog::new_slowlog(u64::MAX, 0),
            latency: crate::latency::new_latency_tracker(),
            cluster: std::sync::Arc::new(crate::cluster::ClusterState::new_disabled()),
            monitor_registry: crate::monitor::new_monitor_registry(),
            tracking_table: crate::tracking::new_tracking_table(),
            client_registry: crate::client_registry::new_client_registry(),
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn apply_command(
        &self,
        cmd: Vec<Vec<u8>>,
        store: &Store,
        repl_state: &Arc<ReplState>,
        index_store: &IndexStore,
        dict_store: &DictStore,
        wait_table: &Arc<WaitTable>,
        ts_index: &SharedTsIndex,
        config: &Arc<Config>,
        compaction_tx: &CompactionTx,
        selected_db: &mut usize,
        watch_registry: &dyn crate::watch::WatchNotifier,
        peer_addr: &str,
    ) -> Result<(), Box<dyn std::error::Error>> {
        use crate::replication::keydb::{self, Translated};
        // What KeyDB sends that Redis does not: member TTLs (`EXPIREMEMBER`),
        // applied as hash-field TTLs, and `RREPLAY`, refused. Any other
        // command is applied as it is, with nothing done first.
        let (cmd, member_ttl) = if keydb::is_keydb_command(&cmd) {
            match keydb::translate(cmd)? {
                Translated::AsIs(cmd) => (cmd, None),
                Translated::MemberTtl { command, what } => (command, Some(what)),
            }
        } else {
            (cmd, None)
        };
        let out = self.execute_applied(
            cmd,
            store,
            repl_state,
            index_store,
            dict_store,
            wait_table,
            ts_index,
            config,
            compaction_tx,
            selected_db,
            watch_registry,
            peer_addr,
        );
        if let Some(what) = member_ttl
            && out.starts_with(b"-WRONGTYPE")
        {
            return Err(Box::new(keydb::Unfollowable(what)));
        }
        if !out.is_empty() && out[0] == b'-' {
            let tail = out.len().min(512);
            log_warn!(
                "Replication: Replicated command error (non-fatal): {}",
                String::from_utf8_lossy(&out[..tail])
            );
        }
        Ok(())
    }

    /// One write from the master, applied; its reply.
    #[allow(clippy::too_many_arguments)]
    fn execute_applied(
        &self,
        cmd: Vec<Vec<u8>>,
        store: &Store,
        repl_state: &Arc<ReplState>,
        index_store: &IndexStore,
        dict_store: &DictStore,
        wait_table: &Arc<WaitTable>,
        ts_index: &SharedTsIndex,
        config: &Arc<Config>,
        compaction_tx: &CompactionTx,
        selected_db: &mut usize,
        watch_registry: &dyn crate::watch::WatchNotifier,
        peer_addr: &str,
    ) -> Vec<u8> {
        use crate::commands::ctx::Ctx;
        use crate::commands::execute_command;
        let cmd_refs: Vec<&[u8]> = cmd.iter().map(|v| v.as_slice()).collect();

        // A write the master made, or one the AOF holds, is applied to the
        // keys as they were when it was made: none of them has expired here
        // that the master has not said so of, by a `DEL` further on. A
        // master that sends no such `DEL`s (before 1.1.3) expired keys by
        // its clock alone, and its writes are applied as replicas applied
        // them then: to a key past its time here, as to no key.
        // So with hash fields, each held or not as the master sends its
        // deletions or not.
        let _hold = crate::expiry::hold_of(
            repl_state.master_propagates_expiry.load(Ordering::Relaxed),
            repl_state
                .master_propagates_field_expiry
                .load(Ordering::Relaxed),
        );
        execute_command(Ctx {
            cmd: cmd_refs,
            store,
            lastsave: &self.lastsave,
            selected_db,
            aof_tx: self.aof_tx.as_ref(),
            // Re-read per command so `CONFIG SET appendonly yes` on a running
            // replica starts logging immediately.
            aof_enabled: self.aof_live
                && crate::aof::AOF_ENABLED.load(std::sync::atomic::Ordering::Relaxed),
            config,
            started_at: &self.started_at,
            index_store,
            dict_store,
            wait_table,
            ts_index,
            pubsub: &self.pubsub,
            hub_tx: &self.discard_hub_tx,
            repl_state,
            watch_registry,
            client_id: 0,
            client_registry: &self.client_registry,
            // Applying a replicated write locally, not replying to a real client.
            resp: 2,
            acl_store: &self.acl_store,
            acl_log: &self.acl_log,
            slowlog: &self.slowlog,
            latency: &self.latency,
            compaction_tx,
            cluster: &self.cluster,
            bypass_cluster_check: true,
            apply_replication: true,
            skip_write_side_effects: false,
            peer_addr,
            monitor_registry: &self.monitor_registry,
            authenticated_user: "default",
            tracking_table: &self.tracking_table,
            blocking: None,
        })
    }
}

/// For a test: `cmd` run as a client of a master runs it, its writes queued
/// on `hub_tx` (which `repl_state` must feed for them to be). Returns the
/// reply.
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
pub(crate) fn run_as_client(
    env: &ReplicationApplyEnv,
    cmd: &[&[u8]],
    store: &Store,
    repl_state: &Arc<ReplState>,
    index_store: &IndexStore,
    hub_tx: &crate::replication::HubTx,
    watch_registry: &dyn crate::watch::WatchNotifier,
) -> Vec<u8> {
    use crate::commands::ctx::Ctx;
    let config = Arc::new(crate::config::Config::default());
    let dict_store = crate::vector::new_dict_store();
    let wait_table = Arc::new(crate::wait_table::WaitTable::new());
    let ts_index = crate::store::new_ts_index();
    let (compaction_tx, _compaction_rx) = crate::vector::new_compaction_channel();
    let mut selected_db = 0usize;
    crate::commands::execute_command(Ctx {
        cmd: cmd.to_vec(),
        store,
        lastsave: &env.lastsave,
        selected_db: &mut selected_db,
        aof_tx: env.aof_tx.as_ref(),
        aof_enabled: false,
        config: &config,
        started_at: &env.started_at,
        index_store,
        dict_store: &dict_store,
        wait_table: &wait_table,
        ts_index: &ts_index,
        pubsub: &env.pubsub,
        hub_tx,
        repl_state,
        watch_registry,
        client_id: 1,
        client_registry: &env.client_registry,
        resp: 2,
        acl_store: &env.acl_store,
        acl_log: &env.acl_log,
        slowlog: &env.slowlog,
        latency: &env.latency,
        compaction_tx: &compaction_tx,
        cluster: &env.cluster,
        bypass_cluster_check: true,
        apply_replication: false,
        skip_write_side_effects: false,
        peer_addr: "client:test",
        monitor_registry: &env.monitor_registry,
        authenticated_user: "default",
        tracking_table: &env.tracking_table,
        blocking: None,
    })
}

/// The address to list a replica under: its connection's IP, with the port it
/// announced via `REPLCONF listening-port` when it announced one. Falling back
/// to the connection's source port (as this always used to) reports an
/// ephemeral port nobody can connect to.
pub(crate) fn replica_endpoint(peer_addr: &str, listening_port: Option<u16>) -> (String, u16) {
    let (ip, source_port) = peer_ip_port(peer_addr);
    match listening_port {
        Some(p) if p != 0 => (ip, p),
        _ => (ip, source_port),
    }
}

/// Split `peer_addr` from the accepted TCP connection into INFO `slaveN:ip` / `port` fields.
pub(crate) fn peer_ip_port(peer_addr: &str) -> (String, u16) {
    use std::net::SocketAddr;
    if let Ok(sa) = peer_addr.parse::<SocketAddr>() {
        return match sa {
            SocketAddr::V4(v4) => (v4.ip().to_string(), v4.port()),
            SocketAddr::V6(v6) => (format!("[{}]", v6.ip()), v6.port()),
        };
    }
    if let Some((host, port_s)) = peer_addr.rsplit_once(':')
        && let Ok(p) = port_s.parse::<u16>()
    {
        return (host.to_string(), p);
    }
    (peer_addr.to_string(), 0)
}

/// Called when a client sends PSYNC — this connection is now a replica.
/// We send the full RDB dump then register with the hub to receive
/// ongoing write command propagation.
#[allow(clippy::too_many_arguments)]
pub async fn handle_replica_connection<R, W>(
    reader: R,
    // The socket's writing half, which the writer task behind `resp_tx`
    // writes to: the payload of a full sync is written to it directly.
    writer: Arc<tokio::sync::Mutex<W>>,
    resp_tx: mpsc::Sender<Vec<u8>>,
    write_task: tokio::task::JoinHandle<()>,
    store: store::Store,
    _lastsave: Arc<parking_lot::RwLock<i64>>,
    _aof_tx: mpsc::UnboundedSender<Vec<u8>>,
    _aof_enabled: bool,
    _config: Arc<crate::config::Config>,
    _started_at: Arc<std::time::Instant>,
    index_store: crate::vector::IndexStore,
    _dict_store: crate::vector::DictStore,
    _wait_table: Arc<crate::wait_table::WaitTable>,
    _ts_index: store::SharedTsIndex,
    _pubsub: crate::pubsub::PubSubHub,
    hub_tx: crate::replication::HubTx,
    repl_state: Arc<crate::replication::ReplState>,
    peer_addr: String,
    // Legacy `SYNC` omits `+FULLRESYNC`; first payload is `$len\r\n` + RDB (Redis test helper attach_to_replication_stream).
    legacy_sync: bool,
    _leftover: Vec<u8>,
    // The port the replica announced with `REPLCONF listening-port`, if any.
    listening_port: Option<u16>,
    // What the replica asked to continue from (`PSYNC <replid> <offset>`).
    psync: Option<crate::replication::PsyncRequest>,
    // The connection's `CLIENT KILL` signal: it ends the link (#595).
    mut kill_rx: crate::client_registry::KillRx,
) -> Result<(), Box<dyn std::error::Error>>
where
    R: tokio::io::AsyncRead + Unpin + Send + 'static,
    W: tokio::io::AsyncWrite + Unpin + Send + 'static,
{
    let rollback_hub = |hub: &crate::replication::HubTx, id: u64| {
        let _ = hub.send(crate::replication::HubMsg::Deregister(id));
    };

    let replica_id = crate::replication::next_replica_id();

    // ── 1. The stream queue. The hub starts filling it at the cut below.
    // Must be **unbounded**: the forwarding task doesn't drain until the payload is sent; a bounded
    // queue hits capacity during long dumps and evicts the replica (connected_slaves goes to 0).
    let (replica_tx, replica_rx) = mpsc::unbounded_channel::<crate::replication::ReplPayload>();
    let (rdb_enqueued_tx, rdb_enqueued_rx) = tokio::sync::oneshot::channel();
    // Shared with the hub: it increments this on enqueue, we decrement it after each
    // successful flush. Lets the hub evict us if we fall far enough behind instead of
    // queueing an unbounded backlog — see `replication::mod::start_hub`.
    let pending_bytes = Arc::new(crate::replication::ReplicaQueue::default());
    // Frees what is queued however the forwarder ends, and says so.
    let mut replica_rx = crate::replication::QueueRx::new(replica_rx, Arc::clone(&pending_bytes));

    // The forwarder writes to the socket itself, one batch at a time, as the
    // io_uring loop's does. Handed to the writer task, the replica's queue
    // was emptied into the writer's at memory speed, however slowly the
    // replica read: memory counted against `maxmemory`, where the replica's
    // own queue is not (#284).
    let writer_fwd = Arc::clone(&writer);
    let write_batch = move |batch: Vec<u8>| {
        let writer = Arc::clone(&writer_fwd);
        async move {
            use tokio::io::AsyncWriteExt;
            crate::stats::TOTAL_NET_OUTPUT_BYTES.fetch_add(batch.len() as u64, Ordering::Relaxed);
            crate::stats::record_write();
            writer.lock().await.write_all(&batch).await.is_ok()
        }
    };
    let pending_bytes_fwd = Arc::clone(&pending_bytes);
    let forward_task = tokio::spawn(async move {
        if rdb_enqueued_rx.await.is_err() {
            return;
        }
        // Fewer replica-socket packets / writer wakeups than one Vec per propagated write.
        const BATCH_MAX_BYTES: usize = 4 * 1024 * 1024;

        loop {
            let first = match replica_rx.recv().await {
                Some(p) => p,
                None => break,
            };
            if pending_bytes_fwd.abandoned() {
                // Let go of for falling too far behind: what is queued is
                // freed now, as `replica_rx` is dropped, not sent (see
                // `ReplicaQueue::abandon`).
                return;
            }

            let mut batch = Vec::with_capacity(first.len().min(BATCH_MAX_BYTES));
            batch.extend_from_slice(first.as_ref());
            // The memory the payloads took while queued (see `ReplicaQueue`).
            let mut held = crate::replication::ReplicaQueue::held_for(first.len());
            drop(first);

            loop {
                if batch.len() >= BATCH_MAX_BYTES {
                    break;
                }
                match replica_rx.try_recv() {
                    Ok(p) => {
                        batch.extend_from_slice(p.as_ref());
                        held += crate::replication::ReplicaQueue::held_for(p.len());
                    }
                    Err(TryRecvError::Empty) => break,
                    Err(TryRecvError::Disconnected) => {
                        pending_bytes_fwd.taken(batch.len(), held);
                        if !pending_bytes_fwd.abandoned() {
                            write_batch(batch).await;
                        }
                        return;
                    }
                }
            }

            pending_bytes_fwd.taken(batch.len(), held);
            if !write_batch(batch).await {
                break;
            }
        }
    });

    // ── 2. A replica that only lost its connection is sent what it missed.
    // Failing that, take the cut: register with the hub and serialise the
    // dataset at one instant, so every write is in exactly one of {payload,
    // stream}.
    let (peer_ip, peer_port) = replica_endpoint(&peer_addr, listening_port);
    let endpoint = format!("{peer_ip}:{peer_port}");
    let registration = crate::replication::ReplicaRegistration {
        replica_id,
        addr: peer_addr.clone(),
        peer_ip,
        peer_port,
        tx: replica_tx,
        pending_bytes,
    };
    let full_sync = match crate::replication::request_continuation(
        &hub_tx,
        &repl_state,
        psync.as_ref(),
        registration,
    )
    .await
    {
        Ok(()) => None,
        Err(registration) => {
            match tokio::task::spawn_blocking({
                let store = Arc::clone(&store);
                let index_store = Arc::clone(&index_store);
                let repl_state = Arc::clone(&repl_state);
                let hub_tx = hub_tx.clone();
                move || {
                    crate::replication::begin_full_sync(
                        &store,
                        &index_store,
                        &repl_state,
                        &hub_tx,
                        registration,
                    )
                }
            })
            .await
            {
                Ok(Ok(v)) => Some(v),
                Ok(Err(e)) => {
                    rollback_hub(&hub_tx, replica_id);
                    return Err(e.into());
                }
                Err(e) => {
                    rollback_hub(&hub_tx, replica_id);
                    return Err(e.into());
                }
            }
        }
    };

    // ── 3. `+CONTINUE`; or `+FULLRESYNC` (omitted for legacy pre-PSYNC
    // `SYNC\r\n`) and then the payload.
    let mut frames: Vec<Vec<u8>> = Vec::with_capacity(3);
    // The payload is not counted against `maxmemory` until it is written
    // (#284).
    let mut payload_not_counted = None;
    match full_sync {
        None => frames.push(format!("+CONTINUE {}\r\n", repl_state.repl_id()).into_bytes()),
        Some(sync) => {
            if !legacy_sync {
                frames.push(sync.announcement(&repl_state.repl_id()).into_bytes());
            }
            frames.push(format!("${}\r\n", sync.payload.len()).into_bytes());
            frames.push(sync.payload);
            payload_not_counted = Some(sync.not_counted);
            if let Some(replica) = repl_state.replica(replica_id) {
                replica.set_state(crate::replication::ReplicaState::SendBulk);
            }
        }
    }
    let full = frames.len() > 1;
    // Written here, as the io_uring loop writes them, not queued for the
    // writer task: the forwarder starts once the payload is written, so the
    // writes made meanwhile wait in the replica's own queue, which is not
    // counted against `maxmemory`, rather than in the writer's behind the
    // payload, which was; and the payload is let go of once it is written.
    // Nothing is queued for the writer task before these.
    //
    // Raced against the replica going silent or being let go of: one that
    // stops reading during its full sync is let go of once its queue passes
    // its limit, and the write is given up then, rather than waited on for
    // good with its queue and the payload held (#542).
    let sent = {
        use tokio::io::AsyncWriteExt;
        let mut out = writer.lock().await;
        let write_frames = async {
            for frame in frames {
                crate::stats::TOTAL_NET_OUTPUT_BYTES
                    .fetch_add(frame.len() as u64, Ordering::Relaxed);
                if out.write_all(&frame).await.is_err() {
                    return false;
                }
            }
            true
        };
        tokio::select! {
            sent = write_frames => sent,
            _ = repl_state.replica_timed_out(replica_id) => {
                log_warn!("Replication: replica {endpoint} let go of during its full sync");
                false
            }
        }
    };
    if !sent {
        rollback_hub(&hub_tx, replica_id);
        drop(rdb_enqueued_tx);
        forward_task.abort();
        return Ok(());
    }
    drop(payload_not_counted);

    let _ = rdb_enqueued_tx.send(());
    if full {
        log_info!("Replication: Sent full RDB to replica; streaming queued writes from hub");
    }

    // ── 4. NEW: spawn ACK reader ─────────────────────────────────────────
    // The replica sends REPLCONF ACK <offset> every second.
    // We must drain the socket or the kernel buffer fills and TCP stalls.
    let hub_tx_ack = hub_tx.clone();
    let ack_reader_task = tokio::spawn(async move {
        use tokio::io::AsyncReadExt;
        let mut reader = reader;
        let mut buf = Vec::with_capacity(128);
        let mut tmp = [0u8; 128];
        loop {
            match reader.read(&mut tmp).await {
                Ok(0) | Err(_) => break, // replica disconnected
                Ok(n) => {
                    buf.extend_from_slice(&tmp[..n]);
                    // Parse all complete RESP commands in buf
                    let mut pos = 0;
                    while let Some((consumed, cmd)) =
                        crate::resp::parse::parse_resp_command(&buf[pos..])
                    {
                        // REPLCONF ACK <offset>
                        if cmd.len() == 3
                            && cmd[0].eq_ignore_ascii_case(b"REPLCONF")
                            && cmd[1].eq_ignore_ascii_case(b"ACK")
                            && let Ok(s) = std::str::from_utf8(cmd[2])
                            && let Ok(offset) = s.parse::<u64>()
                        {
                            let _ = hub_tx_ack
                                .send(crate::replication::HubMsg::AckOffset { replica_id, offset });
                        }
                        pos += consumed;
                    }
                    if pos > 0 {
                        buf.drain(0..pos);
                    }
                    // An ACK is a few dozen bytes: a replica that sends this
                    // much that is not one is not a replica.
                    if buf.len() > ACK_PENDING_MAX {
                        log_warn!(
                            "Replication: replica {replica_id} sent what is not REPLCONF ACK; disconnecting it"
                        );
                        break;
                    }
                }
            }
        }
    });

    // ── 5. Wait for write_task (replica disconnect closes resp_tx), or for
    // `forward_task` to end on its own — which also happens when the hub evicts us
    // for exceeding the backlog byte limit (it drops our `tx`, closing the channel
    // `forward_task` reads from). Either way, force the socket writer closed so the
    // whole connection tears down instead of the reader lingering on a live replica
    // the hub has already forgotten about.
    let mut write_task = write_task;
    let mut forward_task = forward_task;
    tokio::select! {
        _ = &mut write_task => {}
        _ = &mut forward_task => {
            drop(resp_tx);
        }
        // `CLIENT KILL`: the link ends here, as on the io_uring loop, where
        // the kill shuts the socket. The replica connects again and is
        // continued from the backlog.
        Ok(()) = &mut kill_rx => {
            log_info!("Replication: Link to replica {endpoint} killed by CLIENT KILL");
            forward_task.abort();
            write_task.abort();
        }
        // A replica that has gone silent, or that the hub has let go of:
        // see `ReplState::replica_timed_out`.
        silent = repl_state.replica_timed_out(replica_id) => {
            if silent {
                log_warn!(
                    "Replication: disconnecting timedout replica {endpoint}: no REPLCONF ACK for {} s (repl-timeout)",
                    repl_state.repl_timeout().as_secs()
                );
            }
            forward_task.abort();
            write_task.abort();
        }
    }
    // However the connection ended, its forwarder ends with it: left
    // running, it held the replica's queue after the hub had forgotten it.
    forward_task.abort();
    ack_reader_task.abort();

    // Hub drops channel list + ACK + connected_slaves (paired with hub RegisterChannel fetch_add).
    let _ = hub_tx.send(crate::replication::HubMsg::Deregister(replica_id));
    log_info!("Replication: Replica disconnected");
    Ok(())
}

#[cfg(test)]
mod repl_apply_env_tests {
    use super::ReplicationApplyEnv;
    use crate::replication::ReplState;

    #[tokio::test]
    async fn replication_apply_env_reuses_scaffold_for_many_writes() {
        let cfg = std::sync::Arc::new(crate::config::Config::default_replica());
        let store = crate::store::new_store(cfg.databases);
        let repl_state = std::sync::Arc::new(ReplState::new_master());
        let index = crate::vector::new_index_store();
        let dict = crate::vector::new_dict_store();
        let wait = std::sync::Arc::new(crate::wait_table::WaitTable::new());
        let ts = crate::store::new_ts_index();
        let (compaction_tx, compaction_rx) = crate::vector::new_compaction_channel();
        drop(compaction_rx);
        let (hub_tx, _hub_rx) = tokio::sync::mpsc::unbounded_channel();
        let starter = super::ReplicaStarter {
            store: std::sync::Arc::clone(&store),
            index_store: std::sync::Arc::clone(&index),
            dict_store: std::sync::Arc::clone(&dict),
            wait_table: std::sync::Arc::clone(&wait),
            ts_index: std::sync::Arc::clone(&ts),
            config: std::sync::Arc::clone(&cfg),
            compaction_tx: compaction_tx.clone(),
            repl_state: std::sync::Arc::clone(&repl_state),
            hub_tx,
            pubsub: crate::pubsub::PubSubHub::new(),
            client_registry: crate::client_registry::new_client_registry(),
            tracking_table: crate::tracking::new_tracking_table(),
            monitor_registry: crate::monitor::new_monitor_registry(),
        };
        let env = ReplicationApplyEnv::new(&starter);

        let mut db = 0usize;
        let peer = "replica:test".to_string();

        const N: u32 = 1024;
        for i in 0..N {
            let ks = format!("rk{i}");
            env.apply_command(
                vec![b"SET".to_vec(), ks.as_bytes().to_vec(), b"v".to_vec()],
                &store,
                &repl_state,
                &index,
                &dict,
                &wait,
                &ts,
                &cfg,
                &compaction_tx,
                &mut db,
                &crate::watch::NoopWatchRegistry,
                peer.as_str(),
            )
            .expect("apply SET");
        }

        env.apply_command(
            vec![b"GET".to_vec(), br"rk0".to_vec()],
            &store,
            &repl_state,
            &index,
            &dict,
            &wait,
            &ts,
            &cfg,
            &compaction_tx,
            &mut db,
            &crate::watch::NoopWatchRegistry,
            peer.as_str(),
        )
        .unwrap();

        let shard = crate::store::get_shard(&store[0], "rk0");
        let map = shard.read();
        match map.get("rk0") {
            Some(crate::store::ValueRef::String(b)) => assert_eq!(&b[..], b"v"),
            _ => panic!("unexpected value variant for rk0"),
        }
    }
}

/// Regression coverage for a live bug found via `smoke/replication_blackbox.sh`
/// against a real 3-container re-point: a replica moved from master-a to
/// master-b reported `master_link_status:down` in `INFO replication`
/// indefinitely, even though both the connection log and every other
/// replication-state field showed the re-point had fully succeeded.
///
/// Root cause: link state is shared, but a re-point briefly runs two
/// replication sessions concurrently — the new task connects and starts
/// streaming before the superseded task notices its epoch is stale and
/// returns. The superseded task's `SlaveUpstreamGuard` then drops and (pre-fix)
/// unconditionally cleared the flag, clobbering the new task's state. These
/// tests exercise the guard's generation bookkeeping directly — no networking
/// involved, so they catch the exact race the container-level test found, at
/// unit-test speed.
#[cfg(test)]
mod slave_upstream_guard_tests {
    use super::SlaveUpstreamGuard;
    use crate::replication::{LinkState, ReplState};
    use std::sync::Arc;
    use std::sync::atomic::Ordering;

    fn up(rs: &ReplState) -> bool {
        rs.slave_link_up.load(Ordering::Acquire)
    }

    /// An open socket is not a
    /// healthy link. The link is only up once the dataset is synced.
    #[test]
    fn connecting_and_syncing_are_not_up() {
        let rs = Arc::new(ReplState::new_master());
        let epoch = rs.begin_replication_epoch();
        let guard = SlaveUpstreamGuard::connect(&rs, epoch);
        assert!(!up(&rs), "a link that is still connecting must report down");
        assert_eq!(rs.link_state(), LinkState::Connecting);

        guard.mark_syncing();
        assert!(!up(&rs), "a link that is still syncing must report down");
        assert_eq!(rs.link_state(), LinkState::Sync);

        guard.mark_synced();
        assert!(up(&rs));
        assert_eq!(rs.link_state(), LinkState::Connected);
    }

    #[test]
    fn a_superseded_task_cannot_claim_the_link() {
        let rs = Arc::new(ReplState::new_master());
        let stale_gen = rs.begin_replication_epoch();
        rs.begin_replication_epoch(); // supersede before connect() even runs
        let guard = SlaveUpstreamGuard::connect(&rs, stale_gen);
        guard.mark_synced();
        assert!(
            !up(&rs),
            "a task that was already superseded must not mark the link up"
        );
    }

    #[test]
    fn drop_marks_the_link_down_when_still_the_current_generation() {
        let rs = Arc::new(ReplState::new_master());
        let epoch = rs.begin_replication_epoch();
        {
            let guard = SlaveUpstreamGuard::connect(&rs, epoch);
            guard.mark_synced();
            assert!(up(&rs));
        }
        assert!(
            !up(&rs),
            "an ordinary disconnect, with no re-point since, must clear the flag"
        );
        assert_eq!(rs.link_state(), LinkState::Connect);
        assert!(rs.master_link_down_since_seconds().is_some());
    }

    /// The actual bug: a re-point's new task connects and marks the link up,
    /// *then* the superseded old task's guard finally drops. The drop must be
    /// a no-op — it must not clobber the newer generation's state.
    #[test]
    fn stale_guard_drop_does_not_clobber_a_newer_generations_link_state() {
        let rs = Arc::new(ReplState::new_master());
        let old_gen = rs.begin_replication_epoch();
        let old_guard = SlaveUpstreamGuard::connect(&rs, old_gen);
        old_guard.mark_synced();
        assert!(up(&rs));

        // Re-point: a new task claims a newer generation and syncs — exactly
        // what REPLICAOF does while already a slave.
        let new_gen = rs.begin_replication_epoch();
        let new_guard = SlaveUpstreamGuard::connect(&rs, new_gen);
        new_guard.mark_synced();
        assert!(up(&rs));

        // The superseded old task's guard finally drops (its loop noticed the
        // epoch mismatch and returned). Before the fix, this unconditionally
        // marked the link down despite the new generation's connection being
        // fully live and streaming.
        drop(old_guard);
        assert!(
            up(&rs),
            "a superseded task's cleanup must not clear a newer generation's live link"
        );
    }
}

/// A full resync from an empty
/// master silently discarded a larger local dataset.
#[cfg(test)]
mod full_sync_guard_tests {
    use super::{full_sync_refusal, full_sync_refusal_with, load_full_sync_payload};
    use crate::replication::FullSyncGuard;

    #[test]
    fn an_empty_master_is_refused_when_the_replica_holds_data() {
        let reason = full_sync_refusal(FullSyncGuard::Empty, 50, 502, 0).expect("must refuse");
        assert!(reason.contains("502"), "{reason}");
    }

    /// The first sync of a fresh replica, and any sync where there is nothing
    /// local to lose, must go through untouched.
    #[test]
    fn nothing_local_means_nothing_to_protect() {
        for guard in [
            FullSyncGuard::Off,
            FullSyncGuard::Empty,
            FullSyncGuard::Shrink,
        ] {
            assert!(full_sync_refusal(guard, 50, 0, 0).is_none());
            assert!(full_sync_refusal(guard, 50, 0, 1_000).is_none());
        }
    }

    #[test]
    fn off_accepts_everything() {
        assert!(full_sync_refusal(FullSyncGuard::Off, 50, 1_000_000, 0).is_none());
        assert!(full_sync_refusal_with(FullSyncGuard::Off, 50, 1_000_000, 1, true).is_none());
    }

    /// The master restarted without the stream this replica's dataset is
    /// from: in `empty` mode too, a dataset below the ratio is refused (the
    /// AKS run's master had 987 keys to the replica's 25939), and one about
    /// the replica's size — a master back from its AOF — is followed.
    #[test]
    fn a_master_that_lost_its_stream_is_held_to_the_ratio() {
        let r = full_sync_refusal_with(FullSyncGuard::Empty, 50, 25_939, 987, true);
        assert!(r.is_some_and(|r| r.contains("restarted without")));
        assert!(full_sync_refusal_with(FullSyncGuard::Empty, 50, 25_939, 25_900, true).is_none());
        // Not the same history: as before.
        assert!(full_sync_refusal_with(FullSyncGuard::Empty, 50, 25_939, 987, false).is_none());
    }

    /// `empty` is the narrow default: a master with *some* data is the
    /// authority, however much smaller it is.
    #[test]
    fn empty_mode_only_refuses_a_keyless_master() {
        assert!(full_sync_refusal(FullSyncGuard::Empty, 50, 1_000, 1).is_none());
        assert!(full_sync_refusal(FullSyncGuard::Empty, 50, 1_000, 0).is_some());
    }

    #[test]
    fn shrink_mode_refuses_below_the_ratio() {
        // 50%: 499 of 1000 is refused, 500 of 1000 is accepted.
        assert!(full_sync_refusal(FullSyncGuard::Shrink, 50, 1_000, 499).is_some());
        assert!(full_sync_refusal(FullSyncGuard::Shrink, 50, 1_000, 500).is_none());
        // A master that is larger is never a problem.
        assert!(full_sync_refusal(FullSyncGuard::Shrink, 50, 1_000, 5_000).is_none());
        // Ratio 0 degenerates to `empty`.
        assert!(full_sync_refusal(FullSyncGuard::Shrink, 0, 1_000, 1).is_none());
        assert!(full_sync_refusal(FullSyncGuard::Shrink, 0, 1_000, 0).is_some());
    }

    /// A payload that does not parse must be an error. It used to be logged
    /// and then treated as an empty dataset — which was swapped in over the
    /// live one.
    #[test]
    fn a_corrupt_payload_is_an_error_not_an_empty_dataset() {
        // Valid magic, then garbage.
        let mut payload = crate::snapshot::KDB_MAGIC.to_vec();
        payload.extend_from_slice(&1u32.to_le_bytes());
        payload.extend_from_slice(&3u32.to_le_bytes());
        payload.extend_from_slice(b"key");
        payload.push(250); // no such type tag
        assert!(load_full_sync_payload(&payload, 16).is_err());

        // Not a KDB image and not an RDB either.
        assert!(load_full_sync_payload(b"definitely not a dataset", 16).is_err());
    }

    /// A 1.2.0 master's payload that reads more than one way (#441) is an
    /// error, with no staged dataset, and says what to do about the master.
    #[test]
    fn a_payload_that_reads_more_than_one_way_is_an_error() {
        let payload = crate::snapshot::readings_tests::two_ways();
        match load_full_sync_payload(&payload, 16) {
            Err(super::SessionError::Link(why)) => {
                assert!(why.contains("can be read more than one way"), "{why}");
                assert!(why.contains("upgrade the master"), "{why}");
            }
            Err(_) => panic!("refused for something else"),
            Ok(_) => panic!("a dataset was staged"),
        }
    }

    /// Values, expiries and the key count all survive the payload round trip.
    #[test]
    fn payload_round_trip_keeps_keys_and_ttls() {
        let store = crate::store::new_store(2);
        for (db, key) in [(0usize, "a"), (0, "b"), (1, "c")] {
            crate::store::get_shard(&store[db], key)
                .write()
                .insert_str(key, &b"v"[..]);
        }
        let in_an_hour = crate::commands::helpers::now_ms() + 3_600_000;
        crate::store::get_shard(&store[0], "a")
            .write()
            .set_expires("a", in_an_hour);
        // A time to live for a key that does not exist is none.
        assert!(
            !crate::store::get_shard(&store[0], "ghost")
                .write()
                .set_expires("ghost", in_an_hour)
        );

        let payload = crate::snapshot::full_sync_payload(&store, None).unwrap();
        let staged = load_full_sync_payload(&payload, 2).expect("payload loads");
        assert_eq!(staged.keys, 3);
        assert_eq!(staged.keys_with_ttl, 1);
        assert_eq!(
            crate::store::get_shard(&staged.store[0], "a")
                .read()
                .expires("a"),
            Some(in_an_hour)
        );
        assert_eq!(
            crate::store::get_shard(&staged.store[0], "b")
                .read()
                .expires("b"),
            None
        );
        assert!(
            crate::store::get_shard(&staged.store[1], "c")
                .read()
                .contains_key("c")
        );
    }

    /// A key whose TTL ran out while the payload was in transit is loaded
    /// with its time, past as it is: not resurrected without a TTL, and not
    /// deleted by the replica either. Its clients do not see it, and the
    /// master's `DEL` of it is on its way (see `expiry`).
    #[test]
    fn keys_already_expired_are_kept_for_the_masters_del() {
        let store = crate::store::new_store(1);
        for key in ["live", "dead"] {
            crate::store::get_shard(&store[0], key)
                .write()
                .insert_str(key, &b"v"[..]);
        }
        let past = crate::commands::helpers::now_ms() - 5_000;
        crate::store::get_shard(&store[0], "dead")
            .write()
            .set_expires("dead", past);

        let payload = crate::snapshot::full_sync_payload(&store, None).unwrap();
        let staged = load_full_sync_payload(&payload, 1).expect("payload loads");
        assert_eq!(staged.keys, 2);
        let shard = crate::store::get_shard(&staged.store[0], "dead").read();
        assert_eq!(shard.expires("dead"), Some(past));
        assert!(!shard.contains_key("dead"), "past its time to a reader");
    }
}

#[cfg(test)]
mod stream_transaction_tests {
    use super::*;

    fn enc(parts: &[&str]) -> Vec<u8> {
        let parts: Vec<Vec<u8>> = parts.iter().map(|p| p.as_bytes().to_vec()).collect();
        crate::resp::write::encode_resp_command(&parts)
    }

    fn whole(t: StreamTransaction) -> WholeTransaction {
        match t {
            StreamTransaction::Whole(whole) => whole,
            StreamTransaction::Partial => panic!("partial"),
            StreamTransaction::None => panic!("none"),
        }
    }

    #[test]
    fn a_command_that_is_not_multi_is_not_a_transaction() {
        let mut scanned = 0;
        let buf = enc(&["SET", "a", "1"]);
        assert!(matches!(
            transaction_at(&buf, &mut scanned),
            StreamTransaction::None
        ));
        assert!(matches!(
            transaction_at(b"", &mut scanned),
            StreamTransaction::None
        ));
    }

    #[test]
    fn a_transaction_is_whole_only_once_its_exec_is_there() {
        let mut stream = enc(&["MULTI"]);
        stream.extend_from_slice(&enc(&["SET", "a", "1"]));
        stream.extend_from_slice(&enc(&["PING"]));
        stream.extend_from_slice(&enc(&["SET", "b", "2"]));
        let exec_at = stream.len();
        stream.extend_from_slice(&enc(&["EXEC"]));
        let len = stream.len();
        stream.extend_from_slice(&enc(&["SET", "after", "3"]));

        // Arriving a few bytes at a time: partial until the `EXEC` is
        // whole, and what was looked through is not looked through again.
        let mut scanned = 0;
        for cut in 1..len {
            assert!(
                matches!(
                    transaction_at(&stream[..cut], &mut scanned),
                    StreamTransaction::Partial | StreamTransaction::None
                ),
                "at {cut}"
            );
            assert!(scanned <= exec_at);
        }
        assert_eq!(scanned, exec_at);
        let t = whole(transaction_at(&stream, &mut scanned));
        assert_eq!(t.len, len, "MULTI to EXEC, and nothing after");
        assert!(t.heartbeat);
        assert_eq!(
            t.commands,
            vec![
                vec![b"SET".to_vec(), b"a".to_vec(), b"1".to_vec()],
                vec![b"SET".to_vec(), b"b".to_vec(), b"2".to_vec()],
            ]
        );
    }

    #[test]
    fn an_empty_transaction_is_whole_and_applies_nothing() {
        let mut stream = enc(&["multi"]);
        stream.extend_from_slice(&enc(&["exec"]));
        let t = whole(transaction_at(&stream, &mut 0));
        assert_eq!(t.len, stream.len());
        assert!(t.commands.is_empty());
    }
}