halephant-core 0.6.0

A proxy and pooler for Postgres
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
#![allow(clippy::unwrap_used)]
#[path = "pool_test/mock_pg.rs"]
mod mock_pg;

use std::sync::Arc;

use arc_swap::ArcSwap;
use futures_util::{SinkExt, StreamExt};
use tokio::net::{TcpListener, TcpStream};
use tokio_util::codec::Framed;

use halephant_core::config::Config;
use halephant_core::config::cluster::pool::ListenMode;
use halephant_core::pool::PoolManager;
use halephant_core::pool::types::{CheckoutError, classify_checkout_error};
use halephant_core::proto::backend::BackendMessage;
use halephant_core::proto::codec::{BackendCodec, FrontendCodec};
use halephant_core::proto::frontend::FrontendMessage;
use halephant_core::proto::types::TransactionStatus;
use halephant_core::topology::{ClusterTopology, TopologyManager};

use super::test_client_guard;
use mock_pg::{MockBehavior, MockPg};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// All test configs use a very short `checkout_timeout` so exhaustion
/// tests fail fast instead of hanging for the 30-second production
/// default. Tests that want to verify genuine wait-queue behavior
/// configure the sleep interval explicitly.
const TEST_CHECKOUT_TIMEOUT: &str = "50ms";

fn test_config(node_addr: &str) -> Config {
    Config::parse(&format!(
        r#"
        [server]
        checkout_timeout = "{TEST_CHECKOUT_TIMEOUT}"

        [cluster.test]
        nodes = ["{node_addr}"]

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 10 }}

        [cluster.test.pool.testdb.user.testuser]
    "#
    ))
    .unwrap()
}

fn test_config_max(node_addr: &str, max: u32) -> Config {
    Config::parse(&format!(
        r#"
        [server]
        checkout_timeout = "{TEST_CHECKOUT_TIMEOUT}"

        [cluster.test]
        nodes = ["{node_addr}"]

        [cluster.test.pool.testdb]
        max_connections = {{ primary = {max} }}

        [cluster.test.pool.testdb.user.testuser]
    "#
    ))
    .unwrap()
}

fn test_config_with_replica(primary_addr: &str, replica_addr: &str) -> Config {
    Config::parse(&format!(
        r#"
        [server]
        checkout_timeout = "{TEST_CHECKOUT_TIMEOUT}"

        [cluster.test]
        nodes = ["{primary_addr}", "{replica_addr}"]

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 10, replica = 10 }}

        [cluster.test.pool.testdb.user.testuser]

        [cluster.test.pool.testdb.user.rouser]
        max_connections = {{ replica = 10 }}
    "#
    ))
    .unwrap()
}

fn test_config_session(node_addr: &str) -> Config {
    Config::parse(&format!(
        r#"
        [server]
        checkout_timeout = "{TEST_CHECKOUT_TIMEOUT}"

        [cluster.test]
        nodes = ["{node_addr}"]

        [cluster.test.pool.testdb]
        mode = "session"
        max_connections = {{ primary = 10 }}

        [cluster.test.pool.testdb.user.testuser]
    "#
    ))
    .unwrap()
}

/// Create a connected TCP pair (client end, server end).
async fn tcp_pair() -> (TcpStream, TcpStream) {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let (client, server) = tokio::join!(TcpStream::connect(addr), async {
        listener.accept().await.map(|(s, _)| s)
    });
    (client.unwrap(), server.unwrap())
}

/// Seed the topology of the `test` cluster with a single primary address.
/// Tests that drive mocks with behaviors incompatible with the real topology
/// probe (SCRAM, CloseOnQuery, ...) cannot rely on `refresh` to populate
/// topology state, so they inject it directly.
fn seed_primary(topology: &TopologyManager, primary_addr: String) {
    topology.set(
        "test",
        ClusterTopology {
            primary: Some(primary_addr),
            replicas: Vec::new(),
            unreachable: Vec::new(),
        },
    );
}

/// Set up a pool manager backed by a mock primary.
fn setup_pool(mock: &MockPg) -> (Arc<PoolManager>, Arc<ArcSwap<Config>>) {
    setup_pool_with_config(test_config(&mock.addr()), mock)
}

fn setup_pool_with_config(cfg: Config, mock: &MockPg) -> (Arc<PoolManager>, Arc<ArcSwap<Config>>) {
    let config = Arc::new(ArcSwap::from_pointee(cfg));
    let pgpass = Arc::new(halephant_core::auth::pgpass::Pgpass::parse(""));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::clone(&pgpass),
    ));
    seed_primary(&topology, mock.addr());
    let pools = Arc::new(PoolManager::new(
        Arc::clone(&config),
        Arc::clone(&topology),
        pgpass,
    ));
    (pools, config)
}

/// Run transaction::forward in a background task and return its handle.
fn spawn_tx_forward(
    proxy_stream: TcpStream,
    pools: Arc<PoolManager>,
    database: &str,
    user: &str,
    read_only: bool,
) -> tokio::task::JoinHandle<anyhow::Result<()>> {
    let db = database.to_owned();
    let usr = user.to_owned();
    tokio::spawn(async move {
        let client = test_client_guard();
        let mut proxy_client = Framed::new(proxy_stream, FrontendCodec::post_startup());
        halephant_core::proxy::transaction::forward(
            &mut proxy_client,
            &pools,
            &client,
            &mut None,
            ListenMode::Pin,
            &db,
            &usr,
            read_only,
            halephant_core::config::otel::QueryText::Off,
        )
        .await
    })
}

/// Send a simple query and collect all response messages until ReadyForQuery.
async fn query_collect(
    client: &mut Framed<TcpStream, BackendCodec>,
    sql: &str,
) -> Vec<BackendMessage> {
    client
        .send(FrontendMessage::Query(sql.into()))
        .await
        .unwrap();
    let mut msgs = Vec::new();
    loop {
        let msg = client.next().await.unwrap().unwrap();
        let is_ready = matches!(msg, BackendMessage::ReadyForQuery(_));
        msgs.push(msg);
        if is_ready {
            break;
        }
    }
    msgs
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn basic_round_trip() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool(&mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    let msgs = query_collect(&mut client, "SELECT 1").await;

    // Expect: RowDescription, CommandComplete, ReadyForQuery(Idle).
    assert!(
        msgs.iter()
            .any(|m| matches!(m, BackendMessage::RowDescription(_))),
        "expected RowDescription in response"
    );
    assert!(
        msgs.iter()
            .any(|m| matches!(m, BackendMessage::CommandComplete(_))),
        "expected CommandComplete in response"
    );
    assert!(
        matches!(
            msgs.last(),
            Some(BackendMessage::ReadyForQuery(TransactionStatus::Idle))
        ),
        "expected ReadyForQuery(Idle) as final message"
    );

    // Clean shutdown.
    client.send(FrontendMessage::Terminate).await.unwrap();
    handle.await.unwrap().unwrap();
    mock.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn connection_reuse() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool(&mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    // First query — opens a new upstream connection.
    let _ = query_collect(&mut client, "SELECT 1").await;
    assert_eq!(mock.connections(), 1, "first query opens one connection");

    // Second query — should reuse the connection after checkin + reset.
    // Poll until the background reset returns a connection to the idle pool.
    // Each attempt snapshots the mock's connection count before and after; if
    // the count doesn't increase, checkout reused an idle connection.
    let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2);
    loop {
        tokio::time::sleep(std::time::Duration::from_millis(5)).await;
        let before = mock.connections();
        let _ = query_collect(&mut client, "SELECT 2").await;
        if mock.connections() == before {
            break;
        }
        assert!(
            tokio::time::Instant::now() < deadline,
            "connection was not reused within 2 s"
        );
    }

    client.send(FrontendMessage::Terminate).await.unwrap();
    handle.await.unwrap().unwrap();
    mock.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pool_exhaustion() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let config = Arc::new(ArcSwap::from_pointee(test_config_max(&mock.addr(), 1)));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::new(halephant_core::auth::pgpass::Pgpass::parse("")),
    ));
    topology.refresh().await;
    let pools = Arc::new(PoolManager::new(
        Arc::clone(&config),
        Arc::clone(&topology),
        Arc::new(halephant_core::auth::pgpass::Pgpass::parse("")),
    ));

    let client = test_client_guard();

    // First checkout succeeds.
    let guard = pools.checkout(&client, "testdb", "testuser", false).await;
    assert!(guard.is_ok(), "first checkout should succeed");

    // Second checkout exceeds max=1. With queueing, it enqueues and
    // then times out at the configured `checkout_timeout` because the
    // first guard is still held. The classified error mentions the
    // timeout, not literal "pool exhausted".
    let result = pools.checkout(&client, "testdb", "testuser", false).await;
    assert!(result.is_err(), "second checkout should fail");
    let err = result.err().unwrap();
    assert!(
        err.to_string().contains("timed out"),
        "error should mention checkout timeout, got: {err}"
    );

    // Drop the first guard (discards connection).
    drop(guard);
    mock.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn transaction_boundary() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool(&mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    // BEGIN.
    let msgs = query_collect(&mut client, "BEGIN").await;
    assert!(
        matches!(
            msgs.last(),
            Some(BackendMessage::ReadyForQuery(
                TransactionStatus::InTransaction
            ))
        ),
        "expected InTransaction after BEGIN"
    );

    // Query inside transaction.
    let msgs = query_collect(&mut client, "SELECT 1").await;
    assert!(
        matches!(
            msgs.last(),
            Some(BackendMessage::ReadyForQuery(
                TransactionStatus::InTransaction
            ))
        ),
        "expected InTransaction during transaction"
    );

    // COMMIT.
    let msgs = query_collect(&mut client, "COMMIT").await;
    assert!(
        matches!(
            msgs.last(),
            Some(BackendMessage::ReadyForQuery(TransactionStatus::Idle))
        ),
        "expected Idle after COMMIT"
    );

    client.send(FrontendMessage::Terminate).await.unwrap();
    handle.await.unwrap().unwrap();
    mock.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn server_close_mid_transaction() {
    let mock = MockPg::start(MockBehavior::CloseOnQuery).await;
    let (pools, _config) = setup_pool(&mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    // Send a query — the mock will accept the pool's startup handshake but
    // close the connection when it receives the forwarded query.
    client
        .send(FrontendMessage::Query("SELECT 1".into()))
        .await
        .unwrap();

    // The proxy should synthesize an ErrorResponse (FATAL 08006) to the client.
    let mut got_error = false;
    loop {
        match client.next().await {
            Some(Ok(BackendMessage::ErrorResponse(fields))) => {
                let code = fields
                    .fields
                    .iter()
                    .find(|(k, _)| *k == b'C')
                    .map(|(_, v)| v.as_str());
                assert_eq!(code, Some("08006"), "expected connection_failure SQLSTATE");
                got_error = true;
            }
            Some(Ok(BackendMessage::ReadyForQuery(_))) | None => break, // ReadyForQuery or connection closed
            _ => {}
        }
    }
    assert!(got_error, "expected synthesized ErrorResponse from proxy");

    // The forward task should return an error.
    let result = handle.await.unwrap();
    assert!(result.is_err());
    mock.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn server_close_after_startup() {
    // The mock accepts the pool's startup handshake then immediately drops
    // the connection. The proxy may fail sending the query (broken pipe) or
    // detect EOF when reading the response — either way the forward task
    // errors and the client connection closes.
    let mock = MockPg::start(MockBehavior::CloseAfterStartup).await;
    let (pools, _config) = setup_pool(&mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    client
        .send(FrontendMessage::Query("SELECT 1".into()))
        .await
        .unwrap();

    // Drain whatever the proxy sends. Depending on timing we may see a
    // synthesized 08006 ErrorResponse or just EOF.
    while let Some(Ok(_)) = client.next().await {}

    // The forward task must have failed.
    let result = handle.await.unwrap();
    assert!(result.is_err());
    mock.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn read_only_routing() {
    let primary = MockPg::start(MockBehavior::Ok).await;
    let replica = MockPg::start_replica(MockBehavior::Ok).await;
    let config = Arc::new(ArcSwap::from_pointee(test_config_with_replica(
        &primary.addr(),
        &replica.addr(),
    )));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::new(halephant_core::auth::pgpass::Pgpass::parse("")),
    ));
    topology.refresh().await;
    let pools = Arc::new(PoolManager::new(
        Arc::clone(&config),
        Arc::clone(&topology),
        Arc::new(halephant_core::auth::pgpass::Pgpass::parse("")),
    ));

    let client = test_client_guard();

    // Read-only checkout should go to the replica.
    let guard = pools.checkout(&client, "testdb", "testuser", true).await;
    assert!(guard.is_ok(), "read-only checkout should succeed");
    // topology probe uses 1 conn each; checkout adds 1 to replica.
    assert_eq!(
        replica.connections(),
        2, // 1 topology probe + 1 checkout
        "read-only checkout should go to replica"
    );

    drop(guard);

    // Read-write checkout should go to the primary.
    let guard = pools.checkout(&client, "testdb", "testuser", false).await;
    assert!(guard.is_ok(), "read-write checkout should succeed");
    assert_eq!(
        primary.connections(),
        2, // 1 topology probe + 1 checkout
        "read-write checkout should go to primary"
    );

    drop(guard);
    primary.stop().await;
    replica.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn read_only_user_routing() {
    let primary = MockPg::start(MockBehavior::Ok).await;
    let replica = MockPg::start_replica(MockBehavior::Ok).await;
    let config = Arc::new(ArcSwap::from_pointee(test_config_with_replica(
        &primary.addr(),
        &replica.addr(),
    )));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::new(halephant_core::auth::pgpass::Pgpass::parse("")),
    ));
    topology.refresh().await;
    let pools = Arc::new(PoolManager::new(
        Arc::clone(&config),
        Arc::clone(&topology),
        Arc::new(halephant_core::auth::pgpass::Pgpass::parse("")),
    ));

    let (client_tcp, proxy_tcp) = tcp_pair().await;

    // rouser has max_connections = { replica = 10 } (no primary) — is_read_only.
    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "rouser", true);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    let _ = query_collect(&mut client, "SELECT 1").await;
    // The query should have gone to the replica, not the primary.
    assert_eq!(
        replica.connections(),
        2, // 1 topology probe + 1 query checkout
        "read-only user should route to replica"
    );

    client.send(FrontendMessage::Terminate).await.unwrap();
    handle.await.unwrap().unwrap();
    primary.stop().await;
    replica.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn read_write_override_rejected() {
    let primary = MockPg::start(MockBehavior::Ok).await;
    let replica = MockPg::start_replica(MockBehavior::Ok).await;
    let config = Arc::new(ArcSwap::from_pointee(test_config_with_replica(
        &primary.addr(),
        &replica.addr(),
    )));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::new(halephant_core::auth::pgpass::Pgpass::parse("")),
    ));
    topology.refresh().await;
    let pools = Arc::new(PoolManager::new(
        Arc::clone(&config),
        Arc::clone(&topology),
        Arc::new(halephant_core::auth::pgpass::Pgpass::parse("")),
    ));

    let (client_tcp, proxy_tcp) = tcp_pair().await;

    // read_only = true: should reject BEGIN READ WRITE.
    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", true);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    let msgs = query_collect(&mut client, "BEGIN READ WRITE").await;
    // Expect an ErrorResponse with SQLSTATE 25006.
    let has_error = msgs.iter().any(|m| {
        if let BackendMessage::ErrorResponse(fields) = m {
            fields
                .fields
                .iter()
                .any(|(k, v)| *k == b'C' && v == "25006")
        } else {
            false
        }
    });
    assert!(has_error, "expected ErrorResponse with SQLSTATE 25006");

    // The proxy should still be alive — send a normal query.
    let msgs = query_collect(&mut client, "SELECT 1").await;
    assert!(
        matches!(
            msgs.last(),
            Some(BackendMessage::ReadyForQuery(TransactionStatus::Idle))
        ),
        "proxy should still be functional after rejected override"
    );

    client.send(FrontendMessage::Terminate).await.unwrap();
    handle.await.unwrap().unwrap();
    primary.stop().await;
    replica.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn begin_read_only_routes_to_replica() {
    let primary = MockPg::start(MockBehavior::Ok).await;
    let replica = MockPg::start_replica(MockBehavior::Ok).await;
    let config = Arc::new(ArcSwap::from_pointee(test_config_with_replica(
        &primary.addr(),
        &replica.addr(),
    )));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::new(halephant_core::auth::pgpass::Pgpass::parse("")),
    ));
    topology.refresh().await;
    let pools = Arc::new(PoolManager::new(
        Arc::clone(&config),
        Arc::clone(&topology),
        Arc::new(halephant_core::auth::pgpass::Pgpass::parse("")),
    ));

    let (client_tcp, proxy_tcp) = tcp_pair().await;

    // read_only = false, but BEGIN READ ONLY should still route to replica.
    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    let primary_before = primary.connections();
    let msgs = query_collect(&mut client, "BEGIN READ ONLY").await;
    assert!(
        matches!(
            msgs.last(),
            Some(BackendMessage::ReadyForQuery(
                TransactionStatus::InTransaction
            ))
        ),
        "expected InTransaction after BEGIN READ ONLY"
    );

    // The BEGIN should have checked out from the replica, not the primary.
    assert_eq!(
        primary.connections(),
        primary_before,
        "BEGIN READ ONLY should not open a new primary connection"
    );
    assert!(
        replica.connections() > 1,
        "BEGIN READ ONLY should have opened a replica connection"
    );

    // COMMIT to release.
    let _ = query_collect(&mut client, "COMMIT").await;

    client.send(FrontendMessage::Terminate).await.unwrap();
    handle.await.unwrap().unwrap();
    primary.stop().await;
    replica.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn session_mode_forward() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let config = Arc::new(ArcSwap::from_pointee(test_config_session(&mock.addr())));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::new(halephant_core::auth::pgpass::Pgpass::parse("")),
    ));
    topology.refresh().await;
    let pools = Arc::new(PoolManager::new(
        Arc::clone(&config),
        Arc::clone(&topology),
        Arc::new(halephant_core::auth::pgpass::Pgpass::parse("")),
    ));

    // Check out a connection for session-mode forwarding.
    let checkout_client = test_client_guard();
    let mut guard = pools
        .checkout(&checkout_client, "testdb", "testuser", false)
        .await
        .unwrap();

    let (client_tcp, proxy_tcp) = tcp_pair().await;
    let mut proxy_client = Framed::new(proxy_tcp, FrontendCodec::post_startup());
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    // Send post-auth startup to the client.
    halephant_core::messages::send_post_auth_startup(&mut proxy_client, guard.conn())
        .await
        .unwrap();

    // Drain the startup messages from the client side.
    loop {
        let msg = client.next().await.unwrap().unwrap();
        if matches!(msg, BackendMessage::ReadyForQuery(_)) {
            break;
        }
    }

    // Run session forwarding in background.
    let pools_for_session = Arc::clone(&pools);
    let handle = tokio::spawn(async move {
        halephant_core::proxy::session::forward(&mut proxy_client, guard.conn(), &pools_for_session)
            .await
    });

    // Send a query through the session.
    let msgs = query_collect(&mut client, "SELECT 1").await;
    assert!(
        msgs.iter()
            .any(|m| matches!(m, BackendMessage::CommandComplete(_))),
        "expected CommandComplete in session mode"
    );

    // Terminate.
    client.send(FrontendMessage::Terminate).await.unwrap();
    handle.await.unwrap().unwrap();
    mock.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn concurrent_checkouts() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let config = Arc::new(ArcSwap::from_pointee(test_config_max(&mock.addr(), 5)));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::new(halephant_core::auth::pgpass::Pgpass::parse("")),
    ));
    topology.refresh().await;
    let pools = Arc::new(PoolManager::new(
        Arc::clone(&config),
        Arc::clone(&topology),
        Arc::new(halephant_core::auth::pgpass::Pgpass::parse("")),
    ));

    // Check out 5 connections concurrently. Each spawned task owns its
    // own ClientGuard so state transitions don't collide.
    let mut handles = Vec::new();
    for _ in 0..5 {
        let pools = Arc::clone(&pools);
        handles.push(tokio::spawn(async move {
            let client = test_client_guard();
            pools.checkout(&client, "testdb", "testuser", false).await
        }));
    }

    let mut guards = Vec::new();
    for h in handles {
        guards.push(h.await.unwrap().unwrap());
    }

    // All 5 should succeed (+ 1 topology probe = 6 total mock connections).
    assert_eq!(mock.connections(), 6);

    // 6th checkout should time out — pool is at max and all five guards
    // are still held.
    let client = test_client_guard();
    let result = pools.checkout(&client, "testdb", "testuser", false).await;
    assert!(result.is_err(), "6th checkout should fail at max=5");
    assert!(
        result.err().unwrap().to_string().contains("timed out"),
        "6th checkout should time out"
    );

    drop(guards);
    mock.stop().await;
}

