kividb 1.2.2

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
use crate::replication::{ReplState, start_hub};

use config::Config;
use parking_lot::RwLock;
#[allow(unused_imports)]
use std::net::SocketAddr;
use std::{sync::Arc, time::Instant};
#[allow(unused_imports)]
use tokio::net::TcpListener;
use tokio::sync::mpsc;

// First, so its logging macros are in scope in every module after it.
#[macro_use]
pub mod loglevel;
mod acl;
mod aof;
pub mod client_registry;
pub mod cluster;
pub mod cmdstats;
pub mod command_gate;
mod commands;
mod compaction;
mod config;
pub mod eviction;
pub mod expiry;
pub mod field_expiry;
pub mod key_bytes;
pub mod key_moves;
pub mod keyspace_events;
pub mod keyspec;
pub mod latency;
pub mod lazyfree;
pub mod listen;
#[cfg(feature = "lua")]
mod lua_vm_blocking;
mod member_set;
pub mod memory_use;
pub mod monitor;
pub mod node_tls;
pub mod pause;
pub mod protected_mode;
mod pubsub;
pub mod redis_settings;
pub mod replication;
mod resp;
mod script_clock;
mod server;
mod shared_bytes;
pub mod shutdown;
pub mod slowlog;
mod snapshot;
mod stats;
mod store;
pub mod tag_locks;
#[cfg(test)]
mod test_hooks;
pub mod tracking;
pub mod types;
mod update_check;
mod value_slab;
mod vector;
pub mod wait_table;
pub mod watch;
pub mod write_gate;
pub mod write_order;

#[cfg(feature = "tls")]
mod tls;

pub use crate::loglevel::{LOG_LEVEL, log};
use crate::shutdown::{SHUTDOWN_MODE, SHUTDOWN_PENDING, mode};
use std::sync::atomic::Ordering::Relaxed;

#[cfg(target_os = "linux")]
mod server_uring;
#[cfg(target_os = "linux")]
use config::IoModel;
#[cfg(target_os = "linux")]
use std::sync::atomic::{AtomicBool, Ordering};

/// Counts what it allocates: `maxmemory` is measured against that. See
/// `memory_use`.
#[global_allocator]
static ALLOCATOR: memory_use::Counting = memory_use::Counting;

pub static RUNTIME_MAXMEMORY: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);

fn print_banner(threads: usize, config: &Arc<Config>) {
    let version = env!("CARGO_PKG_VERSION");

    // get system info
    let cores = std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(0);

    let mem_gb = {
        // read from /proc/meminfo on linux, fallback on mac
        #[cfg(target_os = "linux")]
        {
            std::fs::read_to_string("/proc/meminfo")
                .ok()
                .and_then(|s| {
                    s.lines()
                        .find(|l| l.starts_with("MemTotal"))
                        .and_then(|l| l.split_whitespace().nth(1))
                        .and_then(|n| n.parse::<u64>().ok())
                })
                .map(|kb| kb / 1024 / 1024)
                .unwrap_or(0)
        }
        #[cfg(not(target_os = "linux"))]
        {
            0u64
        }
    };

    let os = std::env::consts::OS;
    let arch = std::env::consts::ARCH;
    let bind = &config.bind;
    let port = config.port;
    let databases = config.databases;

    let aof_status = if config.aof { "enabled" } else { "disabled" };

    println!(
        r#"                                                                                     
                                                                                                    
                                                   :::.                                     
                                .:-==-:.       :#%@%%%@%%=                                  
                          -*@@%%%######%%%%%=:%%+:::::::=%%:                                
                      :*%%#+-::::::::::::::=*%#:::::::::::#%.                               
                    +%%*::::::::::::::::::::::::::::%@%-::+%#.                              
                  =%%=::::::::::::::::::::::::::::::=#+:::*%@@@#.                           
                .%%+:::::::::::::::::::::::::::::::::::::+%@@@@@@%+.                  ██╗  ██╗ ██╗           ██╗ ███████╗  ███████╗ 
               -%%-::::::::::::::::::::::::::::::::::::*%%*+#%@@@@@%#:                ██║ ██╔╝ ╚═╝           ╚═╝ ╚██╔══██╗ ╚██╔══██╗
              .%%:::::::::::::::::::::::::::::::::%@@%%*.        =#%@@%-              █████╔╝  ██╗ ██╗   ██╗ ██╗  ██║  ██║  ██████╔╝
              +@=::::::::::::::::::::::::::::::::+@#.               .=%@%-            ██╔═██╗  ██║ ╚██╗ ██╔╝ ██║  ██║  ██║  ██╔══██╗
              %#::::::::::::::::::::::::::::::::+%%:                    =%%:          ██║ ╚██╗ ██║  ╚████╔╝  ██║ ███████╔╝ ███████╔╝
              @#:::::::::::::::::::::::::::::::*@%=                       .#+         ╚═╝  ╚═╝ ╚═╝   ╚═══╝   ╚═╝ ╚══════╝  ╚══════╝ 
              %%:::::::::::::::::::::::::::::+%@%-                          .               
              =@*::::::::::::::::::::::::::*%@@*                                            
               *@*::::=+:::::::::::::::-*%@@%%:                                             
                *@#-:##::::::::::-=+*%@@@@%*.                                               
                 :#@%@*::::::*%@@@%%@@@%*:                                                  
                   .*%%=:::*%%%%%%%@@%+                                                     
                     .#@@@%*-   .#%@*.                                                      
                      .#@*        :%@%:                                                     
                        %@*         =%@#                                                    
                         #@#          +%%+                                                  
                          *%%+:...     .*@%*:....                                           
                       *%%%%%%%@%%%%+ %%%%%%%@@%%%%-                                        
                               .+-            :+.                                           
                                                                                                    
    "#
    );

    println!("  KiviDB v{version} - A fast Redis®-compatible store written in Rust");
    println!("  https://kividb.io");
    println!();
    println!("  Licensed under the GNU Affero General Public License, version 3 (AGPLv3)");
    println!();
    println!("  * Version        : {version}");
    let mode = if config.cluster_enabled {
        "cluster"
    } else {
        "standalone"
    };
    println!("  * Mode           : {mode}");
    println!("  * OS             : {os} {arch}");
    if mem_gb > 0 {
        println!("  * Memory         : {mem_gb}GiB available");
    }
    println!("  * CPUs           : {cores} cores detected");
    if port == 0 {
        println!("  * Listening on   : no plaintext port (port 0): TLS only");
    } else {
        println!("  * Listening on   : {bind}:{port}");
    }

    #[cfg(feature = "tls")]
    if config.tls_enabled() {
        println!("  * TLS port       : {}:{}", config.bind, config.tls_port);
    }

    // Cluster-specific lines, only when enabled
    if config.cluster_enabled {
        let bus_port = config.cluster_bus_port();
        println!("  * Cluster bus    : {bind}:{bus_port}");
        println!("  * Node timeout   : {}ms", config.cluster_node_timeout);
        // The node ID isn't known here — it's generated/loaded inside
        // ClusterState::from_disk_or_fresh, which happens AFTER the banner.
        // We could either call it before banner, or print a placeholder
        // and log the actual ID elsewhere. The cleanest approach is to
        // print "Node ID: (pending init)" and rely on a separate log line
        // emitted after ClusterState construction.
        println!("  * Node ID        : (printed after cluster init)");
    }

    println!("  * Worker threads : {threads}");
    println!("  * AOF            : {aof_status}");
    // Name the source recovery will actually use. This line used to read
    // "KDB snapshot (SAVE / BGSAVE)" unconditionally, which was true even with
    // --aof: the AOF was written but never read back, so an operator who
    // enabled it and mounted a volume still lost everything since the last
    // snapshot on a crash.
    println!(
        "  * Persistence    : {}",
        if config.aof {
            "AOF (recovered on start) + KDB snapshot (SAVE / BGSAVE)"
        } else {
            "KDB snapshot (SAVE / BGSAVE)"
        }
    );
    println!("  * Databases      : {databases}");
    println!(
        "  * ACL file       : {}",
        if config.aclfile.is_empty() {
            "none".into()
        } else {
            config.aclfile.clone()
        }
    );
    println!();
}

#[cfg(target_os = "linux")]
fn is_uring_available() -> bool {
    use std::os::unix::io::RawFd;

    #[repr(C)]
    struct IoUringParams {
        sq_entries: u32,
        cq_entries: u32,
        flags: u32,
        sq_thread_cpu: u32,
        sq_thread_idle: u32,
        features: u32,
        wq_fd: u32,
        resv: [u32; 3],
        sq_off: [u8; 40],
        cq_off: [u8; 40],
    }

    let mut params = IoUringParams {
        sq_entries: 0,
        cq_entries: 0,
        flags: 0,
        sq_thread_cpu: 0,
        sq_thread_idle: 0,
        features: 0,
        wq_fd: 0,
        resv: [0; 3],
        sq_off: [0; 40],
        cq_off: [0; 40],
    };

    let ret = unsafe {
        libc::syscall(
            libc::SYS_io_uring_setup,
            1u32,
            &mut params as *mut IoUringParams,
        )
    };

    if ret < 0 {
        return false;
    }

    unsafe { libc::close(ret as RawFd) };
    true
}

// Entry point
fn main() {
    // An error that ends the server is logged like any other line, rather
    // than printed as a Rust `Debug` dump.
    if let Err(e) = run() {
        log_fatal!("{e}");
        std::process::exit(1);
    }
}

