asupersync 0.3.1

Spec-first, cancel-correct, capability-secure async runtime for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
//! Cancel-safe resource pooling with obligation-based return semantics.
//!
//! This module provides a generic resource pooling framework that integrates with
//! asupersync's cancel-safety guarantees. Resources are managed through an
//! obligation-based contract: when a [`PooledResource`] is dropped (or explicitly
//! returned), the underlying resource is automatically sent back to the pool.
//!
//! # Getting Started
//!
//! ## Using the Generic Pool
//!
//! The easiest way to create a pool is with [`GenericPool`] and a factory function:
//!
//! ```ignore
//! use asupersync::sync::{GenericPool, Pool, PoolConfig};
//!
//! // Create a factory that produces resources
//! let factory = || Box::pin(async {
//!     Ok(TcpStream::connect("localhost:5432").await?)
//! });
//!
//! // Create pool with configuration
//! let pool = GenericPool::new(factory, PoolConfig::default());
//!
//! // Acquire and use a resource
//! async fn example(cx: &Cx, pool: &impl Pool<Resource = TcpStream>) {
//!     let conn = pool.acquire(cx).await?;
//!     conn.write_all(b"SELECT 1").await?;
//!     conn.return_to_pool();  // Or just drop - both work!
//! }
//! ```
//!
//! ## Implementing the Pool Trait
//!
//! For custom pool implementations, implement the [`Pool`] trait:
//!
//! ```ignore
//! use asupersync::sync::{Pool, PooledResource, PoolStats, PoolFuture, PoolReturnSender};
//! use asupersync::Cx;
//! use std::sync::mpsc;
//!
//! struct MyPool {
//!     return_tx: PoolReturnSender<Vec<u8>>,
//! }
//!
//! impl Pool for MyPool {
//!     type Resource = Vec<u8>;
//!     type Error = std::io::Error;
//!
//!     fn acquire<'a>(&'a self, cx: &'a Cx) -> PoolFuture<'a, Result<PooledResource<Self::Resource>, Self::Error>> {
//!         let resource = vec![0u8; 128];
//!         let pooled = PooledResource::new(resource, self.return_tx.clone());
//!         Box::pin(async move { Ok(pooled) })
//!     }
//!
//!     fn try_acquire(&self) -> Option<PooledResource<Self::Resource>> {
//!         Some(PooledResource::new(vec![0u8; 128], self.return_tx.clone()))
//!     }
//!
//!     fn stats(&self) -> PoolStats { PoolStats::default() }
//!
//!     fn close(&self) -> PoolFuture<'_, ()> {
//!         Box::pin(async move { })
//!     }
//! }
//! ```
//!
//! # Configuration Guide
//!
//! [`PoolConfig`] provides fine-grained control over pool behavior:
//!
//! | Option | Default | Description |
//! |--------|---------|-------------|
//! | `min_size` | 1 | Minimum resources to keep in pool |
//! | `max_size` | 10 | Maximum total resources |
//! | `acquire_timeout` | 30s | Timeout for acquire operations |
//! | `idle_timeout` | 600s | Max time a resource can be idle |
//! | `max_lifetime` | 3600s | Max lifetime of a resource |
//!
//! ```ignore
//! let config = PoolConfig::with_max_size(20)
//!     .min_size(5)
//!     .acquire_timeout(Duration::from_secs(10))
//!     .idle_timeout(Duration::from_secs(300))
//!     .max_lifetime(Duration::from_secs(1800));
//! ```
//!
//! # Cancel-Safety Patterns
//!
//! The pool is designed for cancel-safety at every phase:
//!
//! ## Cancellation During Wait
//!
//! If a task is cancelled while waiting for a resource (pool at capacity),
//! no resource is leaked. The waiter is simply removed from the queue.
//!
//! ## Cancellation While Holding
//!
//! If a task is cancelled while holding a resource, the [`PooledResource`]'s
//! [`Drop`] implementation ensures the resource is returned to the pool:
//!
//! ```ignore
//! async fn risky_operation(cx: &Cx, pool: &DbPool) -> Result<Data> {
//!     let conn = pool.acquire(cx).await?;
//!
//!     // Even if this panics or cx is cancelled, conn will be returned!
//!     let data = conn.query("SELECT * FROM users").await?;
//!
//!     // Explicit return is optional but recommended for clarity
//!     conn.return_to_pool();
//!     Ok(data)
//! }
//! ```
//!
//! ## Discarding Broken Resources
//!
//! If a resource becomes broken (connection error, invalid state), use
//! [`PooledResource::discard()`] to remove it from the pool rather than
//! returning it:
//!
//! ```ignore
//! async fn handle_connection(conn: PooledResource<TcpStream>) {
//!     match conn.write_all(b"PING").await {
//!         Ok(_) => conn.return_to_pool(),
//!         Err(_) => conn.discard(),  // Don't return broken connections
//!     }
//! }
//! ```
//!
//! ## Obligation Tracking
//!
//! The pool uses an obligation-based model. Once you acquire a resource,
//! you have an "obligation" to return it. This obligation is automatically
//! discharged by either:
//!
//! 1. Calling [`return_to_pool()`](PooledResource::return_to_pool)
//! 2. Calling [`discard()`](PooledResource::discard)
//! 3. Dropping the [`PooledResource`] (implicit return)
//!
//! The obligation prevents double-return bugs and ensures resources
//! are always accounted for.
//!
//! # Metrics and Monitoring
//!
//! Use [`Pool::stats()`] to monitor pool health:
//!
//! ```ignore
//! let stats = pool.stats();
//!
//! tracing::info!(
//!     active = stats.active,
//!     idle = stats.idle,
//!     total = stats.total,
//!     max_size = stats.max_size,
//!     waiters = stats.waiters,
//!     acquisitions = stats.total_acquisitions,
//!     "Pool health check"
//! );
//!
//! // Alert if pool is starved
//! if stats.waiters > 10 {
//!     tracing::warn!(waiters = stats.waiters, "Pool congestion detected");
//! }
//!
//! // Alert if utilization is high
//! let utilization = stats.active as f64 / stats.max_size as f64;
//! if utilization > 0.9 {
//!     tracing::warn!(utilization = %format!("{:.0}%", utilization * 100.0), "Pool near capacity");
//! }
//! ```
//!
//! ## Key Metrics
//!
//! | Metric | Meaning |
//! |--------|---------|
//! | `active` | Resources currently held by tasks |
//! | `idle` | Resources waiting to be used |
//! | `total` | Total resources (active + idle) |
//! | `waiters` | Tasks blocked waiting for resources |
//! | `total_acquisitions` | Lifetime acquisition count |
//! | `total_wait_time` | Cumulative wait time |
//!
//! # Troubleshooting
//!
//! ## Pool Exhaustion
//!
//! If `waiters` is high and `total == max_size`, consider:
//! - Increasing `max_size`
//! - Reducing hold time (return resources faster)
//! - Adding circuit breakers to prevent cascading failures
//!
//! ## Resource Leaks
//!
//! If `total` grows but `idle` stays low, resources may be:
//! - Held too long (check `held_duration()`)
//! - Not being returned properly (ensure `return_to_pool()` or drop is called)
//!
//! ## Stale Resources
//!
//! If connections are timing out, consider:
//! - Reducing `idle_timeout` to evict stale resources faster
//! - Reducing `max_lifetime` to force refresh
//! - Adding health checks before returning resources to pool

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::task::{Context, Poll, Waker};
use std::time::{Duration, Instant};

use parking_lot::Mutex as PoolMutex;
use smallvec::SmallVec;

use crate::cx::Cx;

fn wall_clock_now() -> Instant {
    Instant::now()
}

/// Boxed future helper for async trait-like APIs.
pub type PoolFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// Sender used to return resources back to a pool.
pub type PoolReturnSender<R> = mpsc::Sender<PoolReturn<R>>;

/// Receiver used to observe resources returning to a pool.
pub type PoolReturnReceiver<R> = mpsc::Receiver<PoolReturn<R>>;

type ReturnWakerEntry = (u64, Waker);
type ReturnWakerList = SmallVec<[ReturnWakerEntry; 4]>;
type ReturnWakers = Arc<PoolMutex<ReturnWakerList>>;

/// Trait for resource pools with cancel-safe acquisition.
pub trait Pool: Send + Sync {
    /// The type of resource managed by this pool.
    type Resource: Send;

    /// Error type for acquisition failures.
    type Error: std::error::Error + Send + Sync + 'static;

    /// Acquire a resource from the pool.
    ///
    /// This may block if no resources are available and the pool
    /// is at capacity. The acquire respects the `Cx` deadline.
    ///
    /// # Cancel-Safety
    ///
    /// - Cancelled while waiting: no resource is leaked.
    /// - Cancelled after acquisition: the `PooledResource` returns on drop.
    fn acquire<'a>(
        &'a self,
        cx: &'a Cx,
    ) -> PoolFuture<'a, Result<PooledResource<Self::Resource>, Self::Error>>;

    /// Try to acquire without waiting.
    ///
    /// Returns `None` if no resource is immediately available.
    fn try_acquire(&self) -> Option<PooledResource<Self::Resource>>;

    /// Get current pool statistics.
    fn stats(&self) -> PoolStats;

    /// Close the pool, rejecting new acquisitions.
    fn close(&self) -> PoolFuture<'_, ()>;

    /// Check if a resource is still healthy/usable.
    ///
    /// Called before returning an idle resource from the pool. If this
    /// returns `false`, the resource is discarded and another is tried
    /// (or a new one is created).
    ///
    /// The default implementation assumes all resources are healthy.
    ///
    /// # Example
    ///
    /// ```ignore
    /// async fn health_check(&self, resource: &TcpStream) -> bool {
    ///     // Try a quick ping
    ///     resource.peer_addr().is_ok()
    /// }
    /// ```
    fn health_check<'a>(&'a self, _resource: &'a Self::Resource) -> PoolFuture<'a, bool> {
        Box::pin(async { true })
    }
}

/// Trait for async resource creation and destruction.
///
/// Provides a structured interface for pool resource lifecycle management.
/// [`GenericPool`] accepts any factory function matching the expected signature;
/// implement this trait when you need custom destroy logic or want a named type.
///
/// # Example
///
/// ```ignore
/// use asupersync::sync::AsyncResourceFactory;
///
/// struct PgFactory { url: String }
///
/// impl AsyncResourceFactory for PgFactory {
///     type Resource = PgConnection;
///     type Error = PgError;
///
///     fn create(&self) -> Pin<Box<dyn Future<Output = Result<Self::Resource, Self::Error>> + Send + '_>> {
///         Box::pin(async { PgConnection::connect(&self.url).await })
///     }
/// }
/// ```
pub trait AsyncResourceFactory: Send + Sync {
    /// The type of resource this factory creates.
    type Resource: Send;

    /// The error type for creation failures.
    ///
    /// Note: this is intentionally `Into<Box<dyn Error>>` rather than requiring
    /// `Error` directly. Some callers use boxed trait-object errors
    /// (`Box<dyn Error + Send + Sync>`), and on some toolchains `Box<dyn Error>`
    /// does not satisfy `Error` bounds due to `Sized`/`?Sized` impl details.
    type Error: Send + Sync + 'static + Into<Box<dyn std::error::Error + Send + Sync>>;

    /// Create a new resource asynchronously.
    #[allow(clippy::type_complexity)]
    fn create(
        &self,
    ) -> Pin<Box<dyn Future<Output = Result<Self::Resource, Self::Error>> + Send + '_>>;
}

/// Pool usage statistics.
#[derive(Debug, Clone, Default)]
pub struct PoolStats {
    /// Resources currently in use.
    pub active: usize,
    /// Resources idle in pool.
    pub idle: usize,
    /// Total resources (active + idle).
    pub total: usize,
    /// Maximum pool size.
    pub max_size: usize,
    /// Waiters blocked on acquire.
    pub waiters: usize,
    /// Total acquisitions since pool creation.
    pub total_acquisitions: u64,
    /// Total time spent waiting for resources.
    pub total_wait_time: Duration,
}

/// Return messages sent from `PooledResource` back to a pool implementation.
#[derive(Debug)]
pub enum PoolReturn<R> {
    /// Resource is healthy; return to idle pool.
    Return {
        /// The resource being returned.
        resource: R,
        /// How long the resource was held.
        hold_duration: Duration,
        /// When the resource was originally created (for max_lifetime eviction).
        created_at: Instant,
    },
    /// Resource is broken; discard it.
    Discard {
        /// How long the resource was held before being discarded.
        hold_duration: Duration,
    },
}

#[derive(Debug)]
struct ReturnObligation {
    discharged: bool,
}

impl ReturnObligation {
    #[inline]
    fn new() -> Self {
        Self { discharged: false }
    }

    #[inline]
    fn discharge(&mut self) {
        self.discharged = true;
    }

    #[inline]
    fn is_discharged(&self) -> bool {
        self.discharged
    }
}

/// A resource acquired from a pool.
///
/// This type uses an obligation-style contract: when dropped, it
/// returns the resource to the pool unless explicitly discarded.
#[must_use = "PooledResource must be returned or dropped"]
pub struct PooledResource<R> {
    resource: Option<R>,
    return_obligation: ReturnObligation,
    return_tx: PoolReturnSender<R>,
    acquired_at: Instant,
    created_at: Instant,
    time_getter: fn() -> Instant,
    /// Shared waker list for notifying pool waiters when a resource is
    /// returned.  [`GenericPool`] populates this; custom [`Pool`]
    /// implementations that use only the public `new()` constructor get
    /// `None`, which is harmless — it just means notification relies on
    /// the next `process_returns` call instead of being immediate.
    return_wakers: Option<ReturnWakers>,
}

impl<R> PooledResource<R> {
    /// Creates a new pooled resource wrapper for a freshly created resource.
    ///
    /// This uses the wall clock for hold-duration bookkeeping.
    #[inline]
    pub fn new(resource: R, return_tx: PoolReturnSender<R>) -> Self {
        Self::new_with_time_getter(resource, return_tx, wall_clock_now)
    }

    /// Creates a new pooled resource wrapper with a custom time source.
    #[inline]
    pub fn new_with_time_getter(
        resource: R,
        return_tx: PoolReturnSender<R>,
        time_getter: fn() -> Instant,
    ) -> Self {
        let now = time_getter();
        Self {
            resource: Some(resource),
            return_obligation: ReturnObligation::new(),
            return_tx,
            acquired_at: now,
            created_at: now,
            time_getter,
            return_wakers: None,
        }
    }

    /// Creates a pooled resource wrapper preserving the original creation time.
    fn new_with_created_at(
        resource: R,
        return_tx: PoolReturnSender<R>,
        created_at: Instant,
        time_getter: fn() -> Instant,
    ) -> Self {
        Self {
            resource: Some(resource),
            return_obligation: ReturnObligation::new(),
            return_tx,
            acquired_at: time_getter(),
            created_at,
            time_getter,
            return_wakers: None,
        }
    }

    /// Attach the shared return-notification wakers from a
    /// [`GenericPool`].  Called internally after construction so that
    /// returning/discarding the resource immediately wakes waiting
    /// acquirers.
    fn with_return_notify(mut self, wakers: ReturnWakers) -> Self {
        self.return_wakers = Some(wakers);
        self
    }

    /// Access the resource.
    #[inline]
    #[must_use]
    pub fn get(&self) -> &R {
        self.resource.as_ref().expect("resource taken")
    }

    /// Mutably access the resource.
    #[inline]
    pub fn get_mut(&mut self) -> &mut R {
        self.resource.as_mut().expect("resource taken")
    }

    /// Explicitly return the resource to the pool.
    ///
    /// This discharges the return obligation.
    pub fn return_to_pool(mut self) {
        self.return_inner();
    }

    /// Mark the resource as broken and discard it.
    ///
    /// The pool will create a new resource to replace this one.
    pub fn discard(mut self) {
        self.discard_inner();
    }

    /// How long this resource has been held.
    #[inline]
    #[must_use]
    pub fn held_duration(&self) -> Duration {
        (self.time_getter)().saturating_duration_since(self.acquired_at)
    }

    fn return_inner(&mut self) {
        if self.return_obligation.is_discharged() {
            return;
        }

        let hold_duration = self.held_duration();
        if let Some(resource) = self.resource.take() {
            let _ = self.return_tx.send(PoolReturn::Return {
                resource,
                hold_duration,
                created_at: self.created_at,
            });
        }

        self.return_obligation.discharge();
        // Wake pool waiters so they re-poll and call process_returns
        // to move the returned resource from the mpsc channel into idle.
        self.notify_return_wakers();
    }

    fn discard_inner(&mut self) {
        if self.return_obligation.is_discharged() {
            return;
        }

        let hold_duration = self.held_duration();
        self.resource.take();
        let _ = self.return_tx.send(PoolReturn::Discard { hold_duration });
        self.return_obligation.discharge();
        // Wake pool waiters — a discard frees a creation slot.
        self.notify_return_wakers();
    }

    /// Wake the first registered pool waiter to act as a dispatcher.
    /// When it polls, it will call `process_returns()` which drains the return
    /// channel and wakes the exact number of subsequent waiters needed based on capacity.
    fn notify_return_wakers(&self) {
        if let Some(ref wakers) = self.return_wakers {
            let waker = {
                let lock = wakers.lock();
                lock.first().map(|(_, waker)| waker.clone())
            };
            if let Some(waker) = waker {
                waker.wake();
            }
        }
    }
}

impl<R> Drop for PooledResource<R> {
    fn drop(&mut self) {
        self.return_inner();
    }
}

impl<R> std::ops::Deref for PooledResource<R> {
    type Target = R;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.get()
    }
}

impl<R> std::ops::DerefMut for PooledResource<R> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.get_mut()
    }
}

// PooledResource is auto-derived as Send when R: Send because all fields
// (Option<R>, ReturnObligation, mpsc::Sender<PoolReturn<R>>, Instant) are Send.
// No manual unsafe impl needed.

// ============================================================================
// PoolConfig and GenericPool
// ============================================================================

/// Strategy for handling partial warmup failures.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WarmupStrategy {
    /// Continue with whatever connections succeeded.
    #[default]
    BestEffort,
    /// Fail pool creation if any warmup fails.
    FailFast,
    /// Require at least min_size connections.
    RequireMinimum,
}

/// Configuration for a generic resource pool.
#[derive(Debug, Clone)]
pub struct PoolConfig {
    /// Minimum resources to keep in pool.
    pub min_size: usize,
    /// Maximum resources in pool.
    pub max_size: usize,
    /// Timeout for acquire operations.
    pub acquire_timeout: Duration,
    /// Maximum time a resource can be idle before eviction.
    pub idle_timeout: Duration,
    /// Maximum lifetime of a resource.
    pub max_lifetime: Duration,

    // --- Health check options ---
    /// Perform health check before returning idle resources.
    pub health_check_on_acquire: bool,
    /// Periodic health check interval for idle resources.
    /// If `None`, periodic health checks are disabled.
    pub health_check_interval: Option<Duration>,
    /// Remove unhealthy resources immediately when detected.
    pub evict_unhealthy: bool,

    // --- Warmup options ---
    /// Pre-create this many connections on pool init.
    pub warmup_connections: usize,
    /// Timeout for warmup phase.
    pub warmup_timeout: Duration,
    /// Strategy when warmup partially fails.
    pub warmup_failure_strategy: WarmupStrategy,
}

