sqlmodel-pool 0.3.2

Connection pooling for SQLModel Rust using asupersync
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
//! Connection pooling for SQLModel Rust using asupersync.
//!
//! `sqlmodel-pool` is the **connection lifecycle layer**. It provides a generic,
//! budget-aware pool that integrates with structured concurrency and can wrap any
//! `Connection` implementation.
//!
//! # Role In The Architecture
//!
//! - **Shared connection management**: reuse connections across tasks safely.
//! - **Budget-aware acquisition**: respects `Cx` timeouts and cancellation.
//! - **Health checks**: validates connections before handing them out.
//! - **Metrics**: exposes stats for pool sizing and tuning.
//!
//! # Features
//!
//! - Generic over any `Connection` type
//! - RAII-based connection return (connections returned on drop)
//! - Timeout support via `Cx` context
//! - Connection health validation
//! - Idle and max lifetime tracking
//! - Pool statistics
//!
//! # Example
//!
//! ```rust,ignore
//! use sqlmodel_pool::{Pool, PoolConfig};
//!
//! // Create a pool
//! let config = PoolConfig::new(10)
//!     .min_connections(2)
//!     .acquire_timeout(5000);
//!
//! let pool = Pool::new(config, || async {
//!     // Factory function to create new connections
//!     PgConnection::connect(&cx, &pg_config).await
//! });
//!
//! // Acquire a connection
//! let conn = pool.acquire(&cx).await?;
//!
//! // Use the connection (automatically returned to pool on drop)
//! conn.query(&cx, "SELECT 1", &[]).await?;
//! ```

pub mod replica;
pub use replica::{ReplicaPool, ReplicaStrategy};

pub mod sharding;
pub use sharding::{ModuloShardChooser, QueryHints, ShardChooser, ShardedPool, ShardedPoolStats};

use std::collections::VecDeque;
use std::future::Future;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, Weak};
use std::time::{Duration, Instant};

use asupersync::{
    CancelReason, Cx, Outcome,
    combinator::{Either, Select},
    runtime::RuntimeBuilder,
    sync::OnceCell,
};
use sqlmodel_core::error::{ConnectionError, ConnectionErrorKind, PoolError, PoolErrorKind};
use sqlmodel_core::{Connection, Error};

/// Connection pool configuration.
#[derive(Debug, Clone)]
pub struct PoolConfig {
    /// Minimum number of connections to maintain
    pub min_connections: usize,
    /// Maximum number of connections allowed
    pub max_connections: usize,
    /// Connection idle timeout in milliseconds
    pub idle_timeout_ms: u64,
    /// Maximum time to wait for a connection in milliseconds
    pub acquire_timeout_ms: u64,
    /// Maximum lifetime of a connection in milliseconds
    pub max_lifetime_ms: u64,
    /// Test connections before giving them out
    pub test_on_checkout: bool,
    /// Test connections when returning them to the pool
    pub test_on_return: bool,
}

impl Default for PoolConfig {
    fn default() -> Self {
        Self {
            min_connections: 1,
            max_connections: 10,
            idle_timeout_ms: 600_000,   // 10 minutes
            acquire_timeout_ms: 30_000, // 30 seconds
            max_lifetime_ms: 1_800_000, // 30 minutes
            test_on_checkout: true,
            test_on_return: false,
        }
    }
}

impl PoolConfig {
    /// Create a new pool configuration with the given max connections.
    #[must_use]
    pub fn new(max_connections: usize) -> Self {
        Self {
            max_connections,
            ..Default::default()
        }
    }

    /// Set minimum connections.
    #[must_use]
    pub fn min_connections(mut self, n: usize) -> Self {
        self.min_connections = n;
        self
    }

    /// Set idle timeout in milliseconds.
    #[must_use]
    pub fn idle_timeout(mut self, ms: u64) -> Self {
        self.idle_timeout_ms = ms;
        self
    }

    /// Set acquire timeout in milliseconds.
    #[must_use]
    pub fn acquire_timeout(mut self, ms: u64) -> Self {
        self.acquire_timeout_ms = ms;
        self
    }

    /// Set max lifetime in milliseconds.
    #[must_use]
    pub fn max_lifetime(mut self, ms: u64) -> Self {
        self.max_lifetime_ms = ms;
        self
    }

    /// Enable/disable test on checkout.
    #[must_use]
    pub fn test_on_checkout(mut self, enabled: bool) -> Self {
        self.test_on_checkout = enabled;
        self
    }

    /// Enable/disable test on return.
    #[must_use]
    pub fn test_on_return(mut self, enabled: bool) -> Self {
        self.test_on_return = enabled;
        self
    }
}

/// Pool statistics.
#[derive(Debug, Clone, Default)]
pub struct PoolStats {
    /// Total number of connections (active + idle)
    pub total_connections: usize,
    /// Number of idle connections
    pub idle_connections: usize,
    /// Number of active connections (currently in use)
    pub active_connections: usize,
    /// Number of pending acquire requests
    pub pending_requests: usize,
    /// Total number of connections created
    pub connections_created: u64,
    /// Total number of connections closed
    pub connections_closed: u64,
    /// Total number of successful acquires
    pub acquires: u64,
    /// Total number of acquire timeouts
    pub timeouts: u64,
}

/// Metadata about a pooled connection.
#[derive(Debug)]
struct ConnectionMeta<C> {
    /// The actual connection
    conn: C,
    /// When this connection was created
    created_at: Instant,
    /// When this connection was last used
    last_used: Instant,
}

impl<C> ConnectionMeta<C> {
    fn new(conn: C) -> Self {
        let now = Instant::now();
        Self {
            conn,
            created_at: now,
            last_used: now,
        }
    }

    fn touch(&mut self) {
        self.last_used = Instant::now();
    }

    fn age(&self) -> Duration {
        self.created_at.elapsed()
    }

    fn idle_time(&self) -> Duration {
        self.last_used.elapsed()
    }
}

/// Internal pool state shared between pool and connections.
struct PoolInner<C: Connection> {
    /// Pool configuration
    config: PoolConfig,
    /// Idle connections available for use
    idle: VecDeque<ConnectionMeta<C>>,
    /// Number of connections currently checked out
    active_count: usize,
    /// Total number of connections (idle + active)
    total_count: usize,
    /// Number of waiters in the queue
    waiter_count: usize,
    /// Whether the pool has been closed
    closed: bool,
}

impl<C: Connection> PoolInner<C> {
    fn new(config: PoolConfig) -> Self {
        Self {
            config,
            idle: VecDeque::new(),
            active_count: 0,
            total_count: 0,
            waiter_count: 0,
            closed: false,
        }
    }

    fn can_create_new(&self) -> bool {
        !self.closed && self.total_count < self.config.max_connections
    }

    fn stats(&self) -> PoolStats {
        PoolStats {
            total_connections: self.total_count,
            idle_connections: self.idle.len(),
            active_connections: self.active_count,
            pending_requests: self.waiter_count,
            ..Default::default()
        }
    }
}

/// Shared state wrapper with condition variable for notification.
struct PoolShared<C: Connection> {
    /// Protected pool state
    inner: Mutex<PoolInner<C>>,
    /// Notifies waiters when connections become available
    conn_available: Condvar,
    /// One-shot latch initialized when the irreversible pool drain completes.
    active_drained: OnceCell<()>,
    /// Stable first teardown failure, retained so every current or later
    /// drainer observes the same fail-closed lifecycle state.
    retirement_failure: Mutex<Option<Arc<str>>>,
    /// Statistics counters (atomic for lock-free reads)
    connections_created: AtomicU64,
    connections_closed: AtomicU64,
    acquires: AtomicU64,
    timeouts: AtomicU64,
}

impl<C: Connection> PoolShared<C> {
    fn new(config: PoolConfig) -> Self {
        Self {
            inner: Mutex::new(PoolInner::new(config)),
            conn_available: Condvar::new(),
            active_drained: OnceCell::new(),
            retirement_failure: Mutex::new(None),
            connections_created: AtomicU64::new(0),
            connections_closed: AtomicU64::new(0),
            acquires: AtomicU64::new(0),
            timeouts: AtomicU64::new(0),
        }
    }

    /// Lock the inner mutex, recovering from poisoning for read-only access.
    ///
    /// A poisoned mutex occurs when a thread panicked while holding the lock.
    /// The data inside is still valid for reading, so we recover by logging
    /// and using `into_inner()` to get the guard.
    ///
    /// This should only be used for read-only operations where the data is
    /// always valid regardless of whether a previous operation completed.
    fn lock_or_recover(&self) -> std::sync::MutexGuard<'_, PoolInner<C>> {
        self.inner.lock().unwrap_or_else(|poisoned| {
            tracing::error!(
                "Pool mutex poisoned; recovering for read-only access. \
                 A thread panicked while holding the lock."
            );
            poisoned.into_inner()
        })
    }

    /// Lock the inner mutex, returning an error if poisoned.
    ///
    /// Use this for mutation operations where the pool state may be inconsistent
    /// after a panic. Unlike `lock_or_recover()`, this propagates the error
    /// to the caller.
    #[allow(clippy::result_large_err)] // Error type is large by design for rich diagnostics
    fn lock_or_error(
        &self,
        operation: &'static str,
    ) -> Result<std::sync::MutexGuard<'_, PoolInner<C>>, Error> {
        self.inner
            .lock()
            .map_err(|_| Error::Pool(PoolError::poisoned(operation)))
    }

    /// Release one active slot that is leaving the pool permanently.
    ///
    /// The caller must not invoke this until any required driver close has
    /// completed. Keeping the slot active through close is what makes
    /// `Pool::close_and_drain` a resource-quiescence boundary instead of only
    /// a bookkeeping boundary.
    fn release_active_slot(&self, operation: &'static str) {
        let mut accounting_underflow = false;
        let (drained, notify_open_waiter) = match self.inner.lock() {
            Ok(mut inner) => {
                if inner.active_count == 0 || inner.total_count == 0 {
                    tracing::error!(
                        operation,
                        active_count = inner.active_count,
                        total_count = inner.total_count,
                        "attempted to release an unaccounted pool slot"
                    );
                    accounting_underflow = true;
                }
                inner.active_count = inner.active_count.saturating_sub(1);
                inner.total_count = inner.total_count.saturating_sub(1);
                if accounting_underflow && inner.closed && inner.active_count == 0 {
                    inner.total_count = 0;
                }
                (inner.closed && inner.active_count == 0, !inner.closed)
            }
            Err(poisoned) => {
                tracing::error!(
                    operation,
                    "Pool mutex poisoned while releasing an active slot; \
                     recovering to prevent stranded drain accounting"
                );
                let error = Error::Pool(PoolError::poisoned(operation));
                self.record_retirement_failure(operation, &error);
                let mut inner = poisoned.into_inner();
                if inner.active_count == 0 || inner.total_count == 0 {
                    accounting_underflow = true;
                }
                inner.active_count = inner.active_count.saturating_sub(1);
                inner.total_count = inner.total_count.saturating_sub(1);
                if accounting_underflow && inner.closed && inner.active_count == 0 {
                    inner.total_count = 0;
                }
                (inner.closed && inner.active_count == 0, !inner.closed)
            }
        };

        if accounting_underflow {
            let error = Error::Custom(format!(
                "pool accounting underflow while releasing active slot during {operation}"
            ));
            self.record_retirement_failure(operation, &error);
        }
        if notify_open_waiter {
            self.conn_available.notify_one();
        }
        if drained {
            // Pool closure is irreversible, so a one-shot latch exactly models
            // the single transition to fully drained and wakes every waiter.
            let _ = self.active_drained.set(());
        }
    }

    fn record_retirement_failure(&self, context: &'static str, error: &Error) {
        let message: Arc<str> = format!("{context}: {error}").into();
        let mut failure = self.retirement_failure.lock().unwrap_or_else(|poisoned| {
            tracing::error!(
                context,
                "Pool retirement-failure mutex poisoned; recovering"
            );
            poisoned.into_inner()
        });
        if failure.is_none() {
            *failure = Some(message);
        }
    }

    fn retirement_failure_error(&self) -> Option<Error> {
        let failure = self
            .retirement_failure
            .lock()
            .unwrap_or_else(|poisoned| {
                tracing::error!("Pool retirement-failure mutex poisoned; recovering");
                poisoned.into_inner()
            })
            .clone();
        failure.map(|message| Error::Custom(format!("pool retirement failed: {message}")))
    }
}

