mxc-sdk 1.2.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! WSL Container runner — implements `ScriptRunner` for the WSLC SDK backend.
//!
//! Orchestrates the full lifecycle:
//! `WslcGetMissingComponents → Session → Image check → Process settings → Container → Start →
//!  I/O capture → Exit code → ScriptResponse`
//!
//! RAII guards ensure cleanup even on error paths.
//!
//! `start_container` owns everything up
//! to and including "container started, init process in hand" and is shared by
//! both execution models: the run-to-completion [`ScriptRunner`] here, and the
//! streaming [`SandboxBackend`](crate::mxc_common::sandbox_process::SandboxBackend) in
//! [`crate::wslc_common::sandbox`]. They differ only in where the SDK's I/O callbacks send
//! their bytes — see `IoSink`.

use std::ffi::{c_void, CStr, CString};
use std::fmt::Write;
use std::io::Read;
use std::ptr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};

use crate::mxc_common::logger::{Logger, Mode};
use crate::mxc_common::models::{ExecutionRequest, ScriptResponse, WslcConfig};
use crate::mxc_common::mxc_error::MxcError;
use crate::mxc_common::process_util::InterruptiblePipeWriter;
use crate::mxc_common::sandbox_process::{StdioMode, StreamCloser};
use crate::mxc_common::script_runner::ScriptRunner;
use crate::mxc_common::string_util::CoTaskMemPWSTR;
use crate::mxc_common::validator::validate_network_policy_support;

use crate::wslc_common::container_steps::{
    self, sdk_error, ContainerNetworking, ContainerSettings, HostLoopback,
};
use crate::wslc_common::egress_gateway;
use crate::wslc_common::error::{sdk_api_failure, WslcError, WslcStepError};
use crate::wslc_common::image;
use crate::wslc_common::policy;
use crate::wslc_common::policy_mapping;
use crate::wslc_common::process_env;
use crate::wslc_common::sdk_init;
use crate::wslc_common::session_resources;
use crate::wslc_common::stream_buffer::{stream_pair, StreamReader, StreamWriter};
use crate::wslc_common::wslc_bindings::*;

fn sdk_wait_error(operation: &str, hr: HRESULT, sdk_msg: &str) -> WslcStepError {
    WslcError::sdk(format!("{operation} failed"), hr, sdk_msg)
        .into_step_error()
        .with_api_failure(sdk_api_failure(operation, hr))
}

/// Where the bytes the WSLC SDK hands us in its stdout/stderr callbacks go.
///
/// The WSLC SDK never exposes the container's pipe ends — it pushes output to
/// registered callbacks — so this is the one place the two execution models
/// diverge: run-to-completion accumulates the bytes for the `ScriptResponse`,
/// streaming hands them to the caller's live reader (or to the host's stdio).
enum IoSink {
    /// Accumulate in memory for [`WSLContainerRunner::collect_output`].
    Buffer(Mutex<Vec<u8>>),
    /// Hand to a reader: either the caller's ([`StdioMode::Pipes`]) or an
    /// [`inherit_pump`] forwarding to the host's stdio ([`StdioMode::Inherit`]).
    Stream(StreamWriter),
}

impl IoSink {
    /// Forward one callback chunk.
    ///
    /// This runs on an SDK callback thread, and that same thread delivers the
    /// process-exit callback teardown waits for, so a sink must not stall it:
    /// both sinks only take a short-lived lock, never OS I/O. That is why the
    /// host-stdio (`Inherit`) case is *also* a `Stream` — writing straight
    /// through to `stdout` here would block this thread whenever the host's
    /// pipe is full, and the exit callback would then never arrive. A
    /// [`inherit_pump`] thread does that blocking write instead.
    fn write(&self, bytes: &[u8]) {
        match self {
            IoSink::Buffer(buffer) => lock(buffer).extend_from_slice(bytes),
            IoSink::Stream(writer) => writer.write(bytes),
        }
    }

    /// End the stream so a reader sees EOF once it has drained what is
    /// buffered. Idempotent, and a no-op for the buffer sink.
    fn close(&self) {
        if let IoSink::Stream(writer) = self {
            writer.close();
        }
    }

    /// The bytes captured so far, lossily decoded. Always empty for the
    /// streaming sink — the caller (or the pump) consumed those bytes live.
    fn captured(&self) -> String {
        match self {
            IoSink::Buffer(buffer) => String::from_utf8_lossy(&lock(buffer)).to_string(),
            IoSink::Stream(_) => String::new(),
        }
    }
}

/// Drain `reader` to one of the host's own streams until EOF, on a thread of
/// its own.
///
/// [`StdioMode::Inherit`] means "the sandboxed process writes the host's
/// stdout/stderr", and those are blocking handles: whoever writes them stalls
/// whenever the host stops draining its end. Doing that on the SDK's callback
/// thread would stall the process-exit callback with it — deadlocking teardown
/// against a pipe only the host can drain — so the blocking write happens here,
/// where stalling costs nothing but this thread. Teardown joins these after the
/// container is settled, so a slow host delays only the final flush.
///
/// Write errors end the pump: a host stream that has gone away (a closed pipe)
/// cannot recover, and there is nowhere to report it from — the same reason the
/// callback path drops them.
fn inherit_pump(mut reader: StreamReader, host: HostStream) -> std::thread::JoinHandle<()> {
    std::thread::spawn(move || {
        // Locked per chunk rather than for the whole pump: the host's stdio is
        // shared (the logger writes it too), so holding the lock for the life
        // of the container would block everything else on the host.
        pump(&mut reader, |bytes| match host {
            HostStream::Stdout => write_through(std::io::stdout().lock(), bytes),
            HostStream::Stderr => write_through(std::io::stderr().lock(), bytes),
        })
    })
}

/// Drain `reader` into `write_chunk` until the stream ends.
///
/// Split out from [`inherit_pump`] so the loop can be driven against a sink a
/// test controls — in particular one that blocks, which is the case that must
/// not reach an SDK callback thread.
fn pump(reader: &mut StreamReader, mut write_chunk: impl FnMut(&[u8]) -> std::io::Result<()>) {
    let mut buf = [0u8; 8192];
    loop {
        match reader.read(&mut buf) {
            // EOF, or a stream that cannot be read again: either way, done.
            Ok(0) | Err(_) => return,
            Ok(n) => {
                if write_chunk(&buf[..n]).is_err() {
                    return;
                }
            }
        }
    }
}

/// Which host stream an [`inherit_pump`] drains into.
#[derive(Clone, Copy)]
enum HostStream {
    Stdout,
    Stderr,
}

/// Write one chunk straight through to a host stream, flushing it so output
/// appears as the container produces it.
fn write_through(mut sink: impl std::io::Write, bytes: &[u8]) -> std::io::Result<()> {
    sink.write_all(bytes)?;
    sink.flush()
}

/// How long to wait for the SDK's exit callback, which is what guarantees all
/// output has been flushed and no further callback can arrive. Bounded so a
/// misbehaving runtime can't park teardown forever.
const EXIT_CALLBACK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

/// How long a forced stop waits for the command to exit before treating the stop as unconfirmed.
const STOP_CONFIRM_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

/// How long to wait for an abandoned pull before giving up on its session.
const PULL_DRAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

/// How long the exit callback may trail the exit event before output is
/// reported as possibly incomplete: the SDK delivers it within milliseconds,
/// or 30 s or more late when a command leaves a lot of its stdin unread.
const LATE_EXIT_THRESHOLD: std::time::Duration = std::time::Duration::from_secs(10);

/// Reported when the SDK's exit callback arrives well after the exit event.
const LATE_EXIT_WARNING: &str =
    "WARNING: the WSLc SDK reported the command's exit late, so its output may be incomplete. \
     The SDK does this when a command exits leaving a large amount of its stdin unread; keep \
     input to a command that may not read it small.";

/// Lock a mutex, tolerating poisoning: every mutex here guards plain output
/// state with no invariant a panicking writer could break.
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(|e| e.into_inner())
}

/// Callback context: where each stream's bytes go, plus the process-exit
/// signal the SDK fires once all I/O has been flushed.
struct IoContext {
    stdout: IoSink,
    stderr: IoSink,
    exited: (Mutex<bool>, Condvar),
}

/// How a started container's output is delivered.
#[derive(Clone, Copy)]
pub(crate) enum OutputMode {
    /// Capture in memory, returned in the `ScriptResponse` (run-to-completion).
    Capture,
    /// Stream: hand the caller live pipes ([`StdioMode::Pipes`]) or write
    /// through to the host's own stdio ([`StdioMode::Inherit`]).
    Stream(StdioMode),
}

/// Whether a container's init process gets a stdin pipe.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum InitStdin {
    /// The process reads end-of-file at once.
    Closed,

    /// [`StartedContainer::stdin`] holds the only write end.
    Piped,
}

impl IoContext {
    /// Build the context for `mode`, along with whatever else that mode needs
    /// wired up (see [`IoWiring`]).
    fn new(mode: OutputMode) -> (Self, IoWiring) {
        let (stdout, stderr, wiring) = match mode {
            OutputMode::Capture => (
                IoSink::Buffer(Mutex::new(Vec::new())),
                IoSink::Buffer(Mutex::new(Vec::new())),
                IoWiring::default(),
            ),
            // Inherit is a `Stream` too, drained by a pump thread rather than
            // by the caller — see `inherit_pump` for why the SDK's callback
            // thread must not write the host's stdio itself.
            OutputMode::Stream(StdioMode::Inherit) => {
                let (stdout_writer, stdout_reader) = stream_pair();
                let (stderr_writer, stderr_reader) = stream_pair();
                (
                    IoSink::Stream(stdout_writer),
                    IoSink::Stream(stderr_writer),
                    IoWiring {
                        pipes: None,
                        pumps: vec![
                            inherit_pump(stdout_reader, HostStream::Stdout),
                            inherit_pump(stderr_reader, HostStream::Stderr),
                        ],
                    },
                )
            }
            OutputMode::Stream(StdioMode::Pipes) => {
                let (stdout_writer, stdout_reader) = stream_pair();
                let (stderr_writer, stderr_reader) = stream_pair();
                (
                    IoSink::Stream(stdout_writer),
                    IoSink::Stream(stderr_writer),
                    IoWiring {
                        pipes: Some(StreamPipes {
                            stdout: stdout_reader,
                            stderr: stderr_reader,
                        }),
                        pumps: Vec::new(),
                    },
                )
            }
            OutputMode::Stream(StdioMode::Pty(_)) => {
                unreachable!("PTY mode is rejected before WSLC I/O setup")
            }
            OutputMode::Stream(StdioMode::MergedPipes) => {
                unreachable!("merged stdio is rejected before WSLC I/O setup")
            }
        };
        (
            Self {
                stdout,
                stderr,
                exited: (Mutex::new(false), Condvar::new()),
            },
            wiring,
        )
    }

    /// Close both streaming sinks, EOF-ing any reader the caller holds.
    /// Idempotent — the exit callback normally gets there first.
    fn close_streams(&self) {
        self.stdout.close();
        self.stderr.close();
    }

    /// Block until the SDK's exit callback has fired, up to
    /// [`EXIT_CALLBACK_TIMEOUT`]. Returns whether it fired.
    ///
    /// The predicate loop is load-bearing, not ceremony: a condvar wakeup may be
    /// spurious, and callers treat `false` as "the SDK is done calling back" —
    /// closing the streams (truncating output still being flushed) and releasing
    /// the SDK handles.
    fn wait_for_exit_callback(&self) -> bool {
        let (mutex, cvar) = &self.exited;
        let exited = mutex.lock().unwrap_or_else(|e| e.into_inner());
        let (exited, _) = cvar
            .wait_timeout_while(exited, EXIT_CALLBACK_TIMEOUT, |exited| !*exited)
            .unwrap_or_else(|e| e.into_inner());
        *exited
    }
}

/// Wait for the SDK's exit callback on `io_ctx`, and if it never fires, make the
/// callback context immortal.
///
/// The exit callback is the SDK's only signal that it has stopped invoking
/// `io_callback` / `exit_callback`, both of which dereference the
/// `Arc<IoContext>` handed over as a raw pointer. When the wait times out that
/// guarantee never held, yet the caller is about to release everything — so a
/// delayed callback would read freed memory. Leaking one `Arc` reference keeps
/// the context alive for the life of the process, which is a bounded cost and
/// strictly preferable to a use-after-free on a pathological shutdown.
/// (`wslcsdk.dll` itself is never unloaded, for the same reason — see
/// `WslcSdk::load`.)
///
/// Returns whether the callback was observed.
fn await_callbacks_quiesced(io_ctx: &Arc<IoContext>) -> bool {
    if io_ctx.wait_for_exit_callback() {
        return true;
    }
    std::mem::forget(Arc::clone(io_ctx));
    false
}

/// How a wait ended — and, when the deadline fired, whether the SDK could be
/// made to *prove* the process is gone.
///
/// A timeout stop is only ever a request: `WslcStopContainer`'s HRESULT says
/// the call was accepted, not that the process died. The SDK's exit callback is
/// the only positive proof, so "timed out" and "timed out and was terminated"
/// are deliberately different answers — reporting the second when only the
/// first holds is how a caller ends up believing sandboxed code was killed
/// while it is still running.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum WaitOutcome {
    /// The process exited on its own, within the deadline.
    Exited,
    /// The deadline elapsed and the exit callback confirmed the process is gone.
    TimedOutTerminated,
    /// The deadline elapsed and the exit callback never arrived, even after the
    /// `SIGKILL` escalation: the container may still be running.
    TimedOutUnconfirmed,

    /// Stdin forwarding failed and the wait stopped the container.
    Aborted { confirmed: bool },
}

impl WaitOutcome {
    /// Whether the deadline fired, however it ended.
    pub(crate) fn timed_out(self) -> bool {
        matches!(
            self,
            WaitOutcome::TimedOutTerminated | WaitOutcome::TimedOutUnconfirmed
        )
    }