fn run() -> Result<(), Box<dyn std::error::Error>> {
    // Parsed by hand rather than with `Config::parse()`, to keep the matches:
    // the config file must not override an option given on the command line,
    // and only the matches know which those are.
    let matches = <Config as clap::CommandFactory>::command().get_matches();
    let mut cfg =
        <Config as clap::FromArgMatches>::from_arg_matches(&matches).unwrap_or_else(|e| e.exit());
    let from_cli =
        |option: &str| matches.value_source(option) == Some(clap::parser::ValueSource::CommandLine);
    cfg.bind_explicit =
        matches.value_source("bind") == Some(clap::parser::ValueSource::CommandLine);
    match cfg.apply_config_file(&from_cli) {
        Ok(warnings) => {
            for w in warnings {
                log_warn!("{w}");
            }
        }
        Err(e) => {
            log_fatal!("Bad directive or wrong number of arguments — {e}");
            std::process::exit(1);
        }
    }
    // `dir`: everything on disk is relative to it. The config file's own path
    // is pinned down first, so CONFIG REWRITE still finds it.
    if !cfg.dir.is_empty() {
        if let Ok(absolute) = std::path::absolute(&cfg.configfile) {
            cfg.configfile = absolute.to_string_lossy().into_owned();
        }
        if let Err(e) = std::env::set_current_dir(&cfg.dir) {
            log_fatal!("Can't chdir to '{}': {e}", cfg.dir);
            std::process::exit(1);
        }
    }
    // Refuse a configuration that would start something other than what was
    // asked for — most importantly `--tls-port` on a build with no TLS in it,
    // which used to come up serving plaintext without a word in the log.
    match cfg.validate(cfg!(feature = "tls")) {
        Ok(warnings) => {
            for w in warnings {
                log_warn!("{w}");
            }
        }
        Err(e) => {
            log_fatal!("{e}");
            std::process::exit(1);
        }
    }
    if let Err(e) = crate::node_tls::init(&cfg) {
        log_fatal!("TLS between nodes: {e}");
        std::process::exit(1);
    }
    crate::protected_mode::set(cfg.protected_mode);
    crate::protected_mode::set_bind_explicit(cfg.bind_explicit);
    // `appendfsync`, from the command line or the file (#513). The file's
    // `no` has been warned about as it was read; the command line's is here.
    if from_cli("appendfsync") && cfg.appendfsync.eq_ignore_ascii_case("no") {
        log_warn!(
            "'--appendfsync no' syncs the append-only file once a second, as 'everysec' does"
        );
    }
    let _ = crate::commands::server::config_set_global("appendfsync", &cfg.appendfsync);
    let threads = cfg.resolve_threads();
    let config = Arc::new(cfg);
    RUNTIME_MAXMEMORY.store(config.maxmemory, std::sync::atomic::Ordering::Relaxed);
    // Without Lua there are no scripts to run beside each other, and the
    // commands are spared looking for a tag to wait on.
    tag_locks::set_enabled(cfg!(feature = "lua") && config.lua_parallel_scripts);
    eviction::configure(&config);
    compaction::configure(&config);
    snapshot::SNAPSHOT_DATABASES.store(config.databases, std::sync::atomic::Ordering::Relaxed);
    keyspace_events::KS_FLAGS.store(
        keyspace_events::parse_ks_flags(&config.notify_keyspace_events),
        std::sync::atomic::Ordering::Relaxed,
    );
    let started_at = Instant::now();
    if let Some(l) = log::parse_level(&config.loglevel) {
        LOG_LEVEL.store(l, std::sync::atomic::Ordering::Relaxed);
    }
    loglevel::set_json(config.log_format == "json");
    if let Err(e) = loglevel::set_logfile(&config.logfile) {
        log_fatal!(
            "Can't open the log file '{}': {e}. Check that its directory exists and is \
             writable by this user, or leave logfile unset to log to standard error",
            config.logfile
        );
        std::process::exit(1);
    }

    // Whether a newer release is out on GitHub: the first thing printed.
    // Waits for the reply at most 1.5 s; a later one is dropped. See
    // src/update_check.rs.
    if let Some(pending) = update_check::start(&config) {
        update_check::show(pending);
    }

    print_banner(threads, &config);
    log_info!(
        "KiviDB {} starting: pid {}, {} build, config file {}",
        env!("CARGO_PKG_VERSION"),
        std::process::id(),
        update_check::variant(),
        if config.configfile_loaded {
            format!("'{}'", config.configfile)
        } else {
            "none".to_string()
        }
    );
    // One engine to a data directory, before anything in it is read.
    lock_data_dir();
    // io_uring's workers hold open files of their own, kept from clients.
    #[cfg(target_os = "linux")]
    let uring = match config.io_model {
        IoModel::Uring => true,
        IoModel::Tokio => false,
        IoModel::Auto => is_uring_available(),
    };
    #[cfg(not(target_os = "linux"))]
    let uring = false;
    if let Err(e) = crate::client_registry::fit_max_clients(if uring { threads } else { 0 }) {
        log_fatal!("{e}");
        std::process::exit(1);
    }

    // `backupdirname` is relative to `dir`, which is now the working
    // directory.
    commands::backup::recover(&config);
    // `LASTSAVE` until the first save: the start, as in Redis (#149).
    stats::record_save();
    crate::commands::memory::note_startup();

    #[cfg(target_os = "linux")]
    match config.io_model {
        IoModel::Uring => {
            log_info!("I/O model      : io_uring (forced)");
            run_uring(config, started_at)?;
        }
        IoModel::Tokio => {
            log_info!("I/O model      : tokio (forced)");
            run_tokio(config, started_at)?;
        }
        IoModel::Auto => {
            if uring {
                log_info!("I/O model      : io_uring");
                run_uring(config, started_at)?;
            } else {
                log_info!("I/O model      : tokio (io_uring unavailable)");
                run_tokio(config, started_at)?;
            }
        }
    }

    #[cfg(not(target_os = "linux"))]
    {
        log_info!("I/O model      : tokio");
        run_tokio(Arc::clone(&config), started_at)?;
    }

    Ok(())
}

/// The file in the data directory that a running engine holds locked.
const DATA_DIR_LOCK: &str = "kividb.lock";

/// Take the data directory — the working directory by now — for this
/// process, waiting while another process has it.
///
/// Two engines in one directory read and write the same files. A second one
/// started while the first was stopping, as a replacement container can be
/// on the same volume, loaded the dump the first was about to replace, then
/// carried on the first one's replication stream from where that stopped,
/// and its replicas dropped their data for the older copy (#303). The lock
/// is an exclusive `flock` (`LockFileEx` on Windows) held until the process
/// exits, when the system releases it however the process ends. The other
/// process is usually on its way out, so this waits for it rather than
/// giving up.
fn lock_data_dir() {
    static HELD: std::sync::OnceLock<std::fs::File> = std::sync::OnceLock::new();
    let file = match std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .write(true)
        .open(DATA_DIR_LOCK)
    {
        Ok(file) => file,
        Err(e) => {
            log_warn!(
                "Can't open {DATA_DIR_LOCK} in the data directory ({e}): starting without the \
                 lock that keeps a second process out of it"
            );
            return;
        }
    };
    let waiting_since = Instant::now();
    let mut told: Option<Instant> = None;
    loop {
        match file.try_lock() {
            Ok(()) => break,
            Err(std::fs::TryLockError::WouldBlock) => {
                if told.is_none_or(|at| at.elapsed() >= std::time::Duration::from_secs(5)) {
                    let dir = std::env::current_dir()
                        .map(|dir| dir.display().to_string())
                        .unwrap_or_else(|_| ".".into());
                    log_warn!(
                        "The data directory {dir} is in use by another process (it holds \
                         {DATA_DIR_LOCK}): waiting for it to be free ({}s so far)",
                        waiting_since.elapsed().as_secs()
                    );
                    told = Some(Instant::now());
                }
                std::thread::sleep(std::time::Duration::from_millis(50));
            }
            Err(std::fs::TryLockError::Error(e)) => {
                log_warn!(
                    "Can't lock {DATA_DIR_LOCK} ({e}): starting without the lock that keeps a \
                     second process out of the data directory"
                );
                return;
            }
        }
    }
    if told.is_some() {
        log_info!(
            "The data directory is free after {:.1}s: starting",
            waiting_since.elapsed().as_secs_f64()
        );
    }
    let _ = HELD.set(file);
}

/// Walk keys to populate TEXT / inverted / FLAT data and HNSW graphs. A graph
/// restored from the snapshot is kept and brought up to date with the keys,
/// which an AOF delta may have changed since (see
/// [`vector::backfill_from_db_progress`] `keep_loaded_hnsw`).
///
/// Caller must set [`vector::SNAPSHOT_INDEX_REBUILD`] true before clients are
/// accepted; the background thread clears it when this returns.
fn backfill_snapshot_search_indexes(
    store: &store::Store,
    index_store: &vector::IndexStore,
    names: &[String],
) {
    let mut n = 0usize;
    for name in names {
        let def_for_fill = {
            let idx = index_store.read();
            match idx.get(name) {
                Some(d) => d.clone(),
                None => {
                    log_warn!("Index `{name}` missing after registration — skipping backfill");
                    continue;
                }
            }
        };
        let db_i = def_for_fill.db_index.min(store.len().saturating_sub(1));
        vector::backfill_from_db_progress(&store[db_i], &def_for_fill, true, true);
        n += 1;
    }
    if n > 0 {
        log_info!("Snapshot index merge pass finished for {n} index(es)");
    }
}

fn spawn_snapshot_index_backfill_thread(
    store: store::Store,
    index_store: vector::IndexStore,
    index_names: Vec<String>,
) {
    std::thread::spawn(move || {
        backfill_snapshot_search_indexes(&store, &index_store, &index_names);
        vector::SNAPSHOT_INDEX_REBUILD.store(false, std::sync::atomic::Ordering::Release);
        log_info!("Search index startup complete — full command set is available");
    });
}

/// Load (or create) this node's cluster state, exiting if the cluster config
/// file exists but cannot be used. See `ClusterState::from_config`.
fn load_cluster_state(config: &Config) -> cluster::ClusterState {
    match cluster::ClusterState::from_config(config) {
        Ok(state) => state,
        Err(e) => {
            log_fatal!("{e}");
            std::process::exit(1);
        }
    }
}

/// Start following a master if this node is configured to: `--replicaof`
/// in standalone mode, or the replica role recorded in `nodes.conf` in cluster
/// mode.
///
/// The cluster case used to be handled inline on each startup path, and both
/// copies were wrong. The io_uring one called `tokio::spawn` from a thread with
/// no runtime, which panics, so a cluster replica could not restart on the
/// default I/O model at all. And both, on finding that the recorded master was
/// missing from the node table, returned `Ok(())` from the function that runs
/// the server — a clean exit, with a log line claiming it was "staying as
/// master temporarily".
fn start_configured_replication(
    config: &Config,
    cluster_state: &cluster::ClusterState,
    starter: &replication::replica_client::ReplicaStarter,
) {
    if let Some((host, port)) = config.replicaof_addr() {
        starter.start(host, port);
        return;
    }
    if !config.cluster_enabled {
        return;
    }
    let Some(master_id) = cluster_state.my_master_id() else {
        return;
    };
    let master_addr = cluster_state
        .nodes
        .read()
        .get(&master_id)
        .map(|m| (m.ip.clone(), m.client_port));
    match master_addr {
        Some((ip, port)) if !ip.is_empty() && port != 0 => {
            log_info!(
                "Cluster: Restored replica role of master {} → restarting replication client",
                cluster::node::node_id_str(&master_id)
            );
            starter.start(ip, port);
        }
        _ => {
            // Still a replica as far as the cluster is concerned: mark the
            // role so this node stays read-only, and let gossip supply the
            // master's address (see `cluster::bus` — it re-points us once the
            // master is known).
            log_info!(
                "Cluster: Recorded master {} has no known address yet — waiting for gossip \
                 before replicating",
                cluster::node::node_id_str(&master_id)
            );
            starter.repl_state.become_slave();
        }
    }
}