#[allow(clippy::result_large_err)] // Error is the crate's rich public error type.
fn close_connection_blocking<C: Connection>(conn: C, context: &'static str) -> Result<(), Error> {
    let runtime = match RuntimeBuilder::current_thread().build() {
        Ok(runtime) => runtime,
        Err(error) => {
            tracing::warn!(
                context,
                error = %error,
                "failed to build runtime while closing pooled connection"
            );
            drop(conn);
            return Err(Error::Custom(format!(
                "failed to build runtime while closing pooled connection: {error}"
            )));
        }
    };
    let cx = Cx::for_testing();
    let result = runtime.block_on(async { conn.close_for_pool(&cx).await });
    if let Err(error) = &result {
        tracing::warn!(
            context,
            error = %error,
            "failed to close pooled connection explicitly"
        );
    }
    result
}

/// Owns an active/total pool slot while an asynchronous connection factory is
/// in flight.
///
/// Dropping an `acquire` future must not strand its reserved slot forever:
/// `close_and_drain` may already be waiting for that slot to retire.
struct ActiveSlotGuard<C: Connection> {
    pool: Arc<PoolShared<C>>,
    armed: bool,
}

impl<C: Connection> ActiveSlotGuard<C> {
    fn new(pool: Arc<PoolShared<C>>) -> Self {
        Self { pool, armed: true }
    }

    fn disarm(&mut self) {
        self.armed = false;
    }

    fn release(&mut self, operation: &'static str) {
        if self.armed {
            self.armed = false;
            self.pool.release_active_slot(operation);
        }
    }
}

impl<C: Connection> Drop for ActiveSlotGuard<C> {
    fn drop(&mut self) {
        self.release("connection factory future drop");
    }
}

/// Owns an active connection while checkout validation is in flight.
///
/// On hard cancellation the guard drops the connection resource before it
/// releases the active slot, preserving the drain boundary without requiring
/// asynchronous work from `Drop`.
struct ActiveConnectionGuard<C: Connection> {
    pool: Arc<PoolShared<C>>,
    meta: Option<ConnectionMeta<C>>,
    armed: bool,
}

enum RetirementOutcome {
    Closed,
    Cancelled(CancelReason),
    Failed(Error),
}

impl<C: Connection> ActiveConnectionGuard<C> {
    fn new(pool: Arc<PoolShared<C>>, meta: ConnectionMeta<C>) -> Self {
        Self {
            pool,
            meta: Some(meta),
            armed: true,
        }
    }

    fn connection(&self) -> &C {
        &self
            .meta
            .as_ref()
            .expect("active connection guard already consumed")
            .conn
    }

    fn into_meta(mut self) -> ConnectionMeta<C> {
        self.armed = false;
        self.meta
            .take()
            .expect("active connection guard already consumed")
    }

    fn release(&mut self, operation: &'static str) {
        if self.armed {
            self.armed = false;
            self.pool.connections_closed.fetch_add(1, Ordering::Relaxed);
            self.pool.release_active_slot(operation);
        }
    }

    async fn close(mut self, cx: &Cx, context: &'static str) -> RetirementOutcome {
        // `close_for_pool` consumes the connection. Keep `self` (the armed
        // accounting guard) alive first, then declare the consuming future.
        // Rust drops locals in reverse declaration order, so hard-dropping this
        // async function drops the later close future and its owned connection
        // before `self` releases the active/total slot.
        let meta = self
            .meta
            .take()
            .expect("active connection guard already consumed");
        let close_future = Box::pin(meta.conn.close_for_pool(cx));
        let cancellation_latch = OnceCell::<()>::new();
        let cancellation_future = Box::pin(cancellation_latch.wait(cx));

        // The close hook receives `cx`, but a driver may fail to observe it.
        // Race it against a cancel-aware one-shot wait so cancellation always
        // drops the owned close future and resource. This is an intentional
        // loser drop: there is no task or obligation to drain after the
        // connection-owning future itself has been destroyed.
        let selected = Select::new(close_future, cancellation_future).await;
        let outcome = match selected {
            Ok(Either::Left(result)) => match result {
                Ok(()) => RetirementOutcome::Closed,
                Err(error) => {
                    tracing::warn!(
                        context,
                        error = %error,
                        "failed to close pooled connection explicitly"
                    );
                    self.pool.record_retirement_failure(context, &error);
                    RetirementOutcome::Failed(error)
                }
            },
            Ok(Either::Right(_)) => RetirementOutcome::Cancelled(
                cx.cancel_reason()
                    .unwrap_or_else(|| CancelReason::user("pool retirement cancelled")),
            ),
            Err(error) => {
                tracing::error!(
                    context,
                    error = %error,
                    "fresh pool retirement select completed inconsistently"
                );
                let error = Error::Custom(format!(
                    "pool retirement select completed inconsistently: {error}"
                ));
                self.pool.record_retirement_failure(context, &error);
                RetirementOutcome::Failed(error)
            }
        };
        // Record any failure above before releasing the potentially-final slot:
        // the latch publication is the synchronization point for all drainers.
        self.release(context);
        outcome
    }
}

impl<C: Connection> Drop for ActiveConnectionGuard<C> {
    fn drop(&mut self) {
        if !self.armed {
            return;
        }
        // Async Drop is impossible. Dropping the resource itself is the
        // hard-cancellation fallback; do that before releasing its pool slot so
        // a concurrent drainer cannot observe quiescence too early.
        drop(self.meta.take());
        self.release("checkout validation future drop");
    }
}

/// A connection pool for database connections.
///
/// The pool manages a collection of connections, reusing them across
/// requests to avoid the overhead of establishing new connections.
///
/// # Type Parameters
///
/// - `C`: The connection type, must implement `Connection`
///
/// # Cancellation
///
/// Pool operations respect cancellation via the `Cx` context:
/// - `acquire` will return early if cancellation is requested
/// - Connections are properly cleaned up on cancellation
pub struct Pool<C: Connection> {
    shared: Arc<PoolShared<C>>,
}

impl<C: Connection> Pool<C> {
    /// Create a new connection pool with the given configuration.
    #[must_use]
    pub fn new(config: PoolConfig) -> Self {
        Self {
            shared: Arc::new(PoolShared::new(config)),
        }
    }

    /// Get the pool configuration.
    #[must_use]
    pub fn config(&self) -> PoolConfig {
        let inner = self.shared.lock_or_recover();
        inner.config.clone()
    }

    /// Get the current pool statistics.
    #[must_use]
    pub fn stats(&self) -> PoolStats {
        let inner = self.shared.lock_or_recover();
        let mut stats = inner.stats();
        stats.connections_created = self.shared.connections_created.load(Ordering::Relaxed);
        stats.connections_closed = self.shared.connections_closed.load(Ordering::Relaxed);
        stats.acquires = self.shared.acquires.load(Ordering::Relaxed);
        stats.timeouts = self.shared.timeouts.load(Ordering::Relaxed);
        stats
    }

    /// Check if the pool is at capacity.
    #[must_use]
    pub fn at_capacity(&self) -> bool {
        let inner = self.shared.lock_or_recover();
        inner.total_count >= inner.config.max_connections
    }

    /// Check if the pool has been closed.
    #[must_use]
    pub fn is_closed(&self) -> bool {
        let inner = self.shared.lock_or_recover();
        inner.closed
    }

    /// Acquire a connection from the pool.
    ///
    /// This method will:
    /// 1. Return an idle connection if one is available
    /// 2. Create a new connection if below capacity
    /// 3. Wait for a connection to become available (up to timeout)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The pool is closed
    /// - The acquire timeout is exceeded
    /// - Cancellation is requested via the `Cx` context
    /// - Connection validation fails (if `test_on_checkout` is enabled)
    pub async fn acquire<F, Fut>(&self, cx: &Cx, factory: F) -> Outcome<PooledConnection<C>, Error>
    where
        F: Fn() -> Fut,
        Fut: Future<Output = Outcome<C, Error>>,
    {
        let deadline = Instant::now() + Duration::from_millis(self.config().acquire_timeout_ms);
        let test_on_checkout = self.config().test_on_checkout;
        let max_lifetime = Duration::from_millis(self.config().max_lifetime_ms);
        let idle_timeout = Duration::from_millis(self.config().idle_timeout_ms);

        loop {
            // Check cancellation
            if cx.is_cancel_requested() {
                return Outcome::Cancelled(CancelReason::user("pool acquire cancelled"));
            }

            // Check timeout
            if Instant::now() >= deadline {
                self.shared.timeouts.fetch_add(1, Ordering::Relaxed);
                return Outcome::Err(Error::Pool(PoolError {
                    kind: PoolErrorKind::Timeout,
                    message: "acquire timeout: no connections available".to_string(),
                    source: None,
                }));
            }

            // Try to get an idle connection or determine if we can create new
            let (action, retired) = {
                let mut inner = match self.shared.lock_or_error("acquire") {
                    Ok(guard) => guard,
                    Err(e) => return Outcome::Err(e),
                };
                // Reserve before moving any idle entry into active retirement
                // accounting. Every removed entry is immediately protected by
                // an armed guard, so panic or hard cancellation cannot strand
                // later entries in a raw vector.
                let mut retired = Vec::with_capacity(inner.idle.len());

                let action = if inner.closed {
                    AcquireAction::PoolClosed
                } else {
                    // Try to get an idle connection
                    let mut found_conn = None;
                    while let Some(mut meta) = inner.idle.pop_front() {
                        // Check if connection is too old
                        if meta.age() > max_lifetime {
                            inner.active_count += 1;
                            retired
                                .push(ActiveConnectionGuard::new(Arc::clone(&self.shared), meta));
                            continue;
                        }

                        // Check if connection has been idle too long
                        if meta.idle_time() > idle_timeout {
                            inner.active_count += 1;
                            retired
                                .push(ActiveConnectionGuard::new(Arc::clone(&self.shared), meta));
                            continue;
                        }

                        if !retired.is_empty() {
                            // Retire removed connections before selecting or
                            // reserving an active slot. Otherwise dropping the
                            // acquire future during an async retirement close
                            // would strand that selected slot forever.
                            inner.idle.push_front(meta);
                            break;
                        }

                        // Found a valid connection
                        meta.touch();
                        inner.active_count += 1;
                        found_conn = Some(meta);
                        break;
                    }

                    if !retired.is_empty() {
                        AcquireAction::RetireAndRetry
                    } else if let Some(meta) = found_conn {
                        AcquireAction::ValidateExisting(meta)
                    } else if inner.can_create_new() {
                        // No idle connections, can we create new?
                        inner.total_count += 1;
                        inner.active_count += 1;
                        AcquireAction::CreateNew
                    } else {
                        // Must wait
                        inner.waiter_count += 1;
                        AcquireAction::Wait
                    }
                };
                (action, retired)
            };

            // Teardown may perform driver I/O. Keep it outside the pool mutex
            // so one slow close cannot block returns, acquires, or shutdown.
            for guard in retired {
                match guard
                    .close(cx, "expired pooled connection retirement")
                    .await
                {
                    RetirementOutcome::Closed => {}
                    RetirementOutcome::Cancelled(reason) => {
                        return Outcome::Cancelled(reason);
                    }
                    RetirementOutcome::Failed(error) => return Outcome::Err(error),
                }
            }

            match action {
                AcquireAction::RetireAndRetry => {
                    continue;
                }
                AcquireAction::PoolClosed => {
                    return Outcome::Err(Error::Pool(PoolError {
                        kind: PoolErrorKind::Closed,
                        message: "pool has been closed".to_string(),
                        source: None,
                    }));
                }
                AcquireAction::ValidateExisting(meta) => {
                    // Validate and wrap the connection (lock is released)
                    return self.validate_and_wrap(cx, meta, test_on_checkout).await;
                }
                AcquireAction::CreateNew => {
                    // Create new connection outside of lock
                    let mut slot_guard = ActiveSlotGuard::new(Arc::clone(&self.shared));
                    match factory().await {
                        Outcome::Ok(conn) => {
                            self.shared
                                .connections_created
                                .fetch_add(1, Ordering::Relaxed);
                            let publish = match self.shared.lock_or_error("acquire_publish") {
                                Ok(inner) if inner.closed => {
                                    let retirement = ActiveConnectionGuard::new(
                                        Arc::clone(&self.shared),
                                        ConnectionMeta::new(conn),
                                    );
                                    slot_guard.disarm();
                                    FactoryPublish::Retire {
                                        guard: retirement,
                                        error: Error::Pool(PoolError {
                                            kind: PoolErrorKind::Closed,
                                            message: "pool has been closed".to_string(),
                                            source: None,
                                        }),
                                        context: "acquire publish after pool closure",
                                    }
                                }
                                Ok(_inner) => {
                                    // Disarming while still holding the pool
                                    // mutex is the admission publication point.
                                    // A close either precedes this check and
                                    // rejects the connection, or follows it and
                                    // waits for this active checkout.
                                    self.shared.acquires.fetch_add(1, Ordering::Relaxed);
                                    let meta = ConnectionMeta::new(conn);
                                    slot_guard.disarm();
                                    FactoryPublish::Published(PooledConnection::new(
                                        meta,
                                        Arc::downgrade(&self.shared),
                                    ))
                                }
                                Err(error) => {
                                    let retirement = ActiveConnectionGuard::new(
                                        Arc::clone(&self.shared),
                                        ConnectionMeta::new(conn),
                                    );
                                    slot_guard.disarm();
                                    FactoryPublish::Retire {
                                        guard: retirement,
                                        error,
                                        context: "acquire publish bookkeeping failure",
                                    }
                                }
                            };
                            match publish {
                                FactoryPublish::Published(pooled) => {
                                    return Outcome::Ok(pooled);
                                }
                                FactoryPublish::Retire {
                                    guard,
                                    error,
                                    context,
                                } => match guard.close(cx, context).await {
                                    RetirementOutcome::Closed => return Outcome::Err(error),
                                    RetirementOutcome::Cancelled(reason) => {
                                        return Outcome::Cancelled(reason);
                                    }
                                    RetirementOutcome::Failed(close_error) => {
                                        return Outcome::Err(close_error);
                                    }
                                },
                            }
                        }
                        Outcome::Err(e) => {
                            slot_guard.release("connection factory error");
                            return Outcome::Err(e);
                        }
                        Outcome::Cancelled(reason) => {
                            slot_guard.release("connection factory cancellation");
                            return Outcome::Cancelled(reason);
                        }
                        Outcome::Panicked(info) => {
                            slot_guard.release("connection factory panic");
                            return Outcome::Panicked(info);
                        }
                    }
                }
                AcquireAction::Wait => {
                    // Wait for a connection to become available
                    let remaining = deadline.saturating_duration_since(Instant::now());
                    if remaining.is_zero() {
                        if let Ok(mut inner) = self.shared.lock_or_error("acquire_timeout") {
                            inner.waiter_count -= 1;
                        }
                        self.shared.timeouts.fetch_add(1, Ordering::Relaxed);
                        return Outcome::Err(Error::Pool(PoolError {
                            kind: PoolErrorKind::Timeout,
                            message: "acquire timeout: no connections available".to_string(),
                            source: None,
                        }));
                    }

                    // Wait with timeout (use shorter interval for cancellation checks)
                    let wait_time = remaining.min(Duration::from_millis(100));
                    {
                        let inner = match self.shared.lock_or_error("acquire_wait") {
                            Ok(guard) => guard,
                            Err(e) => return Outcome::Err(e),
                        };
                        // wait_timeout can also return a poisoned error, handle it
                        let _ = self
                            .shared
                            .conn_available
                            .wait_timeout(inner, wait_time)
                            .map_err(|_| {
                                tracing::error!("Pool mutex poisoned during wait_timeout");
                            });
                    }

                    // Decrement waiter count after waking
                    {
                        if let Ok(mut inner) = self.shared.lock_or_error("acquire_wake") {
                            inner.waiter_count = inner.waiter_count.saturating_sub(1);
                        }
                    }

                    // Loop back to try again
                }
            }
        }
    }

