redis-tower 0.1.2

A Tower-based Redis client with strong typing, composable middleware, and resilience
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
//! Auto-pipelining middleware for transparent batching of concurrent requests.
//!
//! When multiple tasks issue commands concurrently, instead of sending them
//! one at a time, [`AutoPipelineService`] collects them into a batch and
//! sends them as a single Redis pipeline. Each caller gets back their
//! individual response.
//!
//! # Example
//!
//! ```no_run
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use redis_tower::{AutoPipelineConfig, AutoPipelineService, CommandAdapter, RedisConnection};
//! use redis_tower::commands::*;
//! use tower::Service;
//!
//! let conn = RedisConnection::connect("127.0.0.1:6379").await?;
//! let mut svc = CommandAdapter::new(AutoPipelineService::new(conn, AutoPipelineConfig::default()));
//! let value: Option<bytes::Bytes> = svc.call(Get::new("key")).await?;
//! # let _ = value;
//! # Ok(())
//! # }
//! ```

use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};

use redis_tower_core::{Frame, ReceivedPushFrame, RedisConnection, RedisError};
use tokio::sync::{mpsc, oneshot, watch};
use tokio_util::sync::PollSender;
use tower_service::Service;
use tracing::warn;

use crate::maintenance::{
    MaintenanceControl, MaintenanceListenerHandle, MaintenanceState, ParsedMaintenanceNotification,
    next_listener_id, parse_maintenance_push, register_connection,
};
use crate::metrics_layer::MetricsRecorder;
use crate::reconnect::{
    ConnectionDisconnectReason, ConnectionEvent, ConnectionEventBus, ConnectionFactory,
    ReconnectConfig, connect_with_timeout,
};

/// Configuration for the auto-pipelining service.
#[derive(Clone)]
pub struct AutoPipelineConfig {
    /// Maximum commands to batch before sending. Default: 100.
    pub max_batch_size: usize,
    /// Time to wait for more commands after draining the immediate queue.
    ///
    /// Default: 0 (no wait -- flushes immediately, only batches requests
    /// that arrive concurrently). Set to 1-2ms for write-heavy workloads
    /// where batching reduces round-trips.
    pub batch_window: Duration,
    /// Capacity of the internal command queue (number of pending requests
    /// that can be buffered).
    ///
    /// When the queue is full, the default behavior is back-pressure: a new
    /// request awaits a free slot (its `poll_ready` returns `Pending`). Set
    /// [`shed_load_on_full`](Self::shed_load_on_full) to fail fast with
    /// `RedisError::QueueFull` instead.
    ///
    /// Default: 1024.
    pub queue_capacity: usize,
    /// Fail fast instead of applying back-pressure when the queue is full.
    ///
    /// When `false` (default), a caller awaits a free slot before its request
    /// is accepted -- real back-pressure that paces producers to the worker's
    /// drain rate. When `true`, a full queue makes the call return
    /// `RedisError::QueueFull` immediately (load shedding), which suits callers
    /// that prefer to reject rather than wait.
    ///
    /// Default: `false`.
    pub shed_load_on_full: bool,
    /// Maximum time to wait for a batch's responses before treating the
    /// connection as failed.
    ///
    /// `None` (default) means no response deadline: a hung or black-holed node
    /// can stall this worker's whole queue until OS TCP keepalive eventually
    /// fires (minutes). Set a value so a stuck node is detected promptly -- the
    /// in-flight batch fails with [`RedisError::CommandTimeout`] and the worker
    /// discards the connection (factory-backed clients then reconnect with
    /// backoff, so a new connection serves subsequent requests).
    ///
    /// The deadline covers a whole pipelined batch's round-trip, so size it
    /// above your slowest legitimate command (a long `BLPOP`/`WAIT`/`DEBUG
    /// SLEEP` will trip it).
    ///
    /// Default: `None`.
    pub response_timeout: Option<Duration>,
    /// Optional metrics recorder for worker-level observability.
    ///
    /// When set, the background worker calls
    /// [`MetricsRecorder::pipeline_flushed`] after each batch flush, reporting
    /// how many frames went out together. This is the one signal only the
    /// worker can see -- a histogram of it shows whether auto-pipelining is
    /// actually batching (`> 1`) or every caller flushes alone (`== 1`).
    ///
    /// For per-command latency/error metrics and tracing spans, wrap the
    /// client in [`MetricsLayer`](crate::MetricsLayer) /
    /// [`TracingLayer`](crate::TracingLayer) via
    /// [`MultiplexedClient::from_layered`](crate::MultiplexedClient::from_layered) --
    /// those compose at the `Service<Frame>` layer where per-command timing is
    /// available.
    ///
    /// Default: `None`.
    pub metrics_recorder: Option<Arc<dyn MetricsRecorder>>,
    /// Treat a `READONLY` reply as a signal that the connection points at a
    /// replica and the worker should reconnect via its factory.
    ///
    /// Off by default. A factory-backed Sentinel client enables this: when a
    /// master is demoted to a replica (`REPLICAOF`) with TCP intact, writes
    /// come back `READONLY` rather than as a connection error, so without this
    /// the worker would keep serving the demoted node forever. With it on, the
    /// caller still receives the `READONLY` error for the current command and
    /// the worker reconnects (re-querying Sentinel) so the next batch lands on
    /// the new master. Standalone and cluster clients leave this off.
    ///
    /// Default: `false`.
    pub reconnect_on_readonly: bool,
}

impl std::fmt::Debug for AutoPipelineConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AutoPipelineConfig")
            .field("max_batch_size", &self.max_batch_size)
            .field("batch_window", &self.batch_window)
            .field("queue_capacity", &self.queue_capacity)
            .field("shed_load_on_full", &self.shed_load_on_full)
            .field("response_timeout", &self.response_timeout)
            .field(
                "metrics_recorder",
                &self.metrics_recorder.as_ref().map(|_| "<recorder>"),
            )
            .field("reconnect_on_readonly", &self.reconnect_on_readonly)
            .finish()
    }
}

impl Default for AutoPipelineConfig {
    fn default() -> Self {
        Self {
            max_batch_size: 100,
            batch_window: Duration::ZERO,
            queue_capacity: 1024,
            shed_load_on_full: false,
            response_timeout: None,
            metrics_recorder: None,
            reconnect_on_readonly: false,
        }
    }
}

/// Reconnect policy for a factory-backed [`AutoPipelineService`].
///
/// Applies only when the service is constructed via
/// [`AutoPipelineService::with_factory`] or
/// [`AutoPipelineService::with_lazy_factory`]. The plain
/// [`AutoPipelineService::new`] path owns a single pre-built connection and
/// does not reconnect.
#[derive(Debug, Clone, Default)]
pub struct AutoPipelineReconnectConfig {
    /// Backoff parameters for reconnection attempts.
    ///
    /// Its [`ReconnectConfig::connect_timeout`] also bounds the initial
    /// factory call made by eager and lazy `with_factory` constructors.
    pub reconnect: ReconnectConfig,
}

impl AutoPipelineReconnectConfig {
    /// Create a new reconnect config with the given backoff parameters.
    pub fn new(reconnect: ReconnectConfig) -> Self {
        Self { reconnect }
    }
}

/// Source of the connection owned by the background worker.
enum ConnSource {
    /// Fixed pre-built connection: no reconnect on failure.
    Fixed,
    /// Factory-backed connection: rebuild on failure using the factory.
    Factory {
        factory: Arc<dyn ConnectionFactory>,
        reconnect: ReconnectConfig,
    },
}

struct MaintenanceWorker {
    state: MaintenanceState,
    control_rx: mpsc::UnboundedReceiver<MaintenanceControl>,
    push_rx: tokio::sync::broadcast::Receiver<ReceivedPushFrame>,
}

/// Why the pipeline worker discarded its current connection.
///
/// The owned Redis error is kept until event publication so formatting it is
/// skipped entirely when lifecycle events have no subscribers.
enum PipelineFailure {
    Connection(RedisError),
    CommandTimeout,
    ReadOnly,
}

impl PipelineFailure {
    fn event_reason(&self) -> ConnectionDisconnectReason {
        match self {
            Self::Connection(error) => ConnectionDisconnectReason::ConnectionError {
                error: Arc::from(error.to_string()),
            },
            Self::CommandTimeout => ConnectionDisconnectReason::CommandTimeout,
            Self::ReadOnly => ConnectionDisconnectReason::ReadOnly,
        }
    }
}

/// A request sent through the channel to the background worker.
///
/// Most callers send a `Single` frame. Callers that need multiple frames to
/// land on the wire contiguously (without other tasks' commands interleaving)
/// -- for example ASKING followed by a migrated command during a cluster
/// resharding -- send a `Multi` request instead. The worker guarantees that
/// all frames inside one `Multi` are flushed back-to-back in the same
/// `execute_pipeline` call.
enum WorkerRequest {
    Single {
        frame: Frame,
        response_tx: oneshot::Sender<Result<Frame, RedisError>>,
    },
    Multi {
        frames: Vec<Frame>,
        response_tx: oneshot::Sender<Result<Vec<Frame>, RedisError>>,
    },
}

impl WorkerRequest {
    fn frame_count(&self) -> usize {
        match self {
            WorkerRequest::Single { .. } => 1,
            WorkerRequest::Multi { frames, .. } => frames.len(),
        }
    }

    fn fail(self, err: RedisError) {
        match self {
            WorkerRequest::Single { response_tx, .. } => {
                let _ = response_tx.send(Err(err));
            }
            WorkerRequest::Multi { response_tx, .. } => {
                let _ = response_tx.send(Err(err));
            }
        }
    }

    /// Return whether the caller has dropped its response future.
    ///
    /// The worker checks this immediately before flattening a batch for the
    /// wire. Requests cancelled while waiting in `batch_window` must not be
    /// executed after their caller deadline has already expired.
    fn response_is_closed(&self) -> bool {
        match self {
            WorkerRequest::Single { response_tx, .. } => response_tx.is_closed(),
            WorkerRequest::Multi { response_tx, .. } => response_tx.is_closed(),
        }
    }
}

/// A `Service<Frame>` that transparently batches concurrent requests into
/// Redis pipelines for better throughput.
///
/// Uses a channel-based approach similar to Tower's `Buffer`:
///
/// 1. `call()` sends the request `Frame` plus a oneshot sender through a channel
/// 2. A background task collects requests for up to `batch_window` duration
///    or `max_batch_size` requests
/// 3. The background task sends all collected frames via `execute_pipeline`
/// 4. Each response is routed back via the corresponding oneshot sender
///
/// Compose with [`CommandAdapter`](crate::CommandAdapter) for typed commands:
///
/// ```no_run
/// # use redis_tower::{AutoPipelineConfig, AutoPipelineService, CommandAdapter, RedisConnection};
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let conn = RedisConnection::connect("127.0.0.1:6379").await?;
/// # let config = AutoPipelineConfig::default();
/// let svc = CommandAdapter::new(AutoPipelineService::new(conn, config));
/// # let _ = svc;
/// # Ok(())
/// # }
/// ```
pub struct AutoPipelineService {
    tx: mpsc::Sender<WorkerRequest>,
    /// Reservation-based view of the same channel, used for the back-pressure
    /// path: `poll_ready` reserves a slot via [`PollSender::poll_reserve`] and
    /// `call` fills it with [`PollSender::send_item`].
    poll_tx: PollSender<WorkerRequest>,
    /// When `true`, `call` uses `try_send` and a full queue yields `QueueFull`
    /// instead of awaiting capacity. Mirrors
    /// [`AutoPipelineConfig::shed_load_on_full`].
    shed_load: bool,
    /// Counts only public service handles. Dropping the final lease wakes and
    /// cancels a worker that may be inside reconnect backoff or a factory call.
    lease: WorkerLease,
    /// Shared connection-health view. The sender is owned only by the worker,
    /// so this channel closes when that worker terminates even if service
    /// clones remain alive.
    connection_health: watch::Receiver<bool>,
    worker: Arc<WorkerHandle>,
}

struct WorkerControl {
    state: Mutex<WorkerControlState>,
    shutdown_tx: watch::Sender<bool>,
    event_bus: Option<ConnectionEventBus>,
}

struct WorkerControlState {
    handles: usize,
    worker_running: bool,
    shutdown_published: bool,
}

impl WorkerControl {
    fn new(shutdown_tx: watch::Sender<bool>, event_bus: Option<ConnectionEventBus>) -> Self {
        Self {
            state: Mutex::new(WorkerControlState {
                handles: 1,
                worker_running: true,
                shutdown_published: false,
            }),
            shutdown_tx,
            event_bus,
        }
    }

    fn add_handle(&self) {
        let mut state = self
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        state.handles = state
            .handles
            .checked_add(1)
            .expect("AutoPipelineService handle count overflowed");
    }

    fn release_handle(&self) {
        let mut state = self
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        state.handles = state
            .handles
            .checked_sub(1)
            .expect("AutoPipelineService handle count underflowed");
        if state.handles == 0 {
            self.shutdown_tx.send_replace(true);
            if !state.worker_running {
                self.publish_shutdown_locked(&mut state);
            }
        }
    }

    fn worker_finished(&self) {
        let mut state = self
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        state.worker_running = false;
        if state.handles == 0 {
            self.publish_shutdown_locked(&mut state);
        }
    }

    fn publish_shutdown_locked(&self, state: &mut WorkerControlState) {
        if state.shutdown_published {
            return;
        }
        state.shutdown_published = true;
        if let Some(events) = &self.event_bus {
            events.publish(ConnectionEvent::Disconnected {
                reason: ConnectionDisconnectReason::Shutdown,
            });
        }
    }