impl Default for PoolConfig {
    fn default() -> Self {
        Self {
            min_size: 1,
            max_size: 10,
            acquire_timeout: Duration::from_secs(30),
            idle_timeout: Duration::from_mins(10),
            max_lifetime: Duration::from_hours(1),
            // Health check defaults
            health_check_on_acquire: false,
            health_check_interval: None,
            evict_unhealthy: true,
            // Warmup defaults
            warmup_connections: 0,
            warmup_timeout: Duration::from_secs(30),
            warmup_failure_strategy: WarmupStrategy::BestEffort,
        }
    }
}

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

    /// Sets the minimum pool size.
    #[must_use]
    pub fn min_size(mut self, min_size: usize) -> Self {
        self.min_size = min_size;
        self
    }

    /// Sets the maximum pool size.
    #[must_use]
    pub fn max_size(mut self, max_size: usize) -> Self {
        self.max_size = max_size;
        self
    }

    /// Sets the acquire timeout.
    #[must_use]
    pub fn acquire_timeout(mut self, timeout: Duration) -> Self {
        self.acquire_timeout = timeout;
        self
    }

    /// Sets the idle timeout.
    #[must_use]
    pub fn idle_timeout(mut self, timeout: Duration) -> Self {
        self.idle_timeout = timeout;
        self
    }

    /// Sets the max lifetime.
    #[must_use]
    pub fn max_lifetime(mut self, lifetime: Duration) -> Self {
        self.max_lifetime = lifetime;
        self
    }

    /// Enables health checking before returning idle resources.
    #[must_use]
    pub fn health_check_on_acquire(mut self, enabled: bool) -> Self {
        self.health_check_on_acquire = enabled;
        self
    }

    /// Sets the periodic health check interval for idle resources.
    #[must_use]
    pub fn health_check_interval(mut self, interval: Option<Duration>) -> Self {
        self.health_check_interval = interval;
        self
    }

    /// Sets whether to immediately evict unhealthy resources.
    #[must_use]
    pub fn evict_unhealthy(mut self, evict: bool) -> Self {
        self.evict_unhealthy = evict;
        self
    }

    /// Sets the number of connections to pre-create during warmup.
    #[must_use]
    pub fn warmup_connections(mut self, count: usize) -> Self {
        self.warmup_connections = count;
        self
    }

    /// Sets the timeout for the warmup phase.
    #[must_use]
    pub fn warmup_timeout(mut self, timeout: Duration) -> Self {
        self.warmup_timeout = timeout;
        self
    }

    /// Sets the strategy for handling partial warmup failures.
    #[must_use]
    pub fn warmup_failure_strategy(mut self, strategy: WarmupStrategy) -> Self {
        self.warmup_failure_strategy = strategy;
        self
    }
}

/// Error type for GenericPool operations.
#[derive(Debug)]
pub enum PoolError {
    /// The pool is closed.
    Closed,
    /// Acquisition timed out.
    Timeout,
    /// Acquisition was cancelled.
    Cancelled,
    /// Resource creation failed.
    CreateFailed(Box<dyn std::error::Error + Send + Sync>),
}

impl std::fmt::Display for PoolError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Closed => write!(f, "pool closed"),
            Self::Timeout => write!(f, "pool acquire timeout"),
            Self::Cancelled => write!(f, "pool acquire cancelled"),
            Self::CreateFailed(e) => write!(f, "resource creation failed: {e}"),
        }
    }
}

impl std::error::Error for PoolError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::CreateFailed(e) => Some(e.as_ref()),
            _ => None,
        }
    }
}

/// An idle resource in the pool.
#[derive(Debug)]
struct IdleResource<R> {
    resource: R,
    idle_since: Instant,
    created_at: Instant,
}

/// A waiter for a resource.
struct PoolWaiter {
    id: u64,
    waker: std::task::Waker,
}

/// Internal state for the generic pool.
struct GenericPoolState<R> {
    /// Idle resources ready for use.
    idle: std::collections::VecDeque<IdleResource<R>>,
    /// Number of resources currently in use.
    active: usize,
    /// Number of resources currently being created asynchronously.
    creating: usize,
    /// Total resources ever created.
    total_created: u64,
    /// Total acquisitions.
    total_acquisitions: u64,
    /// Total wait time accumulated.
    total_wait_time: Duration,
    /// Whether the pool is closed.
    closed: bool,
    /// Waiters queue (FIFO).
    waiters: std::collections::VecDeque<PoolWaiter>,
    /// Next waiter ID.
    next_waiter_id: u64,
}

/// Future that waits for a resource notification.
struct WaitForNotification<'a, 'b, R, F>
where
    R: Send + 'static,
    F: AsyncResourceFactory<Resource = R>,
{
    pool: &'a GenericPool<R, F>,
    waiter_id: &'b mut Option<u64>,
    cx: &'a Cx,
}

impl<R, F> Future for WaitForNotification<'_, '_, R, F>
where
    R: Send + 'static,
    F: AsyncResourceFactory<Resource = R>,
{
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if self.cx.checkpoint().is_err() {
            return Poll::Ready(());
        }

        self.pool.process_returns();

        let mut state = self.pool.state.lock();

        if state.closed {
            return Poll::Ready(());
        }

        let total_including_creating = state.active + state.idle.len() + state.creating;
        let available = state.idle.len()
            + self
                .pool
                .config
                .max_size
                .saturating_sub(total_including_creating);

        // Single-pass: check if already queued, update waker/register, and get position.
        let pos = if let Some(id) = *self.waiter_id {
            if let Some(idx) = state.waiters.iter().position(|w| w.id == id) {
                let w = &mut state.waiters[idx];
                if !w.waker.will_wake(cx.waker()) {
                    w.waker.clone_from(cx.waker());
                }
                idx
            } else {
                // Was removed by try_get_idle but health check failed.
                // Re-register at the FRONT to preserve FIFO fairness.
                state.waiters.push_front(PoolWaiter {
                    id,
                    waker: cx.waker().clone(),
                });
                0
            }
        } else {
            let id = state.next_waiter_id;
            state.next_waiter_id = state.next_waiter_id.wrapping_add(1);
            let idx = state.waiters.len();
            state.waiters.push_back(PoolWaiter {
                id,
                waker: cx.waker().clone(),
            });
            *self.waiter_id = Some(id);
            idx
        };

        let id = self.waiter_id.expect("waiter_id assigned above");
        drop(state);

        if pos < available {
            return Poll::Ready(());
        }

        // Also register in the return_wakers list
        {
            let mut wakers = self.pool.return_wakers.lock();
            if let Some((_, existing)) = wakers.iter_mut().find(|(wid, _)| *wid == id) {
                if !existing.will_wake(cx.waker()) {
                    existing.clone_from(cx.waker());
                }
            } else {
                wakers.push((id, cx.waker().clone()));
            }
        }

        // Process returns again to close the race condition:
        // A resource might have been returned between `drop(state)` and locking `return_wakers`.
        self.pool.process_returns();

        Poll::Pending
    }
}

struct HealthCheckGuard<'a, R, F>
where
    R: Send + 'static,
    F: AsyncResourceFactory<Resource = R>,
{
    pool: &'a GenericPool<R, F>,
    completed: bool,
}

impl<R, F> Drop for HealthCheckGuard<'_, R, F>
where
    R: Send + 'static,
    F: AsyncResourceFactory<Resource = R>,
{
    fn drop(&mut self) {
        if !self.completed {
            self.pool.reject_unhealthy_idle_resource();
        }
    }
}

/// Reservation for an in-flight resource creation slot.
///
/// This ensures pool capacity accounting remains correct across async suspend
/// points: if acquire is cancelled while creating a resource, the reservation
/// is released in `Drop`.
struct CreateSlotReservation<'a, R, F>
where
    R: Send + 'static,
    F: AsyncResourceFactory<Resource = R>,
{
    pool: &'a GenericPool<R, F>,
    committed: bool,
}

impl<'a, R, F> CreateSlotReservation<'a, R, F>
where
    R: Send + 'static,
    F: AsyncResourceFactory<Resource = R>,
{
    fn try_reserve(pool: &'a GenericPool<R, F>, waiter_id: Option<u64>) -> Option<Self> {
        if pool.reserve_create_slot(waiter_id) {
            Some(Self {
                pool,
                committed: false,
            })
        } else {
            None
        }
    }

    fn commit(mut self) -> bool {
        let handed_out = self.pool.commit_create_slot();
        self.committed = true;
        handed_out
    }

    /// Mark the reservation as committed without calling
    /// `commit_create_slot`.  The caller is responsible for adjusting
    /// pool accounting (e.g., via `commit_create_slot_as_idle`).
    fn committed_manually(mut self) {
        self.committed = true;
    }
}

impl<R, F> Drop for CreateSlotReservation<'_, R, F>
where
    R: Send + 'static,
    F: AsyncResourceFactory<Resource = R>,
{
    fn drop(&mut self) {
        if !self.committed {
            self.pool.release_create_slot();
        }
    }
}

impl<F, R, E, Fut> AsyncResourceFactory for F
where
    F: Fn() -> Fut + Send + Sync,
    Fut: Future<Output = Result<R, E>> + Send + 'static,
    R: Send,
    E: Send + Sync + 'static + Into<Box<dyn std::error::Error + Send + Sync>>,
{
    type Resource = R;
    type Error = E;

    fn create(
        &self,
    ) -> Pin<Box<dyn Future<Output = Result<Self::Resource, Self::Error>> + Send + '_>> {
        Box::pin(self())
    }
}

/// A generic resource pool with configurable behavior.
///
/// This pool manages resources created by a factory function and provides
/// cancel-safe acquisition with timeout support.
///
/// # Type Parameters
///
/// - `R`: The resource type
/// - `F`: Factory type that creates resources
pub struct GenericPool<R, F>
where
    R: Send + 'static,
    F: AsyncResourceFactory<Resource = R>,
{
    /// Factory to create new resources.
    factory: F,
    /// Configuration.
    config: PoolConfig,
    /// Internal state.
    state: PoolMutex<GenericPoolState<R>>,
    /// Channel for returning resources.
    return_tx: PoolReturnSender<R>,
    /// Channel receiver for returned resources.
    return_rx: PoolMutex<PoolReturnReceiver<R>>,
    /// Time source for lifecycle bookkeeping that should remain deterministic
    /// in tests and virtual-time harnesses.
    time_getter: fn() -> Instant,
    /// Optional synchronous health check function.
    ///
    /// When set and `config.health_check_on_acquire` is true, idle resources
    /// are checked before being returned from `acquire()`.
    #[allow(clippy::type_complexity)]
    health_check_fn: Option<Box<dyn Fn(&R) -> bool + Send + Sync>>,
    /// Shared waker list: [`PooledResource`] drains and wakes these on
    /// return/discard so that [`WaitForNotification`] futures are
    /// re-polled immediately instead of waiting for the next
    /// `process_returns` call.
    return_wakers: ReturnWakers,
    /// Lock-free snapshot of `GenericPoolState::closed` (monotone false→true).
    closed: AtomicBool,
    /// Optional metrics handle for observability.
    #[cfg(feature = "metrics")]
    metrics: Option<PoolMetricsHandle>,
}

impl<R, F> GenericPool<R, F>
where
    R: Send + 'static,
    F: AsyncResourceFactory<Resource = R>,
{
    /// Creates a new generic pool with the given factory and configuration.
    pub fn new(factory: F, config: PoolConfig) -> Self {
        Self::with_time_getter(factory, config, wall_clock_now)
    }

    /// Creates a new generic pool with a custom time source for lifecycle
    /// bookkeeping such as idle eviction, hold durations, and warmup-created
    /// timestamps.
    pub fn with_time_getter(factory: F, config: PoolConfig, time_getter: fn() -> Instant) -> Self {
        let (return_tx, return_rx) = mpsc::channel();
        Self {
            factory,
            config,
            state: PoolMutex::new(GenericPoolState {
                idle: std::collections::VecDeque::with_capacity(8),
                active: 0,
                creating: 0,
                total_created: 0,
                total_acquisitions: 0,
                total_wait_time: Duration::ZERO,
                closed: false,
                waiters: std::collections::VecDeque::with_capacity(4),
                next_waiter_id: 0,
            }),
            return_tx,
            return_rx: PoolMutex::new(return_rx),
            time_getter,
            health_check_fn: None,
            return_wakers: Arc::new(PoolMutex::new(SmallVec::new())),
            closed: AtomicBool::new(false),
            #[cfg(feature = "metrics")]
            metrics: None,
        }
    }

    /// Creates a new pool with default configuration.
    pub fn with_factory(factory: F) -> Self {
        Self::new(factory, PoolConfig::default())
    }

    /// Returns the time source used for lifecycle bookkeeping.
    #[must_use]
    pub const fn time_getter(&self) -> fn() -> Instant {
        self.time_getter
    }

    /// Configures metrics collection for this pool.
    ///
    /// When metrics are enabled, the pool will record:
    /// - Gauges: size, active, idle, pending (waiters)
    /// - Counters: acquired, released, created, destroyed, timeouts
    /// - Histograms: acquire duration, hold duration, wait duration
    ///
    /// All metrics are labeled with the provided `pool_name`.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use opentelemetry::global;
    /// use asupersync::sync::{GenericPool, PoolConfig, PoolMetrics};
    ///
    /// let meter = global::meter("myapp");
    /// let metrics = PoolMetrics::new(&meter);
    ///
    /// let pool = GenericPool::new(factory, PoolConfig::default())
    ///     .with_metrics("db_pool", metrics.handle("db_pool"));
    /// ```
    #[cfg(feature = "metrics")]
    #[must_use]
    pub fn with_metrics(mut self, handle: PoolMetricsHandle) -> Self {
        self.metrics = Some(handle);
        self
    }

    /// Sets a synchronous health check function for idle resources.
    ///
    /// When set and [`PoolConfig::health_check_on_acquire`] is `true`,
    /// each idle resource is checked before being returned from [`Pool::acquire`].
    /// Resources that fail the check are discarded and the next idle resource
    /// is tried, or a new one is created.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let pool = GenericPool::new(factory, config)
    ///     .with_health_check(|conn: &TcpStream| conn.peer_addr().is_ok());
    /// ```
    #[must_use]
    pub fn with_health_check(mut self, check: impl Fn(&R) -> bool + Send + Sync + 'static) -> Self {
        self.health_check_fn = Some(Box::new(check));
        self
    }

    /// Pre-create resources according to [`PoolConfig::warmup_connections`].
    ///
    /// Call this after constructing the pool to pre-fill the idle queue.
    /// The behavior on partial failure is controlled by
    /// [`PoolConfig::warmup_failure_strategy`].
    ///
    /// Returns the number of resources successfully created.
    ///
    /// # Errors
    ///
    /// - [`WarmupStrategy::FailFast`]: Returns on the first creation failure.
    /// - [`WarmupStrategy::RequireMinimum`]: Returns an error if fewer than
    ///   [`PoolConfig::min_size`] resources were created.
    /// - [`WarmupStrategy::BestEffort`]: Never returns an error from warmup.
    /// - [`PoolConfig::warmup_timeout`]: Applies to the entire warmup phase,
    ///   not each individual create attempt.
    pub async fn warmup(&self) -> Result<usize, PoolError> {
        let mut created = 0;
        let mut last_error = None;
        let warmup_deadline = crate::time::wall_now() + self.config.warmup_timeout;

        let target = self.config.warmup_connections;
        for _ in 0..target {
            // Reserve a creation slot so concurrent acquire() calls see
            // an accurate capacity picture.  Without this, concurrent
            // acquires could exceed max_size during warmup.
            let Some(slot) = CreateSlotReservation::try_reserve(self, None) else {
                break; // max_size reached (possibly by concurrent activity)
            };

            let now = crate::time::wall_now();
            let remaining = Duration::from_nanos(warmup_deadline.duration_since(now));
            let create_result = if remaining.is_zero() {
                Err(PoolError::Timeout)
            } else {
                match crate::time::timeout(now, remaining, self.create_resource()).await {
                    Ok(result) => result,
                    Err(_elapsed) => Err(PoolError::Timeout),
                }
            };

            match create_result {
                Ok(resource) => {
                    // Commit the slot as idle — not active.
                    // CreateSlotReservation::drop is disarmed because we
                    // set committed before drop.
                    slot.committed_manually();
                    self.commit_create_slot_as_idle(resource);
                    created += 1;
                }
                Err(PoolError::Timeout) => match self.config.warmup_failure_strategy {
                    WarmupStrategy::FailFast => return Err(PoolError::Timeout),
                    WarmupStrategy::BestEffort | WarmupStrategy::RequireMinimum => {
                        last_error = Some(PoolError::Timeout);
                        break;
                    }
                },
                Err(e) => {
                    // slot is dropped here → releases the creating count
                    match self.config.warmup_failure_strategy {
                        WarmupStrategy::FailFast => return Err(e),
                        WarmupStrategy::BestEffort | WarmupStrategy::RequireMinimum => {
                            last_error = Some(e);
                        }
                    }
                }
            }
        }

        if self.config.warmup_failure_strategy == WarmupStrategy::RequireMinimum
            && created < self.config.min_size
        {
            return Err(last_error.unwrap_or(PoolError::CreateFailed(
                "warmup did not reach min_size".into(),
            )));
        }

        Ok(created)
    }

    /// Check whether an idle resource passes the configured health check.
    fn is_healthy(&self, resource: &R) -> bool {
        self.health_check_fn
            .as_ref()
            .is_none_or(|check| check(resource))
    }

    /// Handle an unhealthy idle resource that was popped by `try_get_idle`.
    ///
    /// `try_get_idle` increments `active` and `total_acquisitions` when it
    /// pops an idle entry. If health-check rejects that entry we must undo
    /// those counters, and (when metrics are enabled) record a destroy event.
    fn reject_unhealthy_idle_resource(&self) {
        let waker = {
            let mut state = self.state.lock();
            state.active = state.active.saturating_sub(1);
            state.total_acquisitions = state.total_acquisitions.saturating_sub(1);

            let total = state.active + state.idle.len() + state.creating;
            let available = state.idle.len() + self.config.max_size.saturating_sub(total);
            if available > 0 && available - 1 < state.waiters.len() {
                Some(state.waiters[available - 1].waker.clone())
            } else {
                None
            }
        };

        if let Some(waker) = waker {
            waker.wake();
        }

        #[cfg(feature = "metrics")]
        if let Some(ref metrics) = self.metrics {
            metrics.record_destroyed(DestroyReason::Unhealthy);
            self.update_metrics_gauges();
        }
    }

    /// Process returned resources from the return channel.
    #[cfg_attr(not(feature = "metrics"), allow(unused_variables))]
    fn process_returns(&self) {
        let rx = self.return_rx.lock();
        let mut waiters_to_wake: SmallVec<[Waker; 4]> = SmallVec::new();
        while let Ok(ret) = rx.try_recv() {
            match ret {
                PoolReturn::Return {
                    resource,
                    hold_duration,
                    created_at,
                } => {
                    // Record metrics for the release
                    #[cfg(feature = "metrics")]
                    if let Some(ref metrics) = self.metrics {
                        metrics.record_released(hold_duration);
                    }

                    let mut state = self.state.lock();
                    state.active = state.active.saturating_sub(1);

                    if !state.closed {
                        state.idle.push_back(IdleResource {
                            resource,
                            idle_since: (self.time_getter)(),
                            created_at,
                        });

                        let total = state.active + state.idle.len() + state.creating;
                        let available =
                            state.idle.len() + self.config.max_size.saturating_sub(total);
                        if available > 0 && available - 1 < state.waiters.len() {
                            waiters_to_wake.push(state.waiters[available - 1].waker.clone());
                        }
                    }
                    drop(state);
                }
                PoolReturn::Discard { hold_duration } => {
                    // Record metrics for the discard (destroyed as unhealthy)
                    #[cfg(feature = "metrics")]
                    if let Some(ref metrics) = self.metrics {
                        metrics.record_released(hold_duration);
                        metrics.record_destroyed(DestroyReason::Unhealthy);
                    }

                    let mut state = self.state.lock();
                    state.active = state.active.saturating_sub(1);

                    let total = state.active + state.idle.len() + state.creating;
                    let available = state.idle.len() + self.config.max_size.saturating_sub(total);
                    if available > 0 && available - 1 < state.waiters.len() {
                        waiters_to_wake.push(state.waiters[available - 1].waker.clone());
                    }
                    drop(state);
                }
            }
        }
        drop(rx);

        for waker in waiters_to_wake {
            waker.wake();
        }
    }

    /// Try to get an idle resource, returning its original creation time.
    fn try_get_idle(&self, waiter_id: Option<u64>) -> Option<(R, Instant)> {
        let mut state = self.state.lock();

        // Evict expired resources first and track eviction reasons for metrics
        let now = (self.time_getter)();
        #[cfg(feature = "metrics")]
        let mut idle_timeout_evictions = 0u64;
        #[cfg(feature = "metrics")]
        let mut max_lifetime_evictions = 0u64;

        state.idle.retain(|idle| {
            let idle_ok = now.saturating_duration_since(idle.idle_since) < self.config.idle_timeout;
            let lifetime_ok =
                now.saturating_duration_since(idle.created_at) < self.config.max_lifetime;

            #[cfg(feature = "metrics")]
            {
                if !idle_ok {
                    idle_timeout_evictions += 1;
                } else if !lifetime_ok {
                    max_lifetime_evictions += 1;
                }
            }

            idle_ok && lifetime_ok
        });

        // Evictions don't increase `available` window, so we don't need to wake anyone.
        // The slot is just converted from idle to can_create, so the currently
        // authorized task will just create instead of reusing.

        // Record eviction metrics
        #[cfg(feature = "metrics")]
        if let Some(ref metrics) = self.metrics {
            for _ in 0..idle_timeout_evictions {
                metrics.record_destroyed(DestroyReason::IdleTimeout);
            }
            for _ in 0..max_lifetime_evictions {
                metrics.record_destroyed(DestroyReason::MaxLifetime);
            }
        }

        let total = state.active + state.idle.len() + state.creating;
        let available = state.idle.len() + self.config.max_size.saturating_sub(total);

        let pos = waiter_id.map_or_else(
            || state.waiters.len(),
            |id| {
                state
                    .waiters
                    .iter()
                    .position(|w| w.id == id)
                    .unwrap_or(state.waiters.len())
            },
        );

        let can_acquire = pos < available;

        let result = if can_acquire {
            if let Some(idle) = state.idle.pop_front() {
                state.active += 1;
                state.total_acquisitions += 1;
                // Waiter is NOT removed here. It is removed in `acquire` upon success,
                // or remains in queue if health check fails to preserve FIFO.
                Some((idle.resource, idle.created_at))
            } else {
                None
            }
        } else {
            None
        };
        drop(state);

        result
    }

    /// Reserve a creation slot under max-size accounting.
    fn reserve_create_slot(&self, waiter_id: Option<u64>) -> bool {
        let mut state = self.state.lock();
        let total = state.active + state.idle.len() + state.creating;
        if state.closed || total >= self.config.max_size {
            return false;
        }

        let available = state.idle.len() + self.config.max_size.saturating_sub(total);
        let pos = waiter_id.map_or_else(
            || state.waiters.len(),
            |id| {
                state
                    .waiters
                    .iter()
                    .position(|w| w.id == id)
                    .unwrap_or(state.waiters.len())
            },
        );

        if pos >= available {
            return false;
        }

        state.creating += 1;
        if waiter_id.is_some() && pos < state.waiters.len() {
            state.waiters.remove(pos);
        }
        true
    }

    /// Release an uncommitted creation slot and notify one waiter.
    fn release_create_slot(&self) {
        let waker = {
            let mut state = self.state.lock();
            state.creating = state.creating.saturating_sub(1);
            let total = state.active + state.idle.len() + state.creating;
            let available = state.idle.len() + self.config.max_size.saturating_sub(total);
            if available > 0 && available - 1 < state.waiters.len() {
                Some(state.waiters[available - 1].waker.clone())
            } else {
                None
            }
        };
        if let Some(waker) = waker {
            waker.wake();
        }
    }

    /// Commit a completed creation slot into active accounting.
    ///
    /// Returns `true` when the created resource may still be handed out.
    /// If the pool was closed while creation was in flight, this returns
    /// `false` and the caller must drop the freshly created resource.
    fn commit_create_slot(&self) -> bool {
        let mut state = self.state.lock();
        state.creating = state.creating.saturating_sub(1);
        state.total_created += 1;

        if state.closed {
            return false;
        }

        state.active += 1;
        state.total_acquisitions += 1;
        true
    }

    /// Commit a completed creation slot as an idle resource (for warmup).
    /// Unlike `commit_create_slot`, this does NOT increment `active` or
    /// `total_acquisitions` — the resource goes straight to the idle queue.
    fn commit_create_slot_as_idle(&self, resource: R) {
        let waker = {
            let mut state = self.state.lock();
            state.creating = state.creating.saturating_sub(1);
            state.total_created += 1;

            if state.closed {
                // Drop the resource instead of leaking it in the idle queue of a closed pool
                drop(state);
                return;
            }

            let now = (self.time_getter)();
            state.idle.push_back(IdleResource {
                resource,
                idle_since: now,
                created_at: now,
            });

            let total = state.active + state.idle.len() + state.creating;
            let available = state.idle.len() + self.config.max_size.saturating_sub(total);
            if available > 0 && available - 1 < state.waiters.len() {
                Some(state.waiters[available - 1].waker.clone())
            } else {
                None
            }
        };

        if let Some(waker) = waker {
            waker.wake();
        }
    }

    /// Create a new resource using the factory.
    async fn create_resource(&self) -> Result<R, PoolError> {
        let fut = self.factory.create();
        fut.await.map_err(|e| PoolError::CreateFailed(e.into()))
    }

    /// Compute the remaining time for an acquire attempt after applying both
    /// the pool timeout and any tighter deadline carried by the caller's `Cx`.
    fn remaining_acquire_timeout(
        &self,
        cx: &Cx,
        acquire_start: crate::types::Time,
        now: crate::types::Time,
    ) -> Result<Duration, PoolError> {
        let elapsed = Duration::from_nanos(now.duration_since(acquire_start));
        if elapsed >= self.config.acquire_timeout {
            return Err(PoolError::Timeout);
        }

        let remaining = self.config.acquire_timeout.saturating_sub(elapsed);
        if let Some(budget_remaining) = cx.budget().remaining_time(now) {
            if budget_remaining.is_zero() {
                return Err(PoolError::Cancelled);
            }
            Ok(remaining.min(budget_remaining))
        } else {
            Ok(remaining)
        }
    }

    /// Remove a waiter by ID.
    fn remove_waiter(&self, id: u64) {
        let mut state = self.state.lock();
        state.waiters.retain(|w| w.id != id);
    }

    /// Record elapsed wait time for blocked acquires.
    #[cfg_attr(not(feature = "metrics"), allow(unused_variables))]
    fn record_wait_time(&self, wait_duration: Duration) {
        if wait_duration.is_zero() {
            return;
        }

        let mut state = self.state.lock();
        state.total_wait_time = state
            .total_wait_time
            .checked_add(wait_duration)
            .unwrap_or(Duration::MAX);
        drop(state);

        #[cfg(feature = "metrics")]
        if let Some(ref metrics) = self.metrics {
            metrics.record_wait(wait_duration);
        }
    }

    /// Update metrics gauges from current pool state.
    #[cfg(feature = "metrics")]
    fn update_metrics_gauges(&self) {
        if let Some(ref metrics) = self.metrics {
            let stats = {
                let state = self.state.lock();
                PoolStats {
                    active: state.active,
                    idle: state.idle.len(),
                    total: state.active + state.idle.len() + state.creating,
                    max_size: self.config.max_size,
                    waiters: state.waiters.len(),
                    total_acquisitions: state.total_acquisitions,
                    total_wait_time: state.total_wait_time,
                }
            };
            metrics.update_gauges(&stats);
        }
    }
}

