runtrue-wasm-runtime 0.1.0-alpha.6

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

/// Worker protocol implemented by this runtime release.
pub const WASIX_WORKER_PROTOCOL_VERSION: u32 = 8;

/// Exact engine and package cohort required for worker compatibility.
pub const WASIX_COHORT_ID: &str = "wasmer-7.1.0+wasix-0.701.0+webc-11.0.0";

const WASIX_WORKER_ISOLATION_PROFILE_VERSION: u32 = 2;
const WASIX_WORKER_MAX_OPEN_FILES: u64 = 64;
const WASIX_WORKER_MAX_FILE_BYTES: u64 = 512 * 1024 * 1024;
const WASIX_WORKER_MAX_ADDRESS_SPACE_BYTES: u64 = 2 * 1024 * 1024 * 1024;
const WASIX_WORKER_MAX_SUPPLEMENTARY_GROUPS: usize = 64;
const MAX_HANDSHAKE_BYTES: usize = 16 * 1024;
const MAX_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30);
const WASIX_WORKER_MAX_CHECKPOINT_BYTES: usize = 512 * 1024 * 1024;
#[cfg(feature = "wasix-checkpoint")]
const WASIX_WORKER_MAX_MODULE_BYTES: usize = 64 * 1024 * 1024;
#[cfg(feature = "wasix-checkpoint")]
const WASIX_WORKER_MAX_RESTORE_OUTPUT_BYTES: usize = 64 * 1024;
#[cfg(feature = "wasix-checkpoint")]
const WASIX_WORKER_MAX_DIAGNOSTIC_BYTES: usize = 16 * 1024;
#[cfg(feature = "wasix-checkpoint")]
const WASIX_WORKER_MAX_CAPTURE_REQUEST_BYTES: usize = 64 * 1024;
#[cfg(feature = "wasix-checkpoint")]
const WASIX_WORKER_MAX_CAPTURE_ARGUMENTS: usize = 256;
#[cfg(feature = "wasix-checkpoint")]
const WASIX_WORKER_MAX_CAPTURE_ENVIRONMENT: usize = 256;
#[cfg(feature = "wasix-checkpoint")]
const WASIX_WORKER_MAX_CAPTURE_VALUE_BYTES: usize = 4 * 1024;
#[cfg(target_os = "linux")]
const REQUIRED_CHECKPOINT_SEALS: rustix::fs::SealFlags = rustix::fs::SealFlags::SEAL
    .union(rustix::fs::SealFlags::SHRINK)
    .union(rustix::fs::SealFlags::GROW)
    .union(rustix::fs::SealFlags::WRITE);

/// Explicit deployment configuration for the out-of-process WASIX worker.
///
/// The executable is a deployment trust anchor and must be installed at a
/// trusted, administrator-controlled path. Every operation pins and hashes one
/// exact regular file with Linux `openat2`, then executes that descriptor with
/// `execveat`; pathname replacement cannot select a different worker after
/// validation. Version 8 of the worker process boundary is supported on Linux
/// 5.6 or newer only.
#[derive(Clone)]
pub struct WasixWorkerConfig {
    executable: PathBuf,
    handshake_timeout: Duration,
    allowed_supplementary_groups: Vec<u32>,
    placement: Option<Arc<dyn WasixWorkerPlacement>>,
}

impl std::fmt::Debug for WasixWorkerConfig {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("WasixWorkerConfig")
            .field("executable", &self.executable)
            .field("handshake_timeout", &self.handshake_timeout)
            .field(
                "allowed_supplementary_groups",
                &self.allowed_supplementary_groups,
            )
            .field("placement_configured", &self.placement.is_some())
            .finish()
    }
}

impl PartialEq for WasixWorkerConfig {
    fn eq(&self, other: &Self) -> bool {
        self.executable == other.executable
            && self.handshake_timeout == other.handshake_timeout
            && self.allowed_supplementary_groups == other.allowed_supplementary_groups
            && match (&self.placement, &other.placement) {
                (None, None) => true,
                (Some(left), Some(right)) => Arc::ptr_eq(left, right),
                _ => false,
            }
    }
}

impl Eq for WasixWorkerConfig {}

/// Operation for which a fresh isolated WASIX worker was spawned.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum WasixWorkerOperation {
    /// Compatibility and isolation probe without guest input.
    Probe,
    /// Sealed checkpoint transport qualification.
    CheckpointTransport,
    /// Restore and resume an authenticated checkpoint.
    CheckpointRestore,
    /// Execute a source workload until its explicit checkpoint.
    CheckpointCapture,
}

/// Identity passed to a configured pre-input worker placement policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WasixWorkerPlacementRequest {
    process_id: u32,
    operation: WasixWorkerOperation,
}

impl WasixWorkerPlacementRequest {
    /// Operating-system process identifier of the newly spawned worker.
    #[must_use]
    pub const fn process_id(self) -> u32 {
        self.process_id
    }

    /// Worker operation that will run after placement succeeds.
    #[must_use]
    pub const fn operation(self) -> WasixWorkerOperation {
        self.operation
    }
}

/// Synchronous, fail-closed placement policy for newly spawned WASIX workers.
///
/// The callback runs immediately after spawn and before the parent sends module,
/// checkpoint, request, or Execute bytes. A deployment can use the PID to write
/// the worker into a pre-created cgroup v2 `cgroup.procs` file, then verify the
/// resulting membership before returning. Returning an error kills and reaps
/// the worker without authorizing guest execution.
///
/// Implementations must complete promptly and must not retain the PID for a
/// later asynchronous action. The child remains an unreaped child throughout
/// this callback, preventing its PID from being recycled during placement.
pub trait WasixWorkerPlacement: Send + Sync + 'static {
    /// Place and authorize one fresh worker before any workload input is sent.
    ///
    /// # Errors
    ///
    /// Returning an error rejects the worker and aborts the operation.
    fn place(&self, request: WasixWorkerPlacementRequest) -> Result<()>;
}

impl<F> WasixWorkerPlacement for F
where
    F: Fn(WasixWorkerPlacementRequest) -> Result<()> + Send + Sync + 'static,
{
    fn place(&self, request: WasixWorkerPlacementRequest) -> Result<()> {
        self(request)
    }
}

impl WasixWorkerConfig {
    /// Select an absolute worker executable path with a five-second handshake.
    #[must_use]
    pub fn new(executable: impl Into<PathBuf>) -> Self {
        Self {
            executable: executable.into(),
            handshake_timeout: Duration::from_secs(5),
            allowed_supplementary_groups: Vec::new(),
            placement: None,
        }
    }

    /// Set the maximum time allowed for a complete probe, transport, or restore.
    ///
    /// Checkpoint transport applies this deadline to memfd preparation plus
    /// the complete Ready, acknowledgement, EOF, and worker-exit exchange.
    #[must_use]
    pub const fn with_handshake_timeout(mut self, timeout: Duration) -> Self {
        self.handshake_timeout = timeout;
        self
    }

    /// Configured worker executable.
    #[must_use]
    pub fn executable(&self) -> &Path {
        &self.executable
    }

    /// Configured complete-handshake timeout.
    #[must_use]
    pub const fn handshake_timeout(&self) -> Duration {
        self.handshake_timeout
    }

    /// Allow an exact set of inherited non-root supplementary group IDs.
    ///
    /// The secure default is an empty set. Only add groups required by the
    /// dedicated worker service account; group zero is always rejected.
    #[must_use]
    pub fn with_allowed_supplementary_groups(
        mut self,
        groups: impl IntoIterator<Item = u32>,
    ) -> Self {
        self.allowed_supplementary_groups = groups.into_iter().collect();
        self.allowed_supplementary_groups.sort_unstable();
        self.allowed_supplementary_groups.dedup();
        self
    }

    /// Require a deployment placement policy before accepting worker input.
    ///
    /// The policy is invoked for every worker spawned by this configuration.
    /// Failure is fail-closed: the worker is killed and reaped, and no guest,
    /// module, checkpoint, request, or Execute bytes are sent. The default
    /// configuration has no policy and therefore makes no cgroup-placement
    /// claim; production deployments that require per-invocation cgroups must
    /// configure and verify them here.
    #[must_use]
    pub fn with_worker_placement(mut self, placement: impl WasixWorkerPlacement) -> Self {
        self.placement = Some(Arc::new(placement));
        self
    }

    /// Whether a fail-closed external placement policy is configured.
    #[must_use]
    pub fn has_worker_placement(&self) -> bool {
        self.placement.is_some()
    }

    fn validate_common(&self) -> Result<()> {
        if !cfg!(target_os = "linux") {
            return Err(Error::Configuration(
                "the WASIX worker process boundary currently requires Linux".to_owned(),
            ));
        }

        if !self.executable.is_absolute() {
            return Err(Error::Configuration(
                "WASIX worker executable must be an absolute path".to_owned(),
            ));
        }
        if self.handshake_timeout.is_zero() || self.handshake_timeout > MAX_HANDSHAKE_TIMEOUT {
            return Err(Error::Configuration(
                "WASIX worker handshake timeout must be between zero and 30 seconds".to_owned(),
            ));
        }
        if self.allowed_supplementary_groups.len() > WASIX_WORKER_MAX_SUPPLEMENTARY_GROUPS
            || self.allowed_supplementary_groups.contains(&0)
        {
            return Err(Error::Configuration(
                "WASIX worker supplementary group allowlist is invalid".to_owned(),
            ));
        }
        Ok(())
    }

    #[cfg(target_os = "linux")]
    fn pin_executable(&self) -> Result<PinnedWorkerExecutable> {
        self.validate_common()?;
        PinnedWorkerExecutable::open(&self.executable)
    }
}

#[cfg(target_os = "linux")]
struct PinnedWorkerExecutable {
    descriptor: std::os::fd::OwnedFd,
    path: PathBuf,
    sha256: String,
}

#[cfg(target_os = "linux")]
impl PinnedWorkerExecutable {
    fn open(path: &Path) -> Result<Self> {
        use rustix::fs::{CWD, FileType, Mode, OFlags, ResolveFlags, fstat, openat2};

        validate_worker_ancestors(path)?;
        let descriptor = openat2(
            CWD,
            path,
            OFlags::RDONLY | OFlags::CLOEXEC,
            Mode::empty(),
            ResolveFlags::NO_SYMLINKS | ResolveFlags::NO_MAGICLINKS,
        )
        .map_err(|error| {
            Error::Configuration(format!(
                "cannot pin WASIX worker {} with openat2: {error}",
                path.display()
            ))
        })?;
        let stat = fstat(&descriptor).map_err(|error| {
            Error::Configuration(format!(
                "cannot inspect pinned WASIX worker {}: {error}",
                path.display()
            ))
        })?;
        validate_worker_file_stat(path, &stat, FileType::from_raw_mode(stat.st_mode))?;
        validate_worker_file_capabilities(path, &descriptor)?;
        let bytes = u64::try_from(stat.st_size).map_err(|_| {
            Error::Configuration(format!("WASIX worker size is invalid: {}", path.display()))
        })?;
        let sha256 = sha256_descriptor(&descriptor, bytes, "pinned WASIX worker")
            .map_err(Error::Configuration)?;
        Ok(Self {
            descriptor,
            path: path.to_owned(),
            sha256,
        })
    }

    fn command(&self, operation: &'static str) -> Result<Command> {
        use rustix::io::dup;
        use std::os::unix::ffi::OsStrExt as _;

        let descriptor = dup(&self.descriptor).map_err(|error| {
            Error::Execution(format!("cannot duplicate pinned WASIX worker: {error}"))
        })?;
        let argv0 = CString::new(self.path.as_os_str().as_bytes()).map_err(|_| {
            Error::Configuration("WASIX worker path contains a NUL byte".to_owned())
        })?;
        let operation = CString::new(operation).map_err(|_| {
            Error::Configuration("WASIX worker operation contains a NUL byte".to_owned())
        })?;
        let mut command = Command::new("/proc/self/exe");
        command.arg(std::ffi::OsStr::from_bytes(operation.as_bytes()));
        install_pinned_exec(&mut command, descriptor, argv0, operation);
        Ok(command)
    }
}

#[cfg(target_os = "linux")]
fn validate_worker_ancestors(path: &Path) -> Result<()> {
    use std::path::Component;

    let parent = path.parent().ok_or_else(|| {
        Error::Configuration("WASIX worker path has no parent directory".to_owned())
    })?;
    let mut prefix = PathBuf::from("/");
    validate_worker_ancestor(&prefix)?;
    for component in parent.components() {
        match component {
            Component::RootDir => continue,
            Component::Normal(component) => prefix.push(component),
            _ => {
                return Err(Error::Configuration(
                    "WASIX worker path is not canonical".to_owned(),
                ));
            }
        }
        validate_worker_ancestor(&prefix)?;
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn validate_worker_ancestor(path: &Path) -> Result<()> {
    use rustix::fs::{CWD, FileType, Mode, OFlags, ResolveFlags, fstat, openat2};

    let descriptor = openat2(
        CWD,
        path,
        OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC,
        Mode::empty(),
        ResolveFlags::NO_SYMLINKS | ResolveFlags::NO_MAGICLINKS,
    )
    .map_err(|error| {
        Error::Configuration(format!(
            "cannot pin WASIX worker ancestor {}: {error}",
            path.display()
        ))
    })?;
    let stat = fstat(&descriptor).map_err(|error| {
        Error::Configuration(format!(
            "cannot inspect WASIX worker ancestor {}: {error}",
            path.display()
        ))
    })?;
    if FileType::from_raw_mode(stat.st_mode) != FileType::Directory
        || !trusted_worker_owner(stat.st_uid)
        || stat.st_mode & 0o022 != 0
    {
        return Err(Error::Configuration(format!(
            "WASIX worker ancestor is not owner-controlled: {}",
            path.display()
        )));
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn validate_worker_file_stat(
    path: &Path,
    stat: &rustix::fs::Stat,
    file_type: rustix::fs::FileType,
) -> Result<()> {
    if file_type != rustix::fs::FileType::RegularFile
        || stat.st_size <= 0
        || !trusted_worker_owner(stat.st_uid)
        || stat.st_mode & 0o111 == 0
        || stat.st_mode & 0o6022 != 0
    {
        return Err(Error::Configuration(format!(
            "WASIX worker must be one owner-controlled, non-setid executable: {}",
            path.display()
        )));
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn validate_worker_file_capabilities(
    path: &Path,
    descriptor: &impl std::os::fd::AsFd,
) -> Result<()> {
    let mut capabilities = [0_u8; 256];
    match rustix::fs::fgetxattr(descriptor, "security.capability", &mut capabilities) {
        Ok(bytes) if bytes != 0 => Err(Error::Configuration(format!(
            "WASIX worker must not have file capabilities: {}",
            path.display()
        ))),
        Ok(_) | Err(rustix::io::Errno::NODATA | rustix::io::Errno::NOTSUP) => Ok(()),
        Err(error) => Err(Error::Configuration(format!(
            "cannot inspect pinned WASIX worker file capabilities for {}: {error}",
            path.display()
        ))),
    }
}

#[cfg(target_os = "linux")]
fn trusted_worker_owner(owner: u32) -> bool {
    owner == 0 || owner == rustix::process::geteuid().as_raw()
}

#[cfg(target_os = "linux")]
fn sha256_descriptor(
    descriptor: &impl std::os::fd::AsFd,
    bytes: u64,
    label: &str,
) -> std::result::Result<String, String> {
    let mut hash = Sha256::new();
    let mut offset = 0_u64;
    let mut buffer = vec![0_u8; 64 * 1024].into_boxed_slice();
    while offset < bytes {
        let remaining = usize::try_from((bytes - offset).min(buffer.len() as u64))
            .map_err(|_| format!("{label} read length overflows usize"))?;
        let read = rustix::io::pread(descriptor, &mut buffer[..remaining], offset)
            .map_err(|error| format!("cannot read {label}: {error}"))?;
        if read == 0 {
            return Err(format!("{label} ended before its pinned length"));
        }
        hash.update(&buffer[..read]);
        offset = offset
            .checked_add(u64::try_from(read).map_err(|_| format!("{label} read overflow"))?)
            .ok_or_else(|| format!("{label} offset overflow"))?;
    }
    let mut trailing = [0_u8; 1];
    if rustix::io::pread(descriptor, &mut trailing, bytes)
        .map_err(|error| format!("cannot finish reading {label}: {error}"))?
        != 0
    {
        return Err(format!("{label} grew while it was pinned"));
    }
    Ok(hex::encode(hash.finalize()))
}

#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
fn install_pinned_exec(
    command: &mut Command,
    descriptor: std::os::fd::OwnedFd,
    argv0: CString,
    operation: CString,
) {
    use rustix::fs::AtFlags;
    let expected_parent = rustix::process::getpid();
    // SAFETY: the closure runs in the single-threaded post-fork child and uses
    // only async-signal-safe Linux syscalls. It arms PDEATHSIG and closes the
    // PPID race before executing the pinned descriptor. All C strings and
    // pointer arrays remain owned by the closure for the syscall. A successful
    // execveat never returns; failure is surfaced to Command::spawn and cannot
    // fall through to the placeholder executable.
    unsafe {
        command.pre_exec(move || {
            rustix::process::set_parent_process_death_signal(Some(rustix::process::Signal::KILL))
                .map_err(std::io::Error::from)?;
            if rustix::process::getppid() != Some(expected_parent) {
                return Err(std::io::Error::from(rustix::io::Errno::SRCH));
            }
            let argv = [
                argv0.as_ptr().cast(),
                operation.as_ptr().cast(),
                std::ptr::null(),
            ];
            let envp = [std::ptr::null()];
            let errno = rustix::runtime::execveat(
                &descriptor,
                c"",
                argv.as_ptr(),
                envp.as_ptr(),
                AtFlags::EMPTY_PATH,
            );
            Err(std::io::Error::from_raw_os_error(errno.raw_os_error()))
        });
    }
}

/// Compatibility metadata reported by a successfully probed worker process.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WasixWorkerMetadata {
    /// Framing and operation protocol version.
    pub protocol_version: u32,
    /// Runtime crate version used to build the worker.
    pub runtime_version: String,
    /// Exact Wasmer/WASIX/WebC dependency cohort.
    pub cohort_id: String,
    /// Lowercase SHA-256 digest of the exact executable image used by this worker.
    pub worker_build_sha256: String,
    /// Operating-system process identifier of the fresh worker.
    pub process_id: u32,
    /// Verified Linux isolation state established before this frame was written.
    pub isolation: WasixWorkerIsolation,
}

impl WasixWorkerMetadata {
    #[cfg(any(feature = "wasix", test))]
    fn current(isolation: WasixWorkerIsolation, worker_build_sha256: String) -> Self {
        Self {
            protocol_version: WASIX_WORKER_PROTOCOL_VERSION,
            runtime_version: env!("CARGO_PKG_VERSION").to_owned(),
            cohort_id: WASIX_COHORT_ID.to_owned(),
            worker_build_sha256,
            process_id: std::process::id(),
            isolation,
        }
    }

    fn validate(
        &self,
        expected_process_id: u32,
        expected_worker_build_sha256: &str,
        allowed_groups: &[u32],
    ) -> Result<()> {
        if self.protocol_version != WASIX_WORKER_PROTOCOL_VERSION {
            return Err(Error::UnsupportedComponent(format!(
                "WASIX worker protocol {} is incompatible with required protocol {}",
                self.protocol_version, WASIX_WORKER_PROTOCOL_VERSION
            )));
        }
        if self.runtime_version != env!("CARGO_PKG_VERSION") {
            return Err(Error::UnsupportedComponent(format!(
                "WASIX worker runtime {} is incompatible with required runtime {}",
                self.runtime_version,
                env!("CARGO_PKG_VERSION")
            )));
        }
        if self.cohort_id != WASIX_COHORT_ID {
            return Err(Error::UnsupportedComponent(format!(
                "WASIX worker cohort {:?} is incompatible with required cohort {WASIX_COHORT_ID:?}",
                self.cohort_id
            )));
        }
        if self.worker_build_sha256 != expected_worker_build_sha256 {
            return Err(Error::UnsupportedComponent(format!(
                "WASIX worker build {} does not match pinned executable {expected_worker_build_sha256}",
                self.worker_build_sha256
            )));
        }
        if self.process_id != expected_process_id {
            return Err(Error::Execution(format!(
                "WASIX worker reported process {}, but spawned process was {expected_process_id}",
                self.process_id
            )));
        }
        self.isolation.validate(allowed_groups)?;
        Ok(())
    }
}

/// Result of transporting one verified checkpoint into a fresh isolated worker.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WasixCheckpointTransportMetadata {
    /// Compatibility and isolation state reported before checkpoint input was read.
    pub worker: WasixWorkerMetadata,
    /// Authenticated workload and generation bound to the transported journal.
    pub binding: WasixCheckpointBinding,
    /// Exact number of immutable journal bytes accepted by the worker.
    pub journal_bytes: u64,
    /// Lowercase SHA-256 digest independently computed by the worker.
    pub journal_sha256: String,
}

/// Result of restoring an authenticated checkpoint in a fresh isolated worker.
#[cfg(feature = "wasix-checkpoint")]
#[derive(Clone, PartialEq, Eq)]
pub struct WasixCheckpointRestoreMetadata {
    /// Compatibility and isolation state of the destination worker.
    pub worker: WasixWorkerMetadata,
    /// Authenticated workload and generation restored by the worker.
    pub binding: WasixCheckpointBinding,
    /// Bounded standard output emitted after the checkpoint resumed.
    pub stdout: Vec<u8>,
    /// Bounded standard error emitted by the restored guest.
    pub stderr: Vec<u8>,
    /// Bounded diagnostics emitted by the worker process, normally empty.
    pub worker_diagnostics: WasixWorkerDiagnostics,
    /// Lowercase SHA-256 digest of the restored module.
    pub module_sha256: String,
    /// Lowercase SHA-256 digest of the restored journal.
    pub journal_sha256: String,
}

#[cfg(feature = "wasix-checkpoint")]
impl std::fmt::Debug for WasixCheckpointRestoreMetadata {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("WasixCheckpointRestoreMetadata")
            .field("worker", &self.worker)
            .field("binding", &self.binding)
            .field("stdout_bytes", &self.stdout.len())
            .field("stderr_bytes", &self.stderr.len())
            .field("worker_diagnostics", &self.worker_diagnostics)
            .field("module_sha256", &self.module_sha256)
            .field("journal_sha256", &self.journal_sha256)
            .finish()
    }
}

/// Trusted journal capture produced by a fresh isolated source worker.
#[cfg(feature = "wasix-checkpoint")]
pub struct WasixCheckpointCapture {
    /// Compatibility and isolation state of the source worker.
    pub worker: WasixWorkerMetadata,
    /// Workload identity to which the captured journal will be sealed.
    pub binding: WasixCheckpointBinding,
    /// Bounded output emitted before the explicit snapshot.
    pub stdout: Vec<u8>,
    /// Bounded error output emitted before the explicit snapshot.
    pub stderr: Vec<u8>,
    /// Lowercase SHA-256 digest of the executed module.
    pub module_sha256: String,
    /// Lowercase SHA-256 digest of the captured journal prefix.
    pub journal_sha256: String,
    journal: CapturedWasixJournal,
}

#[cfg(feature = "wasix-checkpoint")]
impl std::fmt::Debug for WasixCheckpointCapture {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("WasixCheckpointCapture")
            .field("worker", &self.worker)
            .field("binding", &self.binding)
            .field("stdout_bytes", &self.stdout.len())
            .field("stderr_bytes", &self.stderr.len())
            .field("module_sha256", &self.module_sha256)
            .field("journal_sha256", &self.journal_sha256)
            .field("journal", &self.journal)
            .finish()
    }
}

#[cfg(feature = "wasix-checkpoint")]
impl WasixCheckpointCapture {
    /// Attested journal that can be authenticated with [`crate::WasixCheckpointCodec`].
    #[must_use]
    pub const fn journal(&self) -> &CapturedWasixJournal {
        &self.journal
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct WasixCheckpointTransportAck {
    journal_bytes: u64,
    journal_sha256: String,
}

#[cfg(feature = "wasix-checkpoint")]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct WasixCheckpointRestoreAck {
    module_bytes: u64,
    module_sha256: String,
    journal_bytes: u64,
    journal_sha256: String,
}

#[cfg(feature = "wasix-checkpoint")]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct WasixCheckpointRestoreCompletion {
    exit_code: i32,
    stdout_bytes: u64,
    stdout_sha256: String,
    stderr_bytes: u64,
    stderr_sha256: String,
}

#[cfg(feature = "wasix-checkpoint")]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct WasixCheckpointCaptureRequest {
    arguments: Vec<String>,
    environment: std::collections::BTreeMap<String, String>,
}

#[cfg(feature = "wasix-checkpoint")]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct WasixCheckpointCaptureAck {
    module_bytes: u64,
    module_sha256: String,
    request_bytes: u64,
    request_sha256: String,
}