    /// Run `f` while holding the same lock used by final-handle release.
    /// This linearizes lifecycle events before shutdown or suppresses them
    /// after shutdown, so `Shutdown` remains the terminal event.
    fn with_active_handle<R>(&self, f: impl FnOnce() -> R) -> Option<R> {
        let state = self
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if state.handles == 0 { None } else { Some(f()) }
    }
}

struct WorkerRunGuard {
    control: Arc<WorkerControl>,
}

impl Drop for WorkerRunGuard {
    fn drop(&mut self) {
        self.control.worker_finished();
    }
}

struct WorkerLifecycle {
    control: Arc<WorkerControl>,
    shutdown: watch::Receiver<bool>,
    connection_health: ConnectionHealthPublisher,
    _run_guard: WorkerRunGuard,
}

/// Worker-owned publisher for the current data-connection health.
///
/// Dropping the worker always leaves observers with a final `false` snapshot
/// before closing the watch channel.
struct ConnectionHealthPublisher {
    tx: watch::Sender<bool>,
}

impl ConnectionHealthPublisher {
    fn new(tx: watch::Sender<bool>) -> Self {
        Self { tx }
    }

    fn set(&self, healthy: bool) {
        self.tx.send_if_modified(|current| {
            let changed = *current != healthy;
            *current = healthy;
            changed
        });
    }
}

impl Drop for ConnectionHealthPublisher {
    fn drop(&mut self) {
        self.set(false);
    }
}

struct WorkerLease {
    control: Arc<WorkerControl>,
}

impl Clone for WorkerLease {
    fn clone(&self) -> Self {
        self.control.add_handle();
        Self {
            control: Arc::clone(&self.control),
        }
    }
}

impl Drop for WorkerLease {
    fn drop(&mut self) {
        self.control.release_handle();
    }
}

/// Wrapper around the background task's [`JoinHandle`](tokio::task::JoinHandle)
/// that emits a warning when dropped without being cleanly shut down.
///
/// Stores the handle in an `Option` so it can be `take()`n by [`shutdown()`]
/// without conflicting with the `Drop` impl.
struct WorkerHandle {
    handle: Option<tokio::task::JoinHandle<()>>,
}

impl WorkerHandle {
    fn new(handle: tokio::task::JoinHandle<()>) -> Self {
        Self {
            handle: Some(handle),
        }
    }

    /// Returns `true` if the background task has already finished.
    fn is_finished(&self) -> bool {
        self.handle
            .as_ref()
            .map(|h| h.is_finished())
            .unwrap_or(true)
    }
}

impl Drop for WorkerHandle {
    fn drop(&mut self) {
        // If the task has not yet finished when the last Arc<WorkerHandle>
        // is dropped, the JoinHandle is being abandoned. Any in-flight
        // requests in the pipeline worker may be silently dropped.
        if !self.is_finished() {
            warn!(
                "AutoPipelineService dropped without calling shutdown(); \
                 background worker may still have queued requests in flight"
            );
        }
    }
}

impl AutoPipelineService {
    /// Create a new auto-pipelining service wrapping the given connection.
    ///
    /// The connection is moved into a background task that exclusively owns it.
    /// All requests are sent through a channel and batched automatically.
    ///
    /// The service does **not** reconnect if the connection fails -- every
    /// subsequent request returns [`RedisError::ConnectionClosed`]. Wrap this
    /// in a reconnect layer, or use [`Self::with_factory`] to build a
    /// service that rebuilds its own connection on failure.
    pub fn new(conn: RedisConnection, config: AutoPipelineConfig) -> Self {
        Self::from_parts(Some(conn), config, ConnSource::Fixed, None, None)
    }

    /// Create a non-reconnecting auto-pipeline service with lifecycle events.
    ///
    /// The bus receives [`ConnectionEvent::Connected`] immediately and one
    /// [`ConnectionEvent::Disconnected`] transition if the fixed connection
    /// later fails. This constructor does not add reconnection behavior; use
    /// [`Self::with_factory_and_events`] for that.
    pub fn new_with_events(
        conn: RedisConnection,
        config: AutoPipelineConfig,
        events: ConnectionEventBus,
    ) -> Self {
        Self::from_parts(Some(conn), config, ConnSource::Fixed, Some(events), None)
    }

    /// Create a new auto-pipelining service that rebuilds its connection on
    /// failure using the provided [`ConnectionFactory`].
    ///
    /// On pipeline execution failure, in-flight requests receive
    /// [`RedisError::ConnectionClosed`], then the worker reconnects via the
    /// factory with exponential backoff governed by `reconnect`. Subsequent
    /// requests are served by the new connection.
    ///
    /// The factory is also the right place to replay session setup
    /// (AUTH, SELECT, HELLO, READONLY) on every reconnect -- see
    /// [`UrlConnectionFactory`](crate::reconnect::UrlConnectionFactory)
    /// for a ready-made AUTH+SELECT factory.
    pub async fn with_factory(
        factory: impl ConnectionFactory,
        config: AutoPipelineConfig,
        reconnect: AutoPipelineReconnectConfig,
    ) -> Result<Self, RedisError> {
        Self::with_factory_inner(factory, config, reconnect, None).await
    }

    /// Create a factory-backed auto-pipeline service with lifecycle events.
    ///
    /// Subscribe before calling this constructor to observe the initial
    /// connect result. Disconnect and reconnect transitions are published by
    /// the existing pipeline worker; event delivery does not spawn a separate
    /// task and never blocks that worker.
    pub async fn with_factory_and_events(
        factory: impl ConnectionFactory,
        config: AutoPipelineConfig,
        reconnect: AutoPipelineReconnectConfig,
        events: ConnectionEventBus,
    ) -> Result<Self, RedisError> {
        Self::with_factory_inner(factory, config, reconnect, Some(events)).await
    }

    /// Create an explicitly maintenance-aware factory-backed service.
    ///
    /// The initial connection is verified as RESP3 and successfully registers
    /// `CLIENT MAINT_NOTIFICATIONS` before this constructor returns. Retain the
    /// returned handle to keep handling enabled.
    pub async fn with_factory_and_maintenance(
        factory: impl ConnectionFactory,
        config: AutoPipelineConfig,
        reconnect: AutoPipelineReconnectConfig,
    ) -> Result<(Self, MaintenanceListenerHandle), RedisError> {
        Self::with_factory_and_maintenance_inner(factory, config, reconnect, None).await
    }

    /// Create an explicitly maintenance-aware service with lifecycle events.
    pub async fn with_factory_and_maintenance_and_events(
        factory: impl ConnectionFactory,
        config: AutoPipelineConfig,
        reconnect: AutoPipelineReconnectConfig,
        events: ConnectionEventBus,
    ) -> Result<(Self, MaintenanceListenerHandle), RedisError> {
        Self::with_factory_and_maintenance_inner(factory, config, reconnect, Some(events)).await
    }

    async fn with_factory_and_maintenance_inner(
        factory: impl ConnectionFactory,
        config: AutoPipelineConfig,
        reconnect: AutoPipelineReconnectConfig,
        event_bus: Option<ConnectionEventBus>,
    ) -> Result<(Self, MaintenanceListenerHandle), RedisError> {
        let factory: Arc<dyn ConnectionFactory> = Arc::new(factory);
        let (conn, push_rx) =
            match connect_and_prepare(factory.as_ref(), reconnect.reconnect.connect_timeout, true)
                .await
            {
                Ok((conn, Some(push_rx))) => (conn, push_rx),
                Ok((_conn, None)) => {
                    unreachable!("maintenance setup always returns a push receiver")
                }
                Err(error) => {
                    if let Some(events) = &event_bus {
                        events.publish_with(|| ConnectionEvent::ConnectFailed {
                            error: Arc::from(error.to_string()),
                        });
                    }
                    return Err(error);
                }
            };
        let listener_id = next_listener_id();
        let (control_tx, control_rx) = mpsc::unbounded_channel();
        let source = ConnSource::Factory {
            factory,
            reconnect: reconnect.reconnect,
        };
        let maintenance = MaintenanceWorker {
            state: MaintenanceState::new(listener_id),
            control_rx,
            push_rx,
        };
        let service = Self::from_parts(Some(conn), config, source, event_bus, Some(maintenance));
        let handle = MaintenanceListenerHandle::new(control_tx, listener_id);
        Ok((service, handle))
    }

    async fn with_factory_inner(
        factory: impl ConnectionFactory,
        config: AutoPipelineConfig,
        reconnect: AutoPipelineReconnectConfig,
        event_bus: Option<ConnectionEventBus>,
    ) -> Result<Self, RedisError> {
        let factory: Arc<dyn ConnectionFactory> = Arc::new(factory);
        let conn = match connect_with_timeout(factory.as_ref(), reconnect.reconnect.connect_timeout)
            .await
        {
            Ok(conn) => conn,
            Err(error) => {
                if let Some(events) = &event_bus {
                    events.publish_with(|| ConnectionEvent::ConnectFailed {
                        error: Arc::from(error.to_string()),
                    });
                }
                return Err(error);
            }
        };
        let source = ConnSource::Factory {
            factory,
            reconnect: reconnect.reconnect,
        };
        Ok(Self::from_parts(
            Some(conn),
            config,
            source,
            event_bus,
            None,
        ))
    }

    /// Create a factory-backed service without opening a connection yet.
    ///
    /// Construction is synchronous and performs no network I/O. The first
    /// accepted request invokes the factory and waits for that connection
    /// attempt before it is sent. If the attempt fails, that request receives
    /// [`RedisError::ConnectionClosed`]; the worker remains alive and the next
    /// request makes a fresh attempt. Once connected, failures use `reconnect`
    /// in exactly the same way as [`Self::with_factory`].
    ///
    /// Connection health starts as `false` and becomes `true` immediately
    /// before the first [`ConnectionEvent::Connected`] event is published.
    /// With an event bus, a failed deferred attempt publishes
    /// [`ConnectionEvent::ConnectFailed`]. No `Connected` event is emitted
    /// merely by constructing the service.
    ///
    /// # Panics
    ///
    /// Panics when called outside an entered Tokio runtime because the
    /// lightweight request worker is spawned during construction.
    pub fn with_lazy_factory(
        factory: impl ConnectionFactory,
        config: AutoPipelineConfig,
        reconnect: AutoPipelineReconnectConfig,
    ) -> Self {
        Self::with_lazy_factory_inner(factory, config, reconnect, None)
    }

    /// Create a lazily connected factory-backed service with lifecycle events.
    ///
    /// Subscribe to `events` before this call to observe the first deferred
    /// connection result. Construction itself publishes no connection event.
    ///
    /// # Panics
    ///
    /// Panics when called outside an entered Tokio runtime.
    pub fn with_lazy_factory_and_events(
        factory: impl ConnectionFactory,
        config: AutoPipelineConfig,
        reconnect: AutoPipelineReconnectConfig,
        events: ConnectionEventBus,
    ) -> Self {
        Self::with_lazy_factory_inner(factory, config, reconnect, Some(events))
    }

    fn with_lazy_factory_inner(
        factory: impl ConnectionFactory,
        config: AutoPipelineConfig,
        reconnect: AutoPipelineReconnectConfig,
        event_bus: Option<ConnectionEventBus>,
    ) -> Self {
        let source = ConnSource::Factory {
            factory: Arc::new(factory),
            reconnect: reconnect.reconnect,
        };
        Self::from_parts(None, config, source, event_bus, None)
    }

    fn from_parts(
        conn: Option<RedisConnection>,
        config: AutoPipelineConfig,
        source: ConnSource,
        event_bus: Option<ConnectionEventBus>,
        maintenance: Option<MaintenanceWorker>,
    ) -> Self {
        let (tx, rx) = mpsc::channel(config.queue_capacity);
        let poll_tx = PollSender::new(tx.clone());
        let shed_load = config.shed_load_on_full;
        let (shutdown_tx, shutdown_rx) = watch::channel(false);
        let initially_connected = conn.is_some();
        let (connection_health_tx, connection_health) = watch::channel(initially_connected);
        let control = Arc::new(WorkerControl::new(shutdown_tx, event_bus.clone()));
        let lease = WorkerLease {
            control: Arc::clone(&control),
        };
        if initially_connected && let Some(events) = &event_bus {
            events.publish(ConnectionEvent::Connected);
        }
        let lifecycle = WorkerLifecycle {
            control: Arc::clone(&control),
            shutdown: shutdown_rx,
            connection_health: ConnectionHealthPublisher::new(connection_health_tx),
            _run_guard: WorkerRunGuard {
                control: Arc::clone(&control),
            },
        };
        let runtime = tokio::runtime::Handle::try_current()
            .expect("AutoPipelineService must be constructed inside an entered Tokio runtime");
        let handle = runtime.spawn(pipeline_worker(
            rx,
            conn,
            config,
            source,
            event_bus,
            lifecycle,
            maintenance,
        ));
        Self {
            tx,
            poll_tx,
            shed_load,
            lease,
            connection_health,
            worker: Arc::new(WorkerHandle::new(handle)),
        }
    }

