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
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
use crate::commands;
use crate::pubsub::PubSubHub;
use crate::resp;
use crate::store;
use crate::vector;
use crate::watch::WatchNotifier;
use commands::ctx::Ctx;
use parking_lot::RwLock;
use std::rc::Rc;
use std::sync::Arc;
use std::time::Instant;
use tokio_uring::buf::BoundedBuf;
use tokio_uring::net::TcpStream;

/// Called when a replica sends PSYNC on the io_uring path.
///
/// The outbound (hub → replica) and inbound (REPLCONF ACK) directions run as two
/// concurrent, event-driven consumers sharing one `Rc<TcpStream>` (io_uring's read/write
/// take `&self`, so this is safe within tokio_uring's single-threaded runtime). Each side
/// issues exactly one `read`/`recv` at a time and only starts the next after the previous
/// one actually completes — never on a timer. An earlier version re-issued a fresh 1ms-
/// timeout `read()` on every tick to poll for ACKs; because tokio_uring cannot truly cancel
/// an in-flight op (the buffer must be held until the kernel's completion arrives — see
/// tokio-uring's DESIGN.md), that produced ~1000 abandoned, never-completing reads per
/// second per idle replica, each pinning its buffer forever: unbounded master memory growth
/// with a replica attached, independent of write traffic.
#[allow(clippy::too_many_arguments)]
pub async fn handle_replica_connection_uring(
    stream: Rc<TcpStream>,
    store: store::Store,
    index_store: vector::IndexStore,
    hub_tx: crate::replication::HubTx,
    repl_state: Arc<crate::replication::ReplState>,
    peer_addr: String,
    legacy_sync: bool,
    // The port the replica announced with `REPLCONF listening-port`, if any.
    listening_port: Option<u16>,
    // What the replica asked to continue from (`PSYNC <replid> <offset>`).
    psync: Option<crate::replication::PsyncRequest>,
) -> Result<(), Box<dyn std::error::Error>> {
    use tokio::sync::mpsc;

    // However this ends, the socket is shut down: dropped, the forwarder's and
    // the ACK reader's operations still hold it open (and a stuck write its
    // buffer) until they complete, which for a replica that reads nothing is
    // never. Shut down, they complete at once.
    let _shutdown = ShutdownOnDrop(Rc::clone(&stream));

    // ── 1. The stream queue. Unbounded: bounded queues fill before forwarding runs.
    let (replica_tx, replica_rx) = mpsc::unbounded_channel::<crate::replication::ReplPayload>();
    let replica_id = crate::replication::next_replica_id();

    // Shared with the hub: it increments this on enqueue, the forwarder below
    // decrements it after each successful flush. Lets the hub evict us if we fall
    // far enough behind instead of queueing an unbounded backlog — see
    // `replication::mod::start_hub`.
    let pending_bytes = Arc::new(crate::replication::ReplicaQueue::default());
    // Frees what is queued however the connection ends, also before the
    // forwarder runs, and says so.
    let replica_rx = crate::replication::QueueRx::new(replica_rx, Arc::clone(&pending_bytes));

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

    // ── 3. `+CONTINUE`, or `+FULLRESYNC` (omitted for legacy `SYNC`) ──────
    let greeting = match &full_sync {
        None => Some(format!("+CONTINUE {}\r\n", repl_state.repl_id())),
        Some(sync) if !legacy_sync => Some(sync.announcement(&repl_state.repl_id())),
        Some(_) => None,
    };
    if let Some(greeting) = greeting {
        match write_unless_let_go(&stream, greeting.into_bytes(), &repl_state, replica_id).await {
            Some(Ok(())) => {}
            Some(Err(e)) => {
                let _ = hub_tx.send(crate::replication::HubMsg::Deregister(replica_id));
                return Err(e.into());
            }
            None => {
                let _ = hub_tx.send(crate::replication::HubMsg::Deregister(replica_id));
                return Ok(());
            }
        }
    }

    // ── 4. Spawn the outbound forwarder on its own Rc<TcpStream> handle. Gated on
    // `rdb_enqueued_rx` so propagated writes never interleave with the RDB bytes below.
    // Blocks on `recv()` (event-driven) — no polling, no re-issued ops.
    let (rdb_enqueued_tx, rdb_enqueued_rx) = tokio::sync::oneshot::channel::<()>();
    let stream_fwd = Rc::clone(&stream);
    let mut forward_task = tokio_uring::spawn(async move {
        if rdb_enqueued_rx.await.is_err() {
            return;
        }
        let mut replica_rx = replica_rx;
        // Fewer replica-socket writes / wakeups than one write per propagated command.
        const BATCH_MAX_BYTES: usize = 4 * 1024 * 1024;
        loop {
            let first = match replica_rx.recv().await {
                Some(p) => p,
                None => break,
            };
            if pending_bytes.abandoned() {
                // Let go of for falling too far behind: what is queued is
                // freed now, as `replica_rx` is dropped, not sent (see
                // `ReplicaQueue::abandon`).
                return;
            }
            let mut batch = Vec::with_capacity(first.len().min(BATCH_MAX_BYTES));
            batch.extend_from_slice(first.as_ref());
            // The memory the payloads took while queued (see `ReplicaQueue`).
            let mut held = crate::replication::ReplicaQueue::held_for(first.len());
            drop(first);
            loop {
                if batch.len() >= BATCH_MAX_BYTES {
                    break;
                }
                match replica_rx.try_recv() {
                    Ok(p) => {
                        batch.extend_from_slice(p.as_ref());
                        held += crate::replication::ReplicaQueue::held_for(p.len());
                    }
                    Err(tokio::sync::mpsc::error::TryRecvError::Empty) => break,
                    Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => {
                        pending_bytes.taken(batch.len(), held);
                        if !pending_bytes.abandoned() {
                            let _ = stream_fwd.write_all(batch).await;
                        }
                        return;
                    }
                }
            }
            pending_bytes.taken(batch.len(), held);
            if stream_fwd.write_all(batch).await.0.is_err() {
                break;
            }
        }
    });

    // ── 5. Send the RDB dump, if there is one, then release the forwarder ─
    if let Some(sync) = full_sync {
        if let Some(replica) = repl_state.replica(replica_id) {
            replica.set_state(crate::replication::ReplicaState::SendBulk);
        }
        let header = format!("${}\r\n", sync.payload.len()).into_bytes();
        for part in [header, sync.payload] {
            // A replica that stops reading during its full sync is let go of
            // once its queue passes its limit: the write is given up then,
            // rather than waited on for good with its queue held (#542).
            match write_unless_let_go(&stream, part, &repl_state, replica_id).await {
                Some(Ok(())) => {}
                Some(Err(e)) => {
                    let _ = hub_tx.send(crate::replication::HubMsg::Deregister(replica_id));
                    drop(rdb_enqueued_tx);
                    return Err(e.into());
                }
                None => {
                    log_warn!(
                        "Replication: uring: replica {endpoint} let go of during its full sync"
                    );
                    let _ = hub_tx.send(crate::replication::HubMsg::Deregister(replica_id));
                    drop(rdb_enqueued_tx);
                    forward_task.abort();
                    return Ok(());
                }
            }
        }
        log_info!("Replication: uring: sent full RDB; streaming queued writes from hub");
    }

    let _ = rdb_enqueued_tx.send(());

    // ── 6. Inbound ACK reader, racing the forwarder ───────────────────────
    // Exactly one `read()` in flight at a time, re-issued only after it actually
    // completes. Whichever side ends first (peer gone, write failure, hub tx dropped)
    // wins the select and tears the whole connection down; the loser's in-flight op
    // (at most one, only at teardown) is cancelled once — not thousands of times a
    // second the way the old timeout-poll loop cancelled its reads.
    let ack_reader = async {
        let mut ack_buf = Vec::with_capacity(128);
        let mut ack_parse_start = 0usize;
        let mut read_buf = vec![0u8; 4096];
        loop {
            let (res, buf) = stream.read(read_buf).await;
            read_buf = buf;
            match res {
                Ok(0) | Err(_) => break,
                Ok(n) => {
                    ack_buf.extend_from_slice(&read_buf[..n]);
                    let mut parse_offset = ack_parse_start;
                    while let Some((consumed, cmd)) =
                        crate::resp::parse::parse_resp_command(&ack_buf[parse_offset..])
                    {
                        if cmd.len() == 3
                            && cmd[0].eq_ignore_ascii_case(b"REPLCONF")
                            && cmd[1].eq_ignore_ascii_case(b"ACK")
                            && let Ok(s) = std::str::from_utf8(cmd[2])
                            && let Ok(offset) = s.parse::<u64>()
                        {
                            let _ = hub_tx
                                .send(crate::replication::HubMsg::AckOffset { replica_id, offset });
                        }
                        parse_offset += consumed;
                    }
                    ack_parse_start = parse_offset;
                    if ack_buf.len() - ack_parse_start
                        > crate::replication::replica_client::ACK_PENDING_MAX
                    {
                        log_warn!(
                            "Replication: replica {replica_id} sent what is not REPLCONF ACK; disconnecting it"
                        );
                        break;
                    }
                    if ack_parse_start > 0 && ack_parse_start > ack_buf.len() / 2 {
                        ack_buf.drain(0..ack_parse_start);
                        ack_parse_start = 0;
                    }
                }
            }
        }
    };

    tokio::select! {
        _ = ack_reader => {}
        _ = &mut forward_task => {}
        // A replica that has gone silent, or that the hub has let go of:
        // see `ReplState::replica_timed_out`.
        silent = repl_state.replica_timed_out(replica_id) => {
            if silent {
                log_warn!(
                    "Replication: disconnecting timedout replica {endpoint}: no REPLCONF ACK for {} s (repl-timeout)",
                    repl_state.repl_timeout().as_secs()
                );
            }
        }
    }

    // The forwarder ends with the connection. Left running when the ACK
    // reader, `repl-timeout` or the hub letting go of the replica ended it,
    // it kept the socket open and the replica's queue allocated after the
    // hub had forgotten both.
    forward_task.abort();
    let _ = hub_tx.send(crate::replication::HubMsg::Deregister(replica_id));
    log_info!("Replication: uring: replica disconnected");
    Ok(())
}

/// Shuts a replica's socket down when dropped (see
/// `handle_replica_connection_uring`).
struct ShutdownOnDrop(Rc<TcpStream>);

impl Drop for ShutdownOnDrop {
    fn drop(&mut self) {
        let _ = self.0.shutdown(std::net::Shutdown::Both);
    }
}

/// Write `buf` to a replica, unless it goes silent or the hub lets go of it
/// first (`None`; see `ReplState::replica_timed_out`).
async fn write_unless_let_go(
    stream: &TcpStream,
    buf: Vec<u8>,
    repl_state: &crate::replication::ReplState,
    replica_id: u64,
) -> Option<std::io::Result<()>> {
    tokio::select! {
        (res, _) = stream.write_all(buf) => Some(res),
        _ = repl_state.replica_timed_out(replica_id) => None,
    }
}

#[inline(always)]
fn now_us() -> u64 {
    // For measuring how long a command took, so: a clock that does not go
    // backwards. This was the wall clock, and the difference of two readings
    // of it — a panic in a debug build, and in a release build a command
    // logged as having taken five hundred thousand years, whenever the
    // system clock was set back between them.
    static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
    START
        .get_or_init(std::time::Instant::now)
        .elapsed()
        .as_micros() as u64
}

#[inline(always)]
fn ascii_eq_ignore_case(a: &[u8], b: &[u8]) -> bool {
    a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.eq_ignore_ascii_case(y))
}

