native-ipc 0.6.0

One safe API for least-authority native shared memory: sealed memfd on Linux, Mach memory entries on macOS, exact-rights sections on Windows
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
//! Platform-neutral session negotiation facts.

use crate::batch::{ActiveRegionSet, BatchError, ExpectedBatch, TransferBatch};
use crate::control::{ControlError, ControlFrame};
use core::cell::Cell;
use core::marker::PhantomData;
#[cfg(any(target_os = "macos", target_os = "windows"))]
use core::sync::atomic::{AtomicBool, Ordering};
#[cfg(target_os = "linux")]
use core::sync::atomic::{AtomicI32, Ordering};
use std::ffi::OsString;
use std::num::NonZeroU32;
#[cfg(target_os = "linux")]
use std::os::fd::{FromRawFd, OwnedFd};
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
use std::path::Path;
use std::path::PathBuf;
use std::time::{Duration, Instant};

pub use crate::liveness::{ActiveLeaseFacts, LeaseFactsConsistency};

#[cfg(target_os = "linux")]
const RECEIVER_BOOTSTRAP_ENV_PREFIX: &[u8] = b"NATIVE_IPC_VNEXT_BOOTSTRAP_FD=";
#[cfg(target_os = "linux")]
const RECEIVER_PUBLIC_BOOTSTRAP_ENV_ENTRY: &[u8] = b"NATIVE_IPC_VNEXT_PUBLIC_BOOTSTRAP=1";
#[cfg(target_os = "linux")]
const PR_GET_MDWE: libc::c_int = 66;
#[cfg(target_os = "linux")]
const PR_MDWE_REFUSE_EXEC_GAIN: libc::c_ulong = 1;
#[cfg(target_os = "linux")]
const BOOTSTRAP_ABSENT: i32 = -2;
#[cfg(target_os = "linux")]
const BOOTSTRAP_INVALID: i32 = -1;
#[cfg(target_os = "linux")]
const BOOTSTRAP_TAKEN: i32 = -3;
#[cfg(target_os = "linux")]
static RECEIVER_BOOTSTRAP_FD: AtomicI32 = AtomicI32::new(BOOTSTRAP_ABSENT);
#[cfg(any(target_os = "macos", target_os = "windows"))]
static RECEIVER_BOOTSTRAP_TAKEN: AtomicBool = AtomicBool::new(false);

/// Executable-only ELF preinitializer referenced by [`crate::receiver_main!`].
///
/// # Safety
///
/// This function may be invoked only by the ELF loader through a
/// `.preinit_array` entry in the initial receiver executable. Its pointers must
/// be the loader-supplied initial argument and environment vectors. The hook is
/// a no-op on non-Linux targets solely to keep the helper-only signature
/// platform-neutral.
#[doc(hidden)]
pub unsafe extern "C" fn __receiver_bootstrap_preinit(
    _argument_count: core::ffi::c_int,
    _arguments: *mut *mut core::ffi::c_char,
    environment: *mut *mut core::ffi::c_char,
) {
    #[cfg(target_os = "linux")]
    // SAFETY: the public hook forwards the loader-supplied environment under
    // the same pre-initializer contract.
    unsafe {
        receiver_bootstrap_preinit_linux(environment);
    }
    #[cfg(not(target_os = "linux"))]
    let _ = environment;
}

#[cfg(target_os = "linux")]
unsafe fn receiver_bootstrap_preinit_linux(environment: *mut *mut libc::c_char) {
    // This ELF pre-initializer runs before Rust main and ordinary init-array
    // constructors. It performs no allocation and publishes only after all
    // exact child/descriptor facts and immediate CLOEXEC installation pass.
    let mut entry = environment;
    let public_bootstrap = loop {
        if entry.is_null() {
            return;
        }
        // SAFETY: the loader supplies a null-terminated environment vector.
        let candidate = unsafe { *entry };
        if candidate.is_null() {
            return;
        }
        let mut matches = true;
        for (offset, expected) in RECEIVER_PUBLIC_BOOTSTRAP_ENV_ENTRY.iter().enumerate() {
            // SAFETY: read only the current byte; a NUL ends this C string and
            // prevents any later offset from being dereferenced.
            let actual = unsafe { *candidate.add(offset) }.to_ne_bytes()[0];
            if actual == 0 || actual != *expected {
                matches = false;
                break;
            }
        }
        if matches
            // SAFETY: the exact fixed entry was readable through its last byte.
            && unsafe { *candidate.add(RECEIVER_PUBLIC_BOOTSTRAP_ENV_ENTRY.len()) } == 0
        {
            break candidate;
        }
        // SAFETY: advance within the loader-supplied pointer vector.
        entry = unsafe { entry.add(1) };
    };
    // SAFETY: initial-stack environment strings are writable process storage.
    // Scrubbing the routing marker before normal code prevents descendants from
    // reinterpreting this process's one-shot startup designation.
    unsafe { *public_bootstrap = 0 };

    let mut entry = environment;
    let value = loop {
        if entry.is_null() {
            return;
        }
        // SAFETY: the loader supplies a null-terminated environment vector.
        let candidate = unsafe { *entry };
        if candidate.is_null() {
            return;
        }
        let mut matches = true;
        for (offset, expected) in RECEIVER_BOOTSTRAP_ENV_PREFIX.iter().enumerate() {
            // SAFETY: read only the current byte; a NUL ends this C string and
            // prevents any later offset from being dereferenced.
            let actual = unsafe { *candidate.add(offset) }.to_ne_bytes()[0];
            if actual == 0 || actual != *expected {
                matches = false;
                break;
            }
        }
        if matches {
            // SAFETY: the matched fixed prefix lies within this environment entry.
            let value = unsafe { candidate.add(RECEIVER_BOOTSTRAP_ENV_PREFIX.len()) };
            // SAFETY: initial-stack environment strings are writable process
            // storage. Retain the parsed pointer locally but erase the inherited
            // numeric authority before any normal constructor or application code.
            unsafe { *candidate = 0 };
            break value;
        }
        // SAFETY: advance within the loader-supplied pointer vector.
        entry = unsafe { entry.add(1) };
    };
    let mut raw = 0_i32;
    let mut length = 0_usize;
    loop {
        if length == 10 {
            RECEIVER_BOOTSTRAP_FD.store(BOOTSTRAP_INVALID, Ordering::Release);
            return;
        }
        // SAFETY: getenv returned a live NUL-terminated process string.
        let byte = unsafe { *value.add(length) }.to_ne_bytes()[0];
        if byte == 0 {
            break;
        }
        if !byte.is_ascii_digit() || (length == 0 && byte == b'0') {
            RECEIVER_BOOTSTRAP_FD.store(BOOTSTRAP_INVALID, Ordering::Release);
            return;
        }
        let Some(next) = raw
            .checked_mul(10)
            .and_then(|current| current.checked_add(i32::from(byte - b'0')))
        else {
            RECEIVER_BOOTSTRAP_FD.store(BOOTSTRAP_INVALID, Ordering::Release);
            return;
        };
        raw = next;
        length += 1;
    }
    if length == 0 || raw < 3 {
        RECEIVER_BOOTSTRAP_FD.store(BOOTSTRAP_INVALID, Ordering::Release);
        return;
    }

    // SAFETY: these scalar queries and exact getsockopt output have valid
    // arguments and do not transfer descriptor ownership.
    let descriptor_flags = unsafe { libc::fcntl(raw, libc::F_GETFD) };
    let descriptor_status = unsafe { libc::fcntl(raw, libc::F_GETFL) };
    let mdwe = unsafe { libc::prctl(PR_GET_MDWE, 0, 0, 0, 0) } as libc::c_ulong;
    let pid = unsafe { libc::getpid() };
    let sid = unsafe { libc::getsid(0) };
    let process_group = unsafe { libc::getpgrp() };
    let mut socket_type = 0_i32;
    let mut socket_type_len = core::mem::size_of::<i32>() as libc::socklen_t;
    let socket_result = unsafe {
        libc::getsockopt(
            raw,
            libc::SOL_SOCKET,
            libc::SO_TYPE,
            (&mut socket_type as *mut i32).cast(),
            &mut socket_type_len,
        )
    };
    if descriptor_flags != 0
        || descriptor_status < 0
        || descriptor_status & libc::O_NONBLOCK == 0
        || mdwe != PR_MDWE_REFUSE_EXEC_GAIN
        || pid <= 0
        || sid != pid
        || process_group != pid
        || socket_result != 0
        || socket_type_len as usize != core::mem::size_of::<i32>()
        || socket_type != libc::SOCK_SEQPACKET
    {
        // SAFETY: the process environment designated this live numeric slot as
        // bootstrap authority before any Rust application code ran. Fail closed
        // by removing it rather than permitting later Command inheritance.
        let _ = unsafe { libc::close(raw) };
        RECEIVER_BOOTSTRAP_FD.store(BOOTSTRAP_INVALID, Ordering::Release);
        return;
    }
    // SAFETY: this descriptor is the validated inherited endpoint. Installing
    // CLOEXEC before any application code removes every safe Command delegation
    // window. On failure, close the exact startup descriptor.
    if unsafe { libc::fcntl(raw, libc::F_SETFD, libc::FD_CLOEXEC) } != 0 {
        let _ = unsafe { libc::close(raw) };
        RECEIVER_BOOTSTRAP_FD.store(BOOTSTRAP_INVALID, Ordering::Release);
        return;
    }
    RECEIVER_BOOTSTRAP_FD.store(raw, Ordering::Release);
}

/// Hard protocol maximum for one atomic transfer batch.
pub const HARD_MAX_REGIONS_PER_BATCH: u16 = 16;
/// Hard maximum for the opaque HELLO application payload.
pub const HARD_MAX_BOOTSTRAP_PAYLOAD_BYTES: u32 = 16 * 1024 * 1024;
/// Hard maximum for one opaque application-control payload.
pub const HARD_MAX_CONTROL_PAYLOAD_BYTES: u32 = 16 * 1024 * 1024;
/// Hard maximum logical size of one region.
pub const HARD_MAX_REGION_BYTES: u64 = 1 << 40;
/// Hard maximum aggregate bytes in one transaction.
pub const HARD_MAX_BATCH_BYTES: u64 = 1 << 42;
/// Hard maximum simultaneously charged region mappings.
pub const HARD_MAX_ACTIVE_REGIONS: u32 = 1 << 20;
/// Hard maximum simultaneously charged mapping bytes.
pub const HARD_MAX_ACTIVE_BYTES: u64 = 1 << 44;
/// Hard maximum transactions in one fresh session.
pub const HARD_MAX_TRANSACTIONS: u64 = 1 << 48;

/// Coordinator endpoint marker for [`Session`].
pub struct Coordinator;
/// Receiver endpoint marker for [`Session`].
pub struct Receiver;
/// Authenticated HELLO state awaiting application decisions.
pub struct Negotiating;
/// Bilaterally accepted state that may carry bounded application control.
pub struct Ready;

/// Availability of the public lifecycle/session composition on this target.
///
/// This status applies only to the vNext session layer. The published shared-
/// memory API remains available on every supported target. Consumers may use
/// [`backend_status`] as a const preflight or handle
/// [`SessionError::BackendUnavailable`] from a construction attempt.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BackendStatus {
    /// Public spawn and inherited-bootstrap session construction are composed.
    Available,
    /// Reserved for a supported target whose lifecycle adapter is not composed.
    /// Every target the crate currently compiles for reports [`Self::Available`];
    /// no supported target returns this today.
    Unavailable,
}

/// Reports whether the public lifecycle/session composition is available.
///
/// Linux, macOS Arm64, and Windows all report [`BackendStatus::Available`]:
/// public spawn and inherited-bootstrap session construction are composed on
/// every supported target. [`BackendStatus::Unavailable`] remains reserved for
/// targets whose adapter is not composed.
pub const fn backend_status() -> BackendStatus {
    BackendStatus::Available
}

/// Accepted wire protocol version bound into both challenged ACCEPT frames.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ProtocolVersion {
    major: u16,
    minor: u16,
}

impl ProtocolVersion {
    #[allow(dead_code, reason = "wired into accepted session facts below")]
    pub(crate) const fn new(major: u16, minor: u16) -> Self {
        Self { major, minor }
    }

    /// Incompatible-major protocol number.
    pub const fn major(self) -> u16 {
        self.major
    }

    /// Backward-compatible minor protocol number.
    pub const fn minor(self) -> u16 {
        self.minor
    }
}