    fn confirmed_gone(self) -> bool {
        matches!(
            self,
            WaitOutcome::Exited
                | WaitOutcome::TimedOutTerminated
                | WaitOutcome::Aborted { confirmed: true }
        )
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum StopReason {
    Timeout,
    ForwardingFailure,
}

/// The caller-side read ends of a [`StdioMode::Pipes`] context.
pub(crate) struct StreamPipes {
    pub(crate) stdout: StreamReader,
    pub(crate) stderr: StreamReader,
}

/// Everything an [`IoContext`] needs alongside itself, which varies by
/// [`OutputMode`]: read ends for the caller, or pump threads for the host.
#[derive(Default)]
struct IoWiring {
    /// Caller-side read ends ([`StdioMode::Pipes`] only).
    pipes: Option<StreamPipes>,
    /// Forwarders draining to the host's stdio ([`StdioMode::Inherit`] only),
    /// joined by teardown once the streams are closed.
    pumps: Vec<std::thread::JoinHandle<()>>,
}

/// RAII guard that reclaims an Arc<IoContext> from a raw pointer on drop.
/// Prevents leaking the Arc reference count on early returns.
struct IoCtxRawGuard {
    ptr: *mut c_void,
}

impl IoCtxRawGuard {
    fn new(ptr: *mut c_void) -> Self {
        Self { ptr }
    }
}

impl Drop for IoCtxRawGuard {
    fn drop(&mut self) {
        if !self.ptr.is_null() {
            // SAFETY: `ptr` came from `Arc::into_raw` on an `Arc<IoContext>` and
            // is reclaimed exactly once, here.
            unsafe {
                let _ = Arc::from_raw(self.ptr as *const IoContext);
            }
        }
    }
}

/// Callback invoked by the WSLC SDK for stdout/stderr data.
///
/// # Safety
/// `context` must be a valid pointer obtained from `Arc::into_raw(Arc<IoContext>)`.
/// The `Arc` is kept alive in `run_internal` via `IoCtxRawGuard` (which reclaims it
/// on drop), so the pointer remains valid for the duration of all callbacks.
/// The SDK guarantees `data` is valid for `data_size` bytes during the callback.
unsafe extern "C" fn io_callback(
    io_handle: WslcProcessIOHandle,
    data: *const BYTE,
    data_size: u32,
    context: *mut c_void,
) {
    if context.is_null() || data.is_null() || data_size == 0 {
        return;
    }
    let ctx = &*(context as *const IoContext);
    let bytes = std::slice::from_raw_parts(data, data_size as usize);
    match io_handle {
        WslcProcessIOHandle::WSLC_PROCESS_IO_HANDLE_STDOUT => ctx.stdout.write(bytes),
        WslcProcessIOHandle::WSLC_PROCESS_IO_HANDLE_STDERR => ctx.stderr.write(bytes),
        _ => {}
    }
}

/// Callback invoked when the process exits and all I/O has been flushed.
/// Per SDK docs: "Once this callback is invoked, any registered IO callbacks
/// will no longer be called." This guarantees buffers are complete — and makes
/// this the point at which a streaming caller's readers can safely be EOF'd.
///
/// # Safety
/// Same lifetime requirements as `io_callback` — `context` must be a valid
/// pointer from `Arc::into_raw(Arc<IoContext>)`, kept alive by `IoCtxRawGuard`.
unsafe extern "C" fn exit_callback(_exit_code: i32, context: *mut c_void) {
    if context.is_null() {
        return;
    }
    let ctx = &*(context as *const IoContext);
    // No further I/O callbacks can arrive, so closing the streaming pipes' write
    // ends here is what ends a caller's `read` with EOF.
    ctx.close_streams();
    let (lock, cvar) = &ctx.exited;
    let mut exited = lock.lock().unwrap_or_else(|e| e.into_inner());
    *exited = true;
    cvar.notify_all();
}

/// WSL Container script runner using the WSLC SDK.
pub struct WSLContainerRunner {
    config: WslcConfig,
    pub(crate) piped_stdin: bool,
}

impl WSLContainerRunner {
    pub fn new(config: &WslcConfig) -> Self {
        Self {
            config: config.clone(),
            piped_stdin: false,
        }
    }

    /// A runner whose piped spawns give the process a writable stdin rather
    /// than end-of-file.
    pub fn with_piped_stdin(config: &WslcConfig) -> Self {
        Self {
            piped_stdin: true,
            ..Self::new(config)
        }
    }
}

impl WSLContainerRunner {
    fn session_sizing(&self) -> container_steps::SessionSizing {
        container_steps::SessionSizing {
            cpu_count: self.config.cpu_count,
            memory_mb: self.config.memory_mb,
            gpu: self.config.gpu,
        }
    }

    fn network_mode(&self, request: &ExecutionRequest) -> Result<policy::NetworkMode, MxcError> {
        policy::network_mode(request, !self.config.port_mappings.is_empty())
    }

    fn validate_target_os(&self) -> Result<(), ScriptResponse> {
        if self.config.target_os == "linux" {
            return Ok(());
        }

        Err(WslcError::Rejected(format!(
            "WSLc: wslc.targetOs={:?} is not supported. WSLc runs Linux containers only; \
             omit the field or set it to \"linux\".",
            self.config.target_os
        ))
        .into_response())
    }
}

impl ScriptRunner for WSLContainerRunner {
    /// Reject policies WSLc cannot enforce, before any container is created.
    /// Mirrors the config parser so requests reaching the engine directly
    /// (an already-built `ExecutionRequest`, bypassing the parser) fail here
    /// instead of late in `execute` on the broken in-container iptables path.
    /// An embedded NUL in `containerId` is rejected here too, before
    /// session-name conversion can truncate it and before a dry-run can
    /// report success.
    fn validate_runner(&self, request: &ExecutionRequest) -> Result<(), ScriptResponse> {
        reject_embedded_nul_container_id(&request.container_id)?;
        self.validate_target_os()?;
        reject_unsupported_lifecycle(request)?;

        container_steps::check_sizing_against_host(self.session_sizing())?;

        policy_mapping::container_working_directory(&request.working_directory)
            .map_err(|msg| WslcError::Rejected(msg).into_response())?;
        policy::reject_ui_policy(request).map_err(as_wslc_rejection)?;
        // The shared validator returns an untagged response; retag it so its
        // rejections reach SDK callers as `policy_validation` like the checks above.
        validate_network_policy_support(request, policy::network_policy_support())
            .map_err(|resp| WslcError::Rejected(resp.error_message).into_response())?;
        let network_mode = self.network_mode(request).map_err(as_wslc_rejection)?;
        policy::reject_proxy_credentials_in_argv(request).map_err(as_wslc_rejection)?;
        resolve_custom_proxy(&network_mode)?;
        Ok(())
    }

    fn execute(&mut self, request: &ExecutionRequest, logger: &mut Logger) -> ScriptResponse {
        unsafe { self.run_internal(request, logger) }
    }
}

/// Retag a shared [`policy`] rejection so it reaches SDK callers as
/// `policy_validation` with the same message the state-aware surface emits.
fn as_wslc_rejection(err: MxcError) -> ScriptResponse {
    WslcError::Rejected(err.message).into_response()
}

fn resolve_custom_proxy(
    network_mode: &policy::NetworkMode,
) -> Result<Option<crate::wslc_gateway_policy::CustomProxy>, ScriptResponse> {
    match network_mode {
        policy::NetworkMode::Proxied(egress) => {
            egress_gateway::resolve_custom_proxy(egress).map_err(WslcStepError::into_response)
        }
        policy::NetworkMode::None | policy::NetworkMode::Bridged => Ok(None),
    }
}

/// The first line [`WSLContainerRunner::start_container`] writes, before any
/// SDK call. Tests assert its absence to prove a rejection aborted early.
pub(crate) const START_CONTAINER_BANNER: &str = "[WSLC] Starting WSL Container runner";

/// Refuse an embedded NUL before it can become a WSLc session name.
///
/// `string_util::to_wide` truncates at the first NUL, so `alpha\0evil` and
/// `alpha` would otherwise name the same session. The parser rejects this for
/// JSON entry points; this covers an already-built `ExecutionRequest`. Do not
/// echo the raw id — the NUL would also truncate logs.
fn reject_embedded_nul_container_id(container_id: &str) -> Result<(), ScriptResponse> {
    if container_id.contains('\0') {
        return Err(
            WslcError::Rejected("containerId must not contain null bytes".to_string())
                .into_response(),
        );
    }
    Ok(())
}

/// Refuses the `lifecycle` settings the one-shot surface cannot honour.
///
/// Value-based, not presence-based: the default `destroyOnExit: true` is
/// honoured. `false` cannot be, because [`StartedContainer`] owns the
/// [`WslcSessionGuard`] whose `Drop` ends the session-scoped container either
/// way. The state-aware surface needs no counterpart — the parser rejects the
/// whole `lifecycle` section there.
fn reject_unsupported_lifecycle(request: &ExecutionRequest) -> Result<(), ScriptResponse> {
    if !request.lifecycle.destroy_on_exit {
        return Err(WslcError::Rejected(
            "WSLc: lifecycle.destroyOnExit=false is not supported by the one-shot WSLc surface. \
             The container is scoped to a session this process owns, and terminating that \
             session at the end of the run removes the container regardless of the AutoRemove \
             flag. Omit the field (or set it to true), or use the state-aware lifecycle, whose \
             daemon holds the session open across phases."
                .to_string(),
        )
        .into_response());
    }
    if request.lifecycle.preserve_policy {
        return Err(WslcError::Rejected(
            "WSLc: lifecycle.preservePolicy=true is not supported. WSLc installs no persistent \
             host-side filesystem or network enforcement — mounts and the container networking \
             mode belong to the container itself — so there is no policy to preserve past the \
             run."
                .to_string(),
        )
        .into_response());
    }
    Ok(())
}

const GENERATED_SESSION_NAME_PREFIX: &str = "mxc-wslc-";

/// Name the WSLc session a run gets, minting one when `containerId` is absent:
/// WSLc refuses an empty name with `WSLC_E_INVALID_SESSION_NAME` (0x80040608).
fn resolve_session_name(container_id: &str) -> String {
    if container_id.is_empty() {
        format!(
            "{GENERATED_SESSION_NAME_PREFIX}{}",
            uuid::Uuid::new_v4().simple()
        )
    } else {
        container_id.to_string()
    }
}

impl WSLContainerRunner {
    fn storage_path(&self) -> String {
        self.config.storage_path.clone().unwrap_or_else(|| {
            std::env::temp_dir()
                .join("mxc-wslc-sessions")
                .to_string_lossy()
                .to_string()
        })
    }

    /// # Safety
    /// `sdk` must contain valid, currently-loaded function pointers.
    /// COM must already be initialized on this thread.
    unsafe fn create_session(
        &self,
        sdk: &'static WslcSdk,
        request: &ExecutionRequest,
        session_name: &str,
        network_mode: &policy::NetworkMode,
        logger: &mut Logger,
    ) -> Result<(WslcSessionGuard, bool), ScriptResponse> {
        // Backstop for a direct `execute` that skipped `validate_runner`.
        reject_embedded_nul_container_id(&request.container_id)?;
        let host_loopback = if network_mode.session_host_loopback() {
            HostLoopback::Required
        } else if *network_mode == policy::NetworkMode::Bridged {
            HostLoopback::IfSupported
        } else {
            HostLoopback::Off
        };
        let (session, host_loopback) = container_steps::create_session(
            sdk,
            session_name,
            &self.storage_path(),
            self.session_sizing(),
            host_loopback,
            logger,
        )?;
        let _ = writeln!(logger, "[WSLC] Session created: {session_name}");
        Ok((session, host_loopback))
    }

    /// Wait for process exit with timeout enforcement.
    /// Returns (exit_code, timed_out).
    ///
    /// The deadline is `started.timeout_ms`; `u32::MAX` waits forever.
    /// Shared by the run-to-completion and streaming paths.
    ///
    /// # Safety
    /// `started` must hold live handles and SDK, `exit_event` must be its
    /// process's exit event, and `abort_event` must be null or a live event.
    unsafe fn wait_for_process(
        started: &StartedContainer,
        exit_event: HANDLE,
        abort_event: HANDLE,
        logger: &mut Logger,
    ) -> Result<(i32, WaitOutcome), WslcStepError> {
        let sdk = started.sdk;
        let process_guard = &started.process_guard;
        let container_guard = &started.container_guard;
        let io_ctx = &started.io_ctx;
        let wait_ms = started.timeout_ms;
        let close_stdin = || started.close_stdin();
        let mut stopped: Option<StopReason> = None;
        // Whether the *event* said the process ended. Tracked apart from the
        // callback confirmation below because they are separate pieces of
        // evidence, and reporting an exit requires at least one of them: with
        // neither, `WslcGetProcessExitCode` happily returns `STILL_ACTIVE` for a
        // container that is very much still running.
        let mut exit_signalled = false;
        if !exit_event.is_null() {
            match wait_for_exit_or_abort(exit_event, abort_event, wait_ms) {
                Ok(ExitWait::Exited) => exit_signalled = true,
                Ok(ExitWait::TimedOut) => {
                    let _ = writeln!(
                        logger,
                        "[WSLC] Execution timeout ({}ms) reached — stopping container",
                        wait_ms
                    );
                    stopped = Some(StopReason::Timeout);
                    let _ = stop_container(
                        sdk,
                        container_guard.as_raw(),
                        WslcSignal::WSLC_SIGNAL_SIGTERM,
                        2,
                    );
                }
                Ok(ExitWait::Aborted) => {
                    let _ = writeln!(
                        logger,
                        "[WSLC] Stdin forwarding failed and could not stop the command — \
                         stopping container"
                    );
                    stopped = Some(StopReason::ForwardingFailure);
                    let _ = stop_container(
                        sdk,
                        container_guard.as_raw(),
                        WslcSignal::WSLC_SIGNAL_SIGKILL,
                        0,
                    );
                }
                Err(message) => return Err(WslcError::Runtime(message).into_step_error()),
            }
        }
        let exit_seen = std::time::Instant::now();

        // Input the process can no longer read is dropped, so a writer
        // blocked on it returns now rather than at teardown.
        if exit_signalled {
            close_stdin();
        }

        // Wait for exit callback to fire — guarantees all I/O is flushed, and
        // is the only proof the process is actually gone. Only the final wait
        // below may leak the context, since the SDK can call back late.
        let mut confirmed = io_ctx.wait_for_exit_callback();
        let callback_late = exit_seen.elapsed() >= LATE_EXIT_THRESHOLD;
        if !confirmed {
            if stopped == Some(StopReason::Timeout) {
                // The `SIGTERM` above was only a request, and it plainly did not
                // land: the process is still running and still producing output.
                // Escalate *before* the backstop close below, so that output is
                // not cut off from a process we are about to kill anyway.
                let _ = writeln!(
                    logger,
                    "[WSLC] Container did not stop after the timeout SIGTERM — escalating to \
                     SIGKILL"
                );
                let _ = stop_container(
                    sdk,
                    container_guard.as_raw(),
                    WslcSignal::WSLC_SIGNAL_SIGKILL,
                    0,
                );
            }
            // Re-checked after the escalation: only a callback that still has
            // not fired forces the context leak.
            confirmed = await_callbacks_quiesced(io_ctx);
            if !confirmed {
                let _ = writeln!(
                    logger,
                    "[WSLC] Warning: exit callback did not fire within {}s; leaking the callback \
                     context so a late callback cannot touch freed memory",
                    EXIT_CALLBACK_TIMEOUT.as_secs()
                );
            }
        }
        if callback_late && stopped.is_none() {
            logger.warning_line(LATE_EXIT_WARNING);
        }

        // A process not known to be gone keeps its stdin until teardown, so it
        // cannot read input cut short by the stop as complete.
        if confirmed || started.exit_signalled() {
            close_stdin();
        }

        // Backstop for the streaming path: the exit callback normally closes the
        // pipes, but if it never fired (the warning above) a caller blocked on a
        // `read` would otherwise hang forever. No-op once already closed. Only
        // output from a process that outlived even the escalation above can be
        // cut off here, which is the lesser of the two failures.
        io_ctx.close_streams();

        let mut exit_code: i32 = -1;
        let natural_exit_confirmed = exit_signalled || confirmed;
        let hr = started.test_exit_code_result(
            natural_exit_confirmed,
            sdk.WslcGetProcessExitCode(process_guard.as_raw(), &mut exit_code),
        );
        if hr != S_OK && stopped.is_none() {
            return Err(sdk_wait_error("WslcGetProcessExitCode", hr, ""));
        }
        let outcome = match (stopped, confirmed) {
            // Reported only on positive evidence the process ended: the exit
            // event signalling, or the SDK's exit callback. Without either --
            // a null exit event and no callback -- `exit_code` is meaningless.
            (None, _) if exit_signalled || confirmed => {
                let _ = writeln!(logger, "[WSLC] Process exited with code {}", exit_code);
                WaitOutcome::Exited
            }
            (None, _) => {
                return Err(WslcError::Runtime(
                    "the WSLC process never reported an exit: no exit event was available and the \
                     SDK's exit callback did not fire, so the container may still be running"
                        .to_string(),
                )
                .into_step_error());
            }
            (Some(StopReason::ForwardingFailure), _) => {
                let confirmed = confirmed || started.exit_signalled();
                let _ = writeln!(
                    logger,
                    "[WSLC] Process stopped after stdin forwarding failed (exit confirmed: {})",
                    confirmed
                );
                WaitOutcome::Aborted { confirmed }
            }
            (Some(StopReason::Timeout), true) => {
                let _ = writeln!(logger, "[WSLC] Process killed after timeout");
                WaitOutcome::TimedOutTerminated
            }
            // Neither the SIGTERM nor the SIGKILL above produced an exit
            // callback, so nothing here shows the process died. Callers must
            // not claim it was terminated.
            (Some(StopReason::Timeout), false) => {
                let _ = writeln!(
                    logger,
                    "[WSLC] Warning: the container could not be confirmed terminated after the \
                     timeout"
                );
                WaitOutcome::TimedOutUnconfirmed
            }
        };

        Ok((exit_code, outcome))
    }

    /// Collect captured I/O and build the final ScriptResponse.
    fn collect_output(
        io_ctx: &IoContext,
        exit_code: i32,
        outcome: WaitOutcome,
        wait_ms: u32,
        logger: &mut Logger,
    ) -> ScriptResponse {
        let stdout = io_ctx.stdout.captured();
        let stderr = io_ctx.stderr.captured();

        if !stdout.is_empty() {
            let _ = writeln!(logger, "[WSLC] Captured {} bytes stdout", stdout.len());
        }
        if !stderr.is_empty() {
            let _ = writeln!(logger, "[WSLC] Captured {} bytes stderr", stderr.len());
        }

        ScriptResponse {
            exit_code: if outcome == WaitOutcome::Exited {
                exit_code
            } else {
                -1
            },
            standard_out: stdout,
            standard_err: stderr,
            // The unconfirmed wording is not pedantry: the stop is only ever a
            // request, so claiming a termination the SDK never confirmed can
            // tell a caller their sandboxed code is dead while it is running.
            error_message: match outcome {
                WaitOutcome::Exited => String::new(),
                WaitOutcome::TimedOutTerminated => {
                    format!("Process timed out after {}ms and was terminated", wait_ms)
                }
                WaitOutcome::TimedOutUnconfirmed => format!(
                    "Process timed out after {}ms; the container could not be confirmed \
                     terminated and may still be running",
                    wait_ms
                ),
                WaitOutcome::Aborted { .. } => {
                    "the command was stopped because forwarding its stdin failed".to_string()
                }
            },
            ..Default::default()
        }
    }

    /// Orchestrates the full WSLC lifecycle.
    /// Orchestrates the WSLC lifecycle up to a *started* container: preflight
    /// validation, session, image, process/container settings, start, iptables,
    /// and the init-process handle. The caller decides what happens next — wait
    /// to completion ([`Self::run_internal`]) or stream
    /// (the [`SandboxBackend`](crate::mxc_common::sandbox_process::SandboxBackend) impl
    /// in [`crate::wslc_common::sandbox`]).
    ///
    /// `output` selects where the SDK's output callbacks send their bytes; the
    /// caller-side read ends (if any) come back on [`StartedContainer::pipes`],
    /// and the stdin write end `stdin` asks for on [`StartedContainer::stdin`].
    ///
    /// Helpers handle phases that don't involve dangling-pointer risks;
    /// pointer-heavy SDK configuration stays inline to keep owned string
    /// data alive for the duration needed.
    ///
    /// # Safety
    /// Calls into the WSLC SDK via raw FFI. Owned buffers backing pointers
    /// passed to the SDK (cmdline, env, mounts, etc.) must remain alive
    /// until the SDK call that consumes them returns — every such buffer is a
    /// local of this function, and the SDK consumes them by the time
    /// `WslcCreateContainer` returns here. RAII guards (`WslcSessionGuard`,
    /// `WslcContainerGuard`, `WslcProcessGuard`, `IoCtxRawGuard`) ensure handles
    /// and reference counts are released on every exit path.
    pub(crate) unsafe fn start_container(
        &self,
        request: &ExecutionRequest,
        logger: &mut Logger,
        output: OutputMode,
        stdin: InitStdin,
    ) -> Result<StartedContainer, ScriptResponse> {
        self.validate_target_os()?;
        let _ = writeln!(logger, "{START_CONTAINER_BANNER}");

        // WSLc provision-time filesystem-policy gate (D6 normalization → D3
        // delegation → denied-path overlap), shared verbatim with the
        // state-aware provision path via `policy_mapping::apply_provision_policy_gate`
        // so the two runners cannot drift. Only clone the request when
        // normalization actually tightened something; any failure is surfaced on
        // the streaming logger and returned as a `ScriptResponse` error.
        let normalized;
        let request = match policy_mapping::apply_provision_policy_gate(request, logger) {
            Ok(Some(policy)) => {
                normalized = ExecutionRequest {
                    policy,
                    ..request.clone()
                };
                &normalized
            }
            Ok(None) => request,
            Err(error) => {
                let _ = writeln!(logger, "[WSLC] {}", error.message());
                // SDK v2: FilesystemPolicyError::Host maps to WslcError::Host (backend_error).
                // See docs/development/plans/sdk-v2-error-codes.md.
                return Err(WslcError::Rejected(error.message().to_string()).into_response());
            }
        };

        // -- Init: COM + SDK + preflight --
        let network_mode = self.network_mode(request).map_err(as_wslc_rejection)?;
        // Resolved again so this run relays to an address checked just now.
        let custom_proxy = resolve_custom_proxy(&network_mode)?;
        let sdk = sdk_init::init_and_load_sdk(logger)?;

        // -- Session (configure + create in one step to keep string data alive) --
        let session_name = resolve_session_name(&request.container_id);
        let (session_guard, host_loopback) =
            self.create_session(sdk, request, &session_name, &network_mode, logger)?;

        // -- Image resolution --
        let registry = network_mode.registry_access();
        let resolved = image::resolve_image(
            sdk,
            session_guard.as_raw(),
            &self.config.image,
            self.config.image_tar_path.as_deref(),
            &image::StoreHint::CreateAndRun(self.config.storage_path.clone()),
            registry,
            "[WSLC]",
            logger,
        );
        if let Err(e) = resolved {
            // An abandoned pull is still using this session, so releasing it
            // here would free memory the SDK holds.
            if !image::wait_for_pulls_in_flight(PULL_DRAIN_TIMEOUT) {
                std::mem::forget(session_guard);
            }
            return Err(e.into_response());
        }

        let gateway = match &network_mode {
            policy::NetworkMode::Proxied(egress) => {
                for warning in egress.warning_lines() {
                    logger.warning_line(&warning);
                }
                let storage_path = self.storage_path();
                egress_gateway::sweep_leftovers(sdk, session_guard.as_raw(), &storage_path, logger)
                    .map_err(|e| WslcError::Host(e).into_response())?;
                Some(egress_gateway::Gateway::start(
                    sdk,
                    session_guard.as_raw(),
                    &storage_path,
                    &session_name,
                    egress,
                    custom_proxy,
                    &self.config.port_mappings,
                    logger,
                )?)
            }
            policy::NetworkMode::None | policy::NetworkMode::Bridged => None,
        };

        // -- Process settings --
        // String data (script_cstr, env_cstrings, _cwd_cstr) must stay alive
        // until after WslcCreateContainer, so this stays inline.
        let mut process_settings = std::mem::zeroed::<WslcProcessSettings>();
        let hr = sdk.WslcInitProcessSettings(&mut process_settings);
        if hr != S_OK {
            return Err(sdk_error("WslcInitProcessSettings failed", hr, ""));
        }

        // Register I/O callbacks to capture stdout/stderr.
        // We use Arc so the callback context stays alive even if the function
        // returns early (e.g., container creation fails after callbacks are
        // registered). The SDK may still invoke callbacks on its internal
        // threads; Arc ensures the memory isn't freed until all references
        // (including the one held by the SDK via raw pointer) are dropped.
        let (io_ctx, io_wiring) = IoContext::new(output);
        let io_ctx = Arc::new(io_ctx);
        // Give the SDK an Arc reference via raw pointer. We must reconstruct
        // the Arc later to avoid leaking the reference count.
        let io_ctx_for_sdk = Arc::clone(&io_ctx);
        let io_ctx_raw = Arc::into_raw(io_ctx_for_sdk) as *mut c_void;
        let io_ctx_guard = IoCtxRawGuard::new(io_ctx_raw);

        let callbacks = WslcProcessCallbacks {
            onStdOut: Some(io_callback),
            onStdErr: Some(io_callback),
            onExit: Some(exit_callback),
        };
        let hr = sdk.WslcSetProcessSettingsCallbacks(&mut process_settings, &callbacks, io_ctx_raw);
        if hr != S_OK {
            return Err(sdk_error("WslcSetProcessSettingsCallbacks failed", hr, ""));
        }
        if stdin == InitStdin::Piped {
            let hr = sdk.WslcSetProcessSettingsFlags(
                &mut process_settings,
                WslcProcessFlags::WSLC_PROCESS_FLAG_STDIN,
            );
            if hr != S_OK {
                return Err(sdk_error("WslcSetProcessSettingsFlags failed", hr, ""));
            }
        }

        // Route cooperative HTTP clients through the caller-managed proxy:
        // WSLc has no IP-level enforcement hook, so any destination filtering
        // belongs to the proxy. Inject HTTP(S)_PROXY after scrubbing caller
        // proxy variables.
        // See crate::mxc_common::proxy_env.
        let effective_env: Vec<String> = if let Some(gateway) = &gateway {
            gateway.workload_env(request.env_entries(), process_env::EnvScope::of(request))
        } else if request.policy.network_proxy.is_enabled() {
            // A directly constructed request must retain its proxy URL so the
            // guest receives a routable endpoint instead of an empty setting.
            let proxy_url = match request
                .policy
                .network_proxy
                .address
                .as_ref()
                .and_then(|addr| addr.original_url.clone())
            {
                Some(url) => url,
                None => {
                    return Err(WslcError::Rejected(
                        "WSLC: runtimeConfig.networkProxy requires a URL-backed proxy address. \
                         For directly constructed requests, use ProxyAddress::from_url so \
                         the guest can receive HTTP(S)_PROXY."
                            .to_string(),
                    )
                    .into_response());
                }
            };
            let _ = writeln!(
                logger,
                "[WSLC] Cooperative network proxy configured: {}",
                crate::mxc_common::proxy_env::redact_proxy_url(&proxy_url)
            );
            process_env::with_proxy(request.env_entries(), &proxy_url, host_loopback)
        } else {
            request.env_entries().to_vec()
        };

        // These buffers must outlive WslcCreateContainer: the SDK stores the
        // pointers into process_settings (it does not copy), and reads them at
        // container-create time. Dropping them earlier causes a use-after-free
        // (0xC0000005).
        let _command = container_steps::set_command_line_and_env(
            sdk,
            &mut process_settings,
            process_env::EnvScope::of(request),
            &effective_env,
            &request.script_code,
        )?;

        // `validate_runner` has already rejected an unmappable cwd; the `Err`
        // arm keeps this direct entry point fail-closed as well.
        let _cwd_cstr;
        match policy_mapping::container_working_directory(&request.working_directory) {
            Ok(Some(container_cwd)) => {
                _cwd_cstr = format!("{}\0", container_cwd);
                let hr = sdk.WslcSetProcessSettingsWorkingDirectory(
                    &mut process_settings,
                    _cwd_cstr.as_bytes().as_ptr() as PCSTR,
                );
                if hr != S_OK {
                    return Err(sdk_error(
                        "WslcSetProcessSettingsWorkingDirectory failed",
                        hr,
                        "",
                    ));
                }
            }
            Ok(None) => {}
            Err(msg) => return Err(WslcError::Rejected(msg).into_response()),
        }

        // -- Container settings --
        let mut mounts = match policy_mapping::build_volume_mounts(
            &request.policy.readwrite_paths,
            &request.policy.readonly_paths,
        ) {
            Ok(m) => m,
            Err(e) => {
                let _ = writeln!(logger, "[WSLC] {}", e);
                return Err(WslcError::Rejected(e).into_response());
            }
        };
        // Behind the built-in proxy, the gateway owns the port mappings.
        let (networking, port_mappings) = match (&gateway, &network_mode) {
            (Some(gateway), _) => {
                mounts.push(gateway.resolv_conf_mount());
                (gateway.workload_networking(), &[][..])
            }
            (None, policy::NetworkMode::None) => {
                (ContainerNetworking::None, &self.config.port_mappings[..])
            }
            (None, _) => (ContainerNetworking::Nat, &self.config.port_mappings[..]),
        };
        let mut flags = WslcContainerFlags::WSLC_CONTAINER_FLAG_NONE;
        if request.lifecycle.destroy_on_exit {
            flags |= WslcContainerFlags::WSLC_CONTAINER_FLAG_AUTO_REMOVE;
        }
        if self.config.gpu {
            flags |= WslcContainerFlags::WSLC_CONTAINER_FLAG_ENABLE_GPU;
        }
        let mut container_settings = ContainerSettings::build(
            sdk,
            &self.config.image,
            &mounts,
            port_mappings,
            networking,
            flags,
            logger,
        )?;

        let hr = sdk.WslcSetContainerSettingsInitProcess(
            container_settings.raw_mut(),
            &mut process_settings,
        );
        if hr != S_OK {
            return Err(sdk_error(
                "WslcSetContainerSettingsInitProcess failed",
                hr,
                "",
            ));
        }

        // -- Create & start container --
        let mut container: WslcContainer = ptr::null_mut();
        let mut err_msg = CoTaskMemPWSTR::null();
        let hr = sdk.WslcCreateContainer(
            session_guard.as_raw(),
            container_settings.raw(),
            &mut container,
            err_msg.as_mut_ptr(),
        );
        if hr != S_OK {
            let msg = err_msg.to_string_lossy();
            return Err(sdk_error("WslcCreateContainer failed", hr, &msg));
        }
        let container_guard = WslcContainerGuard::from_raw(container, sdk.release_container_fn());
        let _ = writeln!(logger, "[WSLC] Container created");

        err_msg = CoTaskMemPWSTR::null();
        let hr = sdk.WslcStartContainer(
            container_guard.as_raw(),
            WslcContainerStartFlags::WSLC_CONTAINER_START_FLAG_ATTACH,
            err_msg.as_mut_ptr(),
        );
        if hr != S_OK {
            let msg = err_msg.to_string_lossy();
            return Err(sdk_error("WslcStartContainer failed", hr, &msg));
        }
        let _ = writeln!(logger, "[WSLC] Container started");

        // From here the container is live and the SDK is delivering callbacks
        // into `io_ctx`. A bare `return Err(..)` would drop the locals in
        // reverse declaration order — freeing the callback context (`io_ctx` /
        // `io_ctx_guard`) *before* the session is terminated and the DLL
        // unloaded — so a late callback could dereference freed memory. Every
        // failure past this point therefore quiesces the container first.
        let post_start = Self::container_id(sdk, &container_guard)
            .and_then(|id| Ok((id, Self::attach_init_process(sdk, &container_guard)?)));
        let (container_id, process_guard) = match post_start {
            Ok(started) => started,
            Err(e) => {
                Self::quiesce_started_container(
                    sdk,
                    &container_guard,
                    &io_ctx,
                    request.lifecycle.destroy_on_exit,
                    logger,
                );
                return Err(e);
            }
        };
        let stdin = match stdin {
            InitStdin::Closed => None,
            InitStdin::Piped => match Self::take_init_stdin(sdk, &process_guard) {
                Ok(pipe) => Some(InterruptiblePipeWriter::new(pipe)),

                // The process would wait for input nobody can send, so it is
                // stopped rather than left running.
                Err(e) => {
                    Self::quiesce_started_container(
                        sdk,
                        &container_guard,
                        &io_ctx,
                        request.lifecycle.destroy_on_exit,
                        logger,
                    );
                    return Err(e);
                }
            },
        };

        Ok(StartedContainer {
            process_guard,
            container_guard,
            container_id,
            gateway,
            session_guard,
            io_ctx_guard,
            io_ctx,
            sdk,
            pipes: io_wiring.pipes,
            stdin_closers: Arc::new(Mutex::new(
                stdin
                    .iter()
                    .map(|writer| Box::new(writer.canceller()) as Box<dyn StreamCloser>)
                    .collect(),
            )),
            exit_event: Mutex::new(None),
            stdin,
            pumps: Mutex::new(io_wiring.pumps),
            settled: AtomicBool::new(false),
            destroy_on_exit: request.lifecycle.destroy_on_exit,
            timeout_ms: wait_timeout_ms(request),
            #[cfg(all(feature = "test-support", debug_assertions))]
            test_script_code: request.script_code.clone().into_boxed_str(),
        })
    }

    /// # Safety
    /// `sdk` must hold valid function pointers and `process` must be a live
    /// handle created with `WSLC_PROCESS_FLAG_STDIN`.
    unsafe fn take_init_stdin(
        sdk: &'static WslcSdk,
        process: &WslcProcessGuard,
    ) -> Result<std::fs::File, ScriptResponse> {
        use std::os::windows::io::FromRawHandle;

        let mut handle: HANDLE = ptr::null_mut();
        let hr = sdk.WslcGetProcessIOHandle(
            process.as_raw(),
            WslcProcessIOHandle::WSLC_PROCESS_IO_HANDLE_STDIN,
            &mut handle,
        );
        if hr != S_OK || handle.is_null() {
            return Err(sdk_error("WslcGetProcessIOHandle(stdin) failed", hr, ""));
        }
        // SAFETY: the SDK transfers ownership of the returned handle to the caller.
        Ok(std::fs::File::from_raw_handle(handle))
    }

    /// # Safety
    /// `sdk` must hold valid function pointers and `container` a live handle.
    unsafe fn container_id(
        sdk: &'static WslcSdk,
        container: &WslcContainerGuard,
    ) -> Result<CString, ScriptResponse> {
        let mut id = [0u8; WSLC_CONTAINER_ID_BUFFER_SIZE as usize];
        let hr = sdk.WslcGetContainerID(container.as_raw(), id.as_mut_ptr().cast());
        if hr != S_OK {
            return Err(sdk_error("WslcGetContainerID failed", hr, ""));
        }
        CStr::from_bytes_until_nul(&id)
            .map(CStr::to_owned)
            .map_err(|_| sdk_error("WslcGetContainerID returned no terminator", hr, ""))
    }

    /// Take the container's init process handle. Split out so every failure
    /// between "container started" and "handle in hand" funnels through one
    /// caller-side cleanup path.
    ///
    /// # Safety
    /// `sdk` must hold valid function pointers and `container` a live handle.
    unsafe fn attach_init_process(
        sdk: &'static WslcSdk,
        container: &WslcContainerGuard,
    ) -> Result<WslcProcessGuard, ScriptResponse> {
        let mut process: WslcProcess = ptr::null_mut();
        let hr = sdk.WslcGetContainerInitProcess(container.as_raw(), &mut process);
        if hr != S_OK {
            return Err(sdk_error("WslcGetContainerInitProcess failed", hr, ""));
        }
        Ok(WslcProcessGuard::from_raw(
            process,
            sdk.release_process_fn(),
        ))
    }

    /// Stop a started container and block until the SDK's exit callback has
    /// fired, so no further callback can reference the context the caller is
    /// about to drop. Best-effort: every step's failure is ignored, because the
    /// caller is already unwinding a more meaningful error.
    ///
    /// # Safety
    /// `sdk` must hold valid function pointers and `container` a live handle.
    unsafe fn quiesce_started_container(
        sdk: &'static WslcSdk,
        container: &WslcContainerGuard,
        io_ctx: &Arc<IoContext>,
        destroy_on_exit: bool,
        logger: &mut Logger,
    ) {
        let mut err_msg = CoTaskMemPWSTR::null();
        let _ = sdk.WslcStopContainer(
            container.as_raw(),
            WslcSignal::WSLC_SIGNAL_SIGKILL,
            5,
            err_msg.as_mut_ptr(),
        );
        drop(err_msg);

        io_ctx.close_streams();
        if !await_callbacks_quiesced(io_ctx) {
            let _ = writeln!(
                logger,
                "[WSLC] Warning: exit callback did not fire within {}s while cleaning up a \
                 failed start; leaking the callback context",
                EXIT_CALLBACK_TIMEOUT.as_secs()
            );
        }

        if destroy_on_exit {
            let mut err_msg = CoTaskMemPWSTR::null();
            let _ = sdk.WslcDeleteContainer(
                container.as_raw(),
                WslcDeleteContainerFlags::WSLC_DELETE_CONTAINER_FLAG_FORCE,
                err_msg.as_mut_ptr(),
            );
            drop(err_msg);
        }
    }

    /// Run to completion: start the container, wait for the init process, tear
    /// it down, and return the captured output.
    ///
    /// # Safety
    /// Calls into the WSLC SDK via raw FFI — see
    /// [`start_container`](Self::start_container).
    unsafe fn run_internal(
        &self,
        request: &ExecutionRequest,
        logger: &mut Logger,
    ) -> ScriptResponse {
        let host_stdin = host_stdin_to_forward();
        let init_stdin = match host_stdin {
            Some(_) => InitStdin::Piped,
            None => InitStdin::Closed,
        };
        let mut started =
            match self.start_container(request, logger, OutputMode::Capture, init_stdin) {
                Ok(started) => started,
                Err(response) => return response,
            };
        let forwarding = match (host_stdin, started.stdin.take()) {
            (Some(input), Some(pipe)) => match forward_host_stdin(&started, input, pipe) {
                Ok(forwarding) => Some(forwarding),
                Err((error, pipe)) => {
                    started.quiesce(logger);
                    drop(started);
                    drop(pipe);
                    return WslcError::Runtime(format!(
                        "could not start forwarding stdin to the WSL container: {error}"
                    ))
                    .into_response();
                }
            },
            _ => None,
        };

        // -- Wait for exit --
        let waited = {
            use std::os::windows::io::AsRawHandle;

            let abort_event = forwarding
                .as_ref()
                .map_or(ptr::null_mut(), |(_, abort)| abort.as_raw_handle());
            started.wait_for_exit_or_abort(abort_event, logger)
        };
        let command_gone = matches!(&waited, Ok((_, outcome)) if outcome.confirmed_gone());
        let stdin_failure = forwarding
            .as_ref()
            .and_then(|(forwarding, _)| forwarding.end_run(command_gone));
        let response = match waited {
            Ok((exit_code, outcome)) => {
                // The run-to-completion path reports through `ScriptResponse`,
                // which is built from the process's own result; a teardown
                // failure is logged by `destroy` rather than replacing that result.
                let _ = started.destroy(logger);

                let response = Self::collect_output(
                    &started.io_ctx,
                    exit_code,
                    outcome,
                    started.timeout_ms,
                    logger,
                );
                match stdin_failure {
                    Some(reason) if command_gone => stdin_forwarding_failed(response, &reason),
                    Some(reason) => stdin_forwarding_failed(
                        response,
                        &format!("{reason}; the command could not be confirmed stopped"),
                    ),
                    None => response,
                }
            }
            Err(e) => {
                // `wait_for_exit` can fail while the container is still running
                // (a failed apartment, or `WslcGetProcessExitEvent`). Returning
                // straight away would drop `started`, freeing the callback
                // context and unloading the DLL under live callbacks, so settle
                // the container first.
                started.quiesce(logger);
                e.into_response()
            }
        };

        drop(started);
        if let Some((forwarding, _)) = forwarding {
            forwarding.finish_teardown();
        }
        response
    }
}

/// This process's stdin, unless it is a terminal.
fn host_stdin_to_forward() -> Option<std::io::Stdin> {
    use std::io::IsTerminal;

    let stdin = std::io::stdin();
    if stdin.is_terminal() {
        eprintln!(
            "WARNING: stdin is a terminal, but WSLc create-and-run execution does not forward \
             interactive input. The command sees end-of-file on stdin. Redirect stdin from a file \
             or a pipe to send it input."
        );
        return None;
    }
    Some(stdin)
}

/// Copies host stdin into a container's stdin, closing it at end-of-file.
struct HostStdinForwarding(Arc<Mutex<ForwardingState>>);

#[derive(Default)]
struct ForwardingState {
    failure: Option<String>,
    run_over: bool,
    command_may_run: bool,
    torn_down: bool,
    unclosed_stdin: Option<Box<dyn std::io::Write + Send>>,
}

impl HostStdinForwarding {
    /// If forwarding fails before [`end_run`](Self::end_run), `stop_run` stops
    /// the command and returns whether it is known to have stopped.
    fn start<P: std::io::Write + Send + 'static>(
        mut input: impl Read + Send + 'static,
        pipe: P,
        stop_run: impl FnOnce() -> bool + Send + 'static,
    ) -> Result<Self, (std::io::Error, P)> {
        let state = Arc::new(Mutex::new(ForwardingState::default()));
        let pump_state = Arc::clone(&state);
        let pipe_slot = Arc::new(Mutex::new(Some(pipe)));
        let pump_pipe = Arc::clone(&pipe_slot);

        // Never joined: a host stdin that never closes keeps this thread
        // blocked, and the executor exits once the run is over regardless.
        let spawned = std::thread::Builder::new()
            .name("wslc-host-stdin".to_string())
            .spawn(move || {
                let Some(mut pipe) = lock(&pump_pipe).take() else {
                    return;
                };
                if let Err(error) = forward_stdin(&mut input, &mut pipe) {
                    let mut state = lock(&pump_state);

                    // Closing the pipe while the command may still run would
                    // let it read the early end-of-file as the end of its input.
                    let keep_open = if state.run_over {
                        state.command_may_run && !state.torn_down
                    } else {
                        state.failure = Some(error.to_string());
                        !stop_run()
                    };
                    if keep_open {
                        state.unclosed_stdin = Some(Box::new(pipe));
                        return;
                    }
                }
                drop(pipe);
            });
        let unstarted_pipe = spawned.as_ref().err().and_then(|_| lock(&pipe_slot).take());
        match (spawned, unstarted_pipe) {
            (Err(error), Some(pipe)) => Err((error, pipe)),
            _ => Ok(Self(state)),
        }
    }

    /// Mark the run as over and return any failure from before that point;
    /// later failures are ignored.
    fn end_run(&self, command_gone: bool) -> Option<String> {
        let mut state = lock(&self.0);
        state.run_over = true;
        state.command_may_run = !command_gone;
        state.failure.clone()
    }

    /// Close the container's stdin if forwarding kept it open; call once the
    /// container's session is gone.
    fn finish_teardown(&self) {
        let unclosed = {
            let mut state = lock(&self.0);
            state.torn_down = true;
            state.unclosed_stdin.take()
        };
        drop(unclosed);
    }
}

/// The returned event signals when a forwarding failure could not stop the command.
fn forward_with_abort<P: std::io::Write + Send + 'static>(
    input: impl Read + Send + 'static,
    pipe: P,
    stop_run: impl FnOnce() -> bool + Send + 'static,
) -> Result<(HostStdinForwarding, std::os::windows::io::OwnedHandle), (std::io::Error, P)> {
    use std::os::windows::io::AsRawHandle;

    let events = manual_reset_event().and_then(|abort| {
        let signal_abort = abort.try_clone()?;
        Ok((abort, signal_abort))
    });
    let (abort, signal_abort) = match events {
        Ok(events) => events,
        Err(error) => return Err((error, pipe)),
    };
    let forwarding = HostStdinForwarding::start(input, pipe, move || {
        let stopped = stop_run();
        if !stopped {
            // SAFETY: `signal_abort` is a live event handle owned here.
            let _ = unsafe {
                windows::Win32::System::Threading::SetEvent(windows::Win32::Foundation::HANDLE(
                    signal_abort.as_raw_handle(),
                ))
            };
        }
        stopped
    })?;
    Ok((forwarding, abort))
}