    /// Send multiple frames through the service as a single atomic batch.
    ///
    /// The worker guarantees that all frames in the supplied slice are
    /// flushed back-to-back in one [`RedisConnection::execute_pipeline`]
    /// call, with no interleaving from other concurrent callers. This is
    /// what you want for sequences like `ASKING` + the migrated command
    /// during cluster resharding, where ordering on a single connection
    /// matters.
    ///
    /// Returns one response frame per input frame, in order. If any frame's
    /// response is an error, the overall call still returns the full
    /// response vector -- error inspection is left to the caller.
    pub async fn call_pipeline(&mut self, frames: Vec<Frame>) -> Result<Vec<Frame>, RedisError> {
        if frames.is_empty() {
            return Ok(Vec::new());
        }
        let (resp_tx, resp_rx) = oneshot::channel();
        let request = WorkerRequest::Multi {
            frames,
            response_tx: resp_tx,
        };
        if self.shed_load {
            self.tx.try_send(request).map_err(|e| match e {
                tokio::sync::mpsc::error::TrySendError::Full(_) => RedisError::QueueFull,
                tokio::sync::mpsc::error::TrySendError::Closed(_) => RedisError::ConnectionClosed,
            })?;
        } else {
            // Back-pressure: await a free slot rather than failing fast.
            self.tx
                .reserve()
                .await
                .map_err(|_| RedisError::ConnectionClosed)?
                .send(request);
        }
        resp_rx.await.map_err(|_| RedisError::ConnectionClosed)?
    }

    /// Send multiple frames through the queue slot reserved by
    /// [`Service::poll_ready`] as one atomic worker request.
    ///
    /// This is the multi-frame counterpart to [`Service::call`]. It exists for
    /// frame-level middleware that must prepend connection-local setup to one
    /// command without allowing another caller to interleave between them. In
    /// particular, client-side caching in opt-in mode uses it for `CLIENT
    /// CACHING YES` followed by the cacheable read.
    ///
    /// In back-pressure mode the caller must first drive `poll_ready` to
    /// `Ready(Ok(()))`; this method consumes that exact reservation. In
    /// load-shedding mode `poll_ready` does not reserve capacity and this
    /// method follows [`Service::call`] by using `try_send`.
    pub(crate) fn call_reserved_pipeline(
        &mut self,
        frames: Vec<Frame>,
    ) -> Pin<Box<dyn Future<Output = Result<Vec<Frame>, RedisError>> + Send>> {
        if frames.is_empty() {
            // Release a back-pressure reservation even though there is no
            // worker request to fill it with.
            self.release_reservation();
            return Box::pin(async { Ok(Vec::new()) });
        }

        let (resp_tx, resp_rx) = oneshot::channel();
        let request = WorkerRequest::Multi {
            frames,
            response_tx: resp_tx,
        };

        let send_result = if self.shed_load {
            self.tx.try_send(request).map_err(|e| match e {
                tokio::sync::mpsc::error::TrySendError::Full(_) => RedisError::QueueFull,
                tokio::sync::mpsc::error::TrySendError::Closed(_) => RedisError::ConnectionClosed,
            })
        } else {
            self.poll_tx
                .send_item(request)
                .map_err(|_| RedisError::ConnectionClosed)
        };

        Box::pin(async move {
            send_result?;
            resp_rx.await.map_err(|_| RedisError::ConnectionClosed)?
        })
    }

    /// Release a queue slot previously reserved by [`Service::poll_ready`]
    /// without submitting a worker request.
    ///
    /// Frame middleware uses this when it satisfies a request locally after
    /// readiness was already established. Client-side cache hits are the
    /// canonical case: they must return the cached response while restoring
    /// the auto-pipeline queue's full capacity.
    pub(crate) fn release_reservation(&mut self) {
        let _ = self.poll_tx.abort_send();
    }

    /// Gracefully shut down the pipeline service.
    ///
    /// Drops this instance's sender half. If this is the last live service
    /// clone, it also signals the background worker to close its receiver,
    /// reject any late sends, drain requests that were already accepted, and
    /// exit cleanly. The method waits for that final worker exit.
    ///
    /// If other clones are still alive, returns immediately -- the worker
    /// continues running until the last clone shuts down or is dropped.
    /// When lifecycle events are configured, the service publishes exactly one
    /// [`ConnectionEvent::Disconnected`] with
    /// [`ConnectionDisconnectReason::Shutdown`] after the worker observes that
    /// the final public handle closed. An earlier unexpected `Disconnected`
    /// event does not suppress this distinct terminal transition. `shutdown()`
    /// waits for normal queued work to drain and for this event to be emitted.
    /// If the worker is reconnecting, the final handle cancels its backoff or
    /// in-progress factory call before the worker exits.
    ///
    /// For clean application shutdown, prefer calling `shutdown()` over
    /// simply dropping the service.
    pub async fn shutdown(self) {
        // Drop both sender handles first: decrements the sender count. When all
        // senders are gone the worker's `recv()` returns `None` and the worker
        // exits after flushing any remaining batch. `poll_tx` holds its own
        // clone of the sender, so it must be dropped too or the worker await
        // below would hang.
        drop(self.tx);
        drop(self.poll_tx);
        // The final public service lease signals the worker independently of
        // the request channel, so reconnect backoff and hanging factories are
        // cancellation-safe too.
        drop(self.lease);
        // Attempt to take sole ownership of the WorkerHandle Arc. Succeeds
        // only when we hold the last reference (all other clones have already
        // been dropped or shut down), in which case we await the worker to
        // ensure the final batch is flushed before we return.
        if let Ok(mut worker_handle) = Arc::try_unwrap(self.worker)
            && let Some(handle) = worker_handle.handle.take()
        {
            let _ = handle.await;
        }
    }

    /// Returns `true` while the background worker task is still running.
    ///
    /// A factory-backed worker exits only after exhausting its reconnect budget
    /// (or on a clean [`shutdown`](Self::shutdown)); once it has, this service
    /// can no longer serve requests. A cluster client uses this to detect a
    /// per-node worker that gave up on a dead address so it can replace the
    /// service during a topology refresh.
    pub fn is_alive(&self) -> bool {
        !self.worker.is_finished()
    }

    /// Return the worker's current data-connection health snapshot.
    ///
    /// This is public only so sibling workspace clients can fail closed when
    /// connection-local server state is lost. In particular, a cluster cache
    /// supervisor must not serve hits while any tracked node is disconnected.
    #[doc(hidden)]
    pub fn is_connection_healthy(&self) -> bool {
        *self.connection_health.borrow()
    }

    /// Subscribe to data-connection health transitions.
    ///
    /// The initial value is `true` for a service given an established
    /// connection and `false` for a lazily connected service. Failures publish
    /// `false` before request responders or disconnect events are notified;
    /// initial connection and factory-backed reconnection publish `true` only
    /// after a connection is installed. The channel closes when the worker
    /// terminates. This is public only for sibling workspace clients that own
    /// a coordinated lifecycle across multiple data connections.
    #[doc(hidden)]
    pub fn subscribe_connection_health(&self) -> watch::Receiver<bool> {
        self.connection_health.clone()
    }
}

/// Background task that collects requests and executes them as pipelines.
///
/// Batch size is measured in *frames*, not requests, so a single `Multi`
/// request carrying N frames counts as N toward `max_batch_size`. This keeps
/// the effective flush size stable regardless of how many frames individual
/// callers send.
async fn pipeline_worker(
    mut rx: mpsc::Receiver<WorkerRequest>,
    mut conn: Option<RedisConnection>,
    config: AutoPipelineConfig,
    source: ConnSource,
    event_bus: Option<ConnectionEventBus>,
    lifecycle: WorkerLifecycle,
    maintenance: Option<MaintenanceWorker>,
) {
    let WorkerLifecycle {
        control,
        mut shutdown,
        connection_health,
        _run_guard,
    } = lifecycle;
    let mut outage_reported = false;
    let mut shutting_down = false;
    let (mut maintenance_state, mut maintenance_control_rx, mut maintenance_push_rx) =
        match maintenance {
            Some(maintenance) => (
                Some(maintenance.state),
                Some(maintenance.control_rx),
                Some(maintenance.push_rx),
            ),
            None => (None, None, None),
        };
    'worker: loop {
        drain_maintenance_control(
            &mut maintenance_state,
            &mut maintenance_control_rx,
            &mut maintenance_push_rx,
        );
        if maintenance_state
            .as_ref()
            .and_then(|state| state.pending.as_ref())
            .is_some()
        {
            match wait_for_pending_handoff(
                &mut conn,
                &mut maintenance_state,
                &mut maintenance_control_rx,
                &mut maintenance_push_rx,
                event_bus.as_ref(),
                &mut shutdown,
            )
            .await
            {
                PendingHandoffOutcome::Cancelled => continue,
                PendingHandoffOutcome::Shutdown => {
                    shutting_down = true;
                    rx.close();
                    disable_maintenance(
                        &mut maintenance_state,
                        &mut maintenance_control_rx,
                        &mut maintenance_push_rx,
                    );
                    continue;
                }
                PendingHandoffOutcome::ConnectionFailed(error) => {
                    clear_pending_handoff(&mut maintenance_state);
                    connection_health.set(false);
                    let failure = PipelineFailure::Connection(error);
                    publish_worker_outage(
                        event_bus.as_ref(),
                        &mut outage_reported,
                        failure.event_reason(),
                        &control,
                    );
                    let ConnSource::Factory { factory, reconnect } = &source else {
                        fail_queued_requests(&mut rx);
                        return;
                    };
                    let maintenance_enabled = maintenance_state
                        .as_ref()
                        .is_some_and(|state| state.enabled);
                    if !reconnect_worker_connection(
                        conn.as_mut()
                            .expect("maintenance listener requires a connection"),
                        &mut rx,
                        factory.as_ref(),
                        reconnect,
                        event_bus.as_ref(),
                        &mut shutdown,
                        &control,
                        &connection_health,
                        &mut outage_reported,
                        &mut maintenance_push_rx,
                        maintenance_enabled,
                    )
                    .await
                    {
                        return;
                    }
                    continue;
                }
                PendingHandoffOutcome::Ready { sequence } => {
                    if let Some(state) = &mut maintenance_state {
                        state.pending = None;
                    }
                    connection_health.set(false);
                    publish_worker_outage(
                        event_bus.as_ref(),
                        &mut outage_reported,
                        ConnectionDisconnectReason::MaintenanceHandoff { sequence },
                        &control,
                    );
                    let ConnSource::Factory { factory, reconnect } = &source else {
                        fail_queued_requests(&mut rx);
                        return;
                    };
                    let maintenance_enabled = maintenance_state
                        .as_ref()
                        .is_some_and(|state| state.enabled);
                    if !reconnect_worker_connection(
                        conn.as_mut()
                            .expect("maintenance listener requires a connection"),
                        &mut rx,
                        factory.as_ref(),
                        reconnect,
                        event_bus.as_ref(),
                        &mut shutdown,
                        &control,
                        &connection_health,
                        &mut outage_reported,
                        &mut maintenance_push_rx,
                        maintenance_enabled,
                    )
                    .await
                    {
                        return;
                    }
                    continue;
                }
            }
        }

        // Wait for the first request or final-handle shutdown. Closing the
        // receiver rejects any sender retained outside a public service
        // handle while still allowing already-buffered requests to drain.
        let first = if shutting_down {
            rx.recv().await
        } else {
            loop {
                tokio::select! {
                    biased;
                    () = wait_for_shutdown(&mut shutdown) => {
                        shutting_down = true;
                        rx.close();
                        break rx.recv().await;
                    }
                    control_message = recv_maintenance_control(&mut maintenance_control_rx) => {
                        apply_maintenance_control(
                            control_message,
                            &mut maintenance_state,
                            &mut maintenance_control_rx,
                            &mut maintenance_push_rx,
                        );
                    }
                    push = recv_maintenance_push(&mut maintenance_push_rx) => {
                        if handle_maintenance_push_result(
                            push,
                            &mut maintenance_state,
                            &mut maintenance_push_rx,
                            event_bus.as_ref(),
                        ).is_err() {
                            connection_health.set(false);
                            let failure = PipelineFailure::Connection(
                                maintenance_feed_error(),
                            );
                            publish_worker_outage(
                                event_bus.as_ref(),
                                &mut outage_reported,
                                failure.event_reason(),
                                &control,
                            );
                            let ConnSource::Factory { factory, reconnect } = &source else {
                                fail_queued_requests(&mut rx);
                                return;
                            };
                            let maintenance_enabled = maintenance_state
                                .as_ref()
                                .is_some_and(|state| state.enabled);
                            if !reconnect_worker_connection(
                                conn.as_mut().expect("maintenance feed requires a connection"),
                                &mut rx,
                                factory.as_ref(),
                                reconnect,
                                event_bus.as_ref(),
                                &mut shutdown,
                                &control,
                                &connection_health,
                                &mut outage_reported,
                                &mut maintenance_push_rx,
                                maintenance_enabled,
                            ).await {
                                return;
                            }
                        }
                        if maintenance_state
                            .as_ref()
                            .and_then(|state| state.pending.as_ref())
                            .is_some()
                        {
                            continue 'worker;
                        }
                    }
                    request = rx.recv() => break request,
                    idle_result = read_idle_push_if_connected(&mut conn) => match idle_result {
                        Ok(()) => {
                            // A push was routed to its subscriber. Re-enter the
                            // biased select so queued requests retain priority
                            // over further unsolicited traffic.
                        }
                        Err(error) => {
                            clear_pending_handoff(&mut maintenance_state);
                            connection_health.set(false);
                            let failure = PipelineFailure::Connection(error);
                            publish_worker_outage(
                                event_bus.as_ref(),
                                &mut outage_reported,
                                failure.event_reason(),
                                &control,
                            );
                            match &source {
                                ConnSource::Fixed => {
                                    // An idle failure proves this fixed
                                    // transport cannot serve future work.
                                    // Close the queue and reject anything that
                                    // raced with the socket notification.
                                    rx.close();
                                    while let Ok(request) = rx.try_recv() {
                                        request.fail(RedisError::ConnectionClosed);
                                    }
                                    return;
                                }
                                ConnSource::Factory { factory, reconnect } => {
                                    let maintenance_enabled = maintenance_state
                                        .as_ref()
                                        .is_some_and(|state| state.enabled);
                                    if !reconnect_worker_connection(
                                        conn.as_mut().expect("idle failure requires a connection"),
                                        &mut rx,
                                        factory.as_ref(),
                                        reconnect,
                                        event_bus.as_ref(),
                                        &mut shutdown,
                                        &control,
                                        &connection_health,
                                        &mut outage_reported,
                                        &mut maintenance_push_rx,
                                        maintenance_enabled,
                                    )
                                    .await
                                    {
                                        return;
                                    }
                                }
                            }
                        }
                    },
                }
            }
        };
        let first = match first {
            Some(req) => req,
            None => break, // channel closed, all senders dropped
        };

        let mut frame_count = first.frame_count();
        let mut batch: Vec<WorkerRequest> = vec![first];

        // Drain any immediately-available requests without waiting.
        // This handles the high-concurrency case where multiple requests
        // arrive between flushes.
        while frame_count < config.max_batch_size {
            match rx.try_recv() {
                Ok(req) => {
                    frame_count += req.frame_count();
                    batch.push(req);
                }
                Err(_) => break,
            }
        }

        // If we haven't filled the batch and the window is non-zero,
        // wait briefly for more requests to arrive.
        let mut channel_closed = false;
        if frame_count < config.max_batch_size && !config.batch_window.is_zero() {
            let deadline = tokio::time::Instant::now() + config.batch_window;
            loop {
                if frame_count >= config.max_batch_size {
                    break;
                }

                if shutting_down {
                    match rx.try_recv() {
                        Ok(req) => {
                            frame_count += req.frame_count();
                            batch.push(req);
                            continue;
                        }
                        Err(_) => break,
                    }
                }

                tokio::select! {
                    biased;
                    () = wait_for_shutdown(&mut shutdown) => {
                        shutting_down = true;
                        rx.close();
                    }
                    request = rx.recv() => match request {
                        Some(req) => {
                            frame_count += req.frame_count();
                            batch.push(req);
                        }
                        None => {
                            channel_closed = true;
                            break;
                        }
                    },
                    () = tokio::time::sleep_until(deadline) => break,
                }
            }
        }

        if conn.is_none() {
            let ConnSource::Factory { factory, reconnect } = &source else {
                unreachable!("a fixed worker always starts with a connection");
            };
            let connect = connect_with_timeout(factory.as_ref(), reconnect.connect_timeout);
            tokio::pin!(connect);
            let connect_result = tokio::select! {
                biased;
                () = wait_for_shutdown(&mut shutdown) => {
                    shutting_down = true;
                    rx.close();
                    fail_requests(batch);
                    continue;
                }
                result = &mut connect => result,
            };
            match connect_result {
                Ok(new_conn) => {
                    let connected = control.with_active_handle(|| {
                        connection_health.set(true);
                        if let Some(events) = &event_bus {
                            events.publish(ConnectionEvent::Connected);
                        }
                    });
                    if connected.is_none() {
                        fail_requests(batch);
                        return;
                    }
                    conn = Some(new_conn);
                }
                Err(error) => {
                    control.with_active_handle(|| {
                        if let Some(events) = &event_bus {
                            events.publish_with(|| ConnectionEvent::ConnectFailed {
                                error: Arc::from(error.to_string()),
                            });
                        }
                    });
                    fail_requests(batch);
                    continue;
                }
            }
        }

        let flush_result = flush_batch(
            conn.as_mut().expect("connection established before flush"),
            batch,
            config.response_timeout,
            config.metrics_recorder.as_ref(),
            config.reconnect_on_readonly,
            &connection_health,
        )
        .await;

        if channel_closed {
            if let Err(failure) = flush_result {
                publish_worker_outage(
                    event_bus.as_ref(),
                    &mut outage_reported,
                    failure.event_reason(),
                    &control,
                );
            }
            return;
        }

        if let Err(failure) = flush_result {
            // A listener disable requested while this batch was in flight
            // wins over pushes decoded by the failed exchange. That prevents
            // an obsolete MOVING from extending shutdown through a
            // maintenance-aware reconnect campaign.
            drain_maintenance_control(
                &mut maintenance_state,
                &mut maintenance_control_rx,
                &mut maintenance_push_rx,
            );
            drain_available_maintenance_pushes(
                &mut maintenance_state,
                &mut maintenance_push_rx,
                event_bus.as_ref(),
            );
            clear_pending_handoff(&mut maintenance_state);
            publish_worker_outage(
                event_bus.as_ref(),
                &mut outage_reported,
                failure.event_reason(),
                &control,
            );
            // Pipeline execution failed. Either give up (Fixed source) or
            // reconnect via factory and keep serving.
            match &source {
                ConnSource::Fixed => {
                    // Current behavior: leave the worker running on the dead
                    // connection so any future batches also fail-fast and
                    // upstream retry layers can notice.
                }
                ConnSource::Factory { factory, reconnect } => {
                    let maintenance_enabled = maintenance_state
                        .as_ref()
                        .is_some_and(|state| state.enabled);
                    if !reconnect_worker_connection(
                        conn.as_mut().expect("failed flush requires a connection"),
                        &mut rx,
                        factory.as_ref(),
                        reconnect,
                        event_bus.as_ref(),
                        &mut shutdown,
                        &control,
                        &connection_health,
                        &mut outage_reported,
                        &mut maintenance_push_rx,
                        maintenance_enabled,
                    )
                    .await
                    {
                        return;
                    }
                }
            }
        }
    }
}