    /// Validate a connection and wrap it in a PooledConnection.
    async fn validate_and_wrap(
        &self,
        cx: &Cx,
        meta: ConnectionMeta<C>,
        test_on_checkout: bool,
    ) -> Outcome<PooledConnection<C>, Error> {
        let guard = ActiveConnectionGuard::new(Arc::clone(&self.shared), meta);
        if test_on_checkout {
            // Validate the connection
            match guard.connection().ping(cx).await {
                Outcome::Ok(()) => {
                    self.shared.acquires.fetch_add(1, Ordering::Relaxed);
                    Outcome::Ok(PooledConnection::new(
                        guard.into_meta(),
                        Arc::downgrade(&self.shared),
                    ))
                }
                Outcome::Err(_) | Outcome::Cancelled(_) | Outcome::Panicked(_) => {
                    // Connection is invalid. Keep it active until explicit
                    // retirement completes so close-and-drain cannot return
                    // while the driver still owns the resource.
                    match guard
                        .close(cx, "pooled connection checkout validation failure")
                        .await
                    {
                        RetirementOutcome::Closed => {}
                        RetirementOutcome::Cancelled(reason) => {
                            return Outcome::Cancelled(reason);
                        }
                        RetirementOutcome::Failed(error) => return Outcome::Err(error),
                    }
                    // Return error - caller should retry
                    Outcome::Err(Error::Connection(ConnectionError {
                        kind: ConnectionErrorKind::Disconnected,
                        message: "connection validation failed".to_string(),
                        source: None,
                    }))
                }
            }
        } else {
            self.shared.acquires.fetch_add(1, Ordering::Relaxed);
            Outcome::Ok(PooledConnection::new(
                guard.into_meta(),
                Arc::downgrade(&self.shared),
            ))
        }
    }

    /// Remove every idle connection from admission and transfer it to active
    /// retirement accounting.
    ///
    /// `total_count` deliberately remains unchanged until each retirement
    /// guard has finished or been hard-dropped. This lets `close_and_drain`
    /// treat driver teardown as part of the quiescence boundary.
    fn begin_idle_retirement(&self) -> Vec<ActiveConnectionGuard<C>> {
        match self.shared.inner.lock() {
            Ok(mut inner) => {
                let mut retired = Vec::with_capacity(inner.idle.len());
                while let Some(meta) = inner.idle.pop_front() {
                    inner.active_count += 1;
                    retired.push(ActiveConnectionGuard::new(Arc::clone(&self.shared), meta));
                }
                retired
            }
            Err(_poisoned) => {
                tracing::error!(
                    "Pool mutex poisoned during idle retirement; \
                     idle connections cannot be retired safely"
                );
                Vec::new()
            }
        }
    }

    /// Atomically close admission and transfer all idle inventory to active
    /// retirement accounting.
    fn begin_close(&self) -> Vec<ActiveConnectionGuard<C>> {
        let retired = match self.shared.inner.lock() {
            Ok(mut inner) => {
                inner.closed = true;
                let mut retired = Vec::with_capacity(inner.idle.len());
                while let Some(meta) = inner.idle.pop_front() {
                    inner.active_count += 1;
                    retired.push(ActiveConnectionGuard::new(Arc::clone(&self.shared), meta));
                }
                retired
            }
            Err(poisoned) => {
                // Recover from poisoning - we still want to mark the pool as
                // closed and wake waiters even if counts may be inconsistent.
                tracing::error!(
                    "Pool mutex poisoned during close; attempting recovery. \
                     Pool state may be inconsistent."
                );
                let mut inner = poisoned.into_inner();
                inner.closed = true;
                let mut retired = Vec::with_capacity(inner.idle.len());
                while let Some(meta) = inner.idle.pop_front() {
                    inner.active_count += 1;
                    retired.push(ActiveConnectionGuard::new(Arc::clone(&self.shared), meta));
                }
                retired
            }
        };

        // Wake all waiters so they see the pool is closed
        self.shared.conn_available.notify_all();
        retired
    }

    fn close_retirements_blocking(
        &self,
        retired: Vec<ActiveConnectionGuard<C>>,
        context: &'static str,
    ) {
        for guard in retired {
            let runtime = match RuntimeBuilder::current_thread().build() {
                Ok(runtime) => runtime,
                Err(error) => {
                    tracing::warn!(
                        context,
                        error = %error,
                        "failed to build runtime while retiring pooled connection"
                    );
                    let error = Error::Custom(format!(
                        "failed to build runtime while retiring pooled connection: {error}"
                    ));
                    self.shared.record_retirement_failure(context, &error);
                    drop(guard);
                    continue;
                }
            };
            let cx = Cx::for_testing();
            let _ = runtime.block_on(guard.close(&cx, context));
        }
    }

    /// Close all currently idle connections.
    ///
    /// If the pool mutex is poisoned, this logs an error and leaves the idle
    /// inventory untouched because its accounting cannot be mutated safely.
    pub fn clear_idle(&self) {
        let retired = self.begin_idle_retirement();
        self.close_retirements_blocking(retired, "pool clear_idle");
    }

    /// Close the pool, preventing new connections and closing all idle connections.
    ///
    /// If the pool mutex is poisoned, this logs an error but still wakes waiters.
    pub fn close(&self) {
        let retired = self.begin_close();
        self.close_retirements_blocking(retired, "pool close");

        // Closing an already-empty pool is itself the one and only drain
        // transition. Accounted retirements set the latch when their final
        // guard releases.
        if self.shared.lock_or_recover().active_count == 0 {
            let _ = self.shared.active_drained.set(());
        }
    }

    /// Close the pool and wait for every pool-owned active connection to retire.
    ///
    /// Closing admission and removing idle inventory happen synchronously
    /// before this method first yields. Blocked acquirers are woken and observe
    /// [`PoolErrorKind::Closed`]. Connections already checked out are closed
    /// when returned; this future completes only after their explicit
    /// `close_for_pool` hooks finish and the active count reaches zero.
    ///
    /// The wait is cancellation- and deadline-aware through `cx`. Cancellation
    /// returns [`Outcome::Cancelled`] without reopening the pool: `closed`
    /// remains a one-way lifecycle transition, and a later caller may resume
    /// draining. Dropping this future has the same persistent-close property.
    ///
    /// Multiple concurrent drainers are supported by the pool's one-shot drain
    /// latch. Since pool closure is irreversible, there is no reopen generation
    /// whose notification could be confused with this drain cycle.
    ///
    /// Driver teardown failures are sticky and fail closed: the pool still
    /// retires every accounted resource, but this and every later drainer
    /// returns [`Outcome::Err`] after the active count reaches zero.
    ///
    /// A connection removed with [`PooledConnection::detach`] is caller-owned
    /// and is no longer part of pool accounting, so it is outside this drain
    /// guarantee.
    pub async fn close_and_drain(&self, cx: &Cx) -> Outcome<(), Error> {
        // The irreversible lifecycle transition and waiter wake happen before
        // any cancellation point. Idle inventory remains accounted as active
        // retirement work until each close hook or hard drop releases it.
        let retired = self.begin_close();
        let mut direct_failure = None;
        for guard in retired {
            match guard.close(cx, "pool close-and-drain").await {
                RetirementOutcome::Closed => {}
                RetirementOutcome::Cancelled(reason) => {
                    return Outcome::Cancelled(reason);
                }
                RetirementOutcome::Failed(error) => {
                    direct_failure.get_or_insert(error);
                }
            }
        }

        let poisoned_failure = match self.shared.inner.lock() {
            Ok(inner) => {
                drop(inner);
                None
            }
            Err(poisoned) => {
                let error = Error::Pool(PoolError::poisoned("close_and_drain"));
                self.shared
                    .record_retirement_failure("close_and_drain", &error);
                drop(poisoned.into_inner());
                Some(error)
            }
        };

        if self.shared.lock_or_recover().active_count == 0 {
            let _ = self.shared.active_drained.set(());
        }

        if self.shared.active_drained.wait(cx).await.is_ok() {
            if let Some(error) = direct_failure {
                Outcome::Err(error)
            } else if let Some(error) = poisoned_failure {
                Outcome::Err(error)
            } else if let Some(error) = self.shared.retirement_failure_error() {
                Outcome::Err(error)
            } else {
                Outcome::Ok(())
            }
        } else {
            let reason = cx
                .cancel_reason()
                .unwrap_or_else(|| CancelReason::user("pool drain cancelled"));
            Outcome::Cancelled(reason)
        }
    }