/// Locally observed accepted-session reducer state.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SessionState {
    /// Application control and native transactions may be attempted.
    Ready,
    /// A terminal ambiguity, malformed peer action, or native failure poisoned the session.
    Poisoned,
}

/// Nonblocking peer observation that does not invent an exit code.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PeerStatus {
    /// No authenticated control-endpoint disconnect has been observed.
    Connected,
    /// The authenticated control endpoint closed; this does not prove process exit.
    Disconnected,
}

/// Exact direct-child termination fact reaped by the coordinator.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ChildExitStatus {
    /// The direct child exited normally with this code.
    Exited(i32),
    /// The direct child was terminated by a signal.
    Signaled {
        /// Signal number reported by the kernel.
        signal: i32,
        /// Whether the kernel reported a core dump.
        dumped_core: bool,
    },
    /// Another process-global waiter consumed the direct-child status first.
    AlreadyReaped,
}

/// Bounded statement about descendant cleanup outside the atomic pidfd owner.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DescendantCleanupStatus {
    /// The trusted fresh-session checkpoint was not established.
    NotEstablished,
    /// A fresh process group existed, but bounded group termination could not
    /// be performed under a kernel-witnessed direct-child identity pin.
    FreshGroupUnverified,
    /// SIGKILL was delivered to the kernel-verified fresh process group while
    /// the unreaped direct child pinned its numeric identity, terminating
    /// every ordinary descendant that had not left the group.
    FreshGroupTerminated,
    /// A target-owned containment object proved the complete spawned process tree empty.
    ContainedProcessTreeComplete,
    /// A target-owned containment object exists, but bounded cleanup did not prove it empty.
    OwnedContainmentUnverified,
}

/// Bounded coordinator-owned direct-child cleanup result.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ChildCleanupFacts {
    direct_child: Option<ChildExitStatus>,
    descendants: DescendantCleanupStatus,
    native_error: Option<i32>,
}

impl ChildCleanupFacts {
    #[allow(dead_code, reason = "wired into coordinator lifecycle facts below")]
    pub(crate) const fn new(
        direct_child: Option<ChildExitStatus>,
        descendants: DescendantCleanupStatus,
        native_error: Option<i32>,
    ) -> Self {
        Self {
            direct_child,
            descendants,
            native_error,
        }
    }

    /// Reaped direct-child status, or `None` when bounded cleanup is incomplete.
    pub const fn direct_child(self) -> Option<ChildExitStatus> {
        self.direct_child
    }

    /// What can safely be claimed about the fresh descendant group.
    pub const fn descendants(self) -> DescendantCleanupStatus {
        self.descendants
    }

    /// Last bounded native errno when cleanup could not complete.
    pub const fn native_error(self) -> Option<i32> {
        self.native_error
    }

    /// Whether the exact direct child has been reaped or was already reaped.
    pub const fn direct_child_complete(self) -> bool {
        self.direct_child.is_some()
    }
}

/// Recoverable coordinator close result.
pub enum CoordinatorCloseOutcome {
    /// No active leases remained and the exact direct child was reaped.
    Closed(ChildCleanupFacts),
    /// Active mappings still retain the session; drop them and retry with the returned owner.
    ActiveLeases {
        /// Unconsumed live session owner.
        session: CoordinatorSession<Ready>,
        /// Bounded current active mapping facts.
        facts: ActiveLeaseFacts,
    },
    /// The deadline elapsed or cleanup failed; the returned owner retains exact child authority.
    CleanupPending {
        /// Unconsumed live session owner.
        session: CoordinatorSession<Ready>,
        /// Bounded cleanup facts from this attempt.
        facts: ChildCleanupFacts,
        /// Exact close failure category and the same retained cleanup evidence.
        failure: SessionFailure,
    },
    /// An unexpected local close transition failed without consuming ownership.
    Failed {
        /// Unconsumed session owner that may be aborted or retried.
        session: CoordinatorSession<Ready>,
        /// Bounded failure diagnostics including cleanup already attempted.
        error: SessionFailure,
    },
}

/// Recoverable receiver close result.
pub enum ReceiverCloseOutcome {
    /// No active mappings remained and the inherited endpoint was closed.
    Closed,
    /// Active mappings still retain the session; drop them and retry with the returned owner.
    ActiveLeases {
        /// Unconsumed live session owner.
        session: ReceiverSession<Ready>,
        /// Bounded current active mapping facts.
        facts: ActiveLeaseFacts,
    },
    /// An unexpected local close transition failed without consuming ownership.
    Failed {
        /// Unconsumed session owner that may be aborted or retried.
        session: ReceiverSession<Ready>,
        /// Bounded local failure diagnostics.
        error: SessionFailure,
    },
}

/// Terminal coordinator abort result with bounded cleanup diagnostics.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CoordinatorAbortOutcome {
    cleanup: ChildCleanupFacts,
    failure: Option<SessionFailure>,
}

impl CoordinatorAbortOutcome {
    /// Bounded exact-child and descendant cleanup facts.
    pub const fn cleanup(self) -> ChildCleanupFacts {
        self.cleanup
    }

    /// Failure record when bounded termination/reap did not complete.
    pub const fn failure(self) -> Option<SessionFailure> {
        self.failure
    }
}

/// Role- and state-typed session owner.
///
/// The role aliases [`CoordinatorSession`] and [`ReceiverSession`] are the
/// ordinary spellings. Session values are movable but deliberately not
/// shareable between threads; every control transition requires `&mut self`.
pub struct Session<Role, State> {
    inner: SessionInner,
    role: PhantomData<Role>,
    state: PhantomData<State>,
    not_sync: PhantomData<Cell<()>>,
}

/// Coordinator-owned exact-child session in the supplied typestate.
pub type CoordinatorSession<State> = Session<Coordinator, State>;
/// Receiver-owned inherited-bootstrap session in the supplied typestate.
pub type ReceiverSession<State> = Session<Receiver, State>;

/// Unique inherited receiver bootstrap authority.
///
/// Ordinary helpers obtain this token only from [`crate::receiver_main!`]. Consuming
/// the token transfers the sole inherited native endpoint into negotiation;
/// it is non-cloneable and exposes no raw descriptor.
pub struct ReceiverBootstrap {
    #[cfg(target_os = "linux")]
    inherited: OwnedFd,
    not_sync: PhantomData<Cell<()>>,
}

/// Defines a helper-process entry point with one ownership-bearing bootstrap.
///
/// The supplied closure receives `Result<ReceiverBootstrap, SessionFailure>` and
/// runs only after the library has attempted the one-shot reservation take.
/// Linux validates and reserves its inherited descriptor in an ELF
/// pre-initializer. macOS consumes its one-shot bootstrap designation from
/// Rust main and scrubs the public marker there; the Mach nonce and parent
/// identity are taken and scrubbed when the receiver session connects.
/// Windows takes and scrubs its pipe, nonce, and parent designation when the
/// receiver session connects from the environment.
#[macro_export]
macro_rules! receiver_main {
    ($entry:expr) => {
        #[cfg(target_os = "linux")]
        #[used]
        #[unsafe(link_section = ".preinit_array")]
        static NATIVE_IPC_RECEIVER_BOOTSTRAP_PREINIT: unsafe extern "C" fn(
            ::core::ffi::c_int,
            *mut *mut ::core::ffi::c_char,
            *mut *mut ::core::ffi::c_char,
        ) = $crate::session::__receiver_bootstrap_preinit;

        fn main() {
            let bootstrap = $crate::session::__take_receiver_bootstrap();
            ($entry)(bootstrap);
        }
    };
}

/// Takes the pre-initialized inherited endpoint exactly once.
///
/// This is exported only so [`crate::receiver_main!`] can expand in downstream
/// crates. Applications must invoke that macro instead of calling this hook.
#[doc(hidden)]
pub fn __take_receiver_bootstrap() -> Result<ReceiverBootstrap, SessionFailure> {
    #[cfg(target_os = "linux")]
    {
        let raw = RECEIVER_BOOTSTRAP_FD.swap(BOOTSTRAP_TAKEN, Ordering::AcqRel);
        if raw < 3 {
            return Err(SessionFailure::new(
                SessionOperation::Bootstrap,
                SessionTransactionState::NotEstablished,
                SessionError::InvalidInput,
            ));
        }
        // SAFETY: the pre-initializer reserved this validated descriptor for
        // the one successful atomic take and installed CLOEXEC before main.
        let inherited = unsafe { OwnedFd::from_raw_fd(raw) };
        Ok(ReceiverBootstrap {
            inherited,
            not_sync: PhantomData,
        })
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        Err(SessionFailure::new(
            SessionOperation::Bootstrap,
            SessionTransactionState::NotEstablished,
            SessionError::BackendUnavailable,
        ))
    }
    #[cfg(target_os = "windows")]
    {
        if RECEIVER_BOOTSTRAP_TAKEN.swap(true, Ordering::AcqRel)
            || std::env::var_os("NATIVE_IPC_VNEXT_PUBLIC_BOOTSTRAP").as_deref()
                != Some(std::ffi::OsStr::new("1"))
        {
            return Err(SessionFailure::new(
                SessionOperation::Bootstrap,
                SessionTransactionState::NotEstablished,
                SessionError::InvalidInput,
            ));
        }
        Ok(ReceiverBootstrap {
            not_sync: PhantomData,
        })
    }
    #[cfg(target_os = "macos")]
    {
        if RECEIVER_BOOTSTRAP_TAKEN.swap(true, Ordering::AcqRel)
            || std::env::var_os("NATIVE_IPC_VNEXT_PUBLIC_BOOTSTRAP").as_deref()
                != Some(std::ffi::OsStr::new("1"))
        {
            return Err(SessionFailure::new(
                SessionOperation::Bootstrap,
                SessionTransactionState::NotEstablished,
                SessionError::InvalidInput,
            ));
        }
        // Scrub the one-shot routing marker so descendants of this receiver
        // cannot reinterpret its bootstrap designation, matching the Linux
        // pre-init and Windows connect scrubs. The Mach nonce and parent PID are
        // scrubbed where they are consumed, in `ChildChannel::connect_from_environment`.
        // SAFETY: the bootstrap environment is process-local startup state
        // consumed exactly once here before any application or descendant code.
        unsafe { std::env::remove_var("NATIVE_IPC_VNEXT_PUBLIC_BOOTSTRAP") };
        Ok(ReceiverBootstrap {
            not_sync: PhantomData,
        })
    }
}

enum SessionInner {
    #[cfg(target_os = "linux")]
    CoordinatorNegotiating(crate::backend::linux_vnext::spawn::LinuxCoordinatorNegotiatingSession),
    #[cfg(target_os = "linux")]
    ReceiverNegotiating(crate::backend::linux_vnext::spawn::LinuxReceiverNegotiatingSession),
    #[cfg(target_os = "linux")]
    CoordinatorReady(crate::backend::linux_vnext::spawn::LinuxCoordinatorReadySession),
    #[cfg(target_os = "linux")]
    ReceiverReady(crate::backend::linux_vnext::spawn::LinuxReceiverReadySession),
    #[cfg(target_os = "macos")]
    CoordinatorNegotiating(crate::backend::macos::vnext_session::MacCoordinatorNegotiatingSession),
    #[cfg(target_os = "macos")]
    ReceiverNegotiating(crate::backend::macos::vnext_session::MacReceiverNegotiatingSession),
    #[cfg(target_os = "macos")]
    CoordinatorReady(crate::backend::macos::vnext_session::MacCoordinatorReadySession),
    #[cfg(target_os = "macos")]
    ReceiverReady(crate::backend::macos::vnext_session::MacReceiverReadySession),
    #[cfg(target_os = "windows")]
    CoordinatorNegotiating(
        Box<crate::backend::windows::vnext_session::WindowsCoordinatorNegotiatingSession>,
    ),
    #[cfg(target_os = "windows")]
    ReceiverNegotiating(
        Box<crate::backend::windows::vnext_session::WindowsReceiverNegotiatingSession>,
    ),
    #[cfg(target_os = "windows")]
    CoordinatorReady(Box<crate::backend::windows::vnext_session::WindowsCoordinatorReadySession>),
    #[cfg(target_os = "windows")]
    ReceiverReady(Box<crate::backend::windows::vnext_session::WindowsReceiverReadySession>),
    #[allow(dead_code)]
    Unavailable,
}