/// Wait for an unsolicited push only while a connection exists.
///
/// A lazy worker has no socket to poll before its first command, so this stays
/// pending and lets the request/shutdown branches of the surrounding select
/// drive progress.
async fn read_idle_push_if_connected(conn: &mut Option<RedisConnection>) -> Result<(), RedisError> {
    match conn {
        Some(conn) => conn.read_idle_push().await,
        None => futures::future::pending().await,
    }
}

enum PendingHandoffOutcome {
    Cancelled,
    Ready { sequence: u64 },
    ConnectionFailed(RedisError),
    Shutdown,
}

async fn recv_maintenance_control(
    receiver: &mut Option<mpsc::UnboundedReceiver<MaintenanceControl>>,
) -> Option<MaintenanceControl> {
    match receiver {
        Some(receiver) => receiver.recv().await,
        None => futures::future::pending().await,
    }
}

async fn recv_maintenance_push(
    receiver: &mut Option<tokio::sync::broadcast::Receiver<ReceivedPushFrame>>,
) -> Result<ReceivedPushFrame, tokio::sync::broadcast::error::RecvError> {
    match receiver {
        Some(receiver) => receiver.recv().await,
        None => futures::future::pending().await,
    }
}

fn drain_maintenance_control(
    state: &mut Option<MaintenanceState>,
    receiver: &mut Option<mpsc::UnboundedReceiver<MaintenanceControl>>,
    pushes: &mut Option<tokio::sync::broadcast::Receiver<ReceivedPushFrame>>,
) {
    loop {
        let Some(control) = receiver.as_mut() else {
            return;
        };
        match control.try_recv() {
            Ok(message) => apply_maintenance_control(Some(message), state, receiver, pushes),
            Err(mpsc::error::TryRecvError::Empty) => return,
            Err(mpsc::error::TryRecvError::Disconnected) => {
                *receiver = None;
                if let Some(state) = state {
                    state.enabled = false;
                    state.pending = None;
                }
                *pushes = None;
                return;
            }
        }
    }
}

fn clear_pending_handoff(state: &mut Option<MaintenanceState>) {
    if let Some(state) = state {
        state.pending = None;
    }
}

fn disable_maintenance(
    state: &mut Option<MaintenanceState>,
    receiver: &mut Option<mpsc::UnboundedReceiver<MaintenanceControl>>,
    pushes: &mut Option<tokio::sync::broadcast::Receiver<ReceivedPushFrame>>,
) {
    if let Some(state) = state {
        state.enabled = false;
        state.pending = None;
    }
    *receiver = None;
    *pushes = None;
}

fn apply_maintenance_control(
    message: Option<MaintenanceControl>,
    state: &mut Option<MaintenanceState>,
    receiver: &mut Option<mpsc::UnboundedReceiver<MaintenanceControl>>,
    pushes: &mut Option<tokio::sync::broadcast::Receiver<ReceivedPushFrame>>,
) {
    let Some(message) = message else {
        *receiver = None;
        return;
    };
    match message {
        MaintenanceControl::Disable { listener_id, ack } => {
            if state
                .as_ref()
                .is_some_and(|state| state.listener_id == listener_id)
            {
                disable_maintenance(state, receiver, pushes);
            }
            if let Some(ack) = ack {
                let _ = ack.send(());
            }
        }
    }
}

fn publish_maintenance_notification(
    event_bus: Option<&ConnectionEventBus>,
    notification: ParsedMaintenanceNotification,
) {
    if let Some(events) = event_bus {
        events.publish(ConnectionEvent::MaintenanceNotification {
            kind: notification.kind(),
            sequence: notification.sequence(),
            ttl: notification.ttl(),
        });
    }
}

fn handle_maintenance_push_result(
    push: Result<ReceivedPushFrame, tokio::sync::broadcast::error::RecvError>,
    state: &mut Option<MaintenanceState>,
    receiver: &mut Option<tokio::sync::broadcast::Receiver<ReceivedPushFrame>>,
    event_bus: Option<&ConnectionEventBus>,
) -> Result<(), ()> {
    match push {
        Ok(push) => {
            if let Some(state) = state
                && let Some(received) = parse_maintenance_push(push)
                && let Some(notification) = state.accept(received)
            {
                publish_maintenance_notification(event_bus, notification);
            }
            Ok(())
        }
        Err(_) => {
            *receiver = None;
            Err(())
        }
    }
}

fn drain_available_maintenance_pushes(
    state: &mut Option<MaintenanceState>,
    receiver: &mut Option<tokio::sync::broadcast::Receiver<ReceivedPushFrame>>,
    event_bus: Option<&ConnectionEventBus>,
) {
    loop {
        let Some(pushes) = receiver.as_mut() else {
            return;
        };
        match pushes.try_recv() {
            Ok(push) => {
                let _ = handle_maintenance_push_result(Ok(push), state, receiver, event_bus);
            }
            Err(tokio::sync::broadcast::error::TryRecvError::Empty) => return,
            Err(tokio::sync::broadcast::error::TryRecvError::Lagged(_)) => {
                // The connection is already being discarded. Advance to and
                // record every notification still retained by the bounded
                // feed so a replay on the replacement is deduplicated.
            }
            Err(tokio::sync::broadcast::error::TryRecvError::Closed) => {
                *receiver = None;
                return;
            }
        }
    }
}

fn maintenance_feed_error() -> RedisError {
    RedisError::UnexpectedResponse {
        expected: "a complete maintenance-notification push feed",
        actual: "maintenance push feed closed or overflowed".to_owned(),
    }
}

async fn connect_and_prepare(
    factory: &dyn ConnectionFactory,
    timeout: Option<Duration>,
    maintenance_enabled: bool,
) -> Result<
    (
        RedisConnection,
        Option<tokio::sync::broadcast::Receiver<ReceivedPushFrame>>,
    ),
    RedisError,
> {
    let prepare = async {
        let mut connection = factory.connect().await?;
        let pushes = if maintenance_enabled {
            Some(register_connection(&mut connection).await?)
        } else {
            None
        };
        Ok((connection, pushes))
    };
    match timeout {
        Some(timeout) => tokio::time::timeout(timeout, prepare)
            .await
            .map_err(|_| RedisError::ConnectTimeout)?,
        None => prepare.await,
    }
}

async fn wait_for_pending_handoff(
    conn: &mut Option<RedisConnection>,
    state: &mut Option<MaintenanceState>,
    control_rx: &mut Option<mpsc::UnboundedReceiver<MaintenanceControl>>,
    push_rx: &mut Option<tokio::sync::broadcast::Receiver<ReceivedPushFrame>>,
    event_bus: Option<&ConnectionEventBus>,
    shutdown: &mut watch::Receiver<bool>,
) -> PendingHandoffOutcome {
    loop {
        let Some(pending) = state.as_ref().and_then(|state| state.pending.as_ref()) else {
            return PendingHandoffOutcome::Cancelled;
        };
        let deadline = pending.deadline;
        let sequence = pending.sequence;
        if deadline <= tokio::time::Instant::now() {
            return PendingHandoffOutcome::Ready { sequence };
        }

        tokio::select! {
            biased;
            () = wait_for_shutdown(shutdown) => return PendingHandoffOutcome::Shutdown,
            control = recv_maintenance_control(control_rx) => {
                apply_maintenance_control(control, state, control_rx, push_rx);
                if state.as_ref().and_then(|state| state.pending.as_ref()).is_none() {
                    return PendingHandoffOutcome::Cancelled;
                }
            }
            push = recv_maintenance_push(push_rx) => {
                if handle_maintenance_push_result(push, state, push_rx, event_bus).is_err() {
                    return PendingHandoffOutcome::ConnectionFailed(maintenance_feed_error());
                }
            }
            result = read_idle_push_if_connected(conn) => {
                if let Err(error) = result {
                    return PendingHandoffOutcome::ConnectionFailed(error);
                }
            }
            () = tokio::time::sleep_until(deadline) => {
                // Re-read the state on the next loop because another MOVING
                // notification may have installed an earlier deadline.
            }
        }
    }
}

