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
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
// src/commands/streams.rs

use crate::commands::blocking::{self, ParkOutcome};
use crate::commands::ctx::Ctx;
use crate::commands::helpers::{lazy_expire_on_read, parse_utf8};
use crate::commands::stream_extra::{
    self, Approx, IdmpArg, ReadCaps, TrimRefs, TrimTo, claim_effect, setid_effect, trim_stream,
    trim_stream_approx,
};
use crate::keyspace_events::{KS_STREAM, notify};
use crate::replication::script_feed::{effect, effect_of_metadata, effects_begin};
use crate::resp::write::*;
use crate::store;
use crate::store::ValueRef;
use crate::types::{ConsumerGroup, KiviDBValue, PelEntry, StreamEntry, StreamId, StreamInner};
use crate::{read_lock, write_lock};
use ahash::AHashMap;
use parking_lot::RwLock;
use std::collections::BTreeMap;
use std::ops::Bound;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

// ── RESP3 shaping for XREAD / XREADGROUP ─────────────────────────────────────
//
// The reply is a set of `stream-name → entries` results. RESP2 has no map, so
// Redis sends an array of `[name, entries]` pairs; under RESP3 it switches to a
// real map keyed by stream name (`addReplyMapLen` when `c->resp > 2`). Clients
// rely on that: redis-py returns a list of tuples for RESP2 and a dict for
// RESP3, so getting this wrong doesn't just look different, it breaks callers.

/// Effective protocol for the reply being built (honours `redis.setresp`).
#[inline]
fn reply_resp(ctx: &Ctx) -> u8 {
    crate::commands::handler::effective_resp_for_reply(ctx)
}

/// The wire items contributed by one stream's results.
///
/// RESP2 yields a single `[name, entries]` array; RESP3 yields the name and the
/// entries as two adjacent items, which [`stream_results_reply`] then frames as
/// a map. Returning a `Vec` keeps both shapes flowing through the same
/// `flat_map` at each call site.
#[inline]
fn stream_result_items(resp: u8, key: &[u8], entries: Vec<Vec<u8>>) -> Vec<Vec<u8>> {
    if resp >= 3 {
        vec![resp_bulk(key), resp_array(entries)]
    } else {
        vec![resp_array(vec![resp_bulk(key), resp_array(entries)])]
    }
}

/// Frame the collected [`stream_result_items`] as the whole XREAD reply.
#[inline]
fn stream_results_reply(resp: u8, items: Vec<Vec<u8>>) -> Vec<u8> {
    if resp >= 3 {
        resp_map(items)
    } else {
        resp_array(items)
    }
}

// ── handle ───────────────────────────────────────────────────────────────────

/// The keyspace event of a stream command that has just answered `reply`,
/// if what it did is one. (A consumer coming into being or going announces
/// itself: that is not in any reply.)
fn announce(ctx: &Ctx, name: &str, reply: &[u8]) {
    if crate::keyspace_events::KS_FLAGS.load(std::sync::atomic::Ordering::Relaxed) == 0 {
        return;
    }
    let ok = reply.starts_with(b"+OK");
    let some = reply.first() == Some(&b':') && !reply.starts_with(b":0\r\n");
    let sub = |word: &[u8]| {
        ctx.cmd
            .get(1)
            .is_some_and(|sub| sub.eq_ignore_ascii_case(word))
    };
    let (event, key_at) = match name {
        "XADD" if reply.first() == Some(&b'$') && !reply.starts_with(b"$-1") => ("xadd", 1),
        "XDEL" | "XDELEX" | "XACKDEL" if some => ("xdel", 1),
        "XTRIM" if some => ("xtrim", 1),
        "XSETID" if ok => ("xsetid", 1),
        "XGROUP" if sub(b"CREATE") && ok => ("xgroup-create", 2),
        "XGROUP" if sub(b"SETID") && ok => ("xgroup-setid", 2),
        "XGROUP" if sub(b"DESTROY") && some => ("xgroup-destroy", 2),
        "XGROUP" if sub(b"CREATECONSUMER") && some => ("xgroup-createconsumer", 2),
        _ => return,
    };
    // Any bytes: a key that was not UTF-8 had no event.
    if let Some(key) = ctx.cmd.get(key_at).copied() {
        notify(ctx.pubsub, *ctx.selected_db, KS_STREAM, event, key);
    }
}

pub fn handle(ctx: &mut Ctx, name: &str) -> Option<Vec<u8>> {
    let reply = run(ctx, name)?;
    announce(ctx, name, &reply);
    Some(reply)
}

fn run(ctx: &mut Ctx, name: &str) -> Option<Vec<u8>> {
    match name {
        "XADD" => Some(xadd(ctx)),
        "XLEN" => Some(xlen(ctx)),
        "XRANGE" => Some(xrange(ctx)),
        "XREVRANGE" => Some(xrevrange(ctx)),
        "XREAD" => Some(xread(ctx)),
        "XDEL" => Some(xdel(ctx)),
        "XTRIM" => Some(xtrim(ctx)),
        "XSETID" => Some(xsetid(ctx)),
        "XIDMPRECORD" => Some(xidmprecord(ctx)),
        "XGROUP" => Some(xgroup(ctx)),
        "XREADGROUP" => Some(xreadgroup(ctx)),
        "XACK" => Some(xack(ctx)),
        "XNACK" => Some(xnack(ctx)),
        "XPENDING" => Some(xpending(ctx)),
        "XCLAIM" => Some(xclaim(ctx)),
        "XAUTOCLAIM" => Some(xautoclaim(ctx)),
        "XINFO" => Some(xinfo(ctx)),
        "XACKDEL" => Some(xackdel(ctx)),
        "XDELEX" => Some(xdelex(ctx)),
        "XCFGSET" => Some(xcfgset(ctx)),
        _ => None,
    }
}

// ── helpers ───────────────────────────────────────────────────────────────────

/// `XIDMPRECORD key pid iid id` (Redis 8.10): remember that producer `pid`'s
/// idempotent ID `iid` produced the entry `id` already in the stream, as an
/// `XADD … IDMP` would have. The same record again is OK; the iid recorded
/// for another entry is an error.
fn xidmprecord(ctx: &mut Ctx) -> Vec<u8> {
    let cmd = &ctx.cmd;
    if cmd.len() != 5 {
        return resp_error("ERR wrong number of arguments for 'xidmprecord' command");
    }
    let Some(id) = parse_utf8(cmd[4]).and_then(StreamId::parse) else {
        return resp_error("ERR Invalid stream ID specified as stream command argument");
    };
    if cmd[2].is_empty() {
        return resp_error("ERR producer ID must be non-empty");
    }
    if cmd[3].is_empty() {
        return resp_error("ERR idempotent ID must be non-empty");
    }
    let key: &[u8] = cmd[1];
    let (producer, iid) = (cmd[2], cmd[3]);
    let defaults = stream_extra::idmp_defaults(ctx.config);
    let shard = store::get_shard(&ctx.store[*ctx.selected_db], key);
    let stream = match read_lock!(shard).get(key) {
        Some(ValueRef::Stream(s)) => Arc::clone(s),
        Some(_) => {
            return resp_error("WRONGTYPE Operation against a key holding the wrong kind of value");
        }
        None => return resp_error("ERR no such key"),
    };
    let mut inner = stream.write();
    if !inner.entries.contains_key(&id) {
        return resp_error("ERR No such message in stream");
    }
    let recorded = inner
        .idmp
        .producers
        .get(producer)
        .and_then(|p| p.by_iid.get(iid))
        .cloned();
    match recorded {
        Some(same) if same == id => return resp_simple("OK"),
        Some(_) => {
            return resp_error(
                "ERR IID already exists for this producer with a different stream ID",
            );
        }
        None => {}
    }
    stream_extra::idmp_record(&mut inner, producer, Arc::from(iid), id, now_ms(), defaults);
    resp_simple("OK")
}

fn now_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}

fn get_or_create_stream(ctx: &mut Ctx, key: &[u8]) -> Result<Arc<RwLock<StreamInner>>, Vec<u8>> {
    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let mut map = write_lock!(shard);

    match map.get(key) {
        Some(ValueRef::Stream(s)) => Ok(Arc::clone(s)),
        Some(_) => Err(resp_error(
            "WRONGTYPE Operation against a key holding the wrong kind of value",
        )),
        None => {
            let s = Arc::new(RwLock::new(StreamInner::new()));
            map.insert(key, KiviDBValue::Stream(Arc::clone(&s)));
            Ok(s)
        }
    }
}

/// Parse a stream ID for range queries — handles "-" and "+" as bounds,
/// and "ms" (without seq) as "ms-0" for inclusive range starts.
fn parse_range_id_lo(s: &str) -> Option<StreamId> {
    match s {
        "-" => Some(StreamId::min()),
        "+" => Some(StreamId::max()),
        s => StreamId::parse(s).or_else(|| {
            // bare ms without seq → ms-0 as lower bound
            s.parse::<u64>().ok().map(|ms| StreamId::new(ms, 0))
        }),
    }
}

fn parse_range_id_hi(s: &str) -> Option<StreamId> {
    match s {
        "+" => Some(StreamId::max()),
        "-" => Some(StreamId::min()),
        s => {
            // If explicit ms-seq form, use as-is
            if s.contains('-') {
                StreamId::parse(s)
            } else {
                // Bare ms without seq: expand to ms-MAX as inclusive upper bound
                // so XRANGE s 1000 1000 captures 1000-0, 1000-1, 1000-2, etc.
                s.parse::<u64>().ok().map(|ms| StreamId::new(ms, u64::MAX))
            }
        }
    }
}

/// The ID after `id`, if there is one.
fn id_after(id: &StreamId) -> Option<StreamId> {
    match (id.ms, id.seq) {
        (u64::MAX, u64::MAX) => None,
        (ms, u64::MAX) => Some(StreamId::new(ms + 1, 0)),
        (ms, seq) => Some(StreamId::new(ms, seq + 1)),
    }
}

/// The ID before `id`, if there is one.
fn id_preceding(id: &StreamId) -> Option<StreamId> {
    match (id.ms, id.seq) {
        (0, 0) => None,
        (ms, 0) => Some(StreamId::new(ms - 1, u64::MAX)),
        (ms, seq) => Some(StreamId::new(ms, seq - 1)),
    }
}

/// The IDs from `start` to `end`, both included, that a range command's two
/// arguments name; `None` if there are none. Either may be `(id`, for
/// "not this one": the range then starts just after it, or ends just before.
fn id_interval(start: &str, end: &str) -> Result<Option<(StreamId, StreamId)>, Vec<u8>> {
    let invalid = || resp_error("ERR Invalid stream ID specified as stream command argument");
    // `(-` and `(+` mean nothing: there is no ID to leave out.
    let named = |s: &str| !matches!(s, "-" | "+");
    let lo = match start.strip_prefix('(') {
        Some(id) => parse_range_id_lo(id)
            .filter(|_| named(id))
            .ok_or_else(invalid)
            .and_then(|id| {
                id_after(&id).ok_or_else(|| resp_error("ERR invalid start ID for the interval"))
            })?,
        None => parse_range_id_lo(start).ok_or_else(invalid)?,
    };
    let hi = match end.strip_prefix('(') {
        Some(id) => parse_range_id_hi(id)
            .filter(|_| named(id))
            .ok_or_else(invalid)
            .and_then(|id| {
                id_preceding(&id).ok_or_else(|| resp_error("ERR invalid end ID for the interval"))
            })?,
        None => parse_range_id_hi(end).ok_or_else(invalid)?,
    };
    Ok((lo <= hi).then_some((lo, hi)))
}

/// Format a stream entry as the nested RESP array Redis uses:
/// ["id", ["field", "value", "field", "value", ...]]
fn format_entry(id: &StreamId, entry: &StreamEntry) -> Vec<u8> {
    let field_values: Vec<Vec<u8>> = entry
        .fields
        .iter()
        .flat_map(|(f, v)| vec![resp_bulk(f.as_ref()), resp_bulk(v.as_ref())])
        .collect();
    resp_array(vec![
        resp_bulk_str(&id.to_string()),
        resp_array(field_values),
    ])
}

// ── XADD ─────────────────────────────────────────────────────────────────────

/// Where `XADD`'s options end and its ID argument begins, plus the options
/// themselves.
///
/// ```text
/// XADD key [NOMKSTREAM] [KEEPREF | DELREF | ACKED]
///     [IDMPAUTO producer-id | IDMP producer-id idempotent-id]
///     [<MAXLEN | MINID> [= | ~] threshold [LIMIT count]] <* | id>
///     field value [field value ...]
/// ```
/// — the ID is positional but its index depends on which options were given, so
/// it cannot be read from a fixed offset.
///
/// Shared with `replication::script_feed`, which rewrites an auto-generated ID
/// (`*` or `ms-*`) into the concrete one before propagating. That rewrite has to
/// land on the argument this parser consumed as the ID; a second, drifting copy
/// of this scan would silently corrupt the replication stream instead of failing
/// a test. See `xadd_id_index_matches_executor` in `script_feed`.
pub(crate) struct XaddOptions<'a> {
    /// IDMP or IDMPAUTO given more than once.
    pub idmp_twice: bool,
    pub id_index: usize,
    pub nomkstream: bool,
    pub maxlen: Option<u64>,
    pub minid: Option<StreamId>,
    /// What trimming does about pending-list references (Redis 8.2).
    pub trim_refs: TrimRefs,
    /// Idempotent production (Redis 8.6).
    pub idmp: Option<IdmpArg<'a>>,
    /// `~`: trim by whole nodes. See [`Approx`].
    pub approx: bool,
    /// `LIMIT`'s argument, if it was given; negative if it was not a count.
    pub limit: Option<i64>,
}

pub(crate) fn parse_xadd_options<'a>(cmd: &[&'a [u8]]) -> XaddOptions<'a> {
    let mut i = 2usize;
    let mut nomkstream = false;
    let mut maxlen: Option<u64> = None;
    let mut minid: Option<StreamId> = None;
    let mut trim_refs = TrimRefs::default();
    let mut idmp: Option<IdmpArg<'a>> = None;
    let mut idmp_twice = false;
    let mut approx = false;
    let mut limit: Option<i64> = None;

    while i < cmd.len() {
        let tok = std::str::from_utf8(cmd[i])
            .unwrap_or("")
            .to_ascii_uppercase();
        match tok.as_str() {
            "NOMKSTREAM" => {
                nomkstream = true;
                i += 1;
            }
            "KEEPREF" | "DELREF" | "ACKED" => {
                trim_refs = TrimRefs::parse(cmd[i]).unwrap_or_default();
                i += 1;
            }
            "IDMP" if i + 2 < cmd.len() => {
                if idmp.is_some() {
                    idmp_twice = true;
                }
                idmp = Some(IdmpArg::Explicit {
                    producer: cmd[i + 1],
                    iid: cmd[i + 2],
                });
                i += 3;
            }
            "IDMPAUTO" if i + 1 < cmd.len() => {
                if idmp.is_some() {
                    idmp_twice = true;
                }
                idmp = Some(IdmpArg::Auto {
                    producer: cmd[i + 1],
                });
                i += 2;
            }
            "MAXLEN" => {
                i += 1;
                if let Some(b) = cmd.get(i)
                    && (*b == b"~" || *b == b"=")
                {
                    approx = *b == b"~";
                    i += 1;
                }
                maxlen = cmd
                    .get(i)
                    .and_then(|b| std::str::from_utf8(b).ok())
                    .and_then(|s| s.parse().ok());
                i += 1;
            }
            "MINID" => {
                i += 1;
                if let Some(b) = cmd.get(i)
                    && (*b == b"~" || *b == b"=")
                {
                    approx = *b == b"~";
                    i += 1;
                }
                minid = cmd
                    .get(i)
                    .and_then(|b| std::str::from_utf8(b).ok())
                    .and_then(StreamId::parse);
                i += 1;
            }
            "LIMIT" => {
                limit = Some(
                    cmd.get(i + 1)
                        .and_then(|b| std::str::from_utf8(b).ok())
                        .and_then(|s| s.parse::<i64>().ok())
                        .unwrap_or(-1),
                );
                i += 2;
            }
            _ => break,
        }
    }

    XaddOptions {
        id_index: i,
        idmp_twice,
        nomkstream,
        maxlen,
        minid,
        trim_refs,
        idmp,
        approx,
        limit,
    }
}