/// Required executable-identity policy for an owned helper launch.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ExecutableIdentityPolicy {
    /// Open and retain one absolute regular executable without any symlink
    /// traversal and apply the target's documented image-identity checks.
    /// Linux executes the held object directly. macOS authenticates the
    /// running image against the retained file by content: the kernel-
    /// registered code-directory hash of the exact audit-token-bound child
    /// execution must match a hash computed from the held descriptor, at
    /// launch and again through ACCEPT, independent of pathnames and of the
    /// signing identity (an ad-hoc linker signature suffices). A macOS
    /// executable that carries no code directory — an unsigned image or a
    /// script — cannot be bound and fails construction closed. Windows
    /// retains the opened file, spawns from the retained image, binds the
    /// session transport to the exact spawned process identity, and holds
    /// the child and its descendants in a kill-on-close Job.
    ExactOpenedFile,
}

/// Exact child command. The environment is explicit and starts empty.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SessionCommand {
    executable: PathBuf,
    arguments: Vec<OsString>,
    environment: Vec<(OsString, OsString)>,
}

impl SessionCommand {
    /// Starts a command whose argument zero is the supplied executable path.
    pub fn new(executable: impl Into<PathBuf>) -> Self {
        let executable = executable.into();
        Self {
            arguments: vec![executable.as_os_str().to_owned()],
            executable,
            environment: Vec::new(),
        }
    }

    /// Replaces argument zero without changing the selected executable path.
    pub fn arg0(mut self, argument: impl Into<OsString>) -> Self {
        self.arguments[0] = argument.into();
        self
    }

    /// Appends one exact child argument.
    pub fn arg(mut self, argument: impl Into<OsString>) -> Self {
        self.arguments.push(argument.into());
        self
    }

    /// Adds or replaces one exact child environment entry.
    pub fn env(mut self, key: impl Into<OsString>, value: impl Into<OsString>) -> Self {
        let key = key.into();
        let value = value.into();
        if let Some((_, existing)) = self
            .environment
            .iter_mut()
            .find(|(existing, _)| *existing == key)
        {
            *existing = value;
        } else {
            self.environment.push((key, value));
        }
        self
    }

    /// The cross-platform union of reserved bootstrap environment names.
    /// Every target rejects the full union so a command that spawns on one
    /// platform is not silently accepted with a reserved key on another.
    fn has_reserved_environment(&self) -> bool {
        const RESERVED: [&str; 6] = [
            "NATIVE_IPC_VNEXT_BOOTSTRAP_FD",
            "NATIVE_IPC_VNEXT_PUBLIC_BOOTSTRAP",
            "NATIVE_IPC_MACH_NONCE",
            "NATIVE_IPC_PARENT_PID",
            "NATIVE_IPC_WINDOWS_PIPE",
            "NATIVE_IPC_WINDOWS_NONCE",
        ];
        self.environment.iter().any(|(key, _)| {
            RESERVED
                .iter()
                .any(|name| key.as_os_str() == std::ffi::OsStr::new(name))
        })
    }

    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    pub(crate) fn executable(&self) -> &Path {
        &self.executable
    }

    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    pub(crate) fn arguments(&self) -> &[OsString] {
        &self.arguments
    }

    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    pub(crate) fn environment(&self) -> &[(OsString, OsString)] {
        &self.environment
    }
}

/// Finite negotiation inputs retained under one caller-derived deadline.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SessionOptions {
    deadline: AbsoluteDeadline,
    limits: SessionLimits,
    application_payload: Vec<u8>,
    executable_identity: ExecutableIdentityPolicy,
    require_atomic_u32: bool,
    require_atomic_u64: bool,
}

impl SessionOptions {
    /// Creates an exact-deadline offer with finite default limits.
    pub fn new(deadline: AbsoluteDeadline, executable_identity: ExecutableIdentityPolicy) -> Self {
        Self {
            deadline,
            limits: SessionLimits::default(),
            application_payload: Vec::new(),
            executable_identity,
            require_atomic_u32: false,
            require_atomic_u64: false,
        }
    }

    /// Replaces the finite local limit offer.
    pub fn with_limits(mut self, limits: SessionLimits) -> Self {
        self.limits = limits;
        self
    }

    /// Replaces the bounded opaque application HELLO payload.
    pub fn with_application_payload(mut self, payload: Vec<u8>) -> Self {
        self.application_payload = payload;
        self
    }

    /// Requires lock-free cross-process 32-bit atomic support.
    pub fn require_atomic_u32(mut self) -> Self {
        self.require_atomic_u32 = true;
        self
    }

    /// Requires lock-free cross-process 64-bit atomic support.
    pub fn require_atomic_u64(mut self) -> Self {
        self.require_atomic_u64 = true;
        self
    }

    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    pub(crate) const fn limits(&self) -> SessionLimits {
        self.limits
    }

    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    pub(crate) fn application_payload(&self) -> &[u8] {
        &self.application_payload
    }

    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    pub(crate) const fn requires_atomic_u32(&self) -> bool {
        self.require_atomic_u32
    }

    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    pub(crate) const fn requires_atomic_u64(&self) -> bool {
        self.require_atomic_u64
    }

    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    pub(crate) const fn deadline(&self) -> AbsoluteDeadline {
        self.deadline
    }
}

/// Endpoint that made a clean application negotiation rejection.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SessionEndpoint {
    /// Spawning owner of the exact helper.
    Coordinator,
    /// Exact inherited-bootstrap helper.
    Receiver,
}

/// Nonzero application negotiation rejection reason.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RejectionReason(NonZeroU32);

impl RejectionReason {
    /// The application declined without a more specific incompatibility.
    pub const APPLICATION_DECLINED: Self = Self(NonZeroU32::MIN);
    /// Application protocols or schemas are incompatible.
    pub const INCOMPATIBLE_APPLICATION_PROTOCOL: Self =
        Self(NonZeroU32::new(2).expect("two is nonzero"));
    /// Local application policy rejected the peer.
    pub const APPLICATION_POLICY: Self = Self(NonZeroU32::new(3).expect("three is nonzero"));

    /// Constructs an application-specific reason from the high-half namespace.
    pub const fn application_specific(value: u32) -> Option<Self> {
        if value < 0x8000_0000 {
            return None;
        }
        match NonZeroU32::new(value) {
            Some(value) => Some(Self(value)),
            None => None,
        }
    }

    /// Numeric wire value for logging or application dispatch.
    pub const fn get(self) -> u32 {
        self.0.get()
    }

    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    fn from_wire(value: NonZeroU32) -> Option<Self> {
        match value.get() {
            1 => Some(Self::APPLICATION_DECLINED),
            2 => Some(Self::INCOMPATIBLE_APPLICATION_PROTOCOL),
            3 => Some(Self::APPLICATION_POLICY),
            value => Self::application_specific(value),
        }
    }

    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    const fn as_nonzero(self) -> NonZeroU32 {
        self.0
    }
}

/// Explicit application decision after the peer HELLO is available.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum NegotiationDecision {
    /// Accept the peer's bounded opaque HELLO payload and negotiated facts.
    Accept,
    /// Cleanly reject with a fixed nonzero application reason.
    Reject(RejectionReason),
}

/// Clean application-level result of the challenged negotiation.
pub enum NegotiationOutcome<T> {
    /// Bilateral exact ACCEPT yielded the ready session owner.
    Accepted(T),
    /// One endpoint made a canonical clean application rejection.
    Rejected {
        /// Endpoint that rejected.
        by: SessionEndpoint,
        /// Exact nonzero reason carried by the peer or local decision.
        reason: RejectionReason,
        /// Coordinator-owned child cleanup facts; receivers have no child authority.
        cleanup: Option<ChildCleanupFacts>,
    },
}

/// Public session construction, negotiation, or control failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SessionError {
    /// The selected native target adapter is not composed yet.
    BackendUnavailable,
    /// Local command, environment, payload, or option input is invalid.
    InvalidInput,
    /// The one caller-derived absolute deadline expired.
    DeadlineExpired,
    /// The authenticated control endpoint closed before the operation completed.
    PeerDisconnected,
    /// Kernel-authenticated process or executable identity did not match.
    IdentityMismatch,
    /// The peer supplied malformed or noncanonical framing.
    MalformedPeer,
    /// Local I/O completed at the deadline boundary with unknowable peer state.
    Ambiguous,
    /// HELLO or challenged decision validation failed.
    NegotiationFailed,
    /// Local native capability discovery or limit negotiation failed.
    NativeNegotiation(NegotiationError),
    /// Application-control sequencing or bounds validation failed.
    Control(ControlError),
    /// Portable batch construction or committed-set validation failed.
    Batch(BatchError),
    /// Current active region or byte capacity cannot admit the whole batch.
    ActiveLimit,
    /// The peer reported a bounded local native-preparation failure before capability transfer.
    PeerPreparationFailed,
    /// Native mapping activation failed atomically without exposing a partial set.
    ActivationFailed,
    /// Native negotiation transport was already terminally poisoned.
    Poisoned,
    /// A bounded native operation failed without a more specific safe category.
    Native,
}

impl core::fmt::Display for SessionError {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(formatter, "session operation failed: {self:?}")
    }
}

impl std::error::Error for SessionError {}

/// Bounded public operation category attached to a session failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SessionOperation {
    /// Process-entry bootstrap adoption.
    Bootstrap,
    /// Exact child spawn and authenticated HELLO exchange.
    Spawn,
    /// Bilateral application negotiation.
    Negotiate,
    /// Nonblocking peer observation.
    PollPeer,
    /// Bounded peer/direct-child wait.
    WaitForExit,
    /// Graceful session close.
    Close,
    /// Terminal session abort.
    Abort,
    /// Coordinator capability transfer and activation.
    TransferBatch,
    /// Receiver capability import and activation.
    ReceiveBatch,
    /// Opaque application-control send.
    SendControl,
    /// Opaque application-control receive.
    ReceiveControl,
}

/// Bounded reducer state observed for a failed public operation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SessionTransactionState {
    /// No session owner had been established.
    NotEstablished,
    /// An exact child exists, but authenticated HELLO negotiation has not begun.
    Spawned,
    /// The authenticated endpoints were still negotiating.
    Negotiating,
    /// The accepted control reducer was idle and ready.
    Ready,
    /// A native capability transaction had begun. Only backends whose batch
    /// activation is non-atomic report this state (Linux); macOS and Windows
    /// activate atomically and expose no partially-open transaction, so a
    /// portable consumer must not depend on observing it on every target.
    TransactionOpen,
    /// The session reducer was terminally poisoned.
    Poisoned,
}

/// Bounded diagnostics retained for a failed public session operation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SessionFailure {
    operation: SessionOperation,
    transaction_state: SessionTransactionState,
    reason: SessionError,
    native_code: Option<i32>,
    poisoned: bool,
    peer: Option<PeerStatus>,
    cleanup: Option<ChildCleanupFacts>,
}

impl SessionFailure {
    const fn new(
        operation: SessionOperation,
        transaction_state: SessionTransactionState,
        reason: SessionError,
    ) -> Self {
        Self {
            operation,
            transaction_state,
            reason,
            native_code: None,
            poisoned: matches!(transaction_state, SessionTransactionState::Poisoned),
            peer: if matches!(reason, SessionError::PeerDisconnected) {
                Some(PeerStatus::Disconnected)
            } else {
                None
            },
            cleanup: None,
        }
    }

    const fn with_cleanup(mut self, cleanup: ChildCleanupFacts) -> Self {
        self.cleanup = Some(cleanup);
        self
    }

    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    const fn with_optional_cleanup(mut self, cleanup: Option<ChildCleanupFacts>) -> Self {
        self.cleanup = cleanup;
        self
    }

    const fn with_native_code(mut self, native_code: Option<i32>) -> Self {
        self.native_code = native_code;
        self
    }

    const fn with_poisoned(mut self, poisoned: bool) -> Self {
        self.poisoned = poisoned;
        self
    }

    /// Public operation that failed.
    pub const fn operation(self) -> SessionOperation {
        self.operation
    }

    /// Reducer/transaction state observed for the failure.
    pub const fn transaction_state(self) -> SessionTransactionState {
        self.transaction_state
    }

    /// Portable bounded failure reason.
    pub const fn reason(self) -> SessionError {
        self.reason
    }

    /// Native error code when the backend can preserve one safely.
    pub const fn native_code(self) -> Option<i32> {
        self.native_code
    }