// ---------------------------------------------------------------------------
// SCRAM-SHA-256 upstream authentication
// ---------------------------------------------------------------------------

/// Build a pool backed by a SCRAM-auth mock, with a pgpass entry for the password.
fn setup_scram_pool(mock: &MockPg, password: &str) -> (Arc<PoolManager>, Arc<ArcSwap<Config>>) {
    let config = Arc::new(ArcSwap::from_pointee(test_config(&mock.addr())));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::new(halephant_core::auth::pgpass::Pgpass::parse("")),
    ));
    seed_primary(&topology, mock.addr());
    let pgpass = Arc::new(halephant_core::auth::pgpass::Pgpass::parse(&format!(
        "*:*:*:*:{password}"
    )));
    let pools = Arc::new(PoolManager::new(
        Arc::clone(&config),
        Arc::clone(&topology),
        pgpass,
    ));
    (pools, config)
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn scram_auth_success() {
    let password = "testpassword";
    let verifier = mock_pg::test_verifier(password);
    let mock = MockPg::start(MockBehavior::ScramAuth(verifier)).await;

    let (pools, _config) = setup_scram_pool(&mock, password);

    // Checkout should succeed — SCRAM exchange completes transparently.
    let client = test_client_guard();
    let guard = pools.checkout(&client, "testdb", "testuser", false).await;
    assert!(
        guard.is_ok(),
        "SCRAM checkout should succeed: {:?}",
        guard.err()
    );

    drop(guard);
    mock.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn scram_auth_wrong_password() {
    let verifier = mock_pg::test_verifier("correct");
    let mock = MockPg::start(MockBehavior::ScramAuth(verifier)).await;

    // Provide the wrong password via pgpass.
    let (pools, _config) = setup_scram_pool(&mock, "wrong");

    let client = test_client_guard();
    let result = pools.checkout(&client, "testdb", "testuser", false).await;
    assert!(
        result.is_err(),
        "SCRAM checkout with wrong password should fail"
    );

    mock.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn scram_auth_no_password() {
    let verifier = mock_pg::test_verifier("password");
    let mock = MockPg::start(MockBehavior::ScramAuth(verifier)).await;

    // Empty pgpass — no password available.
    let config = Arc::new(ArcSwap::from_pointee(test_config(&mock.addr())));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::new(halephant_core::auth::pgpass::Pgpass::parse("")),
    ));
    seed_primary(&topology, mock.addr());
    let pools = Arc::new(PoolManager::new(
        Arc::clone(&config),
        Arc::clone(&topology),
        Arc::new(halephant_core::auth::pgpass::Pgpass::parse("")),
    ));

    let client = test_client_guard();
    let result = pools.checkout(&client, "testdb", "testuser", false).await;
    assert!(result.is_err(), "checkout without password should fail");
    let err = result.err().unwrap().to_string();
    assert!(
        err.contains("pgpass") || err.contains("password"),
        "error should mention missing password: {err}"
    );

    mock.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn scram_auth_query_round_trip() {
    let password = "querypass";
    let verifier = mock_pg::test_verifier(password);
    let mock = MockPg::start(MockBehavior::ScramAuth(verifier)).await;

    let (pools, _config) = setup_scram_pool(&mock, password);

    let (client_tcp, proxy_tcp) = tcp_pair().await;
    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    // Run a query through the SCRAM-authenticated connection.
    let msgs = query_collect(&mut client, "SELECT 1").await;
    assert!(
        msgs.iter()
            .any(|m| matches!(m, BackendMessage::CommandComplete(_))),
        "should get CommandComplete"
    );

    client.send(FrontendMessage::Terminate).await.unwrap();
    handle.await.unwrap().unwrap();
    mock.stop().await;
}

// ---------------------------------------------------------------------------
// Scavenger floor preservation
// ---------------------------------------------------------------------------

/// Total idle connections across every pool entry. Helper for scavenger tests.
fn total_idle(pools: &PoolManager) -> u32 {
    pools.pool_stats().iter().map(|(_, s)| s.idle).sum()
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn scavenger_preserves_min_connections_floor() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let toml = format!(
        r#"
        [cluster.test]
        nodes = ["{}"]
        admin_user = "testuser"

        [cluster.test.pool.testdb]
        idle_timeout = "50ms"
        max_connections = {{ primary = 10 }}

        [cluster.test.pool.testdb.user.testuser]
        min_connections = {{ primary = 3 }}
    "#,
        mock.addr()
    );

    let config = Arc::new(ArcSwap::from_pointee(Config::parse(&toml).unwrap()));
    let pgpass = Arc::new(halephant_core::auth::pgpass::Pgpass::parse(""));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::clone(&pgpass),
    ));
    seed_primary(&topology, mock.addr());
    let pools = Arc::new(PoolManager::new(Arc::clone(&config), topology, pgpass));

    pools.warm_up().await;
    assert_eq!(total_idle(&pools), 3, "warm-up should produce 3 idle");

    // Sleep past idle_timeout — every connection is now eligible for
    // idle-timeout removal, but the floor must keep all 3 alive.
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    pools.scavenge_idle();
    assert_eq!(
        total_idle(&pools),
        3,
        "scavenger must preserve min_connections.primary"
    );

    mock.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn scavenger_releases_excess_above_floor() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    // min = 2, but warmup + a transient burst leaves 5 connections idle.
    let toml = format!(
        r#"
        [cluster.test]
        nodes = ["{}"]
        admin_user = "testuser"

        [cluster.test.pool.testdb]
        idle_timeout = "50ms"
        max_connections = {{ primary = 10 }}

        [cluster.test.pool.testdb.user.testuser]
        min_connections = {{ primary = 2 }}
    "#,
        mock.addr()
    );

    let config = Arc::new(ArcSwap::from_pointee(Config::parse(&toml).unwrap()));
    let pgpass = Arc::new(halephant_core::auth::pgpass::Pgpass::parse(""));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::clone(&pgpass),
    ));
    seed_primary(&topology, mock.addr());
    let pools = Arc::new(PoolManager::new(Arc::clone(&config), topology, pgpass));

    pools.warm_up().await;
    assert_eq!(total_idle(&pools), 2, "warm-up populates the floor");

    // Burst: 3 concurrent checkouts. The first 2 reuse warm-up connections;
    // the 3rd opens a fresh one. After every checkin, all 3 return to idle.
    let client = test_client_guard();
    let mut guards = Vec::new();
    for _ in 0..3 {
        guards.push(
            pools
                .checkout(&client, "testdb", "testuser", false)
                .await
                .unwrap(),
        );
    }
    for guard in guards {
        guard.checkin();
    }

    // Wait for the background reset+checkin to drop the burst connections
    // back into the idle queue.
    let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2);
    while total_idle(&pools) < 3 {
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        assert!(
            tokio::time::Instant::now() < deadline,
            "burst connections never returned to idle: idle={}",
            total_idle(&pools)
        );
    }

    // Sleep past idle_timeout. Scavenger should drop the excess (1) but
    // keep the 2-connection floor intact.
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    pools.scavenge_idle();
    assert_eq!(
        total_idle(&pools),
        2,
        "scavenger should release excess down to the floor",
    );

    mock.stop().await;
}

