mxc-sdk 1.1.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! State-aware dispatcher: consumes a checked backend-bound operation and runs
//! the backend's `StatefulSandboxBackend` per-phase typed flow. Typed SDK calls
//! retain backend-native results; raw/executor calls encode those results as a
//! JSON response envelope. Exec streams output live and returns an exit code.
//!
//! `mxc_engine` resolves the backend and applies execution gates before checked
//! binding. The local `run_state_aware` is its fallback for backends without a
//! state-aware implementation and surfaces `unsupported_phase`.
//!
//! `dispatch_state_aware_typed<B>` is the per-backend phase router, generic over
//! the `StatefulSandboxBackend` impl. `dispatch_state_aware<B>` wraps its result
//! in a wire response envelope for raw callers.

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use serde::Serialize;
use serde_json::Value;

use crate::mxc_common::exec_stream::wrap_read_checked;
use crate::mxc_common::id::parse_sandbox_id_prefix;
use crate::mxc_common::models::ContainmentBackend;
use crate::mxc_common::mxc_error::{MxcError, ResponseEnvelope};
use crate::mxc_common::sandbox_process::{PtySize, SandboxProcess};
use crate::mxc_common::state_aware_backend::{
    DeprovisionResult, ExecHandle, ExecOutcome, ExecStdio, ProvisionResult, ProvisionSessionResult,
    StartResult, StatefulSandboxBackend, StopResult,
};
use crate::mxc_common::state_aware_binding::{BoundStateAwareOperation, BoundStateAwareRequest};
use crate::mxc_common::state_aware_request::ParsedStateAwareRequest;
use crate::mxc_common::validator::validate_exec_common;

/// Outcome of dispatching one state-aware request. Distinguishes the two
/// success modes: non-exec phases produce a JSON envelope; exec phases stream
/// their output live and exit with the script's exit code.
#[derive(Debug)]
pub enum DispatchOutcome {
    /// JSON envelope to write to stdout (non-exec phases or dispatch failure).
    Envelope(Value),
    /// Exec phase completed; the executor process should exit with this code.
    /// Stdout already carried the script's output; no JSON envelope is emitted.
    ExecCompleted { exit_code: i32 },
}

/// Typed outcome of backend dispatch before raw response-envelope encoding.
#[derive(Debug)]
pub enum TypedDispatchOutcome<ProvisionMetadata, StartMetadata, StopMetadata, DeprovisionMetadata> {
    DryRun,
    ProvisionSession(ProvisionSessionResult),
    Provision(ProvisionResult<ProvisionMetadata>),
    Start(StartResult<StartMetadata>),
    ExecCompleted { exit_code: i32 },
    Stop(StopResult<StopMetadata>),
    Deprovision(DeprovisionResult<DeprovisionMetadata>),
    DeprovisionSession,
}

pub type TypedBackendDispatchOutcome<B> = TypedDispatchOutcome<
    <B as StatefulSandboxBackend>::ProvisionMetadata,
    <B as StatefulSandboxBackend>::StartMetadata,
    <B as StatefulSandboxBackend>::StopMetadata,
    <B as StatefulSandboxBackend>::DeprovisionMetadata,
>;

/// Fallback dispatch for backends whose state-aware impl isn't reachable
/// from `mxc_common` (e.g. it lives in a backend crate that depends on
/// `mxc_common`, so a direct call here would create a cycle). Callers in
/// `wxc-exec` resolve known backends and invoke `dispatch_state_aware`
/// directly; anything they don't handle falls through to this function,
/// which surfaces `unsupported_phase` for the resolved backend.
pub fn run_state_aware(
    parsed: ParsedStateAwareRequest,
    dry_run: bool,
) -> Result<DispatchOutcome, MxcError> {
    let _ = dry_run;

    let backend = resolve_backend(&parsed)?;
    Err(MxcError::unsupported_phase(format!(
        "backend {:?} does not implement state-aware lifecycle",
        backend
    )))
}

/// Streaming counterpart of the exec phase of [`dispatch_state_aware`]: run the
/// exec phase up to (and including) [`StatefulSandboxBackend::exec`] and return
/// the resulting [`ExecHandle`] to the caller **without** relaying it to
/// this process's stdio.
///
/// This is what lets the library / FFI streaming path drive an exec live —
/// wrapping the returned handle in a [`SandboxProcess`](crate::mxc_common::sandbox_process::SandboxProcess)
/// via [`ExecSandboxProcess`](crate::mxc_common::exec_stream::ExecSandboxProcess) — instead
/// of the run-to-completion relay that [`dispatch_state_aware`] performs for
/// `wxc-exec`. Requires the `exec` phase; any other phase is a
/// `malformed_request`. `dry_run` has no meaning for a streaming exec (there is
/// nothing to stream) and is intentionally not accepted.
pub fn dispatch_state_aware_exec<B: StatefulSandboxBackend>(
    backend: &mut B,
    bound: BoundStateAwareRequest<B>,
) -> Result<ExecHandle, MxcError> {
    let phase = bound.phase();
    let (request, operation) = bound.into_parts();
    let BoundStateAwareOperation::Exec { sandbox_id, config } = operation else {
        return Err(MxcError::malformed_request(format!(
            "streaming exec requires the exec phase, got {phase}"
        )));
    };
    validate_exec_common(&request)?;
    backend.validate_exec(&sandbox_id, &request, config.as_ref())?;
    // The caller drives the returned streams itself, so the backend must
    // surface real pipes and leave this process's console alone.
    backend.exec(&sandbox_id, &request, config, ExecStdio::Piped)
}

/// Caller-owned PTY counterpart of [`dispatch_state_aware_exec`].
pub fn dispatch_state_aware_exec_pty<B: StatefulSandboxBackend>(
    backend: &mut B,
    bound: BoundStateAwareRequest<B>,
    size: PtySize,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    let phase = bound.phase();
    let (request, operation) = bound.into_parts();
    let BoundStateAwareOperation::Exec { sandbox_id, config } = operation else {
        return Err(MxcError::malformed_request(format!(
            "spawning a process with a PTY in an existing container requires the exec phase, got {phase}"
        )));
    };
    validate_exec_common(&request)?;
    backend.validate_exec(&sandbox_id, &request, config.as_ref())?;
    backend.exec_pty(&sandbox_id, &request, config, size)
}

/// Per-backend phase router. The `run_state_aware` arm for a participating
/// backend constructs `B` and delegates here.
pub fn dispatch_state_aware<B: StatefulSandboxBackend>(
    backend: &mut B,
    bound: BoundStateAwareRequest<B>,
    dry_run: bool,
) -> Result<DispatchOutcome, MxcError> {
    match dispatch_state_aware_typed(backend, bound, dry_run)? {
        TypedDispatchOutcome::DryRun => Ok(DispatchOutcome::Envelope(empty_result_envelope())),
        TypedDispatchOutcome::ProvisionSession(result) => Ok(DispatchOutcome::Envelope(
            provision_session_envelope(result)?,
        )),
        TypedDispatchOutcome::Provision(result) => {
            Ok(DispatchOutcome::Envelope(provision_envelope(result)?))
        }
        TypedDispatchOutcome::Start(result) => {
            Ok(DispatchOutcome::Envelope(metadata_envelope(result)?))
        }
        TypedDispatchOutcome::ExecCompleted { exit_code } => {
            Ok(DispatchOutcome::ExecCompleted { exit_code })
        }
        TypedDispatchOutcome::Stop(result) => {
            Ok(DispatchOutcome::Envelope(metadata_envelope(result)?))
        }
        TypedDispatchOutcome::Deprovision(result) => {
            Ok(DispatchOutcome::Envelope(metadata_envelope(result)?))
        }
        TypedDispatchOutcome::DeprovisionSession => {
            Ok(DispatchOutcome::Envelope(empty_result_envelope()))
        }
    }
}

/// Per-backend phase router that retains typed backend results.
pub fn dispatch_state_aware_typed<B: StatefulSandboxBackend>(
    backend: &mut B,
    bound: BoundStateAwareRequest<B>,
    dry_run: bool,
) -> Result<TypedBackendDispatchOutcome<B>, MxcError> {
    let (request, operation) = bound.into_parts();
    match operation {
        BoundStateAwareOperation::ProvisionSession(config) => {
            backend.validate_provision_session(&request, config.as_ref())?;
            if dry_run {
                return Ok(TypedDispatchOutcome::DryRun);
            }
            let result = backend.provision_session(&request, config)?;
            Ok(TypedDispatchOutcome::ProvisionSession(result))
        }
        BoundStateAwareOperation::Provision(config) => {
            backend.validate_provision(&request, config.as_ref())?;
            if dry_run {
                return Ok(TypedDispatchOutcome::DryRun);
            }
            let result = backend.provision(&request, config)?;
            Ok(TypedDispatchOutcome::Provision(result))
        }
        BoundStateAwareOperation::Start { sandbox_id, config } => {
            backend.validate_start(&sandbox_id, &request, config.as_ref())?;
            if dry_run {
                return Ok(TypedDispatchOutcome::DryRun);
            }
            let result = backend.start(&sandbox_id, &request, config)?;
            Ok(TypedDispatchOutcome::Start(result))
        }
        BoundStateAwareOperation::Exec { sandbox_id, config } => {
            validate_exec_common(&request)?;
            backend.validate_exec(&sandbox_id, &request, config.as_ref())?;
            if dry_run {
                return Ok(TypedDispatchOutcome::DryRun);
            }
            let handle = backend.exec(&sandbox_id, &request, config, ExecStdio::Relayed)?;
            let exit_code = relay_exec_to_stdio(handle)?;
            Ok(TypedDispatchOutcome::ExecCompleted { exit_code })
        }
        BoundStateAwareOperation::Stop { sandbox_id, config } => {
            backend.validate_stop(&sandbox_id, &request, config.as_ref())?;
            if dry_run {
                return Ok(TypedDispatchOutcome::DryRun);
            }
            let result = backend.stop(&sandbox_id, &request, config)?;
            Ok(TypedDispatchOutcome::Stop(result))
        }
        BoundStateAwareOperation::Deprovision { sandbox_id, config } => {
            backend.validate_deprovision(&sandbox_id, &request, config.as_ref())?;
            if dry_run {
                return Ok(TypedDispatchOutcome::DryRun);
            }
            let result = backend.deprovision(&sandbox_id, &request, config)?;
            Ok(TypedDispatchOutcome::Deprovision(result))
        }
        BoundStateAwareOperation::DeprovisionSession { session_id } => {
            backend.validate_deprovision_session(&session_id, &request)?;
            if dry_run {
                return Ok(TypedDispatchOutcome::DryRun);
            }
            backend.deprovision_session(&session_id, &request)?;
            Ok(TypedDispatchOutcome::DeprovisionSession)
        }
    }
}