/// What `LIMIT` and `~` came to, or the error in how they were given.
fn approx_of(approx: bool, limit: Option<i64>) -> Result<Option<Approx>, Vec<u8>> {
    match limit {
        Some(_) if !approx => Err(resp_error(
            "ERR syntax error, LIMIT cannot be used without the special ~ option",
        )),
        Some(n) if n < 0 => Err(resp_error("ERR The LIMIT argument must be >= 0.")),
        Some(n) => Ok(Some(Approx::new(Some(n as u64)))),
        None => Ok(approx.then(|| Approx::new(None))),
    }
}

/// The ID an `XADD` asks for.
enum NewId {
    /// `*`
    Auto,
    /// `ms-*`
    AutoSeq(u64),
    Explicit(StreamId),
}

pub fn xadd(ctx: &mut Ctx) -> Vec<u8> {
    let (key, id_str, id_index, fields, nomkstream, maxlen, minid, trim_refs, idmp, approx) = {
        let cmd = &ctx.cmd;
        if cmd.len() < 5 {
            return resp_error("ERR wrong number of arguments for 'xadd' command");
        }

        let key: Vec<u8> = cmd[1].to_vec();

        let XaddOptions {
            id_index,
            idmp_twice,
            nomkstream,
            maxlen,
            minid,
            trim_refs,
            idmp,
            approx,
            limit,
        } = parse_xadd_options(cmd);
        let approx = match approx_of(approx, limit) {
            Ok(approx) => approx,
            Err(e) => return e,
        };
        let mut i = id_index;

        if idmp_twice {
            return resp_error("ERR syntax error, IDMP/IDMPAUTO specified multiple times");
        }
        match &idmp {
            Some(IdmpArg::Explicit { producer, .. } | IdmpArg::Auto { producer })
                if producer.is_empty() =>
            {
                let which = if matches!(idmp, Some(IdmpArg::Auto { .. })) {
                    "IDMPAUTO"
                } else {
                    "IDMP"
                };
                return resp_error(&format!("ERR {which} requires a non-empty producer ID"));
            }
            Some(IdmpArg::Explicit { iid: [], .. }) => {
                return resp_error("ERR IDMP requires a non-empty idempotent ID");
            }
            _ => {}
        }
        let id_str = match cmd.get(i).and_then(|b| std::str::from_utf8(b).ok()) {
            Some(s) => s.to_string(),
            None => return resp_error("ERR syntax error: missing ID"),
        };
        i += 1;
        // The ID is read before the fields are counted, as in Redis.
        let id_ok = id_str == "*"
            || StreamId::parse(&id_str).is_some()
            || id_str
                .strip_suffix("-*")
                .is_some_and(|ms| ms.parse::<u64>().is_ok());
        if !id_ok {
            return resp_error("ERR Invalid stream ID specified as stream command argument");
        }

        if (cmd.len() - i) < 2 || !(cmd.len() - i).is_multiple_of(2) {
            return resp_error("ERR wrong number of arguments: field-value pairs required");
        }
        type FieldsType = Vec<(Arc<[u8]>, Arc<[u8]>)>;
        let fields: FieldsType = cmd[i..]
            .as_chunks::<2>()
            .0
            .iter()
            .map(|chunk| (Arc::from(chunk[0]), Arc::from(chunk[1])))
            .collect();

        // Owned (producer, idempotent ID): the borrow of `ctx.cmd` ends here.
        let idmp: Option<(Vec<u8>, Arc<[u8]>)> =
            idmp.map(|arg| (arg.producer().to_vec(), arg.iid(&fields)));

        (
            key, id_str, id_index, fields, nomkstream, maxlen, minid, trim_refs, idmp, approx,
        )
        // ← &ctx.cmd borrow ends here, all data moved into owned tuple
    };

    if idmp.is_some() {
        // Idempotency is about not producing an entry twice, so the entry's
        // ID has to be the server's to assign. The exception is an XADD that
        // another node already resolved to a concrete ID: a replica (or the
        // AOF) applying its master's stream, or a slot being migrated here.
        if id_str != "*" && !ctx.apply_replication && !ctx.bypass_cluster_check {
            return resp_error("ERR IDMP/IDMPAUTO can be used only with auto-generated IDs");
        }
    }
    // What this command adds — possibly nothing — and how much a `~` trimmed
    // are recorded for propagation rather than inferred from its reply.
    let recorded = idmp.is_some() || approx.is_some();
    if recorded {
        effects_begin();
    }

    // The ID, before there is a stream to put it in: an `XADD` that fails
    // used to leave an empty stream behind where there had been no key.
    let new_id = if id_str == "*" {
        NewId::Auto
    } else if let Some(ms) = id_str.strip_suffix("-*") {
        match ms.parse() {
            Ok(ms) => NewId::AutoSeq(ms),
            Err(_) => {
                return resp_error("ERR Invalid stream ID specified as stream command argument");
            }
        }
    } else {
        match StreamId::parse(&id_str) {
            Some(id) if id == StreamId::min() => {
                return resp_error("ERR The ID specified in XADD must be greater than 0-0");
            }
            Some(id) => NewId::Explicit(id),
            None => {
                return resp_error("ERR Invalid stream ID specified as stream command argument");
            }
        }
    };

    if nomkstream {
        let db_ref = &ctx.store[*ctx.selected_db];
        let shard = store::get_shard(db_ref, &key);
        let map = read_lock!(shard);
        if !map.contains_key(key.as_slice()) {
            return resp_null_bulk();
        }
    }

    // Now safe — no live borrow of ctx.cmd
    let stream = match get_or_create_stream(ctx, &key) {
        Ok(s) => s,
        Err(e) => return e,
    };

    let mut inner = stream.write();
    let now = now_ms();
    let idmp_defaults = stream_extra::idmp_defaults(ctx.config);

    // A retry of a message this producer already delivered: reply with the
    // entry it produced the first time and add nothing. A replica does not
    // second-guess its master, which has already made this decision.
    if let Some((producer, iid)) = &idmp
        && !ctx.apply_replication
        && !ctx.bypass_cluster_check
        && let Some(existing) =
            stream_extra::idmp_lookup(&mut inner, producer, iid, now, idmp_defaults)
    {
        return resp_bulk_str(&existing.to_string());
    }

    // The next ID is worked out without ever adding to a sequence number
    // that is already the largest there is: that was an overflow, and took
    // the connection with it.
    let smaller = || {
        resp_error(
            "ERR The ID specified in XADD is equal or smaller than the target stream top item",
        )
    };
    let last = inner.last_id.clone();
    let entry_id = match new_id {
        NewId::Auto if now > last.ms => StreamId::new(now, 0),
        NewId::Auto => match id_after(&last) {
            Some(id) => id,
            None => {
                return resp_error(
                    "ERR The stream has exhausted the last possible ID, unable to add more items",
                );
            }
        },
        NewId::AutoSeq(ms) if ms > last.ms => StreamId::new(ms, 0),
        NewId::AutoSeq(ms) if ms == last.ms && last.seq < u64::MAX => {
            StreamId::new(ms, last.seq + 1)
        }
        NewId::AutoSeq(_) => return smaller(),
        NewId::Explicit(id) => id,
    };

    if entry_id <= inner.last_id && inner.last_id != StreamId::min() {
        return resp_error(
            "ERR The ID specified in XADD is equal or smaller than the target stream top item",
        );
    }

    let id_str_out = entry_id.to_string();
    stream_extra::record_append(&mut inner, &fields);
    inner
        .entries
        .insert(entry_id.clone(), StreamEntry { fields });
    inner.last_id = entry_id.clone();
    inner.entries_added += 1;

    if let Some((producer, iid)) = idmp {
        stream_extra::idmp_record(&mut inner, &producer, iid, entry_id, now, idmp_defaults);
    }

    // Trim before releasing the lock
    let mut trim = |to: TrimTo| match approx {
        Some(approx) => trim_stream_approx(&mut inner, &to, trim_refs, approx),
        None => trim_stream(&mut inner, &to, trim_refs),
    };
    if let Some(max) = maxlen {
        trim(TrimTo::MaxLen(max));
    }
    if let Some(min) = minid {
        trim(TrimTo::MinId(min));
    }
    if recorded {
        // Propagate the entry under the ID it was given — idempotency
        // arguments included, so the other side remembers the pair too —
        // and a `~` trim as what it came to.
        let mut parts: Vec<Vec<u8>> = ctx.cmd.iter().map(|b| b.to_vec()).collect();
        parts[id_index] = id_str_out.clone().into_bytes();
        if approx.is_some() {
            stream_extra::exact_trim_args(&mut parts, 2, id_index, &inner, trim_refs);
        }
        effect(parts);
    }
    // Persistent policy trim from XCFGSET MAX-ENTRIES.
    // Applied after the per-XADD trim so both can coexist. The more
    // restrictive of the two wins — if XCFGSET says 100 and XADD says
    // MAXLEN 50, we end up with at most 50.
    if let Some(max) = inner.max_entries {
        trim_stream(&mut inner, &TrimTo::MaxLen(max), TrimRefs::KeepRef);
    }

    // Release write lock before notifying waiters
    drop(inner);
    notify_xread_waiters(ctx, &key);

    resp_bulk_str(&id_str_out)
}

// ── XLEN ─────────────────────────────────────────────────────────────────────

pub fn xlen(ctx: &mut Ctx) -> Vec<u8> {
    let cmd = &ctx.cmd;
    if cmd.len() != 2 {
        return resp_error("ERR wrong number of arguments for 'xlen' command");
    }
    let key: &[u8] = cmd[1];

    let gone = lazy_expire_on_read(ctx.store, *ctx.selected_db, key);

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key).filter(|_| !gone) {
        None => resp_integer(0),
        Some(ValueRef::Stream(s)) => resp_integer(s.read().entries.len() as i64),
        Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
    }
}

// ── XRANGE / XREVRANGE ───────────────────────────────────────────────────────

pub fn xrange(ctx: &mut Ctx) -> Vec<u8> {
    // XRANGE key start end [COUNT count]
    let cmd = &ctx.cmd;
    if cmd.len() < 4 {
        return resp_error("ERR wrong number of arguments for 'xrange' command");
    }
    let key: &[u8] = cmd[1];
    let start_str = std::str::from_utf8(cmd[2]).unwrap_or("-");
    let end_str = std::str::from_utf8(cmd[3]).unwrap_or("+");

    let mut count = usize::MAX;
    let mut i = 4;
    while i < cmd.len() {
        if std::str::from_utf8(cmd[i])
            .unwrap_or("")
            .eq_ignore_ascii_case("COUNT")
        {
            count = cmd
                .get(i + 1)
                .and_then(|b| std::str::from_utf8(b).ok())
                .and_then(|s| s.parse().ok())
                .unwrap_or(usize::MAX);
            i += 2;
        } else {
            i += 1;
        }
    }

    // Nothing in the interval: nothing to return, and no range to ask the
    // map for — it does not take one that ends before it starts.
    let (lo, hi, count) = match id_interval(start_str, end_str) {
        Ok(Some((lo, hi))) => (lo, hi, count),
        Ok(None) => (StreamId::min(), StreamId::min(), 0),
        Err(e) => return e,
    };

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        None => resp_array(vec![]),
        Some(ValueRef::Stream(s)) => {
            let inner = s.read();
            let items: Vec<Vec<u8>> = inner
                .entries
                .range(lo..=hi)
                .take(count)
                .map(|(id, entry)| format_entry(id, entry))
                .collect();
            resp_array(items)
        }
        Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
    }
}

pub fn xrevrange(ctx: &mut Ctx) -> Vec<u8> {
    // XREVRANGE key end start [COUNT count]  (note: end before start)
    let cmd = &ctx.cmd;
    if cmd.len() < 4 {
        return resp_error("ERR wrong number of arguments for 'xrevrange' command");
    }
    let key: &[u8] = cmd[1];
    let end_str = std::str::from_utf8(cmd[2]).unwrap_or("+");
    let start_str = std::str::from_utf8(cmd[3]).unwrap_or("-");

    let mut count = usize::MAX;
    let mut i = 4;
    while i < cmd.len() {
        if std::str::from_utf8(cmd[i])
            .unwrap_or("")
            .eq_ignore_ascii_case("COUNT")
        {
            count = cmd
                .get(i + 1)
                .and_then(|b| std::str::from_utf8(b).ok())
                .and_then(|s| s.parse().ok())
                .unwrap_or(usize::MAX);
            i += 2;
        } else {
            i += 1;
        }
    }

    // Nothing in the interval: nothing to return, and no range to ask the
    // map for — it does not take one that ends before it starts.
    let (lo, hi, count) = match id_interval(start_str, end_str) {
        Ok(Some((lo, hi))) => (lo, hi, count),
        Ok(None) => (StreamId::min(), StreamId::min(), 0),
        Err(e) => return e,
    };

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        None => resp_array(vec![]),
        Some(ValueRef::Stream(s)) => {
            let inner = s.read();
            // BTreeMap::range gives ascending; rev() flips it
            let items: Vec<Vec<u8>> = inner
                .entries
                .range(lo..=hi)
                .rev()
                .take(count)
                .map(|(id, entry)| format_entry(id, entry))
                .collect();
            resp_array(items)
        }
        Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
    }
}

// ── XREAD ────────────────────────────────────────────────────────────────────

/// The ID just below `id`: reading "after" it yields `id` itself.
fn id_before(id: &StreamId) -> StreamId {
    if id.seq > 0 {
        StreamId::new(id.ms, id.seq - 1)
    } else {
        StreamId::new(id.ms.saturating_sub(1), u64::MAX)
    }
}

/// One non-blocking pass of `XREAD`: for each stream, the entries after its
/// ID — at most `count` per stream, and within `caps` across all of them.
fn read_streams(
    ctx: &Ctx,
    resp: u8,
    keys: &[&[u8]],
    after: &[StreamId],
    count: usize,
    caps: ReadCaps,
) -> Vec<Vec<u8>> {
    let mut budget = caps.budget();
    let mut results = Vec::new();
    for (key, after_id) in keys.iter().zip(after) {
        if budget.exhausted() {
            break;
        }
        let db_ref = &ctx.store[*ctx.selected_db];
        let shard = store::get_shard(db_ref, key);
        let map = read_lock!(shard);
        let Some(ValueRef::Stream(stream)) = map.get(key) else {
            continue;
        };
        let inner = stream.read();

        let mut entries: Vec<Vec<u8>> = Vec::new();
        let newer = (Bound::Excluded(after_id.clone()), Bound::Unbounded);
        for (id, entry) in inner.entries.range(newer).take(count) {
            let item = format_entry(id, entry);
            if !budget.admit(item.len()) {
                break;
            }
            entries.push(item);
        }
        // Keys with nothing new are left out of the reply.
        if !entries.is_empty() {
            results.extend(stream_result_items(resp, key, entries));
        }
    }
    results
}