// ---------------------------------------------------------------------------
// Per-node min/max with multiple replicas
// ---------------------------------------------------------------------------

/// Seed the `test` cluster with one primary and multiple replicas. Used by
/// the per-node semantic tests so warm-up sees the full topology without
/// running the real probe (which would need each mock to handle the role
/// check query).
fn seed_primary_with_replicas(
    topology: &TopologyManager,
    primary_addr: String,
    replica_addrs: Vec<String>,
) {
    topology.set(
        "test",
        ClusterTopology {
            primary: Some(primary_addr),
            replicas: replica_addrs,
            unreachable: Vec::new(),
        },
    );
}

/// Total idle connections at a specific node across all (db, user) pools.
fn idle_at_node(pools: &PoolManager, node: &str) -> u32 {
    pools
        .pool_stats()
        .iter()
        .filter(|(k, _)| k.node == node)
        .map(|(_, s)| s.idle)
        .sum()
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn warmup_per_node_min_with_two_replicas() {
    // min_connections.replica = 3 means 3 PER replica node, not 3
    // round-robined across replicas. With 2 replicas, expect 6 idle in
    // total (3+3), not 3.
    let primary = MockPg::start(MockBehavior::Ok).await;
    let replica_a = MockPg::start_replica(MockBehavior::Ok).await;
    let replica_b = MockPg::start_replica(MockBehavior::Ok).await;
    let toml = format!(
        r#"
        [cluster.test]
        nodes = ["{}", "{}", "{}"]
        admin_user = "testuser"

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 10, replica = 10 }}

        [cluster.test.pool.testdb.user.testuser]
        min_connections = {{ primary = 0, replica = 3 }}
    "#,
        primary.addr(),
        replica_a.addr(),
        replica_b.addr(),
    );

    let config = Arc::new(ArcSwap::from_pointee(Config::parse(&toml).unwrap()));
    let pgpass = Arc::new(halephant_core::auth::pgpass::Pgpass::parse(""));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::clone(&pgpass),
    ));
    seed_primary_with_replicas(
        &topology,
        primary.addr(),
        vec![replica_a.addr(), replica_b.addr()],
    );
    let pools = Arc::new(PoolManager::new(Arc::clone(&config), topology, pgpass));

    pools.warm_up().await;

    assert_eq!(
        total_idle(&pools),
        6,
        "warm-up should produce 3 per replica = 6 total"
    );
    assert_eq!(idle_at_node(&pools, &replica_a.addr()), 3);
    assert_eq!(idle_at_node(&pools, &replica_b.addr()), 3);

    primary.stop().await;
    replica_a.stop().await;
    replica_b.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn scavenger_preserves_per_replica_floor() {
    let primary = MockPg::start(MockBehavior::Ok).await;
    let replica_a = MockPg::start_replica(MockBehavior::Ok).await;
    let replica_b = MockPg::start_replica(MockBehavior::Ok).await;
    let toml = format!(
        r#"
        [cluster.test]
        nodes = ["{}", "{}", "{}"]
        admin_user = "testuser"

        [cluster.test.pool.testdb]
        idle_timeout = "50ms"
        max_connections = {{ primary = 10, replica = 10 }}

        [cluster.test.pool.testdb.user.testuser]
        min_connections = {{ primary = 0, replica = 2 }}
    "#,
        primary.addr(),
        replica_a.addr(),
        replica_b.addr(),
    );

    let config = Arc::new(ArcSwap::from_pointee(Config::parse(&toml).unwrap()));
    let pgpass = Arc::new(halephant_core::auth::pgpass::Pgpass::parse(""));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::clone(&pgpass),
    ));
    seed_primary_with_replicas(
        &topology,
        primary.addr(),
        vec![replica_a.addr(), replica_b.addr()],
    );
    let pools = Arc::new(PoolManager::new(Arc::clone(&config), topology, pgpass));

    pools.warm_up().await;
    assert_eq!(
        total_idle(&pools),
        4,
        "warm-up should produce 2 per replica"
    );
    assert_eq!(idle_at_node(&pools, &replica_a.addr()), 2);
    assert_eq!(idle_at_node(&pools, &replica_b.addr()), 2);

    // Sleep past idle_timeout. The scavenger must keep the 2-connection
    // floor on each replica intact, not drop one or both replicas to zero.
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    pools.scavenge_idle();
    assert_eq!(
        total_idle(&pools),
        4,
        "scavenger must preserve the floor on every replica"
    );
    assert_eq!(idle_at_node(&pools, &replica_a.addr()), 2);
    assert_eq!(idle_at_node(&pools, &replica_b.addr()), 2);

    primary.stop().await;
    replica_a.stop().await;
    replica_b.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn read_only_falls_back_to_primary_when_replicas_full() {
    // max_connections.replica = 2 means 2 PER replica node. With 2
    // replicas, total replica capacity is 4. The 5th read-only
    // checkout falls back to the primary instead of timing out.
    let primary = MockPg::start(MockBehavior::Ok).await;
    let replica_a = MockPg::start_replica(MockBehavior::Ok).await;
    let replica_b = MockPg::start_replica(MockBehavior::Ok).await;
    let toml = format!(
        r#"
        [server]
        checkout_timeout = "{TEST_CHECKOUT_TIMEOUT}"

        [cluster.test]
        nodes = ["{}", "{}", "{}"]
        admin_user = "testuser"

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 10, replica = 2 }}

        [cluster.test.pool.testdb.user.testuser]
    "#,
        primary.addr(),
        replica_a.addr(),
        replica_b.addr(),
    );

    let config = Arc::new(ArcSwap::from_pointee(Config::parse(&toml).unwrap()));
    let pgpass = Arc::new(halephant_core::auth::pgpass::Pgpass::parse(""));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::clone(&pgpass),
    ));
    seed_primary_with_replicas(
        &topology,
        primary.addr(),
        vec![replica_a.addr(), replica_b.addr()],
    );
    let pools = Arc::new(PoolManager::new(Arc::clone(&config), topology, pgpass));

    let client = test_client_guard();

    // Four read-only checkouts fill both replicas (2 each).
    let mut guards = Vec::new();
    for _ in 0..4 {
        let guard = pools
            .checkout(&client, "testdb", "testuser", true)
            .await
            .expect("first 4 read-only checkouts should succeed");
        guards.push(guard);
    }

    // 5th read-only checkout falls back to the primary.
    let guard5 = pools
        .checkout(&client, "testdb", "testuser", true)
        .await
        .expect("5th read-only checkout should fall back to primary");
    assert_eq!(
        guard5.node(),
        primary.addr(),
        "fallback should route to the primary"
    );

    drop(guards);
    drop(guard5);
    primary.stop().await;
    replica_a.stop().await;
    replica_b.stop().await;
}

// ---------------------------------------------------------------------------
// Wait-queue semantics
// ---------------------------------------------------------------------------

/// A waiter queued on an exhausted pool is woken when an active
/// connection is returned via `checkin`, and the returning connection
/// is handed to the waiter instead of staying idle.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn queue_wakes_waiter_on_checkin() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    // Long checkout_timeout so the test blocks on wakeup, not timeout.
    let toml = format!(
        r#"
        [server]
        checkout_timeout = "5s"

        [cluster.test]
        nodes = ["{}"]
        admin_user = "testuser"

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 1 }}

        [cluster.test.pool.testdb.user.testuser]
    "#,
        mock.addr()
    );
    let config = Arc::new(ArcSwap::from_pointee(Config::parse(&toml).unwrap()));
    let pgpass = Arc::new(halephant_core::auth::pgpass::Pgpass::parse(""));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::clone(&pgpass),
    ));
    seed_primary(&topology, mock.addr());
    let pools = Arc::new(PoolManager::new(Arc::clone(&config), topology, pgpass));

    // Checkout 1 holds the only slot.
    let client1 = test_client_guard();
    let guard1 = pools
        .checkout(&client1, "testdb", "testuser", false)
        .await
        .expect("first checkout should succeed");

    // Checkout 2 enqueues in a background task and blocks.
    let pools2 = Arc::clone(&pools);
    let waiter = tokio::spawn(async move {
        let client2 = test_client_guard();
        pools2.checkout(&client2, "testdb", "testuser", false).await
    });

    // Give the waiter enough time to enqueue.
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;

    // Return guard1 — this should wake the waiter.
    guard1.checkin();

    // Waiter should resolve successfully within a reasonable time.
    let guard2 = tokio::time::timeout(std::time::Duration::from_secs(2), waiter)
        .await
        .expect("waiter did not wake within 2s")
        .expect("waiter task panicked")
        .expect("waiter checkout should succeed");

    drop(guard2);
    mock.stop().await;
}

/// FIFO: when a slot frees, the waiter who enqueued first gets woken.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn queue_is_fifo() {
    use std::sync::atomic::{AtomicU32, Ordering};

    let mock = MockPg::start(MockBehavior::Ok).await;
    let toml = format!(
        r#"
        [server]
        checkout_timeout = "5s"

        [cluster.test]
        nodes = ["{}"]
        admin_user = "testuser"

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 1 }}

        [cluster.test.pool.testdb.user.testuser]
    "#,
        mock.addr()
    );
    let config = Arc::new(ArcSwap::from_pointee(Config::parse(&toml).unwrap()));
    let pgpass = Arc::new(halephant_core::auth::pgpass::Pgpass::parse(""));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::clone(&pgpass),
    ));
    seed_primary(&topology, mock.addr());
    let pools = Arc::new(PoolManager::new(Arc::clone(&config), topology, pgpass));

    // Initial slot holder.
    let client0 = test_client_guard();
    let guard0 = pools
        .checkout(&client0, "testdb", "testuser", false)
        .await
        .unwrap();

    let order = Arc::new(AtomicU32::new(0));

    // Helper: synchronously wait until the total wait-queue depth
    // reaches `target`. This replaces fixed-duration sleeps so the
    // test's ordering guarantees don't depend on CI scheduler jitter.
    let wait_for_depth = |target: u32| {
        let pools = Arc::clone(&pools);
        async move {
            let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2);
            loop {
                let depth: u32 = pools.queue_stats().iter().map(|q| q.depth).sum();
                if depth >= target {
                    return;
                }
                assert!(
                    tokio::time::Instant::now() < deadline,
                    "wait queue never reached depth {target}"
                );
                tokio::time::sleep(std::time::Duration::from_millis(5)).await;
            }
        }
    };

    let waiter_a = {
        let pools = Arc::clone(&pools);
        let order = Arc::clone(&order);
        tokio::spawn(async move {
            let client = test_client_guard();
            let guard = pools
                .checkout(&client, "testdb", "testuser", false)
                .await
                .unwrap();
            let woke_at = order.fetch_add(1, Ordering::SeqCst);
            (woke_at, guard)
        })
    };
    // Ensure A has fully enqueued before spawning B so the FIFO order
    // is deterministic — without this, a slow-to-schedule A could
    // land after B.
    wait_for_depth(1).await;

    let waiter_b = {
        let pools = Arc::clone(&pools);
        let order = Arc::clone(&order);
        tokio::spawn(async move {
            let client = test_client_guard();
            let guard = pools
                .checkout(&client, "testdb", "testuser", false)
                .await
                .unwrap();
            let woke_at = order.fetch_add(1, Ordering::SeqCst);
            (woke_at, guard)
        })
    };
    // Both waiters now enqueued.
    wait_for_depth(2).await;

    // Release the initial slot. Waiter A should wake first.
    guard0.checkin();
    let (a_order, guard_a) = waiter_a.await.unwrap();
    assert_eq!(a_order, 0, "waiter A (enqueued first) should wake first");

    // Release A's slot. Waiter B should wake next.
    guard_a.checkin();
    let (b_order, guard_b) = waiter_b.await.unwrap();
    assert_eq!(b_order, 1, "waiter B (enqueued second) should wake second");

    drop(guard_b);
    mock.stop().await;
}

/// A checkout that times out while queued returns a classified
/// `checkout_timeout` error and leaves the pool state consistent.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn queue_timeout() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let toml = format!(
        r#"
        [server]
        checkout_timeout = "50ms"

        [cluster.test]
        nodes = ["{}"]
        admin_user = "testuser"

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 1 }}

        [cluster.test.pool.testdb.user.testuser]
    "#,
        mock.addr()
    );
    let config = Arc::new(ArcSwap::from_pointee(Config::parse(&toml).unwrap()));
    let pgpass = Arc::new(halephant_core::auth::pgpass::Pgpass::parse(""));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::clone(&pgpass),
    ));
    seed_primary(&topology, mock.addr());
    let pools = Arc::new(PoolManager::new(Arc::clone(&config), topology, pgpass));

    let client = test_client_guard();

    // Take the only slot.
    let guard = pools
        .checkout(&client, "testdb", "testuser", false)
        .await
        .unwrap();

    // Second checkout: should enqueue, hit the 50ms timeout, and fail.
    let start = std::time::Instant::now();
    let result = pools.checkout(&client, "testdb", "testuser", false).await;
    let elapsed = start.elapsed();

    assert!(result.is_err(), "second checkout should time out");
    assert!(
        elapsed >= std::time::Duration::from_millis(50),
        "should have waited at least checkout_timeout before failing: {elapsed:?}"
    );
    assert!(
        elapsed < std::time::Duration::from_millis(500),
        "should have failed quickly after the timeout elapsed: {elapsed:?}"
    );
    assert!(result.err().unwrap().to_string().contains("timed out"));

    drop(guard);
    mock.stop().await;
}