/// Resolves the target backend: from `containment` for the phases that declare
/// it, from the `sandbox_id` prefix for the rest.
pub fn resolve_backend(parsed: &ParsedStateAwareRequest) -> Result<ContainmentBackend, MxcError> {
    let phase = parsed.phase();
    if phase.routes_by_containment() {
        return parsed.containment().ok_or_else(|| {
            MxcError::malformed_request(format!("{phase} phase requires a containment field"))
        });
    }
    let sandbox_id = parsed.sandbox_id_required()?;
    let prefix = parse_sandbox_id_prefix(sandbox_id)?;
    backend_from_prefix(prefix)
}

/// Maps a state-aware sandbox-id prefix to its `ContainmentBackend`.
/// Subsequent state-aware backends register their prefix here.
///
/// Session IDs are deliberately absent: both session phases declare a
/// containment, so none of them reaches this map.
pub(crate) fn backend_from_prefix(prefix: &str) -> Result<ContainmentBackend, MxcError> {
    match prefix {
        "iso" => Ok(ContainmentBackend::IsolationSession),
        "microvm" => Ok(ContainmentBackend::MicroVm),
        "wsb" => Ok(ContainmentBackend::WindowsSandbox),
        "wslc" => Ok(ContainmentBackend::Wslc),
        "w365" => Ok(ContainmentBackend::W365Agents),
        // Future state-aware backends extend this list.
        other => Err(MxcError::unsupported_containment(format!(
            "no state-aware backend registered for prefix {:?}",
            other
        ))),
    }
}

/// Streams the running process's pipes to this process's stdio and waits for exit.
///
/// Relay threads start **before** the waiter runs: a child that fills its
/// stdout pipe buffer would otherwise block forever, since nothing would be
/// draining it while we wait.
///
/// - **stdout / stderr** are pumped to this process's own streams and drained
///   after the waiter returns, so output already in flight is not lost to the
///   executor exiting first. That drain is time-bounded: see [`drain_pumps`]
///   for what is given up when a writer outlives the workload.
/// - **stdin is not forwarded.** `ExecHandle::stdin` is left untouched here.
///   Forwarding it correctly needs an ownership model this type does not yet
///   have -- a pipe reaches EOF only once *every* write handle is closed, and
///   the relay can only borrow-and-duplicate the backend's handle, so neither
///   side is able to close the child's stdin. It also needs a stop signal, as a
///   read on the executor's stdin never returns when that stdin is a console or
///   node-pty handle held open by a parent. IsolationSession's own relay
///   documents both hazards and solves them with
///   `create_relay_thread_with_stop`; the generic path will need an equivalent.
///
///   Until that exists, a backend under [`ExecStdio::Relayed`] **must not
///   give the child a stdin pipe whose write end it keeps**. Nothing here writes
///   to that pipe and nothing can close it, so a workload that reads stdin
///   blocks forever -- and it does so while this function is inside `waiter()`,
///   which the drain bound does not cover, hanging the executor with the sandbox
///   still alive. Wire the child's stdin to something already at EOF instead.
///
/// Each stream is written through and flushed as it arrives rather than via
/// `io::copy`, because Rust's stdout is line-buffered: a progress indicator
/// that emits partial lines (or bare `\r`) must still appear progressively.
///
/// **Backend contract:** the backend must not retain its own copy of the
/// child's *write* ends. The pumps finish on EOF, which the OS reports only
/// once every writer handle is closed; a retained duplicate keeps a pump alive
/// until the drain gives up on it, costing that delay and the output still
/// buffered behind it.
///
/// A backend that relays internally hands back null pipe handles plus a waiter
/// that yields the already-captured exit code. No wrapping succeeds, no thread
/// is spawned, and this reduces to calling the waiter — the original
/// call-through behaviour, unchanged.
///
/// Deliberately not built on IsolationSession's `pipe_relay`, which solves the
/// same problem for that backend: it lives in a `backends/*` crate that
/// `mxc_common` must not depend on, it is Windows-only (raw `HANDLE`s and
/// `CreateThread`), and it is `unsafe`. This dispatcher is cross-platform and
/// stays in safe `std::io`. Its per-write flush is the same conclusion that
/// relay reached independently.
fn relay_exec_to_stdio(handle: ExecHandle) -> Result<i32, MxcError> {
    let ExecHandle {
        stdout,
        stderr,
        stdin: _,
        waiter,
        terminator,
        // This relay forwards no input, so the backend's stdin end is left to
        // the backend's own teardown.
        stdin_closer: _,
    } = handle;

    // Classify every stream before committing to anything. A null handle is an
    // absent stream and is fine; a handle the backend named but that cannot be
    // duplicated is a setup failure -- see `wrap_read_checked`.
    let streams = wrap_read_checked(stdout, "stdout").and_then(|out| {
        let err = wrap_read_checked(stderr, "stderr")?;
        Ok(RelayStreams {
            stdout: out,
            stderr: err,
        })
    });

    relay_prepared_streams(streams, waiter, terminator)
}

/// The streams a relay will pump, once classified.
struct RelayStreams {
    stdout: Option<Box<dyn std::io::Read + Send>>,
    stderr: Option<Box<dyn std::io::Read + Send>>,
}

/// Run the relay over already-classified streams.
///
/// Split from [`relay_exec_to_stdio`] so the failure paths are reachable in a
/// test without fabricating an invalid OS handle: a caller can hand this an
/// `Err` directly and observe the exec being terminated and then reaped.
fn relay_prepared_streams(
    streams: Result<RelayStreams, MxcError>,
    waiter: Box<dyn FnOnce() -> Result<ExecOutcome, MxcError> + Send>,
    terminator: Box<dyn FnOnce() -> Result<(), MxcError> + Send>,
) -> Result<i32, MxcError> {
    let streams = match streams {
        Ok(streams) => streams,
        Err(error) => return abort_relay(waiter, terminator, Vec::new(), error),
    };

    // Pumps are started fallibly and *before* the waiter runs: a child that
    // fills its stdout pipe buffer would otherwise block forever, since nothing
    // would be draining it while we wait. `thread::spawn` would panic if the OS
    // refused, which here would unwind past the terminator and leave the
    // workload running.
    let mut pumps: Vec<Pump> = Vec::new();

    if let Some(src) = streams.stdout {
        match spawn_pump("mxc-relay-stdout", src, std::io::stdout()) {
            Ok(pump) => pumps.push(pump),
            Err(error) => return abort_relay(waiter, terminator, pumps, error),
        }
    }
    if let Some(src) = streams.stderr {
        match spawn_pump("mxc-relay-stderr", src, std::io::stderr()) {
            Ok(pump) => pumps.push(pump),
            Err(error) => return abort_relay(waiter, terminator, pumps, error),
        }
    }

    // `terminator` stays alive until the end of this scope: the closure may own
    // resources tied to the running process, and the waiter-error path below
    // still needs to invoke it.
    let outcome = waiter();

    // A waiter error means "I could not determine the exit", not "the child is
    // dead" -- so the workload may still be running and still holding the write
    // ends. Terminate before draining, exactly as `abort_relay` does. The drain
    // is bounded, so the cost of getting this order wrong is not a hang: it is a
    // stall for the whole grace period, followed by the loss of whatever output
    // was still buffered behind those write ends.
    if outcome.is_err() {
        let _ = terminator();
    }

    // Drain what the child wrote before it exited. Bounded -- see `drain_pumps`.
    drain_pumps(pumps);

    // A backend serving `ExecStdio::Relayed` reports `Exited`, so a timeout
    // here is a contract violation.
    match outcome {
        Ok(ExecOutcome::Exited(code)) => Ok(code),
        Ok(ExecOutcome::TimedOut) => Err(MxcError::backend_error(
            "backend reported a timeout to the relay, which has no way \
             to represent one; a backend serving ExecStdio::Relayed must \
             report ExecOutcome::Exited",
        )),
        Err(error) => Err(error),
    }
}

/// Join `pumps`, giving them at most [`POST_EXIT_DRAIN_GRACE`] between them.
///
/// A pump only ends at EOF, which needs *every* writer closed -- and a
/// backgrounded descendant that inherited the pipe can hold its write end open
/// long after the foreground command exits (the same hazard `sandbox_process`
/// documents, and solves there with a cancel-and-discard). Once the exit code
/// is in hand, truncating late output is the lesser loss against never
/// returning it at all.
///
/// A pump that misses the deadline is **muted** rather than merely abandoned.
/// Its thread outlives this call still holding a live read handle, and an
/// unmuted one would go on writing to the process's stdout -- where it can
/// interleave with whatever the caller emits next. The error envelope is the
/// case that matters: it is JSON, and a machine parses it, so a stray chunk of
/// child output appended to it turns a diagnosable backend error into a parse
/// failure.
///
/// Muting is not instantaneous: a pump blocked mid-write can still land the
/// chunk it already committed to. It takes effect from the next read onward,
/// which closes the window that lasts as long as the process does.
fn drain_pumps(pumps: Vec<Pump>) {
    drain_pumps_within(pumps, POST_EXIT_DRAIN_GRACE);
}