    /// Get the number of idle connections.
    #[must_use]
    pub fn idle_count(&self) -> usize {
        let inner = self.shared.lock_or_recover();
        inner.idle.len()
    }

    /// Get the number of active connections.
    #[must_use]
    pub fn active_count(&self) -> usize {
        let inner = self.shared.lock_or_recover();
        inner.active_count
    }

    /// Get the total number of connections.
    #[must_use]
    pub fn total_count(&self) -> usize {
        let inner = self.shared.lock_or_recover();
        inner.total_count
    }
}

impl<C: Connection> Drop for Pool<C> {
    fn drop(&mut self) {
        self.close();
    }
}

/// Action to take when acquiring a connection.
enum AcquireAction<C> {
    /// Expired idle connections were removed and must retire before retrying.
    RetireAndRetry,
    /// Pool is closed
    PoolClosed,
    /// Found an existing connection to validate
    ValidateExisting(ConnectionMeta<C>),
    /// Create a new connection
    CreateNew,
    /// Wait for a connection to become available
    Wait,
}

enum FactoryPublish<C: Connection> {
    Published(PooledConnection<C>),
    Retire {
        guard: ActiveConnectionGuard<C>,
        error: Error,
        context: &'static str,
    },
}

/// A connection borrowed from the pool.
///
/// When dropped, the connection is automatically returned to the pool.
/// The connection can be used via `Deref` and `DerefMut`.
pub struct PooledConnection<C: Connection> {
    /// The connection metadata (Some while held, None after return)
    meta: Option<ConnectionMeta<C>>,
    /// Weak reference to pool for returning
    pool: Weak<PoolShared<C>>,
}

impl<C: Connection> PooledConnection<C> {
    fn new(meta: ConnectionMeta<C>, pool: Weak<PoolShared<C>>) -> Self {
        Self {
            meta: Some(meta),
            pool,
        }
    }

    /// Detach this connection from the pool.
    ///
    /// The connection will not be returned to the pool when dropped.
    /// This is useful when you need to close a connection explicitly.
    pub fn detach(mut self) -> C {
        let conn = self.meta.take().expect("connection already detached").conn;
        if let Some(pool) = self.pool.upgrade() {
            pool.connections_closed.fetch_add(1, Ordering::Relaxed);
            pool.release_active_slot("pooled connection detach");
        }
        conn
    }

    /// Get the age of this connection (time since creation).
    #[must_use]
    pub fn age(&self) -> Duration {
        self.meta.as_ref().map_or(Duration::ZERO, |m| m.age())
    }

    /// Get the idle time of this connection (time since last use).
    #[must_use]
    pub fn idle_time(&self) -> Duration {
        self.meta.as_ref().map_or(Duration::ZERO, |m| m.idle_time())
    }
}

impl<C: Connection> std::ops::Deref for PooledConnection<C> {
    type Target = C;

    fn deref(&self) -> &Self::Target {
        &self
            .meta
            .as_ref()
            .expect("connection already returned to pool")
            .conn
    }
}

impl<C: Connection> std::ops::DerefMut for PooledConnection<C> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self
            .meta
            .as_mut()
            .expect("connection already returned to pool")
            .conn
    }
}

impl<C: Connection> Drop for PooledConnection<C> {
    fn drop(&mut self) {
        if let Some(mut meta) = self.meta.take() {
            meta.touch(); // Update last used time
            if let Some(pool) = self.pool.upgrade() {
                // Return to pool - but if mutex is poisoned, do not panic in
                // Drop. Close the resource, then recover only enough accounting
                // to prevent a drain waiter from being stranded.
                let mut inner = match pool.inner.lock() {
                    Ok(guard) => guard,
                    Err(poisoned) => {
                        // Release the poisoned guard before the close hook and
                        // poison-aware accounting transition reacquire state.
                        drop(poisoned);
                        tracing::error!(
                            "Pool mutex poisoned during connection return; \
                             connection will be closed instead of returned. A thread panicked while holding the lock."
                        );
                        let context = "pooled connection drop poisoned";
                        if let Err(error) = close_connection_blocking(meta.conn, context) {
                            pool.record_retirement_failure(context, &error);
                        }
                        pool.connections_closed.fetch_add(1, Ordering::Relaxed);
                        pool.release_active_slot(context);
                        return;
                    }
                };

                if inner.closed {
                    drop(inner);
                    let context = "pooled connection drop closed pool";
                    if let Err(error) = close_connection_blocking(meta.conn, context) {
                        pool.record_retirement_failure(context, &error);
                    }
                    pool.connections_closed.fetch_add(1, Ordering::Relaxed);
                    pool.release_active_slot("pooled connection drop closed pool");
                    return;
                }

                // Check max lifetime
                let max_lifetime = Duration::from_millis(inner.config.max_lifetime_ms);
                if meta.age() > max_lifetime {
                    drop(inner);
                    let context = "pooled connection drop max lifetime";
                    if let Err(error) = close_connection_blocking(meta.conn, context) {
                        pool.record_retirement_failure(context, &error);
                    }
                    pool.connections_closed.fetch_add(1, Ordering::Relaxed);
                    pool.release_active_slot("pooled connection drop max lifetime");
                    return;
                }

                inner.active_count -= 1;
                inner.idle.push_back(meta);

                drop(inner);
                pool.conn_available.notify_one();
            } else {
                let _ = close_connection_blocking(meta.conn, "pooled connection drop missing pool");
            }
        }
    }
}