pub fn xread(ctx: &mut Ctx) -> Vec<u8> {
    // XREAD [COUNT count] [MAXCOUNT maxcount] [MAXSIZE maxsize] [BLOCK ms]
    //       STREAMS key [key ...] id [id ...]
    let resp = reply_resp(ctx);
    let cmd = &ctx.cmd;
    if cmd.len() < 4 {
        return resp_error("ERR wrong number of arguments for 'xread' command");
    }

    let mut count: Option<usize> = None;
    let mut caps = ReadCaps::default();
    let mut block_ms: Option<u64> = None;
    let mut i = 1usize;

    while i < cmd.len() {
        let tok = std::str::from_utf8(cmd[i])
            .unwrap_or("")
            .to_ascii_uppercase();
        match tok.as_str() {
            "COUNT" => {
                count = cmd
                    .get(i + 1)
                    .and_then(|b| std::str::from_utf8(b).ok())
                    .and_then(|s| s.parse().ok());
                i += 2;
            }
            "MAXCOUNT" => {
                match ReadCaps::parse_positive("MAXCOUNT", cmd.get(i + 1)) {
                    Ok(n) => caps.max_count = Some(n),
                    Err(e) => return resp_error(&e),
                }
                i += 2;
            }
            "MAXSIZE" => {
                match ReadCaps::parse_positive("MAXSIZE", cmd.get(i + 1)) {
                    Ok(n) => caps.max_size = Some(n),
                    Err(e) => return resp_error(&e),
                }
                i += 2;
            }
            "BLOCK" => {
                block_ms = cmd
                    .get(i + 1)
                    .and_then(|b| std::str::from_utf8(b).ok())
                    .and_then(|s| s.parse().ok());
                i += 2;
            }
            "CLAIM" if i + 1 < cmd.len() => {
                return resp_error(
                    "ERR The CLAIM option is only supported by XREADGROUP. You called XREAD instead.",
                );
            }
            "STREAMS" => {
                i += 1;
                break;
            }
            _ => {
                i += 1;
            }
        }
    }
    if let Err(e) = caps.check_against_count(count) {
        return resp_error(&e);
    }
    let count = count.unwrap_or(usize::MAX);

    // After STREAMS: [key...] [id...]  — equal number of each
    let remaining = cmd.len().saturating_sub(i);
    if remaining < 2 || !remaining.is_multiple_of(2) {
        return resp_error(
            "ERR Unbalanced 'xread' list of streams: for each stream key an ID, '+', or '$' must be specified.",
        );
    }
    let half = remaining / 2;
    let keys: Vec<&[u8]> = cmd[i..i + half].to_vec();
    let ids: Vec<&str> = cmd[i + half..]
        .iter()
        .map(|b| std::str::from_utf8(b).unwrap_or(""))
        .collect();

    // Are we being resumed after a block? If so the IDs were already resolved
    // when the command first arrived and must be reused verbatim — see
    // `BlockState::StreamIds`. Take this before resolving anything.
    let resumed = blocking::take_resume(ctx);
    // The old registrations are dropped here, on every key, not just the one that fired.
    let (carried_ids, carried_deadline) = match blocking::take_state(ctx) {
        Some(blocking::BlockState::StreamIds { ids, deadline, .. }) => (Some(ids), Some(deadline)),
        _ => (None, None),
    };
    let timed_out = matches!(resumed, Some(None));

    // Resolve each ID. "$" means "only entries added after this command";
    // "+" means "the last entry", whatever it is.
    let resolved_ids: Vec<StreamId> = match carried_ids {
        Some(ids) => ids,
        None => keys
            .iter()
            .zip(ids.iter())
            .map(|(key, id_str)| {
                if *id_str == "$" || *id_str == "+" {
                    let db_ref = &ctx.store[*ctx.selected_db];
                    let shard = store::get_shard(db_ref, key);
                    let map = read_lock!(shard);
                    let Some(ValueRef::Stream(s)) = map.get(key) else {
                        return StreamId::min();
                    };
                    let inner = s.read();
                    if *id_str == "$" {
                        inner.last_id.clone()
                    } else {
                        match inner.entries.keys().next_back() {
                            Some(last) => id_before(last),
                            None => inner.last_id.clone(),
                        }
                    }
                } else {
                    StreamId::parse(id_str).unwrap_or(StreamId::min())
                }
            })
            .collect(),
    };

    let results = read_streams(ctx, resp, &keys, &resolved_ids, count, caps);

    if results.is_empty() {
        // Resumed, and the re-read above still found nothing. If the wait
        // timed out, that is the answer. If the stream was written but not
        // with anything to read — an entry added and deleted again in one
        // transaction, the key replaced by something else — the client goes
        // on waiting, as it does in Redis, for the rest of its time.
        if timed_out {
            return resp_null_array();
        }
        if let Some(ms) = block_ms {
            let deadline = carried_deadline.unwrap_or_else(|| {
                blocking::timeout_from_ms(ms).map(|timeout| std::time::Instant::now() + timeout)
            });
            let Some(remaining) = blocking::remaining_time(deadline) else {
                return resp_null_array();
            };
            // Register on all keys FIRST — before the second check.
            // This ensures we cannot miss a notification that arrives
            // between our first read (which found nothing) and registration.
            let mut registered = ctx.wait_table.stream_wait();
            let rxs: Vec<(
                Vec<u8>,
                tokio::sync::oneshot::Receiver<crate::wait_table::Value>,
            )> = keys
                .iter()
                .map(|k| (k.to_vec(), registered.register(k)))
                .collect();

            // SECOND CHECK: re-read immediately after registering.
            // If an XADD landed in the window between our first read and
            // registration, we catch it here and skip the block entirely.
            // This closes the TOCTOU gap.
            let immediate = read_streams(ctx, resp, &keys, &resolved_ids, count, caps);
            if !immediate.is_empty() {
                // Data arrived in the registration window — return it directly.
                // Dropping `registered` unregisters every key.
                return stream_results_reply(resp, immediate);
            }

            // Nothing in the second check either — safe to park now. The
            // re-read on wake is the top of this function running again, which
            // is why the resolved IDs travel with the park.
            return match blocking::park_with_state(
                ctx,
                rxs,
                remaining,
                Some(blocking::BlockState::StreamIds {
                    ids: resolved_ids,
                    deadline,
                    registered,
                }),
            ) {
                ParkOutcome::Parked => Vec::new(),
                ParkOutcome::CannotWait => resp_null_array(),
            };
        }
        return resp_null_array();
    }

    stream_results_reply(resp, results)
}

// ── XDEL ─────────────────────────────────────────────────────────────────────

pub fn xdel(ctx: &mut Ctx) -> Vec<u8> {
    // XDEL key id [id ...]
    let cmd = &ctx.cmd;
    if cmd.len() < 3 {
        return resp_error("ERR wrong number of arguments for 'xdel' command");
    }
    let key: &[u8] = cmd[1];

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        None => resp_integer(0),
        Some(ValueRef::Stream(s)) => {
            let mut inner = s.write();
            let mut removed = 0i64;
            for id_bytes in &cmd[2..] {
                let id_str = std::str::from_utf8(id_bytes).unwrap_or("");
                if let Some(id) = StreamId::parse(id_str)
                    && inner.entries.remove(&id).is_some()
                {
                    removed += 1;
                    if id > inner.max_deleted_id {
                        inner.max_deleted_id = id;
                    }
                }
            }
            resp_integer(removed)
        }
        Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
    }
}

// ── XTRIM ─────────────────────────────────────────────────────────────────────

pub fn xtrim(ctx: &mut Ctx) -> Vec<u8> {
    // XTRIM key <MAXLEN | MINID> [= | ~] threshold [LIMIT count]
    //       [KEEPREF | DELREF | ACKED]
    let cmd = &ctx.cmd;
    if cmd.len() < 4 {
        return resp_error("ERR wrong number of arguments for 'xtrim' command");
    }
    let key: &[u8] = cmd[1];

    let mut i = 3usize;
    // Optional = or ~
    let mut approx = false;
    if let Some(b) = cmd.get(i)
        && (*b == b"=" || *b == b"~")
    {
        approx = *b == b"~";
        i += 1;
    }
    let threshold_str = match cmd.get(i).and_then(|b| std::str::from_utf8(b).ok()) {
        Some(s) => s,
        None => return resp_error("ERR syntax error"),
    };
    // A threshold that does not parse is an error. It used to be read as 0,
    // so `XTRIM s MAXLEN 1O0` — a typo — emptied the stream.
    let to = if cmd[2].eq_ignore_ascii_case(b"MAXLEN") {
        match threshold_str.parse::<u64>() {
            Ok(max) => TrimTo::MaxLen(max),
            Err(_) => return resp_error("ERR value is not an integer or out of range"),
        }
    } else if cmd[2].eq_ignore_ascii_case(b"MINID") {
        match StreamId::parse(threshold_str) {
            Some(min) => TrimTo::MinId(min),
            None => {
                return resp_error("ERR Invalid stream ID specified as stream command argument");
            }
        }
    } else {
        return resp_error("ERR syntax error");
    };
    i += 1;

    let mut refs = TrimRefs::default();
    let mut limit: Option<i64> = None;
    while i < cmd.len() {
        if cmd[i].eq_ignore_ascii_case(b"LIMIT") && i + 1 < cmd.len() {
            limit = Some(
                parse_utf8(cmd[i + 1])
                    .and_then(|s| s.parse::<i64>().ok())
                    .unwrap_or(-1),
            );
            i += 2;
        } else if let Some(mode) = TrimRefs::parse(cmd[i]) {
            refs = mode;
            i += 1;
        } else {
            return resp_error("ERR syntax error");
        }
    }

    let approx = match approx_of(approx, limit) {
        Ok(approx) => approx,
        Err(e) => return e,
    };

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        None => resp_integer(0),
        Some(ValueRef::Stream(s)) => {
            let mut inner = s.write();
            let removed = match approx {
                None => trim_stream(&mut inner, &to, refs),
                Some(approx) => {
                    // Propagated as what it removed; see `exact_trim_args`.
                    effects_begin();
                    let removed = trim_stream_approx(&mut inner, &to, refs, approx);
                    if removed > 0 {
                        let mut parts: Vec<Vec<u8>> = cmd.iter().map(|b| b.to_vec()).collect();
                        let end = parts.len();
                        stream_extra::exact_trim_args(&mut parts, 2, end, &inner, refs);
                        effect(parts);
                    }
                    removed
                }
            };
            resp_integer(removed as i64)
        }
        Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
    }
}

// ── XSETID ───────────────────────────────────────────────────────────────────

pub fn xsetid(ctx: &mut Ctx) -> Vec<u8> {
    // XSETID key last-id [ENTRIESADDED n] [MAXDELETEDID id]
    let cmd = &ctx.cmd;
    if cmd.len() < 3 {
        return resp_error("ERR wrong number of arguments for 'xsetid' command");
    }
    let key: Vec<u8> = cmd[1].to_vec();
    let id_str = std::str::from_utf8(cmd[2]).unwrap_or("");
    let new_last_id = match StreamId::parse(id_str) {
        Some(id) => id,
        None => return resp_error("ERR Invalid stream ID specified as stream command argument"),
    };

    let mut entries_added: Option<u64> = None;
    let mut max_deleted_id: Option<StreamId> = None;
    let mut i = 3usize;
    while i < cmd.len() {
        let Some(value) = cmd.get(i + 1) else {
            return resp_error("ERR syntax error");
        };
        if cmd[i].eq_ignore_ascii_case(b"ENTRIESADDED") {
            entries_added = match parse_utf8(value).and_then(|s| s.parse::<i64>().ok()) {
                Some(n) if n >= 0 => Some(n as u64),
                Some(_) => return resp_error("ERR entries_added must be positive"),
                None => return resp_error("ERR value is not an integer or out of range"),
            };
        } else if cmd[i].eq_ignore_ascii_case(b"MAXDELETEDID") {
            max_deleted_id = match parse_utf8(value).and_then(StreamId::parse) {
                Some(id) if new_last_id < id => {
                    return resp_error(
                        "ERR The ID specified in XSETID is smaller than the provided max_deleted_entry_id",
                    );
                }
                Some(id) => Some(id),
                None => {
                    return resp_error(
                        "ERR Invalid stream ID specified as stream command argument",
                    );
                }
            };
        } else {
            return resp_error("ERR syntax error");
        }
        i += 2;
    }

    // The stream has to be there: `XSETID` used to create it.
    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, &key);
    let map = read_lock!(shard);
    let stream = match map.get(key.as_slice()) {
        Some(ValueRef::Stream(s)) => s,
        Some(_) => {
            return resp_error("WRONGTYPE Operation against a key holding the wrong kind of value");
        }
        None => return resp_error("ERR no such key"),
    };
    let mut inner = stream.write();
    // The last ID cannot be put behind what the stream has held: an entry
    // deleted from it, or the entry at its top.
    if new_last_id < inner.max_deleted_id {
        return resp_error(
            "ERR The ID specified in XSETID is smaller than current max_deleted_entry_id",
        );
    }
    if let Some(top) = inner.entries.keys().next_back() {
        if new_last_id < *top {
            return resp_error(
                "ERR The ID specified in XSETID is smaller than the target stream top item",
            );
        }
        if entries_added.is_some_and(|n| n < inner.entries.len() as u64) {
            return resp_error(
                "ERR The entries_added specified in XSETID is smaller than the target stream length",
            );
        }
    }
    inner.last_id = new_last_id;
    if let Some(n) = entries_added {
        inner.entries_added = n;
    }
    if let Some(id) = max_deleted_id.filter(|id| *id != StreamId::min()) {
        inner.max_deleted_id = id;
    }
    resp_simple("OK")
}

// ── XGROUP CREATE ─────────────────────────────────────────────────────────────

/// `ENTRIESREAD n` for a stream that has had `added` entries: no more
/// than those, as Redis caps it (a lag below zero means nothing).
fn capped_entries_read(n: u64, added: u64) -> u64 {
    if n != ConsumerGroup::NO_COUNT && n > added {
        added
    } else {
        n
    }
}

/// `ENTRIESREAD n`: a count, or -1 for "not known".
fn entries_read_arg(raw: &[u8]) -> Result<u64, Vec<u8>> {
    match parse_utf8(raw).and_then(|s| s.parse::<i64>().ok()) {
        Some(-1) => Ok(ConsumerGroup::NO_COUNT),
        Some(n) if n >= 0 => Ok(n as u64),
        Some(_) => Err(resp_error(
            "ERR value for ENTRIESREAD must be positive or -1",
        )),
        None => Err(resp_error("ERR value is not an integer or out of range")),
    }
}

/// Redis's reply to an `XGROUP` subcommand on a key that does not exist.
const XGROUP_NO_KEY: &str = "ERR The XGROUP subcommand requires the key to exist. \
     Note that for CREATE you may want to use the MKSTREAM option to create an \
     empty stream automatically.";

/// A `HELP` reply: the lines given, between Redis's first and last lines.
fn help_reply(command: &str, lines: &[&str]) -> Vec<u8> {
    let mut out = vec![resp_simple(&format!(
        "{command} <subcommand> [<arg> [value] [opt] ...]. Subcommands are:"
    ))];
    out.extend(lines.iter().map(|line| resp_simple(line)));
    out.push(resp_simple("HELP"));
    out.push(resp_simple("    Print this help."));
    resp_array(out)
}

/// Redis's reply to a subcommand a command does not have.
fn unknown_subcommand(command: &str, sub: &[u8]) -> Vec<u8> {
    resp_error(&format!(
        "ERR unknown subcommand '{}'. Try {command} HELP.",
        String::from_utf8_lossy(sub)
    ))
}