/// [`drain_pumps`] with the grace period injected — the seam that lets a test
/// drive the expiry path without waiting out the real one.
fn drain_pumps_within(pumps: Vec<Pump>, grace: Duration) {
    let deadline = Instant::now() + grace;
    for pump in pumps {
        let remaining = deadline.saturating_duration_since(Instant::now());
        if pump.finished.recv_timeout(remaining).is_ok() {
            let _ = pump.thread.join();
        } else {
            pump.mute();
        }
    }
}

/// How long the relay waits for its pumps to drain after the exec has exited.
/// Long enough to flush what a finished child left in the pipe, short enough
/// that a descendant holding the write end open cannot wedge the executor.
const POST_EXIT_DRAIN_GRACE: Duration = Duration::from_secs(5);

/// A running pump: the thread, plus a signal it sends when its copy loop ends.
/// The signal is what makes the post-exit drain boundable -- `JoinHandle` has
/// no timed join.
struct Pump {
    thread: std::thread::JoinHandle<()>,
    finished: std::sync::mpsc::Receiver<()>,
    muted: Arc<AtomicBool>,
}

impl Pump {
    /// Stop this pump writing to its destination, without waiting for it.
    ///
    /// The thread keeps reading and discarding rather than stopping outright:
    /// its source is still connected to the workload, and abandoning a full
    /// pipe is what wedges a child that is still writing.
    fn mute(&self) {
        self.muted.store(true, Ordering::Relaxed);
    }
}

/// Tear down a relay that could not be set up: terminate the exec that was
/// already started, drain any pump that did start, then **run the waiter** so
/// the exec is reaped rather than merely signalled.
///
/// Terminating is a request, not a reaping. Dropping the waiter instead of
/// running it skips whatever completion work the backend put behind it and, for
/// a local child on Unix, leaves a zombie until the executor exits. The
/// streaming adapter's `Drop` already terminates-then-joins for this reason;
/// this is the same contract on the failure path.
///
/// Running it is as much as this can promise. `waiter` is `FnOnce`, so if it
/// fails -- which by its own contract means the exit could not be determined,
/// not that the child is gone -- it has been consumed and no reaping operation
/// is left to retry. Closing that gap needs a separate, infallible reaper on
/// [`ExecHandle`]; until then a failed wait during teardown can leave the exec
/// terminated but unreaped.
///
/// The drain is bounded for the same reason the post-exit one is: terminating
/// the foreground child does *not* guarantee its write ends are closed, because
/// a backgrounded descendant may still hold them. An unbounded join here would
/// hang before reaching the waiter and so defeat the one thing this function
/// exists to guarantee.
///
/// The waiter's own outcome is discarded: the setup error is what the caller
/// needs to see, and masking it with a teardown result would hide the cause.
fn abort_relay(
    waiter: Box<dyn FnOnce() -> Result<ExecOutcome, MxcError> + Send>,
    terminator: Box<dyn FnOnce() -> Result<(), MxcError> + Send>,
    pumps: Vec<Pump>,
    error: MxcError,
) -> Result<i32, MxcError> {
    let _ = terminator();
    drain_pumps(pumps);
    let _ = waiter();
    Err(error)
}

/// Start one named pump thread, reporting an OS refusal instead of panicking.
///
/// The returned [`Pump`] carries a completion signal alongside the join handle
/// so callers can bound how long they wait for it; see [`drain_pumps`].
fn spawn_pump<R, W>(name: &str, src: R, dst: W) -> Result<Pump, MxcError>
where
    R: std::io::Read + Send + 'static,
    W: std::io::Write + Send + 'static,
{
    let muted = Arc::new(AtomicBool::new(false));
    let thread_muted = Arc::clone(&muted);
    let (finished_tx, finished) = std::sync::mpsc::channel();
    std::thread::Builder::new()
        .name(name.to_string())
        .spawn(move || {
            pump_stream(src, dst, &thread_muted);
            let _ = finished_tx.send(());
        })
        .map(|thread| Pump {
            thread,
            finished,
            muted,
        })
        .map_err(|error| MxcError::backend_error(format!("failed to start {name}: {error}")))
}

/// Copy `src` to `dst` until EOF, flushing after every chunk so output reaches
/// the terminal as it is produced.
///
/// **Draining does not stop when the destination breaks.** If the executor's
/// own stdout goes away, this keeps reading and discards instead of returning:
/// the backend still holds the read handle's peer, so the child may never see
/// a broken pipe -- it would simply fill the buffer and block forever while the
/// waiter waits for an exit that cannot come. Losing output is recoverable;
/// wedging the workload is not.
///
/// `muted` is the same policy imposed from outside: set once the relay has
/// stopped waiting for this pump, so it stops writing to a destination it no
/// longer has exclusive use of, while still draining its source. See
/// [`drain_pumps`].
///
/// Read errors do end the pump: there is nothing left to drain.
fn pump_stream<R: std::io::Read, W: std::io::Write>(mut src: R, mut dst: W, muted: &AtomicBool) {
    let mut buf = [0u8; 8192];
    let mut discarding = false;
    loop {
        match src.read(&mut buf) {
            Ok(0) => break,
            Ok(n) => {
                if !discarding && !muted.load(Ordering::Relaxed) {
                    // A failed flush is as fatal to the destination as a failed
                    // write: either way nothing more will reach it.
                    let wrote = dst.write_all(&buf[..n]).and_then(|()| dst.flush());
                    if wrote.is_err() {
                        discarding = true;
                    }
                }
            }
            Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(_) => break,
        }
    }
}

// ---------- Wire-format envelope construction ----------

/// `{ "result": { "sandboxId": "...", "metadata": {...}? } }`
#[derive(Serialize)]
struct ProvisionWireBody<M: Serialize> {
    #[serde(rename = "sandboxId")]
    sandbox_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    metadata: Option<M>,
}

/// `{ "metadata": {...}? }` — used by start / stop / deprovision phases.
#[derive(Serialize)]
struct MetadataWireBody<M: Serialize> {
    #[serde(skip_serializing_if = "Option::is_none")]
    metadata: Option<M>,
}

/// `{ "result": { "sessionId": "..." } }`
#[derive(Serialize)]
struct ProvisionSessionWireBody {
    #[serde(rename = "sessionId")]
    session_id: String,
}

fn provision_envelope<M: Serialize>(r: ProvisionResult<M>) -> Result<Value, MxcError> {
    let body = ProvisionWireBody {
        sandbox_id: r.sandbox_id,
        metadata: r.metadata,
    };
    let envelope = ResponseEnvelope::Result(body);
    serde_json::to_value(&envelope).map_err(|e| {
        MxcError::backend_error(format!("provision envelope serialisation failed: {}", e))
    })
}

fn metadata_envelope<R: HasMetadata>(r: R) -> Result<Value, MxcError> {
    let body = MetadataWireBody {
        metadata: r.into_metadata(),
    };
    let envelope = ResponseEnvelope::Result(body);
    serde_json::to_value(&envelope).map_err(|e| {
        MxcError::backend_error(format!("metadata envelope serialisation failed: {}", e))
    })
}

fn provision_session_envelope(r: ProvisionSessionResult) -> Result<Value, MxcError> {
    let body = ProvisionSessionWireBody {
        session_id: r.session_id,
    };
    let envelope = ResponseEnvelope::Result(body);
    serde_json::to_value(&envelope).map_err(|e| {
        MxcError::backend_error(format!(
            "session provision envelope serialisation failed: {}",
            e
        ))
    })
}

fn empty_result_envelope() -> Value {
    serde_json::json!({"result": {}})
}

// Lets `metadata_envelope` accept any of the per-phase result types without a
// long manual match.
trait HasMetadata {
    type Metadata: Serialize;
    fn into_metadata(self) -> Option<Self::Metadata>;
}