/// Check if a command name (raw bytes, any case) requires connection-level
/// handling that can't go through the normal execute_command path.
/// Uses a first-byte filter so we never allocate a String on the fast path.
#[inline(always)]
/// Await a parked blocking command on the io_uring path.
///
/// Mirrors `server::park_blocking`; separate only because the write differs —
/// `tokio_uring`'s `write_all` takes ownership of the buffer and hands it back,
/// and the fd is shared with the push forwarder so the write must take
/// `write_guard`.
///
/// `Ok(())` means the delivery is stored and the caller should re-dispatch the
/// same command; `Err(reply)` means reply with this instead and move on.
#[allow(clippy::too_many_arguments)]
async fn park_blocking_uring(
    mut wait: crate::commands::blocking::BlockingWait,
    slot: &mut crate::commands::blocking::BlockingSlot,
    stream: &Rc<TcpStream>,
    write_guard: &Rc<tokio::sync::Mutex<()>>,
    out_buf: &mut Vec<u8>,
    subscriptions: Option<&crate::pubsub::Subscriptions>,
    client: (&crate::client_registry::ClientRegistry, u64),
    interrupted: &mut crate::commands::blocking::Interrupted,
    watch: &PeerWatch,
    repl_state: &crate::replication::ReplState,
) -> Result<(), Vec<u8>> {
    // No wait: a write that got past a `CLIENT PAUSE` before it was set
    // (`blocking::hold_for_pause`). Read again, and held by the pause check.
    if wait.held_by_pause() {
        slot.held_by_pause();
        return Ok(());
    }
    if slot.in_resume() && !wait.may_repark() {
        // A resumed handler parked again — it forgot its resume check. Reply as
        // if the wait timed out rather than looping forever.
        slot.clear_resume();
        return Err(crate::resp::write::resp_null_array());
    }

    // Flush replies to anything pipelined ahead of this command before going to
    // sleep, so a client that sent `SET a 1` and `BLPOP k 0` in one packet is
    // not left waiting on the `+OK`.
    if !out_buf.is_empty() {
        let payload = std::mem::take(out_buf);
        crate::stats::TOTAL_NET_OUTPUT_BYTES
            .fetch_add(payload.len() as u64, std::sync::atomic::Ordering::Relaxed);
        crate::stats::record_write();
        let _w = write_guard.lock().await;
        let (res, mut returned) = stream.write_all(payload).await;
        drop(_w);
        returned.clear();
        *out_buf = returned;
        if res.is_err() {
            // Socket is gone — don't park on a dead connection.
            return Err(Vec::new());
        }
    }
    // The replies to SUBSCRIBE are out: messages may follow them.
    if let Some(subs) = subscriptions {
        subs.flushed();
    }

    let refused_on_replica = wait.refused_on_replica();
    let park_epoch = wait.role_epoch();
    let block_state = wait.take_state();
    #[cfg(debug_assertions)]
    if let Some(delay) = crate::commands::blocking::test_park_delay() {
        tokio::time::sleep(delay).await;
    }
    let (client_registry, client_id) = client;
    let (unblock_tx, mut unblock_rx) = tokio::sync::oneshot::channel();
    client_registry.set_blocked(client_id, Some(unblock_tx), wait.has_timeout());
    let fd = watch.fd;
    let delivery = if crate::commands::blocking::ended_by_role_change(
        park_epoch,
        refused_on_replica,
        repl_state,
    ) {
        // This node became a replica before the client was listed as
        // blocked, so the sweep that ends blocked clients passed it by.
        interrupted.role_changed = true;
        None
    } else {
        let waiting = wait.wait();
        tokio::pin!(waiting);
        // Whether the client is still there. A read cannot be raced against
        // the wait on this loop — a submitted read cannot be taken back — so
        // the socket is watched instead: a client that has gone (or been
        // killed, which shuts the socket down) must not be left in line for
        // an element nobody will receive. See `PeerWatch`.
        let mut gone = watch.gone();
        let mut unblockable = true;
        loop {
            tokio::select! {
                delivery = &mut waiting => {
                    // Woken: what it waited for may be there, for it to take
                    // on the dispatch that resumes it. A client that has
                    // gone in the meantime must not take it, and the watch
                    // below may not have had its turn yet, so the socket is
                    // looked at now.
                    if peer_has_gone(fd) {
                        interrupted.gone = true;
                        break None;
                    }
                    break delivery;
                }
                () = &mut gone => {
                    interrupted.gone = true;
                    break None;
                }
                how = &mut unblock_rx, if unblockable => match how {
                    Ok(how) => {
                        interrupted.unblocked_with_error =
                            how == crate::commands::blocking::Unblock::Error;
                        interrupted.role_changed =
                            how == crate::commands::blocking::Unblock::RoleChange;
                        break None;
                    }
                    Err(_) => unblockable = false,
                },
            }
        }
    };
    client_registry.set_blocked(client_id, None, false);
    // Woken, or unblocked otherwise, at the moment this node became a
    // replica: ended as the sweep ends it.
    if !interrupted.gone
        && crate::commands::blocking::ended_by_role_change(
            park_epoch,
            refused_on_replica,
            repl_state,
        )
    {
        interrupted.unblocked_with_error = false;
        interrupted.role_changed = true;
    }
    // However it ended, the command is dispatched again: with what it was
    // waiting for, or as if its time had run out — which is also how it
    // leaves the line it was standing in — or, its client gone or the role
    // changed, only to leave that line, taking nothing (see
    // `server::park_blocking`).
    if interrupted.gone || interrupted.role_changed {
        slot.set_gone(block_state);
    } else {
        slot.set_pending(delivery, block_state);
    }
    Ok(())
}

/// Whether the client at the other end of `fd` has gone: closed its
/// connection, or only its sending side, or reset it — or the socket has
/// been shut down here, which is how a kill ends a connection. Reads
/// nothing: what the client has sent stays where it is.
///
/// Asked of `poll`, for `POLLRDHUP`, and not by peeking at the data: a
/// client that sent more behind a command that waits, and then closed, has
/// those bytes ahead of its end, and a peek finds the bytes and never the
/// end (#384).
fn peer_has_gone(fd: std::os::fd::RawFd) -> bool {
    let mut look = libc::pollfd {
        fd,
        events: libc::POLLRDHUP,
        revents: 0,
    };
    // SAFETY: one `pollfd` that outlives the call, on a descriptor the
    // caller holds open; a timeout of 0 returns at once.
    let ready = unsafe { libc::poll(&mut look, 1, 0) };
    ready > 0
        && look.revents & (libc::POLLRDHUP | libc::POLLHUP | libc::POLLERR | libc::POLLNVAL) != 0
}

/// A connection's watch on its client's end of the socket, for when the
/// connection waits on something — a blocking command, `WAIT`, a pause —
/// and does not read: see [`PeerWatch::gone`].
///
/// The socket is registered with the runtime's reactor the first time the
/// connection waits, and stays registered until the connection ends, so a
/// wait costs no `epoll_ctl` of its own: registering and taking it out
/// again around every wait cost a BRPOPLPUSH/LPUSH job about 7% more server
/// CPU than doing it once. A connection that never waits is never
/// registered. One that has waited is told of what arrives on it from then
/// on, which the reactor takes in with the completions it is woken for.
struct PeerWatch {
    fd: std::os::fd::RawFd,
    registered: std::cell::OnceCell<Option<tokio::io::unix::AsyncFd<Watched>>>,
}

/// The descriptor as `AsyncFd` holds it. Dropping it does not close it: it
/// is the connection's.
struct Watched(std::os::fd::RawFd);

impl std::os::fd::AsRawFd for Watched {
    fn as_raw_fd(&self) -> std::os::fd::RawFd {
        self.0
    }
}

impl PeerWatch {
    fn new(fd: std::os::fd::RawFd) -> Self {
        Self {
            fd,
            registered: std::cell::OnceCell::new(),
        }
    }

    /// Resolves once the client has gone (see [`peer_has_gone`]), and never
    /// while it is there, whatever it sends. Its end is seen when it
    /// arrives, as Redis sees it by going on reading a blocked client.
    ///
    /// Boxed, so that it is polled out of line: the connection's own future,
    /// which every command goes through, is compiled as it was without it.
    /// Kept in it, these waits cost a pipelined SET about half a percent
    /// more instructions with fat LTO, in code that command never runs.
    fn gone(&self) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + '_>> {
        Box::pin(async move {
            // Registered for reading, which on Linux includes the peer's end
            // of the stream (`EPOLLRDHUP`). What is already there — the end
            // included — is reported at once, and so is anything that has
            // arrived since an earlier wait: the socket is asked then.
            let registered = self.registered.get_or_init(|| {
                tokio::io::unix::AsyncFd::with_interest(
                    Watched(self.fd),
                    tokio::io::Interest::READABLE,
                )
                .ok()
            });
            if let Some(socket) = registered {
                loop {
                    let Ok(mut ready) = socket.readable().await else {
                        break;
                    };
                    if peer_has_gone(self.fd) {
                        return;
                    }
                    ready.clear_ready();
                }
            }
            // No reactor to ask: looked at ten times a second.
            let mut look = tokio::time::interval(std::time::Duration::from_millis(100));
            look.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
            loop {
                look.tick().await;
                if peer_has_gone(self.fd) {
                    return;
                }
            }
        })
    }
}