/// When a waiter's receiver is dropped (cancelled), `wake_one_for_node`
/// skips it and wakes the next one. Confirmed by observing that a
/// cancelled waiter does not "steal" wakeups from later waiters.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn queue_skips_cancelled_waiter() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let toml = format!(
        r#"
        [server]
        checkout_timeout = "5s"

        [cluster.test]
        nodes = ["{}"]
        admin_user = "testuser"

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 1 }}

        [cluster.test.pool.testdb.user.testuser]
    "#,
        mock.addr()
    );
    let config = Arc::new(ArcSwap::from_pointee(Config::parse(&toml).unwrap()));
    let pgpass = Arc::new(halephant_core::auth::pgpass::Pgpass::parse(""));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::clone(&pgpass),
    ));
    seed_primary(&topology, mock.addr());
    let pools = Arc::new(PoolManager::new(Arc::clone(&config), topology, pgpass));

    let client0 = test_client_guard();
    let guard0 = pools
        .checkout(&client0, "testdb", "testuser", false)
        .await
        .unwrap();

    // Enqueue a waiter that we'll cancel.
    let pools_cancelled = Arc::clone(&pools);
    let cancelled = tokio::spawn(async move {
        let client = test_client_guard();
        pools_cancelled
            .checkout(&client, "testdb", "testuser", false)
            .await
    });
    tokio::time::sleep(std::time::Duration::from_millis(20)).await;

    // Enqueue a real waiter behind the cancelled one.
    let pools_real = Arc::clone(&pools);
    let real = tokio::spawn(async move {
        let client = test_client_guard();
        pools_real
            .checkout(&client, "testdb", "testuser", false)
            .await
    });
    tokio::time::sleep(std::time::Duration::from_millis(20)).await;

    // Cancel the first waiter by aborting its task. This drops the
    // receiver side of its oneshot.
    cancelled.abort();
    let _ = cancelled.await; // reap cancelled task

    // Release the slot. wake_one_for_node should skip the cancelled
    // sender and wake the real waiter.
    guard0.checkin();

    let guard = tokio::time::timeout(std::time::Duration::from_secs(2), real)
        .await
        .expect("real waiter did not wake within 2s")
        .expect("real waiter task panicked")
        .expect("real waiter checkout should succeed");

    drop(guard);
    mock.stop().await;
}

/// A replica queue serves waiters regardless of which replica returns
/// an idle connection first. Two waiters enqueue when both replicas are
/// full; freeing one replica wakes one waiter, freeing the other wakes
/// the second.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn queue_replica_is_shared() {
    let primary = MockPg::start(MockBehavior::Ok).await;
    let replica_a = MockPg::start_replica(MockBehavior::Ok).await;
    let replica_b = MockPg::start_replica(MockBehavior::Ok).await;
    let toml = format!(
        r#"
        [server]
        checkout_timeout = "5s"

        [cluster.test]
        nodes = ["{}", "{}", "{}"]
        admin_user = "testuser"

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 10, replica = 1 }}

        [cluster.test.pool.testdb.user.testuser]
    "#,
        primary.addr(),
        replica_a.addr(),
        replica_b.addr(),
    );
    let config = Arc::new(ArcSwap::from_pointee(Config::parse(&toml).unwrap()));
    let pgpass = Arc::new(halephant_core::auth::pgpass::Pgpass::parse(""));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::clone(&pgpass),
    ));
    seed_primary_with_replicas(
        &topology,
        primary.addr(),
        vec![replica_a.addr(), replica_b.addr()],
    );
    let pools = Arc::new(PoolManager::new(Arc::clone(&config), topology, pgpass));

    // Fill both replica slots. Round-robin distributes to A then B.
    let client = test_client_guard();
    let guard_a = pools
        .checkout(&client, "testdb", "testuser", true)
        .await
        .unwrap();
    let guard_b = pools
        .checkout(&client, "testdb", "testuser", true)
        .await
        .unwrap();

    // Two waiters, each on the shared Replica queue.
    let pools1 = Arc::clone(&pools);
    let waiter1 = tokio::spawn(async move {
        let c = test_client_guard();
        pools1.checkout(&c, "testdb", "testuser", true).await
    });
    tokio::time::sleep(std::time::Duration::from_millis(20)).await;
    let pools2 = Arc::clone(&pools);
    let waiter2 = tokio::spawn(async move {
        let c = test_client_guard();
        pools2.checkout(&c, "testdb", "testuser", true).await
    });
    tokio::time::sleep(std::time::Duration::from_millis(20)).await;

    // Release replica A. Waiter 1 should wake.
    guard_a.checkin();
    let g1 = tokio::time::timeout(std::time::Duration::from_secs(2), waiter1)
        .await
        .expect("waiter1 did not wake within 2s")
        .unwrap()
        .expect("waiter1 checkout should succeed");

    // Release replica B. Waiter 2 should wake.
    guard_b.checkin();
    let g2 = tokio::time::timeout(std::time::Duration::from_secs(2), waiter2)
        .await
        .expect("waiter2 did not wake within 2s")
        .unwrap()
        .expect("waiter2 checkout should succeed");

    drop(g1);
    drop(g2);
    primary.stop().await;
    replica_a.stop().await;
    replica_b.stop().await;
}

/// `pools.shutdown()` wakes every queued waiter with a classified
/// `"shutting down"` error instead of making them sit until their
/// individual `checkout_timeout` expires.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shutdown_wakes_queued_waiters() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    // Long checkout_timeout so the test fails clearly if shutdown
    // doesn't wake promptly.
    let toml = format!(
        r#"
        [server]
        checkout_timeout = "10s"

        [cluster.test]
        nodes = ["{}"]
        admin_user = "testuser"

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 1 }}

        [cluster.test.pool.testdb.user.testuser]
    "#,
        mock.addr()
    );
    let config = Arc::new(ArcSwap::from_pointee(Config::parse(&toml).unwrap()));
    let pgpass = Arc::new(halephant_core::auth::pgpass::Pgpass::parse(""));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::clone(&pgpass),
    ));
    seed_primary(&topology, mock.addr());
    let pools = Arc::new(PoolManager::new(Arc::clone(&config), topology, pgpass));

    // Take the only slot.
    let client0 = test_client_guard();
    let _guard0 = pools
        .checkout(&client0, "testdb", "testuser", false)
        .await
        .unwrap();

    // Spawn a waiter and give it time to enqueue.
    let pools_waiter = Arc::clone(&pools);
    let waiter = tokio::spawn(async move {
        let client = test_client_guard();
        pools_waiter
            .checkout(&client, "testdb", "testuser", false)
            .await
    });
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;

    // Shut down the pool. The waiter should wake immediately with a
    // shutting-down error, not wait 10 seconds for `checkout_timeout`.
    let start = std::time::Instant::now();
    pools.shutdown();
    let result = tokio::time::timeout(std::time::Duration::from_secs(2), waiter)
        .await
        .expect("waiter did not wake within 2s of shutdown")
        .expect("waiter task panicked");
    let elapsed = start.elapsed();

    assert!(
        elapsed < std::time::Duration::from_millis(500),
        "shutdown should wake waiters quickly, took: {elapsed:?}"
    );
    let err = result
        .err()
        .expect("waiter should fail with shutting-down error");
    assert!(
        err.to_string().contains("shutting down"),
        "error should mention shutdown, got: {err}"
    );
    assert!(
        matches!(
            err.downcast_ref::<CheckoutError>(),
            Some(CheckoutError::ShuttingDown)
        ),
        "shutdown should downcast to CheckoutError::ShuttingDown"
    );
    assert_eq!(classify_checkout_error(&err), "shutting_down");

    mock.stop().await;
}

/// A client's registry entry shows `state == Waiting` and the correct
/// `waiting_for` target while it's blocked on a checkout, and both
/// reset to `Idle` / `None` on wakeup.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn waiting_for_is_populated_during_wait() {
    use halephant_core::clients::{ClientRegistry, ClientState, WaitRole};

    let mock = MockPg::start(MockBehavior::Ok).await;
    let toml = format!(
        r#"
        [server]
        checkout_timeout = "5s"

        [cluster.test]
        nodes = ["{}"]
        admin_user = "testuser"

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 1 }}

        [cluster.test.pool.testdb.user.testuser]
    "#,
        mock.addr()
    );
    let config = Arc::new(ArcSwap::from_pointee(Config::parse(&toml).unwrap()));
    let pgpass = Arc::new(halephant_core::auth::pgpass::Pgpass::parse(""));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::clone(&pgpass),
    ));
    seed_primary(&topology, mock.addr());
    let pools = Arc::new(PoolManager::new(Arc::clone(&config), topology, pgpass));

    // Hold the only slot.
    let client0 = test_client_guard();
    let guard0 = pools
        .checkout(&client0, "testdb", "testuser", false)
        .await
        .unwrap();

    // Spawn the waiter with its own registry so the test can observe
    // its state via `snapshot()`. The spawned task hands back the
    // ClientGuard alongside the result so the entry lives long enough
    // for the post-wakeup assertions.
    let registry = Arc::new(ClientRegistry::new());
    let waiter_registry = Arc::clone(&registry);
    let pools_waiter = Arc::clone(&pools);
    let waiter = tokio::spawn(async move {
        let client = waiter_registry.register("127.0.0.1:0".parse().unwrap());
        let result = pools_waiter
            .checkout(&client, "testdb", "testuser", false)
            .await;
        (client, result)
    });

    // Poll the registry until the waiter is actually in Waiting state.
    let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2);
    let snap = loop {
        let snap = registry.snapshot();
        if let Some(entry) = snap.first()
            && entry.state == ClientState::Waiting
        {
            break snap;
        }
        assert!(
            tokio::time::Instant::now() < deadline,
            "waiter never transitioned to Waiting"
        );
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    };
    let entry = &snap[0];
    let target = entry
        .waiting_for
        .as_ref()
        .expect("waiting_for should be populated during wait");
    assert_eq!(target.database, "testdb");
    assert_eq!(target.user, "testuser");
    assert_eq!(target.role, WaitRole::Primary);

    // Release the slot. The waiter should succeed, and after wakeup
    // the registry entry should show state == Idle and
    // waiting_for == None.
    guard0.checkin();
    let (held_client, result) = tokio::time::timeout(std::time::Duration::from_secs(2), waiter)
        .await
        .expect("waiter did not wake")
        .expect("waiter task panicked");
    let guard = result.expect("waiter checkout should succeed");

    let after = registry.snapshot();
    let entry = after
        .iter()
        .find(|e| e.id == held_client.id())
        .expect("entry still present");
    assert_eq!(entry.state, ClientState::Idle);
    assert!(
        entry.waiting_for.is_none(),
        "waiting_for should be cleared after wakeup"
    );

    drop(guard);
    drop(held_client);
    mock.stop().await;
}

/// A per-pool `checkout_timeout` override wins over the server-wide
/// default, so a pool can set a short timeout even when the server
/// default is long.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn per_pool_checkout_timeout_overrides_server_default() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    // Server default 30s; pool override 50ms. The pool override must
    // win — otherwise the test would hang for 30 seconds before
    // failing.
    let toml = format!(
        r#"
        [server]
        checkout_timeout = "30s"

        [cluster.test]
        nodes = ["{}"]
        admin_user = "testuser"

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 1 }}
        checkout_timeout = "50ms"

        [cluster.test.pool.testdb.user.testuser]
    "#,
        mock.addr()
    );
    let config = Arc::new(ArcSwap::from_pointee(Config::parse(&toml).unwrap()));
    let pgpass = Arc::new(halephant_core::auth::pgpass::Pgpass::parse(""));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::clone(&pgpass),
    ));
    seed_primary(&topology, mock.addr());
    let pools = Arc::new(PoolManager::new(Arc::clone(&config), topology, pgpass));

    let client = test_client_guard();

    // Take the only slot.
    let _guard = pools
        .checkout(&client, "testdb", "testuser", false)
        .await
        .unwrap();

    // Second checkout times out using the pool override (50ms), not
    // the server default (30s).
    let start = std::time::Instant::now();
    let result = pools.checkout(&client, "testdb", "testuser", false).await;
    let elapsed = start.elapsed();

    assert!(result.is_err(), "second checkout should time out");
    assert!(
        elapsed < std::time::Duration::from_millis(500),
        "pool override should short-circuit the 30s server default, took: {elapsed:?}"
    );
    assert!(result.err().unwrap().to_string().contains("timed out"));

    mock.stop().await;
}

// ---------------------------------------------------------------------------
// Checkout failure classification
// ---------------------------------------------------------------------------

/// A checkout that exhausts `checkout_timeout` fails with the typed
/// [`CheckoutError::Timeout`], so the metric classification downcasts
/// instead of substring-matching error prose. The operator-facing
/// Display text stays stable.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn checkout_timeout_error_is_typed() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool_with_config(test_config_max(&mock.addr(), 1), &mock);

    let client = test_client_guard();
    let _guard = pools
        .checkout(&client, "testdb", "testuser", false)
        .await
        .unwrap();

    let err = pools
        .checkout(&client, "testdb", "testuser", false)
        .await
        .err()
        .expect("second checkout should time out at max=1");
    assert!(
        matches!(
            err.downcast_ref::<CheckoutError>(),
            Some(CheckoutError::Timeout { .. })
        ),
        "timeout should downcast to CheckoutError::Timeout, got: {err}"
    );
    assert!(err.to_string().contains("timed out"));
    assert_eq!(classify_checkout_error(&err), "checkout_timeout");

    mock.stop().await;
}