fn forward_host_stdin<P: std::io::Write + Send + 'static>(
    started: &StartedContainer,
    input: impl Read + Send + 'static,
    pipe: P,
) -> Result<(HostStdinForwarding, std::os::windows::io::OwnedHandle), (std::io::Error, P)> {
    let exit_event = match started.duplicate_exit_event() {
        Ok(exit_event) => exit_event,
        Err(error) => return Err((std::io::Error::other(error), pipe)),
    };

    // SAFETY: the stopper is used only while the run is not over, and
    // `run_internal` ends the run before tearing down.
    let stopper = unsafe { started.stopper() };
    forward_with_abort(input, pipe, move || stopper.stop(exit_event))
}

/// Copy `input` into `pipe` until `input` ends or the process stops reading.
fn forward_stdin(input: &mut impl Read, pipe: &mut impl std::io::Write) -> std::io::Result<()> {
    let mut buf = vec![0u8; 64 * 1024];
    loop {
        let read = match input.read(&mut buf) {
            Ok(0) => return Ok(()),
            Ok(read) => read,
            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(error) => {
                return Err(std::io::Error::new(
                    error.kind(),
                    format!("reading host stdin: {error}"),
                ))
            }
        };
        match pipe.write_all(&buf[..read]) {
            Ok(()) => {}
            Err(error) if error.kind() == std::io::ErrorKind::BrokenPipe => return Ok(()),
            Err(error) => {
                return Err(std::io::Error::new(
                    error.kind(),
                    format!("writing the container's stdin: {error}"),
                ))
            }
        }
    }
}