#[cfg(feature = "wasix-checkpoint")]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct WasixCheckpointCaptureCompletion {
    exit_code: i32,
    journal_bytes: u64,
    journal_sha256: String,
    stdout_bytes: u64,
    stdout_sha256: String,
    stderr_bytes: u64,
    stderr_sha256: String,
}

impl WasixCheckpointTransportAck {
    fn validate(&self, expected_bytes: u64, expected_sha256: &str) -> Result<()> {
        if self.journal_bytes != expected_bytes || self.journal_sha256 != expected_sha256 {
            return Err(Error::Execution(
                "WASIX worker checkpoint acknowledgement did not match the sealed input".to_owned(),
            ));
        }
        Ok(())
    }
}

#[cfg(feature = "wasix-checkpoint")]
impl WasixCheckpointRestoreAck {
    fn validate(
        &self,
        module_bytes: u64,
        module_sha256: &str,
        journal_bytes: u64,
        journal_sha256: &str,
    ) -> Result<()> {
        if self.module_bytes != module_bytes
            || self.module_sha256 != module_sha256
            || self.journal_bytes != journal_bytes
            || self.journal_sha256 != journal_sha256
        {
            return Err(Error::Execution(
                "WASIX worker restore acknowledgement did not match the sealed inputs".to_owned(),
            ));
        }
        Ok(())
    }
}

#[cfg(feature = "wasix-checkpoint")]
impl WasixCheckpointRestoreCompletion {
    fn validate(&self, stdout: &[u8], stderr: &[u8]) -> Result<()> {
        let matches = |bytes: &[u8], expected_bytes: u64, expected_sha256: &str| {
            u64::try_from(bytes.len()).ok() == Some(expected_bytes)
                && hex::encode(Sha256::digest(bytes)) == expected_sha256
        };
        if self.exit_code != 0
            || !matches(stdout, self.stdout_bytes, &self.stdout_sha256)
            || !matches(stderr, self.stderr_bytes, &self.stderr_sha256)
        {
            return Err(Error::Execution(
                "WASIX worker restore completion did not match its output".to_owned(),
            ));
        }
        Ok(())
    }
}

#[cfg(feature = "wasix-checkpoint")]
impl WasixCheckpointCaptureRequest {
    fn new(input: CommandInput) -> Result<(Self, Duration, crate::CancellationToken)> {
        if !input.stdin.is_empty() {
            return Err(Error::Configuration(
                "WASIX checkpoint capture does not yet support standard input".to_owned(),
            ));
        }
        if input.timeout.is_zero() || input.timeout > MAX_HANDSHAKE_TIMEOUT {
            return Err(Error::Configuration(
                "WASIX checkpoint capture timeout must be between zero and 30 seconds".to_owned(),
            ));
        }
        let request = Self {
            arguments: input.args,
            environment: input.env,
        };
        request.validate().map_err(Error::Configuration)?;
        Ok((request, input.timeout, input.cancellation))
    }

    fn validate(&self) -> std::result::Result<(), String> {
        if self.arguments.len() > WASIX_WORKER_MAX_CAPTURE_ARGUMENTS
            || self.environment.len() > WASIX_WORKER_MAX_CAPTURE_ENVIRONMENT
        {
            return Err("WASIX checkpoint capture input contains too many entries".to_owned());
        }
        for argument in &self.arguments {
            validate_capture_value("argument", argument, WASIX_WORKER_MAX_CAPTURE_VALUE_BYTES)?;
        }
        for (key, value) in &self.environment {
            if key.is_empty() || key.contains('=') {
                return Err("WASIX checkpoint capture environment key is invalid".to_owned());
            }
            validate_capture_value("environment key", key, 256)?;
            validate_capture_value(
                "environment value",
                value,
                WASIX_WORKER_MAX_CAPTURE_VALUE_BYTES,
            )?;
        }
        Ok(())
    }
}

#[cfg(feature = "wasix-checkpoint")]
fn validate_capture_value(
    label: &str,
    value: &str,
    maximum: usize,
) -> std::result::Result<(), String> {
    if value.len() > maximum || value.contains('\0') {
        return Err(format!("WASIX checkpoint capture {label} is invalid"));
    }
    Ok(())
}

#[cfg(feature = "wasix-checkpoint")]
impl WasixCheckpointCaptureCompletion {
    fn validate(&self, journal: &[u8], stdout: &[u8], stderr: &[u8]) -> Result<()> {
        let matches = |bytes: &[u8], expected_bytes: u64, expected_sha256: &str| {
            u64::try_from(bytes.len()).ok() == Some(expected_bytes)
                && hex::encode(Sha256::digest(bytes)) == expected_sha256
        };
        if self.exit_code != 0
            || !matches(journal, self.journal_bytes, &self.journal_sha256)
            || !matches(stdout, self.stdout_bytes, &self.stdout_sha256)
            || !matches(stderr, self.stderr_bytes, &self.stderr_sha256)
        {
            return Err(Error::Execution(
                "WASIX worker capture completion did not match its output".to_owned(),
            ));
        }
        Ok(())
    }
}

/// Worker isolation postconditions established before accepting guest input.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WasixWorkerIsolation {
    /// Version of the worker's operating-system isolation profile.
    pub profile_version: u32,
    /// Real, effective, saved, and filesystem Linux user IDs, in that order.
    pub user_ids: [u32; 4],
    /// Real, effective, saved, and filesystem Linux group IDs, in that order.
    pub group_ids: [u32; 4],
    /// Sorted supplementary group IDs retained by the worker.
    pub supplementary_group_ids: Vec<u32>,
    /// Whether supplementary group zero is present.
    pub has_root_supplementary_group: bool,
    /// Verified state of Linux's irreversible no-new-privileges bit.
    pub no_new_privileges: bool,
    /// Whether tracing and core-dump access is enabled.
    pub dumpable: bool,
    /// Effective, permitted, inheritable, and ambient capability masks.
    pub capability_masks: [u64; 4],
    /// Effective and hard core-file limits, in bytes.
    pub core_file_limits: [u64; 2],
    /// Effective and hard per-file size limits, in bytes.
    pub file_size_limits: [u64; 2],
    /// Effective and hard virtual-address-space limits, in bytes.
    pub address_space_limits: [u64; 2],
    /// Effective and hard open-file descriptor limits.
    pub open_file_limits: [u64; 2],
    /// Number of inherited descriptors at or above three closed before Ready.
    pub closed_inherited_descriptor_count: u32,
}

impl WasixWorkerIsolation {
    fn validate(&self, allowed_groups: &[u32]) -> Result<()> {
        if self.profile_version != WASIX_WORKER_ISOLATION_PROFILE_VERSION {
            return Err(Error::UnsupportedComponent(format!(
                "WASIX worker isolation profile {} is incompatible with required profile {WASIX_WORKER_ISOLATION_PROFILE_VERSION}",
                self.profile_version
            )));
        }
        if self.user_ids.contains(&0) || self.group_ids.contains(&0) {
            return Err(Error::Execution(
                "WASIX worker retained a root user or group credential".to_owned(),
            ));
        }
        if self.user_ids[3] != self.user_ids[1] || self.group_ids[3] != self.group_ids[1] {
            return Err(Error::Execution(
                "WASIX worker filesystem credentials differ from its effective identity".to_owned(),
            ));
        }
        if self.has_root_supplementary_group {
            return Err(Error::Execution(
                "WASIX worker retained supplementary group zero".to_owned(),
            ));
        }
        if self.supplementary_group_ids.len() > WASIX_WORKER_MAX_SUPPLEMENTARY_GROUPS
            || self.supplementary_group_ids != allowed_groups
        {
            return Err(Error::Execution(format!(
                "WASIX worker supplementary groups {:?} do not match the deployment allowlist",
                self.supplementary_group_ids
            )));
        }
        if !self.no_new_privileges || self.dumpable {
            return Err(Error::Execution(
                "WASIX worker did not seal privilege escalation and tracing".to_owned(),
            ));
        }
        if self.capability_masks != [0; 4] {
            return Err(Error::Execution(
                "WASIX worker retained Linux capabilities".to_owned(),
            ));
        }
        if self.core_file_limits != [0, 0] {
            return Err(Error::Execution(
                "WASIX worker did not disable core files".to_owned(),
            ));
        }
        let [file_size, hard_file_size] = self.file_size_limits;
        if file_size != hard_file_size || file_size == 0 || file_size > WASIX_WORKER_MAX_FILE_BYTES
        {
            return Err(Error::Execution(format!(
                "WASIX worker file-size limits {:?} exceed the isolation profile",
                self.file_size_limits
            )));
        }
        let [address_space, hard_address_space] = self.address_space_limits;
        if address_space != hard_address_space
            || address_space == 0
            || address_space > WASIX_WORKER_MAX_ADDRESS_SPACE_BYTES
        {
            return Err(Error::Execution(format!(
                "WASIX worker address-space limits {:?} exceed the isolation profile",
                self.address_space_limits
            )));
        }
        let [open_files, hard_open_files] = self.open_file_limits;
        if open_files != hard_open_files
            || open_files == 0
            || open_files > WASIX_WORKER_MAX_OPEN_FILES
        {
            return Err(Error::Execution(format!(
                "WASIX worker open-file limits {:?} exceed the isolation profile",
                self.open_file_limits
            )));
        }
        Ok(())
    }

    #[cfg(test)]
    const fn compatible_for_test() -> Self {
        Self {
            profile_version: WASIX_WORKER_ISOLATION_PROFILE_VERSION,
            user_ids: [65_534; 4],
            group_ids: [65_534; 4],
            supplementary_group_ids: Vec::new(),
            has_root_supplementary_group: false,
            no_new_privileges: true,
            dumpable: false,
            capability_masks: [0; 4],
            core_file_limits: [0; 2],
            file_size_limits: [WASIX_WORKER_MAX_FILE_BYTES; 2],
            address_space_limits: [WASIX_WORKER_MAX_ADDRESS_SPACE_BYTES; 2],
            open_file_limits: [WASIX_WORKER_MAX_OPEN_FILES; 2],
            closed_inherited_descriptor_count: 0,
        }
    }
}

/// Spawn a fresh worker and check its framed protocol, build, cohort, and PID.
///
/// The probe performs no artifact parsing or compilation. It clears the
/// ambient environment, uses `/` as its working directory, and contains the
/// complete probe process tree in a fresh process group.
///
/// # Errors
///
/// Returns an error for an invalid deployment path, timeout, malformed frame,
/// nonzero worker exit, or any identity mismatch.
pub async fn probe_wasix_worker(config: &WasixWorkerConfig) -> Result<WasixWorkerMetadata> {
    config.validate_common()?;
    #[cfg(target_os = "linux")]
    {
        let executable = config.pin_executable()?;
        probe_wasix_worker_linux(config, executable).await
    }
    #[cfg(not(target_os = "linux"))]
    Err(Error::Configuration(
        "the WASIX worker process boundary currently requires Linux".to_owned(),
    ))
}

#[cfg(target_os = "linux")]
async fn probe_wasix_worker_linux(
    config: &WasixWorkerConfig,
    executable: PinnedWorkerExecutable,
) -> Result<WasixWorkerMetadata> {
    let mut command = executable.command("--protocol-probe")?;
    command
        .env_clear()
        .current_dir("/")
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .kill_on_drop(true);
    let mut worker = spawn_wasix_worker(
        config,
        WasixWorkerOperation::Probe,
        &mut command,
        executable.sha256.clone(),
    )
    .await?;
    let stdout = worker
        .child
        .stdout
        .take()
        .ok_or_else(|| Error::Execution("WASIX worker stdout was not piped".to_owned()))?;
    let (cancel, cancelled) = oneshot::channel();
    let supervisor = tokio::spawn(supervise_probe(
        worker,
        stdout,
        config.handshake_timeout,
        config.allowed_supplementary_groups.clone(),
        cancelled,
    ));
    ProbeSupervisor::new(supervisor, cancel).wait().await
}

/// Transport authenticated checkpoint journal bytes into a fresh isolated worker.
///
/// The journal is copied into an anonymous file and sealed against writes and
/// resizing. The child initially receives only a Unix control socket. After
/// the parent validates the isolated worker's Ready frame, it transfers the
/// sealed descriptor with `SCM_RIGHTS`; the worker validates its seals and size
/// before streaming the bytes into SHA-256. This operation deliberately
/// performs no Wasmer journal deserialization.
///
/// # Errors
///
/// Returns an error for invalid deployment configuration, an empty or
/// oversized journal, memfd or seal failures, timeout, cancellation, malformed
/// worker frames, or a digest/length mismatch.
pub async fn probe_wasix_checkpoint_transport(
    config: &WasixWorkerConfig,
    checkpoint: VerifiedWasixCheckpoint,
) -> Result<WasixCheckpointTransportMetadata> {
    config.validate_common()?;
    #[cfg(target_os = "linux")]
    {
        let executable = config.pin_executable()?;
        probe_wasix_checkpoint_transport_linux(config, executable, checkpoint).await
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = checkpoint;
        Err(Error::Configuration(
            "the WASIX checkpoint transport currently requires Linux".to_owned(),
        ))
    }
}

/// Restore an authenticated WASIX checkpoint in a fresh isolated worker.
///
/// The destination receives the exact module and journal as fully sealed
/// anonymous files. It independently checks both digests and acknowledges
/// them before the parent authorizes execution. Destination arguments are
/// deliberately absent: process state, including the source arguments, is
/// recovered only from the authenticated journal.
///
/// # Errors
///
/// Returns an error for an incompatible binding, invalid deployment, input
/// preparation failure, timeout, worker protocol violation, restore failure,
/// or output beyond the fixed capture limit.
#[cfg(feature = "wasix-checkpoint")]
pub async fn restore_wasix_checkpoint(
    config: &WasixWorkerConfig,
    checkpoint: VerifiedWasixCheckpoint,
    module: Vec<u8>,
) -> Result<WasixCheckpointRestoreMetadata> {
    config.validate_common()?;
    #[cfg(target_os = "linux")]
    {
        let executable = config.pin_executable()?;
        restore_wasix_checkpoint_linux(config, executable, checkpoint, module).await
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = (checkpoint, module);
        Err(Error::Configuration(
            "WASIX checkpoint restore currently requires Linux".to_owned(),
        ))
    }
}