/// An upstream that refuses startup with PostgreSQL's own shutdown
/// error (`57P03` — "the database system is shutting down") is a
/// connect failure, not halephant shutting down. The old substring
/// classification confused the two because the upstream's prose leaks
/// into the anyhow message.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn upstream_shutdown_error_is_a_connect_failure() {
    let mock = MockPg::start(MockBehavior::ErrorOnStartup {
        code: "57P03".into(),
        message: "the database system is shutting down".into(),
    })
    .await;
    let (pools, _config) = setup_pool(&mock);

    let client = test_client_guard();
    let err = pools
        .checkout(&client, "testdb", "testuser", false)
        .await
        .err()
        .expect("checkout against a shutting-down upstream should fail");

    assert!(
        err.to_string().contains("shutting down"),
        "expected the upstream error text to surface, got: {err}"
    );
    assert!(
        err.downcast_ref::<CheckoutError>().is_none(),
        "an upstream connect failure must not be typed as CheckoutError"
    );
    assert_eq!(classify_checkout_error(&err), "connect_failed");

    mock.stop().await;
}

/// An unconfigured user is refused before any upstream connection
/// attempt — the mock never sees a connect. The pre-fix fallback
/// connected as the client-facing name instead.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn unconfigured_user_never_reaches_upstream() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool(&mock);

    let client = test_client_guard();
    let err = pools
        .checkout(&client, "testdb", "ghost", false)
        .await
        .err()
        .expect("unconfigured user should be refused");
    assert!(
        matches!(
            err.downcast_ref::<CheckoutError>(),
            Some(CheckoutError::UserNotConfigured { .. })
        ),
        "refusal should downcast to CheckoutError::UserNotConfigured, got: {err}"
    );
    assert_eq!(
        mock.connections(),
        0,
        "refusal must not open an upstream connection"
    );

    mock.stop().await;
}

// ---------------------------------------------------------------------------
// Pool identity — checkout and refill share one connect identity
// ---------------------------------------------------------------------------

fn test_config_alias(node_addr: &str, min_primary: u32) -> Config {
    Config::parse(&format!(
        r#"
        [server]
        checkout_timeout = "{TEST_CHECKOUT_TIMEOUT}"

        [cluster.test]
        nodes = ["{node_addr}"]

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 10 }}

        [cluster.test.pool.testdb.user.app]
        alias = "app_rw"
        min_connections = {{ primary = {min_primary} }}
    "#
    ))
    .unwrap()
}

/// Checkout resolves the upstream identity through the shared
/// `ConnectSpec` resolver: a configured alias connects as the aliased
/// role, not the client-facing name.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn checkout_connects_as_configured_alias() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool_with_config(test_config_alias(&mock.addr(), 0), &mock);

    let client = test_client_guard();
    let guard = pools
        .checkout(&client, "testdb", "app", false)
        .await
        .expect("checkout for the aliased user should succeed");
    assert_eq!(mock.received_startup_users(), vec!["app_rw".to_owned()]);

    drop(guard);
    mock.stop().await;
}

/// Warm-up refill resolves the same upstream identity as checkout —
/// both consume one `ConnectSpec`, so a pool can never mix connections
/// authenticated as different roles.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn warm_up_connects_as_configured_alias() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool_with_config(test_config_alias(&mock.addr(), 2), &mock);

    pools.warm_up().await;

    assert_eq!(
        mock.received_startup_users(),
        vec!["app_rw".to_owned(), "app_rw".to_owned()],
        "every warm-up connection should authenticate as the alias"
    );
    mock.stop().await;
}

// ---------------------------------------------------------------------------
// DEALLOCATE interception
// ---------------------------------------------------------------------------

/// `DEALLOCATE my_stmt` must never reach the upstream, because
/// halephant renames every client Parse to a canonical hashed name
/// before forwarding — the server doesn't know `my_stmt`, only
/// `_hp_<hash>`. The transaction layer intercepts the DEALLOCATE,
/// updates its per-client tracking, and synthesises a
/// `CommandComplete("DEALLOCATE")` + `ReadyForQuery(Idle)` response
/// without touching the server.
///
/// This test verifies both halves: the client sees the synthetic
/// success response, and the mock's query log does not contain the
/// DEALLOCATE string — only the `SELECT` that preceded it.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn deallocate_named_is_intercepted() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool(&mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    // Seed the client-side prepared-statement mapping by sending a
    // Parse/Bind/Execute/Sync batch. The actual content of the Parse
    // doesn't matter — we just need `my_stmt` to exist in
    // ClientPrepared so the DEALLOCATE has something to release.
    client
        .send(FrontendMessage::Parse(
            halephant_core::proto::frontend::Parse {
                name: "my_stmt".into(),
                query: "SELECT 1".into(),
                param_types: vec![],
            },
        ))
        .await
        .unwrap();
    client
        .send(FrontendMessage::Bind(
            halephant_core::proto::frontend::Bind {
                portal: String::new(),
                statement: "my_stmt".into(),
                param_formats: vec![],
                params: vec![],
                result_formats: vec![],
            },
        ))
        .await
        .unwrap();
    client
        .send(FrontendMessage::Execute(
            halephant_core::proto::frontend::Execute {
                portal: String::new(),
                max_rows: 0,
            },
        ))
        .await
        .unwrap();
    client.send(FrontendMessage::Sync).await.unwrap();

    // Drain the extended-protocol responses up to ReadyForQuery so
    // the connection is idle before we issue the DEALLOCATE query.
    loop {
        let msg = client.next().await.unwrap().unwrap();
        if matches!(msg, BackendMessage::ReadyForQuery(_)) {
            break;
        }
    }

    // Now send the DEALLOCATE. If the intercept works, halephant
    // synthesises the response without forwarding. If it doesn't,
    // halephant would forward `DEALLOCATE my_stmt` verbatim — on a
    // real server this would fail with "prepared statement does not
    // exist" because the server only knows `_hp_<hash>`.
    let msgs = query_collect(&mut client, "DEALLOCATE my_stmt").await;
    assert!(
        msgs.iter().any(|m| matches!(
            m,
            BackendMessage::CommandComplete(tag) if tag == "DEALLOCATE"
        )),
        "expected CommandComplete(\"DEALLOCATE\") in response: {msgs:?}"
    );
    assert!(
        matches!(
            msgs.last(),
            Some(BackendMessage::ReadyForQuery(TransactionStatus::Idle))
        ),
        "expected ReadyForQuery(Idle) as final message: {msgs:?}"
    );

    // The critical assertion: the mock's simple-query log must NOT
    // contain the DEALLOCATE. If it does, the intercept isn't
    // actually absorbing the message.
    let received = mock.received_queries();
    assert!(
        !received
            .iter()
            .any(|q| q.to_ascii_uppercase().contains("DEALLOCATE")),
        "mock should not have received any DEALLOCATE query, got: {received:?}"
    );

    drop(client);
    let _ = handle.await;
    mock.stop().await;
}

/// Same as above for `DEALLOCATE ALL`. Verifies the wildcard path
/// through `ClientPrepared::release_all`.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn deallocate_all_is_intercepted() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool(&mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    // Register two prepared statements so `release_all` has
    // something to drain.
    for name in ["stmt_a", "stmt_b"] {
        client
            .send(FrontendMessage::Parse(
                halephant_core::proto::frontend::Parse {
                    name: name.into(),
                    query: format!("SELECT {name}"),
                    param_types: vec![],
                },
            ))
            .await
            .unwrap();
        client
            .send(FrontendMessage::Bind(
                halephant_core::proto::frontend::Bind {
                    portal: String::new(),
                    statement: name.into(),
                    param_formats: vec![],
                    params: vec![],
                    result_formats: vec![],
                },
            ))
            .await
            .unwrap();
        client
            .send(FrontendMessage::Execute(
                halephant_core::proto::frontend::Execute {
                    portal: String::new(),
                    max_rows: 0,
                },
            ))
            .await
            .unwrap();
        client.send(FrontendMessage::Sync).await.unwrap();

        loop {
            let msg = client.next().await.unwrap().unwrap();
            if matches!(msg, BackendMessage::ReadyForQuery(_)) {
                break;
            }
        }
    }

    // DEALLOCATE ALL — absorbed by the intercept.
    let msgs = query_collect(&mut client, "DEALLOCATE ALL").await;
    assert!(
        msgs.iter().any(|m| matches!(
            m,
            BackendMessage::CommandComplete(tag) if tag == "DEALLOCATE"
        )),
        "expected CommandComplete(\"DEALLOCATE\") in response: {msgs:?}"
    );

    let received = mock.received_queries();
    assert!(
        !received
            .iter()
            .any(|q| q.to_ascii_uppercase().contains("DEALLOCATE")),
        "mock should not have received any DEALLOCATE query, got: {received:?}"
    );

    drop(client);
    let _ = handle.await;
    mock.stop().await;
}

// ---------------------------------------------------------------------------
// Prepared statement lifecycle — LRU eviction, unnamed reuse, disconnect
// ---------------------------------------------------------------------------

/// Helper: send Parse + Bind + Execute + Sync and drain until ReadyForQuery.
async fn extended_query(client: &mut Framed<TcpStream, BackendCodec>, name: &str, query: &str) {
    client
        .send(FrontendMessage::Parse(
            halephant_core::proto::frontend::Parse {
                name: name.into(),
                query: query.into(),
                param_types: vec![],
            },
        ))
        .await
        .unwrap();
    client
        .send(FrontendMessage::Bind(
            halephant_core::proto::frontend::Bind {
                portal: String::new(),
                statement: name.into(),
                param_formats: vec![],
                params: vec![],
                result_formats: vec![],
            },
        ))
        .await
        .unwrap();
    client
        .send(FrontendMessage::Execute(
            halephant_core::proto::frontend::Execute {
                portal: String::new(),
                max_rows: 0,
            },
        ))
        .await
        .unwrap();
    client.send(FrontendMessage::Sync).await.unwrap();

    loop {
        let msg = client.next().await.unwrap().unwrap();
        if matches!(msg, BackendMessage::ReadyForQuery(_)) {
            break;
        }
    }
}

/// When the per-server LRU cache is full, the oldest prepared statement
/// is evicted with a Close before the new one is prepared.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn server_lru_eviction_sends_close() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let cfg = Config::parse(&format!(
        r#"
        [server]
        checkout_timeout = "{TEST_CHECKOUT_TIMEOUT}"
        max_prepared_statements = 2

        [cluster.test]
        nodes = ["{}"]

        [cluster.test.pool.testdb.user.testuser]
    "#,
        mock.addr()
    ))
    .unwrap();
    let (pools, _config) = setup_pool_with_config(cfg, &mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    // Wrap all 3 Parses in a single explicit transaction so they hit
    // the same server connection. Without BEGIN, each Parse is its
    // own transaction and the pool may hand out a fresh connection
    // (while the previous is still resetting), preventing the LRU
    // from filling.
    query_collect(&mut client, "BEGIN").await;
    extended_query(&mut client, "s1", "SELECT 1").await;
    extended_query(&mut client, "s2", "SELECT 2").await;
    extended_query(&mut client, "s3", "SELECT 3").await;
    query_collect(&mut client, "COMMIT").await;

    let closes = mock.received_closes();
    assert!(
        !closes.is_empty(),
        "expected at least one Close for LRU eviction, got none"
    );

    // All 3 canonical names should have been Parsed on the server.
    let parses = mock.received_parses();
    assert_eq!(
        parses.len(),
        3,
        "expected 3 Parse messages on server, got {parses:?}"
    );

    drop(client);
    let _ = handle.await;
    mock.stop().await;
}

/// An unnamed Parse("") followed by Bind("") in a later transaction
/// (different server checkout) re-prepares the statement transparently.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn unnamed_reuse_across_transactions() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool(&mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    // Transaction 1: Parse("") + Bind + Execute + Sync.
    extended_query(&mut client, "", "SELECT 1").await;

    // Transaction 2: only Bind("") + Execute + Sync (no new Parse).
    // This is the lib/pq pattern that breaks without unnamed support.
    client
        .send(FrontendMessage::Bind(
            halephant_core::proto::frontend::Bind {
                portal: String::new(),
                statement: String::new(),
                param_formats: vec![],
                params: vec![],
                result_formats: vec![],
            },
        ))
        .await
        .unwrap();
    client
        .send(FrontendMessage::Execute(
            halephant_core::proto::frontend::Execute {
                portal: String::new(),
                max_rows: 0,
            },
        ))
        .await
        .unwrap();
    client.send(FrontendMessage::Sync).await.unwrap();

    let mut saw_complete = false;
    loop {
        let msg = client.next().await.unwrap().unwrap();
        if matches!(msg, BackendMessage::CommandComplete(_)) {
            saw_complete = true;
        }
        assert!(
            !matches!(msg, BackendMessage::ErrorResponse(_)),
            "Bind on unnamed in new transaction should not fail"
        );
        if matches!(msg, BackendMessage::ReadyForQuery(_)) {
            break;
        }
    }
    assert!(saw_complete, "expected CommandComplete from unnamed reuse");

    drop(client);
    let _ = handle.await;
    mock.stop().await;
}

