nbreq 0.3.1

Runtime-independent cancellable HTTP client
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
//! Public TCP connector contract for plain connections, direct TLS and TLS upgrades.
//!
//! [`TcpConnector`] is an Engine-issued capability ticket. Native Engines accept literal-address
//! connections on their existing reactor owner and exact hostname connections through their
//! existing native resolver owner. Engines without the required native owner fail
//! [`ErrorKind::Unsupported`](crate::ErrorKind::Unsupported) before admission.

pub(crate) mod io;
mod tls;
pub use tls::{
    PendingTlsConnect, TlsConnectCompletion, TlsConnectHandle, TlsConnectWaitOutcome,
    TlsConnection, TlsOptions, TlsReader, TlsWriter,
};

use std::cell::Cell;
use std::error::Error as StdError;
use std::fmt;
use std::marker::PhantomData;
use std::net::{IpAddr, Ipv6Addr, SocketAddr};
use std::sync::Arc;
use std::time::Duration;

use crate::dns::normalize_dns_name;
use crate::registry::{Shared, TcpConnectCallback, TcpConnectState};
use crate::{Error, ErrorKind, ExecuteError, RequestId};

use io::TcpIoShared;

/// Destination of a TCP connect request, shared by plain TCP and direct TLS.
/// TLS certificate identity is supplied separately through [`TlsOptions`].
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum TcpConnectTarget {
    /// Resolve this exact hostname, then connect.
    Hostname {
        /// Normalized lookup identity: lowercase ASCII without a terminal dot.
        name: String,
        /// Destination port. Port zero is rejected at build time.
        port: u16,
    },
    /// Connect to this literal address without public DNS.
    Literal(SocketAddr),
}

/// An owned TCP connect request, shared by plain TCP and direct TLS.
/// TLS identity and handshake policy are supplied separately through [`TlsOptions`].
///
/// Establishment deadlines start at admission. For plain TCP, connect timeout covers queued DNS
/// and TCP establishment. For direct TLS, the earlier of this deadline and
/// [`TlsOptions::handshake_timeout`] bounds the complete DNS/TCP/TLS establishment. Connected-phase
/// read/write inactivity policies begin after plain TCP connects or TLS verification completes.
/// Blocking connected operations reject manual mode rather than driving it.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TcpConnectRequest {
    target: TcpConnectTarget,
    connect_timeout: Option<Duration>,
    read_inactivity_timeout: Option<Duration>,
    write_inactivity_timeout: Option<Duration>,
    send_queue_bytes: Option<usize>,
    receive_queue_bytes: Option<usize>,
}

impl TcpConnectRequest {
    /// Starts a connect builder for an exact ASCII or punycode hostname and port.
    #[must_use]
    pub fn hostname(name: impl Into<String>, port: u16) -> TcpConnectRequestBuilder {
        TcpConnectRequestBuilder {
            target: HostnameOrLiteral::Hostname {
                name: name.into(),
                port,
            },
            connect_timeout: Some(Duration::from_secs(10)),
            read_inactivity_timeout: None,
            write_inactivity_timeout: Some(Duration::from_secs(30)),
            send_queue_bytes: None,
            receive_queue_bytes: None,
        }
    }

    /// Starts a connect builder for a literal socket address. DNS is skipped.
    #[must_use]
    pub fn literal(addr: SocketAddr) -> TcpConnectRequestBuilder {
        TcpConnectRequestBuilder {
            target: HostnameOrLiteral::Literal(addr),
            connect_timeout: Some(Duration::from_secs(10)),
            read_inactivity_timeout: None,
            write_inactivity_timeout: Some(Duration::from_secs(30)),
            send_queue_bytes: None,
            receive_queue_bytes: None,
        }
    }

    /// Returns the connect destination.
    #[must_use]
    pub fn target(&self) -> &TcpConnectTarget {
        &self.target
    }

    /// Returns the connect timeout (ten seconds by default). See [`TcpConnectRequest`] for its
    /// admission-based deadline and how it combines with the handshake deadline for direct TLS.
    #[must_use]
    pub fn connect_timeout(&self) -> Option<Duration> {
        self.connect_timeout
    }

    /// Returns the connected-phase read inactivity timeout when one was selected.
    ///
    /// Read inactivity pauses while the consumer has not provided destination capacity.
    #[must_use]
    pub fn read_inactivity_timeout(&self) -> Option<Duration> {
        self.read_inactivity_timeout
    }

    /// Returns the connected-phase write inactivity timeout (30 seconds by default).
    ///
    /// Write inactivity runs only while accepted output is waiting for socket progress.
    #[must_use]
    pub fn write_inactivity_timeout(&self) -> Option<Duration> {
        self.write_inactivity_timeout
    }

    /// Returns the per-connection send-queue window when one was selected.
    #[must_use]
    pub fn send_queue_bytes(&self) -> Option<usize> {
        self.send_queue_bytes
    }

    /// Returns the per-connection unread-receive window when one was selected.
    #[must_use]
    pub fn receive_queue_bytes(&self) -> Option<usize> {
        self.receive_queue_bytes
    }
}

#[derive(Clone, Debug)]
enum HostnameOrLiteral {
    Hostname { name: String, port: u16 },
    Literal(SocketAddr),
}

/// Builder for an owned [`TcpConnectRequest`].
#[derive(Clone, Debug)]
pub struct TcpConnectRequestBuilder {
    target: HostnameOrLiteral,
    connect_timeout: Option<Duration>,
    read_inactivity_timeout: Option<Duration>,
    write_inactivity_timeout: Option<Duration>,
    send_queue_bytes: Option<usize>,
    receive_queue_bytes: Option<usize>,
}

impl TcpConnectRequestBuilder {
    /// Sets the connect timeout. `None` disables it. See [`TcpConnectRequest`] for its
    /// admission-based deadline and how it combines with the handshake deadline for direct TLS.
    #[must_use]
    pub fn connect_timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
        self.connect_timeout = timeout.into();
        self
    }

    /// Sets the connected-phase read inactivity timeout. `None` disables it.
    ///
    /// The clock pauses under consumer backpressure, when no destination capacity is available.
    /// Blocking `read` rejects manual mode rather than driving the Engine.
    #[must_use]
    pub fn read_inactivity_timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
        self.read_inactivity_timeout = timeout.into();
        self
    }

    /// Sets the connected-phase write inactivity timeout. `None` disables it.
    ///
    /// The clock runs only while accepted output is waiting for socket progress. Blocking `send`
    /// and `finish` reject manual mode rather than driving the Engine.
    #[must_use]
    pub fn write_inactivity_timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
        self.write_inactivity_timeout = timeout.into();
        self
    }

    /// Selects a per-connection send-queue window at or below the Engine ceiling.
    ///
    /// Zero is rejected at build time. A value above the Engine ceiling is rejected at start,
    /// submit, or execute without allocating an ID or permit.
    #[must_use]
    pub fn send_queue_bytes(mut self, bytes: usize) -> Self {
        self.send_queue_bytes = Some(bytes);
        self
    }

    /// Selects a per-connection unread-receive window at or below the Engine ceiling.
    #[must_use]
    pub fn receive_queue_bytes(mut self, bytes: usize) -> Self {
        self.receive_queue_bytes = Some(bytes);
        self
    }

    /// Validates the destination and queue windows, then returns the request.
    pub fn build(self) -> Result<TcpConnectRequest, Error> {
        if self.send_queue_bytes == Some(0) || self.receive_queue_bytes == Some(0) {
            return Err(Error::new(
                ErrorKind::InvalidRequest,
                "a TCP queue window must be greater than zero",
            ));
        }
        let target = match self.target {
            HostnameOrLiteral::Hostname { name, port } => {
                if port == 0 {
                    return Err(Error::new(
                        ErrorKind::InvalidRequest,
                        "TCP destination port zero is not allowed",
                    ));
                }
                TcpConnectTarget::Hostname {
                    name: normalize_dns_name(&name)?.identity,
                    port,
                }
            }
            HostnameOrLiteral::Literal(addr) => {
                if addr.port() == 0 {
                    return Err(Error::new(
                        ErrorKind::InvalidRequest,
                        "TCP destination port zero is not allowed",
                    ));
                }
                if is_unspecified_destination(addr.ip()) {
                    return Err(Error::new(
                        ErrorKind::InvalidRequest,
                        "TCP literal destinations cannot be unspecified addresses",
                    ));
                }
                TcpConnectTarget::Literal(addr)
            }
        };
        Ok(TcpConnectRequest {
            target,
            connect_timeout: self.connect_timeout,
            read_inactivity_timeout: self.read_inactivity_timeout,
            write_inactivity_timeout: self.write_inactivity_timeout,
            send_queue_bytes: self.send_queue_bytes,
            receive_queue_bytes: self.receive_queue_bytes,
        })
    }
}

fn is_unspecified_destination(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(addr) => addr.is_unspecified(),
        IpAddr::V6(addr) => {
            addr.is_unspecified()
                || Ipv6Addr::to_ipv4_mapped(&addr).is_some_and(|mapped| mapped.is_unspecified())
        }
    }
}

/// Cheap cloneable plain TCP and direct TLS connector issued by an [`Engine`](crate::Engine).
///
/// TcpConnector has no public constructor. It does not own or extend Engine lifetime. Detached
/// handles reject new work with [`ErrorKind::EngineStopped`].
///
/// ```compile_fail
/// let _ = nbreq::TcpConnector::new();
/// ```
#[derive(Clone, Debug)]
pub struct TcpConnector {
    shared: Arc<Shared>,
}

impl TcpConnector {
    pub(crate) fn new(shared: Arc<Shared>) -> Self {
        Self { shared }
    }

    /// Starts a callback-oriented connect.
    ///
    /// Rejected starts drop the callback without invoking it.
    pub fn start<F>(
        &self,
        request: TcpConnectRequest,
        callback: F,
    ) -> Result<TcpConnectHandle, Error>
    where
        F: FnOnce(TcpConnectCompletion) + Send + 'static,
    {
        let callback: TcpConnectCallback = Box::new(callback);
        let accepted = self
            .shared
            .accept_tcp_connect(self.clone(), request, Some(callback))?;
        Ok(TcpConnectHandle::new(self.clone(), accepted.state.id()))
    }

    /// Submits a connect and returns its direct terminal-state waiter.
    pub fn submit(&self, request: TcpConnectRequest) -> Result<PendingTcpConnect, Error> {
        let accepted = self
            .shared
            .accept_tcp_connect(self.clone(), request, None)?;
        let handle = TcpConnectHandle::new(self.clone(), accepted.state.id());
        Ok(PendingTcpConnect::new(handle, accepted.state))
    }

    /// Submits a connect and blocks on its direct terminal-state waiter.
    pub fn execute(&self, request: TcpConnectRequest) -> Result<TcpConnection, ExecuteError> {
        match self.submit(request) {
            Ok(pending) => match pending.wait() {
                TcpConnectCompletion::Completed(connection) => Ok(connection),
                TcpConnectCompletion::Failed(error) => Err(ExecuteError::Failed(error)),
                TcpConnectCompletion::Cancelled => Err(ExecuteError::Cancelled),
            },
            Err(error) => Err(ExecuteError::Submission(error)),
        }
    }

    /// Cancels an Engine-scoped connect ID.
    ///
    /// Cancellation is idempotent for same-Engine terminal connects and live connections.
    pub fn cancel(&self, request_id: RequestId) -> Result<(), Error> {
        self.shared.cancel(request_id)
    }
}

/// Engine-bound control handle for one accepted connect operation.
#[derive(Clone, Debug)]
pub struct TcpConnectHandle {
    connector: TcpConnector,
    id: RequestId,
}

impl TcpConnectHandle {
    pub(crate) fn new(connector: TcpConnector, id: RequestId) -> Self {
        Self { connector, id }
    }

    /// Returns the opaque Engine-scoped identity.
    #[must_use]
    pub fn id(&self) -> RequestId {
        self.id
    }

    /// Requests cancellation of the in-flight connect.
    pub fn cancel(&self) -> Result<(), Error> {
        self.connector.cancel(self.id)
    }
}

/// Canonical terminal outcome of an accepted connect.
///
/// The completed value is unique and not cloneable.
#[derive(Debug)]
#[non_exhaustive]
pub enum TcpConnectCompletion {
    /// A unique live cleartext connection.
    Completed(TcpConnection),
    /// A transport, protocol, timeout, or policy failure.
    Failed(Error),
    /// Explicit cancellation won the terminal-state race.
    Cancelled,
}

/// Result of a waiter-local connect timeout.
#[derive(Debug)]
#[non_exhaustive]
pub enum TcpConnectWaitOutcome {
    /// The connect reached its canonical terminal outcome.
    Completed(TcpConnectCompletion),
    /// The local wait expired; the connect and its cancellation handle remain live.
    TimedOut(PendingTcpConnect),
}

/// Accepted connect plus a direct terminal-state waiter.
#[derive(Debug)]
pub struct PendingTcpConnect {
    handle: TcpConnectHandle,
    state: Arc<TcpConnectState>,
}

impl PendingTcpConnect {
    pub(crate) fn new(handle: TcpConnectHandle, state: Arc<TcpConnectState>) -> Self {
        Self { handle, state }
    }

    /// Returns a clone of the independent cancellation handle.
    #[must_use]
    pub fn handle(&self) -> TcpConnectHandle {
        self.handle.clone()
    }

    /// Returns whether canonical terminal state has been committed.
    #[must_use]
    pub fn is_complete(&self) -> bool {
        self.state.is_terminal()
    }

    pub(crate) fn try_completion(&self) -> Option<TcpConnectCompletion> {
        self.state.try_completion()
    }

    pub(crate) fn issued_engine_id(&self) -> u64 {
        self.handle.id.engine
    }

    /// Waits for and returns the canonical terminal outcome.
    #[must_use]
    pub fn wait(self) -> TcpConnectCompletion {
        self.state.wait()
    }

    /// Waits locally without changing connect state or cancelling on timeout.
    #[must_use]
    pub fn wait_for(self, duration: Duration) -> TcpConnectWaitOutcome {
        match self.state.wait_for(duration) {
            Some(completion) => TcpConnectWaitOutcome::Completed(completion),
            None => TcpConnectWaitOutcome::TimedOut(self),
        }
    }
}

/// Cloneable cancellation handle for one live TCP connection.
#[derive(Clone, Debug)]
pub struct TcpConnectionHandle {
    connector: TcpConnector,
    id: RequestId,
}

impl TcpConnectionHandle {
    pub(crate) fn new(connector: TcpConnector, id: RequestId) -> Self {
        Self { connector, id }
    }

    /// Returns the opaque Engine-scoped identity.
    #[must_use]
    pub fn id(&self) -> RequestId {
        self.id
    }

    /// Requests abortive cancellation of the live connection.
    pub fn cancel(&self) -> Result<(), Error> {
        self.connector.cancel(self.id)
    }
}

/// Unique unsplit cleartext TCP connection.
///
/// The connection is `Send` and deliberately neither `Clone` nor `Sync`. There is no `into_std`,
/// raw descriptor, escaped socket, or TLS mode.
///
/// Dropping the unsplit connection before its writer has finished and its reader has observed EOF
/// aborts it. Drop after a successful [`Self::try_finish`] does not revoke the write-side request,
/// but dropping before reader EOF still aborts because the read side is abandoned. Dropping after
/// both directions are terminal is harmless.
///
/// ```compile_fail
/// fn require_clone<T: Clone>() {}
/// require_clone::<nbreq::TcpConnection>();
/// ```
///
/// ```compile_fail
/// fn require_sync<T: Sync>() {}
/// require_sync::<nbreq::TcpConnection>();
/// ```
pub struct TcpConnection {
    io: Arc<TcpIoShared>,
    handle: TcpConnectionHandle,
    live: bool,
    _not_sync: PhantomData<Cell<()>>,
}

impl fmt::Debug for TcpConnection {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("TcpConnection")
            .finish_non_exhaustive()
    }
}

impl TcpConnection {
    #[cfg_attr(not(test), allow(dead_code))]
    pub(crate) fn from_shared(io: Arc<TcpIoShared>, handle: TcpConnectionHandle) -> Self {
        Self {
            io,
            handle,
            live: true,
            _not_sync: PhantomData,
        }
    }

    /// Returns an independent cancellation-only handle for this connection.
    #[must_use]
    pub fn handle(&self) -> TcpConnectionHandle {
        self.handle.clone()
    }

    /// Returns the local socket address.
    pub fn local_addr(&self) -> Result<SocketAddr, Error> {
        self.io.local_addr()
    }