impl<C: Connection + std::fmt::Debug> std::fmt::Debug for PooledConnection<C> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PooledConnection")
            .field("conn", &self.meta.as_ref().map(|m| &m.conn))
            .field("age", &self.age())
            .field("idle_time", &self.idle_time())
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use asupersync::{Budget, Time};
    use sqlmodel_core::connection::{IsolationLevel, PreparedStatement, TransactionOps};
    use sqlmodel_core::{Row, Value};
    use std::pin::Pin;
    use std::sync::atomic::{AtomicBool, AtomicUsize};
    use std::task::{Context, Poll, Wake, Waker};

    /// A mock connection for testing pool behavior.
    #[derive(Debug)]
    struct MockConnection {
        id: u32,
        ping_should_fail: Arc<AtomicBool>,
        /// Incremented each time the pool retires this connection via
        /// `close_for_pool` (as opposed to a caller-owned `close`).
        pool_close_calls: Arc<AtomicUsize>,
        /// When true, `close_for_pool` remains pending until its future is
        /// dropped. Used to prove slot guards across close await points.
        pool_close_pending: bool,
        /// When true, pool retirement returns a deterministic driver error.
        pool_close_should_fail: bool,
        /// Optional probe used to prove the pool mutex is not held while the
        /// retirement hook runs.
        pool_shared: Option<Weak<PoolShared<MockConnection>>>,
        pool_lock_was_free: Option<Arc<AtomicBool>>,
    }

    impl MockConnection {
        fn new(id: u32) -> Self {
            Self {
                id,
                ping_should_fail: Arc::new(AtomicBool::new(false)),
                pool_close_calls: Arc::new(AtomicUsize::new(0)),
                pool_close_pending: false,
                pool_close_should_fail: false,
                pool_shared: None,
                pool_lock_was_free: None,
            }
        }

        #[allow(dead_code)]
        fn with_ping_behavior(id: u32, should_fail: Arc<AtomicBool>) -> Self {
            Self {
                id,
                ping_should_fail: should_fail,
                pool_close_calls: Arc::new(AtomicUsize::new(0)),
                pool_close_pending: false,
                pool_close_should_fail: false,
                pool_shared: None,
                pool_lock_was_free: None,
            }
        }

        fn with_pool_close_counter(id: u32, pool_close_calls: Arc<AtomicUsize>) -> Self {
            Self {
                id,
                ping_should_fail: Arc::new(AtomicBool::new(false)),
                pool_close_calls,
                pool_close_pending: false,
                pool_close_should_fail: false,
                pool_shared: None,
                pool_lock_was_free: None,
            }
        }

        fn with_pool_close_probe(
            id: u32,
            pool_close_calls: Arc<AtomicUsize>,
            pool_shared: Weak<PoolShared<MockConnection>>,
            pool_lock_was_free: Arc<AtomicBool>,
        ) -> Self {
            Self {
                id,
                ping_should_fail: Arc::new(AtomicBool::new(false)),
                pool_close_calls,
                pool_close_pending: false,
                pool_close_should_fail: false,
                pool_shared: Some(pool_shared),
                pool_lock_was_free: Some(pool_lock_was_free),
            }
        }

        fn with_pending_pool_close(id: u32, pool_close_calls: Arc<AtomicUsize>) -> Self {
            Self {
                id,
                ping_should_fail: Arc::new(AtomicBool::new(false)),
                pool_close_calls,
                pool_close_pending: true,
                pool_close_should_fail: false,
                pool_shared: None,
                pool_lock_was_free: None,
            }
        }

        fn with_failing_pool_close(id: u32) -> Self {
            Self {
                id,
                ping_should_fail: Arc::new(AtomicBool::new(false)),
                pool_close_calls: Arc::new(AtomicUsize::new(0)),
                pool_close_pending: false,
                pool_close_should_fail: true,
                pool_shared: None,
                pool_lock_was_free: None,
            }
        }
    }

    /// Manually released connection factory used to put `acquire` exactly
    /// across the pool-close publication fence without timing sleeps.
    struct GatedFactory {
        ready: Arc<AtomicBool>,
        conn: Option<MockConnection>,
    }

    #[derive(Default)]
    struct WakeCounter {
        wakes: AtomicUsize,
    }

    impl Wake for WakeCounter {
        fn wake(self: Arc<Self>) {
            self.wakes.fetch_add(1, Ordering::Relaxed);
        }

        fn wake_by_ref(self: &Arc<Self>) {
            self.wakes.fetch_add(1, Ordering::Relaxed);
        }
    }

    impl Future for GatedFactory {
        type Output = Outcome<MockConnection, Error>;

        fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
            if self.ready.load(Ordering::Acquire) {
                Poll::Ready(Outcome::Ok(
                    self.conn
                        .take()
                        .expect("gated factory polled after completion"),
                ))
            } else {
                Poll::Pending
            }
        }
    }

    /// Mock transaction for MockConnection.
    struct MockTx;

    // These test doubles deliberately mirror the trait's async spelling; the
    // bodies are immediate because no real driver I/O occurs.
    #[allow(clippy::unused_async_trait_impl)]
    impl TransactionOps for MockTx {
        async fn query(&self, _cx: &Cx, _sql: &str, _params: &[Value]) -> Outcome<Vec<Row>, Error> {
            Outcome::Ok(vec![])
        }

        async fn query_one(
            &self,
            _cx: &Cx,
            _sql: &str,
            _params: &[Value],
        ) -> Outcome<Option<Row>, Error> {
            Outcome::Ok(None)
        }

        async fn execute(&self, _cx: &Cx, _sql: &str, _params: &[Value]) -> Outcome<u64, Error> {
            Outcome::Ok(0)
        }

        async fn savepoint(&self, _cx: &Cx, _name: &str) -> Outcome<(), Error> {
            Outcome::Ok(())
        }

        async fn rollback_to(&self, _cx: &Cx, _name: &str) -> Outcome<(), Error> {
            Outcome::Ok(())
        }

        async fn release(&self, _cx: &Cx, _name: &str) -> Outcome<(), Error> {
            Outcome::Ok(())
        }

        async fn commit(self, _cx: &Cx) -> Outcome<(), Error> {
            Outcome::Ok(())
        }

        async fn rollback(self, _cx: &Cx) -> Outcome<(), Error> {
            Outcome::Ok(())
        }
    }

    #[allow(clippy::unused_async_trait_impl)]
    impl Connection for MockConnection {
        type Tx<'conn> = MockTx;

        async fn query(&self, _cx: &Cx, _sql: &str, _params: &[Value]) -> Outcome<Vec<Row>, Error> {
            Outcome::Ok(vec![])
        }

        async fn query_one(
            &self,
            _cx: &Cx,
            _sql: &str,
            _params: &[Value],
        ) -> Outcome<Option<Row>, Error> {
            Outcome::Ok(None)
        }

        async fn execute(&self, _cx: &Cx, _sql: &str, _params: &[Value]) -> Outcome<u64, Error> {
            Outcome::Ok(0)
        }

        async fn insert(&self, _cx: &Cx, _sql: &str, _params: &[Value]) -> Outcome<i64, Error> {
            Outcome::Ok(0)
        }

        async fn batch(
            &self,
            _cx: &Cx,
            _statements: &[(String, Vec<Value>)],
        ) -> Outcome<Vec<u64>, Error> {
            Outcome::Ok(vec![])
        }

        async fn begin(&self, _cx: &Cx) -> Outcome<Self::Tx<'_>, Error> {
            Outcome::Ok(MockTx)
        }

        async fn begin_with(
            &self,
            _cx: &Cx,
            _isolation: IsolationLevel,
        ) -> Outcome<Self::Tx<'_>, Error> {
            Outcome::Ok(MockTx)
        }

        async fn prepare(&self, _cx: &Cx, _sql: &str) -> Outcome<PreparedStatement, Error> {
            Outcome::Ok(PreparedStatement::new(1, String::new(), 0))
        }

        async fn query_prepared(
            &self,
            _cx: &Cx,
            _stmt: &PreparedStatement,
            _params: &[Value],
        ) -> Outcome<Vec<Row>, Error> {
            Outcome::Ok(vec![])
        }

        async fn execute_prepared(
            &self,
            _cx: &Cx,
            _stmt: &PreparedStatement,
            _params: &[Value],
        ) -> Outcome<u64, Error> {
            Outcome::Ok(0)
        }

        async fn ping(&self, _cx: &Cx) -> Outcome<(), Error> {
            if self.ping_should_fail.load(Ordering::Relaxed) {
                Outcome::Err(Error::Connection(ConnectionError {
                    kind: ConnectionErrorKind::Disconnected,
                    message: "mock ping failed".to_string(),
                    source: None,
                }))
            } else {
                Outcome::Ok(())
            }
        }

        async fn close(self, _cx: &Cx) -> Result<(), Error> {
            Ok(())
        }

        async fn close_for_pool(self, _cx: &Cx) -> Result<(), Error> {
            if let (Some(pool_shared), Some(pool_lock_was_free)) =
                (self.pool_shared.as_ref(), self.pool_lock_was_free.as_ref())
            {
                let mutex_is_available = pool_shared
                    .upgrade()
                    .is_none_or(|shared| shared.inner.try_lock().is_ok());
                pool_lock_was_free.store(mutex_is_available, Ordering::Relaxed);
            }
            self.pool_close_calls.fetch_add(1, Ordering::Relaxed);
            if self.pool_close_pending {
                std::future::pending::<()>().await;
            }
            if self.pool_close_should_fail {
                return Err(Error::Custom("mock pool close failure".to_string()));
            }
            Ok(())
        }
    }

    #[test]
    fn test_config_default() {
        let config = PoolConfig::default();
        assert_eq!(config.min_connections, 1);
        assert_eq!(config.max_connections, 10);
        assert_eq!(config.idle_timeout_ms, 600_000);
        assert_eq!(config.acquire_timeout_ms, 30_000);
        assert_eq!(config.max_lifetime_ms, 1_800_000);
        assert!(config.test_on_checkout);
        assert!(!config.test_on_return);
    }

    #[test]
    fn test_config_builder() {
        let config = PoolConfig::new(20)
            .min_connections(5)
            .idle_timeout(60_000)
            .acquire_timeout(5_000)
            .max_lifetime(300_000)
            .test_on_checkout(false)
            .test_on_return(true);

        assert_eq!(config.min_connections, 5);
        assert_eq!(config.max_connections, 20);
        assert_eq!(config.idle_timeout_ms, 60_000);
        assert_eq!(config.acquire_timeout_ms, 5_000);
        assert_eq!(config.max_lifetime_ms, 300_000);
        assert!(!config.test_on_checkout);
        assert!(config.test_on_return);
    }

    #[test]
    fn test_config_clone() {
        let config = PoolConfig::new(15).min_connections(3);
        let cloned = config.clone();
        assert_eq!(config.max_connections, cloned.max_connections);
        assert_eq!(config.min_connections, cloned.min_connections);
    }

    #[test]
    fn test_stats_default() {
        let stats = PoolStats::default();
        assert_eq!(stats.total_connections, 0);
        assert_eq!(stats.idle_connections, 0);
        assert_eq!(stats.active_connections, 0);
        assert_eq!(stats.pending_requests, 0);
        assert_eq!(stats.connections_created, 0);
        assert_eq!(stats.connections_closed, 0);
        assert_eq!(stats.acquires, 0);
        assert_eq!(stats.timeouts, 0);
    }

    #[test]
    fn test_stats_clone() {
        let stats = PoolStats {
            total_connections: 5,
            acquires: 100,
            ..Default::default()
        };
        let cloned = stats.clone();
        assert_eq!(stats.total_connections, cloned.total_connections);
        assert_eq!(stats.acquires, cloned.acquires);
    }

    #[test]
    fn test_connection_meta_timing() {
        use std::thread;

        // Create a dummy type for testing
        struct DummyConn;

        let meta = ConnectionMeta::new(DummyConn);
        let initial_age = meta.age();

        // Small sleep to ensure time passes
        thread::sleep(Duration::from_millis(10));

        // Age should have increased
        assert!(meta.age() > initial_age);
        assert!(meta.idle_time() > Duration::ZERO);
    }

    #[test]
    fn test_connection_meta_touch() {
        use std::thread;

        struct DummyConn;

        let mut meta = ConnectionMeta::new(DummyConn);

        // Small sleep to build up some idle time
        thread::sleep(Duration::from_millis(10));
        let idle_before_touch = meta.idle_time();
        assert!(idle_before_touch > Duration::ZERO);

        // Touch should reset idle time
        meta.touch();
        let idle_after_touch = meta.idle_time();

        // After touch, idle time should be very small (less than before)
        assert!(idle_after_touch < idle_before_touch);
    }

    #[test]
    fn test_pool_new() {
        let config = PoolConfig::new(5);
        let pool: Pool<MockConnection> = Pool::new(config);

        // New pool should be empty
        assert_eq!(pool.idle_count(), 0);
        assert_eq!(pool.active_count(), 0);
        assert_eq!(pool.total_count(), 0);
        assert!(!pool.is_closed());
        assert!(!pool.at_capacity());
    }

    #[test]
    fn test_pool_config() {
        let config = PoolConfig::new(7).min_connections(2);
        let pool: Pool<MockConnection> = Pool::new(config);

        let retrieved_config = pool.config();
        assert_eq!(retrieved_config.max_connections, 7);
        assert_eq!(retrieved_config.min_connections, 2);
    }

    #[test]
    fn test_pool_stats_initial() {
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(5));

        let stats = pool.stats();
        assert_eq!(stats.total_connections, 0);
        assert_eq!(stats.idle_connections, 0);
        assert_eq!(stats.active_connections, 0);
        assert_eq!(stats.pending_requests, 0);
        assert_eq!(stats.connections_created, 0);
        assert_eq!(stats.connections_closed, 0);
        assert_eq!(stats.acquires, 0);
        assert_eq!(stats.timeouts, 0);
    }

    #[test]
    fn test_pool_close() {
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(5));

        assert!(!pool.is_closed());
        pool.close();
        assert!(pool.is_closed());
    }

    #[test]
    fn test_close_and_drain_zero_active_completes_immediately() {
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(5));
        let runtime = RuntimeBuilder::current_thread()
            .build()
            .expect("build test runtime");
        let cx = Cx::for_testing();

        let outcome = runtime.block_on(pool.close_and_drain(&cx));

        assert!(matches!(outcome, Outcome::Ok(())));
        assert!(pool.is_closed());
        assert_eq!(pool.active_count(), 0);
        assert_eq!(pool.total_count(), 0);
    }

    #[test]
    fn test_close_and_drain_surfaces_exact_idle_retirement_error() {
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(1));
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
            inner.idle.push_back(ConnectionMeta::new(
                MockConnection::with_failing_pool_close(1),
            ));
        }
        let runtime = RuntimeBuilder::current_thread()
            .build()
            .expect("build test runtime");
        let cx = Cx::for_testing();

        let outcome = runtime.block_on(pool.close_and_drain(&cx));

        match outcome {
            Outcome::Err(Error::Custom(message)) => {
                assert_eq!(message, "mock pool close failure");
            }
            other => panic!("expected exact driver close error, got {other:?}"),
        }
        assert!(pool.is_closed());
        assert_eq!(pool.active_count(), 0);
        assert_eq!(pool.total_count(), 0);

        let later_cx = Cx::for_testing();
        let later = runtime.block_on(pool.close_and_drain(&later_cx));
        match later {
            Outcome::Err(Error::Custom(message)) => {
                assert_eq!(
                    message,
                    "pool retirement failed: pool close-and-drain: mock pool close failure"
                );
            }
            other => panic!("expected persistent retirement error, got {other:?}"),
        }
    }

    #[test]
    fn test_checked_out_retirement_error_reaches_every_drainer() {
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(1));
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
            inner.active_count = 1;
        }
        let pooled = PooledConnection::new(
            ConnectionMeta::new(MockConnection::with_failing_pool_close(1)),
            Arc::downgrade(&pool.shared),
        );
        let first_cx = Cx::for_testing();
        let second_cx = Cx::for_testing();
        let mut first_drain = Box::pin(pool.close_and_drain(&first_cx));
        let mut second_drain = Box::pin(pool.close_and_drain(&second_cx));
        let mut task_cx = Context::from_waker(Waker::noop());

        assert!(matches!(
            first_drain.as_mut().poll(&mut task_cx),
            Poll::Pending
        ));
        assert!(matches!(
            second_drain.as_mut().poll(&mut task_cx),
            Poll::Pending
        ));

        drop(pooled);

        let first_message = match first_drain.as_mut().poll(&mut task_cx) {
            Poll::Ready(Outcome::Err(Error::Custom(message))) => message,
            other => panic!("first drainer did not fail closed: {other:?}"),
        };
        let second_message = match second_drain.as_mut().poll(&mut task_cx) {
            Poll::Ready(Outcome::Err(Error::Custom(message))) => message,
            other => panic!("second drainer did not fail closed: {other:?}"),
        };
        assert_eq!(first_message, second_message);
        assert_eq!(
            first_message,
            "pool retirement failed: pooled connection drop closed pool: \
             mock pool close failure"
        );
        assert!(pool.is_closed());
        assert_eq!(pool.active_count(), 0);
        assert_eq!(pool.total_count(), 0);
    }

    #[test]
    fn test_close_and_drain_waits_for_active_return_and_explicit_close() {
        let pool_close_calls = Arc::new(AtomicUsize::new(0));
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(1));
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
            inner.active_count = 1;
        }
        let pooled = PooledConnection::new(
            ConnectionMeta::new(MockConnection::with_pool_close_counter(
                1,
                Arc::clone(&pool_close_calls),
            )),
            Arc::downgrade(&pool.shared),
        );
        let cx = Cx::for_testing();
        let mut drain = Box::pin(pool.close_and_drain(&cx));
        let mut task_cx = Context::from_waker(Waker::noop());

        assert!(matches!(drain.as_mut().poll(&mut task_cx), Poll::Pending));
        assert!(pool.is_closed());
        assert_eq!(pool.active_count(), 1);
        assert_eq!(pool_close_calls.load(Ordering::Relaxed), 0);

        drop(pooled);

        assert_eq!(pool_close_calls.load(Ordering::Relaxed), 1);
        assert!(matches!(
            drain.as_mut().poll(&mut task_cx),
            Poll::Ready(Outcome::Ok(()))
        ));
        assert_eq!(pool.active_count(), 0);
        assert_eq!(pool.total_count(), 0);
    }

    #[test]
    fn test_close_and_drain_multiple_handles_and_drainers_share_final_wake() {
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(2));
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 2;
            inner.active_count = 2;
        }
        let first = PooledConnection::new(
            ConnectionMeta::new(MockConnection::new(1)),
            Arc::downgrade(&pool.shared),
        );
        let second = PooledConnection::new(
            ConnectionMeta::new(MockConnection::new(2)),
            Arc::downgrade(&pool.shared),
        );
        let first_cx = Cx::for_testing();
        let second_cx = Cx::for_testing();
        let mut first_drain = Box::pin(pool.close_and_drain(&first_cx));
        let mut second_drain = Box::pin(pool.close_and_drain(&second_cx));
        let mut task_cx = Context::from_waker(Waker::noop());

        assert!(matches!(
            first_drain.as_mut().poll(&mut task_cx),
            Poll::Pending
        ));
        assert!(matches!(
            second_drain.as_mut().poll(&mut task_cx),
            Poll::Pending
        ));

        drop(first);
        assert_eq!(pool.active_count(), 1);
        assert!(matches!(
            first_drain.as_mut().poll(&mut task_cx),
            Poll::Pending
        ));
        assert!(matches!(
            second_drain.as_mut().poll(&mut task_cx),
            Poll::Pending
        ));

        drop(second);
        assert_eq!(pool.active_count(), 0);
        assert!(matches!(
            first_drain.as_mut().poll(&mut task_cx),
            Poll::Ready(Outcome::Ok(()))
        ));
        assert!(matches!(
            second_drain.as_mut().poll(&mut task_cx),
            Poll::Ready(Outcome::Ok(()))
        ));
    }

    #[test]
    fn test_close_and_drain_cancellation_keeps_pool_closed() {
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(1));
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
            inner.active_count = 1;
        }
        let pooled = PooledConnection::new(
            ConnectionMeta::new(MockConnection::new(1)),
            Arc::downgrade(&pool.shared),
        );
        let cx = Cx::for_testing();
        let mut drain = Box::pin(pool.close_and_drain(&cx));
        let wake_counter = Arc::new(WakeCounter::default());
        let waker = Waker::from(Arc::clone(&wake_counter));
        let mut task_cx = Context::from_waker(&waker);

        assert!(matches!(drain.as_mut().poll(&mut task_cx), Poll::Pending));
        cx.set_cancel_requested(true);
        assert!(
            wake_counter.wakes.load(Ordering::Relaxed) > 0,
            "Cx cancellation must wake the registered close-and-drain waiter"
        );
        assert!(matches!(
            drain.as_mut().poll(&mut task_cx),
            Poll::Ready(Outcome::Cancelled(_))
        ));
        assert!(pool.is_closed());
        assert_eq!(pool.active_count(), 1);

        drop(drain);
        let resume_cx = Cx::for_testing();
        let mut resumed_drain = Box::pin(pool.close_and_drain(&resume_cx));
        let mut resumed_task_cx = Context::from_waker(Waker::noop());
        assert!(matches!(
            resumed_drain.as_mut().poll(&mut resumed_task_cx),
            Poll::Pending
        ));
        assert!(pool.is_closed());

        drop(pooled);
        assert!(matches!(
            resumed_drain.as_mut().poll(&mut resumed_task_cx),
            Poll::Ready(Outcome::Ok(()))
        ));
        assert!(pool.is_closed());
        assert_eq!(pool.active_count(), 0);
    }

    #[test]
    fn test_close_and_drain_expired_deadline_keeps_pool_closed() {
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(1));
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
            inner.active_count = 1;
        }
        let pooled = PooledConnection::new(
            ConnectionMeta::new(MockConnection::new(1)),
            Arc::downgrade(&pool.shared),
        );
        let cx = Cx::for_testing_with_budget(Budget::new().with_deadline(Time::ZERO));
        let mut drain = Box::pin(pool.close_and_drain(&cx));
        let mut task_cx = Context::from_waker(Waker::noop());

        assert!(matches!(
            drain.as_mut().poll(&mut task_cx),
            Poll::Ready(Outcome::Cancelled(_))
        ));
        assert!(pool.is_closed());
        assert_eq!(pool.active_count(), 1);

        drop(drain);
        drop(pooled);
        assert_eq!(pool.active_count(), 0);
    }

    #[test]
    fn test_dropped_in_flight_factory_releases_reserved_slot() {
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(1));
        let cx = Cx::for_testing();
        let mut acquire = Box::pin(pool.acquire(&cx, || {
            std::future::pending::<Outcome<MockConnection, Error>>()
        }));
        let mut task_cx = Context::from_waker(Waker::noop());

        assert!(matches!(acquire.as_mut().poll(&mut task_cx), Poll::Pending));
        assert_eq!(pool.active_count(), 1);
        assert_eq!(pool.total_count(), 1);

        drop(acquire);

        assert_eq!(pool.active_count(), 0);
        assert_eq!(pool.total_count(), 0);
    }

    #[test]
    fn test_dropped_multi_expired_idle_close_releases_all_retirement_slots() {
        let pool_close_calls = Arc::new(AtomicUsize::new(0));
        let pool: Pool<MockConnection> =
            Pool::new(PoolConfig::new(3).max_lifetime(1).test_on_checkout(false));
        let mut first_expired = ConnectionMeta::new(MockConnection::with_pending_pool_close(
            1,
            Arc::clone(&pool_close_calls),
        ));
        first_expired.created_at = Instant::now()
            .checked_sub(Duration::from_secs(1))
            .expect("one second must fit before the current instant");
        let mut second_expired = ConnectionMeta::new(MockConnection::with_pool_close_counter(
            2,
            Arc::clone(&pool_close_calls),
        ));
        second_expired.created_at = Instant::now()
            .checked_sub(Duration::from_secs(1))
            .expect("one second must fit before the current instant");
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 2;
            inner.idle.push_back(first_expired);
            inner.idle.push_back(second_expired);
        }
        let cx = Cx::for_testing();
        let mut acquire =
            Box::pin(pool.acquire(&cx, || async { Outcome::Ok(MockConnection::new(3)) }));
        let mut task_cx = Context::from_waker(Waker::noop());

        assert!(matches!(acquire.as_mut().poll(&mut task_cx), Poll::Pending));
        assert_eq!(pool_close_calls.load(Ordering::Relaxed), 1);
        assert_eq!(pool.active_count(), 2);
        assert_eq!(pool.total_count(), 2);

        let drain_cx = Cx::for_testing();
        let mut drain = Box::pin(pool.close_and_drain(&drain_cx));
        assert!(matches!(drain.as_mut().poll(&mut task_cx), Poll::Pending));

        drop(acquire);
        assert!(matches!(
            drain.as_mut().poll(&mut task_cx),
            Poll::Ready(Outcome::Ok(()))
        ));
        assert!(pool.is_closed());
        assert_eq!(pool.active_count(), 0);
        assert_eq!(pool.total_count(), 0);
    }

    #[test]
    fn test_dropped_pending_idle_drain_releases_resource_for_other_drainer() {
        let pool_close_calls = Arc::new(AtomicUsize::new(0));
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(1));
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
            inner.idle.push_back(ConnectionMeta::new(
                MockConnection::with_pending_pool_close(1, Arc::clone(&pool_close_calls)),
            ));
        }
        let first_cx = Cx::for_testing();
        let second_cx = Cx::for_testing();
        let mut first_drain = Box::pin(pool.close_and_drain(&first_cx));
        let mut second_drain = Box::pin(pool.close_and_drain(&second_cx));
        let mut task_cx = Context::from_waker(Waker::noop());

        assert!(matches!(
            first_drain.as_mut().poll(&mut task_cx),
            Poll::Pending
        ));
        assert!(pool.is_closed());
        assert_eq!(pool_close_calls.load(Ordering::Relaxed), 1);
        assert_eq!(pool.active_count(), 1);
        assert_eq!(pool.total_count(), 1);

        assert!(matches!(
            second_drain.as_mut().poll(&mut task_cx),
            Poll::Pending
        ));

        first_cx.set_cancel_requested(true);
        assert!(matches!(
            first_drain.as_mut().poll(&mut task_cx),
            Poll::Ready(Outcome::Cancelled(_))
        ));
        drop(first_drain);

        assert_eq!(pool.active_count(), 0);
        assert_eq!(pool.total_count(), 0);
        assert!(matches!(
            second_drain.as_mut().poll(&mut task_cx),
            Poll::Ready(Outcome::Ok(()))
        ));
        assert!(pool.is_closed());
    }

    #[test]
    fn test_dropped_validation_close_releases_armed_active_slot() {
        let pool_close_calls = Arc::new(AtomicUsize::new(0));
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(1).test_on_checkout(true));
        let failed = MockConnection::with_pending_pool_close(1, Arc::clone(&pool_close_calls));
        failed.ping_should_fail.store(true, Ordering::Relaxed);
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
            inner.idle.push_back(ConnectionMeta::new(failed));
        }
        let cx = Cx::for_testing();
        let mut acquire =
            Box::pin(pool.acquire(&cx, || async { Outcome::Ok(MockConnection::new(2)) }));
        let mut task_cx = Context::from_waker(Waker::noop());

        assert!(matches!(acquire.as_mut().poll(&mut task_cx), Poll::Pending));
        assert_eq!(pool_close_calls.load(Ordering::Relaxed), 1);
        assert_eq!(pool.active_count(), 1);
        assert_eq!(pool.total_count(), 1);

        pool.close();
        drop(acquire);

        assert_eq!(pool.active_count(), 0);
        assert_eq!(pool.total_count(), 0);
        let drain_cx = Cx::for_testing();
        let mut drain = Box::pin(pool.close_and_drain(&drain_cx));
        assert!(matches!(
            drain.as_mut().poll(&mut task_cx),
            Poll::Ready(Outcome::Ok(()))
        ));
    }

    #[test]
    fn test_in_flight_factory_cannot_publish_after_close() {
        let pool_close_calls = Arc::new(AtomicUsize::new(0));
        let factory_ready = Arc::new(AtomicBool::new(false));
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(1));
        let cx = Cx::for_testing();
        let mut acquire = Box::pin(pool.acquire(&cx, || GatedFactory {
            ready: Arc::clone(&factory_ready),
            conn: Some(MockConnection::with_pool_close_counter(
                1,
                Arc::clone(&pool_close_calls),
            )),
        }));
        let mut task_cx = Context::from_waker(Waker::noop());

        assert!(matches!(acquire.as_mut().poll(&mut task_cx), Poll::Pending));
        assert_eq!(pool.active_count(), 1);

        pool.close();
        factory_ready.store(true, Ordering::Release);

        assert!(matches!(
            acquire.as_mut().poll(&mut task_cx),
            Poll::Ready(Outcome::Err(Error::Pool(PoolError {
                kind: PoolErrorKind::Closed,
                ..
            })))
        ));
        assert_eq!(pool_close_calls.load(Ordering::Relaxed), 1);
        assert_eq!(pool.active_count(), 0);
        assert_eq!(pool.total_count(), 0);
    }

    #[test]
    fn test_close_wakes_blocked_acquirer_to_observe_closed_state() {
        use std::sync::mpsc;
        use std::thread;

        let pool = Arc::new(Pool::<MockConnection>::new(PoolConfig::new(1)));
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
            inner.active_count = 1;
        }
        let pooled = PooledConnection::new(
            ConnectionMeta::new(MockConnection::new(1)),
            Arc::downgrade(&pool.shared),
        );
        let waiting_pool = Arc::clone(&pool);
        let (started_tx, started_rx) = mpsc::sync_channel(0);
        let waiter = thread::spawn(move || {
            let runtime = RuntimeBuilder::current_thread()
                .build()
                .expect("build waiter runtime");
            let cx = Cx::for_testing();
            started_tx.send(()).expect("signal waiter start");
            matches!(
                runtime.block_on(
                    waiting_pool.acquire(&cx, || async { Outcome::Ok(MockConnection::new(2)) })
                ),
                Outcome::Err(Error::Pool(PoolError {
                    kind: PoolErrorKind::Closed,
                    ..
                }))
            )
        });
        started_rx.recv().expect("waiter thread should start");

        let mut observed_waiter = false;
        for _ in 0..100_000 {
            if pool.stats().pending_requests == 1 {
                observed_waiter = true;
                break;
            }
            thread::yield_now();
        }

        pool.close();
        let observed_closed = waiter.join().expect("waiter thread should not panic");
        drop(pooled);

        assert!(
            observed_waiter,
            "acquirer never registered as a pool waiter"
        );
        assert!(
            observed_closed,
            "blocked acquirer did not observe pool close"
        );
    }

    #[test]
    fn test_pool_close_routes_through_close_for_pool() {
        let pool_close_calls = Arc::new(AtomicUsize::new(0));
        let pool_lock_was_free = Arc::new(AtomicBool::new(false));
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(2));

        // Seed one idle connection whose `close_for_pool` override records
        // the call, proving pool teardown uses the driver's pool-close path
        // rather than the ordinary `close`.
        {
            let mut inner = pool
                .shared
                .inner
                .lock()
                .expect("pool mutex should not be poisoned");
            inner.total_count = 1;
            inner
                .idle
                .push_back(ConnectionMeta::new(MockConnection::with_pool_close_probe(
                    1,
                    Arc::clone(&pool_close_calls),
                    Arc::downgrade(&pool.shared),
                    Arc::clone(&pool_lock_was_free),
                )));
        }

        pool.close();

        assert!(pool.is_closed());
        assert_eq!(pool_close_calls.load(Ordering::Relaxed), 1);
        assert!(pool_lock_was_free.load(Ordering::Relaxed));
    }

    #[test]
    fn test_expired_idle_connection_routes_through_close_for_pool() {
        let pool_close_calls = Arc::new(AtomicUsize::new(0));
        let pool: Pool<MockConnection> =
            Pool::new(PoolConfig::new(2).max_lifetime(1).test_on_checkout(false));
        let mut expired = ConnectionMeta::new(MockConnection::with_pool_close_counter(
            1,
            Arc::clone(&pool_close_calls),
        ));
        expired.created_at = Instant::now()
            .checked_sub(Duration::from_secs(1))
            .expect("one second must fit before the current instant");
        {
            let mut inner = pool
                .shared
                .inner
                .lock()
                .expect("pool mutex should not be poisoned");
            inner.total_count = 1;
            inner.idle.push_back(expired);
        }

        let runtime = RuntimeBuilder::current_thread()
            .build()
            .expect("build test runtime");
        let cx = Cx::for_testing();
        let acquired =
            runtime.block_on(pool.acquire(&cx, || async { Outcome::Ok(MockConnection::new(2)) }));

        assert!(matches!(acquired, Outcome::Ok(_)));
        assert_eq!(pool_close_calls.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn test_failed_validation_routes_through_close_for_pool() {
        let pool_close_calls = Arc::new(AtomicUsize::new(0));
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(2).test_on_checkout(true));
        let failed = MockConnection::with_pool_close_counter(1, Arc::clone(&pool_close_calls));
        failed.ping_should_fail.store(true, Ordering::Relaxed);
        {
            let mut inner = pool
                .shared
                .inner
                .lock()
                .expect("pool mutex should not be poisoned");
            inner.total_count = 1;
            inner.idle.push_back(ConnectionMeta::new(failed));
        }

        let runtime = RuntimeBuilder::current_thread()
            .build()
            .expect("build test runtime");
        let cx = Cx::for_testing();
        let acquired =
            runtime.block_on(pool.acquire(&cx, || async { Outcome::Ok(MockConnection::new(2)) }));

        assert!(matches!(acquired, Outcome::Err(_)));
        assert_eq!(pool_close_calls.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn test_pool_inner_can_create_new() {
        let mut inner = PoolInner::<MockConnection>::new(PoolConfig::new(3));

        // Initially can create new
        assert!(inner.can_create_new());

        // At capacity
        inner.total_count = 3;
        assert!(!inner.can_create_new());

        // Below capacity again
        inner.total_count = 2;
        assert!(inner.can_create_new());

        // Closed pool
        inner.closed = true;
        assert!(!inner.can_create_new());
    }

    #[test]
    fn test_pool_inner_stats() {
        let mut inner = PoolInner::<MockConnection>::new(PoolConfig::new(10));

        inner.total_count = 5;
        inner.active_count = 3;
        inner.waiter_count = 2;
        inner
            .idle
            .push_back(ConnectionMeta::new(MockConnection::new(1)));
        inner
            .idle
            .push_back(ConnectionMeta::new(MockConnection::new(2)));

        let stats = inner.stats();
        assert_eq!(stats.total_connections, 5);
        assert_eq!(stats.idle_connections, 2);
        assert_eq!(stats.active_connections, 3);
        assert_eq!(stats.pending_requests, 2);
    }

    #[test]
    fn test_pooled_connection_age_and_idle_time() {
        use std::thread;

        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(5));

        // Properly initialize pool state as if acquire happened
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
            inner.active_count = 1;
        }

        let meta = ConnectionMeta::new(MockConnection::new(1));
        let pooled = PooledConnection::new(meta, Arc::downgrade(&pool.shared));

        // Should have some small positive age
        assert!(pooled.age() >= Duration::ZERO);

        thread::sleep(Duration::from_millis(5));
        assert!(pooled.age() > Duration::ZERO);
    }

    #[test]
    fn test_pooled_connection_detach() {
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(5));

        // Manually add a connection to simulate acquire
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
            inner.active_count = 1;
        }

        let meta = ConnectionMeta::new(MockConnection::new(42));
        let pooled = PooledConnection::new(meta, Arc::downgrade(&pool.shared));

        // Verify counts before detach
        assert_eq!(pool.total_count(), 1);
        assert_eq!(pool.active_count(), 1);

        // Detach returns the connection
        let conn = pooled.detach();
        assert_eq!(conn.id, 42);

        // After detach, counts should be decremented
        assert_eq!(pool.total_count(), 0);
        assert_eq!(pool.active_count(), 0);

        // connections_closed should be incremented
        let stats = pool.stats();
        assert_eq!(stats.connections_closed, 1);
    }

    #[test]
    fn test_pooled_connection_drop_returns_to_pool() {
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(5));

        // Manually set up pool state as if we acquired a connection
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
            inner.active_count = 1;
        }

        let meta = ConnectionMeta::new(MockConnection::new(1));
        let pooled = PooledConnection::new(meta, Arc::downgrade(&pool.shared));

        // While held, active=1, idle=0
        assert_eq!(pool.active_count(), 1);
        assert_eq!(pool.idle_count(), 0);

        // Drop the connection
        drop(pooled);

        // After drop, active=0, idle=1 (returned to pool)
        assert_eq!(pool.active_count(), 0);
        assert_eq!(pool.idle_count(), 1);
        assert_eq!(pool.total_count(), 1); // Total unchanged
    }

    #[test]
    fn test_pooled_connection_drop_when_pool_closed() {
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(5));

        // Set up pool state
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
            inner.active_count = 1;
        }

        let meta = ConnectionMeta::new(MockConnection::new(1));
        let pooled = PooledConnection::new(meta, Arc::downgrade(&pool.shared));

        // Close the pool while connection is out
        pool.close();

        // Drop the connection
        drop(pooled);

        // Connection should not be returned to idle (pool is closed)
        assert_eq!(pool.idle_count(), 0);
        assert_eq!(pool.active_count(), 0);
        assert_eq!(pool.total_count(), 0);

        // Connection was closed
        assert_eq!(pool.stats().connections_closed, 1);
    }

    #[test]
    fn test_pooled_connection_deref() {
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(5));

        // Properly initialize pool state as if acquire happened
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
            inner.active_count = 1;
        }

        let meta = ConnectionMeta::new(MockConnection::new(99));
        let pooled = PooledConnection::new(meta, Arc::downgrade(&pool.shared));

        // Deref should give access to the connection's id
        assert_eq!(pooled.id, 99);
    }

    #[test]
    fn test_pooled_connection_deref_mut() {
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(5));

        // Properly initialize pool state as if acquire happened
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
            inner.active_count = 1;
        }

        let meta = ConnectionMeta::new(MockConnection::new(1));
        let mut pooled = PooledConnection::new(meta, Arc::downgrade(&pool.shared));

        // DerefMut should allow mutation
        pooled.id = 50;
        assert_eq!(pooled.id, 50);
    }

    #[test]
    fn test_pooled_connection_debug() {
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(5));

        // Properly initialize pool state as if acquire happened
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
            inner.active_count = 1;
        }

        let meta = ConnectionMeta::new(MockConnection::new(1));
        let pooled = PooledConnection::new(meta, Arc::downgrade(&pool.shared));

        let debug_str = format!("{:?}", pooled);
        assert!(debug_str.contains("PooledConnection"));
        assert!(debug_str.contains("age"));
    }

    #[test]
    fn test_pool_at_capacity() {
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(2));

        assert!(!pool.at_capacity());

        // Simulate connections being created
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
        }
        assert!(!pool.at_capacity());

        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 2;
        }
        assert!(pool.at_capacity());
    }

    #[test]
    fn test_acquire_action_enum() {
        // Verify the enum variants exist and can be pattern-matched
        let retire: AcquireAction<MockConnection> = AcquireAction::RetireAndRetry;
        assert!(matches!(retire, AcquireAction::RetireAndRetry));

        let closed: AcquireAction<MockConnection> = AcquireAction::PoolClosed;
        assert!(matches!(closed, AcquireAction::PoolClosed));

        let create: AcquireAction<MockConnection> = AcquireAction::CreateNew;
        assert!(matches!(create, AcquireAction::CreateNew));

        let wait: AcquireAction<MockConnection> = AcquireAction::Wait;
        assert!(matches!(wait, AcquireAction::Wait));

        let meta = ConnectionMeta::new(MockConnection::new(1));
        let validate: AcquireAction<MockConnection> = AcquireAction::ValidateExisting(meta);
        assert!(matches!(validate, AcquireAction::ValidateExisting(_)));
    }

    #[test]
    fn test_pool_shared_atomic_counters() {
        let shared = PoolShared::<MockConnection>::new(PoolConfig::new(5));

        // Initial values should be 0
        assert_eq!(shared.connections_created.load(Ordering::Relaxed), 0);
        assert_eq!(shared.connections_closed.load(Ordering::Relaxed), 0);
        assert_eq!(shared.acquires.load(Ordering::Relaxed), 0);
        assert_eq!(shared.timeouts.load(Ordering::Relaxed), 0);

        // Test incrementing
        shared.connections_created.fetch_add(1, Ordering::Relaxed);
        shared.connections_closed.fetch_add(2, Ordering::Relaxed);
        shared.acquires.fetch_add(10, Ordering::Relaxed);
        shared.timeouts.fetch_add(3, Ordering::Relaxed);

        assert_eq!(shared.connections_created.load(Ordering::Relaxed), 1);
        assert_eq!(shared.connections_closed.load(Ordering::Relaxed), 2);
        assert_eq!(shared.acquires.load(Ordering::Relaxed), 10);
        assert_eq!(shared.timeouts.load(Ordering::Relaxed), 3);
    }

    #[test]
    fn test_pool_close_clears_idle() {
        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(5));

        // Add some idle connections
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 3;
            inner
                .idle
                .push_back(ConnectionMeta::new(MockConnection::new(1)));
            inner
                .idle
                .push_back(ConnectionMeta::new(MockConnection::new(2)));
            inner
                .idle
                .push_back(ConnectionMeta::new(MockConnection::new(3)));
        }

        assert_eq!(pool.idle_count(), 3);
        assert_eq!(pool.total_count(), 3);

        pool.close();

        // After close, idle connections should be cleared
        assert_eq!(pool.idle_count(), 0);
        assert_eq!(pool.total_count(), 0);
        assert!(pool.is_closed());

        // connections_closed should reflect the 3 idle connections
        assert_eq!(pool.stats().connections_closed, 3);
    }

    // ==================== Lock Poisoning Safety Tests ====================
    //
    // These tests verify that the pool correctly handles mutex poisoning,
    // which occurs when a thread panics while holding the lock.
    //
    // Tier 1 (mutations): Return Error if poisoned
    // Tier 2 (read-only): Recover and return valid data
    // Tier 3 (Drop): Log, close, and recover drain accounting (don't panic)

    /// Helper to poison a pool's mutex by panicking while holding the lock.
    ///
    /// Returns the pool with a poisoned mutex.
    fn poison_pool_mutex() -> Pool<MockConnection> {
        use std::panic;
        use std::thread;

        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(5));

        // Set up some valid state before poisoning
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 2;
            inner.active_count = 1;
            inner
                .idle
                .push_back(ConnectionMeta::new(MockConnection::new(1)));
        }

        // Spawn a thread that will panic while holding the lock
        let shared_clone = Arc::clone(&pool.shared);
        let handle = thread::spawn(move || {
            let _guard = shared_clone.inner.lock().unwrap();
            // Panic while holding the lock - this poisons the mutex
            panic!("intentional panic to poison mutex");
        });

        // Wait for the thread to panic (ignore the panic result)
        let _ = handle.join();

        // Verify the mutex is now poisoned
        assert!(pool.shared.inner.lock().is_err());

        pool
    }

    // -------------------- Tier 2: Read-Only Methods --------------------

    #[test]
    fn test_config_after_poisoning_returns_valid_data() {
        let pool = poison_pool_mutex();

        // config() should recover and return the configuration
        let config = pool.config();
        assert_eq!(config.max_connections, 5);
    }

    #[test]
    fn test_stats_after_poisoning_returns_valid_data() {
        let pool = poison_pool_mutex();

        // stats() should recover and return valid statistics
        let stats = pool.stats();
        // The state before poisoning was: total=2, active=1, idle=1
        assert_eq!(stats.total_connections, 2);
        assert_eq!(stats.active_connections, 1);
        assert_eq!(stats.idle_connections, 1);
    }

    #[test]
    fn test_at_capacity_after_poisoning() {
        let pool = poison_pool_mutex();

        // at_capacity() should recover and return correct value
        // Pool has 2 connections, max is 5, so not at capacity
        assert!(!pool.at_capacity());
    }

    #[test]
    fn test_is_closed_after_poisoning() {
        let pool = poison_pool_mutex();

        // is_closed() should recover and return correct value
        assert!(!pool.is_closed());
    }

    #[test]
    fn test_idle_count_after_poisoning() {
        let pool = poison_pool_mutex();

        // idle_count() should recover and return correct value
        assert_eq!(pool.idle_count(), 1);
    }

    #[test]
    fn test_active_count_after_poisoning() {
        let pool = poison_pool_mutex();

        // active_count() should recover and return correct value
        assert_eq!(pool.active_count(), 1);
    }

    #[test]
    fn test_total_count_after_poisoning() {
        let pool = poison_pool_mutex();

        // total_count() should recover and return correct value
        assert_eq!(pool.total_count(), 2);
    }

    // -------------------- Tier 1: Mutation Methods --------------------

    #[test]
    fn test_lock_or_error_returns_error_when_poisoned() {
        use std::thread;

        let shared = Arc::new(PoolShared::<MockConnection>::new(PoolConfig::new(5)));

        // Poison the mutex
        let shared_clone = Arc::clone(&shared);
        let handle = thread::spawn(move || {
            let _guard = shared_clone.inner.lock().unwrap();
            panic!("intentional panic to poison mutex");
        });
        let _ = handle.join();

        // lock_or_error should return an error
        let result = shared.lock_or_error("test_operation");

        // Verify it's a pool poisoning error
        match result {
            Err(Error::Pool(pool_err)) => {
                assert!(matches!(pool_err.kind, PoolErrorKind::Poisoned));
                assert!(pool_err.message.contains("poisoned"));
            }
            Err(other) => panic!("Expected Pool error, got: {:?}", other),
            Ok(_) => panic!("Expected error, got Ok"),
        }
    }

    #[test]
    fn test_lock_or_recover_succeeds_when_poisoned() {
        use std::thread;

        let shared = Arc::new(PoolShared::<MockConnection>::new(PoolConfig::new(5)));

        // Set up some state
        {
            let mut inner = shared.inner.lock().unwrap();
            inner.total_count = 42;
        }

        // Poison the mutex
        let shared_clone = Arc::clone(&shared);
        let handle = thread::spawn(move || {
            let _guard = shared_clone.inner.lock().unwrap();
            panic!("intentional panic to poison mutex");
        });
        let _ = handle.join();

        // Verify mutex is poisoned
        assert!(shared.inner.lock().is_err());

        // lock_or_recover should still succeed and provide access to data
        let inner = shared.lock_or_recover();
        assert_eq!(inner.total_count, 42);
    }

    #[test]
    fn test_close_after_poisoning_recovers_and_closes() {
        let pool = poison_pool_mutex();

        // close() should recover from poisoning and still close the pool
        pool.close();

        // After close, the pool should be marked as closed
        assert!(pool.is_closed());

        // Idle connections should be cleared
        assert_eq!(pool.idle_count(), 0);
    }

    #[test]
    fn test_poisoned_pool_return_completes_drain_accounting() {
        use std::thread;

        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(1));
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
            inner.active_count = 1;
        }
        let pooled = PooledConnection::new(
            ConnectionMeta::new(MockConnection::new(1)),
            Arc::downgrade(&pool.shared),
        );

        let shared = Arc::clone(&pool.shared);
        let poisoner = thread::spawn(move || {
            let _guard = shared.inner.lock().unwrap();
            panic!("intentional panic to poison drain accounting");
        });
        let _ = poisoner.join();

        let cx = Cx::for_testing();
        let mut drain = Box::pin(pool.close_and_drain(&cx));
        let mut task_cx = Context::from_waker(Waker::noop());

        assert!(matches!(drain.as_mut().poll(&mut task_cx), Poll::Pending));
        assert!(pool.is_closed());
        assert_eq!(pool.active_count(), 1);

        drop(pooled);

        assert_eq!(pool.active_count(), 0);
        assert_eq!(pool.total_count(), 0);
        assert!(
            pool.shared.active_drained.get().is_some(),
            "poison-aware final release must publish the drain latch"
        );
        assert!(matches!(
            drain.as_mut().poll(&mut task_cx),
            Poll::Ready(Outcome::Err(Error::Pool(PoolError {
                kind: PoolErrorKind::Poisoned,
                ..
            })))
        ));
    }

    // -------------------- Tier 3: Drop Safety --------------------

    #[test]
    fn test_drop_pooled_connection_after_poisoning_does_not_panic() {
        use std::panic;
        use std::thread;

        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(5));

        // Set up a connection that's "checked out"
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
            inner.active_count = 1;
        }

        // Create a pooled connection
        let meta = ConnectionMeta::new(MockConnection::new(1));
        let pooled = PooledConnection::new(meta, Arc::downgrade(&pool.shared));

        // Poison the mutex by panicking in another thread
        let shared_clone = Arc::clone(&pool.shared);
        let handle = thread::spawn(move || {
            let _guard = shared_clone.inner.lock().unwrap();
            panic!("intentional panic to poison mutex");
        });
        let _ = handle.join();

        // Verify mutex is poisoned
        assert!(pool.shared.inner.lock().is_err());

        // Drop the pooled connection - should NOT panic
        // The connection will be leaked, but that's the correct behavior
        let drop_result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
            drop(pooled);
        }));

        // Dropping should not panic
        assert!(
            drop_result.is_ok(),
            "Dropping PooledConnection after mutex poisoning should not panic"
        );
    }

    #[test]
    fn test_detach_after_poisoning_does_not_panic() {
        use std::panic;
        use std::thread;

        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(5));

        // Set up a connection that's "checked out"
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 1;
            inner.active_count = 1;
        }

        // Create a pooled connection
        let meta = ConnectionMeta::new(MockConnection::new(42));
        let pooled = PooledConnection::new(meta, Arc::downgrade(&pool.shared));

        // Poison the mutex
        let shared_clone = Arc::clone(&pool.shared);
        let handle = thread::spawn(move || {
            let _guard = shared_clone.inner.lock().unwrap();
            panic!("intentional panic to poison mutex");
        });
        let _ = handle.join();

        // Verify mutex is poisoned
        assert!(pool.shared.inner.lock().is_err());

        // Detach should not panic, even though it can't update counters
        let detach_result = panic::catch_unwind(panic::AssertUnwindSafe(|| pooled.detach()));

        assert!(
            detach_result.is_ok(),
            "detach() after mutex poisoning should not panic"
        );

        // Should still get the connection back
        let conn = detach_result.unwrap();
        assert_eq!(conn.id, 42);
    }

    // -------------------- Integration: Pool Survives Thread Panic --------------------

    #[test]
    fn test_pool_survives_thread_panic_during_acquire() {
        use std::thread;

        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(5));
        let pool_arc = Arc::new(pool);

        // Simulate a thread that acquires, does work, then panics
        // The connection should be leaked but pool should remain usable for reads
        let pool_clone = Arc::clone(&pool_arc);
        let handle = thread::spawn(move || {
            // Manually simulate having acquired a connection
            {
                let mut inner = pool_clone.shared.inner.lock().unwrap();
                inner.total_count = 1;
                inner.active_count = 1;
            }

            // Panic while holding the pool's internal mutex to simulate a poisoned lock.
            // This models an internal panic in pool bookkeeping, not user code.
            let _guard = pool_clone.shared.inner.lock().unwrap();
            panic!("simulated panic during database operation");
        });

        // Wait for thread to panic
        let _ = handle.join();

        // Pool's mutex is now poisoned, but read-only methods should still work
        assert_eq!(pool_arc.total_count(), 1);
        assert_eq!(pool_arc.config().max_connections, 5);

        // Stats should be recoverable
        let stats = pool_arc.stats();
        assert_eq!(stats.total_connections, 1);
    }

    #[test]
    fn test_pool_close_after_thread_panic() {
        use std::thread;

        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(5));

        // Add some idle connections
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.total_count = 2;
            inner
                .idle
                .push_back(ConnectionMeta::new(MockConnection::new(1)));
            inner
                .idle
                .push_back(ConnectionMeta::new(MockConnection::new(2)));
        }

        // Poison the mutex
        let shared_clone = Arc::clone(&pool.shared);
        let handle = thread::spawn(move || {
            let _guard = shared_clone.inner.lock().unwrap();
            panic!("intentional panic");
        });
        let _ = handle.join();

        // close() should recover and still work
        pool.close();

        // Pool should be closed and idle connections cleared
        assert!(pool.is_closed());
        assert_eq!(pool.idle_count(), 0);
    }

    #[test]
    fn test_multiple_reads_after_poisoning() {
        let pool = poison_pool_mutex();

        // Multiple read operations should all succeed
        for _ in 0..10 {
            let _ = pool.config();
            let _ = pool.stats();
            let _ = pool.at_capacity();
            let _ = pool.is_closed();
            let _ = pool.idle_count();
            let _ = pool.active_count();
            let _ = pool.total_count();
        }

        // All reads should have recovered successfully
        assert_eq!(pool.total_count(), 2);
    }

    #[test]
    fn test_waiters_count_after_poisoning() {
        use std::thread;

        let pool: Pool<MockConnection> = Pool::new(PoolConfig::new(5));

        // Set up waiter count
        {
            let mut inner = pool.shared.inner.lock().unwrap();
            inner.waiter_count = 3;
        }

        // Poison the mutex
        let shared_clone = Arc::clone(&pool.shared);
        let handle = thread::spawn(move || {
            let _guard = shared_clone.inner.lock().unwrap();
            panic!("intentional panic");
        });
        let _ = handle.join();

        // stats() should recover and show correct waiter count
        let stats = pool.stats();
        assert_eq!(stats.pending_requests, 3);
    }
}