fn fail_requests(requests: Vec<WorkerRequest>) {
    for request in requests {
        request.fail(RedisError::ConnectionClosed);
    }
}

/// Replace a failed factory-backed worker connection.
///
/// Returns `true` when a replacement was installed and the worker should
/// continue. All terminal outcomes fail requests queued during reconnect and
/// return `false`.
#[allow(clippy::too_many_arguments)]
async fn reconnect_worker_connection(
    conn: &mut RedisConnection,
    rx: &mut mpsc::Receiver<WorkerRequest>,
    factory: &dyn ConnectionFactory,
    reconnect: &ReconnectConfig,
    event_bus: Option<&ConnectionEventBus>,
    shutdown: &mut watch::Receiver<bool>,
    control: &WorkerControl,
    connection_health: &ConnectionHealthPublisher,
    outage_reported: &mut bool,
    maintenance_push_rx: &mut Option<tokio::sync::broadcast::Receiver<ReceivedPushFrame>>,
    maintenance_enabled: bool,
) -> bool {
    let started = Instant::now();
    match reconnect_with_backoff(
        factory,
        reconnect,
        event_bus,
        shutdown,
        control,
        maintenance_enabled,
    )
    .await
    {
        ReconnectOutcome::Connected(new_conn, new_push_rx, attempts) => {
            let reconnected = control.with_active_handle(|| {
                *conn = *new_conn;
                *maintenance_push_rx = new_push_rx;
                // Publish health before the lifecycle event so observers can
                // rely on the event/state ordering in either direction.
                connection_health.set(true);
                *outage_reported = false;
                if let Some(events) = event_bus {
                    events.publish(ConnectionEvent::Reconnected {
                        attempts,
                        elapsed: started.elapsed(),
                    });
                }
            });
            if reconnected.is_some() {
                true
            } else {
                fail_queued_requests(rx);
                false
            }
        }
        ReconnectOutcome::Exhausted | ReconnectOutcome::Shutdown => {
            fail_queued_requests(rx);
            false
        }
    }
}

fn fail_queued_requests(rx: &mut mpsc::Receiver<WorkerRequest>) {
    rx.close();
    while let Ok(request) = rx.try_recv() {
        request.fail(RedisError::ConnectionClosed);
    }
}

fn publish_worker_outage(
    event_bus: Option<&ConnectionEventBus>,
    outage_reported: &mut bool,
    reason: ConnectionDisconnectReason,
    control: &WorkerControl,
) {
    if *outage_reported {
        return;
    }
    let active = control.with_active_handle(|| {
        if let Some(events) = event_bus {
            events.publish(ConnectionEvent::Disconnected { reason });
        }
    });
    if active.is_some() {
        *outage_reported = true;
    }
}

/// True if `frame` is a `READONLY` error reply (write attempted against a
/// replica). Used to detect a demoted Sentinel master.
fn is_readonly_frame(frame: &Frame) -> bool {
    matches!(frame, Frame::Error(e) if e.len() >= 8 && e[..8].eq_ignore_ascii_case(b"READONLY"))
}

/// Send a batch of requests as a pipeline and route responses back.
///
/// Frames from all requests are flattened into a single `execute_pipeline`
/// call in request order, preserving within-request contiguity: every frame
/// from a given `Multi` request appears consecutively on the wire, with no
/// other caller's frames in between. Responses are partitioned back to the
/// originating request.
///
/// Takes ownership of `batch` in a single pass to move frames directly into
/// the pipeline vec, avoiding per-Frame clones. A `Responder` enum tracks
/// response routing alongside the frame vec so both the success and error
/// paths can notify all senders without a second iteration.
///
/// Returns `Ok(())` on success and a typed [`PipelineFailure`] on connection
/// loss, timeout, or `READONLY` so the worker can publish the cause and decide
/// whether to reconnect. All individual response channels are always notified
/// before this returns.
async fn flush_batch(
    conn: &mut RedisConnection,
    batch: Vec<WorkerRequest>,
    response_timeout: Option<Duration>,
    recorder: Option<&Arc<dyn MetricsRecorder>>,
    reconnect_on_readonly: bool,
    connection_health: &ConnectionHealthPublisher,
) -> Result<(), PipelineFailure> {
    // A request can be accepted into the worker queue and then cancelled while
    // this worker waits out `batch_window`. `timeout_at` drops the response
    // receiver at the command deadline; prune those requests at the last
    // batching boundary before frames are moved into the wire pipeline.
    let mut batch = batch;
    batch.retain(|request| !request.response_is_closed());
    if batch.is_empty() {
        return Ok(());
    }

    // Owned single-pass: move frames out of each request directly into the
    // pipeline vec, and collect response senders into a parallel `responders`
    // vec. This eliminates the per-Frame clone that the previous two-pass
    // implementation (borrow to build frames, then own to route responses)
    // required.
    let total_frames: usize = batch.iter().map(|r| r.frame_count()).sum();

    // Report the batch size -- the one observability signal only the worker can
    // see (per-command metrics belong to the composed MetricsLayer instead).
    if let Some(recorder) = recorder {
        recorder.pipeline_flushed(total_frames);
    }

    let mut frames: Vec<Frame> = Vec::with_capacity(total_frames);

    enum Responder {
        Single(oneshot::Sender<Result<Frame, RedisError>>),
        Multi(usize, oneshot::Sender<Result<Vec<Frame>, RedisError>>),
    }
    let mut responders: Vec<Responder> = Vec::with_capacity(batch.len());

    for req in batch {
        match req {
            WorkerRequest::Single { frame, response_tx } => {
                frames.push(frame);
                responders.push(Responder::Single(response_tx));
            }
            WorkerRequest::Multi {
                frames: fs,
                response_tx,
            } => {
                let count = fs.len();
                frames.extend(fs);
                responders.push(Responder::Multi(count, response_tx));
            }
        }
    }

    let exec_result = match response_timeout {
        Some(timeout) => match tokio::time::timeout(timeout, conn.execute_pipeline(frames)).await {
            Ok(result) => result,
            Err(_elapsed) => {
                // Response timeout: the connection has written commands whose
                // replies were never read, so its state is now unknown. Fail
                // the whole batch and signal the worker (via Err) to discard
                // and reconnect the connection.
                connection_health.set(false);
                for responder in responders {
                    match responder {
                        Responder::Single(tx) => {
                            let _ = tx.send(Err(RedisError::CommandTimeout));
                        }
                        Responder::Multi(_, tx) => {
                            let _ = tx.send(Err(RedisError::CommandTimeout));
                        }
                    }
                }
                return Err(PipelineFailure::CommandTimeout);
            }
        },
        None => conn.execute_pipeline(frames).await,
    };
    match exec_result {
        Ok(responses) => {
            // A READONLY reply means the connection points at a replica (e.g. a
            // Sentinel master demoted via REPLICAOF). Detect it before routing
            // so the caller still gets the error, then signal the worker to
            // reconnect via the factory onto a real master.
            let saw_readonly = reconnect_on_readonly && responses.iter().any(is_readonly_frame);

            if saw_readonly {
                connection_health.set(false);
            }

            let mut iter = responses.into_iter();
            for responder in responders {
                match responder {
                    Responder::Single(tx) => {
                        let _ = tx.send(iter.next().ok_or(RedisError::ConnectionClosed));
                    }
                    Responder::Multi(count, tx) => {
                        let collected: Vec<Frame> = iter.by_ref().take(count).collect();
                        if collected.len() == count {
                            let _ = tx.send(Ok(collected));
                        } else {
                            let _ = tx.send(Err(RedisError::ConnectionClosed));
                        }
                    }
                }
            }
            if saw_readonly {
                Err(PipelineFailure::ReadOnly)
            } else {
                Ok(())
            }
        }
        Err(error) => {
            connection_health.set(false);
            for responder in responders {
                match responder {
                    Responder::Single(tx) => {
                        let _ = tx.send(Err(RedisError::ConnectionClosed));
                    }
                    Responder::Multi(_, tx) => {
                        let _ = tx.send(Err(RedisError::ConnectionClosed));
                    }
                }
            }
            Err(PipelineFailure::Connection(error))
        }
    }
}

enum ReconnectOutcome {
    Connected(
        Box<RedisConnection>,
        Option<tokio::sync::broadcast::Receiver<ReceivedPushFrame>>,
        usize,
    ),
    Exhausted,
    Shutdown,
}

async fn wait_for_shutdown(shutdown: &mut watch::Receiver<bool>) {
    if *shutdown.borrow() {
        return;
    }
    let _ = shutdown.changed().await;
}

/// Reconnect with exponential backoff until connected, exhausted, or the last
/// public service handle requests worker shutdown.
async fn reconnect_with_backoff(
    factory: &dyn ConnectionFactory,
    config: &ReconnectConfig,
    event_bus: Option<&ConnectionEventBus>,
    shutdown: &mut watch::Receiver<bool>,
    control: &WorkerControl,
    maintenance_enabled: bool,
) -> ReconnectOutcome {
    let mut attempt: usize = 0;
    loop {
        if *shutdown.borrow() {
            return ReconnectOutcome::Shutdown;
        }
        if config.attempt_exhausted(attempt) {
            warn!(
                attempts = attempt,
                "auto_pipeline: reconnect attempts exhausted"
            );
            let active = control.with_active_handle(|| {
                if let Some(events) = event_bus {
                    events.publish(ConnectionEvent::ReconnectExhausted { attempts: attempt });
                }
            });
            if active.is_none() {
                return ReconnectOutcome::Shutdown;
            }
            return ReconnectOutcome::Exhausted;
        }
        let delay = config.delay_for_attempt(attempt);
        let active = control.with_active_handle(|| {
            if let Some(events) = event_bus {
                events.publish(ConnectionEvent::ReconnectAttempt {
                    attempt: attempt + 1,
                    delay,
                });
            }
        });
        if active.is_none() {
            return ReconnectOutcome::Shutdown;
        }
        if !delay.is_zero() {
            tokio::select! {
                biased;
                () = wait_for_shutdown(shutdown) => return ReconnectOutcome::Shutdown,
                () = tokio::time::sleep(delay) => {}
            }
        }
        attempt += 1;
        let connect = connect_and_prepare(factory, config.connect_timeout, maintenance_enabled);
        tokio::pin!(connect);
        let result = tokio::select! {
            biased;
            () = wait_for_shutdown(shutdown) => return ReconnectOutcome::Shutdown,
            result = &mut connect => result,
        };
        match result {
            Ok((conn, push_rx)) => {
                return ReconnectOutcome::Connected(Box::new(conn), push_rx, attempt);
            }
            Err(e) => {
                warn!(attempt, error = %e, "auto_pipeline: reconnect attempt failed");
                let active = control.with_active_handle(|| {
                    if let Some(events) = event_bus {
                        events.publish_with(|| ConnectionEvent::ReconnectFailed {
                            attempt,
                            error: Arc::from(e.to_string()),
                        });
                    }
                });
                if active.is_none() {
                    return ReconnectOutcome::Shutdown;
                }
                continue;
            }
        }
    }
}

impl Service<Frame> for AutoPipelineService {
    type Response = Frame;
    type Error = RedisError;
    type Future = Pin<Box<dyn Future<Output = Result<Frame, RedisError>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        if self.shed_load {
            // Load-shedding: readiness only reflects channel liveness; `call`
            // does the (possibly failing) `try_send`.
            return if self.tx.is_closed() {
                Poll::Ready(Err(RedisError::ConnectionClosed))
            } else {
                Poll::Ready(Ok(()))
            };
        }
        // Back-pressure: reserve a queue slot, pending until one is free.
        self.poll_tx
            .poll_reserve(cx)
            .map_err(|_| RedisError::ConnectionClosed)
    }

    fn call(&mut self, frame: Frame) -> Self::Future {
        let (resp_tx, resp_rx) = oneshot::channel();
        let request = WorkerRequest::Single {
            frame,
            response_tx: resp_tx,
        };

        if self.shed_load {
            // Accept or reject load-shed work synchronously. A returned but
            // unpolled response future must not retain a hidden channel sender
            // that can keep the worker alive after the final service handle is
            // shut down.
            let send_result = self.tx.try_send(request).map_err(|e| match e {
                tokio::sync::mpsc::error::TrySendError::Full(_) => RedisError::QueueFull,
                tokio::sync::mpsc::error::TrySendError::Closed(_) => RedisError::ConnectionClosed,
            });
            return Box::pin(async move {
                send_result?;
                resp_rx.await.map_err(|_| RedisError::ConnectionClosed)?
            });
        }

        // Back-pressure: fill the slot reserved by `poll_ready`. Per the Tower
        // contract, `poll_ready` must have returned `Ready(Ok)` first.
        let send_result = self
            .poll_tx
            .send_item(request)
            .map_err(|_| RedisError::ConnectionClosed);
        Box::pin(async move {
            send_result?;
            resp_rx.await.map_err(|_| RedisError::ConnectionClosed)?
        })
    }
}

impl Clone for AutoPipelineService {
    fn clone(&self) -> Self {
        // Build a fresh PollSender so the clone starts with no reservation held.
        Self {
            tx: self.tx.clone(),
            poll_tx: PollSender::new(self.tx.clone()),
            shed_load: self.shed_load,
            lease: self.lease.clone(),
            connection_health: self.connection_health.clone(),
            worker: Arc::clone(&self.worker),
        }
    }
}