    /// Returns the peer socket address.
    pub fn peer_addr(&self) -> Result<SocketAddr, Error> {
        self.io.peer_addr()
    }

    /// Consumes the unsplit connection into unique reader and writer halves.
    #[must_use]
    pub fn split(mut self) -> (TcpReader, TcpWriter) {
        self.live = false;
        (
            TcpReader {
                io: Arc::clone(&self.io),
                handle: self.handle.clone(),
                _not_sync: PhantomData,
            },
            TcpWriter {
                io: Arc::clone(&self.io),
                handle: self.handle.clone(),
                _not_sync: PhantomData,
            },
        )
    }

    /// Attempts to read available bytes without blocking.
    pub fn try_read(&mut self, destination: &mut [u8]) -> Result<TcpRead, TcpStreamError> {
        self.io.try_read(destination)
    }

    /// Reads bytes on a spawned Engine. Manual Engines return `WrongMode` rather than driving.
    pub fn read(&mut self, destination: &mut [u8]) -> Result<Option<usize>, TcpStreamError> {
        self.io.read(destination)
    }

    /// Attempts to queue owned bytes without blocking. Refused input is returned unchanged.
    pub fn try_send(&mut self, bytes: Vec<u8>) -> Result<(), TcpSendError> {
        self.io.try_send(bytes)
    }

    /// Queues owned bytes on a spawned Engine, returning any unaccepted suffix.
    ///
    /// Manual Engines return [`TcpSendErrorKind::WrongMode`] rather than driving.
    pub fn send(&mut self, bytes: Vec<u8>) -> Result<(), TcpSendError> {
        self.io.send(bytes)
    }

    /// Requests write half-close without blocking, then polls that request.
    ///
    /// The first successful call closes the write side to new sends and asks the owner to drain
    /// accepted output and then half-close. It returns [`TcpFinishStatus::Pending`] until every
    /// accepted byte has reached the socket and write shutdown has completed. Later calls only
    /// poll. This is valid in manual mode and never drives the Engine.
    pub fn try_finish(&mut self) -> Result<TcpFinishStatus, TcpFinishError> {
        self.io.try_finish()
    }

    /// Drains accepted output and then half-closes the write side on a spawned Engine.
    ///
    /// This takes `&mut self` so the unsplit reader remains usable after write-half-close. Manual
    /// Engines reject blocking finish with [`TcpFinishError::WrongMode`] rather than driving.
    pub fn finish(&mut self) -> Result<(), TcpFinishError> {
        self.io.finish()
    }

    /// Registers one write-half-close callback and requests drain-then-half-close.
    ///
    /// Successful registration consumes one shared callback-event permit until the callback
    /// returns. It never runs during resolver/reactor processing, on the spawned network owner, or
    /// under locks. Manual Engines may deliver it on the thread calling [`crate::Engine::drive`]
    /// after the safe network-processing pass; spawned Engines use the accepted callback-dispatch
    /// domain. Dropping the writer after success does not revoke the finish request. A second registration fails with
    /// [`ErrorKind::InvalidRequest`]. Callback-event exhaustion is [`ErrorKind::QueueFull`] and
    /// does not request finish if it was not already requested.
    pub fn finish_with<F>(&mut self, callback: F) -> Result<(), Error>
    where
        F: FnOnce(Result<(), TcpFinishError>) + Send + 'static,
    {
        self.io.finish_with(callback)
    }
}

impl Drop for TcpConnection {
    fn drop(&mut self) {
        if !self.live {
            return;
        }
        self.io.writer_dropped();
        self.io.reader_dropped();
    }
}

/// Unique TCP receiving half.
///
/// Dropping the reader before observed EOF cancels the connection, including after writer finish.
/// Dropping it after EOF is harmless.
///
/// ```compile_fail
/// fn require_clone<T: Clone>() {}
/// require_clone::<nbreq::TcpReader>();
/// ```
///
/// ```compile_fail
/// fn require_sync<T: Sync>() {}
/// require_sync::<nbreq::TcpReader>();
/// ```
pub struct TcpReader {
    io: Arc<TcpIoShared>,
    handle: TcpConnectionHandle,
    _not_sync: PhantomData<Cell<()>>,
}

impl fmt::Debug for TcpReader {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.debug_struct("TcpReader").finish_non_exhaustive()
    }
}

impl TcpReader {
    /// Returns an independent cancellation-only handle for this connection.
    #[must_use]
    pub fn handle(&self) -> TcpConnectionHandle {
        self.handle.clone()
    }

    /// Attempts to read available bytes without blocking.
    pub fn try_read(&mut self, destination: &mut [u8]) -> Result<TcpRead, TcpStreamError> {
        self.io.try_read(destination)
    }

    /// Reads bytes on a spawned Engine. Manual Engines return `WrongMode` rather than driving.
    pub fn read(&mut self, destination: &mut [u8]) -> Result<Option<usize>, TcpStreamError> {
        self.io.read(destination)
    }
}

impl Drop for TcpReader {
    fn drop(&mut self) {
        self.io.reader_dropped();
    }
}

/// Unique TCP sending half.
///
/// Dropping the writer before a successful [`Self::try_finish`] or [`Self::finish`] aborts the
/// connection. Drop after `try_finish` has returned [`TcpFinishStatus::Pending`] or
/// [`TcpFinishStatus::Finished`] does not revoke the request; the Engine owns completing drain and
/// half-close.
///
/// ```compile_fail
/// fn require_clone<T: Clone>() {}
/// require_clone::<nbreq::TcpWriter>();
/// ```
///
/// ```compile_fail
/// fn require_sync<T: Sync>() {}
/// require_sync::<nbreq::TcpWriter>();
/// ```
pub struct TcpWriter {
    io: Arc<TcpIoShared>,
    handle: TcpConnectionHandle,
    _not_sync: PhantomData<Cell<()>>,
}

impl fmt::Debug for TcpWriter {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.debug_struct("TcpWriter").finish_non_exhaustive()
    }
}

impl TcpWriter {
    /// Returns an independent cancellation-only handle for this connection.
    #[must_use]
    pub fn handle(&self) -> TcpConnectionHandle {
        self.handle.clone()
    }

    /// Attempts to queue owned bytes without blocking. Refused input is returned unchanged.
    pub fn try_send(&mut self, bytes: Vec<u8>) -> Result<(), TcpSendError> {
        self.io.try_send(bytes)
    }

    /// Queues owned bytes on a spawned Engine, returning any unaccepted suffix.
    ///
    /// Manual Engines return [`TcpSendErrorKind::WrongMode`] rather than driving.
    pub fn send(&mut self, bytes: Vec<u8>) -> Result<(), TcpSendError> {
        self.io.send(bytes)
    }

    /// Requests write half-close without blocking, then polls that request.
    ///
    /// See [`TcpConnection::try_finish`].
    pub fn try_finish(&mut self) -> Result<TcpFinishStatus, TcpFinishError> {
        self.io.try_finish()
    }

    /// Drains accepted output and then half-closes the write side on a spawned Engine.
    ///
    /// Manual Engines reject blocking finish with [`TcpFinishError::WrongMode`] rather than
    /// driving internally.
    pub fn finish(&mut self) -> Result<(), TcpFinishError> {
        self.io.finish()
    }

    /// Registers one write-half-close callback and requests drain-then-half-close.
    ///
    /// See [`TcpConnection::finish_with`]. At most one callback belongs to the write half, even if
    /// the connection is split after registration.
    pub fn finish_with<F>(&mut self, callback: F) -> Result<(), Error>
    where
        F: FnOnce(Result<(), TcpFinishError>) + Send + 'static,
    {
        self.io.finish_with(callback)
    }
}

impl Drop for TcpWriter {
    fn drop(&mut self) {
        self.io.writer_dropped();
    }
}

/// Passive result of [`TcpConnection::try_finish`] or [`TcpWriter::try_finish`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum TcpFinishStatus {
    /// The finish request is accepted, but accepted output has not yet reached write shutdown.
    Pending,
    /// Accepted output has reached the socket and the write half is shut down.
    Finished,
}

/// Passive read result for one TCP connection or reader.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum TcpRead {
    /// No bytes or terminal state are currently available.
    Pending,
    /// The supplied destination received this many bytes.
    Data(usize),
    /// The reader has observed EOF after draining retained bytes.
    Eof,
}

/// A terminal TCP stream failure, cancellation, reset, or invalid local operation.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum TcpStreamError {
    /// The live connection failed.
    Failed(Error),
    /// Explicit cancellation won the terminal race.
    Cancelled,
    /// The peer reset the connection.
    Reset,
    /// The requested reader or writer operation is invalid in its current mode or state.
    Operation(Error),
}

impl TcpStreamError {
    /// Returns the underlying NBReq error for failures and invalid operations.
    #[must_use]
    pub fn error(&self) -> Option<&Error> {
        match self {
            Self::Failed(error) | Self::Operation(error) => Some(error),
            Self::Cancelled | Self::Reset => None,
        }
    }
}

impl fmt::Display for TcpStreamError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Failed(error) => write!(formatter, "TCP connection failed: {error}"),
            Self::Cancelled => formatter.write_str("TCP connection was cancelled"),
            Self::Reset => formatter.write_str("TCP connection was reset"),
            Self::Operation(error) => write!(formatter, "TCP stream operation failed: {error}"),
        }
    }
}

impl StdError for TcpStreamError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        self.error().map(|error| error as &(dyn StdError + 'static))
    }
}

/// Stable reason a TCP send was not fully accepted.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum TcpSendErrorKind {
    /// The complete buffer would exceed the currently available queue space.
    WouldBlock,
    /// The buffer can never fit within this connection's configured queue window.
    ChunkTooLarge,
    /// The write half is no longer accepting data.
    Closed,
    /// The peer reset the connection.
    Reset,
    /// Explicit cancellation won the terminal race.
    Cancelled,
    /// The owning Engine has stopped.
    EngineStopped,
    /// Blocking send is unavailable for a manually driven Engine.
    WrongMode,
    /// Standalone TCP is not wired on this Engine.
    Unsupported,
}

/// A failed [`TcpConnection::try_send`], [`TcpConnection::send`], [`TcpWriter::try_send`], or
/// [`TcpWriter::send`] operation.
///
/// The unaccepted suffix remains owned by the caller.
#[derive(Debug)]
pub struct TcpSendError {
    kind: TcpSendErrorKind,
    remaining: Vec<u8>,
}

impl TcpSendError {
    pub(crate) fn new(kind: TcpSendErrorKind, remaining: Vec<u8>) -> Self {
        Self { kind, remaining }
    }

    /// Returns the stable reason the bytes were not accepted.
    #[must_use]
    pub fn kind(&self) -> TcpSendErrorKind {
        self.kind
    }

    /// Returns the unaccepted caller-owned suffix.
    #[must_use]
    pub fn into_remaining(self) -> Vec<u8> {
        self.remaining
    }
}

impl fmt::Display for TcpSendError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self.kind {
            TcpSendErrorKind::WouldBlock => "TCP send would block",
            TcpSendErrorKind::ChunkTooLarge => "TCP send exceeds the connection queue window",
            TcpSendErrorKind::Closed => "TCP write half is closed",
            TcpSendErrorKind::Reset => "TCP connection was reset",
            TcpSendErrorKind::Cancelled => "TCP connection was cancelled",
            TcpSendErrorKind::EngineStopped => "the owning Engine has stopped",
            TcpSendErrorKind::WrongMode => "blocking TCP send requires a spawned Engine",
            TcpSendErrorKind::Unsupported => {
                "standalone TCP connections are not available on this Engine"
            }
        })
    }
}

impl StdError for TcpSendError {}

/// Failure while finishing a TCP write half.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum TcpFinishError {
    /// The write half is already closed.
    Closed(Error),
    /// The peer reset the connection.
    Reset,
    /// The owning Engine has stopped.
    EngineStopped,
    /// Blocking finish is unavailable for a manually driven Engine.
    WrongMode,
    /// The live connection failed in transport.
    Failed(Error),
    /// Explicit cancellation won the terminal race.
    Cancelled,
    /// Standalone TCP is not wired on this Engine.
    Unsupported(Error),
}

impl TcpFinishError {
    /// Returns the underlying NBReq error when one is present.
    #[must_use]
    pub fn error(&self) -> Option<&Error> {
        match self {
            Self::Closed(error) | Self::Failed(error) | Self::Unsupported(error) => Some(error),
            Self::Reset | Self::EngineStopped | Self::WrongMode | Self::Cancelled => None,
        }
    }
}

impl fmt::Display for TcpFinishError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Closed(error) => write!(formatter, "TCP write half is closed: {error}"),
            Self::Reset => formatter.write_str("TCP connection was reset"),
            Self::EngineStopped => formatter.write_str("the owning Engine has stopped"),
            Self::WrongMode => formatter.write_str("blocking TCP finish requires a spawned Engine"),
            Self::Failed(error) => write!(formatter, "TCP connection failed: {error}"),
            Self::Cancelled => formatter.write_str("TCP connection was cancelled"),
            Self::Unsupported(error) => write!(formatter, "{error}"),
        }
    }
}