impl<M: Serialize> HasMetadata for StartResult<M> {
    type Metadata = M;
    fn into_metadata(self) -> Option<M> {
        self.metadata
    }
}
impl<M: Serialize> HasMetadata for StopResult<M> {
    type Metadata = M;
    fn into_metadata(self) -> Option<M> {
        self.metadata
    }
}
impl<M: Serialize> HasMetadata for DeprovisionResult<M> {
    type Metadata = M;
    fn into_metadata(self) -> Option<M> {
        self.metadata
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mxc_common::models::ExecutionRequest;
    use crate::mxc_common::models::WslcProvisionSessionConfig;
    use crate::mxc_common::mxc_error::MxcErrorCode;
    use crate::mxc_common::state_aware_operation::{StateAwareOperation, StateAwareProvision};
    use crate::mxc_common::state_aware_request::Phase;
    use serde_json::json;
    use std::cell::Cell;
    use std::cell::RefCell;
    use std::time::Duration;

    const SESSION_ID: &str = "wslcsess:0123456789abcdef0123456789abcdef";

    /// Fully-configurable backend stub for dispatcher tests.
    /// Each phase is wired to either succeed (the default — empty result with
    /// no metadata) or fail with a typed `MxcError` (set via the `*_error`
    /// fields). Calls to each phase method are counted on `*_calls` so tests
    /// can assert the routing landed on the right method.
    struct StubBackend {
        provision_calls: Cell<u32>,
        start_calls: Cell<u32>,
        exec_calls: Cell<u32>,
        stop_calls: Cell<u32>,
        deprovision_calls: Cell<u32>,
        validate_provision_calls: Cell<u32>,
        validate_start_calls: Cell<u32>,
        validate_exec_calls: Cell<u32>,
        validate_stop_calls: Cell<u32>,
        validate_deprovision_calls: Cell<u32>,
        /// The [`ExecStdio`] the dispatcher passed to the most recent
        /// `exec`. Swapping the two variants would compile and silently
        /// change behaviour on both paths.
        last_exec_stdio: Cell<Option<ExecStdio>>,
        provision_error: Option<MxcError>,
        validate_provision_error: Option<MxcError>,
    }

    impl StubBackend {
        fn new() -> Self {
            Self {
                provision_calls: Cell::new(0),
                start_calls: Cell::new(0),
                exec_calls: Cell::new(0),
                stop_calls: Cell::new(0),
                deprovision_calls: Cell::new(0),
                validate_provision_calls: Cell::new(0),
                validate_start_calls: Cell::new(0),
                validate_exec_calls: Cell::new(0),
                validate_stop_calls: Cell::new(0),
                validate_deprovision_calls: Cell::new(0),
                last_exec_stdio: Cell::new(None),
                provision_error: None,
                validate_provision_error: None,
            }
        }
    }

    impl StatefulSandboxBackend for StubBackend {
        const ID_PREFIX: &'static str = "stubd";
        const BACKEND_KEY: &'static str = "stub_dispatch";
        type ProvisionConfig = ();

        type StartConfig = ();
        type ExecConfig = ();
        type StopConfig = ();
        type DeprovisionConfig = ();
        type ProvisionMetadata = ();
        type StartMetadata = ();
        type StopMetadata = ();
        type DeprovisionMetadata = ();

        fn provision(
            &mut self,
            _request: &ExecutionRequest,
            _config: Option<()>,
        ) -> Result<ProvisionResult<()>, MxcError> {
            self.provision_calls.set(self.provision_calls.get() + 1);
            if let Some(e) = self.provision_error.clone() {
                return Err(e);
            }
            Ok(ProvisionResult {
                sandbox_id: format!("{}:fixed-token", Self::ID_PREFIX),
                metadata: None,
            })
        }
        fn start(
            &mut self,
            _sandbox_id: &str,
            _request: &ExecutionRequest,
            _config: Option<()>,
        ) -> Result<StartResult<()>, MxcError> {
            self.start_calls.set(self.start_calls.get() + 1);
            Ok(StartResult { metadata: None })
        }
        fn exec(
            &mut self,
            _sandbox_id: &str,
            _request: &ExecutionRequest,
            _config: Option<()>,
            stdio: ExecStdio,
        ) -> Result<ExecHandle, MxcError> {
            self.exec_calls.set(self.exec_calls.get() + 1);
            self.last_exec_stdio.set(Some(stdio));
            Err(MxcError::backend_error("stub exec not wired"))
        }
        fn stop(
            &mut self,
            _sandbox_id: &str,
            _request: &ExecutionRequest,
            _config: Option<()>,
        ) -> Result<StopResult<()>, MxcError> {
            self.stop_calls.set(self.stop_calls.get() + 1);
            Ok(StopResult { metadata: None })
        }
        fn deprovision(
            &mut self,
            _sandbox_id: &str,
            _request: &ExecutionRequest,
            _config: Option<()>,
        ) -> Result<DeprovisionResult<()>, MxcError> {
            self.deprovision_calls.set(self.deprovision_calls.get() + 1);
            Ok(DeprovisionResult { metadata: None })
        }

        fn validate_provision(
            &self,
            _request: &ExecutionRequest,
            _config: Option<&()>,
        ) -> Result<(), MxcError> {
            self.validate_provision_calls
                .set(self.validate_provision_calls.get() + 1);
            if let Some(e) = self.validate_provision_error.clone() {
                return Err(e);
            }
            Ok(())
        }
        fn validate_start(
            &self,
            _sandbox_id: &str,
            _request: &ExecutionRequest,
            _config: Option<&()>,
        ) -> Result<(), MxcError> {
            self.validate_start_calls
                .set(self.validate_start_calls.get() + 1);
            Ok(())
        }
        fn validate_exec(
            &self,
            _sandbox_id: &str,
            _request: &ExecutionRequest,
            _config: Option<&()>,
        ) -> Result<(), MxcError> {
            self.validate_exec_calls
                .set(self.validate_exec_calls.get() + 1);
            Ok(())
        }
        fn validate_stop(
            &self,
            _sandbox_id: &str,
            _request: &ExecutionRequest,
            _config: Option<&()>,
        ) -> Result<(), MxcError> {
            self.validate_stop_calls
                .set(self.validate_stop_calls.get() + 1);
            Ok(())
        }
        fn validate_deprovision(
            &self,
            _sandbox_id: &str,
            _request: &ExecutionRequest,
            _config: Option<&()>,
        ) -> Result<(), MxcError> {
            self.validate_deprovision_calls
                .set(self.validate_deprovision_calls.get() + 1);
            Ok(())
        }
    }

    /// Configs need no Deserialize implementation: dispatch receives owned values.
    #[derive(Debug, PartialEq, Eq, Default)]
    struct TypedStartConfig {
        configuration_id: String,
    }

    struct TypedConfigStubBackend {
        captured_start_config: Cell<Option<TypedStartConfig>>,
    }

    impl TypedConfigStubBackend {
        fn new() -> Self {
            Self {
                captured_start_config: Cell::new(None),
            }
        }
    }

    impl StatefulSandboxBackend for TypedConfigStubBackend {
        const ID_PREFIX: &'static str = "typed";
        const BACKEND_KEY: &'static str = "typed_stub";
        type ProvisionConfig = ();

        type StartConfig = TypedStartConfig;
        type ExecConfig = ();
        type StopConfig = ();
        type DeprovisionConfig = ();
        type ProvisionMetadata = ();
        type StartMetadata = ();
        type StopMetadata = ();
        type DeprovisionMetadata = ();

        fn exec(
            &mut self,
            _sandbox_id: &str,
            _request: &ExecutionRequest,
            _config: Option<()>,
            _stdio: ExecStdio,
        ) -> Result<ExecHandle, MxcError> {
            Err(MxcError::backend_error("typed stub exec not wired"))
        }

        fn start(
            &mut self,
            _sandbox_id: &str,
            _request: &ExecutionRequest,
            config: Option<TypedStartConfig>,
        ) -> Result<StartResult<()>, MxcError> {
            self.captured_start_config.set(config);
            Ok(StartResult { metadata: None })
        }
    }

    /// Backend stub that implements the session phases, so dispatch ordering
    /// can be observed on a backend that supports them.
    struct SessionStubBackend {
        provision_session_calls: Cell<u32>,
        deprovision_session_calls: Cell<u32>,
        validate_provision_session_calls: Cell<u32>,
        validate_deprovision_session_calls: Cell<u32>,
        released: RefCell<Vec<String>>,
        validated_sizing: Cell<Option<WslcProvisionSessionConfig>>,
        provisioned_sizing: Cell<Option<WslcProvisionSessionConfig>>,
    }

    impl SessionStubBackend {
        fn new() -> Self {
            Self {
                provision_session_calls: Cell::new(0),
                deprovision_session_calls: Cell::new(0),
                validate_provision_session_calls: Cell::new(0),
                validate_deprovision_session_calls: Cell::new(0),
                released: RefCell::new(Vec::new()),
                validated_sizing: Cell::new(None),
                provisioned_sizing: Cell::new(None),
            }
        }
    }

    impl StatefulSandboxBackend for SessionStubBackend {
        const ID_PREFIX: &'static str = "sess";
        const BACKEND_KEY: &'static str = "session_stub";
        type ProvisionConfig = ();

        type StartConfig = ();
        type ExecConfig = ();
        type StopConfig = ();
        type DeprovisionConfig = ();
        type ProvisionMetadata = ();
        type StartMetadata = ();
        type StopMetadata = ();
        type DeprovisionMetadata = ();

        fn exec(
            &mut self,
            _sandbox_id: &str,
            _request: &ExecutionRequest,
            _config: Option<()>,
            _stdio: ExecStdio,
        ) -> Result<ExecHandle, MxcError> {
            Err(MxcError::backend_error("session stub exec not wired"))
        }

        fn provision_session(
            &mut self,
            _request: &ExecutionRequest,
            config: Option<WslcProvisionSessionConfig>,
        ) -> Result<ProvisionSessionResult, MxcError> {
            self.provision_session_calls
                .set(self.provision_session_calls.get() + 1);
            self.provisioned_sizing.set(config);
            Ok(ProvisionSessionResult {
                session_id: "wslcsess:fixed-token".to_string(),
            })
        }

        fn deprovision_session(
            &mut self,
            session_id: &str,
            _request: &ExecutionRequest,
        ) -> Result<(), MxcError> {
            self.deprovision_session_calls
                .set(self.deprovision_session_calls.get() + 1);
            self.released.borrow_mut().push(session_id.to_string());
            Ok(())
        }

        fn validate_provision_session(
            &self,
            _request: &ExecutionRequest,
            config: Option<&WslcProvisionSessionConfig>,
        ) -> Result<(), MxcError> {
            self.validate_provision_session_calls
                .set(self.validate_provision_session_calls.get() + 1);
            self.validated_sizing.set(config.copied());
            Ok(())
        }

        fn validate_deprovision_session(
            &self,
            _session_id: &str,
            _request: &ExecutionRequest,
        ) -> Result<(), MxcError> {
            self.validate_deprovision_session_calls
                .set(self.validate_deprovision_session_calls.get() + 1);
            Ok(())
        }
    }

    fn session_bound(
        phase: Phase,
        session_id: Option<&str>,
    ) -> BoundStateAwareRequest<SessionStubBackend> {
        let operation = match phase {
            Phase::ProvisionSession => BoundStateAwareOperation::ProvisionSession(None),
            Phase::DeprovisionSession => BoundStateAwareOperation::DeprovisionSession {
                session_id: session_id.unwrap().into(),
            },
            other => panic!("session_bound does not cover {other}"),
        };
        BoundStateAwareRequest::for_test(ExecutionRequest::default(), operation)
    }

    fn bound(phase: Phase, sandbox_id: Option<&str>) -> BoundStateAwareRequest<StubBackend> {
        let operation = match phase {
            Phase::ProvisionSession => BoundStateAwareOperation::ProvisionSession(None),
            Phase::Provision => BoundStateAwareOperation::Provision(None),
            Phase::Start => BoundStateAwareOperation::Start {
                sandbox_id: sandbox_id.unwrap().into(),
                config: None,
            },
            Phase::Exec => BoundStateAwareOperation::Exec {
                sandbox_id: sandbox_id.unwrap().into(),
                config: None,
            },
            Phase::Stop => BoundStateAwareOperation::Stop {
                sandbox_id: sandbox_id.unwrap().into(),
                config: None,
            },
            Phase::Deprovision => BoundStateAwareOperation::Deprovision {
                sandbox_id: sandbox_id.unwrap().into(),
                config: None,
            },
            Phase::DeprovisionSession => BoundStateAwareOperation::DeprovisionSession {
                session_id: sandbox_id.unwrap().into(),
            },
        };
        BoundStateAwareRequest::for_test(ExecutionRequest::default(), operation)
    }

    /// Like [`bound`], but with a command line set so the request survives
    /// `validate_exec_common` and dispatch actually reaches `exec`. The default
    /// request has an empty `script_code`, which is rejected before the backend
    /// is called.
    fn bound_runnable_exec(sandbox_id: &str) -> BoundStateAwareRequest<StubBackend> {
        let (mut request, operation) = bound(Phase::Exec, Some(sandbox_id)).into_parts();
        request.script_code = "echo hi".to_string();
        BoundStateAwareRequest::for_test(request, operation)
    }

    fn assert_envelope(outcome: DispatchOutcome) -> Value {
        match outcome {
            DispatchOutcome::Envelope(v) => v,
            DispatchOutcome::ExecCompleted { .. } => panic!("expected envelope"),
        }
    }

    #[test]
    fn dispatch_provision_calls_validate_then_provision() {
        let mut b = StubBackend::new();
        let env = assert_envelope(
            dispatch_state_aware(&mut b, bound(Phase::Provision, None), false).unwrap(),
        );
        assert_eq!(b.validate_provision_calls.get(), 1);
        assert_eq!(b.provision_calls.get(), 1);
        assert_eq!(env, json!({"result": {"sandboxId": "stubd:fixed-token"}}));
    }

    #[test]
    fn dispatch_provision_session_returns_the_minted_session_id() {
        let mut b = SessionStubBackend::new();
        let env = assert_envelope(
            dispatch_state_aware(&mut b, session_bound(Phase::ProvisionSession, None), false)
                .unwrap(),
        );
        assert_eq!(b.validate_provision_session_calls.get(), 1);
        assert_eq!(b.provision_session_calls.get(), 1);
        assert_eq!(
            env,
            json!({"result": {"sessionId": "wslcsess:fixed-token"}})
        );
    }

    #[test]
    fn dispatch_deprovision_session_releases_the_named_session() {
        let mut b = SessionStubBackend::new();
        let env = assert_envelope(
            dispatch_state_aware(
                &mut b,
                session_bound(Phase::DeprovisionSession, Some(SESSION_ID)),
                false,
            )
            .unwrap(),
        );
        assert_eq!(b.validate_deprovision_session_calls.get(), 1);
        assert_eq!(b.deprovision_session_calls.get(), 1);
        assert_eq!(*b.released.borrow(), vec![SESSION_ID.to_string()]);
        assert_eq!(env, json!({"result": {}}));
    }

    #[test]
    fn dispatch_carries_session_sizing_to_both_the_hook_and_the_phase_method() {
        let sizing = WslcProvisionSessionConfig {
            cpu_count: Some(4),
            memory_mb: Some(8192),
            gpu: Some(true),
        };
        let bound = BoundStateAwareRequest::<SessionStubBackend>::for_test(
            ExecutionRequest::default(),
            BoundStateAwareOperation::ProvisionSession(Some(sizing)),
        );
        let mut b = SessionStubBackend::new();
        dispatch_state_aware(&mut b, bound, false).unwrap();
        assert_eq!(b.validated_sizing.get(), Some(sizing));
        assert_eq!(b.provisioned_sizing.get(), Some(sizing));
    }

    #[test]
    fn a_session_dry_run_still_shows_the_hook_its_sizing() {
        let sizing = WslcProvisionSessionConfig {
            cpu_count: Some(2),
            ..Default::default()
        };
        let bound = BoundStateAwareRequest::<SessionStubBackend>::for_test(
            ExecutionRequest::default(),
            BoundStateAwareOperation::ProvisionSession(Some(sizing)),
        );
        let mut b = SessionStubBackend::new();
        dispatch_state_aware(&mut b, bound, true).unwrap();
        assert_eq!(b.validated_sizing.get(), Some(sizing));
        assert_eq!(b.provisioned_sizing.get(), None);
        assert_eq!(b.provision_session_calls.get(), 0);
    }

    #[test]
    fn dispatch_session_dry_run_validates_without_minting_or_releasing() {
        let mut b = SessionStubBackend::new();
        for bound in [
            session_bound(Phase::ProvisionSession, None),
            session_bound(Phase::DeprovisionSession, Some(SESSION_ID)),
        ] {
            assert_eq!(
                assert_envelope(dispatch_state_aware(&mut b, bound, true).unwrap()),
                json!({"result": {}})
            );
        }
        assert_eq!(b.validate_provision_session_calls.get(), 1);
        assert_eq!(b.validate_deprovision_session_calls.get(), 1);
        assert_eq!(b.provision_session_calls.get(), 0);
        assert_eq!(b.deprovision_session_calls.get(), 0);
        assert!(b.released.borrow().is_empty());
    }

    #[test]
    fn dispatch_session_phases_refuse_on_a_backend_without_sessions_even_in_dry_run() {
        for dry_run in [false, true] {
            let mut b = StubBackend::new();
            for bound in [
                bound(Phase::ProvisionSession, None),
                bound(Phase::DeprovisionSession, Some(SESSION_ID)),
            ] {
                let error = dispatch_state_aware(&mut b, bound, dry_run).unwrap_err();
                assert_eq!(error.code, MxcErrorCode::UnsupportedPhase, "{dry_run}");
                assert!(error.message.contains("stub_dispatch"), "{error:?}");
            }
        }
    }

    #[test]
    fn a_session_phase_cannot_be_streamed_as_an_exec() {
        let mut b = SessionStubBackend::new();
        for phase in [Phase::ProvisionSession, Phase::DeprovisionSession] {
            let bound = session_bound(phase, Some(SESSION_ID));
            let error = dispatch_state_aware_exec(&mut b, bound).unwrap_err();
            assert_eq!(error.code, MxcErrorCode::MalformedRequest);
            assert_eq!(
                error.message,
                format!("streaming exec requires the exec phase, got {phase}")
            );
        }
        assert_eq!(b.provision_session_calls.get(), 0);
        assert_eq!(b.deprovision_session_calls.get(), 0);
    }

    #[test]
    fn dispatch_provision_dry_run_skips_provision_call_but_runs_validate() {
        let mut b = StubBackend::new();
        let env = assert_envelope(
            dispatch_state_aware(&mut b, bound(Phase::Provision, None), true).unwrap(),
        );
        assert_eq!(b.validate_provision_calls.get(), 1);
        assert_eq!(b.provision_calls.get(), 0);
        assert_eq!(env, json!({"result": {}}));
    }

    #[test]
    fn dispatch_provision_returns_validate_error_without_calling_provision() {
        let mut b = StubBackend::new();
        b.validate_provision_error = Some(MxcError::policy_validation("nope"));
        let err = dispatch_state_aware(&mut b, bound(Phase::Provision, None), false).unwrap_err();
        assert_eq!(err.code, MxcErrorCode::PolicyValidation);
        assert_eq!(b.validate_provision_calls.get(), 1);
        assert_eq!(b.provision_calls.get(), 0);
    }

    #[test]
    fn dispatch_provision_propagates_provision_error() {
        let mut b = StubBackend::new();
        b.provision_error = Some(MxcError::backend_error("boom"));
        let err = dispatch_state_aware(&mut b, bound(Phase::Provision, None), false).unwrap_err();
        assert_eq!(err.code, MxcErrorCode::BackendError);
        assert_eq!(b.provision_calls.get(), 1);
    }

    #[test]
    fn start_without_sandbox_id_cannot_reach_binding() {
        let error = crate::mxc_common::config_parser::load_mxc_request_from_json(
            r#"{"version":"0.9.0-alpha","phase":"start"}"#,
            &mut crate::mxc_common::logger::Logger::new(crate::mxc_common::logger::Mode::Buffer),
        )
        .unwrap_err();
        let crate::mxc_common::config_parser::ParseError::StateAware(error) = error else {
            panic!("expected state-aware structural rejection");
        };
        assert_eq!(error.code, MxcErrorCode::MalformedRequest);
        assert!(error.message.contains("sandboxId"));
    }

    #[test]
    fn dispatch_start_calls_validate_then_start() {
        let mut b = StubBackend::new();
        let env = assert_envelope(
            dispatch_state_aware(&mut b, bound(Phase::Start, Some("stubd:abc")), false).unwrap(),
        );
        assert_eq!(b.validate_start_calls.get(), 1);
        assert_eq!(b.start_calls.get(), 1);
        assert_eq!(env, json!({"result": {}}));
    }

    #[test]
    fn dispatch_exec_validate_common_rejects_empty_command_line() {
        let mut b = StubBackend::new();
        let err =
            dispatch_state_aware(&mut b, bound(Phase::Exec, Some("stubd:abc")), false).unwrap_err();
        assert_eq!(err.code, MxcErrorCode::MalformedRequest);
        assert_eq!(b.validate_exec_calls.get(), 0);
        assert_eq!(b.exec_calls.get(), 0);
    }

    #[test]
    fn dispatch_exec_dry_run_skips_exec_call() {
        let mut b = StubBackend::new();
        let p = bound_runnable_exec("stubd:abc");
        let env = assert_envelope(dispatch_state_aware(&mut b, p, true).unwrap());
        assert_eq!(b.validate_exec_calls.get(), 1);
        assert_eq!(b.exec_calls.get(), 0);
        assert_eq!(env, json!({"result": {}}));
    }

    // The remaining three phases complete the dry-run contract: `--dry-run`
    // must run the validation hook and then NOT execute the phase body.
    //
    // These exist because the E2E harness cannot pin this. For `start`, `stop`
    // and `deprovision` the real backends return `metadata: None`, which the
    // dispatcher renders as `{"result":{}}` — byte-identical to the dry-run
    // short-circuit's own envelope. So no observable at the process boundary
    // distinguishes "the phase ran" from "the phase was skipped"; only a
    // call-counting backend can. A per-arm regression that stopped honouring
    // `dry_run` in one of these phases would otherwise be invisible.

    #[test]
    fn dispatch_start_dry_run_skips_start_call_but_runs_validate() {
        let mut b = StubBackend::new();
        let env = assert_envelope(
            dispatch_state_aware(&mut b, bound(Phase::Start, Some("stubd:abc")), true).unwrap(),
        );
        assert_eq!(b.validate_start_calls.get(), 1);
        assert_eq!(b.start_calls.get(), 0, "dry-run must not start the sandbox");
        assert_eq!(env, json!({"result": {}}));
    }

    #[test]
    fn dispatch_stop_dry_run_skips_stop_call_but_runs_validate() {
        let mut b = StubBackend::new();
        let env = assert_envelope(
            dispatch_state_aware(&mut b, bound(Phase::Stop, Some("stubd:abc")), true).unwrap(),
        );
        assert_eq!(b.validate_stop_calls.get(), 1);
        assert_eq!(b.stop_calls.get(), 0, "dry-run must not stop the sandbox");
        assert_eq!(env, json!({"result": {}}));
    }

    #[test]
    fn dispatch_deprovision_dry_run_skips_deprovision_call_but_runs_validate() {
        let mut b = StubBackend::new();
        let env = assert_envelope(
            dispatch_state_aware(&mut b, bound(Phase::Deprovision, Some("stubd:abc")), true)
                .unwrap(),
        );
        assert_eq!(b.validate_deprovision_calls.get(), 1);
        assert_eq!(
            b.deprovision_calls.get(),
            0,
            "dry-run must not deprovision the sandbox"
        );
        assert_eq!(env, json!({"result": {}}));
    }

    #[test]
    fn dispatch_stop_routes_correctly() {
        let mut b = StubBackend::new();
        assert_envelope(
            dispatch_state_aware(&mut b, bound(Phase::Stop, Some("stubd:abc")), false).unwrap(),
        );
        assert_eq!(b.validate_stop_calls.get(), 1);
        assert_eq!(b.stop_calls.get(), 1);
    }

    #[test]
    fn dispatch_deprovision_routes_correctly() {
        let mut b = StubBackend::new();
        assert_envelope(
            dispatch_state_aware(&mut b, bound(Phase::Deprovision, Some("stubd:abc")), false)
                .unwrap(),
        );
        assert_eq!(b.validate_deprovision_calls.get(), 1);
        assert_eq!(b.deprovision_calls.get(), 1);
    }

    #[test]
    fn typed_config_stub_receives_typed_start_config() {
        let mut b = TypedConfigStubBackend::new();
        let p = BoundStateAwareRequest::for_test(
            ExecutionRequest::default(),
            BoundStateAwareOperation::Start {
                sandbox_id: "typed:abc".into(),
                config: Some(TypedStartConfig {
                    configuration_id: "small".into(),
                }),
            },
        );
        assert_envelope(dispatch_state_aware(&mut b, p, false).unwrap());
        let captured = b.captured_start_config.into_inner();
        assert_eq!(
            captured,
            Some(TypedStartConfig {
                configuration_id: "small".into()
            })
        );
    }

    #[test]
    fn typed_config_stub_receives_absent_configuration() {
        let mut b = TypedConfigStubBackend::new();
        let p = BoundStateAwareRequest::for_test(
            ExecutionRequest::default(),
            BoundStateAwareOperation::Start {
                sandbox_id: "typed:abc".into(),
                config: None,
            },
        );
        assert_envelope(dispatch_state_aware(&mut b, p, false).unwrap());
        assert_eq!(b.captured_start_config.into_inner(), None);
    }

    #[test]
    fn misplaced_phase_configuration_is_rejected_before_dispatch() {
        let err = crate::mxc_common::config_parser::load_mxc_request_from_json(
            r#"{"version":"0.9.0-alpha","phase":"start","sandboxId":"iso:abc",
                "isolationSession":{"provision":{"appId":"small"}}}"#,
            &mut crate::mxc_common::logger::Logger::new(crate::mxc_common::logger::Mode::Buffer),
        )
        .unwrap_err();
        let crate::mxc_common::config_parser::ParseError::StateAware(err) = err else {
            panic!("expected state-aware structural rejection");
        };
        assert_eq!(err.code, MxcErrorCode::MalformedRequest);
        assert!(
            err.message.contains("isolationSession"),
            "expected envelope-ready error path, got: {}",
            err.message
        );
    }