fn run_tokio(config: Arc<Config>, started_at: Instant) -> Result<(), Box<dyn std::error::Error>> {
    let threads = config.resolve_threads();
    tokio::runtime::Builder::new_multi_thread()
        .worker_threads(threads)
        .enable_all()
        .build()?
        .block_on(async_main_tokio(config, started_at))
}

/// What to tell the operator when the client port cannot be listened on.
fn cant_listen(addr: &SocketAddr, e: &std::io::Error) -> String {
    let hint = match e.kind() {
        std::io::ErrorKind::AddrInUse => {
            "Another process — often another KiviDB or Redis — is using the port. Stop it, or \
             start this server with another --port"
        }
        std::io::ErrorKind::PermissionDenied => {
            "Ports below 1024 need privileges; use a higher --port, or grant \
             CAP_NET_BIND_SERVICE"
        }
        std::io::ErrorKind::AddrNotAvailable => {
            "The bind address is not an address of this machine; check --bind"
        }
        _ => "Check --bind and --port",
    };
    format!("Can't listen on {addr}: {e}. {hint}")
}

/// Make sure nothing else is listening on `addr`, and keep other KiviDBs off
/// it for as long as the returned claim lives (the life of the process).
///
/// Two checks, because the io_uring workers bind with SO_REUSEPORT and the
/// kernel then lets any other socket with that option share the port:
///
/// * A probe socket *without* SO_REUSEPORT. The kernel refuses its bind if
///   any socket at all holds the port, whatever options that one set.
/// * A claim that outlives the probe: an abstract Unix socket named after the
///   address. It closes the gap between the probe and the workers' binds, in
///   which two servers started at once would both pass the probe. The kernel
///   releases it when the process ends, however it ends. Where it cannot be
///   made at all, the probe alone decides.
///
/// A server that has just been killed leaves its listening sockets behind for
/// a moment: io_uring holds them until the kernel has torn its ring down,
/// which happens after the process is gone. A restart straight after a crash
/// would meet them and be refused. So while the claim is ours — no living
/// KiviDB has the port — a probe that finds the port in use is tried again
/// for a few seconds before it is believed.
#[cfg(target_os = "linux")]
fn claim_port(addr: &SocketAddr) -> std::io::Result<Option<std::os::unix::net::UnixListener>> {
    use std::os::linux::net::SocketAddrExt;
    let name = format!("kividb-listen-{addr}");
    let claim = std::os::unix::net::SocketAddr::from_abstract_name(name.as_bytes())
        .and_then(|name| std::os::unix::net::UnixListener::bind_addr(&name));
    let claim = match claim {
        Ok(claim) => Some(claim),
        Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => return Err(e),
        Err(_) => None,
    };
    let patience = if claim.is_some() {
        std::time::Duration::from_secs(3)
    } else {
        std::time::Duration::ZERO
    };
    let started = Instant::now();
    loop {
        let probe = socket2::Socket::new(
            socket2::Domain::for_address(*addr),
            socket2::Type::STREAM,
            None,
        )?;
        // As the workers' sockets: a port in TIME_WAIT after a restart is free.
        probe.set_reuse_address(true)?;
        match probe.bind(&(*addr).into()) {
            Ok(()) => return Ok(claim),
            Err(e) if e.kind() == std::io::ErrorKind::AddrInUse && started.elapsed() < patience => {
                std::thread::sleep(std::time::Duration::from_millis(25));
            }
            Err(e) => return Err(e),
        }
    }
}

/// Log that clients are taken on `addr`, or with port 0 that they are not.
fn ready(addr: &SocketAddr) {
    if addr.port() == 0 {
        log_info!("No plaintext port (port 0): accepting TLS connections only");
    } else {
        log_info!("Ready to accept connections on {addr}");
    }
}

/// The client listener, or a fatal error that says what to do about it.
#[allow(dead_code)]
async fn bind_listener(addr: SocketAddr) -> std::io::Result<TcpListener> {
    TcpListener::bind(addr).await.map_err(|e| {
        let message = cant_listen(&addr, &e);
        std::io::Error::new(e.kind(), message)
    })
}