/// Report a run whose stdin forwarding failed as failed, since the command did
/// not receive all of its input.
fn stdin_forwarding_failed(response: ScriptResponse, reason: &str) -> ScriptResponse {
    let failed = WslcError::Runtime(format!(
        "forwarding stdin to the WSL container failed before the command received all of its \
         input: {reason}"
    ))
    .into_response();
    ScriptResponse {
        exit_code: failed.exit_code,
        error_message: failed.error_message,
        failure_phase: failed.failure_phase,
        ..response
    }
}

/// The wait deadline in milliseconds for `request`; `u32::MAX` means "wait
/// forever" (the request carries `0` for no timeout).
fn wait_timeout_ms(request: &ExecutionRequest) -> u32 {
    if request.script_timeout > 0 {
        request.script_timeout
    } else {
        u32::MAX
    }
}

#[derive(Debug, PartialEq, Eq)]
enum ExitWait {
    Exited,
    TimedOut,
    Aborted,
}

/// Wait up to `wait_ms` for `exit_event`, or for `abort_event` unless it is null.
///
/// # Safety
/// Both handles must be null or live event handles; `exit_event` must not be null.
unsafe fn wait_for_exit_or_abort(
    exit_event: HANDLE,
    abort_event: HANDLE,
    wait_ms: u32,
) -> Result<ExitWait, String> {
    use windows::Win32::Foundation::{GetLastError, WAIT_OBJECT_0, WAIT_TIMEOUT};
    use windows::Win32::System::Threading::WaitForMultipleObjects;

    let mut events = vec![windows::Win32::Foundation::HANDLE(exit_event)];
    if !abort_event.is_null() {
        events.push(windows::Win32::Foundation::HANDLE(abort_event));
    }
    let result = WaitForMultipleObjects(&events, false, wait_ms);
    match result {
        WAIT_OBJECT_0 => Ok(ExitWait::Exited),
        WAIT_TIMEOUT => Ok(ExitWait::TimedOut),
        _ if events.len() == 2 && result.0 == WAIT_OBJECT_0.0 + 1 => Ok(ExitWait::Aborted),

        // The wait told us nothing about the process, so neither "exited" nor
        // "timed out" can be claimed.
        _ => Err(format!(
            "waiting on the WSLC process exit event failed: WaitForMultipleObjects returned \
             0x{:08X} (GetLastError 0x{:08X})",
            result.0,
            GetLastError().0
        )),
    }
}