    // ---------- run_state_aware / resolve_backend ----------

    #[test]
    fn run_state_aware_provision_for_recognized_backend_returns_unsupported_phase() {
        // No state-aware impls registered yet — every recognized backend is
        // unsupported. Smoke-test scenario #2 from decision 6.
        let p = ParsedStateAwareRequest::new(
            ExecutionRequest::default(),
            StateAwareOperation::Provision(StateAwareProvision::Wslc(None)),
        );
        let err = run_state_aware(p, false).unwrap_err();
        assert_eq!(err.code, MxcErrorCode::UnsupportedPhase);
    }

    #[test]
    fn provision_without_containment_cannot_reach_binding() {
        let err = crate::mxc_common::config_parser::load_mxc_request_from_json(
            r#"{"version":"0.9.0-alpha","phase":"provision"}"#,
            &mut crate::mxc_common::logger::Logger::new(crate::mxc_common::logger::Mode::Buffer),
        )
        .unwrap_err();
        let crate::mxc_common::config_parser::ParseError::StateAware(err) = err else {
            panic!("expected state-aware structural rejection");
        };
        assert_eq!(err.code, MxcErrorCode::MalformedRequest);
    }

    #[test]
    fn resolve_backend_for_iso_prefix_returns_isolation_session() {
        let p = parsed_start("iso:wxc-abcd1234");
        assert_eq!(
            resolve_backend(&p).unwrap(),
            ContainmentBackend::IsolationSession
        );
    }