pub fn xgroup_create(ctx: &mut Ctx) -> Vec<u8> {
    let (key, group, id_str, mkstream, entries_read) = {
        let cmd = &ctx.cmd;
        if cmd.len() < 5 {
            return resp_error("ERR wrong number of arguments for 'xgroup|create' command");
        }

        let key: Vec<u8> = cmd[2].to_vec();
        let group = crate::types::StreamName::from(cmd[3]);
        // An ID that is not UTF-8 is no ID, and is refused as one; it was
        // taken as `$` (#576).
        let id_str = std::str::from_utf8(cmd[4]).unwrap_or_default().to_string();

        // The options come after the ID, and are all options, as Redis
        // parses them: a key or group called `mkstream` was taken for the
        // option, and an unknown word was ignored (#576).
        let mut mkstream = false;
        // Not said: not known. It is worked out, where it can be, when the
        // group first reads. See `stream_extra::Shape`.
        let mut entries_read = ConsumerGroup::NO_COUNT;
        let mut at = 5;
        while at < cmd.len() {
            if cmd[at].eq_ignore_ascii_case(b"MKSTREAM") {
                mkstream = true;
                at += 1;
            } else if cmd[at].eq_ignore_ascii_case(b"ENTRIESREAD") && at + 1 < cmd.len() {
                match entries_read_arg(cmd[at + 1]) {
                    Ok(n) => entries_read = n,
                    Err(e) => return e,
                }
                at += 2;
            } else {
                return resp_error(&format!(
                    "ERR unknown subcommand or wrong number of arguments for '{}'. Try XGROUP HELP.",
                    String::from_utf8_lossy(cmd[1])
                ));
            }
        }

        (key, group, id_str, mkstream, entries_read)
        // ← &ctx.cmd borrow ends here
    };

    {
        let db_ref = &ctx.store[*ctx.selected_db];
        let shard = store::get_shard(db_ref, &key);
        let map = read_lock!(shard);
        if !map.contains_key(key.as_slice()) && !mkstream {
            return resp_error(XGROUP_NO_KEY);
        }
    }

    // Before MKSTREAM makes the stream: an ID that is no ID fails the
    // command, and a failed command must leave no key behind. One that did
    // was not sent to replicas or the AOF (an error is not), so only this
    // node had it.
    let given_id = if id_str == "$" {
        None
    } else {
        match parse_range_id_lo(&id_str) {
            Some(id) => Some(id),
            None => {
                return resp_error("ERR Invalid stream ID specified as stream command argument");
            }
        }
    };

    let stream = match get_or_create_stream(ctx, &key) {
        Ok(s) => s,
        Err(e) => return e,
    };
    let mut inner = stream.write();

    if inner.groups.contains_key(&group) {
        return resp_error("BUSYGROUP Consumer Group name already exists");
    }

    let last_id = given_id.unwrap_or_else(|| inner.last_id.clone());

    let entries_read = capped_entries_read(entries_read, inner.entries_added);
    inner.groups.insert(
        group.clone(),
        ConsumerGroup {
            name: group,
            last_id,
            entries_read,
            pel: BTreeMap::new(),
            consumers: AHashMap::new(),
            active: AHashMap::new(),
        },
    );

    resp_simple("OK")
}

pub fn xgroup_destroy(ctx: &mut Ctx) -> Vec<u8> {
    // XGROUP DESTROY key group
    let cmd = &ctx.cmd;
    if cmd.len() != 4 {
        return resp_error("ERR wrong number of arguments for 'xgroup|destroy' command");
    }
    let key: &[u8] = cmd[2];
    let group: &[u8] = cmd[3];

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        None => resp_error(XGROUP_NO_KEY),
        Some(ValueRef::Stream(s)) => {
            let mut inner = s.write();
            resp_integer(inner.groups.remove(group).is_some() as i64)
        }
        Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
    }
}

pub fn xgroup_setid(ctx: &mut Ctx) -> Vec<u8> {
    // XGROUP SETID key group id|$ [ENTRIESREAD n]
    let cmd = &ctx.cmd;
    if cmd.len() != 5 && cmd.len() != 7 {
        return resp_error("ERR wrong number of arguments for 'xgroup|setid' command");
    }
    let key: &[u8] = cmd[2];
    let group = crate::types::StreamName::from(cmd[3]);
    let id_str = std::str::from_utf8(cmd[4]).unwrap_or("$");
    let entries_read: Option<u64> = if cmd.len() == 7 {
        if !cmd[5].eq_ignore_ascii_case(b"ENTRIESREAD") {
            return resp_error("ERR syntax error");
        }
        match entries_read_arg(cmd[6]) {
            Ok(n) => Some(n),
            Err(e) => return e,
        }
    } else {
        None
    };

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        None => resp_error(XGROUP_NO_KEY),
        Some(ValueRef::Stream(s)) => {
            let mut inner = s.write();
            let added = inner.entries_added;
            let new_id = if id_str == "$" {
                inner.last_id.clone()
            } else {
                match parse_range_id_lo(id_str) {
                    Some(id) => id,
                    None => {
                        return resp_error(
                            "ERR Invalid stream ID specified as stream command argument",
                        );
                    }
                }
            };
            match inner.groups.get_mut(&group) {
                None => resp_error_bytes(
                    &[
                        &b"NOGROUP No such consumer group '"[..],
                        c_str(group.as_bytes()),
                        &b"' for key name '"[..],
                        c_str(key),
                        &b"'"[..],
                    ]
                    .concat(),
                ),
                Some(g) => {
                    g.last_id = new_id;
                    // A new position without a count is a position whose
                    // count is not known.
                    g.entries_read =
                        capped_entries_read(entries_read.unwrap_or(ConsumerGroup::NO_COUNT), added);
                    resp_simple("OK")
                }
            }
        }
        Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
    }
}

pub fn xgroup_createconsumer(ctx: &mut Ctx) -> Vec<u8> {
    // XGROUP CREATECONSUMER key group consumer
    let cmd = &ctx.cmd;
    if cmd.len() != 5 {
        return resp_error("ERR wrong number of arguments for 'xgroup|createconsumer' command");
    }
    let key: &[u8] = cmd[2];
    let group = crate::types::StreamName::from(cmd[3]);
    let consumer = crate::types::StreamName::from(cmd[4]);

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        None => resp_error(XGROUP_NO_KEY),
        Some(ValueRef::Stream(s)) => {
            let mut inner = s.write();
            match inner.groups.get_mut(&group) {
                None => resp_error_bytes(
                    &[
                        &b"NOGROUP No such consumer group '"[..],
                        c_str(group.as_bytes()),
                        &b"' for key name '"[..],
                        c_str(key),
                        &b"'"[..],
                    ]
                    .concat(),
                ),
                Some(g) => {
                    if g.consumers.contains_key(&consumer) {
                        resp_integer(0) // already exists
                    } else {
                        g.seen(&consumer, now_ms(), false);
                        resp_integer(1)
                    }
                }
            }
        }
        Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
    }
}

pub fn xgroup_delconsumer(ctx: &mut Ctx) -> Vec<u8> {
    // XGROUP DELCONSUMER key group consumer  → count of pending messages removed
    let cmd = &ctx.cmd;
    if cmd.len() != 5 {
        return resp_error("ERR wrong number of arguments for 'xgroup|delconsumer' command");
    }
    let key: &[u8] = cmd[2];
    let group = crate::types::StreamName::from(cmd[3]);
    let consumer = crate::types::StreamName::from(cmd[4]);

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        None => resp_error(XGROUP_NO_KEY),
        Some(ValueRef::Stream(s)) => {
            let mut inner = s.write();
            match inner.groups.get_mut(&group) {
                None => resp_error_bytes(
                    &[
                        &b"NOGROUP No such consumer group '"[..],
                        c_str(group.as_bytes()),
                        &b"' for key name '"[..],
                        c_str(key),
                        &b"'"[..],
                    ]
                    .concat(),
                ),
                Some(g) => {
                    if g.consumers.remove(&consumer).is_some() {
                        notify(
                            ctx.pubsub,
                            *ctx.selected_db,
                            KS_STREAM,
                            "xgroup-delconsumer",
                            key,
                        );
                    }
                    g.active.remove(&consumer);
                    // Remove all PEL entries for this consumer
                    let pending: i64 =
                        g.pel.values().filter(|p| p.consumer == consumer).count() as i64;
                    g.pel.retain(|_, p| p.consumer != consumer);
                    resp_integer(pending)
                }
            }
        }
        Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
    }
}

// ── XREADGROUP ───────────────────────────────────────────────────────────────

/// Everything `XREADGROUP` was asked for, apart from the streams themselves.
struct GroupRead<'a> {
    group: &'a [u8],
    consumer: &'a [u8],
    /// `COUNT`: the per-stream limit.
    count: usize,
    noack: bool,
    /// `CLAIM min-idle-time` (Redis 8.4), in milliseconds: before reading new
    /// entries, take over pending ones that have been idle at least this long.
    claim_min_idle: Option<u64>,
    /// `MAXCOUNT` / `MAXSIZE` (Redis 8.10).
    caps: ReadCaps,
}

/// An entry as `XREADGROUP … CLAIM` reports it: the usual `[id, fields]` plus
/// how long ago it was last delivered and how many times it had been.
fn format_claimed_entry(
    id: &StreamId,
    entry: &StreamEntry,
    idle_ms: u64,
    deliveries: u64,
) -> Vec<u8> {
    let field_values: Vec<Vec<u8>> = entry
        .fields
        .iter()
        .flat_map(|(f, v)| vec![resp_bulk(f.as_ref()), resp_bulk(v.as_ref())])
        .collect();
    resp_array(vec![
        resp_bulk_str(&id.to_string()),
        resp_array(field_values),
        resp_integer(idle_ms.min(i64::MAX as u64) as i64),
        resp_integer(deliveries.min(i64::MAX as u64) as i64),
    ])
}

/// What C's `%s` prints of `bytes`: up to its first NUL. Redis's NOGROUP
/// errors format the key and the group so.
fn c_str(bytes: &[u8]) -> &[u8] {
    &bytes[..memchr::memchr(0, bytes).unwrap_or(bytes.len())]
}

fn nogroup_error(key: &[u8], group: &[u8]) -> Vec<u8> {
    resp_error_bytes(
        &[
            &b"NOGROUP No such key '"[..],
            c_str(key),
            &b"' or consumer group '"[..],
            c_str(group),
            &b"' in XREADGROUP with GROUP option"[..],
        ]
        .concat(),
    )
}

pub fn xreadgroup(ctx: &mut Ctx) -> Vec<u8> {
    let resp = reply_resp(ctx);
    // XREADGROUP GROUP group consumer [COUNT n] [MAXCOUNT n] [MAXSIZE n]
    //            [BLOCK ms] [CLAIM min-idle-time] [NOACK]
    //            STREAMS key [key...] id [id...]
    let cmd = ctx.cmd.clone();
    if cmd.len() < 7 {
        return resp_error("ERR wrong number of arguments for 'xreadgroup' command");
    }

    // cmd[1] must be "GROUP"
    if !std::str::from_utf8(cmd[1])
        .unwrap_or("")
        .eq_ignore_ascii_case("GROUP")
    {
        return resp_error("ERR syntax error");
    }
    let group = crate::types::StreamName::from(cmd[2]);
    let consumer = crate::types::StreamName::from(cmd[3]);

    let mut count: Option<usize> = None;
    let mut caps = ReadCaps::default();
    let mut noack = false;
    let mut claim_min_idle: Option<u64> = None;
    let mut i = 4usize;
    let mut block_ms: Option<u64> = None;

    // Each option takes its argument, as in Redis; one that is not an option
    // is a syntax error (it used to be skipped).
    let mut saw_streams = false;
    while i < cmd.len() {
        let tok = std::str::from_utf8(cmd[i])
            .unwrap_or("")
            .to_ascii_uppercase();
        let has_arg = i + 1 < cmd.len();
        match tok.as_str() {
            "COUNT" if has_arg => {
                // 0, or less, is no limit, as in Redis.
                count = match parse_utf8(cmd[i + 1]).and_then(|s| s.parse::<i64>().ok()) {
                    Some(n) if n > 0 => Some(n as usize),
                    Some(_) => None,
                    None => return resp_error("ERR value is not an integer or out of range"),
                };
                i += 2;
            }
            "MAXCOUNT" => {
                match ReadCaps::parse_positive("MAXCOUNT", cmd.get(i + 1)) {
                    Ok(n) => caps.max_count = Some(n),
                    Err(e) => return resp_error(&e),
                }
                i += 2;
            }
            "MAXSIZE" => {
                match ReadCaps::parse_positive("MAXSIZE", cmd.get(i + 1)) {
                    Ok(n) => caps.max_size = Some(n),
                    Err(e) => return resp_error(&e),
                }
                i += 2;
            }
            "BLOCK" if has_arg => {
                block_ms = match parse_utf8(cmd[i + 1]).and_then(|s| s.parse::<i64>().ok()) {
                    Some(ms) if ms < 0 => return resp_error("ERR timeout is negative"),
                    Some(ms) => Some(ms as u64),
                    None => return resp_error("ERR timeout is not an integer or out of range"),
                };
                i += 2;
            }
            "CLAIM" => {
                // As Redis reads an integer: `+10` is not one.
                claim_min_idle = match cmd.get(i + 1).and_then(|b| stream_extra::strict_integer(b))
                {
                    Some(ms) if ms < 0 => {
                        return resp_error("ERR min-idle-time must be a positive integer");
                    }
                    Some(ms) => Some(ms as u64),
                    None => {
                        return resp_error("ERR min-idle-time is not an integer or out of range");
                    }
                };
                i += 2;
            }
            "NOACK" => {
                noack = true;
                i += 1;
            }
            "STREAMS" => {
                i += 1;
                saw_streams = true;
                break;
            }
            _ => return resp_error("ERR syntax error"),
        }
    }
    if !saw_streams {
        return resp_error("ERR syntax error");
    }
    if let Err(e) = caps.check_against_count(count) {
        return resp_error(&e);
    }

    let remaining = cmd.len().saturating_sub(i);
    if remaining < 2 || !remaining.is_multiple_of(2) {
        return resp_error(
            "ERR Unbalanced 'xreadgroup' list of streams: for each stream key an ID or '>' must be specified.",
        );
    }
    // Every ID is `>` or one, checked before anything is read.
    for id in &cmd[i + remaining / 2..] {
        if *id == b">" {
            continue;
        }
        if *id == b"$" {
            return resp_error("ERR The $ ID is meaningless in the context of XREADGROUP");
        }
        if parse_utf8(id).and_then(StreamId::parse).is_none() {
            return resp_error("ERR Invalid stream ID specified as stream command argument");
        }
    }
    let half = remaining / 2;
    let keys: Vec<Vec<u8>> = cmd[i..i + half].iter().map(|b| b.to_vec()).collect();
    let ids: Vec<&str> = cmd[i + half..]
        .iter()
        .map(|b| std::str::from_utf8(b).unwrap_or(""))
        .collect();

    let spec = GroupRead {
        group: &group,
        consumer: &consumer,
        count: count.unwrap_or(usize::MAX),
        noack,
        claim_min_idle,
        caps,
    };

    // A resume just re-runs delivery: unlike XREAD, every blocking XREADGROUP
    // reads with ">" ("entries never delivered to this group"), which is
    // relative to group state rather than to when the command arrived — so
    // there is nothing to carry across the park except when the wait is to
    // end.
    //
    // It is woken by an entry being added, and by anything else that writes
    // the key: the stream deleted, or replaced by something that is not a
    // stream, or the group destroyed — which is an error to report, where
    // Redis reports it, rather than a wait that can no longer end. A write
    // that changes nothing for this reader sends it back to wait.
    //
    // Clients blocked on the same stream are woken one at a time, in the
    // order they blocked — the entry goes to the one that has waited longest
    // — and each gives the turn to the one behind it once it has looked,
    // which may be reading for another group.
    let gone = blocking::client_gone(ctx);
    let resumed = blocking::take_resume(ctx);
    let timed_out = matches!(resumed, Some(None));
    let (carried_deadline, ticket) = match blocking::take_state(ctx) {
        Some(blocking::BlockState::GroupRead { deadline, ticket }) => (Some(deadline), ticket),
        _ => (None, ctx.wait_table.new_ticket()),
    };
    // The command is over: out of the line, and the next client's turn.
    let done = |ctx: &Ctx, reply: Vec<u8>| {
        if resumed.is_some() {
            for key in &keys {
                ctx.wait_table.reader_done(key, &ticket);
            }
        }
        reply
    };
    // Its client went while it waited: nothing is delivered — an entry
    // would sit in the consumer's pending list, read by nobody — and it
    // leaves the line.
    if gone {
        return done(ctx, resp_null_array());
    }

    let results = match run_xreadgroup_delivery(ctx, &keys, &ids, &spec) {
        Ok(results) => results,
        Err(e) => return done(ctx, e),
    };
    if !results.is_empty() {
        return done(ctx, stream_results_reply(resp, results));
    }

    // Nothing to deliver. With CLAIM the wait may have been ended by its own
    // timer — "an entry may be claimable now" — rather than by the client's
    // timeout; and any wait may have been ended by a write that left nothing
    // for this reader. If the client's time is not up, it waits again.
    let claim_min_idle = spec.claim_min_idle;
    let waiting_on = match (resumed.is_some(), carried_deadline) {
        (true, Some(deadline)) if claim_min_idle.is_some() || !timed_out => Some(deadline),
        (true, _) => None,
        (false, _) => block_ms.map(|ms| {
            blocking::timeout_from_ms(ms).map(|timeout| std::time::Instant::now() + timeout)
        }),
    };
    let Some((deadline, remaining)) = waiting_on
        .and_then(|deadline| blocking::remaining_time(deadline).map(|left| (deadline, left)))
    else {
        return done(ctx, resp_null_array());
    };

    // Stand in line on every key BEFORE the second check — closes the TOCTOU
    // gap. (A history read never gets here: its reply always names the
    // stream, so it is never empty.)
    let rxs: Vec<(
        Vec<u8>,
        tokio::sync::oneshot::Receiver<crate::wait_table::Value>,
    )> = keys
        .iter()
        .map(|k| (k.clone(), ctx.wait_table.enqueue_reader(k, &ticket)))
        .collect();
    let leave = |ctx: &Ctx| {
        for key in &keys {
            ctx.wait_table.reader_done(key, &ticket);
        }
    };

    // Second check: data may have arrived between the first read and standing
    // in line. Re-run the full delivery path inline — we need group mutation,
    // not just a read.
    let second_check = match run_xreadgroup_delivery(ctx, &keys, &ids, &spec) {
        Ok(results) => results,
        Err(e) => {
            drop(rxs);
            leave(ctx);
            return e;
        }
    };
    if !second_check.is_empty() {
        drop(rxs);
        leave(ctx);
        // `stream_results_reply`, not `resp_array`: under RESP3 this is a map
        // keyed by stream name, and the non-blocking return above already
        // frames it that way. This path and the post-wake one used to emit a
        // flat array regardless, so a RESP3 client got a structurally
        // different reply whenever it happened to block — invisible to
        // RESP2, and only reachable when blocking, which is why it survived
        // the RESP3 sweep.
        return stream_results_reply(resp, second_check);
    }
    // Woken, and nothing for this reader: the one behind it has its turn.
    if resumed.is_some() {
        for key in &keys {
            ctx.wait_table.reader_pass_on(key, &ticket);
        }
    }

    // Nothing yet — park until the stream is written, or the timeout. On
    // resume this function re-runs and `run_xreadgroup_delivery` above does
    // the delivery, so there is no separate post-wake path to keep in sync.
    //
    // With CLAIM, the park ends no later than the moment the first pending
    // entry will have been idle for long enough.
    let wait = match claim_min_idle {
        Some(min_idle) => {
            let claimable = next_claimable_in(ctx, &keys, spec.group, min_idle);
            match (remaining, claimable) {
                (Some(a), Some(b)) => Some(a.min(b)),
                (a, b) => a.or(b),
            }
        }
        None => remaining,
    };
    let state = blocking::BlockState::GroupRead {
        deadline,
        ticket: Arc::clone(&ticket),
    };
    match blocking::park_with_state(ctx, rxs, wait, Some(state)) {
        ParkOutcome::Parked => {
            ticket.parks_in(&keys, true);
            Vec::new()
        }
        ParkOutcome::CannotWait => {
            leave(ctx);
            resp_null_array()
        }
    }
}