impl<R, F> Pool for GenericPool<R, F>
where
    R: Send + 'static,
    F: AsyncResourceFactory<Resource = R>,
{
    type Resource = R;
    type Error = PoolError;

    #[cfg_attr(not(feature = "metrics"), allow(unused_variables))]
    #[allow(clippy::too_many_lines)]
    fn acquire<'a>(
        &'a self,
        cx: &'a Cx,
    ) -> PoolFuture<'a, Result<PooledResource<Self::Resource>, Self::Error>> {
        Box::pin(async move {
            struct WaiterCleanup<'a, R, F>
            where
                R: Send + 'static,
                F: AsyncResourceFactory<Resource = R>,
            {
                pool: &'a GenericPool<R, F>,
                waiter_id: Option<u64>,
            }

            impl<R, F> Drop for WaiterCleanup<'_, R, F>
            where
                R: Send + 'static,
                F: AsyncResourceFactory<Resource = R>,
            {
                fn drop(&mut self) {
                    if let Some(id) = self.waiter_id {
                        let mut state = self.pool.state.lock();
                        let pos = state.waiters.iter().position(|w| w.id == id);
                        if let Some(p) = pos {
                            state.waiters.remove(p);
                        }

                        let waker: Option<std::task::Waker> = if state.closed {
                            None
                        } else {
                            let total_including_creating =
                                state.active + state.idle.len() + state.creating;
                            let available = state.idle.len()
                                + self
                                    .pool
                                    .config
                                    .max_size
                                    .saturating_sub(total_including_creating);

                            pos.and_then(|p| {
                                if p < available
                                    && available > 0
                                    && available - 1 < state.waiters.len()
                                {
                                    Some(state.waiters[available - 1].waker.clone())
                                } else {
                                    None
                                }
                            })
                        };
                        drop(state);

                        if let Some(w) = waker {
                            w.wake();
                        }
                        self.pool.return_wakers.lock().retain(|(wid, _)| *wid != id);
                    }
                    self.pool.process_returns();
                }
            }

            let get_now = || {
                cx.timer_driver()
                    .map_or_else(crate::time::wall_now, |d| d.now())
            };
            let acquire_start = get_now();
            let mut cleanup = WaiterCleanup {
                pool: self,
                waiter_id: None,
            };

            loop {
                // Process any pending returns
                self.process_returns();

                // A waiter can resume because of cancellation/deadline as well
                // as because a resource became available. Re-check before taking
                // any fast path so cancelled acquirers do not steal capacity.
                if cx.checkpoint().is_err() {
                    return Err(PoolError::Cancelled);
                }

                // Check if closed (lock-free fast path).
                if self.closed.load(Ordering::Acquire) {
                    return Err(PoolError::Closed);
                }

                // Try to get a healthy idle resource.
                while let Some((resource, created_at)) = self.try_get_idle(cleanup.waiter_id) {
                    let is_healthy = if self.config.health_check_on_acquire {
                        let mut guard = HealthCheckGuard {
                            pool: self,
                            completed: false,
                        };
                        let healthy = self.is_healthy(&resource);
                        guard.completed = true;
                        healthy
                    } else {
                        true
                    };

                    if !is_healthy {
                        self.reject_unhealthy_idle_resource();
                        continue;
                    }

                    let id = cleanup.waiter_id.take();
                    if let Some(id) = id {
                        self.return_wakers.lock().retain(|(wid, _)| *wid != id);
                        self.remove_waiter(id);
                    }

                    let acquire_duration =
                        Duration::from_nanos(get_now().duration_since(acquire_start));

                    // Record metrics
                    #[cfg(feature = "metrics")]
                    if let Some(ref metrics) = self.metrics {
                        metrics.record_acquired(acquire_duration);
                        self.update_metrics_gauges();
                    }

                    return Ok(PooledResource::new_with_created_at(
                        resource,
                        self.return_tx.clone(),
                        created_at,
                        self.time_getter,
                    )
                    .with_return_notify(Arc::clone(&self.return_wakers)));
                }

                // Try to create a new resource if under capacity
                if let Some(create_slot) =
                    CreateSlotReservation::try_reserve(self, cleanup.waiter_id)
                {
                    let id = cleanup.waiter_id.take();
                    if let Some(id) = id {
                        self.return_wakers.lock().retain(|(wid, _)| *wid != id);
                        self.remove_waiter(id);
                    }

                    let now = get_now();
                    let remaining = match self.remaining_acquire_timeout(cx, acquire_start, now) {
                        Ok(remaining) => remaining,
                        Err(PoolError::Timeout) => {
                            #[cfg(feature = "metrics")]
                            if let Some(ref metrics) = self.metrics {
                                metrics.record_timeout(Duration::from_nanos(
                                    now.duration_since(acquire_start),
                                ));
                            }
                            return Err(PoolError::Timeout);
                        }
                        Err(PoolError::Cancelled) => return Err(PoolError::Cancelled),
                        Err(other) => return Err(other),
                    };

                    if remaining.is_zero() {
                        #[cfg(feature = "metrics")]
                        if let Some(ref metrics) = self.metrics {
                            metrics.record_timeout(Duration::from_nanos(
                                now.duration_since(acquire_start),
                            ));
                        }
                        return if cx.checkpoint().is_err() {
                            Err(PoolError::Cancelled)
                        } else {
                            Err(PoolError::Timeout)
                        };
                    }

                    let create_result =
                        crate::time::timeout(now, remaining, self.create_resource()).await;
                    let resource = match create_result {
                        Ok(Ok(res)) => res,
                        Ok(Err(e)) => return Err(e),
                        Err(_) => {
                            if cx.checkpoint().is_err() {
                                return Err(PoolError::Cancelled);
                            }

                            #[cfg(feature = "metrics")]
                            if let Some(ref metrics) = self.metrics {
                                metrics.record_timeout(Duration::from_nanos(
                                    get_now().duration_since(acquire_start),
                                ));
                            }
                            return Err(PoolError::Timeout);
                        }
                    };

                    let committed = create_slot.commit();
                    let acquire_duration =
                        Duration::from_nanos(get_now().duration_since(acquire_start));

                    // Record metrics for create and acquire
                    #[cfg(feature = "metrics")]
                    if let Some(ref metrics) = self.metrics {
                        metrics.record_created();
                        if committed {
                            metrics.record_acquired(acquire_duration);
                        }
                        self.update_metrics_gauges();
                    }

                    if !committed {
                        return Err(PoolError::Closed);
                    }

                    return Ok(PooledResource::new_with_time_getter(
                        resource,
                        self.return_tx.clone(),
                        self.time_getter,
                    )
                    .with_return_notify(Arc::clone(&self.return_wakers)));
                }

                // Check for timeout
                let now = get_now();
                let remaining = match self.remaining_acquire_timeout(cx, acquire_start, now) {
                    Ok(remaining) => remaining,
                    Err(PoolError::Timeout) => {
                        let elapsed = Duration::from_nanos(now.duration_since(acquire_start));
                        #[cfg(feature = "metrics")]
                        if let Some(ref metrics) = self.metrics {
                            metrics.record_timeout(elapsed);
                        }
                        return Err(PoolError::Timeout);
                    }
                    Err(PoolError::Cancelled) => return Err(PoolError::Cancelled),
                    Err(other) => return Err(other),
                };

                // Check for cancellation
                if let Err(_e) = cx.checkpoint() {
                    return Err(PoolError::Cancelled);
                }

                // Wait for a resource to become available
                let wait_started = now;
                let wait_fut = WaitForNotification {
                    pool: self,
                    waiter_id: &mut cleanup.waiter_id,
                    cx,
                };
                if crate::time::timeout(now, remaining, wait_fut)
                    .await
                    .is_err()
                {
                    let wait_duration =
                        Duration::from_nanos(get_now().duration_since(wait_started));
                    if cx.checkpoint().is_err() {
                        self.record_wait_time(wait_duration);
                        return Err(PoolError::Cancelled);
                    }

                    #[cfg(feature = "metrics")]
                    if let Some(ref metrics) = self.metrics {
                        metrics.record_timeout(wait_duration);
                    }
                    self.record_wait_time(wait_duration);
                    return Err(PoolError::Timeout);
                }
                self.record_wait_time(Duration::from_nanos(get_now().duration_since(wait_started)));
            }
        })
    }

    #[cfg_attr(not(feature = "metrics"), allow(unused_variables))]
    fn try_acquire(&self) -> Option<PooledResource<Self::Resource>> {
        let acquire_start = (self.time_getter)();

        self.process_returns();

        if self.closed.load(Ordering::Acquire) {
            return None;
        }

        while let Some((resource, created_at)) = self.try_get_idle(None) {
            let is_healthy = if self.config.health_check_on_acquire {
                let mut guard = HealthCheckGuard {
                    pool: self,
                    completed: false,
                };
                let healthy = self.is_healthy(&resource);
                guard.completed = true;
                let _ = guard.completed;
                healthy
            } else {
                true
            };

            if !is_healthy {
                self.reject_unhealthy_idle_resource();
                continue;
            }

            // Record metrics for the acquire
            #[cfg(feature = "metrics")]
            if let Some(ref metrics) = self.metrics {
                metrics
                    .record_acquired((self.time_getter)().saturating_duration_since(acquire_start));
                self.update_metrics_gauges();
            }

            return Some(
                PooledResource::new_with_created_at(
                    resource,
                    self.return_tx.clone(),
                    created_at,
                    self.time_getter,
                )
                .with_return_notify(Arc::clone(&self.return_wakers)),
            );
        }

        None
    }

    fn stats(&self) -> PoolStats {
        self.process_returns();

        let pool_stats = {
            let state = self.state.lock();
            PoolStats {
                active: state.active,
                idle: state.idle.len(),
                total: state.active + state.idle.len() + state.creating,
                max_size: self.config.max_size,
                waiters: state.waiters.len(),
                total_acquisitions: state.total_acquisitions,
                total_wait_time: state.total_wait_time,
            }
        };

        // Update metrics gauges
        #[cfg(feature = "metrics")]
        if let Some(ref metrics) = self.metrics {
            metrics.update_gauges(&pool_stats);
        }

        pool_stats
    }

    fn close(&self) -> PoolFuture<'_, ()> {
        Box::pin(async move {
            #[cfg(feature = "metrics")]
            let idle_count: usize;

            let waiters = {
                let mut state = self.state.lock();
                state.closed = true;
                self.closed.store(true, Ordering::Release);

                // Drain waiters, then wake after releasing the state lock.
                let waiters: SmallVec<[Waker; 4]> =
                    state.waiters.drain(..).map(|waiter| waiter.waker).collect();

                // Record how many idle resources we're clearing (only needed for metrics)
                #[cfg(feature = "metrics")]
                {
                    idle_count = state.idle.len();
                }

                // Clear idle resources
                state.idle.clear();
                waiters
            };

            for waker in waiters {
                waker.wake();
            }

            // Record destroyed metrics for all cleared idle resources
            // (they are being destroyed due to pool shutdown, treat as unhealthy reason)
            #[cfg(feature = "metrics")]
            if let Some(ref metrics) = self.metrics {
                for _ in 0..idle_count {
                    metrics.record_destroyed(DestroyReason::Unhealthy);
                }
                self.update_metrics_gauges();
            }
        })
    }
}

// ============================================================================
// Pool Metrics (OpenTelemetry integration)
// ============================================================================

/// Reason why a resource was destroyed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DestroyReason {
    /// Resource failed health check.
    Unhealthy,
    /// Resource exceeded idle timeout.
    IdleTimeout,
    /// Resource exceeded max lifetime.
    MaxLifetime,
}

impl DestroyReason {
    /// Returns the label value for this destroy reason.
    #[must_use]
    pub const fn as_label(&self) -> &'static str {
        match self {
            Self::Unhealthy => "unhealthy",
            Self::IdleTimeout => "idle_timeout",
            Self::MaxLifetime => "max_lifetime",
        }
    }
}