    #[test]
    fn resolve_backend_for_wsb_prefix_returns_windows_sandbox() {
        let p = parsed_start("wsb:deadbeef");
        assert_eq!(
            resolve_backend(&p).unwrap(),
            ContainmentBackend::WindowsSandbox
        );
    }

    #[test]
    fn resolve_backend_for_wslc_prefix_returns_wslc() {
        let p = parsed_start("wslc:deadbeef");
        assert_eq!(resolve_backend(&p).unwrap(), ContainmentBackend::Wslc);
    }

    #[test]
    fn resolve_backend_for_unknown_prefix_returns_unsupported_containment() {
        let p = parsed_start("unknownxyz:abc");
        let err = resolve_backend(&p).unwrap_err();
        assert_eq!(err.code, MxcErrorCode::UnsupportedContainment);
    }

    #[test]
    fn resolve_backend_for_malformed_id_surfaces_malformed_id() {
        let p = parsed_start("no-colon");
        let err = resolve_backend(&p).unwrap_err();
        assert_eq!(err.code, MxcErrorCode::MalformedId);
    }

    #[test]
    fn resolve_backend_for_session_phases_uses_containment_not_the_id_prefix() {
        for operation in [
            StateAwareOperation::ProvisionSession(None),
            StateAwareOperation::DeprovisionSession {
                session_id: SESSION_ID.into(),
            },
        ] {
            let parsed = ParsedStateAwareRequest::new(ExecutionRequest::default(), operation);
            assert_eq!(resolve_backend(&parsed).unwrap(), ContainmentBackend::Wslc);
        }
        assert_eq!(
            backend_from_prefix("wslcsess").unwrap_err().code,
            MxcErrorCode::UnsupportedContainment
        );
    }

    // ===== stdio topology per entry point ===================================

    fn parsed_start(id: &str) -> ParsedStateAwareRequest {
        ParsedStateAwareRequest::new(
            ExecutionRequest::default(),
            StateAwareOperation::Start {
                sandbox_id: id.into(),
            },
        )
    }
    //
    // Which topology each entry point sends is the whole point of the parameter,
    // and getting it backwards would compile: a relayed exec would lose its
    // console, and a piped caller would have its own console written to by a
    // sandbox. Both directions are pinned.

    /// The relayed path relays the handle to this process's stdio, so the backend
    /// may probe this process's terminal state to decide whether to allocate a
    /// pseudo-console.
    #[test]
    fn dispatch_state_aware_asks_for_relayed_stdio() {
        let mut b = StubBackend::new();
        let _ = dispatch_state_aware(&mut b, bound_runnable_exec("stubd:abc"), false);
        assert_eq!(b.exec_calls.get(), 1, "exec should have been reached");
        assert_eq!(
            b.last_exec_stdio.get(),
            Some(ExecStdio::Relayed),
            "the relayed path must not ask a backend for caller-owned pipes"
        );
    }

    /// The streaming path hands the caller the streams, so the backend must be
    /// told to surface separate raw pipes and leave the host console alone.
    #[test]
    fn dispatch_state_aware_exec_asks_for_piped_stdio() {
        let mut b = StubBackend::new();
        let _ = dispatch_state_aware_exec(&mut b, bound_runnable_exec("stubd:abc"));
        assert_eq!(b.exec_calls.get(), 1, "exec should have been reached");
        assert_eq!(
            b.last_exec_stdio.get(),
            Some(ExecStdio::Piped),
            "the streaming path must never let a backend touch the caller's console"
        );
    }

    // ===== relay_exec_to_stdio =============================================

    use crate::mxc_common::state_aware_backend::null_pipe_handle;
    use std::io::{Read, Write};

    // Build a PipeHandle from a live pipe end. The relay duplicates it, so the
    // original stays owned by the test.
    #[cfg(target_os = "windows")]
    fn reader_handle(
        r: &std::io::PipeReader,
    ) -> crate::mxc_common::state_aware_backend::PipeHandle {
        use std::os::windows::io::AsRawHandle;
        windows::Win32::Foundation::HANDLE(r.as_raw_handle() as _)
    }
    #[cfg(not(target_os = "windows"))]
    fn reader_handle(
        r: &std::io::PipeReader,
    ) -> crate::mxc_common::state_aware_backend::PipeHandle {
        use std::os::fd::AsRawFd;
        r.as_raw_fd()
    }