/// How long until some entry pending in `group`, in one of `keys`, will have
/// been idle for `min_idle` milliseconds — `None` if nothing is pending.
fn next_claimable_in(
    ctx: &Ctx,
    keys: &[Vec<u8>],
    group: &[u8],
    min_idle: u64,
) -> Option<std::time::Duration> {
    let now = now_ms();
    let mut soonest: Option<u64> = None;
    for key in keys {
        let shard = store::get_shard(&ctx.store[*ctx.selected_db], key.as_slice());
        let map = read_lock!(shard);
        let Some(ValueRef::Stream(stream)) = map.get(key.as_slice()) else {
            continue;
        };
        let inner = stream.read();
        let Some(g) = inner.groups.get(group) else {
            continue;
        };
        for pending in g.pel.values() {
            let at = pending.delivered_at.saturating_add(min_idle);
            soonest = Some(soonest.map_or(at, |s| s.min(at)));
        }
    }
    // Never zero: a park that ends at once, finds nothing and parks again
    // would spin.
    soonest.map(|at| std::time::Duration::from_millis(at.saturating_sub(now).max(1)))
}

/// Runs the non-blocking XREADGROUP delivery for each (key, id) pair.
/// Returns formatted response entries — empty vec means nothing available.
/// This is the core of xreadgroup without any blocking logic.
///
/// Every pending-list change made here is recorded as an effect (see
/// `script_feed::effects_begin`) and that record — not the command — is what
/// replicas and the AOF receive.
fn run_xreadgroup_delivery(
    ctx: &mut Ctx,
    keys: &[Vec<u8>],
    ids: &[&str],
    spec: &GroupRead,
) -> Result<Vec<Vec<u8>>, Vec<u8>> {
    // Returns the flat item list; the caller frames it with
    // `stream_results_reply`, so both protocols share this code path.
    let resp = reply_resp(ctx);
    let now = now_ms();
    effects_begin();

    // Find every stream and group before delivering from any of them, so a
    // missing key or group fails the command with nothing half-delivered.
    // (They used to be skipped silently, and a missing group produced the
    // same nil as "no new entries".)
    let mut streams = Vec::with_capacity(keys.len());
    for key in keys {
        let db_ref = &ctx.store[*ctx.selected_db];
        let shard = store::get_shard(db_ref, key.as_slice());
        let map = read_lock!(shard);
        match map.get(key.as_slice()) {
            Some(ValueRef::Stream(s)) => {
                if !s.read().groups.contains_key(spec.group) {
                    return Err(nogroup_error(key, spec.group));
                }
                streams.push(Arc::clone(s));
            }
            Some(_) => {
                return Err(resp_error(
                    "WRONGTYPE Operation against a key holding the wrong kind of value",
                ));
            }
            None => return Err(nogroup_error(key, spec.group)),
        }
    }

    let mut budget = spec.caps.budget();
    let mut results: Vec<Vec<u8>> = Vec::new();

    for ((key, id_str), stream) in keys.iter().zip(ids.iter()).zip(streams) {
        let mut guard = stream.write();
        let shape = stream_extra::Shape::of(&guard);
        // Split the borrow: entries are read while the group is updated.
        let StreamInner {
            entries, groups, ..
        } = &mut *guard;
        let Some(g) = groups.get_mut(spec.group) else {
            // Destroyed between the check above and here.
            continue;
        };

        let is_new = !g.consumers.contains_key(spec.consumer);
        g.seen(spec.consumer, now, false);
        if is_new {
            notify(
                ctx.pubsub,
                *ctx.selected_db,
                KS_STREAM,
                "xgroup-createconsumer",
                key,
            );
            effect(vec![
                b"XGROUP".to_vec(),
                b"CREATECONSUMER".to_vec(),
                key.to_vec(),
                spec.group.to_vec(),
                spec.consumer.to_vec(),
            ]);
        }

        let mut items: Vec<Vec<u8>> = Vec::new();
        let history = *id_str != ">";

        if !history {
            // ── 1. CLAIM: idle pending entries first ─────────────────────
            if let Some(min_idle) = spec.claim_min_idle {
                // Entries released with XNACK (delivery time 0) sort first,
                // then the longest idle.
                let mut candidates: Vec<(u64, StreamId)> = g
                    .pel
                    .iter()
                    .filter(|(_, p)| now.saturating_sub(p.delivered_at) >= min_idle)
                    .map(|(id, p)| (p.delivered_at, id.clone()))
                    .collect();
                candidates.sort();
                for (_, id) in candidates {
                    if items.len() >= spec.count || budget.exhausted() {
                        break;
                    }
                    // Pending but since deleted from the stream: nothing to
                    // hand over.
                    let Some(entry) = entries.get(&id) else {
                        continue;
                    };
                    let Some(pending) = g.pel.get_mut(&id) else {
                        continue;
                    };
                    let idle = if pending.delivered_at < stream_extra::NACKED_BELOW {
                        0
                    } else {
                        now.saturating_sub(pending.delivered_at)
                    };
                    let item = format_claimed_entry(&id, entry, idle, pending.delivery_count);
                    if !budget.admit(item.len()) {
                        break;
                    }
                    pending.consumer = crate::types::StreamName::from(spec.consumer);
                    pending.delivered_at = now;
                    pending.delivery_count = pending.delivery_count.saturating_add(1);
                    effect(claim_effect(
                        key,
                        spec.group,
                        spec.consumer,
                        &id,
                        now,
                        pending.delivery_count,
                    ));
                    items.push(item);
                }
            }

            // ── 2. Entries never delivered to this group ─────────────────
            let newer = (Bound::Excluded(g.last_id.clone()), Bound::Unbounded);
            let mut delivered = 0u64;
            for (id, entry) in entries.range(newer) {
                if items.len() >= spec.count || budget.exhausted() {
                    break;
                }
                // With CLAIM every entry has the extended shape, so a client
                // can parse the reply uniformly; a new entry has never been
                // delivered, hence 0 and 0.
                let item = if spec.claim_min_idle.is_some() {
                    format_claimed_entry(id, entry, 0, 0)
                } else {
                    format_entry(id, entry)
                };
                // Checked before the entry is delivered: one that does not
                // fit is neither sent nor added to the pending list.
                if !budget.admit(item.len()) {
                    break;
                }
                if !spec.noack {
                    g.pel.insert(
                        id.clone(),
                        PelEntry {
                            consumer: crate::types::StreamName::from(spec.consumer),
                            delivered_at: now,
                            delivery_count: 1,
                        },
                    );
                    effect(claim_effect(key, spec.group, spec.consumer, id, now, 1));
                }
                shape.deliver(g, id);
                delivered += 1;
                items.push(item);
            }
            if delivered > 0 {
                effect(setid_effect(key, spec.group, &g.last_id, g.entries_read));
            }
        } else {
            // ── History: this consumer's own pending entries after `id` ──
            let from = StreamId::parse(id_str).unwrap_or(StreamId::min());
            let after = if from == StreamId::min() {
                Bound::Unbounded
            } else {
                Bound::Excluded(from)
            };
            let pending_ids: Vec<StreamId> = g
                .pel
                .range((after, Bound::Unbounded))
                .filter(|(_, p)| p.consumer == spec.consumer)
                .take(spec.count)
                .map(|(id, _)| id.clone())
                .collect();
            for id in pending_ids {
                if budget.exhausted() {
                    break;
                }
                let item = match entries.get(&id) {
                    Some(entry) => format_entry(&id, entry),
                    // Still pending, but deleted from the stream since.
                    None => resp_array(vec![resp_bulk_str(&id.to_string()), resp_null_for(resp)]),
                };
                if !budget.admit(item.len()) {
                    break;
                }
                if let Some(pending) = g.pel.get_mut(&id) {
                    pending.delivered_at = now;
                    pending.delivery_count = pending.delivery_count.saturating_add(1);
                    // Not a change of the dataset, to Redis (#27).
                    effect_of_metadata(claim_effect(
                        key,
                        spec.group,
                        spec.consumer,
                        &id,
                        now,
                        pending.delivery_count,
                    ));
                }
                items.push(item);
            }
        }

        if !items.is_empty() {
            g.seen(spec.consumer, now, true);
        }
        // A history read always names the stream, with an empty list when
        // nothing is pending — that empty list is how a consumer learns it
        // has caught up. A read of new entries leaves empty streams out.
        if history || !items.is_empty() {
            results.extend(stream_result_items(resp, key, items));
        }
    }

    Ok(results)
}
// ── XACK ─────────────────────────────────────────────────────────────────────

pub fn xack(ctx: &mut Ctx) -> Vec<u8> {
    // XACK key group id [id ...]
    let cmd = &ctx.cmd;
    if cmd.len() < 4 {
        return resp_error("ERR wrong number of arguments for 'xack' command");
    }
    let key: &[u8] = cmd[1];
    let group = crate::types::StreamName::from(cmd[2]);
    // All of the IDs, before any is acknowledged: one that is not an ID
    // fails the command, and it must not have done half its work by then.
    let mut ids = Vec::with_capacity(cmd.len() - 3);
    for raw in &cmd[3..] {
        match parse_utf8(raw).and_then(StreamId::parse) {
            Some(id) => ids.push(id),
            None => {
                return resp_error("ERR Invalid stream ID specified as stream command argument");
            }
        }
    }

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        None => resp_integer(0),
        Some(ValueRef::Stream(s)) => {
            let mut inner = s.write();
            match inner.groups.get_mut(&group) {
                None => resp_integer(0),
                Some(g) => {
                    let acked = ids.iter().filter(|id| g.pel.remove(id).is_some()).count();
                    resp_integer(acked as i64)
                }
            }
        }
        Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
    }
}

// ── XPENDING ─────────────────────────────────────────────────────────────────

pub fn xpending(ctx: &mut Ctx) -> Vec<u8> {
    let resp = reply_resp(ctx);
    // XPENDING key group [[IDLE min-idle] start end count [consumer]]
    let cmd = &ctx.cmd;
    if cmd.len() < 3 {
        return resp_error("ERR wrong number of arguments for 'xpending' command");
    }
    let key: &[u8] = cmd[1];
    let group = crate::types::StreamName::from(cmd[2]);

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        None => resp_error("ERR no such key"),
        Some(ValueRef::Stream(s)) => {
            let inner = s.read();
            let g = match inner.groups.get(&group) {
                None => return resp_error("NOGROUP No such consumer group"),
                Some(g) => g,
            };

            if cmd.len() == 3 {
                // Summary form: [count, min-id, max-id, [[consumer, count], ...]]
                let count = g.pel.len() as i64;
                let min_id = g
                    .pel
                    .keys()
                    .next()
                    .map(|id| id.to_string())
                    .unwrap_or_default();
                let max_id = g
                    .pel
                    .keys()
                    .next_back()
                    .map(|id| id.to_string())
                    .unwrap_or_default();

                // Consumer → pending count
                // By name, as Redis lists them (#564).
                let mut per_consumer: BTreeMap<&[u8], i64> = BTreeMap::new();
                for pel in g.pel.values() {
                    *per_consumer.entry(pel.consumer.as_bytes()).or_insert(0) += 1;
                }
                let consumer_list: Vec<Vec<u8>> = per_consumer
                    .iter()
                    .map(|(name, cnt)| {
                        resp_array(vec![resp_bulk(name), resp_bulk_str(&cnt.to_string())])
                    })
                    .collect();

                // An empty PEL reports nil min/max IDs, nested inside the
                // summary array — not reachable by top-level normalisation.
                resp_array(vec![
                    resp_integer(count),
                    if min_id.is_empty() {
                        resp_null_for(resp)
                    } else {
                        resp_bulk_str(&min_id)
                    },
                    if max_id.is_empty() {
                        resp_null_for(resp)
                    } else {
                        resp_bulk_str(&max_id)
                    },
                    resp_array(consumer_list),
                ])
            } else {
                // Extended form: XPENDING key group [IDLE ms] start end count [consumer]
                let mut i = 3usize;
                let mut min_idle: Option<u64> = None;

                if std::str::from_utf8(cmd[i])
                    .unwrap_or("")
                    .eq_ignore_ascii_case("IDLE")
                {
                    min_idle = cmd
                        .get(i + 1)
                        .and_then(|b| std::str::from_utf8(b).ok())
                        .and_then(|s| s.parse().ok());
                    i += 2;
                }

                let start_str =
                    std::str::from_utf8(cmd.get(i).copied().unwrap_or(b"-")).unwrap_or("-");
                let end_str =
                    std::str::from_utf8(cmd.get(i + 1).copied().unwrap_or(b"+")).unwrap_or("+");
                let count: usize = cmd
                    .get(i + 2)
                    .and_then(|b| std::str::from_utf8(b).ok())
                    .and_then(|s| s.parse().ok())
                    .unwrap_or(10);
                let filter_consumer: Option<&str> =
                    cmd.get(i + 3).and_then(|b| std::str::from_utf8(b).ok());

                let (lo, hi, count) = match id_interval(start_str, end_str) {
                    Ok(Some((lo, hi))) => (lo, hi, count),
                    Ok(None) => (StreamId::min(), StreamId::min(), 0),
                    Err(e) => return e,
                };
                let now = now_ms();

                let items: Vec<Vec<u8>> = g
                    .pel
                    .range(lo..=hi)
                    .filter(|(_, p)| {
                        if let Some(fc) = filter_consumer {
                            p.consumer == fc
                        } else {
                            true
                        }
                    })
                    .filter(|(_, p)| {
                        if let Some(idle) = min_idle {
                            now.saturating_sub(p.delivered_at) >= idle
                        } else {
                            true
                        }
                    })
                    .take(count)
                    .map(|(id, p)| {
                        // `delivered_at` below `NACKED_BELOW` is XNACK's mark for "released,
                        // never re-delivered". Redis reports that as an idle of
                        // -1 rather than "now", which would otherwise read as an
                        // absurd age measured from the epoch.
                        let idle = if p.delivered_at < stream_extra::NACKED_BELOW {
                            -1
                        } else {
                            now.saturating_sub(p.delivered_at) as i64
                        };
                        resp_array(vec![
                            resp_bulk_str(&id.to_string()),
                            resp_bulk(&p.consumer),
                            resp_integer(idle),
                            resp_integer(p.delivery_count as i64),
                        ])
                    })
                    .collect();

                resp_array(items)
            }
        }
        Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
    }
}