#[cfg(target_os = "linux")]
fn run_uring(config: Arc<Config>, started_at: Instant) -> Result<(), Box<dyn std::error::Error>> {
    stats::IO_URING.store(true, std::sync::atomic::Ordering::Relaxed);
    let store: store::Store = store::new_store(config.databases);
    let index_store = vector::new_index_store();
    let lastsave = Arc::new(RwLock::new(0i64));
    let aof_enabled = config.aof;
    // Initialise the runtime toggle to match the startup flag.
    crate::aof::AOF_ENABLED.store(config.aof, std::sync::atomic::Ordering::Relaxed);
    let started_at = Arc::new(started_at);
    let threads = config.resolve_threads();
    let wait_table = Arc::new(crate::wait_table::WaitTable::new());
    let dict_store = vector::new_dict_store();
    vector::register_dict_store(&index_store, &dict_store);
    let ts_index = store::new_ts_index();
    let pubsub = crate::pubsub::PubSubHub::new();
    let shutdown = Arc::new(AtomicBool::new(false));
    let repl_state = Arc::new(ReplState::from_config(&config));
    let acl_store = acl::new_acl_store(&config.requirepass);
    let acl_log = acl::new_acl_log();
    acl_log.set_max_len(config.acllog_max_len);
    let slowlog = crate::slowlog::new_slowlog_from_config(&config);
    let latency = crate::latency::new_latency_tracker();
    let monitor_registry = crate::monitor::new_monitor_registry();
    let tracking_table = crate::tracking::new_tracking_table();
    let cluster_state = std::sync::Arc::new(load_cluster_state(&config));

    // HNSW compaction worker — drains background rebuild requests.
    // Single OS thread; no tokio runtime needed.
    let (compaction_tx, compaction_rx) = vector::new_compaction_channel();
    {
        let index_store_for_compaction = Arc::clone(&index_store);
        let store_for_compaction = Arc::clone(&store);
        vector::spawn_compaction_worker(
            index_store_for_compaction,
            store_for_compaction,
            compaction_rx,
        );
    }

    if !config.aclfile.is_empty() {
        match acl::load_acl_file(&config.aclfile, &acl_store, &config.requirepass) {
            Ok(_) => log_info!("ACL file loaded: {}", config.aclfile),
            Err(e) => {
                log_fatal!(
                    "Can't load the ACL file '{}': {e}. Fix the line named, or start \
                     without aclfile",
                    config.aclfile
                );
                std::process::exit(1);
            }
        }
    }
    // start_hub needs a tokio runtime — give it its own single-thread runtime
    // just like the AOF writer, so it never competes with the io_uring workers.
    let hub_tx = {
        let repl_state_hub = Arc::clone(&repl_state);
        let (tx, rx) = std::sync::mpsc::sync_channel::<crate::replication::HubTx>(1);
        std::thread::spawn(move || {
            tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .unwrap()
                .block_on(async move {
                    let hub_tx = start_hub(repl_state_hub);
                    tx.send(hub_tx).unwrap();
                    // Keep this runtime alive forever — the hub task lives here
                    std::future::pending::<()>().await;
                });
        });
        rx.recv().unwrap()
    };
    crate::stats::spawn_instantaneous_ops_sampler();
    // No key is swept until what it deletes can be logged: the dataset is
    // loaded and the AOF's sender installed, further down. A `DEL` sent
    // before that went nowhere, and the key came back at the next restart.
    let starting = crate::expiry::Loading::start();
    crate::commands::helpers::spawn_active_expire_task(
        Arc::clone(&store),
        Arc::clone(&index_store),
        pubsub.clone(),
        Arc::clone(&latency),
        &repl_state,
        &hub_tx,
    );
    crate::compaction::spawn(Arc::clone(&store));
    if config.cluster_enabled {
        log_info!(
            "Cluster: Node ID        : {}",
            crate::cluster::node_id_str(&cluster_state.myself())
        );
        log_info!("Cluster: Bus port       : {}", config.cluster_bus_port());
    }
    let watch_registry = crate::watch::new_watch_registry();
    crate::watch::register_for(&store, &watch_registry);
    let client_registry = crate::client_registry::new_client_registry();
    crate::tracking::register_for(&store, &tracking_table, &client_registry, &acl_store);

    log_info!("Shards per DB  : {}", store::num_shards());
    log_info!("I/O model      : io_uring");

    // Local recovery runs on replicas too. A full resync loads into a staging
    // store and swaps it in, so there is nothing to merge with; and a replica
    // that starts empty has no way to notice that the "master" it was pointed
    // at is a blank node about to overwrite the only copy of the data — which
    // is exactly what the full-sync guard needs to see.
    {
        let loaded = crate::aof::recover_local(
            config.aof,
            &store,
            &index_store,
            &dict_store,
            &wait_table,
            &ts_index,
            &config,
            &compaction_tx,
            &repl_state,
        );
        // The expiry task started watching before anything was loaded: the
        // hashes with field TTLs are the ones just loaded.
        crate::field_expiry::rescan(&store);
        // A cluster master killed with no AOF has only what it last saved,
        // if anything: it serves none of its slots until its replica, which
        // may hold the data, has taken over or said it holds nothing.
        if config.cluster_enabled {
            crate::replication::CLEAN_EXIT_MARKER.store(true, std::sync::atomic::Ordering::Relaxed);
            let stopped_cleanly =
                crate::replication::take_clean_exit_marker(loaded.dump_fingerprint);
            let keys: usize = store
                .iter()
                .flat_map(|db| db.iter())
                .map(|shard| crate::read_lock!(shard).len())
                .sum();
            cluster_state.check_dataset_at_start(
                config.aof || stopped_cleanly || !config.preload_file.is_empty(),
                keys,
            );
        }
        // A node that was a replica when it was last saved, and has loaded
        // exactly that save, can ask its master to continue from there.
        if loaded.exact_dump
            && let Some(point) = loaded
                .dump_fingerprint
                .and_then(crate::replication::load_saved_resync_point)
        {
            log_info!(
                "Replication: Loaded dataset is offset {} of {} — a partial resync will be asked for",
                point.offset,
                point.repl_id
            );
            repl_state
                .repl_offset
                .store(point.offset, std::sync::atomic::Ordering::Relaxed);
            repl_state.set_resync_point(Some(point));
        } else if loaded.exact_dump
            && config.replicaof_addr().is_none()
            && cluster_state.my_master_id().is_none()
            && let Some((repl_id, offset)) = loaded
                .dump_fingerprint
                .and_then(crate::replication::load_saved_master_point)
        {
            // And a master stopped cleanly carries on its stream, so that
            // its replicas need not be sent everything again.
            log_info!(
                "Replication: Loaded dataset is offset {offset} of this node's stream {repl_id} \
                 — replicas stopped cleanly with it can be continued"
            );
            repl_state.resume_as_master(repl_id, offset, &hub_tx);
        } else if config.replicaof_addr().is_none()
            && cluster_state.my_master_id().is_none()
            && store
                .iter()
                .any(|db| db.iter().any(|shard| !crate::read_lock!(shard).is_empty()))
        {
            repl_state.fingerprint_at_start(&store, &hub_tx);
        }
        if !loaded.index_names.is_empty() {
            vector::SNAPSHOT_INDEX_REBUILD.store(true, std::sync::atomic::Ordering::Release);
            if loaded.hnsw_loaded {
                log_info!(
                    "HNSW graph(s) loaded from snapshot — running text/numeric index pass in background"
                );
            } else {
                log_info!(
                    "Rebuilding {} search index(es) in the background (most commands return LOADING until rebuild finishes)",
                    loaded.index_names.len()
                );
            }
            spawn_snapshot_index_backfill_thread(
                Arc::clone(&store),
                Arc::clone(&index_store),
                loaded.index_names,
            );
        }
    }

    // Spawn a dedicated thread to watch for SIGTERM / SIGINT.
    // On signal: save snapshot and exit immediately.
    // We don't try to gracefully drain worker threads — io_uring accept()
    // cannot be interrupted without kernel-level mechanisms, and adding
    // timeouts to accept hurts throughput. Instead we just save and exit.
    // NEW — handles both OS signals AND command-issued SHUTDOWN
    let shutdown_signal = Arc::clone(&shutdown);
    let signal_snapshot_store = Arc::clone(&store);
    let signal_snapshot_index_store = Arc::clone(&index_store);
    let signal_repl_state = Arc::clone(&repl_state);
    let signal_hub_tx = hub_tx.clone();
    std::thread::spawn(move || {
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap()
            .block_on(async {
                // Wait for OS signal OR SHUTDOWN command (polled every 100ms).
                // The poll arm is the only addition — OS signal behaviour is
                // identical to before.
                #[cfg(unix)]
                {
                    use tokio::signal::unix::{SignalKind, signal};
                    let mut sigterm = signal(SignalKind::terminate()).unwrap();
                    loop {
                        tokio::select! {
                            _ = tokio::signal::ctrl_c() => {
                                log_info!("SIGINT received — shutting down gracefully");
                                break;
                            }
                            _ = sigterm.recv() => {
                                log_info!("SIGTERM received — shutting down gracefully");
                                break;
                            }
                            _ = tokio::time::sleep(tokio::time::Duration::from_millis(100)) => {
                                // SHUTDOWN_PENDING is set by the command handler.
                                // One atomic load per 100ms — negligible cost.
                                if crate::shutdown::SHUTDOWN_PENDING.load(Ordering::Relaxed) {
                                    log_info!("SHUTDOWN command received — shutting down");
                                    break;
                                }
                            }
                        }
                    }
                }
                #[cfg(not(unix))]
                {
                    loop {
                        tokio::select! {
                            _ = tokio::signal::ctrl_c() => {
                                log_info!("Ctrl+C received — shutting down gracefully");
                                break;
                            }
                            _ = tokio::time::sleep(tokio::time::Duration::from_millis(100)) => {
                                if crate::shutdown::SHUTDOWN_PENDING.load(Ordering::Relaxed) {
                                    log_info!("SHUTDOWN command received — shutting down");
                                    break;
                                }
                            }
                        }
                    }
                }

                // Signal the io_uring accept workers to stop their loop.
                shutdown_signal.store(true, Ordering::SeqCst);
                // And stop their ports, after the flag: the accept each
                // worker is waiting in ends, and the worker sees the flag.
                // Left listening, a port went on taking connections after
                // the process had exited (see `listen::stop_uring_ports`).
                crate::listen::stop_uring_ports();

                // Read the mode the SHUTDOWN command (or OS signal) requested.
                // OS signals leave SHUTDOWN_MODE at its default (SAVE), which is correct.
                let m = crate::shutdown::SHUTDOWN_MODE.load(Ordering::Relaxed);

                if m != crate::shutdown::mode::NOSAVE {
                    // Before the gate below: the clients are paused, the
                    // write stream ends here, and the replicas are given the
                    // time to receive all of it, so that the restart can
                    // continue them from the offset saved below (#306). The
                    // worker threads go on serving the replicas meanwhile.
                    // `SHUTDOWN NOW` does not wait.
                    let started = std::time::Instant::now();
                    let deadline = if m != crate::shutdown::mode::NOW {
                        crate::replication::drain_replicas_for_shutdown(
                            &signal_repl_state,
                            &signal_hub_tx,
                        )
                    } else {
                        started
                    };
                    // No command runs from here to the exit: the snapshot is
                    // cut at one moment (#148), and a write a connection
                    // already open made after that moment was acknowledged
                    // and then lost with the process. Taken alone, the gate
                    // waits for the commands running now and lets no other
                    // start; it is never let go. Forgotten, not kept in a
                    // binding: one dropped at the end of this block opened
                    // the gate again before `process::exit` below, and the
                    // writes that ran in between were acknowledged and lost.
                    // What the final save takes is taken before the gate:
                    // a replica's applier holds it while it waits at the
                    // gate (#308).
                    let hold = match crate::replication::hold_for_final_save(&signal_repl_state) {
                        Ok(hold) => hold,
                        Err(e) => {
                            log_error!("Final snapshot failed: {e}");
                            std::process::exit(1);
                        }
                    };
                    crate::replication::end_stream_for_shutdown(&signal_repl_state);
                    if m != crate::shutdown::mode::NOW {
                        crate::replication::report_replicas_at_shutdown(
                            &signal_repl_state,
                            &signal_hub_tx,
                            started,
                            deadline,
                        );
                    }
                    // Not over the last good dump with a dataset a full
                    // sync is still replacing.
                    let Some(_settled) =
                        crate::replication::dataset_for_final_save(&signal_repl_state)
                    else {
                        log_warn!("{}", crate::replication::FINAL_SAVE_SKIPPED);
                        std::process::exit(0);
                    };
                    log_info!("Writing final snapshot...");
                    // With the replica's position in its master's stream
                    // beside it, so that the restart can ask to continue.
                    let result = crate::replication::save_dataset_held(
                        &hold,
                        &signal_snapshot_store,
                        &signal_snapshot_index_store,
                        &signal_repl_state,
                    );
                    if result.is_ok() {
                        crate::replication::note_clean_exit();
                    }
                    if let Err(e) = result {
                        // Not a clean exit: whatever restarts this node
                        // should know its last writes are not on disk.
                        log_error!(
                            "Final snapshot failed: {e}. Writes since the last successful save \
                             are not in dump.kdb (they are in the AOF, if appendonly is on). \
                             Check free disk space and write permission on the data directory"
                        );
                        std::process::exit(1);
                    }
                    log_info!("Goodbye.");
                    std::mem::forget(hold);
                } else {
                    log_info!("SHUTDOWN NOSAVE — skipping snapshot. Goodbye.");
                }

                std::process::exit(0);
            });
    });

    // The AOF writer has a thread and a runtime of its own (it is just file
    // I/O), and the io_uring workers queue records for it directly: sending
    // on a tokio channel needs no runtime on the sending side.
    //
    // There used to be a std channel in between, and a thread that did
    // nothing but move records from the one to the other. A record that
    // arrived alone — which is how a script's arrives — woke that thread,
    // which woke the writer; and a std receiver spins and yields before it
    // sleeps, which on a one-CPU machine is the worker's own time. Under
    // BullMQ on one CPU it was about a sixth of every script call, and more
    // than half of the server's system time.
    let (aof_tx, tokio_rx) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();
    // Reachable from the replication applier, which is built too deep to be
    // handed this channel directly. See `aof::install_global_aof_sender`.
    aof::install_global_aof_sender(Box::new(aof_tx.clone()));
    // The keys active expiry deletes are logged from here on.
    drop(starting);
    let aof_writer = aof::start_aof_writer(tokio_rx);
    std::thread::spawn(move || {
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap()
            .block_on(aof_writer)
    });

    // Whether or not the AOF is on now: `CONFIG SET appendonly yes` turns
    // it on later, and its log is to be rewritten as one turned on at
    // startup is (#146). With the AOF off, the thread only waits.
    aof::spawn_auto_rewrite_thread(
        Arc::clone(&store),
        Arc::clone(&index_store),
        config.aof_rewrite_percentage,
        config.aof_rewrite_min_size,
    );

    // Replica client — runs on its own thread and runtime (see
    // `ReplicaStarter::start`), so it never competes with the io_uring workers.
    let replica_starter = crate::replication::replica_client::ReplicaStarter {
        store: Arc::clone(&store),
        index_store: Arc::clone(&index_store),
        dict_store: Arc::clone(&dict_store),
        wait_table: Arc::clone(&wait_table),
        ts_index: Arc::clone(&ts_index),
        config: Arc::clone(&config),
        compaction_tx: compaction_tx.clone(),
        repl_state: Arc::clone(&repl_state),
        hub_tx: hub_tx.clone(),
        pubsub: pubsub.clone(),
        client_registry: Arc::clone(&client_registry),
        tracking_table: Arc::clone(&tracking_table),
        monitor_registry: Arc::clone(&monitor_registry),
    };
    // The cluster bus starts here, once everything it may need to act on —
    // the stores, the replication state, the pub/sub hub — exists.
    cluster_state.start(
        &config,
        cluster::ClusterHooks {
            replica_starter: replica_starter.clone(),
            pubsub: pubsub.clone(),
        },
    );
    start_configured_replication(&config, &cluster_state, &replica_starter);

    let addr: SocketAddr = config.addr().parse::<SocketAddr>()?;

    // The workers share the port with SO_REUSEPORT, and so could a second
    // KiviDB started on it by mistake: it would come up "ready", and the
    // kernel would hand each of the two a share of the clients. Claim the
    // port first, and refuse to start if it is taken — as Redis would.
    // Port 0: no plaintext port, until `CONFIG SET port` opens one.
    let _port_claim = if addr.port() == 0 {
        None
    } else {
        match claim_port(&addr) {
            Ok(claim) => claim,
            Err(e) => {
                log_fatal!("{}", cant_listen(&addr, &e));
                std::process::exit(1);
            }
        }
    };

    // Spawn one OS thread per worker. Each thread runs its own
    // tokio_uring runtime — single-threaded, no cross-thread task stealing.
    // The kernel hands each new connection to one of the listeners by a hash
    // of its addresses (SO_REUSEPORT), which is even only over very many:
    // 150 connections on 32 workers left some workers with three times what
    // others had, and those were the limit while the others idled. So a
    // worker that accepts a connection it has too many for passes it to the
    // worker with the fewest: `loads` is how many each has, and `inboxes`
    // is where each is passed them.
    let loads: Arc<Vec<std::sync::atomic::AtomicUsize>> = Arc::new(
        (0..threads)
            .map(|_| std::sync::atomic::AtomicUsize::new(0))
            .collect(),
    );
    type Passed = (std::net::TcpStream, String, crate::client_registry::Slot);
    let (inboxes, mut inbox_ends): (Vec<_>, Vec<_>) = (0..threads)
        .map(|_| {
            let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Passed>();
            (tx, Some(rx))
        })
        .unzip();
    let inboxes = Arc::new(inboxes);
    let handles: Vec<_> = (0..threads)
        .map(|worker| {
            let loads = Arc::clone(&loads);
            let inboxes = Arc::clone(&inboxes);
            let mut inbox = inbox_ends[worker].take().expect("one inbox a worker");
            let shutdown = Arc::clone(&shutdown);
            let store = Arc::clone(&store);
            let lastsave = Arc::clone(&lastsave);
            let aof_tx = aof_tx.clone();
            let config = Arc::clone(&config);
            let started_at = Arc::clone(&started_at);
            let index_store = Arc::clone(&index_store);
            let wait_table = Arc::clone(&wait_table);
            let dict_store = Arc::clone(&dict_store);
            let ts_index = Arc::clone(&ts_index);
            let pubsub = pubsub.clone();
            let hub_tx = hub_tx.clone();
            let repl_state = Arc::clone(&repl_state);
            let watch_registry = Arc::clone(&watch_registry);
            let client_registry = Arc::clone(&client_registry);
            let acl_store = Arc::clone(&acl_store);
            let acl_log = Arc::clone(&acl_log);
            let slowlog = Arc::clone(&slowlog);
            let latency = Arc::clone(&latency);
            let compaction_tx = compaction_tx.clone();
            let cluster_state = Arc::clone(&cluster_state);
            let monitor_registry = Arc::clone(&monitor_registry);
            let tracking_table = Arc::clone(&tracking_table);
            std::thread::spawn(move || {
                let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    tokio_uring::start(async move {
                        // Port 0: none, until `CONFIG SET port` opens one.
                        let listener = (addr.port() != 0).then(|| {
                            let socket =
                                socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None)
                                    .unwrap();
                            socket.set_reuse_address(true).unwrap();
                            socket.set_reuse_port(true).unwrap();
                            socket.set_nonblocking(true).unwrap();
                            if let Err(e) = socket.bind(&addr.into()).and_then(|()| socket.listen(1024)) {
                                log_fatal!("{}", cant_listen(&addr, &e));
                                std::process::exit(1);
                            }
                            tokio_uring::net::TcpListener::from_std(socket.into())
                        });
                        // `CONFIG SET port` moves it.
                        let mut listener = crate::listen::UringListener::new(
                            listener,
                            crate::listen::server_of(&config),
                            addr,
                        );
                        static READY: std::sync::Once = std::sync::Once::new();
                        READY.call_once(|| ready(&addr));

                        /// One connection in a worker's count, until it is dropped.
                        struct Counted(Arc<Vec<std::sync::atomic::AtomicUsize>>, usize);
                        impl Drop for Counted {
                            fn drop(&mut self) {
                                self.0[self.1].fetch_sub(1, Ordering::Relaxed);
                            }
                        }
                        let loads_of_clients = Arc::clone(&loads);
                        let admitting = Arc::clone(&client_registry);
                        // Starts a client on this worker. Its place in the
                        // worker's count was taken by whoever chose the worker.
                        let start_client = std::rc::Rc::new(
                            move |stream: tokio_uring::net::TcpStream,
                                  peer_addr_str: String,
                                  slot: crate::client_registry::Slot| {
                            let store = Arc::clone(&store);
                            let lastsave = Arc::clone(&lastsave);
                            let aof_tx = aof_tx.clone();
                            let config = Arc::clone(&config);
                            let started_at = Arc::clone(&started_at);
                            let index_store = Arc::clone(&index_store);
                            let wait_table = Arc::clone(&wait_table);
                            let dict_store = Arc::clone(&dict_store);
                            let ts_index = Arc::clone(&ts_index);
                            let pubsub = pubsub.clone();
                            let hub_tx = hub_tx.clone();
                            let repl_state = Arc::clone(&repl_state);
                            let watch_registry = Arc::clone(&watch_registry);
                            let client_registry = Arc::clone(&client_registry);
                            let acl_store = Arc::clone(&acl_store);
                            let acl_log = Arc::clone(&acl_log);
                            let slowlog = Arc::clone(&slowlog);
                            let latency = Arc::clone(&latency);
                            let compaction_tx = compaction_tx.clone();
                            let cluster_state = Arc::clone(&cluster_state);
                            let monitor_registry = Arc::clone(&monitor_registry);
                            let tracking_table = Arc::clone(&tracking_table);

                            let counted = Counted(Arc::clone(&loads_of_clients), worker);
                            tokio_uring::spawn(async move {
                                let _counted = counted;
                                let _slot = slot;
                                if let Err(e) = server_uring::handle_client(
                                    stream,
                                    store,
                                    lastsave,
                                    aof_tx,
                                    aof_enabled,
                                    config,
                                    started_at,
                                    index_store,
                                    dict_store,
                                    wait_table,
                                    ts_index,
                                    pubsub,
                                    hub_tx,
                                    repl_state,
                                    watch_registry,
                                    client_registry,
                                    peer_addr_str,
                                    acl_store,
                                    acl_log,
                                    slowlog,
                                    latency,
                                    compaction_tx,
                                    cluster_state,
                                    monitor_registry,
                                    tracking_table
                                )
                                .await
                                {
                                    let s = e.to_string();
                                    if !s.contains("unexpected end of file")
                                        && !s.contains("Connection reset")
                                    {
                                        log_verbose!("Connection error: {e}");
                                    }
                                }
                            });
                            },
                        );
                        {
                            // What other workers pass to this one.
                            let start_client = std::rc::Rc::clone(&start_client);
                            tokio_uring::spawn(async move {
                                while let Some((stream, peer_addr_str, slot)) = inbox.recv().await {
                                    start_client(
                                        tokio_uring::net::TcpStream::from_std(stream),
                                        peer_addr_str,
                                        slot,
                                    );
                                }
                            });
                        }

                        loop {
                            // Shutting down: accept nothing more, and keep
                            // serving the connections this worker has until
                            // the process ends. Returning ended this worker's
                            // runtime and every connection on it, a replica's
                            // among them, before the shutdown had sent that
                            // replica the end of the stream (#306).
                            if shutdown.load(Ordering::Relaxed) {
                                std::future::pending::<()>().await;
                                return;
                            }

                            let (stream, peer_addr) = match listener.accept().await {
                                Ok(v) => v,
                                // Its port was stopped for the shutdown.
                                // The connections open here are served, as
                                // the final snapshot lets them, until the
                                // process ends.
                                Err(_) if shutdown.load(Ordering::Relaxed) => {
                                    std::future::pending::<()>().await;
                                    return;
                                }
                                Err(e) => {
                                    log_throttled!(10, crate::loglevel::WARN, "Accept error: {e} — if this is \"Too many open files\", raise the open-file limit (ulimit -n, or LimitNOFILE= under systemd)");
                                    continue;
                                }
                            };
                            let Some(mut slot) = crate::client_registry::admit(&admitting) else {
                                tokio_uring::spawn(async move {
                                    let _ = stream
                                        .write_all(crate::client_registry::TOO_MANY_CLIENTS.to_vec())
                                        .await;
                                });
                                continue;
                            };
                            crate::stats::TOTAL_CONNECTIONS_RECEIVED
                                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);

                            if shutdown.load(Ordering::Relaxed) {
                                std::future::pending::<()>().await;
                                return;
                            }

                            let mut peer_addr_str = peer_addr.to_string();
                            let mine = loads[worker].fetch_add(1, Ordering::Relaxed) + 1;
                            let (least, fewest) = loads
                                .iter()
                                .map(|load| load.load(Ordering::Relaxed))
                                .enumerate()
                                .min_by_key(|(_, load)| *load)
                                .unwrap_or((worker, mine));
                            if least != worker && fewest + 1 < mine {
                                use std::os::fd::{AsRawFd, FromRawFd};
                                // The other worker is given a second handle
                                // on the socket, and this one's is closed.
                                // SAFETY: the stream's descriptor is open, and
                                // the copy is owned by nothing else.
                                let copy = unsafe { libc::dup(stream.as_raw_fd()) };
                                if copy >= 0 {
                                    let passed = unsafe { std::net::TcpStream::from_raw_fd(copy) };
                                    loads[worker].fetch_sub(1, Ordering::Relaxed);
                                    loads[least].fetch_add(1, Ordering::Relaxed);
                                    match inboxes[least].send((passed, peer_addr_str, slot)) {
                                        Ok(()) => continue,
                                        Err(tokio::sync::mpsc::error::SendError((_, peer, back))) => {
                                            // That worker has gone: it stays here.
                                            loads[least].fetch_sub(1, Ordering::Relaxed);
                                            loads[worker].fetch_add(1, Ordering::Relaxed);
                                            peer_addr_str = peer;
                                            slot = back;
                                        }
                                    }
                                }
                            }
                            start_client(stream, peer_addr_str, slot);
                        }
                    });
                }));
                if result.is_err() {
                    log_warn!(
                        "An io_uring worker failed to start: the kernel or a seccomp profile \
                         (Docker's default one, for example) may not allow io_uring. Start with \
                         --io-model tokio, or allow io_uring"
                    );
                }
            })
        })
        .collect();

    // TLS uses Tokio's `TlsStream` + `server::handle_client` — same as the pure Tokio binary path.
    // io_uring stays on the cleartext port; TLS is accepted on `tls_port` in parallel.
    // Also with no TLS port: `CONFIG SET tls-port` opens one.
    #[cfg(feature = "tls")]
    {
        use crate::tls::acceptor;

        // Checked here, so that a certificate that cannot be loaded stops
        // the server as it starts.
        if config.tls_enabled()
            && let Err(e) = acceptor::build(&acceptor::Files::of(&config))
        {
            log_fatal!("TLS: {e}");
            std::process::exit(1);
        }

        let tls_config = Arc::clone(&config);
        let tls_store = Arc::clone(&store);
        let tls_lastsave = Arc::clone(&lastsave);
        // The writer's own queue, as plaintext connections have. A reply to a
        // write waits until a barrier sent on this queue is in the file, and
        // the connection writes the queue itself to get there (`aof::written`).
        // TLS connections used to have a queue of their own, copied onto this
        // one by a task: the barrier was still on that queue when the
        // connection wrote, and nothing else wrote it until the next
        // once-a-second sync, so each write over TLS waited up to a second.
        let tls_aof_tx = aof_tx.clone();
        let tls_started_at = Arc::clone(&started_at);
        let tls_index_store = Arc::clone(&index_store);
        let tls_wait_table = Arc::clone(&wait_table);
        let tls_dict_store = dict_store.clone();
        let tls_ts_index = ts_index.clone();
        let tls_pubsub = pubsub.clone();
        let tls_hub_tx = hub_tx.clone();
        let tls_repl_state = Arc::clone(&repl_state);
        let tls_watch_registry = Arc::clone(&watch_registry);
        let tls_client_registry = Arc::clone(&client_registry);
        let tls_acl_store = Arc::clone(&acl_store);
        let tls_acl_log = Arc::clone(&acl_log);
        let tls_slowlog = Arc::clone(&slowlog);
        let tls_latency = Arc::clone(&latency);
        let tls_compaction_tx = compaction_tx.clone();
        let tls_cluster_state = Arc::clone(&cluster_state);
        let tls_monitor_registry = Arc::clone(&monitor_registry);
        let tls_tracking_table = Arc::clone(&tracking_table);
        let tls_aof_enabled = aof_enabled;

        let server = crate::listen::server_of(&config);
        std::thread::spawn(move || {
            tokio::runtime::Builder::new_multi_thread()
                .worker_threads(2)
                .enable_all()
                .build()
                .unwrap()
                .block_on(async move {
                    let mut tls_listener = match acceptor::listener(&tls_config) {
                        Ok(l) => l,
                        Err(e) => {
                            log_warn!("TLS: bind failed on io_uring binary path: {e}");
                            return;
                        }
                    };

                    loop {
                        let (tcp_stream, peer_addr) = match tls_listener.accept().await {
                            Ok(pair) => pair,
                            Err(e) => {
                                log_warn!("TLS: accept error: {e}");
                                // Out of file descriptors, it would otherwise spin.
                                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                                continue;
                            }
                        };

                        // Installed before the port is opened.
                        let Some(acceptor) = acceptor::current(server) else {
                            continue;
                        };
                        let Some(slot) = crate::client_registry::admit(&tls_client_registry) else {
                            continue;
                        };
                        let store = Arc::clone(&tls_store);
                        let lastsave = Arc::clone(&tls_lastsave);
                        let aof_tx = tls_aof_tx.clone();
                        let config = Arc::clone(&tls_config);
                        let started_at = Arc::clone(&tls_started_at);
                        let index_store = Arc::clone(&tls_index_store);
                        let wait_table = Arc::clone(&tls_wait_table);
                        let dict_store = tls_dict_store.clone();
                        let ts_index = tls_ts_index.clone();
                        let pubsub = tls_pubsub.clone();
                        let hub_tx = tls_hub_tx.clone();
                        let repl_state = Arc::clone(&tls_repl_state);
                        let watch_registry = Arc::clone(&tls_watch_registry);
                        let client_registry = Arc::clone(&tls_client_registry);
                        let acl_store = Arc::clone(&tls_acl_store);
                        let acl_log = Arc::clone(&tls_acl_log);
                        let slowlog = Arc::clone(&tls_slowlog);
                        let latency = Arc::clone(&tls_latency);
                        let compaction_tx = tls_compaction_tx.clone();
                        let cluster_state = Arc::clone(&tls_cluster_state);
                        let monitor_registry = Arc::clone(&tls_monitor_registry);
                        let tracking_table = Arc::clone(&tls_tracking_table);

                        tokio::spawn(async move {
                            let Some((tls_stream, _slot)) =
                                acceptor::handshake(&acceptor, tcp_stream, peer_addr, slot).await
                            else {
                                return;
                            };
                            crate::stats::TOTAL_CONNECTIONS_RECEIVED
                                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                            let peer_addr_str = peer_addr.to_string();

                            if let Err(e) = server::handle_client(
                                tls_stream,
                                store,
                                lastsave,
                                aof_tx,
                                tls_aof_enabled,
                                config,
                                started_at,
                                index_store,
                                dict_store,
                                wait_table,
                                ts_index,
                                pubsub,
                                hub_tx,
                                repl_state,
                                watch_registry,
                                client_registry,
                                peer_addr_str,
                                acl_store,
                                acl_log,
                                slowlog,
                                latency,
                                compaction_tx,
                                cluster_state,
                                monitor_registry,
                                tracking_table,
                            )
                            .await
                            {
                                let s = e.to_string();
                                if !s.contains("unexpected end of file")
                                    && !s.contains("Connection reset")
                                {
                                    log_verbose!("Connection error: {e}");
                                }
                            }
                        });
                    }
                });
        });
    }

    for h in handles {
        let _ = h.join();
    }
    drop(aof_tx);
    // The accept workers have stopped because the server is shutting down.
    // The final snapshot is written by the signal thread, which then ends the
    // process — and this thread must wait for it. It used to return here
    // instead: with connections arriving, every worker saw the shutdown flag
    // within moments, `main` returned, and the process exited with status 0
    // while the snapshot was still being written — or before it had begun.
    // An idle server did not show it, because a worker with nothing to
    // accept never looks at the flag.
    if shutdown.load(Ordering::SeqCst) {
        loop {
            std::thread::park();
        }
    }
    Ok(())
}