/// Replacing an unnamed Parse("") with a different query releases the
/// old canonical and the new one is used for subsequent Bind("").
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn unnamed_replacement_releases_old_canonical() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool(&mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    extended_query(&mut client, "", "SELECT 1").await;
    extended_query(&mut client, "", "SELECT 2").await;

    let parses = mock.received_parses();
    assert_eq!(parses.len(), 2, "expected 2 Parse messages: {parses:?}");
    assert_ne!(parses[0], parses[1], "canonical names should differ");

    // Bind("") in a new transaction should use the second canonical.
    client
        .send(FrontendMessage::Bind(
            halephant_core::proto::frontend::Bind {
                portal: String::new(),
                statement: String::new(),
                param_formats: vec![],
                params: vec![],
                result_formats: vec![],
            },
        ))
        .await
        .unwrap();
    client
        .send(FrontendMessage::Execute(
            halephant_core::proto::frontend::Execute {
                portal: String::new(),
                max_rows: 0,
            },
        ))
        .await
        .unwrap();
    client.send(FrontendMessage::Sync).await.unwrap();

    loop {
        let msg = client.next().await.unwrap().unwrap();
        assert!(
            !matches!(msg, BackendMessage::ErrorResponse(_)),
            "Bind on replaced unnamed should succeed"
        );
        if matches!(msg, BackendMessage::ReadyForQuery(_)) {
            break;
        }
    }

    // The re-prepare should use the second canonical, not the first.
    let all_parses = mock.received_parses();
    let last_parse = all_parses.last().unwrap();
    assert_eq!(last_parse, &parses[1]);

    drop(client);
    let _ = handle.await;
    mock.stop().await;
}

/// When a client disconnects, `PreparedGuard::drop` releases all
/// refcounts. With a single client, the store should be empty after.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn client_disconnect_releases_all_prepared() {
    use halephant_core::proxy::prepared::canonical_for_test;

    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool(&mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    extended_query(&mut client, "s1", "SELECT 1").await;
    extended_query(&mut client, "s2", "SELECT 2").await;
    extended_query(&mut client, "", "SELECT 3").await;

    // Store should have entries while the client is alive.
    let c1 = canonical_for_test("SELECT 1", &[]);
    let c2 = canonical_for_test("SELECT 2", &[]);
    let c3 = canonical_for_test("SELECT 3", &[]);
    assert!(pools.has_prepared(&c1), "SELECT 1 should be in store");
    assert!(pools.has_prepared(&c2), "SELECT 2 should be in store");
    assert!(pools.has_prepared(&c3), "SELECT 3 should be in store");

    // Drop the client — triggers PreparedGuard::drop → release_all.
    drop(client);
    let _ = handle.await;

    // All refcounts should be zero — entries removed.
    assert!(!pools.has_prepared(&c1), "SELECT 1 should be released");
    assert!(!pools.has_prepared(&c2), "SELECT 2 should be released");
    assert!(!pools.has_prepared(&c3), "SELECT 3 should be released");

    mock.stop().await;
}

/// Discriminant tag for asserting backend-message ordering without
/// caring about message payloads.
#[derive(Debug, PartialEq, Eq)]
enum Tag {
    Parse,
    Bind,
    Command,
}

/// Two SEPARATE autocommit extended-protocol batches pipelined in one
/// flush (each `Parse`/`Bind`/`Execute`/`Sync`) must each run as their
/// own transaction. The proxy must not read batch 2 onto batch 1's
/// backend and then strand batch 2's responses when batch 1's
/// `ReadyForQuery(Idle)` checks that backend back in.
///
/// This is the shape tokio-postgres produces: after a query it pipelines
/// `Close(statement)`/`Sync` (deallocate) ahead of the next query's
/// `Parse`/.../`Sync`. The mock is deliberately slow so the proxy reads
/// the whole pipelined buffer before any reply arrives, deterministically
/// forcing the read-ahead path that used to hang real drivers.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pipelined_autocommit_batches_each_get_a_transaction() {
    let mock = MockPg::start_slow(MockBehavior::Ok, std::time::Duration::from_millis(20)).await;
    let (pools, _config) = setup_pool(&mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    // Buffer two full batches, then flush them together (pipelined).
    for (name, query) in [("a", "SELECT 1"), ("b", "SELECT 2")] {
        client
            .feed(FrontendMessage::Parse(
                halephant_core::proto::frontend::Parse {
                    name: name.into(),
                    query: query.into(),
                    param_types: vec![],
                },
            ))
            .await
            .unwrap();
        client
            .feed(FrontendMessage::Bind(
                halephant_core::proto::frontend::Bind {
                    portal: String::new(),
                    statement: name.into(),
                    param_formats: vec![],
                    params: vec![],
                    result_formats: vec![],
                },
            ))
            .await
            .unwrap();
        client
            .feed(FrontendMessage::Execute(
                halephant_core::proto::frontend::Execute {
                    portal: String::new(),
                    max_rows: 0,
                },
            ))
            .await
            .unwrap();
        client.feed(FrontendMessage::Sync).await.unwrap();
    }
    SinkExt::flush(&mut client).await.unwrap();

    // On the read-ahead bug, batch 2's responses are stranded and this
    // times out. With one transaction per batch, both ReadyForQuery and
    // both CommandComplete arrive.
    let counted = tokio::time::timeout(std::time::Duration::from_secs(5), async {
        let mut completes = 0;
        let mut readies = 0;
        while readies < 2 {
            match client.next().await {
                Some(Ok(BackendMessage::CommandComplete(_))) => completes += 1,
                Some(Ok(BackendMessage::ReadyForQuery(_))) => readies += 1,
                Some(Ok(BackendMessage::ErrorResponse(e))) => {
                    panic!("unexpected error in pipelined batch: {e:?}")
                }
                Some(Ok(_)) => {}
                _ => break,
            }
        }
        (completes, readies)
    })
    .await
    .expect("timed out — batch 2's responses were stranded (read-ahead across Sync)");

    assert_eq!(
        counted.1, 2,
        "expected one ReadyForQuery per pipelined batch"
    );
    assert_eq!(
        counted.0, 2,
        "expected one CommandComplete per pipelined batch"
    );

    client.send(FrontendMessage::Terminate).await.unwrap();
    let _ = handle.await;
    mock.stop().await;
}

/// A client that pipelines two extended-protocol statements in a single
/// implicit transaction — `Parse`/`Bind`/`Execute` twice, then one
/// trailing `Sync` — must receive every response for BOTH statements, in
/// protocol order.
///
/// This is the shape that drivers such as sqlx emit when they batch
/// statements. The transaction-mode proxy used to re-prepare statements
/// by injecting an out-of-band `Sync` and draining the server up to
/// `ReadyForQuery`, which silently swallowed the earlier statement's
/// `BindComplete`/`CommandComplete` and reordered `ParseComplete`. The
/// client then saw a desynchronized stream. This test pins the correct
/// behavior so the regression cannot return.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pipelined_statements_preserve_all_responses() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool(&mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    // Feed buffers without flushing; the trailing Sync flushes the whole
    // batch at once so the proxy reads a genuinely pipelined stream.
    for (name, query) in [("s1", "SELECT 1"), ("s2", "SELECT 2")] {
        client
            .feed(FrontendMessage::Parse(
                halephant_core::proto::frontend::Parse {
                    name: name.into(),
                    query: query.into(),
                    param_types: vec![],
                },
            ))
            .await
            .unwrap();
        client
            .feed(FrontendMessage::Bind(
                halephant_core::proto::frontend::Bind {
                    portal: String::new(),
                    statement: name.into(),
                    param_formats: vec![],
                    params: vec![],
                    result_formats: vec![],
                },
            ))
            .await
            .unwrap();
        client
            .feed(FrontendMessage::Execute(
                halephant_core::proto::frontend::Execute {
                    portal: String::new(),
                    max_rows: 0,
                },
            ))
            .await
            .unwrap();
    }
    client.send(FrontendMessage::Sync).await.unwrap();

    let mut msgs = Vec::new();
    loop {
        let m = client.next().await.unwrap().unwrap();
        let done = matches!(m, BackendMessage::ReadyForQuery(_));
        msgs.push(m);
        if done {
            break;
        }
    }

    // Both statements' completions must arrive — none swallowed.
    let count = |want: &Tag| {
        msgs.iter()
            .filter(|m| match m {
                BackendMessage::ParseComplete => want == &Tag::Parse,
                BackendMessage::BindComplete => want == &Tag::Bind,
                BackendMessage::CommandComplete(_) => want == &Tag::Command,
                _ => false,
            })
            .count()
    };
    assert_eq!(
        count(&Tag::Command),
        2,
        "both statements' CommandComplete must reach the client: {msgs:?}"
    );
    assert_eq!(
        count(&Tag::Bind),
        2,
        "both statements' BindComplete must reach the client: {msgs:?}"
    );
    assert_eq!(
        count(&Tag::Parse),
        2,
        "both statements' ParseComplete must reach the client: {msgs:?}"
    );

    // And in protocol order: each statement's Parse → Bind → Command,
    // not the reordered/duplicated stream the swallow produced.
    let order: Vec<Tag> = msgs
        .iter()
        .filter_map(|m| match m {
            BackendMessage::ParseComplete => Some(Tag::Parse),
            BackendMessage::BindComplete => Some(Tag::Bind),
            BackendMessage::CommandComplete(_) => Some(Tag::Command),
            _ => None,
        })
        .collect();
    assert_eq!(
        order,
        vec![
            Tag::Parse,
            Tag::Bind,
            Tag::Command,
            Tag::Parse,
            Tag::Bind,
            Tag::Command
        ],
        "responses must be in per-statement protocol order: {msgs:?}"
    );

    drop(client);
    let _ = handle.await;
    mock.stop().await;
}

/// A transparent re-prepare (and the LRU eviction it may trigger) must
/// be invisible to the client: the backend's `ParseComplete` for the
/// injected `Parse` and its `CloseComplete` for the evicted statement
/// are halephant's own traffic, not answers to anything the client sent.
///
/// Forces the path with `max_prepared_statements = 1`: preparing `s2`
/// evicts `s1`, so a later `Bind` on `s1` (sent without a fresh `Parse`,
/// the way a driver reuses a client-cached statement) makes halephant
/// re-`Parse` `s1` and evict `s2`. The client's `Bind` step must see a
/// clean `BindComplete` + `CommandComplete`, with no stray
/// `ParseComplete` or `CloseComplete`.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn reprepare_and_eviction_replies_are_hidden_from_client() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let cfg = Config::parse(&format!(
        r#"
        [server]
        checkout_timeout = "{TEST_CHECKOUT_TIMEOUT}"
        max_prepared_statements = 1

        [cluster.test]
        nodes = ["{}"]

        [cluster.test.pool.testdb.user.testuser]
    "#,
        mock.addr()
    ))
    .unwrap();
    let (pools, _config) = setup_pool_with_config(cfg, &mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    // Pin everything to one backend with an explicit transaction so the
    // per-connection LRU actually fills and evicts.
    query_collect(&mut client, "BEGIN").await;
    extended_query(&mut client, "s1", "SELECT 1").await; // prepares _hp(s1)
    extended_query(&mut client, "s2", "SELECT 2").await; // evicts _hp(s1), prepares _hp(s2)

    // Reuse s1 with only Bind + Execute + Sync (no Parse) — s1 is no
    // longer on the backend, so halephant must re-prepare it (injected
    // Parse) and evict s2 (injected Close).
    client
        .feed(FrontendMessage::Bind(
            halephant_core::proto::frontend::Bind {
                portal: String::new(),
                statement: "s1".into(),
                param_formats: vec![],
                params: vec![],
                result_formats: vec![],
            },
        ))
        .await
        .unwrap();
    client
        .feed(FrontendMessage::Execute(
            halephant_core::proto::frontend::Execute {
                portal: String::new(),
                max_rows: 0,
            },
        ))
        .await
        .unwrap();
    client.send(FrontendMessage::Sync).await.unwrap();

    let mut msgs = Vec::new();
    loop {
        let m = client.next().await.unwrap().unwrap();
        let done = matches!(m, BackendMessage::ReadyForQuery(_));
        msgs.push(m);
        if done {
            break;
        }
    }

    assert!(
        msgs.iter()
            .any(|m| matches!(m, BackendMessage::BindComplete)),
        "client should see BindComplete for its Bind: {msgs:?}"
    );
    assert!(
        msgs.iter()
            .any(|m| matches!(m, BackendMessage::CommandComplete(_))),
        "client should see CommandComplete for its Execute: {msgs:?}"
    );
    assert!(
        !msgs
            .iter()
            .any(|m| matches!(m, BackendMessage::ParseComplete)),
        "injected re-prepare ParseComplete must not leak to the client: {msgs:?}"
    );
    assert!(
        !msgs
            .iter()
            .any(|m| matches!(m, BackendMessage::CloseComplete)),
        "injected eviction CloseComplete must not leak to the client: {msgs:?}"
    );

    drop(client);
    let _ = handle.await;
    mock.stop().await;
}

/// Send `Parse(name, query)` + `Sync` and collect responses through
/// `ReadyForQuery`. Used to drive a single rejected-Parse transaction.
async fn parse_only(
    client: &mut Framed<TcpStream, BackendCodec>,
    name: &str,
    query: &str,
) -> Vec<BackendMessage> {
    client
        .feed(FrontendMessage::Parse(
            halephant_core::proto::frontend::Parse {
                name: name.into(),
                query: query.into(),
                param_types: vec![],
            },
        ))
        .await
        .unwrap();
    client.send(FrontendMessage::Sync).await.unwrap();
    let mut msgs = Vec::new();
    loop {
        let m = client.next().await.unwrap().unwrap();
        let done = matches!(m, BackendMessage::ReadyForQuery(_));
        msgs.push(m);
        if done {
            break;
        }
    }
    msgs
}