// ── XCLAIM / XAUTOCLAIM ───────────────────────────────────────────────────────

pub fn xclaim(ctx: &mut Ctx) -> Vec<u8> {
    // XCLAIM key group consumer min-idle-time id [id ...] [IDLE ms] [TIME ms]
    //        [RETRYCOUNT n] [FORCE] [JUSTID] [LASTID id]
    let cmd = &ctx.cmd;
    if cmd.len() < 6 {
        return resp_error("ERR wrong number of arguments for 'xclaim' command");
    }
    let key: &[u8] = cmd[1];
    let group = crate::types::StreamName::from(cmd[2]);
    let new_consumer = crate::types::StreamName::from(cmd[3]);
    let min_idle: u64 = match parse_utf8(cmd[4]).and_then(|s| s.parse().ok()) {
        Some(ms) => ms,
        None => return resp_error("ERR Invalid min-idle-time argument for XCLAIM"),
    };

    // Collect IDs — stop when we hit an option keyword
    let is_option = |tok: &[u8]| {
        [
            &b"IDLE"[..],
            b"TIME",
            b"RETRYCOUNT",
            b"FORCE",
            b"JUSTID",
            b"LASTID",
        ]
        .iter()
        .any(|opt| tok.eq_ignore_ascii_case(opt))
    };
    let mut ids: Vec<StreamId> = Vec::new();
    let mut i = 5usize;
    while i < cmd.len() && !is_option(cmd[i]) {
        match parse_utf8(cmd[i]).and_then(StreamId::parse) {
            Some(id) => ids.push(id),
            None => {
                return resp_error("ERR Invalid stream ID specified as stream command argument");
            }
        }
        i += 1;
    }

    let mut justid = false;
    let mut force = false;
    let mut idle: Option<u64> = None;
    let mut time: Option<u64> = None;
    let mut retry_count: Option<u64> = None;
    let mut last_id: Option<StreamId> = None;

    let number = |arg: Option<&&[u8]>| -> Option<u64> {
        arg.and_then(|b| std::str::from_utf8(b).ok())
            .and_then(|s| s.parse().ok())
    };
    while i < cmd.len() {
        let tok = String::from_utf8_lossy(cmd[i]).to_ascii_uppercase();
        match tok.as_str() {
            "JUSTID" => {
                justid = true;
                i += 1;
            }
            "FORCE" => {
                force = true;
                i += 1;
            }
            "IDLE" | "TIME" | "RETRYCOUNT" => {
                let Some(n) = number(cmd.get(i + 1)) else {
                    return resp_error("ERR value is not an integer or out of range");
                };
                match tok.as_str() {
                    "IDLE" => idle = Some(n),
                    "TIME" => time = Some(n),
                    _ => retry_count = Some(n),
                }
                i += 2;
            }
            "LASTID" => {
                last_id = match cmd
                    .get(i + 1)
                    .and_then(|b| std::str::from_utf8(b).ok())
                    .and_then(StreamId::parse)
                {
                    Some(id) => Some(id),
                    None => {
                        return resp_error(
                            "ERR Invalid stream ID specified as stream command argument",
                        );
                    }
                };
                i += 2;
            }
            _ => return resp_error("ERR syntax error"),
        }
    }

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        None => resp_error_bytes(
            &[
                &b"NOGROUP No such key '"[..],
                c_str(key),
                &b"' or consumer group '"[..],
                c_str(group.as_bytes()),
                &b"'"[..],
            ]
            .concat(),
        ),
        Some(ValueRef::Stream(s)) => {
            let mut guard = s.write();
            let StreamInner {
                entries, groups, ..
            } = &mut *guard;
            let now = now_ms();
            // TIME is an absolute delivery time; IDLE is relative to now.
            let delivered_at = time.unwrap_or_else(|| now.saturating_sub(idle.unwrap_or(0)));

            let Some(g) = groups.get_mut(&group) else {
                return resp_error_bytes(
                    &[
                        &b"NOGROUP No such key '"[..],
                        c_str(key),
                        &b"' or consumer group '"[..],
                        c_str(group.as_bytes()),
                        &b"'"[..],
                    ]
                    .concat(),
                );
            };
            effects_begin();
            if !g.consumers.contains_key(&new_consumer) {
                notify(
                    ctx.pubsub,
                    *ctx.selected_db,
                    KS_STREAM,
                    "xgroup-createconsumer",
                    key,
                );
            }
            g.seen(&new_consumer, now, false);
            if let Some(last) = last_id
                && last > g.last_id
            {
                g.last_id = last;
            }

            let mut claimed: Vec<Vec<u8>> = Vec::new();
            for id in &ids {
                let exists = entries.contains_key(id);
                match g.pel.get(id) {
                    // Pending, but the entry itself is gone: drop the
                    // reference rather than hand out nothing.
                    Some(_) if !exists => {
                        g.pel.remove(id);
                        effect(vec![
                            b"XACK".to_vec(),
                            key.to_vec(),
                            group.as_bytes().to_vec(),
                            id.to_string().into_bytes(),
                        ]);
                        continue;
                    }
                    Some(p) if now.saturating_sub(p.delivered_at) < min_idle => continue,
                    Some(_) => {}
                    // Not pending: only FORCE claims it, and only if it exists.
                    None if force && exists => {}
                    None => continue,
                }

                // An entry FORCE makes starts as one delivery, as Redis's
                // `streamCreateNACK` makes it (JUSTID then leaves it at 1).
                let pending = g.pel.entry(id.clone()).or_insert(PelEntry {
                    consumer: new_consumer.clone(),
                    delivered_at,
                    delivery_count: 1,
                });
                pending.consumer = new_consumer.clone();
                pending.delivered_at = delivered_at;
                pending.delivery_count = match retry_count {
                    Some(n) => n,
                    // JUSTID is a transfer of ownership, not a delivery.
                    None if justid => pending.delivery_count,
                    None => pending.delivery_count.saturating_add(1),
                };
                effect(claim_effect(
                    key,
                    &group,
                    &new_consumer,
                    id,
                    delivered_at,
                    pending.delivery_count,
                ));

                if justid {
                    claimed.push(resp_bulk_str(&id.to_string()));
                } else if let Some(entry) = entries.get(id) {
                    claimed.push(format_entry(id, entry));
                }
            }
            if !claimed.is_empty() {
                g.seen(&new_consumer, now, true);
            }
            resp_array(claimed)
        }
        Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
    }
}

pub fn xautoclaim(ctx: &mut Ctx) -> Vec<u8> {
    // XAUTOCLAIM key group consumer min-idle-time start [COUNT count] [JUSTID]
    let cmd = &ctx.cmd;
    if cmd.len() < 6 {
        return resp_error("ERR wrong number of arguments for 'xautoclaim' command");
    }
    let key: &[u8] = cmd[1];
    let group = crate::types::StreamName::from(cmd[2]);
    let new_consumer = crate::types::StreamName::from(cmd[3]);
    let min_idle: u64 = match parse_utf8(cmd[4]).and_then(|s| s.parse().ok()) {
        Some(ms) => ms,
        None => return resp_error("ERR Invalid min-idle-time argument for XAUTOCLAIM"),
    };
    let start = match parse_range_id_lo(std::str::from_utf8(cmd[5]).unwrap_or("")) {
        Some(id) => id,
        None => {
            return resp_error("ERR Invalid stream ID specified as stream command argument");
        }
    };

    let mut count = 100usize;
    let mut justid = false;
    let mut i = 6usize;
    while i < cmd.len() {
        if cmd[i].eq_ignore_ascii_case(b"COUNT") {
            count = match cmd
                .get(i + 1)
                .and_then(|b| std::str::from_utf8(b).ok())
                .and_then(|s| s.parse::<usize>().ok())
            {
                // The reply is built in one piece, and the scan below looks
                // at ten pending entries for each one asked for.
                Some(n) if n > 0 && n <= (i64::MAX / 16) as usize => n,
                _ => return resp_error("ERR COUNT must be > 0"),
            };
            i += 2;
        } else if cmd[i].eq_ignore_ascii_case(b"JUSTID") {
            justid = true;
            i += 1;
        } else {
            return resp_error("ERR syntax error");
        }
    }

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        None => resp_error_bytes(
            &[
                &b"NOGROUP No such key '"[..],
                c_str(key),
                &b"' or consumer group '"[..],
                c_str(group.as_bytes()),
                &b"'"[..],
            ]
            .concat(),
        ),
        Some(ValueRef::Stream(s)) => {
            let mut guard = s.write();
            let StreamInner {
                entries, groups, ..
            } = &mut *guard;
            let now = now_ms();

            let Some(g) = groups.get_mut(&group) else {
                return resp_error_bytes(
                    &[
                        &b"NOGROUP No such key '"[..],
                        c_str(key),
                        &b"' or consumer group '"[..],
                        c_str(group.as_bytes()),
                        &b"'"[..],
                    ]
                    .concat(),
                );
            };
            effects_begin();
            if !g.consumers.contains_key(&new_consumer) {
                notify(
                    ctx.pubsub,
                    *ctx.selected_db,
                    KS_STREAM,
                    "xgroup-createconsumer",
                    key,
                );
            }
            g.seen(&new_consumer, now, false);

            // Walk the pending list from `start`. An entry that no longer
            // exists in the stream is dropped from the list and reported in
            // the third element of the reply; one that has been idle long
            // enough is claimed. Either counts towards `COUNT`, and the walk
            // looks at no more than ten pending entries for each one asked
            // for: a call's work is bounded however long the list is. The
            // cursor is the pending entry after the last one looked at —
            // where the next call resumes — or 0-0 past the end of the list.
            let scan: Vec<(StreamId, u64)> = g
                .pel
                .range(start..)
                .take(count.saturating_mul(10).saturating_add(1))
                .map(|(id, p)| (id.clone(), p.delivered_at))
                .collect();
            let mut claimed: Vec<Vec<u8>> = Vec::new();
            let mut deleted: Vec<StreamId> = Vec::new();
            let mut cursor = StreamId::min();
            let mut attempts = count.saturating_mul(10);
            for (id, last_delivered) in scan {
                if attempts == 0 || claimed.len() + deleted.len() >= count {
                    cursor = id;
                    break;
                }
                attempts -= 1;
                let Some(entry) = entries.get(&id) else {
                    g.pel.remove(&id);
                    deleted.push(id);
                    continue;
                };
                if now.saturating_sub(last_delivered) < min_idle {
                    continue;
                }
                let Some(pending) = g.pel.get_mut(&id) else {
                    continue;
                };
                pending.consumer = new_consumer.clone();
                pending.delivered_at = now;
                if !justid {
                    pending.delivery_count = pending.delivery_count.saturating_add(1);
                }
                effect(claim_effect(
                    key,
                    &group,
                    &new_consumer,
                    &id,
                    now,
                    pending.delivery_count,
                ));
                claimed.push(if justid {
                    resp_bulk_str(&id.to_string())
                } else {
                    format_entry(&id, entry)
                });
            }
            if !claimed.is_empty() {
                g.seen(&new_consumer, now, true);
            }
            if !deleted.is_empty() {
                let mut xack = vec![b"XACK".to_vec(), key.to_vec(), group.to_vec()];
                xack.extend(deleted.iter().map(|id| id.to_string().into_bytes()));
                effect(xack);
            }

            resp_array(vec![
                resp_bulk_str(&cursor.to_string()),
                resp_array(claimed),
                resp_array(
                    deleted
                        .iter()
                        .map(|id| resp_bulk_str(&id.to_string()))
                        .collect(),
                ),
            ])
        }
        Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
    }
}

// ── XINFO ─────────────────────────────────────────────────────────────────────

pub fn xinfo(ctx: &mut Ctx) -> Vec<u8> {
    let cmd = &ctx.cmd;
    if cmd.len() == 2 && cmd[1].eq_ignore_ascii_case(b"HELP") {
        return help_reply(
            "XINFO",
            &[
                "CONSUMERS <key> <groupname>",
                "    Show consumers of <groupname>.",
                "GROUPS <key>",
                "    Show the stream consumer groups.",
                "STREAM <key> [FULL [COUNT <count>]",
                "    Show information about the stream.",
            ],
        );
    }
    if cmd.len() < 3 {
        return resp_error("ERR wrong number of arguments for 'xinfo' command");
    }
    let subcommand = std::str::from_utf8(cmd[1])
        .unwrap_or("")
        .to_ascii_uppercase();
    match subcommand.as_str() {
        "STREAM" => xinfo_stream(ctx),
        "GROUPS" => xinfo_groups(ctx),
        "CONSUMERS" => xinfo_consumers(ctx),
        _ => unknown_subcommand("XINFO", cmd[1]),
    }
}