    /// Whether the operation left the session terminally poisoned.
    pub const fn is_poisoned(self) -> bool {
        self.poisoned
    }

    /// Bounded peer observation associated with the failure.
    pub const fn peer(self) -> Option<PeerStatus> {
        self.peer
    }

    /// Coordinator-owned cleanup facts, when this operation consumed child authority.
    pub const fn cleanup(self) -> Option<ChildCleanupFacts> {
        self.cleanup
    }
}

impl core::fmt::Display for SessionFailure {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            formatter,
            "session {:?} failed in {:?}: {:?}",
            self.operation, self.transaction_state, self.reason
        )
    }
}

impl std::error::Error for SessionFailure {}

/// Finite resource limits offered and negotiated by both endpoints.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SessionLimits {
    /// Maximum entries in one batch; hard maximum sixteen.
    pub max_regions_per_batch: u16,
    /// Maximum logical bytes in one region.
    pub max_region_bytes: u64,
    /// Maximum aggregate logical/mapped bytes in one batch.
    pub max_batch_bytes: u64,
    /// Maximum charged active region mappings.
    pub max_active_regions: u32,
    /// Maximum charged active mapping bytes.
    pub max_active_bytes: u64,
    /// Maximum monotonically increasing transactions.
    pub max_transactions: u64,
    /// Maximum opaque HELLO application payload bytes.
    pub max_bootstrap_payload_bytes: u32,
    /// Maximum opaque application-control payload bytes.
    pub max_control_payload_bytes: u32,
}

impl Default for SessionLimits {
    fn default() -> Self {
        Self {
            max_regions_per_batch: 16,
            max_region_bytes: 256 * 1024 * 1024,
            max_batch_bytes: 1024 * 1024 * 1024,
            max_active_regions: 4096,
            max_active_bytes: 8 * 1024 * 1024 * 1024,
            max_transactions: 1 << 32,
            max_bootstrap_payload_bytes: 1024 * 1024,
            max_control_payload_bytes: 1024 * 1024,
        }
    }
}

/// Invalid local or peer negotiation offer.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum NegotiationError {
    /// A numeric limit is zero.
    ZeroLimit,
    /// A numeric limit exceeds its field-specific hard maximum.
    AboveHardMaximum,
    /// A byte limit cannot narrow to this target's `usize`.
    NativeSizeNarrowing,
    /// Required lock-free atomic width is not available.
    AtomicUnsupported,
    /// A monotonic deadline cannot be represented.
    InvalidDeadline,
}

impl core::fmt::Display for NegotiationError {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(formatter, "session negotiation failed: {self:?}")
    }
}

impl std::error::Error for NegotiationError {}

impl SessionLimits {
    /// Validates every field before allocation or native import.
    pub fn validate(self) -> Result<Self, NegotiationError> {
        self.validate_for_native_max(usize::MAX as u64)
    }

    fn validate_for_native_max(self, native_usize_max: u64) -> Result<Self, NegotiationError> {
        if self.max_regions_per_batch == 0
            || self.max_region_bytes == 0
            || self.max_batch_bytes == 0
            || self.max_active_regions == 0
            || self.max_active_bytes == 0
            || self.max_transactions == 0
            || self.max_bootstrap_payload_bytes == 0
            || self.max_control_payload_bytes == 0
        {
            return Err(NegotiationError::ZeroLimit);
        }
        if self.max_regions_per_batch > HARD_MAX_REGIONS_PER_BATCH
            || self.max_region_bytes > HARD_MAX_REGION_BYTES
            || self.max_batch_bytes > HARD_MAX_BATCH_BYTES
            || self.max_active_regions > HARD_MAX_ACTIVE_REGIONS
            || self.max_active_bytes > HARD_MAX_ACTIVE_BYTES
            || self.max_transactions > HARD_MAX_TRANSACTIONS
            || self.max_bootstrap_payload_bytes > HARD_MAX_BOOTSTRAP_PAYLOAD_BYTES
            || self.max_control_payload_bytes > HARD_MAX_CONTROL_PAYLOAD_BYTES
        {
            return Err(NegotiationError::AboveHardMaximum);
        }
        if self.max_region_bytes > native_usize_max
            || self.max_batch_bytes > native_usize_max
            || self.max_active_bytes > native_usize_max
            || u64::from(self.max_bootstrap_payload_bytes) > native_usize_max
            || u64::from(self.max_control_payload_bytes) > native_usize_max
        {
            return Err(NegotiationError::NativeSizeNarrowing);
        }
        Ok(self)
    }

    /// Computes checked effective minima after validating both offers.
    pub fn negotiate(local: Self, peer: Self) -> Result<Self, NegotiationError> {
        let local = local.validate()?;
        let peer = peer.validate()?;
        Self {
            max_regions_per_batch: local.max_regions_per_batch.min(peer.max_regions_per_batch),
            max_region_bytes: local.max_region_bytes.min(peer.max_region_bytes),
            max_batch_bytes: local.max_batch_bytes.min(peer.max_batch_bytes),
            max_active_regions: local.max_active_regions.min(peer.max_active_regions),
            max_active_bytes: local.max_active_bytes.min(peer.max_active_bytes),
            max_transactions: local.max_transactions.min(peer.max_transactions),
            max_bootstrap_payload_bytes: local
                .max_bootstrap_payload_bytes
                .min(peer.max_bootstrap_payload_bytes),
            max_control_payload_bytes: local
                .max_control_payload_bytes
                .min(peer.max_control_payload_bytes),
        }
        .validate()
    }
}

/// Cross-process atomic and layout alignment facts for the selected target.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AtomicCapabilities {
    atomic_u32_lock_free: bool,
    atomic_u32_alignment: usize,
    atomic_u64_lock_free: bool,
    atomic_u64_alignment: usize,
    page_alignment: usize,
    cache_line_alignment: usize,
}

impl AtomicCapabilities {
    pub(crate) const fn from_accepted_offer(value: crate::negotiation::AtomicOffer) -> Self {
        Self {
            atomic_u32_lock_free: value.u32_lock_free,
            atomic_u32_alignment: value.u32_alignment as usize,
            atomic_u64_lock_free: value.u64_lock_free,
            atomic_u64_alignment: value.u64_alignment as usize,
            page_alignment: value.page_alignment as usize,
            cache_line_alignment: value.cache_line_alignment as usize,
        }
    }

    /// Constructs facts only after private native discovery has established
    /// lock freedom and runtime page/cache-line alignment.
    #[allow(dead_code, reason = "wired into native HELLO discovery in phase 4b")]
    pub(crate) fn from_verified_native(
        page_alignment: usize,
        cache_line_alignment: usize,
        atomic_u32_lock_free: bool,
        atomic_u64_lock_free: bool,
    ) -> Result<Self, NegotiationError> {
        let atomic_u32_alignment = core::mem::align_of::<core::sync::atomic::AtomicU32>();
        let atomic_u64_alignment = core::mem::align_of::<core::sync::atomic::AtomicU64>();
        if !page_alignment.is_power_of_two()
            || !cache_line_alignment.is_power_of_two()
            || page_alignment < atomic_u32_alignment.max(atomic_u64_alignment)
            || cache_line_alignment < atomic_u32_alignment.max(atomic_u64_alignment)
        {
            return Err(NegotiationError::AtomicUnsupported);
        }
        Ok(Self {
            atomic_u32_lock_free,
            atomic_u32_alignment,
            atomic_u64_lock_free,
            atomic_u64_alignment,
            page_alignment,
            cache_line_alignment,
        })
    }

    /// Whether private target discovery established lock-free 32-bit atomics.
    pub fn atomic_u32_lock_free(self) -> bool {
        self.atomic_u32_lock_free
    }

    /// Required alignment for an atomic 32-bit value.
    pub fn atomic_u32_alignment(self) -> usize {
        self.atomic_u32_alignment
    }

    /// Whether private target discovery established lock-free 64-bit atomics.
    pub fn atomic_u64_lock_free(self) -> bool {
        self.atomic_u64_lock_free
    }

    /// Required alignment for an atomic 64-bit value.
    pub fn atomic_u64_alignment(self) -> usize {
        self.atomic_u64_alignment
    }

    /// Runtime native page alignment.
    pub fn page_alignment(self) -> usize {
        self.page_alignment
    }

    /// Runtime native cache-line alignment used by application layouts.
    pub fn cache_line_alignment(self) -> usize {
        self.cache_line_alignment
    }

    /// Rejects negotiation if required widths are unavailable.
    #[allow(dead_code, reason = "wired into native HELLO negotiation in phase 4b")]
    pub(crate) fn require(
        self,
        u32_required: bool,
        u64_required: bool,
    ) -> Result<Self, NegotiationError> {
        if (u32_required && !self.atomic_u32_lock_free)
            || (u64_required && !self.atomic_u64_lock_free)
        {
            return Err(NegotiationError::AtomicUnsupported);
        }
        Ok(self)
    }
}

/// One monotonic absolute deadline shared by a complete operation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AbsoluteDeadline(Instant);

impl AbsoluteDeadline {
    /// Derives a deadline once at operation entry.
    pub fn after(duration: Duration) -> Result<Self, NegotiationError> {
        if duration.is_zero() {
            return Err(NegotiationError::InvalidDeadline);
        }
        Instant::now()
            .checked_add(duration)
            .map(Self)
            .ok_or(NegotiationError::InvalidDeadline)
    }

    /// Returns the remaining duration, or zero after expiry.
    pub fn remaining(self) -> Duration {
        self.0.saturating_duration_since(Instant::now())
    }

    /// Whether the absolute deadline has expired.
    pub fn is_expired(self) -> bool {
        self.remaining().is_zero()
    }
}

#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
impl<Role, State> Session<Role, State> {
    fn from_inner(inner: SessionInner) -> Self {
        Self {
            inner,
            role: PhantomData,
            state: PhantomData,
            not_sync: PhantomData,
        }
    }
}

impl Session<Coordinator, Negotiating> {
    /// Spawns and authenticates the selected helper under the target's
    /// documented executable-identity policy through both HELLOs.
    pub fn spawn(command: SessionCommand, options: SessionOptions) -> Result<Self, SessionFailure> {
        validate_public_options(&options).map_err(|reason| {
            SessionFailure::new(
                SessionOperation::Spawn,
                SessionTransactionState::NotEstablished,
                reason,
            )
        })?;
        if command.has_reserved_environment() {
            return Err(SessionFailure::new(
                SessionOperation::Spawn,
                SessionTransactionState::NotEstablished,
                SessionError::InvalidInput,
            ));
        }
        #[cfg(target_os = "linux")]
        {
            let inner =
                crate::backend::linux_vnext::spawn::LinuxCoordinatorNegotiatingSession::spawn(
                    &command, &options,
                )
                .map_err(|failure| {
                    let native_code = linux_public_native_code(failure.error);
                    let transaction_state = match failure.state {
                        crate::backend::linux_vnext::spawn::LinuxCoordinatorFailureState::NotEstablished => {
                            SessionTransactionState::NotEstablished
                        }
                        crate::backend::linux_vnext::spawn::LinuxCoordinatorFailureState::Spawned => {
                            SessionTransactionState::Spawned
                        }
                        crate::backend::linux_vnext::spawn::LinuxCoordinatorFailureState::Negotiating => {
                            SessionTransactionState::Negotiating
                        }
                    };
                    SessionFailure::new(
                        SessionOperation::Spawn,
                        transaction_state,
                        failure.error.into(),
                    )
                    .with_native_code(native_code)
                    .with_poisoned(failure.poisoned)
                    .with_optional_cleanup(failure.cleanup)
                })?;
            Ok(Self::from_inner(SessionInner::CoordinatorNegotiating(
                inner,
            )))
        }
        #[cfg(target_os = "macos")]
        {
            let inner =
                crate::backend::macos::vnext_session::MacCoordinatorNegotiatingSession::spawn(
                    &command, &options,
                )
                .map_err(|failure| {
                    let transaction_state = match failure.state {
                        crate::backend::macos::vnext_session::MacCoordinatorFailureState::NotEstablished => {
                            SessionTransactionState::NotEstablished
                        }
                        crate::backend::macos::vnext_session::MacCoordinatorFailureState::Spawned => {
                            SessionTransactionState::Spawned
                        }
                        crate::backend::macos::vnext_session::MacCoordinatorFailureState::Negotiating => {
                            SessionTransactionState::Negotiating
                        }
                    };
                    mac_session_failure(
                        SessionOperation::Spawn,
                        transaction_state,
                        failure.error,
                        failure.poisoned,
                    )
                    .with_optional_cleanup(failure.cleanup)
                })?;
            Ok(Self::from_inner(SessionInner::CoordinatorNegotiating(
                inner,
            )))
        }
        #[cfg(target_os = "windows")]
        {
            let inner = crate::backend::windows::vnext_session::WindowsCoordinatorNegotiatingSession::spawn(
                &command,
                &options,
            )
            .map_err(|failure| {
                let transaction_state = match failure.state {
                    crate::backend::windows::vnext_session::WindowsCoordinatorFailureState::NotEstablished => SessionTransactionState::NotEstablished,
                    crate::backend::windows::vnext_session::WindowsCoordinatorFailureState::Spawned => SessionTransactionState::Spawned,
                    crate::backend::windows::vnext_session::WindowsCoordinatorFailureState::Negotiating => SessionTransactionState::Negotiating,
                };
                windows_session_failure(
                    SessionOperation::Spawn,
                    transaction_state,
                    failure.error,
                    failure.poisoned,
                )
                .with_optional_cleanup(failure.cleanup)
            })?;
            Ok(Self::from_inner(SessionInner::CoordinatorNegotiating(
                Box::new(inner),
            )))
        }
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        {
            let _ = command;
            Err(SessionFailure::new(
                SessionOperation::Spawn,
                SessionTransactionState::NotEstablished,
                SessionError::BackendUnavailable,
            ))
        }
    }