#[cfg(feature = "metrics")]
mod pool_metrics {
    use super::{DestroyReason, Duration, PoolStats};
    use opentelemetry::KeyValue;
    use opentelemetry::metrics::{Counter, Histogram, Meter, ObservableGauge};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicU64, Ordering};

    /// Shared state backing observable gauges for pool metrics.
    #[derive(Debug, Default)]
    pub struct PoolMetricsState {
        /// Current pool size (active + idle).
        pub size: AtomicU64,
        /// Currently active (checked-out) resources.
        pub active: AtomicU64,
        /// Currently idle (available) resources.
        pub idle: AtomicU64,
        /// Number of waiters in queue.
        pub pending: AtomicU64,
    }

    impl PoolMetricsState {
        /// Creates a new metrics state.
        #[must_use]
        pub fn new() -> Self {
            Self::default()
        }

        /// Update all gauge values from pool stats.
        pub fn update_from_stats(&self, stats: &PoolStats) {
            self.size.store(stats.total as u64, Ordering::Relaxed);
            self.active.store(stats.active as u64, Ordering::Relaxed);
            self.idle.store(stats.idle as u64, Ordering::Relaxed);
            self.pending.store(stats.waiters as u64, Ordering::Relaxed);
        }
    }

    /// OpenTelemetry metrics for resource pools.
    ///
    /// This struct provides comprehensive observability for pool operations including:
    /// - Gauges for current pool state (size, active, idle, pending)
    /// - Counters for operations (acquired, released, created, destroyed, timeouts)
    /// - Histograms for latencies (acquire, hold, wait durations)
    ///
    /// # Example
    ///
    /// ```ignore
    /// use opentelemetry::global;
    /// use asupersync::sync::{GenericPool, PoolConfig, PoolMetrics};
    ///
    /// let meter = global::meter("myapp");
    /// let metrics = PoolMetrics::new(&meter);
    ///
    /// let pool = GenericPool::new(factory, PoolConfig::default())
    ///     .with_metrics("db_pool", metrics.handle());
    /// ```
    #[derive(Clone)]
    pub struct PoolMetrics {
        // Gauges (backed by shared state)
        #[allow(dead_code)]
        size: ObservableGauge<u64>,
        #[allow(dead_code)]
        active: ObservableGauge<u64>,
        #[allow(dead_code)]
        idle: ObservableGauge<u64>,
        #[allow(dead_code)]
        pending: ObservableGauge<u64>,

        // Counters
        acquired_total: Counter<u64>,
        released_total: Counter<u64>,
        created_total: Counter<u64>,
        destroyed_total: Counter<u64>,
        timeouts_total: Counter<u64>,

        // Histograms
        acquire_duration: Histogram<f64>,
        hold_duration: Histogram<f64>,
        wait_duration: Histogram<f64>,

        // Shared state for observable gauges
        state: Arc<PoolMetricsState>,
    }

    impl std::fmt::Debug for PoolMetrics {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("PoolMetrics")
                .field("state", &self.state)
                .finish_non_exhaustive()
        }
    }

    impl PoolMetrics {
        /// Creates a new `PoolMetrics` instance from an OpenTelemetry meter.
        #[must_use]
        pub fn new(meter: &Meter) -> Self {
            let state = Arc::new(PoolMetricsState::new());

            let size = meter
                .u64_observable_gauge("asupersync.pool.size")
                .with_description("Current pool size (active + idle)")
                .with_callback({
                    let state = Arc::clone(&state);
                    move |observer| {
                        observer.observe(state.size.load(Ordering::Relaxed), &[]);
                    }
                })
                .build();

            let active = meter
                .u64_observable_gauge("asupersync.pool.active")
                .with_description("Currently checked-out resources")
                .with_callback({
                    let state = Arc::clone(&state);
                    move |observer| {
                        observer.observe(state.active.load(Ordering::Relaxed), &[]);
                    }
                })
                .build();

            let idle = meter
                .u64_observable_gauge("asupersync.pool.idle")
                .with_description("Available idle resources")
                .with_callback({
                    let state = Arc::clone(&state);
                    move |observer| {
                        observer.observe(state.idle.load(Ordering::Relaxed), &[]);
                    }
                })
                .build();

            let pending = meter
                .u64_observable_gauge("asupersync.pool.pending")
                .with_description("Waiters in queue")
                .with_callback({
                    let state = Arc::clone(&state);
                    move |observer| {
                        observer.observe(state.pending.load(Ordering::Relaxed), &[]);
                    }
                })
                .build();

            let acquired_total = meter
                .u64_counter("asupersync.pool.acquired_total")
                .with_description("Total successful acquires")
                .build();

            let released_total = meter
                .u64_counter("asupersync.pool.released_total")
                .with_description("Total returns to pool")
                .build();

            let created_total = meter
                .u64_counter("asupersync.pool.created_total")
                .with_description("Resources created")
                .build();

            let destroyed_total = meter
                .u64_counter("asupersync.pool.destroyed_total")
                .with_description("Resources destroyed")
                .build();

            let timeouts_total = meter
                .u64_counter("asupersync.pool.timeouts_total")
                .with_description("Acquire timeouts")
                .build();

            let acquire_duration = meter
                .f64_histogram("asupersync.pool.acquire_duration_seconds")
                .with_description("Time to acquire a resource")
                .build();

            let hold_duration = meter
                .f64_histogram("asupersync.pool.hold_duration_seconds")
                .with_description("Time resource is held")
                .build();

            let wait_duration = meter
                .f64_histogram("asupersync.pool.wait_duration_seconds")
                .with_description("Time waiting in queue")
                .build();

            Self {
                size,
                active,
                idle,
                pending,
                acquired_total,
                released_total,
                created_total,
                destroyed_total,
                timeouts_total,
                acquire_duration,
                hold_duration,
                wait_duration,
                state,
            }
        }

        /// Returns a reference to the shared metrics state.
        #[must_use]
        pub fn state(&self) -> &Arc<PoolMetricsState> {
            &self.state
        }

        /// Records a successful acquire operation.
        pub fn record_acquired(&self, pool_name: &str, duration: Duration) {
            let labels = [KeyValue::new("pool_name", pool_name.to_string())];
            self.acquired_total.add(1, &labels);
            self.acquire_duration
                .record(duration.as_secs_f64(), &labels);
        }

        /// Records a resource release (return to pool).
        pub fn record_released(&self, pool_name: &str, hold_duration: Duration) {
            let labels = [KeyValue::new("pool_name", pool_name.to_string())];
            self.released_total.add(1, &labels);
            self.hold_duration
                .record(hold_duration.as_secs_f64(), &labels);
        }

        /// Records a resource creation.
        pub fn record_created(&self, pool_name: &str) {
            let labels = [KeyValue::new("pool_name", pool_name.to_string())];
            self.created_total.add(1, &labels);
        }

        /// Records a resource destruction.
        pub fn record_destroyed(&self, pool_name: &str, reason: DestroyReason) {
            let labels = [
                KeyValue::new("pool_name", pool_name.to_string()),
                KeyValue::new("reason", reason.as_label()),
            ];
            self.destroyed_total.add(1, &labels);
        }

        /// Records an acquire timeout.
        pub fn record_timeout(&self, pool_name: &str, wait_duration: Duration) {
            let labels = [KeyValue::new("pool_name", pool_name.to_string())];
            self.timeouts_total.add(1, &labels);
            self.wait_duration
                .record(wait_duration.as_secs_f64(), &labels);
        }

        /// Records time spent waiting in queue (for successful acquires after waiting).
        pub fn record_wait(&self, pool_name: &str, wait_duration: Duration) {
            let labels = [KeyValue::new("pool_name", pool_name.to_string())];
            self.wait_duration
                .record(wait_duration.as_secs_f64(), &labels);
        }

        /// Updates gauge values from pool statistics.
        pub fn update_gauges(&self, stats: &PoolStats) {
            self.state.update_from_stats(stats);
        }

        /// Creates a handle for a named pool.
        #[must_use]
        pub fn handle(&self, pool_name: impl Into<String>) -> PoolMetricsHandle {
            let pool_name = pool_name.into();
            let labels = [KeyValue::new("pool_name", pool_name.clone())];
            PoolMetricsHandle {
                metrics: self.clone(),
                pool_name,
                labels,
            }
        }
    }

    /// Handle to pool metrics with a specific pool name.
    ///
    /// This struct wraps `PoolMetrics` and binds it to a specific pool name,
    /// automatically adding the `pool_name` label to all recorded metrics.
    /// The label is pre-computed once at construction to avoid per-call
    /// String allocation.
    #[derive(Clone)]
    pub struct PoolMetricsHandle {
        metrics: PoolMetrics,
        pool_name: String,
        labels: [KeyValue; 1],
    }

    impl std::fmt::Debug for PoolMetricsHandle {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("PoolMetricsHandle")
                .field("pool_name", &self.pool_name)
                .finish_non_exhaustive()
        }
    }

    impl PoolMetricsHandle {
        /// Returns the pool name for this handle.
        #[must_use]
        pub fn pool_name(&self) -> &str {
            &self.pool_name
        }

        /// Records a successful acquire operation.
        pub fn record_acquired(&self, duration: Duration) {
            self.metrics.acquired_total.add(1, &self.labels);
            self.metrics
                .acquire_duration
                .record(duration.as_secs_f64(), &self.labels);
        }

        /// Records a resource release (return to pool).
        pub fn record_released(&self, hold_duration: Duration) {
            self.metrics.released_total.add(1, &self.labels);
            self.metrics
                .hold_duration
                .record(hold_duration.as_secs_f64(), &self.labels);
        }

        /// Records a resource creation.
        pub fn record_created(&self) {
            self.metrics.created_total.add(1, &self.labels);
        }

        /// Records a resource destruction.
        pub fn record_destroyed(&self, reason: DestroyReason) {
            let labels = [
                self.labels[0].clone(),
                KeyValue::new("reason", reason.as_label()),
            ];
            self.metrics.destroyed_total.add(1, &labels);
        }

        /// Records an acquire timeout.
        pub fn record_timeout(&self, wait_duration: Duration) {
            self.metrics.timeouts_total.add(1, &self.labels);
            self.metrics
                .wait_duration
                .record(wait_duration.as_secs_f64(), &self.labels);
        }

        /// Records time spent waiting in queue.
        pub fn record_wait(&self, wait_duration: Duration) {
            self.metrics
                .wait_duration
                .record(wait_duration.as_secs_f64(), &self.labels);
        }

        /// Updates gauge values from pool statistics.
        pub fn update_gauges(&self, stats: &PoolStats) {
            self.metrics.update_gauges(stats);
        }

        /// Returns a reference to the underlying metrics state.
        #[must_use]
        pub fn state(&self) -> &Arc<PoolMetricsState> {
            self.metrics.state()
        }
    }
}