fn xinfo_stream(ctx: &mut Ctx) -> Vec<u8> {
    // XINFO STREAM key [FULL [COUNT n]]
    //
    // Redis builds this with `addReplyMapLen`, which emits a flat 2N array
    // under RESP2 and a `%N` map under RESP3 — exactly what `resp_map_for`
    // does. The first-entry/last-entry nils are nested inside the reply, so
    // they need protocol-correct encoding too.
    let resp = reply_resp(ctx);
    let cmd = &ctx.cmd;
    let key: &[u8] = cmd[2];

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        None => resp_error("ERR no such key"),
        Some(ValueRef::Stream(s)) => {
            let inner = s.read();
            // XINFO STREAM key FULL [COUNT count]
            if let Some(full) = cmd.get(3) {
                if !full.eq_ignore_ascii_case(b"FULL") {
                    return resp_error("ERR syntax error");
                }
                let count = match cmd.len() {
                    4 => 10,
                    6 if cmd[4].eq_ignore_ascii_case(b"COUNT") => {
                        match parse_utf8(cmd[5]).and_then(|s| s.parse::<i64>().ok()) {
                            // Zero is "all of them".
                            Some(0) => usize::MAX,
                            Some(n) if n > 0 => n as usize,
                            _ => {
                                return resp_error("ERR value is not an integer or out of range");
                            }
                        }
                    }
                    _ => return resp_error("ERR syntax error"),
                };
                let idmp_defaults = stream_extra::idmp_defaults(ctx.config);
                return xinfo_stream_full(resp, &inner, count, idmp_defaults);
            }
            let first_entry = inner
                .entries
                .iter()
                .next()
                .map(|(id, e)| format_entry(id, e))
                .unwrap_or_else(|| resp_null_for(resp));
            let last_entry = inner
                .entries
                .iter()
                .next_back()
                .map(|(id, e)| format_entry(id, e))
                .unwrap_or_else(|| resp_null_for(resp));

            let (idmp_duration, idmp_maxsize) =
                stream_extra::idmp_settings(&inner, stream_extra::idmp_defaults(ctx.config));
            let (pids_tracked, iids_tracked) = stream_extra::idmp_tracked(
                &inner,
                stream_extra::idmp_defaults(ctx.config),
                now_ms(),
            );

            resp_map_for(
                resp,
                vec![
                    resp_bulk_str("length"),
                    resp_integer(inner.entries.len() as i64),
                    // There is no radix tree here. These are what Redis's
                    // would hold: a key for each node of entries (see
                    // `Approx`), and a node or so above them.
                    resp_bulk_str("radix-tree-keys"),
                    resp_integer(stream_extra::node_count(&inner) as i64),
                    resp_bulk_str("radix-tree-nodes"),
                    resp_integer(match stream_extra::node_count(&inner) {
                        0 => 1,
                        nodes => nodes as i64 + 1,
                    }),
                    resp_bulk_str("last-generated-id"),
                    resp_bulk_str(&inner.last_id.to_string()),
                    resp_bulk_str("max-deleted-entry-id"),
                    resp_bulk_str(&inner.max_deleted_id.to_string()),
                    resp_bulk_str("entries-added"),
                    resp_integer(inner.entries_added as i64),
                    resp_bulk_str("recorded-first-entry-id"),
                    resp_bulk_str(&first_entry_id(&inner).to_string()),
                    resp_bulk_str("groups"),
                    resp_integer(inner.groups.len() as i64),
                    // Idempotent production (Redis 8.6).
                    resp_bulk_str("idmp-duration"),
                    resp_integer(idmp_duration as i64),
                    resp_bulk_str("idmp-maxsize"),
                    resp_integer(idmp_maxsize as i64),
                    resp_bulk_str("pids-tracked"),
                    resp_integer(pids_tracked as i64),
                    resp_bulk_str("iids-tracked"),
                    resp_integer(iids_tracked as i64),
                    resp_bulk_str("iids-added"),
                    resp_integer(inner.idmp.iids_added as i64),
                    resp_bulk_str("iids-duplicates"),
                    resp_integer(inner.idmp.iids_duplicates as i64),
                    resp_bulk_str("first-entry"),
                    first_entry,
                    resp_bulk_str("last-entry"),
                    last_entry,
                ],
            )
        }
        Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
    }
}

/// The ID of the stream's first entry; `0-0` if it has none.
fn first_entry_id(stream: &StreamInner) -> StreamId {
    stream
        .entries
        .keys()
        .next()
        .cloned()
        .unwrap_or_else(StreamId::min)
}

/// A group's `entries-read` and `lag`, as `XINFO` shows them: nil where
/// the number is not known.
fn read_and_lag(resp: u8, stream: &StreamInner, g: &ConsumerGroup) -> (Vec<u8>, Vec<u8>) {
    let entries_read = if g.entries_read == ConsumerGroup::NO_COUNT {
        resp_null_for(resp)
    } else {
        resp_integer(g.entries_read as i64)
    };
    let lag = match stream_extra::Shape::of(stream).lag(g) {
        Some(lag) => resp_integer(lag as i64),
        None => resp_null_for(resp),
    };
    (entries_read, lag)
}

/// The groups of a stream, by name: the order Redis lists them in.
fn groups_in_order(stream: &StreamInner) -> Vec<&ConsumerGroup> {
    let mut groups: Vec<&ConsumerGroup> = stream.groups.values().collect();
    groups.sort_by(|a, b| a.name.cmp(&b.name));
    groups
}

/// A group's consumers, by name.
fn consumers_in_order(g: &ConsumerGroup) -> Vec<(&crate::types::StreamName, u64)> {
    let mut consumers: Vec<(&crate::types::StreamName, u64)> = g
        .consumers
        .iter()
        .map(|(name, seen)| (name, *seen))
        .collect();
    consumers.sort();
    consumers
}

/// `XINFO STREAM key FULL`: the stream, its entries, and every group with
/// its pending list and its consumers with theirs — the first `count` of
/// each.
fn xinfo_stream_full(
    resp: u8,
    inner: &StreamInner,
    count: usize,
    idmp_defaults: (u64, u64),
) -> Vec<u8> {
    let entries: Vec<Vec<u8>> = inner
        .entries
        .iter()
        .take(count)
        .map(|(id, e)| format_entry(id, e))
        .collect();
    let groups: Vec<Vec<u8>> = groups_in_order(inner)
        .into_iter()
        .map(|g| {
            let (entries_read, lag) = read_and_lag(resp, inner, g);
            let pel: Vec<Vec<u8>> = g
                .pel
                .iter()
                .take(count)
                .map(|(id, p)| {
                    resp_array(vec![
                        resp_bulk_str(&id.to_string()),
                        resp_bulk(&p.consumer),
                        resp_integer(shown_delivery_time(p.delivered_at)),
                        resp_integer(p.delivery_count as i64),
                    ])
                })
                .collect();
            let consumers: Vec<Vec<u8>> = consumers_in_order(g)
                .into_iter()
                .map(|(name, seen)| {
                    let own = || g.pel.iter().filter(|(_, p)| p.consumer == *name);
                    let pel: Vec<Vec<u8>> = own()
                        .take(count)
                        .map(|(id, p)| {
                            resp_array(vec![
                                resp_bulk_str(&id.to_string()),
                                resp_integer(shown_delivery_time(p.delivered_at)),
                                resp_integer(p.delivery_count as i64),
                            ])
                        })
                        .collect();
                    resp_map_for(
                        resp,
                        vec![
                            resp_bulk_str("name"),
                            resp_bulk(name),
                            resp_bulk_str("seen-time"),
                            resp_integer(seen as i64),
                            resp_bulk_str("active-time"),
                            resp_integer(g.active.get(name).map_or(-1, |at| *at as i64)),
                            resp_bulk_str("pel-count"),
                            resp_integer(own().count() as i64),
                            resp_bulk_str("pending"),
                            resp_array(pel),
                        ],
                    )
                })
                .collect();
            resp_map_for(
                resp,
                vec![
                    resp_bulk_str("name"),
                    resp_bulk(&g.name),
                    resp_bulk_str("last-delivered-id"),
                    resp_bulk_str(&g.last_id.to_string()),
                    resp_bulk_str("entries-read"),
                    entries_read,
                    resp_bulk_str("lag"),
                    lag,
                    resp_bulk_str("pel-count"),
                    resp_integer(g.pel.len() as i64),
                    // Entries `XNACK` released: pending, and no one's.
                    resp_bulk_str("nacked-count"),
                    resp_integer(g.pel.values().filter(|p| p.consumer.is_empty()).count() as i64),
                    // Redis 8.10's name for the pending entries, here and
                    // for each consumer (it was `pel`).
                    resp_bulk_str("pending"),
                    resp_array(pel),
                    resp_bulk_str("consumers"),
                    resp_array(consumers),
                ],
            )
        })
        .collect();
    let (idmp_duration, idmp_maxsize) = stream_extra::idmp_settings(inner, idmp_defaults);
    let (pids_tracked, iids_tracked) = stream_extra::idmp_tracked(inner, idmp_defaults, now_ms());
    let nodes = stream_extra::node_count(inner);
    resp_map_for(
        resp,
        vec![
            resp_bulk_str("length"),
            resp_integer(inner.entries.len() as i64),
            resp_bulk_str("radix-tree-keys"),
            resp_integer(nodes as i64),
            resp_bulk_str("radix-tree-nodes"),
            resp_integer(if nodes == 0 { 1 } else { nodes as i64 + 1 }),
            resp_bulk_str("last-generated-id"),
            resp_bulk_str(&inner.last_id.to_string()),
            resp_bulk_str("max-deleted-entry-id"),
            resp_bulk_str(&inner.max_deleted_id.to_string()),
            resp_bulk_str("entries-added"),
            resp_integer(inner.entries_added as i64),
            resp_bulk_str("recorded-first-entry-id"),
            resp_bulk_str(&first_entry_id(inner).to_string()),
            // Idempotent production (Redis 8.6).
            resp_bulk_str("idmp-duration"),
            resp_integer(idmp_duration as i64),
            resp_bulk_str("idmp-maxsize"),
            resp_integer(idmp_maxsize as i64),
            resp_bulk_str("pids-tracked"),
            resp_integer(pids_tracked as i64),
            resp_bulk_str("iids-tracked"),
            resp_integer(iids_tracked as i64),
            resp_bulk_str("iids-added"),
            resp_integer(inner.idmp.iids_added as i64),
            resp_bulk_str("iids-duplicates"),
            resp_integer(inner.idmp.iids_duplicates as i64),
            resp_bulk_str("entries"),
            resp_array(entries),
            resp_bulk_str("groups"),
            resp_array(groups),
        ],
    )
}

fn xinfo_groups(ctx: &mut Ctx) -> Vec<u8> {
    // XINFO GROUPS key — an array of per-group maps (`addReplyMapLen` per group).
    let resp = reply_resp(ctx);
    let cmd = &ctx.cmd;
    let key: &[u8] = cmd[2];

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        None => resp_error("ERR no such key"),
        Some(ValueRef::Stream(s)) => {
            let inner = s.read();
            let groups: Vec<Vec<u8>> = groups_in_order(&inner)
                .into_iter()
                .map(|g| {
                    let (entries_read, lag) = read_and_lag(resp, &inner, g);
                    resp_map_for(
                        resp,
                        vec![
                            resp_bulk_str("name"),
                            resp_bulk(&g.name),
                            resp_bulk_str("consumers"),
                            resp_integer(g.consumers.len() as i64),
                            resp_bulk_str("pending"),
                            resp_integer(g.pel.len() as i64),
                            resp_bulk_str("last-delivered-id"),
                            resp_bulk_str(&g.last_id.to_string()),
                            resp_bulk_str("entries-read"),
                            entries_read,
                            resp_bulk_str("lag"),
                            lag,
                        ],
                    )
                })
                .collect();
            resp_array(groups)
        }
        Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
    }
}

fn xinfo_consumers(ctx: &mut Ctx) -> Vec<u8> {
    // XINFO CONSUMERS key group — an array of per-consumer maps.
    let resp = reply_resp(ctx);
    let cmd = &ctx.cmd;
    if cmd.len() < 4 {
        return resp_error("ERR wrong number of arguments for 'xinfo|consumers' command");
    }
    let key: &[u8] = cmd[2];
    let group = crate::types::StreamName::from(cmd[3]);

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        None => resp_error("ERR no such key"),
        Some(ValueRef::Stream(s)) => {
            let inner = s.read();
            let g = match inner.groups.get(&group) {
                None => return resp_error("NOGROUP No such consumer group"),
                Some(g) => g,
            };
            let now = now_ms();
            let consumers: Vec<Vec<u8>> = consumers_in_order(g)
                .into_iter()
                .map(|(name, last_seen)| {
                    let pending = g.pel.values().filter(|p| p.consumer == *name).count() as i64;
                    let idle = now.saturating_sub(last_seen);
                    // Since it was last handed entries; -1 if it never was.
                    let inactive = g
                        .active
                        .get(name)
                        .map_or(-1, |at| now.saturating_sub(*at) as i64);
                    resp_map_for(
                        resp,
                        vec![
                            resp_bulk_str("name"),
                            resp_bulk(name),
                            resp_bulk_str("pending"),
                            resp_integer(pending),
                            resp_bulk_str("idle"),
                            resp_integer(idle as i64),
                            resp_bulk_str("inactive"),
                            resp_integer(inactive),
                        ],
                    )
                })
                .collect();
            resp_array(consumers)
        }
        Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
    }
}

// ── XGROUP dispatcher ─────────────────────────────────────────────────────────

pub fn xgroup(ctx: &mut Ctx) -> Vec<u8> {
    let cmd = &ctx.cmd;
    if cmd.len() < 2 {
        return resp_error("ERR wrong number of arguments for 'xgroup' command");
    }
    match std::str::from_utf8(cmd[1])
        .unwrap_or("")
        .to_ascii_uppercase()
        .as_str()
    {
        "CREATE" => xgroup_create(ctx),
        "DESTROY" => xgroup_destroy(ctx),
        "SETID" => xgroup_setid(ctx),
        "CREATECONSUMER" => xgroup_createconsumer(ctx),
        "DELCONSUMER" => xgroup_delconsumer(ctx),
        "HELP" if cmd.len() == 2 => help_reply(
            "XGROUP",
            &[
                "CREATE <key> <groupname> <id|$> [option]",
                "    Create a new consumer group. Options are:",
                "    * MKSTREAM",
                "      Create the empty stream if it does not exist.",
                "    * ENTRIESREAD entries_read",
                "      Set the group's entries_read counter (internal use).",
                "CREATECONSUMER <key> <groupname> <consumer>",
                "    Create a new consumer in the specified group.",
                "DELCONSUMER <key> <groupname> <consumer>",
                "    Remove the specified consumer.",
                "DESTROY <key> <groupname>",
                "    Remove the specified group.",
                "SETID <key> <groupname> <id|$> [ENTRIESREAD entries_read]",
                "    Set the current group ID and entries_read counter.",
            ],
        ),
        _ => unknown_subcommand("XGROUP", cmd[1]),
    }
}

/// Called after every successful XADD to wake any blocked XREAD clients.
fn notify_xread_waiters(ctx: &Ctx, key: &[u8]) {
    ctx.wait_table.notify_stream_waiters(key);
}

// ── XDELEX ───────────────────────────────────────────────────────────────────
//
// XDELEX key [KEEPREF | DELREF | ACKED] IDS numids id [id ...]
//
// Delete entries by ID, saying what happens to consumer groups' references:
//   KEEPREF (default) — delete the entry; pending-list references stay.
//   DELREF            — delete the entry and every pending-list reference to
//                       it, including references to an entry already gone.
//   ACKED             — delete the entry only if every consumer group has read
//                       and acknowledged it.
//
// Per ID:
//    1  → deleted
//   -1  → no such entry in the stream
//    2  → not deleted: still referenced (ACKED). With no consumer groups
//         nothing refers to it, and ACKED deletes it (Redis 8.10).

pub fn xdelex(ctx: &mut Ctx) -> Vec<u8> {
    let cmd = &ctx.cmd;
    if cmd.len() < 5 {
        return resp_error("ERR wrong number of arguments for 'xdelex' command");
    }
    let key: Vec<u8> = cmd[1].to_vec();
    let (refs, ids) = match stream_extra::parse_policy_and_ids(&cmd[2..], false) {
        Ok(parsed) => parsed,
        Err(e) => return e,
    };

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, &key);
    let map = read_lock!(shard);
    let stream = match map.get(key.as_slice()) {
        // No stream → every id is -1.
        None => return resp_array(ids.iter().map(|_| resp_integer(-1)).collect()),
        Some(ValueRef::Stream(s)) => Arc::clone(s),
        Some(_) => {
            return resp_error("WRONGTYPE Operation against a key holding the wrong kind of value");
        }
    };
    drop(map);
    let mut inner = stream.write();

    let replies = ids
        .iter()
        .map(|id| {
            if !inner.entries.contains_key(id) {
                // DELREF still clears references left behind by an entry
                // that was deleted some other way.
                if refs == TrimRefs::DelRef {
                    stream_extra::delete_entry(&mut inner, id, refs);
                }
                return resp_integer(-1);
            }
            // With no groups, nothing refers to it (Redis 8.10).
            if stream_extra::delete_entry(&mut inner, id, refs) {
                resp_integer(1)
            } else {
                resp_integer(2)
            }
        })
        .collect();
    resp_array(replies)
}