impl AutoPipelineService {
    /// Returns the current number of requests pending in the internal queue.
    ///
    /// This is an instantaneous snapshot; the value may change immediately
    /// after reading. Use it for observability (metrics, health checks).
    pub fn queue_depth(&self) -> usize {
        self.tx.max_capacity() - self.tx.capacity()
    }
}

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

    #[test]
    fn lazy_factory_requires_an_entered_tokio_runtime() {
        let result = std::panic::catch_unwind(|| {
            AutoPipelineService::with_lazy_factory(
                || async { Err::<RedisConnection, _>(RedisError::ConnectionClosed) },
                AutoPipelineConfig::default(),
                AutoPipelineReconnectConfig::default(),
            )
        });
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn lazy_factory_defers_connection_and_retries_after_initial_failure() {
        use futures::{SinkExt, StreamExt};
        use std::sync::atomic::{AtomicUsize, Ordering};
        use tokio_util::codec::Framed;

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (stream, _) = listener.accept().await.unwrap();
            let mut framed = Framed::new(
                redis_tower_core::RedisStream::Tcp(stream),
                redis_tower_core::RespCodec::new(),
            );
            let request = framed
                .next()
                .await
                .expect("client closed before request")
                .expect("client sent an invalid request");
            assert_eq!(
                request,
                Frame::SimpleString(bytes::Bytes::from_static(b"PING"))
            );
            framed
                .send(Frame::SimpleString(bytes::Bytes::from_static(b"PONG")))
                .await
                .unwrap();
            let _ = framed.next().await;
        });

        let calls = Arc::new(AtomicUsize::new(0));
        let factory_calls = Arc::clone(&calls);
        let factory = move || {
            let factory_calls = Arc::clone(&factory_calls);
            async move {
                if factory_calls.fetch_add(1, Ordering::AcqRel) == 0 {
                    return Err(RedisError::ConnectionClosed);
                }
                let stream = tokio::net::TcpStream::connect(addr)
                    .await
                    .map_err(|error| RedisError::connection(addr.to_string(), error))?;
                Ok(RedisConnection::from_stream(
                    redis_tower_core::RedisStream::Tcp(stream),
                ))
            }
        };

        let events = ConnectionEventBus::new(8);
        let mut event_stream = events.subscribe();
        let mut service = AutoPipelineService::with_lazy_factory_and_events(
            factory,
            AutoPipelineConfig::default(),
            AutoPipelineReconnectConfig::default(),
            events,
        );

        assert_eq!(calls.load(Ordering::Acquire), 0);
        assert!(!service.is_connection_healthy());
        assert!(
            tokio::time::timeout(Duration::from_millis(10), event_stream.recv())
                .await
                .is_err(),
            "lazy construction must not publish a connection event"
        );

        futures::future::poll_fn(|cx| service.poll_ready(cx))
            .await
            .unwrap();
        assert!(matches!(
            service
                .call(Frame::SimpleString(bytes::Bytes::from_static(b"FIRST")))
                .await,
            Err(RedisError::ConnectionClosed)
        ));
        assert!(!service.is_connection_healthy());
        assert!(matches!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::ConnectFailed { .. }
        ));

        futures::future::poll_fn(|cx| service.poll_ready(cx))
            .await
            .unwrap();
        assert_eq!(
            service
                .call(Frame::SimpleString(bytes::Bytes::from_static(b"PING")))
                .await
                .unwrap(),
            Frame::SimpleString(bytes::Bytes::from_static(b"PONG"))
        );
        assert!(service.is_connection_healthy());
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Connected
        );
        assert_eq!(calls.load(Ordering::Acquire), 2);

        service.shutdown().await;
        server.await.unwrap();
    }

    #[tokio::test]
    async fn lazy_factory_shutdown_cancels_first_connection_attempt() {
        use tokio::sync::Notify;

        let entered = Arc::new(Notify::new());
        let factory_entered = Arc::clone(&entered);
        let factory = move || {
            let factory_entered = Arc::clone(&factory_entered);
            async move {
                factory_entered.notify_one();
                futures::future::pending::<Result<RedisConnection, RedisError>>().await
            }
        };
        let mut service = AutoPipelineService::with_lazy_factory(
            factory,
            AutoPipelineConfig {
                shed_load_on_full: true,
                ..AutoPipelineConfig::default()
            },
            AutoPipelineReconnectConfig::default(),
        );

        let response = service.call(Frame::SimpleString(bytes::Bytes::from_static(b"PING")));
        entered.notified().await;
        tokio::time::timeout(Duration::from_secs(1), service.shutdown())
            .await
            .expect("shutdown must cancel a deferred connection attempt");
        assert!(matches!(response.await, Err(RedisError::ConnectionClosed)));
    }

    #[tokio::test]
    async fn initial_factory_timeout_publishes_connect_failed() {
        let factory =
            || async { futures::future::pending::<Result<RedisConnection, RedisError>>().await };
        let events = ConnectionEventBus::new(4);
        let mut stream = events.subscribe();
        let reconnect = AutoPipelineReconnectConfig::new(
            ReconnectConfig::default().connect_timeout(Duration::from_millis(10)),
        );

        let result = AutoPipelineService::with_factory_and_events(
            factory,
            AutoPipelineConfig::default(),
            reconnect,
            events,
        )
        .await;
        assert!(matches!(result, Err(RedisError::ConnectTimeout)));
        assert_eq!(
            stream.recv().await.unwrap(),
            ConnectionEvent::ConnectFailed {
                error: Arc::from(RedisError::ConnectTimeout.to_string()),
            }
        );
    }

    #[tokio::test]
    async fn reconnect_factory_timeout_is_counted_and_exhausted() {
        let factory =
            || async { futures::future::pending::<Result<RedisConnection, RedisError>>().await };
        let config = ReconnectConfig {
            max_retries: Some(0),
            base_delay: Duration::ZERO,
            max_delay: Duration::ZERO,
            jitter: false,
            connect_timeout: Some(Duration::from_millis(10)),
        };
        let events = ConnectionEventBus::new(4);
        let mut stream = events.subscribe();
        let (shutdown_tx, mut shutdown) = watch::channel(false);
        let control = WorkerControl::new(shutdown_tx, None);

        assert!(matches!(
            reconnect_with_backoff(
                &factory,
                &config,
                Some(&events),
                &mut shutdown,
                &control,
                false,
            )
            .await,
            ReconnectOutcome::Exhausted
        ));
        assert_eq!(
            stream.recv().await.unwrap(),
            ConnectionEvent::ReconnectAttempt {
                attempt: 1,
                delay: Duration::ZERO,
            }
        );
        assert_eq!(
            stream.recv().await.unwrap(),
            ConnectionEvent::ReconnectFailed {
                attempt: 1,
                error: Arc::from(RedisError::ConnectTimeout.to_string()),
            }
        );
        assert_eq!(
            stream.recv().await.unwrap(),
            ConnectionEvent::ReconnectExhausted { attempts: 1 }
        );
    }

    #[tokio::test]
    async fn reconnect_exhaustion_is_published_after_final_failure() {
        let factory = || async { Err::<RedisConnection, _>(RedisError::ConnectionClosed) };
        let config = ReconnectConfig {
            max_retries: Some(2),
            base_delay: Duration::ZERO,
            max_delay: Duration::ZERO,
            jitter: false,
            connect_timeout: None,
        };
        let events = ConnectionEventBus::new(8);
        let mut stream = events.subscribe();
        let (shutdown_tx, mut shutdown) = watch::channel(false);
        let control = WorkerControl::new(shutdown_tx, None);

        assert!(matches!(
            reconnect_with_backoff(
                &factory,
                &config,
                Some(&events),
                &mut shutdown,
                &control,
                false,
            )
            .await,
            ReconnectOutcome::Exhausted
        ));

        assert_eq!(
            stream.recv().await.unwrap(),
            ConnectionEvent::ReconnectAttempt {
                attempt: 1,
                delay: Duration::ZERO,
            }
        );
        assert!(matches!(
            stream.recv().await.unwrap(),
            ConnectionEvent::ReconnectFailed { attempt: 1, .. }
        ));
        assert_eq!(
            stream.recv().await.unwrap(),
            ConnectionEvent::ReconnectAttempt {
                attempt: 2,
                delay: Duration::ZERO,
            }
        );
        assert!(matches!(
            stream.recv().await.unwrap(),
            ConnectionEvent::ReconnectFailed { attempt: 2, .. }
        ));
        assert_eq!(
            stream.recv().await.unwrap(),
            ConnectionEvent::ReconnectAttempt {
                attempt: 3,
                delay: Duration::ZERO,
            }
        );
        assert!(matches!(
            stream.recv().await.unwrap(),
            ConnectionEvent::ReconnectFailed { attempt: 3, .. }
        ));
        assert_eq!(
            stream.recv().await.unwrap(),
            ConnectionEvent::ReconnectExhausted { attempts: 3 }
        );
    }

    #[tokio::test]
    async fn factory_worker_detects_idle_disconnect_and_reconnects_in_order() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use tokio::sync::{Notify, oneshot};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let (first_closed_tx, first_closed_rx) = oneshot::channel();
        let server = tokio::spawn(async move {
            let (first, _) = listener.accept().await.unwrap();
            drop(first);
            let _ = first_closed_tx.send(());

            let (second, _) = listener.accept().await.unwrap();
            let _second = second;
            futures::future::pending::<()>().await;
        });

        let calls = Arc::new(AtomicUsize::new(0));
        let allow_reconnect = Arc::new(Notify::new());
        let factory_calls = Arc::clone(&calls);
        let factory_allow_reconnect = Arc::clone(&allow_reconnect);
        let factory = move || {
            let factory_calls = Arc::clone(&factory_calls);
            let factory_allow_reconnect = Arc::clone(&factory_allow_reconnect);
            async move {
                let call = factory_calls.fetch_add(1, Ordering::AcqRel);
                if call == 1 {
                    return Err(RedisError::ConnectionClosed);
                }
                if call == 2 {
                    factory_allow_reconnect.notified().await;
                }
                let stream = tokio::net::TcpStream::connect(addr)
                    .await
                    .map_err(|error| RedisError::connection(addr.to_string(), error))?;
                Ok(RedisConnection::from_stream(
                    redis_tower_core::RedisStream::Tcp(stream),
                ))
            }
        };

        let events = ConnectionEventBus::new(16);
        let mut event_stream = events.subscribe();
        let reconnect = AutoPipelineReconnectConfig::new(ReconnectConfig {
            max_retries: Some(3),
            base_delay: Duration::ZERO,
            max_delay: Duration::ZERO,
            jitter: false,
            connect_timeout: None,
        });
        let service = AutoPipelineService::with_factory_and_events(
            factory,
            AutoPipelineConfig::default(),
            reconnect,
            events,
        )
        .await
        .unwrap();
        let mut health = service.subscribe_connection_health();
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Connected
        );

        first_closed_rx.await.unwrap();
        assert!(matches!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Disconnected {
                reason: ConnectionDisconnectReason::ConnectionError { .. }
            }
        ));
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::ReconnectAttempt {
                attempt: 1,
                delay: Duration::ZERO,
            }
        );
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::ReconnectFailed {
                attempt: 1,
                error: Arc::from("connection closed"),
            }
        );
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::ReconnectAttempt {
                attempt: 2,
                delay: Duration::ZERO,
            }
        );
        health.changed().await.unwrap();
        assert!(!*health.borrow_and_update());
        assert!(!service.is_connection_healthy());

        allow_reconnect.notify_one();
        assert!(matches!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Reconnected { attempts: 2, .. }
        ));
        health.changed().await.unwrap();
        assert!(*health.borrow_and_update());
        assert!(service.is_connection_healthy());
        assert_eq!(calls.load(Ordering::Acquire), 3);

        service.shutdown().await;
        server.abort();
    }

    #[tokio::test]
    async fn final_handle_shutdown_cancels_hanging_unlimited_reconnect() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use tokio::sync::{Notify, oneshot};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let (first_closed_tx, first_closed_rx) = oneshot::channel();
        let server = tokio::spawn(async move {
            let (first, _) = listener.accept().await.unwrap();
            drop(first);
            let _ = first_closed_tx.send(());
        });

        let calls = Arc::new(AtomicUsize::new(0));
        let reconnect_entered = Arc::new(Notify::new());
        let factory_calls = Arc::clone(&calls);
        let factory_entered = Arc::clone(&reconnect_entered);
        let factory = move || {
            let factory_calls = Arc::clone(&factory_calls);
            let factory_entered = Arc::clone(&factory_entered);
            async move {
                if factory_calls.fetch_add(1, Ordering::AcqRel) > 0 {
                    factory_entered.notify_one();
                    return futures::future::pending::<Result<RedisConnection, RedisError>>().await;
                }
                let stream = tokio::net::TcpStream::connect(addr)
                    .await
                    .map_err(|error| RedisError::connection(addr.to_string(), error))?;
                Ok(RedisConnection::from_stream(
                    redis_tower_core::RedisStream::Tcp(stream),
                ))
            }
        };

        let events = ConnectionEventBus::new(8);
        let mut event_stream = events.subscribe();
        let reconnect = AutoPipelineReconnectConfig::new(ReconnectConfig {
            max_retries: None,
            base_delay: Duration::ZERO,
            max_delay: Duration::from_secs(5),
            jitter: false,
            connect_timeout: None,
        });
        let service = AutoPipelineService::with_factory_and_events(
            factory,
            AutoPipelineConfig::default(),
            reconnect,
            events,
        )
        .await
        .unwrap();
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Connected
        );

        first_closed_rx.await.unwrap();
        assert!(matches!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Disconnected {
                reason: ConnectionDisconnectReason::ConnectionError { .. }
            }
        ));
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::ReconnectAttempt {
                attempt: 1,
                delay: Duration::ZERO,
            }
        );
        reconnect_entered.notified().await;

        tokio::time::timeout(Duration::from_secs(1), service.shutdown())
            .await
            .expect("final-handle shutdown must cancel a hanging reconnect factory");
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Disconnected {
                reason: ConnectionDisconnectReason::Shutdown,
            }
        );
        assert_eq!(
            event_stream.recv().await.unwrap_err(),
            crate::reconnect::ConnectionEventRecvError::Closed
        );
        assert_eq!(calls.load(Ordering::Acquire), 2);

        server.await.unwrap();
    }

    #[tokio::test]
    async fn exhausted_worker_still_publishes_shutdown_on_final_handle() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use tokio::sync::oneshot;

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let (first_closed_tx, first_closed_rx) = oneshot::channel();
        let server = tokio::spawn(async move {
            let (first, _) = listener.accept().await.unwrap();
            drop(first);
            let _ = first_closed_tx.send(());
        });

        let calls = Arc::new(AtomicUsize::new(0));
        let factory_calls = Arc::clone(&calls);
        let factory = move || {
            let factory_calls = Arc::clone(&factory_calls);
            async move {
                if factory_calls.fetch_add(1, Ordering::AcqRel) > 0 {
                    return Err(RedisError::ConnectionClosed);
                }
                let stream = tokio::net::TcpStream::connect(addr)
                    .await
                    .map_err(|error| RedisError::connection(addr.to_string(), error))?;
                Ok(RedisConnection::from_stream(
                    redis_tower_core::RedisStream::Tcp(stream),
                ))
            }
        };

        let events = ConnectionEventBus::new(8);
        let mut event_stream = events.subscribe();
        let reconnect = AutoPipelineReconnectConfig::new(ReconnectConfig {
            max_retries: Some(0),
            base_delay: Duration::ZERO,
            max_delay: Duration::ZERO,
            jitter: false,
            connect_timeout: None,
        });
        let service = AutoPipelineService::with_factory_and_events(
            factory,
            AutoPipelineConfig::default(),
            reconnect,
            events,
        )
        .await
        .unwrap();
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Connected
        );

        first_closed_rx.await.unwrap();
        assert!(matches!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Disconnected {
                reason: ConnectionDisconnectReason::ConnectionError { .. }
            }
        ));
        assert!(matches!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::ReconnectAttempt { attempt: 1, .. }
        ));
        assert!(matches!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::ReconnectFailed { attempt: 1, .. }
        ));
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::ReconnectExhausted { attempts: 1 }
        );

        tokio::time::timeout(Duration::from_secs(1), service.shutdown())
            .await
            .expect("shutdown should join an already exhausted worker");
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Disconnected {
                reason: ConnectionDisconnectReason::Shutdown,
            }
        );
        assert_eq!(
            event_stream.recv().await.unwrap_err(),
            crate::reconnect::ConnectionEventRecvError::Closed
        );
        assert_eq!(calls.load(Ordering::Acquire), 2);

        server.await.unwrap();
    }

    #[test]
    fn config_defaults() {
        let config = AutoPipelineConfig::default();
        assert_eq!(config.max_batch_size, 100);
        assert_eq!(config.batch_window, Duration::ZERO);
        assert_eq!(config.queue_capacity, 1024);
        assert!(
            !config.shed_load_on_full,
            "back-pressure is the default; load shedding is opt-in"
        );
        assert!(
            config.response_timeout.is_none(),
            "no response deadline by default"
        );
        assert!(
            config.metrics_recorder.is_none(),
            "no metrics recorder by default"
        );
    }

    #[test]
    fn config_custom() {
        let config = AutoPipelineConfig {
            max_batch_size: 50,
            batch_window: Duration::from_micros(500),
            queue_capacity: 512,
            shed_load_on_full: true,
            response_timeout: Some(Duration::from_millis(250)),
            metrics_recorder: None,
            reconnect_on_readonly: false,
        };
        assert_eq!(config.max_batch_size, 50);
        assert_eq!(config.batch_window, Duration::from_micros(500));
        assert_eq!(config.queue_capacity, 512);
        assert!(config.shed_load_on_full);
        assert_eq!(config.response_timeout, Some(Duration::from_millis(250)));
        assert!(!config.reconnect_on_readonly);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn fixed_worker_detects_idle_close_and_closes_health_and_queue() {
        let (client, server) = tokio::net::UnixStream::pair().unwrap();
        let conn = RedisConnection::from_stream(redis_tower_core::RedisStream::Unix(client));
        let events = ConnectionEventBus::new(4);
        let mut event_stream = events.subscribe();
        let mut service =
            AutoPipelineService::new_with_events(conn, AutoPipelineConfig::default(), events);
        let mut health = service.subscribe_connection_health();

        assert!(service.is_connection_healthy());
        assert!(*health.borrow());
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Connected
        );

        drop(server);
        let disconnected = tokio::time::timeout(Duration::from_secs(1), event_stream.recv())
            .await
            .expect("idle close was not detected")
            .unwrap();
        assert!(matches!(
            disconnected,
            ConnectionEvent::Disconnected {
                reason: ConnectionDisconnectReason::ConnectionError { .. }
            }
        ));
        assert!(
            !service.is_connection_healthy(),
            "health must be false before Disconnected is observable"
        );

        health
            .changed()
            .await
            .expect("the final unhealthy snapshot must be observable");
        assert!(!*health.borrow_and_update());
        assert!(
            health.changed().await.is_err(),
            "terminal fixed-worker loss must close the health channel"
        );
        assert!(
            futures::future::poll_fn(|cx| service.poll_ready(cx))
                .await
                .is_err(),
            "terminal idle loss must close the request queue"
        );

        service.shutdown().await;
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn pipeline_failure_publishes_unhealthy_before_failing_responder() {
        use futures::StreamExt;
        use tokio_util::codec::Framed;

        let (client, server) = tokio::net::UnixStream::pair().unwrap();
        let server = tokio::spawn(async move {
            let mut framed = Framed::new(
                redis_tower_core::RedisStream::Unix(server),
                redis_tower_core::RespCodec::new(),
            );
            framed
                .next()
                .await
                .expect("client closed before dispatch")
                .expect("client sent an invalid request");
            // Closing after reading the request makes this an in-flight
            // transport failure rather than an idle-close race.
        });

        let conn = RedisConnection::from_stream(redis_tower_core::RedisStream::Unix(client));
        let events = ConnectionEventBus::new(4);
        let mut event_stream = events.subscribe();
        let mut service =
            AutoPipelineService::new_with_events(conn, AutoPipelineConfig::default(), events);
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Connected
        );

        futures::future::poll_fn(|cx| service.poll_ready(cx))
            .await
            .unwrap();
        assert!(
            service
                .call(Frame::SimpleString(bytes::Bytes::from_static(b"PING")))
                .await
                .is_err()
        );
        assert!(
            !service.is_connection_healthy(),
            "the response future observed failure before shared health changed"
        );
        assert!(matches!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Disconnected {
                reason: ConnectionDisconnectReason::ConnectionError { .. }
            }
        ));

        service.shutdown().await;
        server.await.unwrap();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn response_timeout_publishes_unhealthy_before_failing_responder() {
        use futures::StreamExt;
        use tokio_util::codec::Framed;

        let (client, server) = tokio::net::UnixStream::pair().unwrap();
        let server = tokio::spawn(async move {
            let mut framed = Framed::new(
                redis_tower_core::RedisStream::Unix(server),
                redis_tower_core::RespCodec::new(),
            );
            framed
                .next()
                .await
                .expect("client closed before dispatch")
                .expect("client sent an invalid request");
            // Deliberately withhold the response until the client's deadline
            // quarantines and closes the transport.
            let _ = framed.next().await;
        });

        let conn = RedisConnection::from_stream(redis_tower_core::RedisStream::Unix(client));
        let events = ConnectionEventBus::new(4);
        let mut event_stream = events.subscribe();
        let config = AutoPipelineConfig {
            response_timeout: Some(Duration::from_millis(10)),
            ..AutoPipelineConfig::default()
        };
        let mut service = AutoPipelineService::new_with_events(conn, config, events);
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Connected
        );

        futures::future::poll_fn(|cx| service.poll_ready(cx))
            .await
            .unwrap();
        assert!(matches!(
            service
                .call(Frame::SimpleString(bytes::Bytes::from_static(b"PING")))
                .await,
            Err(RedisError::CommandTimeout)
        ));
        assert!(
            !service.is_connection_healthy(),
            "the timeout responder was notified before shared health changed"
        );
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Disconnected {
                reason: ConnectionDisconnectReason::CommandTimeout,
            }
        );

        service.shutdown().await;
        server.await.unwrap();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn idle_push_is_routed_without_delaying_the_next_request() {
        use futures::{SinkExt, StreamExt};
        use tokio_util::codec::Framed;

        let (client, server) = tokio::net::UnixStream::pair().unwrap();
        let mut conn = RedisConnection::from_stream(redis_tower_core::RedisStream::Unix(client));
        let mut pushes = conn.subscribe_pushes();
        let expected_push = Frame::Push(vec![
            Frame::SimpleString(bytes::Bytes::from_static(b"invalidate")),
            Frame::Array(Some(vec![Frame::SimpleString(bytes::Bytes::from_static(
                b"key",
            ))])),
        ]);
        let server_push = expected_push.clone();
        let server = tokio::spawn(async move {
            let mut framed = Framed::new(
                redis_tower_core::RedisStream::Unix(server),
                redis_tower_core::RespCodec::new(),
            );
            framed.send(server_push).await.unwrap();
            framed
                .next()
                .await
                .expect("client closed before request")
                .expect("client sent an invalid request");
            framed
                .send(Frame::SimpleString(bytes::Bytes::from_static(b"PONG")))
                .await
                .unwrap();
            // Keep the socket open until the worker's graceful shutdown drops
            // its side, proving the health assertion below is not racy.
            let _ = framed.next().await;
        });

        let mut service = AutoPipelineService::new(conn, AutoPipelineConfig::default());
        assert_eq!(
            tokio::time::timeout(Duration::from_secs(1), pushes.recv())
                .await
                .expect("idle worker did not route the push")
                .unwrap(),
            expected_push
        );
        futures::future::poll_fn(|cx| service.poll_ready(cx))
            .await
            .unwrap();
        assert_eq!(
            service
                .call(Frame::SimpleString(bytes::Bytes::from_static(b"PING")))
                .await
                .unwrap(),
            Frame::SimpleString(bytes::Bytes::from_static(b"PONG"))
        );
        assert!(service.is_connection_healthy());

        service.shutdown().await;
        server.await.unwrap();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn cancelled_single_and_multi_requests_are_pruned_before_wire() {
        use tokio::io::AsyncReadExt;

        let (client, mut server) = tokio::net::UnixStream::pair().unwrap();
        let conn = RedisConnection::from_stream(redis_tower_core::RedisStream::Unix(client));
        let batch_window = Duration::from_millis(200);
        let mut service = AutoPipelineService::new(
            conn,
            AutoPipelineConfig {
                batch_window,
                ..AutoPipelineConfig::default()
            },
        );

        futures::future::poll_fn(|cx| service.poll_ready(cx))
            .await
            .unwrap();
        let single = service.call(Frame::SimpleString(bytes::Bytes::from_static(
            b"CANCELLED-SINGLE",
        )));
        assert!(
            tokio::time::timeout(Duration::from_millis(25), single)
                .await
                .is_err(),
            "single request unexpectedly completed without a server response"
        );

        let multi = service.call_pipeline(vec![
            Frame::SimpleString(bytes::Bytes::from_static(b"CANCELLED-MULTI-1")),
            Frame::SimpleString(bytes::Bytes::from_static(b"CANCELLED-MULTI-2")),
        ]);
        assert!(
            tokio::time::timeout(Duration::from_millis(25), multi)
                .await
                .is_err(),
            "multi request unexpectedly completed without a server response"
        );

        // Both response receivers are closed well before the batch window
        // ends. The worker must drop both requests rather than flushing their
        // frames after the caller deadlines have expired.
        let mut bytes = [0u8; 256];
        assert!(
            tokio::time::timeout(
                batch_window + Duration::from_millis(100),
                server.read(&mut bytes)
            )
            .await
            .is_err(),
            "a cancelled queued request reached the Redis socket"
        );

        service.shutdown().await;
    }

    #[test]
    fn is_readonly_frame_detects_readonly_errors_only() {
        use bytes::Bytes;
        assert!(is_readonly_frame(&Frame::Error(Bytes::from(
            "READONLY You can't write against a read only replica."
        ))));
        // Case-insensitive on the prefix.
        assert!(is_readonly_frame(&Frame::Error(Bytes::from(
            "readonly nope"
        ))));
        // Other errors and non-error frames are not READONLY.
        assert!(!is_readonly_frame(&Frame::Error(Bytes::from(
            "WRONGTYPE Operation against a key"
        ))));
        assert!(!is_readonly_frame(&Frame::Error(Bytes::from("READ"))));
        assert!(!is_readonly_frame(&Frame::SimpleString(Bytes::from("OK"))));
    }

    fn make_test_svc(
        tx: mpsc::Sender<WorkerRequest>,
        handle: tokio::task::JoinHandle<()>,
        shed_load: bool,
    ) -> AutoPipelineService {
        let (shutdown_tx, _shutdown_rx) = watch::channel(false);
        let (_connection_health_tx, connection_health) = watch::channel(true);
        let control = Arc::new(WorkerControl::new(shutdown_tx, None));
        AutoPipelineService {
            poll_tx: PollSender::new(tx.clone()),
            tx,
            shed_load,
            lease: WorkerLease { control },
            connection_health,
            worker: Arc::new(WorkerHandle::new(handle)),
        }
    }

    #[tokio::test]
    async fn closed_channel_error_is_retryable() {
        // When the background worker is gone (connection death), the error
        // must be retryable so upstream retry layers can reconnect.
        let (tx, rx) = mpsc::channel::<WorkerRequest>(1);
        drop(rx);
        let mut svc = make_test_svc(tx, tokio::spawn(async {}), true);

        let frame = Frame::SimpleString(b"PING"[..].into());
        let err = svc.call(frame).await.unwrap_err();
        assert!(err.is_retryable());
    }

    #[tokio::test]
    async fn closed_channel_returns_error() {
        // Create a service with a channel that we immediately close.
        let (tx, rx) = mpsc::channel::<WorkerRequest>(1);
        drop(rx); // close the receiver
        let mut svc = make_test_svc(tx, tokio::spawn(async {}), true);

        // poll_ready should report closed.
        let ready = futures::future::poll_fn(|cx| svc.poll_ready(cx)).await;
        assert!(ready.is_err());

        // call should also fail.
        let frame = Frame::SimpleString(b"PING"[..].into());
        let result = svc.call(frame).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn shutdown_drains_an_unpolled_shed_load_call() {
        use futures::{SinkExt, StreamExt};
        use tokio_util::codec::Framed;

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let request = Frame::Array(Some(vec![Frame::BulkString(Some(
            bytes::Bytes::from_static(b"PING"),
        ))]));
        let expected_request = request.clone();
        let server = tokio::spawn(async move {
            let (stream, _) = listener.accept().await.unwrap();
            let mut framed = Framed::new(
                redis_tower_core::RedisStream::Tcp(stream),
                redis_tower_core::RespCodec::new(),
            );
            assert_eq!(framed.next().await.unwrap().unwrap(), expected_request);
            framed
                .send(Frame::SimpleString(bytes::Bytes::from_static(b"PONG")))
                .await
                .unwrap();
        });

        let stream = tokio::net::TcpStream::connect(addr).await.unwrap();
        let conn = RedisConnection::from_stream(redis_tower_core::RedisStream::Tcp(stream));
        let events = ConnectionEventBus::new(4);
        let mut event_stream = events.subscribe();
        let config = AutoPipelineConfig {
            // A long window makes it deterministic that final shutdown, not
            // the timer, causes the already-accepted request to flush.
            batch_window: Duration::from_secs(30),
            shed_load_on_full: true,
            ..AutoPipelineConfig::default()
        };
        let mut service = AutoPipelineService::new_with_events(conn, config, events);
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Connected
        );

        // Intentionally retain this future without polling it. `call` must
        // have accepted the request synchronously without hiding a sender in
        // the response future, and shutdown must drain that queued request.
        let response = service.call(request);
        tokio::time::timeout(Duration::from_secs(1), service.shutdown())
            .await
            .expect("an unpolled shed-load call must not keep shutdown alive");
        assert_eq!(
            response.await.unwrap(),
            Frame::SimpleString(bytes::Bytes::from_static(b"PONG"))
        );
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Disconnected {
                reason: ConnectionDisconnectReason::Shutdown,
            }
        );
        assert_eq!(
            event_stream.recv().await.unwrap_err(),
            crate::reconnect::ConnectionEventRecvError::Closed
        );

        server.await.unwrap();
    }

    #[tokio::test]
    async fn final_shutdown_closes_an_idle_worker_with_a_retained_sender() {
        use tokio::io::AsyncReadExt;

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (mut stream, _) = listener.accept().await.unwrap();
            let mut byte = [0_u8; 1];
            assert_eq!(stream.read(&mut byte).await.unwrap(), 0);
        });

        let stream = tokio::net::TcpStream::connect(addr).await.unwrap();
        let conn = RedisConnection::from_stream(redis_tower_core::RedisStream::Tcp(stream));
        let service = AutoPipelineService::new(conn, AutoPipelineConfig::default());

        // Model a sender retained by an already-returned future or adapter.
        // Final public-handle shutdown must wake the idle worker independently
        // of sender count and close the receiver against any late work.
        let retained_sender = service.tx.clone();
        tokio::time::timeout(Duration::from_secs(1), service.shutdown())
            .await
            .expect("final shutdown must wake an idle worker");
        assert!(retained_sender.is_closed());
        drop(retained_sender);

        tokio::time::timeout(Duration::from_secs(1), server)
            .await
            .expect("worker shutdown must close its Redis connection")
            .unwrap();
    }

    #[tokio::test]
    async fn shutdown_last_clone_awaits_worker() {
        // Create a service whose worker exits immediately (no connection, no
        // requests -- the channel closes as soon as tx is dropped).
        let (tx, rx) = mpsc::channel::<WorkerRequest>(1);
        let handle = tokio::spawn(async move {
            // Simulate a worker that drains and exits when the channel closes.
            let mut rx = rx;
            while rx.recv().await.is_some() {}
        });
        let svc = make_test_svc(tx, handle, false);

        // shutdown() on the sole instance should drop tx, succeed in
        // Arc::try_unwrap, and await the worker to completion.
        svc.shutdown().await;
        // If we reach here the worker has exited cleanly.
    }

    #[tokio::test]
    async fn shutdown_publishes_one_intentional_disconnect() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (stream, _) = listener.accept().await.unwrap();
            let _stream = stream;
            futures::future::pending::<()>().await;
        });
        let stream = tokio::net::TcpStream::connect(addr).await.unwrap();
        let conn = RedisConnection::from_stream(redis_tower_core::RedisStream::Tcp(stream));
        let events = ConnectionEventBus::new(4);
        let mut event_stream = events.subscribe();
        let service =
            AutoPipelineService::new_with_events(conn, AutoPipelineConfig::default(), events);
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Connected
        );

        service.shutdown().await;
        assert_eq!(
            event_stream.recv().await.unwrap(),
            ConnectionEvent::Disconnected {
                reason: ConnectionDisconnectReason::Shutdown,
            }
        );

        server.abort();
    }

    #[tokio::test]
    async fn shutdown_non_last_clone_returns_immediately() {
        // When another clone is alive, Arc::try_unwrap fails and shutdown()
        // returns immediately without awaiting the worker.
        let (tx, _rx) = mpsc::channel::<WorkerRequest>(1);
        // Spawn a worker that never exits on its own.
        let handle = tokio::spawn(futures::future::pending::<()>());
        let svc = make_test_svc(tx, handle, false);

        // Keep a second clone alive so Arc::try_unwrap will fail.
        let _clone = svc.clone();

        // shutdown() on this clone should return immediately (not hang).
        svc.shutdown().await;

        // _clone still holds the Arc; worker is still running.
        // Drop the clone to let the worker task get cleaned up.
    }

    #[tokio::test]
    async fn is_alive_tracks_worker_exit() {
        // A running worker reports alive.
        let (tx, _rx) = mpsc::channel::<WorkerRequest>(1);
        let alive = make_test_svc(tx, tokio::spawn(futures::future::pending::<()>()), false);
        assert!(alive.is_alive());

        // A worker that has returned reports not-alive once the task finishes.
        let (tx2, _rx2) = mpsc::channel::<WorkerRequest>(1);
        let dead = make_test_svc(tx2, tokio::spawn(async {}), false);
        // Let the empty worker task complete before checking.
        for _ in 0..10 {
            if !dead.is_alive() {
                break;
            }
            tokio::task::yield_now().await;
        }
        assert!(!dead.is_alive());
    }

    #[tokio::test]
    async fn queue_full_returns_queue_full_error() {
        // Fill the channel (capacity 1), then verify the next call returns QueueFull.
        let (tx, _rx) = mpsc::channel::<WorkerRequest>(1);
        // Fill the one slot without receiving.
        let (dummy_tx, _dummy_rx) = oneshot::channel();
        tx.try_send(WorkerRequest::Single {
            frame: Frame::SimpleString(b"PING"[..].into()),
            response_tx: dummy_tx,
        })
        .unwrap();

        let mut svc = make_test_svc(tx, tokio::spawn(async {}), true);

        let frame = Frame::SimpleString(b"PING"[..].into());
        let err = svc.call(frame).await.unwrap_err();
        assert!(
            matches!(err, RedisError::QueueFull),
            "expected QueueFull, got {err:?}"
        );
    }

    #[tokio::test]
    async fn backpressure_poll_ready_pends_when_full() {
        // Default (back-pressure) mode: a full queue makes poll_ready pend
        // rather than returning QueueFull.
        let (tx, _rx) = mpsc::channel::<WorkerRequest>(1);
        // Occupy the single slot without draining it.
        let (dummy_tx, _dummy_rx) = oneshot::channel();
        tx.try_send(WorkerRequest::Single {
            frame: Frame::SimpleString(b"PING"[..].into()),
            response_tx: dummy_tx,
        })
        .unwrap();

        let mut svc = make_test_svc(tx, tokio::spawn(async {}), false);
        let pending = std::future::poll_fn(|cx| Poll::Ready(svc.poll_ready(cx).is_pending())).await;
        assert!(
            pending,
            "poll_ready must pend (back-pressure) when the queue is full"
        );
    }

    #[tokio::test]
    async fn reserved_pipeline_consumes_poll_ready_slot_as_one_request() {
        let (tx, mut rx) = mpsc::channel::<WorkerRequest>(1);
        let mut svc = make_test_svc(tx, tokio::spawn(async {}), false);

        futures::future::poll_fn(|cx| svc.poll_ready(cx))
            .await
            .unwrap();

        let frames = vec![
            Frame::SimpleString(b"CLIENT CACHING YES"[..].into()),
            Frame::SimpleString(b"GET key"[..].into()),
        ];
        let response = svc.call_reserved_pipeline(frames.clone());

        let request = rx.recv().await.expect("reserved request should be queued");
        match request {
            WorkerRequest::Multi {
                frames: actual,
                response_tx,
            } => {
                assert_eq!(actual, frames);
                response_tx
                    .send(Ok(vec![
                        Frame::SimpleString(b"OK"[..].into()),
                        Frame::BulkString(Some(b"value"[..].into())),
                    ]))
                    .unwrap();
            }
            WorkerRequest::Single { .. } => panic!("reserved pipeline was split into a single"),
        }

        assert_eq!(response.await.unwrap().len(), 2);
    }

    #[tokio::test]
    async fn local_response_can_release_poll_ready_reservation() {
        let (tx, _rx) = mpsc::channel::<WorkerRequest>(1);
        let mut svc = make_test_svc(tx.clone(), tokio::spawn(async {}), false);

        assert_eq!(tx.capacity(), 1);
        futures::future::poll_fn(|cx| svc.poll_ready(cx))
            .await
            .unwrap();
        assert_eq!(tx.capacity(), 0, "poll_ready should reserve capacity");

        svc.release_reservation();
        assert_eq!(
            tx.capacity(),
            1,
            "a locally satisfied request must restore queue capacity"
        );
    }

    #[tokio::test]
    async fn backpressure_poll_ready_errors_when_closed() {
        // A closed channel surfaces as a (retryable) connection error from
        // poll_ready in back-pressure mode -- not a pend.
        let (tx, rx) = mpsc::channel::<WorkerRequest>(1);
        drop(rx);
        let mut svc = make_test_svc(tx, tokio::spawn(async {}), false);
        let ready = std::future::poll_fn(|cx| svc.poll_ready(cx)).await;
        let err = ready.unwrap_err();
        assert!(
            err.is_retryable(),
            "closed-channel error should be retryable"
        );
    }

    #[tokio::test]
    async fn queue_full_not_retryable() {
        assert!(!RedisError::QueueFull.is_retryable());
    }

    #[tokio::test]
    async fn queue_full_not_connection_error() {
        assert!(!RedisError::QueueFull.is_connection_error());
    }

    #[test]
    fn config_queue_capacity_default() {
        let config = AutoPipelineConfig::default();
        assert_eq!(config.queue_capacity, 1024);
    }

    #[tokio::test]
    async fn queue_depth_zero_when_empty() {
        // A fresh channel with nothing sent should report depth 0.
        let (tx, _rx) = mpsc::channel::<WorkerRequest>(64);
        let svc = make_test_svc(tx, tokio::spawn(async {}), false);
        assert_eq!(svc.queue_depth(), 0);
    }

    #[tokio::test]
    async fn queue_depth_increases_with_pending_requests() {
        // With no receiver draining, each enqueued request raises the depth.
        let (tx, _rx) = mpsc::channel::<WorkerRequest>(10);
        let svc = make_test_svc(tx.clone(), tokio::spawn(async {}), false);

        assert_eq!(svc.queue_depth(), 0);

        // Manually enqueue a request to simulate a queued, unconsumed item.
        let (dummy_tx, _dummy_rx) = oneshot::channel();
        tx.try_send(WorkerRequest::Single {
            frame: Frame::SimpleString(b"PING"[..].into()),
            response_tx: dummy_tx,
        })
        .unwrap();

        assert_eq!(svc.queue_depth(), 1);
    }
}