fn manual_reset_event() -> std::io::Result<std::os::windows::io::OwnedHandle> {
    use std::os::windows::io::FromRawHandle;

    // SAFETY: creates a new unnamed event.
    let event = unsafe {
        windows::Win32::System::Threading::CreateEventW(
            None,
            true,
            false,
            windows::core::PCWSTR::null(),
        )
    }
    .map_err(std::io::Error::other)?;

    // SAFETY: `CreateEventW` returned a new handle that nothing else owns.
    Ok(unsafe { std::os::windows::io::OwnedHandle::from_raw_handle(event.0) })
}

/// Signal a container's processes; `timeout_secs` is how long the SDK waits for
/// a graceful stop.
///
/// # Safety
/// `container` must be a live container handle from `sdk`.
unsafe fn stop_container(
    sdk: &WslcSdk,
    container: WslcContainer,
    signal: WslcSignal,
    timeout_secs: u32,
) -> Result<(), String> {
    let _com = ComApartment::enter()?;
    let mut err_msg = CoTaskMemPWSTR::null();
    let hr = sdk.WslcStopContainer(container, signal, timeout_secs, err_msg.as_mut_ptr());
    if hr != S_OK {
        let msg = err_msg.to_string_lossy();
        return Err(format!(
            "WslcStopContainer failed: {msg} (HRESULT 0x{:08X})",
            hr as u32
        ));
    }
    Ok(())
}

/// Force-stops a container from a thread that does not own it; see
/// [`StartedContainer::stopper`].
struct ContainerStopper {
    sdk: &'static WslcSdk,
    container: WslcContainer,
}

// SAFETY: the SDK is apartment-affine, not thread-affine, as `image::PullJob`
// relies on: `stop_container` joins the MTA, where a handle may be used from any
// member thread. `StartedContainer::stopper` makes the caller keep it alive.
unsafe impl Send for ContainerStopper {}

impl ContainerStopper {
    /// Returns whether `exit_event` then showed the process exited.
    fn stop(self, exit_event: Option<std::os::windows::io::OwnedHandle>) -> bool {
        use std::os::windows::io::AsRawHandle;

        // SAFETY: `StartedContainer::stopper`'s caller keeps the container alive.
        let _ =
            unsafe { stop_container(self.sdk, self.container, WslcSignal::WSLC_SIGNAL_SIGKILL, 0) };
        exit_event.is_some_and(|event| {
            // SAFETY: `event` is a live handle owned here.
            let result = unsafe {
                windows::Win32::System::Threading::WaitForSingleObject(
                    windows::Win32::Foundation::HANDLE(event.as_raw_handle()),
                    STOP_CONFIRM_TIMEOUT.as_millis() as u32,
                )
            };
            result == windows::Win32::Foundation::WAIT_OBJECT_0
        })
    }
}

/// Closes every carrier of a process's stdin registered so far.
struct SharedStdinClosers(Arc<Mutex<Vec<Box<dyn StreamCloser>>>>);

impl StreamCloser for SharedStdinClosers {
    fn close(&self) {
        for closer in lock(&self.0).iter() {
            closer.close();
        }
    }
}

/// A started WSLC container plus everything needed to wait on, stream, and tear
/// down its init process.
///
/// Field order is the drop order and matters: the process, container, and
/// session handles are released first, then the SDK callback context. `sdk` is
/// a borrow of the process-wide, never-unloaded instance
/// ([`WslcSdk::shared`]), so it carries no drop-order significance.
pub(crate) struct StartedContainer {
    process_guard: WslcProcessGuard,
    container_guard: WslcContainerGuard,
    /// Looks the container up in the session after its handle disconnects.
    container_id: CString,
    /// The built-in proxy, removed before the session ends.
    gateway: Option<egress_gateway::Gateway>,
    /// Terminates and releases the WSLC session on drop.
    session_guard: WslcSessionGuard,
    /// Held for its `Drop`, which reclaims the `Arc<IoContext>` reference handed
    /// to the SDK by raw pointer.
    #[allow(
        dead_code,
        reason = "RAII guard: reclaims the callback context on drop"
    )]
    io_ctx_guard: IoCtxRawGuard,
    io_ctx: Arc<IoContext>,
    sdk: &'static WslcSdk,
    /// Caller-side read ends, present only for [`StdioMode::Pipes`].
    pub(crate) pipes: Option<StreamPipes>,

    /// The init process's stdin write end, present only for [`InitStdin::Piped`].
    pub(crate) stdin: Option<InterruptiblePipeWriter>,

    /// Close whatever carries the process's stdin, wherever it was taken to.
    stdin_closers: Arc<Mutex<Vec<Box<dyn StreamCloser>>>>,

    /// The process's exit event, fetched once because the SDK does not say
    /// whether each fetch hands back a new handle.
    exit_event: Mutex<Option<usize>>,

    /// Host-stdio forwarders, present only for [`StdioMode::Inherit`]. Joined
    /// by [`join_pumps`](Self::join_pumps) once the streams are closed, so the
    /// container's last output reaches the host before teardown returns.
    /// `Mutex` only so the `&self` teardown methods can take them.
    pumps: Mutex<Vec<std::thread::JoinHandle<()>>>,
    /// Whether teardown has already run, so [`Drop`] knows not to repeat it —
    /// and, crucially, knows to *run* it when an unwind skipped it.
    settled: AtomicBool,
    /// Whether the container is stopped and deleted after the process exits.
    pub(crate) destroy_on_exit: bool,
    /// Wait deadline in milliseconds; `u32::MAX` waits forever.
    pub(crate) timeout_ms: u32,
    #[cfg(all(feature = "test-support", debug_assertions))]
    test_script_code: Box<str>,
}

impl Drop for StartedContainer {
    /// Settle a container no teardown path reached — in practice, one abandoned
    /// by a **panic** unwinding past it.
    ///
    /// Without this, unwinding drops the fields below in declaration order:
    /// the guards close the SDK handles and the `IoContext` is freed while the
    /// SDK may still be invoking callbacks that write through it. Every normal
    /// path already tears down explicitly (and marks the container settled), so
    /// this only fires when something skipped them.
    fn drop(&mut self) {
        if self.settled.load(Ordering::Acquire) {
            return;
        }
        // No error channel and no caller logger here, so the diagnostics are
        // buffered and dropped with `self`; the alternative is a use-after-free.
        let mut logger = Logger::new(Mode::Buffer);
        self.quiesce(&mut logger);
    }
}

impl StartedContainer {
    /// Check a stop or delete result; `Ok(true)` means the service already
    /// removed the auto-remove container. The service disconnects the handle
    /// when it does, but so does a crashed service, so the session must
    /// confirm the container is gone.
    ///
    /// # Safety
    /// The caller must be in a COM apartment.
    unsafe fn teardown_step(
        &self,
        call: &str,
        hr: HRESULT,
        err_msg: &CoTaskMemPWSTR,
    ) -> Result<bool, String> {
        if hr == S_OK {
            return Ok(false);
        }
        let failed = format!(
            "{call} failed: {} (HRESULT 0x{:08X})",
            err_msg.to_string_lossy(),
            hr as u32
        );
        if hr != RPC_E_DISCONNECTED && hr != WSLC_E_CONTAINER_NOT_FOUND {
            return Err(failed);
        }
        match session_resources::open_container(
            self.sdk,
            self.session_guard.as_raw(),
            &self.container_id,
        ) {
            Ok(None) => Ok(true),
            Ok(Some(_)) => Err(format!("{failed}; the container still exists")),
            Err(e) => Err(format!("{failed}; {e}")),
        }
    }

    /// Wait for the init process to exit, enforcing the request's timeout
    /// (stopping the container when it fires). Returns `(exit_code, timed_out)`.
    pub(crate) fn wait_for_exit(
        &self,
        logger: &mut Logger,
    ) -> Result<(i32, WaitOutcome), WslcStepError> {
        self.wait_for_exit_or_abort(ptr::null_mut(), logger)
    }

    fn wait_for_exit_or_abort(
        &self,
        abort_event: HANDLE,
        logger: &mut Logger,
    ) -> Result<(i32, WaitOutcome), WslcStepError> {
        // The handle is `Send`, so this may run on a thread that never entered
        // the apartment `init_and_load_sdk` established; join it for the call.
        let _com = ComApartment::enter().map_err(|e| WslcError::Host(e).into_step_error())?;
        let exit_event = self.exit_event()?;
        // SAFETY: `self` owns live process / container handles and a live SDK.
        unsafe { WSLContainerRunner::wait_for_process(self, exit_event, abort_event, logger) }
    }

    fn test_exit_code_result(&self, natural_exit_confirmed: bool, result: HRESULT) -> HRESULT {
        #[cfg(all(feature = "test-support", debug_assertions))]
        {
            container_steps::test_exit_code_result(
                &self.test_script_code,
                natural_exit_confirmed,
                result,
            )
        }

        #[cfg(not(all(feature = "test-support", debug_assertions)))]
        {
            let _ = natural_exit_confirmed;
            result
        }
    }

    pub(crate) fn add_stdin_closer(&self, closer: Box<dyn StreamCloser>) {
        lock(&self.stdin_closers).push(closer);
    }

    /// Close the process's stdin, ending any write blocked on it.
    pub(crate) fn close_stdin(&self) {
        self.stdin_closer().close();
    }

    /// A closer for the process's stdin that also closes whatever is
    /// registered with [`add_stdin_closer`](Self::add_stdin_closer) later.
    pub(crate) fn stdin_closer(&self) -> Box<dyn StreamCloser> {
        Box::new(SharedStdinClosers(Arc::clone(&self.stdin_closers)))
    }

    /// A copy of the process's exit event that stays valid after this
    /// container is dropped, or `None` if the SDK has no exit event.
    pub(crate) fn duplicate_exit_event(
        &self,
    ) -> Result<Option<std::os::windows::io::OwnedHandle>, String> {
        use std::os::windows::io::FromRawHandle;
        use windows::Win32::Foundation::{DuplicateHandle, DUPLICATE_SAME_ACCESS};
        use windows::Win32::System::Threading::GetCurrentProcess;

        let event = self.exit_event().map_err(|error| error.error_message)?;
        if event.is_null() {
            return Ok(None);
        }
        let mut copy = windows::Win32::Foundation::HANDLE::default();

        // SAFETY: the SDK keeps the event valid while the process handle lives.
        unsafe {
            DuplicateHandle(
                GetCurrentProcess(),
                windows::Win32::Foundation::HANDLE(event),
                GetCurrentProcess(),
                &mut copy,
                0,
                false,
                DUPLICATE_SAME_ACCESS,
            )
        }
        .map_err(|error| format!("duplicating the WSLC process exit event failed: {error}"))?;

        // SAFETY: `DuplicateHandle` returned a new handle that nothing else owns.
        Ok(Some(unsafe {
            std::os::windows::io::OwnedHandle::from_raw_handle(copy.0)
        }))
    }

    /// The process's exit event, or a null handle if the SDK has none.
    fn exit_event(&self) -> Result<HANDLE, WslcStepError> {
        let mut cached = lock(&self.exit_event);
        if let Some(event) = *cached {
            return Ok(event as HANDLE);
        }
        let _com = ComApartment::enter().map_err(|e| WslcError::Host(e).into_step_error())?;
        let mut event: HANDLE = ptr::null_mut();

        // SAFETY: `self` owns a live process handle and SDK.
        let hr = unsafe {
            self.sdk
                .WslcGetProcessExitEvent(self.process_guard.as_raw(), &mut event)
        };
        if hr != S_OK {
            return Err(sdk_wait_error("WslcGetProcessExitEvent", hr, ""));
        }
        *cached = Some(event as usize);
        Ok(event)
    }

    /// Whether the exit event has signalled, which can be long before the exit
    /// callback.
    pub(crate) fn exit_signalled(&self) -> bool {
        self.exit_signalled_within(std::time::Duration::ZERO)
    }

    fn exit_signalled_within(&self, wait: std::time::Duration) -> bool {
        match self.exit_event() {
            Ok(event) if !event.is_null() => {
                // SAFETY: the SDK keeps the event valid while the process handle lives.
                let result = unsafe {
                    windows::Win32::System::Threading::WaitForSingleObject(
                        windows::Win32::Foundation::HANDLE(event),
                        wait.as_millis().try_into().unwrap_or(u32::MAX),
                    )
                };
                result == windows::Win32::Foundation::WAIT_OBJECT_0
            }
            _ => false,
        }
    }

    /// Stop the container and block until the SDK's exit callback has fired,
    /// then tear it down — the teardown for any path that abandons a *started*
    /// container without a completed wait (an error return, or a handle dropped
    /// mid-run).
    ///
    /// The exit callback is the SDK's guarantee that no further callback will
    /// arrive, which must hold before this container's fields drop: they free
    /// the `IoContext` those callbacks write through and then unload the DLL.
    /// The happy path reaches the same guarantee via
    /// [`wait_for_exit`](Self::wait_for_exit) followed by
    /// [`destroy`](Self::destroy).
    pub(crate) fn quiesce(&self, logger: &mut Logger) {
        // Force-stop: this only runs when the run is already being abandoned,
        // so there is no `destroyOnExit: false` container left to keep alive.
        // `0` means "don't wait for a graceful stop".
        let _ = self.stop(WslcSignal::WSLC_SIGNAL_SIGKILL, 0);

        // A command not known to be gone keeps its stdin until teardown, so it
        // cannot read input cut short by the stop as complete.
        let exited = self.exit_signalled_within(STOP_CONFIRM_TIMEOUT);
        if exited {
            self.close_stdin();
        }
        self.close_streams();
        if !await_callbacks_quiesced(&self.io_ctx) {
            let _ = writeln!(
                logger,
                "[WSLC] Warning: exit callback did not fire within {}s while abandoning a \
                 started container; leaking the callback context",
                EXIT_CALLBACK_TIMEOUT.as_secs()
            );
        } else if !exited {
            self.close_stdin();
        }
        // Best-effort by construction: this is the last-resort path (an
        // abandoned run, or `Drop`), so there is no caller left to hand a
        // failure to. `destroy` logs it.
        let _ = self.destroy(logger);
    }

    /// Wait for the host-stdio forwarders to finish.
    ///
    /// Only [`StdioMode::Inherit`] has any, and they end as soon as their
    /// stream is closed and drained — so this is where the container's last
    /// output reaches the host. Deliberately *after* the container is settled:
    /// a host that has stopped draining its own stdout then delays only this
    /// final flush, never the SDK teardown that a callback-thread write would
    /// have stalled.
    fn join_pumps(&self) {
        for pump in lock(&self.pumps).drain(..) {
            let _ = pump.join();
        }
    }