/// A `Parse` the backend rejects must not leave a phantom entry in the
/// per-connection prepared-statement cache. halephant inserts the
/// canonical name optimistically before the backend confirms; if the
/// backend answers `ErrorResponse` instead of `ParseComplete`, that
/// insert must be rolled back. Otherwise the pooled (and reused)
/// connection reports the canonical as prepared when it is not, so a
/// later use is wrongly skipped — falsely "succeeding" or drawing
/// "prepared statement does not exist".
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn failed_parse_does_not_leave_stale_cache_entry() {
    use halephant_core::proxy::prepared::canonical_for_test;

    let mock = MockPg::start(MockBehavior::Ok).await;
    // max=1 forces the second transaction to reuse the same backend.
    let cfg = Config::parse(&format!(
        r#"
        [server]
        checkout_timeout = "5s"

        [cluster.test]
        nodes = ["{}"]

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 1 }}

        [cluster.test.pool.testdb.user.testuser]
    "#,
        mock.addr()
    ))
    .unwrap();
    let (pools, _config) = setup_pool_with_config(cfg, &mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    // Transaction 1: a Parse the backend rejects.
    let tx1 = parse_only(&mut client, "s1", "SELECT INVALID").await;
    assert!(
        tx1.iter()
            .any(|m| matches!(m, BackendMessage::ErrorResponse(_))),
        "tx1 should surface the backend Parse error: {tx1:?}"
    );

    // Transaction 2 reuses the single backend with the SAME query. If the
    // failed canonical were still cached, halephant would synthesize a
    // ParseComplete and skip the backend — falsely reporting success.
    // With rollback it re-forwards the Parse and the backend rejects it
    // again.
    let tx2 = parse_only(&mut client, "s2", "SELECT INVALID").await;
    assert!(
        tx2.iter()
            .any(|m| matches!(m, BackendMessage::ErrorResponse(_))),
        "tx2 must re-validate on the backend, not falsely succeed from a stale cache entry: {tx2:?}"
    );

    // The canonical Parse must have reached the backend both times.
    let canon = canonical_for_test("SELECT INVALID", &[]);
    let forwarded = mock
        .received_parses()
        .iter()
        .filter(|n| **n == canon)
        .count();
    assert_eq!(
        forwarded,
        2,
        "the rejected Parse should be re-forwarded on reuse, not skipped: {:?}",
        mock.received_parses()
    );

    client.send(FrontendMessage::Terminate).await.unwrap();
    let _ = handle.await;
    mock.stop().await;
}

/// Run one session-mode "client" against an already-checked-out backend:
/// send `Parse(name, query)` + `Sync`, collect responses through
/// `ReadyForQuery`, then disconnect so `session::forward` returns. The
/// backend connection (`guard`) is reused across calls, modelling pool
/// reuse of one upstream by successive client sessions.
async fn session_prepare(
    guard: &mut halephant_core::pool::ConnGuard,
    pools: &Arc<PoolManager>,
    name: &str,
    query: &str,
) -> Vec<BackendMessage> {
    let (client_tcp, proxy_tcp) = tcp_pair().await;
    let mut proxy = Framed::new(proxy_tcp, FrontendCodec::post_startup());
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    let session = halephant_core::proxy::session::forward(&mut proxy, guard.conn(), pools);
    let driver = async {
        client
            .feed(FrontendMessage::Parse(
                halephant_core::proto::frontend::Parse {
                    name: name.into(),
                    query: query.into(),
                    param_types: vec![],
                },
            ))
            .await
            .unwrap();
        client.send(FrontendMessage::Sync).await.unwrap();
        let mut msgs = Vec::new();
        loop {
            let m = client.next().await.unwrap().unwrap();
            let done = matches!(m, BackendMessage::ReadyForQuery(_));
            msgs.push(m);
            if done {
                break;
            }
        }
        drop(client); // disconnect → session::forward returns
        msgs
    };
    let (session_res, msgs) = tokio::join!(session, driver);
    session_res.unwrap();
    msgs
}

/// Session mode binds one client to one backend, but the backend is
/// reused by later clients. psycopg3-style drivers auto-name prepared
/// statements per connection (`_pg3_0`, `_pg3_1`, …) restarting from 0
/// each connection, so two different clients both prepare `_pg3_0` for
/// different queries. If halephant forwards those names verbatim, the
/// reused backend already has `_pg3_0` and rejects the second with
/// `42P05 duplicate_prepared_statement`.
///
/// Canonicalizing names (`SHA-256(query, oids)`) — the same machinery
/// transaction mode uses — makes the backend see distinct hashes, so no
/// collision. This pins that session mode applies it.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn session_mode_reused_backend_avoids_duplicate_prepared() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool_with_config(test_config_session(&mock.addr()), &mock);

    let cg = test_client_guard();
    let mut guard = pools
        .checkout(&cg, "testdb", "testuser", false)
        .await
        .unwrap();

    // Client A prepares "_pg3_0" = SELECT 1 and disconnects.
    let a = session_prepare(&mut guard, &pools, "_pg3_0", "SELECT 1").await;
    assert!(
        !a.iter()
            .any(|m| matches!(m, BackendMessage::ErrorResponse(_))),
        "client A's prepare should succeed: {a:?}"
    );

    // Client B reuses the SAME backend and prepares "_pg3_0" = SELECT 2
    // (a DIFFERENT query under the same client-supplied name).
    let b = session_prepare(&mut guard, &pools, "_pg3_0", "SELECT 2").await;
    assert!(
        !b.iter()
            .any(|m| matches!(m, BackendMessage::ErrorResponse(_))),
        "client B must not collide on the reused backend's prepared name: {b:?}"
    );
    assert!(
        b.iter().any(|m| matches!(m, BackendMessage::ParseComplete)),
        "client B should see a ParseComplete: {b:?}"
    );

    drop(guard);
    mock.stop().await;
}

// ---------------------------------------------------------------------------
// Connection limit enforcement — user-level and pool-level
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn user_max_connections_enforced() {
    // Pool allows 10 primary connections, but userA is capped at 2.
    // The 3rd checkout for userA must time out.
    let mock = MockPg::start(MockBehavior::Ok).await;
    let cfg = Config::parse(&format!(
        r#"
        [server]
        checkout_timeout = "{TEST_CHECKOUT_TIMEOUT}"

        [cluster.test]
        nodes = ["{}"]

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 10 }}

        [cluster.test.pool.testdb.user.userA]
        max_connections = {{ primary = 2 }}

        [cluster.test.pool.testdb.user.userB]
    "#,
        mock.addr()
    ))
    .unwrap();
    let (pools, _config) = setup_pool_with_config(cfg, &mock);

    // userA: first 2 checkouts succeed.
    let client_a = test_client_guard();
    let g1 = pools
        .checkout(&client_a, "testdb", "userA", false)
        .await
        .expect("userA checkout 1");
    let g2 = pools
        .checkout(&client_a, "testdb", "userA", false)
        .await
        .expect("userA checkout 2");

    // userA: 3rd checkout hits the per-user limit.
    let err = pools.checkout(&client_a, "testdb", "userA", false).await;
    assert!(
        err.is_err(),
        "userA checkout 3 should fail (per-user max = 2)"
    );

    // userB: still has room under the pool-level limit.
    let client_b = test_client_guard();
    let g3 = pools
        .checkout(&client_b, "testdb", "userB", false)
        .await
        .expect("userB should succeed despite userA being full");

    drop((g1, g2, g3));
    mock.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pool_max_connections_aggregate_across_users() {
    // Pool allows 3 primary connections total. Two users with no
    // per-user limit. The 4th checkout (any user) must time out.
    let mock = MockPg::start(MockBehavior::Ok).await;
    let cfg = Config::parse(&format!(
        r#"
        [server]
        checkout_timeout = "{TEST_CHECKOUT_TIMEOUT}"

        [cluster.test]
        nodes = ["{}"]

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 3 }}

        [cluster.test.pool.testdb.user.userA]
        [cluster.test.pool.testdb.user.userB]
    "#,
        mock.addr()
    ))
    .unwrap();
    let (pools, _config) = setup_pool_with_config(cfg, &mock);

    let client = test_client_guard();
    let g1 = pools
        .checkout(&client, "testdb", "userA", false)
        .await
        .expect("checkout 1");
    let g2 = pools
        .checkout(&client, "testdb", "userB", false)
        .await
        .expect("checkout 2");
    let g3 = pools
        .checkout(&client, "testdb", "userA", false)
        .await
        .expect("checkout 3");

    // 4th checkout: pool aggregate is 3/3 — should time out.
    let err = pools.checkout(&client, "testdb", "userB", false).await;
    assert!(
        err.is_err(),
        "checkout 4 should fail (pool max = 3, 3 already active)"
    );

    drop((g1, g2, g3));
    mock.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn user_limit_within_pool_limit() {
    // Pool allows 4, userA allows 1, userB allows 3.
    // userA gets 1, userB gets 3, total = 4 = pool max.
    // An extra checkout for either user fails.
    let mock = MockPg::start(MockBehavior::Ok).await;
    let cfg = Config::parse(&format!(
        r#"
        [server]
        checkout_timeout = "{TEST_CHECKOUT_TIMEOUT}"

        [cluster.test]
        nodes = ["{}"]

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 4 }}

        [cluster.test.pool.testdb.user.userA]
        max_connections = {{ primary = 1 }}

        [cluster.test.pool.testdb.user.userB]
        max_connections = {{ primary = 3 }}
    "#,
        mock.addr()
    ))
    .unwrap();
    let (pools, _config) = setup_pool_with_config(cfg, &mock);

    let client = test_client_guard();
    let ga = pools
        .checkout(&client, "testdb", "userA", false)
        .await
        .expect("userA checkout 1");

    // userA is at its per-user cap.
    let err_a = pools.checkout(&client, "testdb", "userA", false).await;
    assert!(
        err_a.is_err(),
        "userA checkout 2 should fail (user max = 1)"
    );

    // userB can still get 3.
    let gb1 = pools
        .checkout(&client, "testdb", "userB", false)
        .await
        .expect("userB checkout 1");
    let gb2 = pools
        .checkout(&client, "testdb", "userB", false)
        .await
        .expect("userB checkout 2");
    let gb3 = pools
        .checkout(&client, "testdb", "userB", false)
        .await
        .expect("userB checkout 3");

    // Pool aggregate is now 4/4. userB's 4th hits the pool limit.
    let err_b = pools.checkout(&client, "testdb", "userB", false).await;
    assert!(
        err_b.is_err(),
        "userB checkout 4 should fail (pool max = 4, all used)"
    );

    drop((ga, gb1, gb2, gb3));
    mock.stop().await;
}

/// When userA holds the last pool-level slot and userB is queued,
/// checkin of userA's connection must wake userB — not just userA's
/// (empty) queue.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn cross_user_wake_on_pool_level_checkin() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let cfg = Config::parse(&format!(
        r#"
        [server]
        checkout_timeout = "2s"

        [cluster.test]
        nodes = ["{}"]

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 1 }}

        [cluster.test.pool.testdb.user.userA]
        [cluster.test.pool.testdb.user.userB]
    "#,
        mock.addr()
    ))
    .unwrap();
    let (pools, _config) = setup_pool_with_config(cfg, &mock);

    // userA takes the single slot.
    let client_a = test_client_guard();
    let guard_a = pools
        .checkout(&client_a, "testdb", "userA", false)
        .await
        .expect("userA checkout should succeed");

    // userB's checkout blocks (pool is full).
    let pools2 = Arc::clone(&pools);
    let userb_handle = tokio::spawn(async move {
        let client_b = test_client_guard();
        pools2.checkout(&client_b, "testdb", "userB", false).await
    });

    // Brief yield so userB's checkout enqueues.
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;

    // Return userA's connection — this must wake userB.
    guard_a.checkin();

    // userB should succeed well within the 2s timeout.
    let result = tokio::time::timeout(std::time::Duration::from_secs(1), userb_handle)
        .await
        .expect("userB should be woken within 1s")
        .expect("task should not panic");

    assert!(
        result.is_ok(),
        "userB checkout should succeed after userA checkin, got: {:?}",
        result.err()
    );

    mock.stop().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn read_only_user_does_not_fall_back_to_primary() {
    // A user with max_connections = { replica = 2 } (no primary) must
    // NOT fall back to the primary — user_has_capacity returns false
    // for the primary candidate.
    let primary = MockPg::start(MockBehavior::Ok).await;
    let replica = MockPg::start_replica(MockBehavior::Ok).await;
    let toml = format!(
        r#"
        [server]
        checkout_timeout = "{TEST_CHECKOUT_TIMEOUT}"

        [cluster.test]
        nodes = ["{}", "{}"]
        admin_user = "testuser"

        [cluster.test.pool.testdb]
        max_connections = {{ primary = 10, replica = 2 }}

        [cluster.test.pool.testdb.user.rouser]
        max_connections = {{ replica = 2 }}
    "#,
        primary.addr(),
        replica.addr(),
    );

    let config = Arc::new(ArcSwap::from_pointee(Config::parse(&toml).unwrap()));
    let pgpass = Arc::new(halephant_core::auth::pgpass::Pgpass::parse(""));
    let topology = Arc::new(TopologyManager::new(
        Arc::clone(&config),
        Arc::clone(&pgpass),
    ));
    seed_primary_with_replicas(&topology, primary.addr(), vec![replica.addr()]);
    let pools = Arc::new(PoolManager::new(Arc::clone(&config), topology, pgpass));

    let client = test_client_guard();

    // Fill the replica (2 connections).
    let g1 = pools
        .checkout(&client, "testdb", "rouser", true)
        .await
        .expect("checkout 1");
    let g2 = pools
        .checkout(&client, "testdb", "rouser", true)
        .await
        .expect("checkout 2");

    // 3rd checkout: replica full, primary budget is 0 — must time out.
    let result = pools.checkout(&client, "testdb", "rouser", true).await;
    assert!(
        result.is_err(),
        "read-only user should NOT fall back to primary"
    );

    drop((g1, g2));
    primary.stop().await;
    replica.stop().await;
}