impl StdError for TcpFinishError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        self.error().map(|error| error as &(dyn StdError + 'static))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dispatch::CallbackJob;
    use crate::{Engine, EngineConfig};
    #[cfg(feature = "native")]
    use crate::{LimitKind, TimeoutKind};
    use std::net::{Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6};
    use std::num::NonZeroUsize;
    use std::sync::Arc as StdArc;
    use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
    use std::sync::mpsc;
    use std::time::{Duration, Instant};

    #[test]
    fn hostname_builder_normalizes_name_and_rejects_port_zero() {
        let request = TcpConnectRequest::hostname("Example.COM.", 1234)
            .connect_timeout(Duration::from_secs(5))
            .read_inactivity_timeout(Duration::from_secs(30))
            .write_inactivity_timeout(Duration::from_secs(15))
            .build()
            .expect("hostname connect must build");
        match request.target() {
            TcpConnectTarget::Hostname { name, port } => {
                assert_eq!(name, "example.com");
                assert_eq!(*port, 1234);
            }
            other => panic!("expected hostname target, got {other:?}"),
        }
        assert_eq!(request.connect_timeout(), Some(Duration::from_secs(5)));
        assert_eq!(
            request.read_inactivity_timeout(),
            Some(Duration::from_secs(30))
        );
        assert_eq!(
            request.write_inactivity_timeout(),
            Some(Duration::from_secs(15))
        );
        let error = TcpConnectRequest::hostname("example.com", 0)
            .build()
            .expect_err("port zero must fail at build");
        assert_eq!(error.kind(), ErrorKind::InvalidRequest);
    }

    #[test]
    fn literal_builder_rejects_port_zero_and_unspecified_destinations() {
        let ok = SocketAddr::from((Ipv4Addr::LOCALHOST, 9));
        TcpConnectRequest::literal(ok)
            .build()
            .expect("loopback literal must build");
        TcpConnectRequest::literal(SocketAddr::from((Ipv6Addr::LOCALHOST, 9)))
            .build()
            .expect("IPv6 loopback literal must build");

        for addr in [
            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 80)),
            SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 80, 0, 0)),
            SocketAddr::from((Ipv4Addr::UNSPECIFIED, 80)),
            "0.0.0.0:80".parse().expect("unspecified v4"),
            "[::]:80".parse().expect("unspecified v6"),
            "[::ffff:0.0.0.0]:80"
                .parse()
                .expect("mapped unspecified v4"),
            SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
        ] {
            let error = TcpConnectRequest::literal(addr)
                .build()
                .expect_err("invalid literal must fail at build");
            assert_eq!(error.kind(), ErrorKind::InvalidRequest, "{addr}");
        }
    }

    #[test]
    fn unavailable_connects_reject_before_admission_and_do_not_run_callbacks() {
        let engine = Engine::with_backend(EngineConfig::spawned(), crate::backend::scaffold())
            .expect("scaffold Engine must construct");
        let tcp = engine.tcp_connector();
        let request = TcpConnectRequest::hostname("example.com", 9)
            .build()
            .expect("connect request must build");
        let before = engine.metrics();
        let ran = StdArc::new(AtomicBool::new(false));
        let flag = StdArc::clone(&ran);
        let start_error = tcp
            .start(request.clone(), move |_| {
                flag.store(true, AtomicOrdering::SeqCst);
            })
            .expect_err("F0 connect must be unavailable");
        assert_eq!(start_error.kind(), ErrorKind::Unsupported);
        assert!(!ran.load(AtomicOrdering::SeqCst));
        let execute_error = tcp
            .execute(request)
            .expect_err("F0 execute must be unavailable");
        match execute_error {
            ExecuteError::Submission(error) => assert_eq!(error.kind(), ErrorKind::Unsupported),
            other => panic!("execute must fail before acceptance: {other:?}"),
        }
        let after = engine.metrics();
        assert_eq!(before, after);
        assert_eq!(after.tcp_connects_accepted(), 0);
        assert_eq!(after.current().standalone_tcp_connections(), 0);
        engine.shutdown().expect("scaffold Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn detached_tcp_connector_rejects_after_engine_stop_before_admission() {
        let engine = Engine::new(EngineConfig::spawned()).expect("native Engine must construct");
        let connector = engine.tcp_connector();
        let shared = engine.shared_for_testing();
        engine.shutdown().expect("empty native Engine must stop");

        let error = connector
            .submit(
                TcpConnectRequest::literal(SocketAddr::from((Ipv4Addr::LOCALHOST, 9)))
                    .build()
                    .expect("detached request must build"),
            )
            .expect_err("detached connector must reject new work");
        assert_eq!(error.kind(), ErrorKind::EngineStopped);
        let metrics = shared.metrics_snapshot();
        assert_eq!(metrics.tcp_connects_accepted(), 0);
        assert_eq!(metrics.current().standalone_tcp_connections(), 0);
        assert_eq!(metrics.current().reserved_tcp_queue_bytes(), 0);
    }

    #[test]
    fn per_connection_queue_cannot_exceed_the_engine_ceiling() {
        let engine = Engine::with_backend(
            EngineConfig::spawned().with_max_tcp_queue_bytes_per_connection(8),
            crate::backend::scaffold(),
        )
        .expect("bounded scaffold Engine must construct");
        let request = TcpConnectRequest::literal(SocketAddr::from((Ipv4Addr::LOCALHOST, 9)))
            .send_queue_bytes(16)
            .build()
            .expect("over-ceiling request must still build");
        let error = engine
            .tcp_connector()
            .submit(request)
            .expect_err("over-ceiling send window must fail before admission");
        assert_eq!(error.kind(), ErrorKind::Unsupported);
        engine.shutdown().expect("bounded Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn native_literal_connect_is_duplex_on_the_existing_owner() {
        use std::io::{Read, Write};
        use std::net::TcpListener;
        use std::thread;

        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind loopback fixture");
        let address = listener.local_addr().expect("fixture address");
        let server = thread::spawn(move || {
            let (mut socket, _) = listener.accept().expect("accept standalone TCP");
            let mut bytes = [0_u8; 4];
            socket.read_exact(&mut bytes).expect("read request bytes");
            assert_eq!(&bytes, b"ping");
            socket.write_all(b"pong").expect("write response bytes");
        });

        let config = EngineConfig::spawned();
        let factory = crate::backend::native_http_factory(&config);
        let engine = Engine::with_spawned_factory(config, factory)
            .expect("native standalone TCP Engine must construct");
        let request = TcpConnectRequest::literal(address)
            .connect_timeout(Duration::from_secs(2))
            .send_queue_bytes(16)
            .receive_queue_bytes(16)
            .build()
            .expect("literal request must build");
        let mut connection = engine
            .tcp_connector()
            .execute(request)
            .expect("literal connect must complete");
        assert_eq!(connection.peer_addr().expect("peer address"), address);
        connection.send(b"ping".to_vec()).expect("queue request");
        let mut response = [0_u8; 4];
        assert_eq!(
            connection.read(&mut response).expect("read response"),
            Some(4)
        );
        assert_eq!(&response, b"pong");
        drop(connection);
        server.join().expect("fixture must join");
        engine.shutdown().expect("native Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn native_hostname_connect_uses_the_existing_resolver_and_reactor() {
        use crate::backend::native_dns_wire::test_support::RecordType;
        use std::io::{Read, Write};
        use std::net::TcpListener;
        use std::thread;

        let dns = crate::dns_wiring_tests::DualStackDns::with_handler(|request| {
            let query_type = request.query().expect("fixture query").query_type();
            Some(match query_type {
                RecordType::A => crate::dns_wiring_tests::a_record(&request, Ipv4Addr::LOCALHOST),
                RecordType::AAAA => crate::dns_wiring_tests::nodata(&request),
                other => panic!("unexpected hostname-connect query type: {other:?}"),
            })
        });
        let listener =
            TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind hostname-connect fixture");
        let port = listener.local_addr().expect("fixture address").port();
        let server = thread::spawn(move || {
            let (mut socket, _) = listener.accept().expect("accept hostname TCP");
            let mut byte = [0_u8; 1];
            socket.read_exact(&mut byte).expect("read hostname byte");
            socket.write_all(&byte).expect("echo hostname byte");
        });

        let engine = crate::testing::native_http_engine_with_nameserver(
            EngineConfig::spawned(),
            dns.address(),
        )
        .expect("native hostname Engine must construct");
        let mut connection = engine
            .tcp_connector()
            .execute(
                TcpConnectRequest::hostname("tcp.test", port)
                    .connect_timeout(Duration::from_secs(2))
                    .send_queue_bytes(8)
                    .receive_queue_bytes(8)
                    .build()
                    .expect("hostname request must build"),
            )
            .expect("hostname connect must complete");
        connection.send(vec![9]).expect("hostname byte must send");
        let mut byte = [0_u8; 1];
        assert_eq!(connection.read(&mut byte).expect("hostname echo"), Some(1));
        assert_eq!(byte, [9]);
        assert_eq!(engine.metrics().resolutions_accepted(), 0);
        assert_eq!(engine.metrics().tcp_connects_accepted(), 1);
        assert_eq!(engine.metrics().current().inflight_resolutions(), 0);
        drop(connection);
        server.join().expect("hostname fixture must join");
        engine.shutdown().expect("native Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn native_hostname_connect_tries_resolved_addresses_serially() {
        use crate::backend::native_dns_wire::test_support::RecordType;
        use std::net::TcpListener;
        use std::thread;

        let dns = crate::dns_wiring_tests::DualStackDns::with_handler(|request| {
            Some(match request.query().expect("fixture query").query_type() {
                RecordType::A => crate::dns_wiring_tests::a_record(&request, Ipv4Addr::LOCALHOST),
                RecordType::AAAA => {
                    crate::dns_wiring_tests::aaaa_record(&request, Ipv6Addr::LOCALHOST)
                }
                other => panic!("unexpected serial-connect query type: {other:?}"),
            })
        });
        let listener =
            TcpListener::bind((Ipv6Addr::LOCALHOST, 0)).expect("bind serial-connect fixture");
        let port = listener.local_addr().expect("fixture address").port();
        let server = thread::spawn(move || {
            let (socket, _) = listener.accept().expect("accept second address");
            drop(socket);
        });
        let config = EngineConfig::manual();
        let backend =
            crate::backend::native_http_backend_with_nameserver_and_failed_standalone_addresses(
                &config,
                dns.address(),
                1,
            )
            .expect("serial-connect backend must construct");
        let mut engine =
            Engine::with_backend(config, backend).expect("serial-connect Engine must construct");
        let pending = engine
            .tcp_connector()
            .submit(
                TcpConnectRequest::hostname("serial.test", port)
                    .connect_timeout(Duration::from_secs(2))
                    .build()
                    .expect("serial request must build"),
            )
            .expect("serial connect must submit");
        let connection = match engine
            .drive_until(pending)
            .expect("serial connect must drive")
        {
            TcpConnectCompletion::Completed(connection) => connection,
            other => panic!("second resolved address must connect: {other:?}"),
        };
        assert_eq!(
            connection.peer_addr().expect("peer address").ip(),
            IpAddr::V6(Ipv6Addr::LOCALHOST)
        );
        drop(connection);
        server.join().expect("serial fixture must join");
        engine.shutdown().expect("serial-connect Engine must stop");
    }

    #[cfg(all(feature = "native", feature = "resolver"))]
    #[test]
    fn cached_hostname_deadline_stops_between_serial_attempts() {
        use crate::backend::native_dns_wire::test_support::RecordType;
        use std::io;
        use std::net::TcpListener;

        let dns = crate::dns_wiring_tests::DualStackDns::with_handler(|request| {
            Some(match request.query().expect("fixture query").query_type() {
                RecordType::A => crate::dns_wiring_tests::a_record(&request, Ipv4Addr::LOCALHOST),
                RecordType::AAAA => {
                    crate::dns_wiring_tests::aaaa_record(&request, Ipv6Addr::LOCALHOST)
                }
                other => panic!("unexpected cached-connect query type: {other:?}"),
            })
        });
        let listener = TcpListener::bind((Ipv6Addr::LOCALHOST, 0))
            .expect("bind cached serial-connect fixture");
        listener
            .set_nonblocking(true)
            .expect("make cached serial listener nonblocking");
        let port = listener.local_addr().expect("fixture address").port();
        let config = EngineConfig::spawned();
        let backend = crate::backend::native_http_backend_with_nameserver_and_delayed_failed_standalone_address(
            &config,
            dns.address(),
            Duration::from_millis(50),
        )
        .expect("cached-deadline backend must construct");
        let engine =
            Engine::with_backend(config, backend).expect("cached-deadline Engine must construct");

        let response = engine
            .resolver()
            .execute(
                crate::ResolveRequest::hostname("cached-deadline.test")
                    .build()
                    .expect("cache-prime request must build"),
            )
            .expect("cache-prime resolution must complete");
        assert_eq!(response.status(), crate::ResolveStatus::Answer);
        let queries_after_prime = dns.queries();

        let error = match engine.tcp_connector().execute(
            TcpConnectRequest::hostname("cached-deadline.test", port)
                .connect_timeout(Duration::from_millis(20))
                .build()
                .expect("cached-deadline connect must build"),
        ) {
            Err(ExecuteError::Failed(error)) => error,
            other => panic!("deadline must stop before the second address: {other:?}"),
        };
        assert_eq!(error.kind(), ErrorKind::Timeout);
        assert_eq!(error.timeout_kind(), Some(TimeoutKind::Connect));
        assert_eq!(
            dns.queries(),
            queries_after_prime,
            "hostname connect must consume the shared cached answer"
        );
        match listener.accept() {
            Err(error) if error.kind() == io::ErrorKind::WouldBlock => {}
            Ok((_socket, _peer)) => panic!("expired connect must not try the second address"),
            Err(error) => panic!("cached serial listener failed: {error}"),
        }
        assert_eq!(engine.metrics().current().inflight_resolutions(), 0);
        assert_eq!(engine.metrics().current().standalone_tcp_connections(), 0);
        engine.shutdown().expect("cached-deadline Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn native_hostname_connect_fails_once_after_every_address_fails() {
        use crate::backend::native_dns_wire::test_support::RecordType;

        let dns = crate::dns_wiring_tests::DualStackDns::with_handler(|request| {
            Some(match request.query().expect("fixture query").query_type() {
                RecordType::A => crate::dns_wiring_tests::a_record(&request, Ipv4Addr::LOCALHOST),
                RecordType::AAAA => {
                    crate::dns_wiring_tests::aaaa_record(&request, Ipv6Addr::LOCALHOST)
                }
                other => panic!("unexpected all-fail query type: {other:?}"),
            })
        });
        let config = EngineConfig::manual();
        let backend =
            crate::backend::native_http_backend_with_nameserver_and_failed_standalone_addresses(
                &config,
                dns.address(),
                2,
            )
            .expect("all-fail backend must construct");
        let mut engine =
            Engine::with_backend(config, backend).expect("all-fail Engine must construct");
        let pending = engine
            .tcp_connector()
            .submit(
                TcpConnectRequest::hostname("all-fail.test", 9)
                    .connect_timeout(Duration::from_secs(2))
                    .build()
                    .expect("all-fail request must build"),
            )
            .expect("all-fail request must submit");
        let error = match engine
            .drive_until(pending)
            .expect("all-fail connect must drive")
        {
            TcpConnectCompletion::Failed(error) => error,
            other => panic!("all addresses must fail one connect: {other:?}"),
        };
        assert_eq!(error.kind(), ErrorKind::Transport);
        assert_eq!(
            error.transport_stage(),
            Some(crate::TransportStage::Connect)
        );
        assert_eq!(engine.metrics().tcp_connects_failed(), 1);
        assert_eq!(engine.metrics().current().inflight_resolutions(), 0);
        assert_eq!(engine.metrics().current().standalone_tcp_connections(), 0);
        engine.shutdown().expect("all-fail Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn hostname_dns_negatives_and_operational_failures_keep_their_contract() {
        use crate::backend::native_dns_wire::test_support::{Message, ResponseCode};

        for (label, handler) in [
            (
                "NXDOMAIN",
                crate::dns_wiring_tests::nxdomain as fn(&Message) -> Message,
            ),
            ("NoData", crate::dns_wiring_tests::nodata),
        ] {
            let dns = crate::dns_wiring_tests::DualStackDns::with_handler(move |request| {
                Some(handler(&request))
            });
            let engine = crate::testing::native_http_engine_with_nameserver(
                EngineConfig::spawned(),
                dns.address(),
            )
            .expect("negative DNS Engine must construct");
            let error = match engine.tcp_connector().execute(
                TcpConnectRequest::hostname("negative.test", 9)
                    .connect_timeout(Duration::from_secs(2))
                    .build()
                    .expect("negative request must build"),
            ) {
                Err(ExecuteError::Failed(error)) => error,
                other => panic!("{label} hostname connect must fail: {other:?}"),
            };
            assert_eq!(error.kind(), ErrorKind::Transport, "{label}");
            assert_eq!(
                error.transport_stage(),
                Some(crate::TransportStage::Dns),
                "{label}"
            );
            assert_eq!(error.dns_failure(), None, "{label}");
            engine.shutdown().expect("negative DNS Engine must stop");
        }

        let dns = crate::dns_wiring_tests::DualStackDns::with_handler(|request| {
            Some(crate::dns_wiring_tests::rcode(
                &request,
                ResponseCode::ServFail,
            ))
        });
        let engine = crate::testing::native_http_engine_with_nameserver(
            EngineConfig::spawned(),
            dns.address(),
        )
        .expect("SERVFAIL Engine must construct");
        let error = match engine.tcp_connector().execute(
            TcpConnectRequest::hostname("servfail.test", 9)
                .connect_timeout(Duration::from_secs(2))
                .build()
                .expect("SERVFAIL request must build"),
        ) {
            Err(ExecuteError::Failed(error)) => error,
            other => panic!("SERVFAIL hostname connect must fail: {other:?}"),
        };
        assert_eq!(error.kind(), ErrorKind::Transport);
        assert_eq!(error.transport_stage(), Some(crate::TransportStage::Dns));
        assert_eq!(error.dns_failure(), Some(crate::DnsFailure::ServerFailure));
        engine.shutdown().expect("SERVFAIL Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn hostname_cancel_during_dns_releases_both_admission_budgets() {
        use std::thread;

        let dns = crate::dns_wiring_tests::DualStackDns::with_handler(|_request| None);
        let engine = crate::testing::native_http_engine_with_nameserver(
            EngineConfig::spawned(),
            dns.address(),
        )
        .expect("cancel-during-DNS Engine must construct");
        let pending = engine
            .tcp_connector()
            .submit(
                TcpConnectRequest::hostname("cancel.test", 9)
                    .connect_timeout(Duration::from_secs(2))
                    .build()
                    .expect("cancel request must build"),
            )
            .expect("cancel request must submit");
        let query_deadline = Instant::now() + Duration::from_secs(1);
        while dns.queries() == 0 {
            assert!(
                Instant::now() < query_deadline,
                "hostname DNS query did not start"
            );
            thread::sleep(Duration::from_millis(5));
        }
        pending
            .handle()
            .cancel()
            .expect("DNS-phase cancel must win");
        assert!(matches!(pending.wait(), TcpConnectCompletion::Cancelled));
        let release_deadline = Instant::now() + Duration::from_secs(1);
        loop {
            let metrics = engine.metrics();
            if metrics.current().inflight_resolutions() == 0
                && metrics.current().standalone_tcp_connections() == 0
            {
                break;
            }
            assert!(
                Instant::now() < release_deadline,
                "DNS-phase cancellation did not release admission"
            );
            thread::sleep(Duration::from_millis(5));
        }
        assert_eq!(engine.metrics().tcp_connects_cancelled(), 1);
        assert_eq!(engine.metrics().resolutions_cancelled(), 0);
        engine
            .shutdown()
            .expect("cancel-during-DNS Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn hostname_cancel_at_dns_handoff_cannot_publish_or_leak_a_socket() {
        use crate::backend::native_dns_wire::test_support::RecordType;
        use std::io;
        use std::net::TcpListener;
        use std::thread;

        let dns = crate::dns_wiring_tests::DualStackDns::with_handler(|request| {
            Some(match request.query().expect("fixture query").query_type() {
                RecordType::A => crate::dns_wiring_tests::a_record(&request, Ipv4Addr::LOCALHOST),
                RecordType::AAAA => crate::dns_wiring_tests::nodata(&request),
                other => panic!("unexpected handoff query type: {other:?}"),
            })
        });
        let listener =
            TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind handoff-cancel fixture");
        listener
            .set_nonblocking(true)
            .expect("make handoff listener nonblocking");
        let port = listener.local_addr().expect("fixture address").port();
        let (entered_tx, entered_rx) = mpsc::channel();
        let (release_tx, release_rx) = mpsc::channel();
        let config = EngineConfig::manual();
        let backend =
            crate::backend::native_http_backend_with_nameserver_and_standalone_dns_handoff_gate(
                &config,
                dns.address(),
                entered_tx,
                release_rx,
            )
            .expect("handoff-gated backend must construct");
        let mut engine =
            Engine::with_backend(config, backend).expect("handoff-gated Engine must construct");
        let pending = engine
            .tcp_connector()
            .submit(
                TcpConnectRequest::hostname("handoff.test", port)
                    .connect_timeout(Duration::from_secs(2))
                    .build()
                    .expect("handoff request must build"),
            )
            .expect("handoff request must submit");
        let handle = pending.handle();
        let driver = thread::spawn(move || {
            engine
                .drive(Instant::now() + Duration::from_secs(2))
                .expect("handoff Engine must drive");
            engine
        });
        entered_rx
            .recv_timeout(Duration::from_secs(1))
            .expect("DNS handoff must pause");
        handle.cancel().expect("handoff cancellation must win");
        release_tx.send(()).expect("release DNS handoff");
        assert!(matches!(pending.wait(), TcpConnectCompletion::Cancelled));
        let engine = driver.join().expect("handoff driver must join");
        match listener.accept() {
            Err(error) if error.kind() == io::ErrorKind::WouldBlock => {}
            Ok((_socket, _peer)) => panic!("cancelled handoff must not create a TCP connection"),
            Err(error) => panic!("handoff listener failed: {error}"),
        }
        assert_eq!(engine.metrics().current().inflight_resolutions(), 0);
        assert_eq!(engine.metrics().current().standalone_tcp_connections(), 0);
        engine.shutdown().expect("handoff Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn hostname_connect_timeout_covers_the_dns_phase() {
        let dns = crate::dns_wiring_tests::DualStackDns::with_handler(|_request| None);
        let engine = crate::testing::native_http_engine_with_nameserver(
            EngineConfig::spawned(),
            dns.address(),
        )
        .expect("DNS-timeout Engine must construct");
        let error = match engine.tcp_connector().execute(
            TcpConnectRequest::hostname("timeout.test", 9)
                .connect_timeout(Duration::from_millis(60))
                .build()
                .expect("timeout request must build"),
        ) {
            Err(ExecuteError::Failed(error)) => error,
            other => panic!("DNS-phase connect must time out: {other:?}"),
        };
        assert_eq!(error.kind(), ErrorKind::Timeout);
        assert_eq!(error.timeout_kind(), Some(TimeoutKind::Connect));
        assert_eq!(engine.metrics().current().inflight_resolutions(), 0);
        assert_eq!(engine.metrics().current().standalone_tcp_connections(), 0);
        engine.shutdown().expect("DNS-timeout Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn hostname_terminal_publication_orders_metrics_before_late_callback_activation() {
        let dns = crate::dns_wiring_tests::DualStackDns::with_handler(|_request| None);
        let engine = crate::testing::native_http_engine_with_nameserver(
            EngineConfig::spawned(),
            dns.address(),
        )
        .expect("publication-order Engine must construct");
        let shared = engine.shared_for_testing();

        let (activation_tx, activation_rx) = mpsc::channel();
        let (activation_release_tx, activation_release_rx) = mpsc::channel();
        shared.set_callback_activation_hook(move || {
            activation_tx.send(()).expect("observe callback activation");
            activation_release_rx
                .recv()
                .expect("release callback activation");
        });
        let (terminal_tx, terminal_rx) = mpsc::channel();
        let (terminal_release_tx, terminal_release_rx) = mpsc::channel();
        shared.set_tcp_terminal_commit_hook(move || {
            terminal_tx.send(()).expect("observe terminal commit");
            terminal_release_rx
                .recv()
                .expect("release terminal publication");
        });

        let connector = engine.tcp_connector();
        let callback_shared = StdArc::clone(&shared);
        let (callback_tx, callback_rx) = mpsc::channel();
        let start_thread = std::thread::spawn(move || {
            connector.start(
                TcpConnectRequest::hostname("publication.test", 9)
                    .connect_timeout(Duration::from_millis(60))
                    .build()
                    .expect("publication-order request must build"),
                move |completion| {
                    let metrics = callback_shared.metrics_snapshot();
                    callback_tx
                        .send((
                            completion,
                            metrics.current().inflight_resolutions(),
                            metrics.current().standalone_tcp_connections(),
                        ))
                        .expect("send publication-order callback");
                },
            )
        });

        activation_rx
            .recv_timeout(Duration::from_secs(1))
            .expect("callback activation must pause");
        terminal_rx
            .recv_timeout(Duration::from_secs(1))
            .expect("terminal commit must pause before publication");
        activation_release_tx
            .send(())
            .expect("release late callback activation");
        let _handle = start_thread
            .join()
            .expect("callback start thread must join")
            .expect("callback connect must be accepted");
        assert!(
            callback_rx.recv_timeout(Duration::from_millis(50)).is_err(),
            "callback must not observe the terminal before metrics publication"
        );

        terminal_release_tx
            .send(())
            .expect("release terminal publication");
        let (completion, resolutions, connections) = callback_rx
            .recv_timeout(Duration::from_secs(1))
            .expect("published terminal callback must arrive");
        assert!(matches!(
            completion,
            TcpConnectCompletion::Failed(error)
                if error.kind() == ErrorKind::Timeout
                    && error.timeout_kind() == Some(TimeoutKind::Connect)
        ));
        assert_eq!(resolutions, 0);
        assert_eq!(connections, 0);
        engine
            .shutdown()
            .expect("publication-order Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn hostname_cancel_all_and_callback_delivery_share_the_existing_domains() {
        use crate::backend::native_dns_wire::test_support::RecordType;
        use std::net::TcpListener;
        use std::thread;

        let dns = crate::dns_wiring_tests::DualStackDns::with_handler(|request| {
            Some(match request.query().expect("fixture query").query_type() {
                RecordType::A => crate::dns_wiring_tests::a_record(&request, Ipv4Addr::LOCALHOST),
                RecordType::AAAA => crate::dns_wiring_tests::nodata(&request),
                other => panic!("unexpected callback query type: {other:?}"),
            })
        });
        let listener =
            TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind hostname callback fixture");
        let port = listener.local_addr().expect("fixture address").port();
        let server = thread::spawn(move || {
            let (socket, _) = listener.accept().expect("accept hostname callback TCP");
            drop(socket);
        });
        let engine = crate::testing::native_http_engine_with_nameserver(
            EngineConfig::spawned(),
            dns.address(),
        )
        .expect("hostname callback Engine must construct");
        let (callback_tx, callback_rx) = mpsc::channel();
        let handle = engine
            .tcp_connector()
            .start(
                TcpConnectRequest::hostname("callback.test", port)
                    .connect_timeout(Duration::from_secs(2))
                    .build()
                    .expect("callback request must build"),
                move |completion| {
                    callback_tx
                        .send(completion)
                        .expect("send hostname callback completion");
                },
            )
            .expect("hostname callback must start");
        let connection = match callback_rx
            .recv_timeout(Duration::from_secs(2))
            .expect("hostname callback must arrive")
        {
            TcpConnectCompletion::Completed(connection) => connection,
            other => panic!("hostname callback connect failed: {other:?}"),
        };
        assert_eq!(connection.handle().id(), handle.id());
        drop(connection);
        server.join().expect("hostname callback fixture must join");
        engine
            .shutdown()
            .expect("hostname callback Engine must stop");

        let silent = crate::dns_wiring_tests::DualStackDns::with_handler(|_request| None);
        let engine = crate::testing::native_http_engine_with_nameserver(
            EngineConfig::spawned(),
            silent.address(),
        )
        .expect("hostname cancel-all Engine must construct");
        let pending = engine
            .tcp_connector()
            .submit(
                TcpConnectRequest::hostname("cancel-all.test", 9)
                    .connect_timeout(Duration::from_secs(2))
                    .build()
                    .expect("cancel-all request must build"),
            )
            .expect("cancel-all request must submit");
        let query_deadline = Instant::now() + Duration::from_secs(1);
        while silent.queries() == 0 {
            assert!(Instant::now() < query_deadline, "DNS query did not start");
            thread::sleep(Duration::from_millis(5));
        }
        engine.cancel_all();
        assert!(matches!(pending.wait(), TcpConnectCompletion::Cancelled));
        assert_eq!(engine.metrics().current().inflight_resolutions(), 0);
        assert_eq!(engine.metrics().current().standalone_tcp_connections(), 0);
        engine
            .shutdown()
            .expect("hostname cancel-all Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn hostname_shutdown_during_dns_delivers_engine_stopped_and_joins() {
        use std::thread;

        let dns = crate::dns_wiring_tests::DualStackDns::with_handler(|_request| None);
        let engine = crate::testing::native_http_engine_with_nameserver(
            EngineConfig::spawned(),
            dns.address(),
        )
        .expect("hostname shutdown Engine must construct");
        let shared = engine.shared_for_testing();
        let pending = engine
            .tcp_connector()
            .submit(
                TcpConnectRequest::hostname("shutdown.test", 9)
                    .connect_timeout(Duration::from_secs(2))
                    .build()
                    .expect("shutdown request must build"),
            )
            .expect("shutdown request must submit");
        let query_deadline = Instant::now() + Duration::from_secs(1);
        while dns.queries() == 0 {
            assert!(Instant::now() < query_deadline, "DNS query did not start");
            thread::sleep(Duration::from_millis(5));
        }
        engine.shutdown().expect("hostname shutdown must join");
        assert!(matches!(
            pending.wait(),
            TcpConnectCompletion::Failed(error) if error.kind() == ErrorKind::EngineStopped
        ));
        assert_eq!(
            shared.metrics_snapshot().current().inflight_resolutions(),
            0
        );
        assert_eq!(
            shared
                .metrics_snapshot()
                .current()
                .standalone_tcp_connections(),
            0
        );
    }

    #[cfg(feature = "native")]
    #[test]
    fn native_read_inactivity_fails_a_silent_live_connection() {
        use std::io::Read;
        use std::net::TcpListener;
        use std::thread;

        let listener =
            TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind read-inactivity fixture");
        let address = listener.local_addr().expect("read-inactivity address");
        let server = thread::spawn(move || {
            let (mut socket, _) = listener.accept().expect("accept silent TCP");
            let mut byte = [0_u8; 1];
            let _closed_or_reset = socket.read(&mut byte);
        });

        let config = EngineConfig::spawned();
        let factory = crate::backend::native_http_factory(&config);
        let engine = Engine::with_spawned_factory(config, factory)
            .expect("native standalone TCP Engine must construct");
        let mut connection = engine
            .tcp_connector()
            .execute(
                TcpConnectRequest::literal(address)
                    .read_inactivity_timeout(Duration::from_millis(50))
                    .build()
                    .expect("read-inactivity request must build"),
            )
            .expect("silent TCP must connect");
        let cancel = connection.handle();
        let (result_tx, result_rx) = mpsc::channel();
        thread::spawn(move || {
            let mut byte = [0_u8; 1];
            result_tx
                .send(connection.read(&mut byte))
                .expect("send read-inactivity result");
        });
        let result = match result_rx.recv_timeout(Duration::from_secs(2)) {
            Ok(result) => result,
            Err(error) => {
                cancel.cancel().expect("guard cancellation must succeed");
                panic!("read inactivity did not terminate the connection: {error}");
            }
        };
        assert!(matches!(
            result,
            Err(TcpStreamError::Failed(error))
                if error.kind() == ErrorKind::Timeout
                    && error.timeout_kind() == Some(TimeoutKind::Inactivity)
        ));
        assert_eq!(engine.metrics().current().standalone_tcp_connections(), 0);
        assert_eq!(engine.metrics().current().reserved_tcp_queue_bytes(), 0);
        server.join().expect("silent fixture must join");
        engine.shutdown().expect("native Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn native_read_progress_refreshes_inactivity() {
        use std::io::{Read, Write};
        use std::net::TcpListener;
        use std::thread;

        let listener =
            TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind read-progress fixture");
        let address = listener.local_addr().expect("read-progress address");
        let server = thread::spawn(move || {
            let (mut socket, _) = listener.accept().expect("accept read-progress TCP");
            socket.write_all(b"a").expect("write first progress byte");
            thread::sleep(Duration::from_millis(600));
            socket.write_all(b"b").expect("write second progress byte");
            thread::sleep(Duration::from_millis(600));
            socket.write_all(b"c").expect("write third progress byte");
            let mut byte = [0_u8; 1];
            let _closed_or_reset = socket.read(&mut byte);
        });

        let config = EngineConfig::spawned();
        let factory = crate::backend::native_http_factory(&config);
        let engine = Engine::with_spawned_factory(config, factory)
            .expect("native standalone TCP Engine must construct");
        let mut connection = engine
            .tcp_connector()
            .execute(
                TcpConnectRequest::literal(address)
                    .receive_queue_bytes(8)
                    .read_inactivity_timeout(Duration::from_secs(1))
                    .build()
                    .expect("read-progress request must build"),
            )
            .expect("read-progress TCP must connect");
        let started = Instant::now();
        for expected in b"abc" {
            let mut byte = [0_u8; 1];
            assert_eq!(
                connection.read(&mut byte).expect("read progress byte"),
                Some(1)
            );
            assert_eq!(byte[0], *expected);
        }
        assert!(
            started.elapsed() > Duration::from_secs(1),
            "the fixture did not cross the original inactivity deadline"
        );
        drop(connection);
        server.join().expect("read-progress fixture must join");
        engine.shutdown().expect("native Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn native_receive_backpressure_pauses_then_restarts_read_inactivity() {
        use std::io::{Read, Write};
        use std::net::TcpListener;
        use std::thread;

        let listener =
            TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind read-pressure fixture");
        let address = listener.local_addr().expect("read-pressure address");
        let (written_tx, written_rx) = mpsc::channel();
        let server = thread::spawn(move || {
            let (mut socket, _) = listener.accept().expect("accept read-pressure TCP");
            socket.write_all(b"abc").expect("fill receive window");
            written_tx.send(()).expect("signal filled receive window");
            let mut byte = [0_u8; 1];
            let _closed_or_reset = socket.read(&mut byte);
        });

        let config = EngineConfig::spawned();
        let factory = crate::backend::native_http_factory(&config);
        let engine = Engine::with_spawned_factory(config, factory)
            .expect("native standalone TCP Engine must construct");
        let mut connection = engine
            .tcp_connector()
            .execute(
                TcpConnectRequest::literal(address)
                    .receive_queue_bytes(3)
                    .read_inactivity_timeout(Duration::from_millis(50))
                    .build()
                    .expect("read-pressure request must build"),
            )
            .expect("read-pressure TCP must connect");
        written_rx
            .recv_timeout(Duration::from_secs(1))
            .expect("fixture must write the receive window");
        thread::sleep(Duration::from_millis(150));

        let mut bytes = [0_u8; 3];
        assert_eq!(
            connection
                .try_read(&mut bytes)
                .expect("a full receive window must pause inactivity"),
            TcpRead::Data(3)
        );
        assert_eq!(&bytes, b"abc");

        let cancel = connection.handle();
        let (result_tx, result_rx) = mpsc::channel();
        thread::spawn(move || {
            let mut byte = [0_u8; 1];
            result_tx
                .send(connection.read(&mut byte))
                .expect("send resumed-inactivity result");
        });
        let result = match result_rx.recv_timeout(Duration::from_secs(2)) {
            Ok(result) => result,
            Err(error) => {
                cancel.cancel().expect("guard cancellation must succeed");
                panic!("read inactivity did not restart after drain: {error}");
            }
        };
        assert!(matches!(
            result,
            Err(TcpStreamError::Failed(error))
                if error.kind() == ErrorKind::Timeout
                    && error.timeout_kind() == Some(TimeoutKind::Inactivity)
        ));
        assert_eq!(engine.metrics().current().standalone_tcp_connections(), 0);
        assert_eq!(engine.metrics().current().reserved_tcp_queue_bytes(), 0);
        server.join().expect("read-pressure fixture must join");
        engine.shutdown().expect("native Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn native_write_inactivity_fails_output_stalled_in_the_socket() {
        use std::net::TcpListener;
        use std::thread;

        let listener =
            TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind write-inactivity fixture");
        let address = listener.local_addr().expect("write-inactivity address");
        let (release_tx, release_rx) = mpsc::channel();
        let server = thread::spawn(move || {
            let (_socket, _) = listener.accept().expect("accept stalled writer TCP");
            release_rx.recv().expect("release stalled writer fixture");
        });

        let config = EngineConfig::manual();
        let backend = crate::backend::native_http_backend_with_write_limit(&config, 0)
            .expect("stalled-write backend must construct");
        let mut engine = Engine::with_backend(config, backend)
            .expect("manual standalone TCP Engine must construct");
        let pending = engine
            .tcp_connector()
            .submit(
                TcpConnectRequest::literal(address)
                    .send_queue_bytes(8)
                    .receive_queue_bytes(1)
                    .write_inactivity_timeout(Duration::from_millis(75))
                    .build()
                    .expect("write-inactivity request must build"),
            )
            .expect("stalled writer TCP must submit");
        let mut connection = match engine
            .drive_until(pending)
            .expect("stalled writer TCP must drive")
        {
            TcpConnectCompletion::Completed(connection) => connection,
            other => panic!("stalled writer TCP failed to connect: {other:?}"),
        };
        connection
            .try_send(vec![0xA5; 8])
            .expect("output must be accepted into the bounded window");
        assert_eq!(
            connection
                .try_finish()
                .expect("finish request must be accepted"),
            TcpFinishStatus::Pending
        );
        let started = Instant::now();
        let guard_deadline = Instant::now() + Duration::from_secs(2);
        let error = loop {
            let drive_deadline = (Instant::now() + Duration::from_millis(20)).min(guard_deadline);
            engine
                .drive(drive_deadline)
                .expect("manual stalled-write Engine must drive");
            match connection.try_finish() {
                Ok(TcpFinishStatus::Pending) => {
                    assert!(
                        Instant::now() < guard_deadline,
                        "write inactivity did not terminate the connection"
                    );
                }
                Ok(TcpFinishStatus::Finished) => {
                    panic!("stalled socket unexpectedly finished its write half")
                }
                Err(error) => break error,
            }
        };
        release_tx.send(()).expect("release stalled writer fixture");
        assert!(
            matches!(
                &error,
                TcpFinishError::Failed(error)
                    if error.kind() == ErrorKind::Timeout
                        && error.timeout_kind() == Some(TimeoutKind::Inactivity)
            ),
            "unexpected write-inactivity terminal: {error:?}"
        );
        assert!(
            started.elapsed() < Duration::from_millis(500),
            "write inactivity was not enforced promptly: {:?}",
            started.elapsed()
        );
        assert_eq!(engine.metrics().current().standalone_tcp_connections(), 0);
        assert_eq!(engine.metrics().current().reserved_tcp_queue_bytes(), 0);
        server.join().expect("write-inactivity fixture must join");
        engine.shutdown().expect("native Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn native_partial_write_progress_refreshes_inactivity_and_preserves_bytes() {
        use std::io::{Read, Write};
        use std::net::TcpListener;
        use std::thread;

        let listener =
            TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind partial-write fixture");
        let address = listener.local_addr().expect("partial-write address");
        let server = thread::spawn(move || {
            let (mut socket, _) = listener.accept().expect("accept partial writer TCP");
            let mut bytes = [0_u8; 8];
            socket
                .read_exact(&mut bytes)
                .expect("read every partial write");
            assert_eq!(&bytes, b"abcdefgh");
            socket.write_all(b"ok").expect("reply after partial writes");
        });

        let config = EngineConfig::manual();
        let backend = crate::backend::native_http_backend_with_write_limit(&config, 2)
            .expect("partial-write backend must construct");
        let mut engine = Engine::with_backend(config, backend)
            .expect("manual standalone TCP Engine must construct");
        let pending = engine
            .tcp_connector()
            .submit(
                TcpConnectRequest::literal(address)
                    .send_queue_bytes(8)
                    .receive_queue_bytes(2)
                    .write_inactivity_timeout(Duration::from_millis(200))
                    .build()
                    .expect("partial-write request must build"),
            )
            .expect("partial-write TCP must submit");
        let mut connection = match engine
            .drive_until(pending)
            .expect("partial-write TCP must drive")
        {
            TcpConnectCompletion::Completed(connection) => connection,
            other => panic!("partial-write TCP failed to connect: {other:?}"),
        };
        connection
            .try_send(b"abcdefgh".to_vec())
            .expect("partial output must enter the send window");
        assert_eq!(
            connection
                .try_finish()
                .expect("partial finish request must be accepted"),
            TcpFinishStatus::Pending
        );

        let guard_deadline = Instant::now() + Duration::from_secs(2);
        let mut pending_passes = 0;
        loop {
            engine
                .drive((Instant::now() + Duration::from_millis(20)).min(guard_deadline))
                .expect("partial-write Engine must drive");
            match connection
                .try_finish()
                .expect("partial progress must not time out")
            {
                TcpFinishStatus::Pending => {
                    pending_passes += 1;
                    assert!(
                        Instant::now() < guard_deadline,
                        "partial writes did not drain"
                    );
                    thread::sleep(Duration::from_millis(100));
                }
                TcpFinishStatus::Finished => break,
            }
        }
        assert!(
            pending_passes >= 3,
            "the two-byte test limit did not produce partial progress"
        );

        let mut reply = [0_u8; 2];
        loop {
            engine
                .drive((Instant::now() + Duration::from_millis(20)).min(guard_deadline))
                .expect("partial reply Engine must drive");
            match connection
                .try_read(&mut reply)
                .expect("partial writer reply must remain live")
            {
                TcpRead::Pending => assert!(
                    Instant::now() < guard_deadline,
                    "partial writer reply timed out"
                ),
                TcpRead::Data(2) => break,
                other => panic!("unexpected partial writer read: {other:?}"),
            }
        }
        assert_eq!(&reply, b"ok");
        drop(connection);
        server.join().expect("partial-write fixture must join");
        engine.shutdown().expect("native Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn finish_with_receives_write_inactivity_off_the_owner() {
        use std::net::TcpListener;
        use std::thread;

        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
            .expect("bind finish-callback inactivity fixture");
        let address = listener
            .local_addr()
            .expect("finish-callback inactivity address");
        let (release_tx, release_rx) = mpsc::channel();
        let server = thread::spawn(move || {
            let (_socket, _) = listener
                .accept()
                .expect("accept finish-callback inactivity TCP");
            release_rx
                .recv()
                .expect("release finish-callback inactivity fixture");
        });

        let config = EngineConfig::manual();
        let backend = crate::backend::native_http_backend_with_write_limit(&config, 0)
            .expect("stalled-write backend must construct");
        let mut engine = Engine::with_backend(config, backend)
            .expect("manual standalone TCP Engine must construct");
        let pending = engine
            .tcp_connector()
            .submit(
                TcpConnectRequest::literal(address)
                    .send_queue_bytes(4)
                    .receive_queue_bytes(1)
                    .write_inactivity_timeout(Duration::from_millis(60))
                    .build()
                    .expect("finish-callback request must build"),
            )
            .expect("finish-callback TCP must submit");
        let mut connection = match engine
            .drive_until(pending)
            .expect("finish-callback TCP must drive")
        {
            TcpConnectCompletion::Completed(connection) => connection,
            other => panic!("finish-callback TCP failed to connect: {other:?}"),
        };
        connection
            .try_send(b"full".to_vec())
            .expect("finish-callback output must queue");
        let (callback_tx, callback_rx) = mpsc::channel();
        connection
            .finish_with(move |result| {
                callback_tx
                    .send(result)
                    .expect("send finish-callback inactivity result");
            })
            .expect("finish callback must register");

        let guard_deadline = Instant::now() + Duration::from_secs(2);
        let result = loop {
            engine
                .drive((Instant::now() + Duration::from_millis(20)).min(guard_deadline))
                .expect("finish-callback Engine must drive");
            match callback_rx.try_recv() {
                Ok(result) => break result,
                Err(mpsc::TryRecvError::Empty) => assert!(
                    Instant::now() < guard_deadline,
                    "finish callback did not receive inactivity terminal"
                ),
                Err(error) => panic!("finish callback channel disconnected: {error}"),
            }
        };
        assert!(matches!(
            result,
            Err(TcpFinishError::Failed(error))
                if error.kind() == ErrorKind::Timeout
                    && error.timeout_kind() == Some(TimeoutKind::Inactivity)
        ));
        assert_eq!(engine.metrics().current().standalone_tcp_connections(), 0);
        assert_eq!(engine.metrics().current().reserved_tcp_queue_bytes(), 0);
        release_tx
            .send(())
            .expect("release finish-callback inactivity fixture");
        drop(connection);
        server
            .join()
            .expect("finish-callback inactivity fixture must join");
        engine.shutdown().expect("native Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn native_peer_reset_is_not_flattened_into_a_generic_transport_failure() {
        use std::net::TcpListener;
        use std::thread;

        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind reset fixture");
        let address = listener.local_addr().expect("reset fixture address");
        let (accepted_tx, accepted_rx) = mpsc::channel();
        let (reset_tx, reset_rx) = mpsc::channel();
        let server = thread::spawn(move || {
            let (socket, _) = listener.accept().expect("accept reset TCP");
            accepted_tx.send(()).expect("signal accepted reset TCP");
            reset_rx.recv().expect("release reset fixture");
            socket2::SockRef::from(&socket)
                .set_linger(Some(Duration::ZERO))
                .expect("configure abortive close");
            drop(socket);
        });

        let config = EngineConfig::spawned();
        let factory = crate::backend::native_http_factory(&config);
        let engine = Engine::with_spawned_factory(config, factory)
            .expect("native standalone TCP Engine must construct");
        let mut connection = engine
            .tcp_connector()
            .execute(
                TcpConnectRequest::literal(address)
                    .build()
                    .expect("reset request must build"),
            )
            .expect("reset TCP must connect");
        accepted_rx
            .recv_timeout(Duration::from_secs(1))
            .expect("server must accept reset TCP");
        reset_tx.send(()).expect("trigger abortive close");

        let cancel = connection.handle();
        let (result_tx, result_rx) = mpsc::channel();
        thread::spawn(move || {
            let mut byte = [0_u8; 1];
            result_tx
                .send(connection.read(&mut byte))
                .expect("send reset result");
        });
        let result = match result_rx.recv_timeout(Duration::from_secs(2)) {
            Ok(result) => result,
            Err(error) => {
                cancel.cancel().expect("guard cancellation must succeed");
                panic!("peer reset did not terminate the connection: {error}");
            }
        };
        assert!(matches!(result, Err(TcpStreamError::Reset)));
        server.join().expect("reset fixture must join");
        engine.shutdown().expect("native Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn native_tcp_limits_apply_after_capability_and_before_admission() {
        let config = EngineConfig::spawned().with_max_tcp_queue_bytes_per_connection(8);
        let factory = crate::backend::native_http_factory(&config);
        let engine = Engine::with_spawned_factory(config, factory)
            .expect("native standalone TCP Engine must construct");
        let request = TcpConnectRequest::literal(SocketAddr::from((Ipv4Addr::LOCALHOST, 9)))
            .send_queue_bytes(16)
            .build()
            .expect("over-ceiling request must build");
        let error = engine
            .tcp_connector()
            .submit(request)
            .expect_err("over-ceiling send window must fail before admission");
        assert_eq!(error.kind(), ErrorKind::Limit);
        assert_eq!(error.limit_kind(), Some(LimitKind::TcpQueueBytes));
        assert_eq!(engine.metrics().tcp_connects_accepted(), 0);
        engine.shutdown().expect("native Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn manual_literal_connect_uses_drive_and_cancel_before_drive_wins() {
        use std::io::{Read, Write};
        use std::net::TcpListener;
        use std::thread;

        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind manual fixture");
        let address = listener.local_addr().expect("manual fixture address");
        let server = thread::spawn(move || {
            let (mut socket, _) = listener.accept().expect("accept manual TCP");
            let mut byte = [0_u8; 1];
            socket.read_exact(&mut byte).expect("read manual byte");
            socket.write_all(&byte).expect("echo manual byte");
        });

        let config = EngineConfig::manual();
        let backend = crate::backend::native_http_backend(&config)
            .expect("manual native backend must construct");
        let mut engine = Engine::with_backend(config, backend)
            .expect("manual standalone TCP Engine must construct");
        let connector = engine.tcp_connector();
        let cancelled = connector
            .submit(
                TcpConnectRequest::literal(address)
                    .connect_timeout(Duration::from_secs(2))
                    .build()
                    .expect("cancel request must build"),
            )
            .expect("cancel request must submit");
        cancelled
            .handle()
            .cancel()
            .expect("cancel must be accepted");
        assert!(matches!(
            engine
                .drive_until(cancelled)
                .expect("cancelled waiter must drive"),
            TcpConnectCompletion::Cancelled
        ));

        let pending = connector
            .submit(
                TcpConnectRequest::literal(address)
                    .connect_timeout(Duration::from_secs(2))
                    .send_queue_bytes(8)
                    .receive_queue_bytes(8)
                    .build()
                    .expect("manual request must build"),
            )
            .expect("manual request must submit");
        let mut connection = match engine.drive_until(pending).expect("connect must drive") {
            TcpConnectCompletion::Completed(connection) => connection,
            other => panic!("manual connect failed: {other:?}"),
        };
        connection
            .try_send(vec![7])
            .expect("manual byte must queue");
        let deadline = Instant::now() + Duration::from_secs(2);
        let mut byte = [0_u8; 1];
        loop {
            engine.drive(deadline).expect("manual Engine must drive");
            match connection
                .try_read(&mut byte)
                .expect("manual read must remain live")
            {
                TcpRead::Pending => assert!(Instant::now() < deadline, "manual echo timed out"),
                TcpRead::Data(1) => break,
                other => panic!("unexpected manual read: {other:?}"),
            }
        }
        assert_eq!(byte, [7]);
        drop(connection);
        server.join().expect("manual fixture must join");
        engine.shutdown().expect("manual Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn tcp_wrong_engine_actions_fail_without_touching_the_owner() {
        let dns = crate::dns_wiring_tests::DualStackDns::with_handler(|_request| None);
        let mut owner = crate::testing::native_http_engine_manual_with_nameserver(
            EngineConfig::manual(),
            dns.address(),
        )
        .expect("owning manual Engine must construct");
        let mut foreign = crate::testing::native_http_engine_manual_with_nameserver(
            EngineConfig::manual(),
            dns.address(),
        )
        .expect("foreign manual Engine must construct");

        let first = owner
            .tcp_connector()
            .submit(
                TcpConnectRequest::hostname("wrong-engine-cancel.test", 9)
                    .build()
                    .expect("foreign-cancel request must build"),
            )
            .expect("foreign-cancel request must submit");
        let error = foreign
            .tcp_connector()
            .cancel(first.handle().id())
            .expect_err("foreign connector must reject the owner ID");
        assert_eq!(error.kind(), ErrorKind::WrongEngine);
        first
            .handle()
            .cancel()
            .expect("owning connector must still cancel");
        assert!(matches!(
            owner
                .drive_until(first)
                .expect("owning Engine must observe cancellation"),
            TcpConnectCompletion::Cancelled
        ));

        let second = owner
            .tcp_connector()
            .submit(
                TcpConnectRequest::hostname("wrong-engine-drive.test", 9)
                    .build()
                    .expect("foreign-drive request must build"),
            )
            .expect("foreign-drive request must submit");
        let owner_handle = second.handle();
        let error = foreign
            .drive_until(second)
            .expect_err("foreign Engine must reject the owner waiter");
        assert_eq!(error.kind(), ErrorKind::WrongEngine);
        owner_handle
            .cancel()
            .expect("foreign drive rejection must leave owner cancellation live");
        owner
            .drive(Instant::now() + Duration::from_millis(50))
            .expect("owner must drain cancelled commands");

        let metrics = owner.metrics();
        assert_eq!(metrics.tcp_connects_accepted(), 2);
        assert_eq!(metrics.tcp_connects_cancelled(), 2);
        assert_eq!(metrics.current().inflight_resolutions(), 0);
        assert_eq!(metrics.current().standalone_tcp_connections(), 0);
        assert_eq!(foreign.metrics().tcp_connects_accepted(), 0);
        assert_eq!(dns.queries(), 0);
        owner.shutdown().expect("owning Engine must stop");
        foreign.shutdown().expect("foreign Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn cancel_while_socket_attempt_is_owned_cannot_publish_or_leak() {
        use std::io::{Read, Write};
        use std::net::TcpListener;
        use std::thread;

        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
            .expect("bind socket-phase cancellation fixture");
        let address = listener
            .local_addr()
            .expect("socket-phase cancellation address");
        let (accepted_tx, accepted_rx) = mpsc::channel();
        let (closed_tx, closed_rx) = mpsc::channel();
        let cancelled_server = thread::spawn(move || {
            let (mut socket, _) = listener
                .accept()
                .expect("accept owned socket-phase attempt");
            accepted_tx
                .send(())
                .expect("signal accepted socket-phase attempt");
            let mut byte = [0_u8; 1];
            match socket.read(&mut byte) {
                Ok(0) | Err(_) => {}
                Ok(count) => panic!("cancelled socket sent {count} unexpected bytes"),
            }
            closed_tx.send(()).expect("signal cancelled socket closure");
        });
        let (entered_tx, entered_rx) = mpsc::channel();
        let (release_tx, release_rx) = mpsc::channel();
        let config = EngineConfig::manual();
        let backend = crate::backend::native_http_backend_with_standalone_socket_gate(
            &config, entered_tx, release_rx,
        )
        .expect("socket-gated backend must construct");
        let mut engine = Engine::with_backend(config, backend)
            .expect("socket-gated manual Engine must construct");
        let pending = engine
            .tcp_connector()
            .submit(
                TcpConnectRequest::literal(address)
                    .connect_timeout(Duration::from_secs(2))
                    .send_queue_bytes(4)
                    .receive_queue_bytes(4)
                    .build()
                    .expect("socket-phase request must build"),
            )
            .expect("socket-phase request must submit");
        let cancel = pending.handle();
        let driver = thread::spawn(move || {
            engine
                .drive(Instant::now() + Duration::from_millis(100))
                .expect("socket-gated Engine must drive");
            engine
        });
        entered_rx
            .recv_timeout(Duration::from_secs(1))
            .expect("real socket attempt must become owner-visible");
        accepted_rx
            .recv_timeout(Duration::from_secs(1))
            .expect("owned socket attempt must reach the peer");
        cancel
            .cancel()
            .expect("socket-phase cancellation must commit");
        assert!(matches!(pending.wait(), TcpConnectCompletion::Cancelled));
        release_tx.send(()).expect("release socket attempt owner");
        let mut engine = driver.join().expect("socket-gated driver must join");
        engine
            .drive(Instant::now() + Duration::from_millis(100))
            .expect("owner must tear down cancelled socket attempt");
        closed_rx
            .recv_timeout(Duration::from_secs(1))
            .expect("cancelled socket attempt must close at the peer");
        cancelled_server
            .join()
            .expect("cancelled socket server must join");
        assert_eq!(engine.metrics().current().standalone_tcp_connections(), 0);
        assert_eq!(engine.metrics().current().reserved_tcp_queue_bytes(), 0);

        let listener =
            TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind replacement socket fixture");
        let address = listener.local_addr().expect("replacement socket address");
        let server = thread::spawn(move || {
            let (mut socket, _) = listener.accept().expect("accept replacement socket");
            let mut byte = [0_u8; 1];
            socket.read_exact(&mut byte).expect("read replacement byte");
            assert_eq!(byte, [7]);
            socket.write_all(&byte).expect("echo replacement byte");
        });
        let replacement = engine
            .tcp_connector()
            .submit(
                TcpConnectRequest::literal(address)
                    .connect_timeout(Duration::from_secs(2))
                    .send_queue_bytes(4)
                    .receive_queue_bytes(4)
                    .build()
                    .expect("replacement request must build"),
            )
            .expect("replacement request must submit");
        let mut connection = match engine
            .drive_until(replacement)
            .expect("replacement connect must drive")
        {
            TcpConnectCompletion::Completed(connection) => connection,
            other => panic!("replacement connection failed: {other:?}"),
        };
        connection
            .try_send(vec![7])
            .expect("replacement byte must queue");
        let deadline = Instant::now() + Duration::from_secs(2);
        let mut byte = [0_u8; 1];
        loop {
            engine
                .drive(deadline)
                .expect("replacement Engine must drive");
            match connection
                .try_read(&mut byte)
                .expect("replacement read must stay live")
            {
                TcpRead::Pending => assert!(Instant::now() < deadline, "replacement timed out"),
                TcpRead::Data(1) => break,
                other => panic!("unexpected replacement read: {other:?}"),
            }
        }
        assert_eq!(byte, [7]);
        drop(connection);
        server.join().expect("replacement server must join");
        engine.shutdown().expect("socket-gated Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn live_cancel_releases_tcp_occupancy_and_queue_reservation() {
        use std::io::Read;
        use std::net::TcpListener;
        use std::thread;

        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind cancel fixture");
        let address = listener.local_addr().expect("cancel fixture address");
        let server = thread::spawn(move || {
            let (mut socket, _) = listener.accept().expect("accept cancelled TCP");
            let mut byte = [0_u8; 1];
            let _closed_or_reset = socket.read(&mut byte);
        });
        let config = EngineConfig::spawned().with_max_queued_bytes(16);
        let factory = crate::backend::native_http_factory(&config);
        let engine = Engine::with_spawned_factory(config, factory)
            .expect("native standalone TCP Engine must construct");
        let request = TcpConnectRequest::literal(address)
            .connect_timeout(Duration::from_secs(2))
            .send_queue_bytes(8)
            .receive_queue_bytes(8)
            .build()
            .expect("cancel request must build");
        let mut connection = engine
            .tcp_connector()
            .execute(request)
            .expect("literal connect must complete");
        let live = engine.metrics();
        assert_eq!(live.current().standalone_tcp_connections(), 1);
        assert_eq!(live.current().reserved_tcp_queue_bytes(), 16);
        connection
            .handle()
            .cancel()
            .expect("live cancel must succeed");
        let mut byte = [0_u8; 1];
        assert!(matches!(
            connection.try_read(&mut byte),
            Err(TcpStreamError::Cancelled)
        ));
        let released = engine.metrics();
        assert_eq!(released.current().standalone_tcp_connections(), 0);
        assert_eq!(released.current().reserved_tcp_queue_bytes(), 0);
        drop(connection);
        server.join().expect("cancel fixture must join");
        engine.shutdown().expect("native Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn cancel_all_terminates_live_finish_callback_and_allows_later_tcp() {
        use std::io::Read;
        use std::net::TcpListener;
        use std::thread;

        let listener =
            TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind cancel-all finish fixture");
        let address = listener.local_addr().expect("cancel-all finish address");
        let server = thread::spawn(move || {
            let (mut socket, _) = listener.accept().expect("accept cancel-all TCP");
            let mut bytes = [0_u8; 8];
            while let Ok(count) = socket.read(&mut bytes) {
                if count == 0 {
                    break;
                }
            }
        });

        let config = EngineConfig::manual();
        let backend = crate::backend::native_http_backend_with_write_limit(&config, 0)
            .expect("stalled-write backend must construct");
        let mut engine =
            Engine::with_backend(config, backend).expect("cancel-all manual Engine must construct");
        let pending = engine
            .tcp_connector()
            .submit(
                TcpConnectRequest::literal(address)
                    .send_queue_bytes(4)
                    .receive_queue_bytes(4)
                    .build()
                    .expect("cancel-all request must build"),
            )
            .expect("cancel-all request must submit");
        let mut connection = match engine
            .drive_until(pending)
            .expect("cancel-all connect must drive")
        {
            TcpConnectCompletion::Completed(connection) => connection,
            other => panic!("cancel-all connect failed: {other:?}"),
        };
        connection
            .try_send(b"full".to_vec())
            .expect("cancel-all output must queue");
        let (callback_tx, callback_rx) = mpsc::channel();
        connection
            .finish_with(move |result| {
                callback_tx
                    .send(result)
                    .expect("send cancel-all finish terminal");
            })
            .expect("cancel-all finish callback must register");

        engine.cancel_all();
        let mut byte = [0_u8; 1];
        assert!(matches!(
            connection.try_read(&mut byte),
            Err(TcpStreamError::Cancelled)
        ));
        engine
            .drive(Instant::now() + Duration::from_millis(100))
            .expect("cancel-all Engine must drain owner and callback work");
        assert!(matches!(
            callback_rx
                .recv_timeout(Duration::from_secs(1))
                .expect("cancel-all finish callback must run"),
            Err(TcpFinishError::Cancelled)
        ));
        assert_eq!(engine.metrics().current().standalone_tcp_connections(), 0);
        assert_eq!(engine.metrics().current().reserved_tcp_queue_bytes(), 0);
        drop(connection);
        server.join().expect("cancel-all server must join");

        let listener =
            TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind post-cancel-all fixture");
        let address = listener.local_addr().expect("post-cancel-all address");
        let server = thread::spawn(move || {
            let (_socket, _) = listener.accept().expect("accept post-cancel-all TCP");
        });
        let pending = engine
            .tcp_connector()
            .submit(
                TcpConnectRequest::literal(address)
                    .build()
                    .expect("post-cancel-all request must build"),
            )
            .expect("cancel_all must not close later admission");
        let replacement = match engine
            .drive_until(pending)
            .expect("post-cancel-all connect must drive")
        {
            TcpConnectCompletion::Completed(connection) => connection,
            other => panic!("post-cancel-all connect failed: {other:?}"),
        };
        drop(replacement);
        server.join().expect("post-cancel-all server must join");
        engine.shutdown().expect("cancel-all Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn live_cancel_and_split_half_drops_release_once_under_race() {
        use std::io::Read;
        use std::net::TcpListener;
        use std::sync::Barrier;
        use std::thread;

        const REPEATS: usize = 25;
        let listener =
            TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind cancel/drop race fixture");
        let address = listener.local_addr().expect("cancel/drop race address");
        let server = thread::spawn(move || {
            for _ in 0..REPEATS {
                let (mut socket, _) = listener.accept().expect("accept raced TCP");
                let mut byte = [0_u8; 1];
                let _closed_or_reset = socket.read(&mut byte);
            }
        });

        let config = EngineConfig::spawned();
        let factory = crate::backend::native_http_factory(&config);
        let engine = Engine::with_spawned_factory(config, factory)
            .expect("native standalone TCP Engine must construct");
        for _ in 0..REPEATS {
            let connection = engine
                .tcp_connector()
                .execute(
                    TcpConnectRequest::literal(address)
                        .send_queue_bytes(4)
                        .receive_queue_bytes(4)
                        .build()
                        .expect("raced TCP request must build"),
                )
                .expect("raced TCP must connect");
            let handle = connection.handle();
            let (reader, writer) = connection.split();
            let barrier = StdArc::new(Barrier::new(4));
            let reader_barrier = StdArc::clone(&barrier);
            let reader_drop = thread::spawn(move || {
                reader_barrier.wait();
                drop(reader);
            });
            let writer_barrier = StdArc::clone(&barrier);
            let writer_drop = thread::spawn(move || {
                writer_barrier.wait();
                drop(writer);
            });
            let cancel_barrier = StdArc::clone(&barrier);
            let cancel = thread::spawn(move || {
                cancel_barrier.wait();
                handle.cancel().expect("raced cancel must be idempotent");
            });
            barrier.wait();
            reader_drop.join().expect("reader drop must join");
            writer_drop.join().expect("writer drop must join");
            cancel.join().expect("cancel must join");
            assert_eq!(
                engine.metrics().current().standalone_tcp_connections(),
                0,
                "raced release must happen exactly once"
            );
            assert_eq!(engine.metrics().current().reserved_tcp_queue_bytes(), 0);
        }
        server.join().expect("cancel/drop race fixture must join");
        engine.shutdown().expect("native Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn standalone_occupancy_covers_pending_and_live_then_releases_on_drop() {
        use std::net::TcpListener;
        use std::thread;

        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind occupancy fixture");
        let address = listener.local_addr().expect("occupancy fixture address");
        let server = thread::spawn(move || {
            let (first, _) = listener.accept().expect("accept first TCP session");
            drop(first);
            let (second, _) = listener.accept().expect("accept replacement TCP session");
            drop(second);
        });
        let config = EngineConfig::spawned()
            .with_max_standalone_tcp_connections(NonZeroUsize::new(1).expect("nonzero limit"));
        let factory = crate::backend::native_http_factory(&config);
        let engine = Engine::with_spawned_factory(config, factory)
            .expect("native standalone TCP Engine must construct");
        let connector = engine.tcp_connector();
        let request = || {
            TcpConnectRequest::literal(address)
                .connect_timeout(Duration::from_secs(2))
                .build()
                .expect("occupancy request must build")
        };

        let first = connector
            .execute(request())
            .expect("first TCP session must connect");
        let rejected = connector
            .submit(request())
            .expect_err("a live session must retain the sole occupancy permit");
        assert_eq!(rejected.kind(), ErrorKind::QueueFull);
        drop(first);
        assert_eq!(engine.metrics().current().standalone_tcp_connections(), 0);

        let replacement = connector
            .execute(request())
            .expect("dropping the first session must release occupancy");
        drop(replacement);
        server.join().expect("occupancy fixture must join");
        engine.shutdown().expect("native Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn shutdown_aborts_a_live_native_tcp_session_and_joins() {
        use std::io::Read;
        use std::net::TcpListener;
        use std::thread;

        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind shutdown fixture");
        let address = listener.local_addr().expect("shutdown fixture address");
        let server = thread::spawn(move || {
            let (mut socket, _) = listener.accept().expect("accept shutdown TCP");
            let mut byte = [0_u8; 1];
            let _closed_or_reset = socket.read(&mut byte);
        });
        let config = EngineConfig::spawned();
        let factory = crate::backend::native_http_factory(&config);
        let engine = Engine::with_spawned_factory(config, factory)
            .expect("native standalone TCP Engine must construct");
        let mut connection = engine
            .tcp_connector()
            .execute(
                TcpConnectRequest::literal(address)
                    .connect_timeout(Duration::from_secs(2))
                    .build()
                    .expect("shutdown request must build"),
            )
            .expect("shutdown TCP session must connect");

        engine.shutdown().expect("Engine with live TCP must join");
        let mut byte = [0_u8; 1];
        assert!(matches!(
            connection.try_read(&mut byte),
            Err(TcpStreamError::Failed(error)) if error.kind() == ErrorKind::EngineStopped
        ));
        drop(connection);
        server.join().expect("shutdown fixture must join");
    }

    #[cfg(feature = "native")]
    #[test]
    fn shutdown_delivers_engine_stopped_to_real_finish_callback_and_joins() {
        use std::io::Read;
        use std::net::TcpListener;
        use std::thread;

        let listener =
            TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind shutdown-finish fixture");
        let address = listener.local_addr().expect("shutdown-finish address");
        let server = thread::spawn(move || {
            let (mut socket, _) = listener.accept().expect("accept shutdown-finish TCP");
            let mut bytes = [0_u8; 8];
            while let Ok(count) = socket.read(&mut bytes) {
                if count == 0 {
                    break;
                }
            }
        });

        let config = EngineConfig::manual();
        let backend = crate::backend::native_http_backend_with_write_limit(&config, 0)
            .expect("shutdown-finish stalled backend must construct");
        let mut engine = Engine::with_backend(config, backend)
            .expect("shutdown-finish manual Engine must construct");
        let shared = engine.shared_for_testing();
        let pending = engine
            .tcp_connector()
            .submit(
                TcpConnectRequest::literal(address)
                    .send_queue_bytes(4)
                    .receive_queue_bytes(4)
                    .build()
                    .expect("shutdown-finish request must build"),
            )
            .expect("shutdown-finish request must submit");
        let mut connection = match engine
            .drive_until(pending)
            .expect("shutdown-finish connect must drive")
        {
            TcpConnectCompletion::Completed(connection) => connection,
            other => panic!("shutdown-finish connect failed: {other:?}"),
        };
        connection
            .try_send(b"full".to_vec())
            .expect("shutdown-finish output must queue");
        let (callback_tx, callback_rx) = mpsc::channel();
        connection
            .finish_with(move |result| {
                callback_tx
                    .send(result)
                    .expect("send shutdown-finish terminal");
            })
            .expect("shutdown-finish callback must register");

        engine
            .shutdown()
            .expect("Engine with a real finish callback must join");
        assert!(matches!(
            callback_rx
                .recv_timeout(Duration::from_secs(1))
                .expect("shutdown-finish callback must run"),
            Err(TcpFinishError::EngineStopped)
        ));
        let mut byte = [0_u8; 1];
        assert!(matches!(
            connection.try_read(&mut byte),
            Err(TcpStreamError::Failed(error)) if error.kind() == ErrorKind::EngineStopped
        ));
        let metrics = shared.metrics_snapshot();
        assert_eq!(metrics.current().standalone_tcp_connections(), 0);
        assert_eq!(metrics.current().reserved_tcp_queue_bytes(), 0);
        drop(connection);
        server.join().expect("shutdown-finish server must join");
    }

    #[cfg(feature = "native")]
    #[test]
    fn spawned_start_delivers_one_unique_connection_off_the_reactor() {
        use std::net::TcpListener;
        use std::thread;

        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind callback fixture");
        let address = listener.local_addr().expect("callback fixture address");
        let server = thread::spawn(move || {
            let (_socket, _) = listener.accept().expect("accept callback TCP");
        });
        let config = EngineConfig::spawned();
        let factory = crate::backend::native_http_factory(&config);
        let engine = Engine::with_spawned_factory(config, factory)
            .expect("native standalone TCP Engine must construct");
        let (sent, received) = mpsc::channel();
        let handle = engine
            .tcp_connector()
            .start(
                TcpConnectRequest::literal(address)
                    .connect_timeout(Duration::from_secs(2))
                    .build()
                    .expect("callback request must build"),
                move |completion| {
                    sent.send(completion).expect("send callback completion");
                },
            )
            .expect("callback connect must start");
        let connection = match received
            .recv_timeout(Duration::from_secs(2))
            .expect("callback must arrive")
        {
            TcpConnectCompletion::Completed(connection) => connection,
            other => panic!("callback connect failed: {other:?}"),
        };
        assert_eq!(connection.handle().id(), handle.id());
        drop(connection);
        server.join().expect("callback fixture must join");
        engine.shutdown().expect("native Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn native_finish_drains_then_half_closes_without_losing_the_reader() {
        use std::io::{Read, Write};
        use std::net::TcpListener;
        use std::thread;

        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind finish fixture");
        let address = listener.local_addr().expect("finish fixture address");
        let server = thread::spawn(move || {
            let (mut socket, _) = listener.accept().expect("accept finishing TCP");
            let mut request = Vec::new();
            socket
                .read_to_end(&mut request)
                .expect("observe client write FIN");
            assert_eq!(request, b"finished");
            socket.write_all(b"yes").expect("reply after client FIN");
        });
        let config = EngineConfig::spawned();
        let factory = crate::backend::native_http_factory(&config);
        let engine = Engine::with_spawned_factory(config, factory)
            .expect("native standalone TCP Engine must construct");
        let mut connection = engine
            .tcp_connector()
            .execute(
                TcpConnectRequest::literal(address)
                    .connect_timeout(Duration::from_secs(2))
                    .build()
                    .expect("finish request must build"),
            )
            .expect("finish connect must complete");
        connection
            .send(b"finished".to_vec())
            .expect("finish payload must queue");
        connection.finish().expect("write half must finish");
        let mut response = [0_u8; 3];
        assert_eq!(connection.read(&mut response).expect("read reply"), Some(3));
        assert_eq!(&response, b"yes");
        assert_eq!(connection.read(&mut response).expect("read EOF"), None);
        drop(connection);
        server.join().expect("finish fixture must join");
        engine.shutdown().expect("native Engine must stop");
    }

    #[cfg(feature = "native")]
    #[test]
    fn http_stream_and_tcp_share_the_parent_queue_budget() {
        use std::io::Read;
        use std::net::TcpListener;
        use std::thread;

        let http_listener =
            TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind HTTP budget fixture");
        let http_address = http_listener.local_addr().expect("HTTP fixture address");
        let (http_seen_tx, http_seen_rx) = mpsc::channel();
        let (release_tx, release_rx) = mpsc::channel();
        let http_server = thread::spawn(move || {
            let (mut socket, _) = http_listener.accept().expect("accept streaming HTTP");
            let mut request = [0_u8; 512];
            let _ = socket.read(&mut request).expect("read HTTP request");
            http_seen_tx.send(()).expect("signal HTTP admission");
            release_rx.recv().expect("release HTTP fixture");
        });
        let tcp_listener =
            TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind TCP budget fixture");
        let tcp_address = tcp_listener.local_addr().expect("TCP fixture address");
        let tcp_server = thread::spawn(move || {
            let (_socket, _) = tcp_listener.accept().expect("accept budget TCP");
        });

        let config = EngineConfig::spawned()
            .with_max_stream_queue_bytes_per_request(8)
            .with_max_stream_queued_bytes(16)
            .with_max_tcp_queue_bytes_per_connection(8)
            .with_max_queued_bytes(16);
        let factory = crate::backend::native_http_factory(&config);
        let engine = Engine::with_spawned_factory(config, factory)
            .expect("shared-budget Engine must construct");
        let reader = engine
            .client()
            .submit_stream(
                crate::StreamRequest::get(format!("http://{http_address}/"))
                    .build()
                    .expect("stream request must build"),
            )
            .expect("HTTP stream must reserve eight bytes");
        http_seen_rx
            .recv_timeout(Duration::from_secs(2))
            .expect("HTTP stream must reach fixture");
        let connection = engine
            .tcp_connector()
            .execute(
                TcpConnectRequest::literal(tcp_address)
                    .send_queue_bytes(4)
                    .receive_queue_bytes(4)
                    .build()
                    .expect("TCP request must build"),
            )
            .expect("TCP must consume the remaining eight bytes");
        let rejected = engine
            .tcp_connector()
            .submit(
                TcpConnectRequest::literal(tcp_address)
                    .send_queue_bytes(4)
                    .receive_queue_bytes(4)
                    .build()
                    .expect("second TCP request must build"),
            )
            .expect_err("shared parent budget must reject another reservation");
        assert_eq!(rejected.kind(), ErrorKind::Limit);
        assert_eq!(engine.metrics().tcp_connects_accepted(), 1);

        drop(connection);
        drop(reader);
        release_tx.send(()).expect("release HTTP fixture");
        tcp_server.join().expect("TCP budget fixture must join");
        http_server.join().expect("HTTP budget fixture must join");
        engine.shutdown().expect("shared-budget Engine must stop");
    }

    struct Live {
        occupancy: StdArc<std::sync::atomic::AtomicUsize>,
        reserved: StdArc<std::sync::atomic::AtomicUsize>,
        engine: Engine,
        connection: TcpConnection,
        /// Last field so the fake owner outlives the public handle.
        /// Struct fields drop in declaration order.
        owner: super::io::TcpIoOwner,
    }

    fn live_tcp(mode: crate::RunMode, send: usize, recv: usize) -> Live {
        let config = match mode {
            crate::RunMode::Spawned => EngineConfig::spawned(),
            crate::RunMode::Manual => EngineConfig::manual(),
        };
        live_tcp_cfg(config, send, recv)
    }

    fn live_tcp_cfg(config: EngineConfig, send: usize, recv: usize) -> Live {
        let mode = config.run_mode();
        let engine = Engine::with_backend(config, crate::backend::scaffold())
            .expect("scaffold Engine must construct");
        let attached = attach_live(&engine, mode, send, recv, 1);
        Live {
            occupancy: attached.occupancy,
            reserved: attached.reserved,
            engine,
            connection: attached.connection,
            owner: attached.owner,
        }
    }

    struct Attached {
        occupancy: StdArc<std::sync::atomic::AtomicUsize>,
        reserved: StdArc<std::sync::atomic::AtomicUsize>,
        connection: TcpConnection,
        owner: super::io::TcpIoOwner,
    }

    fn attach_live(
        engine: &Engine,
        mode: crate::RunMode,
        send: usize,
        recv: usize,
        sequence: u64,
    ) -> Attached {
        use super::io::{TcpIoConfig, TcpIoShared};
        let connector = engine.tcp_connector();
        let id = RequestId {
            engine: connector.shared.id,
            sequence,
        };
        let handle = TcpConnectionHandle::new(connector.clone(), id);
        let occupancy = StdArc::new(std::sync::atomic::AtomicUsize::new(1));
        let reserved = StdArc::new(std::sync::atomic::AtomicUsize::new(send + recv));
        let occ = StdArc::clone(&occupancy);
        let res = StdArc::clone(&reserved);
        let (io, owner) = TcpIoShared::pair(TcpIoConfig {
            engine_id: id.engine,
            request_id: id,
            shared: StdArc::clone(&connector.shared),
            run_mode: mode,
            send_window: send,
            receive_window: recv,
            local: SocketAddr::from((Ipv4Addr::LOCALHOST, 1)),
            peer: SocketAddr::from((Ipv4Addr::LOCALHOST, 2)),
            engine_waker: Some(StdArc::new(|| {})),
            on_release: Box::new(move || {
                occ.store(0, AtomicOrdering::SeqCst);
                res.store(0, AtomicOrdering::SeqCst);
            }),
        });
        Attached {
            occupancy,
            reserved,
            connection: TcpConnection::from_shared(io, handle),
            owner,
        }
    }

    fn recv_finish(rx: &mpsc::Receiver<Result<(), TcpFinishError>>) -> Result<(), TcpFinishError> {
        rx.recv_timeout(Duration::from_secs(2))
            .expect("finish callback must run")
    }

    #[test]
    fn try_send_preserves_refused_bytes_and_distinguishes_window_errors() {
        let mut live = live_tcp(crate::RunMode::Manual, 4, 4);
        let too_big = live
            .connection
            .try_send(b"hello".to_vec())
            .expect_err("oversize chunk cannot fit the window");
        assert_eq!(too_big.kind(), TcpSendErrorKind::ChunkTooLarge);
        assert_eq!(too_big.into_remaining(), b"hello");

        live.connection
            .try_send(b"abcd".to_vec())
            .expect("full window can be queued");
        let blocked = live
            .connection
            .try_send(b"x".to_vec())
            .expect_err("occupied window refuses another byte");
        assert_eq!(blocked.kind(), TcpSendErrorKind::WouldBlock);
        assert_eq!(blocked.into_remaining(), b"x");
        live.engine.shutdown().expect("Engine must stop");
    }

    #[test]
    fn staging_into_the_pump_does_not_release_send_window_capacity() {
        let mut live = live_tcp(crate::RunMode::Manual, 8, 4);
        live.connection
            .try_send(b"abcd".to_vec())
            .expect("first chunk fits");
        let staged = live
            .owner
            .take_outbound()
            .expect("owner takes queued bytes");
        assert_eq!(staged, b"abcd");
        assert_eq!(live.owner.outbound_bytes(), 0);
        assert_eq!(live.owner.pump_bytes(), 4);
        assert_eq!(live.owner.send_occupancy(), 4);

        live.connection
            .try_send(b"efgh".to_vec())
            .expect("remaining window still accounts for pump bytes");
        let blocked = live
            .connection
            .try_send(b"x".to_vec())
            .expect_err("pump occupancy still consumes the window");
        assert_eq!(blocked.kind(), TcpSendErrorKind::WouldBlock);

        live.owner.write_progress(4);
        live.connection
            .try_send(b"ijkl".to_vec())
            .expect("socket progress frees window capacity");
        live.engine.shutdown().expect("Engine must stop");
    }

    #[test]
    fn try_finish_is_request_once_and_later_send_is_closed() {
        let mut live = live_tcp(crate::RunMode::Manual, 8, 4);
        live.connection
            .try_send(b"ab".to_vec())
            .expect("bytes queue");
        assert_eq!(
            live.connection.try_finish().expect("finish request"),
            TcpFinishStatus::Pending
        );
        assert!(live.owner.finish_requested());
        assert_eq!(
            live.connection.try_finish().expect("later poll"),
            TcpFinishStatus::Pending
        );
        let closed = live
            .connection
            .try_send(b"cd".to_vec())
            .expect_err("send after finish request is closed");
        assert_eq!(closed.kind(), TcpSendErrorKind::Closed);
        assert_eq!(closed.into_remaining(), b"cd");

        let drained = live.owner.take_outbound().expect("drain accepted output");
        assert_eq!(drained, b"ab");
        live.owner.write_progress(2);
        live.owner
            .complete_write_shutdown()
            .expect("owner completes half-close");
        assert_eq!(
            live.connection.try_finish().expect("completed finish"),
            TcpFinishStatus::Finished
        );
        live.engine.shutdown().expect("Engine must stop");
    }

    #[test]
    fn writer_drop_before_finish_request_aborts_and_releases_once() {
        let mut live = live_tcp(crate::RunMode::Manual, 4, 4);
        live.connection.try_send(b"ab".to_vec()).expect("queued");
        drop(live.connection);
        assert_eq!(live.occupancy.load(AtomicOrdering::SeqCst), 0);
        assert_eq!(live.reserved.load(AtomicOrdering::SeqCst), 0);
        live.engine.shutdown().expect("Engine must stop");
    }

    #[test]
    fn writer_drop_after_pending_finish_does_not_revoke_the_request() {
        let mut live = live_tcp(crate::RunMode::Manual, 8, 4);
        live.connection.try_send(b"ab".to_vec()).expect("queued");
        let (mut reader, mut writer) = live.connection.split();
        assert_eq!(
            writer.try_finish().expect("request finish"),
            TcpFinishStatus::Pending
        );
        drop(writer);
        assert_eq!(live.occupancy.load(AtomicOrdering::SeqCst), 1);

        let drained = live.owner.take_outbound().expect("engine still drains");
        assert_eq!(drained, b"ab");
        live.owner.write_progress(2);
        live.owner
            .complete_write_shutdown()
            .expect("half-close completes after writer drop");
        live.owner.peer_closed();
        assert_eq!(reader.try_read(&mut [0; 8]).expect("eof"), TcpRead::Eof);
        assert_eq!(live.occupancy.load(AtomicOrdering::SeqCst), 0);
        live.engine.shutdown().expect("Engine must stop");
    }

    #[test]
    fn unsplit_drop_while_finishing_without_eof_still_aborts() {
        let mut live = live_tcp(crate::RunMode::Manual, 8, 4);
        live.connection.try_send(b"ab".to_vec()).expect("queued");
        live.connection
            .try_finish()
            .expect("write finish requested");
        drop(live.connection);
        assert_eq!(live.occupancy.load(AtomicOrdering::SeqCst), 0);
        live.engine.shutdown().expect("Engine must stop");
    }

    #[test]
    fn reader_drains_retained_bytes_before_eof_then_drop_is_harmless() {
        let mut live = live_tcp(crate::RunMode::Manual, 4, 8);
        live.owner
            .push_inbound(b"hi".to_vec())
            .expect("inbound fits");
        live.owner.peer_closed();
        let mut buf = [0; 8];
        assert_eq!(
            live.connection.try_read(&mut buf).expect("data"),
            TcpRead::Data(2)
        );
        assert_eq!(&buf[..2], b"hi");
        assert_eq!(
            live.connection.try_read(&mut buf).expect("eof"),
            TcpRead::Eof
        );
        live.connection
            .try_finish()
            .expect("finish empty write side");
        live.owner
            .complete_write_shutdown()
            .expect("empty write shutdown");
        assert_eq!(live.occupancy.load(AtomicOrdering::SeqCst), 0);
        drop(live.connection);
        assert_eq!(live.occupancy.load(AtomicOrdering::SeqCst), 0);
        live.engine.shutdown().expect("Engine must stop");
    }

    #[test]
    fn blocking_finish_and_send_reject_manual_mode_without_consuming_bytes() {
        let mut live = live_tcp(crate::RunMode::Manual, 8, 4);
        let error = live
            .connection
            .send(b"ab".to_vec())
            .expect_err("manual send is WrongMode");
        assert_eq!(error.kind(), TcpSendErrorKind::WrongMode);
        assert_eq!(error.into_remaining(), b"ab");
        match live.connection.finish() {
            Err(TcpFinishError::WrongMode) => {}
            other => panic!("expected WrongMode, got {other:?}"),
        }
        live.engine.shutdown().expect("Engine must stop");
    }

    #[test]
    fn spawned_blocking_finish_waits_for_owner_shutdown() {
        let mut live = live_tcp(crate::RunMode::Spawned, 8, 4);
        live.connection.try_send(b"xy".to_vec()).expect("queued");
        let (mut reader, mut writer) = live.connection.split();
        let join = std::thread::spawn(move || writer.finish());
        let drained = loop {
            if let Some(chunk) = live.owner.take_outbound() {
                break chunk;
            }
            std::thread::yield_now();
        };
        assert_eq!(drained, b"xy");
        live.owner.write_progress(2);
        while !live.owner.finish_requested() {
            std::thread::yield_now();
        }
        live.owner
            .complete_write_shutdown()
            .expect("owner completes finish");
        join.join()
            .expect("finish thread")
            .expect("spawned finish completes");
        live.owner.peer_closed();
        assert_eq!(
            reader.try_read(&mut [0; 4]).expect("eof after peer FIN"),
            TcpRead::Eof
        );
        live.engine.shutdown().expect("Engine must stop");
    }

    #[test]
    fn reset_and_failure_release_once_and_read_allowance_tracks_unread_bytes() {
        let mut live = live_tcp(crate::RunMode::Manual, 4, 8);
        assert_eq!(live.owner.read_allowance(), 8);
        live.owner
            .push_inbound(b"xy".to_vec())
            .expect("inbound fits");
        assert_eq!(live.owner.read_allowance(), 6);
        live.owner.reset();
        let reset = live
            .connection
            .try_send(b"ab".to_vec())
            .expect_err("reset closes send");
        assert_eq!(reset.kind(), TcpSendErrorKind::Reset);
        assert!(live.owner.session_released());
        assert_eq!(live.occupancy.load(AtomicOrdering::SeqCst), 0);

        let mut failed = live_tcp(crate::RunMode::Manual, 4, 4);
        failed
            .owner
            .fail(Error::new(ErrorKind::Internal, "injected owner failure"));
        match failed.connection.try_read(&mut [0; 1]) {
            Err(TcpStreamError::Failed(error)) => {
                assert_eq!(error.kind(), ErrorKind::Internal);
            }
            other => panic!("expected failed read, got {other:?}"),
        }
        assert!(failed.owner.session_released());
        failed.engine.shutdown().expect("Engine must stop");
        live.engine.shutdown().expect("Engine must stop");
    }

    #[test]
    fn finish_with_queue_full_does_not_request_finish() {
        let one = NonZeroUsize::MIN;
        let engine = Engine::with_backend(
            EngineConfig::spawned().with_callback_queue_capacity(one),
            crate::backend::scaffold(),
        )
        .expect("scaffold Engine must construct");
        let mut first = attach_live(&engine, crate::RunMode::Spawned, 8, 4, 1);
        let mut second = attach_live(&engine, crate::RunMode::Spawned, 8, 4, 2);
        let (hold_tx, hold_rx) = mpsc::channel::<()>();
        first
            .connection
            .finish_with(move |_| {
                let _ = hold_rx.recv();
            })
            .expect("first finish callback reserves capacity");
        second
            .connection
            .try_send(b"ab".to_vec())
            .expect("second connection can still send");
        let error = second
            .connection
            .finish_with(|_| panic!("rejected callback must not run"))
            .expect_err("callback capacity is exhausted");
        assert_eq!(error.kind(), ErrorKind::QueueFull);
        second
            .connection
            .try_send(b"cd".to_vec())
            .expect("QueueFull must not close the write half");
        drop(hold_tx);
        first
            .owner
            .complete_write_shutdown()
            .expect("first finish can complete");
        engine.shutdown().expect("Engine must stop");
        drop(second);
        drop(first);
    }

    #[test]
    fn finish_with_queue_full_after_try_finish_does_not_revoke() {
        let one = NonZeroUsize::MIN;
        let engine = Engine::with_backend(
            EngineConfig::spawned().with_callback_queue_capacity(one),
            crate::backend::scaffold(),
        )
        .expect("scaffold Engine must construct");
        let mut first = attach_live(&engine, crate::RunMode::Spawned, 4, 4, 1);
        let mut second = attach_live(&engine, crate::RunMode::Spawned, 4, 4, 2);
        let (hold_tx, hold_rx) = mpsc::channel::<()>();
        first
            .connection
            .finish_with(move |_| {
                let _ = hold_rx.recv();
            })
            .expect("first finish callback reserves capacity");
        second
            .connection
            .try_finish()
            .expect("second write finish requested without a callback");
        let error = second
            .connection
            .finish_with(|_| panic!("rejected callback must not run"))
            .expect_err("callback capacity is exhausted");
        assert_eq!(error.kind(), ErrorKind::QueueFull);
        let closed = second
            .connection
            .try_send(b"x".to_vec())
            .expect_err("existing finish request stays");
        assert_eq!(closed.kind(), TcpSendErrorKind::Closed);
        drop(hold_tx);
        first
            .owner
            .complete_write_shutdown()
            .expect("first finish can complete");
        second
            .owner
            .complete_write_shutdown()
            .expect("second finish request was not revoked");
        engine.shutdown().expect("Engine must stop");
        drop(second);
        drop(first);
    }

    #[test]
    fn finish_with_late_registration_after_finished() {
        let mut live = live_tcp(crate::RunMode::Spawned, 4, 4);
        live.connection
            .try_finish()
            .expect("request empty write finish");
        live.owner
            .complete_write_shutdown()
            .expect("owner completes finish");
        let (tx, rx) = mpsc::channel();
        live.connection
            .finish_with(move |result| {
                let _ = tx.send(result);
            })
            .expect("late registration after Finished");
        recv_finish(&rx).expect("late callback observes success");
        live.engine.shutdown().expect("Engine must stop");
    }

    #[test]
    fn finish_with_rejects_a_second_callback() {
        let mut live = live_tcp(crate::RunMode::Spawned, 4, 4);
        let (tx, rx) = mpsc::channel();
        live.connection
            .finish_with(move |result| {
                let _ = tx.send(result);
            })
            .expect("first callback");
        let (_reader, mut writer) = live.connection.split();
        let error = writer
            .finish_with(|_| panic!("second callback must not run"))
            .expect_err("only one finish callback even after split");
        assert_eq!(error.kind(), ErrorKind::InvalidRequest);
        live.owner
            .complete_write_shutdown()
            .expect("owner completes finish");
        recv_finish(&rx).expect("first callback still runs");
        live.engine.shutdown().expect("Engine must stop");
    }

    #[test]
    fn review_p2_tcp_finish_callback_registration_is_single_use_after_delivery() {
        let mut live = live_tcp(crate::RunMode::Spawned, 4, 4);
        let (first, delivered) = mpsc::channel();
        live.connection
            .finish_with(move |result| {
                first.send(result).expect("first callback delivery");
            })
            .expect("first finish callback must register");
        live.owner
            .complete_write_shutdown()
            .expect("owner completes half-close");
        recv_finish(&delivered).expect("first callback observes success");

        let unexpected = StdArc::new(std::sync::atomic::AtomicUsize::new(0));
        let observed = StdArc::clone(&unexpected);
        let second = live.connection.finish_with(move |_| {
            observed.fetch_add(1, AtomicOrdering::SeqCst);
        });
        live.engine
            .shutdown()
            .expect("finish regression Engine and callbacks must join");
        assert_eq!(
            second
                .expect_err("completion must not reopen finish callback registration")
                .kind(),
            ErrorKind::InvalidRequest
        );
        assert_eq!(
            unexpected.load(AtomicOrdering::SeqCst),
            0,
            "a rejected second callback never runs"
        );
    }

    #[test]
    fn finish_with_survives_writer_drop_after_registration() {
        let mut live = live_tcp(crate::RunMode::Spawned, 8, 4);
        live.connection.try_send(b"ab".to_vec()).expect("queued");
        let (mut reader, mut writer) = live.connection.split();
        let (tx, rx) = mpsc::channel();
        writer
            .finish_with(move |result| {
                let _ = tx.send(result);
            })
            .expect("register finish callback");
        drop(writer);
        assert_eq!(live.occupancy.load(AtomicOrdering::SeqCst), 1);
        let drained = live.owner.take_outbound().expect("engine still drains");
        assert_eq!(drained, b"ab");
        live.owner.write_progress(2);
        live.owner
            .complete_write_shutdown()
            .expect("half-close completes after writer drop");
        recv_finish(&rx).expect("callback still runs");
        live.owner.peer_closed();
        assert_eq!(reader.try_read(&mut [0; 8]).expect("eof"), TcpRead::Eof);
        live.engine.shutdown().expect("Engine must stop");
    }

    #[test]
    fn finish_with_unsplit_drop_delivers_cancelled() {
        let mut live = live_tcp(crate::RunMode::Spawned, 4, 4);
        let (tx, rx) = mpsc::channel();
        live.connection
            .finish_with(move |result| {
                let _ = tx.send(result);
            })
            .expect("register finish callback");
        drop(live.connection);
        match recv_finish(&rx) {
            Err(TcpFinishError::Cancelled) => {}
            other => panic!("expected Cancelled, got {other:?}"),
        }
        live.engine.shutdown().expect("Engine must stop");
    }

    #[test]
    fn finish_with_manual_delivery_waits_for_drive() {
        let mut live = live_tcp(crate::RunMode::Manual, 4, 4);
        let (tx, rx) = mpsc::channel();
        live.connection
            .finish_with(move |result| {
                let _ = tx.send(result);
            })
            .expect("register finish callback");
        live.owner
            .complete_write_shutdown()
            .expect("owner completes finish");
        assert!(
            rx.try_recv().is_err(),
            "manual finish callback must wait for drive"
        );
        live.engine
            .drive(Instant::now())
            .expect("manual drive delivers callbacks");
        recv_finish(&rx).expect("callback runs during drive");
        live.engine.shutdown().expect("Engine must stop");
    }

    #[test]
    fn finish_with_stop_and_reset_and_failure_terminals() {
        let mut stopped = live_tcp(crate::RunMode::Spawned, 4, 4);
        let (tx, rx) = mpsc::channel();
        stopped
            .connection
            .finish_with(move |result| {
                let _ = tx.send(result);
            })
            .expect("register");
        drop(stopped.owner);
        match recv_finish(&rx) {
            Err(TcpFinishError::EngineStopped) => {}
            other => panic!("expected EngineStopped, got {other:?}"),
        }
        stopped.engine.shutdown().expect("Engine must stop");

        let mut reset = live_tcp(crate::RunMode::Spawned, 4, 4);
        let (tx, rx) = mpsc::channel();
        reset
            .connection
            .finish_with(move |result| {
                let _ = tx.send(result);
            })
            .expect("register");
        reset.owner.reset();
        match recv_finish(&rx) {
            Err(TcpFinishError::Reset) => {}
            other => panic!("expected Reset, got {other:?}"),
        }
        reset.engine.shutdown().expect("Engine must stop");

        let mut failed = live_tcp(crate::RunMode::Spawned, 4, 4);
        let (tx, rx) = mpsc::channel();
        failed
            .connection
            .finish_with(move |result| {
                let _ = tx.send(result);
            })
            .expect("register");
        failed.owner.fail(Error::new(
            ErrorKind::Transport,
            "injected transport failure",
        ));
        match recv_finish(&rx) {
            Err(TcpFinishError::Failed(error)) => {
                assert_eq!(error.kind(), ErrorKind::Transport);
            }
            other => panic!("expected Failed, got {other:?}"),
        }
        failed.engine.shutdown().expect("Engine must stop");
    }

    #[test]
    fn finish_with_panic_does_not_kill_dispatcher() {
        let engine = Engine::with_backend(EngineConfig::spawned(), crate::backend::scaffold())
            .expect("scaffold Engine must construct");
        let mut panicking = attach_live(&engine, crate::RunMode::Spawned, 4, 4, 1);
        let mut survivor = attach_live(&engine, crate::RunMode::Spawned, 4, 4, 2);
        panicking
            .connection
            .finish_with(|_| panic!("finish callback panic must be contained"))
            .expect("panicking callback registers");
        panicking
            .owner
            .complete_write_shutdown()
            .expect("panicking finish completes");
        let (tx, rx) = mpsc::channel();
        survivor
            .connection
            .finish_with(move |result| {
                let _ = tx.send(result);
            })
            .expect("survivor callback registers");
        survivor
            .owner
            .complete_write_shutdown()
            .expect("survivor finish completes");
        recv_finish(&rx).expect("dispatcher survives finish-callback panic");
        engine.shutdown().expect("Engine must stop");
        drop(survivor);
        drop(panicking);
    }

    #[test]
    fn finish_with_from_same_request_callback_is_serialized() {
        let live = live_tcp(crate::RunMode::Spawned, 4, 4);
        let shared = live.engine.shared_for_testing();
        let id = live.connection.handle().id();
        let connection = std::sync::Mutex::new(live.connection);
        let owner = std::sync::Mutex::new(live.owner);
        let (running_tx, running_rx) = mpsc::channel();
        let (hold_tx, hold_rx) = mpsc::channel::<()>();
        let (finish_tx, finish_rx) = mpsc::channel();
        shared.enqueue_callback_job(CallbackJob::new(id, move || {
            connection
                .lock()
                .expect("connection lock")
                .finish_with(move |result| {
                    let _ = finish_tx.send(result);
                })
                .expect("finish_with from the in-flight RequestId callback");
            owner
                .lock()
                .expect("owner lock")
                .complete_write_shutdown()
                .expect("complete finish while the RequestId callback is still running");
            running_tx.send(()).expect("test receiver");
            let _ = hold_rx.recv();
        }));
        running_rx
            .recv_timeout(Duration::from_secs(2))
            .expect("connect-callback analogue must call finish_with");
        assert!(
            finish_rx.try_recv().is_err(),
            "finish callback must not run until the RequestId callback returns"
        );
        drop(hold_tx);
        recv_finish(&finish_rx).expect("finish callback runs after return");
        live.engine.shutdown().expect("Engine must stop");
    }

    #[test]
    fn finish_with_admission_and_activation_are_atomic_against_shutdown() {
        let live = live_tcp(crate::RunMode::Spawned, 4, 4);
        let shared = live.engine.shared_for_testing();
        let (activation_tx, activation_rx) = mpsc::channel();
        let (release_tx, release_rx) = mpsc::channel::<()>();
        shared.set_callback_activation_hook(move || {
            activation_tx
                .send(())
                .expect("test observes callback activation");
            release_rx
                .recv()
                .expect("test releases callback activation");
        });

        let Live {
            occupancy,
            reserved,
            engine,
            mut connection,
            owner,
        } = live;
        let (finish_tx, finish_rx) = mpsc::channel();
        let finish_thread = std::thread::spawn(move || {
            connection.finish_with(move |result| {
                let _ = finish_tx.send(result);
            })
        });
        activation_rx
            .recv_timeout(Duration::from_secs(2))
            .expect("finish_with pauses after atomic admission and activation");

        let shutdown_shared = StdArc::clone(&shared);
        let (shutdown_tx, shutdown_rx) = mpsc::channel();
        let shutdown_thread = std::thread::spawn(move || {
            let _ = shutdown_tx.send(engine.shutdown());
        });
        let deadline = Instant::now() + Duration::from_secs(2);
        while !shutdown_shared.stopped.load(AtomicOrdering::Acquire) {
            assert!(Instant::now() < deadline, "shutdown must begin");
            std::thread::yield_now();
        }
        assert!(
            shutdown_rx.recv_timeout(Duration::from_millis(50)).is_err(),
            "shutdown must wait for the activated callback registration"
        );

        drop(owner);
        release_tx.send(()).expect("release finish_with activation");
        finish_thread
            .join()
            .expect("finish_with thread")
            .expect("finish_with registration succeeds");
        match recv_finish(&finish_rx) {
            Err(TcpFinishError::EngineStopped) => {}
            other => panic!("owner stop must win the callback terminal, got {other:?}"),
        }
        shutdown_rx
            .recv_timeout(Duration::from_secs(2))
            .expect("shutdown completes after activation")
            .expect("Engine shuts down cleanly");
        shutdown_thread.join().expect("shutdown thread");
        assert_eq!(occupancy.load(AtomicOrdering::SeqCst), 0);
        assert_eq!(reserved.load(AtomicOrdering::SeqCst), 0);
    }
}