    /// Stop and delete the container when the request asked for it. The session
    /// is terminated by `WslcSessionGuard`'s `Drop`.
    ///
    /// Returns the failure rather than swallowing it: a container that would
    /// not stop or delete still holds a VM-backed sandbox, which the streaming
    /// path turns into a retry from `Drop` instead of a silent leak.
    pub(crate) fn destroy(&self, logger: &mut Logger) -> Result<(), String> {
        // No apartment, no SDK calls — the same rule the handle guards' `Drop`
        // impls follow. Stopping the container matters (it is a live VM, not
        // just an in-process handle), but calling the SDK apartment-less is
        // precisely what the `Send` soundness argument rules out, and it would
        // most likely fail anyway. Reported so the caller learns the container
        // leaked rather than believing it was destroyed.
        let _com = match ComApartment::enter() {
            Ok(com) => com,
            Err(e) => {
                let msg =
                    format!("{e}; skipped container teardown to avoid an apartment-less SDK call");
                let _ = writeln!(logger, "[WSLC] Cleanup failed: {msg}");
                return Err(msg);
            }
        };
        let mut failure: Option<String> = None;
        if self.destroy_on_exit {
            // SAFETY: the guards hold live handles for `self`'s lifetime and
            // `sdk`'s function pointers are valid while it is alive.
            unsafe {
                let mut err_msg = CoTaskMemPWSTR::null();
                let hr = self.sdk.WslcStopContainer(
                    self.container_guard.as_raw(),
                    WslcSignal::WSLC_SIGNAL_SIGTERM,
                    10,
                    err_msg.as_mut_ptr(),
                );
                let stopped = self.teardown_step("WslcStopContainer", hr, &err_msg);
                drop(err_msg);
                let removed = matches!(stopped, Ok(true));
                if removed {
                    let _ = writeln!(logger, "[WSLC] Container already removed by the service");
                }
                if let Err(e) = stopped {
                    failure = Some(e);
                }

                // Attempted even after a failed stop: the delete is forced, so
                // it is the better chance of not leaking the container.
                if !removed {
                    let mut err_msg = CoTaskMemPWSTR::null();
                    let hr = self.sdk.WslcDeleteContainer(
                        self.container_guard.as_raw(),
                        WslcDeleteContainerFlags::WSLC_DELETE_CONTAINER_FLAG_FORCE,
                        err_msg.as_mut_ptr(),
                    );
                    if let Err(e) = self.teardown_step("WslcDeleteContainer", hr, &err_msg) {
                        failure.get_or_insert(e);
                    }
                    drop(err_msg);
                }
            }
        }
        if let Some(gateway) = &self.gateway {
            if let Err(e) = gateway.teardown(logger) {
                failure = Some(match failure {
                    Some(first) => format!("{first}; {e}"),
                    None => e,
                });
            }
        }

        // Teardown has now run, whether or not it succeeded: `Drop` must not
        // repeat the stop/delete, and the streaming path tracks a *failed*
        // teardown through its own `torn_down` flag so it can retry deliberately.
        self.settled.store(true, Ordering::Release);
        // The streams are done, so the forwarders can finish flushing to the
        // host now that the container itself is settled.
        self.close_streams();
        self.join_pumps();

        // Session termination is handled by WslcSessionGuard's Drop impl.
        match failure {
            Some(e) => {
                let _ = writeln!(logger, "[WSLC] Cleanup failed: {e}");
                Err(e)
            }
            None => {
                let _ = writeln!(logger, "[WSLC] Cleanup complete");
                Ok(())
            }
        }
    }

    /// Confirm the init process is really gone, escalating to `SIGKILL` when it
    /// is not — the teardown the timeout path owes its caller.
    ///
    /// [`wait_for_exit`](Self::wait_for_exit)'s timeout branch only *asks* the
    /// container to stop (`SIGTERM` with a two-second grace, HRESULT ignored),
    /// so reaching it proves nothing about whether the sandboxed process died.
    /// Since `SandboxProcess::wait` reporting `TimedOut` promises it was
    /// terminated, that promise is either made true here or reported as unkept.
    ///
    /// The SDK's exit callback is the only positive proof, so a kill that
    /// cannot be observed is an error rather than an assumption.
    pub(crate) fn confirm_terminated(&self, logger: &mut Logger) -> Result<(), String> {
        if self.has_exited() {
            return Ok(());
        }
        let _ = writeln!(
            logger,
            "[WSLC] Container still live after the timeout stop request; escalating to SIGKILL"
        );
        // `0`: the graceful grace period already elapsed in `wait_for_process`.
        self.stop(WslcSignal::WSLC_SIGNAL_SIGKILL, 0)?;
        if !await_callbacks_quiesced(&self.io_ctx) {
            return Err(format!(
                "the WSL container did not report its process exiting within {}s of SIGKILL, so \
                 the timed-out process cannot be confirmed terminated",
                EXIT_CALLBACK_TIMEOUT.as_secs()
            ));
        }
        Ok(())
    }

    /// Signal the container's processes, for
    /// [`SandboxProcess::kill`](crate::mxc_common::sandbox_process::SandboxProcess::kill).
    /// `timeout_secs` is how long the SDK waits for a graceful stop.
    pub(crate) fn stop(&self, signal: WslcSignal, timeout_secs: u32) -> Result<(), String> {
        // SAFETY: as `destroy` — live container handle, live SDK.
        unsafe {
            stop_container(
                self.sdk,
                self.container_guard.as_raw(),
                signal,
                timeout_secs,
            )
        }
    }

    /// A handle that force-stops this container from another thread.
    ///
    /// # Safety
    /// The caller must not use the stopper once this container is dropped.
    unsafe fn stopper(&self) -> ContainerStopper {
        ContainerStopper {
            sdk: self.sdk,
            container: self.container_guard.as_raw(),
        }
    }

    /// Whether the SDK's exit callback has fired (the process is gone and all
    /// its output has been flushed).
    pub(crate) fn has_exited(&self) -> bool {
        *lock(&self.io_ctx.exited.0)
    }

    /// The init process's exit code. Only meaningful once
    /// [`has_exited`](Self::has_exited) is true.
    ///
    /// # Safety
    /// Requires a live process handle and SDK, which `self` owns.
    pub(crate) unsafe fn confirmed_exit_code(&self) -> Result<i32, WslcStepError> {
        let _com = ComApartment::enter().map_err(|e| WslcError::Host(e).into_step_error())?;
        let mut exit_code: i32 = -1;
        let hr = self.test_exit_code_result(
            true,
            self.sdk
                .WslcGetProcessExitCode(self.process_guard.as_raw(), &mut exit_code),
        );
        if hr != S_OK {
            return Err(sdk_wait_error("WslcGetProcessExitCode", hr, ""));
        }
        Ok(exit_code)
    }