    /// Peer HELLO application payload, available before the coordinator decides.
    pub fn peer_application_payload(&self) -> &[u8] {
        match &self.inner {
            #[cfg(target_os = "linux")]
            SessionInner::CoordinatorNegotiating(inner) => inner.peer_application_payload(),
            #[cfg(target_os = "macos")]
            SessionInner::CoordinatorNegotiating(inner) => inner.peer_application_payload(),
            #[cfg(target_os = "windows")]
            SessionInner::CoordinatorNegotiating(inner) => inner.peer_application_payload(),
            #[cfg(target_os = "linux")]
            _ => unreachable!("coordinator negotiating typestate owns its exact backend state"),
            #[cfg(target_os = "macos")]
            _ => unreachable!("coordinator negotiating typestate owns its exact backend state"),
            #[cfg(target_os = "windows")]
            _ => unreachable!("coordinator negotiating typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }

    /// Makes the explicit coordinator decision and awaits the receiver decision.
    pub fn decide(
        self,
        decision: NegotiationDecision,
    ) -> Result<NegotiationOutcome<Session<Coordinator, Ready>>, SessionFailure> {
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        let _ = decision;
        match self.inner {
            #[cfg(target_os = "linux")]
            SessionInner::CoordinatorNegotiating(inner) => {
                let outcome = inner
                    .decide(decision_rejection(decision))
                    .map_err(|failure| {
                        let native_code = linux_public_native_code(failure.error);
                        SessionFailure::new(
                            SessionOperation::Negotiate,
                            SessionTransactionState::Negotiating,
                            failure.error.into(),
                        )
                        .with_native_code(native_code)
                        .with_poisoned(failure.poisoned)
                        .with_optional_cleanup(failure.cleanup)
                    })?;
                map_linux_coordinator_outcome(outcome)
            }
            #[cfg(target_os = "macos")]
            SessionInner::CoordinatorNegotiating(inner) => {
                let outcome = inner
                    .decide(decision_rejection(decision))
                    .map_err(|failure| {
                        mac_session_failure(
                            SessionOperation::Negotiate,
                            SessionTransactionState::Negotiating,
                            failure.error,
                            failure.poisoned,
                        )
                        .with_optional_cleanup(failure.cleanup)
                    })?;
                map_mac_coordinator_outcome(outcome)
            }
            #[cfg(target_os = "windows")]
            SessionInner::CoordinatorNegotiating(inner) => {
                let outcome = (*inner)
                    .decide(decision_rejection(decision))
                    .map_err(|failure| {
                        windows_session_failure(
                            SessionOperation::Negotiate,
                            SessionTransactionState::Negotiating,
                            failure.error,
                            failure.poisoned,
                        )
                        .with_optional_cleanup(failure.cleanup)
                    })?;
                map_windows_coordinator_outcome(outcome)
            }
            #[cfg(target_os = "linux")]
            _ => unreachable!("coordinator negotiating typestate owns its exact backend state"),
            #[cfg(target_os = "macos")]
            _ => unreachable!("coordinator negotiating typestate owns its exact backend state"),
            #[cfg(target_os = "windows")]
            _ => unreachable!("coordinator negotiating typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }
}

impl Session<Receiver, Negotiating> {
    /// Consumes the unique process-entry bootstrap and exchanges HELLOs.
    pub fn from_bootstrap(
        bootstrap: ReceiverBootstrap,
        options: SessionOptions,
    ) -> Result<Self, SessionFailure> {
        validate_public_options(&options).map_err(|reason| {
            SessionFailure::new(
                SessionOperation::Bootstrap,
                SessionTransactionState::NotEstablished,
                reason,
            )
        })?;
        #[cfg(target_os = "linux")]
        {
            let inner = crate::backend::linux_vnext::spawn::LinuxReceiverNegotiatingSession::from_inherited_bootstrap(
                bootstrap.inherited,
                options.limits,
                options.application_payload,
                options.require_atomic_u32,
                options.require_atomic_u64,
                options.deadline,
            )
            .map_err(|error| {
                SessionFailure::new(
                    SessionOperation::Bootstrap,
                    SessionTransactionState::Negotiating,
                    error.into(),
                )
                .with_native_code(linux_public_native_code(error))
                .with_poisoned(true)
            })?;
            Ok(Self::from_inner(SessionInner::ReceiverNegotiating(inner)))
        }
        #[cfg(target_os = "macos")]
        {
            let _bootstrap = bootstrap;
            let inner =
                crate::backend::macos::vnext_session::MacReceiverNegotiatingSession::from_environment(
                    options.limits,
                    options.application_payload,
                    options.require_atomic_u32,
                    options.require_atomic_u64,
                    options.deadline,
                )
                .map_err(|error| {
                    // Parity: an absent bootstrap designation or invalid
                    // caller input means no peer exists and nothing was
                    // negotiated, matching the Linux mapping.
                    let invalid_input = matches!(
                        error,
                        crate::backend::macos::vnext_session::MacPublicSessionError::InvalidInput
                    );
                    let state = if invalid_input {
                        SessionTransactionState::NotEstablished
                    } else {
                        SessionTransactionState::Negotiating
                    };
                    mac_session_failure(
                        SessionOperation::Bootstrap,
                        state,
                        error,
                        !invalid_input,
                    )
                })?;
            Ok(Self::from_inner(SessionInner::ReceiverNegotiating(inner)))
        }
        #[cfg(target_os = "windows")]
        {
            let _bootstrap = bootstrap;
            let inner = crate::backend::windows::vnext_session::WindowsReceiverNegotiatingSession::from_environment(&options)
            .map_err(|error| {
                // Parity: an absent bootstrap designation or invalid caller
                // input means no peer exists and nothing was negotiated,
                // matching the Linux mapping.
                let invalid_input = matches!(
                    error,
                    crate::backend::windows::vnext_session::WindowsPublicSessionError::InvalidInput
                );
                let state = if invalid_input {
                    SessionTransactionState::NotEstablished
                } else {
                    SessionTransactionState::Negotiating
                };
                windows_session_failure(
                    SessionOperation::Bootstrap,
                    state,
                    error,
                    !invalid_input,
                )
            })?;
            Ok(Self::from_inner(SessionInner::ReceiverNegotiating(
                Box::new(inner),
            )))
        }
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        {
            let _ = bootstrap;
            Err(SessionFailure::new(
                SessionOperation::Bootstrap,
                SessionTransactionState::NotEstablished,
                SessionError::BackendUnavailable,
            ))
        }
    }

    /// Peer HELLO application payload, available before awaiting the decision.
    pub fn peer_application_payload(&self) -> &[u8] {
        match &self.inner {
            #[cfg(target_os = "linux")]
            SessionInner::ReceiverNegotiating(inner) => inner.peer_application_payload(),
            #[cfg(target_os = "macos")]
            SessionInner::ReceiverNegotiating(inner) => inner.peer_application_payload(),
            #[cfg(target_os = "windows")]
            SessionInner::ReceiverNegotiating(inner) => inner.peer_application_payload(),
            #[cfg(target_os = "linux")]
            _ => unreachable!("receiver negotiating typestate owns its exact backend state"),
            #[cfg(target_os = "macos")]
            _ => unreachable!("receiver negotiating typestate owns its exact backend state"),
            #[cfg(target_os = "windows")]
            _ => unreachable!("receiver negotiating typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }

    /// Awaits exact coordinator ACCEPT before invoking the receiver decision.
    pub fn decide_after_coordinator(
        self,
        decide: impl FnOnce(&[u8]) -> NegotiationDecision,
    ) -> Result<NegotiationOutcome<Session<Receiver, Ready>>, SessionFailure> {
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        let _ = decide;
        match self.inner {
            #[cfg(target_os = "linux")]
            SessionInner::ReceiverNegotiating(inner) => {
                let outcome = inner
                    .decide_after_coordinator(|payload| decision_rejection(decide(payload)))
                    .map_err(|error| {
                        SessionFailure::new(
                            SessionOperation::Negotiate,
                            SessionTransactionState::Negotiating,
                            error.into(),
                        )
                        .with_native_code(linux_public_native_code(error))
                        .with_poisoned(true)
                    })?;
                map_linux_receiver_outcome(outcome)
            }
            #[cfg(target_os = "macos")]
            SessionInner::ReceiverNegotiating(inner) => {
                let outcome = inner
                    .decide_after_coordinator(|payload| decision_rejection(decide(payload)))
                    .map_err(|error| {
                        mac_session_failure(
                            SessionOperation::Negotiate,
                            SessionTransactionState::Negotiating,
                            error,
                            true,
                        )
                    })?;
                map_mac_receiver_outcome(outcome)
            }
            #[cfg(target_os = "windows")]
            SessionInner::ReceiverNegotiating(inner) => {
                let outcome = (*inner)
                    .decide_after_coordinator(|payload| decision_rejection(decide(payload)))
                    .map_err(|error| {
                        windows_session_failure(
                            SessionOperation::Negotiate,
                            SessionTransactionState::Negotiating,
                            error,
                            true,
                        )
                    })?;
                map_windows_receiver_outcome(outcome)
            }
            #[cfg(target_os = "linux")]
            _ => unreachable!("receiver negotiating typestate owns its exact backend state"),
            #[cfg(target_os = "macos")]
            _ => unreachable!("receiver negotiating typestate owns its exact backend state"),
            #[cfg(target_os = "windows")]
            _ => unreachable!("receiver negotiating typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }
}

impl Session<Coordinator, Ready> {
    #[cfg(all(test, target_os = "linux"))]
    pub(crate) fn fail_next_cleanup_signal_for_test(&self, code: i32) {
        match &self.inner {
            SessionInner::CoordinatorReady(inner) => {
                inner.fail_next_cleanup_signal_for_test(code);
            }
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
        }
    }

    /// Effective finite limits bound into the accepted transcript.
    pub fn negotiated_limits(&self) -> SessionLimits {
        match &self.inner {
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            SessionInner::CoordinatorReady(inner) => inner.limits(),
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }

    /// Effective lock-free atomic and layout alignment facts bound into ACCEPT.
    pub fn atomic_capabilities(&self) -> AtomicCapabilities {
        match &self.inner {
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            SessionInner::CoordinatorReady(inner) => inner.atomics(),
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }

    /// Accepted protocol version from the exact challenged transcript.
    pub fn protocol_version(&self) -> ProtocolVersion {
        match &self.inner {
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            SessionInner::CoordinatorReady(inner) => inner.protocol_version(),
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }

    /// Current local reducer/liveness state.
    pub fn state(&self) -> SessionState {
        match &self.inner {
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            SessionInner::CoordinatorReady(inner) => inner.state(),
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }

    /// Bounded current active-mapping lease counters.
    pub fn active_leases(&self) -> ActiveLeaseFacts {
        match &self.inner {
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            SessionInner::CoordinatorReady(inner) => inner.active_leases(),
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }

    /// Performs one nonblocking authenticated peer observation.
    pub fn poll_peer(&mut self) -> Result<PeerStatus, SessionFailure> {
        match &mut self.inner {
            #[cfg(target_os = "linux")]
            SessionInner::CoordinatorReady(inner) => {
                let result = inner.poll_peer();
                let state = inner.state();
                result
                    .map_err(|error| linux_ready_failure(SessionOperation::PollPeer, state, error))
            }
            #[cfg(target_os = "macos")]
            SessionInner::CoordinatorReady(inner) => {
                let result = inner.poll_peer();
                let state = inner.state();
                result.map_err(|error| mac_ready_failure(SessionOperation::PollPeer, state, error))
            }
            #[cfg(target_os = "windows")]
            SessionInner::CoordinatorReady(inner) => {
                let result = inner.poll_peer();
                let state = inner.state();
                result.map_err(|error| {
                    windows_ready_failure(SessionOperation::PollPeer, state, error)
                })
            }
            #[cfg(target_os = "linux")]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(target_os = "macos")]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(target_os = "windows")]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => Err(SessionFailure::new(
                SessionOperation::PollPeer,
                SessionTransactionState::NotEstablished,
                SessionError::BackendUnavailable,
            )),
        }
    }

    /// Boundedly waits for and reaps the exact direct child without consuming the session.
    pub fn wait_for_exit(&mut self, deadline: AbsoluteDeadline) -> ChildCleanupFacts {
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        let _ = deadline;
        match &mut self.inner {
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            SessionInner::CoordinatorReady(inner) => inner.wait_for_exit(deadline),
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                ChildCleanupFacts::new(None, DescendantCleanupStatus::NotEstablished, None)
            }
        }
    }

    /// Gracefully closes only after active leases are gone and the exact child is reaped.
    pub fn try_close(mut self, deadline: AbsoluteDeadline) -> CoordinatorCloseOutcome {
        let facts = self.active_leases();
        if !facts.is_empty() {
            return CoordinatorCloseOutcome::ActiveLeases {
                session: self,
                facts,
            };
        }
        let cleanup = self.wait_for_exit(deadline);
        if !cleanup.direct_child_complete() {
            let reason = if cleanup.native_error().is_some() {
                SessionError::Native
            } else {
                SessionError::DeadlineExpired
            };
            let failure = SessionFailure::new(
                SessionOperation::Close,
                if self.state() == SessionState::Poisoned {
                    SessionTransactionState::Poisoned
                } else {
                    SessionTransactionState::Ready
                },
                reason,
            )
            .with_native_code(cleanup.native_error())
            .with_poisoned(self.state() == SessionState::Poisoned)
            .with_cleanup(cleanup);
            return CoordinatorCloseOutcome::CleanupPending {
                session: self,
                facts: cleanup,
                failure,
            };
        }
        let close: Result<(), SessionFailure> = match &mut self.inner {
            #[cfg(target_os = "linux")]
            SessionInner::CoordinatorReady(inner) => {
                let result = inner.close_resources();
                let state = inner.state();
                result.map_err(|error| {
                    linux_ready_failure(SessionOperation::Close, state, error).with_cleanup(cleanup)
                })
            }
            #[cfg(target_os = "macos")]
            SessionInner::CoordinatorReady(inner) => {
                let result = inner.close_resources();
                let state = inner.state();
                result.map_err(|error| {
                    mac_ready_failure(SessionOperation::Close, state, error).with_cleanup(cleanup)
                })
            }
            #[cfg(target_os = "windows")]
            SessionInner::CoordinatorReady(inner) => {
                let result = inner.close_resources();
                let state = inner.state();
                result.map_err(|error| {
                    windows_ready_failure(SessionOperation::Close, state, error)
                        .with_cleanup(cleanup)
                })
            }
            #[cfg(target_os = "linux")]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(target_os = "macos")]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(target_os = "windows")]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => Err(SessionFailure::new(
                SessionOperation::Close,
                SessionTransactionState::NotEstablished,
                SessionError::BackendUnavailable,
            )
            .with_cleanup(cleanup)),
        };
        if let Err(error) = close {
            return CoordinatorCloseOutcome::Failed {
                session: self,
                error,
            };
        }
        CoordinatorCloseOutcome::Closed(cleanup)
    }

    /// Terminally poisons live mappings, terminates the exact child, and returns cleanup facts.
    pub fn abort(mut self, deadline: AbsoluteDeadline) -> CoordinatorAbortOutcome {
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        let _ = deadline;
        let cleanup = match &mut self.inner {
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            SessionInner::CoordinatorReady(inner) => inner.abort(deadline),
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                ChildCleanupFacts::new(None, DescendantCleanupStatus::NotEstablished, None)
            }
        };
        let failure = if cleanup.direct_child_complete() {
            None
        } else {
            let reason = if cleanup.native_error().is_some() {
                SessionError::Native
            } else {
                SessionError::DeadlineExpired
            };
            Some(
                SessionFailure::new(
                    SessionOperation::Abort,
                    SessionTransactionState::Poisoned,
                    reason,
                )
                .with_native_code(cleanup.native_error())
                .with_poisoned(true)
                .with_cleanup(cleanup),
            )
        };
        CoordinatorAbortOutcome { cleanup, failure }
    }

    /// Starts a local batch builder bounded by this accepted session.
    pub fn new_transfer_batch(&self) -> Result<TransferBatch, BatchError> {
        let limits = self.negotiated_limits();
        TransferBatch::new(
            limits.max_regions_per_batch,
            limits.max_region_bytes,
            limits.max_batch_bytes,
        )
    }

    /// Completes one atomic capability transaction and activates its full set.
    pub fn transfer_batch(
        &mut self,
        batch: TransferBatch,
        deadline: AbsoluteDeadline,
    ) -> Result<ActiveRegionSet, SessionFailure> {
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        let _ = (batch, deadline);
        match &mut self.inner {
            #[cfg(target_os = "linux")]
            SessionInner::CoordinatorReady(inner) => {
                let result = inner.transfer_batch(batch, deadline);
                let state = inner.state();
                result.map_err(|error| {
                    linux_ready_batch_failure(SessionOperation::TransferBatch, state, error)
                })
            }
            #[cfg(target_os = "macos")]
            SessionInner::CoordinatorReady(inner) => {
                let result = inner.transfer_batch(batch, deadline);
                let state = inner.state();
                result.map_err(|error| {
                    mac_ready_failure(SessionOperation::TransferBatch, state, error)
                })
            }
            #[cfg(target_os = "windows")]
            SessionInner::CoordinatorReady(inner) => {
                let result = inner.transfer_batch(batch, deadline);
                let state = inner.state();
                result.map_err(|error| {
                    windows_ready_failure(SessionOperation::TransferBatch, state, error)
                })
            }
            #[cfg(target_os = "linux")]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(target_os = "macos")]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(target_os = "windows")]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }

    /// Sends one bounded opaque application record under the supplied deadline.
    pub fn send_control(
        &mut self,
        kind: u32,
        payload: &[u8],
        deadline: AbsoluteDeadline,
    ) -> Result<(), SessionFailure> {
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        let _ = (kind, payload, deadline);
        match &mut self.inner {
            #[cfg(target_os = "linux")]
            SessionInner::CoordinatorReady(inner) => {
                let result = inner.send_control(kind, payload, deadline);
                let state = inner.state();
                result.map_err(|error| {
                    linux_ready_failure(SessionOperation::SendControl, state, error)
                })
            }
            #[cfg(target_os = "macos")]
            SessionInner::CoordinatorReady(inner) => {
                let result = inner.send_control(kind, payload, deadline);
                let state = inner.state();
                result
                    .map_err(|error| mac_ready_failure(SessionOperation::SendControl, state, error))
            }
            #[cfg(target_os = "windows")]
            SessionInner::CoordinatorReady(inner) => {
                let result = inner.send_control(kind, payload, deadline);
                let state = inner.state();
                result.map_err(|error| {
                    windows_ready_failure(SessionOperation::SendControl, state, error)
                })
            }
            #[cfg(target_os = "linux")]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(target_os = "macos")]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(target_os = "windows")]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }

    /// Receives one bounded opaque peer record under the supplied deadline.
    pub fn receive_control(
        &mut self,
        deadline: AbsoluteDeadline,
    ) -> Result<ControlFrame, SessionFailure> {
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        let _ = deadline;
        match &mut self.inner {
            #[cfg(target_os = "linux")]
            SessionInner::CoordinatorReady(inner) => {
                let result = inner.receive_control(deadline);
                let state = inner.state();
                result.map_err(|error| {
                    linux_ready_failure(SessionOperation::ReceiveControl, state, error)
                })
            }
            #[cfg(target_os = "macos")]
            SessionInner::CoordinatorReady(inner) => {
                let result = inner.receive_control(deadline);
                let state = inner.state();
                result.map_err(|error| {
                    mac_ready_failure(SessionOperation::ReceiveControl, state, error)
                })
            }
            #[cfg(target_os = "windows")]
            SessionInner::CoordinatorReady(inner) => {
                let result = inner.receive_control(deadline);
                let state = inner.state();
                result.map_err(|error| {
                    windows_ready_failure(SessionOperation::ReceiveControl, state, error)
                })
            }
            #[cfg(target_os = "linux")]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(target_os = "macos")]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(target_os = "windows")]
            _ => unreachable!("coordinator ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }
}

impl Session<Receiver, Ready> {
    /// Effective finite limits bound into the accepted transcript.
    pub fn negotiated_limits(&self) -> SessionLimits {
        match &self.inner {
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            SessionInner::ReceiverReady(inner) => inner.limits(),
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }

    /// Effective lock-free atomic and layout alignment facts bound into ACCEPT.
    pub fn atomic_capabilities(&self) -> AtomicCapabilities {
        match &self.inner {
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            SessionInner::ReceiverReady(inner) => inner.atomics(),
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }

    /// Accepted protocol version from the exact challenged transcript.
    pub fn protocol_version(&self) -> ProtocolVersion {
        match &self.inner {
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            SessionInner::ReceiverReady(inner) => inner.protocol_version(),
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }

    /// Current local reducer/liveness state.
    pub fn state(&self) -> SessionState {
        match &self.inner {
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            SessionInner::ReceiverReady(inner) => inner.state(),
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }

    /// Bounded current active-mapping lease counters.
    pub fn active_leases(&self) -> ActiveLeaseFacts {
        match &self.inner {
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            SessionInner::ReceiverReady(inner) => inner.active_leases(),
            #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }

    /// Performs one nonblocking authenticated peer observation.
    pub fn poll_peer(&mut self) -> Result<PeerStatus, SessionFailure> {
        match &mut self.inner {
            #[cfg(target_os = "linux")]
            SessionInner::ReceiverReady(inner) => {
                let result = inner.poll_peer();
                let state = inner.state();
                result
                    .map_err(|error| linux_ready_failure(SessionOperation::PollPeer, state, error))
            }
            #[cfg(target_os = "macos")]
            SessionInner::ReceiverReady(inner) => {
                let result = inner.poll_peer();
                let state = inner.state();
                result.map_err(|error| mac_ready_failure(SessionOperation::PollPeer, state, error))
            }
            #[cfg(target_os = "windows")]
            SessionInner::ReceiverReady(inner) => {
                let result = inner.poll_peer();
                let state = inner.state();
                result.map_err(|error| {
                    windows_ready_failure(SessionOperation::PollPeer, state, error)
                })
            }
            #[cfg(target_os = "linux")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(target_os = "macos")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(target_os = "windows")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => Err(SessionFailure::new(
                SessionOperation::PollPeer,
                SessionTransactionState::NotEstablished,
                SessionError::BackendUnavailable,
            )),
        }
    }

    /// Boundedly waits for authenticated peer endpoint closure under one deadline.
    pub fn wait_for_exit(
        &mut self,
        deadline: AbsoluteDeadline,
    ) -> Result<PeerStatus, SessionFailure> {
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        let _ = deadline;
        match &mut self.inner {
            #[cfg(target_os = "linux")]
            SessionInner::ReceiverReady(inner) => {
                let result = inner.wait_for_exit(deadline);
                let state = inner.state();
                result.map_err(|error| {
                    linux_ready_failure(SessionOperation::WaitForExit, state, error)
                })
            }
            #[cfg(target_os = "macos")]
            SessionInner::ReceiverReady(inner) => {
                let result = inner.wait_for_exit(deadline);
                let state = inner.state();
                result
                    .map_err(|error| mac_ready_failure(SessionOperation::WaitForExit, state, error))
            }
            #[cfg(target_os = "windows")]
            SessionInner::ReceiverReady(inner) => {
                let result = inner.wait_for_exit(deadline);
                let state = inner.state();
                result.map_err(|error| {
                    windows_ready_failure(SessionOperation::WaitForExit, state, error)
                })
            }
            #[cfg(target_os = "linux")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(target_os = "macos")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(target_os = "windows")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => Err(SessionFailure::new(
                SessionOperation::WaitForExit,
                SessionTransactionState::NotEstablished,
                SessionError::BackendUnavailable,
            )),
        }
    }

    /// Closes the inherited endpoint only after every active mapping lease is gone.
    pub fn try_close(mut self) -> ReceiverCloseOutcome {
        let facts = self.active_leases();
        if !facts.is_empty() {
            return ReceiverCloseOutcome::ActiveLeases {
                session: self,
                facts,
            };
        }
        let close: Result<(), SessionFailure> = match &mut self.inner {
            #[cfg(target_os = "linux")]
            SessionInner::ReceiverReady(inner) => {
                let result = inner.close_resources();
                let state = inner.state();
                result.map_err(|error| linux_ready_failure(SessionOperation::Close, state, error))
            }
            #[cfg(target_os = "macos")]
            SessionInner::ReceiverReady(inner) => {
                let result = inner.close_resources();
                let state = inner.state();
                result.map_err(|error| mac_ready_failure(SessionOperation::Close, state, error))
            }
            #[cfg(target_os = "windows")]
            SessionInner::ReceiverReady(inner) => {
                let result = inner.close_resources();
                let state = inner.state();
                result.map_err(|error| windows_ready_failure(SessionOperation::Close, state, error))
            }
            #[cfg(target_os = "linux")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(target_os = "macos")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(target_os = "windows")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => Err(SessionFailure::new(
                SessionOperation::Close,
                SessionTransactionState::NotEstablished,
                SessionError::BackendUnavailable,
            )),
        };
        if let Err(error) = close {
            return ReceiverCloseOutcome::Failed {
                session: self,
                error,
            };
        }
        ReceiverCloseOutcome::Closed
    }

    /// Terminally poisons every live mapping and closes the inherited endpoint.
    pub fn abort(mut self) {
        match &mut self.inner {
            #[cfg(target_os = "linux")]
            SessionInner::ReceiverReady(inner) => inner.abort(),
            #[cfg(target_os = "macos")]
            SessionInner::ReceiverReady(inner) => inner.abort(),
            #[cfg(target_os = "windows")]
            SessionInner::ReceiverReady(inner) => inner.abort(),
            #[cfg(target_os = "linux")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(target_os = "macos")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(target_os = "windows")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {}
        }
    }

    /// Receives, validates, commits, and activates one exact expected batch.
    pub fn receive_batch(
        &mut self,
        expected: ExpectedBatch,
        deadline: AbsoluteDeadline,
    ) -> Result<ActiveRegionSet, SessionFailure> {
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        let _ = (expected, deadline);
        match &mut self.inner {
            #[cfg(target_os = "linux")]
            SessionInner::ReceiverReady(inner) => {
                let result = inner.receive_batch(expected, deadline);
                let state = inner.state();
                result.map_err(|error| {
                    linux_ready_batch_failure(SessionOperation::ReceiveBatch, state, error)
                })
            }
            #[cfg(target_os = "macos")]
            SessionInner::ReceiverReady(inner) => {
                let result = inner.receive_batch(expected, deadline);
                let state = inner.state();
                result.map_err(|error| {
                    mac_ready_failure(SessionOperation::ReceiveBatch, state, error)
                })
            }
            #[cfg(target_os = "windows")]
            SessionInner::ReceiverReady(inner) => {
                let result = inner.receive_batch(expected, deadline);
                let state = inner.state();
                result.map_err(|error| {
                    windows_ready_failure(SessionOperation::ReceiveBatch, state, error)
                })
            }
            #[cfg(target_os = "linux")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(target_os = "macos")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(target_os = "windows")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }

    /// Sends one bounded opaque application record under the supplied deadline.
    pub fn send_control(
        &mut self,
        kind: u32,
        payload: &[u8],
        deadline: AbsoluteDeadline,
    ) -> Result<(), SessionFailure> {
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        let _ = (kind, payload, deadline);
        match &mut self.inner {
            #[cfg(target_os = "linux")]
            SessionInner::ReceiverReady(inner) => {
                let result = inner.send_control(kind, payload, deadline);
                let state = inner.state();
                result.map_err(|error| {
                    linux_ready_failure(SessionOperation::SendControl, state, error)
                })
            }
            #[cfg(target_os = "macos")]
            SessionInner::ReceiverReady(inner) => {
                let result = inner.send_control(kind, payload, deadline);
                let state = inner.state();
                result
                    .map_err(|error| mac_ready_failure(SessionOperation::SendControl, state, error))
            }
            #[cfg(target_os = "windows")]
            SessionInner::ReceiverReady(inner) => {
                let result = inner.send_control(kind, payload, deadline);
                let state = inner.state();
                result.map_err(|error| {
                    windows_ready_failure(SessionOperation::SendControl, state, error)
                })
            }
            #[cfg(target_os = "linux")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(target_os = "macos")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(target_os = "windows")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }

    /// Receives one bounded opaque peer record under the supplied deadline.
    pub fn receive_control(
        &mut self,
        deadline: AbsoluteDeadline,
    ) -> Result<ControlFrame, SessionFailure> {
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        let _ = deadline;
        match &mut self.inner {
            #[cfg(target_os = "linux")]
            SessionInner::ReceiverReady(inner) => {
                let result = inner.receive_control(deadline);
                let state = inner.state();
                result.map_err(|error| {
                    linux_ready_failure(SessionOperation::ReceiveControl, state, error)
                })
            }
            #[cfg(target_os = "macos")]
            SessionInner::ReceiverReady(inner) => {
                let result = inner.receive_control(deadline);
                let state = inner.state();
                result.map_err(|error| {
                    mac_ready_failure(SessionOperation::ReceiveControl, state, error)
                })
            }
            #[cfg(target_os = "windows")]
            SessionInner::ReceiverReady(inner) => {
                let result = inner.receive_control(deadline);
                let state = inner.state();
                result.map_err(|error| {
                    windows_ready_failure(SessionOperation::ReceiveControl, state, error)
                })
            }
            #[cfg(target_os = "linux")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(target_os = "macos")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(target_os = "windows")]
            _ => unreachable!("receiver ready typestate owns its exact backend state"),
            #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
            SessionInner::Unavailable => {
                unreachable!("unavailable backend cannot construct a session")
            }
        }
    }
}

fn validate_public_options(options: &SessionOptions) -> Result<(), SessionError> {
    if options.deadline.is_expired()
        || options.application_payload.len() > options.limits.max_bootstrap_payload_bytes as usize
    {
        return Err(if options.deadline.is_expired() {
            SessionError::DeadlineExpired
        } else {
            SessionError::InvalidInput
        });
    }
    match options.executable_identity {
        ExecutableIdentityPolicy::ExactOpenedFile => {}
    }
    options
        .limits
        .validate()
        .map(|_| ())
        .map_err(SessionError::NativeNegotiation)
}

#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
const fn decision_rejection(decision: NegotiationDecision) -> Option<NonZeroU32> {
    match decision {
        NegotiationDecision::Accept => None,
        NegotiationDecision::Reject(reason) => Some(reason.as_nonzero()),
    }
}

#[cfg(target_os = "macos")]
fn map_mac_role(role: crate::backend::macos::vnext_session::MacNegotiationRole) -> SessionEndpoint {
    match role {
        crate::backend::macos::vnext_session::MacNegotiationRole::Coordinator => {
            SessionEndpoint::Coordinator
        }
        crate::backend::macos::vnext_session::MacNegotiationRole::Receiver => {
            SessionEndpoint::Receiver
        }
    }
}

#[cfg(target_os = "macos")]
fn map_mac_coordinator_outcome(
    outcome: crate::backend::macos::vnext_session::MacNegotiationOutcome<
        crate::backend::macos::vnext_session::MacCoordinatorReadySession,
    >,
) -> Result<NegotiationOutcome<Session<Coordinator, Ready>>, SessionFailure> {
    match outcome {
        crate::backend::macos::vnext_session::MacNegotiationOutcome::Accepted(inner) => {
            Ok(NegotiationOutcome::Accepted(Session::from_inner(
                SessionInner::CoordinatorReady(inner),
            )))
        }
        crate::backend::macos::vnext_session::MacNegotiationOutcome::Rejected {
            by,
            reason,
            cleanup,
        } => {
            let reason = RejectionReason::from_wire(reason).ok_or_else(|| {
                let failure = SessionFailure::new(
                    SessionOperation::Negotiate,
                    SessionTransactionState::Poisoned,
                    SessionError::MalformedPeer,
                );
                cleanup.map_or(failure, |facts| failure.with_cleanup(facts))
            })?;
            Ok(NegotiationOutcome::Rejected {
                by: map_mac_role(by),
                reason,
                cleanup,
            })
        }
    }
}

#[cfg(target_os = "macos")]
fn map_mac_receiver_outcome(
    outcome: crate::backend::macos::vnext_session::MacNegotiationOutcome<
        crate::backend::macos::vnext_session::MacReceiverReadySession,
    >,
) -> Result<NegotiationOutcome<Session<Receiver, Ready>>, SessionFailure> {
    match outcome {
        crate::backend::macos::vnext_session::MacNegotiationOutcome::Accepted(inner) => Ok(
            NegotiationOutcome::Accepted(Session::from_inner(SessionInner::ReceiverReady(inner))),
        ),
        crate::backend::macos::vnext_session::MacNegotiationOutcome::Rejected {
            by,
            reason,
            cleanup,
        } => {
            let reason = RejectionReason::from_wire(reason).ok_or_else(|| {
                SessionFailure::new(
                    SessionOperation::Negotiate,
                    SessionTransactionState::Poisoned,
                    SessionError::MalformedPeer,
                )
            })?;
            Ok(NegotiationOutcome::Rejected {
                by: map_mac_role(by),
                reason,
                cleanup,
            })
        }
    }
}

#[cfg(target_os = "windows")]
fn map_windows_role(
    role: crate::backend::windows::vnext_session::WindowsNegotiationRole,
) -> SessionEndpoint {
    match role {
        crate::backend::windows::vnext_session::WindowsNegotiationRole::Coordinator => {
            SessionEndpoint::Coordinator
        }
        crate::backend::windows::vnext_session::WindowsNegotiationRole::Receiver => {
            SessionEndpoint::Receiver
        }
    }
}

#[cfg(target_os = "windows")]
fn map_windows_coordinator_outcome(
    outcome: crate::backend::windows::vnext_session::WindowsNegotiationOutcome<
        crate::backend::windows::vnext_session::WindowsCoordinatorReadySession,
    >,
) -> Result<NegotiationOutcome<Session<Coordinator, Ready>>, SessionFailure> {
    match outcome {
        crate::backend::windows::vnext_session::WindowsNegotiationOutcome::Accepted(inner) => {
            Ok(NegotiationOutcome::Accepted(Session::from_inner(
                SessionInner::CoordinatorReady(Box::new(inner)),
            )))
        }
        crate::backend::windows::vnext_session::WindowsNegotiationOutcome::Rejected {
            by,
            reason,
            cleanup,
        } => {
            let reason = RejectionReason::from_wire(reason).ok_or_else(|| {
                let failure = SessionFailure::new(
                    SessionOperation::Negotiate,
                    SessionTransactionState::Poisoned,
                    SessionError::MalformedPeer,
                );
                cleanup.map_or(failure, |facts| failure.with_cleanup(facts))
            })?;
            Ok(NegotiationOutcome::Rejected {
                by: map_windows_role(by),
                reason,
                cleanup,
            })
        }
    }
}

#[cfg(target_os = "windows")]
fn map_windows_receiver_outcome(
    outcome: crate::backend::windows::vnext_session::WindowsNegotiationOutcome<
        crate::backend::windows::vnext_session::WindowsReceiverReadySession,
    >,
) -> Result<NegotiationOutcome<Session<Receiver, Ready>>, SessionFailure> {
    match outcome {
        crate::backend::windows::vnext_session::WindowsNegotiationOutcome::Accepted(inner) => {
            Ok(NegotiationOutcome::Accepted(Session::from_inner(
                SessionInner::ReceiverReady(Box::new(inner)),
            )))
        }
        crate::backend::windows::vnext_session::WindowsNegotiationOutcome::Rejected {
            by,
            reason,
            cleanup,
        } => {
            let reason = RejectionReason::from_wire(reason).ok_or_else(|| {
                SessionFailure::new(
                    SessionOperation::Negotiate,
                    SessionTransactionState::Poisoned,
                    SessionError::MalformedPeer,
                )
            })?;
            Ok(NegotiationOutcome::Rejected {
                by: map_windows_role(by),
                reason,
                cleanup,
            })
        }
    }
}

#[cfg(target_os = "linux")]
fn map_linux_role(
    role: crate::backend::linux_vnext::spawn::LinuxNegotiationRole,
) -> SessionEndpoint {
    match role {
        crate::backend::linux_vnext::spawn::LinuxNegotiationRole::Coordinator => {
            SessionEndpoint::Coordinator
        }
        crate::backend::linux_vnext::spawn::LinuxNegotiationRole::Receiver => {
            SessionEndpoint::Receiver
        }
    }
}

#[cfg(target_os = "linux")]
fn map_linux_coordinator_outcome(
    outcome: crate::backend::linux_vnext::spawn::LinuxNegotiationOutcome<
        crate::backend::linux_vnext::spawn::LinuxCoordinatorReadySession,
    >,
) -> Result<NegotiationOutcome<Session<Coordinator, Ready>>, SessionFailure> {
    match outcome {
        crate::backend::linux_vnext::spawn::LinuxNegotiationOutcome::Accepted(inner) => {
            Ok(NegotiationOutcome::Accepted(Session::from_inner(
                SessionInner::CoordinatorReady(inner),
            )))
        }
        crate::backend::linux_vnext::spawn::LinuxNegotiationOutcome::Rejected {
            by,
            reason,
            cleanup,
        } => {
            let reason = RejectionReason::from_wire(reason).ok_or_else(|| {
                let failure = SessionFailure::new(
                    SessionOperation::Negotiate,
                    SessionTransactionState::Poisoned,
                    SessionError::MalformedPeer,
                );
                cleanup.map_or(failure, |facts| failure.with_cleanup(facts))
            })?;
            Ok(NegotiationOutcome::Rejected {
                by: map_linux_role(by),
                reason,
                cleanup,
            })
        }
    }
}

#[cfg(target_os = "linux")]
fn map_linux_receiver_outcome(
    outcome: crate::backend::linux_vnext::spawn::LinuxNegotiationOutcome<
        crate::backend::linux_vnext::spawn::LinuxReceiverReadySession,
    >,
) -> Result<NegotiationOutcome<Session<Receiver, Ready>>, SessionFailure> {
    match outcome {
        crate::backend::linux_vnext::spawn::LinuxNegotiationOutcome::Accepted(inner) => Ok(
            NegotiationOutcome::Accepted(Session::from_inner(SessionInner::ReceiverReady(inner))),
        ),
        crate::backend::linux_vnext::spawn::LinuxNegotiationOutcome::Rejected {
            by,
            reason,
            cleanup,
        } => {
            let reason = RejectionReason::from_wire(reason).ok_or_else(|| {
                SessionFailure::new(
                    SessionOperation::Negotiate,
                    SessionTransactionState::Poisoned,
                    SessionError::MalformedPeer,
                )
            })?;
            Ok(NegotiationOutcome::Rejected {
                by: map_linux_role(by),
                reason,
                cleanup,
            })
        }
    }
}

#[cfg(target_os = "linux")]
fn linux_ready_failure(
    operation: SessionOperation,
    state: SessionState,
    error: crate::backend::linux_vnext::spawn::LinuxPublicSessionError,
) -> SessionFailure {
    let native_code = linux_public_native_code(error);
    let poisoned = state == SessionState::Poisoned;
    SessionFailure::new(
        operation,
        if poisoned {
            SessionTransactionState::Poisoned
        } else {
            SessionTransactionState::Ready
        },
        error.into(),
    )
    .with_native_code(native_code)
    .with_poisoned(poisoned)
}

#[cfg(target_os = "linux")]
fn linux_ready_batch_failure(
    operation: SessionOperation,
    state: SessionState,
    failure: crate::backend::linux_vnext::spawn::LinuxPublicReadyFailure,
) -> SessionFailure {
    let native_code = linux_public_native_code(failure.error);
    let poisoned = state == SessionState::Poisoned;
    SessionFailure::new(
        operation,
        if failure.transaction_open_on_failure {
            SessionTransactionState::TransactionOpen
        } else if poisoned {
            SessionTransactionState::Poisoned
        } else {
            SessionTransactionState::Ready
        },
        failure.error.into(),
    )
    .with_native_code(native_code)
    .with_poisoned(poisoned)
}

#[cfg(target_os = "linux")]
const fn linux_public_native_code(
    error: crate::backend::linux_vnext::spawn::LinuxPublicSessionError,
) -> Option<i32> {
    match error {
        crate::backend::linux_vnext::spawn::LinuxPublicSessionError::Native(code) => code,
        crate::backend::linux_vnext::spawn::LinuxPublicSessionError::ActivationFailed(code) => code,
        _ => None,
    }
}

#[cfg(target_os = "linux")]
impl From<crate::backend::linux_vnext::spawn::LinuxPublicSessionError> for SessionError {
    fn from(error: crate::backend::linux_vnext::spawn::LinuxPublicSessionError) -> Self {
        match error {
            crate::backend::linux_vnext::spawn::LinuxPublicSessionError::InvalidInput => {
                Self::InvalidInput
            }
            crate::backend::linux_vnext::spawn::LinuxPublicSessionError::DeadlineExpired => {
                Self::DeadlineExpired
            }
            crate::backend::linux_vnext::spawn::LinuxPublicSessionError::PeerExited => {
                Self::PeerDisconnected
            }
            crate::backend::linux_vnext::spawn::LinuxPublicSessionError::IdentityMismatch => {
                Self::IdentityMismatch
            }
            crate::backend::linux_vnext::spawn::LinuxPublicSessionError::MalformedPeer => {
                Self::MalformedPeer
            }
            crate::backend::linux_vnext::spawn::LinuxPublicSessionError::Ambiguous => {
                Self::Ambiguous
            }
            crate::backend::linux_vnext::spawn::LinuxPublicSessionError::NegotiationFailed => {
                Self::NegotiationFailed
            }
            crate::backend::linux_vnext::spawn::LinuxPublicSessionError::NativeNegotiation(
                error,
            ) => Self::NativeNegotiation(error),
            crate::backend::linux_vnext::spawn::LinuxPublicSessionError::Control(error) => {
                Self::Control(error)
            }
            crate::backend::linux_vnext::spawn::LinuxPublicSessionError::Batch(error) => {
                Self::Batch(error)
            }
            crate::backend::linux_vnext::spawn::LinuxPublicSessionError::ActiveLimit => {
                Self::ActiveLimit
            }
            crate::backend::linux_vnext::spawn::LinuxPublicSessionError::PeerPreparationFailed => {
                Self::PeerPreparationFailed
            }
            crate::backend::linux_vnext::spawn::LinuxPublicSessionError::ActivationFailed(_) => {
                Self::ActivationFailed
            }
            crate::backend::linux_vnext::spawn::LinuxPublicSessionError::Poisoned => Self::Poisoned,
            crate::backend::linux_vnext::spawn::LinuxPublicSessionError::Native(_) => Self::Native,
        }
    }
}

#[cfg(target_os = "macos")]
fn mac_session_failure(
    operation: SessionOperation,
    transaction_state: SessionTransactionState,
    error: crate::backend::macos::vnext_session::MacPublicSessionError,
    poisoned: bool,
) -> SessionFailure {
    SessionFailure::new(operation, transaction_state, error.into())
        .with_native_code(mac_public_native_code(error))
        .with_poisoned(poisoned)
}

#[cfg(target_os = "macos")]
fn mac_ready_failure(
    operation: SessionOperation,
    state: SessionState,
    error: crate::backend::macos::vnext_session::MacPublicSessionError,
) -> SessionFailure {
    let poisoned = state == SessionState::Poisoned;
    mac_session_failure(
        operation,
        if poisoned {
            SessionTransactionState::Poisoned
        } else {
            SessionTransactionState::Ready
        },
        error,
        poisoned,
    )
}

#[cfg(target_os = "macos")]
const fn mac_public_native_code(
    error: crate::backend::macos::vnext_session::MacPublicSessionError,
) -> Option<i32> {
    match error {
        crate::backend::macos::vnext_session::MacPublicSessionError::Native(code) => code,
        _ => None,
    }
}

#[cfg(target_os = "macos")]
impl From<crate::backend::macos::vnext_session::MacPublicSessionError> for SessionError {
    fn from(error: crate::backend::macos::vnext_session::MacPublicSessionError) -> Self {
        use crate::backend::macos::vnext_session::MacPublicSessionError as MacError;
        match error {
            MacError::InvalidInput => Self::InvalidInput,
            MacError::DeadlineExpired => Self::DeadlineExpired,
            MacError::PeerExited => Self::PeerDisconnected,
            MacError::IdentityMismatch => Self::IdentityMismatch,
            MacError::MalformedPeer => Self::MalformedPeer,
            MacError::Ambiguous => Self::Ambiguous,
            MacError::NegotiationFailed => Self::NegotiationFailed,
            MacError::NativeNegotiation(error) => Self::NativeNegotiation(error),
            MacError::Control(error) => Self::Control(error),
            MacError::Batch(error) => Self::Batch(error),
            MacError::ActiveLimit => Self::ActiveLimit,
            MacError::PeerPreparationFailed => Self::PeerPreparationFailed,
            MacError::ActivationFailed => Self::ActivationFailed,
            MacError::Poisoned => Self::Poisoned,
            MacError::Native(_) => Self::Native,
        }
    }
}

#[cfg(target_os = "windows")]
fn windows_session_failure(
    operation: SessionOperation,
    transaction_state: SessionTransactionState,
    error: crate::backend::windows::vnext_session::WindowsPublicSessionError,
    poisoned: bool,
) -> SessionFailure {
    let native_code = match &error {
        crate::backend::windows::vnext_session::WindowsPublicSessionError::Native(code) => *code,
        _ => None,
    };
    SessionFailure::new(operation, transaction_state, error.into())
        .with_native_code(native_code)
        .with_poisoned(poisoned)
}

#[cfg(target_os = "windows")]
fn windows_ready_failure(
    operation: SessionOperation,
    state: SessionState,
    error: crate::backend::windows::vnext_session::WindowsPublicSessionError,
) -> SessionFailure {
    let poisoned = state == SessionState::Poisoned;
    windows_session_failure(
        operation,
        if poisoned {
            SessionTransactionState::Poisoned
        } else {
            SessionTransactionState::Ready
        },
        error,
        poisoned,
    )
}

#[cfg(target_os = "windows")]
impl From<crate::backend::windows::vnext_session::WindowsPublicSessionError> for SessionError {
    fn from(error: crate::backend::windows::vnext_session::WindowsPublicSessionError) -> Self {
        use crate::backend::windows::vnext_session::WindowsPublicSessionError as WindowsError;
        match error {
            WindowsError::InvalidInput => Self::InvalidInput,
            WindowsError::DeadlineExpired => Self::DeadlineExpired,
            WindowsError::PeerExited => Self::PeerDisconnected,
            WindowsError::IdentityMismatch => Self::IdentityMismatch,
            WindowsError::MalformedPeer => Self::MalformedPeer,
            WindowsError::Ambiguous => Self::Ambiguous,
            WindowsError::NegotiationFailed => Self::NegotiationFailed,
            WindowsError::NativeNegotiation(error) => Self::NativeNegotiation(error),
            WindowsError::Control(error) => Self::Control(error),
            WindowsError::Batch(error) => Self::Batch(error),
            WindowsError::ActiveLimit => Self::ActiveLimit,
            WindowsError::PeerPreparationFailed => Self::PeerPreparationFailed,
            WindowsError::ActivationFailed => Self::ActivationFailed,
            WindowsError::Poisoned => Self::Poisoned,
            WindowsError::Native(_) => Self::Native,
        }
    }
}

const _: () = assert!(cfg!(target_has_atomic = "32"));
const _: () = assert!(cfg!(target_has_atomic = "64"));

#[cfg(test)]
#[path = "session_test.rs"]
mod tests;