async fn async_main_tokio(
    config: Arc<Config>,
    started_at: Instant,
) -> Result<(), Box<dyn std::error::Error>> {
    log_info!("Shards per DB  : {}", store::num_shards());
    log_info!("Bind address   : {}", config.addr());

    let store: store::Store = store::new_store(config.databases);
    let lastsave = Arc::new(RwLock::new(0i64));
    let aof_enabled = config.aof;
    // Initialise the runtime toggle to match the startup flag.
    crate::aof::AOF_ENABLED.store(config.aof, std::sync::atomic::Ordering::Relaxed);
    let started_at = Arc::new(started_at);
    let index_store = vector::new_index_store();
    let wait_table = Arc::new(crate::wait_table::WaitTable::new());
    let dict_store = vector::new_dict_store();
    vector::register_dict_store(&index_store, &dict_store);
    let ts_index = store::new_ts_index();
    let pubsub = crate::pubsub::PubSubHub::new();
    // Unbounded: a bounded AOF queue drops durability records under load.
    let (aof_tx, aof_rx) = mpsc::unbounded_channel();
    // Reachable from the replication applier, which is built too deep to be
    // handed this channel directly. See `aof::install_global_aof_sender`.
    aof::install_global_aof_sender(Box::new(aof_tx.clone()));
    let repl_state = Arc::new(ReplState::from_config(&config));
    let hub_tx = start_hub(Arc::clone(&repl_state));
    crate::stats::spawn_instantaneous_ops_sampler();
    let latency = crate::latency::new_latency_tracker();
    crate::commands::helpers::spawn_active_expire_task(
        Arc::clone(&store),
        Arc::clone(&index_store),
        pubsub.clone(),
        Arc::clone(&latency),
        &repl_state,
        &hub_tx,
    );
    crate::compaction::spawn(Arc::clone(&store));
    let watch_registry = crate::watch::new_watch_registry();
    crate::watch::register_for(&store, &watch_registry);
    let client_registry = crate::client_registry::new_client_registry();
    let acl_store = acl::new_acl_store(&config.requirepass);
    let acl_log = acl::new_acl_log();
    acl_log.set_max_len(config.acllog_max_len);
    let slowlog = crate::slowlog::new_slowlog_from_config(&config);
    let monitor_registry = crate::monitor::new_monitor_registry();
    let tracking_table = crate::tracking::new_tracking_table();
    crate::tracking::register_for(&store, &tracking_table, &client_registry, &acl_store);
    let cluster_state = std::sync::Arc::new(load_cluster_state(&config));

    // HNSW compaction worker — must live before replication (replica applier sends here).
    let (compaction_tx, compaction_rx) = vector::new_compaction_channel();
    {
        let index_store_for_compaction = Arc::clone(&index_store);
        let store_for_compaction = Arc::clone(&store);
        vector::spawn_compaction_worker(
            index_store_for_compaction,
            store_for_compaction,
            compaction_rx,
        );
    }

    if config.cluster_enabled {
        log_info!(
            "Cluster: Node ID        : {}",
            crate::cluster::node_id_str(&cluster_state.myself())
        );
        log_info!("Cluster: Bus port       : {}", config.cluster_bus_port());
    }

    if !config.aclfile.is_empty() {
        match acl::load_acl_file(&config.aclfile, &acl_store, &config.requirepass) {
            Ok(_) => log_info!("ACL file loaded: {}", config.aclfile),
            Err(e) => {
                log_fatal!(
                    "Can't load the ACL file '{}': {e}. Fix the line named, or start \
                     without aclfile",
                    config.aclfile
                );
                std::process::exit(1);
            }
        }
    }

    let addr: SocketAddr = config.addr().parse()?;
    let mut listener_early: Option<TcpListener> = None;

    // Try native KDB format first, fall back to Redis RDB. Replicas load
    // too — see the note at the same point in `run_uring`.
    {
        let loaded = crate::aof::recover_local(
            config.aof,
            &store,
            &index_store,
            &dict_store,
            &wait_table,
            &ts_index,
            &config,
            &compaction_tx,
            &repl_state,
        );
        // The expiry task started watching before anything was loaded: the
        // hashes with field TTLs are the ones just loaded.
        crate::field_expiry::rescan(&store);
        // A cluster master killed with no AOF has only what it last saved,
        // if anything: it serves none of its slots until its replica, which
        // may hold the data, has taken over or said it holds nothing.
        if config.cluster_enabled {
            crate::replication::CLEAN_EXIT_MARKER.store(true, std::sync::atomic::Ordering::Relaxed);
            let stopped_cleanly =
                crate::replication::take_clean_exit_marker(loaded.dump_fingerprint);
            let keys: usize = store
                .iter()
                .flat_map(|db| db.iter())
                .map(|shard| crate::read_lock!(shard).len())
                .sum();
            cluster_state.check_dataset_at_start(
                config.aof || stopped_cleanly || !config.preload_file.is_empty(),
                keys,
            );
        }
        // A node that was a replica when it was last saved, and has loaded
        // exactly that save, can ask its master to continue from there.
        if loaded.exact_dump
            && let Some(point) = loaded
                .dump_fingerprint
                .and_then(crate::replication::load_saved_resync_point)
        {
            log_info!(
                "Replication: Loaded dataset is offset {} of {} — a partial resync will be asked for",
                point.offset,
                point.repl_id
            );
            repl_state
                .repl_offset
                .store(point.offset, std::sync::atomic::Ordering::Relaxed);
            repl_state.set_resync_point(Some(point));
        } else if loaded.exact_dump
            && config.replicaof_addr().is_none()
            && cluster_state.my_master_id().is_none()
            && let Some((repl_id, offset)) = loaded
                .dump_fingerprint
                .and_then(crate::replication::load_saved_master_point)
        {
            // And a master stopped cleanly carries on its stream, so that
            // its replicas need not be sent everything again.
            log_info!(
                "Replication: Loaded dataset is offset {offset} of this node's stream {repl_id} \
                 — replicas stopped cleanly with it can be continued"
            );
            repl_state.resume_as_master(repl_id, offset, &hub_tx);
        } else if config.replicaof_addr().is_none()
            && cluster_state.my_master_id().is_none()
            && store
                .iter()
                .any(|db| db.iter().any(|shard| !crate::read_lock!(shard).is_empty()))
        {
            repl_state.fingerprint_at_start(&store, &hub_tx);
        }
        if !loaded.index_names.is_empty() {
            vector::SNAPSHOT_INDEX_REBUILD.store(true, std::sync::atomic::Ordering::Release);
            if addr.port() != 0 {
                listener_early = Some(bind_listener(addr).await?);
            }
            if loaded.hnsw_loaded {
                log_info!(
                    "Listening on {addr} — HNSW graph(s) loaded from snapshot; running text/numeric index pass in background"
                );
            } else {
                log_info!(
                    "Listening on {addr} — rebuilding {} search index(es) in the background (most commands return LOADING until rebuild finishes; see INFO logs for progress)",
                    loaded.index_names.len()
                );
            }
            spawn_snapshot_index_backfill_thread(
                Arc::clone(&store),
                Arc::clone(&index_store),
                loaded.index_names,
            );
        }
    }
    // The AOF writer gets a dedicated single-thread runtime rather than a task on
    // the shared one. `rewrite_aof` quiesces by holding every shard lock and then
    // waits for the writer to perform the swap; if the writer were a task here,
    // enough connection tasks blocking synchronously on those same locks could
    // occupy every worker thread and the writer would never be polled -- the
    // server would hang holding all locks. A dedicated runtime makes that
    // impossible. (The io_uring path already does this for its own reasons.)
    // Whether or not the AOF is on now: `CONFIG SET appendonly yes` turns
    // it on later, and its log is to be rewritten as one turned on at
    // startup is (#146). With the AOF off, the thread only waits.
    aof::spawn_auto_rewrite_thread(
        Arc::clone(&store),
        Arc::clone(&index_store),
        config.aof_rewrite_percentage,
        config.aof_rewrite_min_size,
    );
    let aof_writer = aof::start_aof_writer(aof_rx);
    std::thread::spawn(move || {
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap()
            .block_on(aof_writer)
    });

    // Replica client — runs on its own thread and runtime (see
    // `ReplicaStarter::start`).
    let replica_starter = crate::replication::replica_client::ReplicaStarter {
        store: Arc::clone(&store),
        index_store: Arc::clone(&index_store),
        dict_store: Arc::clone(&dict_store),
        wait_table: Arc::clone(&wait_table),
        ts_index: Arc::clone(&ts_index),
        config: Arc::clone(&config),
        compaction_tx: compaction_tx.clone(),
        repl_state: Arc::clone(&repl_state),
        hub_tx: hub_tx.clone(),
        pubsub: pubsub.clone(),
        client_registry: Arc::clone(&client_registry),
        tracking_table: Arc::clone(&tracking_table),
        monitor_registry: Arc::clone(&monitor_registry),
    };
    // The cluster bus starts here, once everything it may need to act on —
    // the stores, the replication state, the pub/sub hub — exists.
    cluster_state.start(
        &config,
        cluster::ClusterHooks {
            replica_starter: replica_starter.clone(),
            pubsub: pubsub.clone(),
        },
    );
    start_configured_replication(&config, &cluster_state, &replica_starter);

    // ONE listener — tokio's multi-thread runtime handles distribution
    // Port 0: none, until `CONFIG SET port` opens one.
    let listener = match listener_early {
        Some(l) => Some(l),
        None if addr.port() == 0 => None,
        None => Some(bind_listener(addr).await?),
    };
    // `CONFIG SET port` moves it.
    let mut listener = crate::listen::Listener::new(
        listener,
        addr,
        crate::listen::server_of(&config),
        crate::listen::Kind::Plain,
    );
    ready(&addr);

    // Also with no TLS port: `CONFIG SET tls-port` opens one.
    #[cfg(feature = "tls")]
    {
        use crate::tls::acceptor;

        let mut tls_listener = match acceptor::listener(&config) {
            Ok(listener) => listener,
            Err(e) => {
                log_fatal!("TLS: {e}");
                std::process::exit(1);
            }
        };

        let tls_config = Arc::clone(&config);
        let tls_store = Arc::clone(&store);
        let tls_lastsave = Arc::clone(&lastsave);
        // The writer's own queue, as plaintext connections have. A reply to a
        // write waits until a barrier sent on this queue is in the file, and
        // the connection writes the queue itself to get there (`aof::written`).
        // TLS connections used to have a queue of their own, copied onto this
        // one by a task: the barrier was still on that queue when the
        // connection wrote, and nothing else wrote it until the next
        // once-a-second sync, so each write over TLS waited up to a second.
        let tls_aof_tx = aof_tx.clone();
        let tls_started_at = Arc::clone(&started_at);
        let tls_index_store = Arc::clone(&index_store);
        let tls_wait_table = Arc::clone(&wait_table);
        let tls_dict_store = dict_store.clone();
        let tls_ts_index = ts_index.clone();
        let tls_pubsub = pubsub.clone();
        let tls_hub_tx = hub_tx.clone();
        let tls_repl_state = Arc::clone(&repl_state);
        let tls_watch_registry = Arc::clone(&watch_registry);
        let tls_client_registry = Arc::clone(&client_registry);
        let tls_acl_store = Arc::clone(&acl_store);
        let tls_acl_log = Arc::clone(&acl_log);
        let tls_slowlog = Arc::clone(&slowlog);
        let tls_latency = Arc::clone(&latency);
        let tls_compaction_tx = compaction_tx.clone();
        let tls_cluster_state = Arc::clone(&cluster_state);
        let tls_monitor_registry = Arc::clone(&monitor_registry);
        let tls_tracking_table = Arc::clone(&tracking_table);

        let server = crate::listen::server_of(&config);
        tokio::spawn(async move {
            loop {
                let (tcp_stream, peer_addr) = match tls_listener.accept().await {
                    Ok(pair) => pair,
                    Err(e) => {
                        log_warn!("TLS: accept error: {e}");
                        // Out of file descriptors, it would otherwise spin.
                        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                        continue;
                    }
                };

                // Installed before the port is opened.
                let Some(acceptor) = acceptor::current(server) else {
                    continue;
                };
                let Some(slot) = crate::client_registry::admit(&tls_client_registry) else {
                    continue;
                };
                let store = Arc::clone(&tls_store);
                let lastsave = Arc::clone(&tls_lastsave);
                let aof_tx = tls_aof_tx.clone();
                let config = Arc::clone(&tls_config);
                let started_at = Arc::clone(&tls_started_at);
                let index_store = Arc::clone(&tls_index_store);
                let wait_table = Arc::clone(&tls_wait_table);
                let dict_store = tls_dict_store.clone();
                let ts_index = tls_ts_index.clone();
                let pubsub = tls_pubsub.clone();
                let hub_tx = tls_hub_tx.clone();
                let repl_state = Arc::clone(&tls_repl_state);
                let watch_registry = Arc::clone(&tls_watch_registry);
                let client_registry = Arc::clone(&tls_client_registry);
                let acl_store = Arc::clone(&tls_acl_store);
                let acl_log = Arc::clone(&tls_acl_log);
                let slowlog = Arc::clone(&tls_slowlog);
                let latency = Arc::clone(&tls_latency);
                let compaction_tx = tls_compaction_tx.clone();
                let cluster_state = Arc::clone(&tls_cluster_state);
                let monitor_registry = Arc::clone(&tls_monitor_registry);
                let tracking_table = Arc::clone(&tls_tracking_table);

                tokio::spawn(async move {
                    let Some((tls_stream, _slot)) =
                        acceptor::handshake(&acceptor, tcp_stream, peer_addr, slot).await
                    else {
                        return;
                    };
                    crate::stats::TOTAL_CONNECTIONS_RECEIVED
                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                    let peer_addr_str = peer_addr.to_string();

                    if let Err(e) = server::handle_client(
                        tls_stream,
                        store,
                        lastsave,
                        aof_tx,
                        aof_enabled,
                        config,
                        started_at,
                        index_store,
                        dict_store,
                        wait_table,
                        ts_index,
                        pubsub,
                        hub_tx,
                        repl_state,
                        watch_registry,
                        client_registry,
                        peer_addr_str,
                        acl_store,
                        acl_log,
                        slowlog,
                        latency,
                        compaction_tx,
                        cluster_state,
                        monitor_registry,
                        tracking_table,
                    )
                    .await
                    {
                        if e.to_string().contains("unexpected end of file")
                            || e.to_string().contains("Connection reset")
                        {
                            return;
                        }
                        log_verbose!("Connection error: {e}");
                    }
                });
            }
        });
    }

    // Set up signal handlers before entering the accept loop.
    // Both SIGTERM (systemd/kill) and SIGINT (Ctrl+C) trigger shutdown.
    #[cfg(unix)]
    let mut sigterm = {
        use tokio::signal::unix::{SignalKind, signal};
        signal(SignalKind::terminate())?
    };

    let snapshot_store = Arc::clone(&store);
    let snapshot_index_store = Arc::clone(&index_store);
    let snapshot_repl_state = Arc::clone(&repl_state);
    // Interval that fires every 50ms to check for command-issued SHUTDOWN.
    // Created OUTSIDE the loop so it accumulates ticks — unlike sleep()
    // inside select!, which resets every iteration and never fires if
    // listener.accept() always completes first.
    let mut shutdown_check = tokio::time::interval(tokio::time::Duration::from_millis(50));
    shutdown_check.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
    // Consume the first tick which fires immediately.
    shutdown_check.tick().await;
    let ctrl_c = tokio::signal::ctrl_c();
    tokio::pin!(ctrl_c);
    loop {
        #[cfg(unix)]
        let shutdown = tokio::select! {
            result = listener.accept() => {
                match result {
                    Ok((socket, peer_addr)) => {
                        let Some(slot) = crate::client_registry::admit(&client_registry) else {
                            crate::client_registry::turn_away(socket);
                            continue;
                        };
                        crate::stats::TOTAL_CONNECTIONS_RECEIVED
                            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);

                        {
                        let peer_addr_str = peer_addr.to_string();
                        let store = Arc::clone(&store);
                        let lastsave = Arc::clone(&lastsave);
                        let aof_tx = aof_tx.clone();
                        let config = Arc::clone(&config);
                        let started_at = Arc::clone(&started_at);
                        let index_store = Arc::clone(&index_store);
                        let wait_table = Arc::clone(&wait_table);
                        let dict_store = Arc::clone(&dict_store);
                        let ts_index = Arc::clone(&ts_index);
                        let pubsub = pubsub.clone();
                        let hub_tx = hub_tx.clone();
                        let repl_state = Arc::clone(&repl_state);
                        let watch_registry = Arc::clone(&watch_registry);
                        let client_registry = Arc::clone(&client_registry);
                        let acl_store = Arc::clone(&acl_store);
                        let acl_log = Arc::clone(&acl_log);
                        let slowlog = Arc::clone(&slowlog);
                        let latency = Arc::clone(&latency);
                        let compaction_tx = compaction_tx.clone();
                        let cluster_state = Arc::clone(&cluster_state);
                        let monitor_registry = Arc::clone(&monitor_registry);
                        let tracking_table = Arc::clone(&tracking_table);
                        tokio::spawn(async move {
                            let _slot = slot;
                            if let Err(e) = server::handle_client(
                                socket,
                                store,
                                lastsave,
                                aof_tx,
                                aof_enabled,
                                config,
                                started_at,
                                index_store,
                                dict_store,
                                wait_table,
                                ts_index,
                                pubsub,
                                hub_tx,
                                repl_state,
                                watch_registry,
                                client_registry,
                                peer_addr_str,
                                acl_store,
                                acl_log,
                                slowlog,
                                latency,
                                compaction_tx,
                                cluster_state,
                                monitor_registry,
                                tracking_table
                            )
                            .await
                            {
                                if e.to_string().contains("unexpected end of file")
                                    || e.to_string().contains("Connection reset")
                                {
                                    return;
                                }
                                log_verbose!("Connection error: {e}");
                            }
                        });
                        false
                        }
                    }
                    Err(e) => {
                        log_throttled!(10, crate::loglevel::WARN, "Accept error: {e} — if this is \"Too many open files\", raise the open-file limit (ulimit -n, or LimitNOFILE= under systemd)");
                        false
                    }
                }
            }
            _ = &mut ctrl_c => {
                log_info!("SIGINT received — shutting down gracefully");
                true
            }
            _ = sigterm.recv() => {
                log_info!("SIGTERM received — shutting down gracefully");
                true
            }
            // NEW: poll for command-issued SHUTDOWN every 50 ms.
            // This arm fires rarely (only after SHUTDOWN is sent by a client),
            // so the 50 ms timer overhead is negligible.
            _ = shutdown_check.tick() => {
                // One atomic load every 50ms. Free when SHUTDOWN is never called.
                SHUTDOWN_PENDING.load(Relaxed)
            }
        };

        #[cfg(not(unix))]
        let shutdown = tokio::select! {
            result = listener.accept() => {
                match result {
                    Ok((socket, peer_addr)) => {
                        let Some(slot) = crate::client_registry::admit(&client_registry) else {
                            crate::client_registry::turn_away(socket);
                            continue;
                        };
                        crate::stats::TOTAL_CONNECTIONS_RECEIVED
                            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);

                        {
                        let peer_addr_str = peer_addr.to_string();
                        let store = Arc::clone(&store);
                        let lastsave = Arc::clone(&lastsave);
                        let aof_tx = aof_tx.clone();
                        let config = Arc::clone(&config);
                        let started_at = Arc::clone(&started_at);
                        let index_store = Arc::clone(&index_store);
                        let wait_table = Arc::clone(&wait_table);
                        let dict_store = Arc::clone(&dict_store);
                        let ts_index = Arc::clone(&ts_index);
                        let pubsub = pubsub.clone();
                        let hub_tx = hub_tx.clone();
                        let repl_state = Arc::clone(&repl_state);
                        let watch_registry = Arc::clone(&watch_registry);
                        let client_registry = Arc::clone(&client_registry);
                        let acl_store = Arc::clone(&acl_store);
                        let acl_log = Arc::clone(&acl_log);
                        let slowlog = Arc::clone(&slowlog);
                        let latency = Arc::clone(&latency);
                        let compaction_tx = compaction_tx.clone();
                        let cluster_state = Arc::clone(&cluster_state);
                        let monitor_registry = Arc::clone(&monitor_registry);
                        let tracking_table = Arc::clone(&tracking_table);
                        tokio::spawn(async move {
                            let _slot = slot;
                            if let Err(e) = server::handle_client(
                                socket,
                                store,
                                lastsave,
                                aof_tx,
                                aof_enabled,
                                config,
                                started_at,
                                index_store,
                                dict_store,
                                wait_table,
                                ts_index,
                                pubsub,
                                hub_tx,
                                repl_state,
                                watch_registry,
                                client_registry,
                                peer_addr_str,
                                acl_store,
                                acl_log,
                                slowlog,
                                latency,
                                compaction_tx,
                                cluster_state,
                                monitor_registry,
                                tracking_table
                            )
                            .await
                            {
                                if e.to_string().contains("unexpected end of file")
                                    || e.to_string().contains("Connection reset")
                                {
                                    return;
                                }
                                log_verbose!("Connection error: {e}");
                            }
                        });
                        false
                        }
                    }
                    Err(e) => {
                        log_throttled!(10, crate::loglevel::WARN, "Accept error: {e} — if this is \"Too many open files\", raise the open-file limit (ulimit -n, or LimitNOFILE= under systemd)");
                        false
                    }
                }
            }
            _ = &mut ctrl_c => {
                log_info!("Ctrl+C received — shutting down gracefully");
                true
            }
            _ = shutdown_check.tick() => {
                SHUTDOWN_PENDING.load(Relaxed)
            }
        };

        if shutdown {
            break;
        }
    }
    // After breaking out of the loop, read the mode to decide how to exit:
    let m = SHUTDOWN_MODE.load(Relaxed);
    drop(aof_tx);
    if m != mode::NOW {
        // Give the AOF writer a moment to flush pending entries.
        // SHUTDOWN NOW skips this wait.
        tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
    }

    if m != mode::NOSAVE {
        log_info!("Stopping — writing final snapshot...");
        let store_c = Arc::clone(&snapshot_store);
        let index_c = Arc::clone(&snapshot_index_store);
        let repl_c = Arc::clone(&snapshot_repl_state);
        let hub_c = hub_tx.clone();
        // With the replica's position in its master's stream beside it, so
        // that the restart can ask to continue.
        let result = tokio::task::spawn_blocking(move || {
            // No command runs from here to the exit, as on io_uring above:
            // the connections already open keep running, and a write one
            // made after the snapshot's cut was acknowledged and then lost.
            // The guard is this thread's, and is never let go.
            // First the clients are paused, the stream ends and the
            // replicas are given the time to receive it all, as on io_uring
            // above (#306).
            let started = std::time::Instant::now();
            let deadline = if m != mode::NOW {
                crate::replication::drain_replicas_for_shutdown(&repl_c, &hub_c)
            } else {
                started
            };
            // What the final save takes is taken before the gate, as on
            // io_uring above (#308).
            let hold = crate::replication::hold_for_final_save(&repl_c)?;
            crate::replication::end_stream_for_shutdown(&repl_c);
            if m != mode::NOW {
                crate::replication::report_replicas_at_shutdown(&repl_c, &hub_c, started, deadline);
            }
            // Not over the last good dump with a dataset a full sync is
            // still replacing.
            let Some(_settled) = crate::replication::dataset_for_final_save(&repl_c) else {
                log_warn!("{}", crate::replication::FINAL_SAVE_SKIPPED);
                std::process::exit(0);
            };
            let saved = crate::replication::save_dataset_held(&hold, &store_c, &index_c, &repl_c);
            std::mem::forget(hold);
            saved
        })
        .await;
        match result {
            Ok(Ok(())) => {
                crate::replication::note_clean_exit();
                log_info!("Goodbye.");
            }
            // Not a clean exit: whatever restarts this node should know its
            // last writes are not on disk.
            Ok(Err(e)) => {
                log_error!(
                    "Final snapshot failed: {e}. Writes since the last successful save \
                             are not in dump.kdb (they are in the AOF, if appendonly is on). \
                             Check free disk space and write permission on the data directory"
                );
                std::process::exit(1);
            }
            Err(e) => {
                log_error!("Snapshot task panicked: {e}");
                std::process::exit(1);
            }
        }
    } else {
        log_info!("SHUTDOWN NOSAVE — skipping snapshot. Goodbye.");
    }

    unsafe { libc::_exit(0) };
    #[allow(unreachable_code)]
    Ok(())
}