#[cfg(feature = "metrics")]
pub use pool_metrics::{PoolMetrics, PoolMetricsHandle, PoolMetricsState};

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::{Cell, RefCell};
    use std::sync::Arc;
    use std::task::{Context, Poll, Waker};

    use crate::Time;
    use crate::time::{TimerDriverHandle, VirtualClock};
    use crate::types::{Budget, RegionId, TaskId};

    std::thread_local! {
        static TEST_POOL_TIME_BASE: RefCell<Option<Instant>> = const { RefCell::new(None) };
        static TEST_POOL_TIME_OFFSET_NANOS: Cell<u64> = const { Cell::new(0) };
    }

    fn test_pool_time_now() -> Instant {
        let offset = TEST_POOL_TIME_OFFSET_NANOS.with(Cell::get);
        TEST_POOL_TIME_BASE.with(|base| {
            let mut base = base.borrow_mut();
            let base_instant = *base.get_or_insert_with(Instant::now);
            base_instant
                .checked_add(Duration::from_nanos(offset))
                .unwrap_or(base_instant)
        })
    }

    fn reset_test_pool_time() {
        TEST_POOL_TIME_BASE.with(|base| {
            *base.borrow_mut() = None;
        });
        TEST_POOL_TIME_OFFSET_NANOS.with(|offset| offset.set(0));
    }

    fn set_test_pool_time_offset(offset: Duration) {
        let nanos = offset.as_nanos().min(u128::from(u64::MAX)) as u64;
        TEST_POOL_TIME_OFFSET_NANOS.with(|value| value.set(nanos));
    }

    fn advance_test_pool_time(delta: Duration) {
        let nanos = delta.as_nanos().min(u128::from(u64::MAX)) as u64;
        TEST_POOL_TIME_OFFSET_NANOS.with(|offset| {
            offset.set(offset.get().saturating_add(nanos));
        });
    }

    fn init_test(name: &str) {
        reset_test_pool_time();
        crate::test_utils::init_test_logging();
        crate::test_phase!(name);
    }

    fn test_cx_with_timer(timer: TimerDriverHandle) -> Cx {
        Cx::new_with_drivers(
            RegionId::new_for_test(0, 0),
            TaskId::new_for_test(0, 0),
            Budget::INFINITE,
            None,
            None,
            None,
            Some(timer),
            None,
        )
    }

    fn test_cx_with_timer_and_budget(timer: TimerDriverHandle, budget: Budget) -> Cx {
        Cx::new_with_drivers(
            RegionId::new_for_test(0, 0),
            TaskId::new_for_test(0, 0),
            budget,
            None,
            None,
            None,
            Some(timer),
            None,
        )
    }

    struct ReentrantReturnWaker {
        return_wakers: ReturnWakers,
        tx: mpsc::Sender<bool>,
    }

    use std::task::Wake;
    impl Wake for ReentrantReturnWaker {
        fn wake(self: Arc<Self>) {
            self.wake_by_ref();
        }

        fn wake_by_ref(self: &Arc<Self>) {
            let lock_was_free = self.return_wakers.try_lock().is_some();
            let _ = self.tx.send(lock_was_free);
        }
    }

    #[test]
    fn pooled_resource_returns_on_drop() {
        init_test("pooled_resource_returns_on_drop");
        let (tx, rx) = mpsc::channel();
        let pooled = PooledResource::new(42u8, tx);
        drop(pooled);

        let msg = rx.recv().expect("return message");
        match msg {
            PoolReturn::Return {
                resource: value,
                hold_duration: _,
                ..
            } => {
                crate::assert_with_log!(value == 42, "return value", 42u8, value);
            }
            PoolReturn::Discard { .. } => unreachable!("unexpected discard"),
        }
        crate::test_complete!("pooled_resource_returns_on_drop");
    }

    #[test]
    fn pooled_resource_return_to_pool_sends_return() {
        init_test("pooled_resource_return_to_pool_sends_return");
        let (tx, rx) = mpsc::channel();
        let pooled = PooledResource::new(7u8, tx);
        pooled.return_to_pool();

        let msg = rx.recv().expect("return message");
        match msg {
            PoolReturn::Return {
                resource: value,
                hold_duration: _,
                ..
            } => {
                crate::assert_with_log!(value == 7, "return value", 7u8, value);
            }
            PoolReturn::Discard { .. } => unreachable!("unexpected discard"),
        }
        crate::test_complete!("pooled_resource_return_to_pool_sends_return");
    }

    #[test]
    fn pooled_resource_return_hold_duration_uses_time_getter() {
        init_test("pooled_resource_return_hold_duration_uses_time_getter");
        let (tx, rx) = mpsc::channel();
        let pooled = PooledResource::new_with_time_getter(7u8, tx, test_pool_time_now);

        advance_test_pool_time(Duration::from_millis(15));
        pooled.return_to_pool();

        let msg = rx.recv().expect("return message");
        match msg {
            PoolReturn::Return {
                resource: value,
                hold_duration,
                ..
            } => {
                crate::assert_with_log!(value == 7, "return value", 7u8, value);
                crate::assert_with_log!(
                    hold_duration == Duration::from_millis(15),
                    "hold duration uses injected time getter",
                    Duration::from_millis(15),
                    hold_duration
                );
            }
            PoolReturn::Discard { .. } => unreachable!("unexpected discard"),
        }

        crate::test_complete!("pooled_resource_return_hold_duration_uses_time_getter");
    }

    #[test]
    fn pooled_resource_notifies_wakers_outside_return_waker_lock() {
        init_test("pooled_resource_notifies_wakers_outside_return_waker_lock");
        let (return_tx, _return_rx) = mpsc::channel();
        let return_wakers = Arc::new(PoolMutex::new(ReturnWakerList::new()));
        let (probe_tx, probe_rx) = mpsc::channel();

        {
            let probe = Arc::new(ReentrantReturnWaker {
                return_wakers: Arc::clone(&return_wakers),
                tx: probe_tx,
            });
            let mut wakers = return_wakers.lock();
            wakers.push((1, Waker::from(probe)));
        }

        let pooled =
            PooledResource::new(7u8, return_tx).with_return_notify(Arc::clone(&return_wakers));
        pooled.return_to_pool();

        let lock_was_free = probe_rx
            .recv_timeout(Duration::from_secs(1))
            .expect("probe wake result");
        crate::assert_with_log!(
            lock_was_free,
            "waker should run after return_wakers lock is released",
            true,
            lock_was_free
        );
        crate::test_complete!("pooled_resource_notifies_wakers_outside_return_waker_lock");
    }

    #[test]
    fn pooled_resource_discard_sends_discard() {
        init_test("pooled_resource_discard_sends_discard");
        let (tx, rx) = mpsc::channel();
        let pooled = PooledResource::new(9u8, tx);
        pooled.discard();

        let msg = rx.recv().expect("return message");
        match msg {
            PoolReturn::Return { .. } => unreachable!("unexpected return"),
            PoolReturn::Discard { hold_duration: _ } => {
                crate::assert_with_log!(true, "discard", true, true);
            }
        }
        crate::test_complete!("pooled_resource_discard_sends_discard");
    }

    #[test]
    fn pooled_resource_discard_hold_duration_uses_time_getter() {
        init_test("pooled_resource_discard_hold_duration_uses_time_getter");
        let (tx, rx) = mpsc::channel();
        let pooled = PooledResource::new_with_time_getter(9u8, tx, test_pool_time_now);

        advance_test_pool_time(Duration::from_millis(12));
        pooled.discard();

        let msg = rx.recv().expect("return message");
        match msg {
            PoolReturn::Return { .. } => unreachable!("unexpected return"),
            PoolReturn::Discard { hold_duration } => {
                crate::assert_with_log!(
                    hold_duration == Duration::from_millis(12),
                    "discard hold duration uses injected time getter",
                    Duration::from_millis(12),
                    hold_duration
                );
            }
        }

        crate::test_complete!("pooled_resource_discard_hold_duration_uses_time_getter");
    }

    #[test]
    fn pooled_resource_deref_access() {
        init_test("pooled_resource_deref_access");
        let (tx, _rx) = mpsc::channel();
        let mut pooled = PooledResource::new(1u8, tx);
        *pooled = 3;
        crate::assert_with_log!(*pooled == 3, "deref", 3u8, *pooled);
        crate::test_complete!("pooled_resource_deref_access");
    }

    // ========================================================================
    // PoolConfig tests
    // ========================================================================

    #[test]
    fn pool_config_default() {
        init_test("pool_config_default");
        let config = PoolConfig::default();
        crate::assert_with_log!(config.min_size == 1, "min_size", 1usize, config.min_size);
        crate::assert_with_log!(config.max_size == 10, "max_size", 10usize, config.max_size);
        crate::assert_with_log!(
            config.acquire_timeout == Duration::from_secs(30),
            "acquire_timeout",
            Duration::from_secs(30),
            config.acquire_timeout
        );
        crate::assert_with_log!(
            config.idle_timeout == Duration::from_mins(10),
            "idle_timeout",
            Duration::from_mins(10),
            config.idle_timeout
        );
        crate::assert_with_log!(
            config.max_lifetime == Duration::from_hours(1),
            "max_lifetime",
            Duration::from_hours(1),
            config.max_lifetime
        );
        crate::test_complete!("pool_config_default");
    }

    #[test]
    fn pool_config_builder() {
        init_test("pool_config_builder");
        let config = PoolConfig::with_max_size(20)
            .min_size(5)
            .acquire_timeout(Duration::from_secs(60))
            .idle_timeout(Duration::from_secs(300))
            .max_lifetime(Duration::from_secs(1800));

        crate::assert_with_log!(config.min_size == 5, "min_size", 5usize, config.min_size);
        crate::assert_with_log!(config.max_size == 20, "max_size", 20usize, config.max_size);
        crate::assert_with_log!(
            config.acquire_timeout == Duration::from_secs(60),
            "acquire_timeout",
            Duration::from_secs(60),
            config.acquire_timeout
        );
        crate::assert_with_log!(
            config.idle_timeout == Duration::from_secs(300),
            "idle_timeout",
            Duration::from_secs(300),
            config.idle_timeout
        );
        crate::assert_with_log!(
            config.max_lifetime == Duration::from_secs(1800),
            "max_lifetime",
            Duration::from_secs(1800),
            config.max_lifetime
        );
        crate::test_complete!("pool_config_builder");
    }

    // ========================================================================
    // GenericPool tests
    // ========================================================================

    #[allow(clippy::type_complexity)]
    fn simple_factory() -> std::pin::Pin<
        Box<dyn Future<Output = Result<u32, Box<dyn std::error::Error + Send + Sync>>> + Send>,
    > {
        Box::pin(async { Ok(42u32) })
    }

    struct TimeoutAfterNSuccessesFactory {
        successes: u32,
        next_attempt: std::sync::atomic::AtomicU32,
    }

    impl AsyncResourceFactory for TimeoutAfterNSuccessesFactory {
        type Resource = u32;
        type Error = Box<dyn std::error::Error + Send + Sync>;

        fn create(
            &self,
        ) -> Pin<Box<dyn Future<Output = Result<Self::Resource, Self::Error>> + Send + '_>>
        {
            let attempt = self
                .next_attempt
                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            let successes = self.successes;
            Box::pin(async move {
                if attempt < successes {
                    Ok(attempt)
                } else {
                    std::future::pending::<Result<u32, Box<dyn std::error::Error + Send + Sync>>>()
                        .await
                }
            })
        }
    }

    #[test]
    fn generic_pool_stats_initial() {
        init_test("generic_pool_stats_initial");
        let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(5));
        let stats = pool.stats();
        crate::assert_with_log!(stats.active == 0, "active", 0usize, stats.active);
        crate::assert_with_log!(stats.idle == 0, "idle", 0usize, stats.idle);
        crate::assert_with_log!(stats.total == 0, "total", 0usize, stats.total);
        crate::assert_with_log!(stats.max_size == 5, "max_size", 5usize, stats.max_size);
        crate::test_complete!("generic_pool_stats_initial");
    }

    #[test]
    fn create_slot_reservation_enforces_max_size_and_releases_on_drop() {
        init_test("create_slot_reservation_enforces_max_size_and_releases_on_drop");
        let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(1));

        let slot1 = CreateSlotReservation::try_reserve(&pool, None);
        crate::assert_with_log!(
            slot1.is_some(),
            "first slot reserved",
            true,
            slot1.is_some()
        );

        let slot2 = CreateSlotReservation::try_reserve(&pool, None);
        crate::assert_with_log!(
            slot2.is_none(),
            "second slot blocked at max_size=1",
            true,
            slot2.is_none()
        );

        drop(slot1);

        let slot3 = CreateSlotReservation::try_reserve(&pool, None);
        crate::assert_with_log!(
            slot3.is_some(),
            "slot released when reservation dropped",
            true,
            slot3.is_some()
        );
        if let Some(slot) = slot3 {
            slot.commit();
        }

        let stats = pool.stats();
        crate::assert_with_log!(
            stats.active == 1,
            "commit converts reserved slot to active resource",
            1usize,
            stats.active
        );
        crate::test_complete!("create_slot_reservation_enforces_max_size_and_releases_on_drop");
    }

    #[test]
    fn pool_stats_total_includes_creating_slots() {
        init_test("pool_stats_total_includes_creating_slots");

        // Verify that PoolStats::total includes in-flight creates (the `creating`
        // counter), not just active + idle. This ensures monitoring accurately
        // reflects actual capacity usage.
        let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(3));

        // Reserve a create slot (simulates async resource creation in progress)
        let slot = CreateSlotReservation::try_reserve(&pool, None);
        assert!(slot.is_some(), "should reserve a create slot");

        let stats = pool.stats();
        // total should be 1 (0 active + 0 idle + 1 creating)
        crate::assert_with_log!(
            stats.total == 1,
            "total includes creating slot",
            1usize,
            stats.total
        );

        // Drop the reservation without committing (simulates cancelled create)
        drop(slot);

        let stats = pool.stats();
        crate::assert_with_log!(
            stats.total == 0,
            "total after released creating slot",
            0usize,
            stats.total
        );

        crate::test_complete!("pool_stats_total_includes_creating_slots");
    }

    #[test]
    fn drop_delegates_to_return_inner_no_double_send() {
        init_test("drop_delegates_to_return_inner_no_double_send");

        // Verify that Drop delegates to return_inner and does not
        // produce double sends on the return channel.
        let (tx, rx) = mpsc::channel();
        {
            let _pooled = PooledResource::new(55u8, tx);
            // _pooled dropped here
        }

        let msg = rx
            .recv()
            .expect("should receive exactly one return message");
        match msg {
            PoolReturn::Return {
                resource: value, ..
            } => {
                crate::assert_with_log!(value == 55, "returned value", 55u8, value);
            }
            PoolReturn::Discard { .. } => unreachable!("expected Return, got Discard"),
        }

        // Verify no second message (no double-send from duplicated drop logic)
        crate::assert_with_log!(
            rx.try_recv().is_err(),
            "no double send from Drop",
            true,
            rx.try_recv().is_err()
        );

        crate::test_complete!("drop_delegates_to_return_inner_no_double_send");
    }

    #[test]
    fn pooled_resource_is_send_when_resource_is_send() {
        fn assert_send<T: Send>() {}

        init_test("pooled_resource_is_send_when_resource_is_send");

        // Verify that PooledResource<R> auto-derives Send when R: Send
        // (no manual unsafe impl needed).
        assert_send::<PooledResource<u8>>();
        assert_send::<PooledResource<String>>();
        assert_send::<PooledResource<Vec<u8>>>();

        crate::test_complete!("pooled_resource_is_send_when_resource_is_send");
    }

    #[test]
    fn generic_pool_try_acquire_creates_resource() {
        init_test("generic_pool_try_acquire_creates_resource");

        // Need to use a runtime to test async behavior
        // For now, test try_acquire which returns None since pool is empty
        let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(5));

        // try_acquire returns None when pool is empty (no pre-created resources)
        let result = pool.try_acquire();
        crate::assert_with_log!(
            result.is_none(),
            "try_acquire empty",
            true,
            result.is_none()
        );

        crate::test_complete!("generic_pool_try_acquire_creates_resource");
    }

    #[test]
    fn pool_error_display() {
        init_test("pool_error_display");

        let closed = PoolError::Closed;
        let timeout = PoolError::Timeout;
        let cancelled = PoolError::Cancelled;
        let create_failed = PoolError::CreateFailed(Box::new(std::io::Error::other("test error")));

        crate::assert_with_log!(
            closed.to_string() == "pool closed",
            "closed display",
            "pool closed",
            closed.to_string()
        );
        crate::assert_with_log!(
            timeout.to_string() == "pool acquire timeout",
            "timeout display",
            "pool acquire timeout",
            timeout.to_string()
        );
        crate::assert_with_log!(
            cancelled.to_string() == "pool acquire cancelled",
            "cancelled display",
            "pool acquire cancelled",
            cancelled.to_string()
        );
        crate::assert_with_log!(
            create_failed
                .to_string()
                .contains("resource creation failed"),
            "create_failed display",
            "contains resource creation failed",
            create_failed.to_string()
        );

        crate::test_complete!("pool_error_display");
    }

    // ========================================================================
    // Cancel-safety tests
    // ========================================================================

    #[test]
    fn cancel_while_holding_resource_returns_on_drop() {
        init_test("cancel_while_holding_resource_returns_on_drop");

        // This test verifies that when a task holding a pooled resource is
        // cancelled, the resource is properly returned to the pool via the
        // Drop implementation.

        let (tx, rx) = mpsc::channel();
        let pooled = PooledResource::new(99u8, tx);

        // Simulate cancellation by just dropping the resource
        // In a real scenario, cancellation would cause the future to be dropped
        drop(pooled);

        // Verify resource was returned
        let msg = rx.recv().expect("should receive return message");
        match msg {
            PoolReturn::Return {
                resource: value,
                hold_duration: _,
                ..
            } => {
                crate::assert_with_log!(value == 99, "returned value", 99u8, value);
            }
            PoolReturn::Discard { .. } => unreachable!("expected Return, got Discard"),
        }

        // Verify channel is empty (exactly one return)
        crate::assert_with_log!(
            rx.try_recv().is_err(),
            "no extra messages",
            true,
            rx.try_recv().is_err()
        );

        crate::test_complete!("cancel_while_holding_resource_returns_on_drop");
    }

    #[test]
    fn obligation_discharged_prevents_double_return() {
        init_test("obligation_discharged_prevents_double_return");

        // Test that explicitly returning a resource prevents the Drop from
        // returning it again (no double-return bug).

        let (tx, rx) = mpsc::channel();
        let pooled = PooledResource::new(77u8, tx);

        // Explicitly return
        pooled.return_to_pool();

        // Verify exactly one return message
        let msg = rx.recv().expect("should receive return message");
        match msg {
            PoolReturn::Return {
                resource: value,
                hold_duration: _,
                ..
            } => {
                crate::assert_with_log!(value == 77, "returned value", 77u8, value);
            }
            PoolReturn::Discard { .. } => unreachable!("expected Return, got Discard"),
        }

        // No second message (drop should not send again)
        crate::assert_with_log!(
            rx.try_recv().is_err(),
            "no double return",
            true,
            rx.try_recv().is_err()
        );

        crate::test_complete!("obligation_discharged_prevents_double_return");
    }

    #[test]
    fn discard_prevents_return_on_drop() {
        init_test("discard_prevents_return_on_drop");

        // Test that discarding a resource prevents the Drop from returning it.

        let (tx, rx) = mpsc::channel();
        let pooled = PooledResource::new(88u8, tx);

        // Explicitly discard
        pooled.discard();

        // Verify we got a discard message
        let msg = rx.recv().expect("should receive discard message");
        match msg {
            PoolReturn::Return { .. } => unreachable!("expected Discard, got Return"),
            PoolReturn::Discard { hold_duration: _ } => {
                // Good - discard was sent
            }
        }

        // No second message
        crate::assert_with_log!(
            rx.try_recv().is_err(),
            "no extra messages after discard",
            true,
            rx.try_recv().is_err()
        );

        crate::test_complete!("discard_prevents_return_on_drop");
    }

    #[test]
    fn generic_pool_close_clears_idle_resources() {
        init_test("generic_pool_close_clears_idle_resources");

        let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(5));

        // Close the pool
        futures_lite::future::block_on(pool.close());

        // Verify pool is closed - try_acquire should return None
        let result = pool.try_acquire();
        crate::assert_with_log!(
            result.is_none(),
            "closed pool returns None",
            true,
            result.is_none()
        );

        // Stats should show empty
        let stats = pool.stats();
        crate::assert_with_log!(stats.idle == 0, "idle after close", 0usize, stats.idle);

        crate::test_complete!("generic_pool_close_clears_idle_resources");
    }

    #[test]
    fn generic_pool_acquire_when_closed_returns_error() {
        init_test("generic_pool_acquire_when_closed_returns_error");

        let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(5));
        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        // Close the pool
        futures_lite::future::block_on(pool.close());

        // Acquire should return Closed error
        let result = futures_lite::future::block_on(pool.acquire(&cx));
        match result {
            Err(PoolError::Closed) => {
                // Good - closed error as expected
            }
            Ok(_) => unreachable!("expected Closed error, got Ok"),
            Err(e) => unreachable!("expected Closed error, got {e:?}"),
        }

        crate::test_complete!("generic_pool_acquire_when_closed_returns_error");
    }

    #[test]
    fn generic_pool_resource_returned_becomes_idle() {
        init_test("generic_pool_resource_returned_becomes_idle");

        let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(5));
        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        // Acquire a resource
        let resource = futures_lite::future::block_on(pool.acquire(&cx))
            .expect("first acquire should succeed");

        // Check stats - should show 1 active
        let stats = pool.stats();
        crate::assert_with_log!(
            stats.active == 1,
            "active after acquire",
            1usize,
            stats.active
        );
        crate::assert_with_log!(stats.idle == 0, "idle after acquire", 0usize, stats.idle);

        // Return the resource
        resource.return_to_pool();

        // Process returns and check stats
        let stats = pool.stats();
        crate::assert_with_log!(
            stats.active == 0,
            "active after return",
            0usize,
            stats.active
        );
        crate::assert_with_log!(stats.idle == 1, "idle after return", 1usize, stats.idle);

        crate::test_complete!("generic_pool_resource_returned_becomes_idle");
    }

    #[test]
    fn generic_pool_discarded_resource_not_returned_to_idle() {
        init_test("generic_pool_discarded_resource_not_returned_to_idle");

        let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(5));
        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        // Acquire a resource
        let resource = futures_lite::future::block_on(pool.acquire(&cx))
            .expect("first acquire should succeed");

        // Discard the resource (simulating a broken connection)
        resource.discard();

        // Process returns and check stats - should show 0 idle (discarded resources don't return)
        let stats = pool.stats();
        crate::assert_with_log!(
            stats.active == 0,
            "active after discard",
            0usize,
            stats.active
        );
        crate::assert_with_log!(stats.idle == 0, "idle after discard", 0usize, stats.idle);

        crate::test_complete!("generic_pool_discarded_resource_not_returned_to_idle");
    }

    #[test]
    fn generic_pool_held_duration_increases() {
        init_test("generic_pool_held_duration_increases");

        let (tx, _rx) = mpsc::channel();
        let pooled = PooledResource::new_with_time_getter(42u8, tx, test_pool_time_now);
        advance_test_pool_time(Duration::from_millis(10));

        let held = pooled.held_duration();
        crate::assert_with_log!(
            held == Duration::from_millis(10),
            "held duration follows injected clock exactly",
            Duration::from_millis(10),
            held
        );

        crate::test_complete!("generic_pool_held_duration_increases");
    }

    #[test]
    fn load_test_many_acquire_return_cycles() {
        init_test("load_test_many_acquire_return_cycles");

        let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(5));
        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        // Run many acquire/return cycles
        for i in 0..100 {
            let resource =
                futures_lite::future::block_on(pool.acquire(&cx)).expect("acquire should succeed");

            // Use the resource
            let _ = *resource;

            // Return it (or drop it - both should work)
            if i % 2 == 0 {
                resource.return_to_pool();
            } else {
                drop(resource);
            }
        }

        // Final stats check
        let stats = pool.stats();
        crate::assert_with_log!(
            stats.active == 0,
            "no active after all returned",
            0usize,
            stats.active
        );
        crate::assert_with_log!(
            stats.total_acquisitions == 100,
            "100 total acquisitions",
            100u64,
            stats.total_acquisitions
        );

        crate::test_complete!("load_test_many_acquire_return_cycles");
    }

    #[test]
    fn record_wait_time_accumulates_in_pool_stats() {
        init_test("record_wait_time_accumulates_in_pool_stats");

        let pool = GenericPool::new(
            simple_factory,
            PoolConfig::with_max_size(1).acquire_timeout(Duration::from_secs(1)),
        );
        let before = pool.stats().total_wait_time;

        pool.record_wait_time(Duration::from_millis(15));
        pool.record_wait_time(Duration::ZERO);

        let stats = pool.stats();
        assert!(
            stats.total_wait_time >= before + Duration::from_millis(15),
            "recorded wait time should be reflected in pool stats, got {:?}",
            stats.total_wait_time
        );

        crate::test_complete!("record_wait_time_accumulates_in_pool_stats");
    }

    #[test]
    fn acquire_timeout_reports_timeout_and_cleans_waiter_state() {
        init_test("acquire_timeout_reports_timeout_and_cleans_waiter_state");

        let clock = Arc::new(VirtualClock::starting_at(Time::ZERO));
        let timer = TimerDriverHandle::with_virtual_clock(clock.clone());
        let cx = test_cx_with_timer(timer.clone());
        let _guard = Cx::set_current(Some(cx.clone()));
        let pool = GenericPool::with_time_getter(
            simple_factory,
            PoolConfig::with_max_size(1).acquire_timeout(Duration::from_millis(25)),
            test_pool_time_now,
        );

        // Hold the only slot so the next acquire must wait and hit timeout.
        let held = futures_lite::future::block_on(pool.acquire(&cx)).expect("first acquire");

        let waker = noop_pool_waker();
        let mut task_cx = Context::from_waker(&waker);
        let mut acquire_fut = std::pin::pin!(pool.acquire(&cx));

        let first_poll = acquire_fut.as_mut().poll(&mut task_cx);
        crate::assert_with_log!(
            first_poll.is_pending(),
            "second acquire should block while pool is exhausted",
            true,
            first_poll.is_pending()
        );
        crate::assert_with_log!(
            pool.stats().waiters == 1,
            "blocked acquire should register exactly one waiter",
            1usize,
            pool.stats().waiters
        );

        advance_test_pool_time(Duration::from_millis(25));
        clock.advance(Time::from_millis(25).as_nanos());
        let _ = timer.process_timers();

        let result = acquire_fut.as_mut().poll(&mut task_cx);

        assert!(
            matches!(result, Poll::Ready(Err(PoolError::Timeout))),
            "second acquire should timeout when pool remains exhausted"
        );

        // Waiter cleanup and wait-time accounting must run even on timeout.
        let stats = pool.stats();
        assert_eq!(stats.waiters, 0, "timeout should not leak waiters");
        assert!(
            stats.total_wait_time == Duration::from_millis(25),
            "timeout wait should be accounted in pool stats; got {got:?}",
            got = stats.total_wait_time
        );

        held.return_to_pool();
        crate::test_complete!("acquire_timeout_reports_timeout_and_cleans_waiter_state");
    }

    #[test]
    fn acquire_budget_deadline_wakes_and_cancels_waiter() {
        init_test("acquire_budget_deadline_wakes_and_cancels_waiter");

        struct FlagWake(Arc<std::sync::atomic::AtomicBool>);

        impl Wake for FlagWake {
            fn wake(self: Arc<Self>) {
                self.0.store(true, std::sync::atomic::Ordering::SeqCst);
            }

            fn wake_by_ref(self: &Arc<Self>) {
                self.0.store(true, std::sync::atomic::Ordering::SeqCst);
            }
        }

        let clock = Arc::new(VirtualClock::starting_at(Time::ZERO));
        let timer = TimerDriverHandle::with_virtual_clock(clock.clone());
        let holding_cx = test_cx_with_timer(timer.clone());
        let deadline_cx = test_cx_with_timer_and_budget(
            timer.clone(),
            Budget::new().with_deadline(Time::from_millis(10)),
        );
        let _guard = Cx::set_current(Some(deadline_cx.clone()));
        let pool = GenericPool::with_time_getter(
            simple_factory,
            PoolConfig::with_max_size(1).acquire_timeout(Duration::from_secs(1)),
            test_pool_time_now,
        );

        let held =
            futures_lite::future::block_on(pool.acquire(&holding_cx)).expect("first acquire");
        let wake_flag = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let waker = Waker::from(Arc::new(FlagWake(Arc::clone(&wake_flag))));
        let mut task_cx = Context::from_waker(&waker);
        let mut acquire_fut = std::pin::pin!(pool.acquire(&deadline_cx));

        let first_poll = acquire_fut.as_mut().poll(&mut task_cx);
        crate::assert_with_log!(
            first_poll.is_pending(),
            "deadline-bound waiter should block while pool is exhausted",
            true,
            first_poll.is_pending()
        );

        advance_test_pool_time(Duration::from_millis(10));
        clock.advance(Time::from_millis(10).as_nanos());
        let _ = timer.process_timers();

        crate::assert_with_log!(
            wake_flag.load(std::sync::atomic::Ordering::SeqCst),
            "budget deadline should wake blocked acquire before pool timeout",
            true,
            wake_flag.load(std::sync::atomic::Ordering::SeqCst)
        );

        let result = acquire_fut.as_mut().poll(&mut task_cx);
        assert!(
            matches!(result, Poll::Ready(Err(PoolError::Cancelled))),
            "budget deadline should cancel blocked acquire"
        );

        let stats = pool.stats();
        assert_eq!(
            stats.waiters, 0,
            "deadline cancellation must not leak waiters"
        );

        held.return_to_pool();
        crate::test_complete!("acquire_budget_deadline_wakes_and_cancels_waiter");
    }

    #[test]
    fn cancelled_waiter_does_not_acquire_returned_resource() {
        init_test("cancelled_waiter_does_not_acquire_returned_resource");

        let clock = Arc::new(VirtualClock::starting_at(Time::ZERO));
        let timer = TimerDriverHandle::with_virtual_clock(clock.clone());
        let holding_cx = test_cx_with_timer(timer.clone());
        let deadline_cx = test_cx_with_timer_and_budget(
            timer.clone(),
            Budget::new().with_deadline(Time::from_millis(10)),
        );
        let _guard = Cx::set_current(Some(deadline_cx.clone()));
        let pool = GenericPool::with_time_getter(
            simple_factory,
            PoolConfig::with_max_size(1).acquire_timeout(Duration::from_secs(1)),
            test_pool_time_now,
        );

        let held =
            futures_lite::future::block_on(pool.acquire(&holding_cx)).expect("first acquire");
        let waker = noop_pool_waker();
        let mut task_cx = Context::from_waker(&waker);
        let mut acquire_fut = std::pin::pin!(pool.acquire(&deadline_cx));

        let first_poll = acquire_fut.as_mut().poll(&mut task_cx);
        crate::assert_with_log!(
            first_poll.is_pending(),
            "deadline-bound waiter should enter the wait queue",
            true,
            first_poll.is_pending()
        );

        advance_test_pool_time(Duration::from_millis(10));
        clock.advance(Time::from_millis(10).as_nanos());

        held.return_to_pool();

        let result = acquire_fut.as_mut().poll(&mut task_cx);
        assert!(
            matches!(result, Poll::Ready(Err(PoolError::Cancelled))),
            "expired waiter must not consume a returned resource"
        );

        let stats = pool.stats();
        assert_eq!(stats.active, 0, "cancelled waiter must not become active");
        assert_eq!(stats.idle, 1, "returned resource should remain idle");
        assert_eq!(stats.waiters, 0, "cancelled waiter must be cleaned up");

        crate::test_complete!("cancelled_waiter_does_not_acquire_returned_resource");
    }

    // ========================================================================
    // Health check tests (asupersync-cl94)
    // ========================================================================

    #[test]
    fn health_check_evicts_unhealthy_idle_resource() {
        init_test("health_check_evicts_unhealthy_idle_resource");

        // Factory produces (id, healthy_flag) tuples
        let counter = std::sync::atomic::AtomicU32::new(0);
        let factory = move || {
            let id = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Box::pin(async move { Ok::<_, Box<dyn std::error::Error + Send + Sync>>((id, true)) })
                as std::pin::Pin<Box<dyn Future<Output = _> + Send>>
        };

        let config = PoolConfig::with_max_size(5).health_check_on_acquire(true);
        // Health check: only resources with id != 0 pass
        let pool = GenericPool::new(factory, config)
            .with_health_check(|&(id, _healthy): &(u32, bool)| id != 0);

        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        // Acquire resource #0
        let r0 = futures_lite::future::block_on(pool.acquire(&cx)).expect("first acquire");
        assert_eq!(r0.0, 0u32, "first resource should be id 0");
        // Return it to the idle pool
        r0.return_to_pool();

        // Now acquire again — id 0 should fail health check, so pool creates id 1
        let r1 = futures_lite::future::block_on(pool.acquire(&cx)).expect("second acquire");
        assert_eq!(r1.0, 1u32, "unhealthy id 0 should be evicted, got new id 1");

        let stats = pool.stats();
        assert_eq!(stats.active, 1, "one resource active");
        assert_eq!(stats.idle, 0, "no idle resources (id 0 was evicted)");

        crate::test_complete!("health_check_evicts_unhealthy_idle_resource");
    }

    #[test]
    fn health_check_passes_healthy_resource() {
        init_test("health_check_passes_healthy_resource");

        let counter = std::sync::atomic::AtomicU32::new(0);
        let factory = move || {
            let id = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Box::pin(async move { Ok::<_, Box<dyn std::error::Error + Send + Sync>>(id) })
                as std::pin::Pin<Box<dyn Future<Output = _> + Send>>
        };

        let config = PoolConfig::with_max_size(5).health_check_on_acquire(true);
        // All resources pass health check
        let pool = GenericPool::new(factory, config).with_health_check(|_id: &u32| true);

        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        // Acquire and return resource #0
        let r0 = futures_lite::future::block_on(pool.acquire(&cx)).expect("first acquire");
        assert_eq!(*r0, 0u32);
        r0.return_to_pool();

        // Acquire again — should reuse #0 since it passes health check
        let r1 = futures_lite::future::block_on(pool.acquire(&cx)).expect("second acquire");
        assert_eq!(*r1, 0, "healthy resource should be reused");

        crate::test_complete!("health_check_passes_healthy_resource");
    }

    #[test]
    fn health_check_disabled_skips_check() {
        init_test("health_check_disabled_skips_check");

        let counter = std::sync::atomic::AtomicU32::new(0);
        let factory = move || {
            let id = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Box::pin(async move { Ok::<_, Box<dyn std::error::Error + Send + Sync>>(id) })
                as std::pin::Pin<Box<dyn Future<Output = _> + Send>>
        };

        // health_check_on_acquire defaults to false
        let config = PoolConfig::with_max_size(5);
        // Health check that rejects everything — but it's disabled
        let pool = GenericPool::new(factory, config).with_health_check(|_id: &u32| false);

        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        let r0 = futures_lite::future::block_on(pool.acquire(&cx)).expect("first acquire");
        assert_eq!(*r0, 0);
        r0.return_to_pool();

        // Should still return #0 because health check is not enabled
        let r1 = futures_lite::future::block_on(pool.acquire(&cx)).expect("second acquire");
        assert_eq!(
            *r1, 0,
            "health check disabled, resource reused despite failing check"
        );

        crate::test_complete!("health_check_disabled_skips_check");
    }

    #[test]
    fn try_acquire_skips_unhealthy_idle_resources_when_health_check_enabled() {
        init_test("try_acquire_skips_unhealthy_idle_resources_when_health_check_enabled");

        let counter = std::sync::atomic::AtomicU32::new(0);
        let factory = move || {
            let id = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Box::pin(async move { Ok::<_, Box<dyn std::error::Error + Send + Sync>>(id) })
                as std::pin::Pin<Box<dyn Future<Output = _> + Send>>
        };

        let config = PoolConfig::with_max_size(5).health_check_on_acquire(true);
        let pool = GenericPool::new(factory, config).with_health_check(|id: &u32| *id != 0);

        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        // Seed two idle resources: #0 (unhealthy), then #1 (healthy).
        let r0 = futures_lite::future::block_on(pool.acquire(&cx)).expect("first acquire");
        let r1 = futures_lite::future::block_on(pool.acquire(&cx)).expect("second acquire");
        assert_eq!(*r0, 0);
        assert_eq!(*r1, 1);
        r0.return_to_pool();
        r1.return_to_pool();

        // try_acquire should skip #0 and return #1.
        let picked = pool
            .try_acquire()
            .expect("should acquire healthy idle resource");
        assert_eq!(
            *picked, 1,
            "try_acquire should skip unhealthy idle resource"
        );

        let stats = pool.stats();
        assert_eq!(stats.active, 1, "one resource checked out");
        assert_eq!(stats.idle, 0, "no healthy idle resources left");

        crate::test_complete!(
            "try_acquire_skips_unhealthy_idle_resources_when_health_check_enabled"
        );
    }

    // ========================================================================
    // Warmup tests (asupersync-cl94)
    // ========================================================================

    #[test]
    fn warmup_creates_resources() {
        init_test("warmup_creates_resources");

        let config = PoolConfig::with_max_size(10).warmup_connections(3);
        let pool = GenericPool::new(simple_factory, config);

        let created = futures_lite::future::block_on(pool.warmup()).expect("warmup should succeed");
        assert_eq!(created, 3, "should create 3 warmup resources");

        let stats = pool.stats();
        assert_eq!(stats.idle, 3, "3 idle resources after warmup");
        assert_eq!(stats.active, 0, "no active resources");

        crate::test_complete!("warmup_creates_resources");
    }

    #[test]
    fn warmup_respects_max_size() {
        init_test("warmup_respects_max_size");

        let config = PoolConfig::with_max_size(2).warmup_connections(5);
        let pool = GenericPool::new(simple_factory, config);

        let created = futures_lite::future::block_on(pool.warmup()).expect("warmup should succeed");
        assert_eq!(created, 2, "warmup must not exceed max_size");

        let stats = pool.stats();
        assert_eq!(stats.idle, 2, "idle resources capped by max_size");
        assert_eq!(stats.total, 2, "total resources capped by max_size");

        crate::test_complete!("warmup_respects_max_size");
    }

    #[test]
    fn warmup_zero_is_noop() {
        init_test("warmup_zero_is_noop");

        let config = PoolConfig::with_max_size(10).warmup_connections(0);
        let pool = GenericPool::new(simple_factory, config);

        let created = futures_lite::future::block_on(pool.warmup()).expect("warmup should succeed");
        assert_eq!(created, 0, "zero warmup creates nothing");

        let stats = pool.stats();
        assert_eq!(stats.idle, 0, "no idle resources");

        crate::test_complete!("warmup_zero_is_noop");
    }

    #[test]
    fn warmup_timeout_fail_fast_returns_timeout() {
        init_test("warmup_timeout_fail_fast_returns_timeout");

        let factory = TimeoutAfterNSuccessesFactory {
            successes: 0,
            next_attempt: std::sync::atomic::AtomicU32::new(0),
        };
        let config = PoolConfig::with_max_size(2)
            .warmup_connections(1)
            .warmup_timeout(Duration::from_millis(25))
            .warmup_failure_strategy(WarmupStrategy::FailFast);
        let pool = GenericPool::new(factory, config);

        let result = futures_lite::future::block_on(pool.warmup());
        assert!(
            matches!(result, Err(PoolError::Timeout)),
            "stalled warmup should return PoolError::Timeout under FailFast"
        );

        let stats = pool.stats();
        assert_eq!(stats.total, 0, "timed out warmup must release create slot");
        assert_eq!(
            stats.idle, 0,
            "timed out warmup must not leak idle resources"
        );

        crate::test_complete!("warmup_timeout_fail_fast_returns_timeout");
    }

    #[test]
    fn warmup_timeout_best_effort_returns_partial_progress() {
        init_test("warmup_timeout_best_effort_returns_partial_progress");

        let factory = TimeoutAfterNSuccessesFactory {
            successes: 1,
            next_attempt: std::sync::atomic::AtomicU32::new(0),
        };
        let config = PoolConfig::with_max_size(3)
            .warmup_connections(2)
            .warmup_timeout(Duration::from_millis(25))
            .warmup_failure_strategy(WarmupStrategy::BestEffort);
        let pool = GenericPool::new(factory, config);

        let created =
            futures_lite::future::block_on(pool.warmup()).expect("BestEffort should keep progress");
        assert_eq!(
            created, 1,
            "warmup should report resources created before timeout"
        );

        let stats = pool.stats();
        assert_eq!(
            stats.idle, 1,
            "successful warmup resource should remain idle"
        );
        assert_eq!(
            stats.total, 1,
            "timeout must not retain the stalled create slot"
        );

        crate::test_complete!("warmup_timeout_best_effort_returns_partial_progress");
    }

    #[test]
    fn warmup_timeout_require_minimum_errors_when_min_not_reached() {
        init_test("warmup_timeout_require_minimum_errors_when_min_not_reached");

        let factory = TimeoutAfterNSuccessesFactory {
            successes: 1,
            next_attempt: std::sync::atomic::AtomicU32::new(0),
        };
        let config = PoolConfig::with_max_size(3)
            .min_size(2)
            .warmup_connections(3)
            .warmup_timeout(Duration::from_millis(25))
            .warmup_failure_strategy(WarmupStrategy::RequireMinimum);
        let pool = GenericPool::new(factory, config);

        let result = futures_lite::future::block_on(pool.warmup());
        assert!(
            matches!(result, Err(PoolError::Timeout)),
            "RequireMinimum should surface timeout when min_size is not reached"
        );

        let stats = pool.stats();
        assert_eq!(
            stats.idle, 1,
            "successful creates before timeout should remain usable"
        );
        assert_eq!(stats.total, 1, "timed out create slot must be released");

        crate::test_complete!("warmup_timeout_require_minimum_errors_when_min_not_reached");
    }

    #[test]
    fn warmup_timeout_require_minimum_keeps_progress_once_min_reached() {
        init_test("warmup_timeout_require_minimum_keeps_progress_once_min_reached");

        let factory = TimeoutAfterNSuccessesFactory {
            successes: 1,
            next_attempt: std::sync::atomic::AtomicU32::new(0),
        };
        let config = PoolConfig::with_max_size(3)
            .min_size(1)
            .warmup_connections(3)
            .warmup_timeout(Duration::from_millis(25))
            .warmup_failure_strategy(WarmupStrategy::RequireMinimum);
        let pool = GenericPool::new(factory, config);

        let created = futures_lite::future::block_on(pool.warmup())
            .expect("RequireMinimum should keep partial progress once min_size is met");
        assert_eq!(
            created, 1,
            "warmup should retain successful creates before timeout"
        );

        let stats = pool.stats();
        assert_eq!(
            stats.idle, 1,
            "resource created before timeout should remain idle"
        );
        assert_eq!(stats.total, 1, "timed out create slot must be released");

        crate::test_complete!("warmup_timeout_require_minimum_keeps_progress_once_min_reached");
    }

    #[test]
    fn warmup_fail_fast_stops_on_error() {
        init_test("warmup_fail_fast_stops_on_error");

        let counter = std::sync::atomic::AtomicU32::new(0);
        let factory = move || {
            let n = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Box::pin(async move {
                if n >= 2 {
                    Err::<u32, _>(Box::new(std::io::Error::other("fail"))
                        as Box<dyn std::error::Error + Send + Sync>)
                } else {
                    Ok(n)
                }
            }) as std::pin::Pin<Box<dyn Future<Output = _> + Send>>
        };

        let config = PoolConfig::with_max_size(10)
            .warmup_connections(5)
            .warmup_failure_strategy(WarmupStrategy::FailFast);
        let pool = GenericPool::new(factory, config);

        let result = futures_lite::future::block_on(pool.warmup());
        assert!(result.is_err(), "FailFast should return error");

        // Only 2 resources created before the third failed
        let stats = pool.stats();
        assert_eq!(stats.idle, 2, "2 created before failure");

        crate::test_complete!("warmup_fail_fast_stops_on_error");
    }

    #[test]
    fn warmup_best_effort_continues_on_error() {
        init_test("warmup_best_effort_continues_on_error");

        let counter = std::sync::atomic::AtomicU32::new(0);
        let factory = move || {
            let n = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Box::pin(async move {
                if n % 2 == 1 {
                    // Odd-numbered creates fail
                    Err::<u32, _>(Box::new(std::io::Error::other("fail"))
                        as Box<dyn std::error::Error + Send + Sync>)
                } else {
                    Ok(n)
                }
            }) as std::pin::Pin<Box<dyn Future<Output = _> + Send>>
        };

        let config = PoolConfig::with_max_size(10)
            .warmup_connections(4)
            .warmup_failure_strategy(WarmupStrategy::BestEffort);
        let pool = GenericPool::new(factory, config);

        let created =
            futures_lite::future::block_on(pool.warmup()).expect("BestEffort never errors");
        assert_eq!(created, 2, "2 of 4 succeeded (evens)");

        let stats = pool.stats();
        assert_eq!(stats.idle, 2, "2 idle after partial warmup");

        crate::test_complete!("warmup_best_effort_continues_on_error");
    }

    #[test]
    fn warmup_require_minimum_fails_below_min() {
        init_test("warmup_require_minimum_fails_below_min");

        let counter = std::sync::atomic::AtomicU32::new(0);
        let factory = move || {
            let n = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Box::pin(async move {
                if n >= 1 {
                    Err::<u32, _>(Box::new(std::io::Error::other("fail"))
                        as Box<dyn std::error::Error + Send + Sync>)
                } else {
                    Ok(n)
                }
            }) as std::pin::Pin<Box<dyn Future<Output = _> + Send>>
        };

        let config = PoolConfig::with_max_size(10)
            .min_size(3)
            .warmup_connections(5)
            .warmup_failure_strategy(WarmupStrategy::RequireMinimum);
        let pool = GenericPool::new(factory, config);

        let result = futures_lite::future::block_on(pool.warmup());
        assert!(
            result.is_err(),
            "RequireMinimum should fail: only 1 created < min_size 3"
        );

        crate::test_complete!("warmup_require_minimum_fails_below_min");
    }

    #[test]
    fn warmup_require_minimum_passes_above_min() {
        init_test("warmup_require_minimum_passes_above_min");

        let config = PoolConfig::with_max_size(10)
            .min_size(2)
            .warmup_connections(5)
            .warmup_failure_strategy(WarmupStrategy::RequireMinimum);
        let pool = GenericPool::new(simple_factory, config);

        let created =
            futures_lite::future::block_on(pool.warmup()).expect("should pass: 5 >= min 2");
        assert_eq!(created, 5, "all 5 warmup resources created");

        crate::test_complete!("warmup_require_minimum_passes_above_min");
    }

    #[test]
    fn warmup_created_timestamps_follow_time_getter() {
        init_test("warmup_created_timestamps_follow_time_getter");

        set_test_pool_time_offset(Duration::from_secs(86_400));

        let config = PoolConfig::with_max_size(4)
            .warmup_connections(1)
            .max_lifetime(Duration::from_secs(1));
        let pool = GenericPool::with_time_getter(simple_factory, config, test_pool_time_now);

        let created = futures_lite::future::block_on(pool.warmup()).expect("warmup should succeed");
        assert_eq!(created, 1, "warmup should create one idle resource");

        let resource = pool
            .try_acquire()
            .expect("warmup resource should not look immediately expired");
        assert_eq!(*resource, 42u32, "warmup resource should stay reusable");

        resource.return_to_pool();
        crate::test_complete!("warmup_created_timestamps_follow_time_getter");
    }

    // ========================================================================
    // Audit regression tests (asupersync-10x0x.44)
    // ========================================================================

    #[test]
    fn return_to_closed_pool_drops_resource() {
        init_test("return_to_closed_pool_drops_resource");

        // Verify that returning a resource to a closed pool silently drops
        // the resource instead of adding it to the idle queue.
        let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(5));
        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        // Acquire a resource
        let resource =
            futures_lite::future::block_on(pool.acquire(&cx)).expect("acquire should succeed");

        // Close the pool while the resource is held
        futures_lite::future::block_on(pool.close());

        // Return the resource — it should be silently dropped, not added to idle
        resource.return_to_pool();

        let stats = pool.stats();
        crate::assert_with_log!(
            stats.idle == 0,
            "no idle after return to closed pool",
            0usize,
            stats.idle
        );
        crate::assert_with_log!(
            stats.active == 0,
            "active decremented despite closed pool",
            0usize,
            stats.active
        );

        crate::test_complete!("return_to_closed_pool_drops_resource");
    }

    #[test]
    fn discard_to_closed_pool_decrements_active() {
        init_test("discard_to_closed_pool_decrements_active");

        let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(5));
        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        let resource =
            futures_lite::future::block_on(pool.acquire(&cx)).expect("acquire should succeed");

        futures_lite::future::block_on(pool.close());

        // Discard the resource after pool is closed
        resource.discard();

        let stats = pool.stats();
        crate::assert_with_log!(
            stats.active == 0,
            "active decremented after discard to closed pool",
            0usize,
            stats.active
        );

        crate::test_complete!("discard_to_closed_pool_decrements_active");
    }

    #[test]
    fn create_slot_reservation_cancel_safety() {
        init_test("create_slot_reservation_cancel_safety");

        // Verify that dropping a CreateSlotReservation without committing
        // correctly releases the slot and wakes a waiter.
        let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(1));

        // Reserve a slot (simulates start of resource creation)
        let slot = CreateSlotReservation::try_reserve(&pool, None);
        assert!(slot.is_some(), "should reserve slot");

        // Verify pool is at capacity
        let slot2 = CreateSlotReservation::try_reserve(&pool, None);
        assert!(slot2.is_none(), "pool at capacity with one creating slot");

        // Drop without committing (simulates cancel during create)
        drop(slot);

        // Creating count should be back to 0
        let stats = pool.stats();
        crate::assert_with_log!(
            stats.total == 0,
            "total back to 0 after cancelled reservation",
            0usize,
            stats.total
        );

        // Should be able to reserve again
        let slot3 = CreateSlotReservation::try_reserve(&pool, None);
        assert!(slot3.is_some(), "slot available after cancel");
        if let Some(s) = slot3 {
            s.commit();
        }

        crate::test_complete!("create_slot_reservation_cancel_safety");
    }

    #[test]
    fn idle_eviction_respects_idle_timeout() {
        init_test("idle_eviction_respects_idle_timeout");

        let config = PoolConfig::with_max_size(5).idle_timeout(Duration::from_millis(10));
        let pool = GenericPool::with_time_getter(simple_factory, config, test_pool_time_now);
        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        let r = futures_lite::future::block_on(pool.acquire(&cx)).expect("acquire");
        r.return_to_pool();

        let stats = pool.stats();
        assert_eq!(stats.idle, 1, "resource should be idle");

        advance_test_pool_time(Duration::from_millis(20));

        let result = pool.try_acquire();
        assert!(
            result.is_none(),
            "expired idle resource should be evicted, try_acquire returns None"
        );

        let stats = pool.stats();
        assert_eq!(
            stats.idle, 0,
            "expired idle resource should have been evicted"
        );

        crate::test_complete!("idle_eviction_respects_idle_timeout");
    }

    #[test]
    fn idle_eviction_respects_max_lifetime() {
        init_test("idle_eviction_respects_max_lifetime");

        let config = PoolConfig::with_max_size(5).max_lifetime(Duration::from_millis(10));
        let pool = GenericPool::with_time_getter(simple_factory, config, test_pool_time_now);
        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        let r = futures_lite::future::block_on(pool.acquire(&cx)).expect("acquire");
        r.return_to_pool();

        advance_test_pool_time(Duration::from_millis(20));

        let result = pool.try_acquire();
        assert!(
            result.is_none(),
            "resource past max_lifetime should be evicted"
        );

        let stats = pool.stats();
        assert_eq!(
            stats.idle, 0,
            "expired resource should be evicted from idle"
        );

        crate::test_complete!("idle_eviction_respects_max_lifetime");
    }

    #[test]
    fn multiple_acquire_return_cycles_keep_accounting_consistent() {
        init_test("multiple_acquire_return_cycles_keep_accounting_consistent");

        // Verify that mixed return_to_pool, discard, and implicit drop
        // all keep the accounting correct over many cycles.
        let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(3));
        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        for i in 0..50 {
            let r = futures_lite::future::block_on(pool.acquire(&cx)).expect("acquire");
            match i % 3 {
                0 => r.return_to_pool(),
                1 => r.discard(),
                _ => drop(r), // implicit return via Drop
            }
        }

        let stats = pool.stats();
        crate::assert_with_log!(
            stats.active == 0,
            "no active after all returned/discarded",
            0usize,
            stats.active
        );
        crate::assert_with_log!(
            stats.total_acquisitions == 50,
            "50 total acquisitions",
            50u64,
            stats.total_acquisitions
        );

        crate::test_complete!("multiple_acquire_return_cycles_keep_accounting_consistent");
    }

    #[test]
    fn warmup_resources_reused_by_acquire() {
        init_test("warmup_resources_reused_by_acquire");

        // Verify that warmup resources are available for acquire.
        let counter = std::sync::atomic::AtomicU32::new(0);
        let factory = move || {
            let id = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Box::pin(async move { Ok::<_, Box<dyn std::error::Error + Send + Sync>>(id) })
                as std::pin::Pin<Box<dyn Future<Output = _> + Send>>
        };

        let config = PoolConfig::with_max_size(10).warmup_connections(2);
        let pool = GenericPool::new(factory, config);

        let created = futures_lite::future::block_on(pool.warmup()).expect("warmup should succeed");
        assert_eq!(created, 2);

        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        // Acquire should reuse warmup resources (ids 0 and 1), not create new ones
        let r1 = futures_lite::future::block_on(pool.acquire(&cx)).expect("acquire 1");
        let r2 = futures_lite::future::block_on(pool.acquire(&cx)).expect("acquire 2");

        // Both should be from warmup (ids 0 or 1)
        assert!(
            *r1 <= 1u32 && *r2 <= 1u32,
            "warmup resources should be reused: got {} and {}",
            *r1,
            *r2
        );
        assert_ne!(*r1, *r2, "should be different resources");

        crate::test_complete!("warmup_resources_reused_by_acquire");
    }

    // ========================================================================
    // PoolConfig health/warmup builder tests (asupersync-cl94)
    // ========================================================================

    #[test]
    fn pool_config_health_check_builder() {
        init_test("pool_config_health_check_builder");

        let config = PoolConfig::with_max_size(5)
            .health_check_on_acquire(true)
            .health_check_interval(Some(Duration::from_secs(60)))
            .evict_unhealthy(false);

        assert!(config.health_check_on_acquire);
        assert_eq!(config.health_check_interval, Some(Duration::from_secs(60)));
        assert!(!config.evict_unhealthy);

        crate::test_complete!("pool_config_health_check_builder");
    }

    #[test]
    fn pool_config_warmup_builder() {
        init_test("pool_config_warmup_builder");

        let config = PoolConfig::with_max_size(5)
            .warmup_connections(3)
            .warmup_timeout(Duration::from_secs(10))
            .warmup_failure_strategy(WarmupStrategy::FailFast);

        assert_eq!(config.warmup_connections, 3);
        assert_eq!(config.warmup_timeout, Duration::from_secs(10));
        assert_eq!(config.warmup_failure_strategy, WarmupStrategy::FailFast);

        crate::test_complete!("pool_config_warmup_builder");
    }

    // ========================================================================
    // Invariant tests: cancel-safety, exhaustion, factory errors
    // ========================================================================

    /// Invariant: dropping an acquire future that is suspended inside
    /// `WaitForNotification` removes the waiter from the queue.
    #[test]
    #[allow(unsafe_code)]
    fn pool_cancel_during_wait_does_not_leak_waiter() {
        init_test("pool_cancel_during_wait_does_not_leak_waiter");

        let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(1));
        let cx_handle: crate::cx::Cx = crate::cx::Cx::for_testing();

        // Acquire the one resource so pool is at capacity.
        let held = futures_lite::future::block_on(pool.acquire(&cx_handle)).expect("first acquire");

        // Create a second acquire future. It will enter WaitForNotification
        // because the pool is exhausted (max_size=1, active=1).
        let waker = noop_pool_waker();
        let mut task_cx = std::task::Context::from_waker(&waker);
        {
            let mut acquire_fut = pool.acquire(&cx_handle);
            // SAFETY: acquire_fut lives on the stack and we do not move it.
            let pinned = std::pin::Pin::new(&mut acquire_fut);
            let poll_result = pinned.poll(&mut task_cx);
            // Should be Pending — pool is full.
            let is_pending = poll_result.is_pending();
            crate::assert_with_log!(is_pending, "acquire is Pending", true, is_pending);

            // Verify a waiter was registered.
            let waiters_before = pool.stats().waiters;
            crate::assert_with_log!(
                waiters_before >= 1,
                "waiter registered",
                true,
                waiters_before >= 1
            );
            // acquire_fut dropped here — WaitForNotification::drop fires.
        }

        // After drop, waiters must be 0.
        let waiters_after = pool.stats().waiters;
        crate::assert_with_log!(
            waiters_after == 0,
            "waiter cleaned on drop",
            0usize,
            waiters_after
        );

        // Return the held resource and verify normal operation.
        held.return_to_pool();
        let reacquired = futures_lite::future::block_on(pool.acquire(&cx_handle));
        let ok = reacquired.is_ok();
        crate::assert_with_log!(ok, "reacquire succeeds", true, ok);

        crate::test_complete!("pool_cancel_during_wait_does_not_leak_waiter");
    }

    /// Invariant: when the pool is at capacity, acquire blocks; when a
    /// resource is returned, the blocked acquirer is woken and succeeds.
    #[test]
    fn pool_exhaustion_blocks_then_unblocks_on_return() {
        init_test("pool_exhaustion_blocks_then_unblocks_on_return");

        let pool = Arc::new(GenericPool::new(
            simple_factory,
            PoolConfig::with_max_size(1),
        ));
        let cx_handle: crate::cx::Cx = crate::cx::Cx::for_testing();

        // Acquire the single resource.
        let held = futures_lite::future::block_on(pool.acquire(&cx_handle)).expect("first acquire");
        let held_val = *held;

        // Spawn a thread that will block on acquire.
        let pool2 = Arc::clone(&pool);
        let blocker = std::thread::spawn(move || {
            let cx2: crate::cx::Cx = crate::cx::Cx::for_testing();
            let waker = noop_pool_waker();
            let mut task_cx = Context::from_waker(&waker);
            let mut acquire_fut = std::pin::pin!(pool2.acquire(&cx2));

            match acquire_fut.as_mut().poll(&mut task_cx) {
                Poll::Pending => {}
                Poll::Ready(result) => return result,
            }

            loop {
                match acquire_fut.as_mut().poll(&mut task_cx) {
                    Poll::Ready(result) => return result,
                    Poll::Pending => std::thread::yield_now(),
                }
            }
        });

        let mut waiter_registered = false;
        for _ in 0..4_096 {
            if pool.stats().waiters == 1 {
                waiter_registered = true;
                break;
            }
            std::thread::yield_now();
        }
        crate::assert_with_log!(
            waiter_registered,
            "blocker should register as a waiter without sleep-based synchronization",
            true,
            waiter_registered
        );

        // Return the resource — this should wake the blocked acquirer.
        held.return_to_pool();

        let result = blocker.join().expect("blocker thread panicked");
        let acquired = result.expect("blocked acquire should succeed");
        let val = *acquired;
        crate::assert_with_log!(
            val == held_val,
            "blocked acquirer got returned resource",
            held_val,
            val
        );

        crate::test_complete!("pool_exhaustion_blocks_then_unblocks_on_return");
    }

    /// Invariant: returning one resource from an exhausted pool only wakes one
    /// waiter; remaining waiters stay queued until another resource return.
    #[test]
    #[allow(clippy::too_many_lines)]
    fn pool_return_wakes_waiters_one_at_a_time() {
        init_test("pool_return_wakes_waiters_one_at_a_time");

        let pool = Arc::new(GenericPool::new(
            simple_factory,
            PoolConfig::with_max_size(1),
        ));
        let cx_handle: crate::cx::Cx = crate::cx::Cx::for_testing();
        let held = futures_lite::future::block_on(pool.acquire(&cx_handle)).expect("first acquire");

        let (acquired_tx, acquired_rx) = std::sync::mpsc::channel();
        let (release_first_tx, release_first_rx) = std::sync::mpsc::channel();
        let (release_second_tx, release_second_rx) = std::sync::mpsc::channel();

        let first_waiter_pool = Arc::clone(&pool);
        let first_waiter_tx = acquired_tx.clone();
        let first_waiter = std::thread::spawn(move || {
            let cx = crate::cx::Cx::for_testing();
            let acquired =
                futures_lite::future::block_on(first_waiter_pool.acquire(&cx)).expect("waiter A");
            first_waiter_tx
                .send(1usize)
                .expect("send waiter A acquisition");
            release_first_rx.recv().expect("waiter A release signal");
            acquired.return_to_pool();
        });

        let second_waiter_pool = Arc::clone(&pool);
        let second_waiter_tx = acquired_tx;
        let second_waiter = std::thread::spawn(move || {
            let cx = crate::cx::Cx::for_testing();
            let acquired =
                futures_lite::future::block_on(second_waiter_pool.acquire(&cx)).expect("waiter B");
            second_waiter_tx
                .send(2usize)
                .expect("send waiter B acquisition");
            release_second_rx.recv().expect("waiter B release signal");
            acquired.return_to_pool();
        });

        let mut both_waiters_registered = false;
        for _ in 0..4_096 {
            if pool.stats().waiters == 2 {
                both_waiters_registered = true;
                break;
            }
            std::thread::yield_now();
        }
        crate::assert_with_log!(
            both_waiters_registered,
            "both blocked acquirers should register as waiters",
            true,
            both_waiters_registered
        );

        held.return_to_pool();

        let first = acquired_rx
            .recv_timeout(Duration::from_secs(1))
            .expect("first waiter should wake");

        let mut one_waiter_still_blocked = false;
        for _ in 0..4_096 {
            let stats = pool.stats();
            if stats.waiters == 1 && stats.active == 1 {
                one_waiter_still_blocked = true;
                break;
            }
            std::thread::yield_now();
        }
        crate::assert_with_log!(
            one_waiter_still_blocked,
            "one waiter should remain queued while the woken waiter holds the resource",
            true,
            one_waiter_still_blocked
        );

        match first {
            1 => release_first_tx.send(()).expect("release waiter A"),
            2 => release_second_tx.send(()).expect("release waiter B"),
            other => panic!("unexpected waiter id: {other}"),
        }

        let second = acquired_rx
            .recv_timeout(Duration::from_secs(1))
            .expect("second waiter should wake after the next return");
        crate::assert_with_log!(
            first != second,
            "resource returns should wake distinct waiters sequentially",
            true,
            first != second
        );

        let mut no_waiters_left = false;
        for _ in 0..4_096 {
            let stats = pool.stats();
            if stats.waiters == 0 && stats.active == 1 {
                no_waiters_left = true;
                break;
            }
            std::thread::yield_now();
        }
        crate::assert_with_log!(
            no_waiters_left,
            "second wake should drain the waiter queue while the final borrower holds the resource",
            true,
            no_waiters_left
        );

        match second {
            1 => release_first_tx
                .send(())
                .expect("release waiter A after second wake"),
            2 => release_second_tx
                .send(())
                .expect("release waiter B after second wake"),
            other => panic!("unexpected waiter id: {other}"),
        }

        first_waiter.join().expect("waiter A should not panic");
        second_waiter.join().expect("waiter B should not panic");

        let stats = pool.stats();
        crate::assert_with_log!(
            stats.waiters == 0,
            "all waiters should be drained after both resources are returned",
            0usize,
            stats.waiters
        );
        crate::assert_with_log!(
            stats.active == 0,
            "no active resources should remain after both waiters release",
            0usize,
            stats.active
        );
        crate::assert_with_log!(
            stats.idle == 1,
            "the single pooled resource should be returned to idle storage",
            1usize,
            stats.idle
        );
        crate::assert_with_log!(
            stats.total == 1,
            "capacity accounting should settle back to a single retained resource",
            1usize,
            stats.total
        );

        crate::test_complete!("pool_return_wakes_waiters_one_at_a_time");
    }

    /// Invariant: if the factory returns an error during acquire, the
    /// creating slot is released and does not permanently reduce capacity.
    #[test]
    fn pool_factory_error_releases_create_slot() {
        init_test("pool_factory_error_releases_create_slot");

        let call_count = Arc::new(std::sync::atomic::AtomicU32::new(0));
        let cc = Arc::clone(&call_count);

        // Factory that fails on the first call, succeeds on subsequent ones.
        let factory = move || {
            let count = cc.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Box::pin(async move {
                if count == 0 {
                    Err::<u32, Box<dyn std::error::Error + Send + Sync>>(
                        "deliberate factory error".into(),
                    )
                } else {
                    Ok(count)
                }
            })
                as std::pin::Pin<
                    Box<
                        dyn Future<Output = Result<u32, Box<dyn std::error::Error + Send + Sync>>>
                            + Send,
                    >,
                >
        };

        let pool = GenericPool::new(factory, PoolConfig::with_max_size(2));
        let cx_handle: crate::cx::Cx = crate::cx::Cx::for_testing();

        // First acquire should fail (factory error).
        let first = futures_lite::future::block_on(pool.acquire(&cx_handle));
        let is_err = first.is_err();
        crate::assert_with_log!(is_err, "first acquire fails", true, is_err);

        // After the error, creating count must be 0 (slot released by RAII).
        let stats = pool.stats();
        crate::assert_with_log!(
            stats.total == 0,
            "no phantom slot leaked",
            0usize,
            stats.total
        );

        // Second acquire should succeed (factory returns Ok now).
        let second = futures_lite::future::block_on(pool.acquire(&cx_handle));
        let ok = second.is_ok();
        crate::assert_with_log!(ok, "second acquire succeeds", true, ok);

        crate::test_complete!("pool_factory_error_releases_create_slot");
    }

    struct DropTrackedResource {
        drops: Arc<std::sync::atomic::AtomicUsize>,
    }

    impl Drop for DropTrackedResource {
        fn drop(&mut self) {
            self.drops.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        }
    }

    #[test]
    fn pool_close_while_create_in_flight_returns_closed() {
        init_test("pool_close_while_create_in_flight_returns_closed");

        let (entered_tx, entered_rx) = std::sync::mpsc::channel();
        let (unblock_tx, unblock_rx) = std::sync::mpsc::channel();
        let unblock_rx = Arc::new(std::sync::Mutex::new(unblock_rx));
        let drop_count = Arc::new(std::sync::atomic::AtomicUsize::new(0));

        let factory = {
            let unblock_rx = Arc::clone(&unblock_rx);
            let drop_count = Arc::clone(&drop_count);
            move || {
                let unblock_rx = Arc::clone(&unblock_rx);
                let entered_tx = entered_tx.clone();
                let drop_count = Arc::clone(&drop_count);
                Box::pin(async move {
                    entered_tx.send(()).expect("factory entered");
                    unblock_rx
                        .lock()
                        .expect("factory unblock receiver lock")
                        .recv()
                        .expect("factory unblock signal");
                    Ok::<DropTrackedResource, Box<dyn std::error::Error + Send + Sync>>(
                        DropTrackedResource { drops: drop_count },
                    )
                })
                    as std::pin::Pin<
                        Box<
                            dyn Future<
                                    Output = Result<
                                        DropTrackedResource,
                                        Box<dyn std::error::Error + Send + Sync>,
                                    >,
                                > + Send,
                        >,
                    >
            }
        };

        let pool = Arc::new(GenericPool::new(factory, PoolConfig::with_max_size(1)));
        let acquire_pool = Arc::clone(&pool);
        let (result_tx, result_rx) = std::sync::mpsc::channel();

        let worker = std::thread::spawn(move || {
            let cx_handle: crate::cx::Cx = crate::cx::Cx::for_testing();
            let result =
                futures_lite::future::block_on(acquire_pool.acquire(&cx_handle)).map(|_| ());
            result_tx.send(result).expect("send acquire result");
        });

        entered_rx.recv().expect("wait for factory entry");
        futures_lite::future::block_on(pool.close());
        unblock_tx.send(()).expect("unblock factory");

        let result = result_rx.recv().expect("receive acquire result");
        crate::assert_with_log!(
            matches!(result, Err(PoolError::Closed)),
            "acquire returns closed once close wins the create race",
            true,
            matches!(result, Err(PoolError::Closed))
        );

        worker.join().expect("worker thread panicked");

        let stats = pool.stats();
        crate::assert_with_log!(
            stats.active == 0,
            "no active resources leaked",
            0usize,
            stats.active
        );
        crate::assert_with_log!(
            stats.total == 0,
            "no total capacity leaked",
            0usize,
            stats.total
        );

        let reacquire = pool.try_acquire();
        crate::assert_with_log!(
            reacquire.is_none(),
            "closed pool does not expose created resource",
            true,
            reacquire.is_none()
        );
        crate::assert_with_log!(
            drop_count.load(std::sync::atomic::Ordering::SeqCst) == 1,
            "freshly created resource is dropped when close wins create race",
            1usize,
            drop_count.load(std::sync::atomic::Ordering::SeqCst)
        );

        crate::test_complete!("pool_close_while_create_in_flight_returns_closed");
    }

    // =========================================================================
    // Pure data-type tests (wave 42 – CyanBarn)
    // =========================================================================

    #[test]
    fn warmup_strategy_debug_clone_copy_eq_default() {
        let def = WarmupStrategy::default();
        assert_eq!(def, WarmupStrategy::BestEffort);
        for s in [
            WarmupStrategy::BestEffort,
            WarmupStrategy::FailFast,
            WarmupStrategy::RequireMinimum,
        ] {
            let copied = s;
            let cloned = s;
            assert_eq!(copied, cloned);
            let dbg = format!("{s:?}");
            assert!(!dbg.is_empty());
        }
        assert_ne!(WarmupStrategy::BestEffort, WarmupStrategy::FailFast);
        assert_ne!(WarmupStrategy::FailFast, WarmupStrategy::RequireMinimum);
    }

    #[test]
    fn destroy_reason_debug_clone_copy_eq() {
        for r in [
            DestroyReason::Unhealthy,
            DestroyReason::IdleTimeout,
            DestroyReason::MaxLifetime,
        ] {
            let copied = r;
            let cloned = r;
            assert_eq!(copied, cloned);
            let dbg = format!("{r:?}");
            assert!(!dbg.is_empty());
        }
        assert_ne!(DestroyReason::Unhealthy, DestroyReason::IdleTimeout);
        assert_eq!(DestroyReason::Unhealthy.as_label(), "unhealthy");
        assert_eq!(DestroyReason::IdleTimeout.as_label(), "idle_timeout");
        assert_eq!(DestroyReason::MaxLifetime.as_label(), "max_lifetime");
    }

    #[test]
    fn pool_stats_debug_clone_default() {
        let def = PoolStats::default();
        assert_eq!(def.active, 0);
        assert_eq!(def.idle, 0);
        assert_eq!(def.total, 0);
        assert_eq!(def.total_acquisitions, 0);
        let cloned = def.clone();
        assert_eq!(cloned.active, 0);
        let dbg = format!("{def:?}");
        assert!(dbg.contains("PoolStats"));
    }

    // ========================================================================
    // Metamorphic Testing: Pool acquire/release lifecycle invariants
    // ========================================================================

    #[test]
    fn metamorphic_resource_conservation_invariant() {
        init_test("metamorphic_resource_conservation_invariant");

        // MR: total_resources(before_operation) == total_resources(after_operation)
        // Conservation holds across any sequence of acquire/release operations
        let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(5));
        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        let initial_stats = pool.stats();
        let initial_total = initial_stats.total;

        // Perform sequence: acquire -> return -> acquire -> discard -> acquire -> drop
        let r1 = futures_lite::future::block_on(pool.acquire(&cx)).expect("acquire 1");
        r1.return_to_pool();

        let r2 = futures_lite::future::block_on(pool.acquire(&cx)).expect("acquire 2");
        r2.discard();

        let r3 = futures_lite::future::block_on(pool.acquire(&cx)).expect("acquire 3");
        drop(r3); // implicit return via Drop

        let final_stats = pool.stats();
        let final_total = final_stats.total;

        // Conservation: total resources should be preserved (accounting for discarded)
        // Note: discard removes from total, so final should equal initial + created - discarded
        crate::assert_with_log!(
            final_total >= initial_total,
            "resource conservation: total preserved or increased",
            true,
            final_total >= initial_total
        );
        crate::assert_with_log!(
            final_stats.active == 0,
            "all resources returned or discarded",
            0usize,
            final_stats.active
        );

        crate::test_complete!("metamorphic_resource_conservation_invariant");
    }

    #[test]
    fn metamorphic_acquire_release_symmetry() {
        init_test("metamorphic_acquire_release_symmetry");

        // MR: acquisitions(seq) == releases(seq) for any complete sequence
        // Each successful acquire must be paired with exactly one release
        let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(3));
        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        let initial_acquisitions = pool.stats().total_acquisitions;

        // Perform sequence of acquire/release pairs
        for i in 0..10 {
            let resource =
                futures_lite::future::block_on(pool.acquire(&cx)).expect("acquire should succeed");

            match i % 3 {
                0 => resource.return_to_pool(),
                1 => resource.discard(),
                _ => drop(resource), // implicit return
            }
        }

        let final_stats = pool.stats();
        let total_acquisitions = final_stats.total_acquisitions - initial_acquisitions;

        // Symmetry: all acquired resources have been released (active == 0)
        crate::assert_with_log!(
            total_acquisitions == 10,
            "10 acquisitions performed",
            10u64,
            total_acquisitions
        );
        crate::assert_with_log!(
            final_stats.active == 0,
            "acquire/release symmetry: all acquired resources released",
            0usize,
            final_stats.active
        );

        crate::test_complete!("metamorphic_acquire_release_symmetry");
    }

    #[test]
    fn metamorphic_resource_reuse_equivalence() {
        init_test("metamorphic_resource_reuse_equivalence");

        // MR: reused_resource.value == original_resource.value
        // Returned resources should be equivalent to original when reacquired
        let counter = std::sync::atomic::AtomicU32::new(0);
        let factory = move || {
            let id = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Box::pin(async move { Ok::<_, Box<dyn std::error::Error + Send + Sync>>(id) })
                as std::pin::Pin<Box<dyn Future<Output = _> + Send>>
        };

        let pool = GenericPool::new(factory, PoolConfig::with_max_size(3));
        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        // Acquire first resource, remember its value
        let r1 = futures_lite::future::block_on(pool.acquire(&cx)).expect("acquire 1");
        let original_value: u32 = *r1;
        r1.return_to_pool();

        // Acquire again - should get the same resource back
        let r2 = futures_lite::future::block_on(pool.acquire(&cx)).expect("acquire 2");
        let reused_value = *r2;

        // Equivalence: reused resource should have same value as original
        crate::assert_with_log!(
            reused_value == original_value,
            "resource reuse equivalence",
            original_value,
            reused_value
        );

        let stats = pool.stats();
        crate::assert_with_log!(
            stats.idle == 0,
            "reused resource removed from idle",
            0usize,
            stats.idle
        );
        crate::assert_with_log!(
            stats.active == 1,
            "reused resource now active",
            1usize,
            stats.active
        );

        r2.return_to_pool();
        crate::test_complete!("metamorphic_resource_reuse_equivalence");
    }

    #[test]
    fn metamorphic_cancelled_waiter_preserves_reuse_identity() {
        init_test("metamorphic_cancelled_waiter_preserves_reuse_identity");

        let counter = std::sync::atomic::AtomicU32::new(0);
        let factory = move || {
            let id = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Box::pin(async move { Ok::<_, Box<dyn std::error::Error + Send + Sync>>(id) })
                as std::pin::Pin<Box<dyn Future<Output = _> + Send>>
        };

        let pool = GenericPool::new(factory, PoolConfig::with_max_size(1));
        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        let held = futures_lite::future::block_on(pool.acquire(&cx)).expect("initial acquire");
        let original_id: u32 = *held;

        let waker = noop_pool_waker();
        let mut task_cx = std::task::Context::from_waker(&waker);
        {
            let mut blocked_acquire = pool.acquire(&cx);
            let poll_result = std::pin::Pin::new(&mut blocked_acquire).poll(&mut task_cx);
            crate::assert_with_log!(
                poll_result.is_pending(),
                "second acquire should block while the only resource is held",
                true,
                poll_result.is_pending()
            );
            crate::assert_with_log!(
                pool.stats().waiters == 1,
                "blocked acquire should register one waiter",
                1usize,
                pool.stats().waiters
            );
        }

        crate::assert_with_log!(
            pool.stats().waiters == 0,
            "dropping the blocked acquire should clean the waiter queue",
            0usize,
            pool.stats().waiters
        );

        held.return_to_pool();

        let reacquired = futures_lite::future::block_on(pool.acquire(&cx)).expect("reacquire");
        let reacquired_id = *reacquired;
        crate::assert_with_log!(
            reacquired_id == original_id,
            "cancelled waiter must not perturb the identity of the next clean reacquire",
            original_id,
            reacquired_id
        );

        let stats = pool.stats();
        crate::assert_with_log!(
            stats.active == 1,
            "reacquired resource should be active and not leaked to the cancelled waiter",
            1usize,
            stats.active
        );
        crate::assert_with_log!(
            stats.waiters == 0,
            "cancelled waiter cleanup must persist after the reacquire",
            0usize,
            stats.waiters
        );

        reacquired.return_to_pool();
        let final_stats = pool.stats();
        crate::assert_with_log!(
            final_stats.idle == 1,
            "returned resource should still be reusable after cancelled waiter cleanup",
            1usize,
            final_stats.idle
        );

        crate::test_complete!("metamorphic_cancelled_waiter_preserves_reuse_identity");
    }

    #[test]
    fn metamorphic_pool_bounds_invariant() {
        init_test("metamorphic_pool_bounds_invariant");

        // MR: total_resources <= max_size for all operation sequences
        // Pool should never exceed configured bounds regardless of operations
        let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(2));
        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        // Try to acquire more than max_size resources concurrently
        let r1 = futures_lite::future::block_on(pool.acquire(&cx)).expect("acquire 1");
        let r2 = futures_lite::future::block_on(pool.acquire(&cx)).expect("acquire 2");

        let stats_at_capacity = pool.stats();
        crate::assert_with_log!(
            stats_at_capacity.total <= 2,
            "bounds invariant: total <= max_size at capacity",
            true,
            stats_at_capacity.total <= 2
        );
        crate::assert_with_log!(
            stats_at_capacity.active == 2,
            "both resources active",
            2usize,
            stats_at_capacity.active
        );

        // try_acquire should fail when at capacity
        let r3_opt = pool.try_acquire();
        crate::assert_with_log!(
            r3_opt.is_none(),
            "bounds invariant: try_acquire fails at capacity",
            true,
            r3_opt.is_none()
        );

        // Return resources and verify bounds still respected
        r1.return_to_pool();
        r2.return_to_pool();

        let final_stats = pool.stats();
        crate::assert_with_log!(
            final_stats.total <= 2,
            "bounds invariant: total <= max_size after returns",
            true,
            final_stats.total <= 2
        );

        crate::test_complete!("metamorphic_pool_bounds_invariant");
    }

    #[test]
    fn metamorphic_release_idempotency() {
        init_test("metamorphic_release_idempotency");

        // MR: release(release(resource)) == release(resource)
        // Multiple releases of same resource should be idempotent (safe no-ops)
        let (tx, rx) = mpsc::channel();
        let pooled = PooledResource::new(42u8, tx);

        // First release
        pooled.return_to_pool();

        // Verify first release message received
        let msg1 = rx.recv().expect("first return message");
        match msg1 {
            PoolReturn::Return {
                resource: value, ..
            } => {
                crate::assert_with_log!(value == 42, "first release value", 42u8, value);
            }
            PoolReturn::Discard { .. } => unreachable!("expected return"),
        }

        // Second release should be no-op (idempotency)
        // Note: pooled was consumed by return_to_pool(), so we test the obligation system
        // by verifying no second message is sent on drop (which would be a no-op)

        // Verify exactly one message (idempotency - no double release)
        crate::assert_with_log!(
            rx.try_recv().is_err(),
            "release idempotency: no second message",
            true,
            rx.try_recv().is_err()
        );

        // Test with discard idempotency
        let (tx2, rx2) = mpsc::channel();
        let pooled2 = PooledResource::new(99u8, tx2);

        pooled2.discard();

        let msg2 = rx2.recv().expect("discard message");
        match msg2 {
            PoolReturn::Discard { .. } => {
                // Good - discard message received
            }
            PoolReturn::Return { .. } => unreachable!("expected discard"),
        }

        // Verify no second discard message
        crate::assert_with_log!(
            rx2.try_recv().is_err(),
            "discard idempotency: no second message",
            true,
            rx2.try_recv().is_err()
        );

        crate::test_complete!("metamorphic_release_idempotency");
    }

    #[test]
    fn metamorphic_operation_sequence_commutativity() {
        init_test("metamorphic_operation_sequence_commutativity");

        // MR: final_state(seq1) == final_state(reorder(seq1)) for independent operations
        // Commutative property: reordering independent operations preserves final state
        let pool1 = GenericPool::new(simple_factory, PoolConfig::with_max_size(3));
        let pool2 = GenericPool::new(simple_factory, PoolConfig::with_max_size(3));
        let cx: crate::cx::Cx = crate::cx::Cx::for_testing();

        // Sequence 1: acquire A, acquire B, return A, return B
        let a1 = futures_lite::future::block_on(pool1.acquire(&cx)).expect("acquire A1");
        let b1 = futures_lite::future::block_on(pool1.acquire(&cx)).expect("acquire B1");
        a1.return_to_pool();
        b1.return_to_pool();

        // Sequence 2: acquire A, acquire B, return B, return A (reordered returns)
        let a2 = futures_lite::future::block_on(pool2.acquire(&cx)).expect("acquire A2");
        let b2 = futures_lite::future::block_on(pool2.acquire(&cx)).expect("acquire B2");
        b2.return_to_pool();
        a2.return_to_pool();

        // Commutativity: both sequences should result in equivalent final states
        let stats1 = pool1.stats();
        let stats2 = pool2.stats();

        crate::assert_with_log!(
            stats1.active == stats2.active,
            "commutativity: active count equivalent",
            stats1.active,
            stats2.active
        );
        crate::assert_with_log!(
            stats1.idle == stats2.idle,
            "commutativity: idle count equivalent",
            stats1.idle,
            stats2.idle
        );
        crate::assert_with_log!(
            stats1.total_acquisitions == stats2.total_acquisitions,
            "commutativity: acquisition count equivalent",
            stats1.total_acquisitions,
            stats2.total_acquisitions
        );

        crate::test_complete!("metamorphic_operation_sequence_commutativity");
    }

    #[test]
    fn metamorphic_concurrent_acquire_serializes() {
        init_test("metamorphic_concurrent_acquire_serializes");

        // MR: concurrent(acquire_n) == serialize(acquire_n)
        // Concurrent acquisitions should serialize properly without race conditions
        let pool = std::sync::Arc::new(GenericPool::new(
            simple_factory,
            PoolConfig::with_max_size(2), // Small pool to force contention
        ));

        // Test concurrent acquisition with limited pool size
        let cx = crate::cx::Cx::for_testing();
        let num_tasks = 6; // More than pool capacity
        let mut handles = Vec::new();

        for i in 0..num_tasks {
            let pool_clone = std::sync::Arc::clone(&pool);
            let cx_clone = cx.clone();
            let handle = std::thread::spawn(move || {
                futures_lite::future::block_on(async move {
                    // Each task tries to acquire, use briefly, then return
                    let resource = pool_clone.acquire(&cx_clone).await.unwrap();

                    // Simulate brief usage
                    futures_lite::future::yield_now().await;

                    resource.return_to_pool();
                    i // Return task ID
                })
            });
            handles.push(handle);
        }

        // All tasks should complete successfully despite serialization
        let mut results = Vec::new();
        for handle in handles {
            let result = handle.join().unwrap();
            results.push(result);
        }
        results.sort_unstable();

        // Verify all tasks completed
        let expected: Vec<_> = (0..num_tasks).collect();
        crate::assert_with_log!(
            results == expected,
            "concurrent acquire serialization: all tasks completed",
            expected,
            results
        );

        // Pool should be in consistent state
        let final_stats = pool.stats();
        crate::assert_with_log!(
            final_stats.active == 0,
            "serialization: no leaked active resources",
            0usize,
            final_stats.active
        );
        crate::assert_with_log!(
            final_stats.total_acquisitions == num_tasks as u64,
            "serialization: all acquisitions counted",
            num_tasks as u64,
            final_stats.total_acquisitions
        );

        crate::test_complete!("metamorphic_concurrent_acquire_serializes");
    }

    #[test]
    fn metamorphic_deterministic_lab_runtime_replay() {
        init_test("metamorphic_deterministic_lab_runtime_replay");

        // MR: replay(operations_seq) == replay(operations_seq)
        // Identical operation sequences should produce identical results under LabRuntime

        let run_sequence = || -> (Vec<usize>, Vec<usize>, Vec<usize>) {
            let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(3));
            let _runtime =
                crate::lab::runtime::LabRuntime::new(crate::lab::config::LabConfig::default());

            let (active_history, idle_history, total_history) =
                futures_lite::future::block_on(async {
                    let cx = crate::cx::Cx::for_testing();
                    let mut active_trace = Vec::new();
                    let mut idle_trace = Vec::new();
                    let mut total_trace = Vec::new();

                    // Deterministic sequence of operations
                    for i in 0..5 {
                        let resource = pool.acquire(&cx).await.unwrap();
                        let stats = pool.stats();
                        active_trace.push(stats.active);
                        idle_trace.push(stats.idle);
                        total_trace.push(stats.total);

                        // Deterministic decision based on iteration
                        if i % 2 == 0 {
                            resource.return_to_pool();
                        } else {
                            resource.discard();
                        }

                        let stats_after = pool.stats();
                        active_trace.push(stats_after.active);
                        idle_trace.push(stats_after.idle);
                        total_trace.push(stats_after.total);

                        // Deterministic yield
                        crate::runtime::yield_now().await;
                    }

                    (active_trace, idle_trace, total_trace)
                });

            (active_history, idle_history, total_history)
        };

        // Run the same sequence multiple times
        let (active1, idle1, total1) = run_sequence();
        let (active2, idle2, total2) = run_sequence();
        let (active3, idle3, total3) = run_sequence();

        // Deterministic property: all runs should produce identical traces
        crate::assert_with_log!(
            active1 == active2,
            "deterministic replay: active traces match (run1 vs run2)",
            active1,
            active2
        );
        crate::assert_with_log!(
            active2 == active3,
            "deterministic replay: active traces match (run2 vs run3)",
            active2,
            active3
        );
        crate::assert_with_log!(
            idle1 == idle2,
            "deterministic replay: idle traces match (run1 vs run2)",
            idle1,
            idle2
        );
        crate::assert_with_log!(
            idle2 == idle3,
            "deterministic replay: idle traces match (run2 vs run3)",
            idle2,
            idle3
        );
        crate::assert_with_log!(
            total1 == total2,
            "deterministic replay: total traces match (run1 vs run2)",
            total1,
            total2
        );
        crate::assert_with_log!(
            total2 == total3,
            "deterministic replay: total traces match (run2 vs run3)",
            total2,
            total3
        );

        // Test determinism with timing-dependent operations
        let timed_sequence = || -> Vec<u32> {
            let pool = GenericPool::new(simple_factory, PoolConfig::with_max_size(2));
            let _runtime =
                crate::lab::runtime::LabRuntime::new(crate::lab::config::LabConfig::default());

            futures_lite::future::block_on(async {
                let cx = crate::cx::Cx::for_testing();
                let mut acquisition_order = Vec::new();

                // Spawn concurrent tasks with deterministic timing
                let task1 = async {
                    crate::runtime::yield_now().await;
                    pool.acquire(&cx).await.unwrap().return_to_pool();
                    1u32
                };

                let task2 = async {
                    crate::runtime::yield_now().await;
                    crate::runtime::yield_now().await;
                    pool.acquire(&cx).await.unwrap().return_to_pool();
                    2u32
                };

                let (result1, result2) = futures_lite::future::zip(task1, task2).await;
                acquisition_order.push(result1);
                acquisition_order.push(result2);
                acquisition_order
            })
        };

        let timing1 = timed_sequence();
        let timing2 = timed_sequence();
        let timing3 = timed_sequence();

        // Timing determinism under LabRuntime
        crate::assert_with_log!(
            timing1 == timing2,
            "timing deterministic replay: order matches (run1 vs run2)",
            timing1,
            timing2
        );
        crate::assert_with_log!(
            timing2 == timing3,
            "timing deterministic replay: order matches (run2 vs run3)",
            timing2,
            timing3
        );

        crate::test_complete!("metamorphic_deterministic_lab_runtime_replay");
    }

    fn noop_pool_waker() -> Waker {
        std::task::Waker::noop().clone()
    }
}