    /// The all-null handle shape (what every in-tree state-aware backend
    /// returns today) must stay a pure call-through: no threads, no wrapping,
    /// just the waiter's exit code. This is the regression guard for the
    /// pre-relay behaviour.
    #[test]
    fn relay_with_null_handles_returns_waiter_exit_code() {
        let handle = ExecHandle {
            stdin_closer: None,
            stdout: null_pipe_handle(),
            stderr: null_pipe_handle(),
            stdin: null_pipe_handle(),
            waiter: Box::new(|| Ok(ExecOutcome::Exited(42))),
            terminator: Box::new(|| Ok(())),
        };
        assert_eq!(relay_exec_to_stdio(handle).unwrap(), 42);
    }

    /// A backend that reports a timeout to the relay has broken the
    /// contract, and the relay says so rather than inventing an exit code.
    ///
    /// The regression this pins is the tempting alternative: mapping it
    /// to some sentinel code, which the CLI would then report as the workload's
    /// own exit status.
    #[test]
    fn relay_refuses_a_timeout_rather_than_inventing_an_exit_code() {
        let handle = ExecHandle {
            stdin_closer: None,
            stdout: null_pipe_handle(),
            stderr: null_pipe_handle(),
            stdin: null_pipe_handle(),
            waiter: Box::new(|| Ok(ExecOutcome::TimedOut)),
            terminator: Box::new(|| Ok(())),
        };
        let err = relay_exec_to_stdio(handle).expect_err("the relay cannot represent a timeout");
        assert!(
            err.message.contains("ExecStdio::Relayed"),
            "the refusal should name the contract it is enforcing: {}",
            err.message
        );
    }

    /// A waiter error still surfaces unchanged through the relay.
    #[test]
    fn relay_with_null_handles_propagates_waiter_error() {
        let handle = ExecHandle {
            stdin_closer: None,
            stdout: null_pipe_handle(),
            stderr: null_pipe_handle(),
            stdin: null_pipe_handle(),
            waiter: Box::new(|| Err(MxcError::backend_error("waiter blew up"))),
            terminator: Box::new(|| Ok(())),
        };
        let err = relay_exec_to_stdio(handle).unwrap_err();
        assert_eq!(err.code, MxcErrorCode::BackendError);
    }

    /// The top-level relay really wraps the handle and pumps it.
    ///
    /// Asserted by consumption rather than by observing output: a pipe delivers
    /// its bytes once, to whoever reads first, so if the relay's pump drained
    /// them the test's own reader sees EOF afterwards. Reverting
    /// `relay_exec_to_stdio` to its original waiter-only body leaves the bytes
    /// sitting in the pipe and fails this.
    ///
    /// That matters because every other relay test calls `relay_prepared_streams`
    /// or `pump_stream` directly, so without this one the entry point the change
    /// is named for could be gutted with the suite still green.
    ///
    /// `reader` deliberately stays alive across the call: the relay duplicates
    /// the handle *inside* it, so dropping it earlier would hand the relay a
    /// closed handle and silently produce no stream. EOF still arrives, because
    /// that depends on the *write* end, which is already closed.
    ///
    /// This does print one line to the real console, because relaying to
    /// `std::io::stdout()` is the behaviour under test and a pump thread's
    /// writes bypass the harness's capture. The payload is kept to a single
    /// short line for that reason; the assertion is `leftover`, not the console.
    #[test]
    fn relay_drains_a_real_stdout_pipe_and_returns_exit_code() {
        let (mut reader, mut writer) = std::io::pipe().expect("pipe");
        writer.write_all(b"relayed-stdout\n").unwrap();
        drop(writer); // EOF, so the pump can finish

        let handle = ExecHandle {
            stdin_closer: None,
            stdout: reader_handle(&reader),
            stderr: null_pipe_handle(),
            stdin: null_pipe_handle(),
            waiter: Box::new(|| Ok(ExecOutcome::Exited(3))),
            terminator: Box::new(|| Ok(())),
        };

        assert_eq!(relay_exec_to_stdio(handle).unwrap(), 3);

        let mut leftover = Vec::new();
        reader.read_to_end(&mut leftover).unwrap();
        assert!(
            leftover.is_empty(),
            "the relay must have consumed the pipe; found {:?}",
            String::from_utf8_lossy(&leftover)
        );
    }

    /// A non-null handle the backend named but that cannot be duplicated is a
    /// setup failure, not an absent stream. The relay must surface it, and must
    /// both terminate *and* reap the exec it already started -- terminating
    /// alone would skip the backend's completion work and, for a local child,
    /// leave a zombie.
    ///
    /// Driven through `relay_prepared_streams` with an `Err` rather than a
    /// fabricated invalid handle: `BorrowedHandle`/`BorrowedFd::borrow_raw`
    /// require a live handle, so passing a bogus raw value to force the failure
    /// would break their safety contract to test it.
    #[test]
    fn relay_with_failed_stream_setup_terminates_and_reaps() {
        let (tx, rx) = std::sync::mpsc::channel();
        let waiter_tx = tx.clone();
        let result = relay_prepared_streams(
            Err(MxcError::backend_error(
                "failed to duplicate the exec stdout pipe handle",
            )),
            Box::new(move || {
                let _ = waiter_tx.send("waiter");
                Ok(ExecOutcome::Exited(0))
            }),
            Box::new(move || {
                let _ = tx.send("terminator");
                Ok(())
            }),
        );

        let err = result.unwrap_err();
        assert_eq!(err.code, MxcErrorCode::BackendError);
        assert!(
            err.message.contains("stdout"),
            "the setup error must survive teardown: {}",
            err.message
        );

        // Terminate first, then reap: killing is a request, waiting is what
        // actually collects the process.
        let order: Vec<&str> = rx.try_iter().collect();
        assert_eq!(
            order,
            vec!["terminator", "waiter"],
            "the exec must be terminated and then waited for"
        );
    }

    /// The terminator must NOT be invoked on a normal completion — it is the
    /// cancellation path, not the teardown path.
    #[test]
    fn relay_does_not_invoke_terminator_on_normal_completion() {
        let (tx, rx) = std::sync::mpsc::channel();
        let handle = ExecHandle {
            stdin_closer: None,
            stdout: null_pipe_handle(),
            stderr: null_pipe_handle(),
            stdin: null_pipe_handle(),
            waiter: Box::new(|| Ok(ExecOutcome::Exited(0))),
            terminator: Box::new(move || {
                let _ = tx.send(());
                Ok(())
            }),
        };
        assert_eq!(relay_exec_to_stdio(handle).unwrap(), 0);
        assert!(
            rx.try_recv().is_err(),
            "terminator must not fire when the process exited on its own"
        );
    }

    /// Every byte crosses the pump, including across multiple reads.
    #[test]
    fn pump_stream_copies_all_bytes() {
        let (src_r, mut src_w) = std::io::pipe().expect("pipe");
        let (mut dst_r, dst_w) = std::io::pipe().expect("pipe");

        let payload: Vec<u8> = (0..40_000u32).map(|i| (i % 251) as u8).collect();
        let expected = payload.clone();
        let writer = std::thread::spawn(move || {
            src_w.write_all(&payload).unwrap();
            drop(src_w);
        });
        let unmuted = Arc::new(AtomicBool::new(false));
        let pump = std::thread::spawn(move || pump_stream(src_r, dst_w, &unmuted));

        let mut got = Vec::new();
        dst_r.read_to_end(&mut got).unwrap();
        writer.join().unwrap();
        pump.join().unwrap();

        assert_eq!(got.len(), expected.len(), "byte count must match");
        assert_eq!(got, expected, "payload must survive the pump intact");
    }