/// Capture an explicit WASIX snapshot in a fresh isolated source worker.
///
/// Authentication remains a parent concern: this returns a non-forgeable
/// journal that callers can pass to [`crate::WasixCheckpointCodec::seal`].
/// Standard input is rejected in this first capture protocol revision.
///
/// # Errors
///
/// Returns an error for invalid input or binding, timeout, cancellation,
/// worker protocol failure, a missing explicit snapshot, or bounded-output
/// overflow.
#[cfg(feature = "wasix-checkpoint")]
pub async fn capture_wasix_checkpoint(
    config: &WasixWorkerConfig,
    binding: WasixCheckpointBinding,
    module: Vec<u8>,
    input: CommandInput,
) -> Result<WasixCheckpointCapture> {
    config.validate_common()?;
    let (request, execution_timeout, cancellation) = WasixCheckpointCaptureRequest::new(input)?;
    if cancellation.is_cancelled() {
        return Err(Error::Cancelled);
    }
    #[cfg(target_os = "linux")]
    {
        let executable = config.pin_executable()?;
        capture_wasix_checkpoint_linux(
            config,
            executable,
            binding,
            module,
            request,
            execution_timeout,
            cancellation,
        )
        .await
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = (binding, module, request, execution_timeout, cancellation);
        Err(Error::Configuration(
            "WASIX checkpoint capture currently requires Linux".to_owned(),
        ))
    }
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
async fn capture_wasix_checkpoint_linux(
    config: &WasixWorkerConfig,
    executable: PinnedWorkerExecutable,
    binding: WasixCheckpointBinding,
    module: Vec<u8>,
    request: WasixCheckpointCaptureRequest,
    execution_timeout: Duration,
    cancellation: crate::CancellationToken,
) -> Result<WasixCheckpointCapture> {
    if binding.command() != "_start" {
        return Err(Error::UnsupportedComponent(
            "WASIX checkpoint capture supports only the \"_start\" command".to_owned(),
        ));
    }
    if module.is_empty() || module.len() > WASIX_WORKER_MAX_MODULE_BYTES {
        return Err(Error::Checkpoint(
            "WASIX capture module exceeds the worker input limit".to_owned(),
        ));
    }
    let request = serde_json::to_vec(&request).map_err(|error| {
        Error::Configuration(format!("capture request encoding failed: {error}"))
    })?;
    if request.is_empty() || request.len() > WASIX_WORKER_MAX_CAPTURE_REQUEST_BYTES {
        return Err(Error::Configuration(
            "WASIX checkpoint capture request exceeds the protocol limit".to_owned(),
        ));
    }
    let request_bytes = u64::try_from(request.len())
        .map_err(|_| Error::Configuration("capture request length overflows u64".to_owned()))?;
    let request_sha256 = hex::encode(Sha256::digest(&request));
    let deadline = tokio::time::Instant::now() + config.handshake_timeout;
    let preparation = ModulePreparation::new(module);
    let prepared_module = tokio::select! {
        () = cancellation.cancelled() => return Err(Error::Cancelled),
        result = preparation.wait(config.handshake_timeout) => result?,
    };
    if prepared_module.sha256 != binding.module_sha256() {
        return Err(Error::Checkpoint(
            "WASIX capture module does not match the checkpoint binding".to_owned(),
        ));
    }
    let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
    if remaining.is_zero() {
        return Err(Error::Timeout);
    }

    let (control, child_control) = checkpoint_control_channel()?;
    let mut command = executable.command("--checkpoint-capture")?;
    command
        .env_clear()
        .current_dir("/")
        .stdin(child_control)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true);
    let mut worker = spawn_wasix_worker(
        config,
        WasixWorkerOperation::CheckpointCapture,
        &mut command,
        executable.sha256.clone(),
    )
    .await?;
    drop(command);
    let stdout =
        worker.child.stdout.take().ok_or_else(|| {
            Error::Execution("WASIX capture worker stdout was not piped".to_owned())
        })?;
    let stderr = worker.child.stderr.take().ok_or_else(|| {
        Error::Execution("WASIX capture worker diagnostics were not piped".to_owned())
    })?;
    let expected = ExpectedCheckpointCapture {
        binding,
        module_bytes: prepared_module.bytes,
        module_sha256: prepared_module.sha256,
        request_bytes,
        request_sha256,
    };
    let capture_input = CheckpointCaptureInput {
        control: Some(control),
        module: Some(prepared_module.file),
        request,
        expected,
    };
    let (cancel, cancelled) = oneshot::channel();
    let operation = CheckpointCaptureOperation {
        handshake_timeout: remaining,
        execution_timeout,
        allowed_supplementary_groups: config.allowed_supplementary_groups.clone(),
        input: capture_input,
        cancellation,
    };
    let supervisor = tokio::spawn(supervise_checkpoint_capture(
        worker, stdout, stderr, operation, cancelled,
    ));
    CheckpointCaptureSupervisor::new(supervisor, cancel)
        .wait()
        .await
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
async fn restore_wasix_checkpoint_linux(
    config: &WasixWorkerConfig,
    executable: PinnedWorkerExecutable,
    checkpoint: VerifiedWasixCheckpoint,
    module: Vec<u8>,
) -> Result<WasixCheckpointRestoreMetadata> {
    let binding = checkpoint.binding().clone();
    if binding.command() != "_start" {
        return Err(Error::UnsupportedComponent(format!(
            "WASIX checkpoint command {:?} cannot be restored; only \"_start\" is supported",
            binding.command()
        )));
    }
    if module.is_empty() || module.len() > WASIX_WORKER_MAX_MODULE_BYTES {
        return Err(Error::Checkpoint(
            "WASIX restore module exceeds the worker input limit".to_owned(),
        ));
    }
    let (journal, checkpoint_worker_build_sha256) = checkpoint.into_parts();
    if executable.sha256 != checkpoint_worker_build_sha256 {
        return Err(Error::Checkpoint(
            "destination worker build does not match the authenticated source worker".to_owned(),
        ));
    }
    if journal.is_empty() || journal.len() > WASIX_WORKER_MAX_CHECKPOINT_BYTES {
        return Err(Error::Checkpoint(
            "verified checkpoint journal exceeds the worker restore limit".to_owned(),
        ));
    }

    let deadline = tokio::time::Instant::now() + config.handshake_timeout;
    let prepared_module = ModulePreparation::new(module)
        .wait(config.handshake_timeout)
        .await?;
    if prepared_module.sha256 != binding.module_sha256() {
        return Err(Error::Checkpoint(
            "WASIX restore module does not match the authenticated checkpoint binding".to_owned(),
        ));
    }
    let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
    if remaining.is_zero() {
        return Err(Error::Timeout);
    }
    let prepared_checkpoint = CheckpointPreparation::new(journal).wait(remaining).await?;
    let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
    if remaining.is_zero() {
        return Err(Error::Timeout);
    }

    let (control, child_control) = checkpoint_control_channel()?;
    let mut command = executable.command("--checkpoint-restore")?;
    command
        .env_clear()
        .current_dir("/")
        .stdin(child_control)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true);
    let mut worker = spawn_wasix_worker(
        config,
        WasixWorkerOperation::CheckpointRestore,
        &mut command,
        executable.sha256.clone(),
    )
    .await?;
    drop(command);
    let stdout =
        worker.child.stdout.take().ok_or_else(|| {
            Error::Execution("WASIX restore worker stdout was not piped".to_owned())
        })?;
    let stderr = worker.child.stderr.take().ok_or_else(|| {
        Error::Execution("WASIX restore worker diagnostics were not piped".to_owned())
    })?;
    let expected = ExpectedCheckpointRestore {
        binding,
        module_bytes: prepared_module.bytes,
        module_sha256: prepared_module.sha256,
        journal_bytes: prepared_checkpoint.journal_bytes,
        journal_sha256: prepared_checkpoint.journal_sha256,
    };
    let input = CheckpointRestoreInput {
        control: Some(control),
        module: Some(prepared_module.file),
        journal: Some(prepared_checkpoint.file),
        expected,
    };
    let (cancel, cancelled) = oneshot::channel();
    let supervisor = tokio::spawn(supervise_checkpoint_restore(
        worker,
        stdout,
        stderr,
        remaining,
        config.allowed_supplementary_groups.clone(),
        input,
        cancelled,
    ));
    CheckpointRestoreSupervisor::new(supervisor, cancel)
        .wait()
        .await
}

#[cfg(target_os = "linux")]
async fn probe_wasix_checkpoint_transport_linux(
    config: &WasixWorkerConfig,
    executable: PinnedWorkerExecutable,
    checkpoint: VerifiedWasixCheckpoint,
) -> Result<WasixCheckpointTransportMetadata> {
    let binding = checkpoint.binding().clone();
    let (journal, checkpoint_worker_build_sha256) = checkpoint.into_parts();
    if executable.sha256 != checkpoint_worker_build_sha256 {
        return Err(Error::Checkpoint(
            "transport worker build does not match the authenticated source worker".to_owned(),
        ));
    }
    if journal.is_empty() || journal.len() > WASIX_WORKER_MAX_CHECKPOINT_BYTES {
        return Err(Error::Checkpoint(
            "verified checkpoint journal exceeds the worker transport limit".to_owned(),
        ));
    }
    let deadline = tokio::time::Instant::now() + config.handshake_timeout;
    let prepared = CheckpointPreparation::new(journal)
        .wait(config.handshake_timeout)
        .await?;
    let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
    if remaining.is_zero() {
        return Err(Error::Timeout);
    }
    let (control, child_control) = checkpoint_control_channel()?;

    let mut command = executable.command("--checkpoint-transport-probe")?;
    command
        .env_clear()
        .current_dir("/")
        .stdin(child_control)
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .kill_on_drop(true);
    let mut worker = spawn_wasix_worker(
        config,
        WasixWorkerOperation::CheckpointTransport,
        &mut command,
        executable.sha256.clone(),
    )
    .await?;
    drop(command);
    let stdout = worker
        .child
        .stdout
        .take()
        .ok_or_else(|| Error::Execution("WASIX worker stdout was not piped".to_owned()))?;
    let (cancel, cancelled) = oneshot::channel();
    let expected = ExpectedCheckpointTransport {
        binding,
        journal_bytes: prepared.journal_bytes,
        journal_sha256: prepared.journal_sha256,
    };
    let input = CheckpointTransportInput {
        control: Some(control),
        file: Some(prepared.file),
        expected,
    };
    let supervisor = tokio::spawn(supervise_checkpoint_transport(
        worker,
        stdout,
        remaining,
        config.allowed_supplementary_groups.clone(),
        input,
        cancelled,
    ));
    CheckpointTransportSupervisor::new(supervisor, cancel)
        .wait()
        .await
}

#[cfg(target_os = "linux")]
fn sealed_checkpoint_input(
    journal: Vec<u8>,
    cancelled: &AtomicBool,
) -> Result<PreparedCheckpointInput> {
    use rustix::fs::{FileType, MemfdFlags, fcntl_add_seals, fcntl_get_seals, fstat, memfd_create};

    let journal_bytes = u64::try_from(journal.len())
        .map_err(|_| Error::Checkpoint("checkpoint journal length overflows u64".to_owned()))?;
    let descriptor = memfd_create(
        "runtrue-wasix-checkpoint",
        MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING,
    )
    .map_err(|error| Error::Execution(format!("failed to create checkpoint memfd: {error}")))?;
    let mut file = std::fs::File::from(descriptor);
    let mut hash = Sha256::new();
    for chunk in journal.chunks(64 * 1024) {
        if cancelled.load(Ordering::Relaxed) {
            return Err(Error::Cancelled);
        }
        hash.update(chunk);
        file.write_all(chunk).map_err(|error| {
            Error::Execution(format!("failed to fill checkpoint memfd: {error}"))
        })?;
    }
    drop(journal);
    if cancelled.load(Ordering::Relaxed) {
        return Err(Error::Cancelled);
    }
    let journal_sha256 = hex::encode(hash.finalize());
    file.seek(SeekFrom::Start(0))
        .map_err(|error| Error::Execution(format!("failed to rewind checkpoint memfd: {error}")))?;
    fcntl_add_seals(&file, REQUIRED_CHECKPOINT_SEALS)
        .map_err(|error| Error::Execution(format!("failed to seal checkpoint memfd: {error}")))?;
    let installed = fcntl_get_seals(&file).map_err(|error| {
        Error::Execution(format!("failed to verify checkpoint memfd seals: {error}"))
    })?;
    if !installed.contains(REQUIRED_CHECKPOINT_SEALS) {
        return Err(Error::Execution(
            "checkpoint memfd is not fully sealed".to_owned(),
        ));
    }
    let stat = fstat(&file).map_err(|error| {
        Error::Execution(format!("failed to inspect checkpoint memfd: {error}"))
    })?;
    if FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile
        || stat.st_nlink != 0
        || u64::try_from(stat.st_size).ok() != Some(journal_bytes)
    {
        return Err(Error::Execution(
            "checkpoint memfd identity is invalid".to_owned(),
        ));
    }
    Ok(PreparedCheckpointInput {
        file,
        journal_bytes,
        journal_sha256,
    })
}