/// `wait`, unless the client goes first: `None` then. For `WAIT` and
/// `WAITAOF`, which a client that has gone must not be left in. Boxed, for
/// the reason given at [`PeerWatch::gone`]; the allocation is made only for
/// them.
fn unless_gone<'a, T: 'a>(
    wait: impl std::future::Future<Output = T> + 'a,
    watch: &'a PeerWatch,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Option<T>> + 'a>> {
    Box::pin(async move {
        tokio::select! {
            biased;
            done = wait => Some(done),
            () = watch.gone() => None,
        }
    })
}

fn needs_slow_path(cmd0: &[u8]) -> bool {
    let first = cmd0.first().copied().unwrap_or(0) | 0x20; // to lowercase
    // Only commands starting with these letters can possibly need interception.
    // s: SUBSCRIBE, SSUBSCRIBE
    // p: PSUBSCRIBE, PSYNC
    // m: MULTI
    // d: DISCARD
    // w: WATCH
    // u: UNWATCH
    // e: EXEC
    // a: AUTH
    if !matches!(
        first,
        b's' | b'p' | b'm' | b'd' | b'w' | b'u' | b'e' | b'a' | b'h' | b'r'
    ) {
        return false;
    }
    // Second filter: byte-wise case-insensitive comparison (no UTF-8 validation).
    ascii_eq_ignore_case(cmd0, b"SUBSCRIBE")
        || ascii_eq_ignore_case(cmd0, b"PSUBSCRIBE")
        || ascii_eq_ignore_case(cmd0, b"SSUBSCRIBE")
        // See the matching note in server.rs: RESP3 clients handle the
        // UNSUBSCRIBE family inline on the slow path instead of in the RESP2
        // subscriber loop. Length-compares first, so hot commands are unaffected.
        || ascii_eq_ignore_case(cmd0, b"UNSUBSCRIBE")
        || ascii_eq_ignore_case(cmd0, b"PUNSUBSCRIBE")
        || ascii_eq_ignore_case(cmd0, b"SUNSUBSCRIBE")
        || ascii_eq_ignore_case(cmd0, b"PSYNC")
        || ascii_eq_ignore_case(cmd0, b"SYNC")
        || ascii_eq_ignore_case(cmd0, b"MULTI")
        || ascii_eq_ignore_case(cmd0, b"DISCARD")
        || ascii_eq_ignore_case(cmd0, b"WATCH")
        || ascii_eq_ignore_case(cmd0, b"UNWATCH")
        || ascii_eq_ignore_case(cmd0, b"EXEC")
        || ascii_eq_ignore_case(cmd0, b"AUTH")
        || ascii_eq_ignore_case(cmd0, b"RESET")
        || ascii_eq_ignore_case(cmd0, b"HELLO")
        || ascii_eq_ignore_case(cmd0, b"WAITAOF")
        || ascii_eq_ignore_case(cmd0, b"WAIT")
        || ascii_eq_ignore_case(cmd0, b"MONITOR")
}

/// Eligibility check for MULTI/EXEC's lock-held fast-apply path (see the EXEC arm in
/// `handle_client`). Returns the queued `(key, value)` pairs only when every queued command
/// is an unconditional `SET key value` (exactly 3 args) — the shape a WATCH+CAS retry loop
/// produces — there's at least one WATCHed key (nothing to protect otherwise), and neither
/// MONITOR nor CLIENT TRACKING is active (the fast path skips those side effects entirely
/// rather than risk getting them subtly wrong, so it declines instead when they matter).
/// Anything else falls back to the existing per-command dispatch loop, unchanged.
fn exec_fast_apply_sets(
    watched_keys_empty: bool,
    queue: &[Vec<Vec<u8>>],
) -> Option<Vec<(String, Vec<u8>)>> {
    if watched_keys_empty
        || crate::monitor::MONITOR_COUNT.load(std::sync::atomic::Ordering::Relaxed) > 0
        || crate::tracking::TRACKING_CLIENT_COUNT.load(std::sync::atomic::Ordering::Relaxed) > 0
    {
        return None;
    }
    queue
        .iter()
        .map(|cmd| {
            if cmd.len() == 3 && cmd[0].eq_ignore_ascii_case(b"SET") {
                std::str::from_utf8(&cmd[1])
                    .ok()
                    .map(|k| (k.to_string(), cmd[2].clone()))
            } else {
                None
            }
        })
        .collect()
}

/// A connection's buffer that has grown past this is given back once it is
/// empty, rather than kept.
const BIG_BUFFER: usize = 256 * 1024;

/// How much room a read is given at a time. Like Redis's `PROTO_IOBUF_LEN`,
/// a fresh read asks for a full 32 KiB so a pipelined batch or a large bulk
/// arrives in as few syscalls as possible; the buffer is only ever reserved
/// in these units, so this is also the floor a reclaimed buffer returns to.
const READ_BUFFER: usize = 32 * 1024;
/// A read is only submitted when the buffer has at least this much spare
/// capacity left. Below it, another `READ_BUFFER`-sized chunk is reserved
/// first, so a read never lands in a sliver of free space.
const READ_MIN: usize = 8 * 1024;

/// A connection's subscriptions, made at its first SUBSCRIBE, with the task
/// that writes its messages. On this thread: the stream is not `Send`. It
/// shares the fd with the connection loop and the push task, hence the guard.
fn open_subscriptions(
    pubsub: &PubSubHub,
    client_registry: &crate::client_registry::ClientRegistry,
    client_id: u64,
    stream: &Rc<TcpStream>,
    write_guard: &Rc<tokio::sync::Mutex<()>>,
) -> crate::pubsub::Subscriptions {
    let (mut subs, mut outbox) =
        crate::pubsub::connect(pubsub, std::sync::Arc::clone(client_registry), client_id);
    let stream = Rc::clone(stream);
    let write_guard = Rc::clone(write_guard);
    let registry = std::sync::Arc::clone(client_registry);
    subs.forwarded_by(tokio_uring::spawn(async move {
        while let Some(batch) = outbox.next().await {
            let _w = write_guard.lock().await;
            // With the guard held: see `Batch::encode`.
            let frames = batch.encode(registry.get_resp(client_id));
            if frames.is_empty() {
                continue;
            }
            crate::stats::TOTAL_NET_OUTPUT_BYTES
                .fetch_add(frames.len() as u64, std::sync::atomic::Ordering::Relaxed);
            crate::stats::record_write();
            let (res, _) = stream.write_all(frames).await;
            if res.is_err() {
                break;
            }
        }
    }));
    subs
}

/// The address a client connected to: `laddr` in `CLIENT LIST`.
fn local_address(stream: &TcpStream) -> Option<std::net::SocketAddr> {
    let fd = std::os::fd::AsRawFd::as_raw_fd(stream);
    // SAFETY: `stream` owns `fd` and outlives this borrow of it.
    let fd = unsafe { std::os::fd::BorrowedFd::borrow_raw(fd) };
    socket2::SockRef::from(&fd).local_addr().ok()?.as_socket()
}

#[allow(clippy::too_many_arguments)]
pub async fn handle_client(
    stream: TcpStream,
    store: store::Store,
    lastsave: Arc<RwLock<i64>>,
    aof_tx: tokio::sync::mpsc::UnboundedSender<Vec<u8>>,
    _aof_enabled: bool,
    config: Arc<crate::config::Config>,
    started_at: Arc<Instant>,
    index_store: vector::IndexStore,
    dict_store: vector::DictStore,
    wait_table: Arc<crate::wait_table::WaitTable>,
    ts_index: store::SharedTsIndex,
    pubsub: PubSubHub,
    hub_tx: crate::replication::HubTx,
    repl_state: Arc<crate::replication::ReplState>,
    watch_registry: crate::watch::WatchRegistry,
    client_registry: crate::client_registry::ClientRegistry,
    peer_addr: String,
    acl_store: crate::acl::AclStore,
    acl_log: crate::acl::SharedAclLog,
    slowlog: crate::slowlog::SharedSlowLog,
    latency: crate::latency::SharedLatencyTracker,
    compaction_tx: crate::vector::CompactionTx,
    cluster_state: Arc<crate::cluster::ClusterState>,
    monitor_registry: crate::monitor::SharedMonitorRegistry,
    tracking_table: crate::tracking::TrackingTable,
) -> Result<(), Box<dyn std::error::Error>> {
    stream.set_nodelay(true)?;
    if let Some(denied) = crate::protected_mode::refusal(&acl_store, &peer_addr) {
        let _ = stream.write_all(denied.to_vec()).await;
        return Ok(());
    }

    // ── Client registry bookkeeping ──────────────────────────────────────
    let client_id = crate::client_registry::next_client_id();
    let (mut client_info, mut kill_rx) =
        crate::client_registry::ClientInfo::new(client_id, peer_addr.clone());
    // The socket's own address, as Redis shows it (#566): not the bind
    // setting, which can be 0.0.0.0.
    client_info.laddr = local_address(&stream).map_or_else(
        || format!("{}:{}", config.bind, config.port),
        |a| a.to_string(),
    );
    let activity = Arc::clone(&client_info.activity);
    let query_buffer = Arc::clone(&client_info.query_buffer);
    // `CLIENT REPLY`.
    let mut reply_gate = crate::client_registry::ReplyGate::default();
    client_registry.register(client_info);

    // However the connection ends — the client leaving, an error, a kill —
    // what was kept for it goes: the keys it was tracking, and its entry in
    // the registry (which is where a tracking client stops being counted).
    struct ClientGuard {
        id: u64,
        registry: crate::client_registry::ClientRegistry,
        tracking: crate::tracking::TrackingTable,
    }
    impl Drop for ClientGuard {
        fn drop(&mut self) {
            self.tracking.unregister_client(self.id);
            self.registry.unregister(self.id);
        }
    }
    let _guard = ClientGuard {
        id: client_id,
        registry: Arc::clone(&client_registry),
        tracking: Arc::clone(&tracking_table),
    };

    // ── Connection state ─────────────────────────────────────────────────
    let mut parse_buf: Vec<u8> = Vec::with_capacity(READ_BUFFER);
    let mut private_query_buffer = false;
    let mut last_query_buffer_activity = Instant::now();
    let query_buffer_idle_resize_after =
        std::time::Duration::from_millis(config.query_buffer_idle_resize_after_ms);
    let mut query_buffer_peak = 0usize;
    query_buffer.update(0, 0, private_query_buffer);
    let mut parse_start = 0usize;
    // How far the request still arriving has been read.
    let mut progress = resp::parse::Progress::default();
    let mut out_buf: Vec<u8> = Vec::with_capacity(65536);
    let mut spare_buf: Vec<u8> = Vec::with_capacity(65536);
    // Push channel for out-of-band invalidation messages (CLIENT TRACKING).
    let (push_tx, mut push_rx) =
        tokio::sync::mpsc::channel::<Vec<u8>>(crate::client_registry::PUSH_QUEUE_FRAMES);
    client_registry.register_push_tx(client_id, push_tx.clone());

    // Out-of-band pushes (CLIENT TRACKING invalidations, RESP3 pub/sub
    // deliveries) are written by their own task rather than being drained by
    // the read loop.
    //
    // Draining them in the read loop — as this path used to — only flushes
    // after the client sends its *next* command. For an invalidation that is a
    // latency bug; for a pub/sub subscriber it is fatal, because an idle
    // subscriber never sends anything and so never receives anything.
    //
    // The obvious alternative, `select!`-ing over `stream.read()`, is not safe
    // here: tokio_uring cannot cancel an in-flight op, so a losing read arm
    // leaks its buffer until the kernel completes it. That is precisely the bug
    // documented on `handle_replica_connection_uring` above (unbounded memory
    // growth per idle connection). A separate task sidesteps it entirely — the
    // read is never raced.
    //
    // Both writers therefore share the fd, so writes are serialised through
    // `write_guard`. Without it two concurrent `write_all` calls can interleave
    // mid-frame (write_all loops internally on partial writes) and corrupt the
    // stream. Uncontended it is a plain atomic swap, and it is taken once per
    // flush — not per command.
    let stream = Rc::new(stream);
    let write_guard: Rc<tokio::sync::Mutex<()>> = Rc::new(tokio::sync::Mutex::new(()));
    // For seeing that the client has gone while the connection waits on
    // something. Declared after `stream`, so that it is dropped first, and
    // the descriptor it watches is still open when it is taken out of the
    // reactor.
    let peer_watch = PeerWatch::new(std::os::fd::AsRawFd::as_raw_fd(&*stream));
    let push_task = {
        let stream = Rc::clone(&stream);
        let write_guard = Rc::clone(&write_guard);
        tokio_uring::spawn(async move {
            while let Some(msg) = push_rx.recv().await {
                let _w = write_guard.lock().await;
                crate::stats::TOTAL_NET_OUTPUT_BYTES
                    .fetch_add(msg.len() as u64, std::sync::atomic::Ordering::Relaxed);
                crate::stats::record_write();
                let (res, _) = stream.write_all(msg).await;
                if res.is_err() {
                    break;
                }
            }
        })
    };
    // Stops the forwarder touching the fd once this connection hands off to a
    // replica/monitor/subscriber loop, or ends.
    struct PushTaskGuard(tokio::task::JoinHandle<()>);
    impl Drop for PushTaskGuard {
        fn drop(&mut self) {
            self.0.abort();
        }
    }
    let _push_task = PushTaskGuard(push_task);

    // ── CLIENT KILL ─────────────────────────────────────────────────────────
    //
    // The tokio loop races `kill_rx` against the socket read in a `select!`.
    // That is not available here: tokio_uring cannot cancel an in-flight op, so
    // a losing read arm would leak its buffer until the kernel completes it.
    // Checking `kill_rx` before each read — which is all this path used to do —
    // only fires once the client sends something, so killing an *idle* client
    // did nothing at all and it kept answering PING.
    //
    // Shutting the socket down instead makes the in-flight read complete on its
    // own, which needs no cancellation: the loop then sees `Ok(0)` and exits by
    // the ordinary close path. Redis sends no reply to a killed client either.
    //
    // Except to one that killed itself (`CLIENT KILL … SKIPME no`), which is
    // owed the reply to that command: for it only the reading side is shut,
    // so the reply is written and the read after it is the one that ends.
    let kill_task = {
        let kill_fd = std::os::fd::AsRawFd::as_raw_fd(&*stream);
        let activity = Arc::clone(&activity);
        tokio_uring::spawn(async move {
            // Resolves with Err when the sender is dropped at deregistration,
            // i.e. the connection ended on its own — nothing to do then.
            if (&mut kill_rx).await.is_ok() {
                let how = if activity.closes_after_reply() {
                    libc::SHUT_RD
                } else {
                    libc::SHUT_RDWR
                };
                // SAFETY: `kill_fd` belongs to `stream`, which is kept alive by
                // the `Rc` held in this function for as long as this task can
                // run — the guard below aborts it before that `Rc` is dropped.
                unsafe {
                    libc::shutdown(kill_fd, how);
                }
            }
        })
    };
    struct KillTaskGuard(tokio::task::JoinHandle<()>);
    impl Drop for KillTaskGuard {
        fn drop(&mut self) {
            self.0.abort();
        }
    }
    let _kill_task = KillTaskGuard(kill_task);

    // This connection's subscriptions, while it has any. `None` otherwise, so
    // that a connection that never uses pub/sub allocates nothing for it.
    let mut subscriptions: Option<crate::pubsub::Subscriptions> = None;
    // How a blocking command's wait was cut short. See `park_blocking_uring`.
    let mut interrupted = crate::commands::blocking::Interrupted::default();

    let mut selected_db: usize = 0;
    // Tracks whether the current authenticated user has a key/command restriction.
    // Drives RESTRICTED_KEY_CLIENTS/RESTRICTED_CMD_CLIENTS so handler.rs can
    // fast-exit on the common path. Kept in sync via acl::track_restriction_counters.
    // Declared before authenticated_user below because the implicit-default-user
    // path also needs to seed these from the "default" user's actual ACL rules.
    let mut key_restricted = false;
    let mut cmd_restricted = false;
    // The ACL as of when those flags were worked out; see `acl::ACL_EPOCH`.
    // Read first, so a change racing with the lookup below is noticed.
    let mut acl_epoch_seen = crate::acl::ACL_EPOCH.load(std::sync::atomic::Ordering::Relaxed);
    // None = not authenticated, Some(name) = authenticated as this user
    let mut authenticated_user: Option<String> = if crate::acl::default_user_is_open(&acl_store) {
        // Connections start implicitly authenticated as "default" when that
        // user needs no password — asked of the user table, where a password
        // from `--requirepass`, from the ACL file or from `ACL SETUSER` all
        // end up, and not of `--requirepass` alone -- but "default" is a real
        // ACL user and can carry
        // its own command/key restrictions (`ACL SETUSER default ... -flushall`).
        // Route through the same counter bookkeeping AUTH uses, or a restricted
        // default user's rules are silently never enforced for connections that
        // never explicitly call AUTH.
        if let Some(user) = acl_store.read().get("default") {
            crate::acl::track_restriction_counters(user, &mut key_restricted, &mut cmd_restricted);
        }
        Some("default".to_string())
    } else {
        None
    };

    // Transaction state — only touched when MULTI/EXEC/WATCH are used.
    use crate::commands::transaction::TxState;
    let mut tx = TxState::new();
    // A command of the batch being answered may have queued an AOF
    // record: its reply waits for it (see `aof::written`).
    let mut aof_wait = false;
    let dirty_flag = Arc::new(std::sync::atomic::AtomicBool::new(false));
    // Negotiated RESP protocol version, updated by HELLO. Kept as local connection
    // state (not read from client_registry per command) so execute_command's
    // per-command null-encoding check doesn't hit the shared client_registry lock
    // on every single command across every worker thread.
    let mut resp_version: u8 = 2;

    enum ConnectionHandoff {
        Replica {
            legacy_sync: bool,
            /// What the replica asked to continue from, if anything.
            psync: Option<crate::replication::PsyncRequest>,
        },
    }
    // `MONITOR` mode, while the connection is in it.
    let mut monitoring: Option<crate::monitor::Monitoring> = None;
    // What a script run for this connection is given: see where it is made.
    #[cfg(feature = "lua")]
    let mut lua_env: Option<crate::lua_vm_blocking::ClientExecEnv> = None;

    loop {
        let was_private_at_read = private_query_buffer;
        // No `kill_rx` check here any more — the watcher task above shuts the
        // socket down, so a kill surfaces as `Ok(0)` from the read below even
        // when the client is idle.
        //
        // The read is never raced. tokio_uring cannot cancel an in-flight op,
        // so a losing `select!` arm would leak the buffer it owns until the
        // kernel completes it (see the note above). Reading straight into
        // `parse_buf` — the same zero-copy path an ordinary client uses — keeps
        // the buffer owned by this loop for exactly the duration of the read.
        // Query-buffer shrinking therefore happens *between* batches: right
        // after a read completes (the buffer is then owned by this loop, with
        // no operation in flight), before the next read is submitted. An idle
        // client whose oversized buffer is not followed by another read keeps
        // that buffer until the next read opportunity; that is the accepted
        // io_uring tradeoff for not racing the read (Redis shrinks such buffers
        // from its client cron instead).
        if parse_buf.capacity().saturating_sub(parse_buf.len()) < READ_MIN {
            parse_buf.reserve(READ_BUFFER);
        }
        let unparsed = parse_buf.len();
        let (res, buffer) = stream.read(parse_buf.slice(unparsed..)).await;
        parse_buf = buffer.into_inner();

        let n = match res {
            Ok(0) => break,
            Ok(n) => n,
            Err(e) => {
                // cleanup runs below via the break path
                let _ = e; // suppress unused warning if needed
                break;
            }
        };
        // Bytes arrived from the socket: the client is active, so its idle
        // clock restarts. Once per read, not once per command — a pipeline
        // that arrives together is one interaction. EOF and read errors
        // `break` above, so they never reach here.
        activity.touch();
        // Between batches, before the activity timestamp is refreshed: if this
        // client was idle for long enough, reclaim an oversized private buffer
        // now. No read is in flight, so rebuilding `parse_buf` is safe.
        //
        // Only buffers past the resize threshold can be reclaimed, so the
        // clock is read only for those; an ordinary client — whose buffer is
        // the small initial one — pays nothing. This keeps `SET`/`GET` at the
        // floor from a `clock_gettime` on every read.
        if private_query_buffer
            && parse_buf.capacity() > resp::parse::QUERY_BUFFER_RESIZE_THRESHOLD
            && parse_buf.capacity().saturating_sub(parse_buf.len())
                > resp::parse::QUERY_BUFFER_MIN_SPARE_FOR_RESIZE
        {
            let resized = resp::parse::resize_private_query_buffer_after(
                &mut parse_buf,
                parse_start,
                &mut private_query_buffer,
                last_query_buffer_activity.elapsed(),
                query_buffer_idle_resize_after,
                query_buffer_peak,
                progress.minimum_capacity(),
            );
            if resized {
                parse_start = 0;
            }
            query_buffer_peak = parse_buf
                .len()
                .saturating_sub(parse_start)
                .max(progress.minimum_capacity());
        }
        if was_private_at_read {
            last_query_buffer_activity = Instant::now();
        }
        crate::stats::TOTAL_NET_INPUT_BYTES
            .fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed);
        crate::stats::record_read();
        activity.note_read(n);

        query_buffer_peak = query_buffer_peak.max(parse_buf.len().saturating_sub(parse_start));
        debug_assert_eq!(parse_buf.len(), unparsed + n);
        query_buffer.update(
            parse_buf.len().saturating_sub(parse_start),
            parse_buf.capacity().saturating_sub(parse_buf.len()),
            private_query_buffer,
        );

        let mut parse_offset = parse_start;
        let commands_before = activity.commands_run();
        let mut connection_handoff: Option<ConnectionHandoff> = None;
        let mut quit_requested = false;
        // Outside the parse loop: a park in one turn hands its delivery to
        // the re-dispatch on the next turn.
        let mut blocking_slot = crate::commands::blocking::BlockingSlot::default();
        // The next turn dispatches the command of this one again: a parked
        // command resumed, or a write a pause sent back to be held. It is
        // the same command: not recorded, settled or begun again.
        let mut redispatch = false;

        // What the client sent that no request can begin with, if it did.
        let mut protocol_error: Option<String> = None;
        let query_buffer_bytes = parse_buf.len();
        let query_buffer_free = parse_buf.capacity().saturating_sub(parse_buf.len());
        let was_private_query_buffer = private_query_buffer;
        while let Some((consumed, cmd)) =
            match progress.next_request(&mut parse_buf, parse_offset, authenticated_user.is_some())
            {
                Ok(request) => request,
                Err(e) => {
                    protocol_error = Some(e);
                    None
                }
            }
        {
            private_query_buffer |= progress.take_private_query_buffer();
            if cmd.is_empty() {
                parse_offset += consumed;
                query_buffer.update(
                    query_buffer_bytes.saturating_sub(parse_offset),
                    query_buffer_free,
                    private_query_buffer,
                );
                continue;
            }
            query_buffer.update(
                query_buffer_bytes.saturating_sub(parse_offset + consumed),
                query_buffer_free,
                private_query_buffer,
            );
            // Re-read every command: CONFIG SET appendonly yes must take effect
            // on this connection, not only on ones accepted after the toggle.
            // Tokio's loop already loads AOF_ENABLED per command; this parameter
            // was the boot-time snapshot and left post-toggle writes unlogged.
            let aof_enabled = crate::aof::AOF_ENABLED.load(std::sync::atomic::Ordering::Relaxed);
            // ── QUIT ─────────────────────────────────────────────────────────
            // Reply +OK and close the connection. Handled in the connection
            // loop rather than the dispatch table because closing the socket
            // is a connection-level concern `execute_command` can't express.
            // See the matching comment in `src/server.rs` — QUIT was listed as
            // a special command in both allowlists but had no dispatch arm, so
            // it returned `-ERR unknown command` and left the socket open.
            //
            // Anything pipelined after QUIT is intentionally not executed —
            // the connection is closing, which is what Redis does too.
            //
            // The `len() == 4` gate keeps this off the hot path: it rejects
            // GET/SET/DEL in a single compare, before the byte-wise loop.
            if cmd[0].len() == 4 && ascii_eq_ignore_case(cmd[0], b"QUIT") {
                out_buf.extend_from_slice(b"+OK\r\n");
                parse_offset += consumed;
                quit_requested = true;
                break;
            }
            // For `CLIENT LIST`'s `cmd=` and `db=`, and `tot-cmds`. Not again
            // for a blocked command dispatched once more with what it waited
            // for: it is one command.
            if !redispatch && !blocking_slot.resuming() {
                activity.record(&cmd, selected_db);
            }
            if !aof_wait && crate::aof::acks_wait() && crate::aof::may_log(&cmd) {
                aof_wait = true;
            }
            // The command before this one is over: its reply is settled, and
            // what it left to tell tracking clients follows it.
            if std::mem::take(&mut redispatch) {
                // A `CLIENT REPLY SKIP` before it is for the dispatch that
                // replies, not used up by the one that did not.
                reply_gate.again(&out_buf);
            } else {
                reply_gate.settle(&mut out_buf);
                crate::tracking::after_command(
                    &tracking_table,
                    &client_registry,
                    client_id,
                    &activity,
                    &mut out_buf,
                );
                reply_gate.begin(&cmd, &mut out_buf);
            }
            // ── ACL changes reach connections that are already open ──────────────
            // One relaxed load per command when nothing has changed.
            if crate::acl::ACL_EPOCH.load(std::sync::atomic::Ordering::Relaxed) != acl_epoch_seen
                && !crate::acl::resync_connection(
                    &acl_store,
                    authenticated_user.as_deref(),
                    &mut acl_epoch_seen,
                    &mut key_restricted,
                    &mut cmd_restricted,
                )
            {
                // The user this connection authenticated as has been deleted.
                quit_requested = true;
                break;
            }
            // ── CLIENT PAUSE enforcement (async-safe) ────────────────────────────
            // Must be done here, not in execute_command, because std::thread::sleep
            // inside a tokio task blocks the worker thread and prevents UNPAUSE
            // from being processed on another connection.
            //
            // A client that goes while its command is held is let go, and the
            // command is not run: as in Redis, which goes on reading a client
            // a pause holds. A blocking pop run for it once the pause ended
            // would take an element for nobody (#384). Except the dispatch
            // that resumes a command that waited: that one runs, only to
            // leave the line it stood in and pass the turn on, and one whose
            // client has already gone is not held at all — it writes nothing.
            //
            // Boxed, and so polled out of line, for the reason given at
            // `PeerWatch::gone`.
            let _ran = if crate::pause::PAUSE_UNTIL_MS.load(std::sync::atomic::Ordering::Relaxed)
                != 0
                && !(blocking_slot.resuming() && (interrupted.gone || interrupted.role_changed))
            {
                let gated: std::pin::Pin<
                    Box<dyn std::future::Future<Output = Option<Option<crate::pause::Ran>>> + '_>,
                > = Box::pin(crate::pause::gate(&cmd, &tx.queue, client_id, || {
                    peer_watch.gone()
                }));
                match gated.await {
                    // The gate may have kept a resume waiting after it was
                    // woken and looked at the socket — while the clients an
                    // ended pause let go went on — and the client may have
                    // gone meanwhile: it is looked at again, or the element
                    // would be popped for nobody.
                    Some(ran) if blocking_slot.resuming() && peer_has_gone(peer_watch.fd) => {
                        blocking_slot.make_gone();
                        interrupted.gone = true;
                        ran
                    }
                    Some(ran) => ran,
                    None if blocking_slot.resuming() => {
                        blocking_slot.make_gone();
                        interrupted.gone = true;
                        None
                    }
                    None => {
                        quit_requested = true;
                        break;
                    }
                }
            } else {
                None
            };
            // ══════════════════════════════════════════════════════════════
            // FAST PATH — zero heap allocations, zero string comparisons
            // for the common case: authenticated, no active transaction,
            // and the command doesn't need connection-level interception.
            //
            // This is what the inner loop looked like in v0.1.10.
            // ══════════════════════════════════════════════════════════════
            // Read for each command — one atomic load — and not once per
            // connection: `CONFIG SET slowlog-log-slower-than` has to reach the
            // connections that are already open, the one that issued it included.
            let slowlog_enabled = slowlog.threshold_us() < u64::MAX;
            // A RESP2 connection with subscriptions may run next to nothing:
            // that is decided on the slow path.
            let subscriber_only = resp_version == 2 && subscriptions.is_some();
            if authenticated_user.is_some()
                && !tx.active
                && !subscriber_only
                && !needs_slow_path(cmd[0])
            {
                #[cfg(feature = "lua")]
                if crate::commands::lua_command_runs_long_sync_vm(cmd.as_slice()) {
                    // Made once for the connection and kept: it is two dozen shared
                    // handles, each counted up to copy and down to drop, and a script
                    // needs none of them copied to run on this thread. Made again if
                    // the connection has become another user since.
                    let user_now = authenticated_user.as_deref().unwrap_or("default");
                    if lua_env
                        .as_ref()
                        .is_some_and(|env| env.authenticated_user != user_now)
                    {
                        lua_env = None;
                    }
                    let env = &*lua_env.get_or_insert_with(|| {
                        crate::lua_vm_blocking::ClientExecEnv::snapshot(
                            &store,
                            &lastsave,
                            crate::lua_vm_blocking::AofBridge::Tokio(aof_tx.clone()),
                            &config,
                            &started_at,
                            &index_store,
                            &dict_store,
                            &wait_table,
                            &ts_index,
                            &pubsub,
                            &hub_tx,
                            &repl_state,
                            &watch_registry,
                            &client_registry,
                            &acl_store,
                            &acl_log,
                            &slowlog,
                            &latency,
                            &compaction_tx,
                            &cluster_state,
                            &monitor_registry,
                            &tracking_table,
                            &peer_addr,
                            client_id,
                            authenticated_user.as_deref().unwrap_or("default"),
                        )
                    });
                    let (response, elapsed_us) = crate::lua_vm_blocking::run_lua_vm_blocking(
                        cmd.as_slice(),
                        &mut selected_db,
                        env,
                        aof_enabled,
                        resp_version,
                    )
                    .await;
                    // A script that got past a `CLIENT PAUSE` before it was
                    // set, and did not run (`pause::HELD_IN_GATE`): read
                    // again, and held by the pause check.
                    if crate::pause::is_held(&response) {
                        redispatch = true;
                        continue;
                    }
                    if slowlog_enabled && elapsed_us >= slowlog.threshold_us() {
                        let client_name = client_registry
                            .get(client_id)
                            .map(|info| info.name.clone())
                            .unwrap_or_default();
                        slowlog.record(&cmd, elapsed_us, &peer_addr, client_name);
                    }
                    out_buf.extend_from_slice(&response);
                    parse_offset += consumed;
                    continue;
                }

                if !slowlog_enabled {
                    let mut response = commands::execute_command(Ctx {
                        cmd,
                        store: &store,
                        lastsave: &lastsave,
                        selected_db: &mut selected_db,
                        aof_tx: &aof_tx,
                        aof_enabled,
                        config: &config,
                        started_at: &started_at,
                        index_store: &index_store,
                        dict_store: &dict_store,
                        wait_table: &wait_table,
                        ts_index: &ts_index,
                        pubsub: &pubsub,
                        hub_tx: &hub_tx,
                        repl_state: &repl_state,
                        watch_registry: watch_registry.as_ref(),
                        client_id,
                        client_registry: &client_registry,
                        resp: resp_version,
                        acl_store: &acl_store,
                        acl_log: &acl_log,
                        slowlog: &slowlog,
                        latency: &latency,
                        compaction_tx: &compaction_tx,
                        cluster: &cluster_state,
                        bypass_cluster_check: false,
                        apply_replication: false,
                        skip_write_side_effects: false,
                        peer_addr: &peer_addr,
                        monitor_registry: &monitor_registry,
                        authenticated_user: authenticated_user.as_deref().unwrap_or("default"),
                        tracking_table: &tracking_table,
                        blocking: Some(blocking_slot.prime()),
                    });
                    if let Some(wait) = blocking_slot.take_parked() {
                        if std::mem::take(&mut aof_wait) {
                            crate::aof::written(&aof_tx).await;
                        }
                        match park_blocking_uring(
                            wait,
                            &mut blocking_slot,
                            &stream,
                            &write_guard,
                            &mut out_buf,
                            subscriptions.as_ref(),
                            (&client_registry, client_id),
                            &mut interrupted,
                            &peer_watch,
                            &repl_state,
                        )
                        .await
                        {
                            // `parse_offset` deliberately not advanced: the same
                            // command is re-dispatched, now carrying the delivery.
                            Ok(()) => {
                                redispatch = true;
                                continue;
                            }
                            Err(reply) => response = reply,
                        }
                    }

                    if interrupted.unblocked_with_error {
                        interrupted.unblocked_with_error = false;
                        response = crate::commands::blocking::UNBLOCKED.to_vec();
                    }
                    if interrupted.gone {
                        // It has left the line; there is nobody to reply to.
                        quit_requested = true;
                        break;
                    }
                    if std::mem::take(&mut interrupted.role_changed) {
                        // This node became a replica: told so, and closed.
                        out_buf.extend_from_slice(crate::commands::blocking::ROLE_CHANGED);
                        quit_requested = true;
                        break;
                    }
                    out_buf.extend_from_slice(&response);
                    parse_offset += consumed;
                    continue;
                }
                let mut waited_from: Option<u64> = None;
                let mut response = commands::execute_command(Ctx {
                    cmd,
                    store: &store,
                    lastsave: &lastsave,
                    selected_db: &mut selected_db,
                    aof_tx: &aof_tx,
                    aof_enabled,
                    config: &config,
                    started_at: &started_at,
                    index_store: &index_store,
                    dict_store: &dict_store,
                    wait_table: &wait_table,
                    ts_index: &ts_index,
                    pubsub: &pubsub,
                    hub_tx: &hub_tx,
                    repl_state: &repl_state,
                    watch_registry: watch_registry.as_ref(),
                    client_id,
                    client_registry: &client_registry,
                    resp: resp_version,
                    acl_store: &acl_store,
                    acl_log: &acl_log,
                    slowlog: &slowlog,
                    latency: &latency,
                    compaction_tx: &compaction_tx,
                    cluster: &cluster_state,
                    bypass_cluster_check: false,
                    apply_replication: false,
                    skip_write_side_effects: false,
                    peer_addr: &peer_addr,
                    monitor_registry: &monitor_registry,
                    authenticated_user: authenticated_user.as_deref().unwrap_or("default"),
                    tracking_table: &tracking_table,
                    blocking: Some(blocking_slot.prime()),
                });
                if let Some(wait) = blocking_slot.take_parked() {
                    waited_from = Some(now_us());
                    if std::mem::take(&mut aof_wait) {
                        crate::aof::written(&aof_tx).await;
                    }
                    match park_blocking_uring(
                        wait,
                        &mut blocking_slot,
                        &stream,
                        &write_guard,
                        &mut out_buf,
                        subscriptions.as_ref(),
                        (&client_registry, client_id),
                        &mut interrupted,
                        &peer_watch,
                        &repl_state,
                    )
                    .await
                    {
                        // See the note at the non-slowlog site above.
                        Ok(()) => {
                            redispatch = true;
                            continue;
                        }
                        Err(reply) => response = reply,
                    }
                }

                if interrupted.unblocked_with_error {
                    interrupted.unblocked_with_error = false;
                    response = crate::commands::blocking::UNBLOCKED.to_vec();
                }
                if interrupted.gone {
                    // It has left the line; there is nobody to reply to.
                    quit_requested = true;
                    break;
                }
                if std::mem::take(&mut interrupted.role_changed) {
                    // This node became a replica: told so, and closed.
                    out_buf.extend_from_slice(crate::commands::blocking::ROLE_CHANGED);
                    quit_requested = true;
                    break;
                }
                // What the handler measured, and for a command that waited
                // (`BLPOP`) the wait as well: the clock is not read again
                // around every command for this.
                let elapsed_us = crate::cmdstats::last_command_us()
                    + waited_from.map_or(0, |from| now_us().saturating_sub(from));

                if elapsed_us >= slowlog.threshold_us() {
                    let client_name = client_registry
                        .get(client_id)
                        .map(|info| info.name.clone())
                        .unwrap_or_default();
                    // The command is still where it was read: it is read
                    // again for the log, now that it has turned out slow,
                    // where every command used to be copied in case it did.
                    if let Ok(Some((_, slow_cmd))) =
                        resp::parse::next_request(&mut parse_buf, parse_offset)
                    {
                        slowlog.record(&slow_cmd, elapsed_us, &peer_addr, client_name);
                    }
                }
                out_buf.extend_from_slice(&response);
                parse_offset += consumed;
                continue;
            }

            // ══════════════════════════════════════════════════════════════
            // SLOW PATH — only reached for auth, transactions, subscribe,
            // psync, or when not yet authenticated. Allocates cmd_name.
            // ══════════════════════════════════════════════════════════════
            let cmd_name = String::from_utf8_lossy(cmd[0]).to_ascii_uppercase();

            // ── Auth gate ─────────────────────────────────────────────────
            if authenticated_user.is_none()
                && !matches!(cmd_name.as_str(), "AUTH" | "QUIT" | "HELLO" | "RESET")
            {
                // As in Redis, nothing goes to the ACL log: no user was
                // refused anything.
                out_buf.extend_from_slice(b"-NOAUTH Authentication required.\r\n");
                parse_offset += consumed;
                continue;
            }

            // ── Permission check: the command, its keys, its channels ─────
            if let Some(ref username) = authenticated_user {
                let denied = acl_store
                    .read()
                    .get(username.as_str())
                    .and_then(|user| crate::acl::check_permission(user, &cmd_name, &cmd).err());
                if let Some(denied) = denied {
                    // As in Redis, a command there is no such command as, or
                    // with the wrong number of arguments, is refused for that
                    // before the user's rules are looked at.
                    let refusal = if !commands::server::is_command(&cmd_name) {
                        commands::handler::unknown_command(&cmd)
                    } else if let Some(wrong) = commands::arity::check(&cmd_name, &cmd) {
                        wrong
                    } else if tx.active && commands::transaction::not_allowed_in_multi(&cmd_name) {
                        crate::resp::write::resp_error(commands::transaction::NOT_IN_MULTI)
                    } else {
                        let _context = tx.active.then(|| crate::acl::log_context("multi"));
                        acl_log.record(
                            denied.reason(),
                            denied.object(),
                            username,
                            &crate::acl::log_client_info(&client_registry, client_id, &peer_addr),
                        );
                        format!("-{}\r\n", denied.message(username)).into_bytes()
                    };
                    // Refused inside MULTI, it is not queued, and EXEC runs nothing, as
                    // for a command refused for any other reason (#159). A refused
                    // EXEC discards the transaction, as in Redis.
                    let reply = commands::transaction::reject(
                        &mut tx,
                        &cmd,
                        watch_registry.as_ref(),
                        &dirty_flag,
                        commands::transaction::Monitored {
                            registry: &monitor_registry,
                            db: selected_db,
                            peer_addr: &peer_addr,
                        },
                        refusal,
                    );
                    out_buf.extend_from_slice(&reply);
                    parse_offset += consumed;
                    continue;
                }
            }

            // ── Subscriptions ─────────────────────────────────────────────
            // A subscribed connection stays in this loop, with a task of its
            // own writing its messages. Under RESP3 that is all there is to
            // it; under RESP2 it may run nothing but the commands below while
            // it has subscriptions. Mirrors the tokio loop in server.rs: inside
            // MULTI they are queued, and EXEC runs them (#23).
            if crate::pubsub::is_subscription_command(cmd_name.as_str()) && !tx.active {
                if let Some(refusal) =
                    crate::pubsub::shard_subscribe_refusal(cmd_name.as_str(), &cmd, &cluster_state)
                {
                    out_buf.extend_from_slice(&refusal);
                    parse_offset += consumed;
                    continue;
                }
                let subs = subscriptions.get_or_insert_with(|| {
                    open_subscriptions(&pubsub, &client_registry, client_id, &stream, &write_guard)
                });
                out_buf.extend_from_slice(&subs.handle(&cmd, resp_version));
                if subs.total() == 0 {
                    subscriptions = None;
                }
                parse_offset += consumed;
                continue;
            }
            if resp_version == 2
                && subscriptions.is_some()
                && let Some(reply) = crate::pubsub::resp2_subscriber_reply(cmd_name.as_str(), &cmd)
            {
                out_buf.extend_from_slice(&reply);
                parse_offset += consumed;
                continue;
            }

            // ── Connection handoffs (break parse loop so `parse_buf` can be drained) ──
            // A replica whose dataset may already be this master's is first
            // offered the fingerprint (see `replication::digest`), and the
            // connection stays a client until it asks again; so is one of a
            // master that lost its dataset (`ReplState::psync_offer`).
            // A replica does not take replicas of its own (#144).
            // Inside MULTI they are refused, as in Redis (`queue_refusal`), and
            // the transaction with them: they do not hand the connection over.
            if (cmd_name == "PSYNC" || cmd_name == "SYNC") && !tx.active && repl_state.is_slave() {
                out_buf.extend_from_slice(&crate::resp::write::resp_error(
                    crate::replication::NOT_A_MASTER,
                ));
                parse_offset += consumed;
                continue;
            }
            if cmd_name == "PSYNC"
                && !tx.active
                && let Some(offer) =
                    repl_state.psync_offer(&cluster_state, &client_registry, client_id, &cmd)
            {
                out_buf.extend_from_slice(&offer);
                parse_offset += consumed;
                continue;
            }
            if (cmd_name == "PSYNC" || cmd_name == "SYNC") && !tx.active {
                parse_offset += consumed;
                connection_handoff = Some(ConnectionHandoff::Replica {
                    legacy_sync: cmd_name == "SYNC",
                    psync: crate::replication::PsyncRequest::parse(&cmd),
                });
                break;
            }
            // Inside MULTI it is queued, as in Redis, and refused when EXEC
            // runs it (#550).
            if cmd_name == "MONITOR" && !tx.active {
                if monitoring.is_none() {
                    monitoring = Some(crate::monitor::Monitoring::start(
                        &monitor_registry,
                        push_tx.clone(),
                    ));
                    client_registry.update(client_id, |info| info.flags = "O".to_string());
                }
                out_buf.extend_from_slice(b"+OK\r\n");
                parse_offset += consumed;
                continue;
            }

            // A transaction's own commands with the wrong number of
            // arguments are refused before they do anything, as in Redis;
            // and, like any command refused inside MULTI, they take the
            // transaction with them. An EXEC refused so ends it (#550).
            if matches!(
                cmd_name.as_str(),
                "MULTI" | "EXEC" | "DISCARD" | "WATCH" | "UNWATCH" | "RESET"
            ) && let Some(wrong) = commands::arity::check(&cmd_name, &cmd)
            {
                let reply = commands::transaction::reject(
                    &mut tx,
                    &cmd,
                    watch_registry.as_ref(),
                    &dirty_flag,
                    commands::transaction::Monitored {
                        registry: &monitor_registry,
                        db: selected_db,
                        peer_addr: &peer_addr,
                    },
                    wrong,
                );
                out_buf.extend_from_slice(&reply);
                parse_offset += consumed;
                continue;
            }

            // `MULTI` or `EXEC`, as the client wrote it: for MONITOR, below.
            let transaction_word: Option<Vec<u8>> =
                matches!(cmd_name.as_str(), "MULTI" | "EXEC").then(|| cmd[0].to_vec());

            // ── Transaction + Auth commands ───────────────────────────────
            // Queued, inside MULTI: counted when EXEC runs them.
            let queued_here = tx.active && matches!(cmd_name.as_str(), "UNWATCH" | "AUTH");
            let response = match cmd_name.as_str() {
                "MULTI" => {
                    if tx.active {
                        b"-ERR MULTI calls can not be nested\r\n".to_vec()
                    } else {
                        tx.active = true;
                        b"+OK\r\n".to_vec()
                    }
                }

                "DISCARD" => {
                    if !tx.active {
                        b"-ERR DISCARD without MULTI\r\n".to_vec()
                    } else {
                        watch_registry.as_ref().unwatch_all(
                            &tx.watched_keys
                                .iter()
                                .map(|_| Arc::clone(&dirty_flag))
                                .collect::<Vec<_>>(),
                        );
                        tx.reset();
                        dirty_flag.store(false, std::sync::atomic::Ordering::Release);
                        b"+OK\r\n".to_vec()
                    }
                }

                "WATCH" => {
                    if tx.active {
                        b"-ERR WATCH inside MULTI is not allowed\r\n".to_vec()
                    } else if cmd.len() < 2 {
                        b"-ERR wrong number of arguments for 'watch' command\r\n".to_vec()
                    } else {
                        for key in &cmd[1..] {
                            // A key that has already expired is watched as
                            // the absent key it is: its removal, when it
                            // comes, is not a change.
                            commands::helpers::lazy_expire_key(&store, selected_db, key);
                            tx.watched_keys
                                .push((selected_db, crate::store::Key::new(key)));
                            watch_registry.as_ref().watch(
                                selected_db,
                                key,
                                Arc::clone(&dirty_flag),
                            );
                        }
                        b"+OK\r\n".to_vec()
                    }
                }

                // Inside MULTI it is queued, as in Redis: run there, it
                // dropped the watches, and EXEC ran after a watched key
                // had changed (#550).
                "UNWATCH" if !tx.active => {
                    watch_registry.as_ref().unwatch_all(
                        &tx.watched_keys
                            .iter()
                            .map(|_| Arc::clone(&dirty_flag))
                            .collect::<Vec<_>>(),
                    );
                    tx.watched_keys.clear();
                    dirty_flag.store(false, std::sync::atomic::Ordering::Release);
                    b"+OK\r\n".to_vec()
                }

                // RESET: the connection as it was when it was opened. The
                // transaction and the watches are dropped, subscriptions and
                // tracking ended, the database is 0, the protocol RESP2, the
                // name gone — and the user is `default` again, if `default`
                // needs no password, or nobody.
                "RESET" => {
                    watch_registry.as_ref().unwatch_all(
                        &tx.watched_keys
                            .iter()
                            .map(|_| Arc::clone(&dirty_flag))
                            .collect::<Vec<_>>(),
                    );
                    tx.reset();
                    dirty_flag.store(false, std::sync::atomic::Ordering::Release);
                    selected_db = 0;
                    resp_version = 2;
                    subscriptions = None;
                    if client_registry
                        .get(client_id)
                        .map(|i| i.tracking)
                        .unwrap_or(false)
                    {
                        tracking_table.disable_tracking();
                    }
                    tracking_table.unregister_client(client_id);
                    monitoring = None;
                    // `HIMPORT` fieldsets are the connection's state (#566).
                    crate::commands::hash_import::forget_client(client_id);
                    client_registry.update(client_id, |info| {
                        info.no_evict = false;
                        info.resp = 2;
                        info.name = String::new();
                        info.tracking = false;
                        info.tracking_bcast = false;
                        info.tracking_optin = false;
                        info.tracking_optout = false;
                        info.tracking_noloop = false;
                        info.tracking_caching_next = None;
                        info.tracking_prefixes.clear();
                        info.tracking_redirect = None;
                        info.tracking_redirect_broken = false;
                        info.flags = "N".to_string();
                        info.user = "default".to_string();
                    });
                    authenticated_user = if crate::acl::default_user_is_open(&acl_store) {
                        if let Some(user) = acl_store.read().get("default") {
                            crate::acl::track_restriction_counters(
                                user,
                                &mut key_restricted,
                                &mut cmd_restricted,
                            );
                        }
                        Some("default".to_string())
                    } else {
                        crate::acl::clear_restriction_counters(
                            &mut key_restricted,
                            &mut cmd_restricted,
                        );
                        None
                    };
                    b"+RESET\r\n".to_vec()
                }

                "EXEC" => {
                    // One watching transaction at a time, from its check to
                    // its last command. See `WATCHED_EXEC`.
                    let _one_at_a_time = if tx.active && !tx.watched_keys.is_empty() {
                        Some(commands::transaction::WATCHED_EXEC.lock().await)
                    } else {
                        None
                    };
                    // A watched key whose time ran out while it was watched
                    // has been modified, whether or not anything has got
                    // round to removing it. Removing it now says so.
                    for (db, key) in &tx.watched_keys {
                        commands::helpers::lazy_expire_key(&store, *db, key);
                    }
                    // When it was routed, for the check inside its gates.
                    let mut routed = crate::cluster::routing::Routed::default();
                    let refusal = if !tx.active {
                        None
                    } else if let Some(busy) =
                        commands::transaction::exec_refusal(&cmd, &tx.queue, &repl_state)
                    {
                        // Before anything else, as for any command: a
                        // script has the server.
                        Some(busy)
                    } else if tx.aborted {
                        Some(
                            b"-EXECABORT Transaction discarded because of previous errors.\r\n"
                                .to_vec(),
                        )
                    } else {
                        crate::cluster::routing::exec_refusal(
                            &crate::cluster::routing::Caller {
                                cluster: &cluster_state,
                                registry: &client_registry,
                                client_id,
                                store: &store,
                                db: selected_db,
                            },
                            &tx.queue,
                            &mut routed,
                        )
                    };
                    if !tx.active {
                        b"-ERR EXEC without MULTI\r\n".to_vec()
                    } else if let Some(refusal) = refusal {
                        // Nothing runs: the transaction is discarded whole.
                        watch_registry.as_ref().unwatch_all(
                            &tx.watched_keys
                                .iter()
                                .map(|_| Arc::clone(&dirty_flag))
                                .collect::<Vec<_>>(),
                        );
                        tx.reset();
                        dirty_flag.store(false, std::sync::atomic::Ordering::Release);
                        refusal
                    } else {
                        // From the check of the watched keys to the last queued
                        // command, the transaction is alone: no other command —
                        // read or write — runs in between. See `command_gate`.
                        // A queued WAIT counts the replicas that have what was
                        // written before this EXEC: each one's target taken after
                        // a hub barrier, as WAIT takes it outside a transaction.
                        // Taken here, before the gates: nothing waits inside them.
                        let wait_targets = if commands::transaction::queues_wait(&tx.queue)
                            && repl_state
                                .connected_replicas
                                .load(std::sync::atomic::Ordering::Relaxed)
                                > 0
                        {
                            let (barrier_tx, barrier_rx) = tokio::sync::oneshot::channel();
                            if hub_tx
                                .send(crate::replication::HubMsg::Barrier(barrier_tx))
                                .is_ok()
                            {
                                let _ = barrier_rx.await;
                            }
                            Some(repl_state.wait_targets())
                        } else {
                            None
                        };
                        // The test hook that holds a write up before its gates
                        // (`pause::test_stall_before_the_gate`).
                        #[cfg(debug_assertions)]
                        for queued in &tx.queue {
                            let queued: Vec<&[u8]> = queued.iter().map(Vec::as_slice).collect();
                            crate::pause::test_stall_before_the_gate(&queued);
                        }
                        let _alone = crate::command_gate::enter_alone();
                        // And as one write: a snapshot, a backup or a full sync cuts
                        // before it or after it, never between two of its commands
                        // (#148). The writes it runs are inside this one.
                        let _whole = crate::write_gate::enter();
                        // A `CLIENT PAUSE` set since it passed the pause
                        // check: out of the gates, read again, and held by
                        // that check, the transaction as it was (#629). See
                        // `pause::pause_clients`.
                        if crate::pause::writes_must_check(routed.at())
                            && crate::pause::exec_held_in_gate(&tx.queue)
                        {
                            redispatch = true;
                            continue;
                        }
                        // And to replicas and the AOF as one: its writes in the
                        // stream between a `MULTI` and an `EXEC`, its records
                        // written together (#172). Dropped first, while the
                        // gates are still held.
                        let _propagation = crate::replication::PropagationGroup::begin(
                            &repl_state,
                            &hub_tx,
                            &aof_tx,
                        );
                        // A `MIGRATE` is moving one of its keys, or its keys
                        // have left since it was routed (#331): it is given up
                        // whole. See `routing::exec_refusal_in_gate`.
                        let refused = crate::cluster::routing::exec_refusal_in_gate(
                            &crate::cluster::routing::Caller {
                                cluster: &cluster_state,
                                registry: &client_registry,
                                client_id,
                                store: &store,
                                db: selected_db,
                            },
                            &tx.queue,
                            routed,
                        );
                        if refused.is_some()
                            || dirty_flag.load(std::sync::atomic::Ordering::Acquire)
                        {
                            watch_registry.as_ref().unwatch_all(
                                &tx.watched_keys
                                    .iter()
                                    .map(|_| Arc::clone(&dirty_flag))
                                    .collect::<Vec<_>>(),
                            );
                            tx.reset();
                            dirty_flag.store(false, std::sync::atomic::Ordering::Release);
                            // RESP3 has a dedicated null type (`_`); a RESP2-style `*-1` null
                            // array is not guaranteed to be recognized as null by a strict RESP3
                            // parser (redis-py's, e.g., parses it as an empty array instead),
                            // which breaks WATCH-abort detection for RESP3 clients entirely.
                            if let Some(refusal) = refused {
                                refusal
                            } else if resp_version == 3 {
                                crate::resp::write::resp_null_resp3()
                            } else {
                                crate::resp::write::resp_null_array()
                            }
                        } else if let Some(sets) =
                            exec_fast_apply_sets(tx.watched_keys.is_empty(), &tx.queue)
                                // The fast path writes without going through the
                                // per-command ACL check. A user with any
                                // restriction takes the generic path, where each
                                // queued command is checked against the rules in
                                // force now — not the ones in force when it was
                                // queued.
                                .filter(|_| !key_restricted && !cmd_restricted)
                        {
                            // ── Lock-held fast-apply path ────────────────────────────────────
                            // The generic path checks `dirty_flag` unlocked, then dispatches the
                            // queued write through the normal per-command path, which re-acquires
                            // the shard lock internally — there's a real gap between "checked
                            // clean" and "committed" during which another connection's write (on
                            // a different worker thread) can land, get lost by neither side ever
                            // observing the other. That's the lost-update race this closes for the
                            // common single/simple-multi-key CAS shape: acquire every affected
                            // shard's write lock up front (sorted by address so two concurrent
                            // fast-apply EXECs can't deadlock on each other), verify `dirty_flag`
                            // *while holding them*, and only then mutate — so no other writer to
                            // any of these shards can possibly interleave between the check and
                            // the commit. We can't just hold the lock and call the normal
                            // per-command dispatch path here: it would try to re-acquire the same
                            // (non-reentrant) shard lock and deadlock against itself. So this path
                            // applies the mutation directly, then replays the exact same
                            // replication/AOF/watch-notify/monitor/tracking side effects via
                            // `apply_write_side_effects` (shared with the normal path, not a
                            // hand-duplicated copy) so nothing observable differs except the race
                            // being closed.
                            use std::sync::atomic::Ordering as AtomicOrdering;

                            let mut shard_ptrs: Vec<usize> = Vec::new();
                            let mut shards: Vec<&store::Shard> = Vec::new();
                            for (db_idx, key) in tx.watched_keys.iter() {
                                let shard = store::get_shard(&store[*db_idx], key);
                                let ptr = Arc::as_ptr(shard) as usize;
                                if !shard_ptrs.contains(&ptr) {
                                    shard_ptrs.push(ptr);
                                    shards.push(shard);
                                }
                            }
                            for (key, _) in sets.iter() {
                                let shard = store::get_shard(&store[selected_db], key);
                                let ptr = Arc::as_ptr(shard) as usize;
                                if !shard_ptrs.contains(&ptr) {
                                    shard_ptrs.push(ptr);
                                    shards.push(shard);
                                }
                            }
                            let mut order: Vec<usize> = (0..shards.len()).collect();
                            order.sort_by_key(|&i| shard_ptrs[i]);

                            // Hold the write gate across the mutation and its side effects,
                            // like any other write (see `write_gate`). Taken before the
                            // shard locks: gate first, shards second, everywhere.
                            let _write_gate = crate::write_gate::enter();
                            // …and, ahead of the shard locks too, the order of
                            // these keys' writes in the stream (`write_order`).
                            let _write_order = crate::write_order::lock_keys(
                                selected_db,
                                sets.iter().map(|(key, _)| key.as_bytes()),
                            );
                            let mut guards: Vec<(usize, _)> = order
                                .iter()
                                .map(|&i| (shard_ptrs[i], shards[i].write()))
                                .collect();

                            // A handoff that set its pause before the gates were
                            // taken has refused this transaction already
                            // (`routing::exec_refusal_in_gate`); one set since waits
                            // for the write gate before it takes its cut.
                            if dirty_flag.load(AtomicOrdering::Acquire) {
                                drop(guards);
                                watch_registry.as_ref().unwatch_all(
                                    &tx.watched_keys
                                        .iter()
                                        .map(|_| Arc::clone(&dirty_flag))
                                        .collect::<Vec<_>>(),
                                );
                                tx.reset();
                                dirty_flag.store(false, AtomicOrdering::Release);
                                if resp_version == 3 {
                                    crate::resp::write::resp_null_resp3()
                                } else {
                                    crate::resp::write::resp_null_array()
                                }
                            } else {
                                // Each SET is a use, and a modification, of its
                                // key, as the same SET is outside a transaction
                                // (it went unrecorded here).
                                let _access = crate::eviction::recording().then(|| {
                                    crate::store::AccessScope::open(crate::eviction::write_stamp(
                                        std::time::Instant::now(),
                                    ))
                                });
                                for (key, value) in sets.iter() {
                                    let shard = store::get_shard(&store[selected_db], key);
                                    let ptr = Arc::as_ptr(shard) as usize;
                                    if let Some((_, guard)) =
                                        guards.iter_mut().find(|(p, _)| *p == ptr)
                                    {
                                        drop(guard.set_str_expiring(&**key, value, None));
                                    }
                                    // Notify while STILL HOLDING this key's shard lock. Doing this
                                    // after `drop(guards)` below would reopen the exact race this
                                    // path exists to close: another fast-apply EXEC could acquire
                                    // the now-free lock and check `dirty_flag` before this notify
                                    // sets it, observe clean, and overwrite this write. notify()
                                    // only touches the (separate) watch-registry lock, so calling
                                    // it here cannot deadlock against the shard lock we're holding.
                                    watch_registry.as_ref().notify(selected_db, key.as_bytes());
                                }
                                // A plain SET takes the key's time to live away, in
                                // the same step as it writes the value. Every
                                // shard is let go of before what a SET wrote over
                                // is announced (`store::unlock_together`).
                                store::unlock_together(guards.into_iter().map(|(_, guard)| guard));

                                let count = sets.len();
                                let mut exec_out = format!("*{count}\r\n").into_bytes();
                                for (key, value) in sets.iter() {
                                    let raw_cmd =
                                        [b"SET".to_vec(), key.clone().into_bytes(), value.clone()];
                                    let cmd_ctx = Ctx {
                                        cmd: raw_cmd.iter().map(|v| v.as_slice()).collect(),
                                        store: &store,
                                        lastsave: &lastsave,
                                        selected_db: &mut selected_db,
                                        aof_tx: &aof_tx,
                                        aof_enabled,
                                        config: &config,
                                        started_at: &started_at,
                                        index_store: &index_store,
                                        dict_store: &dict_store,
                                        wait_table: &wait_table,
                                        ts_index: &ts_index,
                                        pubsub: &pubsub,
                                        hub_tx: &hub_tx,
                                        repl_state: &repl_state,
                                        watch_registry: watch_registry.as_ref(),
                                        client_id,
                                        client_registry: &client_registry,
                                        resp: resp_version,
                                        acl_store: &acl_store,
                                        acl_log: &acl_log,
                                        slowlog: &slowlog,
                                        latency: &latency,
                                        compaction_tx: &compaction_tx,
                                        cluster: &cluster_state,
                                        bypass_cluster_check: false,
                                        apply_replication: false,
                                        skip_write_side_effects: false,
                                        peer_addr: &peer_addr,
                                        monitor_registry: &monitor_registry,
                                        authenticated_user: authenticated_user
                                            .as_deref()
                                            .unwrap_or("default"),
                                        tracking_table: &tracking_table,
                                        blocking: None,
                                    };
                                    crate::keyspace_events::notify(
                                        cmd_ctx.pubsub,
                                        *cmd_ctx.selected_db,
                                        crate::keyspace_events::KS_STRING,
                                        "set",
                                        key,
                                    );
                                    commands::handler::apply_write_side_effects(
                                        &cmd_ctx, "SET", b"+OK\r\n",
                                    );
                                    exec_out.extend_from_slice(b"+OK\r\n");
                                }

                                watch_registry.as_ref().unwatch_all(
                                    &tx.watched_keys
                                        .iter()
                                        .map(|_| Arc::clone(&dirty_flag))
                                        .collect::<Vec<_>>(),
                                );
                                tx.reset();
                                dirty_flag.store(false, AtomicOrdering::Release);
                                exec_out
                            }
                        } else {
                            let queued = std::mem::take(&mut tx.queue);
                            let count = queued.len();
                            let mut exec_out = format!("*{count}\r\n").into_bytes();

                            // A plain FLUSHALL here is not counted as lazily freed.
                            let _queued = crate::lazyfree::running_queued();
                            // What the queued commands write to the ACL log is
                            // in context `multi`, as in Redis.
                            let _context = crate::acl::log_context("multi");
                            for queued_cmd in queued {
                                let queued_name = queued_cmd
                                    .first()
                                    .map(|name| String::from_utf8_lossy(name).to_ascii_uppercase())
                                    .unwrap_or_default();
                                // SUBSCRIBE and its kind, queued: see the tokio loop (#23).
                                if crate::pubsub::is_subscription_command(&queued_name) {
                                    let args: Vec<&[u8]> =
                                        queued_cmd.iter().map(|b| b.as_slice()).collect();
                                    let subs = subscriptions.get_or_insert_with(|| {
                                        open_subscriptions(
                                            &pubsub,
                                            &client_registry,
                                            client_id,
                                            &stream,
                                            &write_guard,
                                        )
                                    });
                                    exec_out.extend_from_slice(&subs.handle(&args, resp_version));
                                    if subs.total() == 0 {
                                        subscriptions = None;
                                    }
                                    continue;
                                }
                                // Those the connection loop answers itself outside a
                                // transaction, answered as Redis's EXEC answers them
                                // (#550, #499).
                                if matches!(
                                    queued_name.as_str(),
                                    "AUTH" | "HELLO" | "UNWATCH" | "MONITOR" | "WAIT" | "WAITAOF"
                                ) {
                                    let args: Vec<&[u8]> =
                                        queued_cmd.iter().map(|b| b.as_slice()).collect();
                                    let reply = if queued_name == "AUTH" {
                                        commands::login::Login {
                                            acl_store: &acl_store,
                                            acl_log: &acl_log,
                                            client_registry: &client_registry,
                                            client_id,
                                            peer_addr: &peer_addr,
                                            user: &mut authenticated_user,
                                            key_restricted: &mut key_restricted,
                                            cmd_restricted: &mut cmd_restricted,
                                        }
                                        .auth(&args)
                                    } else if queued_name == "HELLO" {
                                        commands::login::Login {
                                            acl_store: &acl_store,
                                            acl_log: &acl_log,
                                            client_registry: &client_registry,
                                            client_id,
                                            peer_addr: &peer_addr,
                                            user: &mut authenticated_user,
                                            key_restricted: &mut key_restricted,
                                            cmd_restricted: &mut cmd_restricted,
                                        }
                                        .hello(
                                            &args,
                                            &mut resp_version,
                                            &repl_state,
                                        )
                                    } else {
                                        commands::transaction::connection_reply_in_exec(
                                            &queued_name,
                                            &args,
                                            &commands::transaction::InExec {
                                                acl_store: &acl_store,
                                                acl_log: &acl_log,
                                                user: authenticated_user
                                                    .as_deref()
                                                    .unwrap_or("default"),
                                                peer_addr: &peer_addr,
                                                client_registry: &client_registry,
                                                client_id,
                                                repl_state: &repl_state,
                                                wait_targets: wait_targets.as_deref(),
                                            },
                                        )
                                        .unwrap_or_default()
                                    };
                                    crate::cmdstats::record(
                                        &queued_name,
                                        &args,
                                        &reply,
                                        std::time::Duration::ZERO,
                                    );
                                    exec_out.extend_from_slice(&reply);
                                    continue;
                                }
                                let raw_cmd = queued_cmd.clone();
                                let _exec_slices: Vec<&[u8]> =
                                    queued_cmd.iter().map(|b| b.as_slice()).collect();

                                #[cfg(feature = "lua")]
                                let (resp, elapsed_us) = {
                                    let cmd_start = std::time::Instant::now();
                                    let r = commands::execute_command(Ctx {
                                        cmd: _exec_slices,
                                        store: &store,
                                        lastsave: &lastsave,
                                        selected_db: &mut selected_db,
                                        aof_tx: &aof_tx,
                                        aof_enabled,
                                        config: &config,
                                        started_at: &started_at,
                                        index_store: &index_store,
                                        dict_store: &dict_store,
                                        wait_table: &wait_table,
                                        ts_index: &ts_index,
                                        pubsub: &pubsub,
                                        hub_tx: &hub_tx,
                                        repl_state: &repl_state,
                                        watch_registry: watch_registry.as_ref(),
                                        client_id,
                                        client_registry: &client_registry,
                                        resp: resp_version,
                                        acl_store: &acl_store,
                                        acl_log: &acl_log,
                                        slowlog: &slowlog,
                                        latency: &latency,
                                        compaction_tx: &compaction_tx,
                                        cluster: &cluster_state,
                                        bypass_cluster_check: false,
                                        apply_replication: false,
                                        skip_write_side_effects: false,
                                        peer_addr: &peer_addr,
                                        monitor_registry: &monitor_registry,
                                        authenticated_user: authenticated_user
                                            .as_deref()
                                            .unwrap_or("default"),
                                        tracking_table: &tracking_table,
                                        blocking: None,
                                    });
                                    (r, cmd_start.elapsed().as_micros() as u64)
                                };

                                #[cfg(not(feature = "lua"))]
                                let (resp, elapsed_us) = {
                                    let cmd_start = std::time::Instant::now();
                                    let queued_borrowed: Vec<&[u8]> =
                                        queued_cmd.iter().map(|b| b.as_slice()).collect();
                                    let r = commands::execute_command(Ctx {
                                        cmd: queued_borrowed,
                                        store: &store,
                                        lastsave: &lastsave,
                                        selected_db: &mut selected_db,
                                        aof_tx: &aof_tx,
                                        aof_enabled,
                                        config: &config,
                                        started_at: &started_at,
                                        index_store: &index_store,
                                        dict_store: &dict_store,
                                        wait_table: &wait_table,
                                        ts_index: &ts_index,
                                        pubsub: &pubsub,
                                        hub_tx: &hub_tx,
                                        repl_state: &repl_state,
                                        watch_registry: watch_registry.as_ref(),
                                        client_id,
                                        client_registry: &client_registry,
                                        resp: resp_version,
                                        acl_store: &acl_store,
                                        acl_log: &acl_log,
                                        slowlog: &slowlog,
                                        latency: &latency,
                                        compaction_tx: &compaction_tx,
                                        cluster: &cluster_state,
                                        bypass_cluster_check: false,
                                        apply_replication: false,
                                        skip_write_side_effects: false,
                                        peer_addr: &peer_addr,
                                        monitor_registry: &monitor_registry,
                                        authenticated_user: authenticated_user
                                            .as_deref()
                                            .unwrap_or("default"),
                                        tracking_table: &tracking_table,
                                        blocking: None,
                                    });
                                    (r, cmd_start.elapsed().as_micros() as u64)
                                };

                                if elapsed_us >= slowlog.threshold_us() {
                                    slowlog.record(
                                        &raw_cmd,
                                        elapsed_us,
                                        &peer_addr,
                                        // The name now: a queued CLIENT SETNAME
                                        // or HELLO may have changed it.
                                        client_registry
                                            .get(client_id)
                                            .map(|info| info.name.clone())
                                            .unwrap_or_default(),
                                    );
                                }

                                exec_out.extend_from_slice(&resp);
                            }

                            watch_registry.as_ref().unwatch_all(
                                &tx.watched_keys
                                    .iter()
                                    .map(|_| Arc::clone(&dirty_flag))
                                    .collect::<Vec<_>>(),
                            );
                            tx.reset();
                            dirty_flag.store(false, std::sync::atomic::Ordering::Release);
                            exec_out
                        }
                    }
                }

                // AUTH and HELLO: inside MULTI they are queued, and run
                // when EXEC runs the transaction, as in Redis (#550).
                "AUTH" if !tx.active => commands::login::Login {
                    acl_store: &acl_store,
                    acl_log: &acl_log,
                    client_registry: &client_registry,
                    client_id,
                    peer_addr: &peer_addr,
                    user: &mut authenticated_user,
                    key_restricted: &mut key_restricted,
                    cmd_restricted: &mut cmd_restricted,
                }
                .auth(&cmd),

                "HELLO" if !tx.active => {
                    let reply = commands::login::Login {
                        acl_store: &acl_store,
                        acl_log: &acl_log,
                        client_registry: &client_registry,
                        client_id,
                        peer_addr: &peer_addr,
                        user: &mut authenticated_user,
                        key_restricted: &mut key_restricted,
                        cmd_restricted: &mut cmd_restricted,
                    }
                    .hello(&cmd, &mut resp_version, &repl_state);
                    // Counted here: the commands below are not.
                    crate::cmdstats::record("HELLO", &cmd, &reply, std::time::Duration::ZERO);
                    out_buf.extend_from_slice(&reply);
                    parse_offset += consumed;
                    continue;
                }

                // WAITAOF and WAIT: inside MULTI they are queued, and EXEC
                // answers them without waiting, as in Redis (#499).
                "WAITAOF" if !tx.active => {
                    if cmd.len() < 4 {
                        b"-ERR wrong number of arguments for 'waitaof' command\r\n".to_vec()
                    } else if !aof_enabled
                        && !crate::aof::AOF_ENABLED.load(std::sync::atomic::Ordering::Relaxed)
                    {
                        // Nothing goes to an AOF, so nothing is on disk by
                        // one: it answered that the write was (#137). On at
                        // the start, or turned on since by `CONFIG SET`.
                        let num_local = std::str::from_utf8(cmd[1])
                            .ok()
                            .and_then(|s| s.parse::<i64>().ok())
                            .unwrap_or(0);
                        if num_local != 0 {
                            b"-ERR WAITAOF cannot be used when numlocal is set but appendonly is disabled.\r\n"
                                .to_vec()
                        } else {
                            b"*2\r\n:0\r\n:0\r\n".to_vec()
                        }
                    } else {
                        let timeout_ms: u64 =
                            std::str::from_utf8(cmd.get(3).copied().unwrap_or(b"0"))
                                .ok()
                                .and_then(|s| s.parse().ok())
                                .unwrap_or(0);

                        let target =
                            crate::aof::AOF_WRITTEN.load(std::sync::atomic::Ordering::Relaxed);

                        crate::aof::request_flush();

                        let deadline = tokio::time::Instant::now()
                            + tokio::time::Duration::from_millis(if timeout_ms == 0 {
                                u64::MAX
                            } else {
                                timeout_ms
                            });
                        let role_epoch = crate::commands::blocking::role_changes(&repl_state);

                        let waited = unless_gone(
                            async {
                                loop {
                                    // Ended, as every blocked client is, when
                                    // this node becomes a replica (#591).
                                    if crate::commands::blocking::role_changes(&repl_state)
                                        != role_epoch
                                    {
                                        break crate::commands::blocking::ROLE_CHANGED.to_vec();
                                    }
                                    let fsynced = crate::aof::AOF_FSYNCED
                                        .load(std::sync::atomic::Ordering::Relaxed);
                                    if fsynced >= target || tokio::time::Instant::now() >= deadline
                                    {
                                        break if fsynced >= target {
                                            b"*2\r\n:1\r\n:0\r\n".to_vec()
                                        } else {
                                            b"*2\r\n:0\r\n:0\r\n".to_vec()
                                        };
                                    }
                                    // tokio-uring submits queued I/O when the worker
                                    // parks. A busy yield loop can prevent that.
                                    tokio::time::sleep(tokio::time::Duration::from_millis(1)).await;
                                }
                            },
                            &peer_watch,
                        )
                        .await;
                        match waited {
                            Some(reply) if reply == crate::commands::blocking::ROLE_CHANGED => {
                                out_buf.extend_from_slice(&reply);
                                quit_requested = true;
                                break;
                            }
                            Some(reply) => reply,
                            // The client has gone: there is nobody to answer.
                            None => {
                                quit_requested = true;
                                break;
                            }
                        }
                    }
                }

                "WAIT" if !tx.active => {
                    match crate::replication::wait_args(&cmd, repl_state.is_slave()) {
                        Err(refusal) => refusal,
                        Ok((wanted, timeout_ms)) => {
                            // A blocked client while it waits, as in Redis:
                            // `b` in CLIENT LIST, counted in
                            // `blocked_clients`, and ended by CLIENT UNBLOCK.
                            let (unblock_tx, unblock_rx) = tokio::sync::oneshot::channel();
                            let _blocked = (wanted > 0).then(|| {
                                client_registry.blocked_in(client_id, unblock_tx, timeout_ms > 0)
                            });
                            let waited = unless_gone(
                                crate::replication::wait_for_replicas(
                                    &repl_state,
                                    &hub_tx,
                                    wanted,
                                    timeout_ms,
                                    unblock_rx,
                                ),
                                &peer_watch,
                            )
                            .await;
                            match waited {
                                Some(end) if end.close => {
                                    // This master became a replica: told so,
                                    // and closed, as Redis closes it.
                                    out_buf.extend_from_slice(&end.reply);
                                    parse_offset += consumed;
                                    quit_requested = true;
                                    break;
                                }
                                Some(end) => end.reply,
                                // The client has gone: there is nobody to answer.
                                None => {
                                    quit_requested = true;
                                    break;
                                }
                            }
                        }
                    }
                }

                _ if tx.active => {
                    // Inside a transaction — queue, don't execute. In a
                    // cluster the command is routed now: one that belongs to
                    // another node is refused, and takes the transaction
                    // with it.
                    //
                    // So is one that is no command at all, or has the wrong
                    // number of arguments, or arrives while a script has the
                    // server busy.
                    let refusal =
                        commands::transaction::queue_refusal(&cmd_name, &cmd).or_else(|| {
                            crate::cluster::routing::queue_refusal(
                                &crate::cluster::routing::Caller {
                                    cluster: &cluster_state,
                                    registry: &client_registry,
                                    client_id,
                                    store: &store,
                                    db: selected_db,
                                },
                                &cmd,
                            )
                        });
                    match refusal {
                        Some(refusal) => {
                            tx.aborted = true;
                            refusal
                        }
                        None => {
                            tx.queue.push(cmd.iter().map(|s| s.to_vec()).collect());
                            b"+QUEUED\r\n".to_vec()
                        }
                    }
                }

                // Fallthrough: normal command that happened to match
                // needs_slow_path (e.g. AUTH when already authenticated
                // but first byte matched 'a').
                _ => {
                    let raw_cmd = cmd.clone();

                    #[cfg(feature = "lua")]
                    let (result, elapsed_us) =
                        if crate::commands::lua_command_runs_long_sync_vm(cmd.as_slice()) {
                            // Made once for the connection and kept: it is two dozen shared
                            // handles, each counted up to copy and down to drop, and a script
                            // needs none of them copied to run on this thread. Made again if
                            // the connection has become another user since.
                            let user_now = authenticated_user.as_deref().unwrap_or("default");
                            if lua_env
                                .as_ref()
                                .is_some_and(|env| env.authenticated_user != user_now)
                            {
                                lua_env = None;
                            }
                            let env = &*lua_env.get_or_insert_with(|| {
                                crate::lua_vm_blocking::ClientExecEnv::snapshot(
                                    &store,
                                    &lastsave,
                                    crate::lua_vm_blocking::AofBridge::Tokio(aof_tx.clone()),
                                    &config,
                                    &started_at,
                                    &index_store,
                                    &dict_store,
                                    &wait_table,
                                    &ts_index,
                                    &pubsub,
                                    &hub_tx,
                                    &repl_state,
                                    &watch_registry,
                                    &client_registry,
                                    &acl_store,
                                    &acl_log,
                                    &slowlog,
                                    &latency,
                                    &compaction_tx,
                                    &cluster_state,
                                    &monitor_registry,
                                    &tracking_table,
                                    &peer_addr,
                                    client_id,
                                    authenticated_user.as_deref().unwrap_or("default"),
                                )
                            });
                            crate::lua_vm_blocking::run_lua_vm_blocking(
                                cmd.as_slice(),
                                &mut selected_db,
                                env,
                                aof_enabled,
                                resp_version,
                            )
                            .await
                        } else {
                            let cmd_start = std::time::Instant::now();
                            let r = commands::execute_command(Ctx {
                                cmd,
                                store: &store,
                                lastsave: &lastsave,
                                selected_db: &mut selected_db,
                                aof_tx: &aof_tx,
                                aof_enabled,
                                config: &config,
                                started_at: &started_at,
                                index_store: &index_store,
                                dict_store: &dict_store,
                                wait_table: &wait_table,
                                ts_index: &ts_index,
                                pubsub: &pubsub,
                                hub_tx: &hub_tx,
                                repl_state: &repl_state,
                                watch_registry: watch_registry.as_ref(),
                                client_id,
                                client_registry: &client_registry,
                                resp: resp_version,
                                acl_store: &acl_store,
                                acl_log: &acl_log,
                                slowlog: &slowlog,
                                latency: &latency,
                                compaction_tx: &compaction_tx,
                                cluster: &cluster_state,
                                bypass_cluster_check: false,
                                apply_replication: false,
                                skip_write_side_effects: false,
                                peer_addr: &peer_addr,
                                monitor_registry: &monitor_registry,
                                authenticated_user: authenticated_user
                                    .as_deref()
                                    .unwrap_or("default"),
                                tracking_table: &tracking_table,
                                blocking: None,
                            });
                            (r, cmd_start.elapsed().as_micros() as u64)
                        };

                    #[cfg(not(feature = "lua"))]
                    let (result, elapsed_us) = {
                        let cmd_start = std::time::Instant::now();
                        let r = commands::execute_command(Ctx {
                            cmd,
                            store: &store,
                            lastsave: &lastsave,
                            selected_db: &mut selected_db,
                            aof_tx: &aof_tx,
                            aof_enabled,
                            config: &config,
                            started_at: &started_at,
                            index_store: &index_store,
                            dict_store: &dict_store,
                            wait_table: &wait_table,
                            ts_index: &ts_index,
                            pubsub: &pubsub,
                            hub_tx: &hub_tx,
                            repl_state: &repl_state,
                            watch_registry: watch_registry.as_ref(),
                            client_id,
                            client_registry: &client_registry,
                            resp: resp_version,
                            acl_store: &acl_store,
                            acl_log: &acl_log,
                            slowlog: &slowlog,
                            latency: &latency,
                            compaction_tx: &compaction_tx,
                            cluster: &cluster_state,
                            bypass_cluster_check: false,
                            apply_replication: false,
                            skip_write_side_effects: false,
                            peer_addr: &peer_addr,
                            monitor_registry: &monitor_registry,
                            authenticated_user: authenticated_user.as_deref().unwrap_or("default"),
                            tracking_table: &tracking_table,
                            blocking: None,
                        });
                        (r, cmd_start.elapsed().as_micros() as u64)
                    };

                    // Not a write a pause sent back: it is timed when it runs.
                    if elapsed_us >= slowlog.threshold_us() && !crate::pause::is_held(&result) {
                        let client_name = client_registry
                            .get(client_id)
                            .map(|info| info.name.clone())
                            .unwrap_or_default();

                        slowlog.record(&raw_cmd, elapsed_us, &peer_addr, client_name);
                    }

                    result
                }
            };
            // A write that got past a `CLIENT PAUSE` before it was set, and
            // went no further (`pause::HELD_IN_GATE`): read again, and held.
            if crate::pause::is_held(&response) {
                redispatch = true;
                continue;
            }
            // The other commands answered here, and not by `execute_command`,
            // are counted as well (`HELLO` counts itself, as it replies in
            // several places).
            if !queued_here
                && matches!(
                    cmd_name.as_str(),
                    "DISCARD" | "WATCH" | "UNWATCH" | "RESET" | "AUTH"
                )
            {
                // None of them has subcommands, so the name is all `record` needs.
                crate::cmdstats::record(
                    &cmd_name,
                    &[cmd_name.as_bytes()],
                    &response,
                    std::time::Duration::ZERO,
                );
            }
            // MONITOR sees a transaction as it ran: `MULTI`, the commands —
            // each shown as it was run — and then `EXEC`.
            if let Some(word) = &transaction_word {
                crate::monitor::feed(
                    &monitor_registry,
                    &[word.as_slice()],
                    selected_db,
                    &peer_addr,
                );
                // And they are commands, to be counted.
                crate::cmdstats::record(
                    &cmd_name,
                    &[word.as_slice()],
                    &response,
                    std::time::Duration::ZERO,
                );
            }
            out_buf.extend_from_slice(&response);
            parse_offset += consumed;
        }
        private_query_buffer |= progress.take_private_query_buffer();
        if private_query_buffer && !was_private_query_buffer {
            last_query_buffer_activity = Instant::now();
        }
        let reserve_hint = progress.take_reserve_hint();
        if private_query_buffer
            && !was_private_query_buffer
            && parse_buf.capacity() < resp::parse::PRIVATE_QUERY_BUFFER_MIN_CAPACITY
        {
            parse_buf.reserve(
                resp::parse::PRIVATE_QUERY_BUFFER_MIN_CAPACITY.saturating_sub(parse_buf.len()),
            );
        }
        if reserve_hint > parse_buf.capacity() {
            parse_buf.reserve(reserve_hint.saturating_sub(parse_buf.len()));
        }
        query_buffer_peak = query_buffer_peak.max(reserve_hint);
        reply_gate.settle(&mut out_buf);
        crate::tracking::after_command(
            &tracking_table,
            &client_registry,
            client_id,
            &activity,
            &mut out_buf,
        );
        // Told what was wrong with it, and then the connection is closed:
        // there is no telling where in this stream the next request starts.
        if let Some(e) = protocol_error {
            log_verbose!(
                "Client id={client_id}: protocol error: {e} — closing the connection. The \
                 client sent something that is not RESP: often a wrong port, TLS on a \
                 plaintext port, or HTTP"
            );
            out_buf.extend_from_slice(format!("-ERR Protocol error: {e}\r\n").as_bytes());
            quit_requested = true;
        }

        parse_start = parse_offset;
        if parse_start == parse_buf.len() {
            parse_buf.clear();
            parse_start = 0;
            // A buffer that grew to hold one large request is given back at the
            // end of the batch that finished it, rather than kept at that size
            // for the life of the connection. This is the batch boundary: the
            // request has been parsed and answered, no read is in flight, and
            // `parse_buf` is owned by this loop — so rebuilding it cannot
            // invalidate a pending io_uring operation. It happens here even if
            // the client then goes idle, which is what the idle-driven resize
            // above cannot reach: that one only runs after the *next* read.
            if parse_buf.capacity() > BIG_BUFFER {
                parse_buf = Vec::with_capacity(READ_BUFFER);
                query_buffer_peak = 0;
            }
        } else if parse_start > 0 && parse_start > parse_buf.len() / 2 {
            let remaining = parse_buf.len() - parse_start;
            parse_buf.copy_within(parse_start.., 0);
            parse_buf.truncate(remaining);
            parse_start = 0;
        }
        query_buffer.update(
            parse_buf.len().saturating_sub(parse_start),
            parse_buf.capacity().saturating_sub(parse_buf.len()),
            private_query_buffer,
        );

        // Flush output — swap with spare to avoid malloc/free per write cycle.
        // Pushes are no longer drained here; the forwarder task owns them, so
        // they reach the client immediately instead of waiting for the next
        // command. The guard keeps the two writers from interleaving.
        activity.note_flush(out_buf.len(), commands_before);
        activity.note_tx(tx.active.then_some(tx.queue.len()), tx.watched_keys.len());
        // Replies to writes go out once their records are in the AOF (#147).
        if std::mem::take(&mut aof_wait) {
            crate::aof::written(&aof_tx).await;
        }
        if !out_buf.is_empty() {
            std::mem::swap(&mut out_buf, &mut spare_buf);
            crate::stats::TOTAL_NET_OUTPUT_BYTES
                .fetch_add(spare_buf.len() as u64, std::sync::atomic::Ordering::Relaxed);
            crate::stats::record_write();
            let _w = write_guard.lock().await;
            let (res, returned) = stream.write_all(spare_buf).await;
            drop(_w);
            spare_buf = returned;
            spare_buf.clear();
            // Nor is one that grew to hold one large reply.
            if spare_buf.capacity() > BIG_BUFFER {
                spare_buf = Vec::with_capacity(65536);
            }
            res?;
        }
        // The replies to SUBSCRIBE are out: messages may follow them.
        if let Some(subs) = &subscriptions {
            subs.flushed();
        }

        // QUIT: the +OK is on the wire now, so drop the connection.
        if quit_requested {
            return Ok(());
        }

        match connection_handoff {
            None => {}
            Some(ConnectionHandoff::Replica { legacy_sync, psync }) => {
                parse_buf.drain(0..parse_start);

                let listening_port = client_registry
                    .get(client_id)
                    .map(|info| info.replica_listening_port)
                    .filter(|p| *p != 0);
                // A replica's link from here: `flags=S`, `TYPE replica`, as
                // Redis lists it (#595). `CLIENT KILL` shuts its socket, as
                // any client's, which ends the link.
                client_registry.update(client_id, |info| info.flags = "S".to_string());
                // Out of the reactor while the descriptor is surely open.
                drop(peer_watch);
                handle_replica_connection_uring(
                    stream,
                    Arc::clone(&store),
                    Arc::clone(&index_store),
                    hub_tx.clone(),
                    Arc::clone(&repl_state),
                    peer_addr.clone(),
                    legacy_sync,
                    listening_port,
                    psync,
                )
                .await?;

                return Ok(());
            }
        }
    }
    // Release key-restriction slot if this connection held one.
    if key_restricted {
        crate::acl::RESTRICTED_KEY_CLIENTS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
    }
    if cmd_restricted {
        crate::acl::RESTRICTED_CMD_CLIENTS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
    }
    // What was kept for tracking goes with `_guard`.
    Ok(())
}