    /// A destination that breaks mid-stream must not stop the pump draining.
    ///
    /// The backend still holds the peer of the read handle, so a child whose
    /// output is no longer being consumed does not necessarily see a broken
    /// pipe -- it fills the buffer and blocks, and the waiter then waits for an
    /// exit that cannot happen. Discarding is the lesser loss.
    #[test]
    fn pump_stream_keeps_draining_after_the_destination_fails() {
        /// Accepts the first write, then fails every write and flush.
        struct FailsAfterFirstWrite {
            writes: usize,
        }
        impl std::io::Write for FailsAfterFirstWrite {
            fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
                self.writes += 1;
                if self.writes > 1 {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::BrokenPipe,
                        "destination gone",
                    ));
                }
                Ok(buf.len())
            }
            fn flush(&mut self) -> std::io::Result<()> {
                if self.writes > 1 {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::BrokenPipe,
                        "destination gone",
                    ));
                }
                Ok(())
            }
        }

        let (src_r, mut src_w) = std::io::pipe().expect("pipe");
        let unmuted = Arc::new(AtomicBool::new(false));
        let pump = std::thread::spawn(move || {
            pump_stream(src_r, FailsAfterFirstWrite { writes: 0 }, &unmuted);
        });

        // Far more than one buffer, so the writer would block if the pump
        // stopped reading after the destination broke.
        let chunk = vec![b'x'; 8192];
        for _ in 0..16 {
            src_w
                .write_all(&chunk)
                .expect("the pump must keep draining");
        }
        drop(src_w);

        // The join is the assertion: a pump that stopped reading would leave
        // the writes above blocked and never reach EOF.
        pump.join().expect("pump thread should finish");
    }

    /// The pumps must start *before* the waiter runs.
    ///
    /// Nothing else covers this: the other relay test prewrites a few bytes and
    /// uses an instantly-returning waiter, and the payload test calls
    /// `pump_stream` directly, so both would still pass if the wait happened
    /// first.
    ///
    /// The source signals as soon as it is first read and then reports EOF, and
    /// the waiter blocks until **both** signals arrive; a relay that waited
    /// before draining would never produce them. Both streams are supplied
    /// deliberately: with stdout alone, moving only the stderr pump below the
    /// waiter would go unnoticed, and an stderr-heavy child would then fill its
    /// pipe and deadlock exactly as this rule exists to prevent.
    ///
    /// Signalling rather than filling a pipe keeps this independent of the
    /// platform's pipe-buffer size and, more importantly, writes nothing: the
    /// pumps run on spawned threads whose direct `std::io::stdout()` writes
    /// bypass the test harness's capture, so a volume-based version of this
    /// test dumps its payload into the console output of every run, passing or
    /// not.
    ///
    /// The waiter times out rather than blocking forever, so the regression
    /// surfaces as a failed assertion instead of a hung suite.
    #[test]
    fn relay_starts_pumps_before_waiting() {
        struct SignalsOnFirstRead(Option<std::sync::mpsc::Sender<()>>);
        impl std::io::Read for SignalsOnFirstRead {
            fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
                if let Some(tx) = self.0.take() {
                    let _ = tx.send(());
                }
                Ok(0) // EOF: the pump has done its job by reading at all.
            }
        }

        let (started_tx, started_rx) = std::sync::mpsc::channel();
        let streams = RelayStreams {
            stdout: Some(Box::new(SignalsOnFirstRead(Some(started_tx.clone())))),
            stderr: Some(Box::new(SignalsOnFirstRead(Some(started_tx)))),
        };

        let waiter = Box::new(move || {
            let mut started = 0;
            while started < 2 {
                if started_rx.recv_timeout(Duration::from_secs(10)).is_err() {
                    return Err(MxcError::backend_error(format!(
                        "only {started} of the 2 pumps had started when the waiter began waiting"
                    )));
                }
                started += 1;
            }
            Ok(ExecOutcome::Exited(0))
        });

        let result = relay_prepared_streams(Ok(streams), waiter, Box::new(|| Ok(())));
        assert_eq!(
            result.expect("the pumps must be draining while the waiter waits"),
            0
        );
    }

    /// A waiter that *errors* means the exit could not be determined, not that
    /// the child is dead. The relay must terminate **before** draining: the
    /// workload may still hold the write ends, and a bounded drain that runs
    /// first burns its entire grace and then discards what was still buffered.
    ///
    /// Both halves are pinned, and they need different instruments. The
    /// terminator is observed directly, because the returned error comes from
    /// the waiter and would arrive whether or not anything was terminated. The
    /// *ordering* is pinned by the clock: the only thing that can deliver EOF to
    /// this pump is the terminator dropping the write end, so terminating first
    /// ends the drain at once, whereas draining first waits out the full
    /// `POST_EXIT_DRAIN_GRACE` before giving up.
    #[test]
    fn relay_terminates_before_draining_when_the_waiter_errors() {
        let (src_r, src_w) = std::io::pipe().expect("pipe");
        // Held by the terminator alone: dropping it is what lets the pump EOF.
        let writer = Arc::new(std::sync::Mutex::new(Some(src_w)));
        let closer = Arc::clone(&writer);
        let terminated = Arc::new(AtomicBool::new(false));
        let flag = Arc::clone(&terminated);

        let started = Instant::now();
        let result = relay_prepared_streams(
            Ok(RelayStreams {
                stdout: Some(Box::new(src_r)),
                stderr: None,
            }),
            Box::new(|| Err(MxcError::backend_error("could not determine the exit"))),
            Box::new(move || {
                flag.store(true, Ordering::Relaxed);
                closer.lock().expect("writer lock").take();
                Ok(())
            }),
        );
        let elapsed = started.elapsed();

        assert!(
            terminated.load(Ordering::Relaxed),
            "a waiter error leaves the child possibly alive, so it must be terminated"
        );
        assert!(
            elapsed < POST_EXIT_DRAIN_GRACE / 2,
            "the terminator must run before the drain, not after it; took {elapsed:?}"
        );
        let err = result.unwrap_err();
        assert_eq!(err.code, MxcErrorCode::BackendError);
        assert!(
            err.message.contains("could not determine the exit"),
            "the waiter's error must survive teardown: {}",
            err.message
        );
    }

    /// Output must appear as it is produced, not be held until EOF.
    ///
    /// The destination is wrapped in a `BufWriter` large enough to swallow the
    /// whole payload, which is what makes this discriminating: the real sink is
    /// `std::io::stdout()`, and that is line-buffered, so a pump that wrote
    /// without flushing would strand a partial line exactly like this. Against
    /// a bare `PipeWriter` the bytes would become readable whether or not the
    /// pump flushed, and the test would prove nothing.
    ///
    /// The payload carries no newline and the source stays open, so the only
    /// thing that can deliver it is the pump's explicit flush; without it,
    /// `read_exact` blocks until the harness times the test out.
    #[test]
    fn pump_stream_flushes_before_eof() {
        let (src_r, mut src_w) = std::io::pipe().expect("pipe");
        let (mut dst_r, dst_w) = std::io::pipe().expect("pipe");
        let dst = std::io::BufWriter::with_capacity(64 * 1024, dst_w);

        let unmuted = Arc::new(AtomicBool::new(false));
        let pump = std::thread::spawn(move || pump_stream(src_r, dst, &unmuted));

        src_w.write_all(b"no-newline-yet").unwrap();
        src_w.flush().unwrap();

        let mut got = [0u8; 14];
        dst_r
            .read_exact(&mut got)
            .expect("partial line must arrive before EOF");
        assert_eq!(&got, b"no-newline-yet");

        drop(src_w);
        pump.join().unwrap();
    }

    /// A muted pump stops writing but keeps reading.
    ///
    /// Both halves matter and the test pins both. Muting exists so a pump the
    /// relay has stopped waiting for cannot append stray bytes to whatever the
    /// caller emits next; draining on regardless is what stops the workload
    /// wedging on a pipe nobody empties.
    #[test]
    fn a_muted_pump_stops_writing_but_keeps_draining() {
        let (src_r, mut src_w) = std::io::pipe().expect("pipe");
        let (mut dst_r, dst_w) = std::io::pipe().expect("pipe");

        let muted = Arc::new(AtomicBool::new(false));
        let thread_muted = Arc::clone(&muted);
        let pump = std::thread::spawn(move || pump_stream(src_r, dst_w, &thread_muted));

        src_w.write_all(b"before").unwrap();
        src_w.flush().unwrap();
        let mut got = [0u8; 6];
        dst_r.read_exact(&mut got).expect("pre-mute output");
        assert_eq!(&got, b"before");

        muted.store(true, Ordering::Relaxed);

        // Far more than one pipe buffer. If muting stopped the pump reading,
        // these writes would block and the test would never finish.
        let chunk = vec![b'x'; 8192];
        for _ in 0..16 {
            src_w
                .write_all(&chunk)
                .expect("a muted pump must still drain its source");
        }
        drop(src_w);
        pump.join().unwrap();

        // Nothing written after the mute: the destination saw only "before",
        // so reading it to the end now yields EOF immediately.
        let mut leftover = Vec::new();
        dst_r.read_to_end(&mut leftover).unwrap();
        assert!(
            leftover.is_empty(),
            "a muted pump wrote {} bytes it should have discarded",
            leftover.len()
        );
    }

    /// `abort_relay` must terminate *before* draining, not merely before
    /// reaping.
    ///
    /// Called directly, because the only route to it through
    /// `relay_prepared_streams` is a classification failure, which by
    /// construction has no pumps yet -- so that path can never distinguish the
    /// two orders. The reachable non-empty case is a `spawn_pump` refusal,
    /// which cannot be injected from a test.
    ///
    /// The clock is the instrument: the terminator is the only thing that can
    /// deliver EOF here, so terminating first ends the drain at once, while
    /// draining first waits out the whole grace and then mutes the pump.
    #[test]
    fn abort_relay_terminates_before_draining() {
        let (src_r, src_w) = std::io::pipe().expect("pipe");
        let (dst_r, dst_w) = std::io::pipe().expect("pipe");
        // Held by the terminator alone: dropping it is what lets the pump EOF.
        let writer = Arc::new(std::sync::Mutex::new(Some(src_w)));
        let closer = Arc::clone(&writer);
        let pump = spawn_pump("test-abort-pump", src_r, dst_w).expect("spawn");

        let started = Instant::now();
        let result = abort_relay(
            Box::new(|| Ok(ExecOutcome::Exited(0))),
            Box::new(move || {
                closer.lock().expect("writer lock").take();
                Ok(())
            }),
            vec![pump],
            MxcError::backend_error("stream setup failed"),
        );
        let elapsed = started.elapsed();

        assert!(
            elapsed < POST_EXIT_DRAIN_GRACE / 2,
            "the terminator must run before the drain, not after it; took {elapsed:?}"
        );
        let err = result.expect_err("abort_relay must surface the setup error");
        assert!(
            err.message.contains("stream setup failed"),
            "the setup error must survive teardown: {}",
            err.message
        );

        drop(dst_r);
    }

    /// The drain is bounded, and what it abandons it mutes.
    ///
    /// This is the guarantee both drain sites depend on. `abort_relay` needs it
    /// most: an unbounded join there would hang before reaching the waiter and
    /// so defeat the very reaping that function exists to perform.
    #[test]
    fn drain_pumps_bounds_the_wait_and_mutes_what_it_abandons() {
        // A source that never ends. Holding `src_w` open is what makes this the
        // hazard case: the pump cannot reach EOF, so an unbounded join hangs.
        let (src_r, src_w) = std::io::pipe().expect("pipe");
        let (dst_r, dst_w) = std::io::pipe().expect("pipe");
        let pump = spawn_pump("test-endless-pump", src_r, dst_w).expect("spawn");
        let muted = Arc::clone(&pump.muted);

        let started = Instant::now();
        drain_pumps_within(vec![pump], Duration::from_millis(50));
        let elapsed = started.elapsed();

        assert!(
            elapsed < Duration::from_secs(2),
            "the drain must give up on an endless pump, took {elapsed:?}"
        );
        assert!(
            muted.load(Ordering::Relaxed),
            "an abandoned pump must be muted so it cannot write after the relay returns"
        );

        // Release the thread rather than leaving it parked for the run.
        drop(src_w);
        drop(dst_r);
    }
}