// ---------------------------------------------------------------------------
// Message classification boundaries — protocol-scoped intercepts, SET
// tracking, pin-mode LISTEN, and the explicit-transaction Sync gate
// ---------------------------------------------------------------------------

/// Feed a full extended-protocol batch (`Parse`/`Bind`/`Execute`/`Sync`)
/// without flushing, so several batches can be pipelined into one flush.
async fn feed_extended_batch(
    client: &mut Framed<TcpStream, BackendCodec>,
    name: &str,
    query: &str,
) {
    client
        .feed(FrontendMessage::Parse(
            halephant_core::proto::frontend::Parse {
                name: name.into(),
                query: query.into(),
                param_types: vec![],
            },
        ))
        .await
        .unwrap();
    client
        .feed(FrontendMessage::Bind(
            halephant_core::proto::frontend::Bind {
                portal: String::new(),
                statement: name.into(),
                param_formats: vec![],
                params: vec![],
                result_formats: vec![],
            },
        ))
        .await
        .unwrap();
    client
        .feed(FrontendMessage::Execute(
            halephant_core::proto::frontend::Execute {
                portal: String::new(),
                max_rows: 0,
            },
        ))
        .await
        .unwrap();
    client.feed(FrontendMessage::Sync).await.unwrap();
}

/// Collect responses until (and including) the next `ReadyForQuery`.
async fn collect_until_ready(client: &mut Framed<TcpStream, BackendCodec>) -> Vec<BackendMessage> {
    let mut msgs = Vec::new();
    loop {
        let msg = client.next().await.unwrap().unwrap();
        let done = matches!(msg, BackendMessage::ReadyForQuery(_));
        msgs.push(msg);
        if done {
            return msgs;
        }
    }
}

/// Poll until the pool holds at least `want` idle connections, proving the
/// background reset-and-checkin completed. Panics after 2 s.
async fn wait_for_idle(pools: &PoolManager, want: u32) {
    let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2);
    while total_idle(pools) < want {
        assert!(
            tokio::time::Instant::now() < deadline,
            "connection was not reset and returned to the idle pool within 2 s"
        );
        tokio::time::sleep(std::time::Duration::from_millis(5)).await;
    }
}

/// A pipelined explicit transaction — `BEGIN`, two extended-protocol
/// batches, `COMMIT`, all flushed together — must flow on a single backend
/// with every response delivered. The `Sync` gate must hold before the
/// server confirms the transaction (the proxy cannot yet know the session
/// isn't autocommit) and relax once `ReadyForQuery(InTransaction)` arrives,
/// so the in-transaction batches pipeline freely without stranding any
/// response. The slow mock guarantees the proxy reads the whole pipelined
/// buffer before the first server reply.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pipelined_explicit_transaction_batches_flow_on_one_backend() {
    let mock = MockPg::start_slow(MockBehavior::Ok, std::time::Duration::from_millis(20)).await;
    let (pools, _config) = setup_pool(&mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    // BEGIN, two extended-protocol batches, COMMIT — one flush.
    client
        .feed(FrontendMessage::Query("BEGIN".into()))
        .await
        .unwrap();
    feed_extended_batch(&mut client, "s1", "SELECT 1").await;
    feed_extended_batch(&mut client, "s2", "SELECT 2").await;
    client
        .feed(FrontendMessage::Query("COMMIT".into()))
        .await
        .unwrap();
    SinkExt::flush(&mut client).await.unwrap();

    // Collect until the COMMIT's ReadyForQuery(Idle); a stranded batch
    // fails the timeout instead of hanging the test.
    let msgs = tokio::time::timeout(std::time::Duration::from_secs(5), async {
        let mut msgs = Vec::new();
        loop {
            let msg = client.next().await.unwrap().unwrap();
            let done = matches!(msg, BackendMessage::ReadyForQuery(TransactionStatus::Idle));
            msgs.push(msg);
            if done {
                break;
            }
        }
        msgs
    })
    .await
    .expect("timed out — an in-transaction pipelined batch was stranded");

    let readies: Vec<TransactionStatus> = msgs
        .iter()
        .filter_map(|m| match m {
            BackendMessage::ReadyForQuery(s) => Some(*s),
            _ => None,
        })
        .collect();
    assert_eq!(
        readies,
        vec![
            TransactionStatus::InTransaction, // BEGIN
            TransactionStatus::InTransaction, // batch s1
            TransactionStatus::InTransaction, // batch s2
            TransactionStatus::Idle,          // COMMIT
        ],
        "expected one ReadyForQuery per batch with in-transaction statuses: {msgs:?}"
    );
    let completes = msgs
        .iter()
        .filter(|m| matches!(m, BackendMessage::CommandComplete(_)))
        .count();
    assert_eq!(
        completes, 4,
        "BEGIN, both Executes, and COMMIT must each complete: {msgs:?}"
    );
    let parses = msgs
        .iter()
        .filter(|m| matches!(m, BackendMessage::ParseComplete))
        .count();
    assert_eq!(
        parses, 2,
        "both ParseComplete must reach the client: {msgs:?}"
    );
    assert_eq!(
        mock.connections(),
        1,
        "the explicit transaction must hold a single backend"
    );

    client.send(FrontendMessage::Terminate).await.unwrap();
    handle.await.unwrap().unwrap();
    mock.stop().await;
}

/// A `SET` sent through the simple query protocol executes immediately, so
/// halephant tracks the variable and RESETs it when the connection returns
/// to the pool. Positive control for the Parse-carried case below.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn set_via_query_is_reset_on_checkin() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool(&mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    let _ = query_collect(&mut client, "SET application_name TO 'trackme'").await;

    // The reset round trip completes before the connection reaches the
    // idle pool, so received_queries is settled once idle appears.
    wait_for_idle(&pools, 1).await;
    let received = mock.received_queries();
    assert!(
        received
            .iter()
            .any(|q| q.contains("RESET application_name")),
        "checkin must RESET the session-SET variable, got: {received:?}"
    );

    client.send(FrontendMessage::Terminate).await.unwrap();
    handle.await.unwrap().unwrap();
    mock.stop().await;
}

/// A `SET` carried inside an extended-protocol `Parse` is prepared, not
/// executed, so halephant must NOT track it: the checkin reset would
/// otherwise RESET a variable the session never actually set. Guards the
/// protocol boundary of the SET tracker (simple-protocol `Query`
/// statements only).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn set_via_parse_is_not_tracked_for_reset() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool(&mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    extended_query(
        &mut client,
        "set_stmt",
        "SET application_name TO 'untracked'",
    )
    .await;

    wait_for_idle(&pools, 1).await;
    let received = mock.received_queries();
    assert!(
        !received
            .iter()
            .any(|q| q.contains("RESET application_name")),
        "a Parse-carried SET must not be tracked for reset, got: {received:?}"
    );

    client.send(FrontendMessage::Terminate).await.unwrap();
    handle.await.unwrap().unwrap();
    mock.stop().await;
}

/// A `DEALLOCATE` carried inside an extended-protocol `Parse` must be
/// forwarded, not intercepted: interception is simple-query-protocol only,
/// and a synthetic `CommandComplete` + `ReadyForQuery` here would
/// desynchronize the extended-protocol response stream the client expects
/// (`ParseComplete`/`BindComplete`/...).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn deallocate_via_parse_is_forwarded_not_intercepted() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool(&mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    feed_extended_batch(&mut client, "d1", "DEALLOCATE ALL").await;
    SinkExt::flush(&mut client).await.unwrap();
    let msgs = collect_until_ready(&mut client).await;

    assert!(
        msgs.iter()
            .any(|m| matches!(m, BackendMessage::ParseComplete)),
        "the DEALLOCATE Parse must draw a ParseComplete: {msgs:?}"
    );
    assert!(
        msgs.iter()
            .any(|m| matches!(m, BackendMessage::BindComplete)),
        "the batch must complete through the backend: {msgs:?}"
    );
    assert!(
        !msgs
            .iter()
            .any(|m| matches!(m, BackendMessage::CommandComplete(tag) if tag == "DEALLOCATE")),
        "extended-protocol DEALLOCATE must not draw the synthetic simple-query response: {msgs:?}"
    );
    assert_eq!(
        mock.received_parses().len(),
        1,
        "the DEALLOCATE Parse must reach the backend"
    );

    client.send(FrontendMessage::Terminate).await.unwrap();
    handle.await.unwrap().unwrap();
    mock.stop().await;
}

/// In pin mode a `LISTEN` switches the client to session-style pinning:
/// the backend stays checked out across `ReadyForQuery(Idle)` until
/// `UNLISTEN *`. While pinned, a synthetic intercept reply must carry the
/// real server status (`Idle` after the LISTEN completed), and the pool
/// must refuse the pinned connection to other clients.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pin_mode_listen_pins_connection_until_unlisten_star() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool_with_config(test_config_max(&mock.addr(), 1), &mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    // LISTEN as the first message of a checkout pins immediately, and pin
    // mode forwards it to the backend (no interception).
    let msgs = query_collect(&mut client, "LISTEN pinchan").await;
    assert!(
        matches!(
            msgs.last(),
            Some(BackendMessage::ReadyForQuery(TransactionStatus::Idle))
        ),
        "LISTEN should complete with ReadyForQuery(Idle): {msgs:?}"
    );
    assert!(
        mock.received_queries()
            .iter()
            .any(|q| q.contains("LISTEN pinchan")),
        "pin mode must forward the LISTEN to the backend"
    );

    // The pinned backend is still checked out: with max = 1 a second
    // checkout times out instead of stealing it.
    let other = test_client_guard();
    let result = pools.checkout(&other, "testdb", "testuser", false).await;
    assert!(
        result.is_err(),
        "pinned connection must not be handed to another client"
    );

    // An intercepted DEALLOCATE while pinned-and-idle must advertise the
    // real server status (Idle), not the optimistic in-transaction default
    // that only applies before the first ReadyForQuery.
    let msgs = query_collect(&mut client, "DEALLOCATE bogus").await;
    assert!(
        msgs.iter()
            .any(|m| matches!(m, BackendMessage::CommandComplete(tag) if tag == "DEALLOCATE")),
        "DEALLOCATE must be intercepted with a synthetic response: {msgs:?}"
    );
    assert!(
        matches!(
            msgs.last(),
            Some(BackendMessage::ReadyForQuery(TransactionStatus::Idle))
        ),
        "the synthetic status must mirror the last server status: {msgs:?}"
    );
    assert!(
        !mock
            .received_queries()
            .iter()
            .any(|q| q.to_ascii_uppercase().contains("DEALLOCATE")),
        "the intercepted DEALLOCATE must not reach the backend"
    );

    // UNLISTEN * unpins; the following ReadyForQuery(Idle) releases the
    // backend to the pool, where another client can pick it up.
    let _ = query_collect(&mut client, "UNLISTEN *").await;
    wait_for_idle(&pools, 1).await;
    let guard = pools
        .checkout(&other, "testdb", "testuser", false)
        .await
        .expect("released connection must be checkoutable after UNLISTEN *");
    drop(guard);

    client.send(FrontendMessage::Terminate).await.unwrap();
    handle.await.unwrap().unwrap();
    mock.stop().await;
}

/// `LISTEN` arriving mid-transaction (not as the checkout's first message)
/// must pin through the inner forwarding loop as well: after `COMMIT`
/// returns the session to idle, the backend stays checked out.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pin_mode_listen_mid_transaction_pins_connection() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool_with_config(test_config_max(&mock.addr(), 1), &mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    let _ = query_collect(&mut client, "BEGIN").await;
    let _ = query_collect(&mut client, "LISTEN midchan").await;
    let msgs = query_collect(&mut client, "COMMIT").await;
    assert!(
        matches!(
            msgs.last(),
            Some(BackendMessage::ReadyForQuery(TransactionStatus::Idle))
        ),
        "COMMIT should return the session to idle: {msgs:?}"
    );

    // Still pinned after the transaction completed.
    let other = test_client_guard();
    let result = pools.checkout(&other, "testdb", "testuser", false).await;
    assert!(
        result.is_err(),
        "mid-transaction LISTEN must pin the connection past COMMIT"
    );

    // UNLISTEN * releases it.
    let _ = query_collect(&mut client, "UNLISTEN *").await;
    wait_for_idle(&pools, 1).await;

    client.send(FrontendMessage::Terminate).await.unwrap();
    handle.await.unwrap().unwrap();
    mock.stop().await;
}

/// A `LISTEN` carried in an extended-protocol `Parse` also pins: the
/// classifier reads Parse-carried SQL for routing and pinning, so both
/// protocols trigger session pinning identically.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pin_mode_listen_via_parse_pins_connection() {
    let mock = MockPg::start(MockBehavior::Ok).await;
    let (pools, _config) = setup_pool_with_config(test_config_max(&mock.addr(), 1), &mock);
    let (client_tcp, proxy_tcp) = tcp_pair().await;

    let handle = spawn_tx_forward(proxy_tcp, Arc::clone(&pools), "testdb", "testuser", false);
    let mut client = Framed::new(client_tcp, BackendCodec::new());

    extended_query(&mut client, "l1", "LISTEN extchan").await;

    // Pinned: the backend survives the batch's ReadyForQuery(Idle).
    let other = test_client_guard();
    let result = pools.checkout(&other, "testdb", "testuser", false).await;
    assert!(
        result.is_err(),
        "Parse-carried LISTEN must pin the connection"
    );

    // Client disconnect returns the pinned connection to the pool.
    client.send(FrontendMessage::Terminate).await.unwrap();
    handle.await.unwrap().unwrap();
    wait_for_idle(&pools, 1).await;
    mock.stop().await;
}