// ── XACKDEL ───────────────────────────────────────────────────────────────────
//
// XACKDEL key group [KEEPREF | DELREF | ACKED] IDS numids id [id ...]
//
// XACK and XDELEX in one step: acknowledge each ID in the group and delete
// the entry, under one lock, so no other client sees one without the other.
// The older KiviDB form `XACKDEL key group id [id ...]` is still accepted.
//
// Per ID:
//    1  → acknowledged, and the entry deleted
//   -1  → not pending in this group: nothing acknowledged, nothing deleted
//    2  → acknowledged, but the entry stays: another group has still to read
//         or acknowledge it (ACKED)

pub fn xackdel(ctx: &mut Ctx) -> Vec<u8> {
    let cmd = &ctx.cmd;
    if cmd.len() < 4 {
        return resp_error("ERR wrong number of arguments for 'xackdel' command");
    }
    let key: Vec<u8> = cmd[1].to_vec();
    let group_name = crate::types::StreamName::from(cmd[2]);
    let (refs, ids) = match stream_extra::parse_policy_and_ids(&cmd[3..], true) {
        Ok(parsed) => parsed,
        Err(e) => return e,
    };

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, &key);
    let stream = {
        let map = read_lock!(shard);
        match map.get(key.as_slice()) {
            Some(ValueRef::Stream(s)) => Arc::clone(s),
            Some(_) => {
                return resp_error(
                    "WRONGTYPE Operation against a key holding the wrong kind of value",
                );
            }
            // No such key: -1 for every ID.
            None => return resp_array(ids.iter().map(|_| resp_integer(-1)).collect()),
        }
    };

    // One write lock covers the acknowledgement and the deletion.
    let mut inner = stream.write();
    // No such group: -1 for every ID, as for no such key (Redis 8.10).
    if !inner.groups.contains_key(&group_name) {
        return resp_array(ids.iter().map(|_| resp_integer(-1)).collect());
    }

    let replies = ids
        .iter()
        .map(|id| {
            let was_pending = inner
                .groups
                .get_mut(&group_name)
                .is_some_and(|group| group.pel.remove(id).is_some());
            if !was_pending {
                return resp_integer(-1);
            }
            if stream_extra::delete_entry(&mut inner, id, refs) {
                resp_integer(1)
            } else {
                resp_integer(2)
            }
        })
        .collect();
    resp_array(replies)
}

// ── XCFGSET ───────────────────────────────────────────────────────────────────
//
// XCFGSET key field value [field value ...]
//
// Sets per-stream configuration.
//
//   IDMP-DURATION seconds — how long an idempotent ID is remembered
//                           (1-86400; Redis 8.6).
//   IDMP-MAXSIZE n        — how many idempotent IDs are remembered per
//                           producer (1-10000; Redis 8.6).
//
// Setting either clears every producer's remembered IDs for the stream, as
// in Redis.
//
// Two further fields are KiviDB extensions:
//
//   MAX-ENTRIES n      — persistent MAXLEN policy. Every future XADD trims
//                        the stream to at most n entries after inserting.
//                        Set to 0 to remove the policy (no limit).
//
//   MAX-DELETED-ENTRY-ID id — update the stream's tracked max deleted ID.
//                             Used by replication to track the highest ID
//                             that has ever been deleted. Clients can use
//                             XINFO STREAM to read this back.
//
// Returns OK on success. Errors on:
//   - wrong type
//   - missing/non-existent key (XCFGSET does not create streams)
//   - unknown field name
//   - bad value format

pub fn xcfgset(ctx: &mut Ctx) -> Vec<u8> {
    let cmd = &ctx.cmd;

    // XCFGSET key field value [field value ...]
    if cmd.len() < 2 {
        return resp_error("ERR wrong number of arguments for 'xcfgset' command");
    }

    let key: Vec<u8> = cmd[1].to_vec();

    // XCFGSET does not create streams — get-only, not get-or-create.
    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, &key);
    let map = read_lock!(shard);

    let stream_arc = match map.get(key.as_slice()) {
        Some(ValueRef::Stream(s)) => Arc::clone(s),
        Some(_) => {
            return resp_error("WRONGTYPE Operation against a key holding the wrong kind of value");
        }
        None => return resp_error("ERR no such key"),
    };
    drop(map); // release shard read lock before taking StreamInner write lock

    // Parse all field/value pairs up-front so a bad pair rejects the whole
    // command rather than partially applying it. Mirrors how CONFIG SET works.
    struct Patch {
        max_entries: Option<Option<u64>>, // None = not specified, Some(None) = clear, Some(Some(n)) = set
        max_deleted_id: Option<StreamId>,
        idmp_duration: Option<u64>,
        idmp_maxsize: Option<u64>,
    }
    let mut patch = Patch {
        max_entries: None,
        max_deleted_id: None,
        idmp_duration: None,
        idmp_maxsize: None,
    };

    let mut i = 2usize;
    while i < cmd.len() {
        let field = match parse_utf8(cmd[i]) {
            Some(f) => f.to_ascii_uppercase(),
            None => return resp_error("ERR syntax error"),
        };
        // Every parameter takes a value; one without is a syntax error.
        let Some(raw) = cmd.get(i + 1) else {
            return resp_error("ERR syntax error");
        };
        let value = match parse_utf8(raw) {
            Some(v) => v.to_string(),
            None => return resp_error("ERR value is not an integer or out of range"),
        };

        match field.as_str() {
            "MAX-ENTRIES" => {
                let n: u64 = match value.parse() {
                    Ok(n) => n,
                    Err(_) => return resp_error("ERR value is not an integer or out of range"),
                };
                // 0 means "remove the policy" — stored as None
                patch.max_entries = Some(if n == 0 { None } else { Some(n) });
            }
            "IDMP-DURATION" | "IDMP-MAXSIZE" => {
                let (slot, range, unit) = if field == "IDMP-DURATION" {
                    (
                        &mut patch.idmp_duration,
                        stream_extra::IDMP_DURATION_RANGE,
                        "seconds",
                    )
                } else {
                    (
                        &mut patch.idmp_maxsize,
                        stream_extra::IDMP_MAXSIZE_RANGE,
                        "entries",
                    )
                };
                if slot.is_some() {
                    return resp_error(&format!("ERR {field} specified multiple times"));
                }
                let Some(n) = stream_extra::strict_integer(raw) else {
                    return resp_error("ERR value is not an integer or out of range");
                };
                if !(*range.start() as i64..=*range.end() as i64).contains(&n) {
                    return resp_error(&format!(
                        "ERR {field} must be between {} and {} {unit}",
                        range.start(),
                        range.end()
                    ));
                }
                *slot = Some(n as u64);
            }
            "MAX-DELETED-ENTRY-ID" => match StreamId::parse(&value) {
                Some(id) => patch.max_deleted_id = Some(id),
                None => {
                    return resp_error(
                        "ERR Invalid stream ID specified as stream command argument",
                    );
                }
            },
            _ => return resp_error("ERR syntax error"),
        }
        i += 2;
    }
    if patch.max_entries.is_none()
        && patch.max_deleted_id.is_none()
        && patch.idmp_duration.is_none()
        && patch.idmp_maxsize.is_none()
    {
        return resp_error("ERR At least one parameter must be specified");
    }
    let defaults = stream_extra::idmp_defaults(ctx.config);

    // Apply the patch atomically under a single write lock.
    let mut inner = stream_arc.write();

    if let Some(policy) = patch.max_entries {
        inner.max_entries = policy;

        // Trim immediately if the current length already exceeds the new limit.
        if let Some(max) = inner.max_entries {
            while inner.entries.len() as u64 > max {
                if let Some((id, _)) = inner.entries.pop_first()
                    && id > inner.max_deleted_id
                {
                    inner.max_deleted_id = id;
                }
            }
        }
    }

    if let Some(id) = patch.max_deleted_id {
        // Only advance — never move max_deleted_id backwards.
        if id > inner.max_deleted_id {
            inner.max_deleted_id = id;
        }
    }

    // A value other than the one in force clears the remembered IDs, which
    // were kept under it; the same value keeps them, so that several
    // producers may each set it before they start (Redis 8.10).
    let mut changed = false;
    if let Some(duration) = patch.idmp_duration {
        changed |= inner.idmp.duration_secs.unwrap_or(defaults.0) != duration;
        inner.idmp.duration_secs = Some(duration);
    }
    if let Some(maxsize) = patch.idmp_maxsize {
        changed |= inner.idmp.maxsize.unwrap_or(defaults.1) != maxsize;
        inner.idmp.maxsize = Some(maxsize);
    }
    if changed {
        inner.idmp.producers.clear();
    }

    resp_simple("OK")
}

// ── XNACK (Redis 8.8) ────────────────────────────────────────────────────────

/// `XNACK key group <SILENT | FAIL | FATAL> IDS numids id [id ...]
///        [RETRYCOUNT count] [FORCE]`
///
/// Releases pending entries back to the group PEL *without* acknowledging them,
/// so another consumer can pick them up immediately instead of waiting out a
/// min-idle-time. Each released entry is marked unowned (empty consumer) and
/// given a delivery time of 0, which is what makes it claimable regardless of
/// the `min-idle-time` argument to XCLAIM/XAUTOCLAIM.
///
/// Deviation worth knowing: Redis keeps NACKed entries in a dedicated zone at
/// the head of the PEL so they are *prioritised* over other pending entries.
/// KiviDB's PEL is a `BTreeMap` keyed by stream ID, so ordering stays by ID.
/// The functional effect — immediate claimability — is preserved via the
/// delivery-time-0 marker; the relative ordering against other already-idle
/// entries is not. Documented in `docs/REDIS_8_8_COMMANDS.md`.
/// A pending entry's delivery time as `XINFO STREAM FULL` shows it: 0 for
/// one `XNACK` released, as in Redis (see `stream_extra::nack_time`).
fn shown_delivery_time(delivered_at: u64) -> i64 {
    if delivered_at < stream_extra::NACKED_BELOW {
        0
    } else {
        delivered_at as i64
    }
}

pub fn xnack(ctx: &mut Ctx) -> Vec<u8> {
    let cmd = &ctx.cmd;
    // key group MODE IDS numids id  → 7 minimum
    if cmd.len() < 7 {
        return resp_error("ERR wrong number of arguments for 'xnack' command");
    }
    let key: &[u8] = cmd[1];
    let group = crate::types::StreamName::from(cmd[2]);

    #[derive(Clone, Copy, PartialEq)]
    enum Mode {
        Silent,
        Fail,
        Fatal,
    }
    let mode = if cmd[3].eq_ignore_ascii_case(b"SILENT") {
        Mode::Silent
    } else if cmd[3].eq_ignore_ascii_case(b"FAIL") {
        Mode::Fail
    } else if cmd[3].eq_ignore_ascii_case(b"FATAL") {
        Mode::Fatal
    } else {
        return resp_error("ERR mode must be SILENT, FAIL, or FATAL");
    };

    // The options, in any order, as Redis reads them: `IDS numids id ...`,
    // `FORCE`, `RETRYCOUNT n`.
    let mut ids_at: Option<(usize, usize)> = None;
    let mut retrycount: Option<u64> = None;
    let mut force = false;
    let mut i = 4;
    while i < cmd.len() {
        let more = i + 1 < cmd.len();
        if cmd[i].eq_ignore_ascii_case(b"IDS") && more {
            let numids = match parse_utf8(cmd[i + 1]).and_then(|s| s.parse::<i64>().ok()) {
                Some(n) if (1..=i64::from(i32::MAX)).contains(&n) => n as usize,
                _ => return resp_error("ERR numids must be a positive integer"),
            };
            if numids > cmd.len() - (i + 2) {
                return resp_error("ERR number of IDs doesn't match numids");
            }
            ids_at = Some((i + 2, numids));
            i += 2 + numids;
        } else if cmd[i].eq_ignore_ascii_case(b"FORCE") {
            force = true;
            i += 1;
        } else if cmd[i].eq_ignore_ascii_case(b"RETRYCOUNT") && more {
            match parse_utf8(cmd[i + 1]).and_then(|s| s.parse::<i64>().ok()) {
                Some(n) if n >= 0 => retrycount = Some(n as u64),
                Some(_) => return resp_error("ERR Invalid RETRYCOUNT value, must be >= 0"),
                None => return resp_error("ERR value is not an integer or out of range"),
            }
            i += 2;
        } else {
            return resp_error(&format!(
                "ERR Unrecognized XNACK option '{}'",
                String::from_utf8_lossy(cmd[i])
            ));
        }
    }
    let Some((ids_from, numids)) = ids_at else {
        return resp_error("ERR syntax error, expected IDS keyword");
    };
    let mut ids: Vec<StreamId> = Vec::with_capacity(numids);
    for raw in &cmd[ids_from..ids_from + numids] {
        match StreamId::parse(std::str::from_utf8(raw).unwrap_or("")) {
            Some(id) => ids.push(id),
            None => {
                return resp_error("ERR Invalid stream ID specified as stream command argument");
            }
        }
    }
    let no_group = || {
        resp_error_bytes(
            &[
                &b"NOGROUP No such key '"[..],
                c_str(key),
                &b"' or consumer group '"[..],
                c_str(group.as_bytes()),
                &b"'"[..],
            ]
            .concat(),
        )
    };

    let db_ref = &ctx.store[*ctx.selected_db];
    let shard = store::get_shard(db_ref, key);
    let map = read_lock!(shard);

    match map.get(key) {
        None => no_group(),
        Some(ValueRef::Stream(s)) => {
            let mut inner = s.write();
            // FORCE needs to know which IDs exist in the stream; take that set
            // before borrowing `groups` mutably.
            let existing_ids: Vec<bool> = if force {
                ids.iter()
                    .map(|id| inner.entries.contains_key(id))
                    .collect()
            } else {
                Vec::new()
            };

            let Some(g) = inner.groups.get_mut(&group) else {
                return no_group();
            };

            let mut released = 0i64;
            for (pos, id) in ids.iter().enumerate() {
                match g.pel.get_mut(id) {
                    Some(entry) => {
                        entry.delivery_count = match retrycount {
                            // RETRYCOUNT overrides the mode-based adjustment.
                            Some(n) => n,
                            None => match mode {
                                // "Undo" the delivery increment.
                                Mode::Silent => entry.delivery_count.saturating_sub(1),
                                // Leave the counter alone — another consumer's turn.
                                Mode::Fail => entry.delivery_count,
                                // Permanently failed: LLONG_MAX.
                                Mode::Fatal => i64::MAX as u64,
                            },
                        };
                        // Unowned, and immediately claimable, after what
                        // was released before it.
                        entry.consumer = crate::types::StreamName::default();
                        entry.delivered_at = stream_extra::nack_time();
                        released += 1;
                    }
                    None if force => {
                        // FORCE creates an unowned PEL entry, but only for IDs
                        // that actually exist in the stream.
                        if !existing_ids.get(pos).copied().unwrap_or(false) {
                            continue;
                        }
                        let delivery_count = match (retrycount, mode) {
                            (Some(n), _) => n,
                            (None, Mode::Fatal) => i64::MAX as u64,
                            (None, _) => 0,
                        };
                        g.pel.insert(
                            id.clone(),
                            PelEntry {
                                consumer: crate::types::StreamName::default(),
                                delivered_at: stream_extra::nack_time(),
                                delivery_count,
                            },
                        );
                        released += 1;
                    }
                    // Not pending and no FORCE — ignored, not counted.
                    None => {}
                }
            }
            resp_integer(released)
        }
        Some(_) => resp_error("WRONGTYPE Operation against a key holding the wrong kind of value"),
    }
}