#[cfg(target_os = "linux")]
struct PreparedCheckpointInput {
    file: std::fs::File,
    journal_bytes: u64,
    journal_sha256: String,
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
struct PreparedModuleInput {
    file: std::fs::File,
    bytes: u64,
    sha256: String,
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
fn sealed_module_input(module: Vec<u8>, cancelled: &AtomicBool) -> Result<PreparedModuleInput> {
    use rustix::fs::{FileType, MemfdFlags, fcntl_add_seals, fcntl_get_seals, fstat, memfd_create};

    let bytes = u64::try_from(module.len())
        .map_err(|_| Error::Checkpoint("WASIX module length overflows u64".to_owned()))?;
    let descriptor = memfd_create(
        "runtrue-wasix-module",
        MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING,
    )
    .map_err(|error| Error::Execution(format!("failed to create module memfd: {error}")))?;
    let mut file = std::fs::File::from(descriptor);
    let mut hash = Sha256::new();
    for chunk in module.chunks(64 * 1024) {
        if cancelled.load(Ordering::Relaxed) {
            return Err(Error::Cancelled);
        }
        hash.update(chunk);
        file.write_all(chunk)
            .map_err(|error| Error::Execution(format!("failed to fill module memfd: {error}")))?;
    }
    drop(module);
    if cancelled.load(Ordering::Relaxed) {
        return Err(Error::Cancelled);
    }
    let sha256 = hex::encode(hash.finalize());
    file.seek(SeekFrom::Start(0))
        .map_err(|error| Error::Execution(format!("failed to rewind module memfd: {error}")))?;
    fcntl_add_seals(&file, REQUIRED_CHECKPOINT_SEALS)
        .map_err(|error| Error::Execution(format!("failed to seal module memfd: {error}")))?;
    let installed = fcntl_get_seals(&file).map_err(|error| {
        Error::Execution(format!("failed to verify module memfd seals: {error}"))
    })?;
    let stat = fstat(&file)
        .map_err(|error| Error::Execution(format!("failed to inspect module memfd: {error}")))?;
    if !installed.contains(REQUIRED_CHECKPOINT_SEALS)
        || FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile
        || stat.st_nlink != 0
        || u64::try_from(stat.st_size).ok() != Some(bytes)
    {
        return Err(Error::Execution(
            "module memfd identity is invalid".to_owned(),
        ));
    }
    Ok(PreparedModuleInput {
        file,
        bytes,
        sha256,
    })
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
struct ModulePreparation {
    task: tokio::task::JoinHandle<Result<PreparedModuleInput>>,
    cancelled: Arc<AtomicBool>,
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
impl ModulePreparation {
    fn new(module: Vec<u8>) -> Self {
        let cancelled = Arc::new(AtomicBool::new(false));
        let task_cancelled = Arc::clone(&cancelled);
        let task = tokio::task::spawn_blocking(move || {
            sealed_module_input(module, task_cancelled.as_ref())
        });
        Self { task, cancelled }
    }

    async fn wait(mut self, timeout: Duration) -> Result<PreparedModuleInput> {
        if let Ok(result) = tokio::time::timeout(timeout, &mut self.task).await {
            result.map_err(|error| {
                Error::Execution(format!("module memfd preparation failed to join: {error}"))
            })?
        } else {
            self.cancelled.store(true, Ordering::Relaxed);
            let _ = (&mut self.task).await;
            Err(Error::Timeout)
        }
    }
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
impl Drop for ModulePreparation {
    fn drop(&mut self) {
        self.cancelled.store(true, Ordering::Relaxed);
        self.task.abort();
    }
}

#[cfg(target_os = "linux")]
struct CheckpointPreparation {
    task: tokio::task::JoinHandle<Result<PreparedCheckpointInput>>,
    cancelled: Arc<AtomicBool>,
}

#[cfg(target_os = "linux")]
impl CheckpointPreparation {
    fn new(journal: Vec<u8>) -> Self {
        let cancelled = Arc::new(AtomicBool::new(false));
        let task_cancelled = Arc::clone(&cancelled);
        let task = tokio::task::spawn_blocking(move || {
            sealed_checkpoint_input(journal, task_cancelled.as_ref())
        });
        Self { task, cancelled }
    }

    async fn wait(mut self, timeout: Duration) -> Result<PreparedCheckpointInput> {
        if let Ok(result) = tokio::time::timeout(timeout, &mut self.task).await {
            result.map_err(|error| {
                Error::Execution(format!(
                    "checkpoint memfd preparation failed to join: {error}"
                ))
            })?
        } else {
            self.cancelled.store(true, Ordering::Relaxed);
            let _ = (&mut self.task).await;
            Err(Error::Timeout)
        }
    }
}

#[cfg(target_os = "linux")]
impl Drop for CheckpointPreparation {
    fn drop(&mut self) {
        self.cancelled.store(true, Ordering::Relaxed);
        self.task.abort();
    }
}

#[cfg(target_os = "linux")]
struct ExpectedCheckpointTransport {
    binding: WasixCheckpointBinding,
    journal_bytes: u64,
    journal_sha256: String,
}

#[cfg(target_os = "linux")]
struct CheckpointTransportInput {
    control: Option<tokio::net::UnixStream>,
    file: Option<std::fs::File>,
    expected: ExpectedCheckpointTransport,
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
struct ExpectedCheckpointRestore {
    binding: WasixCheckpointBinding,
    module_bytes: u64,
    module_sha256: String,
    journal_bytes: u64,
    journal_sha256: String,
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
struct CheckpointRestoreInput {
    control: Option<tokio::net::UnixStream>,
    module: Option<std::fs::File>,
    journal: Option<std::fs::File>,
    expected: ExpectedCheckpointRestore,
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
struct ExpectedCheckpointCapture {
    binding: WasixCheckpointBinding,
    module_bytes: u64,
    module_sha256: String,
    request_bytes: u64,
    request_sha256: String,
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
struct CheckpointCaptureInput {
    control: Option<tokio::net::UnixStream>,
    module: Option<std::fs::File>,
    request: Vec<u8>,
    expected: ExpectedCheckpointCapture,
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
struct CheckpointCaptureOperation {
    handshake_timeout: Duration,
    execution_timeout: Duration,
    allowed_supplementary_groups: Vec<u32>,
    input: CheckpointCaptureInput,
    cancellation: crate::CancellationToken,
}

#[cfg(target_os = "linux")]
fn checkpoint_control_channel() -> Result<(tokio::net::UnixStream, Stdio)> {
    use rustix::net::{AddressFamily, SocketFlags, SocketType, socketpair};

    let (parent, child) = socketpair(
        AddressFamily::UNIX,
        SocketType::STREAM,
        SocketFlags::CLOEXEC,
        None,
    )
    .map_err(|error| {
        Error::Execution(format!(
            "failed to create checkpoint descriptor channel: {error}"
        ))
    })?;
    let parent = std::os::unix::net::UnixStream::from(parent);
    parent.set_nonblocking(true).map_err(|error| {
        Error::Execution(format!(
            "failed to configure checkpoint descriptor channel: {error}"
        ))
    })?;
    let parent = tokio::net::UnixStream::from_std(parent).map_err(|error| {
        Error::Execution(format!(
            "failed to register checkpoint descriptor channel: {error}"
        ))
    })?;
    Ok((parent, Stdio::from(std::fs::File::from(child))))
}

#[cfg(target_os = "linux")]
async fn send_checkpoint_descriptor(
    control: &tokio::net::UnixStream,
    checkpoint: &std::fs::File,
    marker: u8,
) -> Result<()> {
    loop {
        control.writable().await.map_err(|error| {
            Error::Execution(format!(
                "checkpoint descriptor channel was not writable: {error}"
            ))
        })?;
        match control.try_io(tokio::io::Interest::WRITABLE, || {
            send_checkpoint_descriptor_once(control, checkpoint, marker)
        }) {
            Ok(()) => return Ok(()),
            Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {}
            Err(error) => {
                return Err(Error::Execution(format!(
                    "failed to send checkpoint descriptor: {error}"
                )));
            }
        }
    }
}

#[cfg(target_os = "linux")]
fn send_checkpoint_descriptor_once(
    control: &tokio::net::UnixStream,
    checkpoint: &std::fs::File,
    marker: u8,
) -> std::io::Result<()> {
    use rustix::net::{SendAncillaryBuffer, SendAncillaryMessage, SendFlags, sendmsg};
    use std::{io::IoSlice, mem::MaybeUninit, os::fd::AsFd as _};

    let descriptors = [checkpoint.as_fd()];
    let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
    let mut ancillary = SendAncillaryBuffer::new(&mut space);
    if !ancillary.push(SendAncillaryMessage::ScmRights(&descriptors)) {
        return Err(std::io::Error::other(
            "checkpoint descriptor ancillary buffer is too small",
        ));
    }
    let marker = [marker];
    let sent = sendmsg(
        control,
        &[IoSlice::new(&marker)],
        &mut ancillary,
        SendFlags::NOSIGNAL,
    )
    .map_err(std::io::Error::from)?;
    if sent != marker.len() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::WriteZero,
            "checkpoint descriptor marker was not sent",
        ));
    }
    Ok(())
}

#[cfg(target_os = "linux")]
async fn supervise_checkpoint_transport(
    mut worker: WorkerProcess,
    mut stdout: tokio::process::ChildStdout,
    handshake_timeout: Duration,
    allowed_supplementary_groups: Vec<u32>,
    mut input: CheckpointTransportInput,
    mut cancelled: oneshot::Receiver<()>,
) -> Result<WasixCheckpointTransportMetadata> {
    let process_id = worker.process_id;
    let outcome = tokio::select! {
        biased;
        _ = &mut cancelled => Err(Error::Cancelled),
        result = tokio::time::timeout(
            handshake_timeout,
            perform_checkpoint_transport(
                &mut worker,
                &mut stdout,
                process_id,
                &allowed_supplementary_groups,
                &mut input,
            ),
        ) => match result {
            Ok(result) => result,
            Err(_) => Err(Error::Timeout),
        },
    };

    if outcome.is_err() && worker.active {
        drop(stdout);
        spawn_worker_reaper(worker);
    }
    outcome
}

#[cfg(target_os = "linux")]
async fn perform_checkpoint_transport(
    worker: &mut WorkerProcess,
    stdout: &mut tokio::process::ChildStdout,
    process_id: u32,
    allowed_supplementary_groups: &[u32],
    input: &mut CheckpointTransportInput,
) -> Result<WasixCheckpointTransportMetadata> {
    let ready = read_frame(stdout).await?;
    let metadata: WasixWorkerMetadata = serde_json::from_slice(&ready)
        .map_err(|error| Error::Execution(format!("invalid WASIX worker ready frame: {error}")))?;
    metadata.validate(
        process_id,
        &worker.worker_build_sha256,
        allowed_supplementary_groups,
    )?;

    let control = input
        .control
        .as_ref()
        .ok_or_else(|| Error::Execution("checkpoint control socket is unavailable".to_owned()))?;
    let file = input
        .file
        .as_ref()
        .ok_or_else(|| Error::Execution("sealed checkpoint input is unavailable".to_owned()))?;
    send_checkpoint_descriptor(control, file, b'C').await?;
    input.control.take();
    input.file.take();

    let frame = read_frame(stdout).await?;
    let acknowledgement: WasixCheckpointTransportAck =
        serde_json::from_slice(&frame).map_err(|error| {
            Error::Execution(format!("invalid WASIX checkpoint acknowledgement: {error}"))
        })?;
    acknowledgement.validate(input.expected.journal_bytes, &input.expected.journal_sha256)?;
    finish_worker_output(worker, stdout, "checkpoint transport").await?;
    Ok(WasixCheckpointTransportMetadata {
        worker: metadata,
        binding: input.expected.binding.clone(),
        journal_bytes: acknowledgement.journal_bytes,
        journal_sha256: acknowledgement.journal_sha256,
    })
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
async fn supervise_checkpoint_restore(
    mut worker: WorkerProcess,
    mut stdout: tokio::process::ChildStdout,
    mut stderr: tokio::process::ChildStderr,
    handshake_timeout: Duration,
    allowed_supplementary_groups: Vec<u32>,
    mut input: CheckpointRestoreInput,
    mut cancelled: oneshot::Receiver<()>,
) -> Result<WasixCheckpointRestoreMetadata> {
    let diagnostics = tokio::spawn(async move { read_worker_diagnostics(&mut stderr).await });
    let process_id = worker.process_id;
    let outcome = tokio::select! {
        biased;
        _ = &mut cancelled => Err(Error::Cancelled),
        result = tokio::time::timeout(
            handshake_timeout,
            perform_checkpoint_restore(
                &mut worker,
                &mut stdout,
                process_id,
                &allowed_supplementary_groups,
                &mut input,
            ),
        ) => match result {
            Ok(result) => result.map_err(|failure| {
                Error::CheckpointRestore(WasixCheckpointRestoreFailure::new(
                    failure.phase,
                    failure.reason,
                    WasixWorkerDiagnostics::new(Vec::new(), false),
                ))
            }),
            Err(_) => Err(Error::Timeout),
        },
    };

    let mut observed_exit_status = None;
    if outcome.is_err() && worker.active {
        drop(stdout);
        observed_exit_status = observe_failed_restore_worker_exit(&mut worker).await;
        worker.kill_tree();
        if observed_exit_status.is_none() {
            let _ = worker.child.start_kill();
            let _ = worker.child.wait().await;
        }
        worker.disarm();
    }
    let diagnostics = match diagnostics.await {
        Ok(Ok(diagnostics)) => diagnostics,
        Ok(Err(_)) | Err(_) => WasixWorkerDiagnostics::new(Vec::new(), true),
    };
    match outcome {
        Ok(mut metadata) => {
            metadata.worker_diagnostics = diagnostics;
            Ok(metadata)
        }
        Err(Error::CheckpointRestore(failure)) => {
            let failure =
                WasixCheckpointRestoreFailure::new(failure.phase(), failure.reason(), diagnostics);
            let failure = if let Some(status) = observed_exit_status {
                let (exit_code, exit_signal) = worker_exit_status_parts(status);
                failure.with_exit_status(exit_code, exit_signal)
            } else {
                failure
            };
            Err(Error::CheckpointRestore(failure))
        }
        Err(error) => Err(error),
    }
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
async fn observe_failed_restore_worker_exit(
    worker: &mut WorkerProcess,
) -> Option<std::process::ExitStatus> {
    if let Ok(Some(status)) = worker.child.try_wait() {
        return Some(status);
    }
    tokio::time::timeout(Duration::from_millis(100), worker.child.wait())
        .await
        .ok()
        .and_then(std::result::Result::ok)
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
fn worker_exit_status_parts(status: std::process::ExitStatus) -> (Option<i32>, Option<i32>) {
    use std::os::unix::process::ExitStatusExt as _;
    (status.code(), status.signal())
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
struct RestoreOperationFailure {
    phase: WasixCheckpointRestorePhase,
    reason: WasixCheckpointRestoreFailureReason,
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
impl RestoreOperationFailure {
    const fn new(
        phase: WasixCheckpointRestorePhase,
        reason: WasixCheckpointRestoreFailureReason,
    ) -> Self {
        Self { phase, reason }
    }

    const fn protocol(phase: WasixCheckpointRestorePhase) -> Self {
        Self::new(phase, WasixCheckpointRestoreFailureReason::Protocol)
    }

    const fn runtime() -> Self {
        Self::new(
            WasixCheckpointRestorePhase::Execution,
            WasixCheckpointRestoreFailureReason::Runtime,
        )
    }
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
async fn read_worker_diagnostics(
    stderr: &mut (impl AsyncRead + Unpin),
) -> std::io::Result<WasixWorkerDiagnostics> {
    let mut bytes = Vec::new();
    bytes
        .try_reserve_exact(WASIX_WORKER_MAX_DIAGNOSTIC_BYTES)
        .map_err(|error| std::io::Error::other(format!("diagnostic allocation failed: {error}")))?;
    let mut truncated = false;
    let mut buffer = [0_u8; 4096];
    loop {
        let read = stderr.read(&mut buffer).await?;
        if read == 0 {
            break;
        }
        let remaining = WASIX_WORKER_MAX_DIAGNOSTIC_BYTES.saturating_sub(bytes.len());
        let retained = read.min(remaining);
        bytes.extend_from_slice(&buffer[..retained]);
        truncated |= retained != read;
    }
    Ok(WasixWorkerDiagnostics::new(bytes, truncated))
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
async fn perform_checkpoint_restore(
    worker: &mut WorkerProcess,
    stdout: &mut tokio::process::ChildStdout,
    process_id: u32,
    allowed_supplementary_groups: &[u32],
    input: &mut CheckpointRestoreInput,
) -> std::result::Result<WasixCheckpointRestoreMetadata, RestoreOperationFailure> {
    let (metadata, acknowledgement) = prepare_checkpoint_restore(
        stdout,
        process_id,
        &worker.worker_build_sha256,
        allowed_supplementary_groups,
        input,
    )
    .await?;
    input.control.take();
    input.module.take();
    input.journal.take();
    let (restored_stdout, restored_stderr) = collect_checkpoint_restore_output(stdout).await?;
    finish_worker_output(worker, stdout, "checkpoint restore")
        .await
        .map_err(|_| {
            RestoreOperationFailure::new(
                WasixCheckpointRestorePhase::Shutdown,
                WasixCheckpointRestoreFailureReason::WorkerProcess,
            )
        })?;
    Ok(WasixCheckpointRestoreMetadata {
        worker: metadata,
        binding: input.expected.binding.clone(),
        stdout: restored_stdout,
        stderr: restored_stderr,
        worker_diagnostics: WasixWorkerDiagnostics::new(Vec::new(), false),
        module_sha256: acknowledgement.module_sha256,
        journal_sha256: acknowledgement.journal_sha256,
    })
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
async fn prepare_checkpoint_restore(
    stdout: &mut tokio::process::ChildStdout,
    process_id: u32,
    expected_worker_build_sha256: &str,
    allowed_supplementary_groups: &[u32],
    input: &mut CheckpointRestoreInput,
) -> std::result::Result<(WasixWorkerMetadata, WasixCheckpointRestoreAck), RestoreOperationFailure>
{
    use tokio::io::AsyncWriteExt as _;

    let ready_failure = || RestoreOperationFailure::protocol(WasixCheckpointRestorePhase::Ready);
    let ready = read_frame(stdout).await.map_err(|_| ready_failure())?;
    let metadata: WasixWorkerMetadata =
        serde_json::from_slice(&ready).map_err(|_| ready_failure())?;
    metadata
        .validate(
            process_id,
            expected_worker_build_sha256,
            allowed_supplementary_groups,
        )
        .map_err(|_| ready_failure())?;

    let input_failure = || RestoreOperationFailure::protocol(WasixCheckpointRestorePhase::Input);
    let control = input.control.as_mut().ok_or_else(input_failure)?;
    let module = input.module.as_ref().ok_or_else(input_failure)?;
    send_checkpoint_descriptor(control, module, b'M')
        .await
        .map_err(|_| input_failure())?;
    let journal = input.journal.as_ref().ok_or_else(input_failure)?;
    send_checkpoint_descriptor(control, journal, b'C')
        .await
        .map_err(|_| input_failure())?;
    let frame = read_frame(stdout).await.map_err(|_| input_failure())?;
    let acknowledgement: WasixCheckpointRestoreAck =
        serde_json::from_slice(&frame).map_err(|_| input_failure())?;
    acknowledgement
        .validate(
            input.expected.module_bytes,
            &input.expected.module_sha256,
            input.expected.journal_bytes,
            &input.expected.journal_sha256,
        )
        .map_err(|_| input_failure())?;

    let authorization_failure =
        || RestoreOperationFailure::protocol(WasixCheckpointRestorePhase::Authorization);
    control
        .write_all(b"E")
        .await
        .map_err(|_| authorization_failure())?;
    control
        .shutdown()
        .await
        .map_err(|_| authorization_failure())?;
    Ok((metadata, acknowledgement))
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
async fn collect_checkpoint_restore_output(
    stdout: &mut tokio::process::ChildStdout,
) -> std::result::Result<(Vec<u8>, Vec<u8>), RestoreOperationFailure> {
    let frame = read_frame(stdout)
        .await
        .map_err(|_| RestoreOperationFailure::runtime())?;
    let completion: WasixCheckpointRestoreCompletion = serde_json::from_slice(&frame)
        .map_err(|_| RestoreOperationFailure::protocol(WasixCheckpointRestorePhase::Execution))?;
    let output_failure = || RestoreOperationFailure::protocol(WasixCheckpointRestorePhase::Output);
    let restored_stdout = read_restore_output_frame(stdout, "stdout")
        .await
        .map_err(|_| output_failure())?;
    let restored_stderr = read_restore_output_frame(stdout, "stderr")
        .await
        .map_err(|_| output_failure())?;
    completion
        .validate(&restored_stdout, &restored_stderr)
        .map_err(|_| RestoreOperationFailure::protocol(WasixCheckpointRestorePhase::Output))?;
    Ok((restored_stdout, restored_stderr))
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
async fn supervise_checkpoint_capture(
    mut worker: WorkerProcess,
    mut stdout: tokio::process::ChildStdout,
    mut stderr: tokio::process::ChildStderr,
    mut operation: CheckpointCaptureOperation,
    mut cancelled: oneshot::Receiver<()>,
) -> Result<WasixCheckpointCapture> {
    let diagnostics = tokio::spawn(async move { read_worker_diagnostics(&mut stderr).await });
    let process_id = worker.process_id;
    let cancellation = operation.cancellation.clone();
    let outcome = tokio::select! {
        biased;
        _ = &mut cancelled => Err(Error::Cancelled),
        () = cancellation.cancelled() => Err(Error::Cancelled),
        result = perform_checkpoint_capture(
            &mut worker,
            &mut stdout,
            process_id,
            &operation.allowed_supplementary_groups,
            operation.handshake_timeout,
            operation.execution_timeout,
            &mut operation.input,
        ) => match result {
            Ok(capture) => Ok(capture),
            Err(CaptureOperationError::Failure(failure)) => {
                let public_failure = WasixCheckpointCaptureFailure::new(
                    failure.phase,
                    failure.reason,
                    WasixWorkerDiagnostics::new(Vec::new(), false),
                );
                let public_failure = if let Some(status) = failure.exit_status {
                    let (exit_code, exit_signal) = worker_exit_status_parts(status);
                    public_failure.with_exit_status(exit_code, exit_signal)
                } else {
                    public_failure
                };
                Err(Error::CheckpointCapture(public_failure))
            }
            Err(CaptureOperationError::Timeout) => Err(Error::Timeout),
        },
    };

    let mut observed_exit_status = None;
    if outcome.is_err() && worker.active {
        drop(stdout);
        if matches!(&outcome, Err(Error::CheckpointCapture(_))) {
            observed_exit_status = observe_failed_worker_exit(&mut worker).await;
        }
        worker.kill_tree();
        if observed_exit_status.is_none() {
            let _ = worker.child.start_kill();
            let _ = worker.child.wait().await;
        }
        worker.disarm();
    }
    let diagnostics = match diagnostics.await {
        Ok(Ok(diagnostics)) => diagnostics,
        Ok(Err(_)) | Err(_) => WasixWorkerDiagnostics::new(Vec::new(), true),
    };
    match outcome {
        Ok(capture) => Ok(capture),
        Err(Error::CheckpointCapture(failure)) => {
            let exit_status = observed_exit_status.map(worker_exit_status_parts);
            let exit_code = exit_status.map_or_else(|| failure.exit_code(), |status| status.0);
            let exit_signal = exit_status.map_or_else(|| failure.exit_signal(), |status| status.1);
            Err(Error::CheckpointCapture(
                WasixCheckpointCaptureFailure::new(failure.phase(), failure.reason(), diagnostics)
                    .with_exit_status(exit_code, exit_signal),
            ))
        }
        Err(error) => Err(error),
    }
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
enum CaptureOperationError {
    Failure(CaptureOperationFailure),
    Timeout,
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
impl From<CaptureOperationFailure> for CaptureOperationError {
    fn from(failure: CaptureOperationFailure) -> Self {
        Self::Failure(failure)
    }
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
struct CaptureOperationFailure {
    phase: WasixCheckpointCapturePhase,
    reason: WasixCheckpointCaptureFailureReason,
    exit_status: Option<std::process::ExitStatus>,
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
impl CaptureOperationFailure {
    const fn new(
        phase: WasixCheckpointCapturePhase,
        reason: WasixCheckpointCaptureFailureReason,
    ) -> Self {
        Self {
            phase,
            reason,
            exit_status: None,
        }
    }

    const fn protocol(phase: WasixCheckpointCapturePhase) -> Self {
        Self::new(phase, WasixCheckpointCaptureFailureReason::Protocol)
    }

    const fn runtime() -> Self {
        Self::new(
            WasixCheckpointCapturePhase::Execution,
            WasixCheckpointCaptureFailureReason::Runtime,
        )
    }

    fn worker_process(status: std::process::ExitStatus) -> Self {
        Self {
            phase: WasixCheckpointCapturePhase::Shutdown,
            reason: WasixCheckpointCaptureFailureReason::WorkerProcess,
            exit_status: Some(status),
        }
    }
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
async fn observe_failed_worker_exit(
    worker: &mut WorkerProcess,
) -> Option<std::process::ExitStatus> {
    if let Ok(Some(status)) = worker.child.try_wait() {
        return Some(status);
    }
    tokio::time::timeout(Duration::from_millis(100), worker.child.wait())
        .await
        .ok()
        .and_then(std::result::Result::ok)
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
async fn perform_checkpoint_capture(
    worker: &mut WorkerProcess,
    stdout: &mut tokio::process::ChildStdout,
    process_id: u32,
    allowed_supplementary_groups: &[u32],
    handshake_timeout: Duration,
    execution_timeout: Duration,
    input: &mut CheckpointCaptureInput,
) -> std::result::Result<WasixCheckpointCapture, CaptureOperationError> {
    let (metadata, acknowledgement) = tokio::time::timeout(
        handshake_timeout,
        prepare_checkpoint_capture(
            stdout,
            process_id,
            &worker.worker_build_sha256,
            allowed_supplementary_groups,
            input,
        ),
    )
    .await
    .map_err(|_| CaptureOperationError::Timeout)??;
    let (completion, journal, captured_stdout, captured_stderr) = tokio::time::timeout(
        execution_timeout,
        collect_checkpoint_capture_output(worker, stdout),
    )
    .await
    .map_err(|_| CaptureOperationError::Timeout)??;
    let journal = CapturedWasixJournal::from_attested_worker_capture(
        journal,
        input.expected.binding.clone(),
        metadata.worker_build_sha256.clone(),
    )
    .map_err(|_| CaptureOperationFailure::protocol(WasixCheckpointCapturePhase::Output))?;
    Ok(WasixCheckpointCapture {
        worker: metadata,
        binding: input.expected.binding.clone(),
        stdout: captured_stdout,
        stderr: captured_stderr,
        module_sha256: acknowledgement.module_sha256,
        journal_sha256: completion.journal_sha256,
        journal,
    })
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
async fn prepare_checkpoint_capture(
    stdout: &mut tokio::process::ChildStdout,
    process_id: u32,
    expected_worker_build_sha256: &str,
    allowed_supplementary_groups: &[u32],
    input: &mut CheckpointCaptureInput,
) -> std::result::Result<(WasixWorkerMetadata, WasixCheckpointCaptureAck), CaptureOperationFailure>
{
    use tokio::io::AsyncWriteExt as _;

    let ready_failure = || CaptureOperationFailure::protocol(WasixCheckpointCapturePhase::Ready);
    let ready = read_frame(stdout).await.map_err(|_| ready_failure())?;
    let metadata: WasixWorkerMetadata =
        serde_json::from_slice(&ready).map_err(|_| ready_failure())?;
    metadata
        .validate(
            process_id,
            expected_worker_build_sha256,
            allowed_supplementary_groups,
        )
        .map_err(|_| ready_failure())?;

    let input_failure = || CaptureOperationFailure::protocol(WasixCheckpointCapturePhase::Input);
    let control = input.control.as_mut().ok_or_else(input_failure)?;
    let module = input.module.as_ref().ok_or_else(input_failure)?;
    send_checkpoint_descriptor(control, module, b'M')
        .await
        .map_err(|_| input_failure())?;
    write_control_frame(control, &input.request)
        .await
        .map_err(|_| input_failure())?;
    let frame = read_frame(stdout).await.map_err(|_| input_failure())?;
    let acknowledgement: WasixCheckpointCaptureAck =
        serde_json::from_slice(&frame).map_err(|_| input_failure())?;
    if acknowledgement.module_bytes != input.expected.module_bytes
        || acknowledgement.module_sha256 != input.expected.module_sha256
        || acknowledgement.request_bytes != input.expected.request_bytes
        || acknowledgement.request_sha256 != input.expected.request_sha256
    {
        return Err(input_failure());
    }

    let authorization_failure =
        || CaptureOperationFailure::protocol(WasixCheckpointCapturePhase::Authorization);
    control
        .write_all(b"E")
        .await
        .map_err(|_| authorization_failure())?;
    control
        .shutdown()
        .await
        .map_err(|_| authorization_failure())?;
    input.control.take();
    input.module.take();
    Ok((metadata, acknowledgement))
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
async fn collect_checkpoint_capture_output(
    worker: &mut WorkerProcess,
    stdout: &mut tokio::process::ChildStdout,
) -> std::result::Result<
    (WasixCheckpointCaptureCompletion, Vec<u8>, Vec<u8>, Vec<u8>),
    CaptureOperationFailure,
> {
    let frame = read_frame(stdout)
        .await
        .map_err(|_| CaptureOperationFailure::runtime())?;
    let completion: WasixCheckpointCaptureCompletion = serde_json::from_slice(&frame)
        .map_err(|_| CaptureOperationFailure::protocol(WasixCheckpointCapturePhase::Execution))?;
    let output_failure = || CaptureOperationFailure::protocol(WasixCheckpointCapturePhase::Output);
    let journal = read_bounded_worker_frame(
        stdout,
        WASIX_WORKER_MAX_CHECKPOINT_BYTES,
        false,
        "capture journal",
    )
    .await
    .map_err(|_| output_failure())?;
    let captured_stdout = read_bounded_worker_frame(
        stdout,
        WASIX_WORKER_MAX_RESTORE_OUTPUT_BYTES,
        true,
        "capture stdout",
    )
    .await
    .map_err(|_| output_failure())?;
    let captured_stderr = read_bounded_worker_frame(
        stdout,
        WASIX_WORKER_MAX_RESTORE_OUTPUT_BYTES,
        true,
        "capture stderr",
    )
    .await
    .map_err(|_| output_failure())?;
    completion
        .validate(&journal, &captured_stdout, &captured_stderr)
        .map_err(|_| output_failure())?;
    finish_checkpoint_capture_output(worker, stdout).await?;
    Ok((completion, journal, captured_stdout, captured_stderr))
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
async fn finish_checkpoint_capture_output(
    worker: &mut WorkerProcess,
    stdout: &mut tokio::process::ChildStdout,
) -> std::result::Result<(), CaptureOperationFailure> {
    let shutdown_failure =
        || CaptureOperationFailure::protocol(WasixCheckpointCapturePhase::Shutdown);
    let mut trailing = [0_u8; 1];
    if stdout
        .read(&mut trailing)
        .await
        .map_err(|_| shutdown_failure())?
        != 0
    {
        return Err(shutdown_failure());
    }
    let status = worker.child.wait().await.map_err(|_| {
        CaptureOperationFailure::new(
            WasixCheckpointCapturePhase::Shutdown,
            WasixCheckpointCaptureFailureReason::WorkerProcess,
        )
    })?;
    worker.kill_tree();
    worker.disarm();
    if !status.success() {
        return Err(CaptureOperationFailure::worker_process(status));
    }
    Ok(())
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
async fn write_control_frame(control: &mut tokio::net::UnixStream, frame: &[u8]) -> Result<()> {
    use tokio::io::AsyncWriteExt as _;

    let length = u32::try_from(frame.len())
        .map_err(|_| Error::Configuration("capture request length overflows u32".to_owned()))?;
    control
        .write_all(&length.to_be_bytes())
        .await
        .map_err(|error| Error::Execution(format!("failed to send capture request: {error}")))?;
    control
        .write_all(frame)
        .await
        .map_err(|error| Error::Execution(format!("failed to send capture request: {error}")))
}

async fn supervise_probe(
    mut worker: WorkerProcess,
    mut stdout: tokio::process::ChildStdout,
    handshake_timeout: Duration,
    allowed_supplementary_groups: Vec<u32>,
    mut cancelled: oneshot::Receiver<()>,
) -> Result<WasixWorkerMetadata> {
    let process_id = worker.process_id;
    let outcome = tokio::select! {
        biased;
        _ = &mut cancelled => Err(Error::Cancelled),
        result = tokio::time::timeout(
            handshake_timeout,
            perform_handshake(
                &mut worker,
                &mut stdout,
                process_id,
                &allowed_supplementary_groups,
            ),
        ) => match result {
            Ok(result) => result,
            Err(_) => Err(Error::Timeout),
        },
    };

    if outcome.is_err() && worker.active {
        drop(stdout);
        spawn_worker_reaper(worker);
    }
    outcome
}

async fn perform_handshake(
    worker: &mut WorkerProcess,
    stdout: &mut tokio::process::ChildStdout,
    process_id: u32,
    allowed_supplementary_groups: &[u32],
) -> Result<WasixWorkerMetadata> {
    let frame = read_frame(stdout).await?;
    let metadata: WasixWorkerMetadata = serde_json::from_slice(&frame)
        .map_err(|error| Error::Execution(format!("invalid WASIX worker ready frame: {error}")))?;
    metadata.validate(
        process_id,
        &worker.worker_build_sha256,
        allowed_supplementary_groups,
    )?;

    finish_worker_output(worker, stdout, "probe").await?;
    Ok(metadata)
}

async fn finish_worker_output(
    worker: &mut WorkerProcess,
    stdout: &mut tokio::process::ChildStdout,
    operation: &str,
) -> Result<()> {
    let mut trailing = [0_u8; 1];
    if stdout.read(&mut trailing).await.map_err(|error| {
        Error::Execution(format!(
            "failed to finish WASIX worker {operation}: {error}"
        ))
    })? != 0
    {
        return Err(Error::Execution(format!(
            "WASIX worker emitted trailing {operation} bytes"
        )));
    }
    let status = worker.child.wait().await.map_err(|error| {
        Error::Execution(format!(
            "failed to wait for WASIX worker {operation}: {error}"
        ))
    })?;
    worker.kill_tree();
    worker.disarm();
    if !status.success() {
        return Err(Error::Execution(format!(
            "WASIX worker {operation} exited with {status}"
        )));
    }
    Ok(())
}

struct ProbeSupervisor {
    task: tokio::task::JoinHandle<Result<WasixWorkerMetadata>>,
    cancel: Option<oneshot::Sender<()>>,
}

impl ProbeSupervisor {
    const fn new(
        task: tokio::task::JoinHandle<Result<WasixWorkerMetadata>>,
        cancel: oneshot::Sender<()>,
    ) -> Self {
        Self {
            task,
            cancel: Some(cancel),
        }
    }

    async fn wait(mut self) -> Result<WasixWorkerMetadata> {
        let outcome = (&mut self.task).await.map_err(|error| {
            Error::Execution(format!("WASIX worker supervisor failed: {error}"))
        })?;
        self.cancel.take();
        outcome
    }
}

impl Drop for ProbeSupervisor {
    fn drop(&mut self) {
        if let Some(cancel) = self.cancel.take() {
            let _ = cancel.send(());
        }
    }
}

struct CheckpointTransportSupervisor {
    task: tokio::task::JoinHandle<Result<WasixCheckpointTransportMetadata>>,
    cancel: Option<oneshot::Sender<()>>,
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
struct CheckpointRestoreSupervisor {
    task: tokio::task::JoinHandle<Result<WasixCheckpointRestoreMetadata>>,
    cancel: Option<oneshot::Sender<()>>,
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
impl CheckpointRestoreSupervisor {
    const fn new(
        task: tokio::task::JoinHandle<Result<WasixCheckpointRestoreMetadata>>,
        cancel: oneshot::Sender<()>,
    ) -> Self {
        Self {
            task,
            cancel: Some(cancel),
        }
    }

    async fn wait(mut self) -> Result<WasixCheckpointRestoreMetadata> {
        let outcome = (&mut self.task).await.map_err(|error| {
            Error::Execution(format!(
                "WASIX checkpoint restore supervisor failed: {error}"
            ))
        })?;
        self.cancel.take();
        outcome
    }
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
impl Drop for CheckpointRestoreSupervisor {
    fn drop(&mut self) {
        if let Some(cancel) = self.cancel.take() {
            let _ = cancel.send(());
        }
    }
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
struct CheckpointCaptureSupervisor {
    task: tokio::task::JoinHandle<Result<WasixCheckpointCapture>>,
    cancel: Option<oneshot::Sender<()>>,
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
impl CheckpointCaptureSupervisor {
    const fn new(
        task: tokio::task::JoinHandle<Result<WasixCheckpointCapture>>,
        cancel: oneshot::Sender<()>,
    ) -> Self {
        Self {
            task,
            cancel: Some(cancel),
        }
    }

    async fn wait(mut self) -> Result<WasixCheckpointCapture> {
        let outcome = (&mut self.task).await.map_err(|error| {
            Error::Execution(format!(
                "WASIX checkpoint capture supervisor failed: {error}"
            ))
        })?;
        self.cancel.take();
        outcome
    }
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
impl Drop for CheckpointCaptureSupervisor {
    fn drop(&mut self) {
        if let Some(cancel) = self.cancel.take() {
            let _ = cancel.send(());
        }
    }
}

impl CheckpointTransportSupervisor {
    const fn new(
        task: tokio::task::JoinHandle<Result<WasixCheckpointTransportMetadata>>,
        cancel: oneshot::Sender<()>,
    ) -> Self {
        Self {
            task,
            cancel: Some(cancel),
        }
    }

    async fn wait(mut self) -> Result<WasixCheckpointTransportMetadata> {
        let outcome = (&mut self.task).await.map_err(|error| {
            Error::Execution(format!(
                "WASIX checkpoint transport supervisor failed: {error}"
            ))
        })?;
        self.cancel.take();
        outcome
    }
}

impl Drop for CheckpointTransportSupervisor {
    fn drop(&mut self) {
        if let Some(cancel) = self.cancel.take() {
            let _ = cancel.send(());
        }
    }
}

async fn spawn_wasix_worker(
    config: &WasixWorkerConfig,
    operation: WasixWorkerOperation,
    command: &mut Command,
    worker_build_sha256: String,
) -> Result<WorkerProcess> {
    #[cfg(unix)]
    command.process_group(0);
    let child = command.spawn().map_err(|error| {
        Error::Execution(format!(
            "failed to spawn WASIX worker {}: {error}",
            config.executable.display()
        ))
    })?;
    let mut worker = WorkerProcess::new(child, worker_build_sha256)?;

    if let Some(placement) = &config.placement {
        let request = WasixWorkerPlacementRequest {
            process_id: worker.process_id,
            operation,
        };
        let outcome =
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| placement.place(request)));
        let rejection = match outcome {
            Ok(Ok(())) => None,
            Ok(Err(error)) => Some(format!(
                "WASIX worker placement rejected the process: {error}"
            )),
            Err(_) => Some("WASIX worker placement policy panicked".to_owned()),
        };
        if let Some(rejection) = rejection {
            worker.kill_tree();
            let _ = worker.child.start_kill();
            let _ = worker.child.wait().await;
            worker.disarm();
            return Err(Error::Execution(rejection));
        }
    }

    Ok(worker)
}

struct WorkerProcess {
    child: tokio::process::Child,
    process_id: u32,
    worker_build_sha256: String,
    active: bool,
}

impl WorkerProcess {
    fn new(child: tokio::process::Child, worker_build_sha256: String) -> Result<Self> {
        let process_id = child.id().ok_or_else(|| {
            Error::Execution("WASIX worker did not expose a process identifier".to_owned())
        })?;
        Ok(Self {
            child,
            process_id,
            worker_build_sha256,
            active: true,
        })
    }

    fn kill_tree(&mut self) {
        if !self.active {
            return;
        }
        #[cfg(unix)]
        if let Some(group) = rustix::process::Pid::from_raw(self.process_id.cast_signed()) {
            let _ = rustix::process::kill_process_group(group, rustix::process::Signal::KILL);
        }
    }

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

fn spawn_worker_reaper(mut worker: WorkerProcess) {
    worker.kill_tree();
    let _ = worker.child.start_kill();
    tokio::spawn(async move {
        let _ = worker.child.wait().await;
        worker.disarm();
    });
}

impl Drop for WorkerProcess {
    fn drop(&mut self) {
        self.kill_tree();
        if self.active {
            let _ = self.child.start_kill();
        }
    }
}

async fn read_frame(reader: &mut (impl AsyncRead + Unpin)) -> Result<Vec<u8>> {
    let mut length = [0_u8; 4];
    reader.read_exact(&mut length).await.map_err(|error| {
        Error::Execution(format!("failed to read WASIX worker frame length: {error}"))
    })?;
    let length = usize::try_from(u32::from_be_bytes(length)).unwrap_or(usize::MAX);
    if length == 0 || length > MAX_HANDSHAKE_BYTES {
        return Err(Error::Execution(format!(
            "WASIX worker frame length {length} is invalid"
        )));
    }
    let mut frame = Vec::new();
    frame.try_reserve_exact(length).map_err(|error| {
        Error::Execution(format!("failed to allocate WASIX worker frame: {error}"))
    })?;
    frame.resize(length, 0);
    reader
        .read_exact(&mut frame)
        .await
        .map_err(|error| Error::Execution(format!("failed to read WASIX worker frame: {error}")))?;
    Ok(frame)
}

#[cfg(feature = "wasix-checkpoint")]
async fn read_restore_output_frame(
    reader: &mut (impl AsyncRead + Unpin),
    stream: &str,
) -> Result<Vec<u8>> {
    read_bounded_worker_frame(
        reader,
        WASIX_WORKER_MAX_RESTORE_OUTPUT_BYTES,
        true,
        &format!("restore {stream}"),
    )
    .await
}

#[cfg(feature = "wasix-checkpoint")]
async fn read_bounded_worker_frame(
    reader: &mut (impl AsyncRead + Unpin),
    maximum: usize,
    allow_empty: bool,
    label: &str,
) -> Result<Vec<u8>> {
    let mut length = [0_u8; 4];
    reader.read_exact(&mut length).await.map_err(|error| {
        Error::Execution(format!("failed to read WASIX {label} length: {error}"))
    })?;
    let length = usize::try_from(u32::from_be_bytes(length)).unwrap_or(usize::MAX);
    if (!allow_empty && length == 0) || length > maximum {
        return Err(Error::Execution(format!(
            "WASIX {label} length {length} is invalid"
        )));
    }
    let mut frame = Vec::new();
    frame
        .try_reserve_exact(length)
        .map_err(|error| Error::Execution(format!("failed to allocate WASIX {label}: {error}")))?;
    frame.resize(length, 0);
    reader
        .read_exact(&mut frame)
        .await
        .map_err(|error| Error::Execution(format!("failed to read WASIX {label}: {error}")))?;
    Ok(frame)
}

#[cfg(feature = "wasix")]
fn enter_wasix_worker_isolation() -> std::result::Result<WasixWorkerIsolation, String> {
    #[cfg(target_os = "linux")]
    {
        enter_linux_wasix_worker_isolation()
    }
    #[cfg(not(target_os = "linux"))]
    {
        Err("the WASIX worker isolation boundary requires Linux".to_owned())
    }
}

#[cfg(all(feature = "wasix", target_os = "linux"))]
fn rearm_worker_parent_death(
    expected_parent: rustix::process::Pid,
) -> std::result::Result<(), String> {
    rustix::process::set_parent_process_death_signal(Some(rustix::process::Signal::KILL))
        .map_err(|error| format!("failed to re-arm worker parent-death protection: {error}"))?;
    if rustix::process::getppid() != Some(expected_parent) {
        return Err("WASIX worker parent exited during isolation setup".to_owned());
    }
    Ok(())
}

#[cfg(all(feature = "wasix", target_os = "linux"))]
fn enter_linux_wasix_worker_isolation() -> std::result::Result<WasixWorkerIsolation, String> {
    use nix::unistd::{
        Gid, Uid, getgroups, getresgid, getresuid, setfsgid, setfsuid, setgroups, setresgid,
        setresuid,
    };
    use rustix::{
        process::{DumpableBehavior, Resource},
        thread::{CapabilitySet, CapabilitySets},
    };

    let expected_parent = rustix::process::getppid()
        .ok_or_else(|| "WASIX worker has no live parent process".to_owned())?;
    let closed_inherited_descriptor_count = close_inherited_worker_descriptors()?;
    let core_file_limits = lower_worker_limit(Resource::Core, 0)?;
    let file_size_limits = lower_worker_limit(Resource::Fsize, WASIX_WORKER_MAX_FILE_BYTES)?;
    let address_space_limits =
        lower_worker_limit(Resource::As, WASIX_WORKER_MAX_ADDRESS_SPACE_BYTES)?;
    let open_file_limits = lower_worker_limit(Resource::Nofile, WASIX_WORKER_MAX_OPEN_FILES)?;

    rustix::thread::set_keep_capabilities(false)
        .map_err(|error| format!("failed to disable retained worker capabilities: {error}"))?;
    rustix::thread::clear_ambient_capability_set()
        .map_err(|error| format!("failed to clear ambient worker capabilities: {error}"))?;

    let initial_users = getresuid()
        .map_err(|error| format!("failed to inspect initial worker user IDs: {error}"))?;
    let initial_groups = getresgid()
        .map_err(|error| format!("failed to inspect initial worker group IDs: {error}"))?;
    let has_root_credentials = [
        initial_users.real.as_raw(),
        initial_users.effective.as_raw(),
        initial_users.saved.as_raw(),
        initial_groups.real.as_raw(),
        initial_groups.effective.as_raw(),
        initial_groups.saved.as_raw(),
    ]
    .contains(&0);

    if has_root_credentials {
        let worker_user = Uid::from_raw(65_534);
        let worker_group = Gid::from_raw(65_534);
        setgroups(&[])
            .map_err(|error| format!("failed to clear worker supplementary groups: {error}"))?;
        setresgid(worker_group, worker_group, worker_group)
            .map_err(|error| format!("failed to drop worker group credentials: {error}"))?;
        setresuid(worker_user, worker_user, worker_user)
            .map_err(|error| format!("failed to drop worker user credentials: {error}"))?;
    }

    let final_users =
        getresuid().map_err(|error| format!("failed to inspect final worker user IDs: {error}"))?;
    let final_groups = getresgid()
        .map_err(|error| format!("failed to inspect final worker group IDs: {error}"))?;
    let _previous_filesystem_group = setfsgid(final_groups.effective);
    let _previous_filesystem_user = setfsuid(final_users.effective);

    // Linux clears PDEATHSIG when effective or filesystem credentials change.
    // Re-arm it after every credential transition, then close the corresponding
    // parent-loss race before the worker can report Ready or accept input.
    rearm_worker_parent_death(expected_parent)?;

    let empty_capabilities = CapabilitySets {
        effective: CapabilitySet::empty(),
        permitted: CapabilitySet::empty(),
        inheritable: CapabilitySet::empty(),
    };
    rustix::thread::set_capabilities(None, empty_capabilities)
        .map_err(|error| format!("failed to clear worker capabilities: {error}"))?;
    rustix::thread::set_no_new_privs(true)
        .map_err(|error| format!("failed to set worker no-new-privileges: {error}"))?;
    rustix::process::set_dumpable_behavior(DumpableBehavior::NotDumpable)
        .map_err(|error| format!("failed to disable worker dumpability: {error}"))?;

    let user_ids = read_linux_status_ids("Uid")?;
    let group_ids = read_linux_status_ids("Gid")?;
    let mut supplementary_groups = getgroups()
        .map_err(|error| format!("failed to verify worker supplementary groups: {error}"))?;
    supplementary_groups.sort_unstable_by_key(|group| group.as_raw());
    let capabilities = rustix::thread::capabilities(None)
        .map_err(|error| format!("failed to verify worker capabilities: {error}"))?;
    let no_new_privileges = rustix::thread::no_new_privs()
        .map_err(|error| format!("failed to verify worker no-new-privileges: {error}"))?;
    let dumpable = rustix::process::dumpable_behavior()
        .map_err(|error| format!("failed to verify worker dumpability: {error}"))?
        != DumpableBehavior::NotDumpable;
    let isolation = WasixWorkerIsolation {
        profile_version: WASIX_WORKER_ISOLATION_PROFILE_VERSION,
        user_ids,
        group_ids,
        supplementary_group_ids: supplementary_groups
            .iter()
            .map(|group| group.as_raw())
            .collect(),
        has_root_supplementary_group: supplementary_groups.iter().any(|group| group.as_raw() == 0),
        no_new_privileges,
        dumpable,
        capability_masks: [
            capabilities.effective.bits(),
            capabilities.permitted.bits(),
            capabilities.inheritable.bits(),
            read_linux_status_mask("CapAmb")?,
        ],
        core_file_limits,
        file_size_limits,
        address_space_limits,
        open_file_limits,
        closed_inherited_descriptor_count,
    };
    isolation
        .validate(isolation.supplementary_group_ids.as_slice())
        .map_err(|error| format!("worker isolation verification failed: {error}"))?;
    Ok(isolation)
}

#[cfg(all(feature = "wasix", target_os = "linux"))]
fn close_inherited_worker_descriptors() -> std::result::Result<u32, String> {
    let inherited = open_worker_descriptors()?;
    let count = u32::try_from(inherited.len())
        .map_err(|_| "inherited worker descriptor count exceeds the protocol".to_owned())?;
    for descriptor in inherited {
        close_raw_worker_descriptor(descriptor);
    }
    let remaining = open_worker_descriptors()?;
    if !remaining.is_empty() {
        return Err(format!(
            "worker retained inherited descriptors {remaining:?}"
        ));
    }
    Ok(count)
}

#[cfg(all(feature = "wasix", target_os = "linux"))]
fn open_worker_descriptors() -> std::result::Result<Vec<i32>, String> {
    use nix::{dir::Dir, fcntl::OFlag, sys::stat::Mode};
    use std::os::fd::AsRawFd as _;

    let mut directory = Dir::open(
        "/proc/self/fd",
        OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC,
        Mode::empty(),
    )
    .map_err(|error| format!("failed to inspect inherited worker descriptors: {error}"))?;
    let directory_descriptor = directory.as_raw_fd();
    let mut descriptors = Vec::new();
    for entry in directory.iter() {
        let entry = entry.map_err(|error| {
            format!("failed to enumerate inherited worker descriptors: {error}")
        })?;
        let Some(name) = entry.file_name().to_str().ok() else {
            continue;
        };
        let Ok(descriptor) = name.parse::<i32>() else {
            continue;
        };
        if descriptor > 2 && descriptor != directory_descriptor {
            descriptors.push(descriptor);
        }
    }
    descriptors.sort_unstable();
    descriptors.dedup();
    Ok(descriptors)
}

#[cfg(all(feature = "wasix", target_os = "linux"))]
#[allow(unsafe_code)]
fn close_raw_worker_descriptor(descriptor: i32) {
    // SAFETY: descriptors come from a single-threaded snapshot of
    // /proc/self/fd, excluding this scan's owned directory descriptor. No
    // runtime threads exist yet, so none can close or reuse them concurrently.
    unsafe { rustix::io::close(descriptor) };
}

#[cfg(all(feature = "wasix", target_os = "linux"))]
fn read_linux_status_mask(field: &str) -> std::result::Result<u64, String> {
    let status = read_linux_status_field(field)?;
    let value = status.trim();
    u64::from_str_radix(value, 16)
        .map_err(|error| format!("worker status contained an invalid {field} mask: {error}"))
}

#[cfg(all(feature = "wasix", target_os = "linux"))]
fn read_linux_status_ids(field: &str) -> std::result::Result<[u32; 4], String> {
    let status = read_linux_status_field(field)?;
    let values: Vec<_> = status
        .split_whitespace()
        .map(|value| {
            value.parse::<u32>().map_err(|error| {
                format!("worker status contained an invalid {field} identifier: {error}")
            })
        })
        .collect::<std::result::Result<_, _>>()?;
    values
        .try_into()
        .map_err(|_| format!("worker status did not contain four {field} identifiers"))
}

#[cfg(all(feature = "wasix", target_os = "linux"))]
fn read_linux_status_field(field: &str) -> std::result::Result<String, String> {
    let status = fs::read_to_string("/proc/self/status")
        .map_err(|error| format!("failed to inspect worker security state: {error}"))?;
    status
        .lines()
        .find_map(|line| {
            let (name, value) = line.split_once(':')?;
            (name == field).then(|| value.trim().to_owned())
        })
        .ok_or_else(|| format!("worker status did not contain {field}"))
}

#[cfg(all(feature = "wasix", target_os = "linux"))]
fn lower_worker_limit(
    resource: rustix::process::Resource,
    profile_maximum: u64,
) -> std::result::Result<[u64; 2], String> {
    use rustix::process::Rlimit;

    let inherited = rustix::process::getrlimit(resource);
    let maximum = inherited
        .current
        .into_iter()
        .chain(inherited.maximum)
        .fold(profile_maximum, u64::min);
    rustix::process::setrlimit(
        resource,
        Rlimit {
            current: Some(maximum),
            maximum: Some(maximum),
        },
    )
    .map_err(|error| format!("failed to lower worker {resource:?} limit: {error}"))?;
    let installed = rustix::process::getrlimit(resource);
    let current = installed
        .current
        .ok_or_else(|| format!("worker {resource:?} soft limit remained unbounded"))?;
    let hard = installed
        .maximum
        .ok_or_else(|| format!("worker {resource:?} hard limit remained unbounded"))?;
    Ok([current, hard])
}

#[cfg(all(feature = "wasix", target_os = "linux"))]
fn current_worker_build_sha256() -> std::result::Result<String, String> {
    use rustix::fs::{FileType, Mode, OFlags, fstat, open};

    let executable = open(
        "/proc/self/exe",
        OFlags::RDONLY | OFlags::CLOEXEC,
        Mode::empty(),
    )
    .map_err(|error| format!("cannot open running WASIX worker image: {error}"))?;
    let stat = fstat(&executable)
        .map_err(|error| format!("cannot inspect running WASIX worker image: {error}"))?;
    if FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile || stat.st_size <= 0 {
        return Err("running WASIX worker image is not a regular executable".to_owned());
    }
    let bytes = u64::try_from(stat.st_size)
        .map_err(|_| "running WASIX worker image size is invalid".to_owned())?;
    sha256_descriptor(&executable, bytes, "running WASIX worker image")
}

#[cfg(all(feature = "wasix", not(target_os = "linux")))]
fn current_worker_build_sha256() -> std::result::Result<String, String> {
    Err("WASIX worker build identity requires Linux".to_owned())
}

/// Enter the worker isolation profile and write one version 8 ready frame.
///
/// This function must be called from the worker's initial thread before a
/// Tokio runtime is created and before any guest-controlled bytes are read.
#[doc(hidden)]
#[cfg(feature = "wasix")]
pub fn write_wasix_worker_probe(mut writer: impl Write) -> std::result::Result<(), String> {
    let worker_build_sha256 = current_worker_build_sha256()?;
    let isolation = enter_wasix_worker_isolation()?;
    let frame = serde_json::to_vec(&WasixWorkerMetadata::current(
        isolation,
        worker_build_sha256,
    ))
    .map_err(|error| format!("cannot encode worker metadata: {error}"))?;
    write_worker_frame(&mut writer, &frame)
}

/// Enter isolation, receive a sealed descriptor, and acknowledge its exact digest.
///
/// This transport probe never deserializes Wasmer journal records. It must run
/// on the worker's initial thread before any runtime threads are created.
#[doc(hidden)]
#[cfg(all(feature = "wasix", target_os = "linux"))]
pub fn write_wasix_checkpoint_transport_probe(
    reader: impl std::os::fd::AsFd,
    mut writer: impl Write,
) -> std::result::Result<(), String> {
    use rustix::fs::{Mode, OFlags, open};

    let worker_build_sha256 = current_worker_build_sha256()?;
    let isolation = enter_wasix_worker_isolation()?;
    let ready = serde_json::to_vec(&WasixWorkerMetadata::current(
        isolation,
        worker_build_sha256,
    ))
    .map_err(|error| format!("cannot encode worker metadata: {error}"))?;
    write_worker_frame(&mut writer, &ready)?;

    let checkpoint = receive_checkpoint_descriptor(&reader, b'C', "checkpoint")?;
    let accepted =
        inspect_sealed_worker_input(&checkpoint, WASIX_WORKER_MAX_CHECKPOINT_BYTES, "checkpoint")?;

    let null = open("/dev/null", OFlags::RDONLY | OFlags::CLOEXEC, Mode::empty())
        .map_err(|error| format!("cannot open null input for checkpoint worker: {error}"))?;
    rustix::stdio::dup2_stdin(&null)
        .map_err(|error| format!("cannot clear checkpoint worker stdin: {error}"))?;
    drop(reader);

    let acknowledgement = WasixCheckpointTransportAck {
        journal_bytes: accepted.bytes,
        journal_sha256: accepted.sha256,
    };
    let frame = serde_json::to_vec(&acknowledgement)
        .map_err(|error| format!("cannot encode checkpoint acknowledgement: {error}"))?;
    write_worker_frame(&mut writer, &frame)
}

#[cfg(all(feature = "wasix", target_os = "linux"))]
struct SealedWorkerInputMetadata {
    bytes: u64,
    sha256: String,
}

#[cfg(all(feature = "wasix", target_os = "linux"))]
fn inspect_sealed_worker_input(
    descriptor: &impl std::os::fd::AsFd,
    maximum_bytes: usize,
    label: &str,
) -> std::result::Result<SealedWorkerInputMetadata, String> {
    use rustix::fs::{FileType, fcntl_get_seals, fstat};

    let installed = fcntl_get_seals(descriptor)
        .map_err(|error| format!("{label} descriptor does not expose seals: {error}"))?;
    if !installed.contains(REQUIRED_CHECKPOINT_SEALS) {
        return Err(format!("{label} descriptor is not fully sealed"));
    }
    let stat = fstat(descriptor)
        .map_err(|error| format!("cannot inspect sealed {label} descriptor: {error}"))?;
    let bytes =
        u64::try_from(stat.st_size).map_err(|_| format!("{label} descriptor size is negative"))?;
    let maximum_bytes =
        u64::try_from(maximum_bytes).map_err(|_| format!("worker {label} limit overflows u64"))?;
    if FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile
        || stat.st_nlink != 0
        || bytes == 0
        || bytes > maximum_bytes
    {
        return Err(format!("{label} descriptor identity or size is invalid"));
    }

    let mut hash = Sha256::new();
    let mut offset = 0_u64;
    let mut buffer = vec![0_u8; 64 * 1024];
    while offset < bytes {
        let buffer_bytes = u64::try_from(buffer.len())
            .map_err(|_| format!("{label} read buffer length overflows u64"))?;
        let remaining = usize::try_from((bytes - offset).min(buffer_bytes))
            .map_err(|_| format!("{label} read length overflows usize"))?;
        let read = rustix::io::pread(descriptor, &mut buffer[..remaining], offset)
            .map_err(|error| format!("cannot read sealed {label} descriptor: {error}"))?;
        if read == 0 {
            return Err(format!("sealed {label} descriptor ended prematurely"));
        }
        hash.update(&buffer[..read]);
        offset = offset
            .checked_add(
                u64::try_from(read).map_err(|_| format!("{label} read length overflows u64"))?,
            )
            .ok_or_else(|| format!("{label} read offset overflowed"))?;
    }
    let mut trailing = [0_u8; 1];
    if rustix::io::pread(descriptor, &mut trailing, bytes)
        .map_err(|error| format!("cannot finish sealed {label} descriptor: {error}"))?
        != 0
    {
        return Err(format!("sealed {label} descriptor contains trailing bytes"));
    }
    Ok(SealedWorkerInputMetadata {
        bytes,
        sha256: hex::encode(hash.finalize()),
    })
}

/// Restore a checkpoint after validating two sealed inputs and authorization.
#[doc(hidden)]
#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
pub fn write_wasix_checkpoint_restore(
    mut reader: impl std::io::Read + std::os::fd::AsFd,
    mut writer: impl Write,
) -> std::result::Result<(), String> {
    use rustix::fs::{Mode, OFlags, open};

    let worker_build_sha256 = current_worker_build_sha256()?;
    let isolation = enter_wasix_worker_isolation()?;
    let ready = serde_json::to_vec(&WasixWorkerMetadata::current(
        isolation,
        worker_build_sha256,
    ))
    .map_err(|error| format!("cannot encode worker metadata: {error}"))?;
    write_worker_frame(&mut writer, &ready)?;

    let module = receive_checkpoint_descriptor(&reader, b'M', "module")?;
    let module_metadata =
        inspect_sealed_worker_input(&module, WASIX_WORKER_MAX_MODULE_BYTES, "module")?;
    let journal = receive_checkpoint_descriptor(&reader, b'C', "checkpoint")?;
    let journal_metadata =
        inspect_sealed_worker_input(&journal, WASIX_WORKER_MAX_CHECKPOINT_BYTES, "checkpoint")?;
    let acknowledgement = WasixCheckpointRestoreAck {
        module_bytes: module_metadata.bytes,
        module_sha256: module_metadata.sha256,
        journal_bytes: journal_metadata.bytes,
        journal_sha256: journal_metadata.sha256,
    };
    let frame = serde_json::to_vec(&acknowledgement)
        .map_err(|error| format!("cannot encode restore acknowledgement: {error}"))?;
    write_worker_frame(&mut writer, &frame)?;

    let mut authorization = [0_u8; 1];
    reader
        .read_exact(&mut authorization)
        .map_err(|error| format!("cannot read restore authorization: {error}"))?;
    if authorization != [b'E'] {
        return Err("restore authorization is malformed".to_owned());
    }
    let mut trailing = [0_u8; 1];
    if reader
        .read(&mut trailing)
        .map_err(|error| format!("cannot finish restore authorization: {error}"))?
        != 0
    {
        return Err("restore authorization contains trailing bytes".to_owned());
    }

    let null = open("/dev/null", OFlags::RDONLY | OFlags::CLOEXEC, Mode::empty())
        .map_err(|error| format!("cannot open null input for restore worker: {error}"))?;
    rustix::stdio::dup2_stdin(&null)
        .map_err(|error| format!("cannot clear restore worker stdin: {error}"))?;
    drop(reader);

    let restored = execute_wasix_checkpoint_restore(&module, module_metadata.bytes, journal)?;
    let completion = WasixCheckpointRestoreCompletion {
        exit_code: restored.exit_code,
        stdout_bytes: u64::try_from(restored.stdout.len())
            .map_err(|_| "restore output length overflows u64".to_owned())?,
        stdout_sha256: hex::encode(Sha256::digest(&restored.stdout)),
        stderr_bytes: u64::try_from(restored.stderr.len())
            .map_err(|_| "restore error output length overflows u64".to_owned())?,
        stderr_sha256: hex::encode(Sha256::digest(&restored.stderr)),
    };
    let frame = serde_json::to_vec(&completion)
        .map_err(|error| format!("cannot encode restore completion: {error}"))?;
    write_worker_frame(&mut writer, &frame)?;
    write_worker_output_frame(&mut writer, &restored.stdout, "restore stdout")?;
    write_worker_output_frame(&mut writer, &restored.stderr, "restore stderr")
}

/// Capture one explicit WASIX snapshot in an isolated source worker.
#[doc(hidden)]
#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
pub fn write_wasix_checkpoint_capture(
    mut reader: impl std::io::Read + std::os::fd::AsFd,
    mut writer: impl Write,
) -> std::result::Result<(), String> {
    use rustix::fs::{Mode, OFlags, open};

    let worker_build_sha256 = current_worker_build_sha256()?;
    let isolation = enter_wasix_worker_isolation()?;
    let ready = serde_json::to_vec(&WasixWorkerMetadata::current(
        isolation,
        worker_build_sha256,
    ))
    .map_err(|error| format!("cannot encode worker metadata: {error}"))?;
    write_worker_frame(&mut writer, &ready)?;

    let module = receive_checkpoint_descriptor(&reader, b'M', "module")?;
    let module_metadata =
        inspect_sealed_worker_input(&module, WASIX_WORKER_MAX_MODULE_BYTES, "module")?;
    let request_bytes = read_worker_control_frame(
        &mut reader,
        WASIX_WORKER_MAX_CAPTURE_REQUEST_BYTES,
        "capture request",
    )?;
    let request: WasixCheckpointCaptureRequest = serde_json::from_slice(&request_bytes)
        .map_err(|error| format!("cannot decode capture request: {error}"))?;
    request.validate()?;
    let acknowledgement = WasixCheckpointCaptureAck {
        module_bytes: module_metadata.bytes,
        module_sha256: module_metadata.sha256,
        request_bytes: u64::try_from(request_bytes.len())
            .map_err(|_| "capture request length overflows u64".to_owned())?,
        request_sha256: hex::encode(Sha256::digest(&request_bytes)),
    };
    let frame = serde_json::to_vec(&acknowledgement)
        .map_err(|error| format!("cannot encode capture acknowledgement: {error}"))?;
    write_worker_frame(&mut writer, &frame)?;
    read_worker_execute_authorization(&mut reader, "capture")?;

    let null = open("/dev/null", OFlags::RDONLY | OFlags::CLOEXEC, Mode::empty())
        .map_err(|error| format!("cannot open null input for capture worker: {error}"))?;
    rustix::stdio::dup2_stdin(&null)
        .map_err(|error| format!("cannot clear capture worker stdin: {error}"))?;
    drop(reader);

    let captured = execute_wasix_checkpoint_capture(&module, module_metadata.bytes, request)?;
    let completion = WasixCheckpointCaptureCompletion {
        exit_code: captured.exit_code,
        journal_bytes: u64::try_from(captured.journal.len())
            .map_err(|_| "capture journal length overflows u64".to_owned())?,
        journal_sha256: hex::encode(Sha256::digest(&captured.journal)),
        stdout_bytes: u64::try_from(captured.stdout.len())
            .map_err(|_| "capture stdout length overflows u64".to_owned())?,
        stdout_sha256: hex::encode(Sha256::digest(&captured.stdout)),
        stderr_bytes: u64::try_from(captured.stderr.len())
            .map_err(|_| "capture stderr length overflows u64".to_owned())?,
        stderr_sha256: hex::encode(Sha256::digest(&captured.stderr)),
    };
    let frame = serde_json::to_vec(&completion)
        .map_err(|error| format!("cannot encode capture completion: {error}"))?;
    write_worker_frame(&mut writer, &frame)?;
    write_worker_bounded_frame(
        &mut writer,
        &captured.journal,
        WASIX_WORKER_MAX_CHECKPOINT_BYTES,
        false,
        "capture journal",
    )?;
    write_worker_output_frame(&mut writer, &captured.stdout, "capture stdout")?;
    write_worker_output_frame(&mut writer, &captured.stderr, "capture stderr")
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
fn read_worker_control_frame(
    reader: &mut impl std::io::Read,
    maximum: usize,
    label: &str,
) -> std::result::Result<Vec<u8>, String> {
    let mut length = [0_u8; 4];
    reader
        .read_exact(&mut length)
        .map_err(|error| format!("cannot read {label} length: {error}"))?;
    let length = usize::try_from(u32::from_be_bytes(length)).unwrap_or(usize::MAX);
    if length == 0 || length > maximum {
        return Err(format!("{label} length {length} is invalid"));
    }
    let mut frame = Vec::new();
    frame
        .try_reserve_exact(length)
        .map_err(|error| format!("cannot allocate {label}: {error}"))?;
    frame.resize(length, 0);
    reader
        .read_exact(&mut frame)
        .map_err(|error| format!("cannot read {label}: {error}"))?;
    Ok(frame)
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
fn read_worker_execute_authorization(
    reader: &mut impl std::io::Read,
    operation: &str,
) -> std::result::Result<(), String> {
    let mut authorization = [0_u8; 1];
    reader
        .read_exact(&mut authorization)
        .map_err(|error| format!("cannot read {operation} authorization: {error}"))?;
    if authorization != [b'E'] {
        return Err(format!("{operation} authorization is malformed"));
    }
    let mut trailing = [0_u8; 1];
    if reader
        .read(&mut trailing)
        .map_err(|error| format!("cannot finish {operation} authorization: {error}"))?
        != 0
    {
        return Err(format!("{operation} authorization contains trailing bytes"));
    }
    Ok(())
}

#[doc(hidden)]
#[cfg(all(feature = "wasix-checkpoint", not(target_os = "linux")))]
pub fn write_wasix_checkpoint_restore(
    _reader: impl Read,
    _writer: impl Write,
) -> std::result::Result<(), String> {
    Err("WASIX checkpoint restore requires Linux".to_owned())
}

#[doc(hidden)]
#[cfg(all(feature = "wasix-checkpoint", not(target_os = "linux")))]
pub fn write_wasix_checkpoint_capture(
    _reader: impl Read,
    _writer: impl Write,
) -> std::result::Result<(), String> {
    Err("WASIX checkpoint capture requires Linux".to_owned())
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
fn execute_wasix_checkpoint_restore(
    module: &std::os::fd::OwnedFd,
    module_length: u64,
    journal: std::os::fd::OwnedFd,
) -> std::result::Result<ExecutedCheckpointRestore, String> {
    use crate::wasix_output::BoundedWasixOutput;
    use std::sync::Arc;
    use wasmer::Module;
    use wasmer_wasix::{
        PluggableRuntime, Runtime, UnsupportedVirtualNetworking, WasiEnvBuilder,
        bin_factory::spawn_exec_module,
        runtime::{
            resolver::MultiSource,
            task_manager::{VirtualTaskManagerExt, tokio::TokioTaskManager},
        },
    };

    let module_bytes = read_sealed_module_bytes(module, module_length)?;

    let engine = bounded_wasix_worker_engine();
    let module = Module::new(&engine, &module_bytes)
        .map_err(|error| format!("cannot compile sealed restore module: {error}"))?;
    drop(module_bytes);
    let module_hash = module
        .info()
        .hash()
        .ok_or_else(|| "compiled restore module has no content hash".to_owned())?;

    let journal = checked_restore_journal(journal, module_hash.as_bytes())?;

    let tokio_runtime = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .map_err(|error| format!("cannot initialize WASIX restore runtime: {error}"))?;
    let runtime_handle = tokio_runtime.handle().clone();
    let runtime_guard = runtime_handle.enter();
    let task_manager = Arc::new(TokioTaskManager::new(runtime_handle.clone()));
    let mut concrete_runtime = PluggableRuntime::new(task_manager.clone());
    concrete_runtime.set_engine(engine);
    concrete_runtime.set_networking_implementation(UnsupportedVirtualNetworking::default());
    concrete_runtime.http_client = None;
    concrete_runtime.set_source(MultiSource::default());
    concrete_runtime.add_read_only_journal(journal);
    let runtime: Arc<dyn Runtime + Send + Sync> = Arc::new(concrete_runtime);

    let stdout = BoundedWasixOutput::new(WASIX_WORKER_MAX_RESTORE_OUTPUT_BYTES)
        .map_err(|error| format!("cannot allocate bounded restore output: {error}"))?;
    let stderr = BoundedWasixOutput::new(WASIX_WORKER_MAX_RESTORE_OUTPUT_BYTES)
        .map_err(|error| format!("cannot allocate bounded restore error output: {error}"))?;
    let mut builder = WasiEnvBuilder::new("restored-checkpoint");
    builder.set_runtime(runtime.clone());
    builder.set_module_hash(module_hash);
    builder.set_stdout(Box::new(stdout.clone()));
    builder.set_stderr(Box::new(stderr.clone()));
    builder.with_skip_stdio_during_bootstrap(true);
    let environment = builder
        .build()
        .map_err(|error| format!("cannot build WASIX restore environment: {error}"))?;
    let mut task = spawn_exec_module(module, environment, &runtime)
        .map_err(|error| format!("cannot spawn restored WASIX process: {error}"))?;
    let exit_code = runtime
        .task_manager()
        .spawn_and_block_on(async move { task.wait_finished().await })
        .map_err(|error| format!("cannot join restored WASIX process: {error}"))?
        .map_err(|error| format!("restored WASIX process failed: {error}"))?;
    if !exit_code.is_success() {
        return Err(format!("restored WASIX process exited with {exit_code}"));
    }
    quiesce_wasix_task_manager(&task_manager);
    drop(runtime);
    drop(runtime_guard);
    drop(tokio_runtime);
    let captured_stdout = stdout
        .finish()
        .map_err(|error| format!("cannot finish bounded restore output: {error}"))?;
    let captured_stderr = stderr
        .finish()
        .map_err(|error| format!("cannot finish bounded restore error output: {error}"))?;
    Ok(ExecutedCheckpointRestore {
        exit_code: exit_code.raw(),
        stdout: captured_stdout,
        stderr: captured_stderr,
    })
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
struct ExecutedCheckpointRestore {
    exit_code: i32,
    stdout: Vec<u8>,
    stderr: Vec<u8>,
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
fn quiesce_wasix_task_manager(
    task_manager: &std::sync::Arc<wasmer_wasix::runtime::task_manager::tokio::TokioTaskManager>,
) {
    task_manager.pool_handle().join();
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
struct ExecutedCheckpointCapture {
    exit_code: i32,
    journal: Vec<u8>,
    stdout: Vec<u8>,
    stderr: Vec<u8>,
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
fn execute_wasix_checkpoint_capture(
    module: &std::os::fd::OwnedFd,
    module_length: u64,
    request: WasixCheckpointCaptureRequest,
) -> std::result::Result<ExecutedCheckpointCapture, String> {
    use crate::wasix_output::BoundedWasixOutput;
    use std::sync::Arc;
    use wasmer::Module;
    use wasmer_wasix::{
        PluggableRuntime, Runtime, UnsupportedVirtualNetworking, WasiEnvBuilder,
        bin_factory::spawn_exec_module,
        journal::{LogFileJournal, SnapshotTrigger},
        runtime::{
            resolver::MultiSource,
            task_manager::{VirtualTaskManagerExt, tokio::TokioTaskManager},
        },
    };

    let module_bytes = read_sealed_module_bytes(module, module_length)?;
    let engine = bounded_wasix_worker_engine();
    let module = Module::new(&engine, &module_bytes)
        .map_err(|error| format!("cannot compile sealed capture module: {error}"))?;
    drop(module_bytes);
    let module_hash = module
        .info()
        .hash()
        .ok_or_else(|| "compiled capture module has no content hash".to_owned())?;
    let expected_module_hash = module_hash.as_bytes().to_vec();

    let journal_file = create_capture_journal_file()?;
    let journal = Arc::new(
        LogFileJournal::from_file(
            journal_file
                .try_clone()
                .map_err(|error| format!("cannot clone capture journal memfd: {error}"))?,
        )
        .map_err(|error| format!("cannot open capture journal: {error}"))?,
    );

    let tokio_runtime = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .map_err(|error| format!("cannot initialize WASIX capture runtime: {error}"))?;
    let runtime_handle = tokio_runtime.handle().clone();
    let runtime_guard = runtime_handle.enter();
    let task_manager = Arc::new(TokioTaskManager::new(runtime_handle.clone()));
    let mut concrete_runtime = PluggableRuntime::new(task_manager.clone());
    concrete_runtime.set_engine(engine);
    concrete_runtime.set_networking_implementation(UnsupportedVirtualNetworking::default());
    concrete_runtime.http_client = None;
    concrete_runtime.set_source(MultiSource::default());
    concrete_runtime.add_writable_journal(journal.clone());
    let runtime: Arc<dyn Runtime + Send + Sync> = Arc::new(concrete_runtime);

    let stdout = BoundedWasixOutput::new(WASIX_WORKER_MAX_RESTORE_OUTPUT_BYTES)
        .map_err(|error| format!("cannot allocate bounded capture stdout: {error}"))?;
    let stderr = BoundedWasixOutput::new(WASIX_WORKER_MAX_RESTORE_OUTPUT_BYTES)
        .map_err(|error| format!("cannot allocate bounded capture stderr: {error}"))?;
    let mut builder = WasiEnvBuilder::new("checkpoint-source");
    builder.set_runtime(runtime.clone());
    builder.set_module_hash(module_hash);
    builder.add_args(request.arguments);
    builder.add_envs(request.environment);
    builder.set_stdout(Box::new(stdout.clone()));
    builder.set_stderr(Box::new(stderr.clone()));
    builder.with_skip_stdio_during_bootstrap(true);
    builder.add_snapshot_trigger(SnapshotTrigger::Explicit);
    builder.with_stop_running_after_snapshot(true);
    let environment = builder
        .build()
        .map_err(|error| format!("cannot build WASIX capture environment: {error}"))?;
    let mut task = spawn_exec_module(module, environment, &runtime)
        .map_err(|error| format!("cannot spawn WASIX capture process: {error}"))?;
    let exit_code = runtime
        .task_manager()
        .spawn_and_block_on(async move { task.wait_finished().await })
        .map_err(|error| format!("cannot join WASIX capture process: {error}"))?
        .map_err(|error| format!("WASIX capture process failed: {error}"))?;
    if !exit_code.is_success() {
        return Err(format!("WASIX capture process exited with {exit_code}"));
    }
    quiesce_wasix_task_manager(&task_manager);
    drop(runtime);
    drop(journal);
    drop(runtime_guard);
    drop(tokio_runtime);
    let captured_stdout = stdout
        .finish()
        .map_err(|error| format!("cannot finish bounded capture stdout: {error}"))?;
    let captured_stderr = stderr
        .finish()
        .map_err(|error| format!("cannot finish bounded capture stderr: {error}"))?;
    let captured_journal = finalize_capture_journal(&journal_file, &expected_module_hash)?;
    Ok(ExecutedCheckpointCapture {
        exit_code: exit_code.raw(),
        journal: captured_journal,
        stdout: captured_stdout,
        stderr: captured_stderr,
    })
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
fn finalize_capture_journal(
    journal_file: &std::fs::File,
    expected_module_hash: &[u8],
) -> std::result::Result<Vec<u8>, String> {
    let checkpoint_end = inspect_captured_journal(journal_file, expected_module_hash)?;
    journal_file
        .set_len(checkpoint_end)
        .map_err(|error| format!("cannot truncate capture journal prefix: {error}"))?;
    rustix::fs::fcntl_add_seals(journal_file, REQUIRED_CHECKPOINT_SEALS)
        .map_err(|error| format!("cannot seal capture journal: {error}"))?;
    let accepted = inspect_sealed_worker_input(
        journal_file,
        WASIX_WORKER_MAX_CHECKPOINT_BYTES,
        "capture journal",
    )?;
    read_sealed_module_bytes(journal_file, accepted.bytes)
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
fn create_capture_journal_file() -> std::result::Result<std::fs::File, String> {
    let descriptor = rustix::fs::memfd_create(
        "runtrue-wasix-capture-journal",
        rustix::fs::MemfdFlags::CLOEXEC | rustix::fs::MemfdFlags::ALLOW_SEALING,
    )
    .map_err(|error| format!("cannot create capture journal memfd: {error}"))?;
    Ok(std::fs::File::from(descriptor))
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
fn bounded_wasix_worker_engine() -> wasmer::Engine {
    use wasmer::{
        Pages,
        sys::{BaseTunables, NativeEngineExt as _},
    };

    let mut engine = wasmer::Engine::default();
    let tunables = BaseTunables {
        static_memory_bound: Pages(4_096),
        static_memory_offset_guard_size: 64 * 1024,
        dynamic_memory_offset_guard_size: 64 * 1024,
    };
    engine.set_tunables(tunables);
    engine
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
fn inspect_captured_journal(
    journal_file: &std::fs::File,
    expected_module_hash: &[u8],
) -> std::result::Result<u64, String> {
    use wasmer_wasix::journal::{JournalEntry, LogFileJournal, ReadableJournal, SnapshotTrigger};

    let inspection = LogFileJournal::from_file(
        journal_file
            .try_clone()
            .map_err(|error| format!("cannot clone completed capture journal: {error}"))?,
    )
    .map_err(|error| format!("cannot inspect completed capture journal: {error}"))?;
    let mut module_records = 0_u32;
    let mut thread_records = 0_u32;
    let mut explicit_snapshots = 0_u32;
    let mut checkpoint_end = None;
    while let Some(record) = inspection
        .read()
        .map_err(|error| format!("cannot decode completed capture journal: {error}"))?
    {
        match record.record {
            JournalEntry::InitModuleV1 { wasm_hash } => {
                if wasm_hash.as_ref() != expected_module_hash {
                    return Err("capture journal module hash does not match the module".to_owned());
                }
                module_records = module_records.saturating_add(1);
            }
            JournalEntry::SetThreadV1 { .. } => {
                thread_records = thread_records.saturating_add(1);
            }
            JournalEntry::SnapshotV1 {
                trigger: SnapshotTrigger::Explicit,
                ..
            } => {
                explicit_snapshots = explicit_snapshots.saturating_add(1);
                checkpoint_end = Some(record.record_end);
            }
            _ => {}
        }
    }
    if module_records != 1 || thread_records == 0 || explicit_snapshots != 1 {
        return Err("capture journal is missing required explicit snapshot state".to_owned());
    }
    checkpoint_end.ok_or_else(|| "capture journal has no explicit snapshot boundary".to_owned())
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
fn read_sealed_module_bytes(
    module: &impl std::os::fd::AsFd,
    module_length: u64,
) -> std::result::Result<Vec<u8>, String> {
    let module_length = usize::try_from(module_length)
        .map_err(|_| "sealed restore module length overflows usize".to_owned())?;
    let mut module_bytes = Vec::new();
    module_bytes
        .try_reserve_exact(module_length)
        .map_err(|error| format!("cannot allocate sealed restore module: {error}"))?;
    module_bytes.resize(module_length, 0);
    let mut offset = 0_usize;
    while offset < module_bytes.len() {
        let positional_offset = u64::try_from(offset)
            .map_err(|_| "sealed restore module offset overflows u64".to_owned())?;
        let read = rustix::io::pread(module, &mut module_bytes[offset..], positional_offset)
            .map_err(|error| format!("cannot read sealed restore module: {error}"))?;
        if read == 0 {
            return Err("sealed restore module ended before its acknowledged length".to_owned());
        }
        offset = offset
            .checked_add(read)
            .ok_or_else(|| "sealed restore module offset overflowed".to_owned())?;
    }
    Ok(module_bytes)
}

#[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
fn checked_restore_journal(
    journal: std::os::fd::OwnedFd,
    module_hash: &[u8],
) -> std::result::Result<std::sync::Arc<wasmer_wasix::journal::LogFileJournal>, String> {
    use wasmer_wasix::journal::{JournalEntry, LogFileJournal, ReadableJournal};

    let journal_file = std::fs::File::from(journal);
    let inspection_file = journal_file
        .try_clone()
        .map_err(|error| format!("cannot clone sealed restore journal: {error}"))?;
    let inspection = LogFileJournal::from_file(inspection_file)
        .map_err(|error| format!("cannot open sealed restore journal: {error}"))?;
    let mut module_records = 0_u32;
    while let Some(record) = inspection
        .read()
        .map_err(|error| format!("cannot inspect sealed restore journal: {error}"))?
    {
        if let JournalEntry::InitModuleV1 { wasm_hash } = record.record {
            if wasm_hash.as_ref() != module_hash {
                return Err(
                    "restore journal module hash does not match the sealed module".to_owned(),
                );
            }
            module_records = module_records
                .checked_add(1)
                .ok_or_else(|| "restore journal module record count overflowed".to_owned())?;
        }
    }
    if module_records != 1 {
        return Err(format!(
            "restore journal contains {module_records} module initialization records"
        ));
    }
    Ok(std::sync::Arc::new(
        LogFileJournal::from_file(journal_file)
            .map_err(|error| format!("cannot reopen sealed restore journal: {error}"))?,
    ))
}

#[cfg(all(feature = "wasix", target_os = "linux"))]
fn receive_checkpoint_descriptor(
    control: &impl std::os::fd::AsFd,
    expected_marker: u8,
    label: &str,
) -> std::result::Result<std::os::fd::OwnedFd, String> {
    use rustix::net::{RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, ReturnFlags, recvmsg};
    use std::{io::IoSliceMut, mem::MaybeUninit};

    let mut marker = [0_u8; 1];
    let mut payload = [IoSliceMut::new(&mut marker)];
    let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
    let mut ancillary = RecvAncillaryBuffer::new(&mut space);
    let message = recvmsg(
        control,
        &mut payload,
        &mut ancillary,
        RecvFlags::CMSG_CLOEXEC,
    )
    .map_err(|error| format!("cannot receive {label} descriptor: {error}"))?;
    if message.bytes != 1
        || marker != [expected_marker]
        || message
            .flags
            .intersects(ReturnFlags::TRUNC | ReturnFlags::CTRUNC)
    {
        return Err(format!("{label} descriptor message is malformed"));
    }

    let mut checkpoint = None;
    for message in ancillary.drain() {
        let RecvAncillaryMessage::ScmRights(mut descriptors) = message else {
            return Err(format!(
                "{label} descriptor message has unexpected metadata"
            ));
        };
        let descriptor = descriptors
            .next()
            .ok_or_else(|| format!("{label} descriptor message is empty"))?;
        if checkpoint.replace(descriptor).is_some() || descriptors.next().is_some() {
            return Err(format!(
                "{label} descriptor message contains multiple files"
            ));
        }
    }
    checkpoint.ok_or_else(|| format!("{label} descriptor message did not contain a file"))
}

#[doc(hidden)]
#[cfg(all(feature = "wasix", not(target_os = "linux")))]
pub fn write_wasix_checkpoint_transport_probe(
    _reader: impl Read,
    _writer: impl Write,
) -> std::result::Result<(), String> {
    Err("the WASIX checkpoint transport requires Linux".to_owned())
}

#[cfg(feature = "wasix")]
fn write_worker_frame(writer: &mut impl Write, frame: &[u8]) -> std::result::Result<(), String> {
    if frame.len() > MAX_HANDSHAKE_BYTES {
        return Err("worker metadata exceeds the protocol frame limit".to_owned());
    }
    let length = u32::try_from(frame.len())
        .map_err(|_| "worker metadata exceeds the protocol frame limit".to_owned())?;
    writer
        .write_all(&length.to_be_bytes())
        .and_then(|()| writer.write_all(frame))
        .and_then(|()| writer.flush())
        .map_err(|error| format!("cannot write worker metadata: {error}"))
}

#[cfg(feature = "wasix-checkpoint")]
fn write_worker_output_frame(
    writer: &mut impl Write,
    frame: &[u8],
    label: &str,
) -> std::result::Result<(), String> {
    write_worker_bounded_frame(
        writer,
        frame,
        WASIX_WORKER_MAX_RESTORE_OUTPUT_BYTES,
        true,
        label,
    )
}

#[cfg(feature = "wasix-checkpoint")]
fn write_worker_bounded_frame(
    writer: &mut impl Write,
    frame: &[u8],
    maximum: usize,
    allow_empty: bool,
    label: &str,
) -> std::result::Result<(), String> {
    if (!allow_empty && frame.is_empty()) || frame.len() > maximum {
        return Err(format!("{label} exceeds the protocol frame limit"));
    }
    let length = u32::try_from(frame.len())
        .map_err(|_| format!("{label} exceeds the protocol frame limit"))?;
    writer
        .write_all(&length.to_be_bytes())
        .and_then(|()| writer.write_all(frame))
        .and_then(|()| writer.flush())
        .map_err(|error| format!("cannot write {label}: {error}"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::io::AsyncWriteExt;

    #[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
    #[test]
    fn restore_quiescence_waits_for_background_thread_pool_work() {
        use std::sync::atomic::{AtomicBool, Ordering};
        use wasmer_wasix::runtime::task_manager::{
            VirtualTaskManager as _, tokio::TokioTaskManager,
        };

        let runtime = tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .build()
            .expect("test runtime must build");
        let task_manager = std::sync::Arc::new(TokioTaskManager::new(runtime.handle().clone()));
        let completed = std::sync::Arc::new(AtomicBool::new(false));
        let task_completed = completed.clone();
        task_manager
            .task_dedicated(Box::new(move || {
                std::thread::sleep(Duration::from_millis(25));
                task_completed.store(true, Ordering::Release);
            }))
            .expect("background work must spawn");

        quiesce_wasix_task_manager(&task_manager);

        assert!(
            completed.load(Ordering::Acquire),
            "quiescence must wait for native WASIX task-pool work"
        );
    }

    #[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
    #[tokio::test]
    async fn premature_restore_worker_eof_reports_phase_status_and_diagnostics() {
        let mut command = Command::new("/bin/sh");
        command
            .arg("-c")
            .arg("printf 'premature restore EOF diagnostic' >&2; exit 17")
            .env_clear()
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true)
            .process_group(0);
        let child = command.spawn().expect("test restore worker must spawn");
        let mut worker =
            WorkerProcess::new(child, "0".repeat(64)).expect("test worker must expose its pid");
        let stdout = worker
            .child
            .stdout
            .take()
            .expect("test worker stdout must be piped");
        let stderr = worker
            .child
            .stderr
            .take()
            .expect("test worker stderr must be piped");
        let binding = WasixCheckpointBinding::new(
            format!("sha256:{}", "1".repeat(64)),
            "2".repeat(64),
            "_start",
            "premature-eof-test",
            1,
        )
        .expect("test binding must be valid");
        let input = CheckpointRestoreInput {
            control: None,
            module: None,
            journal: None,
            expected: ExpectedCheckpointRestore {
                binding,
                module_bytes: 1,
                module_sha256: "2".repeat(64),
                journal_bytes: 1,
                journal_sha256: "3".repeat(64),
            },
        };
        let (_cancel, cancelled) = oneshot::channel();

        let error = supervise_checkpoint_restore(
            worker,
            stdout,
            stderr,
            Duration::from_secs(5),
            Vec::new(),
            input,
            cancelled,
        )
        .await
        .expect_err("premature worker EOF must fail the restore");
        let display = error.to_string();
        let debug = format!("{error:?}");
        let Error::CheckpointRestore(failure) = error else {
            panic!("premature EOF must be a structured restore failure: {error:?}");
        };

        assert_eq!(failure.phase(), WasixCheckpointRestorePhase::Ready);
        assert_eq!(
            failure.reason(),
            WasixCheckpointRestoreFailureReason::Protocol
        );
        assert_eq!(failure.exit_code(), Some(17));
        assert_eq!(failure.exit_signal(), None);
        assert_eq!(
            failure.diagnostics().as_bytes(),
            b"premature restore EOF diagnostic"
        );
        assert!(!display.contains("premature restore EOF diagnostic"));
        assert!(!debug.contains("premature restore EOF diagnostic"));
    }

    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn pinned_worker_survives_path_replacement() {
        use std::os::unix::fs::PermissionsExt as _;

        let current = std::env::current_exe().unwrap();
        let directory = tempfile::Builder::new()
            .prefix("runtrue-pinned-worker-")
            .tempdir_in(current.parent().unwrap())
            .unwrap();
        let worker = directory.path().join("worker");
        std::fs::copy(&current, &worker).unwrap();
        std::fs::set_permissions(&worker, std::fs::Permissions::from_mode(0o700)).unwrap();
        let pinned = PinnedWorkerExecutable::open(&worker).unwrap();

        std::fs::rename(&worker, directory.path().join("replaced-worker")).unwrap();
        std::fs::write(&worker, b"#!/bin/sh\nexit 99\n").unwrap();
        std::fs::set_permissions(&worker, std::fs::Permissions::from_mode(0o700)).unwrap();

        let mut command = pinned.command("--list").unwrap();
        command
            .env_clear()
            .current_dir("/")
            .stdin(Stdio::null())
            .kill_on_drop(true);
        let output = tokio::time::timeout(Duration::from_secs(10), command.output())
            .await
            .unwrap()
            .unwrap();
        assert!(output.status.success(), "{output:?}");
        assert!(
            String::from_utf8_lossy(&output.stdout)
                .contains("pinned_worker_survives_path_replacement")
        );
    }

    #[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
    fn fake_capture_operation(
        cancellation: crate::CancellationToken,
    ) -> CheckpointCaptureOperation {
        let binding = WasixCheckpointBinding::new(
            format!("sha256:{}", "1".repeat(64)),
            "2".repeat(64),
            "_start",
            "capture-diagnostics-test",
            1,
        )
        .expect("test binding must be valid");
        CheckpointCaptureOperation {
            handshake_timeout: Duration::from_secs(5),
            execution_timeout: Duration::from_secs(5),
            allowed_supplementary_groups: Vec::new(),
            input: CheckpointCaptureInput {
                control: None,
                module: None,
                request: Vec::new(),
                expected: ExpectedCheckpointCapture {
                    binding,
                    module_bytes: 1,
                    module_sha256: "2".repeat(64),
                    request_bytes: 1,
                    request_sha256: "3".repeat(64),
                },
            },
            cancellation,
        }
    }

    #[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
    fn spawn_fake_capture_worker(
        script: &str,
    ) -> (
        WorkerProcess,
        tokio::process::ChildStdout,
        tokio::process::ChildStderr,
    ) {
        let mut command = Command::new("/bin/sh");
        command
            .arg("-c")
            .arg(script)
            .env_clear()
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true)
            .process_group(0);
        let child = command.spawn().expect("fake capture worker must spawn");
        let mut worker =
            WorkerProcess::new(child, "0".repeat(64)).expect("fake worker must expose its pid");
        let stdout = worker
            .child
            .stdout
            .take()
            .expect("fake worker stdout must be piped");
        let stderr = worker
            .child
            .stderr
            .take()
            .expect("fake worker stderr must be piped");
        (worker, stdout, stderr)
    }

    #[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
    #[tokio::test]
    async fn premature_capture_worker_eof_reports_phase_status_and_diagnostics() {
        let (worker, stdout, stderr) =
            spawn_fake_capture_worker("printf 'premature capture EOF diagnostic' >&2; exit 17");
        let (_cancel, cancelled) = oneshot::channel();
        let error = supervise_checkpoint_capture(
            worker,
            stdout,
            stderr,
            fake_capture_operation(crate::CancellationToken::new()),
            cancelled,
        )
        .await
        .expect_err("premature worker EOF must fail capture");
        let display = error.to_string();
        let debug = format!("{error:?}");
        let Error::CheckpointCapture(failure) = error else {
            panic!("premature EOF must be a structured capture failure: {error:?}");
        };

        assert_eq!(failure.phase(), WasixCheckpointCapturePhase::Ready);
        assert_eq!(
            failure.reason(),
            WasixCheckpointCaptureFailureReason::Protocol
        );
        assert_eq!(failure.exit_code(), Some(17));
        assert_eq!(failure.exit_signal(), None);
        assert_eq!(
            failure.diagnostics().as_bytes(),
            b"premature capture EOF diagnostic"
        );
        assert!(!display.contains("premature capture EOF diagnostic"));
        assert!(!debug.contains("premature capture EOF diagnostic"));
    }

    #[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
    #[tokio::test]
    async fn signalled_capture_worker_reports_its_termination_signal() {
        let (worker, stdout, stderr) =
            spawn_fake_capture_worker("printf 'signalled capture diagnostic' >&2; kill -TERM $$");
        let (_cancel, cancelled) = oneshot::channel();
        let error = supervise_checkpoint_capture(
            worker,
            stdout,
            stderr,
            fake_capture_operation(crate::CancellationToken::new()),
            cancelled,
        )
        .await
        .expect_err("signalled worker must fail capture");
        let Error::CheckpointCapture(failure) = error else {
            panic!("worker signal must be a structured capture failure: {error:?}");
        };

        assert_eq!(failure.phase(), WasixCheckpointCapturePhase::Ready);
        assert_eq!(failure.exit_code(), None);
        assert_eq!(failure.exit_signal(), Some(15));
        assert_eq!(
            failure.diagnostics().as_bytes(),
            b"signalled capture diagnostic"
        );
    }

    #[cfg(all(feature = "wasix-checkpoint", target_os = "linux"))]
    #[tokio::test]
    async fn capture_cancellation_kills_and_reaps_the_worker_group() {
        let (worker, stdout, stderr) = spawn_fake_capture_worker("sleep 30");
        let process_id = worker.process_id;
        let cancellation = crate::CancellationToken::new();
        let cancel_capture = cancellation.clone();
        let (_cancel, cancelled) = oneshot::channel();
        let supervisor = tokio::spawn(supervise_checkpoint_capture(
            worker,
            stdout,
            stderr,
            fake_capture_operation(cancellation),
            cancelled,
        ));
        tokio::task::yield_now().await;
        cancel_capture.cancel();

        assert!(matches!(
            supervisor.await.expect("supervisor must be joinable"),
            Err(Error::Cancelled)
        ));
        let process = rustix::process::Pid::from_raw(process_id.cast_signed())
            .expect("fake worker pid must be valid");
        assert_eq!(
            rustix::process::test_kill_process(process),
            Err(rustix::io::Errno::SRCH),
            "cancelled capture worker must be synchronously reaped"
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn cancelled_checkpoint_preparation_stops_before_transport() {
        let cancelled = AtomicBool::new(true);
        assert!(matches!(
            sealed_checkpoint_input(vec![1_u8; 64 * 1024], &cancelled),
            Err(Error::Cancelled)
        ));
    }

    #[test]
    fn rejects_each_worker_compatibility_mismatch() {
        let process_id = std::process::id();
        let worker_build_sha256 = "4".repeat(64);

        let isolation = WasixWorkerIsolation::compatible_for_test();
        let mut metadata =
            WasixWorkerMetadata::current(isolation.clone(), worker_build_sha256.clone());
        metadata.protocol_version += 1;
        assert!(matches!(
            metadata.validate(process_id, &worker_build_sha256, &[]),
            Err(Error::UnsupportedComponent(_))
        ));

        let mut metadata =
            WasixWorkerMetadata::current(isolation.clone(), worker_build_sha256.clone());
        metadata.runtime_version.push_str("-other");
        assert!(matches!(
            metadata.validate(process_id, &worker_build_sha256, &[]),
            Err(Error::UnsupportedComponent(_))
        ));

        let mut metadata =
            WasixWorkerMetadata::current(isolation.clone(), worker_build_sha256.clone());
        metadata.cohort_id.push_str("-other");
        assert!(matches!(
            metadata.validate(process_id, &worker_build_sha256, &[]),
            Err(Error::UnsupportedComponent(_))
        ));

        let mut metadata =
            WasixWorkerMetadata::current(isolation.clone(), worker_build_sha256.clone());
        metadata.worker_build_sha256 = "5".repeat(64);
        assert!(matches!(
            metadata.validate(process_id, &worker_build_sha256, &[]),
            Err(Error::UnsupportedComponent(_))
        ));

        let mut metadata = WasixWorkerMetadata::current(isolation, worker_build_sha256.clone());
        metadata.process_id = process_id.saturating_add(1);
        assert!(matches!(
            metadata.validate(process_id, &worker_build_sha256, &[]),
            Err(Error::Execution(_))
        ));
    }

    #[test]
    fn rejects_each_worker_isolation_mismatch() {
        let compatible = WasixWorkerIsolation::compatible_for_test();
        let mut incompatible = Vec::new();

        let mut isolation = compatible.clone();
        isolation.profile_version += 1;
        incompatible.push(isolation);
        let mut isolation = compatible.clone();
        isolation.user_ids[1] = 0;
        incompatible.push(isolation);
        let mut isolation = compatible.clone();
        isolation.group_ids[2] = 0;
        incompatible.push(isolation);
        let mut isolation = compatible.clone();
        isolation.user_ids[3] = 123;
        incompatible.push(isolation);
        let mut isolation = compatible.clone();
        isolation.has_root_supplementary_group = true;
        incompatible.push(isolation);
        let mut isolation = compatible.clone();
        isolation.supplementary_group_ids = vec![123];
        incompatible.push(isolation);
        let mut isolation = compatible.clone();
        isolation.no_new_privileges = false;
        incompatible.push(isolation);
        let mut isolation = compatible.clone();
        isolation.dumpable = true;
        incompatible.push(isolation);
        let mut isolation = compatible.clone();
        isolation.capability_masks[0] = 1;
        incompatible.push(isolation);
        let mut isolation = compatible.clone();
        isolation.core_file_limits = [1; 2];
        incompatible.push(isolation);
        let mut isolation = compatible.clone();
        isolation.file_size_limits = [WASIX_WORKER_MAX_FILE_BYTES + 1; 2];
        incompatible.push(isolation);
        let mut isolation = compatible.clone();
        isolation.address_space_limits = [WASIX_WORKER_MAX_ADDRESS_SPACE_BYTES + 1; 2];
        incompatible.push(isolation);
        let mut isolation = compatible;
        isolation.open_file_limits = [65; 2];
        incompatible.push(isolation);

        for isolation in incompatible {
            assert!(isolation.validate(&[]).is_err(), "{isolation:?}");
        }
    }

    #[tokio::test]
    async fn rejects_zero_oversized_and_truncated_frames() {
        for bytes in [
            0_u32.to_be_bytes().to_vec(),
            u32::try_from(MAX_HANDSHAKE_BYTES + 1)
                .unwrap()
                .to_be_bytes()
                .to_vec(),
            [5_u32.to_be_bytes().as_slice(), b"no"].concat(),
        ] {
            let (mut writer, mut reader) = tokio::io::duplex(32);
            writer.write_all(&bytes).await.unwrap();
            drop(writer);
            assert!(matches!(
                read_frame(&mut reader).await,
                Err(Error::Execution(_))
            ));
        }
    }

    #[cfg(feature = "wasix-checkpoint")]
    #[tokio::test]
    async fn worker_diagnostics_are_bounded_and_report_truncation() {
        let (mut writer, mut reader) = tokio::io::duplex(WASIX_WORKER_MAX_DIAGNOSTIC_BYTES * 2);
        let emitted = vec![b'x'; WASIX_WORKER_MAX_DIAGNOSTIC_BYTES + 1];
        let write = tokio::spawn(async move {
            writer
                .write_all(&emitted)
                .await
                .expect("test diagnostics must be writable");
            writer
                .shutdown()
                .await
                .expect("test diagnostics must reach EOF");
        });

        let diagnostics = read_worker_diagnostics(&mut reader)
            .await
            .expect("test diagnostics must be readable");
        write.await.expect("diagnostic writer must be joinable");

        assert_eq!(diagnostics.len(), WASIX_WORKER_MAX_DIAGNOSTIC_BYTES);
        assert!(diagnostics.is_truncated());
        assert!(diagnostics.as_bytes().iter().all(|byte| *byte == b'x'));
    }
}