    /// EOF any streaming reader the caller still holds.
    pub(crate) fn close_streams(&self) {
        self.io_ctx.close_streams();
    }
}

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

    #[test]
    fn run_rejects_unsupported_target_os_before_sdk_load() {
        let request = ExecutionRequest {
            containment: crate::mxc_common::models::ContainmentBackend::Wslc,
            script_code: "echo hi".to_string(),
            ..Default::default()
        };
        let config = WslcConfig {
            target_os: "windows".to_string(),
            ..WslcConfig::default()
        };
        let mut logger = Logger::new(crate::mxc_common::logger::Mode::Buffer);
        let mut runner = WSLContainerRunner::new(&config);

        let response = runner.execute(&request, &mut logger);

        assert_eq!(
            response.failure_phase,
            crate::mxc_common::models::FailurePhase::Rejected
        );
        assert!(response.error_message.contains("wslc.targetOs"));
        assert!(!logger.get_buffer().contains(START_CONTAINER_BANNER));
    }

    #[test]
    fn run_rejects_denied_path_overlap_before_sdk_load() {
        // Wiring guard: a deniedPaths entry nested under a mounted parent must be
        // rejected at the pre-flight overlap check (run_internal, before SDK
        // load), so no container is ever started. The pure-function unit tests
        // in policy_mapping do not cover this call-site ordering. Uses
        // non-existent paths so D6 (Absent) and delegation (unknown) pass through
        // to the overlap check.
        let request = ExecutionRequest {
            containment: crate::mxc_common::models::ContainmentBackend::Wslc,
            policy: crate::mxc_common::models::ContainerPolicy {
                readwrite_paths: vec![r"C:\mxc-nonexistent-parent".to_string()],
                denied_paths: vec![r"C:\mxc-nonexistent-parent\secrets".to_string()],
                ..Default::default()
            },
            script_code: "echo hi".to_string(),
            ..Default::default()
        };

        let mut logger = Logger::new(crate::mxc_common::logger::Mode::Buffer);
        let mut runner = WSLContainerRunner::new(&WslcConfig::default());
        let response = runner.execute(&request, &mut logger);

        assert_eq!(
            response.exit_code,
            crate::mxc_common::models::FailurePhase::Rejected.failure_exit_code(),
            "overlap must fail the run"
        );
        assert_eq!(
            response.failure_phase,
            crate::mxc_common::models::FailurePhase::Rejected
        );
        assert!(
            response.error_message.contains("cannot be enforced"),
            "expected the overlap error, got: {}",
            response.error_message
        );
    }

    #[test]
    fn run_rejects_denied_alias_via_junction() {
        // Tier-2 wiring guard: a deniedPaths entry that only lands inside a
        // mounted parent AFTER junction resolution must still be rejected at the
        // pre-flight overlap check. Tier 1 (lexical) cannot see this alias; tier
        // 2 canonicalizes on disk. Uses a real directory junction (no admin).
        use std::process::Command;

        let tmp = tempfile::TempDir::new().unwrap();
        let real = tmp.path().join("real");
        let secret = real.join("secret");
        std::fs::create_dir_all(&secret).unwrap();
        let link = tmp.path().join("link");

        let status = Command::new("cmd")
            .args(["/c", "mklink", "/J"])
            .arg(&link)
            .arg(&real)
            .status()
            .unwrap();
        if !status.success() {
            eprintln!("skipping run_rejects_denied_alias_via_junction: mklink /J failed");
            return;
        }

        let request = ExecutionRequest {
            containment: crate::mxc_common::models::ContainmentBackend::Wslc,
            policy: crate::mxc_common::models::ContainerPolicy {
                readwrite_paths: vec![real.to_string_lossy().into_owned()],
                denied_paths: vec![link.join("secret").to_string_lossy().into_owned()],
                ..Default::default()
            },
            script_code: "echo hi".to_string(),
            ..Default::default()
        };

        let mut logger = Logger::new(crate::mxc_common::logger::Mode::Buffer);
        let mut runner = WSLContainerRunner::new(&WslcConfig::default());
        let response = runner.execute(&request, &mut logger);

        assert_eq!(
            response.exit_code,
            crate::mxc_common::models::FailurePhase::Rejected.failure_exit_code(),
            "junction-aliased deny must fail the run"
        );
        assert_eq!(
            response.failure_phase,
            crate::mxc_common::models::FailurePhase::Rejected
        );
        assert!(
            response.error_message.contains("cannot be enforced"),
            "expected the overlap error, got: {}",
            response.error_message
        );
    }

    #[test]
    fn run_rejects_absent_denied_leaf_via_junction() {
        // Finding B: a not-yet-created deny under a junctioned mount. The leaf
        // does not exist, so tier 2 must resolve the deepest existing ancestor
        // (the junction) and re-append the missing tail before comparing.
        use std::process::Command;

        let tmp = tempfile::TempDir::new().unwrap();
        let real = tmp.path().join("real");
        std::fs::create_dir_all(&real).unwrap();
        let link = tmp.path().join("link");

        let status = Command::new("cmd")
            .args(["/c", "mklink", "/J"])
            .arg(&link)
            .arg(&real)
            .status()
            .unwrap();
        if !status.success() {
            eprintln!("skipping run_rejects_absent_denied_leaf_via_junction: mklink /J failed");
            return;
        }

        let request = ExecutionRequest {
            containment: crate::mxc_common::models::ContainmentBackend::Wslc,
            policy: crate::mxc_common::models::ContainerPolicy {
                readwrite_paths: vec![real.to_string_lossy().into_owned()],
                // `real\newsecret` never created — only reachable via the junction.
                denied_paths: vec![link.join("newsecret").to_string_lossy().into_owned()],
                ..Default::default()
            },
            script_code: "echo hi".to_string(),
            ..Default::default()
        };

        let mut logger = Logger::new(crate::mxc_common::logger::Mode::Buffer);
        let mut runner = WSLContainerRunner::new(&WslcConfig::default());
        let response = runner.execute(&request, &mut logger);

        assert_eq!(
            response.exit_code,
            crate::mxc_common::models::FailurePhase::Rejected.failure_exit_code(),
            "absent junction-aliased deny must fail the run"
        );
        assert_eq!(
            response.failure_phase,
            crate::mxc_common::models::FailurePhase::Rejected
        );
        assert!(
            response.error_message.contains("cannot be enforced"),
            "expected the overlap error, got: {}",
            response.error_message
        );
    }

    #[test]
    fn validate_runner_tags_shared_validator_rejections() {
        // The shared network validator builds untagged responses; WSLc retags them
        // so callers get `policy_validation` rather than an opaque backend error.
        let mut request = ExecutionRequest {
            containment: crate::mxc_common::models::ContainmentBackend::Wslc,
            ..Default::default()
        };
        request.policy.allowed_proxy_peer = Some("Contoso.Proxy_123".to_string());
        let runner = WSLContainerRunner::new(&WslcConfig::default());
        let err = runner.validate_runner(&request).unwrap_err();
        assert!(err.error_message.contains("allowedProxyPeer"));
        assert_eq!(
            err.failure_phase,
            crate::mxc_common::models::FailurePhase::Rejected
        );
    }

    #[test]
    fn validate_runner_rejects_more_processors_than_the_host_has() {
        let impossible = u32::from(u16::MAX);
        let runner = WSLContainerRunner::new(&WslcConfig {
            cpu_count: Some(impossible),
            ..WslcConfig::default()
        });
        let request = ExecutionRequest {
            containment: crate::mxc_common::models::ContainmentBackend::Wslc,
            ..Default::default()
        };

        let refused = runner
            .validate_runner(&request)
            .expect_err("more processors than any host has must be refused");

        assert_eq!(
            refused.failure_phase,
            crate::mxc_common::models::FailurePhase::Rejected
        );
        assert!(
            refused.error_message.contains("cpu_count"),
            "the refusal must name the processor count: {}",
            refused.error_message
        );
    }

    /// `memory_mb` is a ceiling the host backs on demand, not a reservation.
    #[test]
    fn validate_runner_accepts_memory_past_what_the_host_has_installed() {
        let runner = WSLContainerRunner::new(&WslcConfig {
            memory_mb: Some(1024 * 1024),
            ..WslcConfig::default()
        });
        let request = ExecutionRequest {
            containment: crate::mxc_common::models::ContainmentBackend::Wslc,
            ..Default::default()
        };

        assert!(
            runner.validate_runner(&request).is_ok(),
            "a 1 TB ceiling is not a 1 TB reservation; refusing it would refuse \
             a configuration that demonstrably runs"
        );
    }

    #[test]
    fn validate_runner_accepts_bare_defaults() {
        // Both supported all-or-nothing postures are enforceable.
        for action in [
            crate::mxc_common::models::NetworkAction::Allow,
            crate::mxc_common::models::NetworkAction::Deny,
        ] {
            let request = ExecutionRequest {
                containment: crate::mxc_common::models::ContainmentBackend::Wslc,
                policy: crate::mxc_common::models::ContainerPolicy {
                    network_egress: Some(crate::mxc_common::models::NetworkEgressPolicy {
                        default: action,
                        ..Default::default()
                    }),
                    network_ingress: Some(crate::mxc_common::models::NetworkIngressPolicy {
                        default: action,
                        host_loopback: action,
                    }),
                    ..Default::default()
                },
                ..Default::default()
            };
            let runner = WSLContainerRunner::new(&WslcConfig::default());
            assert!(runner.validate_runner(&request).is_ok());
        }
    }

    #[test]
    fn validate_runner_accepts_linux_target_os() {
        let request = ExecutionRequest {
            containment: crate::mxc_common::models::ContainmentBackend::Wslc,
            ..Default::default()
        };
        let runner = WSLContainerRunner::new(&WslcConfig {
            target_os: "linux".to_string(),
            ..WslcConfig::default()
        });

        assert!(runner.validate_runner(&request).is_ok());
    }

    #[test]
    fn validate_runner_rejects_unsupported_target_os() {
        let request = ExecutionRequest {
            containment: crate::mxc_common::models::ContainmentBackend::Wslc,
            ..Default::default()
        };

        for target_os in ["windows", "", "Linux", "linx"] {
            let runner = WSLContainerRunner::new(&WslcConfig {
                target_os: target_os.to_string(),
                ..WslcConfig::default()
            });
            let response = runner
                .validate_runner(&request)
                .expect_err("non-Linux target OS must be rejected");

            assert_eq!(
                response.failure_phase,
                crate::mxc_common::models::FailurePhase::Rejected
            );
            assert!(response.error_message.contains("wslc.targetOs"));
            assert!(
                response.error_message.contains(&format!("{target_os:?}")),
                "the rejection must name {target_os:?}: {}",
                response.error_message
            );
        }
    }

    #[test]
    fn validate_runner_rejects_supplied_ui() {
        let request = ExecutionRequest {
            containment: crate::mxc_common::models::ContainmentBackend::Wslc,
            policy: crate::mxc_common::models::ContainerPolicy {
                ui: crate::mxc_common::models::UiPolicy::default(),
                ui_specified: true,
                ..Default::default()
            },
            ..Default::default()
        };
        let runner = WSLContainerRunner::new(&WslcConfig::default());
        let err = runner.validate_runner(&request).unwrap_err();
        assert!(
            err.error_message.contains("ui section is not supported"),
            "got: {}",
            err.error_message
        );
        assert_eq!(
            err.failure_phase,
            crate::mxc_common::models::FailurePhase::Rejected
        );
    }

    #[test]
    fn validate_runner_accepts_absent_ui() {
        let request = ExecutionRequest {
            containment: crate::mxc_common::models::ContainmentBackend::Wslc,
            ..Default::default()
        };
        assert!(!request.policy.ui_specified);
        let runner = WSLContainerRunner::new(&WslcConfig::default());
        assert!(runner.validate_runner(&request).is_ok());
    }

    #[test]
    fn one_shot_proxies_port_mappings_under_isolated_networking() {
        let config = WslcConfig {
            port_mappings: vec![crate::mxc_common::models::PortMapping {
                windows_port: 8080,
                container_port: 80,
                protocol: "tcp".to_string(),
            }],
            ..Default::default()
        };
        let request = ExecutionRequest {
            containment: crate::mxc_common::models::ContainmentBackend::Wslc,
            ..Default::default()
        };

        let runner = WSLContainerRunner::new(&config);
        runner.validate_runner(&request).unwrap();
        assert!(matches!(
            runner.network_mode(&request).unwrap(),
            policy::NetworkMode::Proxied(_)
        ));
    }

    #[test]
    fn one_shot_accepts_port_mappings_under_bridged_networking() {
        let config = WslcConfig {
            port_mappings: vec![crate::mxc_common::models::PortMapping {
                windows_port: 8080,
                container_port: 80,
                protocol: "tcp".to_string(),
            }],
            ..Default::default()
        };
        let request = ExecutionRequest {
            containment: crate::mxc_common::models::ContainmentBackend::Wslc,
            policy: crate::mxc_common::models::ContainerPolicy {
                network_egress: Some(crate::mxc_common::models::NetworkEgressPolicy {
                    default: crate::mxc_common::models::NetworkAction::Allow,
                    ..Default::default()
                }),
                network_ingress: Some(crate::mxc_common::models::NetworkIngressPolicy {
                    default: crate::mxc_common::models::NetworkAction::Allow,
                    host_loopback: crate::mxc_common::models::NetworkAction::Allow,
                }),
                ..Default::default()
            },
            ..Default::default()
        };

        assert!(WSLContainerRunner::new(&config)
            .validate_runner(&request)
            .is_ok());
    }

    /// `destroyOnExit: true` matches what one-shot does; `false` and
    /// `preservePolicy: true` do not. The accepted value is the near-miss a
    /// blanket `lifecycle` rejection would swallow.
    #[test]
    fn validate_runner_rejects_the_lifecycle_settings_one_shot_cannot_honour() {
        let runner = WSLContainerRunner::new(&WslcConfig::default());

        let accepted = ExecutionRequest {
            containment: crate::mxc_common::models::ContainmentBackend::Wslc,
            lifecycle: crate::mxc_common::models::LifecycleConfig {
                destroy_on_exit: true,
                preserve_policy: false,
            },
            ..Default::default()
        };
        assert!(
            runner.validate_runner(&accepted).is_ok(),
            "destroyOnExit=true is what one-shot does and must stay accepted"
        );

        for (lifecycle, needle) in [
            (
                crate::mxc_common::models::LifecycleConfig {
                    destroy_on_exit: false,
                    preserve_policy: false,
                },
                "destroyOnExit=false",
            ),
            (
                crate::mxc_common::models::LifecycleConfig {
                    destroy_on_exit: true,
                    preserve_policy: true,
                },
                "preservePolicy",
            ),
        ] {
            let request = ExecutionRequest {
                containment: crate::mxc_common::models::ContainmentBackend::Wslc,
                lifecycle,
                ..Default::default()
            };
            let err = runner.validate_runner(&request).unwrap_err();
            assert!(
                err.error_message.contains(needle),
                "expected {needle}; got: {}",
                err.error_message
            );
            assert_eq!(
                err.failure_phase,
                crate::mxc_common::models::FailurePhase::Rejected
            );
        }
    }

    fn request_with_container_id(container_id: &str) -> ExecutionRequest {
        ExecutionRequest {
            containment: crate::mxc_common::models::ContainmentBackend::Wslc,
            script_code: "echo hi".to_string(),
            container_id: container_id.to_string(),
            ..Default::default()
        }
    }

    /// An embedded NUL must fail at `validate_runner`, not only inside
    /// `create_session`. Session-name conversion truncates at the first NUL,
    /// so the check has to run before a dry-run can report success.
    #[test]
    fn validate_runner_rejects_embedded_nul_container_id() {
        let runner = WSLContainerRunner::new(&WslcConfig::default());
        assert!(
            runner
                .validate_runner(&request_with_container_id("alpha"))
                .is_ok(),
            "a containerId without a NUL must stay accepted"
        );

        let err = runner
            .validate_runner(&request_with_container_id("alpha\0evil"))
            .expect_err("an embedded NUL must be rejected");
        assert!(
            err.error_message
                .contains("containerId must not contain null bytes"),
            "got: {}",
            err.error_message
        );
        assert!(
            !err.error_message.contains("alpha"),
            "the raw id must not be echoed: {}",
            err.error_message
        );
        assert_eq!(
            err.failure_phase,
            crate::mxc_common::models::FailurePhase::Rejected
        );
    }

    /// Dry-run returns success as soon as `validate_runner` passes, so a NUL
    /// id must fail there rather than look like a validated request.
    #[test]
    fn dry_run_rejects_embedded_nul_container_id_before_container_start() {
        let mut clean = request_with_container_id("alpha");
        clean.dry_run = true;
        let mut clean_logger = Logger::new(Mode::Buffer);
        let mut runner = WSLContainerRunner::new(&WslcConfig::default());
        let clean_response = ScriptRunner::run(&mut runner, &clean, &mut clean_logger);
        assert_eq!(clean_response.exit_code, 0);
        assert!(
            !clean_logger.get_buffer().contains(START_CONTAINER_BANNER),
            "a passing dry-run must not start a container; logger: {}",
            clean_logger.get_buffer()
        );

        let mut request = request_with_container_id("alpha\0evil");
        request.dry_run = true;
        let mut logger = Logger::new(Mode::Buffer);
        let response = ScriptRunner::run(&mut runner, &request, &mut logger);
        // Follow the shared refusal exit code: -1 on this branch, 1 after the
        // CI merge picks up main's `Rejected` phase mapping.
        assert_eq!(
            response.exit_code,
            WslcError::Rejected(String::new()).into_response().exit_code
        );
        assert!(
            response
                .error_message
                .contains("containerId must not contain null bytes"),
            "got: {}",
            response.error_message
        );
        assert_eq!(
            response.failure_phase,
            crate::mxc_common::models::FailurePhase::Rejected
        );
        assert!(
            !logger.get_buffer().contains(START_CONTAINER_BANNER),
            "dry-run must reject before `start_container`; logger: {}",
            logger.get_buffer()
        );
    }

    /// A rejection must abort the request rather than tear a container down
    /// after building one. `SandboxBackend::spawn`'s half is in `sandbox.rs`.
    #[test]
    fn validate_runner_rejects_before_any_container_work() {
        let request = ExecutionRequest {
            containment: crate::mxc_common::models::ContainmentBackend::Wslc,
            script_code: "echo hi".to_string(),
            policy: crate::mxc_common::models::ContainerPolicy {
                ui_specified: true,
                ..Default::default()
            },
            ..Default::default()
        };
        let runner = WSLContainerRunner::new(&WslcConfig::default());
        let err = runner.validate_runner(&request).unwrap_err();
        assert_eq!(
            err.failure_phase,
            crate::mxc_common::models::FailurePhase::Rejected,
            "a policy refusal is a rejection, not a runtime failure"
        );
    }

    fn request_with_cwd(cwd: &str) -> ExecutionRequest {
        ExecutionRequest {
            containment: crate::mxc_common::models::ContainmentBackend::Wslc,
            script_code: "pwd".to_string(),
            working_directory: cwd.to_string(),
            ..Default::default()
        }
    }

    /// Regression for #902: a cwd that cannot be mapped under `/mnt/<drive>`
    /// used to be dropped silently, running the workload in the container's
    /// default directory. It must now fail the launch and name the value.
    #[test]
    fn validate_runner_rejects_unmappable_working_directory() {
        let runner = WSLContainerRunner::new(&WslcConfig::default());
        for cwd in ["/workspace", "sub", "C:work", r"\\server\share"] {
            let err = runner
                .validate_runner(&request_with_cwd(cwd))
                .expect_err("an unmappable cwd must be rejected");
            assert_eq!(
                err.failure_phase,
                crate::mxc_common::models::FailurePhase::Rejected,
                "cwd {cwd:?}"
            );
            assert!(
                err.error_message.contains(&format!("{cwd:?}")),
                "the error must name the value {cwd:?}: {}",
                err.error_message
            );
        }
    }

    #[test]
    fn validate_runner_accepts_mappable_or_omitted_working_directory() {
        let runner = WSLContainerRunner::new(&WslcConfig::default());
        for cwd in [r"C:\work", "C:/work", "", "   "] {
            assert!(
                runner.validate_runner(&request_with_cwd(cwd)).is_ok(),
                "cwd {cwd:?} must be accepted"
            );
        }
    }

    // -- Host-stdio forwarding (`StdioMode::Inherit`) --------------------

    /// The regression this whole indirection exists for: the SDK's callback
    /// thread must not do the host's blocking I/O, because that same thread
    /// delivers the process-exit callback teardown waits on.
    ///
    /// The sink here never returns, standing in for a host that has stopped
    /// draining its stdout. Writing through it from the callback path — which
    /// is what `IoSink::Inherit` used to do — would park this test.
    #[test]
    fn callback_writes_do_not_block_on_a_stalled_host_sink() {
        let (writer, mut reader) = stream_pair();
        let sink = IoSink::Stream(writer);

        let released = Arc::new((Mutex::new(false), Condvar::new()));
        let pump_gate = Arc::clone(&released);
        let pump_thread = std::thread::spawn(move || {
            pump(&mut reader, |_| {
                // Blocks exactly like a write to a full host pipe.
                let (mutex, cvar) = &*pump_gate;
                let mut done = mutex.lock().unwrap();
                while !*done {
                    done = cvar.wait(done).unwrap();
                }
                Ok(())
            })
        });

        let start = std::time::Instant::now();
        for _ in 0..64 {
            sink.write(&[b'x'; 64 * 1024]);
        }
        sink.close();
        let elapsed = start.elapsed();

        // Let the pump go so the test doesn't leak a parked thread.
        {
            let (mutex, cvar) = &*released;
            *mutex.lock().unwrap() = true;
            cvar.notify_all();
        }
        pump_thread.join().expect("pump thread");

        assert!(
            elapsed < std::time::Duration::from_secs(5),
            "callback-path writes must not block on a stalled host sink, took {elapsed:?}"
        );
    }

    #[test]
    fn pump_forwards_every_chunk_then_ends_at_eof() {
        let (writer, mut reader) = stream_pair();
        writer.write(b"first ");
        writer.write(b"second");
        writer.close();

        let mut seen = Vec::new();
        pump(&mut reader, |bytes| {
            seen.extend_from_slice(bytes);
            Ok(())
        });

        assert_eq!(seen, b"first second", "pump must forward the whole stream");
    }

    /// A host stream that has gone away (a closed pipe) cannot recover, so the
    /// pump must give up rather than spin on a stream that is still open.
    #[test]
    fn pump_stops_when_the_host_sink_errors() {
        let (writer, mut reader) = stream_pair();
        writer.write(b"delivered");
        writer.write(b"dropped");
        // Deliberately left open: only the sink error may end the pump.

        let mut writes = 0usize;
        pump(&mut reader, |_| {
            writes += 1;
            Err(std::io::Error::other("host stream closed"))
        });

        assert_eq!(writes, 1, "pump must stop at the first sink error");
    }

    /// `Inherit` must not hand read ends to the caller (they belong to the
    /// pumps), and `Pipes` must not spawn pumps (the caller drains those).
    #[test]
    fn io_wiring_matches_the_output_mode() {
        let (_ctx, capture) = IoContext::new(OutputMode::Capture);
        assert!(capture.pipes.is_none(), "capture has no caller pipes");
        assert!(capture.pumps.is_empty(), "capture has no host pumps");

        let (ctx, inherit) = IoContext::new(OutputMode::Stream(StdioMode::Inherit));
        assert!(inherit.pipes.is_none(), "inherit keeps its readers");
        assert_eq!(inherit.pumps.len(), 2, "inherit pumps stdout and stderr");
        // Close so the pumps end, then join them rather than leaking threads.
        ctx.close_streams();
        for pump in inherit.pumps {
            pump.join().expect("inherit pump");
        }

        let (_ctx, pipes) = IoContext::new(OutputMode::Stream(StdioMode::Pipes));
        assert!(pipes.pipes.is_some(), "pipes hands the caller its readers");
        assert!(pipes.pumps.is_empty(), "pipes has no host pumps");
    }

    // -- Host stdin forwarding --------------------------------------------

    struct BrokenInput;

    impl Read for BrokenInput {
        fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
            Err(std::io::Error::other("input broke"))
        }
    }

    struct ClosedPipe;

    impl std::io::Write for ClosedPipe {
        fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
            Err(std::io::ErrorKind::BrokenPipe.into())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    struct FailingPipe;

    impl std::io::Write for FailingPipe {
        fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
            Err(std::io::Error::other("pipe broke"))
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn forwarding_copies_every_byte_value() {
        let input: Vec<u8> = (0..=255u8).cycle().take(300_000).collect();
        let mut forwarded = Vec::new();

        forward_stdin(&mut input.as_slice(), &mut forwarded).unwrap();

        assert_eq!(forwarded, input);
    }

    #[test]
    fn a_command_that_stops_reading_stdin_is_not_a_forwarding_failure() {
        forward_stdin(&mut &b"nobody reads this"[..], &mut ClosedPipe)
            .expect("a closed stdin pipe just ends forwarding");
    }

    #[test]
    fn a_failed_write_to_the_container_is_a_forwarding_failure() {
        let error = forward_stdin(&mut &b"truncated"[..], &mut FailingPipe).unwrap_err();

        assert!(
            error.to_string().contains("writing the container's stdin")
                && error.to_string().contains("pipe broke"),
            "{error}"
        );
    }

    fn local_pipe() -> (std::fs::File, std::fs::File) {
        let (reader, writer) = crate::mxc_common::process_util::create_local_pipe().unwrap();
        (
            std::fs::File::from(reader.try_into_std_owned_handle().unwrap()),
            std::fs::File::from(writer.try_into_std_owned_handle().unwrap()),
        )
    }

    fn read_to_end_in_background(
        mut reader: std::fs::File,
    ) -> std::sync::mpsc::Receiver<std::io::Result<Vec<u8>>> {
        let (read_tx, read_rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let mut received = Vec::new();
            let _ = read_tx.send(reader.read_to_end(&mut received).map(|_| received));
        });
        read_rx
    }

    fn assert_still_open(read: &std::sync::mpsc::Receiver<std::io::Result<Vec<u8>>>) {
        assert!(
            read.recv_timeout(std::time::Duration::from_millis(300))
                .is_err(),
            "the command saw end-of-file before teardown"
        );
    }

    fn assert_closed(read: &std::sync::mpsc::Receiver<std::io::Result<Vec<u8>>>) {
        let received = read
            .recv_timeout(std::time::Duration::from_secs(5))
            .expect("the command never saw end-of-file")
            .unwrap();
        assert!(received.is_empty());
    }

    struct FailsWhenTold(std::sync::mpsc::Receiver<()>);

    impl Read for FailsWhenTold {
        fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
            let _ = self.0.recv();
            Err(std::io::Error::other("input broke"))
        }
    }

    #[test]
    fn a_host_stdin_read_failure_stops_the_run_then_closes_the_pipe() {
        let (reader, writer) = local_pipe();
        let stopped = Arc::new(AtomicBool::new(false));
        let stop = Arc::clone(&stopped);

        let forwarding = HostStdinForwarding::start(BrokenInput, writer, move || {
            stop.store(true, Ordering::SeqCst);
            true
        })
        .map_err(|(error, _)| error)
        .unwrap();

        assert_closed(&read_to_end_in_background(reader));
        assert!(stopped.load(Ordering::SeqCst), "the run was not stopped");
        assert_eq!(
            forwarding.end_run(true).as_deref(),
            Some("reading host stdin: input broke")
        );
    }

    #[test]
    fn an_unconfirmed_stop_wakes_a_wait_without_timeout_and_keeps_stdin_open_until_teardown() {
        use std::os::windows::io::AsRawHandle;

        let (reader, writer) = local_pipe();
        let never_exits = manual_reset_event().unwrap();
        let (forwarding, abort) = forward_with_abort(BrokenInput, writer, || false)
            .map_err(|(error, _)| error)
            .unwrap();
        let (woke_tx, woke_rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            // SAFETY: both handles are live events owned by this thread.
            let woke = unsafe {
                wait_for_exit_or_abort(never_exits.as_raw_handle(), abort.as_raw_handle(), u32::MAX)
            };
            let _ = woke_tx.send(woke);
        });

        let woke = woke_rx
            .recv_timeout(std::time::Duration::from_secs(5))
            .expect("the wait was not woken");
        assert_eq!(woke, Ok(ExitWait::Aborted));
        let read = read_to_end_in_background(reader);
        assert_still_open(&read);
        assert_eq!(
            forwarding.end_run(false).as_deref(),
            Some("reading host stdin: input broke")
        );
        assert_still_open(&read);
        forwarding.finish_teardown();
        assert_closed(&read);
    }

    #[test]
    fn a_confirmed_stop_closes_stdin_without_waking_the_wait() {
        use std::os::windows::io::AsRawHandle;

        let (reader, writer) = local_pipe();
        let never_exits = manual_reset_event().unwrap();
        let (_forwarding, abort) = forward_with_abort(BrokenInput, writer, || true)
            .map_err(|(error, _)| error)
            .unwrap();

        assert_closed(&read_to_end_in_background(reader));
        // SAFETY: both handles are live events owned by this test.
        let woke = unsafe {
            wait_for_exit_or_abort(never_exits.as_raw_handle(), abort.as_raw_handle(), 0)
        };
        assert_eq!(woke, Ok(ExitWait::TimedOut));
    }

    #[test]
    fn a_wait_reports_whichever_event_signals() {
        use std::os::windows::io::AsRawHandle;

        let set = |event: &std::os::windows::io::OwnedHandle| {
            // SAFETY: `event` is a live event handle.
            unsafe {
                windows::Win32::System::Threading::SetEvent(windows::Win32::Foundation::HANDLE(
                    event.as_raw_handle(),
                ))
            }
            .unwrap();
        };
        let wait = |exit: &std::os::windows::io::OwnedHandle, abort: HANDLE| {
            // SAFETY: both handles are live events or null.
            unsafe { wait_for_exit_or_abort(exit.as_raw_handle(), abort, 0) }.unwrap()
        };
        let exit = manual_reset_event().unwrap();
        let abort = manual_reset_event().unwrap();

        assert_eq!(wait(&exit, abort.as_raw_handle()), ExitWait::TimedOut);
        set(&abort);
        assert_eq!(wait(&exit, abort.as_raw_handle()), ExitWait::Aborted);
        assert_eq!(wait(&exit, ptr::null_mut()), ExitWait::TimedOut);
        set(&exit);
        assert_eq!(wait(&exit, abort.as_raw_handle()), ExitWait::Exited);
    }

    #[test]
    fn a_host_stdin_failure_after_a_confirmed_run_is_ignored() {
        let (reader, writer) = local_pipe();
        let (fail, told) = std::sync::mpsc::channel();
        let stopped = Arc::new(AtomicBool::new(false));
        let stop = Arc::clone(&stopped);

        let forwarding = HostStdinForwarding::start(FailsWhenTold(told), writer, move || {
            stop.store(true, Ordering::SeqCst);
            true
        })
        .map_err(|(error, _)| error)
        .unwrap();
        assert_eq!(forwarding.end_run(true), None);
        fail.send(()).unwrap();

        assert_closed(&read_to_end_in_background(reader));
        assert!(
            !stopped.load(Ordering::SeqCst),
            "a finished run was stopped"
        );
        assert_eq!(forwarding.end_run(true), None);
    }

    #[test]
    fn a_host_stdin_failure_after_an_unconfirmed_run_keeps_stdin_open_until_teardown() {
        let (reader, writer) = local_pipe();
        let (fail, told) = std::sync::mpsc::channel();

        let forwarding = HostStdinForwarding::start(FailsWhenTold(told), writer, || {
            panic!("a finished run was stopped")
        })
        .map_err(|(error, _)| error)
        .unwrap();
        assert_eq!(forwarding.end_run(false), None);
        fail.send(()).unwrap();

        let read = read_to_end_in_background(reader);
        assert_still_open(&read);
        forwarding.finish_teardown();
        assert_closed(&read);
    }

    #[test]
    fn a_run_whose_stdin_was_cut_short_is_reported_as_failed_with_its_output() {
        let completed = ScriptResponse {
            exit_code: 0,
            standard_out: "partial result".to_string(),
            ..Default::default()
        };

        let response = stdin_forwarding_failed(completed, "input broke");

        assert_eq!(response.exit_code, -1);
        assert_eq!(
            response.failure_phase,
            crate::mxc_common::models::FailurePhase::PostLaunchFailed
        );
        assert!(
            response.error_message.contains("input broke"),
            "{}",
            response.error_message
        );
        assert_eq!(response.standard_out, "partial result");
    }

    // -- Timeout reporting ------------------------------------------------

    /// The run-to-completion path must not claim a termination the SDK never
    /// confirmed: a stop is only a request, so an unconfirmed timeout leaves
    /// sandboxed code possibly still running and the message has to say so.
    #[test]
    fn an_unconfirmed_timeout_does_not_claim_the_process_was_terminated() {
        let (ctx, _) = IoContext::new(OutputMode::Capture);
        let mut logger = Logger::new(Mode::Buffer);

        let confirmed = WSLContainerRunner::collect_output(
            &ctx,
            0,
            WaitOutcome::TimedOutTerminated,
            1500,
            &mut logger,
        );
        let unconfirmed = WSLContainerRunner::collect_output(
            &ctx,
            0,
            WaitOutcome::TimedOutUnconfirmed,
            1500,
            &mut logger,
        );

        assert!(confirmed.error_message.contains("was terminated"));
        assert!(
            !unconfirmed.error_message.contains("was terminated"),
            "an unconfirmed timeout must not claim a termination, got: {}",
            unconfirmed.error_message
        );
        assert!(
            unconfirmed.error_message.contains("may still be running"),
            "an unconfirmed timeout must say the container may still be running, got: {}",
            unconfirmed.error_message
        );
        // Both are still timeouts, so both fail the run.
        assert_eq!(confirmed.exit_code, -1);
        assert_eq!(unconfirmed.exit_code, -1);
    }

    #[test]
    fn a_normal_exit_reports_its_code_and_no_error() {
        let (ctx, _) = IoContext::new(OutputMode::Capture);
        let mut logger = Logger::new(Mode::Buffer);

        let response =
            WSLContainerRunner::collect_output(&ctx, 42, WaitOutcome::Exited, 1500, &mut logger);

        assert_eq!(response.exit_code, 42);
        assert!(response.error_message.is_empty());
        assert!(!WaitOutcome::Exited.timed_out());
        assert!(WaitOutcome::TimedOutTerminated.timed_out());
        assert!(WaitOutcome::TimedOutUnconfirmed.timed_out());
        assert!(!WaitOutcome::Aborted { confirmed: true }.timed_out());
        assert!(WaitOutcome::Aborted { confirmed: true }.confirmed_gone());
        assert!(!WaitOutcome::Aborted { confirmed: false }.confirmed_gone());
        assert!(!WaitOutcome::TimedOutUnconfirmed.confirmed_gone());
    }

    /// `Capture` keeps the bytes for the `ScriptResponse`; the streaming sink
    /// must report none, since the caller (or a pump) consumed them live.
    #[test]
    fn only_the_capture_sink_reports_captured_bytes() {
        let buffer = IoSink::Buffer(Mutex::new(Vec::new()));
        buffer.write(b"captured");
        assert_eq!(buffer.captured(), "captured");

        let (writer, _reader) = stream_pair();
        let stream = IoSink::Stream(writer);
        stream.write(b"streamed");
        assert_eq!(stream.captured(), "", "streamed bytes are not re-reported");
    }

    #[test]
    fn prerequisite_error_for_wsl_package_missing() {
        let message =
            sdk_init::prerequisite_error(WslcComponentFlags::WSLC_COMPONENT_FLAG_WSL_PACKAGE);

        assert!(message.contains("WslPackage"));
        assert!(message.contains("3.0.5"));
        assert!(message.contains("wsl --update"));
        assert!(!message.contains("--pre-release"));
        assert!(!message.contains("Virtual Machine Platform"));
    }

    #[test]
    fn prerequisite_error_for_virtual_machine_platform_missing() {
        let message = sdk_init::prerequisite_error(
            WslcComponentFlags::WSLC_COMPONENT_FLAG_VIRTUAL_MACHINE_PLATFORM,
        );

        assert!(message.contains("VirtualMachinePlatform"));
        assert!(message.contains("Virtual Machine Platform"));
        assert!(!message.contains("wsl --update"));
    }

    #[test]
    fn prerequisite_error_for_combined_missing_components() {
        let combined = WslcComponentFlags::WSLC_COMPONENT_FLAG_VIRTUAL_MACHINE_PLATFORM
            | WslcComponentFlags::WSLC_COMPONENT_FLAG_WSL_PACKAGE;
        let message = sdk_init::prerequisite_error(combined);

        assert!(message.contains("VirtualMachinePlatform"));
        assert!(message.contains("WslPackage"));
        assert!(message.contains("wsl --update"));
        assert!(message.contains("Virtual Machine Platform"));
    }

    #[test]
    fn prerequisite_error_for_sdk_needs_update() {
        let message =
            sdk_init::prerequisite_error(WslcComponentFlags::WSLC_COMPONENT_FLAG_SDK_NEEDS_UPDATE);

        assert_eq!(
            message,
            "WSLC runtime unavailable. Missing components: SdkNeedsUpdate (0x4). \
             Please update MXC — the WSLc SDK it ships is too old for your installed \
             version of WSL."
        );
        assert!(message.contains("SdkNeedsUpdate"));
        assert!(message.contains("update MXC"));
        // The user's WSL is fine (and newer) — no install/update advice for it.
        assert!(!message.contains("ensure WSL2 and the WSLC SDK are installed"));
        assert!(!message.contains("wsl --update"));
        assert!(!message.contains("Virtual Machine Platform"));
    }

    #[test]
    fn prerequisite_error_for_sdk_update_combined_with_another_component() {
        let combined = WslcComponentFlags::WSLC_COMPONENT_FLAG_SDK_NEEDS_UPDATE
            | WslcComponentFlags::WSLC_COMPONENT_FLAG_VIRTUAL_MACHINE_PLATFORM;
        let message = sdk_init::prerequisite_error(combined);

        assert!(message.contains("update MXC"));
        assert!(message.contains("Virtual Machine Platform"));
        assert!(!message.contains("ensure WSL2 and the WSLC SDK are installed"));
    }

    #[test]
    fn prerequisite_error_falls_back_for_unrecognized_components() {
        // An unknown future bit still has to produce actionable text.
        let message = sdk_init::prerequisite_error(WslcComponentFlags(0x8000));

        assert!(message.contains("ensure WSL2 and the WSLC SDK are installed"));
    }

    #[test]
    fn session_name_is_the_container_id_when_the_request_names_one() {
        assert_eq!(resolve_session_name("pitest"), "pitest");
        assert_eq!(resolve_session_name("wslc-hello-world"), "wslc-hello-world");
    }

    #[test]
    fn absent_container_id_mints_a_session_name() {
        let name = resolve_session_name("");

        assert!(
            name.starts_with(GENERATED_SESSION_NAME_PREFIX),
            "expected a minted name, got: {name}"
        );
        assert!(
            name.len() > GENERATED_SESSION_NAME_PREFIX.len(),
            "an empty name is what WSLc refuses with WSLC_E_INVALID_SESSION_NAME, got: {name}"
        );
    }

    #[test]
    fn minted_session_names_do_not_repeat() {
        assert_ne!(resolve_session_name(""), resolve_session_name(""));
    }
}